diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b5e478b..84b6778 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -83,29 +83,29 @@ jobs: # Budgets are unchanged and no test is dropped: each runs in exactly one of the two steps. - name: Run tests with ThreadSanitizer race detector (-race) & coverage env: - CPU_BUDGET_TESTS: '^(TestR9H3Adversarial240KBPerformanceBudget|TestR8RedactEmbeddedURLsLinear1MiBUnder15ms|TestR9RedactEmbeddedURLs90DiverseLeakVectorsAndLinear1MiB|TestRound8H8LinearCPUBudgetsUnder40ms)$' + CPU_BUDGET_TESTS: '^(TestR9H3Adversarial240KBPerformanceBudget|TestR8RedactEmbeddedURLsLinear1MiBUnder15ms|TestR9RedactEmbeddedURLs90DiverseLeakVectorsAndLinear1MiB|TestRound8H8LinearCPUBudgetsUnder40ms|TestWave3CommunityNegativeShellsAndPerfBudget|TestWave3CyclingComponentsM7PerfBudget|TestWave3CyclingOEMsAdversarialUnclosedDiv100KLatencyAndCPSCQueryTerm|TestWave3CyclingOEMsM7RegressionsAndPerfBudget|TestWave3DevInfraHTMLAndCWSScan|TestWave3DevM7StreamingAndLatencyFixes|TestWave3EduM7CanvasFalsePositiveAndEdlioLatency|TestWave3FinanceM7SECCompanyFactsStreamingLatency|TestWave3GovM7PreemptionsAndLatency|TestWave3JobsM7ParadoxOliviaLatency|TestWave3ResaleM7RegressionsAndPerfBudget|TestWave3SecurityIntelHTMLExtractorsAndFixtures|TestWave3SocialCreatorFixturesGoldenAndNegativeShells|TestWave3StoreAddonsPreemptionAnd2MBPerfBudget|TestM3MultiPassEntitySanitizeMarkdownAndPerf)$' run: go test -v -race -count=1 -skip "$CPU_BUDGET_TESTS" -coverprofile=coverage.out ./... && go tool cover -func=coverage.out | tail -n 15 - name: Run CPU-budget tests with -race (no coverage instrumentation) env: - CPU_BUDGET_TESTS: '^(TestR9H3Adversarial240KBPerformanceBudget|TestR8RedactEmbeddedURLsLinear1MiBUnder15ms|TestR9RedactEmbeddedURLs90DiverseLeakVectorsAndLinear1MiB|TestRound8H8LinearCPUBudgetsUnder40ms)$' + CPU_BUDGET_TESTS: '^(TestR9H3Adversarial240KBPerformanceBudget|TestR8RedactEmbeddedURLsLinear1MiBUnder15ms|TestR9RedactEmbeddedURLs90DiverseLeakVectorsAndLinear1MiB|TestRound8H8LinearCPUBudgetsUnder40ms|TestWave3CommunityNegativeShellsAndPerfBudget|TestWave3CyclingComponentsM7PerfBudget|TestWave3CyclingOEMsAdversarialUnclosedDiv100KLatencyAndCPSCQueryTerm|TestWave3CyclingOEMsM7RegressionsAndPerfBudget|TestWave3DevInfraHTMLAndCWSScan|TestWave3DevM7StreamingAndLatencyFixes|TestWave3EduM7CanvasFalsePositiveAndEdlioLatency|TestWave3FinanceM7SECCompanyFactsStreamingLatency|TestWave3GovM7PreemptionsAndLatency|TestWave3JobsM7ParadoxOliviaLatency|TestWave3ResaleM7RegressionsAndPerfBudget|TestWave3SecurityIntelHTMLExtractorsAndFixtures|TestWave3SocialCreatorFixturesGoldenAndNegativeShells|TestWave3StoreAddonsPreemptionAnd2MBPerfBudget|TestM3MultiPassEntitySanitizeMarkdownAndPerf)$' run: | go test -v -race -count=1 -run "$CPU_BUDGET_TESTS" ./internal/mcpfed ./internal/politeness ./internal/extract | tee cpu-budget.log - test "$(grep -c '^--- PASS: ' cpu-budget.log)" -eq 4 + test "$(grep -c '^--- PASS: ' cpu-budget.log)" -eq 19 - name: Run native Go fuzzing smoke suite run: | - go test -fuzz=FuzzRobotsParseAndMatch -fuzztime=2s ./internal/politeness - go test -fuzz=FuzzParseRetryAfter -fuzztime=2s ./internal/politeness - go test -fuzz=FuzzIsPublicIP -fuzztime=2s ./internal/politeness - go test -fuzz=FuzzClassify -fuzztime=2s ./internal/classify - go test -fuzz=FuzzExtractHTML -fuzztime=2s ./internal/extract - go test -fuzz=FuzzParseLlmsTxt -fuzztime=2s ./internal/extract - go test -fuzz=FuzzExtractPDFPureGo -fuzztime=2s ./internal/extract - go test -fuzz=FuzzDeclarativeFormat -fuzztime=2s ./internal/extract - go test -fuzz=FuzzBotAuthVerifyRequest -fuzztime=2s ./internal/botauth - go test -fuzz=FuzzValidateCustomHeaders -fuzztime=2s ./internal/crawl - go test -fuzz=FuzzPublicHTTPS -fuzztime=2s ./internal/crawl + go test -run '^FuzzRobotsParseAndMatch$' -fuzz=FuzzRobotsParseAndMatch -fuzztime=2s ./internal/politeness + go test -run '^FuzzParseRetryAfter$' -fuzz=FuzzParseRetryAfter -fuzztime=2s ./internal/politeness + go test -run '^FuzzIsPublicIP$' -fuzz=FuzzIsPublicIP -fuzztime=2s ./internal/politeness + go test -run '^FuzzClassify$' -fuzz=FuzzClassify -fuzztime=2s ./internal/classify + go test -run '^FuzzExtractHTML$' -fuzz=FuzzExtractHTML -fuzztime=2s ./internal/extract + go test -run '^FuzzParseLlmsTxt$' -fuzz=FuzzParseLlmsTxt -fuzztime=2s ./internal/extract + go test -run '^FuzzExtractPDFPureGo$' -fuzz=FuzzExtractPDFPureGo -fuzztime=2s ./internal/extract + go test -run '^FuzzDeclarativeFormat$' -fuzz=FuzzDeclarativeFormat -fuzztime=2s ./internal/extract + go test -run '^FuzzBotAuthVerifyRequest$' -fuzz=FuzzBotAuthVerifyRequest -fuzztime=2s ./internal/botauth + go test -run '^FuzzValidateCustomHeaders$' -fuzz=FuzzValidateCustomHeaders -fuzztime=2s ./internal/crawl + go test -run '^FuzzPublicHTTPS$' -fuzz=FuzzPublicHTTPS -fuzztime=2s ./internal/crawl - name: Run allocation microbenchmarks & WASI WebAssembly build check run: | diff --git a/Makefile b/Makefile index 9ee1324..b33efed 100644 --- a/Makefile +++ b/Makefile @@ -19,12 +19,12 @@ test: vet go test -v -race -cover ./... fuzz: - go test -fuzz=FuzzRobotsParseAndMatch -fuzztime=3s ./internal/politeness - go test -fuzz=FuzzParseRetryAfter -fuzztime=3s ./internal/politeness - go test -fuzz=FuzzIsPublicIP -fuzztime=3s ./internal/politeness - go test -fuzz=FuzzClassify -fuzztime=3s ./internal/classify - go test -fuzz=FuzzExtractHTML -fuzztime=3s ./internal/extract - go test -fuzz=FuzzParseLlmsTxt -fuzztime=3s ./internal/extract + go test -run '^FuzzRobotsParseAndMatch$$' -fuzz=FuzzRobotsParseAndMatch -fuzztime=3s ./internal/politeness + go test -run '^FuzzParseRetryAfter$$' -fuzz=FuzzParseRetryAfter -fuzztime=3s ./internal/politeness + go test -run '^FuzzIsPublicIP$$' -fuzz=FuzzIsPublicIP -fuzztime=3s ./internal/politeness + go test -run '^FuzzClassify$$' -fuzz=FuzzClassify -fuzztime=3s ./internal/classify + go test -run '^FuzzExtractHTML$$' -fuzz=FuzzExtractHTML -fuzztime=3s ./internal/extract + go test -run '^FuzzParseLlmsTxt$$' -fuzz=FuzzParseLlmsTxt -fuzztime=3s ./internal/extract bench: go test -bench=. -benchmem ./... diff --git a/cmd/edgefetch-wasm/main_test.go b/cmd/edgefetch-wasm/main_test.go index f4c1f02..837dae5 100644 --- a/cmd/edgefetch-wasm/main_test.go +++ b/cmd/edgefetch-wasm/main_test.go @@ -133,6 +133,29 @@ func TestWasmReactorExportsRoundTrip(t *testing.T) { if strLen == 0 || strings.Contains(string(wasmOutBuf[:strLen]), "Account Manager II | FedEx Careers

Account Manager II

` + curMD := "# Account Manager II" + postMeta := `{"op":"post_extract_html","meta":{"baseUrl":"https://careers.fedex.com/account-manager-ii/job/P25-397759-1","htmlByteLen":` + strconv.Itoa(len(paradoxHTML)) + `}}` + _ = efInPtr(uint32(len(postMeta) + len(paradoxHTML) + len(curMD))) + copy(wasmInBuf, postMeta) + copy(wasmInBuf[len(postMeta):], paradoxHTML) + copy(wasmInBuf[len(postMeta)+len(paradoxHTML):], curMD) + postLen := efCallRaw(uint32(len(postMeta)), uint32(len(postMeta)+len(paradoxHTML)+len(curMD))) + if postLen == 0 || !strings.Contains(string(wasmOutBuf[:postLen]), `"ok":true`) || !strings.Contains(string(wasmOutBuf[:postLen]), `"extractorId":"paradox-olivia"`) { + t.Fatalf("unexpected post_extract_html efCallRaw output: %q", string(wasmOutBuf[:postLen])) + } + // Non-matching page via post_extract_html raw meta-pair returns ok:false + emptyHTML := `Blank

Nothing special here.

` + negMeta := `{"op":"post_extract_html","meta":{"baseUrl":"https://example.org/plain","htmlByteLen":` + strconv.Itoa(len(emptyHTML)) + `}}` + _ = efInPtr(uint32(len(negMeta) + len(emptyHTML))) + copy(wasmInBuf, negMeta) + copy(wasmInBuf[len(negMeta):], emptyHTML) + negLen := efCallRaw(uint32(len(negMeta)), uint32(len(negMeta)+len(emptyHTML))) + if negLen == 0 || !strings.Contains(string(wasmOutBuf[:negLen]), `"ok":false`) { + t.Fatalf("expected post_extract_html ok:false for non-matching page, got: %q", string(wasmOutBuf[:negLen])) + } } func TestWasmManifestFormatTwinPageKeyOptIn(t *testing.T) { diff --git a/cmd/edgefetch-wasm/reactor.go b/cmd/edgefetch-wasm/reactor.go index 230a402..d6e536a 100644 --- a/cmd/edgefetch-wasm/reactor.go +++ b/cmd/edgefetch-wasm/reactor.go @@ -1170,22 +1170,24 @@ func dispatchWasmRPC(rawReq []byte) (any, error) { return map[string]any{"matched": false}, nil } out := map[string]any{ - "matched": true, - "id": m.ID, - "adapterId": m.AdapterID, - "fetchUrl": m.FetchURL, - "kind": string(m.Kind), - "accept": m.Accept, - "rawAccept": m.RawAccept(), - "maxBytes": m.EffectiveMaxBytes(), - "commerceMode": m.CommerceMode(), - "requiresPageKeyOptIn": m.RequiresPageKeyOptIn, - "authMode": m.AuthMode, - "userAgentProfile": m.UserAgentProfile, - "minIntervalMs": m.MinIntervalMs, - "maxCacheTtlMs": m.MaxCacheTtlMs, - "maxConcurrent": m.MaxConcurrent, - "strictRobots": m.StrictRobots, + "matched": true, + "id": m.ID, + "adapterId": m.AdapterID, + "fetchUrl": m.FetchURL, + "kind": string(m.Kind), + "accept": m.Accept, + "rawAccept": m.RawAccept(), + "maxBytes": m.EffectiveMaxBytes(), + "commerceMode": m.CommerceMode(), + "requiresPageKeyOptIn": m.RequiresPageKeyOptIn, + "authMode": m.AuthMode, + "userAgentProfile": m.UserAgentProfile, + "minIntervalMs": m.MinIntervalMs, + "maxCacheTtlMs": m.MaxCacheTtlMs, + "maxConcurrent": m.MaxConcurrent, + "strictRobots": m.StrictRobots, + "allowCrossOriginRedirects": m.AllowCrossOriginRedirects(), + "allowTruncatedStream": m.AllowTruncatedStream(), } if m.FallbackFetchURL != "" { out["fallbackFetchUrl"] = m.FallbackFetchURL @@ -1341,22 +1343,24 @@ func dispatchWasmRPC(rawReq []byte) (any, error) { return map[string]any{"matched": false}, nil } out := map[string]any{ - "matched": true, - "id": m.ID, - "adapterId": m.AdapterID, - "fetchUrl": m.FetchURL, - "kind": string(m.Kind), - "accept": m.Accept, - "rawAccept": m.RawAccept(), - "maxBytes": m.EffectiveMaxBytes(), - "commerceMode": m.CommerceMode(), - "requiresPageKeyOptIn": m.RequiresPageKeyOptIn, - "authMode": m.AuthMode, - "userAgentProfile": m.UserAgentProfile, - "minIntervalMs": m.MinIntervalMs, - "maxCacheTtlMs": m.MaxCacheTtlMs, - "maxConcurrent": m.MaxConcurrent, - "strictRobots": m.StrictRobots, + "matched": true, + "id": m.ID, + "adapterId": m.AdapterID, + "fetchUrl": m.FetchURL, + "kind": string(m.Kind), + "accept": m.Accept, + "rawAccept": m.RawAccept(), + "maxBytes": m.EffectiveMaxBytes(), + "commerceMode": m.CommerceMode(), + "requiresPageKeyOptIn": m.RequiresPageKeyOptIn, + "authMode": m.AuthMode, + "userAgentProfile": m.UserAgentProfile, + "minIntervalMs": m.MinIntervalMs, + "maxCacheTtlMs": m.MaxCacheTtlMs, + "maxConcurrent": m.MaxConcurrent, + "strictRobots": m.StrictRobots, + "allowCrossOriginRedirects": m.AllowCrossOriginRedirects(), + "allowTruncatedStream": m.AllowTruncatedStream(), } if m.FallbackFetchURL != "" { out["fallbackFetchUrl"] = m.FallbackFetchURL @@ -2054,6 +2058,52 @@ func dispatchWasmRPC(rawReq []byte) (any, error) { } return map[string]any{"url": extract.ScrubTwinURLSecrets(p.URL)}, nil + case "check_unbounded_twin_guard": + var p struct { + URL string `json:"url"` + } + if err := json.Unmarshal(env.Payload, &p); err != nil { + return nil, err + } + blocked, msg := extract.CheckUnboundedTwinEndpointGuard(p.URL) + if !blocked { + return map[string]any{"blocked": false}, nil + } + return map[string]any{"blocked": true, "message": msg}, nil + + case "nostr_prepare_nip01": + var p struct { + URL string `json:"url"` + SelfHost string `json:"selfHost"` + SubID string `json:"subId"` + MaxEvents int `json:"maxEvents"` + } + if err := json.Unmarshal(env.Payload, &p); err != nil { + return nil, err + } + return extract.PrepareNostrNIP01(p.URL, p.SelfHost, p.SubID, p.MaxEvents), nil + + case "nostr_format_nip01": + var p struct { + OrigURL string `json:"origUrl"` + RelayURL string `json:"relayUrl"` + SubID string `json:"subId"` + NIP11Raw string `json:"nip11Raw"` + Frames []string `json:"frames"` + MaxEvents int `json:"maxEvents"` + } + if err := json.Unmarshal(env.Payload, &p); err != nil { + return nil, err + } + if p.Frames != nil && len(p.NIP11Raw) == 0 && p.RelayURL == "" { + return map[string]any{"events": extract.ParseNostrNIP01Frames(p.SubID, p.Frames, p.MaxEvents)}, nil + } + doc, ok := extract.FormatNostrNIP01Frames(p.OrigURL, p.RelayURL, p.SubID, p.NIP11Raw, p.Frames, p.MaxEvents) + if !ok || doc == nil { + return map[string]any{"ok": false}, nil + } + return map[string]any{"ok": true, "doc": doc}, nil + case "refine_blocked_map": var p classify.RefineBlockedMapInput if err := json.Unmarshal(env.Payload, &p); err != nil { diff --git a/docs/LIVE-ADAPTER-AUDIT-ROUND2-2026-11.md b/docs/LIVE-ADAPTER-AUDIT-ROUND2-2026-11.md new file mode 100644 index 0000000..8ca9fd8 --- /dev/null +++ b/docs/LIVE-ADAPTER-AUDIT-ROUND2-2026-11.md @@ -0,0 +1,794 @@ +# EdgeFetch Wave 3 / Round 2 Full-Inventory Live Adapter & OTel Trace Audit (2026-11) + +- **Branch:** `feat/adapters-201-400-round2` / `feat/wave3-b7-live-trace-audit` (rebased onto `origin/main` `v2.8.32` + `#148` + `#140` `ecd3c11fa133a6c842fa1c05207bda656cf57380`) +- **Audit Date:** 2026-11-29 (`m7_audit_results.json`: `2026-11-29T12:04:07.907Z`..`2026-11-29T12:09:55.739Z`) +- **WASM Artifact (`hub/src/edgefetch-core.wasm`):** `33,720,584` bytes (`32.16 MiB` raw), deterministic SHA-256 `032C149F22950AFCF611D0647A308D1B7536D00BD572A03311E9C5878C22119B` (verified bit-for-bit identical across forced rebuilds via `node hub/scripts/build-wasm.mjs --force`) +- **WASM Memory Baseline:** `11.00 MiB` (`11534336 B` `<= 12 MiB` budget), `initHeapAlloc=258.2 KiB`, `initSys=2.19 MiB`, `initHeapObjects=1137`, `initNumGC=0`, `ZERO_CRYPTO_DEPS` (`GOOS=wasip1 GOARCH=wasm CGO_ENABLED=0`) +- **OpenAPI Spec Parity (`docs/openapi.json`):** OpenAPI 3.1.0, `v2.8.32`, `47` paths, SHA-256 `073355A04008ED6CC3F98FC6358056F47AF743583B81200BB58C5A400CAE6056` (byte-identical on `npm --prefix hub run openapi:generate` and verified in `hub/test/hub.test.ts`) + +--- + +## 1. Summary & Methodology + +Milestone M7 executed a 100% inventory live origin audit, OpenTelemetry span attribution & secret-scrubbing verification, 4-way negative-probe validation, and fix-on-the-spot sweep across all **200** Wave 3 Round 2 manifests (`#201–#400`), all **7** M0-converted formerly-`detect-only` Wave 2 manifests, all **17** manifest-level `page-key` manifests plus `shopify-storefront-graphql` companion `page-key` discovery (default-ON + explicit `false` opt-out), all **486** compiled YAML manifests (`285` baseline + `job-boards-jsonld-pack` from `#140` + `200` Round 2 with all 11 `#140` overlaps deduplicated 1:1), all **50** Go non-manifest/companion/SSR/built-in extractors, and all **90** keyed provider / OTLP secret-redaction targets with **zero failures**. + +### Harness & Execution Protocol +- **Single Shared WASM Reactor + Host-Disjoint Concurrency:** Executed against **1** shared `edgefetch-core.wasm` instance (`initialMemoryBytes = 11,534,336 B` / `11.00 MiB`, `5` reactor generations across sustained Track A/B/C load, `0` unexpected evictions) with **10** concurrent host-disjoint workers (`concurrency: 10`, within the `8–10` worker specification). +- **Polite Live Crawl & Red-Line Compliance:** Checked `robots.txt` before origin fetches, honored `Crawl-delay` directives (capped at `30s`, e.g., `www.gao.gov` `Crawl-delay: 420`) and `>= 1 req/s` per-host pacing (`minIntervalMs`, e.g., `musicbrainz.org`), sent required User-Agent profiles (`musicbrainz`, `sec-edgar`, `weather-gov`), performed **zero** CAPTCHA/WAF/PoW/login bypasses, **zero** HTML form submissions, and **zero** inbound cookie storage or replay. Genuine origin blocks (`401`/`402`/`403`/WAF/CAPTCHA/PoW/cookie-gate/`robots.txt`/unhydrated CSR shells) were recorded honestly as `blocked_by_origin` and cross-verified against offline golden fixtures. +- **OTel Span & Negative Probes:** Track A verified `edgefetch.adapter_id` span attribution via `RequestTracer` across **512** live URLs (`221` Track A manifests). Track B verified **486/486** compiled manifest smoke runs (`448` golden fixtures + `38` synthetic golden checks), **3,785/3,785** negative probes (4 standard shells `http-404`, `redirect-to-error`, `maintenance-page`, `empty-spa-shell` per adapter plus fixture-specific `negativeCases` — `0` `contentState: "active"` leaks), and **50/50** Go non-manifest/built-in extractors. Track C verified **5/5** `makeKeyHint` length-boundary checks and **90/90** keyed provider / OTLP redaction targets. + +### Final M7 Audit Totals (`m7_audit_results.json`) + +| Audit Track / Metric | Scope | Passed | Failures | Key Metrics | +|---|---:|---:|---:|---| +| **Track A — Live + OTel Audit** | 221 manifests (200 Round 2 + 7 M0-converted + 14 Wave 2 `page-key`, 512 URLs) | **221 / 221** | **0** | `183` live passes (`148` full + `35` partial w/ origin blocks), `25` `blocked_by_origin` + golden PASS, `13` `key_required` 422 clean + golden PASS, max CPU **`73.79 ms`** (`< 75 ms`) | +| **Track A — `page-key` Default-ON + Opt-Out** | All 17 `page-key` manifests (14 Wave 2 + 3 Wave 3) + `shopify-storefront-graphql` companion `page-key` | **18 / 18** | **0** | Default/omitted resolves twin/companion; `allowPageKeyTwins: false` resolves `null` | +| **Track B — Full Inventory Smoke** | All 486 compiled YAML manifests (448 fixtures + 38 synthetic) | **486 / 486** | **0** | Max CPU **`3.53 ms`**, 100% `edgefetch.adapter_id` span match & Rule 4 clean | +| **Track B — Negative Probes** | 4-way standard shells + fixture `negativeCases` | **3,785 / 3,785** | **0** | Zero `contentState: "active"` leaks across 404/error/maintenance/CSR shells | +| **Track B — Go Built-ins & Companions** | ATS, commerce, CMS twins, SSR hydration, schema-org, MediaWiki/SO/RFC/LLMs/PDF | **50 / 50** | **0** | 15 ATS + 3 feeds + 2 ATS discovery + 8 commerce + 4 CMS/companions + 12 hydration + 6 built-ins | +| **Track C — `makeKeyHint` & Keyed Redaction / OTLP** | 5 `makeKeyHint` cases + 90 targets (71 keyed manifests + 6 specs + 13 sub-providers) | **5/5** & **90/90** | **0** | `< 16 -> ****`, `>= 16 -> ...last4`; raw/encoded/`+`/lowerHex scrubbing; cross/same-origin 302 block; OTLP `sanitizeSpanAttributes` + `buildOtlpTracePayload` clean | +| **Combined Total** | Tracks A + B + C | **All Green** | **0** | `totalFailures: 0` | + +--- + +## 2. Full Inventory Table 1 — All 486 Compiled YAML Manifests + +Every manifest in `internal/extract/manifests/*.yaml` and `internal/extract/manifests/compiled.json` (sorted alphabetically by `id`). Track A manifests (`221`: `200` Round 2 + `7` M0-converted + `14` Wave 2 `page-key`) include live polite origin outcomes, `edgefetch.adapter_id` spans, and Track A CPU latencies; all `486` manifests include Track B offline smoke and 4-way + fixture negative verification. + +| # | id | category | batch | auth_mode | Live / Polite Outcome or Track B Smoke | `edgefetch.adapter_id` Span | CPU Latency (ms) / 4-Way Negative Status | +|---:|---|---|---|---|---|---|---| +| 1 | `acalog` | public-records | wave3-b1 | `html` | pass (2 URLs) | `acalog` (verified) | 5.63 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 2 | `accela-citizen-access` | public-records | wave3-b1 | `html` | pass (1 URL) | `accela-citizen-access` (verified) | 2.32 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 3 | `aem` | developer | wave2a-b1 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `aem` (smoke verified) | 0.54 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 4 | `aftership-tracking-page` | commerce-social | wave3-b2 | `pub` | blocked_by_origin (HTTP 403, golden fallback PASS) | `aftership-tracking-page` (verified) | 1.76 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 5 | `agenda-portal-pack` | public-records | wave3-b1 | `html` | pass (2 live) + blocked_by_origin (1, golden fallback PASS) | `agenda-portal-pack` (verified) | 9.34 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 6 | `airnow` | research-health | wave2c-b4 | `key` | Track B smoke PASS (fixture, HTTP 200, `active`) | `airnow` (smoke verified) | 0.95 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 7 | `algolia` | developer | wave2a-b1 | `page-key` | blocked_by_origin (HTTP 403, golden fallback PASS) | `algolia` (verified) | 0.77 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 8 | `american-legal-publishing` | public-records | wave2c-b3 | `html` | Track B smoke PASS (fixture, HTTP 200, `active`) | `american-legal-publishing` (smoke verified) | 1.35 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 9 | `ansible-puppet-forge` | developer | wave3-b4 | `pub` | pass (2 URLs) | `ansible-puppet-forge` (verified) | 6.95 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 10 | `ap-news` | commerce-social | wave2d-b5 | `html` | Track B smoke PASS (fixture, HTTP 200, `active`) | `ap-news` (smoke verified) | 0.86 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 11 | `api-docs-portals` | developer | wave2d-b6 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `api-docs-portals` (smoke verified) | 2.05 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 12 | `apis-guru` | developer | wave3-b4 | `pub` | pass (3 URLs) | `apis-guru` (verified) | 5.93 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 13 | `appfolio-listings` | commerce-social | wave3-b2 | `pub` | pass (1 URL) | `appfolio-listings` (verified) | 32.14 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 14 | `apple-app-store` | developer | baseline | `undefined` | Track B smoke PASS (synthetic, HTTP 200, `active`) | `apple-app-store` (smoke verified) | 1.89 ms (smoke) / synthetic + 4-way neg pass | +| 15 | `arc-xp` | commerce-social | wave2a-b1 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `arc-xp` (smoke verified) | 0.49 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 16 | `arcgis-hub` | public-records | wave3-b1 | `pub` | pass (2 URLs) | `arcgis-hub` (verified) | 0.96 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 17 | `arcgis` | public-records | baseline | `undefined` | Track B smoke PASS (fixture, HTTP 200, `active`) | `arcgis` (smoke verified) | 2.19 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 18 | `artifact-hub` | developer | wave3-b4 | `pub` | pass (2 URLs) | `artifact-hub` (verified) | 5.22 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 19 | `arxiv` | research-health | baseline | `undefined` | Track B smoke PASS (fixture, HTTP 200, `active`) | `arxiv` (smoke verified) | 0.38 ms (smoke) / golden + 4-way + 0 fixture neg (4 neg pass) | +| 20 | `association-ams-pack` | commerce-social | wave3-b2 | `html` | pass (2 URLs) | `association-ams-pack` (verified) | 5.84 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 21 | `atlassian-statuspage` | developer | wave2a-b1 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `atlassian-statuspage` (smoke verified) | 2.18 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 22 | `auto-dealer-inventory` | commerce-social | wave2c-b4 | `html` | Track B smoke PASS (fixture, HTTP 200, `active`) | `auto-dealer-inventory` (smoke verified) | 3.53 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 23 | `auto-parts-fitment` | commerce-social | wave2d-b5 | `html` | Track B smoke PASS (fixture, HTTP 200, `active`) | `auto-parts-fitment` (smoke verified) | 2.76 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 24 | `back-market-swappa` | commerce-social | wave3-b5 | `html` | blocked_by_origin (HTTP 422, golden fallback PASS) | `back-market-swappa` (verified) | 3.79 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 25 | `bamboohr-breezy-recruitee` | jobs | baseline | `undefined` | Track B smoke PASS (fixture, HTTP 200, `active`) | `bamboohr-board` (smoke verified) | 1.01 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 26 | `bandcamp` | commerce-social | wave3-b6 | `html` | pass (2 URLs) | `bandcamp` (verified) | 23.53 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 27 | `bazaarvoice` | commerce-social | wave2a-b1 | `page-key` | pass (1 URL) | `bazaarvoice` (verified) | 0.88 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 28 | `bbb` | commerce-social | wave2d-b6 | `html` | Track B smoke PASS (fixture, HTTP 200, `active`) | `bbb` (smoke verified) | 1.72 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 29 | `bea` | finance | wave2c-b3 | `key` | Track B smoke PASS (fixture, HTTP 200, `active`) | `bea` (smoke verified) | 0.84 ms (smoke) / golden + 4-way + 5 fixture neg (9 neg pass) | +| 30 | `bentobox` | commerce-social | wave3-b2 | `html` | pass (1 live) + blocked_by_origin (1, golden fallback PASS) | `bentobox` (verified) | 4.46 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 31 | `bestbuy` | commerce-social | wave2d-b5 | `key` | Track B smoke PASS (fixture, HTTP 200, `active`) | `bestbuy` (smoke verified) | 1.19 ms (smoke) / golden + 4-way + 5 fixture neg (9 neg pass) | +| 32 | `bgp-asn` | developer | wave3-b4 | `pub` | pass (2 URLs) | `bgp-asn` (verified) | 50.38 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 33 | `bicycle-blue-book` | commerce-social | wave3-b5 | `html` | pass (2 URLs) | `bicycle-blue-book` (verified) | 12.72 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 34 | `bicycle-brake-docs` | commerce-social | wave3-b5 | `html` | pass (4 URLs) | `bicycle-brake-docs` (verified) | 33.08 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 35 | `bicycle-tire-specs` | commerce-social | wave3-b5 | `html` | pass (6 URLs) | `bicycle-tire-specs` (verified) | 30.37 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 36 | `bicycleretailer` | commerce-social | wave1 | `undefined` | Track B smoke PASS (synthetic, HTTP 200, `active`) | `bicycleretailer` (smoke verified) | 0.43 ms (smoke) / synthetic + 4-way neg pass | +| 37 | `big-cartel` | commerce-social | wave2b-b2a | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `big-cartel` (smoke verified) | 1.45 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 38 | `bigcommerce-store` | commerce-social | wave1 | `undefined` | Track B smoke PASS (fixture, HTTP 200, `active`) | `bigcommerce-store` (smoke verified) | 0.74 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 39 | `bike-index` | public-records | wave2b-b2a | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `bike-index` (smoke verified) | 1.37 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 40 | `bikereg-usacycling` | commerce-social | wave3-b2 | `pub` | pass (3 URLs) | `bikereg-usacycling` (verified) | 3.08 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 41 | `biorxiv-medrxiv` | research-health | wave3-b4 | `pub` | pass (3 URLs) | `biorxiv-medrxiv` (verified) | 14.24 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 42 | `bis-entity-list` | public-records | wave3-b3 | `pub` | pass (3 URLs) | `bis-entity-list` (verified) | 26.22 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 43 | `bitbucket-cloud` | developer | wave3-b4 | `pub` | pass (2 URLs) | `bitbucket-cloud` (verified) | 0.40 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 44 | `blackboard-wcm` | public-records | wave3-b1 | `html` | pass (1 live) + blocked_by_origin (1, golden fallback PASS) | `blackboard-wcm` (verified) | 15.97 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 45 | `bloomreach-discovery` | commerce-social | wave2b-b2a | `page-key` | pass (1 URL) | `bloomreach-discovery` (verified) | 0.60 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 46 | `bls` | public-records | wave2c-b3 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `bls` (smoke verified) | 0.48 ms (smoke) / golden + 4-way + 5 fixture neg (9 neg pass) | +| 47 | `bluesky-thread` | commerce-social | baseline | `undefined` | Track B smoke PASS (synthetic, HTTP 200, `active`) | `bluesky-thread` (smoke verified) | 0.23 ms (smoke) / synthetic + 4-way neg pass | +| 48 | `boarddocs` | public-records | wave3-b1 | `pub` | blocked_by_origin (HTTP 403, golden fallback PASS) | `boarddocs` (verified) | 1.27 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 49 | `bosch-ebike-help` | developer | wave1 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `bosch-ebike-help` (smoke verified) | 2.99 ms (smoke) / golden + 4-way + 0 fixture neg (4 neg pass) | +| 50 | `branded-tracking-pack` | commerce-social | wave3-b2 | `pub` | blocked_by_origin (HTTP 200, golden fallback PASS) | `branded-tracking-pack` (verified) | 0.54 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 51 | `brightcove` | commerce-social | wave2d-b5 | `page-key` | pass (1 live) + blocked_by_origin (1, golden fallback PASS) | `brightcove` (verified) | 52.72 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 52 | `brightspot` | commerce-social | wave2d-b5 | `html` | Track B smoke PASS (fixture, HTTP 200, `active`) | `brightspot` (smoke verified) | 0.32 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 53 | `browser-addons-amo-cws` | developer | wave3-b4 | `pub` | pass (2 URLs) | `browser-addons-amo-cws` (verified) | 6.03 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 54 | `bts-transtats` | public-records | wave2c-b4 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `bts-transtats` (smoke verified) | 0.91 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 55 | `bugzilla` | developer | wave3-b4 | `pub` | pass (1 live) + blocked_by_origin (2, golden fallback PASS) | `bugzilla` (verified) | 0.44 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 56 | `bullhorn-career-portal` | jobs | wave3-b1 | `pub` | pass (1 URL) | `bullhorn-career-portal` (verified) | 1.29 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 57 | `bumm-de` | commerce-social | wave1 | `undefined` | Track B smoke PASS (synthetic, HTTP 200, `active`) | `bumm-de` (smoke verified) | 0.32 ms (smoke) / synthetic + 4-way neg pass | +| 58 | `bundlephobia-packagephobia` | developer | wave3-b4 | `pub` | pass (2 URLs) | `bundlephobia-packagephobia` (verified) | 0.25 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 59 | `canvas-public-courses` | public-records | wave3-b1 | `pub` | pass (1 live) + blocked_by_origin (1, golden fallback PASS) | `canvas-public-courses` (verified) | 2.59 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 60 | `cargo-ebike-oems` | commerce-social | wave3-b5 | `html` | pass (4 URLs) | `cargo-ebike-oems` (verified) | 31.17 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 61 | `carrier-tracking-official` | commerce-social | wave3-b3 | `key` | pass (key_required_unconfigured_clean, 3 URLs + golden fallback) | `carrier-tracking-official` (verified) | 1.30 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 62 | `cbo` | public-records | wave3-b3 | `pub` | pass (1 live) + blocked_by_origin (1, golden fallback PASS) | `cbo` (verified) | 2.71 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 63 | `cbp-cross-rulings` | public-records | wave3-b3 | `pub` | pass (2 URLs) | `cbp-cross-rulings` (verified) | 0.79 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 64 | `cdc-wonder-healthdata` | research-health | wave2c-b4 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `cdc-wonder-healthdata` (smoke verified) | 0.25 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 65 | `census-foreign-trade` | public-records | wave3-b3 | `pub` | blocked_by_origin (HTTP 200, golden fallback PASS) | `census-foreign-trade` (verified) | 0.63 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 66 | `census` | public-records | wave2c-b3 | `key` | Track B smoke PASS (fixture, HTTP 200, `active`) | `census` (smoke verified) | 0.87 ms (smoke) / golden + 4-way + 5 fixture neg (9 neg pass) | +| 67 | `certificate-transparency` | developer | wave3-b4 | `pub` | pass (1 URL) | `certificate-transparency` (verified) | 0.54 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 68 | `cfpb-complaints` | finance | wave2c-b3 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `cfpb-complaints` (smoke verified) | 1.12 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 69 | `chairish-1stdibs` | commerce-social | wave3-b5 | `html` | pass (2 URLs) | `chairish-1stdibs` (verified) | 18.45 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 70 | `chambermaster-growthzone` | commerce-social | wave3-b2 | `html` | pass (2 URLs) | `chambermaster-growthzone` (verified) | 4.45 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 71 | `changelog-roadmap-pack` | developer | wave2b-b2b | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `changelog-roadmap-pack` (smoke verified) | 1.12 ms (smoke) / golden + 4-way + 5 fixture neg (9 neg pass) | +| 72 | `chronicling-america` | public-records | wave2c-b4 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `chronicling-america` (smoke verified) | 2.30 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 73 | `cisa-advisories-ics` | developer | wave3-b4 | `pub` | pass (3 URLs) | `cisa-advisories-ics` (verified) | 27.25 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 74 | `cisa-kev` | developer | wave3-b4 | `pub` | pass (2 URLs) | `cisa-kev` (verified) | 44.12 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 75 | `civicclerk` | public-records | wave3-b1 | `pub` | pass (3 URLs) | `civicclerk` (verified) | 5.13 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 76 | `civicplus` | public-records | wave3-b1 | `html` | pass (3 URLs) | `civicplus` (verified) | 55.81 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 77 | `ckan` | public-records | baseline | `undefined` | Track B smoke PASS (fixture, HTTP 200, `active`) | `ckan` (smoke verified) | 0.42 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 78 | `classic-forum-pack` | commerce-social | wave2b-b2b | `html` | Track B smoke PASS (fixture, HTTP 200, `active`) | `classic-forum-pack` (smoke verified) | 2.18 ms (smoke) / golden + 4-way + 5 fixture neg (9 neg pass) | +| 79 | `clinicaltrials` | research-health | baseline | `undefined` | Track B smoke PASS (fixture, HTTP 200, `active`) | `clinicaltrials` (smoke verified) | 0.63 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 80 | `cms-data` | research-health | wave2c-b4 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `cms-data` (smoke verified) | 0.77 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 81 | `cms-price-transparency` | research-health | wave3-b3 | `pub` | pass (4 URLs) | `cms-price-transparency` (verified) | 4.67 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 82 | `college-scorecard` | public-records | wave2c-b3 | `key` | Track B smoke PASS (fixture, HTTP 200, `active`) | `college-scorecard` (smoke verified) | 1.17 ms (smoke) / golden + 4-way + 5 fixture neg (9 neg pass) | +| 83 | `company-newsrooms` | commerce-social | wave3-b2 | `pub` | pass (3 live) + blocked_by_origin (1, golden fallback PASS) | `company-newsrooms` (verified) | 12.03 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 84 | `confluence-public` | developer | wave2b-b2b | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `confluence-public` (smoke verified) | 0.67 ms (smoke) / golden + 4-way + 5 fixture neg (9 neg pass) | +| 85 | `congress-gov` | public-records | wave2c-b3 | `key` | Track B smoke PASS (fixture, HTTP 200, `active`) | `congress-gov` (smoke verified) | 1.04 ms (smoke) / golden + 4-way + 5 fixture neg (9 neg pass) | +| 86 | `constructor-io` | commerce-social | wave2b-b2a | `page-key` | pass (1 URL) | `constructor-io` (verified) | 2.02 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 87 | `copyright-office` | public-records | wave2c-b4 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `copyright-office` (smoke verified) | 0.90 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 88 | `core-ac` | research-health | wave3-b4 | `key` | pass (key_required_unconfigured_clean, 3 URLs + golden fallback) | `core-ac` (verified) | 0.76 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 89 | `cornell-lii` | public-records | wave1 | `undefined` | Track B smoke PASS (synthetic, HTTP 200, `active`) | `cornell-lii` (smoke verified) | 0.29 ms (smoke) / synthetic + 4-way neg pass | +| 90 | `costco-sams-club` | commerce-social | wave2d-b5 (m0-converted) | `html` | pass (2 URLs) | `costco-sams-club` (verified) | 15.41 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 91 | `county-assessor` | public-records | wave2d-b6 | `html` | Track B smoke PASS (fixture, HTTP 200, `active`) | `county-assessor` (smoke verified) | 1.60 ms (smoke) / golden + 4-way + 6 fixture neg (10 neg pass) | +| 92 | `coursedog` | public-records | wave3-b1 | `pub` | pass (2 live) + blocked_by_origin (1, golden fallback PASS) | `coursedog` (verified) | 43.66 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 93 | `courseleaf` | public-records | wave3-b1 | `html` | pass (2 live) + blocked_by_origin (1, golden fallback PASS) | `courseleaf` (verified) | 6.89 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 94 | `courtlistener` | public-records | wave2c-b3 | `key` | Track B smoke PASS (fixture, HTTP 200, `active`) | `courtlistener` (smoke verified) | 0.67 ms (smoke) / golden + 4-way + 5 fixture neg (9 neg pass) | +| 95 | `coveo` | developer | wave2b-b2a | `page-key` | pass (1 URL) | `coveo` (verified) | 4.62 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 96 | `cpsc-ebike-battery` | public-records | wave2b-b2a | `html` | Track B smoke PASS (fixture, HTTP 200, `active`) | `cpsc-ebike-battery` (smoke verified) | 0.89 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 97 | `cpsc-ebike-incidents` | public-records | wave3-b5 | `pub` | pass (2 URLs) | `cpsc-ebike-incidents` (verified) | 22.40 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 98 | `cpsc-recalls` | public-records | wave1 | `undefined` | Track B smoke PASS (fixture, HTTP 200, `active`) | `cpsc-recalls` (smoke verified) | 0.33 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 99 | `crates-io` | developer | baseline | `undefined` | Track B smoke PASS (synthetic, HTTP 200, `active`) | `crates-io` (smoke verified) | 0.33 ms (smoke) / synthetic + 4-way neg pass | +| 100 | `creator-digital-stores` | commerce-social | wave3-b5 | `html` | pass (1 URL) | `creator-digital-stores` (verified) | 8.85 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 101 | `cve-org` | developer | wave3-b4 | `pub` | pass (1 URL) | `cve-org` (verified) | 0.97 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 102 | `dailymed` | research-health | wave2c-b4 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `dailymed` (smoke verified) | 2.16 ms (smoke) / golden + 4-way + 5 fixture neg (9 neg pass) | +| 103 | `datacite` | research-health | wave3-b4 | `pub` | pass (2 URLs) | `datacite` (verified) | 0.75 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 104 | `dblp` | research-health | wave3-b4 | `pub` | blocked_by_origin (HTTP 0, golden fallback PASS) | `dblp` (verified) | 0.59 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 105 | `dealer-locator-pack` | commerce-social | wave2b-b2a | `page-key` | blocked_by_origin (HTTP 0, golden fallback PASS) | `dealer-locator-pack` (verified) | 0.86 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 106 | `deps-dev` | developer | wave2d-b6 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `deps-dev` (smoke verified) | 1.18 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 107 | `dev-to` | commerce-social | baseline | `undefined` | Track B smoke PASS (synthetic, HTTP 200, `active`) | `dev-to` (smoke verified) | 0.21 ms (smoke) / synthetic + 4-way neg pass | +| 108 | `dining-reservations` | commerce-social | wave2d-b6 (m0-converted) | `html` | blocked_by_origin (HTTP 0, golden fallback PASS) | `dining-reservations` (verified) | 1.96 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 109 | `discogs` | commerce-social | wave3-b6 | `pub` | pass (3 URLs) | `discogs` (verified) | 0.90 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 110 | `discourse-topic` | commerce-social | baseline | `undefined` | Track B smoke PASS (synthetic, HTTP 200, `active`) | `discourse-topic` (smoke verified) | 0.41 ms (smoke) / synthetic + 4-way neg pass | +| 111 | `dkan` | public-records | wave3-b1 | `pub` | pass (2 URLs) | `dkan` (verified) | 0.24 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 112 | `docker-hub` | developer | wave1 | `undefined` | Track B smoke PASS (fixture, HTTP 200, `active`) | `docker-hub` (smoke verified) | 0.30 ms (smoke) / golden + 4-way + 0 fixture neg (4 neg pass) | +| 113 | `docs-rs` | developer | wave2d-b6 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `docs-rs` (smoke verified) | 0.58 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 114 | `doe-osti` | research-health | wave3-b4 | `pub` | pass (3 URLs) | `doe-osti` (verified) | 0.80 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 115 | `doi-crossref` | research-health | baseline | `undefined` | Track B smoke PASS (synthetic, HTTP 200, `active`) | `doi-crossref` (smoke verified) | 0.23 ms (smoke) / synthetic + 4-way neg pass | +| 116 | `dol-enforcement` | public-records | wave3-b3 | `key` | pass (3 URLs) | `dol-enforcement` (verified) | 10.69 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 117 | `dpla` | public-records | wave2c-b4 | `key` | Track B smoke PASS (fixture, HTTP 200, `active`) | `dpla` (smoke verified) | 0.55 ms (smoke) / golden + 4-way + 5 fixture neg (9 neg pass) | +| 118 | `e-bike-state-laws` | public-records | wave3-b5 | `html` | pass (3 live) + blocked_by_origin (1, golden fallback PASS) | `e-bike-state-laws` (verified) | 11.03 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 119 | `ebay` | commerce-social | wave2d-b5 | `key` | Track B smoke PASS (fixture, HTTP 200, `active`) | `ebay` (smoke verified) | 0.77 ms (smoke) / golden + 4-way + 5 fixture neg (9 neg pass) | +| 120 | `ebike-drive-systems` | commerce-social | wave3-b5 | `html` | pass (4 URLs) | `ebike-drive-systems` (verified) | 34.91 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 121 | `ebike-state-laws` | public-records | wave2b-b2a | `html` | Track B smoke PASS (fixture, HTTP 200, `active`) | `ebike-state-laws` (smoke verified) | 0.86 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 122 | `ecfr` | public-records | wave2c-b3 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `ecfr` (smoke verified) | 0.77 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 123 | `ecode360-general-code` | public-records | wave2c-b3 | `html` | Track B smoke PASS (fixture, HTTP 200, `active`) | `ecode360-general-code` (smoke verified) | 0.34 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 124 | `ecwid` | commerce-social | wave2b-b2a | `page-key` | pass (1 URL) | `ecwid` (verified) | 31.66 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 125 | `edge-cloud-changelogs` | developer | wave2d-b6 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `edge-cloud-changelogs` (smoke verified) | 1.44 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 126 | `edlio-thrillshare` | public-records | wave3-b1 | `html` | pass (3 URLs) | `edlio-thrillshare` (verified) | 8.02 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 127 | `edu-job-boards` | jobs | wave3-b1 | `pub` | pass (3 live) + blocked_by_origin (1, golden fallback PASS) | `edu-job-boards` (verified) | 4.97 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 128 | `edx-coursera` | public-records | wave3-b1 | `pub` | pass (3 URLs) | `edx-coursera` (verified) | 9.81 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 129 | `eeoc-litigation` | public-records | wave3-b3 | `pub` | pass (3 URLs) | `eeoc-litigation` (verified) | 17.58 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 130 | `eia` | public-records | wave2c-b3 | `key` | Track B smoke PASS (fixture, HTTP 200, `active`) | `eia` (smoke verified) | 0.55 ms (smoke) / golden + 4-way + 5 fixture neg (9 neg pass) | +| 131 | `electronics-retail-specs` | commerce-social | wave2d-b5 | `html` | Track B smoke PASS (fixture, HTTP 200, `active`) | `electronics-retail-specs` (smoke verified) | 1.27 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 132 | `endoflife-date` | developer | wave3-b4 | `pub` | pass (3 URLs) | `endoflife-date` (verified) | 1.23 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 133 | `energy-star` | public-records | wave3-b6 | `pub` | pass (3 URLs) | `energy-star` (verified) | 2.22 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 134 | `enterprise-ats-full` | jobs | wave2d-b5 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `enterprise-ats-full` (smoke verified) | 1.32 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 135 | `enterprise-ats` | jobs | baseline | `undefined` | Track B smoke PASS (fixture, HTTP 200, `active`) | `oracle-hcm-board` (smoke verified) | 0.36 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 136 | `epa-envirofacts-echo` | research-health | wave2c-b4 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `epa-envirofacts-echo` (smoke verified) | 0.87 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 137 | `epa-fueleconomy` | public-records | wave2c-b4 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `epa-fueleconomy` (smoke verified) | 0.97 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 138 | `etsy` | commerce-social | wave2d-b5 | `key` | Track B smoke PASS (fixture, HTTP 200, `active`) | `etsy` (smoke verified) | 0.92 ms (smoke) / golden + 4-way + 5 fixture neg (9 neg pass) | +| 139 | `eur-lex` | public-records | wave1 | `undefined` | Track B smoke PASS (fixture, HTTP 200, `active`) | `eur-lex` (smoke verified) | 0.34 ms (smoke) / golden + 4-way + 0 fixture neg (4 neg pass) | +| 140 | `eventbrite` | commerce-social | wave2d-b6 | `key` | Track B smoke PASS (fixture, HTTP 200, `active`) | `eventbrite` (smoke verified) | 1.75 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 141 | `everycrsreport` | public-records | wave3-b3 | `pub` | pass (3 URLs) | `everycrsreport` (verified) | 2.18 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 142 | `exploit-db` | developer | wave3-b4 | `pub` | pass (2 URLs) | `exploit-db` (verified) | 20.79 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 143 | `faa-registry` | public-records | wave2c-b4 | `html` | Track B smoke PASS (fixture, HTTP 200, `active`) | `faa-registry` (smoke verified) | 0.80 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 144 | `farcaster-hub` | commerce-social | wave3-b6 | `key` | pass (3 URLs) | `farcaster-hub` (verified) | 11.62 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 145 | `fcc-ecfs` | public-records | wave3-b3 | `key` | pass (key_required_unconfigured_clean, 2 URLs + golden fallback) | `fcc-ecfs` (verified) | 0.83 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 146 | `fcc-id` | public-records | wave1 | `undefined` | Track B smoke PASS (fixture, HTTP 200, `active`) | `fcc-id` (smoke verified) | 0.63 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 147 | `fcc-test-report` | public-records | wave3-b6 | `pub` | blocked_by_origin (HTTP 403, golden fallback PASS) | `fcc-test-report` (verified) | 1.91 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 148 | `fcc-uls` | public-records | wave3-b3 | `pub` | pass (3 URLs) | `fcc-uls` (verified) | 1.32 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 149 | `fdic-bankfind` | finance | wave2c-b3 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `fdic-bankfind` (smoke verified) | 0.57 ms (smoke) / golden + 4-way + 5 fixture neg (9 neg pass) | +| 150 | `fec` | public-records | wave2c-b3 | `key` | Track B smoke PASS (fixture, HTTP 200, `active`) | `fec` (smoke verified) | 0.76 ms (smoke) / golden + 4-way + 5 fixture neg (9 neg pass) | +| 151 | `fed-h15-datadownload` | finance | wave3-b6 | `pub` | pass (3 URLs) | `fed-h15-datadownload` (verified) | 8.75 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 152 | `federal-register` | public-records | wave1 | `undefined` | Track B smoke PASS (fixture, HTTP 200, `active`) | `federal-register` (smoke verified) | 0.50 ms (smoke) / golden + 4-way + 0 fixture neg (4 neg pass) | +| 153 | `fediverse-pack` | commerce-social | wave3-b2 | `pub` | pass (2 URLs) | `fediverse-pack` (verified) | 0.66 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 154 | `fema-openfema` | public-records | wave2c-b4 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `fema-openfema` (smoke verified) | 0.70 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 155 | `ferc-nrc-dockets` | public-records | wave3-b3 | `pub` | blocked_by_origin (HTTP 403, golden fallback PASS) | `ferc-nrc-dockets` (verified) | 1.32 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 156 | `ffiec-cdr` | finance | wave3-b6 | `pub` | pass (2 URLs) | `ffiec-cdr` (verified) | 2.05 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 157 | `finalsite` | public-records | wave3-b1 | `html` | pass (2 URLs) | `finalsite` (verified) | 6.78 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 158 | `financial-regulators-enforcement` | finance | wave3-b3 | `pub` | pass (4 URLs) | `financial-regulators-enforcement` (verified) | 5.21 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 159 | `finra-brokercheck` | finance | wave2c-b3 (m0-converted) | `pub` | pass (3 URLs) | `finra-brokercheck` (verified) | 0.47 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 160 | `first-epss` | developer | wave3-b4 | `pub` | pass (1 URL) | `first-epss` (verified) | 0.23 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 161 | `fmcsa-safer` | public-records | wave2c-b4 | `key` | Track B smoke PASS (fixture, HTTP 200, `active`) | `fmcsa-safer` (smoke verified) | 0.67 ms (smoke) / golden + 4-way + 5 fixture neg (9 neg pass) | +| 162 | `foursquare-places` | commerce-social | wave2d-b6 | `key` | Track B smoke PASS (fixture, HTTP 200, `active`) | `foursquare-places` (smoke verified) | 1.06 ms (smoke) / golden + 4-way + 5 fixture neg (9 neg pass) | +| 163 | `fox-ridefox` | developer | wave3-b5 | `html` | pass (2 URLs) | `fox-ridefox` (verified) | 20.19 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 164 | `fpds-sam-contract-awards` | public-records | wave2c-b3 | `key` | Track B smoke PASS (fixture, HTTP 200, `active`) | `fpds-sam-contract-awards` (smoke verified) | 0.74 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 165 | `fred` | finance | wave2c-b3 | `key` | Track B smoke PASS (fixture, HTTP 200, `active`) | `fred` (smoke verified) | 0.91 ms (smoke) / golden + 4-way + 5 fixture neg (9 neg pass) | +| 166 | `freshdesk-portal` | developer | wave2b-b2b | `html` | Track B smoke PASS (fixture, HTTP 200, `active`) | `freshdesk-portal` (smoke verified) | 1.14 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 167 | `ftc-cases` | public-records | wave3-b3 | `pub` | pass (3 URLs) | `ftc-cases` (verified) | 49.90 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 168 | `gannett-usatoday-network` | commerce-social | wave2d-b5 | `html` | Track B smoke PASS (fixture, HTTP 200, `active`) | `gannett-usatoday-network` (smoke verified) | 0.35 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 169 | `gao-reports` | public-records | wave3-b3 | `pub` | pass (2 URLs) | `gao-reports` (verified) | 20.63 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 170 | `gem-ats` | jobs | baseline | `undefined` | Track B smoke PASS (fixture, HTTP 200, `active`) | `gem-board` (smoke verified) | 0.25 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 171 | `genius-lyrics` | commerce-social | wave3-b6 | `html` | pass (2 live) + blocked_by_origin (1, golden fallback PASS) | `genius-lyrics` (verified) | 16.35 ms / golden + 4-way + 6 fixture neg (10 neg pass) | +| 172 | `geometrygeeks-99spokes` | commerce-social | wave3-b5 | `html` | pass (1 URL) | `geometrygeeks-99spokes` (verified) | 3.53 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 173 | `gerrit` | developer | wave3-b4 | `pub` | pass (3 URLs) | `gerrit` (verified) | 2.60 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 174 | `giant-liv-bikes` | commerce-social | wave1 | `undefined` | Track B smoke PASS (synthetic, HTTP 200, `active`) | `giant-liv-bikes` (smoke verified) | 0.71 ms (smoke) / synthetic + 4-way neg pass | +| 175 | `github-gist` | developer | baseline | `undefined` | Track B smoke PASS (synthetic, HTTP 200, `active`) | `github-gist` (smoke verified) | 0.47 ms (smoke) / synthetic + 4-way neg pass | +| 176 | `gitlab-forgejo` | developer | baseline | `undefined` | Track B smoke PASS (fixture, HTTP 200, `active`) | `gitlab-readme-json` (smoke verified) | 0.21 ms (smoke) / golden + 4-way + 0 fixture neg (4 neg pass) | +| 177 | `google-my-maps-kml` | commerce-social | wave2b-b2a | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `google-my-maps-kml` (smoke verified) | 1.24 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 178 | `google-places` | commerce-social | wave2d-b6 | `key` | Track B smoke PASS (fixture, HTTP 200, `active`) | `google-places` (smoke verified) | 0.81 ms (smoke) / golden + 4-way + 5 fixture neg (9 neg pass) | +| 179 | `google-play` | developer | baseline | `undefined` | Track B smoke PASS (synthetic, HTTP 200, `active`) | `google-play` (smoke verified) | 0.25 ms (smoke) / synthetic + 4-way neg pass | +| 180 | `google-shopping-feed` | commerce-social | wave2d-b5 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `google-shopping-feed` (smoke verified) | 1.31 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 181 | `gorgias-reamaze` | commerce-social | wave3-b2 | `html` | pass (2 URLs) | `gorgias-reamaze` (verified) | 20.74 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 182 | `gov-wordpress-newsrooms` | public-records | wave3-b3 | `pub` | pass (3 URLs) | `gov-wordpress-newsrooms` (verified) | 11.15 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 183 | `granicus-govdelivery` | public-records | wave3-b1 | `pub` | pass (1 URL) | `granicus-govdelivery` (verified) | 2.23 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 184 | `grants-gov` | public-records | wave2c-b3 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `grants-gov` (smoke verified) | 0.57 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 185 | `greenhouse-lever-boards` | jobs | baseline | `undefined` | Track B smoke PASS (fixture, HTTP 200, `active`) | `greenhouse-board` (smoke verified) | 0.21 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 186 | `gs1-us-datahub` | commerce-social | wave3-b6 | `key` | pass (1 live) + blocked_by_origin (2, golden fallback PASS) | `gs1-us-datahub` (verified) | 7.86 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 187 | `gsa-site-scanning` | public-records | wave3-b3 | `key` | pass (key_required_unconfigured_clean, 2 URLs + golden fallback) | `gsa-site-scanning` (verified) | 0.52 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 188 | `hackernews` | commerce-social | baseline | `undefined` | Track B smoke PASS (synthetic, HTTP 200, `active`) | `hackernews` (smoke verified) | 0.42 ms (smoke) / synthetic + 4-way neg pass | +| 189 | `hardware-farm-specs` | commerce-social | wave2d-b5 | `html` | Track B smoke PASS (fixture, HTTP 200, `active`) | `hardware-farm-specs` (smoke verified) | 0.70 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 190 | `hathitrust` | public-records | wave2c-b4 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `hathitrust` (smoke verified) | 2.17 ms (smoke) / golden + 4-way + 5 fixture neg (9 neg pass) | +| 191 | `hcl-websphere-commerce` | commerce-social | wave2a-b1 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `hcl-websphere-commerce` (smoke verified) | 1.00 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 192 | `headless-cms-delivery` | developer | wave2b-b2b | `page-key` | pass (4 URLs) | `headless-cms-delivery` (verified) | 11.27 ms / golden + 4-way + 6 fixture neg (10 neg pass) | +| 193 | `headless-commerce` | commerce-social | wave2b-b2a | `html` | Track B smoke PASS (fixture, HTTP 200, `active`) | `headless-commerce` (smoke verified) | 0.66 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 194 | `healthcare-careers` | jobs | wave3-b1 | `html` | blocked_by_origin (HTTP 200, golden fallback PASS) | `healthcare-careers` (verified) | 0.41 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 195 | `healthcare-gov-marketplace` | research-health | wave3-b3 | `key` | pass (3 URLs) | `healthcare-gov-marketplace` (verified) | 4.65 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 196 | `helpscout-docs` | developer | wave2b-b2b | `html` | Track B smoke PASS (fixture, HTTP 200, `active`) | `helpscout-docs` (smoke verified) | 0.77 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 197 | `hex-pm` | developer | baseline | `undefined` | Track B smoke PASS (synthetic, HTTP 200, `active`) | `hex-pm` (smoke verified) | 0.22 ms (smoke) / synthetic + 4-way neg pass | +| 198 | `home-depot-lowes` | commerce-social | wave2d-b5 | `html` | Track B smoke PASS (fixture, HTTP 200, `active`) | `home-depot-lowes` (smoke verified) | 0.35 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 199 | `home-goods-jsonld` | commerce-social | wave2d-b5 | `html` | Track B smoke PASS (fixture, HTTP 200, `active`) | `home-goods-jsonld` (smoke verified) | 0.40 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 200 | `homebrew-formulae` | developer | wave1 | `undefined` | Track B smoke PASS (fixture, HTTP 200, `active`) | `homebrew-formulae` (smoke verified) | 0.21 ms (smoke) / golden + 4-way + 0 fixture neg (4 neg pass) | +| 201 | `hourly-smb-ats` | jobs | wave2d-b5 | `html` | Track B smoke PASS (fixture, HTTP 200, `active`) | `hourly-smb-ats` (smoke verified) | 1.81 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 202 | `hrsa-samhsa-locator` | research-health | wave2c-b4 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `hrsa-samhsa-locator` (smoke verified) | 0.65 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 203 | `hubspot-cms` | developer | wave2b-b2b | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `hubspot-cms` (smoke verified) | 0.84 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 204 | `hud-fhfa` | public-records | wave2d-b6 | `key` | Track B smoke PASS (fixture, HTTP 200, `active`) | `hud-fhfa` (smoke verified) | 0.72 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 205 | `huggingface` | genai | baseline | `undefined` | Track B smoke PASS (synthetic, HTTP 200, `active`) | `huggingface-card` (smoke verified) | 0.93 ms (smoke) / synthetic + 4-way neg pass | +| 206 | `icims` | jobs | baseline | `undefined` | Track B smoke PASS (fixture, HTTP 200, `active`) | `icims` (smoke verified) | 1.54 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 207 | `idx-broker-showcase` | commerce-social | wave3-b2 | `html` | pass (2 URLs) | `idx-broker-showcase` (verified) | 24.71 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 208 | `ietf-rfc` | developer | baseline | `undefined` | Track B smoke PASS (synthetic, HTTP 200, `active`) | `ietf-rfc` (smoke verified) | 0.95 ms (smoke) / synthetic + 4-way neg pass | +| 209 | `ifixit` | developer | wave3-b5 | `pub` | pass (3 URLs) | `ifixit` (verified) | 9.88 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 210 | `igdb` | commerce-social | wave3-b6 | `key` | pass (key_required_unconfigured_clean, 2 URLs + golden fallback) | `igdb` (verified) | 0.65 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 211 | `imdb-datasets` | commerce-social | wave3-b6 | `pub` | pass (3 URLs) | `imdb-datasets` (verified) | 4.38 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 212 | `import-alerts-aphis-fda` | public-records | wave3-b3 | `pub` | pass (2 live) + blocked_by_origin (2, golden fallback PASS) | `import-alerts-aphis-fda` (verified) | 20.23 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 213 | `intercom-help` | developer | wave2b-b2b | `html` | Track B smoke PASS (fixture, HTTP 200, `active`) | `intercom-help` (smoke verified) | 1.23 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 214 | `internet-archive` | genai | baseline | `undefined` | Track B smoke PASS (synthetic, HTTP 200, `active`) | `internet-archive` (smoke verified) | 0.49 ms (smoke) / synthetic + 4-way neg pass | +| 215 | `ir-portal-pack` | finance | wave3-b2 | `pub` | pass (3 URLs) | `ir-portal-pack` (verified) | 14.61 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 216 | `irs-teos` | public-records | wave2c-b3 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `irs-teos` (smoke verified) | 0.46 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 217 | `javadoc-dokka` | developer | wave2d-b6 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `javadoc-dokka` (smoke verified) | 0.35 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 218 | `jazzhr` | jobs | baseline | `undefined` | Track B smoke PASS (fixture, HTTP 200, `active`) | `jazzhr` (smoke verified) | 0.23 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 219 | `jira-public` | developer | wave3-b4 | `pub` | pass (3 URLs) | `jira-public` (verified) | 10.44 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 220 | `job-boards-jsonld-pack` | jobs | pr-140 | `html` | Track B smoke PASS (fixture, HTTP 200, `active`) | `job-boards-jsonld-pack` (smoke verified) | 1.12 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 221 | `jsr-io` | developer | baseline | `undefined` | Track B smoke PASS (synthetic, HTTP 200, `active`) | `jsr-io` (smoke verified) | 0.79 ms (smoke) / synthetic + 4-way neg pass | +| 222 | `judge-me` | commerce-social | wave2b-b2a | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `judge-me` (smoke verified) | 0.77 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 223 | `junar-tyler-data` | public-records | wave3-b1 | `pub` | pass (1 live) + blocked_by_origin (2, golden fallback PASS) | `junar-tyler-data` (verified) | 9.23 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 224 | `jwplayer` | commerce-social | wave2d-b5 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `jwplayer` (smoke verified) | 0.51 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 225 | `kaggle` | developer | wave2d-b6 | `key` | Track B smoke PASS (fixture, HTTP 200, `active`) | `kaggle` (smoke verified) | 0.77 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 226 | `kb-platform-pack` | developer | wave2b-b2b | `html` | Track B smoke PASS (fixture, HTTP 200, `active`) | `kb-platform-pack` (smoke verified) | 0.69 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 227 | `khoros-lithium` | developer | wave2a-b1 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `khoros-lithium` (smoke verified) | 0.55 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 228 | `klaviyo-attentive-forms` | commerce-social | wave3-b2 | `html` | pass (1 URL) | `klaviyo-attentive-forms` (verified) | 9.22 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 229 | `klevu` | commerce-social | wave2b-b2a | `page-key` | pass (1 URL) | `klevu` (verified) | 0.78 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 230 | `kroger` | commerce-social | wave2d-b5 | `key` | Track B smoke PASS (fixture, HTTP 200, `active`) | `kroger` (smoke verified) | 0.60 ms (smoke) / golden + 4-way + 5 fixture neg (9 neg pass) | +| 231 | `lang-registry-pack` | developer | wave2d-b6 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `lang-registry-pack` (smoke verified) | 0.45 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 232 | `laserfiche-weblink` | public-records | wave3-b1 | `pub` | pass (1 live) + blocked_by_origin (1, golden fallback PASS) | `laserfiche-weblink` (verified) | 1.84 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 233 | `legacy-cart` | commerce-social | wave2b-b2a | `html` | Track B smoke PASS (fixture, HTTP 200, `active`) | `legacy-cart` (smoke verified) | 3.26 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 234 | `legistar` | public-records | baseline | `undefined` | Track B smoke PASS (fixture, HTTP 200, `active`) | `legistar` (smoke verified) | 0.20 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 235 | `lemmy` | commerce-social | wave3-b2 | `pub` | pass (4 URLs) | `lemmy` (verified) | 1.87 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 236 | `libraries-io` | developer | wave2d-b6 | `key` | Track B smoke PASS (fixture, HTTP 200, `active`) | `libraries-io` (smoke verified) | 0.78 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 237 | `lightspeed-ecom` | commerce-social | wave2a-b1 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `lightspeed-ecom` (smoke verified) | 0.54 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 238 | `lobsters` | commerce-social | baseline | `undefined` | Track B smoke PASS (synthetic, HTTP 200, `active`) | `lobsters` (smoke verified) | 0.18 ms (smoke) / synthetic + 4-way neg pass | +| 239 | `loc-gov` | public-records | wave2c-b4 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `loc-gov` (smoke verified) | 0.33 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 240 | `local-classifieds-marketplaces` | commerce-social | wave3-b5 | `html` | pass (3 live) + blocked_by_origin (1, golden fallback PASS) | `local-classifieds-marketplaces` (verified) | 12.88 ms / golden + 4-way + 6 fixture neg (10 neg pass) | +| 241 | `market-quotes-pack` | finance | wave3-b6 | `key` | pass (key_required_unconfigured_clean, 4 URLs + golden fallback) | `market-quotes-pack` (verified) | 2.16 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 242 | `mastodon-status` | commerce-social | baseline | `undefined` | Track B smoke PASS (synthetic, HTTP 200, `active`) | `mastodon-status` (smoke verified) | 0.20 ms (smoke) / synthetic + 4-way neg pass | +| 243 | `maven-central` | developer | wave1 | `undefined` | Track B smoke PASS (fixture, HTTP 200, `active`) | `maven-central` (smoke verified) | 0.31 ms (smoke) / golden + 4-way + 0 fixture neg (4 neg pass) | +| 244 | `mcp-directories` | developer | wave2d-b6 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `mcp-directories` (smoke verified) | 0.50 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 245 | `mcp-registry` | developer | wave2d-b6 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `mcp-registry` (smoke verified) | 0.64 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 246 | `mediawiki` | commerce-social | baseline | `undefined` | Track B smoke PASS (synthetic, HTTP 200, `active`) | `mediawiki` (smoke verified) | 0.86 ms (smoke) / synthetic + 4-way neg pass | +| 247 | `medicaid-nadac` | research-health | wave3-b3 | `pub` | pass (3 URLs) | `medicaid-nadac` (verified) | 0.38 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 248 | `medium` | commerce-social | wave2d-b5 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `medium` (smoke verified) | 0.72 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 249 | `medlineplus` | research-health | wave2c-b4 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `medlineplus` (smoke verified) | 0.60 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 250 | `medusa` | commerce-social | wave2b-b2a | `page-key` | pass (2 URLs) | `medusa` (verified) | 51.67 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 251 | `meetup-luma` | commerce-social | wave2d-b6 | `html` | Track B smoke PASS (fixture, HTTP 200, `active`) | `meetup-luma` (smoke verified) | 0.74 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 252 | `midmarket-career-portals` | jobs | wave2d-b5 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `midmarket-career-portals` (smoke verified) | 0.49 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 253 | `mitre-attack` | developer | wave3-b4 | `pub` | pass (3 URLs) | `mitre-attack` (verified) | 36.39 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 254 | `mitre-cwe-capec` | developer | wave3-b4 | `pub` | pass (1 live) + blocked_by_origin (2, golden fallback PASS) | `mitre-cwe-capec` (verified) | 6.04 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 255 | `mlb-statsapi` | commerce-social | wave2d-b6 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `mlb-statsapi` (smoke verified) | 1.51 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 256 | `model-hub-pack` | genai | wave2d-b6 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `model-hub-pack` (smoke verified) | 0.82 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 257 | `modern-community-pack` | commerce-social | wave2b-b2b | `html` | Track B smoke PASS (fixture, HTTP 200, `active`) | `modern-community-pack` (smoke verified) | 1.49 ms (smoke) / golden + 4-way + 5 fixture neg (9 neg pass) | +| 258 | `msrb-emma` | finance | wave3-b6 | `html` | blocked_by_origin (HTTP 403, golden fallback PASS) | `msrb-emma` (verified) | 2.50 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 259 | `mtb-geometry-brands` | commerce-social | wave3-b5 | `html` | pass (5 URLs) | `mtb-geometry-brands` (verified) | 25.89 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 260 | `multifamily-portals` | commerce-social | wave3-b2 | `html` | pass (1 URL) | `multifamily-portals` (verified) | 9.98 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 261 | `municipal-cms-pack` | public-records | wave3-b1 | `html` | pass (3 URLs) | `municipal-cms-pack` (verified) | 73.79 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 262 | `municode` | public-records | wave2c-b3 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `municode` (smoke verified) | 0.57 ms (smoke) / golden + 4-way + 5 fixture neg (9 neg pass) | +| 263 | `musicbrainz-coverart` | commerce-social | wave3-b6 | `pub` | pass (1 live) + blocked_by_origin (2, golden fallback PASS) | `musicbrainz-coverart` (verified) | 0.40 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 264 | `nasa-ads` | research-health | wave3-b4 | `key` | pass (key_required_unconfigured_clean, 2 URLs + golden fallback) | `nasa-ads` (verified) | 0.77 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 265 | `nasa-apis` | research-health | wave2c-b4 | `key` | Track B smoke PASS (fixture, HTTP 200, `active`) | `nasa-apis` (smoke verified) | 1.14 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 266 | `nasdaq-data-link` | finance | wave3-b6 | `key` | pass (key_required_unconfigured_clean, 2 URLs + golden fallback) | `nasdaq-data-link` (verified) | 1.05 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 267 | `national-archives` | public-records | wave2c-b4 | `key` | Track B smoke PASS (fixture, HTTP 200, `active`) | `national-archives` (smoke verified) | 0.63 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 268 | `ncaa-espn` | commerce-social | wave2d-b6 (m0-converted) | `pub` | pass (4 URLs) | `ncaa-espn` (verified) | 42.88 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 269 | `nces-ipeds` | public-records | wave2c-b3 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `nces-ipeds` (smoke verified) | 0.47 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 270 | `ncua-credit-unions` | finance | wave2c-b3 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `ncua-credit-unions` (smoke verified) | 0.53 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 271 | `neogov` | jobs | wave3-b1 | `pub` | blocked_by_origin (HTTP 0, golden fallback PASS) | `neogov` (verified) | 1.27 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 272 | `newsletter-archives` | commerce-social | wave2d-b5 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `newsletter-archives` (smoke verified) | 0.81 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 273 | `newswire-pack` | commerce-social | wave2d-b5 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `newswire-pack` (smoke verified) | 0.34 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 274 | `nfpa` | public-records | wave1 | `undefined` | Track B smoke PASS (fixture, HTTP 200, `active`) | `nfpa` (smoke verified) | 1.03 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 275 | `nhl-api` | commerce-social | wave2d-b6 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `nhl-api` (smoke verified) | 1.76 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 276 | `nhtsa-vpic-recalls` | public-records | wave1 | `undefined` | Track B smoke PASS (synthetic, HTTP 200, `active`) | `nhtsa-vpic-recalls` (smoke verified) | 0.29 ms (smoke) / synthetic + 4-way neg pass | +| 277 | `nih-reporter` | research-health | wave3-b4 | `pub` | pass (2 URLs) | `nih-reporter` (verified) | 1.05 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 278 | `nist-nvd` | developer | baseline | `undefined` | Track B smoke PASS (fixture, HTTP 200, `active`) | `nist-nvd` (smoke verified) | 0.35 ms (smoke) / golden + 4-way + 0 fixture neg (4 neg pass) | +| 279 | `nlrb-cases` | public-records | wave3-b3 | `pub` | pass (2 URLs) | `nlrb-cases` (verified) | 14.53 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 280 | `noaa-ncei-cdo` | research-health | wave2c-b4 | `key` | Track B smoke PASS (fixture, HTTP 200, `active`) | `noaa-ncei-cdo` (smoke verified) | 0.67 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 281 | `noaa-tides-currents` | research-health | wave2c-b4 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `noaa-tides-currents` (smoke verified) | 0.73 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 282 | `nostr-relays` | commerce-social | wave3-b6 | `pub` | pass (4 URLs) | `nostr-relays` (verified) | 2.59 ms / golden + 4-way + 6 fixture neg (10 neg pass) | +| 283 | `notion-public-site` | developer | wave2b-b2b | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `notion-public-site` (smoke verified) | 1.04 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 284 | `npm-registry` | developer | baseline | `undefined` | Track B smoke PASS (synthetic, HTTP 200, `active`) | `npm-registry` (smoke verified) | 0.19 ms (smoke) / synthetic + 4-way neg pass | +| 285 | `nppes-npi` | research-health | wave2c-b4 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `nppes-npi` (smoke verified) | 0.81 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 286 | `npr-pbs` | commerce-social | wave2d-b5 | `html` | Track B smoke PASS (fixture, HTTP 200, `active`) | `npr-pbs` (smoke verified) | 0.25 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 287 | `nps` | public-records | wave2c-b4 | `key` | Track B smoke PASS (fixture, HTTP 200, `active`) | `nps` (smoke verified) | 0.50 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 288 | `nsf-awards` | research-health | wave3-b4 | `pub` | pass (2 live) + blocked_by_origin (1, golden fallback PASS) | `nsf-awards` (verified) | 0.66 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 289 | `nuget-gallery` | developer | wave1 | `undefined` | Track B smoke PASS (fixture, HTTP 200, `active`) | `nuget-gallery` (smoke verified) | 1.02 ms (smoke) / golden + 4-way + 0 fixture neg (4 neg pass) | +| 290 | `nyt-api` | commerce-social | wave2d-b5 | `key` | Track B smoke PASS (fixture, HTTP 200, `active`) | `nyt-api` (smoke verified) | 0.46 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 291 | `ofac-sdn` | public-records | wave3-b3 | `pub` | pass (1 live) + blocked_by_origin (1, golden fallback PASS) | `ofac-sdn` (verified) | 0.93 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 292 | `okendo` | commerce-social | wave2b-b2a | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `okendo` (smoke verified) | 0.43 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 293 | `open-icecat` | commerce-social | wave3-b6 | `pub` | pass (2 URLs) | `open-icecat` (verified) | 7.41 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 294 | `open-product-wikidata-gtin` | commerce-social | wave3-b6 | `pub` | blocked_by_origin (HTTP 0, golden fallback PASS) | `open-product-wikidata-gtin` (verified) | 0.51 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 295 | `openalex` | research-health | baseline | `undefined` | Track B smoke PASS (synthetic, HTTP 200, `active`) | `openalex` (smoke verified) | 0.53 ms (smoke) / synthetic + 4-way neg pass | +| 296 | `opencorporates` | public-records | wave2c-b3 | `key` | Track B smoke PASS (fixture, HTTP 200, `active`) | `opencorporates` (smoke verified) | 0.56 ms (smoke) / golden + 4-way + 5 fixture neg (9 neg pass) | +| 297 | `opendatasoft` | public-records | wave3-b1 | `pub` | pass (2 live) + blocked_by_origin (1, golden fallback PASS) | `opendatasoft` (verified) | 6.39 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 298 | `openfda` | research-health | baseline | `undefined` | Track B smoke PASS (synthetic, HTTP 200, `active`) | `openfda` (smoke verified) | 0.22 ms (smoke) / synthetic + 4-way neg pass | +| 299 | `openfoodfacts` | commerce-social | baseline | `undefined` | Track B smoke PASS (synthetic, HTTP 200, `active`) | `openfoodfacts` (smoke verified) | 0.48 ms (smoke) / synthetic + 4-way neg pass | +| 300 | `opengov-portals` | public-records | wave3-b1 | `pub` | pass (3 URLs) | `opengov-portals` (verified) | 5.24 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 301 | `openrouter` | genai | baseline | `undefined` | Track B smoke PASS (synthetic, HTTP 200, `active`) | `openrouter` (smoke verified) | 0.31 ms (smoke) / synthetic + 4-way neg pass | +| 302 | `openstreetmap` | public-records | wave2c-b4 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `openstreetmap` (smoke verified) | 0.80 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 303 | `oracle-commerce` | commerce-social | wave2a-b1 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `oracle-commerce` (smoke verified) | 1.08 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 304 | `orcid` | research-health | wave3-b4 | `pub` | blocked_by_origin (HTTP 0, golden fallback PASS) | `orcid` (verified) | 0.87 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 305 | `os-package-pack` | developer | wave2d-b6 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `os-package-pack` (smoke verified) | 0.96 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 306 | `osha-establishment` | public-records | wave3-b3 | `pub` | blocked_by_origin (HTTP 403, golden fallback PASS) | `osha-establishment` (verified) | 1.13 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 307 | `osv-ghsa` | developer | wave1 | `undefined` | Track B smoke PASS (fixture, HTTP 200, `active`) | `osv-ghsa` (smoke verified) | 0.52 ms (smoke) / golden + 4-way + 0 fixture neg (4 neg pass) | +| 308 | `outdoor-retail-specs` | commerce-social | wave2b-b2a | `html` | Track B smoke PASS (fixture, HTTP 200, `active`) | `outdoor-retail-specs` (smoke verified) | 1.59 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 309 | `oversight-gov` | public-records | wave3-b3 | `pub` | blocked_by_origin (HTTP 406, golden fallback PASS) | `oversight-gov` (verified) | 1.33 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 310 | `pacer-case-locator` | public-records | wave2c-b3 (m0-converted) | `html` | pass (2 live) + blocked_by_origin (1, golden fallback PASS) | `pacer-case-locator` (verified) | 6.38 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 311 | `packagist` | developer | baseline | `undefined` | Track B smoke PASS (synthetic, HTTP 200, `active`) | `packagist` (smoke verified) | 0.34 ms (smoke) / synthetic + 4-way neg pass | +| 312 | `paradox-olivia` | jobs | wave3-b1 | `html` | pass (1 URL) | `paradox-olivia` (verified) | 38.62 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 313 | `park-tool` | developer | wave3-b5 | `html` | pass (2 URLs) | `park-tool` (verified) | 8.28 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 314 | `patreon-public` | commerce-social | wave3-b6 | `html` | pass (1 live) + blocked_by_origin (1, golden fallback PASS) | `patreon-public` (verified) | 33.14 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 315 | `peer-resale-fashion` | commerce-social | wave3-b5 | `html` | pass (2 live) + blocked_by_origin (1, golden fallback PASS) | `peer-resale-fashion` (verified) | 47.87 ms / golden + 4-way + 6 fixture neg (10 neg pass) | +| 316 | `peertube` | commerce-social | wave3-b2 | `pub` | pass (3 URLs) | `peertube` (verified) | 0.69 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 317 | `pinkbike-buysell` | commerce-social | wave3-b5 | `html` | blocked_by_origin (HTTP 403, golden fallback PASS) | `pinkbike-buysell` (verified) | 0.90 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 318 | `pinpoint` | jobs | baseline | `undefined` | Track B smoke PASS (fixture, HTTP 200, `active`) | `pinpoint` (smoke verified) | 0.23 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 319 | `pkg-go-dev` | developer | baseline | `undefined` | Track B smoke PASS (synthetic, HTTP 200, `active`) | `pkg-go-dev` (smoke verified) | 0.21 ms (smoke) / synthetic + 4-way neg pass | +| 320 | `pm-listing-widgets` | commerce-social | wave3-b2 | `html` | pass (2 URLs) | `pm-listing-widgets` (verified) | 6.92 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 321 | `podcast-index` | commerce-social | wave3-b6 | `key` | pass (key_required_unconfigured_clean, 2 URLs + golden fallback) | `podcast-index` (verified) | 0.66 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 322 | `podcasts-apple-lookup` | commerce-social | wave2d-b5 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `podcasts-apple-lookup` (smoke verified) | 0.59 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 323 | `polymarket` | finance | baseline | `undefined` | Track B smoke PASS (synthetic, HTTP 200, `active`) | `polymarket` (smoke verified) | 0.56 ms (smoke) / synthetic + 4-way neg pass | +| 324 | `popmenu` | commerce-social | wave3-b2 | `html` | blocked_by_origin (HTTP 403, golden fallback PASS) | `popmenu` (verified) | 0.84 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 325 | `powerreviews` | commerce-social | wave2a-b1 | `page-key` | pass (1 URL) | `powerreviews` (verified) | 4.91 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 326 | `prestashop` | commerce-social | wave2b-b2a | `html` | Track B smoke PASS (fixture, HTTP 200, `active`) | `prestashop` (smoke verified) | 0.79 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 327 | `primegov` | public-records | wave3-b1 | `pub` | blocked_by_origin (HTTP 0, golden fallback PASS) | `primegov` (verified) | 0.52 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 328 | `product-feed-discovery` | commerce-social | wave2d-b5 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `product-feed-discovery` (smoke verified) | 0.92 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 329 | `product-hunt` | commerce-social | wave3-b6 | `key` | pass (key_required_unconfigured_clean, 2 URLs + golden fallback) | `product-hunt` (verified) | 0.73 ms / golden + 4-way + 6 fixture neg (10 neg pass) | +| 330 | `prop65-warnings` | public-records | wave3-b6 | `html` | blocked_by_origin (HTTP 200, golden fallback PASS) | `prop65-warnings` (verified) | 0.95 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 331 | `propublica-nonprofits` | public-records | wave2c-b3 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `propublica-nonprofits` (smoke verified) | 0.78 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 332 | `pubchem` | research-health | baseline | `undefined` | Track B smoke PASS (synthetic, HTTP 200, `active`) | `pubchem` (smoke verified) | 0.28 ms (smoke) / synthetic + 4-way neg pass | +| 333 | `public-bid-portals` | public-records | wave3-b1 | `html` | pass (2 URLs) | `public-bid-portals` (verified) | 7.27 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 334 | `public-booking` | commerce-social | wave2d-b6 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `public-booking` (smoke verified) | 0.62 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 335 | `public-forms` | commerce-social | wave2d-b6 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `public-forms` (smoke verified) | 1.14 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 336 | `public-job-feeds` | jobs | baseline | `undefined` | Track B smoke PASS (fixture, HTTP 200, `active`) | `himalayas-feed` (smoke verified) | 0.41 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 337 | `public-share-links` | commerce-social | wave2d-b6 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `public-share-links` (smoke verified) | 0.52 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 338 | `pubmed-pmc` | research-health | baseline | `undefined` | Track B smoke PASS (synthetic, HTTP 200, `active`) | `pubmed-europepmc` (smoke verified) | 0.38 ms (smoke) / synthetic + 4-way neg pass | +| 339 | `pypi-project` | developer | baseline | `undefined` | Track B smoke PASS (fixture, HTTP 200, `active`) | `pypi-project` (smoke verified) | 0.41 ms (smoke) / golden + 4-way + 5 fixture neg (9 neg pass) | +| 340 | `q4-ir` | finance | wave3-b2 | `pub` | pass (2 URLs) | `q4-ir` (verified) | 0.80 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 341 | `qbp-frame-brands` | commerce-social | wave3-b5 | `html` | pass (2 URLs) | `qbp-frame-brands` (verified) | 10.05 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 342 | `race-results-pack` | commerce-social | wave3-b2 | `html` | pass (1 URL) | `race-results-pack` (verified) | 2.61 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 343 | `rdap` | developer | wave3-b4 | `pub` | pass (5 URLs) | `rdap` (verified) | 2.56 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 344 | `readthedocs-sphinx` | developer | wave2d-b6 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `readthedocs-sphinx` (smoke verified) | 0.35 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 345 | `rebuy-searchanise` | commerce-social | wave3-b2 | `page-key` | pass (1 URL) | `rebuy-searchanise` (verified) | 0.61 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 346 | `recharge-bold-subscriptions` | commerce-social | wave3-b2 | `html` | pass (1 URL) | `recharge-bold-subscriptions` (verified) | 48.68 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 347 | `recreation-gov-ridb` | public-records | wave2c-b4 | `key` | Track B smoke PASS (fixture, HTTP 200, `active`) | `recreation-gov-ridb` (smoke verified) | 0.53 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 348 | `reddit-thread` | commerce-social | baseline | `undefined` | Track B smoke PASS (synthetic, HTTP 200, `active`) | `reddit-thread` (smoke verified) | 0.54 ms (smoke) / synthetic + 4-way neg pass | +| 349 | `regulations-gov` | public-records | wave2c-b3 | `key` | Track B smoke PASS (fixture, HTTP 200, `active`) | `regulations-gov` (smoke verified) | 0.92 ms (smoke) / golden + 4-way + 5 fixture neg (9 neg pass) | +| 350 | `repology` | developer | wave2d-b6 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `repology` (smoke verified) | 0.54 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 351 | `research-repo-pack` | research-health | wave3-b4 | `pub` | pass (4 URLs) | `research-repo-pack` (verified) | 10.97 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 352 | `reverb` | commerce-social | wave3-b5 | `pub` | pass (3 URLs) | `reverb` (verified) | 0.46 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 353 | `rippling` | jobs | baseline | `undefined` | Track B smoke PASS (fixture, HTTP 200, `active`) | `rippling-board` (smoke verified) | 0.48 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 354 | `ror` | research-health | wave3-b4 | `pub` | pass (2 live) + blocked_by_origin (1, golden fallback PASS) | `ror` (verified) | 1.40 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 355 | `rubygems` | developer | baseline | `undefined` | Track B smoke PASS (synthetic, HTTP 200, `active`) | `rubygems` (smoke verified) | 0.16 ms (smoke) / synthetic + 4-way neg pass | +| 356 | `rumble-odysee` | commerce-social | wave2d-b5 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `rumble-odysee` (smoke verified) | 0.50 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 357 | `runsignup` | commerce-social | wave3-b2 | `pub` | pass (3 URLs) | `runsignup` (verified) | 1.60 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 358 | `rxnorm-rxnav` | research-health | wave2c-b4 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `rxnorm-rxnav` (smoke verified) | 0.68 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 359 | `saleor` | commerce-social | wave2b-b2a | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `saleor` (smoke verified) | 1.60 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 360 | `salesforce-knowledge` | developer | wave2b-b2b | `html` | Track B smoke PASS (fixture, HTTP 200, `active`) | `salesforce-knowledge` (smoke verified) | 0.54 ms (smoke) / golden + 4-way + 6 fixture neg (10 neg pass) | +| 361 | `sam-gov` | public-records | wave2c-b3 | `key` | Track B smoke PASS (fixture, HTTP 200, `active`) | `sam-gov` (smoke verified) | 0.63 ms (smoke) / golden + 4-way + 5 fixture neg (9 neg pass) | +| 362 | `sap-commerce-occ` | commerce-social | wave2a-b1 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `sap-commerce-occ` (smoke verified) | 0.36 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 363 | `sap-rmk-jibe` | jobs | baseline | `undefined` | Track B smoke PASS (fixture, HTTP 200, `active`) | `sap-rmk-jibe` (smoke verified) | 0.29 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 364 | `sba-dsbs-loans` | finance | wave3-b3 | `pub` | pass (2 URLs) | `sba-dsbs-loans` (verified) | 2.59 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 365 | `schema-course` | public-records | wave3-b1 | `html` | pass (1 URL) | `schema-course` (verified) | 1.23 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 366 | `schema-dataset` | research-health | wave3-b2 | `html` | pass (1 URL) | `schema-dataset` (verified) | 3.05 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 367 | `schema-event` | commerce-social | wave3-b2 | `html` | pass (2 URLs) | `schema-event` (verified) | 4.96 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 368 | `schema-faq-howto` | public-records | wave3-b2 | `html` | pass (2 URLs) | `schema-faq-howto` (verified) | 4.39 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 369 | `schema-localbusiness` | commerce-social | wave3-b2 | `html` | pass (1 URL) | `schema-localbusiness` (verified) | 3.60 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 370 | `schema-medical` | research-health | wave3-b2 | `html` | pass (2 URLs) | `schema-medical` (verified) | 1.68 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 371 | `schema-menu` | commerce-social | wave3-b2 | `html` | pass (1 URL) | `schema-menu` (verified) | 9.26 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 372 | `schema-recipe` | commerce-social | wave3-b2 | `html` | pass (1 URL) | `schema-recipe` (verified) | 2.33 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 373 | `schema-software-app` | developer | wave3-b2 | `html` | pass (2 URLs) | `schema-software-app` (verified) | 1.88 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 374 | `schema-vehicle` | commerce-social | wave3-b2 | `html` | pass (1 URL) | `schema-vehicle` (verified) | 4.12 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 375 | `searchspring` | commerce-social | wave2a-b1 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `searchspring` (smoke verified) | 0.65 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 376 | `sec-edgar` | finance | baseline | `undefined` | Track B smoke PASS (fixture, HTTP 200, `active`) | `sec-edgar` (smoke verified) | 0.38 ms (smoke) / golden + 4-way + 0 fixture neg (4 neg pass) | +| 377 | `sec-xbrl-frames` | finance | wave3-b6 | `pub` | pass (3 URLs) | `sec-xbrl-frames` (verified) | 16.18 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 378 | `security-txt` | developer | wave3-b4 | `pub` | pass (2 URLs) | `security-txt` (verified) | 0.20 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 379 | `semantic-scholar` | research-health | wave3-b4 | `pub` | pass (1 live) + blocked_by_origin (1, golden fallback PASS) | `semantic-scholar` (verified) | 0.51 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 380 | `senate-lda` | public-records | wave2c-b3 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `senate-lda` (smoke verified) | 0.74 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 381 | `servicenow-kb` | developer | wave2b-b2b | `html` | Track B smoke PASS (fixture, HTTP 200, `active`) | `servicenow-kb` (smoke verified) | 0.55 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 382 | `setlist-lastfm` | commerce-social | wave3-b6 | `key` | pass (3 URLs) | `setlist-lastfm` (verified) | 13.05 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 383 | `sfcc-demandware` | commerce-social | wave1 | `undefined` | Track B smoke PASS (fixture, HTTP 200, `active`) | `sfcc-demandware` (smoke verified) | 0.54 ms (smoke) / golden + 4-way + 0 fixture neg (4 neg pass) | +| 384 | `sheldon-brown` | research-health | wave3-b5 | `html` | pass (2 URLs) | `sheldon-brown` (verified) | 19.18 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 385 | `shopify-filter-apps` | commerce-social | wave3-b2 | `page-key` | blocked_by_origin (HTTP 403, golden fallback PASS) | `shopify-filter-apps` (verified) | 0.65 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 386 | `shopify-hydrogen` | commerce-social | wave3-b2 | `page-key` | pass (1 URL) | `shopify-hydrogen` (verified) | 3.13 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 387 | `shopify-storefront-graphql` | commerce-social | wave3-b2 | `pub` | pass (1 URL) | `shopify-storefront-graphql` (verified) | 2.51 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 388 | `shopify` | commerce-social | baseline | `undefined` | Track B smoke PASS (synthetic, HTTP 200, `active`) | `shopify-catalog-page` (smoke verified) | 0.69 ms (smoke) / synthetic + 4-way neg pass | +| 389 | `shopware-magento` | commerce-social | wave1 | `undefined` | Track B smoke PASS (fixture, HTTP 200, `active`) | `shopware-magento` (smoke verified) | 1.53 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 390 | `slide-decks` | commerce-social | wave2d-b6 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `slide-decks` (smoke verified) | 0.81 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 391 | `small-search` | commerce-social | wave2b-b2a | `page-key` | pass (1 URL) | `small-search` (verified) | 0.86 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 392 | `smartetailing` | commerce-social | wave2a-b1 | `html` | Track B smoke PASS (fixture, HTTP 200, `active`) | `smartetailing` (smoke verified) | 0.31 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 393 | `smb-ats-full` | jobs | wave3-b1 | `pub` | pass (2 URLs) | `smb-ats-full` (verified) | 5.07 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 394 | `smithsonian-open-access` | public-records | wave2c-b4 | `key` | Track B smoke PASS (fixture, HTTP 200, `active`) | `smithsonian-open-access` (smoke verified) | 0.82 ms (smoke) / golden + 4-way + 5 fixture neg (9 neg pass) | +| 395 | `socrata` | public-records | baseline | `undefined` | Track B smoke PASS (fixture, HTTP 200, `active`) | `socrata` (smoke verified) | 0.29 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 396 | `sourceforge-launchpad` | developer | wave3-b4 | `pub` | pass (1 live) + blocked_by_origin (3, golden fallback PASS) | `sourceforge-launchpad` (verified) | 0.62 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 397 | `specialized-turbo-support` | developer | wave3-b5 | `html` | blocked_by_origin (HTTP 200, golden fallback PASS) | `specialized-turbo-support` (verified) | 1.09 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 398 | `specialized` | commerce-social | wave2b-b2a | `html` | Track B smoke PASS (fixture, HTTP 200, `active`) | `specialized` (smoke verified) | 2.04 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 399 | `spotify-web-api` | commerce-social | wave3-b6 | `key` | pass (3 URLs) | `spotify-web-api` (verified) | 5.43 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 400 | `spree-solidus` | commerce-social | wave2b-b2a | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `spree-solidus` (smoke verified) | 0.74 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 401 | `square-online` | commerce-social | wave2b-b2a | `html` | Track B smoke PASS (fixture, HTTP 200, `active`) | `square-online` (smoke verified) | 1.09 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 402 | `square-toast-menu` | commerce-social | wave3-b2 | `html` | pass (2 URLs) | `square-toast-menu` (verified) | 20.12 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 403 | `squarespace-commerce` | commerce-social | wave1 | `undefined` | Track B smoke PASS (fixture, HTTP 200, `active`) | `squarespace-commerce` (smoke verified) | 1.61 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 404 | `sram-docs` | developer | wave1 | `undefined` | Track B smoke PASS (fixture, HTTP 200, `active`) | `sram-docs` (smoke verified) | 0.77 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 405 | `sram-models` | commerce-social | wave1 | `undefined` | Track B smoke PASS (synthetic, HTTP 200, `active`) | `sram-models` (smoke verified) | 0.22 ms (smoke) / synthetic + 4-way neg pass | +| 406 | `ssrn-nber` | research-health | wave3-b4 | `html` | pass (1 live) + blocked_by_origin (1, golden fallback PASS) | `ssrn-nber` (verified) | 6.74 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 407 | `stackexchange-qa` | developer | baseline | `undefined` | Track B smoke PASS (synthetic, HTTP 200, `active`) | `stackexchange-qa` (smoke verified) | 0.79 ms (smoke) / synthetic + 4-way neg pass | +| 408 | `staffing-ats-pack` | jobs | wave3-b1 | `pub` | pass (1 URL) | `staffing-ats-pack-crelate-rss` (verified) | 7.17 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 409 | `stamped-loox-junip` | commerce-social | wave2b-b2a | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `stamped-loox-junip` (smoke verified) | 1.04 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 410 | `state-court-portals` | public-records | wave2c-b3 (m0-converted) | `html` | pass (1 live) + blocked_by_origin (1, golden fallback PASS) | `state-court-portals` (verified) | 5.31 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 411 | `state-legislatures` | public-records | wave2c-b3 | `key` | Track B smoke PASS (fixture, HTTP 200, `active`) | `state-legislatures` (smoke verified) | 0.60 ms (smoke) / golden + 4-way + 6 fixture neg (10 neg pass) | +| 412 | `state-sos-business` | public-records | wave2c-b3 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `state-sos-business` (smoke verified) | 0.36 ms (smoke) / golden + 4-way + 5 fixture neg (9 neg pass) | +| 413 | `state-workforce-boards` | jobs | wave2d-b5 | `html` | Track B smoke PASS (fixture, HTTP 200, `active`) | `state-workforce-boards` (smoke verified) | 1.48 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 414 | `status-page-pack` | developer | wave2b-b2b | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `status-page-pack` (smoke verified) | 0.61 ms (smoke) / golden + 4-way + 5 fixture neg (9 neg pass) | +| 415 | `steam-store` | commerce-social | wave3-b6 | `pub` | pass (2 live) + blocked_by_origin (1, golden fallback PASS) | `steam-store` (verified) | 1.18 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 416 | `stockist` | commerce-social | wave2a-b1 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `stockist` (smoke verified) | 0.27 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 417 | `storemapper` | commerce-social | wave2a-b1 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `storemapper` (smoke verified) | 0.22 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 418 | `storerocket` | commerce-social | wave2a-b1 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `storerocket` (smoke verified) | 0.55 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 419 | `strava-segments` | commerce-social | wave2d-b6 | `key` | Track B smoke PASS (fixture, HTTP 200, `active`) | `strava-segments` (smoke verified) | 0.98 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 420 | `substack-notes-beehiiv` | commerce-social | wave3-b6 | `key` | pass (2 URLs) | `substack-notes-beehiiv` (verified) | 44.08 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 421 | `supremecourt-gov` | public-records | wave2c-b3 | `html` | Track B smoke PASS (fixture, HTTP 200, `active`) | `supremecourt-gov` (smoke verified) | 0.87 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 422 | `suspension-cockpit-compat` | commerce-social | wave3-b5 | `html` | pass (4 URLs) | `suspension-cockpit-compat` (verified) | 43.60 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 423 | `taleo-full` | jobs | wave3-b1 | `pub` | pass (2 URLs) | `taleo-full` (verified) | 5.67 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 424 | `target` | commerce-social | wave2d-b5 (m0-converted) | `html` | pass (1 URL) | `target` (verified) | 3.44 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 425 | `teamtailor` | jobs | baseline | `undefined` | Track B smoke PASS (fixture, HTTP 200, `active`) | `teamtailor` (smoke verified) | 0.23 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 426 | `tech-job-boards-jsonld` | jobs | wave2d-b5 | `html` | Track B smoke PASS (fixture, HTTP 200, `active`) | `tech-job-boards-jsonld` (smoke verified) | 0.57 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 427 | `terraform-registry` | developer | wave1 | `undefined` | Track B smoke PASS (fixture, HTTP 200, `active`) | `terraform-registry` (smoke verified) | 0.25 ms (smoke) / golden + 4-way + 0 fixture neg (4 neg pass) | +| 428 | `threads-api` | commerce-social | wave3-b6 | `key` | pass (key_required_unconfigured_clean, 2 URLs + golden fallback) | `threads-api` (verified) | 1.06 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 429 | `ticketmaster-discovery` | commerce-social | wave2d-b6 | `key` | Track B smoke PASS (fixture, HTTP 200, `active`) | `ticketmaster-discovery` (smoke verified) | 0.77 ms (smoke) / golden + 4-way + 5 fixture neg (9 neg pass) | +| 430 | `tmdb` | commerce-social | wave3-b6 | `key` | pass (1 live) + blocked_by_origin (2, golden fallback PASS) | `tmdb` (verified) | 23.48 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 431 | `townnews-blox` | commerce-social | wave2a-b1 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `townnews-blox` (smoke verified) | 0.38 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 432 | `tq-ebike` | commerce-social | wave1 | `undefined` | Track B smoke PASS (synthetic, HTTP 200, `active`) | `tq-ebike` (smoke verified) | 0.31 ms (smoke) / synthetic + 4-way neg pass | +| 433 | `trade-gov-csl` | public-records | wave3-b3 | `key` | pass (2 URLs) | `trade-gov-csl` (verified) | 15.48 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 434 | `trailforks-mtb-project` | commerce-social | wave2b-b2a | `key` | Track B smoke PASS (fixture, HTTP 200, `active`) | `trailforks-mtb-project` (smoke verified) | 0.72 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 435 | `transitland-gtfs` | public-records | wave2c-b4 | `key` | Track B smoke PASS (fixture, HTTP 200, `active`) | `transitland-gtfs` (smoke verified) | 0.52 ms (smoke) / golden + 4-way + 5 fixture neg (9 neg pass) | +| 436 | `treasury-fiscal-data` | finance | wave2c-b3 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `treasury-fiscal-data` (smoke verified) | 0.44 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 437 | `trustpilot` | commerce-social | wave2b-b2a | `html` | Track B smoke PASS (fixture, HTTP 200, `active`) | `trustpilot` (smoke verified) | 0.64 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 438 | `tumblr` | commerce-social | wave3-b6 | `key` | pass (3 URLs) | `tumblr` (verified) | 62.42 ms / golden + 4-way + 6 fixture neg (10 neg pass) | +| 439 | `tvmaze` | commerce-social | wave3-b6 | `pub` | pass (2 URLs) | `tvmaze` (verified) | 2.32 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 440 | `twitch-kick` | commerce-social | wave2d-b5 | `key` | Track B smoke PASS (fixture, HTTP 200, `active`) | `twitch-kick` (smoke verified) | 0.63 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 441 | `tyler-energov` | public-records | wave3-b1 | `pub` | blocked_by_origin (HTTP 200, golden fallback PASS) | `tyler-energov` (verified) | 0.70 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 442 | `ukg-paylocity-dover` | jobs | wave1 | `undefined` | Track B smoke PASS (fixture, HTTP 200, `active`) | `ukg-paylocity-dover` (smoke verified) | 0.83 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 443 | `ul-product-iq` | public-records | wave3-b5 | `html` | pass (1 URL) | `ul-product-iq` (verified) | 1.08 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 444 | `unpaywall` | research-health | wave3-b4 | `pub` | pass (1 URL) | `unpaywall` (verified) | 1.12 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 445 | `upcitemdb-barcodelookup` | commerce-social | wave3-b6 | `key` | pass (3 URLs) | `upcitemdb-barcodelookup` (verified) | 2.38 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 446 | `us-cfr-govinfo` | public-records | wave1 | `undefined` | Track B smoke PASS (fixture, HTTP 200, `active`) | `us-cfr-govinfo` (smoke verified) | 0.21 ms (smoke) / golden + 4-way + 0 fixture neg (4 neg pass) | +| 447 | `us-ebike-oems` | commerce-social | wave3-b5 | `html` | pass (3 live) + blocked_by_origin (1, golden fallback PASS) | `us-ebike-oems` (verified) | 47.91 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 448 | `usajobs` | jobs | wave2d-b5 | `key` | Track B smoke PASS (fixture, HTTP 200, `active`) | `usajobs` (smoke verified) | 0.69 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 449 | `usaspending` | public-records | baseline | `undefined` | Track B smoke PASS (fixture, HTTP 200, `active`) | `usaspending` (smoke verified) | 0.23 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 450 | `uscode-house` | public-records | wave2c-b3 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `uscode-house` (smoke verified) | 0.75 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 451 | `usda-nass-fdc` | research-health | wave2c-b3 | `key` | Track B smoke PASS (fixture, HTTP 200, `active`) | `usda-nass-fdc` (smoke verified) | 0.58 ms (smoke) / golden + 4-way + 5 fixture neg (9 neg pass) | +| 452 | `used-bikes-shopify` | commerce-social | wave3-b5 | `pub` | pass (3 URLs) | `used-bikes-shopify` (verified) | 9.64 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 453 | `usfs-blm-trails` | public-records | wave2c-b4 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `usfs-blm-trails` (smoke verified) | 0.81 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 454 | `usgs-earthquakes` | research-health | wave2c-b4 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `usgs-earthquakes` (smoke verified) | 0.71 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 455 | `usgs-water` | research-health | wave2c-b4 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `usgs-water` (smoke verified) | 1.14 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 456 | `usitc-hts` | public-records | wave3-b3 | `pub` | pass (2 URLs) | `usitc-hts` (verified) | 1.02 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 457 | `usps-addresses` | public-records | wave3-b3 | `key` | pass (key_required_unconfigured_clean, 2 URLs + golden fallback) | `usps-addresses` (verified) | 0.53 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 458 | `uspto-patentsview` | public-records | wave2c-b4 | `key` | Track B smoke PASS (fixture, HTTP 200, `active`) | `uspto-patentsview` (smoke verified) | 1.07 ms (smoke) / golden + 4-way + 5 fixture neg (9 neg pass) | +| 459 | `uspto-ppubs` | public-records | wave2c-b4 | `html` | Track B smoke PASS (fixture, HTTP 200, `active`) | `uspto-ppubs` (smoke verified) | 0.86 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 460 | `uspto-tsdr` | public-records | wave2c-b4 | `key` | Track B smoke PASS (fixture, HTTP 200, `active`) | `uspto-tsdr` (smoke verified) | 0.68 ms (smoke) / golden + 4-way + 5 fixture neg (9 neg pass) | +| 461 | `ustr-301` | public-records | wave3-b3 | `pub` | pass (3 URLs) | `ustr-301` (verified) | 11.03 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 462 | `va-lighthouse-facilities` | research-health | wave3-b3 | `key` | pass (2 URLs) | `va-lighthouse-facilities` (verified) | 38.85 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 463 | `vanilla-forums` | commerce-social | wave2b-b2b | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `vanilla-forums` (smoke verified) | 0.61 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 464 | `vendor-csaf` | developer | wave3-b4 | `pub` | pass (3 URLs) | `vendor-csaf` (verified) | 4.34 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 465 | `vimeo` | commerce-social | wave2d-b5 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `vimeo` (smoke verified) | 0.45 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 466 | `vscode-open-vsx` | developer | wave3-b4 | `pub` | pass (2 URLs) | `vscode-open-vsx` (verified) | 6.71 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 467 | `vtex` | commerce-social | wave2a-b1 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `vtex` (smoke verified) | 0.63 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 468 | `walmart` | commerce-social | wave2d-b5 | `key` | Track B smoke PASS (fixture, HTTP 200, `active`) | `walmart` (smoke verified) | 0.66 ms (smoke) / golden + 4-way + 5 fixture neg (9 neg pass) | +| 469 | `weather-gov` | research-health | wave2c-b4 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `weather-gov` (smoke verified) | 1.03 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 470 | `web-compat-data` | developer | wave3-b4 | `pub` | pass (5 URLs) | `web-compat-data` (verified) | 5.64 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 471 | `wheel-hub-specs` | commerce-social | wave3-b5 | `html` | pass (4 URLs) | `wheel-hub-specs` (verified) | 72.50 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 472 | `wikidata-openlibrary` | research-health | wave1 | `undefined` | Track B smoke PASS (fixture, HTTP 200, `active`) | `wikidata-openlibrary` (smoke verified) | 1.07 ms (smoke) / golden + 4-way + 0 fixture neg (4 neg pass) | +| 473 | `wild-apricot` | commerce-social | wave3-b2 | `html` | pass (2 live) + blocked_by_origin (1, golden fallback PASS) | `wild-apricot` (verified) | 5.09 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 474 | `wistia` | commerce-social | wave2d-b5 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `wistia` (smoke verified) | 0.59 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 475 | `wix-stores` | commerce-social | wave2b-b2a | `html` | Track B smoke PASS (fixture, HTTP 200, `active`) | `wix-stores` (smoke verified) | 1.32 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 476 | `woocommerce` | commerce-social | baseline | `undefined` | Track B smoke PASS (synthetic, HTTP 200, `active`) | `woocommerce-catalog-page` (smoke verified) | 1.58 ms (smoke) / synthetic + 4-way neg pass | +| 477 | `wordpress-org-plugins` | developer | wave3-b4 | `pub` | pass (1 URL) | `wordpress-org-plugins` (verified) | 13.28 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 478 | `wordpress-vip-newspack` | commerce-social | wave2d-b5 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `wordpress-vip-newspack` (smoke verified) | 0.65 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 479 | `workable` | jobs | baseline | `undefined` | Track B smoke PASS (fixture, HTTP 200, `active`) | `workable-board` (smoke verified) | 0.23 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 480 | `xenforo-thread` | commerce-social | wave1 | `undefined` | Track B smoke PASS (fixture, HTTP 200, `active`) | `xenforo-thread` (smoke verified) | 1.07 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 481 | `ycombinator` | finance | baseline | `undefined` | Track B smoke PASS (synthetic, HTTP 200, `active`) | `ycombinator` (smoke verified) | 0.29 ms (smoke) / synthetic + 4-way neg pass | +| 482 | `yelp-fusion` | commerce-social | wave2d-b6 | `key` | Track B smoke PASS (fixture, HTTP 200, `active`) | `yelp-fusion` (smoke verified) | 1.08 ms (smoke) / golden + 4-way + 5 fixture neg (9 neg pass) | +| 483 | `yext-locator` | commerce-social | wave2a-b1 | `page-key` | pass (1 URL) | `yext-locator` (verified) | 8.32 ms / golden + 4-way + 4 fixture neg (8 neg pass) | +| 484 | `yotpo` | commerce-social | wave2a-b1 | `pub` | Track B smoke PASS (fixture, HTTP 200, `active`) | `yotpo` (smoke verified) | 0.40 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | +| 485 | `youtube-data-api` | commerce-social | wave3-b6 | `key` | pass (key_required_unconfigured_clean, 3 URLs + golden fallback) | `youtube-data-api` (verified) | 1.26 ms / golden + 4-way + 5 fixture neg (9 neg pass) | +| 486 | `zendesk-hc` | developer | wave1 | `undefined` | Track B smoke PASS (fixture, HTTP 200, `active`) | `zendesk-hc` (smoke verified) | 0.37 ms (smoke) / golden + 4-way + 4 fixture neg (8 neg pass) | + +--- + +## 3. Full Inventory Table 2 — All 50 Go Non-Manifest / Companion / SSR / Built-in Extractors + +Every non-manifest Go/companion/ATS/hydration/built-in extractor verified in `m7_audit_results.json` (`builtinsPassed: 50/50`). + +| # | id | subsystem | `edgefetch.adapter_id` | Go / TS Source | Track B Probe Status | +|---:|---|---|---|---|---| +| 1 | `ashby-board` | ats | `ashby-board` | `internal/jobs/ats.go` | PASS (2.43 ms; status=200 span=ashby-board extractorId=ashby-board) | +| 2 | `ashby-job` | ats | `ashby-job` | `internal/jobs/ats.go` | PASS (0.99 ms; status=200 span=ashby-job extractorId=ashby-job) | +| 3 | `workday-board` | ats | `workday-board` | `internal/jobs/ats.go` | PASS (1.93 ms; status=200 span=workday-board extractorId=workday-board) | +| 4 | `workday-job` | ats | `workday-job` | `internal/jobs/ats.go` | PASS (1.76 ms; status=200 span=workday-job extractorId=workday-job) | +| 5 | `greenhouse-board` | ats | `greenhouse-board` | `internal/jobs/ats.go` | PASS (1.18 ms; status=200 span=greenhouse-board extractorId=greenhouse-board) | +| 6 | `greenhouse-eu-board` | ats | `greenhouse-eu-board` | `internal/jobs/ats.go` | PASS (0.91 ms; status=200 span=greenhouse-eu-board extractorId=greenhouse-eu-board) | +| 7 | `greenhouse-job` | ats | `greenhouse-job` | `internal/jobs/ats.go` | PASS (1.13 ms; status=200 span=greenhouse-job extractorId=greenhouse-job) | +| 8 | `lever-board` | ats | `lever-board` | `internal/jobs/ats.go` | PASS (1.76 ms; status=200 span=lever-board extractorId=lever-board) | +| 9 | `lever-eu-board` | ats | `lever-eu-board` | `internal/jobs/ats.go` | PASS (0.83 ms; status=200 span=lever-eu-board extractorId=lever-eu-board) | +| 10 | `lever-job` | ats | `lever-job` | `internal/jobs/ats.go` | PASS (1.19 ms; status=200 span=lever-job extractorId=lever-job) | +| 11 | `workable-board` | ats | `workable-board` | `internal/jobs/ats.go` | PASS (0.71 ms; status=200 span=workable-board extractorId=workable-board) | +| 12 | `workable-job` | ats | `workable-job` | `internal/jobs/ats.go` | PASS (1.12 ms; status=200 span=workable-job extractorId=workable-job) | +| 13 | `gem-board` | ats | `gem-board` | `internal/jobs/ats.go` | PASS (0.83 ms; status=200 span=gem-board extractorId=gem-board) | +| 14 | `rippling-board` | ats | `rippling-board` | `internal/jobs/ats.go` | PASS (0.76 ms; status=200 span=rippling-board extractorId=rippling-board) | +| 15 | `rippling-job` | ats | `rippling-job` | `internal/jobs/ats.go` | PASS (1.60 ms; status=200 span=rippling-job extractorId=rippling-job) | +| 16 | `weworkremotely-feed` | ats-feed | `weworkremotely-feed` | `internal/jobs/ats.go + internal/jobs/ats_feeds.go` | PASS (1.09 ms; status=200 span=weworkremotely-feed extractorId=weworkremotely-feed) | +| 17 | `himalayas-feed` | ats-feed | `himalayas-feed` | `internal/jobs/ats.go + internal/jobs/ats_feeds.go` | PASS (0.56 ms; status=200 span=himalayas-feed extractorId=himalayas-feed) | +| 18 | `workingnomads-feed` | ats-feed | `workingnomads-feed` | `internal/jobs/ats.go + internal/jobs/ats_feeds.go` | PASS (1.35 ms; status=200 span=workingnomads-feed extractorId=workingnomads-feed) | +| 19 | `jobposting-jsonld` | ats-jsonld | `null` (structural/JSON-LD/hydration) | `internal/jobs/jsonld.go` | PASS (0.33 ms; remote) | +| 20 | `ats-board-discovery` | ats-discovery | `discovered board atsSpec.id when resolved` | `internal/jobs/discovery.go` | PASS (2.26 ms; boards=1) | +| 21 | `shopify-engine` | catalog-commerce | `shopify` | `internal/catalog/shopify.go + internal/catalog/shopify_html.go` | PASS (1.69 ms; extractorId=none) | +| 22 | `woocommerce-engine` | catalog-commerce | `woocommerce` | `internal/catalog/woocommerce.go + internal/catalog/woocommerce_html.go` | PASS (1.86 ms; extractorId=woocommerce) | +| 23 | `squarespace-commerce-engine` | catalog-commerce | `squarespace-commerce` | `internal/catalog/squarespace.go` | PASS (0.85 ms; extractorId=none) | +| 24 | `sfcc-demandware-engine` | catalog-commerce | `sfcc-demandware` | `internal/catalog/sfcc.go` | PASS (0.79 ms; extractorId=sfcc-demandware) | +| 25 | `shopware-magento-engine` | catalog-commerce | `shopware-magento` | `internal/catalog/shopware_magento.go` | PASS (1.39 ms; extractorId=shopware-magento) | +| 26 | `bigcommerce-engine` | catalog-commerce | `bigcommerce-store` | `internal/catalog/bigcommerce.go` | PASS (0.68 ms; extractorId=none) | +| 27 | `wave2a-commerce-engines` | catalog-commerce | `vtex` | sap-commerce-occ \ | PASS (0.12 ms; vtex_product) | +| 28 | `wave2b-commerce-engines` | catalog-commerce | `medusa` | big-cartel \ | PASS (0.10 ms; medusa_product) | +| 29 | `wordpress-rest` | cms-auto-twin | `wordpress-rest` | `internal/extract/cms_twins.go` | PASS (2.36 ms; status=200 span=null extractorId=undefined) | +| 30 | `gatsby-page-data` | cms-auto-twin | `gatsby-page-data` | `internal/extract/cms_twins.go` | PASS (3.40 ms; status=200 span=null extractorId=undefined) | +| 31 | `platform-companion-twins` | platform-companion | `matched companion adapterId (e.g. algolia, bazaarvoice, powerreviews, yext-locator, ecwid, medusa, klevu, headless-cms-delivery, vtex, sap-commerce-occ, oracle-commerce, hcl-websphere-commerce, lightspeed-ecom, big-cartel, spree-solidus, saleor, searchspring, yotpo, stockist, storemapper, storerocket, khoros-lithium, aem, arc-xp, townnews-blox, status-page-pack, changelog-roadmap-pack, hubspot-cms)` | `internal/extract/platform_twins.go` | PASS (0.21 ms; found=undefined id=none) | +| 32 | `cpsc-recalls-companion` | platform-companion | `cpsc-recalls` | `internal/extract/manifests/cpsc-recalls.yaml` | PASS (4.51 ms; status=200 span=cpsc-recalls extractorId=cpsc-recalls) | +| 33 | `hydration:nextjs` | ssr-hydration | `null` (structural/JSON-LD/hydration) | `internal/extract/hydration.go` | PASS (0.30 ms; framework=nextjs) | +| 34 | `hydration:nextjs-rsc` | ssr-hydration | `null` (structural/JSON-LD/hydration) | `internal/extract/hydration.go` | PASS (0.24 ms; framework=nextjs-rsc) | +| 35 | `hydration:nuxt` | ssr-hydration | `null` (structural/JSON-LD/hydration) | `internal/extract/hydration.go` | PASS (0.20 ms; framework=nuxt) | +| 36 | `hydration:angular` | ssr-hydration | `null` (structural/JSON-LD/hydration) | `internal/extract/hydration.go` | PASS (0.29 ms; framework=angular) | +| 37 | `hydration:wix` | ssr-hydration | `null` (structural/JSON-LD/hydration) | `internal/extract/hydration.go` | PASS (0.15 ms; framework=wix) | +| 38 | `hydration:remix` | ssr-hydration | `null` (structural/JSON-LD/hydration) | `internal/extract/hydration.go` | PASS (0.15 ms; framework=remix) | +| 39 | `hydration:apollo` | ssr-hydration | `null` (structural/JSON-LD/hydration) | `internal/extract/hydration.go` | PASS (0.17 ms; framework=apollo) | +| 40 | `hydration:squarespace` | ssr-hydration | `null` (structural/JSON-LD/hydration) | `internal/extract/hydration.go` | PASS (0.17 ms; framework=squarespace) | +| 41 | `hydration:substack` | ssr-hydration | `null` (structural/JSON-LD/hydration) | `internal/extract/hydration.go` | PASS (0.36 ms; framework=substack) | +| 42 | `hydration:inertia` | ssr-hydration | `null` (structural/JSON-LD/hydration) | `internal/extract/hydration.go` | PASS (0.19 ms; framework=inertia) | +| 43 | `hydration:gatsby` | ssr-hydration | `null` (structural/JSON-LD/hydration) | `internal/extract/hydration.go` | PASS (0.05 ms; framework=checked) | +| 44 | `hydration:cdp-xhr-json` | ssr-hydration | `null` (structural/JSON-LD/hydration) | `internal/extract/hydration.go` | PASS (1.44 ms; distilled=true) | +| 45 | `schema-org` | universal-schema-org | `schema-org` | `internal/extract/schema_org.go` | PASS (0.23 ms; Article) | +| 46 | `mediawiki-builtin` | builtin-html-doc | `mediawiki` | `internal/extract/html_doc_extract.go:5532 + internal/extract/wikipedia.go` | PASS (3.94 ms; status=200 span=mediawiki extractorId=mediawiki) | +| 47 | `stackexchange-qa-builtin` | builtin-html-doc | `stackexchange-qa` | `internal/extract/html_doc_extract.go:5519` | PASS (3.49 ms; status=200 span=stackexchange-qa extractorId=stackexchange-qa) | +| 48 | `ietf-rfc-builtin` | builtin-html-doc | `ietf-rfc` | `internal/extract/html_doc_extract.go:5525` | PASS (2.44 ms; status=200 span=ietf-rfc extractorId=ietf-rfc) | +| 49 | `llms-txt` | builtin-llms | `null` (structural/JSON-LD/hydration) | `internal/extract/llms.go` | PASS (0.64 ms; links=1) | +| 50 | `pdf-extractor` | builtin-pdf | `null` (structural/JSON-LD/hydration) | `internal/extract/pdf.go` | PASS (0.74 ms; title=--- Page 1 ---) | + +--- + +## 4. `detect-only` Retirement & `page-key` Default-ON Verification + +### 4.1 Zero `detect-only` Scraper Stubs & 7 Converted Wave 2 Manifests +- **`compiled.json` Check:** `0` of `486` compiled manifests declare `auth_mode: detect-only`. +- **Pre-Fetch Retirement (`internal/classify/detect_only.go:19-21`):** `ClassifyDetectOnly(_, _)` unconditionally returns `DetectOnlyResult{Matched: false}` so no public URL is blocked pre-fetch across `/v1/scrape`, `/v1/extract`, `/v1/map`, `/v1/crawl`, or crawler MCP tools. +- **Part 2 MCP Federation `closed_api_refusal` Intact:** Virtual OAuth MCP refusal (`closed_api_refusal`, HTTP `403`) remains strictly enforced in `hub/src/mcp-catalog.ts:822,830-899`, `hub/src/mcp-federation.ts:2134,2376,2500`, `hub/src/admin.ts`, and re-exported by `hub/src/mcp-virtual.ts:23,46` for closed-API targets (`linkedin`, `indeed`, `glassdoor`, `zillow`). +- **7 Converted Wave 2 Manifests Verified in Track A & Track B:** + +| id | Wave 2 # | Category | Conversion | Track A Live Outcome | `edgefetch.adapter_id` Span | Golden + Negative Status | +|---|---|---|---|---|---|---| +| `costco-sams-club` | #138 | commerce-social | `detect-only` -> `html` | pass (HTTP 200, 15.41 ms) | `costco-sams-club` | golden + 4-way + 4 fixture neg (8 neg pass) | +| `dining-reservations` | #190 | commerce-social | `detect-only` -> `html` | blocked_by_origin (HTTP 0, 1.96 ms) | `dining-reservations` | golden + 4-way + 4 fixture neg (8 neg pass) | +| `finra-brokercheck` | #83 | finance | `detect-only` -> `pub` | pass (HTTP 200, 0.47 ms) | `finra-brokercheck` | golden + 4-way + 4 fixture neg (8 neg pass) | +| `ncaa-espn` | #195 | commerce-social | `detect-only` -> `pub` | pass (HTTP 200, 42.88 ms) | `ncaa-espn` | golden + 4-way + 4 fixture neg (8 neg pass) | +| `pacer-case-locator` | #64 | public-records | `detect-only` -> `html` | pass_partial_blocked (HTTP 200, 6.38 ms) | `pacer-case-locator` | golden + 4-way + 4 fixture neg (8 neg pass) | +| `state-court-portals` | #72 | public-records | `detect-only` -> `html` | pass_partial_blocked (HTTP 200, 5.31 ms) | `state-court-portals` | golden + 4-way + 4 fixture neg (8 neg pass) | +| `target` | #136 | commerce-social | `detect-only` -> `html` | pass (HTTP 200, 3.44 ms) | `target` | golden + 4-way + 4 fixture neg (8 neg pass) | + +### 4.2 `page-key` Default-ON + Explicit `false` Opt-Out Verification (`17` Manifests + `shopify-storefront-graphql` Companion = `18/18`) +- `resolveAllowPageKeyTwins` (`hub/src/storage.ts:191-199`), `resolveSiteExtractorTwin` (`hub/src/extractors/registry.ts:309,332`), `hub/src/mcp.ts:796,885`, and Go `ResolveDeclarativeTwin` / `DiscoverPlatformCompanionTwin` (`*bool` `AllowPageKeyTwins`, `nil = true`) default `page-key` twins to **ON** while honoring explicit `allowPageKeyTwins: false` or `EDGEFETCH_ALLOW_PAGE_KEY_TWINS="false"|"0"`. +- All **17** manifest-level `page-key` manifests (14 Wave 2 + 3 Wave 3) plus `shopify-storefront-graphql` (`auth_mode: pub` tokenless route + `page-key` companion discovery) passed both default-ON resolution and explicit-OFF isolation in `m7_audit_results.json`: + +| # | id | Default / `allowPageKeyTwins: true` | Explicit `allowPageKeyTwins: false` | Status | +|---:|---|---|---|---| +| 1 | `algolia` | `algolia` | `null` | PASS | +| 2 | `bazaarvoice` | `bazaarvoice` | `null` | PASS | +| 3 | `bloomreach-discovery` | `bloomreach-discovery` | `null` | PASS | +| 4 | `brightcove` | `brightcove` | `null` | PASS | +| 5 | `constructor-io` | `constructor-io` | `null` | PASS | +| 6 | `coveo` | `coveo` | `null` | PASS | +| 7 | `dealer-locator-pack` | `dealer-locator-pack` | `null` | PASS | +| 8 | `ecwid` | `ecwid` | `null` | PASS | +| 9 | `headless-cms-delivery` | `headless-cms-delivery` | `null` | PASS | +| 10 | `klevu` | `klevu` | `null` | PASS | +| 11 | `medusa` | `medusa` | `null` | PASS | +| 12 | `powerreviews` | `powerreviews` | `null` | PASS | +| 13 | `small-search` | `small-search` | `null` | PASS | +| 14 | `yext-locator` | `yext-locator` | `null` | PASS | +| 15 | `rebuy-searchanise` | `rebuy-searchanise` | `null` | PASS | +| 16 | `shopify-filter-apps` | `shopify-filter-apps` | `null` | PASS | +| 17 | `shopify-hydrogen` | `null` (`html_only_no_prefetch_twin`; live HTML `shopify-hydrogen` PASS) | `null` | PASS | +| 18 | `shopify-storefront-graphql` | `shopify-storefront-graphql` | `null` | PASS | + +--- + +## 5. Track C Keyed API Secret-Redaction, `makeKeyHint` & OTLP Scrubbing Summary + +### 5.1 `makeKeyHint` Boundary Checks (`5/5`) +Verified via `sealUserApiKey` (`< 16` chars -> `****`; `>= 16` chars -> `...` + last 4 characters): + +| # | Case | Key Length | Expected Hint | Observed Hint | Status | +|---:|---|---:|---|---|---| +| 1 | `len4` | 4 | `****` | `****` | PASS | +| 2 | `len8` | 8 | `****` | `****` | PASS | +| 3 | `len15` | 15 | `****` | `****` | PASS | +| 4 | `len16` | 16 | `...abcd` | `...abcd` | PASS | +| 5 | `len32` | 31 | `...wxyz` | `...wxyz` | PASS | + +### 5.2 Keyed Manifest & Provider Redaction + OTLP Scrubbing (`90/90`) +Every keyed manifest (`71`), official provider spec (`69` specs, `8` `DATA_GOV_ADAPTER_IDS`, deduplicated with manifests), and multi-host sub-provider route (`13`) — **90** targets total — passed all 5 Track C invariants: +1. **200 Echo Redaction (`fetchWithOfficialApiKey`):** Canary secrets (plus `PODCASTINDEX_API_SECRET` / `TWITCH_CLIENT_ID` where applicable) in raw, URL-encoded, `+`-space, lower-hex, and `URLSearchParams` forms are scrubbed to `[redacted]` in `body` and `finalUrl`. +2. **Cross-Origin 302 Blocking:** Redirects to `https://evil.example.org/steal` fail closed with `403 cross_origin_redirect_blocked`. +3. **Same-Origin 302 Blocking:** Redirects on official keyed calls fail closed with `403 redirect_blocked`. +4. **Direct Body Scrubbing (`redactSecretsInBody`):** Zero canary variants survive direct scrubbing. +5. **OTel Span & OTLP Payload Scrubbing:** `sanitizeSpanAttributes`, `buildOtlpTracePayload`, and `executeScrapeCall` / `executeExtractCall` error paths leak zero canary variants while preserving `edgefetch.adapter_id` spans. + +| # | Target ID | Kind | Provider ID | Env Key | Status | +|---:|---|---|---|---|---| +| 1 | `airnow` | `keyed_manifest` | `airnow` | `AIRNOW_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 2 | `bea` | `keyed_manifest` | `bea` | `BEA_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 3 | `bestbuy` | `keyed_manifest` | `bestbuy` | `BESTBUY_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 4 | `bls` | `keyed_manifest` | `bls` | `BLS_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 5 | `carrier-tracking-official` | `keyed_manifest` | `carrier-tracking-official` | `USPS_ACCESS_TOKEN` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 6 | `census` | `keyed_manifest` | `census` | `CENSUS_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 7 | `college-scorecard` | `keyed_manifest` | `college-scorecard` | `DATA_GOV_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 8 | `congress-gov` | `keyed_manifest` | `congress-gov` | `DATA_GOV_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 9 | `core-ac` | `keyed_manifest` | `core-ac` | `CORE_AC_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 10 | `courtlistener` | `keyed_manifest` | `courtlistener` | `COURTLISTENER_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 11 | `dol-enforcement` | `keyed_manifest` | `dol-enforcement` | `DOL_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 12 | `dpla` | `keyed_manifest` | `dpla` | `DPLA_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 13 | `ebay` | `keyed_manifest` | `ebay` | `EBAY_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 14 | `eia` | `keyed_manifest` | `eia` | `EIA_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 15 | `etsy` | `keyed_manifest` | `etsy` | `ETSY_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 16 | `eventbrite` | `keyed_manifest` | `eventbrite` | `EVENTBRITE_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 17 | `farcaster-hub` | `keyed_manifest` | `farcaster-hub` | `NEYNAR_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 18 | `fcc-ecfs` | `keyed_manifest` | `fcc-ecfs` | `DATA_GOV_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 19 | `fec` | `keyed_manifest` | `fec` | `DATA_GOV_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 20 | `ffiec-cdr` | `keyed_manifest` | `ffiec-cdr` | `FFIEC_CDR_API_TOKEN` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 21 | `fmcsa-safer` | `keyed_manifest` | `fmcsa-safer` | `FMCSA_WEB_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 22 | `foursquare-places` | `keyed_manifest` | `foursquare-places` | `FOURSQUARE_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 23 | `fpds-sam-contract-awards` | `keyed_manifest` | `fpds-sam-contract-awards` | `SAM_GOV_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 24 | `fred` | `keyed_manifest` | `fred` | `FRED_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 25 | `google-places` | `keyed_manifest` | `google-places` | `GOOGLE_PLACES_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 26 | `gs1-us-datahub` | `keyed_manifest` | `gs1-us-datahub` | `GS1_US_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 27 | `gsa-site-scanning` | `keyed_manifest` | `gsa-site-scanning` | `DATA_GOV_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 28 | `healthcare-gov-marketplace` | `keyed_manifest` | `healthcare-gov-marketplace` | `HEALTHCARE_GOV_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 29 | `hud-fhfa` | `keyed_manifest` | `hud-fhfa` | `HUD_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 30 | `igdb` | `keyed_manifest` | `igdb` | `TWITCH_API_TOKEN` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 31 | `kaggle` | `keyed_manifest` | `kaggle` | `KAGGLE_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 32 | `kroger` | `keyed_manifest` | `kroger` | `KROGER_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 33 | `libraries-io` | `keyed_manifest` | `libraries-io` | `LIBRARIES_IO_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 34 | `market-quotes-pack` | `keyed_manifest` | `market-quotes-pack` | `ALPHAVANTAGE_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 35 | `nasa-ads` | `keyed_manifest` | `nasa-ads` | `NASA_ADS_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 36 | `nasa-apis` | `keyed_manifest` | `nasa-apis` | `NASA_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 37 | `nasdaq-data-link` | `keyed_manifest` | `nasdaq-data-link` | `NASDAQ_DATA_LINK_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 38 | `national-archives` | `keyed_manifest` | `national-archives` | `NARA_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 39 | `noaa-ncei-cdo` | `keyed_manifest` | `noaa-ncei-cdo` | `NOAA_NCEI_TOKEN` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 40 | `nps` | `keyed_manifest` | `nps` | `DATA_GOV_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 41 | `nyt-api` | `keyed_manifest` | `nyt-api` | `NYT_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 42 | `opencorporates` | `keyed_manifest` | `opencorporates` | `OPENCORPORATES_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 43 | `podcast-index` | `keyed_manifest` | `podcast-index` | `PODCASTINDEX_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 44 | `product-hunt` | `keyed_manifest` | `product-hunt` | `PRODUCTHUNT_API_TOKEN` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 45 | `recreation-gov-ridb` | `keyed_manifest` | `recreation-gov-ridb` | `RECREATION_GOV_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 46 | `regulations-gov` | `keyed_manifest` | `regulations-gov` | `DATA_GOV_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 47 | `sam-gov` | `keyed_manifest` | `sam-gov` | `SAM_GOV_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 48 | `setlist-lastfm` | `keyed_manifest` | `setlist-lastfm` | `SETLISTFM_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 49 | `smithsonian-open-access` | `keyed_manifest` | `smithsonian-open-access` | `DATA_GOV_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 50 | `spotify-web-api` | `keyed_manifest` | `spotify-web-api` | `SPOTIFY_ACCESS_TOKEN` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 51 | `state-legislatures` | `keyed_manifest` | `state-legislatures` | `OPENSTATES_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 52 | `strava-segments` | `keyed_manifest` | `strava-segments` | `STRAVA_ACCESS_TOKEN` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 53 | `substack-notes-beehiiv` | `keyed_manifest` | `substack-notes-beehiiv` | `BEEHIIV_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 54 | `threads-api` | `keyed_manifest` | `threads-api` | `THREADS_ACCESS_TOKEN` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 55 | `ticketmaster-discovery` | `keyed_manifest` | `ticketmaster-discovery` | `TICKETMASTER_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 56 | `tmdb` | `keyed_manifest` | `tmdb` | `TMDB_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 57 | `trade-gov-csl` | `keyed_manifest` | `trade-gov-csl` | `TRADE_GOV_CSL_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 58 | `trailforks-mtb-project` | `keyed_manifest` | `trailforks-mtb-project` | `TRAILFORKS_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 59 | `transitland-gtfs` | `keyed_manifest` | `transitland-gtfs` | `TRANSITLAND_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 60 | `tumblr` | `keyed_manifest` | `tumblr` | `TUMBLR_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 61 | `twitch-kick` | `keyed_manifest` | `twitch-kick` | `TWITCH_API_TOKEN` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 62 | `upcitemdb-barcodelookup` | `keyed_manifest` | `upcitemdb-barcodelookup` | `BARCODELOOKUP_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 63 | `usajobs` | `keyed_manifest` | `usajobs` | `USAJOBS_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 64 | `usda-nass-fdc` | `keyed_manifest` | `usda-nass-fdc` | `USDA_FDC_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 65 | `usps-addresses` | `keyed_manifest` | `usps-addresses` | `USPS_ACCESS_TOKEN` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 66 | `uspto-patentsview` | `keyed_manifest` | `uspto-patentsview` | `USPTO_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 67 | `uspto-tsdr` | `keyed_manifest` | `uspto-tsdr` | `USPTO_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 68 | `va-lighthouse-facilities` | `keyed_manifest` | `va-lighthouse-facilities` | `VA_LIGHTHOUSE_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 69 | `walmart` | `keyed_manifest` | `walmart` | `WALMART_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 70 | `yelp-fusion` | `keyed_manifest` | `yelp-fusion` | `YELP_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 71 | `youtube-data-api` | `keyed_manifest` | `youtube-data-api` | `YOUTUBE_DATA_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 72 | `api-data-gov` | `official_spec` | `api-data-gov` | `DATA_GOV_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 73 | `senate-lda` | `official_spec` | `senate-lda` | `SENATE_LDA_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 74 | `legiscan` | `official_spec` | `legiscan` | `LEGISCAN_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 75 | `semantic-scholar` | `official_spec` | `semantic-scholar` | `SEMANTIC_SCHOLAR_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 76 | `open-icecat` | `official_spec` | `open-icecat` | `ICECAT_API_TOKEN` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 77 | `discogs` | `official_spec` | `discogs` | `DISCOGS_API_TOKEN` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 78 | `state-legislatures:legiscan` | `sub_provider` | `state-legislatures` | `LEGISCAN_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 79 | `usda-nass-fdc:nass` | `sub_provider` | `usda-nass-fdc` | `USDA_NASS_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 80 | `usda-nass-fdc:fdc` | `sub_provider` | `usda-nass-fdc` | `USDA_FDC_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 81 | `twitch-kick:kick` | `sub_provider` | `twitch-kick` | `KICK_API_TOKEN` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 82 | `carrier-tracking-official:usps` | `sub_provider` | `carrier-tracking-official` | `USPS_ACCESS_TOKEN` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 83 | `carrier-tracking-official:ups` | `sub_provider` | `carrier-tracking-official` | `UPS_ACCESS_TOKEN` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 84 | `carrier-tracking-official:fedex` | `sub_provider` | `carrier-tracking-official` | `FEDEX_ACCESS_TOKEN` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 85 | `upcitemdb-barcodelookup:barcodelookup` | `sub_provider` | `upcitemdb-barcodelookup` | `BARCODELOOKUP_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 86 | `setlist-lastfm:lastfm` | `sub_provider` | `setlist-lastfm` | `LASTFM_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 87 | `market-quotes-pack:alphavantage` | `sub_provider` | `market-quotes-pack` | `ALPHAVANTAGE_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 88 | `market-quotes-pack:polygon` | `sub_provider` | `market-quotes-pack` | `POLYGON_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 89 | `market-quotes-pack:tiingo` | `sub_provider` | `market-quotes-pack` | `TIINGO_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | +| 90 | `substack-notes-beehiiv:beehiiv` | `sub_provider` | `substack-notes-beehiiv` | `BEEHIIV_API_KEY` | PASS (200 redact + cross/same 302 block + direct scrub + OTLP span scrub) | + +--- + +## 6. Bugs Fixed in M7 + +All regressions surfaced across the 5 cross-batch triage items and M7 live/OTel/latency/classifier/streaming sweeps were diagnosed to genuine root causes and fixed on the spot: + +### 6.1 Cross-Batch Triage Items (Triage 1–5) +- **Triage 1 — `sram-docs` Early JSON Guard (`internal/extract/m3_html_modes.go:1790-1794`):** Added BOM-trimmed `{`/`[` and missing `<`/`>` prefilter in `runSramDocsExtractorDeclHTML` before `stripDropTagsLinearDeclHTML` / `ParseHTMLDoc`, cutting `valid-json-hostile-angles-100k` bulkhead fuzz latency from `58–77 ms` to `< 18 ms` (`m3_html_modes_test.go:1096-1124`). +- **Triage 2 — `router.go` Short-Token Boundary Matching & `auth-mcp-isolation.test.ts` (`internal/agentloop/router.go`, `router_test.go`, `hub/test/auth-mcp-isolation.test.ts:6270`):** Replaced 2-char substring `strings.Contains` matching (`"yc"`/`"hn"` matching `"bicycle"`/`"technical"`) with word-boundary token sets (`reBoundarySplit`) + explicit short-token aliases (`"yc" -> "ycombinator"`, `"hn" -> "hackernews"`), keeping `ycombinator` & `hackernews` #1/#2 for `"yc hn"` and updating `auth-mcp-isolation.test.ts` to accept `cve-org || nist-nvd || osv-cve` while asserting `nist-nvd` remains present. +- **Triage 3 — `/v1/extract` Empty-Markdown Fallback (`hub/src/search-index.ts:3072-3075`):** Aligned with `hub/src/scrape.ts` so empty HTML extraction (`""`) never falls through to `rawBodyStr` on unhydrated `energystar` SPA shells (`empty_shell` instead of `active`). +- **Triage 4 — `company-newsrooms.yaml` `/feed` Scoping (`internal/extract/manifests/company-newsrooms.yaml:22-30`):** Scoped `routes[0].match` to the manifest's 5 declared hosts (`news.cision.com`, `multimedia.cision.com`, `*.prowly.com`, `*.prezly.com`, `press.brusselsairlines.com`) so `company-newsrooms` no longer hijacks `milkroad.beehiiv.com/feed` (`newsletter-archives`). +- **Triage 5 — `content_state.go` Redundant `"invalid as"` Clause (`internal/classify/content_state.go:2758-2761`):** Removed the redundant `<10`-word `"invalid as"` check already covered by `reNotFoundBodyCSGo` / `reNotFoundHeadingCSGo`. + +### 6.2 Go Core Performance, Streaming & Prefilters +- **Single-Call Universal HTML Extraction (`cmd/edgefetch-wasm/reactor.go`, `hub/test/post-fetch-wasm.ts`):** Aligned with `#148` (`ecd3c11`) zero-JSON-escape `post_extract_html` raw-pair RPC (`postExtractHtml`), running universal HTML extraction in a single JS->WASM call instead of 88+ boundary crossings (`paradox-olivia` on `careers.fedex.com` dropped from `86–119 ms` to `38.62 ms` in Track A) with zero TypeScript post-fetch candidate loops in `hub/src/extractors/registry.ts`. +- **Mode Prefilters Before `HasNegativeShell` (`wave3_store_addons.go`, `wave3_jobs_public.go`, `wave3_edu.go`, `wave3_prop_rest_ir.go`, `wave3_community.go`):** Added zero-allocation `containsAnyFoldASCIIExtract` mode prefilters ahead of `HasNegativeShell` DOM/lowercase allocations. +- **DOM & Script/Style Trimming + Linear Scanners (`wave3_gov.go`, `wave3_cycling_oems.go`, `wave3_cycling_components.go`, `wave3_resale.go`, `wave3_media_lyrics.go`, `wave3_store_addons.go`, `wave3_edu.go`, `wave3_security_intel.go`):** Short-circuited `municipal-cms-pack` `bodyFrag` extraction and capped `bodyFrag` at `80 KiB` (`glendaleaz.gov/Home` `150,191 -> 52,911` chars, `73.79 ms < 75 ms`); moved JSON-LD/hydration/meta extraction before `stripScriptsAndStylesDeclHTML` + `512 KiB` caps; replaced regex/O(N*M) scans with `indexFoldASCIIExtract`, `wave3CyclingScanNuxtGeomKVLinear`, `ExtractBalancedJSONAt`, and linear RSS/XML/CISA-KEV scans. +- **Bounded Streaming for Large Feeds (`wave3_security_intel.go`, `wave3_dev_infra.go`, `wave3_finance.go`):** Added `wave3SecStreamTruncatedMitreCollection` for `512 KiB` Range-truncated `mitre-attack` bundles; wired `Wave3DevFormatWebCompatText` (`web_compat_json` / `web_compat_bounded`) with `json.NewDecoder` prefix streaming for `web-features/data.json`; added `wave3DevStreamPuppetForgeModuleFromNextData` (`ansible-puppet-forge`); added `wave3FinFormatSECCompanyFactsStream` for `> 64 KiB` `sec-xbrl-frames` companyfacts payloads. + +### 6.3 Preemption, Classifier, Extraction & Manifest / Retry Fixes (Go-First) +- **Companion Twin & Custom-Domain Preemption (`internal/extract/platform_twins.go`, `internal/extract/declarative.go`, `internal/extract/html_doc_extract.go`, `hub/src/scrape.ts`, `hub/src/search-index.ts`):** Restricted `DiscoverPlatformCompanionTwin` and custom-domain commerce enrichment (`shopify`, `woocommerce`, `squarespace-commerce`, `sfcc-demandware`, `shopware-magento`) via Go `IsDomainSpecificExtractorID` (`extracted.skipOverlayEnrichment`) and `extracted.authoritative`; skipped `browser-auto` render fallback whenever Go `extractHtmlDocument` already matched an `extractorId`. +- **CSR Shell, Cookie Gate, Login Wall & Passive WAF Guards (`internal/extract/declarative_html.go`, `internal/classify/content_state.go`, `internal/classify/waf.go`, `wave3_scholarly.go`, `wave3_prop_rest_ir.go`, `wave3_regulators.go`, `wave2_upgraded_extractors.go`):** Implemented pure-Go zero-regex `IsObviousUnhydratedCSRShell` (`extracted.unhydratedCsrShell`) and Go CSR checks (``, `#application`, eGain `.loading_container`, `data-ng-app="app.main"`, `#cr-portal-title`, Cision `#item-listing-container` KnockoutJS, Narvar `fallback_tracking_number`), gated P1 meta-description rescue on `!extracted?.unhydratedCsrShell`, classified `pcl.uscourts.gov` as `login_wall`, added Go Azure `406` WAF detection (`detectAzure406WafBlockCSGo`), and gated passive WAF SDK substring checks (`awswaf`, `challenge-platform`) on `len(rawHTML) < 16384 && !hasRealBodyMarkers`. +- **Extractor Accuracy (`wave3_gov.go`, `wave3_edu.go`, `wave3_jobs_public.go`, `wave3_scholarly.go`, `wave3_cycling_oems.go`, `wave3_cycling_components.go`, `wave3_resale.go`, `wave3_media_lyrics.go`, `wave3_prop_rest_ir.go`, `wave3_store_addons.go`, `wave2_upgraded_extractors.go`):** Added Taleo `fillList` SSR joblist/jobdetail parsing (`taleo-full`), fixed GovDelivery `IsFragment: false` table preservation, Laserfiche `repoName` fallback, balanced `
` slicing for `state-court-portals`, OpenGov `window.gon` balanced JSON skipping, `canvas-public-courses` marker narrowing, Dryad JSON-LD `@id`/`creator` (`research-repo-pack`), `r-m.de`/`pushindustries.com` media-iframe exemption, Gumroad Inertia `data-page`, AZLyrics comment-inside-div slicing, Prowly/Cision selectors, and Gorgias `selectedCategory`/`childrenArticles`/`sidebarCategories`. +- **Redirect `Range`, Truncated Streams, `Crawl-delay` Budgets & Transient Retries (`internal/extract/declarative.go`, `internal/extract/policy.go`, `internal/extract/platform_twins.go`, `internal/extract/wave3_social_creator.go`, `hub/src/overflow.ts`, `hub/src/scrape.ts`, `internal/extract/manifests/*.yaml`):** Forwarded validated `Range` headers across redirects (`ofac-sdn`), moved twin redirect/truncated-stream policy (`ValidateTwinRedirectFull`, `AllowCrossOriginRedirects`, `AllowTruncatedStream`), `saferproducts.gov` unbounded query guard (`CheckUnboundedTwinEndpointGuard`), `bgp.he.net` `1 MiB` truncation (`MaxFetchBytes`), and Nostr NIP-01 framing/formatting (`PrepareNostrNIP01`, `FormatNostrNIP01Frames`) into Go/WASM, bumped twin `maxSeconds` (`30 -> 45`) so `30s` `Crawl-delay` hosts (`www.gao.gov`) retain HTTP request budget, added polite single GET/HEAD transient retry, and updated `34+` manifest `exampleUrls`/`domains`/`headers` (including `nostr-relays` `purplepag.es` and `e-bike-state-laws` `content.leg.colorado.gov`). +- **Challenger Iteration 2 Hardening (`internal/extract/declarative_html.go`, `internal/classify/content_state.go`, `internal/classify/waf.go`, `internal/extract/manifests/ir-portal-pack.yaml`):** Implemented cached-`>` linear `O(N)` scanning + BOM/JSON/angle-bracket short-circuits in `IsObviousUnhydratedCSRShell`, `applyDeclarativeHTMLExtractorLazy` (`postExtractHtml`), `stripWafDropBlocksLinearCSGo`, and `detectAzure406WafBlockCSGo` (`< 5 ms` on 50k `<` / 20k `
` / 20k `${' + 2k `, + }, + { + url: 'https://hts.usitc.gov/search?query=8712', + html: `HTS`, + }, + { + url: 'https://search.certifications.sba.gov/profile/123', + html: `SBA
`, + }, + ]; + for (const tc of csrPayloads) { + const t0 = performance.now(); + const out = postExtractHtml(tc.html, tc.url, ''); + const dt = performance.now() - t0; + assert.equal(out, null, `78 KB CSR shell for ${tc.url} must return null`); + assert.ok(dt < 75, `78 KB CSR shell for ${tc.url} exceeded 75ms budget: ${dt.toFixed(2)}ms`); + } + assert.deepEqual( + extractSensitiveHeaderSecrets({ transactionSrc: 'edgefetch', transId: 'edgefetch-123', 'subscription-key': 'sub_secret_1234' }), + ['sub_secret_1234'], + ); +}); + +test('Wave 3 B3 Round 2 Remediations: ofac-sdn untrusted S3 cross-origin redirect fail-closed, URLSearchParams/%2b scrubbing, attr-first CSR shell, BOM sdnList', async () => { + resetIsolateBudgetForTests(); + resetOverflowRobotsCacheForTests(); + + // 1. P1: ofac-sdn S3 redirect rejects /exports/error/SDN.XML, /Published/error/SDN.XML, evil-bucket, wrong region, and notice.html + // AND both executeScrapeCall + executeExtractCall fail closed (contentState !== 'active', zero second-hop retry) + const ofacSourceUrl = 'https://sanctionslistservice.ofac.treas.gov/api/PublicationPreview/exports/SDN.XML'; + const ofacFx = JSON.parse(readFileSync(resolve('test', 'fixtures', 'adapters', 'ofac-sdn.json'), 'utf8')) as B3Fixture; + for (const goodS3 of [ + 'https://wc2h-sls-prod-public-published.s3.us-gov-west-1.amazonaws.com/Published/Current/SDN.XML', + 'https://wc2h-sls-prod-public-published.s3.us-gov-west-1.amazonaws.com/Published/2026-11-20/SDN.XML', + 'https://wc2h-sls-prod-public-published.s3.us-gov-west-1.amazonaws.com/Published/4bd23a9b-4fdf-4f09-a396-4d7e72836c71/2026-11-20/6b7c553e-b803-4d42-8b47-9585baa70caa/SDN.XML?X-Amz-Expires=3600', + 'https://wc2h-sls-prod-public-published.s3.us-gov-west-1.amazonaws.com/exports/SDN.XML', + ]) { + assert.equal(isTrustedTwinRedirectUrl('ofac-sdn', ofacSourceUrl, { finalUrl: goodS3 }), true, `good S3 must pass: ${goodS3}`); + assert.equal(isTwinRedirectedToErrorPage(ofacSourceUrl, { finalUrl: goodS3 }), false); + const okScrape = await executeScrapeCall({ + payload: { url: ofacSourceUrl, discoverLlmsTxt: false, noCache: true }, + env: {}, + executeHubFetch: async (_t, body) => { + const req = (JSON.parse(body) as { requests: Array<{ id: string }> }).requests[0]!; + return { + status: 200, + via: 'hub:overflow', + bodyText: JSON.stringify({ + results: [{ id: req.id, url: ofacSourceUrl, finalUrl: goodS3, outcome: 'ok', status: 200, contentType: 'application/xml', body: ofacFx.mockPayload }], + }), + }; + }, + }); + assert.equal(okScrape.body.contentState, 'active', `good S3 scrape must stay active: ${goodS3}`); + } + + const untrustedRedirects = [ + { + name: 'nested /exports/error/SDN.XML', + finalUrl: 'https://wc2h-sls-prod-public-published.s3.us-gov-west-1.amazonaws.com/exports/error/SDN.XML', + contentType: 'application/xml', + body: ofacFx.mockPayload, + }, + { + name: 'nested /Published/error/SDN.XML', + finalUrl: 'https://wc2h-sls-prod-public-published.s3.us-gov-west-1.amazonaws.com/Published/error/SDN.XML', + contentType: 'application/xml', + body: ofacFx.mockPayload, + }, + { + name: 'nested /Published/error_page/SDN.XML', + finalUrl: 'https://wc2h-sls-prod-public-published.s3.us-gov-west-1.amazonaws.com/Published/error_page/SDN.XML', + contentType: 'application/xml', + body: ofacFx.mockPayload, + }, + { + name: 'nested /Published/error-page/SDN.XML', + finalUrl: 'https://wc2h-sls-prod-public-published.s3.us-gov-west-1.amazonaws.com/Published/error-page/SDN.XML', + contentType: 'application/xml', + body: ofacFx.mockPayload, + }, + { + name: 'nested /Published/maintenance/SDN.XML', + finalUrl: 'https://wc2h-sls-prod-public-published.s3.us-gov-west-1.amazonaws.com/Published/maintenance/SDN.XML', + contentType: 'application/xml', + body: ofacFx.mockPayload, + }, + { + name: 'arbitrary S3 bucket', + finalUrl: 'https://evil-bucket.s3.us-gov-west-1.amazonaws.com/Published/Current/SDN.XML', + contentType: 'application/xml', + body: ofacFx.mockPayload, + }, + { + name: 'wrong S3 region', + finalUrl: 'https://wc2h-sls-prod-public-published.s3.amazonaws.com/Published/Current/SDN.XML', + contentType: 'application/xml', + body: ofacFx.mockPayload, + }, + { + name: 'non-XML notice.html on S3 host', + finalUrl: 'https://wc2h-sls-prod-public-published.s3.us-gov-west-1.amazonaws.com/Published/Current/notice.html', + contentType: 'text/html', + body: `Notice

OFAC Notice

${'Please download the latest list from our portal. '.repeat(20)}

`, + }, + ]; + for (const tc of untrustedRedirects) { + assert.equal( + isTrustedTwinRedirectUrl('ofac-sdn', ofacSourceUrl, { finalUrl: tc.finalUrl }), + false, + `${tc.name} must fail isTrustedTwinRedirectUrl`, + ); + let scrapeFetchCount = 0; + const scRes = await executeScrapeCall({ + payload: { url: ofacSourceUrl, discoverLlmsTxt: false, noCache: true }, + env: {}, + executeHubFetch: async (_t, body) => { + scrapeFetchCount += 1; + const req = (JSON.parse(body) as { requests: Array<{ id: string }> }).requests[0]!; + return { + status: 200, + via: 'hub:overflow', + bodyText: JSON.stringify({ + results: [{ id: req.id, url: ofacSourceUrl, finalUrl: tc.finalUrl, outcome: 'ok', status: 200, contentType: tc.contentType, body: tc.body }], + }), + }; + }, + }); + assert.equal(scrapeFetchCount, 1, `${tc.name}: scrape must fail closed without second-hop fallthrough`); + assert.notEqual(scRes.body.contentState, 'active', `${tc.name}: scrape contentState must not be active`); + assert.equal(scRes.body.markdown ?? '', '', `${tc.name}: scrape must not leak untrusted body`); + + let extractFetchCount = 0; + const exRes = await executeExtractCall({ + payload: { urls: [ofacSourceUrl], noCache: true }, + env: {}, + executeHubFetch: async (_t, body) => { + extractFetchCount += 1; + const req = (JSON.parse(body) as { requests: Array<{ id: string }> }).requests[0]!; + return { + status: 200, + via: 'hub:overflow', + bodyText: JSON.stringify({ + results: [{ id: req.id, url: ofacSourceUrl, finalUrl: tc.finalUrl, outcome: 'ok', status: 200, contentType: tc.contentType, body: tc.body }], + }), + }; + }, + }); + assert.equal(extractFetchCount, 1, `${tc.name}: extract must fail closed without retry fallthrough`); + const exItem = (exRes.body.results as Array<{ contentState?: string; markdown?: string }>)[0]!; + assert.notEqual(exItem.contentState, 'active', `${tc.name}: extract contentState must not be active`); + assert.equal(exItem.markdown ?? '', '', `${tc.name}: extract must not leak untrusted body`); + } + + // 2. P2: URLSearchParams (! ' ( ) *) and lowercase %xx secret scrubbing in scrubSecretFromText & HTTP 502 + const uspSecret = "sec!ret'with(parens)*99"; + const uspEncoded = new URLSearchParams([['k', uspSecret]]).toString().slice(2); + const uspLower = uspEncoded.replace(/%[0-9A-F]{2}/g, (m) => m.toLowerCase()); + assert.equal( + scrubSecretFromText(`Upstream query param failed: val=${uspEncoded} lower=${uspLower}`, [uspSecret]).includes('sec%21ret'), + false, + ); + const plusLowerSecret = 'sec+ret/with space=99&token'; + const plusLowerEnc = encodeURIComponent(plusLowerSecret).replace(/%[0-9A-F]{2}/g, (m) => m.toLowerCase()); + assert.equal(scrubSecretFromText(`Upstream error val=${plusLowerEnc}`, [plusLowerSecret]).includes('%2b'), false); + + const err502UspRes = await executeScrapeCall({ + payload: { url: 'https://marketplace.api.healthcare.gov/api/v1/plans/search', discoverLlmsTxt: false, noCache: true }, + env: { + HEALTHCARE_GOV_API_KEY: uspSecret, + SAFE_PUBLIC_FETCH: (async (input: RequestInfo | URL) => { + const u = reqUrl(input); + if (u.pathname === '/robots.txt') return new Response('User-agent: *\nAllow: /\n', { status: 200 }); + throw new Error(`Upstream failed on param value=${uspEncoded} and lower=${uspLower}`); + }) as typeof fetch, + } as never, + executeHubFetch: async () => { + throw new Error('must use fetchWithOfficialApiKey'); + }, + }); + assert.equal(err502UspRes.status, 502); + const err502UspStr = JSON.stringify(err502UspRes.body); + assert.equal(err502UspStr.includes(uspSecret), false); + assert.equal(err502UspStr.includes(uspEncoded), false); + assert.equal(err502UspStr.includes(uspLower), false); + + // 2b. Mixed-case %xx escapes (e.g. sec%2bret%2Fwith+space%3d99%26token) redacted across redactSecretsInBody, scrubSecretFromText, fetchWithOfficialApiKey, and HTTP 502 + const mixedCaseEncoded = 'sec%2bret%2Fwith+space%3d99%26token'; + const nonMatchingCase = 'SEC%2bret%2Fwith+space%3d99%26token'; + assert.equal( + redactSecretsInBody(`val=${mixedCaseEncoded} keep=${nonMatchingCase}`, [plusLowerSecret]), + `val=[redacted] keep=${nonMatchingCase}`, + ); + assert.equal( + scrubSecretFromText(`Upstream mixed val=${mixedCaseEncoded}`, [plusLowerSecret]), + 'Upstream mixed val=[redacted]', + ); + const mixedFetchRes = await fetchWithOfficialApiKey({ + url: 'https://api.va.gov/services/va_facilities/v1/facilities?state=TX', + apiKey: plusLowerSecret, + injection: { kind: 'header', name: 'apikey' }, + fetchFn: async (input) => { + const u = reqUrl(input); + if (u.pathname === '/robots.txt') return new Response('User-agent: *\nAllow: /\n', { status: 200 }); + return new Response(JSON.stringify({ echoed: mixedCaseEncoded, ok: true }), { + status: 200, + headers: { 'content-type': 'application/json' }, + }); + }, + }); + assert.equal(mixedFetchRes.ok, true); + if (mixedFetchRes.ok) { + assert.equal(mixedFetchRes.body.includes(mixedCaseEncoded), false); + assert.ok(mixedFetchRes.body.includes('[redacted]')); + } + const err502MixedRes = await executeScrapeCall({ + payload: { url: 'https://marketplace.api.healthcare.gov/api/v1/plans/search', discoverLlmsTxt: false, noCache: true }, + env: { + HEALTHCARE_GOV_API_KEY: plusLowerSecret, + SAFE_PUBLIC_FETCH: (async (input: RequestInfo | URL) => { + const u = reqUrl(input); + if (u.pathname === '/robots.txt') return new Response('User-agent: *\nAllow: /\n', { status: 200 }); + throw new Error(`Upstream failed on mixed-case key=${mixedCaseEncoded}`); + }) as typeof fetch, + } as never, + executeHubFetch: async () => { + throw new Error('must use fetchWithOfficialApiKey'); + }, + }); + assert.equal(err502MixedRes.status, 502); + const err502MixedStr = JSON.stringify(err502MixedRes.body); + assert.equal(err502MixedStr.includes(plusLowerSecret), false); + assert.equal(err502MixedStr.includes(mixedCaseEncoded), false); + assert.ok(err502MixedStr.includes('[redacted]')); + + // 3. Minor edge hardening: attribute-first
(<75ms), minimal var dd= on bis.gov, BOM empty + const attrShellHtml = (title: string) => + `${title}
`; + for (const targetUrl of ['https://www.nlrb.gov/case/01-CA-123456', 'https://example.com/page']) { + const t0 = performance.now(); + const res = postExtractHtml(attrShellHtml('App'), targetUrl, ''); + const dt = performance.now() - t0; + assert.equal(res, null, `attribute-first CSR shell on ${targetUrl} must return null`); + assert.ok(dt < 75, `attribute-first CSR shell on ${targetUrl} exceeded 75ms budget: ${dt.toFixed(2)}ms`); + } + const ddMinimalHtml = `BIS

Please enable JS and disable any ad blocker.

`; + assert.equal(postExtractHtml(ddMinimalHtml, 'https://www.bis.gov/entity-list', ''), null); + + const bomEmptySdn = `\uFEFF11/28/20260`; + const bomSdnScrape = await executeScrapeCall({ + payload: { url: ofacSourceUrl, discoverLlmsTxt: false, noCache: true }, + env: {}, + executeHubFetch: async (_t, body) => { + const req = (JSON.parse(body) as { requests: Array<{ id: string }> }).requests[0]!; + return { + status: 200, + via: 'hub:overflow', + bodyText: JSON.stringify({ + results: [{ id: req.id, url: ofacSourceUrl, outcome: 'ok', status: 200, contentType: 'application/xml', body: bomEmptySdn }], + }), + }; + }, + }); + assert.equal(bomSdnScrape.body.contentState, 'empty_shell'); +}); diff --git a/hub/test/wave3-b4-research-security-dev.test.ts b/hub/test/wave3-b4-research-security-dev.test.ts new file mode 100644 index 0000000..6f62b2f --- /dev/null +++ b/hub/test/wave3-b4-research-security-dev.test.ts @@ -0,0 +1,1013 @@ +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import test from 'node:test'; +import { resolveAdapterPolicyForUrl } from '../src/adapter-policy'; +import { + fetchWithOfficialApiKey, + redactSecretsInBody, + resolveOfficialApiProviderSpec, + resolveOfficialApiProviderSpecForUrl, + scrubSecretFromText, + sealUserApiKey, +} from '../src/api-keys'; +import { KNOWN_TELEMETRY_ADAPTER_IDS } from '../src/dev-telemetry'; +import { validateSingleErrorEvent } from '../../telemetry/src/index'; +import { DECLARATIVE_SITE_ADAPTERS } from '../src/extractors/declarative'; +import { resolveSiteExtractorTwin } from '../src/extractors/registry'; +import { postExtractHtml } from './post-fetch-wasm'; +import { RequestTracer } from '../src/otel'; +import { resetOverflowRobotsCacheForTests } from '../src/overflow'; +import { + executeScrapeCall, + extractHtmlDocument, + isTrustedTwinRedirectUrl, + isTwinRedirectedToErrorPage, +} from '../src/scrape'; +import { executeExtractCall } from '../src/search-index'; +import { resetIsolateBudgetForTests } from '../src/wasm-bridge'; +import { assertFastAsync, assertFastUnscaledSync } from './perf-budget'; + +const WAVE3_B4_CAT_L_IDS = [ + 'semantic-scholar', + 'unpaywall', + 'core-ac', + 'orcid', + 'ror', + 'dblp', + 'biorxiv-medrxiv', + 'nasa-ads', + 'nih-reporter', + 'nsf-awards', + 'doe-osti', + 'research-repo-pack', + 'datacite', + 'ssrn-nber', +] as const; + +const WAVE3_B4_CAT_M_IDS = [ + 'cisa-kev', + 'first-epss', + 'mitre-attack', + 'mitre-cwe-capec', + 'cve-org', + 'cisa-advisories-ics', + 'vendor-csaf', + 'security-txt', + 'exploit-db', + 'certificate-transparency', + 'rdap', + 'bgp-asn', +] as const; + +const WAVE3_B4_CAT_N_IDS = [ + 'bitbucket-cloud', + 'sourceforge-launchpad', + 'gerrit', + 'bugzilla', + 'jira-public', + 'wordpress-org-plugins', + 'vscode-open-vsx', + 'browser-addons-amo-cws', + 'artifact-hub', + 'ansible-puppet-forge', + 'apis-guru', + 'endoflife-date', + 'web-compat-data', + 'bundlephobia-packagephobia', +] as const; + +const ALL_B4_IDS = [ + ...WAVE3_B4_CAT_L_IDS, + ...WAVE3_B4_CAT_M_IDS, + ...WAVE3_B4_CAT_N_IDS, +] as const; + +interface B4Fixture { + adapterId: string; + mode: 'twin' | 'html'; + inputUrl: string; + expectedFetchUrl?: string; + mockPayload: string; + expectTitleIncludes?: string; + expectMarkdownIncludes: string[]; + negativeCases: Array<{ + name: string; + status?: number; + inputUrl?: string; + finalUrl?: string; + payload: string; + }>; +} + +const noopHtmlToMd = () => ({ markdown: '', links: [] as string[] }); + +function reqUrl(input: RequestInfo | URL): URL { + return new URL(typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url); +} + +test('Wave 3 B4 Integration: All 40 adapter IDs registered, telemetry aligned, zero Rule 7 additions', () => { + assert.equal(ALL_B4_IDS.length, 40, 'Batch B4 must cover all 40 adapters (#301-#340)'); + const registered = new Map(DECLARATIVE_SITE_ADAPTERS.map((a) => [a.id, a])); + + for (const id of ALL_B4_IDS) { + const adapter = registered.get(id); + assert.ok(adapter, `Missing DECLARATIVE_SITE_ADAPTERS entry: ${id}`); + assert.notEqual(adapter.authMode, 'detect-only', `${id} must never be detect-only`); + assert.ok(KNOWN_TELEMETRY_ADAPTER_IDS.has(id), `Missing KNOWN_TELEMETRY_ADAPTER_IDS entry: ${id}`); + assert.equal( + validateSingleErrorEvent({ + schemaVersion: 1, + version: '2.8.32', + runtime: 'workers', + os: 'cloudflare', + arch: 'v8', + mode: 'hub', + spanName: 'edgefetch.scrape', + adapterId: id, + wafVendor: '', + httpStatus: 500, + errorClass: 'timeout', + }).ok, + true, + `Missing telemetry/src/index.ts VALID_ADAPTER_IDS entry: ${id}`, + ); + assert.ok(adapter.exampleUrls.length >= 1, `${id} missing exampleUrls`); + } + + for (const id of WAVE3_B4_CAT_L_IDS) { + assert.equal(registered.get(id)?.category, 'research-health', `${id} must have category research-health`); + } + for (const id of [...WAVE3_B4_CAT_M_IDS, ...WAVE3_B4_CAT_N_IDS]) { + assert.equal(registered.get(id)?.category, 'developer', `${id} must have category developer`); + } + + // Rule 7: Zero additions to APPROVED_CROSS_DOMAIN_TWIN_HOSTS + const compileSrc = readFileSync(resolve('scripts', 'compile-manifests.mjs'), 'utf8'); + const crossBlock = compileSrc.slice( + compileSrc.indexOf('APPROVED_CROSS_DOMAIN_TWIN_HOSTS'), + compileSrc.indexOf('APPROVED_WILDCARD_DOMAIN_PATTERNS'), + ); + for (const id of ALL_B4_IDS) { + assert.equal(crossBlock.includes(`'${id}'`), false, `Rule 7 violation: ${id} in APPROVED_CROSS_DOMAIN_TWIN_HOSTS`); + } + for (const forbiddenHost of ['api.biorxiv.org', 'cveawg.mitre.org', 'api.osf.io']) { + assert.equal(crossBlock.includes(forbiddenHost), false, `Rule 7 violation: ${forbiddenHost} in APPROVED_CROSS_DOMAIN_TWIN_HOSTS`); + } + + const declGoSrc = readFileSync(resolve('..', 'internal', 'extract', 'declarative.go'), 'utf8'); + const goCrossMatch = /var approvedCrossDomainTwinHostsGo = map\[string\]map\[string\]bool\{([\s\S]*?)\n\}/.exec(declGoSrc); + assert.ok(goCrossMatch); + for (const id of ALL_B4_IDS) { + assert.equal(goCrossMatch[1]!.includes(`"${id}"`), false, `Rule 7 Go violation: ${id} in approvedCrossDomainTwinHostsGo`); + } +}); + +test('Wave 3 B4 Fixtures: All 40 golden + >=4 negative cases pass via formatTwin/HTML, executeScrapeCall, executeExtractCall & RequestTracer', async () => { + resetIsolateBudgetForTests(); + resetOverflowRobotsCacheForTests(); + + const keyedSecrets: Record = { + 'core-ac': 'secret_core_ac_api_key_9988776655', + 'nasa-ads': 'secret_nasa_ads_api_key_9988776655', + }; + + for (const slug of ALL_B4_IDS) { + const fx = JSON.parse(readFileSync(resolve('test', 'fixtures', 'adapters', `${slug}.json`), 'utf8')) as B4Fixture; + assert.equal(fx.adapterId, slug); + assert.ok(fx.negativeCases.length >= 4, `${slug} must have >= 4 negativeCases`); + + const resolvedTwin = fx.mode === 'twin' ? resolveSiteExtractorTwin(fx.inputUrl) : null; + const isKeyTwin = Boolean(resolvedTwin && resolvedTwin.authMode === 'key'); + const fetchUrl = fx.expectedFetchUrl || fx.inputUrl; + const trimmedMock = fx.mockPayload.trimStart(); + const contentType = + fx.mode === 'html' + ? 'text/html' + : trimmedMock.startsWith(' 0, `${slug}: formatTwin returned null/empty`); + if (fx.expectTitleIncludes) { + assert.ok(out.title.includes(fx.expectTitleIncludes), `${slug}: title "${out.title}" missing "${fx.expectTitleIncludes}"`); + } + for (const needle of fx.expectMarkdownIncludes) { + assert.ok(out.markdown.includes(needle), `${slug}: markdown missing "${needle}"`); + } + if (out.records) { + assert.ok(out.records.length <= 25, `${slug}: records[] exceeds 25`); + } + } else { + const postOut = postExtractHtml(fx.mockPayload, fx.inputUrl, ''); + assert.ok(postOut && postOut.extractorId === slug && postOut.markdown.trim().length > 0, `${slug}: HTML extraction failed`); + if (fx.expectTitleIncludes && postOut.title) { + assert.ok(postOut.title.includes(fx.expectTitleIncludes), `${slug}: title "${postOut.title}" missing "${fx.expectTitleIncludes}"`); + } + for (const needle of fx.expectMarkdownIncludes) { + assert.ok(postOut.markdown.includes(needle), `${slug}: markdown missing "${needle}"`); + } + if (postOut.records) { + assert.ok(postOut.records.length <= 25, `${slug}: records[] exceeds 25`); + } + } + + const apiKeyVal = isKeyTwin ? keyedSecrets[slug] : undefined; + const makeKeyFetchEnv = (statusCode: number, bodyStr: string, ct: string) => ({ + SAFE_PUBLIC_FETCH: (async (input: RequestInfo | URL) => { + const u = reqUrl(input); + if (u.pathname === '/robots.txt') return new Response('User-agent: *\nAllow: /\n', { status: 200 }); + return new Response(bodyStr, { status: statusCode, headers: { 'content-type': ct } }); + }) as typeof fetch, + }); + const makeOverflowMock = (statusCode: number, bodyStr: string, ct: string, finalUrl?: string) => async (_t: unknown, body: string) => { + const req = (JSON.parse(body) as { requests: Array<{ id: string; url: string }> }).requests[0]!; + const outcome = + statusCode >= 200 && statusCode < 300 ? 'ok' : statusCode === 404 ? 'not_found' : statusCode === 410 ? 'gone' : 'error'; + return { + status: 200, + via: 'hub:overflow', + bodyText: JSON.stringify({ + results: [ + { + id: req.id, + url: req.url, + ...(finalUrl ? { finalUrl } : {}), + outcome, + status: statusCode, + contentType: ct, + body: bodyStr, + }, + ], + }), + }; + }; + + // Golden scrape + RequestTracer + const scTracer = RequestTracer.fromRequest(new Request('https://hub.example.com/v1/scrape')); + let scRes!: Awaited>; + await scTracer.withSpan('edgefetch.scrape', async () => { + scRes = await executeScrapeCall({ + payload: { + url: fx.inputUrl, + formats: ['markdown', 'records'], + discoverLlmsTxt: false, + noCache: true, + ...(apiKeyVal ? { apiKeys: { [slug]: apiKeyVal } } : {}), + }, + env: (isKeyTwin ? makeKeyFetchEnv(200, fx.mockPayload, contentType) : {}) as never, + tracer: scTracer, + executeHubFetch: isKeyTwin + ? async () => { + throw new Error(`${slug}: keyed twin must use fetchWithOfficialApiKey`); + } + : makeOverflowMock(200, fx.mockPayload, contentType, fx.mode === 'twin' ? fetchUrl : undefined), + }); + }); + assert.equal(scRes.status, 200, `${slug} scrape failed: ${JSON.stringify(scRes.body)}`); + assert.equal(scRes.body.extractorId, slug, `${slug} scrape extractorId mismatch`); + assert.equal(scRes.body.contentState, 'active', `${slug} scrape contentState must be active`); + assert.equal( + scTracer.getRecordedSpans().find((s) => s.name === 'edgefetch.scrape')?.attributes?.['edgefetch.adapter_id'], + slug, + `${slug} scrape span missing edgefetch.adapter_id`, + ); + + // Golden extract + RequestTracer + const exTracer = RequestTracer.fromRequest(new Request('https://hub.example.com/v1/extract')); + let exRes!: Awaited>; + await exTracer.withSpan('edgefetch.extract', async () => { + exRes = await executeExtractCall({ + payload: { + urls: [fx.inputUrl], + noCache: true, + ...(apiKeyVal ? { apiKeys: { [slug]: apiKeyVal } } : {}), + }, + env: (isKeyTwin ? makeKeyFetchEnv(200, fx.mockPayload, contentType) : {}) as never, + tracer: exTracer, + executeHubFetch: isKeyTwin + ? async () => { + throw new Error(`${slug}: keyed extract must use fetchWithOfficialApiKey`); + } + : makeOverflowMock(200, fx.mockPayload, contentType, fx.mode === 'twin' ? fetchUrl : undefined), + }); + }); + assert.equal(exRes.status, 200, `${slug} extract failed`); + assert.equal( + exTracer.getRecordedSpans().find((s) => s.name === 'edgefetch.extract')?.attributes?.['edgefetch.adapter_id'], + slug, + `${slug} extract span missing edgefetch.adapter_id`, + ); + + // >= 4 negative cases + for (const nc of fx.negativeCases) { + const ncUrl = nc.inputUrl || fx.inputUrl; + const ncStatus = nc.status ?? 200; + const ncTrim = nc.payload.trimStart(); + const ncCt = ncTrim.startsWith('<') ? 'text/html' : ncTrim.startsWith('{') || ncTrim.startsWith('[') ? 'application/json' : 'text/plain'; + const ncTwin = resolveSiteExtractorTwin(ncUrl); + + if (nc.finalUrl && nc.finalUrl !== ncUrl) { + if (fx.mode === 'twin') { + assert.equal( + isTrustedTwinRedirectUrl(slug, fetchUrl, { finalUrl: nc.finalUrl }), + false, + `${slug}:${nc.name} redirect to ${nc.finalUrl} must be rejected`, + ); + } else { + const isErrRedir = isTwinRedirectedToErrorPage(ncUrl, { finalUrl: nc.finalUrl }); + const negHtml = postExtractHtml(nc.payload, nc.finalUrl, ''); + assert.ok(isErrRedir || negHtml === null, `${slug}:${nc.name} error redirect must not extract`); + } + } else if (ncTwin && ncTwin.id === slug) { + const negTwin = ncTwin.formatTwin(nc.payload, ncUrl, noopHtmlToMd); + assert.equal(Boolean(negTwin && negTwin.markdown.trim()), false, `${slug}:${nc.name} formatTwin must return null/empty`); + } else { + const negHtml = postExtractHtml(nc.payload, ncUrl, ''); + assert.equal(negHtml, null, `${slug}:${nc.name} HTML extractor must return null`); + } + + const useKeyFetch = Boolean(ncTwin && ncTwin.id === slug && ncTwin.authMode === 'key' && !nc.finalUrl); + const scNeg = await executeScrapeCall({ + payload: { + url: ncUrl, + discoverLlmsTxt: false, + noCache: true, + ...(useKeyFetch && apiKeyVal ? { apiKeys: { [slug]: apiKeyVal } } : {}), + }, + env: (useKeyFetch ? makeKeyFetchEnv(ncStatus, nc.payload, ncCt) : {}) as never, + executeHubFetch: makeOverflowMock(ncStatus, nc.payload, ncCt, nc.finalUrl), + }); + assert.notEqual( + (scNeg.body as { contentState?: string }).contentState, + 'active', + `scrape ${slug}:${nc.name} must NEVER return contentState=active`, + ); + + const exNeg = await executeExtractCall({ + payload: { + urls: [ncUrl], + noCache: true, + ...(useKeyFetch && apiKeyVal ? { apiKeys: { [slug]: apiKeyVal } } : {}), + }, + env: (useKeyFetch ? makeKeyFetchEnv(ncStatus, nc.payload, ncCt) : {}) as never, + executeHubFetch: makeOverflowMock(ncStatus, nc.payload, ncCt, nc.finalUrl), + }); + const exFirst = ((exNeg.body as { results?: Array<{ contentState?: string }> }).results ?? [])[0]; + assert.notEqual( + exFirst?.contentState, + 'active', + `extract ${slug}:${nc.name} must NEVER return contentState=active`, + ); + } + } +}); + +test('Wave 3 B4 Cat L: Keyed APIs (core-ac/nasa-ads/semantic-scholar), secret redaction, Unpaywall email, Crawl-delay policy, DBLP Anubis, Rule 7 bioRxiv/medRxiv', async () => { + resetIsolateBudgetForTests(); + resetOverflowRobotsCacheForTests(); + + // 1. Keyed API providers: core-ac & nasa-ads require key (422 key_required), inject Bearer, redact secret; semantic-scholar has optional x-api-key spec + assert.equal(resolveOfficialApiProviderSpecForUrl('core-ac').envKeyName, 'CORE_AC_API_KEY'); + assert.deepEqual(resolveOfficialApiProviderSpecForUrl('core-ac').defaultInjection, { + kind: 'header', + name: 'Authorization', + prefix: 'Bearer ', + }); + assert.equal(resolveOfficialApiProviderSpecForUrl('nasa-ads').envKeyName, 'NASA_ADS_API_KEY'); + assert.deepEqual(resolveOfficialApiProviderSpecForUrl('nasa-ads').defaultInjection, { + kind: 'header', + name: 'Authorization', + prefix: 'Bearer ', + }); + assert.equal(resolveOfficialApiProviderSpec('semantic-scholar').envKeyName, 'SEMANTIC_SCHOLAR_API_KEY'); + assert.deepEqual(resolveOfficialApiProviderSpec('semantic-scholar').defaultInjection, { + kind: 'header', + name: 'x-api-key', + }); + + const core422 = await executeScrapeCall({ + payload: { url: 'https://api.core.ac.uk/v3/works/11689643', discoverLlmsTxt: false, noCache: true }, + env: {}, + executeHubFetch: async () => { + throw new Error('core-ac without key must return 422 key_required'); + }, + }); + assert.equal(core422.status, 422); + assert.equal(core422.body.error, 'key_required'); + + const coreSecret = 'core_bearer_secret+with space/9988'; + const coreScrape = await executeScrapeCall({ + payload: { url: 'https://api.core.ac.uk/v3/works/11689643', discoverLlmsTxt: false, noCache: true }, + env: { + CORE_AC_API_KEY: coreSecret, + SAFE_PUBLIC_FETCH: (async (input: RequestInfo | URL, init?: RequestInit) => { + const u = reqUrl(input); + if (u.pathname === '/robots.txt') return new Response('User-agent: *\nAllow: /\n', { status: 200 }); + assert.equal(new Headers(init?.headers).get('authorization'), `Bearer ${coreSecret}`); + return new Response( + JSON.stringify({ + id: 11689643, + title: 'Solar Energy Conversion Systems', + doi: '10.1016/j.solener.2020.01.001', + yearPublished: 2020, + echoRaw: coreSecret, + echoEnc: encodeURIComponent(coreSecret), + echoPlus: encodeURIComponent(coreSecret).replace(/%20/g, '+'), + authors: [{ name: 'Elena Vance' }], + abstract: `Grid study token=${coreSecret}`, + }), + { status: 200, headers: { 'content-type': 'application/json' } }, + ); + }) as typeof fetch, + } as never, + executeHubFetch: async () => { + throw new Error('core-ac must use fetchWithOfficialApiKey'); + }, + }); + assert.equal(coreScrape.status, 200); + assert.equal(coreScrape.body.extractorId, 'core-ac'); + const coreSerialized = JSON.stringify(coreScrape.body); + assert.equal(coreSerialized.includes(coreSecret), false); + assert.equal(coreSerialized.includes(encodeURIComponent(coreSecret)), false); + assert.equal(coreSerialized.includes(encodeURIComponent(coreSecret).replace(/%20/g, '+')), false); + + const ads422 = await executeScrapeCall({ + payload: { url: 'https://api.adsabs.harvard.edu/v1/search/query?q=bibcode:2017arXiv170603762V', discoverLlmsTxt: false, noCache: true }, + env: {}, + executeHubFetch: async () => { + throw new Error('nasa-ads without key must return 422 key_required'); + }, + }); + assert.equal(ads422.status, 422); + assert.equal(ads422.body.error, 'key_required'); + + const adsSecret = 'nasa_ads_bearer_secret_1234567890'; + const adsErr502 = await executeScrapeCall({ + payload: { url: 'https://api.adsabs.harvard.edu/v1/search/query?q=bibcode:2017arXiv170603762V', discoverLlmsTxt: false, noCache: true }, + env: { + NASA_ADS_API_KEY: adsSecret, + SAFE_PUBLIC_FETCH: (async (input: RequestInfo | URL) => { + const u = reqUrl(input); + if (u.pathname === '/robots.txt') return new Response('User-agent: *\nAllow: /\n', { status: 200 }); + throw new Error(`Upstream failed with token=${encodeURIComponent(adsSecret)}`); + }) as typeof fetch, + } as never, + executeHubFetch: async () => { + throw new Error('nasa-ads must use fetchWithOfficialApiKey'); + }, + }); + assert.equal(adsErr502.status, 502); + assert.equal(JSON.stringify(adsErr502.body).includes(adsSecret), false); + + // makeKeyHint (< 16 -> ****) & redactSecretsInBody / scrubSecretFromText + const masterKey = 'vault-master-key-wave3-b4-integration-0123456789'; + const shortCore = await sealUserApiKey({ vaultMasterKey: masterKey, userId: 'u1', provider: 'core-ac', apiKey: 'short-15-chars!' }); + assert.equal(shortCore.ok, true); + if (shortCore.ok) assert.equal(shortCore.keyHint, '****'); + const longAds = await sealUserApiKey({ vaultMasterKey: masterKey, userId: 'u1', provider: 'nasa-ads', apiKey: 'long-enough-16ch' }); + assert.equal(longAds.ok, true); + if (longAds.ok) assert.equal(longAds.keyHint, '...16ch'); + + const directFetch = await fetchWithOfficialApiKey({ + url: 'https://api.adsabs.harvard.edu/v1/search/query?q=test', + apiKey: adsSecret, + injection: { kind: 'header', name: 'Authorization', prefix: 'Bearer ' }, + fetchFn: async (input) => { + const u = reqUrl(input); + if (u.pathname === '/robots.txt') return new Response('User-agent: *\nAllow: /\n', { status: 200 }); + return new Response(JSON.stringify({ echoed: adsSecret }), { status: 200, headers: { 'content-type': 'application/json' } }); + }, + }); + assert.equal(directFetch.ok, true); + if (directFetch.ok) assert.equal(directFetch.body.includes(adsSecret), false); + assert.equal(redactSecretsInBody(`val=${encodeURIComponent('k+1 2')}`, ['k+1 2']), 'val=[redacted]'); + assert.equal(scrubSecretFromText(`err=${encodeURIComponent('k+1 2')}`, ['k+1 2']), 'err=[redacted]'); + + // 2. #302 unpaywall: unconditionally enforces ?email=bot@edgefetch.dev (even if caller passes another email) + const unpaywallNoEmail = resolveSiteExtractorTwin('https://api.unpaywall.org/v2/10.1038/s41586-021-03819-2'); + assert.ok(unpaywallNoEmail && unpaywallNoEmail.id === 'unpaywall'); + assert.equal(new URL(unpaywallNoEmail.fetchUrl).searchParams.get('email'), 'bot@edgefetch.dev'); + + const unpaywallCallerEmail = resolveSiteExtractorTwin('https://api.unpaywall.org/v2/10.1038/s41586-021-03819-2?email=caller@example.com'); + assert.ok(unpaywallCallerEmail && unpaywallCallerEmail.id === 'unpaywall'); + assert.equal(new URL(unpaywallCallerEmail.fetchUrl).searchParams.get('email'), 'bot@edgefetch.dev'); + assert.equal(unpaywallCallerEmail.fetchUrl.includes('caller@example.com'), false); + + // 3. Per-host Crawl-delay policy defaults in internal/extract/policy.go via WASM + const policyExpectations = [ + { url: 'https://dblp.org/search/publ/api?q=llm', id: 'dblp', minIntervalMs: 4000, maxConcurrent: 1, strictRobots: true }, + { url: 'https://www.medrxiv.org/content/10.1101/2020.05.28.20116129v1', id: 'biorxiv-medrxiv', minIntervalMs: 7000, maxConcurrent: 1, strictRobots: true }, + { url: 'https://zenodo.org/records/24485086', id: 'research-repo-pack', minIntervalMs: 10000, maxConcurrent: 1, strictRobots: true }, + { url: 'https://osf.io/abcde/', id: 'research-repo-pack', minIntervalMs: 10000, maxConcurrent: 1, strictRobots: true }, + { url: 'https://datadryad.org/dataset/doi:10.5061/dryad.7rh4625', id: 'research-repo-pack', minIntervalMs: 5000, maxConcurrent: 1, strictRobots: true }, + { url: 'https://papers.ssrn.com/sol3/papers.cfm?abstract_id=4131630', id: 'ssrn-nber', minIntervalMs: 5000, maxConcurrent: 1, strictRobots: true }, + ]; + for (const pe of policyExpectations) { + const pol = resolveAdapterPolicyForUrl(pe.url); + assert.equal(pol.adapterId, pe.id, `policy adapterId mismatch for ${pe.url}`); + assert.equal(pol.minIntervalMs, pe.minIntervalMs, `policy minIntervalMs mismatch for ${pe.url}`); + assert.equal(pol.maxConcurrent, pe.maxConcurrent, `policy maxConcurrent mismatch for ${pe.url}`); + assert.equal(pol.strictRobots, pe.strictRobots, `policy strictRobots mismatch for ${pe.url}`); + } + + // 4. #306 dblp Anubis PoW rejection + const anubisHtml = + 'Making sure you\'re not a bot!

Making sure you\'re not a bot!

'; + assert.equal( + postExtractHtml(anubisHtml, 'https://dblp.org/rec/conf/nips/VaswaniSPUJGKP17.html', ''), + null, + 'Anubis PoW HTML must be rejected', + ); + + // 5. #307 biorxiv-medrxiv Rule 7: www.medrxiv.org does NOT cross-domain twin to api.biorxiv.org + assert.equal(resolveSiteExtractorTwin('https://www.medrxiv.org/content/10.1101/2020.05.28.20116129v1'), null); + const medrxivHtml = + 'medRxiv Preprint

Clinical Trial Analysis

Detailed clinical trial study abstract and findings across cohorts.

'; + const medrxivOut = postExtractHtml( + medrxivHtml, + 'https://www.medrxiv.org/content/10.1101/2020.05.28.20116129v1', + '', + + ); + assert.ok(medrxivOut && medrxivOut.extractorId === 'biorxiv-medrxiv'); + assert.ok(medrxivOut.markdown.includes('Clinical Trial Analysis')); +}); + +test('Wave 3 B4 Cat M: CISA separation, CVE Rule 7 & Vue CSR guard, STIX/CSV bounded Range scanning, BGP.he >1MiB guard', async () => { + resetIsolateBudgetForTests(); + resetOverflowRobotsCacheForTests(); + + // 1. #315 cisa-kev vs #320 cisa-advisories-ics separation + assert.equal( + resolveSiteExtractorTwin('https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json')?.id, + 'cisa-kev', + ); + assert.equal( + resolveSiteExtractorTwin('https://www.cisa.gov/sites/default/files/csv/known_exploited_vulnerabilities.csv')?.id, + 'cisa-kev', + ); + assert.equal(resolveSiteExtractorTwin('https://www.cisa.gov/cybersecurity-advisories/ics-advisories.xml')?.id, 'cisa-advisories-ics'); + assert.equal(resolveSiteExtractorTwin('https://www.cisa.gov/cybersecurity-advisories/ics-advisories.xml')?.id !== 'cisa-kev', true); + + const kevCatalogOut = postExtractHtml( + 'Known Exploited Vulnerabilities Catalog | CISA

Known Exploited Vulnerabilities Catalog

CVE-2024-3094 Tukaani XZ Utils vulnerability.

', + 'https://www.cisa.gov/known-exploited-vulnerabilities-catalog', + '', + + ); + assert.equal(kevCatalogOut?.extractorId, 'cisa-kev'); + + const icsPageOut = postExtractHtml( + 'ICSA-26-328-01 | CISA

ICSA-26-328-01 Example PLC

CVE-2026-41001 affects industrial controllers.

', + 'https://www.cisa.gov/news-events/ics-advisories/icsa-26-328-01', + '', + + ); + assert.equal(icsPageOut?.extractorId, 'cisa-advisories-ics'); + + // 2. #319 cve-org Rule 7 (no cve.org -> cveawg.mitre.org twin) & Vue CSR shell rejection + assert.equal(resolveSiteExtractorTwin('https://www.cve.org/CVERecord?id=CVE-2024-3094'), null); + assert.equal(resolveSiteExtractorTwin('https://cveawg.mitre.org/api/cve/CVE-2024-3094')?.id, 'cve-org'); + assert.equal( + postExtractHtml( + 'CVE Record
', + 'https://www.cve.org/CVERecord?id=CVE-2024-3094', + '', + + ), + null, + ); + + // 3. #317 mitre-attack Range + bounded linear STIX bundle scanner + const stixUrl = 'https://raw.githubusercontent.com/mitre-attack/attack-stix-data/master/enterprise-attack/enterprise-attack.json'; + const stixTwin = resolveSiteExtractorTwin(stixUrl); + assert.ok(stixTwin && stixTwin.id === 'mitre-attack'); + assert.equal(stixTwin.headers?.Range, 'bytes=0-524287'); + assert.equal(stixTwin.maxBytes, 1048576); + const stixPrefixBody = + '{"type":"bundle","id":"bundle--1","objects":[{"type":"x-mitre-collection","name":"Enterprise ATT&CK","x_mitre_version":"16.1"},{"type":"attack-pattern","name":"PowerShell","external_references":[{"source_name":"mitre-attack","external_id":"T1059.001"}]},{"type":"attack-pattern","name":"TRUNCATED_AT_RANGE'; + const stixScrape = await executeScrapeCall({ + payload: { url: stixUrl, formats: ['markdown', 'records'], discoverLlmsTxt: false, noCache: true }, + env: {}, + executeHubFetch: async (_t, body) => { + const req = (JSON.parse(body) as { requests: Array<{ id: string }> }).requests[0]!; + return { + status: 200, + via: 'hub:overflow', + bodyText: JSON.stringify({ + results: [{ id: req.id, url: stixUrl, outcome: 'ok', status: 200, contentType: 'application/json', body: stixPrefixBody }], + }), + }; + }, + }); + assert.equal(stixScrape.status, 200); + assert.equal(stixScrape.body.extractorId, 'mitre-attack'); + assert.equal(stixScrape.body.contentState, 'active'); + assert.ok(String(stixScrape.body.markdown).includes('T1059.001')); + assert.equal(String(stixScrape.body.markdown).includes('TRUNCATED_AT_RANGE'), false); + + // 4. #323 exploit-db Range + bounded CSV scanner dropping partial trailing line + const edbCsvUrl = 'https://gitlab.com/exploit-database/exploitdb/-/raw/main/files_exploits.csv'; + const edbCsvTwin = resolveSiteExtractorTwin(edbCsvUrl); + assert.ok(edbCsvTwin && edbCsvTwin.id === 'exploit-db'); + assert.equal(edbCsvTwin.headers?.Range, 'bytes=0-2097151'); + assert.equal(edbCsvTwin.maxBytes, 2097152); + const edbCsvBody = + 'id,file,description,date_published,author,type,platform,port,date_added,date_updated,verified,codes,tags,aliases,screenshot_url,application_url,source_url\n' + + '51000,exploits/hardware/webapps/51000.py,"Example Router RCE",2022-08-01,Researcher,webapps,hardware,,2022-08-01,2022-08-01,1,CVE-2020-20277,,,,,\n' + + '51001,exploits/linux/local/51001.c,"TRUNCATED_CSV_TAIL'; + const edbFormatted = edbCsvTwin.formatTwin(edbCsvBody, edbCsvUrl, noopHtmlToMd); + assert.ok(edbFormatted && edbFormatted.markdown.includes('51000')); + assert.equal(edbFormatted.markdown.includes('TRUNCATED_CSV_TAIL'), false); + + // 5. #326 bgp-asn >1.5 MiB HTML sliced safely within < 75ms + const largeBgpHtml = `AS13335 Cloudflare, Inc. - bgp.he.net

AS13335 Cloudflare, Inc.

Origin AS13335 | 1.1.1.0/24
${''.repeat(130_000)}
`; + assert.ok(largeBgpHtml.length > 1_500_000); + const t0 = performance.now(); + const bgpOut = postExtractHtml(largeBgpHtml, 'https://bgp.he.net/AS13335', ''); + const bgpMs = performance.now() - t0; + assert.ok(bgpOut && bgpOut.extractorId === 'bgp-asn'); + assert.ok(bgpMs < 75, `bgp_he_html >1.5MiB took ${bgpMs.toFixed(1)}ms (>75ms)`); +}); + +test('Wave 3 B4 Cat N: Gerrit XSSI strip, CWS >262KB HTML scan, APIs.guru bounded prefix scan, no forbidden rewrites, Vercel checkpoint rejection', async () => { + resetIsolateBudgetForTests(); + resetOverflowRobotsCacheForTests(); + + // 1. #329 gerrit )]}'\n XSSI stripping end-to-end + const gerritUrl = 'https://review.opendev.org/changes/1010181/detail'; + const gerritScrape = await executeScrapeCall({ + payload: { url: gerritUrl, formats: ['markdown', 'records'], discoverLlmsTxt: false, noCache: true }, + env: {}, + executeHubFetch: async (_t, body) => { + const req = (JSON.parse(body) as { requests: Array<{ id: string }> }).requests[0]!; + return { + status: 200, + via: 'hub:overflow', + bodyText: JSON.stringify({ + results: [ + { + id: req.id, + url: gerritUrl, + outcome: 'ok', + status: 200, + contentType: 'application/json', + body: ")]}'\n{\"project\":\"openstack/nova\",\"branch\":\"master\",\"subject\":\"Fix scheduler race\",\"status\":\"MERGED\",\"_number\":1010181,\"insertions\":42,\"deletions\":7,\"updated\":\"2026-11-12 08:45:19.000000000\"}", + }, + ], + }), + }; + }, + }); + assert.equal(gerritScrape.status, 200); + assert.equal(gerritScrape.body.extractorId, 'gerrit'); + assert.equal(gerritScrape.body.contentState, 'active'); + assert.ok(String(gerritScrape.body.markdown).includes('openstack/nova')); + + // 2. #330 bugzilla, #331 jira-public, #332 wordpress-org-plugins, #336 ansible-puppet-forge do NOT rewrite HTML pages to disallowed APIs + assert.equal(resolveSiteExtractorTwin('https://bugzilla.mozilla.org/show_bug.cgi?id=1900000'), null); + assert.equal(resolveSiteExtractorTwin('https://issues.apache.org/jira/browse/KAFKA-17000'), null); + assert.equal(resolveSiteExtractorTwin('https://wordpress.org/plugins/woocommerce/'), null); + assert.equal(resolveSiteExtractorTwin('https://forge.puppet.com/modules/puppetlabs/stdlib'), null); + + // 3. #334 browser-addons-amo-cws: CWS HTML scan past 262 KB (> 350 KB offset) + const cwsUrl = 'https://chromewebstore.google.com/detail/ublock-origin/cjpalhdlnbpafiamejdnhcphjbkeiagm'; + const cwsPadding = ``; // ~364 KB > 262 KB + assert.ok(cwsPadding.length > 350_000); + const cwsDeepHtml = + `${cwsPadding}uBlock Origin - Chrome Web Store` + + `

uBlock Origin

An efficient wide-spectrum blocker for browsers.

30,000,000+ users
`; + const cwsScrape = await executeScrapeCall({ + payload: { url: cwsUrl, formats: ['markdown', 'records'], discoverLlmsTxt: false, noCache: true }, + env: {}, + executeHubFetch: async (_t, body) => { + const req = (JSON.parse(body) as { requests: Array<{ id: string }> }).requests[0]!; + return { + status: 200, + via: 'hub:overflow', + bodyText: JSON.stringify({ + results: [{ id: req.id, url: cwsUrl, outcome: 'ok', status: 200, contentType: 'text/html', body: cwsDeepHtml }], + }), + }; + }, + }); + assert.equal(cwsScrape.status, 200); + assert.equal(cwsScrape.body.extractorId, 'browser-addons-amo-cws'); + assert.equal(cwsScrape.body.contentState, 'active'); + assert.ok(String(cwsScrape.body.markdown).includes('uBlock Origin')); + + // 4. #337 apis-guru: Range-bounded list.json linear prefix scan omits truncated entry + const apisListUrl = 'https://api.apis.guru/v2/list.json'; + const apisListTwin = resolveSiteExtractorTwin(apisListUrl); + assert.ok(apisListTwin && apisListTwin.id === 'apis-guru'); + assert.equal(apisListTwin.headers?.Range, 'bytes=0-2097151'); + assert.equal(apisListTwin.maxBytes, 2097152); + const apisPrefixBody = + '{"github.com":{"preferred":"1.1.4","versions":{"1.1.4":{"info":{"title":"GitHub v3 REST API"},"swaggerUrl":"https://api.apis.guru/v2/specs/github.com/1.1.4/openapi.json"}}},"truncated.example.org":{"preferred":"1.0.0","versions":{"1.0.0":{"info":{"title":"TRUNCATED_AT_RANGE'; + const apisOut = apisListTwin.formatTwin(apisPrefixBody, apisListUrl, noopHtmlToMd); + assert.ok(apisOut && apisOut.markdown.includes('GitHub v3 REST API')); + assert.equal(apisOut.markdown.includes('TRUNCATED_AT_RANGE'), false); + + // 5. #340 bundlephobia-packagephobia: Vercel Security Checkpoint rejected cleanly + const pkgCheckpointHtml = + 'Vercel Security Checkpoint

We are verifying your browser...

'; + assert.equal( + postExtractHtml(pkgCheckpointHtml, 'https://packagephobia.com/result?p=lodash', ''), + null, + ); + const pkg429Scrape = await executeScrapeCall({ + payload: { url: 'https://packagephobia.com/result?p=lodash', discoverLlmsTxt: false, noCache: true }, + env: {}, + executeHubFetch: async (_t, body) => { + const req = (JSON.parse(body) as { requests: Array<{ id: string }> }).requests[0]!; + return { + status: 200, + via: 'hub:overflow', + bodyText: JSON.stringify({ + results: [{ id: req.id, url: 'https://packagephobia.com/result?p=lodash', outcome: 'ok', status: 429, contentType: 'text/html', body: pkgCheckpointHtml }], + }), + }; + }, + }); + assert.notEqual(pkg429Scrape.body.contentState, 'active'); +}); + +test('Wave 3 B4 Remediations: soft-404 headings, bgp.he.net >4MiB/3.29MiB, CWS 1.63MiB <75ms, KEV ?cve= miss, apis-guru 0-entry, bare cisa.gov, STIX order, ?EMAIL=', async () => { + resetIsolateBudgetForTests(); + resetOverflowRobotsCacheForTests(); + + const makeMock = (statusCode: number, bodyStr: string, ct: string, urlStr: string) => async (_t: unknown, reqBody: string) => { + const req = (JSON.parse(reqBody) as { requests: Array<{ id: string }> }).requests[0]!; + return { + status: 200, + via: 'hub:overflow', + bodyText: JSON.stringify({ + results: [{ id: req.id, url: urlStr, outcome: 'ok', status: statusCode, contentType: ct, body: bodyStr }], + }), + }; + }; + + // 1. [P0] Soft-404 headings (#332, #336, #333) + const soft404HeadingCases = [ + { + url: 'https://wordpress.org/plugins/missing-plugin/', + html: 'Plugin not found | WordPress.org

Plugin not found

', + }, + { + url: 'https://forge.puppet.com/modules/puppetlabs/nope', + html: 'Module not found | Puppet Forge

Module not found

', + }, + { + url: 'https://marketplace.visualstudio.com/items?itemName=missing.nope', + html: 'Extension not found | Visual Studio Marketplace

Extension not found

', + }, + ]; + for (const tc of soft404HeadingCases) { + const res = await executeScrapeCall({ + payload: { url: tc.url, discoverLlmsTxt: false, noCache: true }, + env: {}, + executeHubFetch: makeMock(200, tc.html, 'text/html', tc.url), + }); + assert.equal(res.status, 200); + assert.equal(res.body.contentState, 'soft_404', `${tc.url} must classify as soft_404`); + } + + // 2. [P1 + P2] #326 bgp-asn 4.5 MiB (>4 MiB) & 3.29 MiB pre-slice + <75ms latency + const bgpUrl = 'https://bgp.he.net/AS13335'; + const bgpRows = Array.from({ length: 25 }, (_, i) => `1.1.${i}.0/24Cloudflare, Inc.`).join(''); + const bgpHead = + `AS13335 Cloudflare, Inc. - bgp.he.net

AS13335 Cloudflare, Inc.

Origin AS13335 | Cloudflare, Inc. | RIR: ARIN
${bgpRows}
PrefixDescription
`; + const bgpTail = '
'; + const bgp45Mb = bgpHead + ''.repeat(184_000) + bgpTail; // ~4.60 MB > 4 MiB + const bgp33Mb = bgpHead + ''.repeat(138_000) + bgpTail; // ~3.45 MB (~3.29 MiB) + assert.ok(bgp45Mb.length > 4_400_000); + assert.ok(bgp33Mb.length > 3_300_000 && bgp33Mb.length < 4_194_304); + + const bgpApply45 = assertFastUnscaledSync('bgp.he.net 4.5MiB postExtractHtml', 75, () => { + const out = postExtractHtml(bgp45Mb, bgpUrl, ''); + assert.ok(out && out.extractorId === 'bgp-asn' && out.markdown.includes('AS13335')); + return out; + }); + assert.ok(bgpApply45.markdown.includes('AS13335')); + + for (const [label, html] of [ + ['4.5MiB', bgp45Mb], + ['3.29MiB', bgp33Mb], + ] as const) { + assertFastUnscaledSync(`bgp.he.net ${label} postExtractHtml`, 75, () => { + const out = postExtractHtml(html, bgpUrl, ''); + assert.ok(out && out.extractorId === 'bgp-asn' && out.markdown.includes('AS13335')); + return out; + }); + const lastRes = await assertFastAsync(`bgp.he.net ${label} executeScrapeCall`, 75, () => + executeScrapeCall({ + payload: { url: bgpUrl, formats: ['markdown', 'records'], discoverLlmsTxt: false, noCache: true }, + env: {}, + executeHubFetch: makeMock(200, html, 'text/html', bgpUrl), + }), + ); + assert.equal(lastRes.status, 200); + assert.equal(lastRes.body.extractorId, 'bgp-asn', `bgp.he.net ${label} must use bgp-asn`); + assert.equal(lastRes.body.contentState, 'active'); + assert.ok(String(lastRes.body.markdown).includes('AS13335')); + } + + const bgpEx45 = await executeExtractCall({ + payload: { urls: [bgpUrl], noCache: true }, + env: {}, + executeHubFetch: makeMock(200, bgp45Mb, 'text/html', bgpUrl), + }); + const bgpExItem = ((bgpEx45.body as { results?: Array<{ extractorId?: string; contentState?: string }> }).results ?? [])[0]; + assert.equal(bgpExItem?.extractorId, 'bgp-asn'); + assert.equal(bgpExItem?.contentState, 'active'); + + // 2b. [P1] #326 bgp.he.net Invalid AS soft-404 (180 B, 4.5 MiB, past-64KB) in both executeScrapeCall & executeExtractCall + unclosed '.repeat(184_000)}`; + const bgpInvalidPast64k = + `AS9999999 - bgp.he.net` + + `${''.repeat(3_500)}

Invalid AS

Invalid AS specified. Please enter a valid ASN.

` + + `${''.repeat(180_000)}`; + for (const [label, invalidHtml] of [ + ['180B', bgpInvalid180], + ['4.5MiB', bgpInvalid45], + ['past64KB', bgpInvalidPast64k], + ] as const) { + const invScrape = await executeScrapeCall({ + payload: { url: bgpInvalidUrl, formats: ['markdown', 'records'], discoverLlmsTxt: false, noCache: true }, + env: {}, + executeHubFetch: makeMock(200, invalidHtml, 'text/html', bgpInvalidUrl), + }); + assert.equal(invScrape.status, 200); + assert.equal(invScrape.body.contentState, 'soft_404', `bgp.he.net ${label} Invalid AS scrape must be soft_404`); + assert.equal(String(invScrape.body.markdown ?? '').includes('<!--'), false, `bgp.he.net ${label} must trim trailing unclosed '.repeat(48_000)}` + + `uBlock Origin - Chrome Web Store` + + `` + + `` + + `

uBlock Origin

30,000,000+ users
Version
1.61.2
` + + ``; + assert.ok(cws163Html.length >= 1_550_000); + let bestCwsApplyMs = Number.POSITIVE_INFINITY; + for (let i = 0; i < 5; i++) { + const t0 = performance.now(); + const out = postExtractHtml(cws163Html, cwsUrl, ''); + bestCwsApplyMs = Math.min(bestCwsApplyMs, performance.now() - t0); + assert.ok(out && out.extractorId === 'browser-addons-amo-cws' && out.markdown.includes('1.61.2')); + } + assert.ok(bestCwsApplyMs < 75, `CWS 1.63 MiB postExtractHtml best-of-5=${bestCwsApplyMs.toFixed(1)}ms (>75ms)`); + + let bestCwsExtractDocMs = Number.POSITIVE_INFINITY; + for (let i = 0; i < 5; i++) { + const t0 = performance.now(); + const doc = extractHtmlDocument(cws163Html, { baseUrl: cwsUrl }); + bestCwsExtractDocMs = Math.min(bestCwsExtractDocMs, performance.now() - t0); + assert.equal(doc.extractorId, 'browser-addons-amo-cws'); + assert.ok(doc.markdown.includes('1.61.2')); + } + assert.ok(bestCwsExtractDocMs < 75, `CWS 1.63 MiB extractHtmlDocument best-of-5=${bestCwsExtractDocMs.toFixed(1)}ms (>75ms)`); + + const cws163Res = await assertFastAsync('CWS 1.63 MiB <50-word executeScrapeCall', 75, () => + executeScrapeCall({ + payload: { url: cwsUrl, formats: ['markdown', 'records'], discoverLlmsTxt: false, noCache: true }, + env: {}, + executeHubFetch: makeMock(200, cws163Html, 'text/html', cwsUrl), + }), + ); + assert.equal(cws163Res.status, 200); + assert.equal(cws163Res.body.extractorId, 'browser-addons-amo-cws'); + assert.equal(cws163Res.body.contentState, 'active'); + assert.ok(String(cws163Res.body.markdown).includes('1.61.2')); + assert.equal((cws163Res.body.records as Array> | undefined)?.[0]?.version, '1.61.2'); + + const cwsNoiseVersionHtml = + `${''.repeat(12)}` + + `${''.repeat(48_000)}` + + `uBlock Origin - Chrome Web Store` + + `` + + `` + + `

uBlock Origin

30,000,000+ users
Version
1.61.2
` + + ``; + const cwsNoiseRes = await assertFastAsync('CWS 1.63 MiB 12-version-noise executeScrapeCall', 75, () => + executeScrapeCall({ + payload: { url: cwsUrl, formats: ['markdown', 'records'], discoverLlmsTxt: false, noCache: true }, + env: {}, + executeHubFetch: makeMock(200, cwsNoiseVersionHtml, 'text/html', cwsUrl), + }), + ); + assert.equal(cwsNoiseRes.status, 200); + assert.equal(cwsNoiseRes.body.extractorId, 'browser-addons-amo-cws'); + assert.equal(cwsNoiseRes.body.contentState, 'active'); + assert.equal((cwsNoiseRes.body.records as Array> | undefined)?.[0]?.version, '1.61.2'); + assert.ok(String(cwsNoiseRes.body.markdown).includes('1.61.2')); + + const cws900kSoft404 = + `${''.repeat(80_000)}Item not available - Chrome Web Store` + + `

This item is no longer available.

`; + const cwsSoft404Res = await executeScrapeCall({ + payload: { url: cwsUrl, discoverLlmsTxt: false, noCache: true }, + env: {}, + executeHubFetch: makeMock(200, cws900kSoft404, 'text/html', cwsUrl), + }); + assert.equal(cwsSoft404Res.body.contentState, 'soft_404'); + + // 4. [P1] #315 cisa-kev ?cve= miss must not leak raw catalog JSON as active + const kevMissUrl = 'https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json?cve=CVE-9999-99999'; + const kevCatalogJson = JSON.stringify({ + title: 'CISA KEV Catalog', + catalogVersion: '2026.11.28', + count: 2, + vulnerabilities: [ + { cveID: 'CVE-2024-3094', vendorProject: 'Tukaani', product: 'XZ Utils', vulnerabilityName: 'XZ Backdoor', dateAdded: '2024-04-01', dueDate: '2024-04-22' }, + { cveID: 'CVE-2024-21762', vendorProject: 'Fortinet', product: 'FortiOS', vulnerabilityName: 'SSL VPN', dateAdded: '2024-02-09', dueDate: '2024-02-16' }, + ], + }); + const kevMissRes = await executeScrapeCall({ + payload: { url: kevMissUrl, formats: ['markdown', 'records'], discoverLlmsTxt: false, noCache: true }, + env: {}, + executeHubFetch: makeMock(200, kevCatalogJson, 'application/json', kevMissUrl), + }); + assert.equal(kevMissRes.status, 200); + assert.equal(kevMissRes.body.extractorId, 'cisa-kev'); + assert.notEqual(kevMissRes.body.contentState, 'active'); + assert.ok(String(kevMissRes.body.markdown).length < 512); + assert.ok(String(kevMissRes.body.markdown).includes('No matching KEV entry found for CVE-9999-99999')); + + // 5. [P1] #337 apis-guru 0-complete-entry truncated list.json prefix must not return contentState=active + const apisListUrl = 'https://api.apis.guru/v2/list.json'; + const apisZeroPrefix = '{"onlypartial.com":{"preferred":"1.0.0","versions":{"1.0.0":{"info":{"title":"TRUNCATED'; + const apisZeroRes = await executeScrapeCall({ + payload: { url: apisListUrl, formats: ['markdown', 'records'], discoverLlmsTxt: false, noCache: true }, + env: {}, + executeHubFetch: makeMock(200, apisZeroPrefix, 'application/json', apisListUrl), + }); + assert.equal(apisZeroRes.status, 200); + assert.equal(apisZeroRes.body.extractorId, 'apis-guru'); + assert.equal(apisZeroRes.body.contentState, 'empty_shell'); + + // 6. [P1] #315 vs #320 bare cisa.gov routing + assert.equal(resolveSiteExtractorTwin('https://cisa.gov/cybersecurity-advisories/ics-advisories.xml')?.id, 'cisa-advisories-ics'); + assert.equal(resolveSiteExtractorTwin('https://cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json')?.id, 'cisa-kev'); + assert.equal(resolveSiteExtractorTwin('https://cisa.gov/sites/default/files/csv/known_exploited_vulnerabilities.csv')?.id, 'cisa-kev'); + const bareIcsHtmlRes = postExtractHtml( + 'ICSA-26-328-01 | CISA

ICSA-26-328-01 PLC

CVE-2026-41001 industrial advisory.

', + 'https://cisa.gov/news-events/ics-advisories/icsa-26-328-01', + '', + + ); + assert.equal(bareIcsHtmlRes?.extractorId, 'cisa-advisories-ics'); + const bareKevHtmlRes = postExtractHtml( + 'Known Exploited Vulnerabilities Catalog | CISA

Known Exploited Vulnerabilities Catalog

CVE-2024-3094.

', + 'https://cisa.gov/known-exploited-vulnerabilities-catalog', + '', + + ); + assert.equal(bareKevHtmlRes?.extractorId, 'cisa-kev'); + + // 7. [P2] #317 mitre-attack objects-before-bundle (> 4 KB) & #302 unpaywall uppercase ?EMAIL= + const stixUrl = 'https://raw.githubusercontent.com/mitre-attack/attack-stix-data/master/enterprise-attack/enterprise-attack.json'; + const stixObjectsFirst = + `{"objects":[{"type":"x-mitre-collection","name":"Enterprise ATT&CK","x_mitre_version":"16.1"},{"type":"attack-pattern","name":"PowerShell","description":"${'B'.repeat(5000)}","external_references":[{"source_name":"mitre-attack","external_id":"T1059.001"}]}],"id":"bundle--1","type":"bundle"}`; + const stixOfRes = await executeScrapeCall({ + payload: { url: stixUrl, formats: ['markdown', 'records'], discoverLlmsTxt: false, noCache: true }, + env: {}, + executeHubFetch: makeMock(200, stixObjectsFirst, 'application/json', stixUrl), + }); + assert.equal(stixOfRes.status, 200); + assert.equal(stixOfRes.body.extractorId, 'mitre-attack'); + assert.equal(stixOfRes.body.contentState, 'active'); + assert.ok(String(stixOfRes.body.markdown).includes('T1059.001')); + + const unpaywallUpper = resolveSiteExtractorTwin('https://api.unpaywall.org/v2/10.1038/s41586-021-03819-2?EMAIL=alice@example.com'); + assert.ok(unpaywallUpper && unpaywallUpper.id === 'unpaywall'); + assert.equal(unpaywallUpper.fetchUrl.toLowerCase().includes('alice'), false); + assert.equal(unpaywallUpper.fetchUrl.includes('EMAIL='), false); + assert.equal(new URL(unpaywallUpper.fetchUrl).searchParams.get('email'), 'bot@edgefetch.dev'); +}); diff --git a/hub/test/wave3-b5-cycling-resale.test.ts b/hub/test/wave3-b5-cycling-resale.test.ts new file mode 100644 index 0000000..ce29579 --- /dev/null +++ b/hub/test/wave3-b5-cycling-resale.test.ts @@ -0,0 +1,760 @@ +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import test from 'node:test'; +import { resolveAdapterPolicyForUrl } from '../src/adapter-policy'; +import { KNOWN_TELEMETRY_ADAPTER_IDS } from '../src/dev-telemetry'; +import { validateSingleErrorEvent } from '../../telemetry/src/index'; +import { DECLARATIVE_SITE_ADAPTERS } from '../src/extractors/declarative'; +import { resolveSiteExtractorTwin } from '../src/extractors/registry'; +import { postExtractHtml } from './post-fetch-wasm'; +import { checkUnboundedTwinEndpointGuard } from '../src/extractors/twin-companions'; +import { RequestTracer } from '../src/otel'; +import { resetOverflowRobotsCacheForTests } from '../src/overflow'; +import { + executeScrapeCall, + isTrustedTwinRedirectUrl, + isTwinRedirectedToErrorPage, +} from '../src/scrape'; +import { executeExtractCall } from '../src/search-index'; +import { callCoreWasm, resetIsolateBudgetForTests } from '../src/wasm-bridge'; +import { assertFastAsync, assertFastUnscaledSync } from './perf-budget'; + +const WAVE3_B5_CAT_O1_IDS = [ + 'fox-ridefox', + 'park-tool', + 'ifixit', + 'ebike-drive-systems', + 'specialized-turbo-support', + 'bicycle-tire-specs', + 'wheel-hub-specs', + 'bicycle-brake-docs', + 'suspension-cockpit-compat', +] as const; + +const WAVE3_B5_CAT_O2_IDS = [ + 'cargo-ebike-oems', + 'us-ebike-oems', + 'qbp-frame-brands', + 'mtb-geometry-brands', + 'geometrygeeks-99spokes', + 'sheldon-brown', + 'ul-product-iq', + 'e-bike-state-laws', + 'cpsc-ebike-incidents', +] as const; + +const WAVE3_B5_CAT_P_IDS = [ + 'reverb', + 'pinkbike-buysell', + 'used-bikes-shopify', + 'bicycle-blue-book', + 'back-market-swappa', + 'peer-resale-fashion', + 'local-classifieds-marketplaces', + 'creator-digital-stores', + 'chairish-1stdibs', +] as const; + +const ALL_B5_IDS = [ + ...WAVE3_B5_CAT_O1_IDS, + ...WAVE3_B5_CAT_O2_IDS, + ...WAVE3_B5_CAT_P_IDS, +] as const; + +interface B5Fixture { + adapterId: string; + mode: 'twin' | 'html'; + inputUrl: string; + expectedFetchUrl?: string; + mockPayload: string; + expectTitleIncludes?: string; + expectMarkdownIncludes: string[]; + negativeCases: Array<{ + name: string; + status?: number; + inputUrl?: string; + finalUrl?: string; + payload: string; + }>; +} + +const noopHtmlToMd = () => ({ markdown: '', links: [] as string[] }); + +const EXPECTED_CATEGORY_BY_ID: Record<(typeof ALL_B5_IDS)[number], string> = { + 'fox-ridefox': 'developer', + 'park-tool': 'developer', + ifixit: 'developer', + 'ebike-drive-systems': 'commerce-social', + 'specialized-turbo-support': 'developer', + 'bicycle-tire-specs': 'commerce-social', + 'wheel-hub-specs': 'commerce-social', + 'bicycle-brake-docs': 'commerce-social', + 'suspension-cockpit-compat': 'commerce-social', + 'cargo-ebike-oems': 'commerce-social', + 'us-ebike-oems': 'commerce-social', + 'qbp-frame-brands': 'commerce-social', + 'mtb-geometry-brands': 'commerce-social', + 'geometrygeeks-99spokes': 'commerce-social', + 'sheldon-brown': 'research-health', + 'ul-product-iq': 'public-records', + 'e-bike-state-laws': 'public-records', + 'cpsc-ebike-incidents': 'public-records', + reverb: 'commerce-social', + 'pinkbike-buysell': 'commerce-social', + 'used-bikes-shopify': 'commerce-social', + 'bicycle-blue-book': 'commerce-social', + 'back-market-swappa': 'commerce-social', + 'peer-resale-fashion': 'commerce-social', + 'local-classifieds-marketplaces': 'commerce-social', + 'creator-digital-stores': 'commerce-social', + 'chairish-1stdibs': 'commerce-social', +}; + +function makeOverflowMock(statusCode: number, bodyStr: string, ct: string, finalUrl?: string) { + return async (_t: unknown, body: string) => { + const req = (JSON.parse(body) as { requests: Array<{ id: string; url: string }> }).requests[0]!; + const outcome = + statusCode >= 200 && statusCode < 300 + ? 'ok' + : statusCode === 404 + ? 'not_found' + : statusCode === 410 + ? 'gone' + : statusCode === 403 + ? 'blocked' + : 'error'; + return { + status: 200, + via: 'hub:overflow', + bodyText: JSON.stringify({ + results: [ + { + id: req.id, + url: req.url, + ...(finalUrl ? { finalUrl } : {}), + outcome, + status: statusCode, + contentType: ct, + body: bodyStr, + }, + ], + }), + }; + }; +} + +test('Wave 3 B5 Integration: All 27 adapter IDs registered, telemetry aligned, zero Rule 7 additions & Rule 9 clean', () => { + assert.equal(ALL_B5_IDS.length, 27, 'Batch B5 must cover all 27 adapters (#341-#367)'); + const registered = new Map(DECLARATIVE_SITE_ADAPTERS.map((a) => [a.id, a])); + + for (const id of ALL_B5_IDS) { + const adapter = registered.get(id); + assert.ok(adapter, `Missing DECLARATIVE_SITE_ADAPTERS entry: ${id}`); + assert.notEqual(adapter.authMode, 'detect-only', `${id} must never be detect-only`); + assert.equal(adapter.category, EXPECTED_CATEGORY_BY_ID[id], `${id} category mismatch`); + assert.ok(KNOWN_TELEMETRY_ADAPTER_IDS.has(id), `Missing KNOWN_TELEMETRY_ADAPTER_IDS entry: ${id}`); + assert.equal( + validateSingleErrorEvent({ + schemaVersion: 1, + version: '2.8.32', + runtime: 'workers', + os: 'cloudflare', + arch: 'v8', + mode: 'hub', + spanName: 'edgefetch.scrape', + adapterId: id, + wafVendor: '', + httpStatus: 500, + errorClass: 'timeout', + }).ok, + true, + `Missing telemetry/src/index.ts VALID_ADAPTER_IDS entry: ${id}`, + ); + assert.ok(adapter.exampleUrls.length >= 1, `${id} missing exampleUrls`); + } + + // Rule 7: Zero additions to APPROVED_CROSS_DOMAIN_TWIN_HOSTS (TS or Go) + const compileSrc = readFileSync(resolve('scripts', 'compile-manifests.mjs'), 'utf8'); + const crossBlock = compileSrc.slice( + compileSrc.indexOf('APPROVED_CROSS_DOMAIN_TWIN_HOSTS'), + compileSrc.indexOf('APPROVED_WILDCARD_DOMAIN_PATTERNS'), + ); + for (const id of ALL_B5_IDS) { + assert.equal(crossBlock.includes(`'${id}'`), false, `Rule 7 violation: ${id} in APPROVED_CROSS_DOMAIN_TWIN_HOSTS`); + } + for (const forbiddenHost of ['api.reverb.com', 'www.ifixit.com', 'upway.co']) { + assert.equal(crossBlock.includes(forbiddenHost), false, `Rule 7 violation: ${forbiddenHost} in APPROVED_CROSS_DOMAIN_TWIN_HOSTS`); + } + + const declGoSrc = readFileSync(resolve('..', 'internal', 'extract', 'declarative.go'), 'utf8'); + const goCrossMatch = /var approvedCrossDomainTwinHostsGo = map\[string\]map\[string\]bool\{([\s\S]*?)\n\}/.exec(declGoSrc); + assert.ok(goCrossMatch); + for (const id of ALL_B5_IDS) { + assert.equal(goCrossMatch[1]!.includes(`"${id}"`), false, `Rule 7 Go violation: ${id} in approvedCrossDomainTwinHostsGo`); + } + + // Rule 9: Zero private / internal names across all 27 B5 manifests, fixtures, and Go sources/tests + const privateBrandRe = new RegExp(Buffer.from('c2hlcGhlcmR8c2hvcGRhd2d8anVpY2VkLj93aGVlbHM=', 'base64').toString('utf8'), 'i'); + for (const id of ALL_B5_IDS) { + const yamlText = readFileSync(resolve('..', 'internal', 'extract', 'manifests', `${id}.yaml`), 'utf8'); + assert.equal(privateBrandRe.test(yamlText), false, `Rule 9 violation in ${id}.yaml`); + const fxText = readFileSync(resolve('test', 'fixtures', 'adapters', `${id}.json`), 'utf8'); + assert.equal(privateBrandRe.test(fxText), false, `Rule 9 violation in ${id}.json`); + } + for (const goRel of [ + 'wave3_cycling_components.go', + 'wave3_cycling_components_test.go', + 'wave3_cycling_oems.go', + 'wave3_cycling_oems_test.go', + 'wave3_resale.go', + 'wave3_resale_test.go', + ]) { + const goText = readFileSync(resolve('..', 'internal', 'extract', goRel), 'utf8'); + assert.equal(privateBrandRe.test(goText), false, `Rule 9 violation in ${goRel}`); + } +}); + +test('Wave 3 B5 Fixtures: All 27 golden + >=4 negative cases pass via formatTwin/HTML, executeScrapeCall, executeExtractCall & RequestTracer', async () => { + resetIsolateBudgetForTests(); + resetOverflowRobotsCacheForTests(); + + for (const slug of ALL_B5_IDS) { + const fx = JSON.parse(readFileSync(resolve('test', 'fixtures', 'adapters', `${slug}.json`), 'utf8')) as B5Fixture; + assert.equal(fx.adapterId, slug); + assert.ok(fx.negativeCases.length >= 4, `${slug} must have >= 4 negativeCases`); + + const resolvedTwin = fx.mode === 'twin' ? resolveSiteExtractorTwin(fx.inputUrl) : null; + const fetchUrl = fx.expectedFetchUrl || fx.inputUrl; + const trimmedMock = fx.mockPayload.trimStart(); + const contentType = + fx.mode === 'html' + ? 'text/html' + : trimmedMock.startsWith('{') || trimmedMock.startsWith('[') + ? 'application/json' + : 'text/plain'; + + if (fx.mode === 'twin') { + assert.ok(resolvedTwin && resolvedTwin.id === slug, `${slug}: expected twin for ${fx.inputUrl}`); + if (fx.expectedFetchUrl) { + assert.equal(resolvedTwin.fetchUrl, fx.expectedFetchUrl, `${slug}: unexpected fetchUrl`); + } + const out = resolvedTwin.formatTwin(fx.mockPayload, fx.inputUrl, noopHtmlToMd); + assert.ok(out && out.markdown.trim().length > 0, `${slug}: formatTwin returned null/empty`); + if (fx.expectTitleIncludes) { + assert.ok(out.title.includes(fx.expectTitleIncludes), `${slug}: title "${out.title}" missing "${fx.expectTitleIncludes}"`); + } + for (const needle of fx.expectMarkdownIncludes) { + assert.ok(out.markdown.includes(needle), `${slug}: markdown missing "${needle}"`); + } + if (out.records) { + assert.ok(out.records.length <= 25, `${slug}: records[] exceeds 25`); + } + } else { + const postOut = postExtractHtml(fx.mockPayload, fx.inputUrl, ''); + assert.ok(postOut && postOut.extractorId === slug && postOut.markdown.trim().length > 0, `${slug}: HTML extraction failed`); + if (fx.expectTitleIncludes && postOut.title) { + assert.ok(postOut.title.includes(fx.expectTitleIncludes), `${slug}: title "${postOut.title}" missing "${fx.expectTitleIncludes}"`); + } + for (const needle of fx.expectMarkdownIncludes) { + assert.ok(postOut.markdown.includes(needle), `${slug}: markdown missing "${needle}"`); + } + if (postOut.records) { + assert.ok(postOut.records.length <= 25, `${slug}: records[] exceeds 25`); + } + } + + // Golden scrape + RequestTracer + const scTracer = RequestTracer.fromRequest(new Request('https://hub.example.com/v1/scrape')); + let scRes!: Awaited>; + await scTracer.withSpan('edgefetch.scrape', async () => { + scRes = await executeScrapeCall({ + payload: { + url: fx.inputUrl, + formats: ['markdown', 'records'], + discoverLlmsTxt: false, + noCache: true, + }, + env: {}, + tracer: scTracer, + executeHubFetch: makeOverflowMock(200, fx.mockPayload, contentType, fx.mode === 'twin' ? fetchUrl : undefined), + }); + }); + assert.equal(scRes.status, 200, `${slug} scrape failed: ${JSON.stringify(scRes.body)}`); + assert.equal(scRes.body.extractorId, slug, `${slug} scrape extractorId mismatch`); + assert.equal(scRes.body.contentState, 'active', `${slug} scrape contentState must be active`); + assert.equal( + scTracer.getRecordedSpans().find((s) => s.name === 'edgefetch.scrape')?.attributes?.['edgefetch.adapter_id'], + slug, + `${slug} scrape span missing edgefetch.adapter_id`, + ); + + // Golden extract + RequestTracer + const exTracer = RequestTracer.fromRequest(new Request('https://hub.example.com/v1/extract')); + let exRes!: Awaited>; + await exTracer.withSpan('edgefetch.extract', async () => { + exRes = await executeExtractCall({ + payload: { + urls: [fx.inputUrl], + noCache: true, + }, + env: {}, + tracer: exTracer, + executeHubFetch: makeOverflowMock(200, fx.mockPayload, contentType, fx.mode === 'twin' ? fetchUrl : undefined), + }); + }); + assert.equal(exRes.status, 200, `${slug} extract failed`); + assert.equal( + exTracer.getRecordedSpans().find((s) => s.name === 'edgefetch.extract')?.attributes?.['edgefetch.adapter_id'], + slug, + `${slug} extract span missing edgefetch.adapter_id`, + ); + + // >= 4 negative cases + for (const nc of fx.negativeCases) { + const ncUrl = nc.inputUrl || fx.inputUrl; + const ncStatus = nc.status ?? 200; + const ncTrim = nc.payload.trimStart(); + const ncCt = ncTrim.startsWith('<') ? 'text/html' : ncTrim.startsWith('{') || ncTrim.startsWith('[') ? 'application/json' : 'text/plain'; + const ncTwin = resolveSiteExtractorTwin(ncUrl); + + if (nc.finalUrl && nc.finalUrl !== ncUrl) { + if (fx.mode === 'twin') { + assert.equal( + isTrustedTwinRedirectUrl(slug, fetchUrl, { finalUrl: nc.finalUrl }), + false, + `${slug}:${nc.name} redirect to ${nc.finalUrl} must be rejected`, + ); + } else { + const isErrRedir = isTwinRedirectedToErrorPage(ncUrl, { finalUrl: nc.finalUrl }); + const negHtml = postExtractHtml(nc.payload, nc.finalUrl, ''); + assert.ok(isErrRedir || negHtml === null, `${slug}:${nc.name} error redirect must not extract`); + } + } else if (ncTwin && ncTwin.id === slug) { + const negTwin = ncTwin.formatTwin(nc.payload, ncUrl, noopHtmlToMd); + assert.equal(Boolean(negTwin && negTwin.markdown.trim()), false, `${slug}:${nc.name} formatTwin must return null/empty`); + } else { + const negHtml = postExtractHtml(nc.payload, ncUrl, ''); + assert.equal(negHtml, null, `${slug}:${nc.name} HTML extractor must return null`); + } + + const scNeg = await executeScrapeCall({ + payload: { + url: ncUrl, + discoverLlmsTxt: false, + noCache: true, + }, + env: {}, + executeHubFetch: makeOverflowMock(ncStatus, nc.payload, ncCt, nc.finalUrl), + }); + assert.notEqual( + (scNeg.body as { contentState?: string }).contentState, + 'active', + `scrape ${slug}:${nc.name} must NEVER return contentState=active`, + ); + + const exNeg = await executeExtractCall({ + payload: { + urls: [ncUrl], + noCache: true, + }, + env: {}, + executeHubFetch: makeOverflowMock(ncStatus, nc.payload, ncCt, nc.finalUrl), + }); + const exFirst = ((exNeg.body as { results?: Array<{ contentState?: string }> }).results ?? [])[0]; + assert.notEqual( + exFirst?.contentState, + 'active', + `extract ${slug}:${nc.name} must NEVER return contentState=active`, + ); + } + } +}); + +test('Wave 3 B5 Cat O1/O2: #346 ETRTO ISO 5775 validation, #358 vs cpsc-recalls disjoint routing & #354 real extraction + WAF/CSR negative handling', async () => { + resetIsolateBudgetForTests(); + resetOverflowRobotsCacheForTests(); + + // 1. #346 ETRTO validation: valid ISO 5775 sizes retained, non-tire NN-NNN tokens excluded from ETRTO field + const tireHtml = `Grand Prix 5000 - Continental
+

Continental Grand Prix 5000

+

Part codes 25-145, 96-160, and 40-700 must not parse as ETRTO. Available in 700 x 28C, 120 TPI, BlackChili Compound, Foldable bead, Tubeless Ready (TR).

+ + + +
SizeETRTOWeight
700x28C28-622235 g
700x32C32-622290 g
+
`; + const tireOut = assertFastUnscaledSync('bicycle-tire-specs ETRTO', 75, () => + postExtractHtml(tireHtml, 'https://www.continental-tires.com/products/bicycle/tires/grand-prix-5000/', ''), + ); + assert.ok(tireOut && tireOut.extractorId === 'bicycle-tire-specs'); + const etrtoLine = tireOut.markdown.split('\n').find((l) => l.includes('ETRTO (ISO 5775)')) ?? ''; + assert.ok(etrtoLine.includes('28-622'), 'missing valid ETRTO 28-622'); + assert.ok(etrtoLine.includes('32-622'), 'missing valid ETRTO 32-622'); + assert.equal(etrtoLine.includes('25-145'), false, 'SKU 25-145 must NOT be classified as ETRTO'); + assert.equal(etrtoLine.includes('96-160'), false, 'token 96-160 must NOT be classified as ETRTO'); + assert.equal(etrtoLine.includes('40-700'), false, 'invalid BSD 40-700 must NOT be classified as ETRTO'); + + // 2. #358 cpsc-ebike-incidents vs cpsc-recalls symmetric path/query disjointness + const recallTwin = resolveSiteExtractorTwin('https://www.saferproducts.gov/RestWebServices/Recall?format=json&RecallNumber=24123'); + assert.equal(recallTwin?.id, 'cpsc-recalls'); + + const incidentTypeTwin = resolveSiteExtractorTwin('https://www.saferproducts.gov/RestWebServices/Recall?format=json&ProductType=Bicycle'); + assert.equal(incidentTypeTwin?.id, 'cpsc-ebike-incidents'); + assert.equal(incidentTypeTwin?.maxBytes, 2_097_152); + + const incidentDescTwin = resolveSiteExtractorTwin('https://saferproducts.gov/RestWebServices/Recall?format=json&ProductDescription=ebike'); + assert.equal(incidentDescTwin?.id, 'cpsc-ebike-incidents'); + + // Unfiltered SaferProducts dump must match neither + assert.equal(resolveSiteExtractorTwin('https://www.saferproducts.gov/RestWebServices/Recall?format=json'), null); + + // HTML disjointness: cpsc.gov/Recalls -> cpsc-recalls; saferproducts.gov/PublicSearch -> cpsc-ebike-incidents + const cpscRecallHtml = + 'Cipton Recalls Bicycle Helmets | CPSC.gov

Cipton Recalls Bicycle Helmets

Recall Number: 24-123

Consumers should stop using the helmets immediately due to impact hazard.

'; + assert.equal( + postExtractHtml( + cpscRecallHtml, + 'https://www.cpsc.gov/Recalls/2027/Cipton-Recalls-Bicycle-Helmets', + '', + + )?.extractorId, + 'cpsc-recalls', + ); + + const publicSearchPopulatedHtml = + 'Public Search - SaferProducts

Public Incident Search Results

Report NoProductDate
20260401-12345Class 2 E-Bike Battery2026-04-01
'; + assert.equal( + postExtractHtml( + publicSearchPopulatedHtml, + 'https://www.saferproducts.gov/PublicSearch?Term=ebike', + '', + + )?.extractorId, + 'cpsc-ebike-incidents', + ); + + // Unhydrated #tableResultsRefresh with zero rows must be rejected + const unhydratedSearchHtml = + 'Public Search - SaferProducts
'; + assert.equal( + postExtractHtml( + unhydratedSearchHtml, + 'https://www.saferproducts.gov/PublicSearch?Term=Hoverboards&handler=TermClick', + '', + + ), + null, + ); + + // 3. #354 geometrygeeks-99spokes REAL extraction on both geometrygeeks.bike & 99spokes.com + WAF/CSR rejections + const spokes99Html = `2024 Specialized Stumpjumper Comp | 99 Spokes +

2024 Specialized Stumpjumper Comp

`; + const spokesRes = await executeScrapeCall({ + payload: { url: 'https://99spokes.com/bikes/specialized/2024/stumpjumper-comp', formats: ['markdown', 'records'], discoverLlmsTxt: false, noCache: true }, + env: {}, + executeHubFetch: makeOverflowMock(200, spokes99Html, 'text/html'), + }); + assert.equal(spokesRes.status, 200); + assert.equal(spokesRes.body.extractorId, 'geometrygeeks-99spokes'); + assert.equal(spokesRes.body.contentState, 'active'); + assert.ok(String(spokesRes.body.markdown).includes('445')); + + const cfWafRes = await executeScrapeCall({ + payload: { url: 'https://99spokes.com/bikes/specialized/2024/stumpjumper-comp', discoverLlmsTxt: false, noCache: true }, + env: {}, + executeHubFetch: makeOverflowMock( + 403, + 'Attention Required! | Cloudflare

Sorry, you have been blocked

', + 'text/html', + ), + }); + assert.notEqual(cfWafRes.body.contentState, 'active'); +}); + +test('Wave 3 B5 Cat P: #359 Accept-Version: 3.0, #361 TPC/Upway before shopify.yaml, #364/#365 real + login_wall/WAF/CSR, #366 *.sellfy.store', async () => { + resetIsolateBudgetForTests(); + resetOverflowRobotsCacheForTests(); + + // 1. #359 Reverb Accept-Version: 3.0 + application/hal+json + reverb_search_json + const reverbItemTwin = resolveSiteExtractorTwin('https://reverb.com/item/36356670-fender-stratocaster-knob-set-black'); + assert.ok(reverbItemTwin && reverbItemTwin.id === 'reverb'); + assert.equal(reverbItemTwin.headers?.['Accept-Version'], '3.0'); + assert.equal(reverbItemTwin.accept, 'application/hal+json'); + + const reverbSearchUrl = 'https://api.reverb.com/api/listings?query=stratocaster&per_page=2'; + const reverbSearchTwin = resolveSiteExtractorTwin(reverbSearchUrl); + assert.ok(reverbSearchTwin && reverbSearchTwin.id === 'reverb'); + assert.equal(reverbSearchTwin.headers?.['Accept-Version'], '3.0'); + const reverbSearchOut = reverbSearchTwin.formatTwin( + JSON.stringify({ + total: 2, + current_page: 1, + total_pages: 1, + listings: [ + { id: 1001, title: 'Fender Stratocaster Neck', make: 'Fender', condition: { display_name: 'Mint' }, price: { amount: '399.00', currency: 'USD' }, _links: { web: { href: 'https://reverb.com/item/1001' } } }, + { id: 1002, title: 'Fender Stratocaster Body', make: 'Fender', condition: { display_name: 'Very Good' }, price: { amount: '499.00', currency: 'USD' }, _links: { web: { href: 'https://reverb.com/item/1002' } } }, + ], + }), + reverbSearchUrl, + noopHtmlToMd, + ); + assert.ok(reverbSearchOut && reverbSearchOut.markdown.includes('Fender Stratocaster Neck')); + + // 2. #361 used-bikes-shopify: TPC twin + Upway HTML both precede universal shopify.yaml + const tpcUrl = 'https://www.theproscloset.com/products/10226226168000-cervelo-p-series-red-axs-time-trial-bike-2022-58cm'; + const tpcTwin = resolveSiteExtractorTwin(tpcUrl); + assert.equal(tpcTwin?.id, 'used-bikes-shopify'); + assert.equal(tpcTwin?.fetchUrl, `${tpcUrl}.js`); + + const upwayUrl = 'https://upway.co/products/lane-lane-express-uaa01'; + assert.equal(resolveSiteExtractorTwin(upwayUrl), null, 'Upway must never resolve a Shopify .js/.json twin'); + assert.equal(resolveSiteExtractorTwin(`${upwayUrl}.js`), null); + const upwayPolicy = resolveAdapterPolicyForUrl(upwayUrl); + assert.equal(upwayPolicy.adapterId, 'used-bikes-shopify'); + assert.equal(upwayPolicy.minIntervalMs, 2000); + assert.equal(upwayPolicy.strictRobots, true); + + const upwayHtml = `Lane Express Commuter E-Bike | Upway + +

Lane Express Commuter E-Bike

Certified pre-owned e-bike with 500Wh battery and 120 miles.

`; + const upwayRes = await assertFastAsync('Upway executeScrapeCall', 75, () => + executeScrapeCall({ + payload: { url: upwayUrl, formats: ['markdown', 'records'], discoverLlmsTxt: false, noCache: true }, + env: {}, + executeHubFetch: makeOverflowMock(200, upwayHtml, 'text/html'), + }), + ); + assert.equal(upwayRes.status, 200); + assert.equal(upwayRes.body.extractorId, 'used-bikes-shopify'); + assert.equal(upwayRes.body.contentState, 'active'); + + // 3. #364 peer-resale-fashion & #365 local-classifieds-marketplaces: REAL extraction + login_wall / WAF / CSR negative handling + const depopHtml = `Vintage Cycling Jersey | Depop + +

Vintage Cycling Jersey

Medium size Italian wool jersey.

`; + const depopOut = postExtractHtml(depopHtml, 'https://www.depop.com/products/cyclist-vintage-jersey/', ''); + assert.equal(depopOut?.extractorId, 'peer-resale-fashion'); + + const fbPublicUrl = 'https://www.facebook.com/marketplace/item/998877665544/'; + const fbPublicHtml = `Trek Domane SL 6 | Facebook Marketplace + +

Trek Domane SL 6

54cm carbon endurance road bike.

`; + const fbPubRes = await executeScrapeCall({ + payload: { url: fbPublicUrl, formats: ['markdown', 'records'], discoverLlmsTxt: false, noCache: true }, + env: {}, + executeHubFetch: makeOverflowMock(200, fbPublicHtml, 'text/html'), + }); + assert.equal(fbPubRes.status, 200); + assert.equal(fbPubRes.body.extractorId, 'local-classifieds-marketplaces'); + assert.equal(fbPubRes.body.contentState, 'active'); + + const fbLoginHtml = + 'Log in to Facebook

Log in to Facebook

'; + const fbLoginRes = await executeScrapeCall({ + payload: { url: 'https://www.facebook.com/marketplace/sanfrancisco/bicycles', discoverLlmsTxt: false, noCache: true }, + env: {}, + executeHubFetch: makeOverflowMock(200, fbLoginHtml, 'text/html'), + }); + assert.equal(fbLoginRes.body.contentState, 'login_wall', 'Facebook Marketplace login gate must classify as login_wall'); + + const fbCsrHtml = + 'Bicycles | Facebook Marketplace
'; + assert.equal( + postExtractHtml(fbCsrHtml, 'https://www.facebook.com/marketplace/sanfrancisco/bicycles', ''), + null, + 'Facebook WebSite-only CSR shell must be rejected', + ); + + // 4. #366 creator-digital-stores: *.sellfy.store + *.gumroad.com + *.lemonsqueezy.com (and non-matching domain excluded) + const sellfyUrl = 'https://demo.sellfy.store/p/trail-preset-pack/'; + const sellfyHtml = `Trail LUT Preset Pack | Sellfy + +

Trail LUT Preset Pack

20 color grading LUTs for trail footage.

`; + const sellfyOut = postExtractHtml(sellfyHtml, sellfyUrl, ''); + assert.equal(sellfyOut?.extractorId, 'creator-digital-stores'); + assert.ok(sellfyOut?.markdown.includes('19.00 USD')); + + const unrelatedSellfyPath = postExtractHtml(sellfyHtml, 'https://example.com/p/trail-preset-pack/', ''); + assert.notEqual(unrelatedSellfyPath?.extractorId, 'creator-digital-stores'); + + const lemonUrl = 'https://acme.lemonsqueezy.com/buy/pro-kit'; + const lemonOut = postExtractHtml( + `Pro Kit | Lemon Squeezy

Pro Kit

`, + lemonUrl, + '', + + ); + assert.equal(lemonOut?.extractorId, 'creator-digital-stores'); +}); + +test('Wave 3 B5 Challenger Remediation Regressions: passive CF 200, h1+unclosed-div-100k < 75ms, 200 bare shells, CPSC %20, Lemmy offerup.com/post', async () => { + resetIsolateBudgetForTests(); + resetOverflowRobotsCacheForTests(); + + // 1. Passive Cloudflare challenge-platform script on 200 OK full resale product pages + const cfPassiveScript = ''; + for (const tc of [ + { + id: 'used-bikes-shopify', + url: 'https://upway.co/products/specialized-turbo-vado-4', + html: `2023 Specialized Turbo Vado 4.0 | Upway${cfPassiveScript}

2023 Specialized Turbo Vado 4.0

`, + }, + { + id: 'back-market-swappa', + url: 'https://swappa.com/buy/apple-iphone-14', + html: `Apple iPhone 14 | Swappa${cfPassiveScript}

Apple iPhone 14

`, + }, + { + id: 'pinkbike-buysell', + url: 'https://www.pinkbike.com/buysell/3910001/', + html: `2023 Santa Cruz Bronson | Pinkbike${cfPassiveScript}

2023 Santa Cruz Bronson

`, + }, + { + id: 'chairish-1stdibs', + url: 'https://www.chairish.com/product/99887766/mid-century-chair', + html: `Mid-Century Lounge Chair | Chairish${cfPassiveScript}

Mid-Century Lounge Chair

`, + }, + ]) { + const res = await executeScrapeCall({ + payload: { url: tc.url, formats: ['markdown', 'records'], discoverLlmsTxt: false, noCache: true }, + env: {}, + executeHubFetch: makeOverflowMock(200, tc.html, 'text/html'), + }); + assert.equal(res.status, 200, `${tc.id} passive CF scrape failed`); + assert.equal(res.body.extractorId, tc.id, `${tc.id} extractorId mismatch`); + assert.equal(res.body.contentState, 'active', `${tc.id} contentState must be active`); + } + + // 2. Hostile h1 + 100 KB unclosed
Bike

Bike

${'
`; + for (const id of ALL_B5_IDS) { + if (id === 'reverb') continue; // twin-only manifest + const fx = JSON.parse(readFileSync(resolve('test', 'fixtures', 'adapters', `${id}.json`), 'utf8')) as B5Fixture; + const testUrl = id === 'cpsc-ebike-incidents' ? 'https://www.saferproducts.gov/PublicSearch?Term=ebike' : fx.inputUrl; + assertFastUnscaledSync(`h1+unclosed-div-100k:${id}`, 75, () => + callCoreWasm('manifest_extract_html', { + adapterId: id, + rawHtml: hostileHtml, + baseUrl: testUrl, + currentMd: '', + }), + ); + } + + // 3. 200 OK bare CSR / deleted / soft-block shells must never return contentState='active' + for (const scCase of [ + { + name: 'facebook-bare-mount_0_0', + url: 'https://www.facebook.com/marketplace/item/123456', + html: 'Facebook Marketplace
', + }, + { + name: 'egain-loading_container', + url: 'https://support.specialized.com/kb/sp_en-us/home', + html: '

Loading...

', + }, + { + name: 'craigslist-deleted-posting', + url: 'https://sfbay.craigslist.org/sfc/bik/d/123.html', + html: 'craigslist | deleted

This posting has been deleted by its author.

', + }, + { + name: 'craigslist-blocked-title', + url: 'https://sfbay.craigslist.org/sfc/bik/d/123.html', + html: 'blocked

Your request has been blocked.

', + }, + { + name: 'ul-prospector-warning-blocked', + url: 'https://productiq.ulprospector.com/', + html: 'Warning: Blocked - UL Prospector

Access Denied

Warning: Blocked - UL Prospector

', + }, + { + name: 'backmarket-bot-need-challenge-html', + url: 'https://www.backmarket.com/en-us/p/item/123', + html: 'Challenge
bot-need-challenge
', + }, + { + name: 'missing-auth-token-html', + url: 'https://support.specialized.com/kb/sp_en-us/api', + html: '
{"message":"Missing Authentication Token"}
', + }, + ]) { + const res = await executeScrapeCall({ + payload: { url: scCase.url, discoverLlmsTxt: false, noCache: true }, + env: {}, + executeHubFetch: makeOverflowMock(200, scCase.html, 'text/html'), + }); + assert.notEqual( + (res.body as { contentState?: string }).contentState, + 'active', + `${scCase.name} must never return contentState=active`, + ); + } + + // 4. #358 cpsc-ebike-incidents %20 multi-word ProductType & ProductDescription parity + const scooterUrl = 'https://www.saferproducts.gov/RestWebServices/Recall?ProductType=Electric%20Scooter'; + assert.equal( + checkUnboundedTwinEndpointGuard(new URL(scooterUrl), scooterUrl), + null, + 'Electric%20Scooter must pass unbounded twin guard', + ); + const scooterTwin = resolveSiteExtractorTwin(scooterUrl); + assert.equal(scooterTwin?.id, 'cpsc-ebike-incidents'); + assert.equal( + scooterTwin?.fetchUrl, + 'https://www.saferproducts.gov/RestWebServices/Recall?format=json&ProductType=Electric%20Scooter', + ); + + const batteryUrl = 'https://www.saferproducts.gov/RestWebServices/Recall?ProductDescription=lithium%20battery'; + assert.equal( + checkUnboundedTwinEndpointGuard(new URL(batteryUrl), batteryUrl), + null, + 'lithium%20battery must pass unbounded twin guard', + ); + const batteryTwin = resolveSiteExtractorTwin(batteryUrl); + assert.equal(batteryTwin?.id, 'cpsc-ebike-incidents'); + assert.equal( + batteryTwin?.fetchUrl, + 'https://www.saferproducts.gov/RestWebServices/Recall?format=json&ProductDescription=lithium%20battery', + ); + + for (const badCpscUrl of [ + 'https://www.saferproducts.gov/RestWebServices/Recall?ProductType=a', + 'https://www.saferproducts.gov/RestWebServices/Recall?ProductType=..', + 'https://www.saferproducts.gov/RestWebServices/Recall?ProductType=a..b', + 'https://www.saferproducts.gov/RestWebServices/Recall?ProductType=foo%26bar', + 'https://www.saferproducts.gov/RestWebServices/Recall?ProductType=foo%3Cscript%3E', + 'https://www.saferproducts.gov/RestWebServices/Recall?ProductDescription=bad%22quote', + ]) { + assert.notEqual( + checkUnboundedTwinEndpointGuard(new URL(badCpscUrl), badCpscUrl), + null, + `guard must block ${badCpscUrl}`, + ); + assert.equal(resolveSiteExtractorTwin(badCpscUrl), null, `twin must reject ${badCpscUrl}`); + } + + // 5. lemmy.yaml Route 4 excludes offerup.com/post/... while preserving lemmy.world/post/... + assert.equal(resolveSiteExtractorTwin('https://offerup.com/post/123456'), null); + assert.equal(resolveSiteExtractorTwin('https://www.offerup.com/post/123456'), null); + const lemmyTwin = resolveSiteExtractorTwin('https://lemmy.world/post/54926010'); + assert.equal(lemmyTwin?.id, 'lemmy'); + assert.equal(lemmyTwin?.fetchUrl, 'https://lemmy.world/api/v3/post?id=54926010'); +}); diff --git a/hub/test/wave3-b6-gtin-media-finance-social.test.ts b/hub/test/wave3-b6-gtin-media-finance-social.test.ts new file mode 100644 index 0000000..2caf8b3 --- /dev/null +++ b/hub/test/wave3-b6-gtin-media-finance-social.test.ts @@ -0,0 +1,1040 @@ +import assert from 'node:assert/strict'; +import { createHash } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import test from 'node:test'; +import { gzipSync } from 'node:zlib'; +import { resolveAdapterPolicyForUrl, resolveUserAgentProfile } from '../src/adapter-policy'; +import { + fetchWithOfficialApiKey, + redactSecretsInBody, + resolveOfficialApiExtraHeaders, + resolveOfficialApiExtraHeadersAsync, + resolveOfficialApiExtraSecrets, + resolveOfficialApiProviderSpec, + resolveOfficialApiProviderSpecForUrl, + scrubSecretFromText, + sealUserApiKey, +} from '../src/api-keys'; +import { KNOWN_TELEMETRY_ADAPTER_IDS } from '../src/dev-telemetry'; +import { validateSingleErrorEvent } from '../../telemetry/src/index'; +import { DECLARATIVE_SITE_ADAPTERS } from '../src/extractors/declarative'; +import { resolveSiteExtractorTwin } from '../src/extractors/registry'; +import { postExtractHtml } from './post-fetch-wasm'; +import { RequestTracer } from '../src/otel'; +import { resetOverflowRobotsCacheForTests } from '../src/overflow'; +import { + decodeBoundedGzipTsvFromBase64, + executeScrapeCall, + fetchNostrRelayNip01Events, + isTrustedTwinRedirectUrl, + isTwinRedirectedToErrorPage, +} from '../src/scrape'; +import { executeExtractCall } from '../src/search-index'; +import { callCoreWasm, resetIsolateBudgetForTests } from '../src/wasm-bridge'; +import { assertFastAsync, assertFastUnscaledSync } from './perf-budget'; + +const WAVE3_B6_CAT_Q_IDS = [ + 'gs1-us-datahub', + 'open-icecat', + 'upcitemdb-barcodelookup', + 'open-product-wikidata-gtin', + 'energy-star', + 'fcc-test-report', + 'prop65-warnings', +] as const; + +const WAVE3_B6_CAT_R_IDS = [ + 'tmdb', + 'imdb-datasets', + 'tvmaze', + 'musicbrainz-coverart', + 'discogs', + 'podcast-index', + 'spotify-web-api', + 'setlist-lastfm', + 'steam-store', + 'igdb', + 'bandcamp', + 'genius-lyrics', +] as const; + +const WAVE3_B6_CAT_S_IDS = [ + 'fed-h15-datadownload', + 'nasdaq-data-link', + 'market-quotes-pack', + 'sec-xbrl-frames', + 'msrb-emma', + 'ffiec-cdr', +] as const; + +const WAVE3_B6_CAT_T_IDS = [ + 'youtube-data-api', + 'threads-api', + 'tumblr', + 'farcaster-hub', + 'nostr-relays', + 'product-hunt', + 'substack-notes-beehiiv', + 'patreon-public', +] as const; + +const ALL_B6_IDS = [ + ...WAVE3_B6_CAT_Q_IDS, + ...WAVE3_B6_CAT_R_IDS, + ...WAVE3_B6_CAT_S_IDS, + ...WAVE3_B6_CAT_T_IDS, +] as const; + +interface B6Fixture { + adapterId: string; + mode: 'twin' | 'html'; + inputUrl: string; + expectedFetchUrl?: string; + mockPayload: string; + expectTitleIncludes?: string; + expectMarkdownIncludes: string[]; + negativeCases: Array<{ + name: string; + status?: number; + inputUrl?: string; + finalUrl?: string; + payload: string; + }>; +} + +const noopHtmlToMd = () => ({ markdown: '', links: [] as string[] }); + +const EXPECTED_CATEGORY_BY_ID: Record<(typeof ALL_B6_IDS)[number], string> = { + 'gs1-us-datahub': 'commerce-social', + 'open-icecat': 'commerce-social', + 'upcitemdb-barcodelookup': 'commerce-social', + 'open-product-wikidata-gtin': 'commerce-social', + 'energy-star': 'public-records', + 'fcc-test-report': 'public-records', + 'prop65-warnings': 'public-records', + tmdb: 'commerce-social', + 'imdb-datasets': 'commerce-social', + tvmaze: 'commerce-social', + 'musicbrainz-coverart': 'commerce-social', + discogs: 'commerce-social', + 'podcast-index': 'commerce-social', + 'spotify-web-api': 'commerce-social', + 'setlist-lastfm': 'commerce-social', + 'steam-store': 'commerce-social', + igdb: 'commerce-social', + bandcamp: 'commerce-social', + 'genius-lyrics': 'commerce-social', + 'fed-h15-datadownload': 'finance', + 'nasdaq-data-link': 'finance', + 'market-quotes-pack': 'finance', + 'sec-xbrl-frames': 'finance', + 'msrb-emma': 'finance', + 'ffiec-cdr': 'finance', + 'youtube-data-api': 'commerce-social', + 'threads-api': 'commerce-social', + tumblr: 'commerce-social', + 'farcaster-hub': 'commerce-social', + 'nostr-relays': 'commerce-social', + 'product-hunt': 'commerce-social', + 'substack-notes-beehiiv': 'commerce-social', + 'patreon-public': 'commerce-social', +}; + +function makeOverflowMock(statusCode: number, bodyStr: string, ct: string, finalUrl?: string) { + return async (_t: unknown, body: string) => { + const req = (JSON.parse(body) as { requests: Array<{ id: string; url: string }> }).requests[0]!; + const outcome = + statusCode >= 200 && statusCode < 300 + ? 'ok' + : statusCode === 404 + ? 'not_found' + : statusCode === 410 + ? 'gone' + : statusCode === 403 + ? 'blocked' + : 'error'; + return { + status: 200, + via: 'hub:overflow', + bodyText: JSON.stringify({ + results: [ + { + id: req.id, + url: req.url, + ...(finalUrl ? { finalUrl } : {}), + outcome, + status: statusCode, + contentType: ct, + body: bodyStr, + }, + ], + }), + }; + }; +} + +function makeKeyFetchEnv(statusCode: number, bodyStr: string, ct: string) { + return { + SAFE_PUBLIC_FETCH: (async (input: RequestInfo | URL) => { + const u = new URL(typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url); + if (u.pathname === '/robots.txt') { + return new Response('User-agent: *\nAllow: /\n', { status: 200, headers: { 'content-type': 'text/plain' } }); + } + return new Response(bodyStr, { status: statusCode, headers: { 'content-type': ct } }); + }) as typeof fetch, + }; +} + +function reqUrl(input: RequestInfo | URL): URL { + return new URL(typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url); +} + +class MockNostrWebSocket { + static instances: MockNostrWebSocket[] = []; + readonly url: string; + readonly sentMessages: string[] = []; + closedWith?: { code?: number; reason?: string }; + readyState = 0; + private listeners = new Map void>>(); + + constructor(url: string) { + this.url = url; + MockNostrWebSocket.instances.push(this); + } + + addEventListener(type: string, fn: (ev: unknown) => void): void { + const arr = this.listeners.get(type) ?? []; + arr.push(fn); + this.listeners.set(type, arr); + } + + emit(type: string, ev: unknown): void { + for (const fn of this.listeners.get(type) ?? []) { + fn(ev); + } + } + + send(data: string): void { + this.sentMessages.push(data); + } + + close(code?: number, reason?: string): void { + this.closedWith = { code, reason }; + this.readyState = 3; + this.emit('close', {}); + } +} + +test('Wave 3 B6 Integration: All 33 adapter IDs registered, telemetry aligned, zero Rule 7 additions & Rule 9 clean', () => { + assert.equal(ALL_B6_IDS.length, 33, 'Batch B6 must cover all 33 adapters (#368-#400)'); + const registered = new Map(DECLARATIVE_SITE_ADAPTERS.map((a) => [a.id, a])); + + for (const id of ALL_B6_IDS) { + const adapter = registered.get(id); + assert.ok(adapter, `Missing DECLARATIVE_SITE_ADAPTERS entry: ${id}`); + assert.notEqual(adapter.authMode, 'detect-only', `${id} must never be detect-only`); + assert.equal(adapter.category, EXPECTED_CATEGORY_BY_ID[id], `${id} category mismatch`); + assert.ok(KNOWN_TELEMETRY_ADAPTER_IDS.has(id), `Missing KNOWN_TELEMETRY_ADAPTER_IDS entry: ${id}`); + assert.equal( + validateSingleErrorEvent({ + schemaVersion: 1, + version: '2.8.32', + runtime: 'workers', + os: 'cloudflare', + arch: 'v8', + mode: 'hub', + spanName: 'edgefetch.scrape', + adapterId: id, + wafVendor: '', + httpStatus: 500, + errorClass: 'timeout', + }).ok, + true, + `Missing telemetry/src/index.ts VALID_ADAPTER_IDS entry: ${id}`, + ); + assert.ok(adapter.exampleUrls.length >= 1, `${id} missing exampleUrls`); + } + + // Rule 7: Zero additions to APPROVED_CROSS_DOMAIN_TWIN_HOSTS (TS or Go) + const compileSrc = readFileSync(resolve('scripts', 'compile-manifests.mjs'), 'utf8'); + const crossBlock = compileSrc.slice( + compileSrc.indexOf('APPROVED_CROSS_DOMAIN_TWIN_HOSTS'), + compileSrc.indexOf('APPROVED_WILDCARD_DOMAIN_PATTERNS'), + ); + for (const id of ALL_B6_IDS) { + assert.equal(crossBlock.includes(`'${id}'`), false, `Rule 7 violation: ${id} in APPROVED_CROSS_DOMAIN_TWIN_HOSTS`); + } + for (const forbiddenHost of ['coverartarchive.org', 'api.barcodelookup.com', 'api.igdb.com']) { + assert.equal(crossBlock.includes(forbiddenHost), false, `Rule 7 violation: ${forbiddenHost} in APPROVED_CROSS_DOMAIN_TWIN_HOSTS`); + } + + const declGoSrc = readFileSync(resolve('..', 'internal', 'extract', 'declarative.go'), 'utf8'); + const goCrossMatch = /var approvedCrossDomainTwinHostsGo = map\[string\]map\[string\]bool\{([\s\S]*?)\n\}/.exec(declGoSrc); + assert.ok(goCrossMatch); + for (const id of ALL_B6_IDS) { + assert.equal(goCrossMatch[1]!.includes(`"${id}"`), false, `Rule 7 Go violation: ${id} in approvedCrossDomainTwinHostsGo`); + } + + // Rule 9: Zero private / internal names across all 33 B6 manifests, fixtures, and Go sources/tests + const privateBrandRe = new RegExp(Buffer.from('c2hlcGhlcmR8c2hvcGRhd2d8anVpY2VkLj93aGVlbHM=', 'base64').toString('utf8'), 'i'); + for (const id of ALL_B6_IDS) { + const yamlText = readFileSync(resolve('..', 'internal', 'extract', 'manifests', `${id}.yaml`), 'utf8'); + assert.equal(privateBrandRe.test(yamlText), false, `Rule 9 violation in ${id}.yaml`); + const fxText = readFileSync(resolve('test', 'fixtures', 'adapters', `${id}.json`), 'utf8'); + assert.equal(privateBrandRe.test(fxText), false, `Rule 9 violation in ${id}.json`); + } + for (const goRel of [ + 'wave3_gtin_identity.go', + 'wave3_gtin_identity_test.go', + 'wave3_media_lyrics.go', + 'wave3_media_lyrics_test.go', + 'wave3_finance.go', + 'wave3_finance_test.go', + 'wave3_social_creator.go', + 'wave3_social_creator_test.go', + ]) { + const goText = readFileSync(resolve('..', 'internal', 'extract', goRel), 'utf8'); + assert.equal(privateBrandRe.test(goText), false, `Rule 9 violation in ${goRel}`); + } +}); + +test('Wave 3 B6 Fixtures: All 33 golden + >=4 negative cases pass via formatTwin/HTML, executeScrapeCall, executeExtractCall & RequestTracer', async () => { + resetIsolateBudgetForTests(); + resetOverflowRobotsCacheForTests(); + + const b6ApiKeys = { + 'gs1-us-datahub': 'gs1-us-test-key-0123456789abcdef', + 'upcitemdb-barcodelookup': 'upc-barcodelookup-key-0123456789abcdef', + tmdb: 'tmdb-test-api-key-0123456789abcdef', + 'podcast-index': 'podcast-index-key-0123456789abcdef', + PODCASTINDEX_API_SECRET: 'podcast-index-secret-0123456789abcdef', + 'spotify-web-api': 'spotify-access-token-0123456789abcdef', + 'setlist-lastfm': 'setlist-lastfm-key-0123456789abcdef', + igdb: 'igdb-twitch-token-0123456789abcdef', + TWITCH_CLIENT_ID: 'twitch-client-id-0123456789abcdef', + 'nasdaq-data-link': 'nasdaq-data-link-key-0123456789abcdef', + 'market-quotes-pack': 'market-quotes-key-0123456789abcdef', + 'ffiec-cdr': 'ffiec-cdr-token-0123456789abcdef', + 'youtube-data-api': 'youtube-data-api-key-0123456789abcdef', + 'threads-api': 'threads-access-token-0123456789abcdef', + tumblr: 'tumblr-api-key-0123456789abcdef', + 'farcaster-hub': 'neynar-api-key-0123456789abcdef', + 'product-hunt': 'producthunt-token-0123456789abcdef', + 'substack-notes-beehiiv': 'beehiiv-api-key-0123456789abcdef', + }; + + for (const slug of ALL_B6_IDS) { + const fx = JSON.parse(readFileSync(resolve('test', 'fixtures', 'adapters', `${slug}.json`), 'utf8')) as B6Fixture; + assert.equal(fx.adapterId, slug); + assert.ok(fx.negativeCases.length >= 4, `${slug} must have >= 4 negativeCases`); + + const resolvedTwin = fx.mode === 'twin' ? resolveSiteExtractorTwin(fx.inputUrl) : null; + const isKeyTwin = Boolean(resolvedTwin && resolvedTwin.authMode === 'key'); + const fetchUrl = fx.expectedFetchUrl || fx.inputUrl; + const trimmedMock = fx.mockPayload.trimStart(); + const contentType = + fx.mode === 'html' + ? 'text/html' + : trimmedMock.startsWith('{') || trimmedMock.startsWith('[') + ? 'application/json' + : 'text/plain'; + + if (fx.mode === 'twin') { + assert.ok(resolvedTwin && resolvedTwin.id === slug, `${slug}: expected twin for ${fx.inputUrl}`); + if (fx.expectedFetchUrl) { + assert.equal(resolvedTwin.fetchUrl, fx.expectedFetchUrl, `${slug}: unexpected fetchUrl`); + } + const out = resolvedTwin.formatTwin(fx.mockPayload, fx.inputUrl, noopHtmlToMd); + assert.ok(out && out.markdown.trim().length > 0, `${slug}: formatTwin returned null/empty`); + if (fx.expectTitleIncludes) { + assert.ok(out.title.includes(fx.expectTitleIncludes), `${slug}: title "${out.title}" missing "${fx.expectTitleIncludes}"`); + } + for (const needle of fx.expectMarkdownIncludes) { + assert.ok(out.markdown.includes(needle), `${slug}: markdown missing "${needle}"`); + } + if (out.records) { + assert.ok(out.records.length <= 25, `${slug}: records[] exceeds 25`); + } + } else { + const postOut = postExtractHtml(fx.mockPayload, fx.inputUrl, ''); + assert.ok(postOut && postOut.extractorId === slug && postOut.markdown.trim().length > 0, `${slug}: HTML extraction failed`); + if (fx.expectTitleIncludes && postOut.title) { + assert.ok(postOut.title.includes(fx.expectTitleIncludes), `${slug}: title "${postOut.title}" missing "${fx.expectTitleIncludes}"`); + } + for (const needle of fx.expectMarkdownIncludes) { + assert.ok(postOut.markdown.includes(needle), `${slug}: markdown missing "${needle}"`); + } + if (postOut.records) { + assert.ok(postOut.records.length <= 25, `${slug}: records[] exceeds 25`); + } + } + + // Golden scrape + RequestTracer + const scTracer = RequestTracer.fromRequest(new Request('https://hub.example.com/v1/scrape')); + let scRes!: Awaited>; + await scTracer.withSpan('edgefetch.scrape', async () => { + scRes = await executeScrapeCall({ + payload: { + url: fx.inputUrl, + formats: ['markdown', 'records'], + discoverLlmsTxt: false, + noCache: true, + ...(isKeyTwin ? { apiKeys: b6ApiKeys } : {}), + }, + env: (isKeyTwin ? makeKeyFetchEnv(200, fx.mockPayload, contentType) : {}) as never, + tracer: scTracer, + executeHubFetch: isKeyTwin + ? async () => { + throw new Error(`${slug}: keyed twin must use fetchWithOfficialApiKey`); + } + : makeOverflowMock(200, fx.mockPayload, contentType, fx.mode === 'twin' ? fetchUrl : undefined), + }); + }); + assert.equal(scRes.status, 200, `${slug} scrape failed: ${JSON.stringify(scRes.body)}`); + assert.equal(scRes.body.extractorId, slug, `${slug} scrape extractorId mismatch`); + assert.equal(scRes.body.contentState, 'active', `${slug} scrape contentState must be active`); + assert.equal( + scTracer.getRecordedSpans().find((s) => s.name === 'edgefetch.scrape')?.attributes?.['edgefetch.adapter_id'], + slug, + `${slug} scrape span missing edgefetch.adapter_id`, + ); + + // Golden extract + RequestTracer + const exTracer = RequestTracer.fromRequest(new Request('https://hub.example.com/v1/extract')); + let exRes!: Awaited>; + await exTracer.withSpan('edgefetch.extract', async () => { + exRes = await executeExtractCall({ + payload: { + urls: [fx.inputUrl], + noCache: true, + ...(isKeyTwin ? { apiKeys: b6ApiKeys } : {}), + }, + env: (isKeyTwin ? makeKeyFetchEnv(200, fx.mockPayload, contentType) : {}) as never, + tracer: exTracer, + executeHubFetch: isKeyTwin + ? async () => { + throw new Error(`${slug}: keyed extract must use fetchWithOfficialApiKey`); + } + : makeOverflowMock(200, fx.mockPayload, contentType, fx.mode === 'twin' ? fetchUrl : undefined), + }); + }); + assert.equal(exRes.status, 200, `${slug} extract failed`); + assert.equal( + exTracer.getRecordedSpans().find((s) => s.name === 'edgefetch.extract')?.attributes?.['edgefetch.adapter_id'], + slug, + `${slug} extract span missing edgefetch.adapter_id`, + ); + + // >= 4 negative cases + for (const nc of fx.negativeCases) { + const ncUrl = nc.inputUrl || fx.inputUrl; + const ncStatus = nc.status ?? 200; + const ncTrim = nc.payload.trimStart(); + const ncCt = ncTrim.startsWith('<') ? 'text/html' : ncTrim.startsWith('{') || ncTrim.startsWith('[') ? 'application/json' : 'text/plain'; + const ncTwin = resolveSiteExtractorTwin(ncUrl); + + if (nc.finalUrl && nc.finalUrl !== ncUrl) { + if (fx.mode === 'twin' && ncTwin && ncTwin.id === slug) { + assert.equal( + isTrustedTwinRedirectUrl(slug, fetchUrl, { finalUrl: nc.finalUrl }), + false, + `${slug}:${nc.name} redirect to ${nc.finalUrl} must be rejected`, + ); + } else { + const isErrRedir = isTwinRedirectedToErrorPage(ncUrl, { finalUrl: nc.finalUrl }); + const negHtml = postExtractHtml(nc.payload, nc.finalUrl, ''); + assert.ok(isErrRedir || negHtml === null, `${slug}:${nc.name} error redirect must not extract`); + } + } else if (ncTwin && ncTwin.id === slug) { + const negTwin = ncTwin.formatTwin(nc.payload, ncUrl, noopHtmlToMd); + assert.equal(Boolean(negTwin && negTwin.markdown.trim()), false, `${slug}:${nc.name} formatTwin must return null/empty`); + } else { + const negHtml = postExtractHtml(nc.payload, ncUrl, ''); + assert.equal(negHtml, null, `${slug}:${nc.name} HTML extractor must return null`); + } + + const useKeyFetch = Boolean(ncTwin && ncTwin.id === slug && ncTwin.authMode === 'key' && !nc.finalUrl); + const scNeg = await executeScrapeCall({ + payload: { + url: ncUrl, + discoverLlmsTxt: false, + noCache: true, + ...(useKeyFetch ? { apiKeys: b6ApiKeys } : {}), + }, + env: (useKeyFetch ? makeKeyFetchEnv(ncStatus, nc.payload, ncCt) : {}) as never, + executeHubFetch: makeOverflowMock(ncStatus, nc.payload, ncCt, nc.finalUrl), + }); + assert.notEqual( + (scNeg.body as { contentState?: string }).contentState, + 'active', + `scrape ${slug}:${nc.name} must NEVER return contentState=active`, + ); + + const exNeg = await executeExtractCall({ + payload: { + urls: [ncUrl], + noCache: true, + ...(useKeyFetch ? { apiKeys: b6ApiKeys } : {}), + }, + env: (useKeyFetch ? makeKeyFetchEnv(ncStatus, nc.payload, ncCt) : {}) as never, + executeHubFetch: makeOverflowMock(ncStatus, nc.payload, ncCt, nc.finalUrl), + }); + const exFirst = ((exNeg.body as { results?: Array<{ contentState?: string }> }).results ?? [])[0]; + assert.notEqual( + exFirst?.contentState, + 'active', + `extract ${slug}:${nc.name} must NEVER return contentState=active`, + ); + } + } +}); + +test('Wave 3 B6 Cat Q: Strict 8/12/13/14-digit GTIN validation (#368-#371), fcc-id exhibit mode & Incapsula/SPA rejections', () => { + resetIsolateBudgetForTests(); + + // Valid 8, 12, 13, 14-digit GTINs resolve on #369 & #370 + for (const goodUrl of [ + 'https://live.icecat.biz/api?shopname=openicecat-live&lang=en>IN=12345670', + 'https://live.icecat.biz/api?shopname=openicecat-live&lang=en>IN=012000161155', + 'https://live.icecat.biz/api?shopname=openicecat-live&lang=en>IN=8710103792772', + 'https://live.icecat.biz/api?shopname=openicecat-live&lang=en>IN=00871010379277', + 'https://api.upcitemdb.com/prod/trial/lookup?upc=012000161155', + 'https://api.barcodelookup.com/v3/products?barcode=0012000161155', + ]) { + assert.ok(resolveSiteExtractorTwin(goodUrl), `Expected valid GTIN route to match: ${goodUrl}`); + } + + // Invalid 9/10/11-digit codes, ASINs, SKUs, hex strings MUST be rejected by route matchers + for (const badUrl of [ + 'https://live.icecat.biz/api?shopname=openicecat-live&lang=en>IN=B08N5WRWNW', + 'https://live.icecat.biz/api?shopname=openicecat-live&lang=en>IN=1234567890', + 'https://live.icecat.biz/api?shopname=openicecat-live&lang=en>IN=12345678901', + 'https://api.upcitemdb.com/prod/trial/lookup?upc=SKU-12345', + 'https://api.upcitemdb.com/prod/trial/lookup?upc=123456789', + 'https://api.barcodelookup.com/v3/products?barcode=deadbeef1234', + ]) { + assert.equal(resolveSiteExtractorTwin(badUrl), null, `Expected invalid GTIN route to be rejected: ${badUrl}`); + } + + // OpenGTINdb invalid EAN (10-digit) rejected at route match time; invalid GTIN codes in payload omitted from records[] + assert.equal(resolveSiteExtractorTwin('https://opengtindb.org/?ean=1234567890&cmd=query&queryid=400000000'), null); + const openGtinTwin = resolveSiteExtractorTwin('https://opengtindb.org/?ean=4006381333931&cmd=query&queryid=400000000'); + assert.ok(openGtinTwin && openGtinTwin.id === 'open-product-wikidata-gtin'); + const icecatTwin = resolveSiteExtractorTwin('https://live.icecat.biz/api?shopname=openicecat-live&lang=en&icecat_id=32928991'); + assert.ok(icecatTwin && icecatTwin.id === 'open-icecat'); + const icecatBadGtinOut = icecatTwin.formatTwin( + JSON.stringify({ + msg: 'OK', + data: { + GeneralInfo: { + IcecatId: 32928991, + Title: 'Widget', + Brand: 'Acme', + GTIN: ['1234567890', 'B08N5WRWNW'], + }, + }, + }), + 'https://live.icecat.biz/api?shopname=openicecat-live&lang=en&icecat_id=32928991', + noopHtmlToMd, + ); + assert.ok(icecatBadGtinOut); + assert.equal(icecatBadGtinOut.records?.[0]?.gtin, undefined, 'Invalid 10-digit/ASIN codes must NOT appear as GTIN'); + + // Upgraded fcc-id exhibit link extraction on fccid.io/ + const fccIdHtml = `FCC ID BCG-E3542A by Apple Inc.
+

FCC ID BCG-E3542A

+

Grantee: Apple Inc. Equipment Class: DTS Digital Transmission System.

+ Test Report PDF + RF Exposure Info +
`; + const fccIdOut = postExtractHtml(fccIdHtml, 'https://fccid.io/BCG-E3542A', ''); + assert.equal(fccIdOut?.extractorId, 'fcc-id'); + assert.ok(fccIdOut?.markdown.includes('Test Report')); +}); + +test('Wave 3 B6 Cat R: #376 IMDb bounded gzip + nonCommercialLicense, #378 MusicBrainz UA/rate & PoW, #386 multi-site lyrics', async () => { + resetIsolateBudgetForTests(); + resetOverflowRobotsCacheForTests(); + + // 1. #376 imdb-datasets: full gzip AND mid-stream truncated gzip base64 -> TSV + nonCommercialLicense: true + const tsvText = [ + 'tconst\taverageRating\tnumVotes', + 'tt0000001\t5.7\t2244', + 'tt0000002\t5.5\t308', + 'tt0000003\t6.5\t2286', + ].join('\n'); + const fullGzB64 = gzipSync(Buffer.from(tsvText, 'utf8')).toString('base64'); + const decodedFull = await decodeBoundedGzipTsvFromBase64(fullGzB64); + assert.ok(decodedFull && decodedFull.includes('tt0000001\t5.7\t2244')); + + // Large multi-row gzipped TSV sliced before trailer (simulating HTTP 206 Range chunk) + const manyRows = ['tconst\taverageRating\tnumVotes']; + for (let i = 1; i <= 500; i++) { + manyRows.push(`tt${String(i).padStart(7, '0')}\t${((i % 9) + 1).toFixed(1)}\t${100 + i}`); + } + const fullManyGz = gzipSync(Buffer.from(`${manyRows.join('\n')}\n`, 'utf8')); + const truncatedGzB64 = fullManyGz.subarray(0, Math.max(40, fullManyGz.byteLength - 16)).toString('base64'); + const decodedTrunc = await decodeBoundedGzipTsvFromBase64(truncatedGzB64); + assert.ok(decodedTrunc && decodedTrunc.includes('tconst\taverageRating\tnumVotes'), 'Truncated gzip stream must yield decoded prefix rows'); + + // Bounded <= 2 MiB decompression cap check + const bigRow = 'tt0000001\t8.8\t123456\t' + 'abcdefghij'.repeat(20) + '\n'; + const over2MiBText = 'tconst\taverageRating\tnumVotes\textra\n' + bigRow.repeat(12_000); + const over2MiBGzB64 = gzipSync(Buffer.from(over2MiBText, 'utf8')).toString('base64'); + const boundedDecoded = await decodeBoundedGzipTsvFromBase64(over2MiBGzB64); + assert.ok(boundedDecoded); + assert.ok(Buffer.byteLength(boundedDecoded, 'utf8') <= 2 * 1024 * 1024 + 512, 'Decompressed TSV must stay bounded to <= 2 MiB'); + + const imdbScrape = await executeScrapeCall({ + payload: { + url: 'https://datasets.imdbws.com/title.ratings.tsv.gz', + formats: ['markdown', 'records'], + discoverLlmsTxt: false, + noCache: true, + }, + env: {}, + executeHubFetch: async (_t, body) => { + const req = (JSON.parse(body) as { requests: Array<{ id: string; url: string; headers?: Record }> }).requests[0]!; + assert.equal(req.headers?.Range, 'bytes=0-262143'); + return { + status: 200, + via: 'hub:overflow', + bodyText: JSON.stringify({ + results: [ + { + id: req.id, + url: req.url, + outcome: 'ok', + status: 206, + contentType: 'binary/octet-stream', + bodyEncoding: 'base64', + body: fullGzB64, + }, + ], + }), + }; + }, + }); + assert.equal(imdbScrape.status, 200); + assert.equal(imdbScrape.body.extractorId, 'imdb-datasets'); + assert.equal(imdbScrape.body.contentState, 'active'); + assert.ok(String(imdbScrape.body.markdown).includes('IMDb Non-Commercial Datasets')); + assert.ok(String(imdbScrape.body.markdown).includes('nonCommercialLicense: true')); + const imdbRecs = imdbScrape.body.records as Array>; + assert.ok(Array.isArray(imdbRecs) && imdbRecs.length >= 3); + assert.equal(imdbRecs[0]?.nonCommercialLicense, true); + + // Also verify executeExtractCall decodes base64 gzip for #376 + const imdbExtract = await executeExtractCall({ + payload: { urls: ['https://datasets.imdbws.com/title.ratings.tsv.gz'], includeRawContent: true, noCache: true }, + env: {}, + executeHubFetch: async (_t, body) => { + const req = (JSON.parse(body) as { requests: Array<{ id: string; url: string }> }).requests[0]!; + return { + status: 200, + via: 'hub:overflow', + bodyText: JSON.stringify({ + results: [ + { + id: req.id, + url: req.url, + outcome: 'ok', + status: 206, + contentType: 'binary/octet-stream', + bodyEncoding: 'base64', + body: fullGzB64, + }, + ], + }), + }; + }, + }); + assert.equal(imdbExtract.status, 200); + const imdbExRes = (imdbExtract.body as { results: Array<{ contentState?: string; rawContent?: string; chunks: Array<{ text: string }> }> }).results[0]!; + assert.equal(imdbExRes.contentState, 'active'); + const imdbExText = imdbExRes.rawContent || imdbExRes.chunks.map((c) => c.text).join('\n'); + assert.ok(imdbExText.includes('tt0000001')); + + // 2. #378 MusicBrainz UA profile, rate limit policy, and /__meb_verify PoW prose shell rejection + const mbPol = resolveAdapterPolicyForUrl('https://musicbrainz.org/ws/2/artist/5b11f4ce-a62d-471e-81fc-a69a8278c7da?fmt=json'); + assert.equal(mbPol.adapterId, 'musicbrainz-coverart'); + assert.equal(mbPol.userAgentProfile, 'musicbrainz'); + assert.equal(mbPol.maxConcurrent, 1); + assert.ok((mbPol.minIntervalMs ?? 0) >= 1000); + assert.equal(resolveUserAgentProfile('musicbrainz'), 'EdgeFetch/2.7 (bot@edgefetch.dev; musicbrainz-client)'); + + const mebProseHtml = + 'Verifying your browser

Please wait while we verify your browser request.

'; + const mebScrape = await executeScrapeCall({ + payload: { url: 'https://musicbrainz.org/release/76df3287-6cda-33eb-8e9a-044b5e15ffdd', discoverLlmsTxt: false, noCache: true }, + env: {}, + executeHubFetch: makeOverflowMock(200, mebProseHtml, 'text/html'), + }); + assert.notEqual(mebScrape.body.contentState, 'active', 'MusicBrainz /__meb_verify PoW prose shell must never be active'); + + // 3. #386 Real multi-site lyrics extraction across Genius, AZLyrics, Musixmatch, and SongMeanings (zero copyright refusal) + const azHtml = `Rick Astley - Never Gonna Give You Up Lyrics | AZLyrics.com
"Never Gonna Give You Up"
We're no strangers to love
You know the rules and so do I
`; + const azOut = postExtractHtml(azHtml, 'https://www.azlyrics.com/lyrics/rickastley/nevergonnagiveyouup.html', ''); + assert.equal(azOut?.extractorId, 'genius-lyrics'); + assert.ok(azOut?.markdown.includes("We're no strangers to love\nYou know the rules and so do I")); + + const mxmHtml = `Never Gonna Give You Up Lyrics - Musixmatch
We're no strangers to love
`; + const mxmOut = postExtractHtml(mxmHtml, 'https://www.musixmatch.com/lyrics/Rick-Astley/Never-Gonna-Give-You-Up', ''); + assert.equal(mxmOut?.extractorId, 'genius-lyrics'); + assert.ok(mxmOut?.markdown.includes("We're no strangers to love")); + + const smHtml = `Rick Astley - Never Gonna Give You Up Lyrics | SongMeanings

Never Gonna Give You Up

Classic 1987 pop commitment anthem.
`; + const smOut = postExtractHtml(smHtml, 'https://songmeanings.com/songs/view/3530822107858506064/', ''); + assert.equal(smOut?.extractorId, 'genius-lyrics'); + assert.ok(smOut?.markdown.includes("We're no strangers to love")); + assert.ok(smOut?.markdown.includes('Classic 1987 pop commitment anthem.')); +}); + +test('Wave 3 B6 Cat T: #397 Nostr NIP-11 + bounded read-only WS NIP-01 REQ + SSRF guards + njump.me', async () => { + resetIsolateBudgetForTests(); + resetOverflowRobotsCacheForTests(); + MockNostrWebSocket.instances = []; + + assert.equal(callCoreWasm<{ enabled: boolean }>('nostr_prepare_nip01', { url: 'https://nos.lol/' }).enabled, false); + assert.equal(callCoreWasm<{ enabled: boolean }>('nostr_prepare_nip01', { url: 'https://nos.lol/?nip01=1&kinds=1&limit=5' }).enabled, true); + assert.equal(callCoreWasm<{ enabled: boolean }>('nostr_prepare_nip01', { url: 'https://nos.lol/?kinds=1,30023' }).enabled, true); + + // SSRF / port / credential / private-IP guards fail closed BEFORE opening WS + let factoryCalled = false; + for (const badUrl of [ + 'http://nos.lol/?nip01=1', + 'https://nos.lol:8443/?nip01=1', + 'https://user:pass@nos.lol/?nip01=1', + 'https://127.0.0.1/?nip01=1', + 'https://169.254.169.254/?nip01=1', + 'https://hub.example.com/?nip01=1', + ]) { + const res = await fetchNostrRelayNip01Events({ + url: badUrl, + selfHost: 'hub.example.com', + webSocketFactory: () => { + factoryCalled = true; + return new MockNostrWebSocket('wss://bad/') as unknown as WebSocket; + }, + }); + assert.equal(res.ok, false, `Expected Nostr WS SSRF rejection for ${badUrl}`); + } + assert.equal(factoryCalled, false, 'WebSocket factory must NEVER be called for unsafe Nostr URLs'); + + // robots_disallowed on NIP-11 precheck also blocks WS + const robotsBlocked = await executeScrapeCall({ + payload: { url: 'https://nos.lol/?nip01=1&kinds=1', discoverLlmsTxt: false, noCache: true }, + env: {}, + executeHubFetch: async (_t, body) => { + const req = (JSON.parse(body) as { requests: Array<{ id: string; url: string }> }).requests[0]!; + return { + status: 200, + via: 'hub:overflow', + bodyText: JSON.stringify({ + results: [{ id: req.id, url: req.url, outcome: 'robots_disallowed', status: 422, problem: 'Disallowed by robots.txt' }], + }), + }; + }, + webSocketFactory: () => { + factoryCalled = true; + return new MockNostrWebSocket('wss://nos.lol/') as unknown as WebSocket; + }, + }); + assert.equal(factoryCalled, false, 'WebSocket must NOT open when robots.txt disallows NIP-11 origin'); + assert.notEqual(robotsBlocked.body.contentState, 'active'); + + // Mocked bounded read-only WS NIP-01 REQ -> sends ONLY REQ & CLOSE (ZERO EVENT/AUTH/COUNT), collects events & stops on EOSE + const nip11Json = JSON.stringify({ + name: 'nos.lol', + description: 'Public Nostr relay', + supported_nips: [1, 11], + software: 'https://github.com/hoytech/strfry', + version: '1.0.0', + }); + const wsScrape = await executeScrapeCall({ + payload: { + url: 'https://nos.lol/?nip01=1&kinds=1&limit=99', + formats: ['markdown', 'records'], + discoverLlmsTxt: false, + noCache: true, + }, + env: {}, + executeHubFetch: makeOverflowMock(200, nip11Json, 'application/nostr+json', 'https://nos.lol/'), + webSocketFactory: (wssUrl: string) => { + assert.equal(wssUrl, 'wss://nos.lol/'); + const sock = new MockNostrWebSocket(wssUrl); + queueMicrotask(() => { + sock.readyState = 1; + sock.emit('open', {}); + const reqFrame = JSON.parse(sock.sentMessages[0]!) as [string, string, { kinds: number[]; limit: number }]; + assert.equal(reqFrame[0], 'REQ'); + assert.deepEqual(reqFrame[2].kinds, [1]); + assert.equal(reqFrame[2].limit, 20, 'limit=99 must clamp to <= 20'); + const subId = reqFrame[1]; + sock.emit('message', { + data: JSON.stringify([ + 'EVENT', + subId, + { + id: 'a'.repeat(64), + pubkey: 'b'.repeat(64), + created_at: 1732838400, + kind: 1, + tags: [['t', 'nostr']], + content: 'Live WS note clean text.', + sig: 'c'.repeat(128), + }, + ]), + }); + sock.emit('message', { data: JSON.stringify(['EOSE', subId]) }); + }); + return sock as unknown as WebSocket; + }, + }); + assert.equal(wsScrape.status, 200); + assert.equal(wsScrape.body.extractorId, 'nostr-relays'); + assert.equal(wsScrape.body.contentState, 'active'); + assert.ok(String(wsScrape.body.markdown).includes('Live WS note')); + assert.equal(String(wsScrape.body.markdown).includes('`) - reVisibleDropBlocksCSGo = newLazyRegexp(`(?is)<(?:pre|code|blockquote|textarea|svg|style|script)\b[^>]*>.*?`) - reScrubDomBlocksCSGo = newLazyRegexp(`(?is)<(?:pre|code|blockquote|textarea|svg|style)\b[^>]*>.*?`) reProseLeakBlocksCSGo = newLazyRegexp(`(?is)<(?:script|style|noscript|template)\b[^>]*>.*?`) reHeadBlockCSGo = newLazyRegexp(`(?is)]*>.*?`) reH1BlockCSGo = newLazyRegexp(`(?is)]*>(.*?)`) @@ -79,21 +76,23 @@ var ( reCloudflareTitleFullCSGo = newLazyRegexp(`(?i)^(?:just a moment\.{0,3}|attention required!\s*\|\s*cloudflare|ddos-guard|checking your browser)$`) reGenericChallengeTitleFullCSGo = newLazyRegexp(`(?i)^(?:verify you are human|human verification|pardon our interruption|access to this page has been denied|bot verification|security check|vercel security checkpoint)$`) reAkamaiRefFullCSGo = newLazyRegexp(`(?i)reference\s*#18\.[0-9a-f]{4,}\.[0-9]{6,}`) + reHashcashConfigAssignCSGo = newLazyRegexp(`(?i)(?:window\.|\b(?:var|let|const)\s+)hashcash_config\b|\bhashcash_config\s*=`) - reNonContentIframeHostCSGo = newLazyRegexp(`(?i)(?:googletagmanager\.com|doubleclick\.net|googlesyndication\.com|google-analytics\.com|facebook\.com/tr|challenges\.cloudflare\.com|recaptcha|hcaptcha|captcha-delivery\.com|_incapsula_resource|js\.stripe\.com|newrelic\.com|demdex\.net)`) - reIframeSkipSchemeCSGo = newLazyRegexp(`(?i)^(?:about:blank|javascript:|data:)`) - reIframeSrcValidCSGo = newLazyRegexp(`(?i)^(?:https?://|//|/[A-Za-z0-9_.-])`) - reHiddenStyleCSGo = newLazyRegexp(`(?i)(?:display\s*:\s*none|visibility\s*:\s*hidden)`) - reHiddenBoolAttrCSGo = newLazyRegexp(`(?i)(?:^|\s)hidden(?:\s*=\s*(?:""|''|"true"|'true'|"hidden"|'hidden'|true|hidden))?(?:\s|$)`) - reSimpleTagAttrCSGo = newLazyRegexp(`([a-zA-Z_:][a-zA-Z0-9_.:-]*)\s*(?:=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>` + "`" + `]+)))?`) - reWidgetSameHostHintCSGo = newLazyRegexp(`(?i)(?:icims|in_iframe|embed|widget|greenhouse|lever|ashby|workday|smartrecruiters|bamboohr|workable|recruitee|jobvite|taleo)`) + reNonContentIframeHostCSGo = newLazyRegexp(`(?i)(?:googletagmanager\.com|doubleclick\.net|googlesyndication\.com|google-analytics\.com|facebook\.com/tr|challenges\.cloudflare\.com|recaptcha|hcaptcha|captcha-delivery\.com|_incapsula_resource|js\.stripe\.com|newrelic\.com|demdex\.net)`) + reIframeSkipSchemeCSGo = newLazyRegexp(`(?i)^(?:about:blank|javascript:|data:)`) + reIframeSrcValidCSGo = newLazyRegexp(`(?i)^(?:https?://|//|/[A-Za-z0-9_.-])`) + reHiddenStyleCSGo = newLazyRegexp(`(?i)(?:display\s*:\s*none|visibility\s*:\s*hidden)`) + reHiddenBoolAttrCSGo = newLazyRegexp(`(?i)(?:^|\s)hidden(?:\s*=\s*(?:""|''|"true"|'true'|"hidden"|'hidden'|true|hidden))?(?:\s|$)`) + reSimpleTagAttrCSGo = newLazyRegexp(`([a-zA-Z_:][a-zA-Z0-9_.:-]*)\s*(?:=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>` + "`" + `]+)))?`) + reWidgetSameHostHintCSGo = newLazyRegexp(`(?i)(?:icims|in_iframe|embed|widget|greenhouse|lever|ashby|workday|smartrecruiters|bamboohr|workable|recruitee|jobvite|taleo)`) + reEmptyItemListingContainerCSGo = newLazyRegexp(`(?is)]*\bid\s*=\s*["']item-listing-container["'][^>]*>\s*
`) reClosedPostingCSGo = newLazyRegexp(`(?i)\b(?:this\s+(?:job|position|role|posting)\s+(?:is\s+no\s+longer|has\s+been\s+(?:filled|closed))|(?:this\s+)?job\s+board\s+(?:is\s+(?:currently\s+)?(?:disabled|unavailable)|does\s+not\s+exist)|no\s+longer\s+accepting\s+applications|position\s+has\s+been\s+filled|job\s+is\s+no\s+longer\s+(?:open|available|active)|sorry,\s*this\s+job\s+(?:opening\s+)?is\s+closed)\b`) reSoft404H1CSGo = newLazyRegexp(`(?m)^#\s+([^\n]+)`) - reNotFoundHeadingCSGo = newLazyRegexp(`(?i)\b(?:404\b|page\s+not\s+found|job\s+not\s+found|post(?:ing)?\s+not\s+found|couldn['’]t\s+find\s+(?:that|this)\s+page|page\s+doesn['’]t\s+exist)\b`) + reNotFoundHeadingCSGo = newLazyRegexp(`(?i)\b(?:404\b|(?:page|job|post(?:ing)?|plugin|module|extension)\s+not\s+found|item\s+not\s+available|couldn['’]t\s+find\s+(?:that|this)\s+page|page\s+doesn['’]t\s+exist|this\s+posting\s+has\s+been\s+(?:deleted|removed)|invalid\s+as(?:\s+specified)?|not\s+a\s+valid\s+asn)\b`) reNotFound404StatusHeadingCSGo = newLazyRegexp(`(?i)\bnot\s+found\b`) reUnambiguousErrorTitleCSGo = newLazyRegexp(`(?i)^(?:(?:error\s+)?404(?:\s*[-:|–—]\s*.*)?|(?:error\s+)?404\s*(?:page\s+)?not\s+found(?:\s*[-:|–—]\s*.*)?|page\s+not\s+found(?:\s*[-:|–—]\s*.*)?|not\s+found(?:\s*[-:|–—]\s*.*)?)$`) - reNotFoundBodyCSGo = newLazyRegexp(`(?i)\b(?:the\s+page\s+you\s+(?:requested|are\s+looking\s+for)\s+(?:could\s+not\s+be\s+found|does\s+not\s+exist)|error\s+404|we\s+can['’]t\s+seem\s+to\s+find\s+the\s+page)\b`) + reNotFoundBodyCSGo = newLazyRegexp(`(?i)\b(?:the\s+page\s+you\s+(?:requested|are\s+looking\s+for)\s+(?:could\s+not\s+be\s+found|does\s+not\s+exist)|error\s+404|we\s+can['’]t\s+seem\s+to\s+find\s+the\s+page|this\s+item\s+is\s+no\s+longer\s+available|this\s+posting\s+has\s+been\s+(?:deleted|removed)|invalid\s+as(?:\s+specified)?|not\s+a\s+valid\s+asn)\b`) reForumStatusSoft404CSGo = newLazyRegexp(`(?is)(?:\bvbulletin\s+message\b.{0,200}?\b(?:no|invalid)\s+(?:thread|forum|post)\s+specified\b|\bthe\s+discussion\s+you\s+requested\s+could\s+not\s+be\s+found\b)`) reStatusPageNotFoundJSONCSGo = newLazyRegexp(`(?is)"error"\s*:\s*"status page not found"`) reMetaErrorPageDescCSGo = newLazyRegexp(`(?is)]*\bcontent\s*=\s*["'][^"']{0,200}\berror\s+page\b[^"']*["']`) @@ -102,11 +101,11 @@ var ( // Present-tense site maintenance notice. The subject must be the site/service itself (or "we"), so news about a // bridge or road "down for maintenance" and how-to maintenance articles do not match; future-tense notices // ("will undergo maintenance on Saturday") never match because a present-tense verb is required. - reMaintenanceStatusCSGo = newLazyRegexp(`(?i)(?:\b(?:(?:this|our|the)\s+)?(?:site|website|web\s+site|page|service|store|shop|app|application|server|platform|portal)(?:\s+(?:is|are))?|\bwe['’]re|\bwe\s+are)\s+(?:currently\s+)?(?:(?:down\s+for|undergoing|under)\s+(?:some\s+)?(?:scheduled\s+|planned\s+)?maintenance\b|temporarily\s+unavailable\b)|\bbe\s+right\s+back\b`) + reMaintenanceStatusCSGo = newLazyRegexp(`(?i)(?:\b(?:(?:this|our|the)\s+)?(?:site|website|web\s+site|page|service|store|shop|app|application|server|platform|portal|repository|catalog)(?:\s+(?:is|are))?|\bwe['’]re|\bwe\s+are)\s+(?:currently\s+)?(?:(?:down\s+for|undergoing|under)\s+(?:some\s+)?(?:scheduled\s+|planned\s+)?maintenance\b|temporarily\s+unavailable\b)|\bbe\s+right\s+back\b`) reMaintenance503MarkersCSGo = newLazyRegexp(`(?i)\b(?:scheduled\s+maintenance|down\s+for\s+maintenance|under\s+maintenance|undergoing\s+(?:scheduled\s+|planned\s+)?maintenance|service\s+unavailable|temporarily\s+unavailable)\b`) reAccessRestricted402CSGo = newLazyRegexp(`(?i)\b(?:access\s+restricted|unable\s+to\s+allow\s+access|payment\s+required)\b`) reMaintenanceRetryCSGo = newLazyRegexp(`(?i)\b(?:check\s+back|try\s+again|back\s+(?:soon|shortly|online)|return\s+shortly)\b`) - reLoginGateCopyCSGo = newLazyRegexp(`(?i)\b(?:sign\s+in\s+to\s+(?:view|read|continue|access)|log\s+in\s+to\s+(?:view|read|continue|access)|please\s+(?:sign|log)\s+in\s+to\s+continue|create\s+a\s+free\s+account\s+to\s+continue\s+reading)\b`) + reLoginGateCopyCSGo = newLazyRegexp(`(?i)\b(?:sign\s+in\s+to\s+(?:view|read|continue|access|download|bid)|log\s*in\s+to\s+(?:view|read|continue|access|download|bid)|register\s+to\s+download|must\s+be\s+logged\s+in|login\s+required|please\s+(?:sign|log)\s+in\s+to\s+continue|create\s+a\s+free\s+account\s+to\s+continue\s+reading)\b`) reDNSNotFoundCSGo = newLazyRegexp(`(?i)\b(?:enotfound|nxdomain|dns_not_found|eai_noname)\b|no such host|name or service not known|nodename nor servname provided|domain does not exist`) reSchemeDowngradeCSGo = newLazyRegexp(`(?is)(?:scheme_downgrade|https?-to-http|scheme\s+downgrade|(?:disallowed_url|redirect).{0,140}?(?:only\s+https://|scheme\s+must\s+be\s+https|to\s+http://))`) @@ -118,8 +117,67 @@ var ( reBlockedAggregatorHostCSGo = newLazyRegexp(`(?i)(?:^|\.)(?:linkedin\.com|indeed\.com|dice\.com|startup\.jobs|glassdoor\.com|ziprecruiter\.com)$`) reSmartRecruitersAPIHostCSGo = newLazyRegexp(`(?i)^api\.smartrecruiters\.com$`) rePyPIJSONPathCSGo = newLazyRegexp(`(?i)/json/?$`) + reJSRedirectShellCSGo = newLazyRegexp(`(?is)(?:window|document|self|top)?\.?location(?:\.href)?\s*=\s*["']([^"']{1,500})["']|location\.replace\(\s*["']([^"']{1,500})["']\s*\)`) + reEmptyAppRootCSGo = newLazyRegexp(`(?is)]*>\s*`) + reEmptyDivAppIDCSGo = newLazyRegexp(`(?is)]*\bid\s*=\s*["']application["'][^>]*>\s*
`) ) +// SPA shell container ids probed by ClassifyContentState's empty-shell heuristic. +const ( + spaIDRoot = 1 << iota + spaIDApp + spaIDSiteContainer + spaIDRecapp + spaIDPortalSprawlLoader + spaIDNext + spaIDNuxt + spaIDMain + spaIDApplication + spaIDCrPortalTitle + spaIDMount00 +) + +var spaShellIDBitsCSGo = map[string]int{ + "root": spaIDRoot, "app": spaIDApp, "site-container": spaIDSiteContainer, "recapp": spaIDRecapp, + "portal-sprawl-loader": spaIDPortalSprawlLoader, "__next": spaIDNext, "__nuxt": spaIDNuxt, "main": spaIDMain, + "application": spaIDApplication, "cr-portal-title": spaIDCrPortalTitle, "mount_0_0": spaIDMount00, +} + +// spaShellIDsCSGo reports which SPA shell ids occur in lowerHTML, in one pass. A bit is set exactly when the substring +// id="" or id='' occurs, the same test as one strings.Contains per id and quote style (an id= followed by +// a quote, the value and the same quote), without rescanning the whole document for each of the 22 probes. +func spaShellIDsCSGo(lowerHTML string) int { + found := 0 + for pos := 0; ; { + rel := strings.Index(lowerHTML[pos:], "id=") + if rel < 0 { + return found + } + at := pos + rel + 3 + pos = pos + rel + 1 + if at >= len(lowerHTML) { + return found + } + q := lowerHTML[at] + if q != '"' && q != '\'' { + continue + } + end := strings.IndexByte(lowerHTML[at+1:], q) + if end < 0 || end > 32 { + continue + } + found |= spaShellIDBitsCSGo[lowerHTML[at+1:at+1+end]] + } +} + +// matchJSRedirectShellCSGo runs reJSRedirectShellCSGo only when its mandatory literal "location" is present. +func matchJSRedirectShellCSGo(window string) []string { + if indexFoldASCIICSGo(window, "location") < 0 { + return nil + } + return reJSRedirectShellCSGo.FindStringSubmatch(window) +} + func capStringBytesUTF8CSGo(s string, maxBytes int) string { if len(s) <= maxBytes { return s @@ -267,8 +325,10 @@ func countWordsUpToFromTextCSGo(text string, limit int) int { func countWordsFromHTMLCSGo(htmlFragment string) int { plain := stripTagsQuoteAwareCSGo(htmlFragment, 98_304) - plain = html.UnescapeString(plain) - plain = reNamedEntitiesCSGo.ReplaceAllString(plain, " ") + if strings.IndexByte(plain, '&') >= 0 { + plain = html.UnescapeString(plain) + plain = reNamedEntitiesCSGo.ReplaceAllString(plain, " ") + } plain = strings.TrimSpace(plain) if plain == "" { return 0 @@ -483,6 +543,158 @@ func stripVisibleHTMLDropBlocksLinearCSGo(rawHTML string) string { return sb.String() } +func stripWafDropBlocksLinearCSGo(rawHTML string, includeScript bool, dataScriptOnly bool) string { + n := len(rawHTML) + if n == 0 || strings.IndexByte(rawHTML, '<') < 0 || !strings.Contains(rawHTML, "= n { + break + } + tagIdx := -1 + var tagLen int + var closeTagLower string + c1 := rawHTML[lt+1] | 0x20 + if dataScriptOnly { + if c1 == 's' && lt+7 < n && indexFoldASCIICSGo(rawHTML[lt+1:lt+7], "script") == 0 { + tagIdx = tagScript + tagLen = 6 + closeTagLower = "= n { + break + } + after := rawHTML[afterIdx] + if after != '>' && after != ' ' && after != '\t' && after != '\n' && after != '\r' && after != '\f' && after != '/' { + pos = lt + 1 + continue + } + openEndRel := strings.IndexByte(rawHTML[afterIdx:], '>') + if openEndRel < 0 { + break + } + openEnd := afterIdx + openEndRel + 1 + if missingClose[tagIdx] { + pos = openEnd + continue + } + if dataScriptOnly && !reDataScriptAttrCSGo.MatchString(rawHTML[afterIdx:openEnd-1]) { + pos = openEnd + continue + } + searchFrom := openEnd + blockEnd := -1 + for searchFrom < n { + closeIdx := indexFoldASCIICSGoFrom(rawHTML, closeTagLower, searchFrom) + if closeIdx < 0 { + missingClose[tagIdx] = true + break + } + closeAttrStart := closeIdx + len(closeTagLower) + closeEndRel := strings.IndexByte(rawHTML[closeAttrStart:], '>') + if closeEndRel < 0 { + missingClose[tagIdx] = true + break + } + validClose := true + for k := 0; k < closeEndRel; k++ { + b := rawHTML[closeAttrStart+k] + if b != ' ' && b != '\t' && b != '\n' && b != '\r' && b != '\f' { + validClose = false + break + } + } + if validClose { + blockEnd = closeAttrStart + closeEndRel + 1 + break + } + searchFrom = closeAttrStart + } + if blockEnd < 0 { + pos = openEnd + continue + } + if lastCopy == 0 { + sb.Grow(n / 2) + } + sb.WriteString(rawHTML[lastCopy:lt]) + sb.WriteByte(' ') + lastCopy = blockEnd + pos = blockEnd + } + if lastCopy == 0 { + return rawHTML + } + sb.WriteString(rawHTML[lastCopy:]) + return sb.String() +} + func hasRichSchemaJSONLDCSGo(sample string) bool { if indexFoldASCIICSGo(sample, "ld+json") < 0 && indexFoldASCIICSGo(sample, "ld+json") < 0 && @@ -539,8 +751,31 @@ func hasRichSchemaJSONLDCSGo(sample string) bool { return false } +func hasMarkdownBlockquoteLineCSGo(text string) bool { + if strings.IndexByte(text, '>') < 0 { + return false + } + pos := 0 + n := len(text) + for pos < n { + k := pos + for k < n && k-pos < 3 && (text[k] == ' ' || text[k] == '\t') { + k++ + } + if k < n && text[k] == '>' { + return true + } + nl := strings.IndexByte(text[pos:], '\n') + if nl < 0 { + break + } + pos += nl + 1 + } + return false +} + func stripMarkdownFencesAndBlockquotesCSGo(text string) string { - if !strings.Contains(text, "```") && !strings.Contains(text, "~~~") && strings.IndexByte(text, '>') < 0 { + if !strings.Contains(text, "```") && !strings.Contains(text, "~~~") && !hasMarkdownBlockquoteLineCSGo(text) { return text } lines := strings.Split(text, "\n") @@ -728,13 +963,13 @@ func ClassifyWAFAndChallengeFull(in WAFChallengeInput) *WAFMatch { if rawBody == "" && strings.TrimSpace(in.Title) == "" { return nil } - if status >= 200 && status < 300 && len(rawBody) > 49_152 { + if (status >= 200 && status < 300 || status == 406) && len(rawBody) > 49_152 { return nil } sample := capStringBytesUTF8CSGo(rawBody, 98_304) - noComments := reWafHTMLComments.ReplaceAllString(sample, " ") - visibleClean := reVisibleDropBlocksCSGo.ReplaceAllString(noComments, " ") + noComments := stripHTMLCommentsLinearCSGo(sample) + visibleClean := stripWafDropBlocksLinearCSGo(noComments, true, false) visibleWords := countWordsFromHTMLCSGo(visibleClean) if in.RawHTML == "" && in.VisibleText != "" { if vw := countWordsFromTextCSGo(in.VisibleText); vw > visibleWords { @@ -766,26 +1001,25 @@ func ClassifyWAFAndChallengeFull(in WAFChallengeInput) *WAFMatch { } // --- Layer 3: Strip
, , 
, JSON-LD, hydration JSON, Markdown fences, & blockquotes --- - noDataScripts := reScriptBlocksCSGo.ReplaceAllStringFunc(noComments, func(full string) string { - sub := reScriptBlocksCSGo.FindStringSubmatch(full) - if len(sub) >= 2 && reDataScriptAttrCSGo.MatchString(sub[1]) { - return " " - } - return full - }) - scrubbedDom := reScrubDomBlocksCSGo.ReplaceAllString(noDataScripts, " ") + noDataScripts := stripWafDropBlocksLinearCSGo(noComments, false, true) + scrubbedDom := stripWafDropBlocksLinearCSGo(noDataScripts, false, false) scrubbed := stripMarkdownFencesAndBlockquotesCSGo(scrubbedDom) scrubbedLower := strings.ToLower(scrubbed) - title := extractRawTitle(scrubbed) + title := "" + if strings.Contains(scrubbedLower, "' { + sb.WriteByte(' ') + i = cur + 1 + removed = true + break + } + if ch == '<' { + sb.WriteString(s[i+lt : cur]) + i = cur + removed = true + break + } + cur++ + } + if !removed { + sb.WriteString(s[i+lt:]) + break + } + } + return sb.String() +} + +func isASCIIWordByteCSGo(b byte) bool { + return (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') || (b >= '0' && b <= '9') || b == '_' +} + +func containsWordBoundedPhraseCSGo(lowerText, phrase string) bool { + off := 0 + for off <= len(lowerText)-len(phrase) { + idx := strings.Index(lowerText[off:], phrase) + if idx < 0 { + return false + } + abs := off + idx + end := abs + len(phrase) + leftOK := abs == 0 || !isASCIIWordByteCSGo(lowerText[abs-1]) + rightOK := end == len(lowerText) || !isASCIIWordByteCSGo(lowerText[end]) + if leftOK && rightOK { + return true + } + off = abs + 1 + } + return false +} + +func hasAzure406ReferenceTokenCSGo(lowerPlain string) bool { + const needle = "bad request. reference:" + off := 0 + for off <= len(lowerPlain)-len(needle) { + idx := strings.Index(lowerPlain[off:], needle) + if idx < 0 { + return false + } + abs := off + idx + if abs > 0 && isASCIIWordByteCSGo(lowerPlain[abs-1]) { + off = abs + 1 + continue + } + cur := abs + len(needle) + for cur < len(lowerPlain) && lowerPlain[cur] == ' ' { + cur++ + } + refLen := 0 + for cur+refLen < len(lowerPlain) { + c := lowerPlain[cur+refLen] + if (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '.' || c == '_' || c == '-' { + refLen++ + } else { + break + } + } + if refLen >= 4 { + return true + } + off = abs + 1 + } + return false +} + +func detectAzure406WafBlockCSGo(rawBody, visibleClean string, hasAzureHdr bool) *WAFMatch { + if rawBody == "" || len(rawBody) > 16_384 { + return nil + } + words := strings.Fields(stripSimpleAngleTagsCSGo(visibleClean)) + if len(words) == 0 || len(words) >= 60 { + return nil + } + lowerPlain := strings.ToLower(strings.Join(words, " ")) + if hasAzure406ReferenceTokenCSGo(lowerPlain) { + return &WAFMatch{ + Vendor: "generic", + Category: "waf_block", + Confidence: 0.92, + Signals: []string{"dom:azure-406-reference"}, + Summary: "Azure Front Door / App Gateway WAF 406 block", + } + } + if hasAzureHdr && (containsWordBoundedPhraseCSGo(lowerPlain, "bad request") || + containsWordBoundedPhraseCSGo(lowerPlain, "not acceptable") || + containsWordBoundedPhraseCSGo(lowerPlain, "access denied") || + containsWordBoundedPhraseCSGo(lowerPlain, "request blocked")) { + return &WAFMatch{ + Vendor: "generic", + Category: "waf_block", + Confidence: 0.90, + Signals: []string{"header:x-azure-ref", "status:406"}, + Summary: "Azure Front Door / App Gateway WAF 406 block", + } + } return nil } @@ -1064,7 +1442,7 @@ func scanOpenTagsLinearCSGo(rawHTML, targetTagLower string, maxBytes int, onTag } func scanIframesInternalCSGo(rawHTML, pageURL string, anyRelativeShell bool) (IframeScanResult, bool) { - if rawHTML == "" || !strings.Contains(strings.ToLower(capStringBytesUTF8CSGo(rawHTML, maxHTMLScanCharsCSGo)), "= n { + break + } + nb := src[afterIdx] + if nb != '>' && nb != ' ' && nb != '\t' && nb != '\n' && nb != '\r' && nb != '\f' && nb != '/' { + pos = afterIdx + continue + } + depth := 1 + scan := afterIdx + endBlock := -1 + for scan < n && depth > 0 { + nextOpen := indexFoldASCIICSGoFrom(src, openNeedle, scan) + nextClose := indexFoldASCIICSGoFrom(src, closeNeedle, scan) + if nextClose < 0 { + break + } + if nextOpen >= 0 && nextOpen < nextClose { + na := nextOpen + len(openNeedle) + if na < n && (src[na] == '>' || src[na] == ' ' || src[na] == '\t' || src[na] == '\n' || src[na] == '\r' || src[na] == '\f' || src[na] == '/') { + depth++ + } + scan = na + continue + } + ca := nextClose + len(closeNeedle) + if ca < n && src[ca] != '>' && src[ca] != ' ' && src[ca] != '\t' && src[ca] != '\n' && src[ca] != '\r' && src[ca] != '\f' { + scan = ca + continue + } + gtRel := strings.IndexByte(src[ca:], '>') + if gtRel < 0 { + break + } + depth-- + scan = ca + gtRel + 1 + if depth == 0 { + endBlock = scan + } + } + if endBlock < 0 { + pos = afterIdx + continue + } + if lastCopy == 0 { + outsideSb.Grow(n) + } + insideSb.WriteString(src[rel:endBlock]) + insideSb.WriteByte(' ') + outsideSb.WriteString(src[lastCopy:rel]) + outsideSb.WriteByte(' ') + lastCopy = endBlock + pos = endBlock } - low := strings.ToLower(capStringBytesUTF8CSGo(trimmed, 8_192)) - if strings.Contains(low, " 0 - case []any: - return len(tv) > 0 - case bool: - return tv - default: +func hasDivWithClassSubstrCSGo(src, classSubLower string) bool { + if src == "" || indexFoldASCIICSGo(src, classSubLower) < 0 { return false } + found := false + scanOpenTagsLinearCSGo(src, "div", maxHTMLScanCharsCSGo, func(attrs string) bool { + cls := readSimpleTagAttrCSGo(attrs, "class") + if indexFoldASCIICSGo(cls, classSubLower) >= 0 { + found = true + return false + } + return true + }) + return found } -func isAPIErrorJSONNestedResultCSGo(m map[string]any, depth int) (hasErr bool, hasData bool) { - if len(m) == 0 || depth > 3 { - return false, false +func stripDivsWithClassSubstrCSGo(src, classSubLower string) string { + if src == "" || indexFoldASCIICSGo(src, classSubLower) < 0 { + return src } - for k, v := range m { - lk := strings.ToLower(k) - if lk == "error" || lk == "errors" || lk == "err" || lk == "errormessage" || lk == "webserviceerror" { - if isNonEmptyJSONErrorValCSGo(v) { - hasErr = true - } - continue + var sb strings.Builder + lastCopy := 0 + pos := 0 + n := len(src) + for pos < n { + rel := indexFoldASCIICSGoFrom(src, "= n { + break + } + nb := src[after] + if nb != '>' && nb != ' ' && nb != '\t' && nb != '\n' && nb != '\r' && nb != '\f' && nb != '/' { + pos = after continue } - if lk == "results" || lk == "result" || lk == "response" { - if arr, ok := v.([]any); ok && len(arr) > 0 { + gtRel := strings.IndexByte(src[after:], '>') + if gtRel < 0 { + break + } + openEnd := after + gtRel + 1 + cls := readSimpleTagAttrCSGo(src[after:openEnd-1], "class") + if indexFoldASCIICSGo(cls, classSubLower) < 0 { + pos = openEnd + continue + } + depth := 1 + scan := openEnd + endBlock := -1 + for scan < n && depth > 0 { + nextOpen := indexFoldASCIICSGoFrom(src, "= 0 && nextOpen < nextClose { + na := nextOpen + 4 + if na < n && (src[na] == '>' || src[na] == ' ' || src[na] == '\t' || src[na] == '\n' || src[na] == '\r' || src[na] == '\f' || src[na] == '/') { + depth++ + } + scan = na + continue + } + ca := nextClose + 5 + cgtRel := strings.IndexByte(src[ca:], '>') + if cgtRel < 0 { + break + } + depth-- + scan = ca + cgtRel + 1 + if depth == 0 { + endBlock = scan + } + } + if endBlock < 0 { + pos = openEnd + continue + } + if lastCopy == 0 { + sb.Grow(n) + } + sb.WriteString(src[lastCopy:rel]) + sb.WriteByte(' ') + lastCopy = endBlock + pos = endBlock + } + if lastCopy == 0 { + return src + } + sb.WriteString(src[lastCopy:]) + return sb.String() +} + +func splitMainPrePostCSGo(src string) (mainInside, preMainOutside, postMainOutside string, found bool) { + if src == "" || indexFoldASCIICSGo(src, "= n { + break + } + nb := src[afterIdx] + if nb != '>' && nb != ' ' && nb != '\t' && nb != '\n' && nb != '\r' && nb != '\f' && nb != '/' { + pos = afterIdx + continue + } + depth := 1 + scan := afterIdx + endBlock := -1 + for scan < n && depth > 0 { + nextOpen := indexFoldASCIICSGoFrom(src, openNeedle, scan) + nextClose := indexFoldASCIICSGoFrom(src, closeNeedle, scan) + if nextClose < 0 { + break + } + if nextOpen >= 0 && nextOpen < nextClose { + na := nextOpen + len(openNeedle) + if na < n && (src[na] == '>' || src[na] == ' ' || src[na] == '\t' || src[na] == '\n' || src[na] == '\r' || src[na] == '\f' || src[na] == '/') { + depth++ + } + scan = na + continue + } + ca := nextClose + len(closeNeedle) + if ca < n && src[ca] != '>' && src[ca] != ' ' && src[ca] != '\t' && src[ca] != '\n' && src[ca] != '\r' && src[ca] != '\f' { + scan = ca + continue + } + gtRel := strings.IndexByte(src[ca:], '>') + if gtRel < 0 { + break + } + depth-- + scan = ca + gtRel + 1 + if depth == 0 { + endBlock = scan + } + } + if endBlock < 0 { + pos = afterIdx + continue + } + insideSb.WriteString(src[rel:endBlock]) + insideSb.WriteByte(' ') + if matched == 0 { + preSb.WriteString(src[lastCopy:rel]) + } else { + postSb.WriteString(src[lastCopy:rel]) + postSb.WriteByte(' ') + } + matched++ + lastCopy = endBlock + pos = endBlock + } + if matched == 0 { + return "", src, "", false + } + postSb.WriteString(src[lastCopy:]) + return insideSb.String(), preSb.String(), postSb.String(), true +} + +func hasNonHeaderPasswordInputCSGo(cleanVisibleHTML string) bool { + if cleanVisibleHTML == "" || indexFoldASCIICSGo(cleanVisibleHTML, "password") < 0 { + return false + } + stripped := stripBalancedTagBlocksCSGo(cleanVisibleHTML, "header") + stripped = stripBalancedTagBlocksCSGo(stripped, "nav") + return hasPasswordInputLinearCSGo(stripped) +} + +func isPublicBidHeaderOnlyPasswordCSGo(cleanVisibleHTML string) bool { + if cleanVisibleHTML == "" || indexFoldASCIICSGo(cleanVisibleHTML, "mets-field") < 0 { + return false + } + var bodyOnly string + mainInside, preMainOutside, postMainOutside, hasMain := splitMainPrePostCSGo(cleanVisibleHTML) + if hasMain { + if hasPasswordInputLinearCSGo(mainInside) || hasDivWithClassSubstrCSGo(mainInside, "loginwindow") { + return false + } + preOutside := stripBalancedTagBlocksCSGo(preMainOutside, "header") + preOutside = stripBalancedTagBlocksCSGo(preOutside, "nav") + preOutside = stripDivsWithClassSubstrCSGo(preOutside, "loginwindow") + postOutside := stripBalancedTagBlocksCSGo(postMainOutside, "header") + postOutside = stripBalancedTagBlocksCSGo(postOutside, "nav") + bodyOnly = mainInside + " " + preOutside + " " + postOutside + } else { + bodyOnly = stripBalancedTagBlocksCSGo(cleanVisibleHTML, "header") + bodyOnly = stripBalancedTagBlocksCSGo(bodyOnly, "nav") + } + if hasPasswordInputLinearCSGo(bodyOnly) { + return false + } + if indexFoldASCIICSGo(bodyOnly, "mets-field") < 0 { + return false + } + // Require a non-empty non-login

solicitation heading in the main body. + hasValidH1 := false + for _, m := range reH1BlockCSGo.FindAllStringSubmatch(capStringBytesUTF8CSGo(bodyOnly, 65_536), 6) { + h1Text := strings.TrimSpace(html.UnescapeString(stripTagsQuoteAwareCSGo(m[1], 4096))) + if h1Text != "" && !reLoginGateHeadingCSGo.MatchString(h1Text) { + hasValidH1 = true + break + } + } + if !hasValidH1 { + return false + } + lowBodyText := strings.ToLower(html.UnescapeString(stripTagsQuoteAwareCSGo(capStringBytesUTF8CSGo(bodyOnly, 65_536), 65_536))) + collapsedBodyText := strings.Join(strings.Fields(lowBodyText), " ") + for _, phrase := range []string{ + "register to download", + "must be logged in", + "sign in to view", + "log in to view", + "login to view", + "sign in to download", + "log in to download", + "login to download", + "sign in to bid", + "log in to bid", + "login to bid", + "login required", + } { + if strings.Contains(collapsedBodyText, phrase) { + return false + } + } + return true +} + +func isSamlLoginWithPasswordCSGo(finalURL, rawHTML, precomputedVisible string) bool { + if rawHTML == "" { + return false + } + boundedRaw := capStringBytesUTF8CSGo(rawHTML, maxHTMLScanCharsCSGo) + if indexFoldASCIICSGo(boundedRaw, "password") < 0 { + return false + } + hasSamlURL := indexFoldASCIICSGo(finalURL, "/idp/profile/saml2/") >= 0 || + indexFoldASCIICSGo(finalURL, "/saml2/") >= 0 || + indexFoldASCIICSGo(finalURL, "samlrequest") >= 0 + hasSamlRaw := hasSamlURL || + indexFoldASCIICSGo(boundedRaw, "samlrequest") >= 0 || + indexFoldASCIICSGo(boundedRaw, "/idp/profile/saml2/") >= 0 || + indexFoldASCIICSGo(boundedRaw, "/saml2/") >= 0 + if !hasSamlRaw { + return false + } + visible := precomputedVisible + if visible == "" { + visible = stripVisibleHTMLDropBlocksLinearCSGo(boundedRaw) + } + if !hasPasswordInputLinearCSGo(visible) { + return false + } + if !hasSamlURL && + indexFoldASCIICSGo(visible, "samlrequest") < 0 && + indexFoldASCIICSGo(visible, "/idp/profile/saml2/") < 0 && + indexFoldASCIICSGo(visible, "/saml2/") < 0 { + return false + } + return !hasRichSchemaJSONLDCSGo(boundedRaw) +} + +func hasNonEmptyElementMatchingCSGo(rawHTML string, matchTagAndAttrs func(tagLower, attrs string) bool) bool { + if rawHTML == "" { + return false + } + src := stripVisibleHTMLDropBlocksLinearCSGo(capStringBytesUTF8CSGo(rawHTML, maxHTMLScanCharsCSGo)) + n := len(src) + pos := 0 + for pos < n { + relLt := strings.IndexByte(src[pos:], '<') + if relLt < 0 { + break + } + lt := pos + relLt + if lt+2 >= n { + break + } + if src[lt+1] == '!' && lt+3 < n && src[lt+2] == '-' && src[lt+3] == '-' { + relEnd := strings.Index(src[lt+4:], "-->") + if relEnd < 0 { + break + } + pos = lt + 4 + relEnd + 3 + continue + } + if src[lt+1] == '/' || src[lt+1] == '!' || src[lt+1] == '?' { + pos = lt + 1 + continue + } + nameStart := lt + 1 + nameEnd := nameStart + for nameEnd < n { + c := src[nameEnd] + if !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '_') { + break + } + nameEnd++ + } + if nameEnd == nameStart || nameEnd >= n { + pos = lt + 1 + continue + } + after := src[nameEnd] + if after != '>' && after != ' ' && after != '\t' && after != '\n' && after != '\r' && after != '\f' && after != '/' { + pos = lt + 1 + continue + } + tagLower := strings.ToLower(src[nameStart:nameEnd]) + cur := nameEnd + var quote byte + openEnd := -1 + for cur < n { + ch := src[cur] + if quote != 0 { + if ch == quote { + quote = 0 + } + } else if ch == '"' || ch == '\'' { + quote = ch + } else if ch == '>' { + openEnd = cur + 1 + break + } + cur++ + } + if openEnd < 0 { + break + } + attrEnd := openEnd - 1 + if attrEnd > nameEnd && src[attrEnd-1] == '/' { + pos = openEnd + continue + } + attrs := src[nameEnd:attrEnd] + if !matchTagAndAttrs(tagLower, attrs) { + pos = openEnd + continue + } + innerLimit := openEnd + 131_072 + if innerLimit > n { + innerLimit = n + } + openNeedle := "<" + tagLower + closeNeedle := " 0 { + nextOpen := indexFoldASCIICSGoFrom(src[:innerLimit], openNeedle, scan) + nextClose := indexFoldASCIICSGoFrom(src[:innerLimit], closeNeedle, scan) + if nextClose < 0 { + break + } + if nextOpen >= 0 && nextOpen < nextClose { + na := nextOpen + len(openNeedle) + if na < innerLimit && (src[na] == '>' || src[na] == ' ' || src[na] == '\t' || src[na] == '\n' || src[na] == '\r' || src[na] == '\f' || src[na] == '/') { + oc := na + var oq byte + oEnd := -1 + for oc < innerLimit { + ch := src[oc] + if oq != 0 { + if ch == oq { + oq = 0 + } + } else if ch == '"' || ch == '\'' { + oq = ch + } else if ch == '>' { + oEnd = oc + 1 + break + } + oc++ + } + if oEnd > 0 { + if src[oEnd-2] != '/' { + depth++ + } + scan = oEnd + continue + } + } + scan = na + continue + } + ca := nextClose + len(closeNeedle) + if ca < innerLimit && src[ca] != '>' && src[ca] != ' ' && src[ca] != '\t' && src[ca] != '\n' && src[ca] != '\r' && src[ca] != '\f' { + scan = ca + continue + } + gtRel := strings.IndexByte(src[ca:innerLimit], '>') + if gtRel < 0 { + break + } + depth-- + if depth == 0 { + innerEnd = nextClose + break + } + scan = ca + gtRel + 1 + } + if innerEnd > openEnd { + inner := src[openEnd:innerEnd] + plain := stripTagsQuoteAwareCSGo(inner, 65_536) + plain = html.UnescapeString(plain) + plain = strings.TrimSpace(plain) + if plain != "" { + return true + } + } + pos = openEnd + } + return false +} + +func hasLaserficheDocumentRowsCSGo(boundedRaw string) bool { + if indexFoldASCIICSGo(boundedRaw, "ocrtext") >= 0 || + indexFoldASCIICSGo(boundedRaw, "metadatapanel") >= 0 || + indexFoldASCIICSGo(boundedRaw, "doctext") >= 0 { + if hasNonEmptyElementMatchingCSGo(boundedRaw, func(tagLower, attrs string) bool { + if tagLower != "div" && tagLower != "span" && tagLower != "p" && tagLower != "section" && tagLower != "td" { + return false + } + if indexFoldASCIICSGo(attrs, "ocrtext") < 0 && + indexFoldASCIICSGo(attrs, "metadatapanel") < 0 && + indexFoldASCIICSGo(attrs, "doctext") < 0 { + return false + } + id := strings.ToLower(readSimpleTagAttrCSGo(attrs, "id")) + if id == "ocrtext" || id == "metadatapanel" { + return true + } + cls := strings.ToLower(readSimpleTagAttrCSGo(attrs, "class")) + for _, tok := range strings.Fields(cls) { + if tok == "doctext" { + return true + } + } + return false + }) { + return true + } + } + hasDocLink := false + scanOpenTagsLinearCSGo(boundedRaw, "a", maxHTMLScanCharsCSGo, func(attrs string) bool { + href := strings.ToLower(readSimpleTagAttrCSGo(attrs, "href")) + if strings.Contains(href, "docview.aspx") || strings.Contains(href, "electronicfile.aspx") { + hasDocLink = true + return false + } + return true + }) + return hasDocLink +} + +func isLaserficheEmptyShellCSGo(finalURL, rawHTML string) bool { + if rawHTML == "" { + return false + } + boundedRaw := capStringBytesUTF8CSGo(rawHTML, maxHTMLScanCharsCSGo) + if (strings.Contains(boundedRaw, "STR_ERROR_PAGE_TITLE") || strings.Contains(boundedRaw, "INDEX_COOKIE_WARNING")) && + !hasRichSchemaJSONLDCSGo(boundedRaw) { + return true + } + if strings.Contains(boundedRaw, "STR_VIDEO_LINK_DESCRIPTION") && + !hasLaserficheDocumentRowsCSGo(boundedRaw) && + !hasRichSchemaJSONLDCSGo(boundedRaw) { + return true + } + if indexFoldASCIICSGo(finalURL, "/weblink/") >= 0 && + (indexFoldASCIICSGo(finalURL, "cookiecheck.aspx") >= 0 || + indexFoldASCIICSGo(finalURL, "?cr=1") >= 0 || + indexFoldASCIICSGo(finalURL, "&cr=1") >= 0) { + return !hasLaserficheDocumentRowsCSGo(boundedRaw) + } + return false +} + +func hasNonEmptyH1CSGo(cleanVisibleHTML string) bool { + if cleanVisibleHTML == "" || indexFoldASCIICSGo(cleanVisibleHTML, "= 0 || indexFoldASCIICSGo(vis, "= 0 { + vis = stripWafDropBlocksLinearCSGo(vis, false, false) + } + if indexFoldASCIICSGo(vis, "log in to pcl") < 0 && indexFoldASCIICSGo(vis, "log in to pacer systems") < 0 { + return false + } + if hasPasswordInputLinearCSGo(vis) || + strings.Contains(lowURL, "pcl.uscourts.gov") || + strings.Contains(lowURL, "pacer.login.uscourts.gov") || + words < 200 || + indexFoldASCIICSGo(title, "pacer") >= 0 { + return true + } + return false + } + if strings.Contains(lowURL, "pcl.uscourts.gov") || strings.Contains(lowURL, "pacer.login.uscourts.gov") { + return indexFoldASCIICSGo(proseOnly, "log in to pcl") >= 0 || indexFoldASCIICSGo(proseOnly, "log in to pacer systems") >= 0 + } + return false +} + +func hasNonEmptySpanOrDivIDCSGo(boundedRaw, idNeedleLower string) bool { + if boundedRaw == "" || idNeedleLower == "" || indexFoldASCIICSGo(boundedRaw, idNeedleLower) < 0 { + return false + } + return hasNonEmptyElementMatchingCSGo(boundedRaw, func(tagLower, attrs string) bool { + if tagLower != "span" && tagLower != "div" { + return false + } + if indexFoldASCIICSGo(attrs, idNeedleLower) < 0 { + return false + } + id := strings.ToLower(readSimpleTagAttrCSGo(attrs, "id")) + return id != "" && strings.Contains(id, idNeedleLower) + }) +} + +func isAccelaEmptyShellCSGo(finalURL, rawHTML, title string) bool { + if rawHTML == "" { + return false + } + boundedRaw := capStringBytesUTF8CSGo(rawHTML, maxHTMLScanCharsCSGo) + isAccelaHostOrPath := indexFoldASCIICSGo(finalURL, "accela.com") >= 0 || + indexFoldASCIICSGo(finalURL, "/citizenaccess/") >= 0 + isAccelaTitle := indexFoldASCIICSGo(title, "accela citizen access") >= 0 || + indexFoldASCIICSGo(boundedRaw, "accela citizen access") >= 0 + isDefaultAspx := indexFoldASCIICSGo(finalURL, "/default.aspx") >= 0 + hasMsgBar := indexFoldASCIICSGo(boundedRaw, "message bar") >= 0 + hasAspNetForm := indexFoldASCIICSGo(boundedRaw, "aspnetform") >= 0 + hasAccelaMarker := isAccelaHostOrPath || isAccelaTitle || + (hasAspNetForm && hasMsgBar && indexFoldASCIICSGo(boundedRaw, "accela") >= 0) + + if !(hasAccelaMarker && (isDefaultAspx || (hasMsgBar && hasAspNetForm))) { + return false + } + if hasNonEmptySpanOrDivIDCSGo(boundedRaw, "lblpermitnumber") || + hasNonEmptySpanOrDivIDCSGo(boundedRaw, "lblpermittype") || + hasNonEmptySpanOrDivIDCSGo(boundedRaw, "divworklocation") || + hasNonEmptySpanOrDivIDCSGo(boundedRaw, "divprojectdescription") || + hasRichSchemaJSONLDCSGo(boundedRaw) { + return false + } + return true +} + +func hasAnubisPoWMarkersCSGo(lowerBody string) bool { + if lowerBody == "" { + return false + } + hasPhrase := strings.Contains(lowerBody, "making sure you're not a bot") || + strings.Contains(lowerBody, "making sure you're not a bot") || + strings.Contains(lowerBody, "making sure you're not a bot") + hasScriptOrAsset := strings.Contains(lowerBody, `id="anubis_version"`) || + strings.Contains(lowerBody, `id='anubis_version'`) || + strings.Contains(lowerBody, `id="anubis_challenge"`) || + strings.Contains(lowerBody, `id='anubis_challenge'`) || + strings.Contains(lowerBody, "/.within.website/x/xess/") + if hasPhrase && (strings.Contains(lowerBody, "anubis") || hasScriptOrAsset) { + return true + } + return hasScriptOrAsset && strings.Contains(lowerBody, "/.within.website/x/xess/") && + (strings.Contains(lowerBody, `id="anubis_version"`) || strings.Contains(lowerBody, `id='anubis_version'`) || + strings.Contains(lowerBody, `id="anubis_challenge"`) || strings.Contains(lowerBody, `id='anubis_challenge'`)) +} + +func hasHashcashPoWMarkersCSGo(lowerBody string) bool { + if lowerBody == "" { + return false + } + if strings.Contains(lowerBody, "/__challenge/challenge.js") { + return true + } + if !strings.Contains(lowerBody, "") + if endRel < 0 { + sb.WriteString(s[pos:]) + break + } + sb.WriteString(s[pos:start]) + sb.WriteByte(' ') + pos = start + 4 + endRel + 3 + } + return sb.String() +} + +func stripVisibleSoft404NoiseCSGo(cleanVisibleHTML string) string { + stripped := stripHTMLCommentsLinearCSGo(cleanVisibleHTML) + if indexFoldASCIICSGo(stripped, "= 0 { + stripped = reHeadBlockCSGo.ReplaceAllString(stripped, " ") + } + if indexFoldASCIICSGo(stripped, "= 0 || + indexFoldASCIICSGo(stripped, "= 0 || + indexFoldASCIICSGo(stripped, "= 0 || + indexFoldASCIICSGo(stripped, "= 0 { + stripped = stripWafDropBlocksLinearCSGo(stripped, false, false) + } + return stripped +} + +func isNonEmptyJSONErrorValCSGo(v any) bool { + switch tv := v.(type) { + case string: + return strings.TrimSpace(tv) != "" + case map[string]any: + return len(tv) > 0 + case []any: + return len(tv) > 0 + case bool: + return tv + default: + return false + } +} + +func isAPIErrorJSONNestedResultCSGo(m map[string]any, depth int) (hasErr bool, hasData bool) { + if len(m) == 0 || depth > 3 { + return false, false + } + for k, v := range m { + lk := strings.ToLower(k) + if lk == "error" || lk == "errors" || lk == "err" || lk == "errormessage" || lk == "webserviceerror" { + if isNonEmptyJSONErrorValCSGo(v) { + hasErr = true + } + continue + } + if lk == "message" || lk == "status" || lk == "queryrows" || lk == "count" || lk == "code" { + continue + } + if lk == "results" || lk == "result" || lk == "response" { + if arr, ok := v.([]any); ok && len(arr) > 0 { return false, true } if sub, ok := v.(map[string]any); ok && len(sub) > 0 { @@ -1579,6 +2788,10 @@ func isAPIErrorJSONShellCSGo(raw string) bool { return false } if m, ok := v.(map[string]any); ok && len(m) > 0 { + if failed, okFail := m["failed"].(bool); okFail && failed { + hasErr = true + continue + } // WordPress REST errors use {"code":"rest_*","message":"...","data":{"status":404}} if stNum, okSt := m["status"].(float64); okSt && stNum >= 400 && stNum <= 599 && len(m) <= 3 { nestedComplex := false @@ -1624,10 +2837,28 @@ func isAPIErrorJSONShellCSGo(raw string) bool { hasProblemStatus = true } } + if lk == "information" || lk == "note" { + if s, ok := v.(string); ok && len(obj) == 1 { + ls := strings.ToLower(s) + if strings.Contains(ls, "rate limit") || + strings.Contains(ls, "api key") || + strings.Contains(ls, "alpha vantage") || + strings.Contains(ls, "call frequency") { + hasProblemIdentity = true + hasErr = true + } + } + } if lk == "type" || lk == "title" || lk == "message" || lk == "detail" || lk == "description" { if s, ok := v.(string); ok && strings.TrimSpace(s) != "" { hasProblemIdentity = true ls := strings.ToLower(s) + if lk == "message" && len(obj) <= 2 && + (strings.HasPrefix(strings.TrimSpace(ls), "403 forbidden") || + strings.HasPrefix(strings.TrimSpace(ls), "401 unauthorized") || + strings.HasPrefix(strings.TrimSpace(ls), "missing authentication token")) { + hasErr = true + } if reNotFoundBodyCSGo.MatchString(s) || strings.Contains(ls, "not found") || strings.Contains(ls, "does not exist") || @@ -1658,8 +2889,24 @@ func isXMLShortErrorShellCSGo(raw string) bool { return strings.Contains(low, "") } +func hasSecurityTxtContactCSGo(raw string) bool { + for _, line := range strings.Split(raw, "\n") { + clean := strings.TrimSpace(strings.TrimPrefix(line, "\uFEFF")) + if clean == "" || strings.HasPrefix(clean, "#") { + continue + } + if len(clean) >= 8 && strings.EqualFold(clean[:8], "contact:") && strings.TrimSpace(clean[8:]) != "" { + return true + } + } + return false +} + func isEmptyJSONResponseShellCSGo(raw string) bool { - trimmed := strings.TrimSpace(raw) + trimmed := strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(raw), "\uFEFF")) + if strings.HasPrefix(trimmed, ")]}'") { + trimmed = strings.TrimSpace(trimmed[4:]) + } if len(trimmed) < 2 || len(trimmed) > 8192 || (trimmed[0] != '{' && trimmed[0] != '[') { return false } @@ -1688,21 +2935,31 @@ func isEmptyJSONResponseShellCSGo(raw string) bool { } for k, val := range tv { lk := strings.ToLower(k) + if lk == "type" { + if s, ok := val.(string); ok && strings.EqualFold(strings.TrimSpace(s), "FeatureCollection") { + continue + } + } isPaginationIndex := lk == "page" || lk == "pages" || lk == "per_page" || - lk == "limit" || lk == "offset" || lk == "skip" || lk == "top" + lk == "limit" || lk == "offset" || lk == "skip" || lk == "top" || lk == "start" || + lk == "status-code" || lk == "status_code" isMetaKey := inMeta || isPaginationIndex || lk == "meta" || lk == "metadata" || lk == "pagination" || - lk == "total" || lk == "totalrecords" || lk == "total_records" || lk == "total-count" || + lk == "total" || lk == "@total" || lk == "totalrecords" || lk == "total_records" || lk == "total-count" || lk == "total_count" || lk == "totalpages" || lk == "recordcount" || lk == "hit_count" || lk == "num_results" || lk == "resultcount" || lk == "section" || lk == "searchresultcount" || lk == "searchresultcountall" || lk == "totalcount" || lk == "totalitems" || lk == "total_items" || lk == "totalgames" || lk == "total_games" || lk == "totalelements" || lk == "total_elements" || + lk == "numbermatched" || lk == "numberreturned" || + lk == "next" || lk == "previous" || lk == "@odata.context" || lk == "count" || lk == "value" || lk == "api_version" || lk == "version" || lk == "status" - isContainerKey := lk == "hits" || lk == "results" || lk == "data" || lk == "items" || + isContainerKey := lk == "hits" || lk == "result" || lk == "results" || lk == "response" || lk == "data" || lk == "items" || lk == "records" || lk == "rows" || lk == "organizations" || lk == "opportunitiesdata" || lk == "recdata" || lk == "idgroup" || lk == "features" || lk == "docs" || lk == "entries" || lk == "feeds" || lk == "products" || lk == "itemsummaries" || + lk == "vulnerabilities" || lk == "playlist" || lk == "media" || lk == "searchresult" || lk == "searchresultitems" || + lk == "getpressreleaselistresult" || lk == "geteventlistresult" || lk == "_embedded" _, isEmptySlice := val.([]any) isEmptyArrVal := isEmptySlice && len(val.([]any)) == 0 @@ -1735,6 +2992,26 @@ func isEmptyJSONResponseShellCSGo(raw string) bool { return hasEmptyContainer && !hasContent } +func isEmptySDNListShellCSGo(raw string) bool { + trimmed := strings.TrimSpace(strings.TrimLeft(strings.TrimSpace(raw), "\uFEFF")) + if len(trimmed) == 0 || len(trimmed) > 65536 || trimmed[0] != '<' { + return false + } + headLen := len(trimmed) + if headLen > 4096 { + headLen = 4096 + } + head := strings.ToLower(trimmed[:headLen]) + if !strings.Contains(head, " 8192 || trimmed[0] != '<' { @@ -1747,9 +3024,15 @@ func isEmptyXMLFeedShellCSGo(raw string) bool { if strings.Contains(low, "") && !strings.Contains(low, "") && !strings.Contains(low, ", so + // scan it at most once instead of once per heuristic (each scan is O(N) over up to maxHTMLScanCharsCSGo bytes). + cleanH1State := 0 // 0 = not yet scanned, 1 = no

, 2 = non-empty

+ cleanHasNonEmptyH1 := func() bool { + if cleanH1State == 0 { + cleanH1State = 1 + if hasNonEmptyH1CSGo(cleanVisibleHTML) { + cleanH1State = 2 + } + } + return cleanH1State == 2 + } + // Same for the visible-HTML word count, which many thin-shell heuristics consult. + cleanWordCount := -1 + cleanVisibleWordCount := func() int { + if cleanWordCount < 0 { + cleanWordCount = countWordsFromHTMLCSGo(cleanVisibleHTML) + } + return cleanWordCount + } topProse := capStringBytesUTF8CSGo(proseOnly, 900) topSlice := title + "\n" + topProse @@ -1911,7 +3228,7 @@ func ClassifyContentState(status int, rawHTML, markdown, finalURL, title string) // 2. Soft-404 check (unambiguous 404/not-found even with >= 120 words of nav chrome, OR HTTP 2xx/404/410 with compact < 120-word body & 404/not-found title/H1 or < 60-word not-found body) if (status >= 200 && status < 300) || status == 404 || status == 410 { trimmedTitle := strings.TrimSpace(title) - if trimmedTitle != "" && reUnambiguousErrorTitleCSGo.MatchString(trimmedTitle) { + if trimmedTitle != "" && (reUnambiguousErrorTitleCSGo.MatchString(trimmedTitle) || strings.EqualFold(trimmedTitle, "Page not found | AppFolio")) { return ContentStateResult{ State: "soft_404", Reason: "HTTP " + strconv.Itoa(status) + " response has an unambiguous 404/Not Found <title>.", @@ -1919,10 +3236,10 @@ func ClassifyContentState(status int, rawHTML, markdown, finalURL, title string) } } } - if ((status >= 200 && status < 300) || status == 401 || status == 404 || status == 410 || (status >= 500 && status <= 599)) && words < 120 { + if ((status >= 200 && status < 300) || status == 400 || status == 401 || status == 403 || status == 404 || status == 410 || (status >= 500 && status <= 599)) && words < 120 { if rawHTML != "" && (isAPIErrorJSONShellCSGo(rawHTML) || isXMLShortErrorShellCSGo(rawHTML) || isStatusIOErrorJSONBody(rawHTML)) { errState := "soft_404" - if status >= 500 { + if status >= 500 || status == 403 { errState = "temporarily_unavailable" } return ContentStateResult{ @@ -1952,7 +3269,11 @@ func ClassifyContentState(status int, rawHTML, markdown, finalURL, title string) isXMLShortErrorShellCSGo(rawHTML) || (countWordsFromTextCSGo(visibleBody) < 20 && reMetaErrorPageDescCSGo.MatchString(capStringBytesUTF8CSGo(cleanVisibleHTML, 16_384)) && - reGenericErrorHeadingCSGo.MatchString(visibleBody))) { + reGenericErrorHeadingCSGo.MatchString(visibleBody)) || + (countWordsFromTextCSGo(visibleBody) < 30 && + strings.EqualFold(strings.TrimSpace(title), "Application Error") && + (strings.Contains(strings.ToLower(visibleBody), "system error") || + strings.Contains(strings.ToLower(visibleBody), "unexpected error")))) { isNotFoundBody = true } } @@ -1984,10 +3305,98 @@ func ClassifyContentState(status int, rawHTML, markdown, finalURL, title string) } } } - if (status == 503 || status == 402 || status == 403 || status == 429) && rawHTML != "" && words < 120 && + if ((status >= 200 && status < 300) || status == 403 || status == 429 || status == 445) && rawHTML != "" && words < 120 && + !hasRichSchemaJSONLDCSGo(capStringBytesUTF8CSGo(rawHTML, maxHTMLScanCharsCSGo)) { + anubisCandidate := strings.ToLower(stripWafDropBlocksLinearCSGo(capStringBytesUTF8CSGo(rawHTML, 65_536), false, false)) + if hasAnubisPoWMarkersCSGo(anubisCandidate) { + return ContentStateResult{ + State: "temporarily_unavailable", + Reason: "Anubis proof-of-work anti-bot challenge interstitial.", + Confidence: 0.92, + } + } + } + if status >= 200 && status < 300 && rawHTML != "" && words < 40 && + reCloudflareTitleFullCSGo.MatchString(strings.TrimSpace(title)) && + !hasRichSchemaJSONLDCSGo(capStringBytesUTF8CSGo(rawHTML, maxHTMLScanCharsCSGo)) { + lowCF := strings.ToLower(stripWafDropBlocksLinearCSGo(capStringBytesUTF8CSGo(rawHTML, 65_536), false, false)) + if strings.Contains(lowCF, "enable javascript and cookies to continue") || + strings.Contains(lowCF, "challenges.cloudflare.com/turnstile") || + strings.Contains(lowCF, "cf-turnstile") || + strings.Contains(lowCF, "_cf_chl_opt") || + strings.Contains(lowCF, "challenge-platform") || + strings.Contains(lowCF, "checking your browser") { + return ContentStateResult{ + State: "temporarily_unavailable", + Reason: "HTTP " + strconv.Itoa(status) + " response is a Cloudflare challenge interstitial.", + Confidence: 0.92, + } + } + } + if status >= 200 && status < 300 && rawHTML != "" && words < 80 && + !hasRichSchemaJSONLDCSGo(capStringBytesUTF8CSGo(rawHTML, maxHTMLScanCharsCSGo)) { + lowF5 := strings.ToLower(stripWafDropBlocksLinearCSGo(capStringBytesUTF8CSGo(rawHTML, 65_536), false, false)) + if strings.Contains(lowF5, "the requested url was rejected") && + strings.Contains(lowF5, "your support id is") { + return ContentStateResult{ + State: "temporarily_unavailable", + Reason: "HTTP " + strconv.Itoa(status) + " response is an F5 BIG-IP ASM WAF block page.", + Confidence: 0.92, + } + } + if words < 40 && cleanVisibleWordCount() < 40 { + lowBlockTitle := strings.ToLower(strings.TrimSpace(title)) + if lowBlockTitle == "blocked" || + strings.HasPrefix(lowBlockTitle, "warning: blocked") || + lowBlockTitle == "forbidden" || + strings.HasPrefix(lowBlockTitle, "forbidden - ") || + strings.HasPrefix(lowBlockTitle, "403 forbidden") || + lowBlockTitle == "access denied" || + strings.HasPrefix(lowBlockTitle, "access denied - ") || + strings.HasPrefix(lowBlockTitle, "access denied |") || + strings.HasPrefix(lowBlockTitle, "request blocked") { + return ContentStateResult{ + State: "temporarily_unavailable", + Reason: "HTTP " + strconv.Itoa(status) + " response is a soft-block / access-denied page.", + Confidence: 0.90, + } + } + } + if words < 25 && cleanVisibleWordCount() < 25 { + lowVisibleCS := strings.ToLower(cleanVisibleHTML) + if strings.Contains(lowF5, "bot-need-challenge") || strings.Contains(lowVisibleCS, "bot-need-challenge") { + return ContentStateResult{ + State: "temporarily_unavailable", + Reason: "HTTP " + strconv.Itoa(status) + " response is an anti-bot challenge interstitial (bot-need-challenge).", + Confidence: 0.90, + } + } + if (strings.Contains(lowF5, "missing authentication token") || strings.Contains(lowVisibleCS, "missing authentication token") || strings.Contains(strings.ToLower(proseOnly), "missing authentication token")) && + !strings.Contains(lowF5, "<article") && + !strings.Contains(lowF5, "<table") { + return ContentStateResult{ + State: "temporarily_unavailable", + Reason: "HTTP " + strconv.Itoa(status) + " thin response is a Missing Authentication Token gateway error shell.", + Confidence: 0.90, + } + } + } + if strings.Contains(lowF5, "/__meb_verify") || + strings.Contains(lowF5, "/_fs-ch-") || + (cleanVisibleWordCount() < 80 && hasHashcashPoWMarkersCSGo(lowF5)) || + (strings.EqualFold(strings.TrimSpace(title), "verifying your browser") && + (strings.Contains(lowF5, "verify") || strings.Contains(lowF5, "challenge"))) { + return ContentStateResult{ + State: "temporarily_unavailable", + Reason: "HTTP " + strconv.Itoa(status) + " response is a browser proof-of-work verification challenge.", + Confidence: 0.92, + } + } + } + if (status == 503 || status == 402 || status == 403 || status == 406 || status == 429) && rawHTML != "" && words < 120 && !hasRichSchemaJSONLDCSGo(capStringBytesUTF8CSGo(rawHTML, maxHTMLScanCharsCSGo)) { if status == 403 || status == 429 { - lowChallengeRaw := strings.ToLower(reScrubDomBlocksCSGo.ReplaceAllString(capStringBytesUTF8CSGo(rawHTML, maxHTMLScanCharsCSGo), " ")) + lowChallengeRaw := strings.ToLower(stripWafDropBlocksLinearCSGo(capStringBytesUTF8CSGo(rawHTML, maxHTMLScanCharsCSGo), false, false)) if strings.Contains(lowChallengeRaw, "_cf_chl_opt") || strings.Contains(lowChallengeRaw, "challenge-platform") || strings.Contains(lowChallengeRaw, "cf-turnstile") || @@ -1996,6 +3405,7 @@ func ClassifyContentState(status int, rawHTML, markdown, finalURL, title string) strings.Contains(lowChallengeRaw, "kp_uidz") || strings.Contains(lowChallengeRaw, "_incapsula_resource") || strings.Contains(lowChallengeRaw, "x-amzn-waf-action") || + (cleanVisibleWordCount() < 80 && hasHashcashPoWMarkersCSGo(lowChallengeRaw)) || reCloudflareTitleFullCSGo.MatchString(strings.TrimSpace(title)) { return ContentStateResult{ State: "temporarily_unavailable", @@ -2004,6 +3414,13 @@ func ClassifyContentState(status int, rawHTML, markdown, finalURL, title string) } } } + if status == 406 && words < 40 { + return ContentStateResult{ + State: "temporarily_unavailable", + Reason: "HTTP 406 Not Acceptable response without page content.", + Confidence: 0.90, + } + } if status == 429 && words < 40 { return ContentStateResult{ State: "temporarily_unavailable", @@ -2045,7 +3462,21 @@ func ClassifyContentState(status int, rawHTML, markdown, finalURL, title string) } } - // 3. Login-wall check (thin body < 110 words gated by sign-in prompt or password input outside scripts/templates) + // 3. Login-wall check (explicit SAML/IdP SSO password forms regardless of word count, or thin body < 110 words gated by sign-in prompt / password input) + if (status < 400 || status == 401) && rawHTML != "" && isSamlLoginWithPasswordCSGo(finalURL, rawHTML, cleanVisibleHTML) { + return ContentStateResult{ + State: "login_wall", + Reason: "SAML/IdP SSO login page with password authentication form.", + Confidence: 0.92, + } + } + if (status < 400 || status == 401) && isPacerLoginWallCSGo(finalURL, rawHTML, proseOnly, title, words) { + return ContentStateResult{ + State: "login_wall", + Reason: "PACER / PCL portal authentication wall.", + Confidence: 0.92, + } + } if words < 110 { if rawHTML != "" && isProtectedWPJSONShellCSGo(rawHTML) { return ContentStateResult{ @@ -2055,11 +3486,23 @@ func ClassifyContentState(status int, rawHTML, markdown, finalURL, title string) } } hasPasswordInput := hasPasswordInputLinearCSGo(cleanVisibleHTML) + if hasPasswordInput && isPublicBidHeaderOnlyPasswordCSGo(cleanVisibleHTML) { + hasPasswordInput = false + } trimmedTitle := strings.TrimSpace(title) hasLoginGateHeading := trimmedTitle != "" && reLoginGateHeadingCSGo.MatchString(trimmedTitle) - hasLoginGateCopy := reLoginGateCopyCSGo.MatchString(topSlice) - if hasLoginGateCopy || (hasPasswordInput && (hasLoginGateHeading || words < 65)) || - (hasLoginGateHeading && words < 20 && (cleanVisibleHTML == "" || countWordsFromHTMLCSGo(cleanVisibleHTML) < 25) && !hasRichSchemaJSONLDCSGo(capStringBytesUTF8CSGo(rawHTML, maxHTMLScanCharsCSGo))) { + loginProse := proseOnly + if len(loginProse) > 4096 { + loginProse = capStringBytesUTF8CSGo(loginProse, 4096) + } + hasLoginGateCopy := reLoginGateCopyCSGo.MatchString(title + "\n" + loginProse) + if !hasLoginGateCopy && hasPasswordInput && cleanVisibleHTML != "" { + visLoginText := html.UnescapeString(stripTagsQuoteAwareCSGo(capStringBytesUTF8CSGo(cleanVisibleHTML, 32_768), 32_768)) + hasLoginGateCopy = reLoginGateCopyCSGo.MatchString(visLoginText) + } + hasBodyOrModalPassword := hasPasswordInput && (words < 65 || hasLoginGateHeading || (hasNonHeaderPasswordInputCSGo(cleanVisibleHTML) && (indexFoldASCIICSGo(cleanVisibleHTML, "mets-field") >= 0 || hasDivWithClassSubstrCSGo(cleanVisibleHTML, "loginwindow")))) + if hasLoginGateCopy || hasBodyOrModalPassword || + (hasLoginGateHeading && words < 20 && (cleanVisibleHTML == "" || cleanVisibleWordCount() < 25) && !hasRichSchemaJSONLDCSGo(capStringBytesUTF8CSGo(rawHTML, maxHTMLScanCharsCSGo))) { return ContentStateResult{ State: "login_wall", Reason: "Content is gated behind an authentication / sign-in wall.", @@ -2067,9 +3510,18 @@ func ClassifyContentState(status int, rawHTML, markdown, finalURL, title string) } } } + if (status < 400 || status == 401) && rawHTML != "" && words < 40 && + !hasRichSchemaJSONLDCSGo(capStringBytesUTF8CSGo(rawHTML, maxHTMLScanCharsCSGo)) && + isWildApricotLoginOnlyShellCSGo(rawHTML) { + return ContentStateResult{ + State: "login_wall", + Reason: "Wild Apricot login-only gadget shell without public member or event content.", + Confidence: 0.90, + } + } if status == 403 && words < 40 && !hasRichSchemaJSONLDCSGo(capStringBytesUTF8CSGo(rawHTML, maxHTMLScanCharsCSGo)) && - (cleanVisibleHTML == "" || countWordsFromHTMLCSGo(cleanVisibleHTML) < 40) { + (cleanVisibleHTML == "" || cleanVisibleWordCount() < 40) { return ContentStateResult{ State: "temporarily_unavailable", Reason: "HTTP 403 response has an empty or WAF-only body without page content.", @@ -2092,26 +3544,194 @@ func ClassifyContentState(status int, rawHTML, markdown, finalURL, title string) Confidence: 0.90, } } - if ((status >= 200 && status < 300) || status == 404 || status == 410) && words < 120 && rawHTML != "" { - if isEmptyJSONResponseShellCSGo(rawHTML) || isEmptyXMLFeedShellCSGo(rawHTML) { + if ((status >= 200 && status < 300) || status == 404 || status == 410) && rawHTML != "" { + if (words < 120 && (isEmptyJSONResponseShellCSGo(rawHTML) || isEmptyXMLFeedShellCSGo(rawHTML))) || isEmptySDNListShellCSGo(rawHTML) { return ContentStateResult{ State: "empty_shell", Reason: "HTTP 2xx feed/JSON response has an empty result set / empty object shell.", Confidence: 0.90, } } + if words < 80 && !strings.Contains(proseOnly, "| API Key |") && strings.Contains(strings.ToLower(finalURL), "apis.guru/v2/list.json") { + trimmedPrefix := strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(rawHTML), "\uFEFF")) + if strings.HasPrefix(trimmedPrefix, "{") { + var completeObj any + if err := json.Unmarshal([]byte(trimmedPrefix), &completeObj); err != nil { + return ContentStateResult{ + State: "empty_shell", + Reason: "Truncated APIs.guru list.json prefix contains 0 complete API entries.", + Confidence: 0.90, + } + } + } + } + } + if status >= 200 && status < 300 && words < 10 { + trimmedRaw := strings.TrimSpace(rawHTML) + if trimmedRaw == "" { + trimmedRaw = strings.TrimSpace(proseOnly) + } + if trimmedRaw != "" && + strings.HasPrefix(trimmedRaw, "error=") && + !strings.HasPrefix(trimmedRaw, "error=0\n") && + !strings.HasPrefix(trimmedRaw, "error=0\r") && + trimmedRaw != "error=0" && + !strings.Contains(trimmedRaw, "<") { + return ContentStateResult{ + State: "empty_shell", + Reason: "OpenGTINdb query returned a non-zero error status without product data.", + Confidence: 0.90, + } + } + } + if status >= 200 && status < 300 && words < 80 { + if strings.Contains(proseOnly, "No matching KEV entry found for ") { + return ContentStateResult{ + State: "empty_shell", + Reason: "CISA KEV CVE filter matched 0 catalog entries.", + Confidence: 0.90, + } + } + if strings.Contains(proseOnly, "No complete API entries fit within the bounded prefix.") { + return ContentStateResult{ + State: "empty_shell", + Reason: "Truncated APIs.guru list.json prefix contains 0 complete API entries.", + Confidence: 0.90, + } + } + } + if status >= 200 && status < 300 && rawHTML != "" { + if isLaserficheEmptyShellCSGo(finalURL, rawHTML) { + return ContentStateResult{ + State: "empty_shell", + Reason: "Laserfiche WebLink cookie-check / ?cr=1 error shell without substantive document rows.", + Confidence: 0.90, + } + } + if isAccelaEmptyShellCSGo(finalURL, rawHTML, title) { + return ContentStateResult{ + State: "empty_shell", + Reason: "Accela Citizen Access Default.aspx / Message Bar shell without permit data.", + Confidence: 0.90, + } + } + } + if status >= 200 && status < 300 && words < 200 && rawHTML != "" && + indexFoldASCIICSGo(capStringBytesUTF8CSGo(rawHTML, maxHTMLScanCharsCSGo), "fallback_tracking_number") >= 0 && + indexFoldASCIICSGo(capStringBytesUTF8CSGo(rawHTML, maxHTMLScanCharsCSGo), "narvar") >= 0 { + lowCleanNarvar := strings.ToLower(cleanVisibleHTML) + if strings.Contains(lowCleanNarvar, "fallback_tracking_number") && + strings.Contains(lowCleanNarvar, "your delivery status is temporarily unavailable") { + return ContentStateResult{ + State: "empty_shell", + Reason: "Unhydrated Narvar tracking template shell (fallback_tracking_number without tracking payload).", + Confidence: 0.90, + } + } + } + if status >= 200 && status < 300 { + if secU, err := url.Parse(strings.TrimSpace(finalURL)); err == nil && + strings.HasSuffix(strings.ToLower(secU.Path), "/security.txt") { + secBody := rawHTML + if secBody == "" { + secBody = markdown + } + if secBody != "" && + !strings.Contains(strings.ToLower(secBody), "<html") && + !hasSecurityTxtContactCSGo(secBody) { + return ContentStateResult{ + State: "empty_shell", + Reason: "RFC 9116 security.txt response lacks any required Contact: directive.", + Confidence: 0.90, + } + } + } + } + if status >= 200 && status < 300 && words < 250 && rawHTML != "" && + indexFoldASCIICSGo(capStringBytesUTF8CSGo(rawHTML, 262_144), "<app-root") >= 0 { + boundedRawApp := capStringBytesUTF8CSGo(rawHTML, maxHTMLScanCharsCSGo) + if !hasRichSchemaJSONLDCSGo(boundedRawApp) { + visApp := cleanVisibleHTML + if visApp == "" { + visApp = stripVisibleHTMLDropBlocksLinearCSGo(capStringBytesUTF8CSGo(rawHTML, 262_144)) + } + lowVisApp := strings.ToLower(visApp) + hasArtOrTableApp := strings.Contains(lowVisApp, "<article") || strings.Contains(lowVisApp, "<table") + if !hasArtOrTableApp && indexFoldASCIICSGo(visApp, "<app-root") >= 0 && !hasNonEmptyH1CSGo(visApp) && reEmptyAppRootCSGo.MatchString(capStringBytesUTF8CSGo(visApp, 262_144)) { + return ContentStateResult{ + State: "empty_shell", + Reason: "Unhydrated Angular <app-root></app-root> CSR shell without rendered content.", + Confidence: 0.88, + } + } + } + } + if status >= 200 && status < 300 && words < 110 && rawHTML != "" { + boundedRaw110 := capStringBytesUTF8CSGo(rawHTML, maxHTMLScanCharsCSGo) + if !hasRichSchemaJSONLDCSGo(boundedRaw110) { + lowClean110 := strings.ToLower(cleanVisibleHTML) + hasArtOrTable := strings.Contains(lowClean110, "<article") || strings.Contains(lowClean110, "<table") + hasH1 := cleanHasNonEmptyH1() + headSample64 := capStringBytesUTF8CSGo(rawHTML, 65_536) + if words < 80 && !hasArtOrTable && !hasH1 && strings.Contains(headSample64, "<!-- layout: page-react.html -->") { + return ContentStateResult{ + State: "empty_shell", + Reason: "Unhydrated React layout shell (page-react.html) without heading or article content.", + Confidence: 0.88, + } + } + if indexFoldASCIICSGo(cleanVisibleHTML, "item-listing-container") >= 0 && + reEmptyItemListingContainerCSGo.MatchString(capStringBytesUTF8CSGo(cleanVisibleHTML, 262_144)) && + (indexFoldASCIICSGo(boundedRaw110, "ko.hoganTemplateEngine") >= 0 || + strings.Contains(lowClean110, "there are no items matching the current filter")) { + return ContentStateResult{ + State: "empty_shell", + Reason: "Unhydrated Cision KnockoutJS listing shell (#item-listing-container empty).", + Confidence: 0.88, + } + } + headSample8 := capStringBytesUTF8CSGo(rawHTML, 8_192) + if words < 40 && (indexFoldASCIICSGo(headSample8, `data-ng-app="app.main"`) >= 0 || + indexFoldASCIICSGo(headSample8, `data-ng-app='app.main'`) >= 0 || + indexFoldASCIICSGo(headSample8, `ng-app="app.main"`) >= 0 || + indexFoldASCIICSGo(headSample8, `ng-app='app.main'`) >= 0) { + nonNavVis := stripBalancedTagBlocksCSGo(stripBalancedTagBlocksCSGo(cleanVisibleHTML, "header"), "nav") + if (countWordsFromHTMLCSGo(nonNavVis) < 25 && !hasH1) || + strings.Contains(lowClean110, "welcome to portal home") || + strings.Contains(lowClean110, "{{vm.") { + return ContentStateResult{ + State: "empty_shell", + Reason: "Unhydrated AngularJS (app.main) SPA shell.", + Confidence: 0.88, + } + } + } + } } if status >= 200 && status < 300 && words < 50 && rawHTML != "" { iframeShell, isIcims := scanIframesInternalCSGo(rawHTML, finalURL, true) if iframeShell.HasExternalIframe { - reason := "Unrendered HTML shell (< 50 words) wrapping an external or widget <iframe>." - if isIcims { - reason = "Unrendered iCIMS ATS iframe shell (#icims_content_iframe) with < 50 words of outer chrome." + boundedRawIframe := capStringBytesUTF8CSGo(rawHTML, maxHTMLScanCharsCSGo) + skipIframeEmptyShell := false + if !isIcims { + if hasRichSchemaJSONLDCSGo(boundedRawIframe) && (words >= 15 || cleanVisibleWordCount() >= 25) { + skipIframeEmptyShell = true + } else if isMediaOnlyIframeHostsCSGo(iframeShell.WidgetHosts) && (words >= 15 || cleanVisibleWordCount() >= 35 || cleanHasNonEmptyH1()) { + skipIframeEmptyShell = true + } else if words >= 20 && cleanVisibleWordCount() >= 80 && cleanHasNonEmptyH1() && !hasATSWidgetHostCSGo(iframeShell.WidgetHosts, iframeShell.IframeSrcs) { + skipIframeEmptyShell = true + } } - return ContentStateResult{ - State: "empty_shell", - Reason: reason, - Confidence: 0.88, + if !skipIframeEmptyShell { + reason := "Unrendered HTML shell (< 50 words) wrapping an external or widget <iframe>." + if isIcims { + reason = "Unrendered iCIMS ATS iframe shell (#icims_content_iframe) with < 50 words of outer chrome." + } + return ContentStateResult{ + State: "empty_shell", + Reason: reason, + Confidence: 0.88, + } } } if words < 40 && (indexFoldASCIICSGo(rawHTML, "aura") >= 0 || indexFoldASCIICSGo(rawHTML, "siteforce:communityapp") >= 0) { @@ -2127,7 +3747,7 @@ func ClassifyContentState(status int, rawHTML, markdown, finalURL, title string) strings.Contains(lowRawSF, "lightning-formatted-rich-text") || strings.Contains(lowRawSF, `"techarticle"`) || hasRichSchemaJSONLDCSGo(capStringBytesUTF8CSGo(rawHTML, maxHTMLScanCharsCSGo)) - if isAuraErrorOrLoad && isAuraPlatform && !hasHydratedSF && countWordsFromHTMLCSGo(cleanVisibleHTML) < 40 { + if isAuraErrorOrLoad && isAuraPlatform && !hasHydratedSF && cleanVisibleWordCount() < 40 { return ContentStateResult{ State: "empty_shell", Reason: "Unhydrated Salesforce Aura CSR loading/error shell without article content.", @@ -2135,9 +3755,36 @@ func ClassifyContentState(status int, rawHTML, markdown, finalURL, title string) } } } + // Title gate first: lower-casing the whole bounded document is only worth it for a "Route Tracking" page. + if words < 30 && strings.EqualFold(strings.TrimSpace(title), "Route Tracking") { + lowRawRoute := strings.ToLower(capStringBytesUTF8CSGo(rawHTML, maxHTMLScanCharsCSGo)) + if (strings.Contains(lowRawRoute, `id="root"`) || strings.Contains(lowRawRoute, `id='root'`)) && + !strings.Contains(lowRawRoute, "trackingnumber") && + !strings.Contains(lowRawRoute, "tracking_number") && + !strings.Contains(lowRawRoute, "checkpoints") && + !strings.Contains(lowRawRoute, "trackingstatus") && + !strings.Contains(lowRawRoute, "deliverystatus") && + !strings.Contains(lowRawRoute, "ordernumber") && + !strings.Contains(lowRawRoute, "order_number") && + !strings.Contains(lowRawRoute, "courierslug") && + cleanVisibleWordCount() < 30 { + return ContentStateResult{ + State: "empty_shell", + Reason: "Unrendered Route Tracking CSR shell without hydrated tracking or order payload.", + Confidence: 0.90, + } + } + } if words < 20 { lowRaw := strings.ToLower(capStringBytesUTF8CSGo(rawHTML, maxHTMLScanCharsCSGo)) - if words == 0 && strings.Contains(lowRaw, "_incapsula_resource") && strings.Contains(lowRaw, "incapsula incident id") { + boundedRawHTML := capStringBytesUTF8CSGo(rawHTML, maxHTMLScanCharsCSGo) + hasRichLD := hasRichSchemaJSONLDCSGo(boundedRawHTML) + hasMetaFrag := (strings.Contains(lowRaw, `name="fragment"`) || strings.Contains(lowRaw, `name='fragment'`)) && + (strings.Contains(lowRaw, `content="!"`) || strings.Contains(lowRaw, `content='!'`)) + hasNotPrerender := strings.Contains(lowRaw, "isnotprerender=!1") + hasEmptyChamberMn := isChamberMasterEmptyMnContentCSGo(boundedRawHTML) + if words == 0 && strings.Contains(lowRaw, "_incapsula_resource") && + (strings.Contains(lowRaw, "incapsula incident id") || cleanVisibleWordCount() == 0) { return ContentStateResult{ State: "temporarily_unavailable", Reason: "Imperva/Incapsula challenge interstitial.", @@ -2160,36 +3807,40 @@ func ClassifyContentState(status int, rawHTML, markdown, finalURL, title string) Confidence: 0.90, } } - if countWordsFromHTMLCSGo(cleanVisibleHTML) <= 5 && strings.Contains(lowRaw, "x-amzn-waf-action") { + if cleanVisibleWordCount() <= 5 && strings.Contains(lowRaw, "x-amzn-waf-action") { return ContentStateResult{ State: "temporarily_unavailable", Reason: "AWS WAF challenge interstitial.", Confidence: 0.90, } } - hasSpaMarker := strings.Contains(lowRaw, `id="root"`) || - strings.Contains(lowRaw, `id='root'`) || - strings.Contains(lowRaw, `id="app"`) || - strings.Contains(lowRaw, `id='app'`) || - strings.Contains(lowRaw, `id="site-container"`) || - strings.Contains(lowRaw, `id='site-container'`) || - strings.Contains(lowRaw, `id="recapp"`) || - strings.Contains(lowRaw, `id='recapp'`) || - strings.Contains(lowRaw, `id="portal-sprawl-loader"`) || - strings.Contains(lowRaw, `id='portal-sprawl-loader'`) || - strings.Contains(lowRaw, `id="__next"`) || - strings.Contains(lowRaw, `id='__next'`) || - strings.Contains(lowRaw, `id="__nuxt"`) || - strings.Contains(lowRaw, `id='__nuxt'`) || - strings.Contains(lowRaw, `<app-root`) || + spaIDs := spaShellIDsCSGo(lowRaw) + hasSpaMarker := spaIDs&(spaIDRoot|spaIDApp|spaIDSiteContainer|spaIDRecapp|spaIDPortalSprawlLoader|spaIDNext|spaIDNuxt) != 0 || + (spaIDs&spaIDMain != 0 && (strings.Contains(lowRaw, `<div id="main"></div>`) || strings.Contains(lowRaw, `<div id='main'></div>`))) || + (spaIDs&spaIDApplication != 0 && (strings.Contains(lowRaw, `<div id="application"></div>`) || strings.Contains(lowRaw, `<div id='application'></div>`))) || + (strings.Contains(lowRaw, "application") && reEmptyDivAppIDCSGo.MatchString(capStringBytesUTF8CSGo(lowRaw, 65_536))) || + (strings.TrimSpace(title) == "" && spaIDs&spaIDCrPortalTitle != 0) || + (spaIDs&spaIDMount00 != 0 && !hasRichLD) || + (strings.Contains(lowRaw, "parselaunchparams") && strings.Contains(lowRaw, "loading_container") && !hasRichLD) || + (strings.Contains(lowRaw, `<app-root`) && (reEmptyAppRootCSGo.MatchString(capStringBytesUTF8CSGo(cleanVisibleHTML, 262_144)) || !cleanHasNonEmptyH1())) || + strings.Contains(lowRaw, `<hts-root`) || strings.Contains(lowRaw, `<ui-view`) || strings.Contains(lowRaw, `<ng-view`) || strings.Contains(lowRaw, `<div class="layout"></div>`) || strings.Contains(lowRaw, `<div class='layout'></div>`) || ((strings.Contains(lowRaw, `class="layout"`) || strings.Contains(lowRaw, `class='layout'`)) && strings.Contains(lowRaw, `<script`)) || - (strings.Contains(lowRaw, `<noscript`) && strings.Contains(lowRaw, `javascript`)) + (strings.Contains(lowRaw, `<noscript`) && strings.Contains(lowRaw, `javascript`)) || + ((hasMetaFrag || hasNotPrerender) && !hasRichLD && !strings.Contains(lowRaw, "<table") && !strings.Contains(lowRaw, "<article")) || + hasEmptyChamberMn + if words < 15 && !hasRichLD && isEmptyMainDataBasepathShellCSGo(boundedRawHTML) { + return ContentStateResult{ + State: "empty_shell", + Reason: "Unrendered SPA container (#main[data-basepath]) with empty inner content.", + Confidence: 0.88, + } + } if hasSpaMarker { - if countWordsFromHTMLCSGo(cleanVisibleHTML) < 15 { + if cleanVisibleWordCount() < 15 { return ContentStateResult{ State: "empty_shell", Reason: "Unrendered SPA HTML shell with < 15 visible words.", @@ -2197,10 +3848,36 @@ func ClassifyContentState(status int, rawHTML, markdown, finalURL, title string) } } } + if words < 10 && + cleanVisibleWordCount() < 10 && + !hasRichLD && + !cleanHasNonEmptyH1() && + !strings.Contains(lowRaw, "<article") && + !strings.Contains(lowRaw, "<table") && + strings.Contains(lowRaw, "<script") { + // reJSRedirectShellCSGo requires the literal "location"; the fold-insensitive probe skips the submatch engine on + // script-heavy shells with no redirect (adversarial unclosed <script> floods otherwise scan all 32 KiB). + jsWindow := capStringBytesUTF8CSGo(rawHTML, 32_768) + if jm := matchJSRedirectShellCSGo(jsWindow); len(jm) >= 3 { + target := strings.ToLower(strings.TrimSpace(jm[1] + jm[2])) + if strings.Contains(target, "login") || strings.Contains(target, "signin") || strings.Contains(target, "sign-in") || strings.Contains(target, "sso") || strings.Contains(target, "auth") { + return ContentStateResult{ + State: "login_wall", + Reason: "JavaScript redirect shell targeting a login/authentication endpoint.", + Confidence: 0.90, + } + } + return ContentStateResult{ + State: "empty_shell", + Reason: "JavaScript redirect HTML shell without server-rendered content.", + Confidence: 0.88, + } + } + } lowTitleShell := strings.ToLower(strings.TrimSpace(title)) if (lowTitleShell == "job details" || lowTitleShell == "careers" || lowTitleShell == "job posting" || lowTitleShell == "loading" || lowTitleShell == "loading...") && words < 5 && - countWordsFromHTMLCSGo(cleanVisibleHTML) <= 6 && + cleanVisibleWordCount() <= 6 && !hasRichSchemaJSONLDCSGo(capStringBytesUTF8CSGo(rawHTML, maxHTMLScanCharsCSGo)) { return ContentStateResult{ State: "empty_shell", @@ -2208,6 +3885,19 @@ func ClassifyContentState(status int, rawHTML, markdown, finalURL, title string) Confidence: 0.88, } } + if words < 5 && + cleanVisibleWordCount() <= 6 && + !hasRichSchemaJSONLDCSGo(capStringBytesUTF8CSGo(rawHTML, maxHTMLScanCharsCSGo)) && + strings.Contains(lowRaw, "<form") && + !strings.Contains(lowRaw, "<table") && + !strings.Contains(lowRaw, "<article") && + (strings.Contains(lowRaw, "genericsearch.cfm") || strings.Contains(lowTitleShell, "search")) { + return ContentStateResult{ + State: "empty_shell", + Reason: "Empty unsubmitted search form shell with <= 6 visible words and no results.", + Confidence: 0.88, + } + } } } diff --git a/internal/classify/content_state_soft404_test.go b/internal/classify/content_state_soft404_test.go index 2c5d482..c8ef0cd 100644 --- a/internal/classify/content_state_soft404_test.go +++ b/internal/classify/content_state_soft404_test.go @@ -683,4 +683,217 @@ func TestClassifyContentStateSalesforceAuraCSRShell(t *testing.T) { if gotKasada429.State != "temporarily_unavailable" { t.Fatalf("expected HTTP 429 Kasada bot-gate shell to classify temporarily_unavailable, got %+v", gotKasada429) } + + // 6. Empty <sdnList> > 8192 bytes (10 KB) with zero <sdnEntry> elements -> empty_shell + largeEmptySDN := `<?xml version="1.0" encoding="utf-8"?><sdnList><publshInformation><Publish_Date>11/28/2026</Publish_Date><Record_Count>0</Record_Count></publshInformation><!-- ` + strings.Repeat("padding ", 1300) + ` --></sdnList>` + if len(largeEmptySDN) <= 8192 { + t.Fatalf("test fixture must exceed 8192 bytes, got %d", len(largeEmptySDN)) + } + gotLargeSDN := ClassifyContentStateFull(ContentStateInput{ + Status: 200, + URL: "https://sanctionslistservice.ofac.treas.gov/api/PublicationPreview/exports/SDN.XML", + FinalURL: "https://sanctionslistservice.ofac.treas.gov/api/PublicationPreview/exports/SDN.XML", + RawHTML: largeEmptySDN, + Markdown: largeEmptySDN, + }) + if gotLargeSDN.State != "empty_shell" { + t.Fatalf("expected >8KiB empty <sdnList> to classify empty_shell, got %+v", gotLargeSDN) + } + + // 7. Nested /exports/error, /exports/error/SDN.XML, /Published/error/SDN.XML, /error.xml, and /Error.aspx redirect paths -> soft_404 + for _, errFin := range []string{ + "https://wc2h-sls-prod-public-published.s3.us-gov-west-1.amazonaws.com/exports/error", + "https://wc2h-sls-prod-public-published.s3.us-gov-west-1.amazonaws.com/exports/error/SDN.XML", + "https://wc2h-sls-prod-public-published.s3.us-gov-west-1.amazonaws.com/Published/error/SDN.XML", + "https://wc2h-sls-prod-public-published.s3.us-gov-west-1.amazonaws.com/error.xml", + "https://wc2h-sls-prod-public-published.s3.us-gov-west-1.amazonaws.com/Error.aspx", + } { + gotRedir := ClassifyContentStateFull(ContentStateInput{ + Status: 200, + URL: "https://sanctionslistservice.ofac.treas.gov/api/PublicationPreview/exports/SDN.XML", + FinalURL: errFin, + RawHTML: `<!doctype html><html><head><title>Notice

` + strings.Repeat("Service error details ", 120) + `

`, + Markdown: strings.Repeat("Service error details ", 120), + }) + if gotRedir.State != "soft_404" { + t.Fatalf("expected redirect to %s to classify soft_404, got %+v", errFin, gotRedir) + } + } + + // 8. UTF-8 BOM-prefixed > 8192-byte empty -> empty_shell + bomLargeSDN := "\uFEFF" + largeEmptySDN + gotBOMSDN := ClassifyContentStateFull(ContentStateInput{ + Status: 200, + URL: "https://sanctionslistservice.ofac.treas.gov/api/PublicationPreview/exports/SDN.XML", + FinalURL: "https://sanctionslistservice.ofac.treas.gov/api/PublicationPreview/exports/SDN.XML", + RawHTML: bomLargeSDN, + Markdown: bomLargeSDN, + }) + if gotBOMSDN.State != "empty_shell" { + t.Fatalf("expected UTF-8 BOM >8KiB empty to classify empty_shell, got %+v", gotBOMSDN) + } +} + +func TestClassifyWave3B4EmptyShellsAndSoft404s(t *testing.T) { + cases := []struct { + name string + url string + raw string + wantState string + }{ + { + name: "gerrit xssi empty array", + url: "https://review.opendev.org/changes/?q=status:merged", + raw: ")]}'\n[]", + wantState: "empty_shell", + }, + { + name: "nsf empty response.award array", + url: "https://api.nsf.gov/services/v1/awards/9999999.json", + raw: `{"response":{"award":[]}}`, + wantState: "empty_shell", + }, + { + name: "first epss empty data array", + url: "https://api.first.org/data/v1/epss?cve=CVE-9999-99999", + raw: `{"status":"OK","status-code":200,"total":0,"data":[]}`, + wantState: "empty_shell", + }, + { + name: "dblp empty result.hits", + url: "https://dblp.org/search/publ/api?q=zzzznotfound999&format=json", + raw: `{"result":{"hits":{"@total":"0","hit":[]}}}`, + wantState: "empty_shell", + }, + { + name: "security.txt missing Contact directive", + url: "https://www.cloudflare.com/.well-known/security.txt", + raw: "# Comment only\nExpires: 2027-06-30T23:59:59Z\n", + wantState: "empty_shell", + }, + { + name: "cws item not available soft_404", + url: "https://chromewebstore.google.com/detail/missing/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + raw: `Item not available - Chrome Web Store

This item is no longer available.

`, + wantState: "soft_404", + }, + { + name: "bgp.he.net Invalid AS soft_404", + url: "https://bgp.he.net/AS999999999", + raw: `AS999999999 - bgp.he.net
Invalid AS
`, + wantState: "soft_404", + }, + { + name: "bgp.he.net 180B Invalid AS specified soft_404", + url: "https://bgp.he.net/AS9999999", + raw: `

Invalid AS

Invalid AS specified. Please enter a valid ASN.

`, + wantState: "soft_404", + }, + { + name: "bgp.he.net Not a valid ASN soft_404", + url: "https://bgp.he.net/AS9999999", + raw: `bgp.he.net

Not a valid ASN

`, + wantState: "soft_404", + }, + { + name: "bgp.he.net past-64KB Invalid AS soft_404", + url: "https://bgp.he.net/AS9999999", + raw: `AS9999999 - bgp.he.net` + strings.Repeat("", 6000) + `

Invalid AS

Invalid AS specified. Please enter a valid ASN.

`, + wantState: "soft_404", + }, + { + name: "wordpress.org plugin not found soft_404 (#332)", + url: "https://wordpress.org/plugins/missing-plugin/", + raw: `Plugin not found | WordPress.org

Plugin not found

`, + wantState: "soft_404", + }, + { + name: "forge.puppet.com module not found soft_404 (#336)", + url: "https://forge.puppet.com/modules/puppetlabs/nope", + raw: `Module not found | Puppet Forge

Module not found

`, + wantState: "soft_404", + }, + { + name: "marketplace.visualstudio.com extension not found soft_404 (#333)", + url: "https://marketplace.visualstudio.com/items?itemName=missing.nope", + raw: `Extension not found | Visual Studio Marketplace

Extension not found

`, + wantState: "soft_404", + }, + { + name: "apis-guru 0-complete-entry truncated list.json prefix (#337)", + url: "https://api.apis.guru/v2/list.json", + raw: `{"onlypartial.com":{"preferred":"1.0.0","versions":{"1.0.0":{"info":{"title":"TRUNCATED`, + wantState: "empty_shell", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got := ClassifyContentStateFull(ContentStateInput{ + Status: 200, + URL: tc.url, + FinalURL: tc.url, + RawHTML: tc.raw, + }) + if got.State != tc.wantState { + t.Fatalf("%s: got state=%q (%s), want %q", tc.name, got.State, got.Reason, tc.wantState) + } + }) + } + // Also verify text/plain scrape.ts path where RawHTML is omitted and text is in Markdown, plus CISA KEV 0-match & APIs.guru bounded notice. + mdCases := []struct { + name string + url string + md string + wantState string + }{ + { + name: "security.txt markdown-only path", + url: "https://www.cloudflare.com/.well-known/security.txt", + md: "# Comment only\nExpires: 2027-06-30T23:59:59Z\n", + wantState: "empty_shell", + }, + { + name: "cisa-kev 0-match cve query (#315)", + url: "https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json?cve=CVE-9999-99999", + md: "# CISA KEV — CVE-9999-99999\n\n- **Returned**: 0\n\nNo matching KEV entry found for CVE-9999-99999.", + wantState: "empty_shell", + }, + { + name: "apis-guru 0-entry truncated notice (#337)", + url: "https://api.apis.guru/v2/list.json", + md: "# APIs.guru Directory Index (Bounded Sample)\n\n- **Returned**: 0\n- **Truncated**: true\n\nNo complete API entries fit within the bounded prefix.", + wantState: "empty_shell", + }, + { + name: "wordpress.org plugin not found markdown fallback (#332)", + url: "https://wordpress.org/plugins/missing-plugin/", + md: "# Plugin not found", + wantState: "soft_404", + }, + { + name: "forge.puppet.com module not found markdown fallback (#336)", + url: "https://forge.puppet.com/modules/puppetlabs/nope", + md: "# Module not found", + wantState: "soft_404", + }, + { + name: "marketplace.visualstudio.com extension not found markdown fallback (#333)", + url: "https://marketplace.visualstudio.com/items?itemName=missing.nope", + md: "# Extension not found", + wantState: "soft_404", + }, + } + for _, tc := range mdCases { + t.Run(tc.name, func(t *testing.T) { + got := ClassifyContentStateFull(ContentStateInput{ + Status: 200, + URL: tc.url, + FinalURL: tc.url, + Markdown: tc.md, + }) + if got.State != tc.wantState { + t.Fatalf("%s: got %q (%s), want %q", tc.name, got.State, got.Reason, tc.wantState) + } + }) + } } diff --git a/internal/classify/content_state_test.go b/internal/classify/content_state_test.go new file mode 100644 index 0000000..495b6e2 --- /dev/null +++ b/internal/classify/content_state_test.go @@ -0,0 +1,947 @@ +package classify + +import ( + "strings" + "testing" +) + +func TestClassifyContentStateWave3B1Remediations(t *testing.T) { + // 1. #212 public-bid-portals: concise (<65w) public BidNet solicitation with header .loginWindow password input stays "active" + conciseBidNetHTML := `RFP-2026-101 - Snow Plowing

RFP-2026-101 - Snow Plowing

Reference Number
0000443657
Closing Date
2026-12-20
Location
Denver, CO
` + conciseBidNetMD := "# RFP-2026-101 - Snow Plowing\n\n- **Platform**: bidnet\n- **Reference Number**: 0000443657\n- **Closing Date**: 2026-12-20\n- **Location**: Denver, CO\n" + resBidPublic := ClassifyContentStateFull(ContentStateInput{ + Status: 200, + URL: "https://www.bidnetdirect.com/colorado/solicitations/open-bids/rfp/0000443657", + FinalURL: "https://www.bidnetdirect.com/colorado/solicitations/open-bids/rfp/0000443657", + Title: "RFP-2026-101 - Snow Plowing", + RawHTML: conciseBidNetHTML, + Markdown: conciseBidNetMD, + }) + if resBidPublic.State != "active" { + t.Fatalf("#212 concise public BidNet solicitation got %q (%s), want active", resBidPublic.State, resBidPublic.Reason) + } + + // Genuinely login-gated BidNet detail (password input in main, or login-gate copy, or no .mets-field) MUST still be login_wall + gatedBidNetMainPwd := `Bid Documents

RFP-2026-101

` + if got := ClassifyContentStateFull(ContentStateInput{ + Status: 200, + URL: "https://www.bidnetdirect.com/colorado/solicitations/open-bids/rfp/0000443657", + RawHTML: gatedBidNetMainPwd, + Markdown: "# RFP-2026-101", + }); got.State != "login_wall" { + t.Fatalf("#212 gated bid with main password input got %q, want login_wall", got.State) + } + + gatedBidNetCopy := `Bid Documents

RFP-2026-101

Please sign in to view solicitation attachments and register to download bid documents.

` + if got := ClassifyContentStateFull(ContentStateInput{ + Status: 200, + URL: "https://www.bidnetdirect.com/colorado/solicitations/open-bids/rfp/0000443657", + RawHTML: gatedBidNetCopy, + Markdown: "# RFP-2026-101\n\nPlease sign in to view solicitation attachments and register to download bid documents.", + }); got.State != "login_wall" { + t.Fatalf("#212 gated bid with sign-in copy got %q, want login_wall", got.State) + } + + // General site with
and <65 words (no .mets-field) MUST NOT be weakened -> login_wall + genericHeaderLogin := `Member Portal

Welcome

Short portal stub.

` + if got := ClassifyContentStateFull(ContentStateInput{ + Status: 200, + URL: "https://portal.example.org/home", + RawHTML: genericHeaderLogin, + Markdown: "# Welcome\n\nShort portal stub.", + }); got.State != "login_wall" { + t.Fatalf("generic header password site got %q, want login_wall", got.State) + } + + // 2. #208 laserfiche-weblink: STR_ERROR_PAGE_TITLE alone, INDEX_COOKIE_WARNING alone, and ?cr=1 / CookieCheck.aspx >=60w + lfCases := []struct { + name string + url string + html string + md string + }{ + { + name: "STR_ERROR_PAGE_TITLE only", + url: "https://records.hawaiicounty.gov/WebLink/Browse.aspx?dbid=1&cr=1", + html: `STR_ERROR_PAGE_TITLE

Cookies are disabled.

`, + md: "Cookies are disabled.", + }, + { + name: "INDEX_COOKIE_WARNING only", + url: "https://records.hawaiicounty.gov/WebLink/Browse.aspx?dbid=1", + html: `WebLink

INDEX_COOKIE_WARNING

`, + md: "INDEX_COOKIE_WARNING", + }, + { + name: "cr=1 with >=60 words cookie help text", + url: "https://records.hawaiicounty.gov/WebLink/Browse.aspx?dbid=1&cr=1", + html: `WebLink Cookie Check

Browser Cookies Required

` + strings.Repeat("Please enable browser cookies in your settings and refresh this WebLink session to view repository folders. ", 6) + `

`, + md: "# Browser Cookies Required\n\n" + strings.Repeat("Please enable browser cookies in your settings and refresh this WebLink session to view repository folders. ", 6), + }, + { + name: "CookieCheck.aspx without document rows", + url: "https://records.hawaiicounty.gov/WebLink/CookieCheck.aspx", + html: `Cookie Check

Checking session cookies.

`, + md: "Checking session cookies.", + }, + } + for _, tc := range lfCases { + got := ClassifyContentStateFull(ContentStateInput{ + Status: 200, + URL: tc.url, + FinalURL: tc.url, + RawHTML: tc.html, + Markdown: tc.md, + }) + if got.State != "empty_shell" { + t.Fatalf("#208 Laserfiche %s: got %q (%s), want empty_shell", tc.name, got.State, got.Reason) + } + } + + // Valid Laserfiche document page MUST stay active + lfValidHTML := `Ordinance 26-14 - Laserfiche WebLink

Ordinance 26-14

County of Hawaii ordinance amending zoning code sections.

View Document PDF
` + if got := ClassifyContentStateFull(ContentStateInput{ + Status: 200, + URL: "https://records.hawaiicounty.gov/WebLink/DocView.aspx?id=991357&dbid=1", + RawHTML: lfValidHTML, + Markdown: "# Ordinance 26-14\n\nCounty of Hawaii ordinance amending zoning code sections.", + }); got.State != "active" { + t.Fatalf("#208 valid Laserfiche DocView got %q (%s), want active", got.State, got.Reason) + } + + // 3. #209 accela-citizen-access: Default.aspx "Message Bar" / aspnetForm shells (short & welcome-copy) -> empty_shell + accelaShort := `Accela Citizen Access

Message Bar

` + if got := ClassifyContentStateFull(ContentStateInput{ + Status: 200, + URL: "https://aca-prod.accela.com/SANDIEGO/Default.aspx", + FinalURL: "https://aca-prod.accela.com/SANDIEGO/Default.aspx", + Title: "Accela Citizen Access", + RawHTML: accelaShort, + Markdown: "# Message Bar", + }); got.State != "empty_shell" { + t.Fatalf("#209 Accela Default.aspx short shell got %q (%s), want empty_shell", got.State, got.Reason) + } + accelaWelcomeCopy := strings.Repeat("Welcome to the municipal Accela Citizen Access online permitting portal where residents can search records and inspect applications. ", 5) + accelaWelcome := `Accela Citizen Access

Message Bar

` + accelaWelcomeCopy + `

` + if got := ClassifyContentStateFull(ContentStateInput{ + Status: 200, + URL: "https://aca-prod.accela.com/SANDIEGO/Default.aspx", + FinalURL: "https://aca-prod.accela.com/SANDIEGO/Default.aspx", + Title: "Accela Citizen Access", + RawHTML: accelaWelcome, + Markdown: "# Message Bar\n\n" + accelaWelcomeCopy, + }); got.State != "empty_shell" { + t.Fatalf("#209 Accela Default.aspx welcome-copy shell got %q (%s), want empty_shell", got.State, got.Reason) + } + + // Valid Accela CapDetail with permit spans MUST stay active + accelaValid := `Accela Citizen Access

Message Bar

PMT-3398658Combination Building Permit` + if got := ClassifyContentStateFull(ContentStateInput{ + Status: 200, + URL: "https://aca-prod.accela.com/SANDIEGO/Cap/CapDetail.aspx?capID1=REC26", + Title: "PMT-3398658 - Combination Building Permit", + RawHTML: accelaValid, + Markdown: "# PMT-3398658 - Combination Building Permit\n\n- **Platform**: Accela Citizen Access (Read-Only)", + }); got.State != "active" { + t.Fatalf("#209 valid Accela CapDetail got %q (%s), want active", got.State, got.Reason) + } + + // 4. #223 canvas-public-courses: SAML/IdP SSO redirect with >110 words of instructions -> login_wall + longSSOInstructions := strings.Repeat("Use your university single sign-on credentials and multi-factor authentication token to access campus courses and library resources. ", 12) + samlLongHTML := `University Web Login

University Web Login

` + longSSOInstructions + `

` + if got := ClassifyContentStateFull(ContentStateInput{ + Status: 200, + URL: "https://canvas.univ.edu/courses/101", + FinalURL: "https://idp.univ.edu/idp/profile/SAML2/Redirect/SSO", + Title: "University Web Login", + RawHTML: samlLongHTML, + Markdown: "# University Web Login\n\n" + longSSOInstructions, + }); got.State != "login_wall" { + t.Fatalf("#223 SAML >110 words got %q (%s), want login_wall", got.State, got.Reason) + } + + // Technical article discussing SAML with Article JSON-LD and no password form MUST stay active + samlDocsHTML := `Configuring SAML2 SSO

Configuring SAML2 SSO

` + longSSOInstructions + `

/idp/profile/SAML2/Redirect/SSO?SAMLRequest=abc
` + if got := ClassifyContentStateFull(ContentStateInput{ + Status: 200, + URL: "https://docs.example.com/saml2-guide", + Title: "Configuring SAML2 SSO", + RawHTML: samlDocsHTML, + Markdown: "# Configuring SAML2 SSO\n\n" + longSSOInstructions, + }); got.State != "active" { + t.Fatalf("SAML tech doc got %q (%s), want active", got.State, got.Reason) + } + + // 5. Iteration 3 Challenger bypass regressions: + // 5a. #212 public-bid-portals: header .loginWindow + "sign in to download" (and log in to download / sign in to bid / login required) -> login_wall + for _, phrase := range []string{ + "Please sign in to download the RFP package.", + "Please log in to download solicitation files.", + "Login to download bid package.", + "You must sign in to bid on this opportunity.", + "Login required to view attachments.", + } { + bidPhraseHTML := `RFP-2026-101 - Snow Plowing

RFP-2026-101 - Snow Plowing

` + phrase + `

Reference Number
0000443657
` + if got := ClassifyContentStateFull(ContentStateInput{ + Status: 200, + URL: "https://www.bidnetdirect.com/colorado/solicitations/open-bids/rfp/0000443657", + FinalURL: "https://www.bidnetdirect.com/colorado/solicitations/open-bids/rfp/0000443657", + Title: "RFP-2026-101 - Snow Plowing", + RawHTML: bidPhraseHTML, + Markdown: "# RFP-2026-101 - Snow Plowing\n\n" + phrase + "\n\nReference Number: 0000443657", + }); got.State != "login_wall" { + t.Fatalf("#212 BidNet header password + %q got %q (%s), want login_wall", phrase, got.State, got.Reason) + } + } + + // 5b. #212 public-bid-portals:
inside
with .mets-field -> login_wall + bidMainLoginWindow := `RFP-2026-101 - Snow Plowing

RFP-2026-101 - Snow Plowing

Reference Number
0000443657
` + if got := ClassifyContentStateFull(ContentStateInput{ + Status: 200, + URL: "https://www.bidnetdirect.com/colorado/solicitations/open-bids/rfp/0000443657", + FinalURL: "https://www.bidnetdirect.com/colorado/solicitations/open-bids/rfp/0000443657", + Title: "RFP-2026-101 - Snow Plowing", + RawHTML: bidMainLoginWindow, + Markdown: "# RFP-2026-101 - Snow Plowing\n\nReference Number: 0000443657", + }); got.State != "login_wall" { + t.Fatalf("#212 BidNet .loginWindow inside
got %q (%s), want login_wall", got.State, got.Reason) + } + + // 5c. #208 laserfiche-weblink: ?cr=1 with empty
or whitespace
-> empty_shell + for _, emptyContainer := range []string{ + `
`, + `
 
`, + `
`, + } { + lfEmptyHTML := `WebLink

Cookies Required

` + emptyContainer + `

` + strings.Repeat("Please enable browser cookies in your settings and refresh this WebLink session to view repository folders. ", 6) + `

` + if got := ClassifyContentStateFull(ContentStateInput{ + Status: 200, + URL: "https://records.hawaiicounty.gov/WebLink/Browse.aspx?dbid=1&cr=1", + FinalURL: "https://records.hawaiicounty.gov/WebLink/Browse.aspx?dbid=1&cr=1", + RawHTML: lfEmptyHTML, + Markdown: "# Cookies Required\n\n" + strings.Repeat("Please enable browser cookies in your settings and refresh this WebLink session to view repository folders. ", 6), + }); got.State != "empty_shell" { + t.Fatalf("#208 Laserfiche ?cr=1 with %s got %q (%s), want empty_shell", emptyContainer, got.State, got.Reason) + } + } + + // 5d. #209 accela-citizen-access: Default.aspx with
.loginWindow vs 82w positive BidNet + summary75w := strings.Repeat("Qualified civil engineering consulting firms provide roadway design, drainage analysis, signal timing, utility coordination, and public outreach support. ", 4) + for _, tc := range []struct { + name string + phrase string + }{ + {"75w login required", "Login required to download solicitation attachments."}, + {"75w register to download", "Please register to download the complete RFP package."}, + {"75w must be logged in", "You must be logged in to view bid documents."}, + {"75w login to download", "Login to download bid package and addenda."}, + } { + bid75wHTML := `202686685 - Roadway Improvements

202686685 - Roadway Improvements

Reference Number
0000443656

` + summary75w + tc.phrase + `

` + bid75wMD := "# 202686685 - Roadway Improvements\n\n- **Platform**: bidnet\n- **Reference Number**: 0000443656\n\n## Details\n\n" + summary75w + tc.phrase + if got := ClassifyContentStateFull(ContentStateInput{ + Status: 200, + URL: "https://www.bidnetdirect.com/colorado/solicitations/open-bids/rfp/0000443656", + FinalURL: "https://www.bidnetdirect.com/colorado/solicitations/open-bids/rfp/0000443656", + Title: "202686685 - Roadway Improvements", + RawHTML: bid75wHTML, + Markdown: bid75wMD, + }); got.State != "login_wall" { + t.Fatalf("#212 %s got %q (%s), want login_wall", tc.name, got.State, got.Reason) + } + } + + // 75w .loginWindow inside
(no gate phrase) -> login_wall + bid75wMainLogin := `202686685 - Roadway Improvements

202686685 - Roadway Improvements

Reference Number
0000443656

` + summary75w + `

` + bid75wMainLoginMD := "# 202686685 - Roadway Improvements\n\n- **Platform**: bidnet\n- **Reference Number**: 0000443656\n\n## Details\n\n" + summary75w + if got := ClassifyContentStateFull(ContentStateInput{ + Status: 200, + URL: "https://www.bidnetdirect.com/colorado/solicitations/open-bids/rfp/0000443656", + FinalURL: "https://www.bidnetdirect.com/colorado/solicitations/open-bids/rfp/0000443656", + Title: "202686685 - Roadway Improvements", + RawHTML: bid75wMainLogin, + Markdown: bid75wMainLoginMD, + }); got.State != "login_wall" { + t.Fatalf("#212 75w .loginWindow inside
got %q (%s), want login_wall", got.State, got.Reason) + } + + // Post-
.loginWindow modal (both concise and 75w) -> login_wall + for _, tc := range []struct { + name string + body string + md string + }{ + { + name: "concise post-
.loginWindow", + body: `

RFP-2026-101

Reference Number
0000443656
`, + md: "# RFP-2026-101\n\n- **Platform**: bidnet\n- **Reference Number**: 0000443656", + }, + { + name: "75w post-
.loginWindow", + body: `

RFP-2026-101

Reference Number
0000443656

` + summary75w + `

`, + md: "# RFP-2026-101\n\n- **Platform**: bidnet\n- **Reference Number**: 0000443656\n\n## Details\n\n" + summary75w, + }, + } { + htmlDoc := `RFP-2026-101` + tc.body + `` + if got := ClassifyContentStateFull(ContentStateInput{ + Status: 200, + URL: "https://www.bidnetdirect.com/colorado/solicitations/open-bids/rfp/0000443656", + FinalURL: "https://www.bidnetdirect.com/colorado/solicitations/open-bids/rfp/0000443656", + Title: "RFP-2026-101", + RawHTML: htmlDoc, + Markdown: tc.md, + }); got.State != "login_wall" { + t.Fatalf("#212 %s got %q (%s), want login_wall", tc.name, got.State, got.Reason) + } + } + + // Positive controls: 82w BidNet with header .loginWindow AND pre-
.loginWindow stay active; 80w generic page with header password stays active + pos82wHTML := `202686685 - W. 38th Ave. Multimodal Improvements Design Services

202686685 - W. 38th Ave. Multimodal Improvements Design Services

Reference Number
0000443656
Closing Date
2026-12-15 14:00 MST
Location
Denver, Colorado

The City and County of Denver Department of Transportation and Infrastructure seeks qualified civil engineering consulting firms to provide preliminary and final roadway design, multimodal pedestrian safety engineering, storm drainage analysis, signal timing design, utility coordination, public outreach support, environmental clearance documentation, and construction phase engineering support services along the West 38th Avenue corridor.

` + pos82wMD := "# 202686685 - W. 38th Ave. Multimodal Improvements Design Services\n\n- **Platform**: bidnet\n- **Agency**: City and County of Denver DOTI\n- **Reference Number**: 0000443656\n- **Closing Date**: 2026-12-15 14:00 MST\n- **Location**: Denver, Colorado\n\n## Details\n\nThe City and County of Denver Department of Transportation and Infrastructure seeks qualified civil engineering consulting firms to provide preliminary and final roadway design, multimodal pedestrian safety engineering, storm drainage analysis, signal timing design, utility coordination, public outreach support, environmental clearance documentation, and construction phase engineering support services along the West 38th Avenue corridor." + if got := ClassifyContentStateFull(ContentStateInput{ + Status: 200, + URL: "https://www.bidnetdirect.com/colorado/solicitations/open-bids/rfp/0000443656", + FinalURL: "https://www.bidnetdirect.com/colorado/solicitations/open-bids/rfp/0000443656", + Title: "202686685 - W. 38th Ave. Multimodal Improvements Design Services", + RawHTML: pos82wHTML, + Markdown: pos82wMD, + }); got.State != "active" { + t.Fatalf("#212 82w positive BidNet solicitation got %q (%s), want active", got.State, got.Reason) + } + preMainBidHTML := `RFP-2026-101

RFP-2026-101

Reference Number
0000443656

` + summary75w + `

` + if got := ClassifyContentStateFull(ContentStateInput{ + Status: 200, + URL: "https://www.bidnetdirect.com/colorado/solicitations/open-bids/rfp/0000443656", + FinalURL: "https://www.bidnetdirect.com/colorado/solicitations/open-bids/rfp/0000443656", + Title: "RFP-2026-101", + RawHTML: preMainBidHTML, + Markdown: "# RFP-2026-101\n\n- **Platform**: bidnet\n- **Reference Number**: 0000443656\n\n## Details\n\n" + summary75w, + }); got.State != "active" { + t.Fatalf("#212 pre-
.loginWindow positive BidNet got %q (%s), want active", got.State, got.Reason) + } + generic80wHTML := `City Transit Update

City Transit Update

` + summary75w + `

` + if got := ClassifyContentStateFull(ContentStateInput{ + Status: 200, + URL: "https://transit.example.gov/updates/1", + FinalURL: "https://transit.example.gov/updates/1", + Title: "City Transit Update", + RawHTML: generic80wHTML, + Markdown: "# City Transit Update\n\n" + summary75w, + }); got.State != "active" { + t.Fatalf("generic 80w header-only password page got %q (%s), want active", got.State, got.Reason) + } +} + +func TestClassifyContentStateWave3B2NegativeShells(t *testing.T) { + // 1. Anubis PoW: encoded apostrophe ' / ' + id="anubis_version" / id="anubis_challenge" / /.within.website/x/xess/ + anubisRaw := `Making sure you're not a bot!

Making sure you're not a bot!

` + if wm := ClassifyWAFAndChallengeFull(WAFChallengeInput{Status: 445, RawHTML: anubisRaw}); wm == nil || wm.Category != "challenge" { + t.Fatalf("Anubis PoW encoded ' WAF check got %+v, want challenge", wm) + } + if cs := ClassifyContentStateFull(ContentStateInput{Status: 445, URL: "https://gehirneimer.de/", RawHTML: anubisRaw, Markdown: ""}); cs.State != "temporarily_unavailable" { + t.Fatalf("Anubis PoW 445 ContentState got %q (%s), want temporarily_unavailable", cs.State, cs.Reason) + } + anubisHex := `Making sure you're not a bot!

Making sure you're not a bot!

` + if wm := ClassifyWAFAndChallengeFull(WAFChallengeInput{Status: 200, RawHTML: anubisHex}); wm == nil || wm.Category != "challenge" { + t.Fatalf("Anubis PoW ' 200 WAF check got %+v, want challenge", wm) + } + + // 2. CSR SPA shells: / isNotPrerender=!1 + thin body, and Route Tracking 1KB shell + athlinksShell := `Athlinks
` + if cs := ClassifyContentStateFull(ContentStateInput{Status: 200, URL: "https://www.athlinks.com/event/382820", RawHTML: athlinksShell, Markdown: ""}); cs.State != "empty_shell" { + t.Fatalf("Athlinks CSR meta fragment shell got %q (%s), want empty_shell", cs.State, cs.Reason) + } + routeShell := `Route Tracking
` + if cs := ClassifyContentStateFull(ContentStateInput{Status: 200, URL: "https://tracking.route.com/", Title: "Route Tracking", RawHTML: routeShell, Markdown: ""}); cs.State != "empty_shell" { + t.Fatalf("Route Tracking 1KB empty CSR shell got %q (%s), want empty_shell", cs.State, cs.Reason) + } + + // 3. AppFolio /page-not-found-sub soft 404 (both redirect and title) + appFolio404HTML := `Page not found | AppFolio

Page not found

The page you requested could not be found.

` + if cs := ClassifyContentStateFull(ContentStateInput{ + Status: 200, + URL: "https://lapmg.appfolio.com/listings/detail/missing", + FinalURL: "https://www.appfolio.com/page-not-found-sub", + RawHTML: appFolio404HTML, + Markdown: "Page not found", + }); cs.State != "soft_404" { + t.Fatalf("AppFolio /page-not-found-sub got %q (%s), want soft_404", cs.State, cs.Reason) + } + + // 4. Empty JSON containers & error JSON shells: Q4 GetPressReleaseListResult / GetEventListResult, Boost 403, GraphQL errors, Searchanise invalid key + for _, tc := range []struct { + name string + status int + body string + }{ + {"q4-press-empty", 200, `{"GetPressReleaseListResult":[]}`}, + {"q4-event-empty", 200, `{"GetEventListResult":[]}`}, + {"boost-403", 403, `{"message":"403 Forbidden: "}`}, + {"graphql-error", 401, `{"errors":[{"message":"Unauthorized storefront access token"}],"data":{}}`}, + {"searchanise-error", 400, `{"error":"Invalid API key"}`}, + } { + if cs := ClassifyContentStateFull(ContentStateInput{Status: tc.status, URL: "https://api.example.com/feed", RawHTML: tc.body, Markdown: ""}); cs.State == "active" { + t.Fatalf("%s must not classify as active (got %q)", tc.name, cs.State) + } + } + + // 5. ChamberMaster empty mn-content & Wild Apricot /sys/login / WaGadgetLoginButton-only shells + cmEmpty := `Directory
` + if cs := ClassifyContentStateFull(ContentStateInput{Status: 200, URL: "https://chamber.example.org/list/", RawHTML: cmEmpty, Markdown: ""}); cs.State != "empty_shell" { + t.Fatalf("ChamberMaster empty mn-content got %q (%s), want empty_shell", cs.State, cs.Reason) + } + waLoginOnly := `Members` + if cs := ClassifyContentStateFull(ContentStateInput{Status: 200, URL: "https://club.wildapricot.org/sys/login", FinalURL: "https://club.wildapricot.org/sys/login", RawHTML: waLoginOnly, Markdown: "Member Login"}); cs.State != "login_wall" { + t.Fatalf("Wild Apricot /sys/login got %q (%s), want login_wall", cs.State, cs.Reason) + } + // Positive control: Wild Apricot with public WaGadgetEvents stays active + waPublic := `Annual Conference

Annual Conference

Full agenda and speaker lineup for the statewide association conference in June.

` + if cs := ClassifyContentStateFull(ContentStateInput{ + Status: 200, + URL: "https://www.ndshp.org/event-6925405", + FinalURL: "https://www.ndshp.org/event-6925405", + Title: "Annual Conference", + RawHTML: waPublic, + Markdown: "# Annual Conference\n\nFull agenda and speaker lineup for the statewide association conference in June.", + }); cs.State != "active" { + t.Fatalf("Wild Apricot public WaGadgetEvents got %q (%s), want active", cs.State, cs.Reason) + } + + // 6. Finding 10: HTTP 200 Cloudflare "Just a moment..." + challenge copy (<40w) and Anubis PoW (45w, <120w) -> temporarily_unavailable + cf200 := `Just a moment...

Enable JavaScript and cookies to continue

` + if cs := ClassifyContentStateFull(ContentStateInput{ + Status: 200, + URL: "https://protected.example.com/", + FinalURL: "https://protected.example.com/", + Title: "Just a moment...", + RawHTML: cf200, + Markdown: "Enable JavaScript and cookies to continue", + }); cs.State != "temporarily_unavailable" { + t.Fatalf("HTTP 200 Cloudflare Just a moment... got %q (%s), want temporarily_unavailable", cs.State, cs.Reason) + } + + anubis45wBody := "Making sure you're not a bot! Please wait while your browser solves a brief proof-of-work verification challenge before accessing this site. JavaScript is required to complete Anubis verification and proceed to the requested community repository page automatically." + anubis45wHTML := `Making sure you're not a bot!

` + anubis45wBody + `

` + if cs := ClassifyContentStateFull(ContentStateInput{ + Status: 200, + URL: "https://git.example.org/", + FinalURL: "https://git.example.org/", + Title: "Making sure you're not a bot!", + RawHTML: anubis45wHTML, + Markdown: anubis45wBody, + }); cs.State != "temporarily_unavailable" { + t.Fatalf("HTTP 200 Anubis PoW (45w) got %q (%s), want temporarily_unavailable", cs.State, cs.Reason) + } +} + +func TestClassifyContentStateWave3B5HardenedShells(t *testing.T) { + cases := []struct { + name string + status int + url string + title string + rawHTML string + markdown string + wantNot string + wantExact string + }{ + { + name: "facebook-bare-mount_0_0-without-noscript", + status: 200, + url: "https://www.facebook.com/marketplace/item/123", + title: "Facebook Marketplace", + rawHTML: `Facebook Marketplace
`, + markdown: "", + wantExact: "empty_shell", + }, + { + name: "egain-loading_container-without-app", + status: 200, + url: "https://support.specialized.com/kb/sp_en-us/home", + title: "", + rawHTML: `

Loading...

`, + markdown: "Loading...", + wantExact: "empty_shell", + }, + { + name: "craigslist-deleted-posting-200", + status: 200, + url: "https://sfbay.craigslist.org/sfc/bik/d/123.html", + title: "craigslist | deleted", + rawHTML: `craigslist | deleted

This posting has been deleted by its author.

`, + markdown: "This posting has been deleted by its author.", + wantExact: "soft_404", + }, + { + name: "craigslist-blocked-title-200", + status: 200, + url: "https://sfbay.craigslist.org/sfc/bik/d/123.html", + title: "blocked", + rawHTML: `blocked

Your request has been blocked.

`, + markdown: "Your request has been blocked.", + wantExact: "temporarily_unavailable", + }, + { + name: "ul-prospector-warning-blocked-200", + status: 200, + url: "https://productiq.ulprospector.com/", + title: "Warning: Blocked - UL Prospector", + rawHTML: `Warning: Blocked - UL Prospector

Access Denied

Warning: Blocked - UL Prospector

`, + markdown: "Access Denied", + wantExact: "temporarily_unavailable", + }, + { + name: "depop-forbidden-title-200", + status: 200, + url: "https://www.depop.com/category/mens/", + title: "Forbidden - Depop", + rawHTML: `Forbidden - Depop

403 Forbidden

`, + markdown: "403 Forbidden", + wantExact: "temporarily_unavailable", + }, + { + name: "bot-need-challenge-html-200", + status: 200, + url: "https://www.backmarket.com/en-us/p/item/123", + title: "Challenge", + rawHTML: `Challenge
bot-need-challenge
`, + markdown: "bot-need-challenge", + wantExact: "temporarily_unavailable", + }, + { + name: "missing-authentication-token-html-200", + status: 200, + url: "https://support.specialized.com/api/item", + title: "", + rawHTML: `
{"message":"Missing Authentication Token"}
`, + markdown: "```\n{\"message\":\"Missing Authentication Token\"}\n```", + wantExact: "temporarily_unavailable", + }, + { + name: "missing-authentication-token-json-403", + status: 403, + url: "https://api.example.com/v1/item", + title: "", + rawHTML: `{"message":"Missing Authentication Token"}`, + markdown: "", + wantExact: "temporarily_unavailable", + }, + { + name: "positive-article-discussing-deleted-and-blocks-stays-active", + status: 200, + url: "https://docs.example.com/troubleshooting", + title: "Troubleshooting HTTP Error Responses in API Gateways", + rawHTML: `Troubleshooting HTTP Error Responses in API Gateways

Troubleshooting HTTP Error Responses in API Gateways

When building resilient web scrapers and API clients, engineers frequently encounter responses such as Missing Authentication Token from AWS API Gateway, bot-need-challenge anti-bot signals, loading_container placeholders in eGain support portals, and phrases like this posting has been deleted on classifieds sites. Understanding the difference between a real technical article and a thin negative shell requires checking word counts, structured JSON-LD metadata, and DOM density carefully so documentation pages remain active while genuine error shells are filtered cleanly across production pipelines. Furthermore, monitoring status codes alongside semantic content signals ensures high precision and zero false rejections across diverse web platforms and developer documentation portals.

`, + markdown: "Troubleshooting HTTP Error Responses in API Gateways. When building resilient web scrapers and API clients, engineers frequently encounter responses such as Missing Authentication Token from AWS API Gateway, bot-need-challenge anti-bot signals, loading_container placeholders in eGain support portals, and phrases like this posting has been deleted on classifieds sites. Understanding the difference between a real technical article and a thin negative shell requires checking word counts, structured JSON-LD metadata, and DOM density carefully so documentation pages remain active while genuine error shells are filtered cleanly across production pipelines. Furthermore, monitoring status codes alongside semantic content signals ensures high precision and zero false rejections across diverse web platforms and developer documentation portals.", + wantExact: "active", + }, + } + + for _, tc := range cases { + res := ClassifyContentStateFull(ContentStateInput{ + Status: tc.status, + URL: tc.url, + FinalURL: tc.url, + Title: tc.title, + RawHTML: tc.rawHTML, + Markdown: tc.markdown, + }) + if tc.wantExact != "" && res.State != tc.wantExact { + t.Fatalf("%s: got state=%q (%s), want %q", tc.name, res.State, res.Reason, tc.wantExact) + } + if tc.wantNot != "" && res.State == tc.wantNot { + t.Fatalf("%s: got state=%q (%s), must not be %q", tc.name, res.State, res.Reason, tc.wantNot) + } + } +} + +func TestClassifyContentStateWave3B6Remediations(t *testing.T) { + // 1. HASHCASH_CONFIG PoW interstitials (HTTP 200 / 403 / 429) must classify as challenge / temporarily_unavailable + powCases := []struct { + name string + status int + url string + title string + rawHTML string + markdown string + }{ + { + name: "patreon-hashcash-200", + status: 200, + url: "https://www.patreon.com/creators/example", + title: "Patreon", + rawHTML: `Patreon

Verifying your browser before redirecting...

`, + markdown: "Verifying your browser before redirecting...", + }, + { + name: "genius-hashcash-challenge-js-200", + status: 200, + url: "https://genius.com/Example-lyrics", + title: "Genius", + rawHTML: `Genius

Please wait while we verify your session.

`, + markdown: "Please wait while we verify your session.", + }, + { + name: "nos-lol-hashcash-403-45w", + status: 403, + url: "https://nos.lol/", + title: "Verification", + rawHTML: `Verification

` + strings.Repeat("Browser proof of work verification step required. ", 7) + `

`, + markdown: strings.Repeat("Browser proof of work verification step required. ", 7), + }, + { + name: "hashcash-429-45w", + status: 429, + url: "https://example.org/protected", + title: "Rate Limit Challenge", + rawHTML: `Rate Limit Challenge

` + strings.Repeat("Please wait while proof of work completes. ", 7) + `

`, + markdown: strings.Repeat("Please wait while proof of work completes. ", 7), + }, + } + + for _, tc := range powCases { + waf := ClassifyWAFAndChallengeFull(WAFChallengeInput{ + Status: tc.status, + URL: tc.url, + Title: tc.title, + RawHTML: tc.rawHTML, + Markdown: tc.markdown, + }) + if waf == nil || waf.Category != "challenge" || waf.Vendor != "generic" { + t.Fatalf("%s: ClassifyWAFAndChallengeFull got %+v, want vendor=generic category=challenge", tc.name, waf) + } + cs := ClassifyContentStateFull(ContentStateInput{ + Status: tc.status, + URL: tc.url, + FinalURL: tc.url, + Title: tc.title, + RawHTML: tc.rawHTML, + Markdown: tc.markdown, + }) + if cs.State != "temporarily_unavailable" { + t.Fatalf("%s: ClassifyContentStateFull got %q (%s), want temporarily_unavailable", tc.name, cs.State, cs.Reason) + } + } + + // 2. Negative anti-FP controls for HASHCASH_CONFIG: short prose mention (no JS assignment) and >=120-word blog with

+	shortProseHTML := `PoW Note

Tumblr uses HASHCASH_CONFIG for rate limiting.

` + shortProseMD := "Tumblr uses HASHCASH_CONFIG for rate limiting." + if got := ClassifyWAFAndChallengeFull(WAFChallengeInput{ + Status: 200, + URL: "https://blog.example.com/pow-note", + Title: "PoW Note", + RawHTML: shortProseHTML, + Markdown: shortProseMD, + }); got != nil { + t.Fatalf("short prose HASHCASH_CONFIG mention must NOT false-positive in ClassifyWAFAndChallengeFull, got %+v", got) + } + if cs := ClassifyContentStateFull(ContentStateInput{ + Status: 200, + URL: "https://blog.example.com/pow-note", + FinalURL: "https://blog.example.com/pow-note", + Title: "PoW Note", + RawHTML: shortProseHTML, + Markdown: shortProseMD, + }); cs.State != "active" { + t.Fatalf("short prose HASHCASH_CONFIG mention got state=%q (%s), want active", cs.State, cs.Reason) + } + + longBlogBody := strings.Repeat("Hashcash proof-of-work challenges protect public web endpoints from automated abuse without relying on invasive third-party tracking cookies or visual puzzles. ", 16) + longBlogHTML := `Hashcash Proof of Work Guide

Hashcash Proof of Work Guide

` + longBlogBody + `

window.HASHCASH_CONFIG = { difficulty: 4 };
` + longBlogMD := "# Hashcash Proof of Work Guide\n\n" + longBlogBody + "\n\n```\nwindow.HASHCASH_CONFIG = { difficulty: 4 };\n```\n" + if got := ClassifyWAFAndChallengeFull(WAFChallengeInput{ + Status: 200, + URL: "https://docs.example.com/hashcash", + Title: "Hashcash Proof of Work Guide", + RawHTML: longBlogHTML, + Markdown: longBlogMD, + }); got != nil { + t.Fatalf(">=120-word blog with
 HASHCASH_CONFIG must NOT false-positive in ClassifyWAFAndChallengeFull, got %+v", got)
+	}
+	if cs := ClassifyContentStateFull(ContentStateInput{
+		Status:   200,
+		URL:      "https://docs.example.com/hashcash",
+		FinalURL: "https://docs.example.com/hashcash",
+		Title:    "Hashcash Proof of Work Guide",
+		RawHTML:  longBlogHTML,
+		Markdown: longBlogMD,
+	}); cs.State != "active" {
+		t.Fatalf(">=120-word blog with 
 HASHCASH_CONFIG got state=%q (%s), want active", cs.State, cs.Reason)
+	}
+
+	// 3. energystar #main[data-basepath] empty shell WITH >= 15 words in 
`) - reWafNavAnchor = newLazyRegexp(`(?is)]*\bhref\s*=`) - reWafSchemaRichType = newLazyRegexp(`(?is)]*type\s*=\s*["']application/ld\+json["'][^>]*>[^<]*"@type"\s*:\s*(?:\[[^\]]*)?["'](?:Article|TechArticle|NewsArticle|BlogPosting|ScholarlyArticle|JobPosting|Product|SoftwareSourceCode|FAQPage|APIReference)["']`) + reWafHTMLComments = newLazyRegexp(`(?is)`) + reWafAnyTag = newLazyRegexp(`(?s)<[^>]+>`) + reWafTitle = newLazyRegexp(`(?is)]*>(.*?)`) + reWafMainOrArticle = newLazyRegexp(`(?is)<(?:main|article)\b[^>]*>(.*?)`) + reWafSubheadings = newLazyRegexp(`(?is)]*>.*?`) + reWafNavBlock = newLazyRegexp(`(?is)]*>(.*?)`) + reWafNavAnchor = newLazyRegexp(`(?is)]*\bhref\s*=`) + reWafSchemaRichType = newLazyRegexp(`(?is)]*type\s*=\s*["']application/ld\+json["'][^>]*>[^<]*"@type"\s*:\s*(?:\[[^\]]*)?["'](?:Article|TechArticle|NewsArticle|BlogPosting|ScholarlyArticle|JobPosting|Product|SoftwareSourceCode|FAQPage|APIReference)["']`) reCloudflareTitle = newLazyRegexp(`(?i)^\s*(?:just a moment\.{0,3}|attention required!\s*\|\s*cloudflare|ddos-guard|checking your browser)\s*$`) reGenericTitle = newLazyRegexp(`(?i)^\s*(?:verify you are human|human verification|pardon our interruption|access to this page has been denied|bot verification|security check)\s*$`) @@ -52,7 +49,7 @@ func extractRawTitle(raw string) string { // as challenges even if they embed a footer reCAPTCHA/hCaptcha or discuss WAFs/Turnstile in prose! func hasStructuralContentVeto(status int, rawHTML string) (veto bool, visibleWords int) { noComments := reWafHTMLComments.ReplaceAllString(rawHTML, " ") - visibleClean := reWafAllScriptsStrip.ReplaceAllString(reWafCodeQuoteStrip.ReplaceAllString(noComments, " "), " ") + visibleClean := stripWafDropBlocksLinearCSGo(noComments, true, false) visibleWords = countPlainWords(visibleClean) if status < 200 || status >= 300 { @@ -183,7 +180,7 @@ func ClassifyWAF(status int, header map[string][]string, body []byte) *WAFMatch } // --- Layer 3: Strip
, , 
, JSON-LD, and SSR hydration JSON before body pattern matching --- - scrubbed := reWafCodeQuoteStrip.ReplaceAllString(reWafScriptDataStrip.ReplaceAllString(rawStr, " "), " ") + scrubbed := stripWafDropBlocksLinearCSGo(stripWafDropBlocksLinearCSGo(rawStr, false, true), false, false) scrubbedLower := strings.ToLower(scrubbed) title := extractRawTitle(scrubbed) serverHdr := "" @@ -316,7 +313,8 @@ func ClassifyWAF(status int, header map[string][]string, body []byte) *WAFMatch } if strings.Contains(scrubbedLower, "checking your browser before accessing ") || strings.Contains(scrubbedLower, "please wait while we check your browser") || - (strings.Contains(scrubbedLower, "making sure you're not a bot") && strings.Contains(scrubbedLower, "anubis")) { + (strings.Contains(scrubbedLower, "making sure you're not a bot") && strings.Contains(scrubbedLower, "anubis")) || + hasHashcashPoWMarkersCSGo(scrubbedLower) { return &WAFMatch{ Vendor: "generic", Category: "challenge", @@ -327,5 +325,14 @@ func ClassifyWAF(status int, header map[string][]string, body []byte) *WAFMatch } } + // 10. Azure Front Door / Application Gateway WAF HTTP 406 block (< 60 visible words, <= 16 KiB body) + if status == 406 && len(body) <= 16_384 { + hasAzureHdr := header != nil && (headerGet(header, "x-azure-ref") != "" || headerGet(header, "x-fd-healthprobe") != "") + vis := stripWafDropBlocksLinearCSGo(stripHTMLCommentsLinearCSGo(rawStr), true, false) + if m := detectAzure406WafBlockCSGo(string(body), vis, hasAzureHdr); m != nil { + return m + } + } + return nil } diff --git a/internal/classify/waf_test.go b/internal/classify/waf_test.go index 87540ba..6d66157 100644 --- a/internal/classify/waf_test.go +++ b/internal/classify/waf_test.go @@ -684,3 +684,38 @@ func TestKasada403And429AndTurnstile403Classification(t *testing.T) { t.Fatalf("expected 403 login form to classify login_wall, got %+v", login403) } } + +func TestClassifyWAFHashcashPoWInterstitialsAndAntiFP(t *testing.T) { + // Positive PoW cases on HTTP 200 + for _, tc := range []struct { + name string + body string + }{ + { + name: "window.HASHCASH_CONFIG", + body: `Patreon

Verifying your browser before redirecting...

`, + }, + { + name: "/__challenge/challenge.js", + body: `Verification

Please wait while we verify your request.

`, + }, + } { + m := ClassifyWAF(200, http.Header{"Content-Type": []string{"text/html"}}, []byte(tc.body)) + if m == nil || m.Vendor != "generic" || m.Category != "challenge" { + t.Fatalf("%s: ClassifyWAF got %+v, want vendor=generic category=challenge", tc.name, m) + } + } + + // Negative anti-FP controls + shortProse := `PoW Note

Tumblr uses HASHCASH_CONFIG for rate limiting.

` + if got := ClassifyWAF(200, http.Header{"Content-Type": []string{"text/html"}}, []byte(shortProse)); got != nil { + t.Fatalf("short prose HASHCASH_CONFIG mention must NOT trigger ClassifyWAF, got %+v", got) + } + + longBlog := `Hashcash Guide

Hashcash Guide

` + + strings.Repeat("Hashcash proof-of-work challenges protect public endpoints without tracking cookies or visual captchas. ", 16) + + `

window.HASHCASH_CONFIG = { difficulty: 4 };
` + if got := ClassifyWAF(200, http.Header{"Content-Type": []string{"text/html"}}, []byte(longBlog)); got != nil { + t.Fatalf(">=120-word blog with
 HASHCASH_CONFIG must NOT trigger ClassifyWAF, got %+v", got)
+	}
+}
diff --git a/internal/extract/declarative.go b/internal/extract/declarative.go
index 03a5c34..5803fe8 100644
--- a/internal/extract/declarative.go
+++ b/internal/extract/declarative.go
@@ -818,6 +818,73 @@ func (m *DeclarativeTwinMatch) EffectiveMaxBytes() int {
 	return 4 << 20
 }
 
+// AllowCrossOriginRedirects reports whether this twin route is vetted to follow a trusted cross-origin CDN/S3 redirect.
+func (m *DeclarativeTwinMatch) AllowCrossOriginRedirects() bool {
+	if m == nil {
+		return false
+	}
+	id := m.AdapterID
+	if id == "" {
+		id = m.ID
+	}
+	if (id == "ofac-sdn" || m.ID == "ofac-sdn") && isOfacSdnTrustedSourceURLGo(m.FetchURL) {
+		return true
+	}
+	if (id == "musicbrainz-coverart" || m.ID == "musicbrainz-coverart") && isCoverArtArchiveSourceURLGo(m.FetchURL) {
+		return true
+	}
+	return false
+}
+
+// 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 (m *DeclarativeTwinMatch) AllowTruncatedStream() bool {
+	if m == nil {
+		return false
+	}
+	mb := m.EffectiveMaxBytes()
+	if mb <= 0 || mb > (4<<20) {
+		return false
+	}
+	id := m.AdapterID
+	if id == "" {
+		id = m.ID
+	}
+	if m.Kind == classify.KindText {
+		return id != "us-cfr-govinfo" && m.ID != "us-cfr-govinfo" && mb < (4<<20)
+	}
+	return id == "cms-price-transparency" || m.ID == "cms-price-transparency" || id == "web-compat-data" || m.ID == "web-compat-data"
+}
+
+// IsDomainSpecificExtractorID reports whether extractorID is a domain-specific adapter that preempts generic custom-domain storefront overlay enrichment.
+func IsDomainSpecificExtractorID(extractorID string) bool {
+	id := strings.ToLower(strings.TrimSpace(extractorID))
+	if id == "" || strings.HasPrefix(id, "schema-") {
+		return false
+	}
+	switch id {
+	case "shopify",
+		"woocommerce",
+		"bigcommerce-store",
+		"squarespace-commerce",
+		"sfcc-demandware",
+		"shopware-magento",
+		"shopify-hydrogen",
+		"shopify-storefront-graphql",
+		"shopify-filter-apps",
+		"aem",
+		"arc-xp",
+		"townnews-blox",
+		"brightspot",
+		"hubspot-cms",
+		"wordpress-vip-newspack",
+		"headless-commerce",
+		"headless-cms-delivery":
+		return false
+	default:
+		return true
+	}
+}
+
 type declarativeWildcard struct {
 	kind    string // "suffix", "prefix", or "infix"
 	pattern string
@@ -881,6 +948,68 @@ var approvedWildcardDomainPatternsGo = map[string]bool{
 	"*.zendesk.com":        true,
 	"*.giant-bicycles.com": true,
 	"*.liv-cycling.com":    true,
+	// Wave 3 B1 Category A
+	"*.civicclerk.com":      true,
+	"*.primegov.com":        true,
+	"*.escribemeetings.com": true,
+	"*.novusagenda.com":     true,
+	"*.civicweb.net":        true,
+	"*.opengov.com":         true,
+	"*.bonfirehub.com":      true,
+	"*.hub.arcgis.com":      true,
+	"*.opendata.arcgis.com": true,
+	"*.opendatasoft.com":    true,
+	"*.junar.com":           true,
+	// Wave 3 B1 Category B
+	"*.edlio.com":             true,
+	"*.apptegy.us":            true,
+	"*.sites.thrillshare.com": true,
+	"*.acalog.com":            true,
+	"*.coursedog.com":         true,
+	"*.instructure.com":       true,
+	// Wave 3 B1 Category C
+	"*.governmentjobs.com":   true,
+	"*.schooljobs.com":       true,
+	"*.bullhornstaffing.com": true,
+	"*.taleo.net":            true,
+	"*.paradox.ai":           true,
+	"*.jobdiva.com":          true,
+	"*.ceipal.com":           true,
+	"*.zohorecruit.com":      true,
+	"*.freshteam.com":        true,
+	"*.homerun.co":           true,
+	"*.healthcaresource.com": true,
+	// Wave 3 B2 Category E
+	"*.chambermaster.com": true,
+	"*.growthzoneapp.com": true,
+	"*.wildapricot.org":   true,
+	"*.memberclicks.net":  true,
+	"*.site-ym.com":       true,
+	// Wave 3 B2 Categories F/G/H
+	"*.appfolio.com":       true,
+	"*.managebuilding.com": true,
+	"*.propertyware.com":   true,
+	"*.rentmanager.com":    true,
+	"*.rentcafe.com":       true,
+	"*.entrata.com":        true,
+	"*.realpage.com":       true,
+	"*.idxbroker.com":      true,
+	"*.popmenu.com":        true,
+	"*.getbento.com":       true,
+	"*.q4web.com":          true,
+	"*.prowly.com":         true,
+	"*.prezly.com":         true,
+	// Wave 3 B2 Category I
+	"*.aftership.com": true,
+	"*.narvar.com":    true,
+	"*.gorgias.help":  true,
+	"*.reamaze.com":   true,
+	// Wave 3 B5 Category P
+	"*.craigslist.org":   true,
+	"*.gumroad.com":      true,
+	"*.lemonsqueezy.com": true,
+	// Wave 3 B6 Category R
+	"*.bandcamp.com": true,
 }
 
 var reservedCoreATSDomainsGo = map[string]bool{
@@ -905,6 +1034,22 @@ var approvedSAPATSExactExemptionsGo = map[string]bool{
 	"enterprise-ats:jobs.jobvite.com":         true,
 	"gem-ats:jobs.gem.com":                    true,
 	"ukg-paylocity-dover:jobs.dover.com":      true,
+	"paradox-olivia:jobs.mchire.com":          true,
+	"staffing-ats-pack:jobs.crelate.com":      true,
+	"smb-ats-full:jobs.manatal.com":           true,
+	"edu-job-boards:jobs.chronicle.com":       true,
+}
+
+var approvedPathDisjointExactExemptionsGo = map[string]bool{
+	"cpsc-ebike-incidents|cpsc-recalls:saferproducts.gov":     true,
+	"cpsc-ebike-incidents|cpsc-recalls:www.saferproducts.gov": true,
+}
+
+func isExemptPathDisjointExactClaimGo(ownerA, ownerB, exactDom string) bool {
+	if ownerA > ownerB {
+		ownerA, ownerB = ownerB, ownerA
+	}
+	return approvedPathDisjointExactExemptionsGo[ownerA+"|"+ownerB+":"+exactDom]
 }
 
 func claimedRegistrableDomainsGo(domains []string) map[string]bool {
@@ -1489,7 +1634,7 @@ func ValidateDeclarativeManifests(manifests []DeclarativeAdapterManifest) error
 				wildcardOwners[normDom] = m.ID
 				wildcardClaims = append(wildcardClaims, domainClaim{id: m.ID, pattern: normDom})
 			} else {
-				if prev, exists := exactOwners[normDom]; exists && prev != m.ID {
+				if prev, exists := exactOwners[normDom]; exists && prev != m.ID && !isExemptPathDisjointExactClaimGo(prev, m.ID, normDom) {
 					return fmt.Errorf("manifest %q duplicate domain %q overlaps claim by %q (H7)", m.ID, normDom, prev)
 				}
 				for _, prevWild := range wildcardClaims {
@@ -2284,136 +2429,6 @@ func (m *DeclarativeTwinMatch) ValidateRedirectTarget(finalURL string) bool {
 	return false
 }
 
-func buildResolvedTwinURLGo(route DeclarativeRouteSpec, u *url.URL, host string, params map[string]string) (string, bool) {
-	twin := route.Twin
-	var candidate string
-	if twin.FetchURL == "{requestUrl}" {
-		cloned := *u
-		cloned.Fragment = ""
-		cloned.User = nil
-		cloned.Host = host
-		if twin.OverridePathIf != nil {
-			cleanCur := strings.TrimRight(cloned.Path, "/")
-			if cleanCur == "" {
-				cleanCur = "/"
-			}
-			for _, mp := range twin.OverridePathIf.MatchPaths {
-				want := strings.TrimRight(mp, "/")
-				if want == "" {
-					want = "/"
-				}
-				if strings.EqualFold(cleanCur, want) {
-					cloned.Path = twin.OverridePathIf.NewPath
-					cloned.RawPath = ""
-					break
-				}
-			}
-		}
-		if len(twin.DefaultQueryParams) > 0 || len(twin.SetQueryParams) > 0 {
-			q := cloned.Query()
-			queryModified := false
-			for k, v := range twin.DefaultQueryParams {
-				if q.Get(k) == "" {
-					q.Set(k, v)
-					queryModified = true
-				}
-			}
-			for k, v := range twin.SetQueryParams {
-				if q.Get(k) != v || len(q[k]) != 1 {
-					q.Set(k, v)
-					queryModified = true
-				}
-			}
-			if queryModified {
-				keys := make([]string, 0, len(q))
-				for k := range q {
-					keys = append(keys, k)
-				}
-				sort.Slice(keys, func(i, j int) bool {
-					if keys[i] == "ss" && keys[j] == "in_iframe" {
-						return true
-					}
-					if keys[i] == "in_iframe" && keys[j] == "ss" {
-						return false
-					}
-					return keys[i] < keys[j]
-				})
-				var qParts []string
-				for _, k := range keys {
-					ek := url.QueryEscape(k)
-					for _, v := range q[k] {
-						qParts = append(qParts, ek+"="+url.QueryEscape(v))
-					}
-				}
-				cloned.RawQuery = strings.Join(qParts, "&")
-			}
-		}
-		candidate = cloned.String()
-	} else {
-		rawSet := make(map[string]bool, len(twin.RawPathParams))
-		for _, rp := range twin.RawPathParams {
-			rawSet[rp] = true
-		}
-		candidate = expandTemplate(twin.FetchURL, func(key string) string {
-			switch key {
-			case "host":
-				return host
-			case "origin":
-				return "https://" + host
-			case "baseCleanUrl":
-				return "https://" + host + strings.TrimRight(u.Path, "/")
-			}
-			val := params[key]
-			if rawSet[key] {
-				return encodeSafeSubpath(val)
-			}
-			return encodeURIComponent(val)
-		})
-	}
-	if !isSafePublicTwinURL(candidate) {
-		return "", false
-	}
-	return candidate, true
-}
-
-func normalizeDeclarativeAccept(kind, rawAccept string) string {
-	if kind != "text" {
-		if strings.TrimSpace(rawAccept) == "" {
-			return "application/json"
-		}
-		return strings.TrimSpace(rawAccept)
-	}
-	trimmed := strings.ToLower(strings.TrimSpace(rawAccept))
-	if isAllowedGoKindTextAcceptGo(trimmed) {
-		return trimmed
-	}
-	for _, rawPart := range strings.Split(trimmed, ",") {
-		primary := strings.TrimSpace(strings.SplitN(rawPart, ";", 2)[0])
-		if isAllowedGoKindTextAcceptGo(primary) {
-			return primary
-		}
-	}
-	return "text/plain"
-}
-
-func isAllowedGoKindTextAcceptGo(mime string) bool {
-	switch mime {
-	case "text/html", "text/markdown", "text/x-markdown", "application/xml", "text/xml", "application/rss+xml", "application/atom+xml", "application/json", "text/calendar", "text/plain":
-		return true
-	default:
-		return false
-	}
-}
-
-func isSafePublicHostnameGo(h string) bool {
-	return IsSafePublicHostname(h)
-}
-
-// IsSafeDeclarativeTwinURL reports whether raw is a safe public HTTPS declarative twin URL.
-func IsSafeDeclarativeTwinURL(raw string) bool {
-	return isSafePublicTwinURL(raw)
-}
-
 var (
 	reWorkdayHostTenantGo     = newLazyRegexp(`^([a-z0-9-]+)\.(?:wd\d+\.)?(myworkday(?:jobs|site)\.com)$`)
 	reTwinRedirectErrorPathGo = newLazyRegexp(`(?i)(?:^|/)(?:errors?|40[34](?:-page)?|not-?found|page-?not-?found(?:-sub)?|notfound|sorrypages?)(?:\.[a-z0-9]{1,8})?(?:/|$)`)
@@ -2601,6 +2616,146 @@ func ValidateTwinRedirectFull(twinID, initialFetchURL, finalURL, selfHost string
 	return false, errorPage
 }
 
+func buildResolvedTwinURLGo(route DeclarativeRouteSpec, u *url.URL, host string, params map[string]string) (string, bool) {
+	twin := route.Twin
+	var candidate string
+	if twin.FetchURL == "{requestUrl}" {
+		cloned := *u
+		cloned.Fragment = ""
+		cloned.User = nil
+		cloned.Host = host
+		if twin.OverridePathIf != nil {
+			cleanCur := strings.TrimRight(cloned.Path, "/")
+			if cleanCur == "" {
+				cleanCur = "/"
+			}
+			for _, mp := range twin.OverridePathIf.MatchPaths {
+				want := strings.TrimRight(mp, "/")
+				if want == "" {
+					want = "/"
+				}
+				if strings.EqualFold(cleanCur, want) {
+					cloned.Path = twin.OverridePathIf.NewPath
+					cloned.RawPath = ""
+					break
+				}
+			}
+		}
+		if len(twin.DefaultQueryParams) > 0 || len(twin.SetQueryParams) > 0 {
+			q := cloned.Query()
+			queryModified := false
+			for k, v := range twin.DefaultQueryParams {
+				if q.Get(k) == "" {
+					q.Set(k, v)
+					queryModified = true
+				}
+			}
+			for k, v := range twin.SetQueryParams {
+				var toDelete []string
+				for existingKey := range q {
+					if existingKey != k && strings.EqualFold(existingKey, k) {
+						toDelete = append(toDelete, existingKey)
+					}
+				}
+				for _, dk := range toDelete {
+					q.Del(dk)
+					queryModified = true
+				}
+				if q.Get(k) != v || len(q[k]) != 1 {
+					q.Set(k, v)
+					queryModified = true
+				}
+			}
+			if queryModified {
+				keys := make([]string, 0, len(q))
+				for k := range q {
+					keys = append(keys, k)
+				}
+				sort.Slice(keys, func(i, j int) bool {
+					if keys[i] == "ss" && keys[j] == "in_iframe" {
+						return true
+					}
+					if keys[i] == "in_iframe" && keys[j] == "ss" {
+						return false
+					}
+					return keys[i] < keys[j]
+				})
+				var qParts []string
+				for _, k := range keys {
+					ek := url.QueryEscape(k)
+					for _, v := range q[k] {
+						qParts = append(qParts, ek+"="+url.QueryEscape(v))
+					}
+				}
+				cloned.RawQuery = strings.Join(qParts, "&")
+			}
+		}
+		candidate = cloned.String()
+	} else {
+		rawSet := make(map[string]bool, len(twin.RawPathParams))
+		for _, rp := range twin.RawPathParams {
+			rawSet[rp] = true
+		}
+		candidate = expandTemplate(twin.FetchURL, func(key string) string {
+			switch key {
+			case "host":
+				return host
+			case "origin":
+				return "https://" + host
+			case "baseCleanUrl":
+				return "https://" + host + strings.TrimRight(u.Path, "/")
+			}
+			val := params[key]
+			if rawSet[key] {
+				return encodeSafeSubpath(val)
+			}
+			return encodeURIComponent(val)
+		})
+	}
+	if !isSafePublicTwinURL(candidate) {
+		return "", false
+	}
+	return candidate, true
+}
+
+func normalizeDeclarativeAccept(kind, rawAccept string) string {
+	if kind != "text" {
+		if strings.TrimSpace(rawAccept) == "" {
+			return "application/json"
+		}
+		return strings.TrimSpace(rawAccept)
+	}
+	trimmed := strings.ToLower(strings.TrimSpace(rawAccept))
+	if isAllowedGoKindTextAcceptGo(trimmed) {
+		return trimmed
+	}
+	for _, rawPart := range strings.Split(trimmed, ",") {
+		primary := strings.TrimSpace(strings.SplitN(rawPart, ";", 2)[0])
+		if isAllowedGoKindTextAcceptGo(primary) {
+			return primary
+		}
+	}
+	return "text/plain"
+}
+
+func isAllowedGoKindTextAcceptGo(mime string) bool {
+	switch mime {
+	case "text/html", "text/markdown", "text/x-markdown", "application/xml", "text/xml", "application/rss+xml", "application/atom+xml", "application/json", "text/calendar", "text/plain":
+		return true
+	default:
+		return false
+	}
+}
+
+func isSafePublicHostnameGo(h string) bool {
+	return IsSafePublicHostname(h)
+}
+
+// IsSafeDeclarativeTwinURL reports whether raw is a safe public HTTPS declarative twin URL.
+func IsSafeDeclarativeTwinURL(raw string) bool {
+	return isSafePublicTwinURL(raw)
+}
+
 // FormatJSONWithExtractSpec formats a raw JSON/Inertia twin payload against an explicit DeclarativeExtractSpec and route params.
 func FormatJSONWithExtractSpec(rawBody string, ext DeclarativeExtractSpec, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool) {
 	if params == nil {
@@ -3496,6 +3651,9 @@ func matchDeclarativeRoute(spec DeclarativeMatchSpec, u *url.URL, host string, r
 			} else if !validateDeclarativeParam(val, qp.Charset, qp.AllowValues, nil, qp.MinLen, qp.MaxLen) {
 				return nil, false
 			}
+			if qp.Charset == "cpsc_query_term" {
+				val = strings.TrimSpace(val)
+			}
 			transformed := applyParamTransformGo(val, qp.Transform)
 			if qp.Transform == "strip_dashes" && !validateDeclarativeParam(transformed, qp.Charset, qp.AllowValues, nil, qp.MinLen, qp.MaxLen) {
 				return nil, false
@@ -3584,6 +3742,18 @@ func validateDeclarativeParam(val, charset string, allowValues, reserved []strin
 			}
 		}
 		return true
+	case "cpsc_query_term":
+		trimmed := strings.TrimSpace(val)
+		if len(trimmed) < minLen || len(trimmed) > maxLen || strings.Contains(trimmed, "..") {
+			return false
+		}
+		for i := 0; i < len(trimmed); i++ {
+			b := trimmed[i]
+			if !isASCIIAlnum(b) && b != '.' && b != '_' && b != '~' && b != '-' && b != ' ' {
+				return false
+			}
+		}
+		return true
 	case "pkg":
 		for i := 0; i < len(val); i++ {
 			b := val[i]
@@ -4926,6 +5096,36 @@ func (m *DeclarativeTwinMatch) formatTextTwin(rawBody string) (*DeclarativeForma
 	if IsWave2dSportsMiscTextMode(ext.TextMode) {
 		return FormatWave2dSportsMiscTextDoc(ext.TextMode, rawBody, m.params, m.origURL)
 	}
+	if IsWave3GovTextMode(ext.TextMode) {
+		return FormatWave3GovTextDoc(ext.TextMode, rawBody, m.params, m.origURL)
+	}
+	if IsWave3PropRestIRTextMode(ext.TextMode) {
+		return FormatWave3PropRestIRTextDoc(ext.TextMode, rawBody, m.params, m.origURL)
+	}
+	if IsWave3TradeTextMode(ext.TextMode) {
+		return FormatWave3TradeTextDoc(ext.TextMode, rawBody, m.params, m.origURL)
+	}
+	if IsWave3RegulatorsHealthTextMode(ext.TextMode) {
+		return FormatWave3RegulatorsHealthTextDoc(ext.TextMode, rawBody, m.params, m.origURL)
+	}
+	if IsWave3ScholarlyTextMode(ext.TextMode) {
+		return FormatWave3ScholarlyTextDoc(ext.TextMode, rawBody, m.params, m.origURL)
+	}
+	if isWave3SecurityIntelTextMode(ext.TextMode) {
+		return formatWave3SecurityIntelText(ext.TextMode, rawBody, m.params, m.origURL)
+	}
+	if IsWave3DevInfraTextMode(ext.TextMode) {
+		return FormatWave3DevInfraTextDoc(ext.TextMode, rawBody, m.params, m.origURL)
+	}
+	if IsWave3GTINIdentityTextMode(ext.TextMode) {
+		return FormatWave3GTINIdentityTextDoc(ext.TextMode, rawBody, m.params, m.origURL)
+	}
+	if IsWave3MediaLyricsTextMode(ext.TextMode) {
+		return FormatWave3MediaLyricsTextDoc(ext.TextMode, rawBody, m.params, m.origURL)
+	}
+	if IsWave3FinanceTextMode(ext.TextMode) {
+		return FormatWave3FinanceTextDoc(ext.TextMode, rawBody, m.params, m.origURL)
+	}
 	if ext.JSONSource == "inertia_data_page" {
 		jsonBytes, ok := extractInertiaDataPageBytesGo(rawBody)
 		if !ok {
@@ -5727,6 +5927,63 @@ func (m *DeclarativeTwinMatch) formatJSONBytesTwin(rawBytes []byte, ext Declarat
 	if IsWave2UpgradedJSONMode(ext.JSONMode) {
 		return FormatWave2UpgradedJSONDoc(ext.JSONMode, rawBytes, m.params, m.origURL)
 	}
+	if IsWave3GovJSONMode(ext.JSONMode) {
+		return FormatWave3GovJSONDoc(ext.JSONMode, rawBytes, m.params, m.origURL)
+	}
+	if IsWave3EduJSONMode(ext.JSONMode) {
+		return FormatWave3EduJSONDoc(ext.JSONMode, rawBytes, m.params, m.origURL)
+	}
+	if IsWave3JobsPublicJSONMode(ext.JSONMode) {
+		return FormatWave3JobsPublicJSONDoc(ext.JSONMode, rawBytes, m.params, m.origURL)
+	}
+	if IsWave3CommunityJSONMode(ext.JSONMode) {
+		return FormatWave3CommunityJSONDoc(ext.JSONMode, rawBytes, m.params, m.origURL)
+	}
+	if IsWave3PropRestIRJSONMode(ext.JSONMode) {
+		return FormatWave3PropRestIRJSONDoc(ext.JSONMode, rawBytes, m.params, m.origURL)
+	}
+	if IsWave3StoreAddonsJSONMode(ext.JSONMode) {
+		return FormatWave3StoreAddonsJSONDoc(ext.JSONMode, rawBytes, m.params, m.origURL)
+	}
+	if IsWave3TradeJSONMode(ext.JSONMode) {
+		return FormatWave3TradeJSONDoc(ext.JSONMode, rawBytes, m.params, m.origURL)
+	}
+	if IsWave3RegulatorsJSONMode(ext.JSONMode) {
+		return FormatWave3RegulatorsJSONDoc(ext.JSONMode, rawBytes, m.params, m.origURL)
+	}
+	if IsWave3RegulatorsHealthJSONMode(ext.JSONMode) {
+		return FormatWave3RegulatorsHealthJSONDoc(ext.JSONMode, rawBytes, m.params, m.origURL)
+	}
+	if IsWave3ScholarlyJSONMode(ext.JSONMode) {
+		return FormatWave3ScholarlyJSONDoc(ext.JSONMode, rawBytes, m.params, m.origURL)
+	}
+	if isWave3SecurityIntelJSONMode(ext.JSONMode) {
+		return formatWave3SecurityIntelJSON(ext.JSONMode, rawBytes, m.params, m.origURL)
+	}
+	if IsWave3DevInfraJSONMode(ext.JSONMode) {
+		return FormatWave3DevInfraJSONDoc(ext.JSONMode, rawBytes, m.params, m.origURL)
+	}
+	if IsWave3CyclingComponentsJSONMode(ext.JSONMode) {
+		return FormatWave3CyclingComponentsJSONDoc(ext.JSONMode, rawBytes, m.params, m.origURL)
+	}
+	if IsWave3CyclingOEMsJSONMode(ext.JSONMode) {
+		return FormatWave3CyclingOEMsJSONDoc(ext.JSONMode, rawBytes, m.params, m.origURL)
+	}
+	if IsWave3ResaleJSONMode(ext.JSONMode) {
+		return FormatWave3ResaleJSONDoc(ext.JSONMode, rawBytes, m.params, m.origURL)
+	}
+	if IsWave3GTINIdentityJSONMode(ext.JSONMode) {
+		return FormatWave3GTINIdentityJSONDoc(ext.JSONMode, rawBytes, m.params, m.origURL)
+	}
+	if IsWave3MediaLyricsJSONMode(ext.JSONMode) {
+		return FormatWave3MediaLyricsJSONDoc(ext.JSONMode, rawBytes, m.params, m.origURL)
+	}
+	if IsWave3FinanceJSONMode(ext.JSONMode) {
+		return FormatWave3FinanceJSONDoc(ext.JSONMode, rawBytes, m.params, m.origURL)
+	}
+	if IsWave3SocialCreatorJSONMode(ext.JSONMode) {
+		return FormatWave3SocialCreatorJSONDoc(ext.JSONMode, rawBytes, m.params, m.origURL)
+	}
 	var rootObj map[string]any
 	var selectiveCache *selectiveJSONCache
 	unwrappedArray := false
diff --git a/internal/extract/declarative_html.go b/internal/extract/declarative_html.go
index b895821..f5f1063 100644
--- a/internal/extract/declarative_html.go
+++ b/internal/extract/declarative_html.go
@@ -4635,6 +4635,230 @@ func firstNonWhitespaceByteDeclHTML(s string) byte {
 	return 0
 }
 
+func hasHTMLTagPrefixDeclHTML(lower string, prefix string) bool {
+	off := 0
+	for {
+		idx := strings.Index(lower[off:], prefix)
+		if idx < 0 {
+			return false
+		}
+		end := off + idx + len(prefix)
+		if end < len(lower) {
+			next := lower[end]
+			if next == '>' || next == '/' || next == ' ' || next == '\t' || next == '\n' || next == '\r' {
+				return true
+			}
+		}
+		off = end
+	}
+}
+
+func hasEmptyAppOrDivMountDeclHTML(probe, probeLower string) bool {
+	if strings.Contains(probeLower, `data-ng-app="app.main"`) || strings.Contains(probeLower, `data-ng-app='app.main'`) {
+		return true
+	}
+	if strings.Contains(probeLower, "loading_container") {
+		cachedGtLC := -1
+		offLC := 0
+		for offLC < len(probeLower) {
+			idx := strings.Index(probeLower[offLC:], "loading_container")
+			if idx < 0 {
+				break
+			}
+			mPos := offLC + idx
+			offLC = mPos + len("loading_container")
+			k := mPos - 1
+			for k >= 0 && probeLower[k] != '<' && probeLower[k] != '>' {
+				k--
+			}
+			if k < 0 || probeLower[k] != '<' {
+				continue
+			}
+			if cachedGtLC < mPos {
+				gtRel := strings.IndexByte(probeLower[mPos:], '>')
+				if gtRel < 0 {
+					break
+				}
+				cachedGtLC = mPos + gtRel
+			}
+			if strings.IndexByte(probeLower[k+1:cachedGtLC], '<') >= 0 {
+				continue
+			}
+			attrStart := k + 1
+			for attrStart < cachedGtLC && !isHTMLWsByteDeclHTML(probeLower[attrStart]) && probeLower[attrStart] != '/' {
+				attrStart++
+			}
+			if attrStart < cachedGtLC && attrHasTokenLinearDeclHTML(probe[attrStart:cachedGtLC], "class", "loading_container") {
+				return true
+			}
+		}
+	}
+	for _, customTag := range []string{"app-root", "hts-root"} {
+		openNeedle := "<" + customTag
+		closeNeedle := ""
+		cachedGt := -1
+		off := 0
+		for off < len(probeLower) {
+			idx := strings.Index(probeLower[off:], openNeedle)
+			if idx < 0 {
+				break
+			}
+			tagStart := off + idx
+			afterName := tagStart + len(openNeedle)
+			if afterName >= len(probeLower) {
+				break
+			}
+			nc := probeLower[afterName]
+			if nc == '>' || nc == ' ' || nc == '\t' || nc == '\n' || nc == '\r' {
+				if cachedGt < afterName {
+					gtRel := strings.IndexByte(probeLower[afterName:], '>')
+					if gtRel < 0 {
+						break
+					}
+					cachedGt = afterName + gtRel
+				}
+				if ltRel := strings.IndexByte(probeLower[afterName:cachedGt], '<'); ltRel >= 0 {
+					off = afterName + ltRel
+					continue
+				}
+				innerStart := cachedGt + 1
+				trimmedRest := strings.TrimLeft(probeLower[innerStart:], " \t\r\n")
+				if strings.HasPrefix(trimmedRest, closeNeedle) {
+					return true
+				}
+				off = innerStart
+				continue
+			}
+			off = afterName
+		}
+	}
+	cachedGtDiv := -1
+	off := 0
+	for off < len(probeLower) {
+		idx := strings.Index(probeLower[off:], "= len(probeLower) {
+			break
+		}
+		nc := probeLower[afterName]
+		if nc == ' ' || nc == '\t' || nc == '\n' || nc == '\r' {
+			if cachedGtDiv < afterName {
+				gtRel := strings.IndexByte(probeLower[afterName:], '>')
+				if gtRel < 0 {
+					break
+				}
+				cachedGtDiv = afterName + gtRel
+			}
+			if ltRel := strings.IndexByte(probeLower[afterName:cachedGtDiv], '<'); ltRel >= 0 {
+				off = afterName + ltRel
+				continue
+			}
+			attrStr := probe[afterName:cachedGtDiv]
+			if idVal, hasID := getAttrValueLinearDeclHTML(attrStr, "id"); hasID {
+				switch strings.ToLower(strings.TrimSpace(idVal)) {
+				case "root", "app", "application", "__next", "react-root":
+					innerStart := cachedGtDiv + 1
+					trimmedRest := strings.TrimLeft(probeLower[innerStart:], " \t\r\n")
+					if strings.HasPrefix(trimmedRest, "
") { + return true + } + } + } + off = cachedGtDiv + 1 + continue + } + off = afterName + } + return false +} + +// IsObviousUnhydratedCSRShell reports whether rawHTML is an empty client-side SPA mount shell without SSR or JSON-LD content. +func IsObviousUnhydratedCSRShell(rawHTML string) bool { + if rawHTML == "" { + return false + } + firstByte := firstNonWhitespaceByteDeclHTML(rawHTML) + if firstByte == 0 || firstByte == '{' || firstByte == '[' { + return false + } + if strings.IndexByte(rawHTML, '<') < 0 || strings.IndexByte(rawHTML, '>') < 0 { + return false + } + probe := rawHTML + if len(probe) > 262_144 { + probe = probe[:262_144] + } + probeLower := strings.ToLower(probe) + if !hasEmptyAppOrDivMountDeclHTML(probe, probeLower) { + return false + } + fullLower := probeLower + if len(rawHTML) > len(probe) { + fullLower = strings.ToLower(rawHTML) + } + if hasHTMLTagPrefixDeclHTML(fullLower, " 1_048_576 { + sliced = truncateUTF8SafeFullDocGo(sliced, 1_048_576) + } + if lastOpen := strings.LastIndex(sliced, "") { + sliced = sliced[:lastOpen] + } + if strings.HasSuffix(sliced, " scanCap { scanCap = opts.MaxScanChars } + if !opts.IsFragment && isBgpHeNetBaseURLGo(baseURL) { + rawHTML = trimBgpHeNetTruncatedHTMLGo(rawHTML) + } boundedRawHTML := truncateUTF8SafeFullDocGo(rawHTML, scanCap) if strings.IndexByte(boundedRawHTML, 0) >= 0 { boundedRawHTML = strings.ReplaceAll(boundedRawHTML, "\x00", "") @@ -7939,37 +7945,43 @@ func ExtractHTMLDocumentFull(rawHTML string, opts FullExtractOptions) ExtractedD if siteTruncated != nil && *siteTruncated { truncated = true } + authoritativeAdapter := extractorID == "browser-addons-amo-cws" + skipOverlay := authoritativeAdapter || IsDomainSpecificExtractorID(extractorID) + unhydratedShell := !opts.IsFragment && IsObviousUnhydratedCSRShell(boundedRawHTML) return ExtractedDocumentFull{ - Title: title, - Description: description, - Author: author, - PublishedTime: publishedTime, - ModifiedTime: modifiedTime, - SiteName: siteName, - WordCount: wordCount, - Language: language, - Favicon: favicon, - OGImage: ogImage, - CanonicalURL: canonicalURL, - MarkdownAlternateURL: markdownAlternateURL, - RobotsMeta: robotsMeta, - ExtractorID: extractorID, - Records: siteRecords, - Total: siteTotal, - Returned: siteReturned, - NextCursor: siteNextCursor, - InertiaHydrated: inertiaHydrated, - Markdown: finalMD, - RawSanitizedMarkdown: rawSanitizedMD, - Text: plainText, - Links: links, - Images: images, - Branding: branding, - StructuredData: jsonLdEntities, - TotalChars: totalChars, - ReturnedChars: returnedChars, - Truncated: truncated, - NextOffset: nextOffset, + Title: title, + Description: description, + Author: author, + PublishedTime: publishedTime, + ModifiedTime: modifiedTime, + SiteName: siteName, + WordCount: wordCount, + Language: language, + Favicon: favicon, + OGImage: ogImage, + CanonicalURL: canonicalURL, + MarkdownAlternateURL: markdownAlternateURL, + RobotsMeta: robotsMeta, + ExtractorID: extractorID, + Records: siteRecords, + Total: siteTotal, + Returned: siteReturned, + NextCursor: siteNextCursor, + UnhydratedCSRShell: unhydratedShell, + Authoritative: authoritativeAdapter, + SkipOverlayEnrichment: skipOverlay, + InertiaHydrated: inertiaHydrated, + Markdown: finalMD, + RawSanitizedMarkdown: rawSanitizedMD, + Text: plainText, + Links: links, + Images: images, + Branding: branding, + StructuredData: jsonLdEntities, + TotalChars: totalChars, + ReturnedChars: returnedChars, + Truncated: truncated, + NextOffset: nextOffset, } } diff --git a/internal/extract/m3_html_modes.go b/internal/extract/m3_html_modes.go index 1b00a02..dff3638 100644 --- a/internal/extract/m3_html_modes.go +++ b/internal/extract/m3_html_modes.go @@ -1788,6 +1788,10 @@ func collectTechDocPDFLinksDeclHTML(doc *HTMLDoc, base *url.URL) []string { } func runSramDocsExtractorDeclHTML(ctx *htmlExtractContextDeclHTML, extractorID string) *DeclarativePostFetchResult { + trimmed := strings.TrimLeft(ctx.rawHTML, "\ufeff \t\r\n") + if trimmed == "" || trimmed[0] == '{' || trimmed[0] == '[' || strings.IndexByte(trimmed, '<') < 0 || strings.IndexByte(trimmed, '>') < 0 { + return nil + } bounded := truncateUTF8SafeFullDocGo(ctx.rawHTML, HardMaxHTMLDocChars) cleaned := stripDataImageURIsDeclHTML(bounded) cleaned = stripDropTagsLinearDeclHTML(cleaned, map[string]bool{ diff --git a/internal/extract/m3_html_modes_test.go b/internal/extract/m3_html_modes_test.go index bacc2e8..e6abe70 100644 --- a/internal/extract/m3_html_modes_test.go +++ b/internal/extract/m3_html_modes_test.go @@ -1092,3 +1092,36 @@ func TestM3XenForoVerticalScopeAndSramManualData(t *testing.T) { t.Fatalf("expected empty sram-docs manual-data shell to be rejected, got %+v", resEmpty) } } + +func TestM3SramDocsRejectsJSONAndHostileAngles(t *testing.T) { + u, err := url.Parse("https://docs.sram.com/en-US/publications/2eIzVnWuTRM7vhoKQjadQr") + if err != nil { + t.Fatalf("url.Parse failed: %v", err) + } + noopMD := func(rawHTML, baseURL string) (string, []string) { + return "", nil + } + + payloads := []string{ + `{"title":"<<<<"}`, + "\ufeff \n\t" + `{"title":"` + strings.Repeat("<", 35_000) + `","summary":"` + strings.Repeat(``, 1_500) + `"}`, + `[{"title":"<<<<"}]`, + "", + "plain text without tags", + " api.biorxiv.org twin)." +domains: + - api.biorxiv.org + - www.biorxiv.org + - biorxiv.org + - www.medrxiv.org + - medrxiv.org +auth_mode: pub +min_interval_ms: 1000 +exampleUrls: + - "https://api.biorxiv.org/details/biorxiv/10.1101/2020.09.02.278911/na/json" + - "https://api.biorxiv.org/details/medrxiv/10.1101/2020.05.28.20116129/na/json" + - "https://www.biorxiv.org/content/10.1101/2020.09.02.278911v1" + +routes: + - match: + hosts: + - api.biorxiv.org + pathPrefix: /details/ + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: biorxiv_medrxiv_json + +htmlRoutes: + - id: biorxiv-medrxiv + match: + hosts: + - www.biorxiv.org + - biorxiv.org + - www.medrxiv.org + - medrxiv.org + exactSegments: false + mode: biorxiv_medrxiv_html diff --git a/internal/extract/manifests/bis-entity-list.yaml b/internal/extract/manifests/bis-entity-list.yaml new file mode 100644 index 0000000..f543ef9 --- /dev/null +++ b/internal/extract/manifests/bis-entity-list.yaml @@ -0,0 +1,24 @@ +# Shared Go + TypeScript Declarative Site Adapter: BIS Entity List & EAR (#277) +id: bis-entity-list +name: BIS Export Administration Regulations & Entity List +category: public-records +description: "Extracts Bureau of Industry and Security (BIS) EAR Part 744 / Entity List guidance and enforcement press releases from www.bis.gov, bis.gov, and media.bis.gov." +domains: + - www.bis.gov + - bis.gov + - media.bis.gov +auth_mode: pub +exampleUrls: + - "https://www.bis.gov/about-bis" + - "https://www.bis.gov/press-release/bis-issues-rule-addressing-remote-access-american-super-intelligence-technology" + - "https://www.bis.gov/press-release/bis-reaches-administrative-enforcement-settlement-lambda-research-corporation" + +htmlRoutes: + - id: bis-entity-list + match: + hosts: + - www.bis.gov + - bis.gov + - media.bis.gov + exactSegments: false + mode: bis_entity_list_html diff --git a/internal/extract/manifests/bitbucket-cloud.yaml b/internal/extract/manifests/bitbucket-cloud.yaml new file mode 100644 index 0000000..808c460 --- /dev/null +++ b/internal/extract/manifests/bitbucket-cloud.yaml @@ -0,0 +1,61 @@ +# Shared Go + TypeScript Declarative Site Adapter: Bitbucket Cloud (#327) +id: bitbucket-cloud +name: Bitbucket Cloud +category: developer +description: "Extracts repository, pull request, and issue metadata from Bitbucket Cloud REST 2.0 JSON endpoints and bitbucket.org repository URLs with CSR SPA shell guards." +domains: + - api.bitbucket.org + - bitbucket.org +auth_mode: pub +exampleUrls: + - "https://api.bitbucket.org/2.0/repositories/atlassian/aui" + - "https://bitbucket.org/atlassian/aui" + +routes: + - match: + hosts: + - api.bitbucket.org + pathPrefix: /2.0/repositories/ + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: bitbucket_json + + - match: + hosts: + - bitbucket.org + exactSegments: true + pathSegments: + - param: ws + charset: pkg + reserved: + - account + - dashboard + - repo + - product + - features + - enterprise + - blog + - plans + - security + - support + - param: repo + charset: pkg + twin: + fetchUrl: "https://api.bitbucket.org/2.0/repositories/{ws}/{repo}" + kind: json + accept: application/json + maxBytes: 1048576 + extract: + jsonMode: bitbucket_json + +htmlRoutes: + - id: bitbucket-cloud + match: + hosts: + - bitbucket.org + exactSegments: false + mode: bitbucket_html diff --git a/internal/extract/manifests/blackboard-wcm.yaml b/internal/extract/manifests/blackboard-wcm.yaml new file mode 100644 index 0000000..a2152f8 --- /dev/null +++ b/internal/extract/manifests/blackboard-wcm.yaml @@ -0,0 +1,27 @@ +# Shared Go + TypeScript Declarative Site Adapter: Blackboard WCM / SchoolMessenger Presence (#218) +id: blackboard-wcm +name: "Blackboard WCM & SchoolMessenger Presence" +category: public-records +description: "Extracts Blackboard Web Community Manager (Schoolwires) and SchoolMessenger Presence K-12 district news, calendars, and staff directories while excluding Finalsite /fs/ sites." +domains: + - www.bhusd.org + - bhusd.org + - www.neshaminy.org +universalEngine: true +auth_mode: html +strict_robots: true +min_interval_ms: 2000 +exampleUrls: + - "https://www.neshaminy.org/our_district/neshaminy_newsroom" + - "https://www.bhusd.org/media/filter/news" + +htmlRoutes: + - id: blackboard-wcm + match: + excludeHosts: + - www.finalsite.com + - finalsite.com + - www.greenwichschools.org + - www.choate.edu + exactSegments: false + mode: blackboard_wcm_html diff --git a/internal/extract/manifests/boarddocs.yaml b/internal/extract/manifests/boarddocs.yaml new file mode 100644 index 0000000..35a8b27 --- /dev/null +++ b/internal/extract/manifests/boarddocs.yaml @@ -0,0 +1,44 @@ +# Shared Go + TypeScript Declarative Site Adapter: BoardDocs (#204) +id: boarddocs +name: Diligent BoardDocs Public Meeting Portals +category: public-records +description: "Extracts public school board and municipal BoardDocs meeting lists, agendas, and HTML views while detecting CloudFront blocks." +domains: + - go.boarddocs.com +auth_mode: pub +strict_robots: true +exampleUrls: + - "https://go.boarddocs.com/ca/sandi/Board.nsf/BD-GetMeetingsList" + - "https://go.boarddocs.com/ca/sandi/Board.nsf/Public" + +routes: + - match: + exactSegments: true + pathSegments: + - param: state + charset: alnum_dash + minLen: 2 + maxLen: 8 + - param: org + charset: alnum_dash + minLen: 2 + maxLen: 48 + - Board.nsf + - param: action + allowValues: + - BD-GetMeetingsList + - BD-GetAgenda + - BD-GetAgendaItem + twin: + fetchUrl: "{requestUrl}" + kind: text + accept: application/xml + maxBytes: 4194304 + extract: + textMode: boarddocs_text + +htmlRoutes: + - id: boarddocs + match: + exactSegments: false + mode: boarddocs_html diff --git a/internal/extract/manifests/branded-tracking-pack.yaml b/internal/extract/manifests/branded-tracking-pack.yaml new file mode 100644 index 0000000..19dd6d1 --- /dev/null +++ b/internal/extract/manifests/branded-tracking-pack.yaml @@ -0,0 +1,19 @@ +# Shared Go + TypeScript Declarative Site Adapter: Branded Tracking Pack (#268) +id: branded-tracking-pack +name: "Branded Tracking Pack (Narvar / Route / ParcelPanel)" +category: commerce-social +description: "Extracts hydrated Narvar, ParcelPanel, Route, Malomo, and Wonderment tracking pages while strictly rejecting empty CSR shells such as unhydrated Route pages." +domains: + - "*.narvar.com" + - tracking.route.com +universalEngine: true +auth_mode: pub +min_interval_ms: 1000 +exampleUrls: + - "https://tracking.narvar.com/asics/tracking" + +htmlRoutes: + - id: branded-tracking-pack + match: + exactSegments: false + mode: branded_tracking_pack_html diff --git a/internal/extract/manifests/browser-addons-amo-cws.yaml b/internal/extract/manifests/browser-addons-amo-cws.yaml new file mode 100644 index 0000000..a999363 --- /dev/null +++ b/internal/extract/manifests/browser-addons-amo-cws.yaml @@ -0,0 +1,51 @@ +# Shared Go + TypeScript Declarative Site Adapter: Firefox AMO & Chrome Web Store (#334) +id: browser-addons-amo-cws +name: Firefox AMO & Chrome Web Store +category: developer +description: "Extracts browser extension metadata, versions, permissions, and user ratings from Firefox Add-ons v5 JSON API and Chrome Web Store detail HTML (full 2 MiB scan)." +domains: + - addons.mozilla.org + - chromewebstore.google.com +auth_mode: pub +exampleUrls: + - "https://addons.mozilla.org/api/v5/addons/addon/ublock-origin/" + - "https://chromewebstore.google.com/detail/bitwarden-password-manage/nngceckbapebfimnlniiiahkandclblb" + +routes: + - match: + hosts: + - addons.mozilla.org + pathPrefix: /api/v5/addons/addon/ + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 1048576 + extract: + jsonMode: amo_addon_json + + - match: + hosts: + - addons.mozilla.org + optionalLeadingLocale: true + exactSegments: true + pathSegments: + - firefox + - addon + - param: slug + charset: pkg + twin: + fetchUrl: "https://addons.mozilla.org/api/v5/addons/addon/{slug}/" + kind: json + accept: application/json + maxBytes: 1048576 + extract: + jsonMode: amo_addon_json + +htmlRoutes: + - id: browser-addons-amo-cws + match: + hosts: + - chromewebstore.google.com + pathPrefix: /detail/ + mode: chrome_web_store_html diff --git a/internal/extract/manifests/bugzilla.yaml b/internal/extract/manifests/bugzilla.yaml new file mode 100644 index 0000000..8744e4d --- /dev/null +++ b/internal/extract/manifests/bugzilla.yaml @@ -0,0 +1,44 @@ +# Shared Go + TypeScript Declarative Site Adapter: Bugzilla (#330) +id: bugzilla +name: Bugzilla Issue Tracker +category: developer +description: "Universal Bugzilla extractor supporting direct /rest/bug/ JSON endpoints and robots-compliant /show_bug.cgi SSR HTML extraction without rewriting /show_bug.cgi to /rest/." +domains: + - bugzilla.kernel.org + - bugzilla.mozilla.org +universalEngine: true +auth_mode: pub +min_interval_ms: 3000 +exampleUrls: + - "https://bugzilla.kernel.org/rest/bug/218000" + - "https://bugzilla.kernel.org/show_bug.cgi?id=218000" + - "https://bugzilla.mozilla.org/show_bug.cgi?id=1800000" + +routes: + - match: + anyOf: + - pathPrefix: /rest/bug/ + - pathPrefix: /bugzilla/rest/bug/ + excludeSegmentSuffixes: + - .html + - .htm + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: bugzilla_json + +htmlRoutes: + - id: bugzilla + match: + anyOf: + - pathEquals: + - /show_bug.cgi + - /bugzilla/show_bug.cgi + queryParams: + - name: id + param: bugId + charset: pkg + mode: bugzilla_html diff --git a/internal/extract/manifests/bullhorn-career-portal.yaml b/internal/extract/manifests/bullhorn-career-portal.yaml new file mode 100644 index 0000000..5742250 --- /dev/null +++ b/internal/extract/manifests/bullhorn-career-portal.yaml @@ -0,0 +1,40 @@ +# Shared Go + TypeScript Declarative Site Adapter: Bullhorn Career Portal (#227) +id: bullhorn-career-portal +name: "Bullhorn Career Portal" +category: jobs +description: "Extracts open JobOrder listings from public-rest*.bullhornstaffing.com REST endpoints and hydrated Bullhorn Career Portal pages while rejecting errors.badCorpToken and empty results." +domains: + - "*.bullhornstaffing.com" +universalEngine: true +auth_mode: pub +exampleUrls: + - "https://public-rest91.bullhornstaffing.com/rest-services/1VCNF4/search/JobOrder?query=(isOpen:1)&fields=id,title,publishedCategory,address,employmentType,dateLastPublished&count=25" + +routes: + # Public Bullhorn REST JobOrder search or entity lookup + - match: + hostSubdomain: + suffix: .bullhornstaffing.com + param: cluster + reserved: + - www + - login + - auth + - static + pathPrefix: /rest-services/ + pathContainsSegment: JobOrder + exactSegments: false + twin: + id: bullhorn-career-portal + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 4194304 + extract: + jsonMode: bullhorn_joborder_json + +htmlRoutes: + - id: bullhorn-career-portal + mode: bullhorn_portal_html + match: + exactSegments: false diff --git a/internal/extract/manifests/bundlephobia-packagephobia.yaml b/internal/extract/manifests/bundlephobia-packagephobia.yaml new file mode 100644 index 0000000..c828003 --- /dev/null +++ b/internal/extract/manifests/bundlephobia-packagephobia.yaml @@ -0,0 +1,73 @@ +# Shared Go + TypeScript Declarative Site Adapter: Bundlephobia & Packagephobia (#340) +id: bundlephobia-packagephobia +name: Bundlephobia & Packagephobia +category: developer +description: "Extracts npm bundle minified/gzip sizes and install size metrics from bundlephobia.com and packagephobia.com with Vercel Security Checkpoint / 429 HTML shell rejection." +domains: + - bundlephobia.com + - packagephobia.com +auth_mode: pub +exampleUrls: + - "https://bundlephobia.com/api/size?package=lodash@4.17.21" + - "https://bundlephobia.com/package/lodash@4.17.21" + +routes: + - match: + hosts: + - bundlephobia.com + exactSegments: true + pathEquals: + - /api/size + queryParams: + - name: package + param: pkg + charset: safe_subpath + minLen: 1 + maxLen: 214 + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 1048576 + extract: + jsonMode: bundlephobia_json + + - match: + hosts: + - bundlephobia.com + pathPrefix: /package/ + pathSegments: + - package + - param: pkg + charset: safe_subpath + greedy: true + twin: + fetchUrl: "https://bundlephobia.com/api/size?package={pkg}" + kind: json + accept: application/json + maxBytes: 1048576 + extract: + jsonMode: bundlephobia_json + + - match: + hosts: + - packagephobia.com + exactSegments: true + pathEquals: + - /v2/api.json + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 1048576 + extract: + jsonMode: packagephobia_json + +htmlRoutes: + - id: bundlephobia-packagephobia + match: + hosts: + - bundlephobia.com + - packagephobia.com + exactSegments: false + mode: bundle_packagephobia_html diff --git a/internal/extract/manifests/canvas-public-courses.yaml b/internal/extract/manifests/canvas-public-courses.yaml new file mode 100644 index 0000000..8d5c41b --- /dev/null +++ b/internal/extract/manifests/canvas-public-courses.yaml @@ -0,0 +1,32 @@ +# Shared Go + TypeScript Declarative Site Adapter: Canvas LMS Public Courses (#223) +# NOTE: Avoid https://canvas.instructure.com/ root (503 maintenance); classify SAML SSO redirects as login_wall. +id: canvas-public-courses +name: "Canvas LMS Public Courses" +category: public-records +description: "Extracts public Instructure Canvas LMS courses via /api/v1/courses JSON and public syllabus HTML while classifying SAML SSO redirects as login_wall and 503 maintenance shells as non-active." +domains: + - "*.instructure.com" +universalEngine: true +auth_mode: pub +strict_robots: true +min_interval_ms: 1000 +exampleUrls: + - "https://mit.instructure.com/search/all_courses" + - "https://mit.instructure.com/api/v1/courses/694" + +routes: + - match: + pathPrefix: /api/v1/courses + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: canvas_course_json + +htmlRoutes: + - id: canvas-public-courses + match: + exactSegments: false + mode: canvas_public_html diff --git a/internal/extract/manifests/cargo-ebike-oems.yaml b/internal/extract/manifests/cargo-ebike-oems.yaml new file mode 100644 index 0000000..af37970 --- /dev/null +++ b/internal/extract/manifests/cargo-ebike-oems.yaml @@ -0,0 +1,27 @@ +# Shared Go + TypeScript Declarative Site Adapter: Cargo E-Bike OEMs (#350) +id: cargo-ebike-oems +name: "Cargo E-Bike OEMs (Yuba, Xtracycle, Tern, Riese & Muller)" +category: commerce-social +description: "Extracts cargo e-bike payload, GVWR, battery Wh, motor torque/power, and product specifications from Yuba, Xtracycle, Tern, and Riese & Muller." +domains: + - yubabikes.com + - www.yubabikes.com + - xtracycle.com + - www.xtracycle.com + - ternbicycles.com + - www.ternbicycles.com + - r-m.de + - www.r-m.de +auth_mode: html +min_interval_ms: 1000 +exampleUrls: + - "https://yubabikes.com/shop/bikes/longtail/" + - "https://xtracycle.com/products/swoop-asm-family-cargo" + - "https://www.ternbicycles.com/en/bikes/473/gsd" + - "https://www.r-m.de/en-en/bikes/nevo5/" + +htmlRoutes: + - id: cargo-ebike-oems + match: + exactSegments: false + mode: cargo_ebike_oems_html diff --git a/internal/extract/manifests/carrier-tracking-official.yaml b/internal/extract/manifests/carrier-tracking-official.yaml new file mode 100644 index 0000000..9e963b1 --- /dev/null +++ b/internal/extract/manifests/carrier-tracking-official.yaml @@ -0,0 +1,73 @@ +# Shared Go + TypeScript Declarative Site Adapter: Official Carrier Tracking (#299) +id: carrier-tracking-official +name: "Official Carrier Tracking APIs (USPS, UPS, FedEx)" +category: commerce-social +description: "Keyed OAuth Bearer official tracking APIs for USPS (/tracking/), UPS (/api/track/v1/details with transactionSrc/transId), and FedEx (POST /track/v1/trackingnumbers)." +domains: + - onlinetools.ups.com + - wwwcie.ups.com + - apis.fedex.com + - apis-sandbox.fedex.com +universalEngine: true +auth_mode: key +min_interval_ms: 1000 +exampleUrls: + - "https://apis.usps.com/tracking/v3/tracking/9400111899223344556677" + - "https://onlinetools.ups.com/api/track/v1/details/1Z999AA10123456784" + - "https://apis.fedex.com/track/v1/trackingnumbers" + +routes: + - match: + hosts: + - apis.usps.com + - apis-tem.usps.com + pathPrefix: /tracking/ + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + method: GET + auth_mode: key + maxBytes: 1048576 + extract: + jsonMode: carrier_tracking_json + + - match: + hosts: + - onlinetools.ups.com + - wwwcie.ups.com + pathPrefix: /api/track/v1/details + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + method: GET + headers: + transactionSrc: edgefetch + auth_mode: key + maxBytes: 1048576 + extract: + jsonMode: carrier_tracking_json + + - match: + hosts: + - apis.fedex.com + - apis-sandbox.fedex.com + pathPrefix: /track/v1/trackingnumbers + queryParams: + - name: trackingNumber + param: trackingNumber + charset: alnum_dash + optional: true + default: "784592018372" + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + method: POST + contentType: application/json + requestBody: '{"includeDetailedScans":true,"trackingInfo":[{"trackingNumberInfo":{"trackingNumber":"{trackingNumber}"}}]}' + auth_mode: key + maxBytes: 1048576 + extract: + jsonMode: carrier_tracking_json diff --git a/internal/extract/manifests/cbo.yaml b/internal/extract/manifests/cbo.yaml new file mode 100644 index 0000000..f032889 --- /dev/null +++ b/internal/extract/manifests/cbo.yaml @@ -0,0 +1,31 @@ +# Shared Go + TypeScript Declarative Site Adapter: Congressional Budget Office (#290) +id: cbo +name: "Congressional Budget Office (CBO)" +category: public-records +description: "Extracts CBO publication and cost-estimate RSS feeds and HTML publication pages while cleanly classifying DataDome JS challenges as non-active." +domains: + - www.cbo.gov + - cbo.gov +auth_mode: pub +min_interval_ms: 1000 +exampleUrls: + - "https://www.cbo.gov/publications/all/rss.xml" + - "https://www.cbo.gov/publication/62899" + +routes: + - match: + pathPrefix: /publications/ + pathSuffix: .xml + twin: + fetchUrl: "{requestUrl}" + kind: text + accept: application/rss+xml + maxBytes: 1048576 + extract: + textMode: cbo_rss_xml + +htmlRoutes: + - id: cbo + match: + exactSegments: false + mode: cbo_html diff --git a/internal/extract/manifests/cbp-cross-rulings.yaml b/internal/extract/manifests/cbp-cross-rulings.yaml new file mode 100644 index 0000000..d08aa06 --- /dev/null +++ b/internal/extract/manifests/cbp-cross-rulings.yaml @@ -0,0 +1,32 @@ +# Shared Go + TypeScript Declarative Site Adapter: CBP CROSS Customs Rulings (#272) +id: cbp-cross-rulings +name: CBP CROSS Customs Rulings +category: public-records +description: "Extracts U.S. Customs and Border Protection CROSS ruling search and ruling detail JSON endpoints while rejecting unhydrated Angular CSR shells and security-parameter 403 blocks." +domains: + - rulings.cbp.gov +auth_mode: pub +exampleUrls: + - "https://rulings.cbp.gov/api/ruling/N310000" + - "https://rulings.cbp.gov/api/ruling/N310001" + +routes: + - match: + hosts: + - rulings.cbp.gov + pathPrefix: /api/ + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: cbp_cross_json + +htmlRoutes: + - id: cbp-cross-rulings + match: + hosts: + - rulings.cbp.gov + exactSegments: false + mode: cbp_cross_html diff --git a/internal/extract/manifests/census-foreign-trade.yaml b/internal/extract/manifests/census-foreign-trade.yaml new file mode 100644 index 0000000..8c4445f --- /dev/null +++ b/internal/extract/manifests/census-foreign-trade.yaml @@ -0,0 +1,20 @@ +# Shared Go + TypeScript Declarative Site Adapter: Census Foreign Trade / USA Trade Online (#273) +id: census-foreign-trade +name: U.S. Census Foreign Trade (USA Trade Online) +category: public-records +description: "Covers USA Trade Online portal pages (usatradeonline.census.gov, usatrade.census.gov) disjoint from census.yaml, which handles api.census.gov/data/timeseries/intltrade/* via census_json." +domains: + - usatradeonline.census.gov + - usatrade.census.gov +auth_mode: pub +exampleUrls: + - "https://usatradeonline.census.gov/" + +htmlRoutes: + - id: census-foreign-trade + match: + hosts: + - usatradeonline.census.gov + - usatrade.census.gov + exactSegments: false + mode: census_foreign_trade_html diff --git a/internal/extract/manifests/certificate-transparency.yaml b/internal/extract/manifests/certificate-transparency.yaml new file mode 100644 index 0000000..d1ac70a --- /dev/null +++ b/internal/extract/manifests/certificate-transparency.yaml @@ -0,0 +1,51 @@ +# Shared Go + TypeScript Declarative Site Adapter: Certificate Transparency (#324) +id: certificate-transparency +name: Certificate Transparency (Cert Spotter & crt.sh) +category: developer +description: "Extracts Certificate Transparency log issuances from api.certspotter.com and crt.sh JSON/HTML endpoints with bounded records and negative shell guards." +domains: + - api.certspotter.com + - crt.sh +auth_mode: pub +min_interval_ms: 1000 +exampleUrls: + - "https://api.certspotter.com/v1/issuances?domain=example.com" + +routes: + - match: + hosts: + - api.certspotter.com + exactSegments: false + pathPrefix: /v1/issuances + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: cert_transparency_json + + - match: + hosts: + - crt.sh + exactSegments: false + queryParams: + - name: output + param: out + allowValues: + - json + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 4194304 + extract: + jsonMode: cert_transparency_json + +htmlRoutes: + - id: certificate-transparency + match: + hosts: + - crt.sh + exactSegments: false + mode: cert_transparency_html diff --git a/internal/extract/manifests/chairish-1stdibs.yaml b/internal/extract/manifests/chairish-1stdibs.yaml new file mode 100644 index 0000000..59f9aab --- /dev/null +++ b/internal/extract/manifests/chairish-1stdibs.yaml @@ -0,0 +1,28 @@ +# Shared Go + TypeScript Declarative Site Adapter: Chairish & 1stDibs (#367) +id: chairish-1stdibs +name: Chairish & 1stDibs Vintage Design Marketplaces +category: commerce-social +description: "Extracts vintage and luxury furniture/design Product and multi-currency Offer[] JSON-LD along with dimensions and condition attributes from Chairish and 1stDibs." +domains: + - chairish.com + - www.chairish.com + - 1stdibs.com + - www.1stdibs.com +auth_mode: html +min_interval_ms: 1500 +strict_robots: true +exampleUrls: + - "https://www.chairish.com/product/194022/early-c1920s-liberty-co-attr-anglo-english-egyptian-revival-thebes-stool-original-ebony-finish" + - "https://www.1stdibs.com/furniture/seating/armchairs/pair-vintage-red-1970s-vico-magistretti-carimate-armchairs-chair-cassina-2pc/id-f_53095452/" + +htmlRoutes: + - id: chairish-1stdibs + match: + anyOf: + - pathPrefix: /product/ + - pathPrefix: /furniture/ + - pathPrefix: /art/ + - pathPrefix: /jewelry/ + - pathPrefix: /fashion/ + - pathPrefix: /creators/ + mode: chairish_1stdibs_html diff --git a/internal/extract/manifests/chambermaster-growthzone.yaml b/internal/extract/manifests/chambermaster-growthzone.yaml index 7744348..851f0b9 100644 --- a/internal/extract/manifests/chambermaster-growthzone.yaml +++ b/internal/extract/manifests/chambermaster-growthzone.yaml @@ -2,9 +2,12 @@ id: chambermaster-growthzone name: ChamberMaster / GrowthZone Chamber Directories category: commerce-social -description: "Universal extractor for chamber-of-commerce member directories hosted on ChamberMaster / GrowthZone (/list/ category and search pages, /list/member/ detail pages): member name, address, phone, website, hours, categories, and description." +description: "Universal extractor for chamber-of-commerce member directories and event calendars hosted on ChamberMaster / GrowthZone (/list/ category and search pages, /list/member/ detail pages, and /events/ calendars): member name, address, phone, website, hours, categories, events, and description." domains: - business.fortworthchamber.com + - www.brownstownchamber.org + - "*.chambermaster.com" + - "*.growthzoneapp.com" universalEngine: true auth_mode: html min_interval_ms: 2000 @@ -12,10 +15,10 @@ strict_robots: true exampleUrls: - "https://business.fortworthchamber.com/list/category/apartments-25" - "https://business.fortworthchamber.com/list/member/the-harden-at-public-market-50786" + - "https://www.brownstownchamber.org/events/" htmlRoutes: - id: chambermaster-growthzone match: - pathPrefix: /list exactSegments: false mode: chambermaster_html diff --git a/internal/extract/manifests/cisa-advisories-ics.yaml b/internal/extract/manifests/cisa-advisories-ics.yaml new file mode 100644 index 0000000..c7dd6a9 --- /dev/null +++ b/internal/extract/manifests/cisa-advisories-ics.yaml @@ -0,0 +1,42 @@ +# Shared Go + TypeScript Declarative Site Adapter: CISA Cybersecurity & ICS Advisories (#320) +id: cisa-advisories-ics +name: CISA Cybersecurity & ICS Advisories +category: developer +description: "Extracts CISA cybersecurity and ICS advisory RSS feeds (with embedded CVE and CSAF links) and Drupal 11 SSR advisory/alert HTML pages on www.cisa.gov." +domains: + - www.cisa.gov +universalEngine: true +auth_mode: pub +min_interval_ms: 1000 +exampleUrls: + - "https://www.cisa.gov/cybersecurity-advisories/ics-advisories.xml" + - "https://www.cisa.gov/cybersecurity-advisories/all.xml" + - "https://www.cisa.gov/news-events/ics-advisories/icsa-26-328-01" + +routes: + - match: + hosts: + - www.cisa.gov + - cisa.gov + exactSegments: false + pathPrefix: /cybersecurity-advisories/ + pathSuffix: .xml + twin: + fetchUrl: "{requestUrl}" + kind: text + accept: application/rss+xml + maxBytes: 2097152 + extract: + textMode: cisa_advisories_rss + +htmlRoutes: + - id: cisa-advisories-ics + match: + hosts: + - www.cisa.gov + - cisa.gov + exactSegments: false + anyOf: + - pathPrefix: /news-events/ + - pathPrefix: /cybersecurity-advisories + mode: cisa_advisories_html diff --git a/internal/extract/manifests/cisa-kev.yaml b/internal/extract/manifests/cisa-kev.yaml new file mode 100644 index 0000000..822d1b8 --- /dev/null +++ b/internal/extract/manifests/cisa-kev.yaml @@ -0,0 +1,55 @@ +# Shared Go + TypeScript Declarative Site Adapter: CISA Known Exploited Vulnerabilities (KEV) (#315) +id: cisa-kev +name: CISA Known Exploited Vulnerabilities (KEV) Catalog +category: developer +description: "Bounded JSON/CSV extractor for CISA's Known Exploited Vulnerabilities (KEV) catalog with optional ?cve= filtering plus SSR catalog HTML extraction." +domains: + - cisa.gov +universalEngine: true +auth_mode: pub +min_interval_ms: 1000 +exampleUrls: + - "https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json" + - "https://www.cisa.gov/known-exploited-vulnerabilities-catalog" + +routes: + - match: + hosts: + - www.cisa.gov + - cisa.gov + exactSegments: true + pathEquals: + - /sites/default/files/feeds/known_exploited_vulnerabilities.json + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 4194304 + extract: + jsonMode: cisa_kev_json + + - match: + hosts: + - www.cisa.gov + - cisa.gov + exactSegments: true + pathEquals: + - /sites/default/files/csv/known_exploited_vulnerabilities.csv + twin: + fetchUrl: "{requestUrl}" + kind: text + accept: text/plain + maxBytes: 4194304 + extract: + textMode: cisa_kev_csv + +htmlRoutes: + - id: cisa-kev + match: + hosts: + - www.cisa.gov + - cisa.gov + exactSegments: true + pathEquals: + - /known-exploited-vulnerabilities-catalog + mode: cisa_kev_html diff --git a/internal/extract/manifests/civicclerk.yaml b/internal/extract/manifests/civicclerk.yaml new file mode 100644 index 0000000..3fddffd --- /dev/null +++ b/internal/extract/manifests/civicclerk.yaml @@ -0,0 +1,84 @@ +# Shared Go + TypeScript Declarative Site Adapter: CivicClerk (#205) +id: civicclerk +name: CivicPlus CivicClerk Agenda Portals +category: public-records +description: "Extracts municipal meeting events and agendas via CivicClerk OData v1 API with portal-to-API same-eTLD+1 twin upgrades." +domains: + - "*.civicclerk.com" +auth_mode: pub +exampleUrls: + - "https://mauicounty.api.civicclerk.com/v1/Events?$top=3" + - "https://mauicounty.api.civicclerk.com/v1/Events/1023" + - "https://mauicounty.portal.civicclerk.com/" + +routes: + - match: + hostSubdomain: + suffix: .api.civicclerk.com + param: tenant + reserved: + - www + - api + - auth + - login + - admin + pathPrefix: /v1/Events + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 4194304 + extract: + jsonMode: civicclerk_json + + - match: + hostSubdomain: + suffix: .portal.civicclerk.com + param: tenant + reserved: + - www + - api + - auth + - login + - admin + exactSegments: false + pathSegments: + - event + - param: eventId + charset: digits + minLen: 1 + maxLen: 16 + twin: + fetchUrl: "https://{tenant}.api.civicclerk.com/v1/Events/{eventId}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: civicclerk_json + + - match: + hostSubdomain: + suffix: .portal.civicclerk.com + param: tenant + reserved: + - www + - api + - auth + - login + - admin + pathEquals: + - / + - /events + twin: + fetchUrl: "https://{tenant}.api.civicclerk.com/v1/Events?$top=25" + kind: json + accept: application/json + maxBytes: 4194304 + extract: + jsonMode: civicclerk_json + +htmlRoutes: + - id: civicclerk + match: + exactSegments: false + mode: civicclerk_html diff --git a/internal/extract/manifests/civicplus.yaml b/internal/extract/manifests/civicplus.yaml index 3a9479a..c4e12af 100644 --- a/internal/extract/manifests/civicplus.yaml +++ b/internal/extract/manifests/civicplus.yaml @@ -1,21 +1,31 @@ -# Shared Go + TypeScript Declarative Site Adapter: CivicPlus CivicEngage AgendaCenter (#201) +# Shared Go + TypeScript Declarative Site Adapter: CivicPlus CivicEngage (#201) id: civicplus -name: CivicPlus CivicEngage Agenda Center +name: CivicPlus CivicEngage Agenda & Document Portals category: public-records -description: "Universal extractor for CivicPlus CivicEngage /AgendaCenter pages on any city or county domain: meeting dates, agenda titles, agenda/HTML/packet links, and minutes, grouped by board. Fingerprint-gated (catAgendaRow + CivicPlus markup); robots.txt on CivicPlus sites disallows /RSSFeed.aspx, so the HTML page is used." +description: "Universal extractor for CivicPlus CivicEngage /AgendaCenter, /DocumentCenter, and /CivicAlerts.aspx pages on city and county domains: meeting dates, agenda titles, agenda/HTML/packet/minutes links, public document directories, and municipal alerts. Fingerprint-gated; never touches robots.txt-disallowed /RSSFeed.aspx." domains: - www.gulfshoresal.gov - www.ankenyiowa.gov + - www.springfieldmo.gov + - www.brownwoodtexas.gov + - www.fayetteville-ar.gov universalEngine: true auth_mode: html min_interval_ms: 2000 strict_robots: true exampleUrls: - "https://www.gulfshoresal.gov/AgendaCenter" + - "https://www.brownwoodtexas.gov/DocumentCenter" + - "https://www.springfieldmo.gov/CivicAlerts.aspx" htmlRoutes: - id: civicplus match: - pathPrefix: /AgendaCenter - exactSegments: false + anyOf: + - pathPrefix: /AgendaCenter + exactSegments: false + - pathPrefix: /DocumentCenter + exactSegments: false + - pathEquals: + - /CivicAlerts.aspx mode: civicplus_agenda_html diff --git a/internal/extract/manifests/cms-price-transparency.yaml b/internal/extract/manifests/cms-price-transparency.yaml new file mode 100644 index 0000000..fc892e6 --- /dev/null +++ b/internal/extract/manifests/cms-price-transparency.yaml @@ -0,0 +1,88 @@ +# Shared Go + TypeScript Declarative Site Adapter: CMS Price Transparency (#296) +id: cms-price-transparency +name: "CMS Hospital & Payer Price Transparency (HPT & MRF)" +category: research-health +description: "Universal engine for hospital /cms-hpt.txt discovery files, bounded Range-streaming MRF JSON/CSV charge files, ZIP/gzip archive detection, and payer TiC index feeds." +domains: + - stanfordhealthcare.org + - www.mountsinai.org + - nyulangone.org + - www.ucsfhealth.org + - transparency-in-coverage.uhc.com +universalEngine: true +auth_mode: pub +min_interval_ms: 1000 +exampleUrls: + - "https://stanfordhealthcare.org/cms-hpt.txt" + - "https://nyulangone.org/cms-hpt.txt" + - "https://stanfordhealthcare.org/content/dam/SHC/patientsandvisitors/pricingtransparency/946174066_stanford-health-care_standardcharges.json" + - "https://transparency-in-coverage.uhc.com/api/v1/uhc/blobs/" + +routes: + - match: + pathEquals: + - /cms-hpt.txt + twin: + fetchUrl: "{requestUrl}" + kind: text + accept: text/plain + maxBytes: 524288 + extract: + textMode: cms_hpt_txt + + - match: + pathSuffix: standardcharges.json + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + headers: + Range: "bytes=0-2097151" + maxBytes: 2097152 + extract: + jsonMode: cms_mrf_json + + - match: + pathSuffix: standardcharges.csv + twin: + fetchUrl: "{requestUrl}" + kind: text + accept: text/plain + headers: + Range: "bytes=0-2097151" + maxBytes: 2097152 + extract: + textMode: cms_mrf_csv + + - match: + hosts: + - transparency-in-coverage.uhc.com + pathPrefix: /api/v1/uhc/blobs + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: cms_mrf_json + + - match: + anyOf: + - pathSuffix: table-of-contents.json + - pathSuffix: _index.json + - pathSuffix: -index.json + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + headers: + Range: "bytes=0-2097151" + maxBytes: 2097152 + extract: + jsonMode: cms_mrf_json + +htmlRoutes: + - id: cms-price-transparency + match: + exactSegments: false + mode: cms_price_transparency_html diff --git a/internal/extract/manifests/company-newsrooms.yaml b/internal/extract/manifests/company-newsrooms.yaml new file mode 100644 index 0000000..8fa2b90 --- /dev/null +++ b/internal/extract/manifests/company-newsrooms.yaml @@ -0,0 +1,52 @@ +# Shared Go + TypeScript Declarative Site Adapter: Company Newsrooms (#261) +id: company-newsrooms +name: "Company Newsrooms (Prowly / Prezly / Cision)" +category: commerce-social +description: "Extracts corporate newsrooms and RSS/Atom press release feeds from Prowly, Prezly, and Cision PR portals." +domains: + - news.cision.com + - multimedia.cision.com + - "*.prowly.com" + - "*.prezly.com" + - press.brusselsairlines.com +universalEngine: true +auth_mode: pub +strict_robots: true +min_interval_ms: 1000 +exampleUrls: + - "https://residence.prowly.com/rss" + - "https://residence.prowly.com/" + - "https://press.brusselsairlines.com/feed" + - "https://news.cision.com/tietoevry" + +routes: + - match: + hosts: + - news.cision.com + - multimedia.cision.com + - "*.prowly.com" + - "*.prezly.com" + - press.brusselsairlines.com + anyOf: + - pathEquals: + - /rss + - /feed + - /rss.xml + - /feed.xml + - pathSuffix: /rss + - pathSuffix: /feed + - pathSuffix: .rss + exactSegments: false + twin: + fetchUrl: "{requestUrl}" + kind: text + accept: application/rss+xml + maxBytes: 2097152 + extract: + textMode: company_newsroom_rss_xml + +htmlRoutes: + - id: company-newsrooms + match: + exactSegments: false + mode: company_newsrooms_html diff --git a/internal/extract/manifests/compiled.json b/internal/extract/manifests/compiled.json index 95f3b7f..9bdee39 100644 --- a/internal/extract/manifests/compiled.json +++ b/internal/extract/manifests/compiled.json @@ -1 +1 @@ -{"version":2,"manifests":[{"id":"aem","name":"Adobe Experience Manager (AEM)","category":"developer","description":"Upgrades AEM /content//...html pages to .model.json / .infinity.json Sling model twins, with clean HTML fallback when disabled or on 404/403.","domains":["wknd.site"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://wknd.site/content/wknd/us/en.html","https://wknd.site/content/wknd/us/en.model.json"],"routes":[{"match":{"excludeHosts":["www.govinfo.gov","govinfo.gov"],"pathSuffix":".model.json"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"aem_model"}},{"match":{"excludeHosts":["www.govinfo.gov","govinfo.gov"],"pathSuffix":".infinity.json"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"aem_model"}},{"match":{"excludeHosts":["www.govinfo.gov","govinfo.gov"],"pathSuffix":".html","pathSegments":["content",{"param":"siteSeg","charset":"url_seg","reserved":["pkg","dam"],"minLen":1,"maxLen":120},{"param":"pagePath","charset":"safe_subpath","stripSuffix":".html","greedy":true,"minLen":1,"maxLen":400}]},"twin":{"fetchUrl":"https://{host}/content/{siteSeg}/{pagePath}.model.json","rawPathParams":["pagePath"],"kind":"json","accept":"application/json"},"extract":{"jsonMode":"aem_model"}}],"htmlRoutes":[{"id":"aem","match":{"exactSegments":false},"mode":"aem_html"}]},{"id":"airnow","name":"AirNow Air Quality API","category":"research-health","description":"US EPA AirNow air quality observation and forecast JSON API (API_KEY query parameter) with airnow.gov HTML fallback.","domains":["www.airnowapi.org","airnowapi.org","www.airnow.gov","airnow.gov","docs.airnowapi.org"],"auth_mode":"key","exampleUrls":["https://www.airnowapi.org/aq/observation/zipCode/current/?format=application/json&zipCode=20002&distance=25","https://www.airnow.gov/?city=Washington&state=DC&country=USA"],"routes":[{"match":{"hosts":["www.airnowapi.org","airnowapi.org"],"pathPrefix":"/aq/"},"twin":{"fetchUrl":"{requestUrl}","setQueryParams":{"format":"application/json"},"kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"airnow_json"}}],"htmlRoutes":[{"id":"airnow","match":{"hosts":["www.airnow.gov","airnow.gov","docs.airnowapi.org"],"exactSegments":false},"mode":"airnow_html"}]},{"id":"algolia","name":"Algolia On-Site Search","category":"developer","description":"Opt-in page-key adapter for Algolia search index JSON twins; defaults OFF and falls back cleanly to HTML/JSON-LD when disabled.","domains":["latency-dsn.algolia.net"],"universalEngine":true,"auth_mode":"page-key","requires_page_key_opt_in":true,"exampleUrls":["https://latency-dsn.algolia.net/1/indexes/instant_search?query=apple"],"routes":[{"match":{"hostSubdomain":{"suffix":".algolia.net","param":"appHost"},"pathSegments":["1","indexes",{"param":"indexName","charset":"url_seg","minLen":1,"maxLen":120},{"param":"op","allowValues":["query"],"optional":true}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"jsonMode":"algolia_search"}}],"htmlRoutes":[{"id":"algolia","match":{"exactSegments":false},"mode":"algolia_html"}]},{"id":"american-legal-publishing","name":"American Legal Publishing Municipal Codes","category":"public-records","description":"HTML extractor for American Legal Publishing Code Library municipal codes and ordinance sections.","domains":["codelibrary.amlegal.com"],"auth_mode":"html","exampleUrls":["https://codelibrary.amlegal.com/codes/san_francisco/latest/overview","https://codelibrary.amlegal.com/codes/chicago/latest/overview"],"htmlRoutes":[{"id":"american-legal-publishing","match":{"exactSegments":false},"mode":"amlegal_html"}]},{"id":"ap-news","name":"Associated Press (AP News)","category":"commerce-social","description":"Extracts NewsArticle JSON-LD and RichTextStoryBody from AP News HTML pages while respecting robots.txt feed exclusions.","domains":["apnews.com","www.apnews.com"],"auth_mode":"html","exampleUrls":["https://apnews.com/hub/us-news"],"htmlRoutes":[{"id":"ap-news","match":{"exactSegments":false},"mode":"ap_news_html"}]},{"id":"api-docs-portals","name":"API Docs Portals (OpenAPI, Redocly, Postman, Stoplight)","category":"developer","description":"Universal extractor for OpenAPI 2/3 JSON specs, Postman Collection JSON, and Redocly/Postman/Stoplight API documentation portals.","domains":["petstore3.swagger.io","redocly.com","www.postman.com","learn.openapis.org"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://petstore3.swagger.io/api/v3/openapi.json","https://learn.openapis.org/"],"routes":[{"match":{"anyOf":[{"pathEquals":["/openapi.json","/swagger.json","/api-docs","/v2/api-docs","/v3/api-docs"]},{"pathSuffix":"/openapi.json"},{"pathSuffix":"/swagger.json"},{"pathSuffix":"/collection.json"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"openapi_postman_json"}}],"htmlRoutes":[{"id":"api-docs-portals","match":{"exactSegments":false},"mode":"api_docs_portal_html"}]},{"id":"apple-app-store","name":"Apple App Store","category":"developer","description":"Extracts structured iOS/macOS App Store metadata (developer, rating, review count, price, category, version notes, and description).","domains":["apps.apple.com"],"exampleUrls":["https://apps.apple.com/us/app/cloudflare-one-agent/id6443476492"],"htmlRoutes":[{"match":{"pathContainsSegment":"app","minSegments":2},"mode":"dom","jsonLdTypes":["SoftwareApplication","MobileApplication","WebApplication"],"vars":{"title":{"jsonLdPaths":["name"],"metaKeys":["og:title"],"stripRegexSuffix":"\\s+on the App\\s*Store$","cssText":["h1"]},"developer":{"jsonLdPaths":["author.name"],"cssText":["h2.product-header__identity"]},"ratingVal":{"jsonLdPaths":["aggregateRating.ratingValue"]},"ratingCount":{"jsonLdPaths":["aggregateRating.reviewCount","aggregateRating.ratingCount"]},"ratingOnly":{"template":"{ratingVal} / 5","whenVars":["ratingVal"]},"rating":{"template":"{ratingVal} / 5 ({ratingCount} ratings)","whenVars":["ratingVal","ratingCount"],"fallbackVar":"ratingOnly"},"currency":{"jsonLdPaths":["offers.0.priceCurrency","offers.priceCurrency"],"default":"USD"},"price":{"jsonLdPaths":["offers.0.price","offers.price"],"format":"free_or_currency","currencyVar":"currency"},"category":{"jsonLdPaths":["applicationCategory"]},"osSys":{"jsonLdPaths":["operatingSystem"]},"desc":{"jsonLdPaths":["description"],"metaKeys":["description"]},"descShort":{"template":"{desc}","whenVars":["desc"],"sliceMax":260},"version":{"regexExtract":{"source":"clean_html","pattern":"Version\\s+([0-9][0-9A-Za-z._-]*)","group":1}}},"requireVars":["title"],"requireBulletsOrVars":["desc"],"titleTemplate":"{title}","descriptionVar":"descShort","authorVar":"developer","bullets":[{"label":"Developer","template":"{developer}","whenVar":"developer"},{"label":"Category","template":"{category}","whenVar":"category"},{"label":"Rating","template":"{rating}","whenVar":"rating"},{"label":"Price","template":"{price}","whenVar":"price"},{"label":"Platform","template":"{osSys}","whenVar":"osSys"},{"label":"Latest Version","template":"`{version}`","whenVar":"version"}],"sections":[{"heading":"Description","textVar":"desc"}]}]},{"id":"arc-xp","name":"Arc XP Publishing (Fusion / ANS)","category":"commerce-social","description":"Extracts Arc XP /pf/api/v3/content/fetch ANS JSON twins and inline Fusion.globalContent publisher articles.","domains":["www.clickondetroit.com"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://www.clickondetroit.com/news/local/2026/11/27/1-killed-in-shooting-in-downtown-birmingham/"],"routes":[{"match":{"pathPrefix":"/pf/api/v3/content/fetch/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"arc_xp_ans"}}],"htmlRoutes":[{"id":"arc-xp","match":{"exactSegments":false},"mode":"arc_xp_html"}]},{"id":"arcgis","name":"ArcGIS REST FeatureServer & MapServer Layers","category":"public-records","description":"Upgrades public ArcGIS REST FeatureServer/MapServer layer URLs to ?f=json metadata, geometry type, spatial reference, and field schemas.","domains":["services.arcgis.com","*.arcgis.com"],"universalEngine":true,"exampleUrls":["https://services.arcgis.com/P3ePLMYs2RVChkJx/ArcGIS/rest/services/2020_Census_State_Apportionment/FeatureServer/0"],"match":{"arcgisRestLayer":true,"pathSegments":[{"param":"restPath","charset":"safe_subpath","greedy":true,"maxLen":500}]},"twin":{"fetchUrl":"{requestUrl}","setQueryParams":{"f":"json"},"kind":"json","accept":"application/json"},"extract":{"rejectIfFieldTruthy":"error","vars":{"name":{"paths":["name","mapName","serviceDescription"],"trim":true,"default":"ArcGIS Service"},"desc":{"paths":["description","serviceDescription"],"format":"strip_tags"},"descShort":{"paths":["description","serviceDescription"],"format":"strip_tags","sliceMax":260},"geomType":{"paths":["geometryType"]},"maxRec":{"paths":["maxRecordCount"]},"capabilities":{"paths":["capabilities"]},"wkid":{"paths":["extent.spatialReference.latestWkid","extent.spatialReference.wkid"]},"baseClean":{"template":"https://{host}/{restPath}"},"hasFields":{"paths":["fields"],"format":"array_len","excludeEquals":"0"},"hasLayers":{"paths":["layers"],"format":"array_len","excludeEquals":"0"}},"titleTemplate":"{name}","descriptionVar":"descShort","bullets":[{"label":"REST Endpoint","template":"`{baseClean}`"},{"label":"Geometry Type","template":"`{geomType}`","whenVar":"geomType"},{"label":"Spatial Reference (WKID)","template":"`EPSG:{wkid}`","whenVar":"wkid"},{"label":"Max Record Count / Query","template":"{maxRec}","whenVar":"maxRec"},{"label":"Capabilities","template":"{capabilities}","whenVar":"capabilities"}],"sections":[{"heading":"Description","textVar":"desc"},{"heading":"Layer Fields","headingTemplate":"Layer Fields ({count})","whenVar":"hasFields","arrayPath":"fields","limit":40,"columns":[{"header":"Field","paths":["name"],"code":true},{"header":"Alias","paths":["alias"]},{"header":"Type","paths":["type"],"stripPrefix":"esriFieldType"}]},{"heading":"Sublayers","headingTemplate":"Sublayers ({count})","whenVar":"hasLayers","unlessVar":"hasFields","arrayPath":"layers","limit":30,"itemVars":{"layerId":{"paths":["id"],"default":"0"},"layerName":{"paths":["name"],"default":"Layer"}},"columns":[{"header":"ID","paths":["id"]},{"header":"Layer","template":"[{layerName}]({baseClean}/{layerId})"},{"header":"Geometry","paths":["geometryType"]}]}]}},{"id":"arxiv","name":"arXiv Preprints","category":"research-health","description":"Extracts arXiv preprint title, authors, submission date, subject classifications, PDF/HTML links, and clean abstract from arxiv.org/abs/ (strictly respecting robots.txt).","domains":["arxiv.org","www.arxiv.org"],"exampleUrls":["https://arxiv.org/abs/1706.03762"],"htmlRoutes":[{"match":{"pathSegments":["abs",{"param":"arxivId","charset":"arxiv_id","greedy":true}]},"mode":"dom","requireVars":["title","abstract"],"vars":{"titleDom":{"cssText":["h1.title"],"stripPrefix":"Title:"},"title":{"metaKeys":["citation_title"],"fallbackVar":"titleDom"},"authors":{"allMetaKey":"citation_author","cssAllText":{"selector":"div.authors a","limit":50,"join":", "},"limit":20,"join":", "},"authorsShort":{"allMetaKey":"citation_author","cssAllText":{"selector":"div.authors a","limit":50,"join":", "},"limit":4,"join":", "},"date":{"metaKeys":["citation_date","citation_online_date"]},"doi":{"metaKeys":["citation_doi"]},"primarySubject":{"cssText":["span.primary-subject"]},"absMeta":{"metaKeys":["citation_abstract"]},"abstract":{"cssText":["blockquote.abstract"],"stripPrefix":"Abstract:","fallbackVar":"absMeta"},"abstractShort":{"template":"{abstract}","whenVars":["abstract"],"sliceMax":260},"pdfUrl":{"template":"https://arxiv.org/pdf/{arxivId}"},"htmlPaperUrl":{"template":"https://arxiv.org/html/{arxivId}"}},"titleTemplate":"{title}","descriptionVar":"abstractShort","authorVar":"authorsShort","publishedTimeVar":"date","bullets":[{"label":"arXiv ID","template":"`{arxivId}`"},{"label":"Authors","template":"{authors}","whenVar":"authors"},{"label":"Submitted","template":"{date}","whenVar":"date"},{"label":"Primary Subject","template":"{primarySubject}","whenVar":"primarySubject"},{"label":"DOI","template":"`{doi}`","whenVar":"doi"},{"label":"Full Text","template":"[PDF]({pdfUrl}) · [ar5iv / HTML]({htmlPaperUrl})"}],"sections":[{"heading":"Abstract","textVar":"abstract"}],"linkTemplates":["https://arxiv.org/pdf/{arxivId}","https://arxiv.org/html/{arxivId}"]}]},{"id":"atlassian-statuspage","name":"Atlassian Statuspage","category":"developer","description":"Extracts Atlassian Statuspage /api/v2/summary.json and incidents.json endpoints (when robots.txt permits) plus Statuspage HTML pages.","domains":["statuspage.io","www.statuspage.io","www.githubstatus.com"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://www.githubstatus.com/","https://discord.statuspage.io/"],"routes":[{"match":{"pathEquals":["/api/v2/summary.json","/api/v2/incidents.json","/api/v2/status.json","/api/v2/components.json"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"statuspage_v2"}}],"htmlRoutes":[{"id":"atlassian-statuspage","match":{"exactSegments":false},"mode":"statuspage_html"}]},{"id":"auto-dealer-inventory","name":"Auto Dealer Inventory (Universal)","category":"commerce-social","description":"Universal automotive dealer SRP/VDP HTML and Schema.org Vehicle/Car JSON-LD extractor for Dealer.com, Dealer Inspire, and DealerOn storefronts.","domains":["www.johneaglehonda.com"],"universalEngine":true,"auth_mode":"html","exampleUrls":["https://www.johneaglehonda.com/used-inventory/index.htm","https://www.johneaglehonda.com/used/Honda/2021-Honda-Accord--for-sale-houston-texas-f65329b9ac180db0f233180fce0b2e1d.htm"],"htmlRoutes":[{"id":"auto-dealer-inventory","match":{"anyOf":[{"pathPrefix":"/used-inventory/"},{"pathPrefix":"/new-inventory/"},{"pathPrefix":"/all-inventory/"},{"pathPrefix":"/certified-inventory/"},{"pathPrefix":"/inventory/"},{"pathPrefix":"/used/"},{"pathPrefix":"/new/"},{"pathPrefix":"/vehicles/"},{"pathPrefix":"/vehicle/"},{"pathPrefix":"/vdp/"},{"pathPrefix":"/srp/"},{"pathEquals":["/searchused.aspx","/searchnew.aspx","/searchall.aspx"]}]},"mode":"auto_dealer_html"}]},{"id":"auto-parts-fitment","name":"Auto Parts Fitment & SKU Extractor","category":"commerce-social","description":"Extracts auto parts SKUs, part numbers, strict GTINs, and explicit vehicle fitment (year, make, model, engine) for AutoZone, O'Reilly, NAPA, and Advance Auto Parts.","domains":["autozone.com","www.autozone.com","oreillyauto.com","www.oreillyauto.com","napaonline.com","www.napaonline.com","shop.advanceautoparts.com","www.advanceautoparts.com"],"auth_mode":"html","min_interval_ms":2000,"strict_robots":true,"exampleUrls":["https://www.autozone.com/brakes-and-traction-control/brake-pads/duralast-gold-ceramic-brake-pads-dg1410/141001_0_0","https://www.napaonline.com/en/p/NAPA1410"],"htmlRoutes":[{"id":"auto-parts-fitment","match":{"exactSegments":false},"mode":"auto_parts_fitment_html"}]},{"id":"bamboohr-breezy-recruitee","name":"BambooHR, Breezy HR, Recruitee & Personio Boards","category":"jobs","description":"Upgrades BambooHR (/careers/list & /detail), Breezy HR (/json), Recruitee (/api/offers), and Personio (/xml) career boards to structured feeds.","domains":["*.bamboohr.com","*.breezy.hr","*.recruitee.com","*.jobs.personio.de","*.jobs.personio.com"],"exampleUrls":["https://posthog.bamboohr.com/careers","https://breezy.breezy.hr/","https://bunq.recruitee.com/","https://personio.jobs.personio.de/"],"routes":[{"match":{"hosts":["*.bamboohr.com"],"hostSubdomain":{"suffix":".bamboohr.com","param":"org","reserved":["www","resources","help","documentation","developers","blog","status","api"]},"pathSegments":[{"param":"boardSection","charset":"alnum","allowValues":["careers","jobs"],"optional":true}]},"twin":{"id":"bamboohr-board","fetchUrl":"https://{host}/careers/list","kind":"json","accept":"application/json"},"extract":{"vars":{"count":{"paths":["result"],"format":"array_len"}},"requireVars":["count"],"titleTemplate":"{org} — BambooHR Careers ({count} open roles)","sections":[{"heading":"","arrayPath":"result","limit":100,"emptyText":"No open positions currently listed.","itemVars":{"id":{"paths":["id"]},"jTitle":{"paths":["jobOpeningName"],"trim":true,"default":"Role"},"jUrl":{"template":"https://{host}/careers/{id}"},"dept":{"paths":["departmentLabel"],"trim":true,"default":"-"},"city":{"paths":["location.city"],"trim":true},"state":{"paths":["location.state"],"trim":true},"bothLoc":{"template":"{city}, {state}","whenVars":["city","state"]},"oneLoc":{"paths":["location.city","location.state"],"trim":true},"remoteLoc":{"paths":["isRemote"],"format":"bool_map","trueValue":"Remote","falseValue":"-"},"loc":{"template":"{bothLoc}","whenVars":["bothLoc"],"fallbackVar":"oneLoc","fallbackTemplate":"{remoteLoc}"}},"collectLinkVars":["jUrl"],"columns":[{"header":"Role","template":"[{jTitle}]({jUrl})"},{"header":"Department","template":"{dept}"},{"header":"Location","template":"{loc}"}]}]}},{"match":{"hosts":["*.bamboohr.com"],"hostSubdomain":{"suffix":".bamboohr.com","param":"org","reserved":["www","resources","help","documentation","developers","blog","status","api"]},"exactSegments":false,"pathSegments":["careers",{"param":"jobId","charset":"digits"}]},"twin":{"id":"bamboohr-job","fetchUrl":"https://{host}/careers/{jobId}/detail","kind":"json","accept":"application/json"},"extract":{"rootPath":"result.jobOpening","requireFields":["jobOpeningName"],"vars":{"jobTitle":{"paths":["jobOpeningName"],"trim":true},"body":{"paths":["description"],"format":"html_to_md"}},"titleTemplate":"{jobTitle} @ {org}","bodyVar":"body"}},{"match":{"hosts":["*.breezy.hr"],"hostSubdomain":{"suffix":".breezy.hr","param":"org","reserved":["www","app"]},"pathSegments":[]},"twin":{"id":"breezy-hr","fetchUrl":"https://{host}/json","kind":"json","accept":"application/json"},"extract":{"wrapRootArrayAs":"jobs","vars":{"count":{"paths":["jobs"],"format":"array_len"}},"requireVars":["count"],"titleTemplate":"{org} — Breezy HR Board ({count} open roles)","sections":[{"heading":"","arrayPath":"jobs","limit":100,"emptyText":"No open positions currently listed.","itemVars":{"jTitle":{"paths":["name"],"trim":true,"default":"Role"},"rawUrl":{"paths":["url"],"requireHttps":true},"jUrl":{"template":"{rawUrl}","whenVars":["rawUrl"],"fallbackTemplate":"https://{host}"},"dept":{"paths":["department"],"trim":true,"default":"-"},"remoteLoc":{"paths":["location.is_remote"],"format":"bool_map","trueValue":"Remote","falseValue":"-"},"loc":{"paths":["location.name"],"trim":true,"fallbackTemplate":"{remoteLoc}"}},"collectLinkVars":["jUrl"],"columns":[{"header":"Role","template":"[{jTitle}]({jUrl})"},{"header":"Department","template":"{dept}"},{"header":"Location","template":"{loc}"}]}]}},{"match":{"hosts":["*.recruitee.com"],"hostSubdomain":{"suffix":".recruitee.com","param":"org","reserved":["www","app"]},"exactSegments":false,"pathSegments":["o",{"param":"targetSlug","charset":"pkg"}]},"twin":{"id":"recruitee","fetchUrl":"https://{host}/api/offers","kind":"json","accept":"application/json"},"extract":{"findInArray":{"arrayPath":"offers","matchField":"slug","matchTemplate":"{targetSlug}"},"vars":{"jobTitle":{"paths":["title"],"trim":true,"default":"Role"},"desc":{"paths":["description"],"format":"html_to_md"},"reqs":{"paths":["requirements"],"format":"html_to_md"}},"titleTemplate":"{jobTitle} @ {org}","bodyVar":"desc","sections":[{"heading":"Requirements","textVar":"reqs"}]}},{"match":{"hosts":["*.recruitee.com"],"hostSubdomain":{"suffix":".recruitee.com","param":"org","reserved":["www","app"]},"pathSegments":[]},"twin":{"id":"recruitee","fetchUrl":"https://{host}/api/offers","kind":"json","accept":"application/json"},"extract":{"vars":{"count":{"paths":["offers"],"format":"array_len"}},"requireVars":["count"],"titleTemplate":"{org} — Recruitee Job Board ({count} open roles)","sections":[{"heading":"","arrayPath":"offers","limit":100,"emptyText":"No open positions currently listed.","itemVars":{"oTitle":{"paths":["title"],"trim":true,"default":"Role"},"slug":{"paths":["slug"]},"rawUrl":{"paths":["careers_url"],"requireHttps":true},"oUrl":{"template":"{rawUrl}","whenVars":["rawUrl"],"fallbackTemplate":"https://{host}/o/{slug}"},"dept":{"paths":["department"],"trim":true,"default":"-"},"remoteLoc":{"paths":["remote"],"format":"bool_map","trueValue":"Remote","falseValue":"-"},"loc":{"paths":["location"],"trim":true,"fallbackTemplate":"{remoteLoc}"},"isRemote":{"paths":["remote"],"format":"bool_map","trueValue":"Remote","falseValue":""},"hybridOrOnsite":{"paths":["hybrid"],"format":"bool_map","trueValue":"Hybrid","falseValue":"On-site"},"workplace":{"template":"{isRemote}","whenVars":["isRemote"],"fallbackVar":"hybridOrOnsite"}},"collectLinkVars":["oUrl"],"columns":[{"header":"Role","template":"[{oTitle}]({oUrl})"},{"header":"Department","template":"{dept}"},{"header":"Location","template":"{loc}"},{"header":"Workplace","template":"{workplace}"}]}]}},{"match":{"anyOf":[{"hosts":["*.jobs.personio.de"],"hostSubdomain":{"suffix":".jobs.personio.de","param":"org"},"pathSegments":[]},{"hosts":["*.jobs.personio.com"],"hostSubdomain":{"suffix":".jobs.personio.com","param":"org"},"pathSegments":[]}]},"twin":{"id":"personio","fetchUrl":"https://{host}/xml?language=en","kind":"text","accept":"application/xml"},"extract":{"xml":{"mode":"items_table","requireAnyTags":["workzag-jobs","position"],"itemTag":"position","titleTemplate":"{org} — Personio Job Board ({itemCount} open roles)","emptyText":"No open positions currently listed.","limit":100,"itemVars":{"id":{"tags":["id"]},"pName":{"tags":["name"],"default":"Role"},"dept":{"tags":["department"],"default":"-"},"office":{"tags":["office"],"default":"-"},"schedule":{"tags":["schedule"],"default":"-"}},"columns":[{"header":"Role","template":"[{pName}](https://{host}/job/{id})"},{"header":"Department","template":"{dept}"},{"header":"Office","template":"{office}"},{"header":"Schedule","template":"{schedule}"}]}}}]},{"id":"bazaarvoice","name":"Bazaarvoice Product Reviews","category":"commerce-social","description":"Opt-in page-key adapter for Bazaarvoice Display API reviews; defaults OFF and falls back cleanly to HTML/JSON-LD when disabled.","domains":["api.bazaarvoice.com","www.bazaarvoice.com"],"universalEngine":true,"auth_mode":"page-key","requires_page_key_opt_in":true,"exampleUrls":["https://api.bazaarvoice.com/data/reviews.json?apiversion=5.4&passkey=lgnkpccztvv6hpje273tu0cx8&Filter=ProductId:YWSHTS&Include=Products&Stats=Reviews&Limit=5"],"routes":[{"match":{"hosts":["api.bazaarvoice.com"],"pathEquals":["/data/reviews.json","/data/display/0.2alpha/product/summary"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"jsonMode":"bazaarvoice_reviews"}}],"htmlRoutes":[{"id":"bazaarvoice","match":{"exactSegments":false},"mode":"bazaarvoice_html"}]},{"id":"bbb","name":"Better Business Bureau (BBB)","category":"commerce-social","description":"Extracts BBB business profile metadata, accreditation status, rating, contact details, and categories from public bbb.org profile pages while strictly honoring robots.txt.","domains":["bbb.org","www.bbb.org"],"auth_mode":"html","strict_robots":true,"exampleUrls":["https://www.bbb.org/us/md/linthicum-heights/profile/property-management/american-community-management-inc-0011-10073"],"htmlRoutes":[{"id":"bbb","match":{"exactSegments":false},"mode":"bbb_html"}]},{"id":"bea","name":"Bureau of Economic Analysis (BEA)","category":"finance","description":"U.S. Bureau of Economic Analysis apps.bea.gov JSON API adapter (NIPA/GDP/Regional/International) with bea.gov HTML fallback.","domains":["bea.gov","www.bea.gov","apps.bea.gov"],"auth_mode":"key","exampleUrls":["https://apps.bea.gov/api/data?method=GetDataSetList&ResultFormat=JSON","https://www.bea.gov/data/gdp/gross-domestic-product"],"routes":[{"match":{"hosts":["apps.bea.gov"],"exactSegments":true,"pathEquals":["/api/data","/API/data","/api/data/","/API/data/"]},"twin":{"fetchUrl":"{requestUrl}","defaultQueryParams":{"ResultFormat":"JSON"},"kind":"json","accept":"application/json","maxBytes":4194304,"auth_mode":"key"},"extract":{"jsonMode":"bea_json"}}],"htmlRoutes":[{"id":"bea","match":{"hosts":["bea.gov","www.bea.gov"],"exactSegments":false},"mode":"bea_html"}]},{"id":"bestbuy","name":"Best Buy Products API","category":"commerce-social","description":"Extracts Best Buy product pricing, SKU, UPC/GTIN, availability, and search results via the official Best Buy Products API.","domains":["bestbuy.com","www.bestbuy.com","api.bestbuy.com"],"auth_mode":"key","exampleUrls":["https://api.bestbuy.com/v1/products/6500131.json","https://api.bestbuy.com/v1/products?format=json"],"routes":[{"match":{"hosts":["bestbuy.com","www.bestbuy.com"],"exactSegments":false,"pathSegments":["site",{"param":"slug","charset":"slug","maxLen":200},{"param":"sku","charset":"digits","stripSuffix":".p","minLen":5,"maxLen":12}]},"twin":{"fetchUrl":"https://api.bestbuy.com/v1/products/{sku}.json","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"bestbuy_json"}},{"match":{"hosts":["api.bestbuy.com"],"pathPrefix":"/v1/products"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"bestbuy_json"}}]},{"id":"bicycleretailer","name":"Bicycle Retailer & Industry News","category":"commerce-social","description":"Extracts Drupal .node-article body, .view-content listings, and author/publishedTime metadata from bicycleretailer.com while stripping sidebar ads and leaving /rss.xml to feed XML parsing.","domains":["www.bicycleretailer.com","bicycleretailer.com"],"exampleUrls":["https://www.bicycleretailer.com/industry-news/2026/11/25/preliminary-analysis-industry-spared-new-recommended-tariffs","https://www.bicycleretailer.com/industry-news"],"htmlRoutes":[{"id":"bicycleretailer","mode":"dom","match":{"exactSegments":false,"reservedFirstSegment":["admin","user"],"excludeSegmentSuffixes":[".xml",".rss",".atom"]},"vars":{"title":{"cssText":["article.node-article h1","main h1","h1","title"],"metaKeys":["og:title"],"trim":true},"author":{"metaKeys":["author","article:author"],"trim":true},"publishedTime":{"metaKeys":["article:published_time"],"trim":true},"body":{"cssHtmlToMd":["article.node-article .field-name-body",".node-article .field-name-body",".field-name-body",".view-content","article.node-article","main"],"format":"strip_leading_h1","trim":true}},"requireVars":["title"],"titleTemplate":"{title}","authorVar":"author","publishedTimeVar":"publishedTime","bodyVar":"body","preserveBodyLinksFromVar":"body"}]},{"id":"big-cartel","name":"Big Cartel Storefronts & Products","category":"commerce-social","description":"Extracts Big Cartel /products.json catalogs and /product/{slug}.js product twins without colliding with Shopify /products.json, plus storefront HTML/JSON-LD fallback.","domains":["shop.bigcartel.com"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://shop.bigcartel.com/product/buy-from-artists-tote-bag.js","https://shop.bigcartel.com/products.json"],"routes":[{"match":{"anyOf":[{"hosts":["shop.bigcartel.com"],"pathEquals":["/products.json"]},{"hostSubdomain":{"suffix":".bigcartel.com","param":"shopSub","reserved":["www","my","api","developers","blog","assets","help"]},"pathEquals":["/products.json"]}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"commerceMode":"big_cartel_json"}},{"match":{"excludeHosts":["bigcartel.com","www.bigcartel.com","api.bigcartel.com","my.bigcartel.com","developers.bigcartel.com","blog.bigcartel.com","assets.bigcartel.com","help.bigcartel.com"],"exactSegments":true,"pathSuffix":".js","pathSegments":["product",{"param":"slug","charset":"pkg","stripSuffix":".js","minLen":1,"maxLen":160}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"commerceMode":"big_cartel_json"}}],"htmlRoutes":[{"id":"big-cartel","match":{"exactSegments":false},"mode":"big_cartel_html"}]},{"id":"bigcommerce-store","name":"BigCommerce Stencil Storefronts","category":"commerce-social","description":"Extracts BigCommerce Stencil BCData, JSON-LD, Microdata, cart-form options, product specs, category grids, and bounded /xmlsitemap.php product sitemaps.","domains":["*.mybigcommerce.com","www.bigcommerce.com","ascolour.com"],"universalEngine":true,"exampleUrls":["https://ascolour.com/xmlsitemap.php","https://ascolour.com/classic-organic-tee-5026g/"],"routes":[{"match":{"exactSegments":true,"pathEquals":["/xmlsitemap.php"]},"twin":{"id":"bigcommerce-store","fetchUrl":"{requestUrl}","kind":"text","accept":"application/xml","maxBytes":4194304},"extract":{"commerceMode":"bigcommerce_sitemap"}}],"htmlRoutes":[{"id":"bigcommerce-store","match":{"exactSegments":false},"mode":"bigcommerce_html"}]},{"id":"bike-index","name":"Bike Index Registry","category":"public-records","description":"Public Bike Index REST API v3 adapter for bicycle registrations, stolen reports, and search queries with HTML detail fallback.","domains":["bikeindex.org","www.bikeindex.org"],"auth_mode":"pub","exampleUrls":["https://bikeindex.org/api/v3/search?page=1&per_page=5","https://bikeindex.org/api/v3/bikes/3550041","https://bikeindex.org/bikes/3550041"],"routes":[{"match":{"hosts":["bikeindex.org","www.bikeindex.org"],"pathEquals":["/api/v3/search","/api/v3/search/"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"bike_index_json"}},{"match":{"hosts":["bikeindex.org","www.bikeindex.org"],"pathSegments":["api","v3","bikes",{"param":"bikeId","charset":"digits","minLen":1,"maxLen":16}]},"twin":{"fetchUrl":"https://bikeindex.org/api/v3/bikes/{bikeId}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"bike_index_json"}},{"match":{"hosts":["bikeindex.org","www.bikeindex.org"],"pathSegments":["bikes",{"param":"bikeId","charset":"digits","minLen":1,"maxLen":16}]},"twin":{"fetchUrl":"https://bikeindex.org/api/v3/bikes/{bikeId}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"bike_index_json"}}],"htmlRoutes":[{"id":"bike-index","match":{"exactSegments":false},"mode":"bike_index_html"}]},{"id":"bloomreach-discovery","name":"Bloomreach Discovery On-Site Search","category":"commerce-social","description":"Opt-in page-key adapter for Bloomreach Discovery core search JSON endpoints; defaults OFF and falls back cleanly to HTML/JSON-LD when disabled.","domains":["core.dxpapi.com"],"universalEngine":true,"auth_mode":"page-key","requires_page_key_opt_in":true,"exampleUrls":["https://core.dxpapi.com/api/v1/core/?account_id=6276&auth_key=jazzhands&domain_key=example_com&request_type=search&search_type=keyword&q=shoes&fl=pid,title,price,url&rows=10&start=0&url=https://www.example.com/search"],"routes":[{"match":{"hostSubdomain":{"suffix":".dxpapi.com","param":"apiHost"},"pathEquals":["/api/v1/core","/api/v1/core/"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"jsonMode":"bloomreach_discovery"}}],"htmlRoutes":[{"id":"bloomreach-discovery","match":{"exactSegments":false},"mode":"bloomreach_discovery_html"}]},{"id":"bls","name":"Bureau of Labor Statistics (BLS)","category":"public-records","description":"U.S. Bureau of Labor Statistics publicAPI v1 (pub) and v2 (key) time-series JSON adapter with bls.gov HTML fallback.","domains":["bls.gov","www.bls.gov","data.bls.gov","api.bls.gov"],"auth_mode":"pub","strict_robots":true,"exampleUrls":["https://www.bls.gov/cpi/","https://www.bls.gov/ooh/"],"routes":[{"match":{"hosts":["api.bls.gov"],"exactSegments":false,"pathPrefix":"/publicAPI/v1/timeseries/data"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"pub"},"extract":{"jsonMode":"bls_json"}},{"match":{"hosts":["api.bls.gov"],"exactSegments":false,"pathPrefix":"/publicAPI/v2/timeseries/data"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"key"},"extract":{"jsonMode":"bls_json"}}],"htmlRoutes":[{"id":"bls","match":{"hosts":["bls.gov","www.bls.gov","data.bls.gov"],"exactSegments":false},"mode":"bls_html"}]},{"id":"bluesky-thread","name":"Bluesky ATProto Post Threads","category":"commerce-social","description":"Upgrades bsky.app post URLs to public.api.bsky.app ATProto getPostThread JSON with replies and embeds.","domains":["bsky.app","staging.bsky.app"],"exampleUrls":["https://bsky.app/profile/golang.org/post/3mzyghkrmjh2y"],"match":{"exactSegments":false,"pathSegments":["profile",{"param":"actor","charset":"url_seg"},"post",{"param":"rkey","charset":"pkg"}]},"twin":{"id":"bluesky-thread","fetchUrl":"https://public.api.bsky.app/xrpc/app.bsky.feed.getPostThread?uri=at%3A%2F%2F{actor}%2Fapp.bsky.feed.post%2F{rkey}&depth=6","kind":"json","accept":"application/json"},"extract":{"rootPath":"thread","requireFields":["post.record.text"],"vars":{"handle":{"paths":["post.author.handle"],"fallbackTemplate":"{actor}"},"displayName":{"paths":["post.author.displayName"],"fallbackTemplate":"{handle}"},"text":{"paths":["post.record.text"],"format":"plain_text","trim":true},"desc":{"paths":["post.record.text"],"trim":true,"sliceMax":220},"createdAt":{"paths":["post.record.createdAt"]},"createdAtShort":{"paths":["post.record.createdAt"],"replaceAll":{"from":"T","to":" "},"sliceMax":16},"postedPrefix":{"template":"{createdAtShort} UTC · ","whenVars":["createdAtShort"]},"likes":{"paths":["post.likeCount"],"default":"0"},"reposts":{"paths":["post.repostCount"],"default":"0"},"extUri":{"paths":["post.embed.external.uri"]},"extTitle":{"paths":["post.embed.external.title"],"fallbackTemplate":"{extUri}"},"extDesc":{"paths":["post.embed.external.description"]},"extDescSuffix":{"template":" — {extDesc}","whenVars":["extDesc"]},"linkedEmbed":{"template":"> **Linked**: [{extTitle}]({extUri}){extDescSuffix}","whenVars":["extUri"]}},"titleTemplate":"{displayName} (@{handle}) on Bluesky","descriptionVar":"desc","authorTemplate":"@{handle}","publishedTimeVar":"createdAt","bodyVar":"text","footerItalicTemplate":"Posted {postedPrefix}{likes} likes · {reposts} reposts","sections":[{"heading":"","textVar":"linkedEmbed"},{"heading":"","listArrayPath":"post.embed.images","limit":10,"requireItemVar":"imgAlt","itemVars":{"imgAlt":{"paths":["alt"],"trim":true}},"itemTemplate":"*Image alt*: {imgAlt}"},{"heading":"Replies","listArrayPath":"replies","limit":15,"requireItemVar":"replyText","itemVars":{"replyAuthor":{"paths":["post.author.handle"],"default":"user"},"replyText":{"paths":["post.record.text"],"trim":true,"replaceAll":{"from":"\n","to":" "}}},"itemTemplate":"**@{replyAuthor}**: {replyText}"}]}},{"id":"bosch-ebike-help","name":"Bosch eBike Systems Help Center","category":"developer","description":"Bosch eBike error codes from help.bosch-ebike.com via the keyless public /v2/error_code JSON endpoint the Help Center SPA renders (code / severity / component / description / remedy per system generation), with a bounded HTML fallback for SSR help articles that strips data:image blobs and dodo-service-include chrome and never presents the loading SPA shell as content. Never calls the robots-disallowed /api/* paths.","domains":["help.bosch-ebike.com"],"auth_mode":"pub","exampleUrls":["https://help.bosch-ebike.com/en/help-center/error/6A0004","https://help.bosch-ebike.com/help-center/error/6A0004"],"routes":[{"match":{"hosts":["help.bosch-ebike.com"],"anyOf":[{"pathSegments":[{"param":"lang","allowValues":["cs","da","de","en","es","fr","it","nl","no","pl","sv"]},"help-center","error",{"param":"code","charset":"hex","minLen":3,"maxLen":6,"transform":"upper"}]},{"optionalLeadingLocale":true,"defaults":{"lang":"en"},"pathSegments":["help-center","error",{"param":"code","charset":"hex","minLen":3,"maxLen":6,"transform":"upper"}]},{"defaults":{"lang":"en"},"pathSegments":["er",{"param":"code","charset":"hex","minLen":3,"maxLen":6,"transform":"upper"}]}]},"twin":{"fetchUrl":"https://help.bosch-ebike.com/v2/error_code?externalID={code}&languageId={lang}","kind":"json","accept":"application/json","maxBytes":524288},"extract":{"jsonMode":"bosch_ebike_error_code_json"}}],"htmlRoutes":[{"id":"bosch-ebike-help","match":{"exactSegments":false},"mode":"bosch_help_html"}]},{"id":"brightcove","name":"Brightcove Playback & Player","category":"commerce-social","description":"Opt-in page-key adapter for Brightcove Playback API v1; defaults OFF and falls back cleanly to Brightcove player HTML extraction.","domains":["edge.api.brightcove.com","players.brightcove.net"],"auth_mode":"page-key","requires_page_key_opt_in":true,"exampleUrls":["https://edge.api.brightcove.com/playback/v1/accounts/1752604059001/videos/4093643993001","https://players.brightcove.net/1752604059001/default_default/index.html?videoId=4093643993001"],"routes":[{"match":{"hosts":["edge.api.brightcove.com"],"exactSegments":true,"pathSegments":["playback","v1","accounts",{"param":"accountId","charset":"digits","minLen":4,"maxLen":24},"videos",{"param":"videoId","charset":"url_seg","minLen":4,"maxLen":64}]},"twin":{"id":"brightcove","fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"jsonMode":"brightcove_playback_json"}}],"htmlRoutes":[{"id":"brightcove","match":{"exactSegments":false},"mode":"brightcove_html"}]},{"id":"brightspot","name":"Brightspot Publishing CMS","category":"commerce-social","description":"Extracts NewsArticle JSON-LD and Brightspot RichText article bodies across Brightspot-powered newsrooms.","domains":["www.latimes.com","news.byu.edu"],"universalEngine":true,"auth_mode":"html","exampleUrls":["https://www.latimes.com/travel/story/2023-10-19/los-angeles-neighborhood-city-guides"],"htmlRoutes":[{"id":"brightspot","match":{"exactSegments":false},"mode":"brightspot_html"}]},{"id":"bts-transtats","name":"BTS TranStats & Open Data","category":"public-records","description":"Bureau of Transportation Statistics (data.bts.gov Socrata views/resource/catalog JSON + www.transtats.bts.gov HTML tables with TranStats error page rejection).","domains":["data.bts.gov","transtats.bts.gov","www.transtats.bts.gov"],"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://data.bts.gov/api/views/crem-w557.json","https://data.bts.gov/resource/crem-w557.json?$limit=2","https://www.transtats.bts.gov/Tables.asp?QO_VQ=EFD&QO_anzr=Nv4"],"routes":[{"match":{"hosts":["data.bts.gov"],"anyOf":[{"pathPrefix":"/api/views/","pathSuffix":".json"},{"pathPrefix":"/resource/","pathSuffix":".json"},{"pathEquals":["/api/catalog/v1"]}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"bts_transtats_json"}},{"match":{"hosts":["data.bts.gov"],"minSegments":2,"anyOf":[{"exactSegments":false,"pathSegments":["d",{"param":"viewId","charset":"socrata_4x4","transform":"lower"}]},{"scanSegment":{"lastOrBeforeLiteral":"about_data","param":"viewId","charset":"socrata_4x4","transform":"lower"}}]},"twin":{"fetchUrl":"https://data.bts.gov/api/views/{viewId}.json","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"bts_transtats_json"}}],"htmlRoutes":[{"id":"bts-transtats","match":{"hosts":["transtats.bts.gov","www.transtats.bts.gov"],"exactSegments":false},"mode":"bts_transtats_html"}]},{"id":"bumm-de","name":"Busch & Mueller (bumm.de)","category":"commerce-social","description":"Extracts TYPO3 JSON-LD Product metadata, table.attributes-table technical specs, and PDF mounting manual links from bumm.de product pages.","domains":["bumm.de","www.bumm.de"],"exampleUrls":["https://bumm.de/en/product-detail/iq-xl-highbeam/","https://bumm.de/de/produktdetail/briq-s/"],"htmlRoutes":[{"id":"bumm-de","mode":"dom","match":{"optionalLeadingLocale":true,"exactSegments":false,"reservedFirstSegment":["typo3"],"anyOf":[{"pathSegments":["product-detail",{"param":"slug","charset":"url_seg","minLen":1,"maxLen":160}]},{"pathSegments":["produktdetail",{"param":"slug","charset":"url_seg","minLen":1,"maxLen":160}]},{"pathSegments":["products","detail",{"param":"slug","charset":"url_seg","minLen":1,"maxLen":160}]}]},"jsonLdTypes":["Product"],"vars":{"title":{"jsonLdPaths":["name"],"cssText":["main h1","h1","title"],"trim":true},"brand":{"jsonLdPaths":["brand.name","brand"],"trim":true},"sku":{"jsonLdPaths":["sku"],"trim":true},"price":{"jsonLdPaths":["offers.price","offers.0.price"],"trim":true},"currency":{"jsonLdPaths":["offers.priceCurrency","offers.0.priceCurrency"],"trim":true},"body":{"cssHtmlToMd":["main",".product-detail","body"],"format":"strip_leading_h1","trim":true}},"requireVars":["title"],"titleTemplate":"{title}","bullets":[{"label":"Brand","template":"{brand}","whenVar":"brand"},{"label":"SKU","template":"`{sku}`","whenVar":"sku"},{"label":"Price","template":"{price} {currency}","whenVar":"price"}],"bodyVar":"body","preserveBodyLinksFromVar":"body"}]},{"id":"cdc-wonder-healthdata","name":"CDC WONDER & HealthData.gov","category":"research-health","description":"HealthData.gov and data.cdc.gov Socrata views/resource/catalog JSON adapter (coexisting cleanly with socrata.yaml) plus CDC WONDER HTML.","domains":["healthdata.gov","www.healthdata.gov","wonder.cdc.gov"],"universalEngine":true,"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://healthdata.gov/api/views/j8mb-icvb.json","https://data.cdc.gov/api/views/9bhg-hcku.json","https://wonder.cdc.gov/ucd-icd10.html"],"routes":[{"match":{"hosts":["healthdata.gov","www.healthdata.gov","data.cdc.gov"],"anyOf":[{"pathPrefix":"/api/views/","pathSuffix":".json"},{"pathPrefix":"/resource/","pathSuffix":".json"},{"pathEquals":["/api/catalog/v1"]}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"cdc_healthdata_json"}},{"match":{"hosts":["healthdata.gov","www.healthdata.gov"],"minSegments":2,"anyOf":[{"exactSegments":false,"pathSegments":["d",{"param":"viewId","charset":"socrata_4x4","transform":"lower"}]},{"scanSegment":{"lastOrBeforeLiteral":"about_data","param":"viewId","charset":"socrata_4x4","transform":"lower"}}]},"twin":{"fetchUrl":"https://{host}/api/views/{viewId}.json","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"cdc_healthdata_json"}}],"htmlRoutes":[{"id":"cdc-wonder-healthdata","match":{"hosts":["wonder.cdc.gov","healthdata.gov","www.healthdata.gov"],"exactSegments":false},"mode":"cdc_wonder_html"}]},{"id":"census","name":"U.S. Census Bureau Data API","category":"public-records","description":"U.S. Census Bureau Data API (/data/{year}/... keyed JSON matrix) and /data.json DCAT catalog adapter with data.census.gov fallback.","domains":["data.census.gov","api.census.gov","census.gov","www.census.gov"],"auth_mode":"key","exampleUrls":["https://api.census.gov/data/2023/acs/acs1?get=NAME,B01001_001E&for=state:06","https://api.census.gov/data/2023/acs/acs1.json","https://www.census.gov/topics/population.html"],"routes":[{"match":{"hosts":["api.census.gov"],"exactSegments":false,"pathPrefix":"/data/","pathSuffix":".json"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304,"auth_mode":"pub"},"extract":{"jsonMode":"census_json"}},{"match":{"hosts":["api.census.gov"],"exactSegments":false,"pathPrefix":"/data/","excludeSegmentSuffixes":[".html",".htm"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304,"auth_mode":"key"},"extract":{"jsonMode":"census_json"}},{"match":{"hosts":["api.census.gov"],"exactSegments":true,"pathEquals":["/data.json"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304,"auth_mode":"pub"},"extract":{"jsonMode":"census_json"}}],"htmlRoutes":[{"id":"census","match":{"hosts":["data.census.gov","census.gov","www.census.gov"],"exactSegments":false},"mode":"census_html"}]},{"id":"cfpb-complaints","name":"CFPB Consumer Complaint Database","category":"finance","description":"Upgrades consumerfinance.gov complaint detail URLs to keyless CFPB Consumer Complaint Database JSON API v1 with HTML fallback.","domains":["www.consumerfinance.gov","consumerfinance.gov"],"auth_mode":"pub","exampleUrls":["https://www.consumerfinance.gov/data-research/consumer-complaints/search/detail/3204968","https://www.consumerfinance.gov/data-research/consumer-complaints/search/api/v1/3204968"],"routes":[{"match":{"hosts":["www.consumerfinance.gov","consumerfinance.gov"],"exactSegments":false,"pathSegments":["data-research","consumer-complaints","search","detail",{"param":"complaintId","charset":"digits","minLen":1,"maxLen":20}]},"twin":{"fetchUrl":"https://www.consumerfinance.gov/data-research/consumer-complaints/search/api/v1/{complaintId}","kind":"json","accept":"application/json","auth_mode":"pub","maxBytes":2097152},"extract":{"jsonMode":"cfpb_complaints_json"}},{"match":{"hosts":["www.consumerfinance.gov","consumerfinance.gov"],"pathPrefix":"/data-research/consumer-complaints/search/api/v1/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"pub","maxBytes":2097152},"extract":{"jsonMode":"cfpb_complaints_json"}}],"htmlRoutes":[{"id":"cfpb-complaints","match":{"hosts":["www.consumerfinance.gov","consumerfinance.gov"],"pathPrefix":"/data-research/consumer-complaints/","exactSegments":false},"mode":"cfpb_complaints_html"}]},{"id":"chambermaster-growthzone","name":"ChamberMaster / GrowthZone Chamber Directories","category":"commerce-social","description":"Universal extractor for chamber-of-commerce member directories hosted on ChamberMaster / GrowthZone (/list/ category and search pages, /list/member/ detail pages): member name, address, phone, website, hours, categories, and description.","domains":["business.fortworthchamber.com"],"universalEngine":true,"auth_mode":"html","min_interval_ms":2000,"strict_robots":true,"exampleUrls":["https://business.fortworthchamber.com/list/category/apartments-25","https://business.fortworthchamber.com/list/member/the-harden-at-public-market-50786"],"htmlRoutes":[{"id":"chambermaster-growthzone","match":{"pathPrefix":"/list","exactSegments":false},"mode":"chambermaster_html"}]},{"id":"changelog-roadmap-pack","name":"Changelog & Roadmap Pack","category":"developer","description":"Extracts changelog releases and roadmap items from Canny, Productboard Portal, Headway, Beamer (via /loadMoreNews companion), and LaunchNotes.","domains":["feedback.canny.io","portal.productboard.com","headwayapp.co","app.getbeamer.com","updates.launchnotes.io"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://feedback.canny.io/changelog","https://portal.productboard.com/pb/1-productboard-portal/tabs/7-under-consideration","https://app.getbeamer.com/beamer/changelog","https://updates.launchnotes.io/"],"routes":[{"match":{"pathEquals":["/changelog.json","/releases.json","/updates.json"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"changelog_roadmap_json"}}],"htmlRoutes":[{"id":"changelog-roadmap-pack","match":{"exactSegments":false},"mode":"changelog_roadmap_html"}]},{"id":"chronicling-america","name":"Chronicling America (Historic American Newspapers)","category":"public-records","description":"Library of Congress Chronicling America historic newspapers adapter rewriting legacy chroniclingamerica.loc.gov and collection URLs directly to www.loc.gov ?fo=json.","domains":["chroniclingamerica.loc.gov"],"universalEngine":true,"auth_mode":"pub","min_interval_ms":5000,"strict_robots":true,"exampleUrls":["https://www.loc.gov/collections/chronicling-america/?fo=json","https://chroniclingamerica.loc.gov/lccn/sn83030214.json","https://www.loc.gov/collections/chronicling-america/"],"routes":[{"match":{"hosts":["chroniclingamerica.loc.gov"],"exactSegments":false,"pathSegments":["lccn",{"param":"lccn","charset":"url_seg","stripSuffix":".json","minLen":4,"maxLen":32}]},"twin":{"fetchUrl":"https://www.loc.gov/item/{lccn}/?fo=json","kind":"json","accept":"application/json","maxBytes":4194304,"auth_mode":"pub"},"extract":{"jsonMode":"chronicling_america_json"}},{"match":{"hosts":["chroniclingamerica.loc.gov"],"anyOf":[{"pathEquals":["/","/newspapers.json"]},{"pathPrefix":"/search/"}]},"twin":{"fetchUrl":"https://www.loc.gov/collections/chronicling-america/?fo=json","kind":"json","accept":"application/json","maxBytes":4194304,"auth_mode":"pub"},"extract":{"jsonMode":"chronicling_america_json"}},{"match":{"hosts":["www.loc.gov","loc.gov"],"exactSegments":false,"pathSegments":["chroniclingamerica","lccn",{"param":"lccn","charset":"url_seg","stripSuffix":".json","minLen":4,"maxLen":32}]},"twin":{"fetchUrl":"https://www.loc.gov/item/{lccn}/?fo=json","kind":"json","accept":"application/json","maxBytes":4194304,"auth_mode":"pub"},"extract":{"jsonMode":"chronicling_america_json"}},{"match":{"hosts":["www.loc.gov","loc.gov"],"anyOf":[{"pathPrefix":"/collections/chronicling-america"},{"pathPrefix":"/chroniclingamerica"}]},"twin":{"fetchUrl":"https://www.loc.gov/collections/chronicling-america/?fo=json","kind":"json","accept":"application/json","maxBytes":4194304,"auth_mode":"pub"},"extract":{"jsonMode":"chronicling_america_json"}}],"htmlRoutes":[{"id":"chronicling-america","match":{"anyOf":[{"hosts":["chroniclingamerica.loc.gov"],"exactSegments":false},{"hosts":["www.loc.gov","loc.gov"],"pathPrefix":"/collections/chronicling-america"},{"hosts":["www.loc.gov","loc.gov"],"pathPrefix":"/chroniclingamerica"}]},"mode":"chronicling_america_html"}]},{"id":"civicplus","name":"CivicPlus CivicEngage Agenda Center","category":"public-records","description":"Universal extractor for CivicPlus CivicEngage /AgendaCenter pages on any city or county domain: meeting dates, agenda titles, agenda/HTML/packet links, and minutes, grouped by board. Fingerprint-gated (catAgendaRow + CivicPlus markup); robots.txt on CivicPlus sites disallows /RSSFeed.aspx, so the HTML page is used.","domains":["www.gulfshoresal.gov","www.ankenyiowa.gov"],"universalEngine":true,"auth_mode":"html","min_interval_ms":2000,"strict_robots":true,"exampleUrls":["https://www.gulfshoresal.gov/AgendaCenter"],"htmlRoutes":[{"id":"civicplus","match":{"pathPrefix":"/AgendaCenter","exactSegments":false},"mode":"civicplus_agenda_html"}]},{"id":"ckan","name":"CKAN Open Data Portals (Data.gov, UK, AU, Canada & City Portals)","category":"public-records","description":"Upgrades CKAN open-data portal dataset pages to /api/3/action/package_show JSON with organization, license, and downloadable resources.","domains":["catalog.data.gov","data.boston.gov","data.sanantonio.gov","data.sanjoseca.gov","data.wprdc.org","data.gov.uk","www.data.gov.uk","data.gov.au","open.canada.ca"],"exampleUrls":["https://open.canada.ca/data/en/dataset/0032ce54-c5dd-4b66-99a0-320a7b5e99f2"],"routes":[{"match":{"hosts":["catalog.data.gov","data.boston.gov","data.sanantonio.gov","data.sanjoseca.gov","data.wprdc.org"],"exactSegments":true,"pathSegments":["dataset",{"param":"pkgId","charset":"pkg","minLen":2,"maxLen":160}]},"twin":{"fetchUrl":"https://{host}/api/3/action/package_show?id={pkgId}","kind":"json","accept":"application/json"},"extract":{"requireFieldEquals":{"path":"success","value":"true"},"requireAnyFields":["result"],"vars":{"title":{"paths":["result.title","result.title.en"],"trim":true,"fallbackTemplate":"{pkgId}"},"orgTitle":{"paths":["result.organization.title"]},"license":{"paths":["result.license_title"]},"modified":{"paths":["result.metadata_modified"],"sliceMax":10},"notes":{"paths":["result.notes"],"format":"strip_tags"},"notesShort":{"paths":["result.notes"],"format":"strip_tags","sliceMax":260},"tags":{"paths":["result.tags"],"subFieldsJoin":{"fields":["display_name"],"sep":"","fallbackField":"name"},"limit":12,"join":", "}},"titleTemplate":"{title}","descriptionVar":"notesShort","authorVar":"orgTitle","publishedTimeVar":"modified","bullets":[{"label":"Portal","template":"`{host}`"},{"label":"Publisher","template":"{orgTitle}","whenVar":"orgTitle"},{"label":"License","template":"{license}","whenVar":"license"},{"label":"Last Updated","template":"{modified}","whenVar":"modified"},{"label":"Tags","template":"{tags}","whenVar":"tags"}],"sections":[{"heading":"Description","textVar":"notes"},{"heading":"Data Resources","headingTemplate":"Data Resources ({count})","arrayPath":"result.resources","limit":20,"collectLinkVars":["rUrl"],"itemVars":{"rName":{"paths":["name","description","format"],"trim":true,"default":"Resource"},"rUrl":{"paths":["url"],"requireHttps":true},"rCell":{"template":"[{rName}]({rUrl})","whenVars":["rName","rUrl"],"fallbackVar":"rName"},"rFmt":{"paths":["format"],"upper":true,"default":"-"}},"columns":[{"header":"Resource","template":"{rCell}"},{"header":"Format","template":"{rFmt}"}]}]}},{"match":{"hosts":["data.gov.uk","www.data.gov.uk"],"exactSegments":true,"pathSegments":["dataset",{"param":"pkgId","charset":"pkg","minLen":2,"maxLen":160}]},"twin":{"fetchUrl":"https://data.gov.uk/api/action/package_show?id={pkgId}","kind":"json","accept":"application/json"},"extract":{"requireFieldEquals":{"path":"success","value":"true"},"requireAnyFields":["result"],"vars":{"title":{"paths":["result.title","result.title.en"],"trim":true,"fallbackTemplate":"{pkgId}"},"orgTitle":{"paths":["result.organization.title"]},"license":{"paths":["result.license_title"]},"modified":{"paths":["result.metadata_modified"],"sliceMax":10},"notes":{"paths":["result.notes"],"format":"strip_tags"},"notesShort":{"paths":["result.notes"],"format":"strip_tags","sliceMax":260},"tags":{"paths":["result.tags"],"subFieldsJoin":{"fields":["display_name"],"sep":"","fallbackField":"name"},"limit":12,"join":", "}},"titleTemplate":"{title}","descriptionVar":"notesShort","authorVar":"orgTitle","publishedTimeVar":"modified","bullets":[{"label":"Portal","template":"`{host}`"},{"label":"Publisher","template":"{orgTitle}","whenVar":"orgTitle"},{"label":"License","template":"{license}","whenVar":"license"},{"label":"Last Updated","template":"{modified}","whenVar":"modified"},{"label":"Tags","template":"{tags}","whenVar":"tags"}],"sections":[{"heading":"Description","textVar":"notes"},{"heading":"Data Resources","headingTemplate":"Data Resources ({count})","arrayPath":"result.resources","limit":20,"collectLinkVars":["rUrl"],"itemVars":{"rName":{"paths":["name","description","format"],"trim":true,"default":"Resource"},"rUrl":{"paths":["url"],"requireHttps":true},"rCell":{"template":"[{rName}]({rUrl})","whenVars":["rName","rUrl"],"fallbackVar":"rName"},"rFmt":{"paths":["format"],"upper":true,"default":"-"}},"columns":[{"header":"Resource","template":"{rCell}"},{"header":"Format","template":"{rFmt}"}]}]}},{"match":{"hosts":["data.gov.au"],"exactSegments":true,"pathSegments":["data","dataset",{"param":"pkgId","charset":"pkg","minLen":2,"maxLen":160}]},"twin":{"fetchUrl":"https://data.gov.au/data/api/3/action/package_show?id={pkgId}","kind":"json","accept":"application/json"},"extract":{"requireFieldEquals":{"path":"success","value":"true"},"requireAnyFields":["result"],"vars":{"title":{"paths":["result.title","result.title.en"],"trim":true,"fallbackTemplate":"{pkgId}"},"orgTitle":{"paths":["result.organization.title"]},"license":{"paths":["result.license_title"]},"modified":{"paths":["result.metadata_modified"],"sliceMax":10},"notes":{"paths":["result.notes"],"format":"strip_tags"},"notesShort":{"paths":["result.notes"],"format":"strip_tags","sliceMax":260},"tags":{"paths":["result.tags"],"subFieldsJoin":{"fields":["display_name"],"sep":"","fallbackField":"name"},"limit":12,"join":", "}},"titleTemplate":"{title}","descriptionVar":"notesShort","authorVar":"orgTitle","publishedTimeVar":"modified","bullets":[{"label":"Portal","template":"`{host}`"},{"label":"Publisher","template":"{orgTitle}","whenVar":"orgTitle"},{"label":"License","template":"{license}","whenVar":"license"},{"label":"Last Updated","template":"{modified}","whenVar":"modified"},{"label":"Tags","template":"{tags}","whenVar":"tags"}],"sections":[{"heading":"Description","textVar":"notes"},{"heading":"Data Resources","headingTemplate":"Data Resources ({count})","arrayPath":"result.resources","limit":20,"collectLinkVars":["rUrl"],"itemVars":{"rName":{"paths":["name","description","format"],"trim":true,"default":"Resource"},"rUrl":{"paths":["url"],"requireHttps":true},"rCell":{"template":"[{rName}]({rUrl})","whenVars":["rName","rUrl"],"fallbackVar":"rName"},"rFmt":{"paths":["format"],"upper":true,"default":"-"}},"columns":[{"header":"Resource","template":"{rCell}"},{"header":"Format","template":"{rFmt}"}]}]}},{"match":{"hosts":["open.canada.ca"],"exactSegments":true,"pathSegments":["data","en","dataset",{"param":"pkgId","charset":"pkg","minLen":2,"maxLen":160}]},"twin":{"fetchUrl":"https://open.canada.ca/data/api/action/package_show?id={pkgId}","kind":"json","accept":"application/json"},"extract":{"requireFieldEquals":{"path":"success","value":"true"},"requireAnyFields":["result"],"vars":{"title":{"paths":["result.title","result.title.en"],"trim":true,"fallbackTemplate":"{pkgId}"},"orgTitle":{"paths":["result.organization.title"]},"license":{"paths":["result.license_title"]},"modified":{"paths":["result.metadata_modified"],"sliceMax":10},"notes":{"paths":["result.notes"],"format":"strip_tags"},"notesShort":{"paths":["result.notes"],"format":"strip_tags","sliceMax":260},"tags":{"paths":["result.tags"],"subFieldsJoin":{"fields":["display_name"],"sep":"","fallbackField":"name"},"limit":12,"join":", "}},"titleTemplate":"{title}","descriptionVar":"notesShort","authorVar":"orgTitle","publishedTimeVar":"modified","bullets":[{"label":"Portal","template":"`{host}`"},{"label":"Publisher","template":"{orgTitle}","whenVar":"orgTitle"},{"label":"License","template":"{license}","whenVar":"license"},{"label":"Last Updated","template":"{modified}","whenVar":"modified"},{"label":"Tags","template":"{tags}","whenVar":"tags"}],"sections":[{"heading":"Description","textVar":"notes"},{"heading":"Data Resources","headingTemplate":"Data Resources ({count})","arrayPath":"result.resources","limit":20,"collectLinkVars":["rUrl"],"itemVars":{"rName":{"paths":["name","description","format"],"trim":true,"default":"Resource"},"rUrl":{"paths":["url"],"requireHttps":true},"rCell":{"template":"[{rName}]({rUrl})","whenVars":["rName","rUrl"],"fallbackVar":"rName"},"rFmt":{"paths":["format"],"upper":true,"default":"-"}},"columns":[{"header":"Resource","template":"{rCell}"},{"header":"Format","template":"{rFmt}"}]}]}}]},{"id":"classic-forum-pack","name":"Classic Forum Pack","category":"commerce-social","description":"Extracts structured posts, authors, timestamps, and quote blocks from Invision Community, vBulletin (vB3/4 & vB5), and phpBB thread HTML while rejecting HTTP 200 soft-404s.","domains":["gtaforums.com","forum.doom9.org","forum.image-line.com"],"universalEngine":true,"auth_mode":"html","exampleUrls":["https://gtaforums.com/topic/1007946-gtao-event-12th-nov-2026-as-the-trip-to-leonida-approaches-go-back-to-the-basics-w-bonuses-on-all-contact-missions-free-mode-challenges-stunt-race-series-more/","https://forum.doom9.org/showthread.php?t=187224","https://forum.image-line.com/viewtopic.php?t=343634"],"htmlRoutes":[{"id":"classic-forum-pack","match":{"exactSegments":false},"mode":"classic_forum_pack_html"}]},{"id":"clinicaltrials","name":"ClinicalTrials.gov Studies","category":"research-health","description":"Extracts clinical trial NCT ID, recruitment status, phase, conditions, interventions, sponsor, and summary from rendered clinicaltrials.gov/study/NCT... pages (strictly respecting robots.txt).","domains":["clinicaltrials.gov","www.clinicaltrials.gov"],"exampleUrls":["https://clinicaltrials.gov/study/NCT04280705"],"htmlRoutes":[{"match":{"scanSegment":{"param":"nctId","charset":"nct_id","transform":"upper"}},"mode":"dom","jsonLdTypes":["MedicalStudy","MedicalTrial","ClinicalTrial"],"embeddedBalancedKey":"protocolSection","requireVars":["title","hasAnyDetail"],"vars":{"title":{"embeddedPaths":["identificationModule.briefTitle"],"jsonLdPaths":["name"],"metaKeys":["og:title"]},"overallStatus":{"embeddedPaths":["statusModule.overallStatus"],"jsonLdPaths":["status"]},"phases":{"embeddedPaths":["designModule.phases"],"join":", "},"leadSponsor":{"embeddedPaths":["sponsorCollaboratorsModule.leadSponsor.name"],"jsonLdPaths":["sponsor.name"]},"conditions":{"embeddedPaths":["conditionsModule.conditions"],"jsonLdPaths":["healthCondition"],"limit":10,"join":", "},"summary":{"embeddedPaths":["descriptionModule.briefSummary"],"jsonLdPaths":["description"],"metaKeys":["description"]},"summaryShort":{"template":"{summary}","whenVars":["summary"],"sliceMax":260},"hasAnyDetail":{"template":"1","whenAnyVars":["overallStatus","phases","leadSponsor","conditions","summary"]}},"titleTemplate":"{title} ({nctId})","descriptionVar":"summaryShort","bullets":[{"label":"NCT Number","template":"`{nctId}`"},{"label":"Status","template":"{overallStatus}","whenVar":"overallStatus"},{"label":"Phase","template":"{phases}","whenVar":"phases"},{"label":"Lead Sponsor","template":"{leadSponsor}","whenVar":"leadSponsor"},{"label":"Conditions","template":"{conditions}","whenVar":"conditions"}],"sections":[{"heading":"Brief Summary","textVar":"summary"}],"appendCurrentMdDelta":{"baseVar":"summary","minExtraChars":120}}]},{"id":"cms-data","name":"CMS Data & Provider Data Catalog","category":"research-health","description":"Centers for Medicare & Medicaid Services (CMS) DKAN metastore, datastore query, and data-api v1 adapter enforcing 10s crawl-delay.","domains":["data.cms.gov"],"auth_mode":"pub","min_interval_ms":10000,"strict_robots":true,"exampleUrls":["https://data.cms.gov/provider-data/api/1/metastore/schemas/dataset/items/mj5m-pzi6","https://data.cms.gov/provider-data/api/1/datastore/query/mj5m-pzi6/0?limit=2","https://data.cms.gov/data-api/v1/dataset/9767cb68-8ea9-4f0b-8179-9431abc89f11/data?size=2"],"routes":[{"match":{"anyOf":[{"pathPrefix":"/provider-data/api/"},{"pathPrefix":"/data-api/v1/"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"cms_data_json"}},{"match":{"exactSegments":true,"pathSegments":["provider-data","dataset",{"param":"datasetId","charset":"alnum_dash","minLen":4,"maxLen":64}]},"twin":{"fetchUrl":"https://data.cms.gov/provider-data/api/1/metastore/schemas/dataset/items/{datasetId}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"cms_data_json"}}],"htmlRoutes":[{"id":"cms-data","match":{"exactSegments":false},"mode":"cms_data_html"}]},{"id":"college-scorecard","name":"College Scorecard (U.S. Department of Education)","category":"public-records","description":"U.S. Department of Education College Scorecard API adapter scoped to api.data.gov/ed/collegescorecard with compact default fields.","domains":["collegescorecard.ed.gov","api.data.gov"],"auth_mode":"key","exampleUrls":["https://api.data.gov/ed/collegescorecard/v1/schools?id=166027","https://collegescorecard.ed.gov/school/?166027-Harvard-University"],"routes":[{"match":{"hosts":["api.data.gov"],"exactSegments":false,"pathPrefix":"/ed/collegescorecard"},"twin":{"fetchUrl":"{requestUrl}","defaultQueryParams":{"fields":"id,school.name,school.city,school.state,school.school_url,latest.student.size,latest.admissions.admission_rate.overall,latest.cost.tuition.in_state,latest.cost.tuition.out_of_state,latest.earnings.10_yrs_after_entry.median","per_page":"10"},"kind":"json","accept":"application/json","maxBytes":4194304,"auth_mode":"key"},"extract":{"jsonMode":"college_scorecard_json"}}],"htmlRoutes":[{"id":"college-scorecard","match":{"hosts":["collegescorecard.ed.gov"],"exactSegments":false},"mode":"college_scorecard_html"}]},{"id":"confluence-public","name":"Confluence Public Spaces","category":"developer","description":"Upgrades public Confluence /wiki/spaces/.../pages/{pageId} URLs to same-origin REST content API JSON twins with SSR HTML fallback; keyless public spaces only.","domains":["openmrs.atlassian.net","ecosystem.atlassian.net"],"universalEngine":true,"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://openmrs.atlassian.net/wiki/spaces/docs/pages/25462110/Reporting+Module","https://openmrs.atlassian.net/wiki/spaces/docs/overview"],"routes":[{"match":{"pathPrefix":"/wiki/spaces/","exactSegments":false,"pathSegments":["wiki","spaces",{"param":"space","charset":"url_seg","minLen":1,"maxLen":80},"pages",{"param":"pageId","charset":"digits","minLen":1,"maxLen":20},{"param":"slug","charset":"safe_subpath","optional":true,"greedy":true}]},"twin":{"fetchUrl":"https://{host}/wiki/rest/api/content/{pageId}?expand=body.view,space,version,ancestors","kind":"json","accept":"application/json"},"extract":{"jsonMode":"confluence_public"}},{"match":{"exactSegments":true,"pathSegments":["wiki","rest","api","content",{"param":"pageId","charset":"digits","minLen":1,"maxLen":20}]},"twin":{"fetchUrl":"{requestUrl}","defaultQueryParams":{"expand":"body.view,space,version,ancestors"},"kind":"json","accept":"application/json"},"extract":{"jsonMode":"confluence_public"}},{"match":{"exactSegments":true,"pathSegments":["wiki","api","v2","pages",{"param":"pageId","charset":"digits","minLen":1,"maxLen":20}]},"twin":{"fetchUrl":"{requestUrl}","defaultQueryParams":{"body-format":"view"},"kind":"json","accept":"application/json"},"extract":{"jsonMode":"confluence_public"}}],"htmlRoutes":[{"id":"confluence-public","match":{"exactSegments":false},"mode":"confluence_public_html"}]},{"id":"congress-gov","name":"Congress.gov Federal Legislation","category":"public-records","description":"Official api.congress.gov v3 API adapter for federal bills, amendments, nominations, committees, and members with HTML fallback for www.congress.gov.","domains":["congress.gov","www.congress.gov","api.congress.gov"],"auth_mode":"key","min_interval_ms":2000,"exampleUrls":["https://api.congress.gov/v3/bill/118/hr/815?format=json","https://www.congress.gov/bill/118th-congress/house-bill/815"],"routes":[{"match":{"hosts":["api.congress.gov"],"pathPrefix":"/v3/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":4194304},"extract":{"jsonMode":"congress_gov_json"}},{"match":{"hosts":["congress.gov","www.congress.gov"],"exactSegments":false,"pathSegments":["bill",{"param":"congress","charset":"alnum_dash","minLen":3,"maxLen":20,"transform":"leading_digits"},"house-bill",{"param":"billNumber","charset":"digits","minLen":1,"maxLen":8}]},"twin":{"fetchUrl":"https://api.congress.gov/v3/bill/{congress}/hr/{billNumber}?format=json","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":4194304},"extract":{"jsonMode":"congress_gov_json"}},{"match":{"hosts":["congress.gov","www.congress.gov"],"exactSegments":false,"pathSegments":["bill",{"param":"congress","charset":"alnum_dash","minLen":3,"maxLen":20,"transform":"leading_digits"},"senate-bill",{"param":"billNumber","charset":"digits","minLen":1,"maxLen":8}]},"twin":{"fetchUrl":"https://api.congress.gov/v3/bill/{congress}/s/{billNumber}?format=json","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":4194304},"extract":{"jsonMode":"congress_gov_json"}},{"match":{"hosts":["congress.gov","www.congress.gov"],"exactSegments":false,"pathSegments":["bill",{"param":"congress","charset":"alnum_dash","minLen":3,"maxLen":20,"transform":"leading_digits"},"house-joint-resolution",{"param":"billNumber","charset":"digits","minLen":1,"maxLen":8}]},"twin":{"fetchUrl":"https://api.congress.gov/v3/bill/{congress}/hjres/{billNumber}?format=json","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":4194304},"extract":{"jsonMode":"congress_gov_json"}},{"match":{"hosts":["congress.gov","www.congress.gov"],"exactSegments":false,"pathSegments":["bill",{"param":"congress","charset":"alnum_dash","minLen":3,"maxLen":20,"transform":"leading_digits"},"senate-joint-resolution",{"param":"billNumber","charset":"digits","minLen":1,"maxLen":8}]},"twin":{"fetchUrl":"https://api.congress.gov/v3/bill/{congress}/sjres/{billNumber}?format=json","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":4194304},"extract":{"jsonMode":"congress_gov_json"}},{"match":{"hosts":["congress.gov","www.congress.gov"],"exactSegments":false,"pathSegments":["bill",{"param":"congress","charset":"alnum_dash","minLen":3,"maxLen":20,"transform":"leading_digits"},"house-concurrent-resolution",{"param":"billNumber","charset":"digits","minLen":1,"maxLen":8}]},"twin":{"fetchUrl":"https://api.congress.gov/v3/bill/{congress}/hconres/{billNumber}?format=json","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":4194304},"extract":{"jsonMode":"congress_gov_json"}},{"match":{"hosts":["congress.gov","www.congress.gov"],"exactSegments":false,"pathSegments":["bill",{"param":"congress","charset":"alnum_dash","minLen":3,"maxLen":20,"transform":"leading_digits"},"senate-concurrent-resolution",{"param":"billNumber","charset":"digits","minLen":1,"maxLen":8}]},"twin":{"fetchUrl":"https://api.congress.gov/v3/bill/{congress}/sconres/{billNumber}?format=json","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":4194304},"extract":{"jsonMode":"congress_gov_json"}},{"match":{"hosts":["congress.gov","www.congress.gov"],"exactSegments":false,"pathSegments":["bill",{"param":"congress","charset":"alnum_dash","minLen":3,"maxLen":20,"transform":"leading_digits"},"house-resolution",{"param":"billNumber","charset":"digits","minLen":1,"maxLen":8}]},"twin":{"fetchUrl":"https://api.congress.gov/v3/bill/{congress}/hres/{billNumber}?format=json","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":4194304},"extract":{"jsonMode":"congress_gov_json"}},{"match":{"hosts":["congress.gov","www.congress.gov"],"exactSegments":false,"pathSegments":["bill",{"param":"congress","charset":"alnum_dash","minLen":3,"maxLen":20,"transform":"leading_digits"},"senate-resolution",{"param":"billNumber","charset":"digits","minLen":1,"maxLen":8}]},"twin":{"fetchUrl":"https://api.congress.gov/v3/bill/{congress}/sres/{billNumber}?format=json","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":4194304},"extract":{"jsonMode":"congress_gov_json"}}],"htmlRoutes":[{"id":"congress-gov","match":{"hosts":["congress.gov","www.congress.gov"],"exactSegments":false},"mode":"congress_gov_html"}]},{"id":"constructor-io","name":"Constructor.io On-Site Search","category":"commerce-social","description":"Opt-in page-key adapter for Constructor.io search JSON endpoints; defaults OFF and falls back cleanly to HTML/JSON-LD when disabled.","domains":["ac.cnstrc.com"],"universalEngine":true,"auth_mode":"page-key","requires_page_key_opt_in":true,"exampleUrls":["https://ac.cnstrc.com/search/shirt?key=key_kUTI6qLxMCLBIaN9&num_results_per_page=10"],"routes":[{"match":{"anyOf":[{"hostSubdomain":{"suffix":".cnstrc.com","param":"regionHost"},"pathSegments":["search",{"param":"query","charset":"url_seg","minLen":1,"maxLen":200}]},{"hostSubdomain":{"suffix":".cnstrc.com","param":"regionHost"},"pathSegments":["v1","search",{"param":"query","charset":"url_seg","minLen":1,"maxLen":200}]}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"jsonMode":"constructor_io"}}],"htmlRoutes":[{"id":"constructor-io","match":{"exactSegments":false},"mode":"constructor_io_html"}]},{"id":"copyright-office","name":"U.S. Copyright Office Public Records","category":"public-records","description":"U.S. Copyright Office Public Records System (publicrecords.copyright.gov) keyless JSON API adapter with HTML fallback.","domains":["publicrecords.copyright.gov","api.publicrecords.copyright.gov","cocatalog.loc.gov"],"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://api.publicrecords.copyright.gov/search_service_external/simple_search_dsl?query=TX0009000001&page_number=1&records_per_page=5","https://publicrecords.copyright.gov/detailed-record/voyager_32941460"],"routes":[{"match":{"hosts":["api.publicrecords.copyright.gov"],"pathPrefix":"/search_service_external/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"pub"},"extract":{"jsonMode":"copyright_office_json"}},{"match":{"hosts":["publicrecords.copyright.gov"],"exactSegments":false,"pathSegments":["detailed-record",{"param":"recordId","charset":"alnum_dash","minLen":3,"maxLen":80}]},"twin":{"fetchUrl":"https://api.publicrecords.copyright.gov/search_service_external/simple_search_dsl?query={recordId}&page_number=1&records_per_page=5","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"pub"},"extract":{"jsonMode":"copyright_office_json"}}],"htmlRoutes":[{"id":"copyright-office","match":{"hosts":["publicrecords.copyright.gov","cocatalog.loc.gov"],"exactSegments":false},"mode":"copyright_office_html"}]},{"id":"cornell-lii","name":"Cornell Law LII (CFR & US Code)","category":"public-records","description":"Extracts clean statutory and CFR regulatory text from www.law.cornell.edu/cfr/* and /uscode/* while stripping navigation and donation sidebars.","domains":["www.law.cornell.edu","law.cornell.edu"],"exampleUrls":["https://www.law.cornell.edu/cfr/text/16/part-1512","https://www.law.cornell.edu/uscode/text/15/2051"],"htmlRoutes":[{"id":"cornell-lii","mode":"dom","match":{"anyOf":[{"exactSegments":false,"pathSegments":["cfr",{"param":"rest","charset":"safe_subpath","greedy":true,"minLen":1,"maxLen":200}]},{"exactSegments":false,"pathSegments":["uscode",{"param":"rest","charset":"safe_subpath","greedy":true,"minLen":1,"maxLen":200}]}]},"vars":{"title":{"cssText":["#page-title","main#content h1","#content h1","h1","title"],"trim":true},"body":{"cssHtmlToMd":["#content .tab-pane.active","main#content","#content","main","article"],"format":"strip_leading_h1","trim":true}},"requireVars":["title","body"],"titleTemplate":"{title}","bodyVar":"body","preserveBodyLinksFromVar":"body"}]},{"id":"costco-sams-club","name":"Costco & Sam's Club","category":"commerce-social","description":"Extracts Costco and Sam's Club public product pages from schema.org Product JSON-LD and Sam's Club __NEXT_DATA__ hydration, strictly rejecting Kasada, Akamai, and empty SPA shells.","domains":["costco.com","www.costco.com","costco.ca","www.costco.ca","samsclub.com","www.samsclub.com"],"auth_mode":"html","min_interval_ms":3000,"max_concurrent":1,"strict_robots":true,"exampleUrls":["https://www.costco.com/p/-/costco-shop-card/10024438","https://www.samsclub.com/ip/tnt-fireworks-revolution-rumble/20020700393"],"htmlRoutes":[{"id":"costco-sams-club","match":{"hosts":["costco.com","www.costco.com","costco.ca","www.costco.ca","samsclub.com","www.samsclub.com"]},"mode":"costco_sams_club_html"}]},{"id":"county-assessor","name":"County Assessor & Property Records","category":"public-records","description":"Universal extractor for Vision Government Solutions (VGSI), Tyler Technologies iasWorld, and SchneiderCorp qPublic/Beacon county property assessor portals.","domains":["gis.vgsi.com","icare.fairfaxcounty.gov","property.muni.org","qpublic.schneidercorp.com","beacon.schneidercorp.com"],"universalEngine":true,"auth_mode":"html","strict_robots":true,"exampleUrls":["https://gis.vgsi.com/madisonct/Parcel.aspx?pid=4","https://gis.vgsi.com/madisonct/Parcel.aspx?pid=10","https://gis.vgsi.com/newhavenct/Parcel.aspx?pid=1"],"htmlRoutes":[{"id":"county-assessor","match":{"exactSegments":false},"mode":"county_assessor_html"}]},{"id":"courseleaf","name":"CourseLeaf University Course Catalogs","category":"public-records","description":"Universal extractor for CourseLeaf catalog pages (catalog..edu/courses// and program pages): course code, title, credits, description, requisites, and grading from div.courseblock. Fingerprint-gated; never calls /ribbit/, which CourseLeaf robots.txt files disallow.","domains":["catalog.unc.edu"],"universalEngine":true,"auth_mode":"html","min_interval_ms":2000,"strict_robots":true,"exampleUrls":["https://catalog.unc.edu/courses/comp/"],"htmlRoutes":[{"id":"courseleaf","match":{"exactSegments":false},"mode":"courseleaf_courses_html"}]},{"id":"courtlistener","name":"CourtListener Federal & State Case Law","category":"public-records","description":"Official CourtListener REST API v4 adapter for opinions, clusters, RECAP dockets, and court metadata with HTML fallback.","domains":["courtlistener.com","www.courtlistener.com"],"auth_mode":"key","exampleUrls":["https://www.courtlistener.com/api/rest/v4/courts/scotus/","https://www.courtlistener.com/api/rest/v4/clusters/108713/","https://www.courtlistener.com/opinion/108713/marbury-v-madison/"],"routes":[{"match":{"pathPrefix":"/api/rest/v4/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":4194304},"extract":{"jsonMode":"courtlistener_v4_json"}},{"match":{"exactSegments":false,"pathSegments":["opinion",{"param":"clusterId","charset":"digits","minLen":1,"maxLen":16}]},"twin":{"fetchUrl":"https://www.courtlistener.com/api/rest/v4/clusters/{clusterId}/","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":4194304},"extract":{"jsonMode":"courtlistener_v4_json"}},{"match":{"exactSegments":false,"pathSegments":["docket",{"param":"docketId","charset":"digits","minLen":1,"maxLen":16}]},"twin":{"fetchUrl":"https://www.courtlistener.com/api/rest/v4/dockets/{docketId}/","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":4194304},"extract":{"jsonMode":"courtlistener_v4_json"}}],"htmlRoutes":[{"id":"courtlistener","match":{"exactSegments":false},"mode":"courtlistener_html"}]},{"id":"coveo","name":"Coveo Cloud Search","category":"developer","description":"Opt-in page-key adapter for Coveo /rest/search/v2 endpoints; honors robots.txt Allow /rest/search and defaults OFF.","domains":["platform.cloud.coveo.com"],"universalEngine":true,"auth_mode":"page-key","requires_page_key_opt_in":true,"exampleUrls":["https://platform.cloud.coveo.com/rest/search/v2?organizationId=mycoveocloudv2organizationg8tp8wu3&access_token=xx564559b1-0045-48e1-953c-3addd1ee4457&q=coveo&numberOfResults=10"],"routes":[{"match":{"hostSubdomain":{"suffix":".cloud.coveo.com","param":"regionHost"},"pathEquals":["/rest/search/v2"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"jsonMode":"coveo"}}],"htmlRoutes":[{"id":"coveo","match":{"exactSegments":false},"mode":"coveo_html"}]},{"id":"cpsc-ebike-battery","name":"E-Bike Battery Safety Standards (UL 2849)","category":"public-records","description":"Extracts UL 2849 / UL 2271 e-bike electrical system and battery certification guidance from ul.com (complementing cpsc-recalls and ebike-state-laws).","domains":["ul.com","www.ul.com"],"auth_mode":"html","exampleUrls":["https://www.ul.com/services/e-bikes-certificationevaluating-and-testing-ul-2849","https://www.ul.com/industries/automotive-and-mobility/micromobility-device-evaluation-testing-and-certification","https://www.ul.com/resources/comparison-e-bikes-standards-en-15194-and-ul-2849"],"htmlRoutes":[{"id":"cpsc-ebike-battery","match":{"exactSegments":false},"mode":"cpsc_ebike_battery_html"}]},{"id":"cpsc-recalls","name":"CPSC Recalls & SaferProducts.gov","category":"public-records","description":"Formats bounded saferproducts.gov RecallNumber queries via JSON twin and extracts structured recall details and RecallNumber from cpsc.gov/Recalls pages (never fetching the unfiltered 25 MiB SaferProducts dump).","domains":["www.saferproducts.gov","saferproducts.gov","www.cpsc.gov","cpsc.gov"],"exampleUrls":["https://www.saferproducts.gov/RestWebServices/Recall?format=json&RecallNumber=24123","https://www.cpsc.gov/Recalls/2027/Cipton-Recalls-Bicycle-Helmets-Due-to-Risk-of-Serious-Injury-or-Death-from-Head-Injury-Violate-Mandatory-Standard-for-Bicycle-Helmets"],"routes":[{"match":{"hosts":["www.saferproducts.gov","saferproducts.gov"],"pathEquals":["/RestWebServices/Recall","/RestWebServices/Recall/"],"queryParams":[{"names":["RecallNumber","recallnumber","recallNumber","RECALLNUMBER"],"param":"recallNum","charset":"cpsc_recall_num","minLen":2,"maxLen":24,"transform":"strip_dashes"}]},"twin":{"fetchUrl":"https://www.saferproducts.gov/RestWebServices/Recall?format=json&RecallNumber={recallNum}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"unwrapFirstArrayElement":true,"requireFields":["RecallNumber","Title"],"vars":{"title":{"paths":["Title"],"trim":true},"recallNumber":{"paths":["RecallNumber"],"trim":true},"recallDate":{"paths":["RecallDate"],"sliceMax":10},"lastPublishDate":{"paths":["LastPublishDate"],"sliceMax":10},"description":{"paths":["Description"],"trim":true},"descShort":{"paths":["Description"],"trim":true,"sliceMax":260},"consumerContact":{"paths":["ConsumerContact"],"trim":true},"recallUrl":{"paths":["URL"],"requireHttps":true},"hazards":{"paths":["Hazards"],"subField":"Name","join":"; ","limit":10},"remedies":{"paths":["Remedies"],"subField":"Name","join":"; ","limit":10},"manufacturers":{"paths":["Manufacturers"],"subField":"Name","join":", ","limit":10},"retailers":{"paths":["Retailers"],"subField":"Name","join":", ","limit":10},"injuries":{"paths":["Injuries"],"subField":"Name","join":"; ","limit":10}},"titleTemplate":"{title} (Recall #{recallNumber})","descriptionVar":"descShort","publishedTimeVar":"recallDate","bullets":[{"label":"Recall Number","template":"`{recallNumber}`"},{"label":"Recall Date","template":"{recallDate}","whenVar":"recallDate"},{"label":"Last Published","template":"{lastPublishDate}","whenVar":"lastPublishDate"},{"label":"Hazards","template":"{hazards}","whenVar":"hazards"},{"label":"Remedies","template":"{remedies}","whenVar":"remedies"},{"label":"Injuries / Incidents","template":"{injuries}","whenVar":"injuries"},{"label":"Manufacturers","template":"{manufacturers}","whenVar":"manufacturers"},{"label":"Retailers","template":"{retailers}","whenVar":"retailers"},{"label":"Consumer Contact","template":"{consumerContact}","whenVar":"consumerContact"},{"label":"CPSC URL","template":"{recallUrl}","whenVar":"recallUrl"}],"sections":[{"heading":"Description","textVar":"description"},{"heading":"Products","arrayPath":"Products","limit":25,"columns":[{"header":"Name","paths":["Name"]},{"header":"Model","paths":["Model"],"code":true},{"header":"Units","paths":["NumberOfUnits"]},{"header":"Type","paths":["Type"]}]},{"heading":"Images","arrayPath":"Images","limit":10,"requireItemVar":"imgUrl","collectLinkVars":["imgUrl"],"itemVars":{"imgUrl":{"paths":["URL"],"requireHttps":true},"imgCap":{"paths":["Caption"],"default":"Recall product image"}},"itemTemplate":"[{imgCap}]({imgUrl})"}],"linksVars":["recallUrl"],"recordFields":{"recallNumber":"{recallNumber}","title":"{title}","recallDate":"{recallDate}","url":"{recallUrl}","hazards":"{hazards}","remedies":"{remedies}","manufacturers":"{manufacturers}"}}}],"htmlRoutes":[{"match":{"anyOf":[{"hosts":["www.cpsc.gov","cpsc.gov"],"exactSegments":false,"pathSegments":["Recalls",{"param":"year","charset":"digits","minLen":4,"maxLen":4},{"param":"slug","charset":"url_seg"}]},{"hosts":["www.cpsc.gov","cpsc.gov"],"exactSegments":false,"pathSegments":["recalls",{"param":"year","charset":"digits","minLen":4,"maxLen":4},{"param":"slug","charset":"url_seg"}]}]},"mode":"dom","vars":{"title":{"cssText":["h1"],"metaKeys":["og:title"],"trim":true},"recallNumber":{"regexExtract":{"source":"doc_text_and_img_alts","pattern":"(?i)Recall\\s*(?:Number|No\\.?|#)\\s*:?\\s*([0-9]{2}-?[0-9]{2,5})","group":1},"trim":true},"recallDate":{"metaKeys":["article:published_time"],"cssText":["time",".recall-detail__date"],"trim":true},"summary":{"metaKeys":["description","og:description"],"trim":true},"body":{"cssHtmlToMd":["main article",".recall-detail",".node--type-recall","main","article"],"format":"strip_leading_h1"}},"requireVars":["title","body"],"titleTemplate":"{title}","descriptionVar":"summary","publishedTimeVar":"recallDate","bullets":[{"label":"Recall Number","template":"`{recallNumber}`","whenVar":"recallNumber"},{"label":"Recall Date","template":"{recallDate}","whenVar":"recallDate"}],"bodyVar":"body"}]},{"id":"crates-io","name":"Rust Crates.io","category":"developer","description":"Upgrades crates.io pages to the v1 JSON API with Cargo install command, MSRV, Cargo features, downloads, and release history.","domains":["crates.io","www.crates.io"],"exampleUrls":["https://crates.io/crates/serde"],"match":{"exactSegments":false,"pathSegments":["crates",{"param":"crateName","charset":"alnum_dash","minLen":1,"maxLen":64}]},"twin":{"fetchUrl":"https://crates.io/api/v1/crates/{crateName}","kind":"json","accept":"application/json"},"extract":{"requireFields":["crate.name"],"vars":{"name":{"paths":["crate.name"]},"ver":{"paths":["crate.max_stable_version","crate.max_version","versions.0.num"]},"desc":{"paths":["crate.description"],"trim":true},"license":{"paths":["versions.0.license"]},"msrv":{"paths":["versions.0.rust_version"]},"repo":{"paths":["crate.repository"]},"docs":{"paths":["crate.documentation"],"fallbackTemplate":"https://docs.rs/{name}"},"downloads":{"paths":["crate.downloads"],"format":"int_comma"},"features":{"paths":["versions.0.features"],"format":"object_keys","limit":14,"itemWrap":"`","join":", "},"categories":{"paths":["categories"],"subField":"category","join":", "},"keywords":{"paths":["keywords"],"subField":"keyword","join":", "}},"titleTemplate":"{name} v{ver} (Rust Crate)","titleWhenVar":"ver","titleFallbackTemplate":"{name} (Rust Crate)","descriptionVar":"desc","introVar":"desc","bullets":[{"label":"Cargo","template":"`cargo add {name}`"},{"label":"Version","template":"`{ver}`","whenVar":"ver"},{"label":"MSRV","template":"Rust `{msrv}`","whenVar":"msrv"},{"label":"License","template":"{license}","whenVar":"license"},{"label":"Downloads","template":"{downloads}","whenVar":"downloads"},{"label":"API Docs","template":"{docs}","whenVar":"docs"},{"label":"Repository","template":"{repo}","whenVar":"repo"},{"label":"Cargo Features","template":"{features}","whenVar":"features"},{"label":"Categories","template":"{categories}","whenVar":"categories"},{"label":"Keywords","template":"{keywords}","whenVar":"keywords"}],"sections":[{"heading":"Recent Releases","arrayPath":"versions","minItems":2,"limit":6,"columns":[{"header":"Version","paths":["num"],"code":true},{"header":"Published","paths":["created_at"],"sliceMax":10},{"header":"MSRV","paths":["rust_version"]}]}],"linksVars":["docs","repo"]}},{"id":"dailymed","name":"NLM DailyMed Drug Labels","category":"research-health","description":"National Library of Medicine DailyMed v2 REST API adapter for JSON catalog endpoints and HL7 SPL XML documents with drugInfo HTML fallback.","domains":["dailymed.nlm.nih.gov"],"auth_mode":"pub","exampleUrls":["https://dailymed.nlm.nih.gov/dailymed/services/v2/spls.json?pagesize=2","https://dailymed.nlm.nih.gov/dailymed/services/v2/spls/0f3234b2-806e-4fab-99f5-b7d15177565b.xml","https://dailymed.nlm.nih.gov/dailymed/services/v2/drugnames.json?drug_name=lipitor&pagesize=2"],"routes":[{"match":{"pathPrefix":"/dailymed/services/v2/spls/","pathSuffix":".xml"},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"text/html","maxBytes":4194304},"extract":{"textMode":"dailymed_spl_xml"}},{"match":{"pathEquals":["/dailymed/services/v2/spls.json","/dailymed/services/v2/drugnames.json","/dailymed/services/v2/drugclasses.json","/dailymed/services/v2/ndcs.json","/dailymed/services/v2/rxcuis.json","/dailymed/services/v2/uniis.json"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"dailymed_list_json"}},{"match":{"pathEquals":["/dailymed/drugInfo.cfm"],"queryParams":[{"name":"setid","param":"setid","charset":"alnum_dash","minLen":32,"maxLen":40}]},"twin":{"fetchUrl":"https://dailymed.nlm.nih.gov/dailymed/services/v2/spls/{setid}.xml","kind":"text","accept":"text/html","maxBytes":4194304},"extract":{"textMode":"dailymed_spl_xml"}}],"htmlRoutes":[{"id":"dailymed","match":{"pathPrefix":"/dailymed/","exactSegments":false},"mode":"dailymed_html"}]},{"id":"dealer-locator-pack","name":"Dealer Locator Pack (Bullseye, Storepoint, MetaLocator, Where2GetIt)","category":"commerce-social","description":"Opt-in page-key adapter pack for Bullseye, Storepoint, MetaLocator, and Where2GetIt locator APIs; defaults OFF and falls back to HTML/JSON-LD.","domains":["ws.bullseyelocations.com","www.bullseyelocations.com","api.storepoint.co","hosted.where2getit.com","api.metalocator.com"],"universalEngine":true,"auth_mode":"page-key","requires_page_key_opt_in":true,"exampleUrls":["https://www.bullseyelocations.com/"],"routes":[{"match":{"anyOf":[{"hosts":["ws.bullseyelocations.com","www.bullseyelocations.com"],"pathEquals":["/RestSearch.svc/DoSearch2","/RestSearch.svc/DoSearch"]},{"hosts":["api.storepoint.co"],"pathPrefix":"/v1/"},{"hosts":["api.storepoint.co"],"pathPrefix":"/public/v1/"},{"hosts":["api.metalocator.com"],"pathPrefix":"/api/"},{"hosts":["hosted.where2getit.com"],"pathSegments":[{"param":"brand","charset":"alnum_dash","minLen":1,"maxLen":64},"responsive","ajax"]},{"hosts":["hosted.where2getit.com"],"pathSegments":[{"param":"brand","charset":"alnum_dash","minLen":1,"maxLen":64},"rest",{"param":"action","charset":"alnum_dash","minLen":1,"maxLen":64}]}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"jsonMode":"dealer_locator_pack"}}],"htmlRoutes":[{"id":"dealer-locator-pack","match":{"exactSegments":false},"mode":"dealer_locator_pack_html"}]},{"id":"deps-dev","name":"Open Source Insights (deps.dev)","category":"developer","description":"Extracts package versions, default/latest stable release, licenses, advisories, and dependencies via the deps.dev v3 JSON API.","domains":["deps.dev","api.deps.dev"],"auth_mode":"pub","exampleUrls":["https://api.deps.dev/v3/systems/npm/packages/express"],"routes":[{"match":{"hosts":["api.deps.dev"],"pathPrefix":"/v3/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"deps_dev_json"}},{"match":{"hosts":["deps.dev"],"exactSegments":false,"pathSegments":["npm",{"param":"scope","charset":"npm_scope","minLen":2,"maxLen":80},{"param":"pkg","charset":"npm_pkg","minLen":1,"maxLen":120}]},"twin":{"fetchUrl":"https://api.deps.dev/v3/systems/npm/packages/{scope}%2F{pkg}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"deps_dev_json"}},{"match":{"hosts":["deps.dev"],"exactSegments":false,"pathSegments":[{"param":"system","allowValues":["npm","pypi","cargo","nuget","go","maven"]},{"param":"pkg","charset":"url_seg","minLen":1,"maxLen":200}]},"twin":{"fetchUrl":"https://api.deps.dev/v3/systems/{system}/packages/{pkg}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"deps_dev_json"}}],"htmlRoutes":[{"id":"deps-dev","match":{"hosts":["deps.dev"],"exactSegments":false},"mode":"deps_dev_html"}]},{"id":"dev-to","name":"DEV Community Articles (dev.to)","category":"commerce-social","description":"Upgrades dev.to// articles to dev.to/api/articles raw body_markdown.","domains":["dev.to","www.dev.to"],"exampleUrls":["https://dev.to/ben/long-live-rails-3p21"],"match":{"exactSegments":true,"pathSegments":[{"param":"author","charset":"alnum_dash","reserved":["t","top","latest","pod","videos","tags","search","settings","enter","new","about","privacy","terms"]},{"param":"slug","charset":"alnum_dash"}]},"twin":{"fetchUrl":"https://dev.to/api/articles/{author}/{slug}","kind":"json","accept":"application/json"},"extract":{"requireFields":["title","body_markdown"],"vars":{"title":{"paths":["title"],"trim":true},"desc":{"paths":["description"],"trim":true},"author":{"paths":["user.name"]},"publishedTime":{"paths":["published_timestamp"]},"body":{"paths":["body_markdown"],"stripFrontmatter":true,"trim":true}},"titleTemplate":"{title}","descriptionVar":"desc","authorVar":"author","publishedTimeVar":"publishedTime","bodyVar":"body"}},{"id":"dining-reservations","name":"Dining Reservations (OpenTable / Resy / ToastTab)","category":"commerce-social","description":"Extracts public restaurant venue metadata from OpenTable, Resy, and ToastTab Local pages via Restaurant/FoodEstablishment JSON-LD and hydrated DOM while rejecting Cloudflare challenges and unhydrated Angular shells.","domains":["opentable.com","www.opentable.com","resy.com","www.resy.com","toasttab.com","www.toasttab.com"],"auth_mode":"html","min_interval_ms":2000,"max_concurrent":1,"strict_robots":true,"exampleUrls":["https://www.opentable.com/r/gary-danko-san-francisco","https://resy.com/cities/new-york-ny/venues/carbone","https://www.toasttab.com/local"],"htmlRoutes":[{"id":"dining-reservations","match":{"hosts":["opentable.com","www.opentable.com","resy.com","www.resy.com","toasttab.com","www.toasttab.com"]},"mode":"dining_reservations_html"}]},{"id":"discourse-topic","name":"Discourse Forum Threads (Universal Engine)","category":"commerce-social","description":"Upgrades any Discourse forum thread (/t//) to its .json post_stream with Accepted Solution badges.","domains":["meta.discourse.org","community.home-assistant.io","users.rust-lang.org","discuss.python.org"],"universalEngine":true,"exampleUrls":["https://community.home-assistant.io/t/how-to-help-us-help-you-or-how-to-ask-a-good-question/114371"],"match":{"exactSegments":false,"pathSegments":["t",{"param":"slug","charset":"url_seg"},{"param":"topicId","charset":"digits"}]},"twin":{"id":"discourse-topic","fetchUrl":"https://{host}/t/{slug}/{topicId}.json","kind":"json","accept":"application/json"},"extract":{"requireFields":["title"],"requireAnyFields":["post_stream.posts"],"vars":{"title":{"paths":["title"],"trim":true},"tags":{"paths":["tags"],"itemWrap":"`","join":", ","limit":20},"firstAuthor":{"paths":["post_stream.posts.0.username"]},"firstCreated":{"paths":["post_stream.posts.0.created_at"]},"acceptedPostNum":{"paths":["accepted_answer.post_number"]}},"titleTemplate":"{title}","authorVar":"firstAuthor","publishedTimeVar":"firstCreated","metaLine":[{"label":"Tags","template":"{tags}","whenVar":"tags"}],"sections":[{"heading":"","subsectionsArrayPath":"post_stream.posts","limit":20,"requireItemVar":"body","subsectionHeadingTemplate":"Original Post — {userWithDate}","subsectionAltWhenVar":"nonOpPostNum","subsectionAltHeadingTemplate":"{replyBadge} — {userWithDate}","subsectionBodyVar":"body","itemVars":{"postNum":{"paths":["post_number"],"fallbackTemplate":"{index1}"},"nonOpPostNum":{"paths":["post_number"],"excludeEquals":"1"},"isAcceptedFlag":{"paths":["accepted_answer"],"format":"bool_map","trueValue":"1","falseValue":""},"isAcceptedPostNum":{"paths":["post_number"],"equalsVar":"acceptedPostNum"},"replyBadge":{"template":"✅ Accepted Solution","whenAnyVars":["isAcceptedFlag","isAcceptedPostNum"],"fallbackTemplate":"Reply #{postNum}"},"username":{"paths":["username"]},"userLabel":{"template":"@{username}","whenVars":["username"],"default":"user"},"createdDate":{"paths":["created_at"],"sliceMax":10},"userWithDate":{"template":"{userLabel} ({createdDate})","whenVars":["createdDate"],"fallbackVar":"userLabel"},"body":{"paths":["cooked"],"format":"html_to_md"}}}]}},{"id":"dkan","name":"DKAN Open Data Portals (Metastore & Datastore)","category":"public-records","description":"Universal DKAN 2 adapter (data.medicaid.gov and state/city DKAN portals): formats /api/1/metastore/schemas/dataset/items catalogs and single datasets (publisher, modified, keywords, distributions) and /api/1/datastore/query// rows with data-dictionary column labels. Dataset pages on declared portals upgrade to the metastore JSON.","domains":["data.medicaid.gov"],"universalEngine":true,"auth_mode":"pub","min_interval_ms":2000,"exampleUrls":["https://data.medicaid.gov/api/1/metastore/schemas/dataset/items?show-reference-ids=false","https://data.medicaid.gov/api/1/datastore/query/ae4d5347-5137-5f6c-b66c-3420fa0316d8/0?limit=3","https://data.medicaid.gov/dataset/ae4d5347-5137-5f6c-b66c-3420fa0316d8"],"routes":[{"match":{"pathPrefix":"/api/1/metastore/schemas/dataset/items"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"dkan_metastore_json"}},{"match":{"exactSegments":false,"pathSegments":["api","1","datastore","query",{"param":"datasetId","charset":"slug","minLen":4,"maxLen":80}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"dkan_datastore_json"}},{"match":{"hosts":["data.medicaid.gov"],"exactSegments":true,"pathSegments":["dataset",{"param":"datasetId","charset":"slug","minLen":4,"maxLen":80}]},"twin":{"fetchUrl":"https://{host}/api/1/metastore/schemas/dataset/items/{datasetId}?show-reference-ids=false","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"dkan_metastore_json"}}]},{"id":"docker-hub","name":"Docker Hub","category":"developer","description":"Upgrades hub.docker.com repository and /tags pages (both /_/ official library and /r//) to the keyless Docker Hub v2 JSON API.","domains":["hub.docker.com"],"exampleUrls":["https://hub.docker.com/_/alpine","https://hub.docker.com/_/alpine/tags","https://hub.docker.com/r/library/nginx","https://hub.docker.com/r/library/nginx/tags"],"routes":[{"match":{"defaults":{"ns":"library"},"exactSegments":false,"pathSegments":["_",{"param":"repo","charset":"pkg","minLen":1,"maxLen":128},"tags"]},"twin":{"fetchUrl":"https://hub.docker.com/v2/repositories/library/{repo}/tags?page_size=25","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"requireAnyFields":["results"],"vars":{"totalCount":{"paths":["count"],"format":"int_comma"}},"titleTemplate":"{ns}/{repo} — Docker Tags ({totalCount} total)","titleWhenVar":"totalCount","titleFallbackTemplate":"{ns}/{repo} — Docker Tags","sections":[{"heading":"Recent Tags","arrayPath":"results","limit":25,"itemVars":{"platforms":{"paths":["images"],"subFieldsJoin":{"fields":["os","architecture"],"sep":"/"},"join":", ","limit":8},"sizeHuman":{"paths":["full_size"],"format":"bytes_human"}},"columns":[{"header":"Tag","paths":["name"],"code":true},{"header":"Size","template":"{sizeHuman}"},{"header":"Architectures","template":"{platforms}"},{"header":"Last Updated","paths":["last_updated"],"sliceMax":10}]}]}},{"match":{"exactSegments":false,"pathSegments":["r",{"param":"ns","charset":"pkg","minLen":1,"maxLen":128},{"param":"repo","charset":"pkg","minLen":1,"maxLen":128},"tags"]},"twin":{"fetchUrl":"https://hub.docker.com/v2/repositories/{ns}/{repo}/tags?page_size=25","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"requireAnyFields":["results"],"vars":{"totalCount":{"paths":["count"],"format":"int_comma"}},"titleTemplate":"{ns}/{repo} — Docker Tags ({totalCount} total)","titleWhenVar":"totalCount","titleFallbackTemplate":"{ns}/{repo} — Docker Tags","sections":[{"heading":"Recent Tags","arrayPath":"results","limit":25,"itemVars":{"platforms":{"paths":["images"],"subFieldsJoin":{"fields":["os","architecture"],"sep":"/"},"join":", ","limit":8},"sizeHuman":{"paths":["full_size"],"format":"bytes_human"}},"columns":[{"header":"Tag","paths":["name"],"code":true},{"header":"Size","template":"{sizeHuman}"},{"header":"Architectures","template":"{platforms}"},{"header":"Last Updated","paths":["last_updated"],"sliceMax":10}]}]}},{"match":{"defaults":{"ns":"library"},"exactSegments":false,"pathSegments":["_",{"param":"repo","charset":"pkg","minLen":1,"maxLen":128}]},"twin":{"fetchUrl":"https://hub.docker.com/v2/repositories/library/{repo}/","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"requireFields":["name","namespace"],"vars":{"namespace":{"paths":["namespace"]},"name":{"paths":["name"]},"desc":{"paths":["description"],"trim":true},"pulls":{"paths":["pull_count"],"format":"int_comma"},"stars":{"paths":["star_count"],"format":"int_comma"},"statusDesc":{"paths":["status_description"]},"lastUpdated":{"paths":["last_updated"],"sliceMax":10},"fullDesc":{"paths":["full_description"],"format":"demote_h1","trim":true}},"titleTemplate":"{namespace}/{name} (Docker Hub)","descriptionVar":"desc","publishedTimeVar":"lastUpdated","introVar":"desc","bullets":[{"label":"Pull Command","template":"`docker pull {name}`"},{"label":"Pulls","template":"{pulls}","whenVar":"pulls"},{"label":"Stars","template":"{stars}","whenVar":"stars"},{"label":"Status","template":"{statusDesc}","whenVar":"statusDesc"},{"label":"Last Updated","template":"{lastUpdated}","whenVar":"lastUpdated"}],"bodyVar":"fullDesc"}},{"match":{"exactSegments":false,"pathSegments":["r",{"param":"ns","charset":"pkg","minLen":1,"maxLen":128},{"param":"repo","charset":"pkg","minLen":1,"maxLen":128}]},"twin":{"fetchUrl":"https://hub.docker.com/v2/repositories/{ns}/{repo}/","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"requireFields":["name","namespace"],"vars":{"namespace":{"paths":["namespace"]},"name":{"paths":["name"]},"desc":{"paths":["description"],"trim":true},"pulls":{"paths":["pull_count"],"format":"int_comma"},"stars":{"paths":["star_count"],"format":"int_comma"},"statusDesc":{"paths":["status_description"]},"lastUpdated":{"paths":["last_updated"],"sliceMax":10},"fullDesc":{"paths":["full_description"],"format":"demote_h1","trim":true}},"titleTemplate":"{namespace}/{name} (Docker Hub)","descriptionVar":"desc","publishedTimeVar":"lastUpdated","introVar":"desc","bullets":[{"label":"Pull Command","template":"`docker pull {namespace}/{name}`"},{"label":"Pulls","template":"{pulls}","whenVar":"pulls"},{"label":"Stars","template":"{stars}","whenVar":"stars"},{"label":"Status","template":"{statusDesc}","whenVar":"statusDesc"},{"label":"Last Updated","template":"{lastUpdated}","whenVar":"lastUpdated"}],"bodyVar":"fullDesc"}}]},{"id":"docs-rs","name":"Rust docs.rs Crate Documentation","category":"developer","description":"Extracts Rust crate metadata, version, feature flags, doc coverage, and rustdoc API pages from docs.rs SSR HTML (avoiding /json zstd binary archives).","domains":["docs.rs"],"auth_mode":"pub","exampleUrls":["https://docs.rs/crate/serde/latest","https://docs.rs/serde/latest/serde/"],"htmlRoutes":[{"id":"docs-rs","match":{"hosts":["docs.rs"],"exactSegments":false},"mode":"docs_rs_html"}]},{"id":"doi-crossref","name":"DOI.org & Crossref Bibliographic Resolver","category":"research-health","description":"Upgrades doi.org/10./ links to api.crossref.org/works/ bibliographic JSON (authors, venue, citations, JATS abstract, and publisher URL).","domains":["doi.org","www.doi.org","dx.doi.org"],"exampleUrls":["https://doi.org/10.1038/s41586-021-03819-2"],"match":{"pathSegments":[{"param":"doi","charset":"doi_rest","greedy":true,"minLen":8,"maxLen":240}]},"twin":{"fetchUrl":"https://api.crossref.org/works/{doi}","kind":"json","accept":"application/json"},"extract":{"rootPath":"message","requireVars":["title"],"vars":{"title":{"paths":["title.0"],"fallbackTemplate":"{doi}","format":"strip_tags"},"authors":{"paths":["author"],"subFieldsJoin":{"fields":["given","family"],"sep":" ","fallbackField":"name"},"join":", ","limit":16},"authorsShort":{"paths":["author"],"subFieldsJoin":{"fields":["given","family"],"sep":" ","fallbackField":"name"},"join":", ","limit":4},"venue":{"paths":["container-title.0"]},"publisher":{"paths":["publisher"]},"venueFull":{"template":"{venue} ({publisher})","whenVars":["venue","publisher"],"fallbackVar":"venue"},"citations":{"paths":["is-referenced-by-count"],"format":"int_comma"},"pubUrl":{"paths":["URL"],"fallbackTemplate":"https://doi.org/{doi}","requireHttps":true},"pubDate":{"paths":["issued.date-parts.0"],"format":"date_parts"},"abstract":{"paths":["abstract"],"format":"jats_abstract"},"abstractShort":{"paths":["abstract"],"format":"jats_abstract","sliceMax":260}},"titleTemplate":"{title}","descriptionVar":"abstractShort","authorVar":"authorsShort","publishedTimeVar":"pubDate","bullets":[{"label":"DOI","template":"`{doi}`"},{"label":"Authors","template":"{authors}","whenVar":"authors"},{"label":"Venue / Journal","template":"{venueFull}","whenVar":"venueFull"},{"label":"Published","template":"{pubDate}","whenVar":"pubDate"},{"label":"Cited By (Crossref)","template":"{citations}","whenVar":"citations"},{"label":"Publisher Link","template":"{pubUrl}","whenVar":"pubUrl"}],"sections":[{"heading":"Abstract","textVar":"abstract"}],"linksVars":["pubUrl"]}},{"id":"dpla","name":"Digital Public Library of America (DPLA)","category":"public-records","description":"Digital Public Library of America (DPLA) API v2 adapter with HTML fallback and 2000ms Crawl-delay politeness.","domains":["dp.la","www.dp.la","api.dp.la"],"auth_mode":"key","min_interval_ms":2000,"exampleUrls":["https://api.dp.la/v2/items?q=kittens","https://dp.la/item/c3e08f4945e5b7d26386942a4a7f24a2"],"routes":[{"match":{"hosts":["api.dp.la"],"pathPrefix":"/v2/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"key"},"extract":{"jsonMode":"dpla_json"}},{"match":{"hosts":["dp.la","www.dp.la"],"exactSegments":false,"pathSegments":["item",{"param":"itemId","charset":"alnum_dash","minLen":4,"maxLen":64}]},"twin":{"fetchUrl":"https://api.dp.la/v2/items/{itemId}","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"key"},"extract":{"jsonMode":"dpla_json"}}],"htmlRoutes":[{"id":"dpla","match":{"hosts":["dp.la","www.dp.la"],"exactSegments":false,"reservedFirstSegment":["search","qa"]},"mode":"dpla_html"}]},{"id":"ebay","name":"eBay Official Browse API","category":"commerce-social","description":"Extracts eBay item pricing, condition, MPN, strict GTIN, and search summaries via the official eBay Browse API.","domains":["ebay.com","www.ebay.com","api.ebay.com"],"auth_mode":"key","exampleUrls":["https://www.ebay.com/itm/133000133001","https://api.ebay.com/buy/browse/v1/item/v1|133000133001|0"],"routes":[{"match":{"hosts":["ebay.com","www.ebay.com"],"anyOf":[{"exactSegments":true,"pathSegments":["itm",{"param":"itemId","charset":"digits","minLen":6,"maxLen":16}]},{"exactSegments":false,"pathSegments":["itm",{"param":"slug","charset":"url_seg","maxLen":200},{"param":"itemId","charset":"digits","minLen":6,"maxLen":16}]}]},"twin":{"fetchUrl":"https://api.ebay.com/buy/browse/v1/item/v1|{itemId}|0","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"ebay_json"}},{"match":{"hosts":["api.ebay.com"],"pathPrefix":"/buy/browse/v1/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"ebay_json"}}]},{"id":"ebike-state-laws","name":"US E-Bike & Bicycle State Laws","category":"public-records","description":"Extracts US state electric bicycle and cycling statutes from PeopleForBikes Prismic/Next.js state tables and League of American Bicyclists state law profiles.","domains":["peopleforbikes.org","www.peopleforbikes.org","bikeleague.org","www.bikeleague.org"],"auth_mode":"html","exampleUrls":["https://www.peopleforbikes.org/electric-bikes/state-laws","https://www.peopleforbikes.org/electric-bikes/policies-and-laws","https://bikeleague.org/bike-laws/state-bike-laws/?bikelaw-by-state=colorado"],"htmlRoutes":[{"id":"ebike-state-laws","match":{"exactSegments":false},"mode":"ebike_state_laws_html"}]},{"id":"ecfr","name":"Electronic Code of Federal Regulations (eCFR)","category":"public-records","description":"Public eCFR Versioner and Search API adapter enforcing strict robots.txt politeness on structure, ancestry, versions, titles, and search endpoints.","domains":["ecfr.gov","www.ecfr.gov"],"auth_mode":"pub","strict_robots":true,"exampleUrls":["https://www.ecfr.gov/api/versioner/v1/titles.json","https://www.ecfr.gov/api/versioner/v1/ancestry/2025-01-01/title-16.json?part=1512","https://www.ecfr.gov/api/search/v1/results?query=bicycle&per_page=2"],"routes":[{"match":{"anyOf":[{"pathEquals":["/api/versioner/v1/titles.json","/api/search/v1/results","/api/admin/v1/agencies.json"]},{"pathPrefix":"/api/versioner/v1/structure/"},{"pathPrefix":"/api/versioner/v1/ancestry/"},{"pathPrefix":"/api/versioner/v1/versions/"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"ecfr_api_json"}},{"match":{"exactSegments":false,"pathSegments":["current",{"param":"title","charset":"alnum_dash","stripPrefix":"title-","minLen":1,"maxLen":12}]},"twin":{"fetchUrl":"https://www.ecfr.gov/api/search/v1/results?query=title+{title}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"ecfr_api_json"}}]},{"id":"ecode360-general-code","name":"eCode360 Municipal Codes","category":"public-records","description":"HTML extractor for General Code eCode360 municipal ordinances, chapters, and statutory sections.","domains":["ecode360.com","www.ecode360.com"],"auth_mode":"html","exampleUrls":["https://ecode360.com/44475260","https://ecode360.com/OR5214"],"htmlRoutes":[{"id":"ecode360-general-code","match":{"exactSegments":false},"mode":"ecode360_html"}]},{"id":"ecwid","name":"Ecwid Storefronts & REST API v3","category":"commerce-social","description":"Opt-in page-key adapter for Ecwid /api/v3/{storeId}/products JSON twins with clean HTML/JSON-LD storefront fallback when disabled.","domains":["app.ecwid.com","www.ecwid.com"],"universalEngine":true,"auth_mode":"page-key","requires_page_key_opt_in":true,"exampleUrls":["https://mdemo.company.site/Black-Tank-p109736045"],"routes":[{"match":{"hosts":["app.ecwid.com"],"pathSegments":["api","v3",{"param":"storeId","charset":"digits","minLen":1,"maxLen":20},"products"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"commerceMode":"ecwid_v3_json"}},{"match":{"hosts":["app.ecwid.com"],"pathSegments":["api","v3",{"param":"storeId","charset":"digits","minLen":1,"maxLen":20},"products",{"param":"productId","charset":"digits","minLen":1,"maxLen":20}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"commerceMode":"ecwid_v3_json"}}],"htmlRoutes":[{"id":"ecwid","match":{"exactSegments":false},"mode":"ecwid_html"}]},{"id":"edge-cloud-changelogs","name":"Edge & Cloud Changelogs (Cloudflare, Vercel, Netlify)","category":"developer","description":"Extracts RSS 2.0 and Atom 1.0 release changelogs from Cloudflare Developers, Vercel, and Netlify with same-origin HTML-to-feed upgrades.","domains":["developers.cloudflare.com","vercel.com","www.vercel.com","netlify.com","www.netlify.com"],"auth_mode":"pub","exampleUrls":["https://developers.cloudflare.com/changelog/rss/d1.xml","https://vercel.com/atom","https://www.netlify.com/changelog/feed.xml"],"routes":[{"match":{"hosts":["developers.cloudflare.com"],"anyOf":[{"pathEquals":["/changelog/rss/index.xml","/changelog/index.xml"]},{"pathPrefix":"/changelog/rss/","pathSuffix":".xml"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"application/xml","maxBytes":2097152},"extract":{"textMode":"edge_cloud_changelog_xml"}},{"match":{"hosts":["developers.cloudflare.com"],"pathEquals":["/changelog","/changelog/"]},"twin":{"fetchUrl":"https://developers.cloudflare.com/changelog/rss/index.xml","kind":"text","accept":"application/xml","maxBytes":2097152},"extract":{"textMode":"edge_cloud_changelog_xml"}},{"match":{"hosts":["vercel.com","www.vercel.com"],"pathEquals":["/atom","/changelog/atom"]},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"application/atom+xml","maxBytes":2097152},"extract":{"textMode":"edge_cloud_changelog_xml"}},{"match":{"hosts":["vercel.com","www.vercel.com"],"pathEquals":["/changelog","/changelog/"]},"twin":{"fetchUrl":"https://vercel.com/atom","kind":"text","accept":"application/atom+xml","maxBytes":2097152},"extract":{"textMode":"edge_cloud_changelog_xml"}},{"match":{"hosts":["netlify.com","www.netlify.com"],"pathEquals":["/changelog/feed.xml","/changelog/rss.xml"]},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"application/xml","maxBytes":2097152},"extract":{"textMode":"edge_cloud_changelog_xml"}},{"match":{"hosts":["netlify.com","www.netlify.com"],"pathEquals":["/changelog","/changelog/"]},"twin":{"fetchUrl":"https://www.netlify.com/changelog/feed.xml","kind":"text","accept":"application/xml","maxBytes":2097152},"extract":{"textMode":"edge_cloud_changelog_xml"}}],"htmlRoutes":[{"id":"edge-cloud-changelogs","match":{"hosts":["developers.cloudflare.com","vercel.com","www.vercel.com","netlify.com","www.netlify.com"],"pathPrefix":"/changelog","exactSegments":false},"mode":"edge_cloud_changelog_html"}]},{"id":"eia","name":"U.S. Energy Information Administration (EIA)","category":"public-records","description":"U.S. Energy Information Administration Open Data v2 JSON API adapter with eia.gov HTML table/prose fallback.","domains":["eia.gov","www.eia.gov","api.eia.gov"],"auth_mode":"key","exampleUrls":["https://api.eia.gov/v2/petroleum/pri/gnd/data/?frequency=weekly&data[0]=value&length=10","https://www.eia.gov/opendata/","https://www.eia.gov/petroleum/gasdiesel/"],"routes":[{"match":{"hosts":["api.eia.gov"],"exactSegments":false,"pathPrefix":"/v2/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304,"auth_mode":"key"},"extract":{"jsonMode":"eia_json"}}],"htmlRoutes":[{"id":"eia","match":{"hosts":["eia.gov","www.eia.gov"],"exactSegments":false},"mode":"eia_html"}]},{"id":"electronics-retail-specs","name":"US Electronics Retailers Spec Extractor","category":"commerce-social","description":"Extracts structured Product JSON-LD and technical specification tables for Newegg, B&H Photo Video, and Micro Center.","domains":["newegg.com","www.newegg.com","bhphotovideo.com","www.bhphotovideo.com","microcenter.com","www.microcenter.com"],"auth_mode":"html","min_interval_ms":2000,"strict_robots":true,"exampleUrls":["https://www.microcenter.com/product/678482/amd-ryzen-7-7800x3d-raphael-am5-42ghz-8-core-boxed-processor-heatsink-not-included","https://www.bhphotovideo.com/c/product/1791390-REG/sony_ilce7m4_b.html"],"htmlRoutes":[{"id":"electronics-retail-specs","match":{"exactSegments":false},"mode":"electronics_retail_specs_html"}]},{"id":"enterprise-ats-full","name":"Enterprise ATS Full (Eightfold, Phenom, Avature, Cornerstone)","category":"jobs","description":"Upgrades Eightfold /careers & /careers/job/ to robots-allowed /api/pcsx/search & /api/pcsx/position_details JSON twins, plus Phenom, Avature, and Cornerstone HTML extractors.","domains":["www.phenom.com","eightfold.ai","nvidia.eightfold.ai","paypal.eightfold.ai","bloomberg.avature.net","www.avature.net","www.csod.com","cornerstone.csod.com"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://nvidia.eightfold.ai/careers/job/893391708161","https://cornerstone.csod.com/ux/ats/careersite/2/home/requisition/11818?c=cornerstone","https://bloomberg.avature.net/careers/JobDetail/Senior-Software-Engineer-Electronic-Trading/46354"],"routes":[{"match":{"hostSubdomain":{"suffix":".eightfold.ai","param":"tenant","reserved":["www","api","login","auth","static"]},"pathPrefix":"/careers/job/","scanSegment":{"afterLiteral":"job","param":"jobId","charset":"slug","minLen":1,"maxLen":64}},"twin":{"fetchUrl":"https://{host}/api/pcsx/position_details?position_id={jobId}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"eightfold_job_json"}},{"match":{"hostSubdomain":{"suffix":".eightfold.ai","param":"tenant","reserved":["www","api","login","auth","static"]},"pathEquals":["/api/pcsx/position_details"],"queryParams":[{"name":"position_id","param":"jobId","charset":"slug","minLen":1,"maxLen":64}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"eightfold_job_json"}},{"match":{"hostSubdomain":{"suffix":".eightfold.ai","param":"tenant","reserved":["www","api","login","auth","static"]},"exactSegments":true,"pathSegments":["careers"],"queryParams":[{"name":"domain","param":"domain","charset":"pkg","minLen":3,"maxLen":120}]},"twin":{"fetchUrl":"https://{host}/api/pcsx/search?domain={domain}&query=&start=0","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"eightfold_board_json"}},{"match":{"hostSubdomain":{"suffix":".eightfold.ai","param":"tenant","reserved":["www","api","login","auth","static"]},"exactSegments":true,"pathSegments":["careers"]},"twin":{"fetchUrl":"https://{host}/api/pcsx/search?domain={tenant}.com&query=&start=0","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"eightfold_board_json"}},{"match":{"hostSubdomain":{"suffix":".eightfold.ai","param":"tenant","reserved":["www","api","login","auth","static"]},"pathEquals":["/api/pcsx/search"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"eightfold_board_json"}}],"htmlRoutes":[{"id":"enterprise-ats-full","mode":"enterprise_ats_full_html","match":{"excludeHosts":["recruiting.ultipro.com","recruiting.paylocity.com","app.dover.com","jobs.dover.com","jobs.smartrecruiters.com","*.oraclecloud.com","jobs.jobvite.com"],"anyOf":[{"hostSubdomain":{"suffix":".eightfold.ai","param":"tenant","reserved":["www","api","login","auth","static"]},"exactSegments":false},{"hosts":["careers.phenom.com","www.phenom.com"],"exactSegments":false},{"hostSubdomain":{"suffix":".avature.net","param":"tenant","reserved":["www","login","auth"]},"exactSegments":false},{"hosts":["www.avature.net"],"exactSegments":false},{"hostSubdomain":{"suffix":".csod.com","param":"tenant","reserved":["www","login","auth"]},"pathPrefix":"/ux/ats/careersite/","exactSegments":false},{"hosts":["www.csod.com"],"pathPrefix":"/ux/ats/careersite/","exactSegments":false}]}}]},{"id":"enterprise-ats","name":"SmartRecruiters, Oracle HCM Cloud & Jobvite","category":"jobs","description":"Keyless Oracle HCM Cloud recruitingCEJobRequisitions REST twin + robots.txt-safe SmartRecruiters and Jobvite HTML posting extractors.","domains":["jobs.smartrecruiters.com","*.oraclecloud.com","jobs.jobvite.com"],"exampleUrls":["https://jobs.smartrecruiters.com/Canva/6000000001554828-enterprise-security-manager-","https://eeho.fa.us2.oraclecloud.com/hcmUI/CandidateExperience/en/sites/CX_1001/requisitions","https://jobs.jobvite.com/optimizely/job/oHG8efwt"],"routes":[{"match":{"anyOf":[{"hosts":["*.fa.*oraclecloud.com"],"exactSegments":false,"pathSegments":["hcmUI","CandidateExperience",{"param":"lang","charset":"pkg"},"sites",{"param":"siteNumber","charset":"slug"}],"scanSegment":{"afterLiteral":"job","param":"reqId","charset":"slug"}},{"hosts":["*.fa.*oraclecloud.com"],"exactSegments":false,"pathContainsSegment":"requisitions","pathSegments":["hcmUI","CandidateExperience",{"param":"lang","charset":"pkg"},"sites",{"param":"siteNumber","charset":"slug"}],"scanSegment":{"afterLiteral":"preview","param":"reqId","charset":"slug"}},{"hosts":["*.fa.*oraclecloud.com"],"exactSegments":false,"pathSegments":["hcmUI","CandidateExperience","sites",{"param":"siteNumber","charset":"slug"}],"scanSegment":{"afterLiteral":"job","param":"reqId","charset":"slug"}},{"hosts":["*.fa.*oraclecloud.com"],"exactSegments":false,"pathContainsSegment":"requisitions","pathSegments":["hcmUI","CandidateExperience","sites",{"param":"siteNumber","charset":"slug"}],"scanSegment":{"afterLiteral":"preview","param":"reqId","charset":"slug"}},{"hosts":["*.fa.*oraclecloud.com"],"exactSegments":false,"pathSegments":["sites",{"param":"siteNumber","charset":"slug"}],"scanSegment":{"afterLiteral":"job","param":"reqId","charset":"slug"}},{"hosts":["*.fa.*oraclecloud.com"],"exactSegments":false,"pathContainsSegment":"requisitions","pathSegments":["sites",{"param":"siteNumber","charset":"slug"}],"scanSegment":{"afterLiteral":"preview","param":"reqId","charset":"slug"}}]},"twin":{"id":"oracle-hcm-job","fetchUrl":"https://{host}/hcmRestApi/resources/latest/recruitingCEJobRequisitionDetails?onlyData=true&expand=all&finder=ById;Id=%22{reqId}%22,siteNumber={siteNumber}","kind":"json","accept":"application/json"},"extract":{"rootPath":"items.0","requireFields":["Title"],"vars":{"jobTitle":{"paths":["Title"],"trim":true},"loc":{"paths":["PrimaryLocation"],"trim":true},"wp":{"paths":["WorkplaceType"],"trim":true},"posted":{"paths":["ExternalPostedStartDate"],"sliceMax":10,"trim":true},"extDesc":{"paths":["ExternalDescriptionStr"],"format":"html_to_md"},"extResp":{"paths":["ExternalResponsibilitiesStr"],"format":"html_to_md"},"extQual":{"paths":["ExternalQualificationsStr"],"format":"html_to_md"}},"titleTemplate":"{jobTitle}","publishedTimeVar":"posted","bullets":[{"label":"Requisition ID","template":"`{reqId}`"},{"label":"Primary Location","template":"{loc}","whenVar":"loc"},{"label":"Workplace","template":"{wp}","whenVar":"wp"},{"label":"Posted","template":"{posted}","whenVar":"posted"}],"bodyVar":"extDesc","sections":[{"heading":"Responsibilities","textVar":"extResp"},{"heading":"Qualifications","textVar":"extQual"}]}},{"match":{"anyOf":[{"hosts":["*.fa.*oraclecloud.com"],"pathSuffix":"/requisitions","scanSegment":{"afterLiteral":"sites","param":"siteNumber","charset":"slug"}},{"hosts":["*.fa.*oraclecloud.com"],"pathSuffix":"/requisitions/","scanSegment":{"afterLiteral":"sites","param":"siteNumber","charset":"slug"}},{"hosts":["*.fa.*oraclecloud.com"],"exactSegments":true,"pathSegments":["hcmUI","CandidateExperience",{"param":"lang","charset":"pkg"},"sites",{"param":"siteNumber","charset":"slug"}]},{"hosts":["*.fa.*oraclecloud.com"],"exactSegments":true,"pathSegments":["hcmUI","CandidateExperience","sites",{"param":"siteNumber","charset":"slug"}]},{"hosts":["*.fa.*oraclecloud.com"],"exactSegments":true,"pathSegments":["sites",{"param":"siteNumber","charset":"slug"}]}]},"twin":{"id":"oracle-hcm-board","fetchUrl":"https://{host}/hcmRestApi/resources/latest/recruitingCEJobRequisitions?onlyData=true&expand=requisitionList.secondaryLocations&finder=findReqs;siteNumber={siteNumber},limit=25","kind":"json","accept":"application/json"},"extract":{"rootPath":"items.0","vars":{"reqCount":{"paths":["requisitionList"],"format":"array_len"},"total":{"paths":["TotalJobsCount"],"fallbackTemplate":"{reqCount}"}},"requireVars":["reqCount"],"titleTemplate":"Oracle HCM ({siteNumber}) — Open Requisitions ({total})","sections":[{"heading":"","arrayPath":"requisitionList","limit":50,"emptyText":"No open requisitions currently listed.","itemVars":{"id":{"paths":["Id"]},"rTitle":{"paths":["Title"],"trim":true,"default":"Requisition"},"rUrl":{"template":"https://{host}/hcmUI/CandidateExperience/en/sites/{siteNumber}/job/{id}"},"loc":{"paths":["PrimaryLocation"],"trim":true,"default":"-"},"wp":{"paths":["WorkplaceType"],"trim":true,"default":"-"},"posted":{"paths":["PostedDate"],"sliceMax":10,"trim":true,"default":"-"}},"collectLinkVars":["rUrl"],"columns":[{"header":"Requisition","template":"[{rTitle}]({rUrl})"},{"header":"Location","template":"{loc}"},{"header":"Workplace","template":"{wp}"},{"header":"Posted","template":"{posted}"}]}]}}],"htmlRoutes":[{"id":"smartrecruiters","mode":"dom","match":{"hosts":["jobs.smartrecruiters.com"],"exactSegments":false,"minSegments":2,"pathSegments":[{"param":"org","charset":"pkg"}]},"jsonLdTypes":["JobPosting"],"vars":{"jobTitle":{"jsonLdPaths":["title"],"cssText":["h1.job-title"]},"company":{"jsonLdPaths":["hiringOrganization.name"],"fallbackTemplate":"{org}"},"body":{"cssHtmlToMd":["div[itemprop=\"description\"]","section#st-jobDescription"],"jsonLdPaths":["description"]}},"requireVars":["jobTitle","body"],"titleTemplate":"{jobTitle} @ {company}","bodyVar":"body"},{"id":"jobvite","mode":"dom","match":{"hosts":["jobs.jobvite.com"],"exactSegments":false,"pathSegments":[{"param":"org","charset":"pkg"},"job",{"param":"jobId","charset":"pkg"}]},"vars":{"jobTitle":{"cssText":["h2.jv-header"]},"meta":{"cssText":["p.jv-job-detail-meta"]},"body":{"cssHtmlToMd":["div.jv-job-detail-description"]}},"requireVars":["jobTitle","body"],"titleTemplate":"{jobTitle} @ {org}","metaItalicTemplate":"{meta}","metaItalicWhenVar":"meta","bodyVar":"body"}]},{"id":"epa-envirofacts-echo","name":"EPA Envirofacts & ECHO","category":"research-health","description":"US EPA Envirofacts REST API (data.epa.gov/efservice), ECHO REST services, and echo.epa.gov HTML facility fallback with strict robots.txt politeness.","domains":["data.epa.gov","enviro.epa.gov","echo.epa.gov","echodata.epa.gov"],"auth_mode":"pub","strict_robots":true,"min_interval_ms":10000,"exampleUrls":["https://data.epa.gov/efservice/tri_facility/state_abbr/DC/rows/0:2/JSON","https://echo.epa.gov/detailed-facility-report?fid=110000350174"],"routes":[{"match":{"hosts":["data.epa.gov"],"pathPrefix":"/efservice/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"epa_envirofacts_json"}},{"match":{"hosts":["enviro.epa.gov"],"pathPrefix":"/enviro/efservice/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"epa_envirofacts_json"}},{"match":{"hosts":["echodata.epa.gov"],"pathPrefix":"/echo/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"epa_envirofacts_json"}}],"htmlRoutes":[{"id":"epa-envirofacts-echo","match":{"hosts":["echo.epa.gov"],"exactSegments":false},"mode":"epa_echo_html"}]},{"id":"epa-fueleconomy","name":"EPA FuelEconomy.gov","category":"public-records","description":"U.S. DOE/EPA FuelEconomy.gov /ws/rest/ JSON API adapter for vehicle MPG, range, CO2, and make/model/year menus.","domains":["fueleconomy.gov","www.fueleconomy.gov"],"auth_mode":"pub","exampleUrls":["https://www.fueleconomy.gov/ws/rest/vehicle/41276","https://www.fueleconomy.gov/ws/rest/vehicle/menu/make?year=2024"],"routes":[{"match":{"pathPrefix":"/ws/rest/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"fueleconomy_json"}}]},{"id":"etsy","name":"Etsy Open API v3","category":"commerce-social","description":"Extracts Etsy listing title, converted price, SKU, quantity, state, and shop search results via the official Etsy Open API v3.","domains":["etsy.com","www.etsy.com","openapi.etsy.com"],"auth_mode":"key","exampleUrls":["https://www.etsy.com/listing/134000134/walnut-desk-tray","https://openapi.etsy.com/v3/application/listings/134000134"],"routes":[{"match":{"hosts":["etsy.com","www.etsy.com"],"exactSegments":false,"pathSegments":["listing",{"param":"listingId","charset":"digits","minLen":5,"maxLen":16}]},"twin":{"fetchUrl":"https://openapi.etsy.com/v3/application/listings/{listingId}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"etsy_json"}},{"match":{"hosts":["openapi.etsy.com"],"pathPrefix":"/v3/application/listings"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"etsy_json"}}]},{"id":"eur-lex","name":"EUR-Lex","category":"public-records","description":"Upgrades eur-lex.europa.eu/legal-content//TXT/?uri=* pages to the static /TXT/HTML/?uri=* twin while respecting robots.txt Crawl-delay and never touching disallowed /TXT/DOC/.","domains":["eur-lex.europa.eu"],"exampleUrls":["https://eur-lex.europa.eu/legal-content/EN/TXT/?uri=CELEX:32016R0679"],"match":{"exactSegments":true,"pathSegments":["legal-content",{"param":"lang","charset":"alnum","minLen":2,"maxLen":3,"transform":"upper"},"TXT"],"queryParams":[{"name":"uri","param":"uri","charset":"safe_subpath","minLen":3,"maxLen":200}]},"twin":{"fetchUrl":"https://eur-lex.europa.eu/legal-content/{lang}/TXT/HTML/?uri={uri}","kind":"text","accept":"text/html","maxBytes":4194304},"extract":{"textMode":"html_document","titleTemplate":"EUR-Lex {uri} ({lang})"}},{"id":"eventbrite","name":"Eventbrite Events","category":"commerce-social","description":"Extracts Eventbrite event details via the official Eventbrite v3 API when configured, with Event/Festival JSON-LD and __NEXT_DATA__ HTML fallback.","domains":["eventbrite.com","www.eventbrite.com","www.eventbriteapi.com"],"auth_mode":"key","exampleUrls":["https://www.eventbrite.com/e/music-mimosa-festival-fall-edition-tickets-2004426596909","https://www.eventbriteapi.com/v3/events/2004426596909/"],"routes":[{"match":{"hosts":["www.eventbriteapi.com"],"pathPrefix":"/v3/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"key"},"extract":{"jsonMode":"eventbrite_json"}},{"match":{"hosts":["eventbrite.com","www.eventbrite.com"],"exactSegments":true,"pathSegments":["e",{"param":"eventId","charset":"digits","minLen":6,"maxLen":20}]},"twin":{"fetchUrl":"https://www.eventbriteapi.com/v3/events/{eventId}/","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"key"},"extract":{"jsonMode":"eventbrite_json"}}],"htmlRoutes":[{"id":"eventbrite","match":{"hosts":["eventbrite.com","www.eventbrite.com"],"exactSegments":false},"mode":"eventbrite_html"}]},{"id":"faa-registry","name":"FAA Aircraft Registry","category":"public-records","description":"FAA Civil Aviation Registry HTML extractor for N-Number lookups (/aircraftinquiry/Search/NNumberResult); note origin Akamai may return 403 to non-browser bot UAs.","domains":["registry.faa.gov"],"auth_mode":"html","strict_robots":true,"exampleUrls":["https://registry.faa.gov/aircraftinquiry/Search/NNumberResult?NNumberTxt=N101"],"htmlRoutes":[{"id":"faa-registry","match":{"hosts":["registry.faa.gov"],"pathPrefix":"/aircraftinquiry/search/","excludeSegmentSuffixes":[".asp"],"exactSegments":false},"mode":"faa_registry_html"}]},{"id":"fcc-id","name":"FCC ID Equipment Authorization","category":"public-records","description":"Extracts FCC ID grant metadata, technical frequency/power tables, and exhibit PDF links from fccid.io public HTML pages while respecting robots.txt disallows.","domains":["fccid.io","www.fccid.io"],"exampleUrls":["https://fccid.io/BCG-E3542A"],"htmlRoutes":[{"id":"fcc-id","mode":"dom","match":{"exactSegments":false,"reservedFirstSegment":["ViewExhibitReport.cfm","subscribe.php","frequency","search","api"],"pathSegments":[{"param":"grantee","charset":"url_seg","minLen":2,"maxLen":64},{"param":"product","charset":"url_seg","optional":true,"minLen":1,"maxLen":120}]},"vars":{"title":{"cssText":["h1","title"],"metaKeys":["og:title"],"trim":true},"summary":{"cssText":["main p","article p"],"minLen":20,"sliceMax":400,"trim":true}},"requireVars":["title","summary"],"titleTemplate":"{title}","descriptionVar":"summary","introVar":"summary","bullets":[{"label":"FCC ID","template":"`{grantee}`"}],"appendCurrentMdDelta":{"minExtraChars":0}}]},{"id":"fdic-bankfind","name":"FDIC BankFind Suite","category":"finance","description":"Extracts insured institution profiles and failed bank lists directly from api.fdic.gov/banks/ (avoiding banks.data.fdic.gov/api 301 redirects) with 1 req/s politeness and SPA shell rejection.","domains":["banks.data.fdic.gov","api.fdic.gov","www.fdic.gov","fdic.gov"],"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://api.fdic.gov/banks/institutions?filters=CERT:3511&limit=1","https://www.fdic.gov/resources/resolutions/bank-failures/","https://api.fdic.gov/banks/failures?limit=1"],"routes":[{"match":{"hosts":["api.fdic.gov"],"pathPrefix":"/banks/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"pub","maxBytes":2097152},"extract":{"jsonMode":"fdic_bankfind_json"}},{"match":{"hosts":["banks.data.fdic.gov"],"exactSegments":false,"pathSegments":["api",{"param":"endpoint","charset":"url_seg","minLen":2,"maxLen":64}]},"twin":{"fetchUrl":"https://api.fdic.gov/banks/{endpoint}","kind":"json","accept":"application/json","auth_mode":"pub","maxBytes":2097152},"extract":{"jsonMode":"fdic_bankfind_json"}},{"match":{"hosts":["www.fdic.gov","fdic.gov"],"pathPrefix":"/resources/resolutions/bank-failures"},"twin":{"fetchUrl":"https://api.fdic.gov/banks/failures?sort_by=FAILDATE&sort_order=DESC&limit=25","kind":"json","accept":"application/json","auth_mode":"pub","maxBytes":2097152},"extract":{"jsonMode":"fdic_bankfind_json"}}],"htmlRoutes":[{"id":"fdic-bankfind","match":{"hosts":["banks.data.fdic.gov","www.fdic.gov","fdic.gov"],"exactSegments":false},"mode":"fdic_bankfind_html"}]},{"id":"fec","name":"FEC Campaign Finance","category":"public-records","description":"Upgrades fec.gov candidate and committee pages to official OpenFEC API v1 JSON summaries via api.data.gov key helper with HTML fallback.","domains":["www.fec.gov","fec.gov","api.open.fec.gov"],"auth_mode":"key","exampleUrls":["https://www.fec.gov/data/candidate/S8FL00216/","https://api.open.fec.gov/v1/candidate/S8FL00216/"],"routes":[{"match":{"hosts":["www.fec.gov","fec.gov"],"exactSegments":false,"pathSegments":["data","candidate",{"param":"candId","charset":"alnum","minLen":6,"maxLen":16}]},"twin":{"fetchUrl":"https://api.open.fec.gov/v1/candidate/{candId}/","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"fec_json"}},{"match":{"hosts":["www.fec.gov","fec.gov"],"exactSegments":false,"pathSegments":["data","committee",{"param":"commId","charset":"alnum","minLen":6,"maxLen":16}]},"twin":{"fetchUrl":"https://api.open.fec.gov/v1/committee/{commId}/","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"fec_json"}},{"match":{"hosts":["api.open.fec.gov"],"pathPrefix":"/v1/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"fec_json"}}],"htmlRoutes":[{"id":"fec","match":{"hosts":["www.fec.gov","fec.gov"],"exactSegments":false},"mode":"fec_html"}]},{"id":"federal-register","name":"Federal Register","category":"public-records","description":"Upgrades federalregister.gov/documents///
//* pages to the official /api/v1/documents/.json twin (strictly excluding disallowed /documents/current).","domains":["www.federalregister.gov","federalregister.gov"],"exampleUrls":["https://www.federalregister.gov/documents/2024/05/07/2024-09171/non-compete-clause-rule"],"match":{"exactSegments":false,"pathSegments":["documents",{"param":"yyyy","charset":"digits","minLen":4,"maxLen":4},{"param":"mm","charset":"digits","minLen":2,"maxLen":2},{"param":"dd","charset":"digits","minLen":2,"maxLen":2},{"param":"docNumber","charset":"alnum_dash","minLen":3,"maxLen":64}]},"twin":{"fetchUrl":"https://www.federalregister.gov/api/v1/documents/{docNumber}.json","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"requireFields":["title","document_number"],"vars":{"title":{"paths":["title"],"trim":true},"docNumber":{"paths":["document_number"]},"docType":{"paths":["type"]},"citation":{"paths":["citation"]},"pubDate":{"paths":["publication_date"]},"urlDate":{"template":"{yyyy}-{mm}-{dd}"},"pubDateMatchesUrl":{"paths":["publication_date"],"equalsVar":"urlDate"},"effectiveOn":{"paths":["effective_on"]},"dates":{"paths":["dates"],"trim":true},"action":{"paths":["action"],"trim":true},"agencies":{"paths":["agencies"],"subField":"name","join":", ","limit":12},"cfrRefs":{"paths":["cfr_references"],"subFieldsJoin":{"fields":["title","part"],"sep":" CFR Part ","fallbackField":"title"},"join":"; ","limit":20},"dockets":{"paths":["docket_ids"],"join":", ","limit":12},"abstract":{"paths":["abstract"],"trim":true},"abstractShort":{"paths":["abstract"],"trim":true,"sliceMax":260},"pdfUrl":{"paths":["pdf_url"],"requireHttps":true},"bodyHtmlUrl":{"paths":["body_html_url"],"requireHttps":true},"xmlUrl":{"paths":["full_text_xml_url"],"requireHttps":true},"htmlUrl":{"paths":["html_url"],"requireHttps":true}},"titleTemplate":"{title}","descriptionVar":"abstractShort","authorVar":"agencies","publishedTimeVar":"pubDate","bullets":[{"label":"Document Number","template":"`{docNumber}`"},{"label":"Type","template":"{docType}","whenVar":"docType"},{"label":"Citation","template":"{citation}","whenVar":"citation"},{"label":"Agencies","template":"{agencies}","whenVar":"agencies"},{"label":"Published","template":"{pubDate}","whenVar":"pubDate"},{"label":"Warning","template":"Publication date {pubDate} does not match the URL date {urlDate}; the URL may point to a different document than its date suggests.","whenVar":"pubDate","unlessVar":"pubDateMatchesUrl"},{"label":"Effective On","template":"{effectiveOn}","whenVar":"effectiveOn"},{"label":"Dates","template":"{dates}","whenVar":"dates"},{"label":"Action","template":"{action}","whenVar":"action"},{"label":"CFR References","template":"{cfrRefs}","whenVar":"cfrRefs"},{"label":"Docket IDs","template":"{dockets}","whenVar":"dockets"},{"label":"PDF","template":"{pdfUrl}","whenVar":"pdfUrl"},{"label":"Body HTML","template":"{bodyHtmlUrl}","whenVar":"bodyHtmlUrl"},{"label":"Full Text XML","template":"{xmlUrl}","whenVar":"xmlUrl"}],"sections":[{"heading":"Abstract","textVar":"abstract"},{"heading":"CFR References","arrayPath":"cfr_references","limit":25,"columns":[{"header":"Title","paths":["title"]},{"header":"Part","paths":["part"]},{"header":"Chapter","paths":["chapter"]}]}],"linksVars":["pdfUrl","htmlUrl","bodyHtmlUrl","xmlUrl"]}},{"id":"fema-openfema","name":"FEMA OpenFEMA API v2","category":"public-records","description":"FEMA OpenFEMA v2 JSON dataset API (DisasterDeclarationsSummaries and public datasets) honoring strict robots.txt 15s crawl-delay.","domains":["www.fema.gov","fema.gov"],"auth_mode":"pub","strict_robots":true,"min_interval_ms":15000,"exampleUrls":["https://www.fema.gov/api/open/v2/DisasterDeclarationsSummaries?%24top=2"],"routes":[{"match":{"hosts":["www.fema.gov","fema.gov"],"pathPrefix":"/api/open/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"fema_openfema_json"}}]},{"id":"finra-brokercheck","name":"FINRA BrokerCheck","category":"finance","description":"Extracts FINRA BrokerCheck individual broker and firm registration, employment, exam, and disclosure records via same-eTLD+1 api.brokercheck.finra.org.","domains":["brokercheck.finra.org","api.brokercheck.finra.org"],"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://brokercheck.finra.org/individual/summary/810315","https://brokercheck.finra.org/firm/summary/79","https://api.brokercheck.finra.org/search/firm/79"],"routes":[{"match":{"hosts":["brokercheck.finra.org"],"pathSegments":["individual","summary",{"param":"crd","charset":"digits","minLen":1,"maxLen":12}]},"twin":{"fetchUrl":"https://api.brokercheck.finra.org/search/individual/{crd}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"finra_brokercheck_json"}},{"match":{"hosts":["brokercheck.finra.org"],"pathSegments":["firm","summary",{"param":"crd","charset":"digits","minLen":1,"maxLen":12}]},"twin":{"fetchUrl":"https://api.brokercheck.finra.org/search/firm/{crd}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"finra_brokercheck_json"}},{"match":{"hosts":["api.brokercheck.finra.org"],"pathPrefix":"/search/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"finra_brokercheck_json"}}],"htmlRoutes":[{"id":"finra-brokercheck","match":{"hosts":["brokercheck.finra.org"]},"mode":"finra_brokercheck_html"}]},{"id":"fmcsa-safer","name":"FMCSA SAFER Carrier Registry","category":"public-records","description":"FMCSA QCMobile REST API (webKey) adapter for USDOT/MC carrier lookups with safer.fmcsa.dot.gov Company Snapshot HTML fallback.","domains":["safer.fmcsa.dot.gov","mobile.fmcsa.dot.gov"],"auth_mode":"key","exampleUrls":["https://mobile.fmcsa.dot.gov/qc/services/carriers/44110","https://safer.fmcsa.dot.gov/query.asp?searchtype=ANY&query_type=queryCarrierSnapshot&query_param=USDOT&query_string=44110"],"routes":[{"match":{"hosts":["mobile.fmcsa.dot.gov"],"pathPrefix":"/qc/services/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"fmcsa_safer_json"}},{"match":{"hosts":["safer.fmcsa.dot.gov"],"pathEquals":["/query.asp"],"queryParams":[{"name":"query_param","param":"queryParam","allowValues":["USDOT"]},{"name":"query_string","param":"dotNumber","charset":"digits","minLen":1,"maxLen":12}]},"twin":{"fetchUrl":"https://mobile.fmcsa.dot.gov/qc/services/carriers/{dotNumber}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"fmcsa_safer_json"}}],"htmlRoutes":[{"id":"fmcsa-safer","match":{"hosts":["safer.fmcsa.dot.gov"],"exactSegments":false},"mode":"fmcsa_safer_html"}]},{"id":"foursquare-places","name":"Foursquare Places API v3","category":"commerce-social","description":"Extracts place search results, venue details, and tips from the official Foursquare Places API v3 (api.foursquare.com).","domains":["api.foursquare.com"],"auth_mode":"key","exampleUrls":["https://api.foursquare.com/v3/places/search?query=coffee&near=Seattle","https://api.foursquare.com/v3/places/4b86a9f7f964a520d69331e3"],"routes":[{"match":{"hosts":["api.foursquare.com"],"anyOf":[{"pathEquals":["/v3/places/search"]},{"pathPrefix":"/v3/places/"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"key"},"extract":{"jsonMode":"foursquare_places_json"}}]},{"id":"fpds-sam-contract-awards","name":"FPDS & SAM.gov Contract Awards","category":"public-records","description":"Extracts keyless FPDS Atom XML contract award feeds (FEEDNAME=PUBLIC) and key-authenticated api.sam.gov/contract-awards JSON without colliding with sam-gov.","domains":["fpds.gov","www.fpds.gov"],"universalEngine":true,"auth_mode":"key","exampleUrls":["https://www.fpds.gov/ezsearch/FEEDS/ATOM?FEEDNAME=PUBLIC&q=LAST_MOD_DATE:[2026/06/25,2026/06/26]","https://api.sam.gov/contract-awards/v1/search?limit=1"],"routes":[{"match":{"hosts":["fpds.gov","www.fpds.gov"],"pathEquals":["/ezsearch/FEEDS/ATOM"]},"twin":{"fetchUrl":"{requestUrl}","defaultQueryParams":{"FEEDNAME":"PUBLIC"},"kind":"text","accept":"application/atom+xml","auth_mode":"pub","maxBytes":4194304},"extract":{"textMode":"fpds_atom_xml"}},{"match":{"hosts":["fpds.gov","www.fpds.gov"],"pathEquals":["/ezsearch/search.do"],"queryParams":[{"name":"q","param":"q","charset":"safe_subpath","minLen":1,"maxLen":240}]},"twin":{"fetchUrl":"https://www.fpds.gov/ezsearch/FEEDS/ATOM?FEEDNAME=PUBLIC&q={q}","kind":"text","accept":"application/atom+xml","auth_mode":"pub","maxBytes":4194304},"extract":{"textMode":"fpds_atom_xml"}},{"match":{"hosts":["fpds.gov","www.fpds.gov"],"pathEquals":["/ezsearch/search.do"],"queryParams":[{"name":"s","param":"s","charset":"url_seg","minLen":1,"maxLen":120}]},"twin":{"fetchUrl":"https://www.fpds.gov/ezsearch/FEEDS/ATOM?FEEDNAME=PUBLIC&s={s}","kind":"text","accept":"application/atom+xml","auth_mode":"pub","maxBytes":4194304},"extract":{"textMode":"fpds_atom_xml"}},{"match":{"hosts":["api.sam.gov"],"pathPrefix":"/contract-awards"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"fpds_sam_awards_json"}}],"htmlRoutes":[{"id":"fpds-sam-contract-awards","match":{"hosts":["fpds.gov","www.fpds.gov"],"exactSegments":false},"mode":"fpds_sam_awards_html"}]},{"id":"fred","name":"FRED Economic Data","category":"finance","description":"Federal Reserve Economic Data (FRED) API v1 JSON observations/series adapter with stlouisfed.org HTML series fallback.","domains":["fred.stlouisfed.org","api.stlouisfed.org"],"auth_mode":"key","min_interval_ms":1000,"exampleUrls":["https://fred.stlouisfed.org/series/GDP","https://api.stlouisfed.org/fred/series/observations?series_id=GDP&file_type=json","https://api.stlouisfed.org/fred/series?series_id=GDP&file_type=json"],"routes":[{"match":{"hosts":["api.stlouisfed.org"],"exactSegments":false,"pathPrefix":"/fred/"},"twin":{"fetchUrl":"{requestUrl}","setQueryParams":{"file_type":"json"},"kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"key"},"extract":{"jsonMode":"fred_json"}},{"match":{"hosts":["fred.stlouisfed.org"],"exactSegments":false,"pathSegments":["series",{"param":"seriesId","charset":"alnum_dash","minLen":1,"maxLen":64}]},"twin":{"fetchUrl":"https://api.stlouisfed.org/fred/series/observations?series_id={seriesId}&file_type=json&limit=25&sort_order=desc","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"key"},"extract":{"jsonMode":"fred_json"}}],"htmlRoutes":[{"id":"fred","match":{"hosts":["fred.stlouisfed.org"],"exactSegments":false,"pathSegments":["series",{"param":"seriesId","charset":"alnum_dash","minLen":1,"maxLen":64}]},"mode":"fred_html"}]},{"id":"freshdesk-portal","name":"Freshdesk Support Portal","category":"developer","description":"Extracts Freshdesk support portal articles, folders, and categories from public knowledge base HTML.","domains":["support.freshdesk.com"],"universalEngine":true,"auth_mode":"html","exampleUrls":["https://support.freshdesk.com/support/solutions/articles/240170-setting-up-your-support-email-in-gmail-video-guide","https://support.freshdesk.com/support/solutions/folders/275395"],"htmlRoutes":[{"id":"freshdesk-portal","match":{"exactSegments":false},"mode":"freshdesk_portal_html"}]},{"id":"gannett-usatoday-network","name":"Gannett / USA TODAY Network","category":"commerce-social","description":"Extracts NewsArticle JSON-LD and Gannett story content across USA TODAY and Gannett regional newspapers while rejecting Access Restricted gates.","domains":["www.usatoday.com","usatoday.com","www.azcentral.com","www.freep.com","www.indystar.com","www.cincinnati.com","www.dispatch.com","www.detroitnews.com","www.jsonline.com","www.tennessean.com","www.courier-journal.com"],"auth_mode":"html","exampleUrls":["https://www.usatoday.com/"],"htmlRoutes":[{"id":"gannett-usatoday-network","match":{"exactSegments":false},"mode":"gannett_usatoday_html"}]},{"id":"gem-ats","name":"Gem Job Boards","category":"jobs","description":"Upgrades jobs.gem.com/ boards and job posts to the keyless api.gem.com/job_board/v0//job_posts/ JSON feed.","domains":["jobs.gem.com"],"exampleUrls":["https://jobs.gem.com/gem"],"routes":[{"match":{"exactSegments":false,"pathSegments":[{"param":"org","charset":"slug","maxLen":80},{"param":"postId","charset":"pkg"}]},"twin":{"id":"gem-ats","fetchUrl":"https://api.gem.com/job_board/v0/{org}/job_posts/","kind":"json","accept":"application/json"},"extract":{"wrapRootArrayAs":"posts","findInArray":{"arrayPath":"posts","matchFields":["id","public_id"],"matchTemplate":"{postId}","endsWithField":"absolute_url","endsWithTemplate":"/{postId}"},"vars":{"jobTitle":{"paths":["title"],"trim":true,"default":"Job Posting"},"loc":{"paths":["location.name","location_type"],"trim":true},"depts":{"paths":["departments"],"subField":"name","join":", "},"bodyHtml":{"paths":["content"],"format":"html_to_md"},"bodyPlain":{"paths":["content_plain"],"format":"plain_text","trim":true},"body":{"template":"{bodyHtml}","whenVars":["bodyHtml"],"fallbackVar":"bodyPlain"}},"titleTemplate":"{jobTitle} @ {org}","bullets":[{"label":"Company","template":"{org}"},{"label":"Location","template":"{loc}","whenVar":"loc"},{"label":"Department","template":"{depts}","whenVar":"depts"}],"bodyVar":"body","fallbackExtract":{"wrapRootArrayAs":"posts","vars":{"count":{"paths":["posts"],"format":"array_len"}},"requireVars":["count"],"titleTemplate":"{org} — Gem Job Board ({count} open roles)","sections":[{"heading":"","arrayPath":"posts","limit":100,"emptyText":"No open positions currently listed.","itemVars":{"pTitle":{"paths":["title"],"trim":true,"default":"Role"},"id":{"paths":["id"]},"rawUrl":{"paths":["absolute_url"],"requireHttps":true},"pUrl":{"template":"{rawUrl}","whenVars":["rawUrl"],"fallbackTemplate":"https://jobs.gem.com/{org}/{id}"},"loc":{"paths":["location.name"],"trim":true,"default":"-"},"wp":{"paths":["location_type"],"trim":true,"default":"-"},"created":{"paths":["first_published_at","created_at"],"sliceMax":10,"trim":true,"default":"-"}},"collectLinkVars":["pUrl"],"columns":[{"header":"Role","template":"[{pTitle}]({pUrl})"},{"header":"Location","template":"{loc}"},{"header":"Workplace","template":"{wp}"},{"header":"Published","template":"{created}"}]}]}}},{"match":{"pathSegments":[{"param":"org","charset":"slug","maxLen":80}]},"twin":{"id":"gem-ats","fetchUrl":"https://api.gem.com/job_board/v0/{org}/job_posts/","kind":"json","accept":"application/json"},"extract":{"wrapRootArrayAs":"posts","vars":{"count":{"paths":["posts"],"format":"array_len"}},"requireVars":["count"],"titleTemplate":"{org} — Gem Job Board ({count} open roles)","sections":[{"heading":"","arrayPath":"posts","limit":100,"emptyText":"No open positions currently listed.","itemVars":{"pTitle":{"paths":["title"],"trim":true,"default":"Role"},"id":{"paths":["id"]},"rawUrl":{"paths":["absolute_url"],"requireHttps":true},"pUrl":{"template":"{rawUrl}","whenVars":["rawUrl"],"fallbackTemplate":"https://jobs.gem.com/{org}/{id}"},"loc":{"paths":["location.name"],"trim":true,"default":"-"},"wp":{"paths":["location_type"],"trim":true,"default":"-"},"created":{"paths":["first_published_at","created_at"],"sliceMax":10,"trim":true,"default":"-"}},"collectLinkVars":["pUrl"],"columns":[{"header":"Role","template":"[{pTitle}]({pUrl})"},{"header":"Location","template":"{loc}"},{"header":"Workplace","template":"{wp}"},{"header":"Published","template":"{created}"}]}]}}]},{"id":"giant-liv-bikes","name":"Giant & Liv Bicycles Specs & Manuals","category":"commerce-social","description":"Extracts bike specifications, geometry GFM tables, and owner manual PDF links from Giant and Liv regional HTML pages while respecting Crawl-delay and never hitting /shop*, /comparison*, /account*, or /apiproxy/*.","domains":["www.giant-bicycles.com","*.giant-bicycles.com","giant-bicycles.com","www.liv-cycling.com","*.liv-cycling.com","liv-cycling.com"],"exampleUrls":["https://www.giant-bicycles.com/us/defy-advanced-pro-0","https://www.liv-cycling.com/us/avail-advanced-pro-0","https://www.giant-bicycles.com/us/manuals"],"htmlRoutes":[{"id":"giant-liv-bikes","mode":"giant_liv_html","match":{"exactSegments":false,"excludeSegmentSuffixes":[".xml",".json"],"anyOf":[{"exactSegments":false,"optionalLeadingLocale":true,"reservedFirstSegment":["shop","comparison","account","apiproxy","int","global"]},{"exactSegments":false,"pathSegments":[{"param":"locale3","allowValues":["int","global"]},{"param":"seg1","charset":"url_seg","minLen":1,"maxLen":160,"reserved":["shop","comparison","account","apiproxy"]}]}]}}]},{"id":"github-gist","name":"GitHub Gists","category":"developer","description":"Extracts multi-file GitHub Gist code blocks with fenced language tags and rendered Markdown.","domains":["gist.github.com"],"exampleUrls":["https://gist.github.com/octocat/6cad326836d38bd3a7ae"],"htmlRoutes":[{"match":{"minSegments":2},"mode":"gist_files"}]},{"id":"gitlab-forgejo","name":"GitLab, Codeberg & Forgejo Twins","category":"developer","description":"Upgrades GitLab repo roots and file blobs via robots.txt-allowed ?format=json&viewer=simple endpoints, and extracts clean README content from Codeberg/Gitea SSR repo pages.","domains":["gitlab.com","gitlab.*","codeberg.org","gitea.com"],"exampleUrls":["https://gitlab.com/gitlab-org/cli","https://gitlab.com/inkscape/inkscape/-/blob/master/CMakeLists.txt","https://codeberg.org/forgejo/forgejo"],"routes":[{"match":{"hosts":["gitlab.com","gitlab.*"],"splitOnSegment":{"delimiter":"-","leftParam":"nsProj","leftMinSegs":2,"afterLiteral":"blob","rightParam":"rawTail","tailParam":"filePath"}},"twin":{"id":"gitlab-blob-json","fetchUrl":"https://{host}/{nsProj}/-/blob/{rawTail}?format=json&viewer=simple","rawPathParams":["nsProj","rawTail"],"kind":"json","accept":"application/json"},"extract":{"vars":{"plain":{"paths":["html"],"format":"gitlab_blob_html"}},"requireVars":["plain"],"titleTemplate":"{nsProj}/{filePath}","codeByPath":{"sourceVar":"plain","pathParam":"filePath","rawIfMarkdown":true}}},{"match":{"hosts":["gitlab.com","gitlab.*"],"minSegments":2,"maxSegments":5,"allSegmentsCharset":"pkg","reservedFirstSegment":["explore","groups","users","dashboard","help","topics","orgs","admin","search","abuse_reports","oauth","snippets","-"],"excludeSegmentSuffixes":[".git",".atom"]},"twin":{"id":"gitlab-readme-json","fetchUrl":"https://{host}/{joinedPath}/-/blob/HEAD/README.md?format=json&viewer=simple","rawPathParams":["joinedPath"],"kind":"json","accept":"application/json"},"extract":{"vars":{"readme":{"paths":["html"],"format":"gitlab_blob_html","trim":true}},"requireVars":["readme"],"titleTemplate":"{joinedPath}","bodyVar":"readme"}}],"htmlRoutes":[{"match":{"hosts":["codeberg.org","gitea.com"],"exactSegments":true,"pathSegments":[{"param":"owner","charset":"pkg"},{"param":"repo","charset":"pkg"}]},"mode":"dom","vars":{"desc":{"metaKeys":["og:description","description"]},"readme":{"cssHtmlToMd":["div.markup"],"minLen":40}},"requireVars":["readme"],"titleTemplate":"{owner}/{repo}","descriptionVar":"desc","blockquoteTemplate":"> **{owner}/{repo}** — {desc}","blockquoteWhenVar":"desc","bodyVar":"readme","preserveBodyLinksFromVar":"readme"}]},{"id":"google-my-maps-kml","name":"Google My Maps KML","category":"commerce-social","description":"Upgrades public Google My Maps /maps/d/ viewer, embed, and KML links to bounded KML placemark extraction with validated coordinates.","domains":["google.com","www.google.com","maps.google.com"],"auth_mode":"pub","exampleUrls":["https://www.google.com/maps/d/viewer?mid=1Mdlz2iXu_iZCPhUhzKvT2B2j-6E"],"routes":[{"match":{"anyOf":[{"hosts":["google.com","www.google.com","maps.google.com"],"pathSegments":["maps","d",{"param":"view","allowValues":["viewer","embed","edit","kml"]}],"queryParams":[{"name":"mid","param":"mid","charset":"alnum_dash","minLen":12,"maxLen":64}]},{"hosts":["google.com","www.google.com","maps.google.com"],"pathSegments":["maps","d","u",{"param":"userIdx","charset":"digits","minLen":1,"maxLen":4},{"param":"view","allowValues":["viewer","embed","edit","kml"]}],"queryParams":[{"name":"mid","param":"mid","charset":"alnum_dash","minLen":12,"maxLen":64}]}]},"twin":{"fetchUrl":"https://www.google.com/maps/d/kml?mid={mid}&forcekml=1","kind":"text","accept":"application/xml"},"extract":{"textMode":"kml_placemarks"}}]},{"id":"google-places","name":"Google Places API (New)","category":"commerce-social","description":"Extracts place details and text/nearby search results from the official Google Places API (New) with required X-Goog-Api-Key and X-Goog-FieldMask headers.","domains":["developers.google.com"],"universalEngine":true,"auth_mode":"key","exampleUrls":["https://places.googleapis.com/v1/places/ChIJj61dQgK6j4AR4GeTYWZsKWw","https://places.googleapis.com/v1/places:searchText?textQuery=coffee"],"routes":[{"match":{"hosts":["places.googleapis.com"],"anyOf":[{"pathEquals":["/v1/places:searchText","/v1/places:searchNearby"]}],"queryParams":[{"name":"textQuery","param":"textQuery","charset":"url_seg","maxLen":120,"optional":true,"default":"coffee"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","method":"POST","contentType":"application/json","requestBody":"{\"textQuery\":\"{textQuery}\"}","headers":{"X-Goog-FieldMask":"places.id,places.displayName,places.formattedAddress,places.rating,places.userRatingCount,places.websiteUri,places.nationalPhoneNumber,places.googleMapsUri,places.primaryType,places.businessStatus,places.priceLevel"},"maxBytes":2097152,"auth_mode":"key"},"extract":{"jsonMode":"google_places_json"}},{"match":{"hosts":["places.googleapis.com"],"pathPrefix":"/v1/places/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","headers":{"X-Goog-FieldMask":"id,displayName,formattedAddress,rating,userRatingCount,websiteUri,nationalPhoneNumber,googleMapsUri,primaryType,businessStatus,priceLevel,regularOpeningHours"},"maxBytes":2097152,"auth_mode":"key"},"extract":{"jsonMode":"google_places_json"}}]},{"id":"google-play","name":"Google Play Store","category":"developer","description":"Extracts structured Google Play app metadata (package ID, developer, rating, downloads/reviews, category, price, and full description).","domains":["play.google.com"],"exampleUrls":["https://play.google.com/store/apps/details?id=com.cloudflare.onedotonedotonedotone"],"htmlRoutes":[{"match":{"pathPrefix":"/store/apps/details","queryParams":[{"name":"id","param":"pkgId","charset":"pkg","optional":true}]},"mode":"dom","jsonLdTypes":["SoftwareApplication","MobileApplication"],"vars":{"title":{"jsonLdPaths":["name"],"metaKeys":["og:title"],"stripRegexSuffix":"\\s*-\\s*Apps on Google Play$"},"developer":{"jsonLdPaths":["author.name"]},"ratingVal":{"jsonLdPaths":["aggregateRating.ratingValue"]},"ratingCount":{"jsonLdPaths":["aggregateRating.ratingCount","aggregateRating.reviewCount"]},"ratingOnly":{"template":"{ratingVal} / 5","whenVars":["ratingVal"]},"rating":{"template":"{ratingVal} / 5 ({ratingCount} reviews)","whenVars":["ratingVal","ratingCount"],"fallbackVar":"ratingOnly"},"currency":{"jsonLdPaths":["offers.0.priceCurrency","offers.priceCurrency"],"default":"USD"},"price":{"jsonLdPaths":["offers.0.price","offers.price"],"format":"free_or_currency","currencyVar":"currency"},"category":{"jsonLdPaths":["applicationCategory"]},"contentRating":{"jsonLdPaths":["contentRating"]},"desc":{"jsonLdPaths":["description"],"metaKeys":["description"]},"descShort":{"template":"{desc}","whenVars":["desc"],"sliceMax":260}},"requireVars":["title"],"requireBulletsOrVars":["desc"],"titleTemplate":"{title}","descriptionVar":"descShort","authorVar":"developer","bullets":[{"label":"Package ID","template":"`{pkgId}`","whenVar":"pkgId"},{"label":"Developer","template":"{developer}","whenVar":"developer"},{"label":"Category","template":"{category}","whenVar":"category"},{"label":"Rating","template":"{rating}","whenVar":"rating"},{"label":"Price","template":"{price}","whenVar":"price"},{"label":"Content Rating","template":"{contentRating}","whenVar":"contentRating"}],"sections":[{"heading":"About This App","textVar":"desc"}]}]},{"id":"google-shopping-feed","name":"Google Shopping Merchant Center XML/Atom Feed","category":"commerce-social","description":"Universal XML/Atom parser for Google Merchant Center RSS 2.0 and Atom 1.0 product feeds with strict GTIN validation and compact records.","domains":["btrsports.co.uk"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://raw.githubusercontent.com/web3at50/btr-feed/main/affiliate-feed.xml"],"routes":[{"match":{"excludeHosts":["feeds.npr.org","npr.org","www.npr.org","pbs.org","www.pbs.org","prnewswire.com","www.prnewswire.com","businesswire.com","www.businesswire.com","globenewswire.com","www.globenewswire.com","medium.com","www.medium.com","*.medium.com","ghost.org","www.ghost.org","*.ghost.io","buttondown.com","www.buttondown.com","buttondown.email","rss.beehiiv.com","milkroad.beehiiv.com","*.beehiiv.com","wordpress.org","www.wordpress.org","*.wordpress.com","weworkremotely.com","www.weworkremotely.com","bicycleretailer.com","www.bicycleretailer.com","earthquake.usgs.gov","api.nasa.gov","recruiting.paylocity.com","app.jazz.co","*.applytojob.com","www.fpds.gov","fpds.gov","*.substack.com","substack.com","careers.*.com","jobs.*.com"],"anyOf":[{"pathEquals":["/google-merchant.xml","/google-shopping.xml","/merchant-feed.xml","/product-feed.xml","/shopping-feed.xml"]},{"pathPrefix":"/feeds/","pathSuffix":".xml"},{"pathPrefix":"/feeds/","pathSuffix":".atom"},{"pathPrefix":"/feeds/","pathSuffix":".rss"},{"pathContainsSegment":"google-merchant","pathSuffix":".xml"},{"pathContainsSegment":"google-shopping","pathSuffix":".xml"},{"hosts":["raw.githubusercontent.com"],"pathEquals":["/web3at50/btr-feed/main/affiliate-feed.xml"]}]},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"application/xml","maxBytes":4194304},"extract":{"textMode":"google_shopping_feed_xml"}}]},{"id":"grants-gov","name":"Grants.gov Federal Grant Opportunities","category":"public-records","description":"Upgrades grants.gov opportunity pages to official keyless POST api.grants.gov/v1/api/fetchOpportunity JSON with HTML fallback.","domains":["grants.gov","www.grants.gov","api.grants.gov"],"auth_mode":"pub","exampleUrls":["https://www.grants.gov/search-results-detail/357601","https://api.grants.gov/v1/api/fetchOpportunity"],"routes":[{"match":{"hosts":["grants.gov","www.grants.gov"],"exactSegments":false,"pathSegments":["search-results-detail",{"param":"oppId","charset":"digits","minLen":1,"maxLen":20}]},"twin":{"fetchUrl":"https://api.grants.gov/v1/api/fetchOpportunity","kind":"json","accept":"application/json","method":"POST","contentType":"application/json","requestBody":"{\"opportunityId\":{oppId}}","auth_mode":"pub","maxBytes":2097152},"extract":{"jsonMode":"grants_gov_json"}},{"match":{"hosts":["api.grants.gov"],"pathPrefix":"/v1/api/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"pub","maxBytes":2097152},"extract":{"jsonMode":"grants_gov_json"}}],"htmlRoutes":[{"id":"grants-gov","match":{"hosts":["grants.gov","www.grants.gov"],"exactSegments":false},"mode":"grants_gov_html"}]},{"id":"greenhouse-lever-boards","name":"Greenhouse & Lever Whole-Board + EU APIs","category":"jobs","description":"Upgrades Greenhouse (US & EU) and Lever (US & EU) board root URLs to their official JSON posting feeds with truncation metadata.","domains":["boards.greenhouse.io","job-boards.greenhouse.io","eu-boards.greenhouse.io","job-boards.eu.greenhouse.io","jobs.lever.co","jobs.eu.lever.co"],"exampleUrls":["https://job-boards.greenhouse.io/anthropic","https://job-boards.greenhouse.io/celonis","https://jobs.lever.co/spotify"],"routes":[{"match":{"hosts":["boards.greenhouse.io","job-boards.greenhouse.io"],"pathSegments":[{"param":"org","charset":"pkg","maxLen":80,"reserved":["embed","v1","api","static","assets","favicon.ico"]}]},"twin":{"id":"greenhouse-board","fetchUrl":"https://boards-api.greenhouse.io/v1/boards/{org}/jobs","kind":"json","accept":"application/json"},"extract":{"vars":{"jobCount":{"paths":["jobs"],"format":"array_len"},"total":{"paths":["meta.total"],"fallbackTemplate":"{jobCount}"}},"requireVars":["jobCount"],"titleTemplate":"{org} — Greenhouse Job Board ({total} open roles)","sections":[{"heading":"","arrayPath":"jobs","limit":120,"linkScanLimit":2000,"emptyText":"No open positions currently listed.","paginationMeta":{"totalPath":"meta.total","cursorMode":"offset"},"itemVars":{"jTitle":{"paths":["title"],"trim":true,"default":"Role"},"id":{"paths":["id"]},"rawUrl":{"paths":["absolute_url"],"requireHttps":true},"jUrl":{"template":"{rawUrl}","whenVars":["rawUrl"],"fallbackTemplate":"https://{host}/{org}/jobs/{id}"},"dept":{"paths":["departments"],"subField":"name","join":", ","default":"-"},"loc":{"paths":["location.name"],"trim":true,"default":"-"},"updated":{"paths":["updated_at"],"sliceMax":10,"trim":true,"default":"-"}},"collectLinkVars":["jUrl"],"columns":[{"header":"Role","template":"[{jTitle}]({jUrl})"},{"header":"Department","template":"{dept}"},{"header":"Location","template":"{loc}"},{"header":"Updated","template":"{updated}"}]}]}},{"match":{"hosts":["eu-boards.greenhouse.io","job-boards.eu.greenhouse.io"],"pathSegments":[{"param":"org","charset":"pkg","maxLen":80,"reserved":["embed","v1","api","static","assets","favicon.ico"]}]},"twin":{"id":"greenhouse-eu-board","fetchUrl":"https://boards-api.eu.greenhouse.io/v1/boards/{org}/jobs","kind":"json","accept":"application/json"},"extract":{"vars":{"jobCount":{"paths":["jobs"],"format":"array_len"},"total":{"paths":["meta.total"],"fallbackTemplate":"{jobCount}"}},"requireVars":["jobCount"],"titleTemplate":"{org} — Greenhouse Job Board ({total} open roles)","sections":[{"heading":"","arrayPath":"jobs","limit":120,"linkScanLimit":2000,"emptyText":"No open positions currently listed.","paginationMeta":{"totalPath":"meta.total","cursorMode":"offset"},"itemVars":{"jTitle":{"paths":["title"],"trim":true,"default":"Role"},"id":{"paths":["id"]},"rawUrl":{"paths":["absolute_url"],"requireHttps":true},"jUrl":{"template":"{rawUrl}","whenVars":["rawUrl"],"fallbackTemplate":"https://{host}/{org}/jobs/{id}"},"dept":{"paths":["departments"],"subField":"name","join":", ","default":"-"},"loc":{"paths":["location.name"],"trim":true,"default":"-"},"updated":{"paths":["updated_at"],"sliceMax":10,"trim":true,"default":"-"}},"collectLinkVars":["jUrl"],"columns":[{"header":"Role","template":"[{jTitle}]({jUrl})"},{"header":"Department","template":"{dept}"},{"header":"Location","template":"{loc}"},{"header":"Updated","template":"{updated}"}]}]}},{"match":{"hosts":["jobs.lever.co"],"pathSegments":[{"param":"org","charset":"pkg","maxLen":80,"reserved":["embed","v1","api","static","assets","favicon.ico"]}]},"twin":{"id":"lever-board","fetchUrl":"https://api.lever.co/v0/postings/{org}?mode=json&limit=100","kind":"json","accept":"application/json"},"extract":{"wrapRootArrayAs":"jobs","vars":{"total":{"paths":["jobs"],"format":"array_len"}},"requireVars":["total"],"titleTemplate":"{org} — Lever Job Board ({total} open roles)","sections":[{"heading":"","arrayPath":"jobs","limit":120,"linkScanLimit":2000,"emptyText":"No open positions currently listed.","paginationMeta":{"cursorMode":"last_id","idField":"id"},"itemVars":{"jTitle":{"paths":["text"],"trim":true,"default":"Role"},"id":{"paths":["id"]},"rawUrl":{"paths":["hostedUrl"],"requireHttps":true},"jUrl":{"template":"{rawUrl}","whenVars":["rawUrl"],"fallbackTemplate":"https://{host}/{org}/{id}"},"team":{"paths":["categories.team","categories.department"],"trim":true,"default":"-"},"loc":{"paths":["categories.location"],"trim":true,"default":"-"},"wp":{"paths":["workplaceType"],"trim":true,"default":"-"}},"collectLinkVars":["jUrl"],"columns":[{"header":"Role","template":"[{jTitle}]({jUrl})"},{"header":"Team","template":"{team}"},{"header":"Location","template":"{loc}"},{"header":"Workplace","template":"{wp}"}]}]}},{"match":{"hosts":["jobs.eu.lever.co"],"pathSegments":[{"param":"org","charset":"pkg","maxLen":80,"reserved":["embed","v1","api","static","assets","favicon.ico"]}]},"twin":{"id":"lever-eu-board","fetchUrl":"https://api.eu.lever.co/v0/postings/{org}?mode=json&limit=100","kind":"json","accept":"application/json"},"extract":{"wrapRootArrayAs":"jobs","vars":{"total":{"paths":["jobs"],"format":"array_len"}},"requireVars":["total"],"titleTemplate":"{org} — Lever Job Board ({total} open roles)","sections":[{"heading":"","arrayPath":"jobs","limit":120,"linkScanLimit":2000,"emptyText":"No open positions currently listed.","paginationMeta":{"cursorMode":"last_id","idField":"id"},"itemVars":{"jTitle":{"paths":["text"],"trim":true,"default":"Role"},"id":{"paths":["id"]},"rawUrl":{"paths":["hostedUrl"],"requireHttps":true},"jUrl":{"template":"{rawUrl}","whenVars":["rawUrl"],"fallbackTemplate":"https://{host}/{org}/{id}"},"team":{"paths":["categories.team","categories.department"],"trim":true,"default":"-"},"loc":{"paths":["categories.location"],"trim":true,"default":"-"},"wp":{"paths":["workplaceType"],"trim":true,"default":"-"}},"collectLinkVars":["jUrl"],"columns":[{"header":"Role","template":"[{jTitle}]({jUrl})"},{"header":"Team","template":"{team}"},{"header":"Location","template":"{loc}"},{"header":"Workplace","template":"{wp}"}]}]}}]},{"id":"hackernews","name":"Hacker News Stories & Who is Hiring (Algolia API)","category":"commerce-social","description":"Upgrades news.ycombinator.com/item?id= threads (including monthly Who is Hiring threads) to hn.algolia.com/api/v1/items/ JSON.","domains":["news.ycombinator.com"],"exampleUrls":["https://news.ycombinator.com/item?id=41000000"],"match":{"exactSegments":true,"pathSegments":["item"],"queryParams":[{"name":"id","param":"itemId","charset":"digits","minLen":1,"maxLen":12}]},"twin":{"id":"hackernews","fetchUrl":"https://hn.algolia.com/api/v1/items/{itemId}","kind":"json","accept":"application/json"},"extract":{"requireFields":["id"],"vars":{"title":{"paths":["title"],"trim":true,"fallbackTemplate":"HN Comment #{itemId}"},"author":{"paths":["author"]},"points":{"paths":["points"]},"createdAt":{"paths":["created_at"]},"postedDate":{"paths":["created_at"],"sliceMax":10},"storyUrl":{"paths":["url"]},"storyText":{"paths":["text"],"format":"html_to_md"}},"titleTemplate":"{title}","authorVar":"author","publishedTimeVar":"createdAt","metaLine":[{"label":"Points","template":"{points}","whenVar":"points"},{"label":"By","template":"{author}","whenVar":"author"},{"label":"Posted","template":"{postedDate}","whenVar":"postedDate"},{"label":"URL","template":"{storyUrl}","whenVar":"storyUrl"}],"bodyVar":"storyText","linksVars":["storyUrl"],"sections":[{"heading":"Comments","headingTemplate":"Comments ({topCount} top-level)","treeComments":{"childrenPath":"children","authorPath":"author","htmlTextPath":"text","maxDepth":2,"maxItems":60}}]}},{"id":"hardware-farm-specs","name":"Hardware & Farm Supply Spec Extractor","category":"commerce-social","description":"Extracts Product JSON-LD, specification tables, and Apollo SimpleProduct metadata for Tractor Supply and Harbor Freight.","domains":["tractorsupply.com","www.tractorsupply.com","harborfreight.com","www.harborfreight.com"],"auth_mode":"html","min_interval_ms":2000,"strict_robots":true,"exampleUrls":["https://www.harborfreight.com/20v-brushless-cordless-12-in-drilldriver-tool-only-59420.html"],"htmlRoutes":[{"id":"hardware-farm-specs","match":{"exactSegments":false},"mode":"hardware_farm_specs_html"}]},{"id":"hathitrust","name":"HathiTrust Digital Library","category":"public-records","description":"HathiTrust Bibliographic API (catalog.hathitrust.org/api/volumes) adapter for OCLC, ISBN, LCCN, ISSN, and Record IDs.","domains":["catalog.hathitrust.org","babel.hathitrust.org"],"auth_mode":"pub","min_interval_ms":1000,"strict_robots":false,"exampleUrls":["https://catalog.hathitrust.org/api/volumes/brief/oclc/424023.json","https://catalog.hathitrust.org/api/volumes/brief/isbn/9780030110405.json","https://catalog.hathitrust.org/Record/000578050"],"routes":[{"match":{"hosts":["catalog.hathitrust.org"],"pathPrefix":"/api/volumes/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"pub"},"extract":{"jsonMode":"hathitrust_json"}},{"match":{"hosts":["catalog.hathitrust.org"],"exactSegments":false,"pathSegments":["Record",{"param":"recordId","charset":"digits","minLen":5,"maxLen":20}]},"twin":{"fetchUrl":"https://catalog.hathitrust.org/api/volumes/brief/recordnumber/{recordId}.json","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"pub"},"extract":{"jsonMode":"hathitrust_json"}}]},{"id":"hcl-websphere-commerce","name":"HCL / WebSphere Commerce (WCS)","category":"commerce-social","description":"Extracts HCL/IBM WebSphere Commerce /wcs/resources/store//productview REST JSON and storefront HTML/companion twins.","domains":["www.childrensplace.com"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://www.childrensplace.com/us/p/Girls-Basic-Super-Skinny-Jeans-3044219-33C4"],"routes":[{"match":{"pathSegments":["wcs","resources","store",{"param":"storeId","charset":"digits","minLen":2,"maxLen":16},"productview","byPartNumber",{"param":"partNumber","charset":"pkg","minLen":1,"maxLen":120}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"commerceMode":"hcl_wcs_product"}},{"match":{"pathSegments":["wcs","resources","store",{"param":"storeId","charset":"digits","minLen":2,"maxLen":16},"productview","byId",{"param":"productId","charset":"pkg","minLen":1,"maxLen":120}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"commerceMode":"hcl_wcs_product"}}],"htmlRoutes":[{"id":"hcl-websphere-commerce","match":{"exactSegments":false},"mode":"hcl_wcs_html"}]},{"id":"headless-cms-delivery","name":"Headless CMS Delivery","category":"developer","description":"Opt-in single-page doc delivery twin for Sanity, Storyblok, Prismic, Contentful, Builder.io, and Strapi (gated by allowPageKeyTwins; falls back to HTML/JSON-LD when OFF).","domains":["3do82whm.apicdn.sanity.io","www.sanity.io","api.storyblok.com","www.storyblok.com","nextjs-starter-prismic-blog.cdn.prismic.io","prismic.io","cdn.contentful.com","cdn.builder.io","www.builder.io","strapi.io"],"universalEngine":true,"auth_mode":"page-key","requires_page_key_opt_in":true,"exampleUrls":["https://3do82whm.apicdn.sanity.io/v2021-10-21/data/query/next?query=*%5Bslug.current%20%3D%3D%20%22content-lake%22%5D%5B0%5D%7B_id%2C_type%2Ctitle%2Cslug%7D","https://nextjs-starter-prismic-blog.cdn.prismic.io/api/v2/documents/search?ref=ZuGtnBkAAEcAW15g&q=%5B%5B%3Ad+%3D+at%28document.id%2C+%22YlcmoRMAACMAI0gs%22%29+%5D%5D","https://cdn.builder.io/api/v3/content/docs/9f6f5d07-9c2e-4b44-983a-3f065151247f?apiKey=YJIGb4i01jvw0SRdL5Bt","https://www.sanity.io/docs/content-lake"],"routes":[{"match":{"hosts":["cdn.contentful.com"],"exactSegments":true,"pathSegments":["spaces",{"param":"spaceId","charset":"url_seg","minLen":1,"maxLen":64},"environments",{"param":"envId","charset":"url_seg","minLen":1,"maxLen":64},"entries",{"param":"entryId","charset":"url_seg","minLen":1,"maxLen":128}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"jsonMode":"headless_cms_doc"}},{"match":{"hosts":["api.storyblok.com","api-us.storyblok.com"],"exactSegments":false,"pathSegments":["v2","cdn","stories",{"param":"slug","charset":"safe_subpath","minLen":1,"maxLen":200,"greedy":true}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"jsonMode":"headless_cms_doc"}},{"match":{"hosts":["cdn.builder.io"],"exactSegments":true,"pathSegments":["api","v3","content",{"param":"model","charset":"url_seg","minLen":1,"maxLen":80},{"param":"entryId","charset":"url_seg","minLen":1,"maxLen":128}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"jsonMode":"headless_cms_doc"}},{"match":{"hostSubdomain":{"suffix":".apicdn.sanity.io","param":"projectId"},"exactSegments":true,"pathSegments":[{"param":"version","charset":"url_seg","minLen":4,"maxLen":24},"data","query",{"param":"dataset","charset":"url_seg","minLen":1,"maxLen":64}],"queryParams":[{"name":"query","param":"groqQuery","charset":"sanity_single_doc_query","minLen":5,"maxLen":400}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"jsonMode":"headless_cms_doc"}},{"match":{"hostSubdomain":{"suffix":".cdn.prismic.io","param":"repo"},"exactSegments":true,"pathSegments":["api","v2","documents","search"],"queryParams":[{"name":"q","param":"prismicQ","charset":"prismic_single_doc_query","minLen":5,"maxLen":300}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"jsonMode":"headless_cms_doc"}},{"match":{"exactSegments":true,"excludeSegmentSuffixes":[".json",".xml",".csv"],"pathSegments":["api",{"param":"contentType","charset":"strapi_content_type","minLen":1,"maxLen":80,"reserved":["auth","users","upload","graphql","all","list","search","export","v0","v1","v2","v3","v4","v5","v6","v7","v8","v9"]},{"param":"docId","charset":"strapi_doc_id","minLen":1,"maxLen":128,"reserved":["all","list","search","export","graphql","graphql.json","users"]}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"jsonMode":"headless_cms_doc"}}],"htmlRoutes":[{"id":"headless-cms-delivery","match":{"exactSegments":false},"mode":"headless_cms_html"}]},{"id":"headless-commerce","name":"Headless & Enterprise Commerce (commercetools, Elastic Path, Kibo, Optimizely)","category":"commerce-social","description":"Extracts commercetools, Elastic Path, Kibo/Mozu, and Optimizely Configured Commerce JSON-LD (with additionalProperty specs), Microdata, and hydration state.","domains":["www.bang-olufsen.com","www.guestsupply.com"],"universalEngine":true,"auth_mode":"html","exampleUrls":["https://www.bang-olufsen.com/en/us/headphones/beoplay-h100","https://www.guestsupply.com/product/0078423-Keystone-Liquid-Laundry-Built-Detergent-5-Gallon-1602538"],"htmlRoutes":[{"id":"headless-commerce","match":{"exactSegments":false},"mode":"headless_commerce_html"}]},{"id":"helpscout-docs","name":"Help Scout Docs","category":"developer","description":"Extracts Help Scout Docs knowledge base articles and collections from server-rendered HTML and BreadcrumbList JSON-LD.","domains":["docs.helpscout.com"],"universalEngine":true,"auth_mode":"html","exampleUrls":["https://docs.helpscout.com/article/666-use-dkim-to-help-with-email-delivery","https://docs.helpscout.com/collection/1543-getting-started"],"htmlRoutes":[{"id":"helpscout-docs","match":{"exactSegments":false},"mode":"helpscout_docs_html"}]},{"id":"hex-pm","name":"Hex.pm Elixir & Erlang Registry","category":"developer","description":"Upgrades hex.pm package pages to /api/packages/ metadata and HexDocs links.","domains":["hex.pm","www.hex.pm"],"exampleUrls":["https://hex.pm/packages/phoenix"],"match":{"exactSegments":true,"pathSegments":["packages",{"param":"pkg","charset":"alnum_dash"}]},"twin":{"fetchUrl":"https://hex.pm/api/packages/{pkg}","kind":"json","accept":"application/json"},"extract":{"requireFields":["name"],"vars":{"name":{"paths":["name"]},"desc":{"paths":["meta.description"],"trim":true},"licenses":{"paths":["meta.licenses"],"join":", "},"ver":{"paths":["releases.0.version"]},"verOrDefault":{"paths":["releases.0.version"],"default":"0.1"},"docsUrl":{"paths":["docs_html_url"],"fallbackTemplate":"https://hexdocs.pm/{name}"}},"titleTemplate":"{name} {ver} (Hex)","titleWhenVar":"ver","titleFallbackTemplate":"{name} (Hex)","descriptionVar":"desc","introVar":"desc","bullets":[{"label":"Mix","template":"`{:{name}, \"~> {verOrDefault}\"}`"},{"label":"HexDocs","template":"{docsUrl}"},{"label":"License","template":"{licenses}","whenVar":"licenses"}],"objectLinksPath":"meta.links"}},{"id":"home-depot-lowes","name":"Home Depot & Lowe's Product JSON-LD","category":"commerce-social","description":"Strictly low-rate, robots-enforced JSON-LD Product/ProductGroup extractor for Home Depot and Lowe's product pages.","domains":["homedepot.com","www.homedepot.com","lowes.com","www.lowes.com"],"auth_mode":"html","min_interval_ms":3000,"max_concurrent":1,"strict_robots":true,"exampleUrls":["https://www.homedepot.com/p/Milwaukee-M18-FUEL-Hammer-Drill-2904-20/320326137","https://www.lowes.com/pd/DEWALT-20V-MAX-Drill/501326137"],"htmlRoutes":[{"id":"home-depot-lowes","match":{"exactSegments":false},"mode":"home_depot_lowes_html"}]},{"id":"home-goods-jsonld","name":"US Home Goods Product JSON-LD","category":"commerce-social","description":"Structured Product and ProductGroup JSON-LD extractor for Wayfair and Overstock.","domains":["wayfair.com","www.wayfair.com","overstock.com","www.overstock.com"],"auth_mode":"html","min_interval_ms":2000,"strict_robots":true,"exampleUrls":["https://www.wayfair.com/furniture/pdp/mercury-row-perdue-815-velvet-square-arm-convertible-sofa-w009315804.html?piid=1134429065","https://www.overstock.com/Home-Garden/accent-chair/1400001/product.html"],"htmlRoutes":[{"id":"home-goods-jsonld","match":{"exactSegments":false},"mode":"home_goods_jsonld_html"}]},{"id":"homebrew-formulae","name":"Homebrew Formulae & Casks","category":"developer","description":"Upgrades formulae.brew.sh/formula/ and /cask/ pages to the official Homebrew JSON API with install commands, dependencies, deprecation/disable notices, and 30-day install analytics.","domains":["formulae.brew.sh"],"exampleUrls":["https://formulae.brew.sh/formula/jq","https://formulae.brew.sh/cask/iterm2"],"routes":[{"match":{"exactSegments":true,"excludeSegmentSuffixes":[".json"],"pathSegments":["formula",{"param":"id","charset":"brew_id","minLen":1,"maxLen":128}]},"twin":{"fetchUrl":"https://formulae.brew.sh/api/formula/{id}.json","rawPathParams":["id"],"kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"requireFields":["name"],"vars":{"name":{"paths":["name"]},"fullName":{"paths":["full_name","name"]},"desc":{"paths":["desc"],"trim":true},"version":{"paths":["versions.stable","versions.head"]},"license":{"paths":["license"]},"homepage":{"paths":["homepage"],"requireHttps":true},"deps":{"paths":["dependencies"],"itemWrap":"`","join":", ","limit":20},"buildDeps":{"paths":["build_dependencies"],"itemWrap":"`","join":", ","limit":15},"caveats":{"paths":["caveats"],"trim":true},"installs30d":{"dynamicKeyPath":{"base":"analytics.install.30d","keyVar":"id"},"format":"int_comma"},"disabledFlag":{"paths":["disabled"],"format":"bool_map","trueValue":"Disabled","falseValue":""},"disabledReason":{"paths":["disable_reason"]},"disabledDate":{"paths":["disable_date"]},"deprecatedFlag":{"paths":["deprecated"],"format":"bool_map","trueValue":"Deprecated","falseValue":""},"deprecationReason":{"paths":["deprecation_reason"]},"deprecationDate":{"paths":["deprecation_date"]},"replacement":{"paths":["disable_replacement_formula","disable_replacement_cask","deprecation_replacement_formula","deprecation_replacement_cask"]},"disabledSummary":{"template":"Disabled ({disabledReason}, {disabledDate})","whenVars":["disabledFlag","disabledReason","disabledDate"],"fallbackVar":"disabledFlag"},"deprecatedSummary":{"template":"Deprecated ({deprecationReason}, {deprecationDate})","whenVars":["deprecatedFlag","deprecationReason","deprecationDate"],"fallbackVar":"deprecatedFlag"},"statusNotice":{"template":"{disabledSummary}","whenVars":["disabledSummary"],"fallbackVar":"deprecatedSummary"}},"titleTemplate":"{fullName} (Homebrew Formula)","descriptionVar":"desc","blockquoteTemplate":"> **Notice**: {statusNotice}","blockquoteWhenVar":"statusNotice","introVar":"desc","bullets":[{"label":"Install","template":"`brew install {name}`"},{"label":"Stable Version","template":"`{version}`","whenVar":"version"},{"label":"License","template":"{license}","whenVar":"license"},{"label":"Replacement","template":"`{replacement}`","whenVar":"replacement"},{"label":"30d Installs","template":"{installs30d}","whenVar":"installs30d"},{"label":"Homepage","template":"{homepage}","whenVar":"homepage"},{"label":"Dependencies","template":"{deps}","whenVar":"deps"},{"label":"Build Dependencies","template":"{buildDeps}","whenVar":"buildDeps"}],"sections":[{"heading":"Caveats","textVar":"caveats"}],"linksVars":["homepage"]}},{"match":{"exactSegments":true,"excludeSegmentSuffixes":[".json"],"pathSegments":["cask",{"param":"id","charset":"brew_id","minLen":1,"maxLen":128}]},"twin":{"fetchUrl":"https://formulae.brew.sh/api/cask/{id}.json","rawPathParams":["id"],"kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"requireFields":["token"],"vars":{"token":{"paths":["token"]},"displayName":{"paths":["name.0","full_token","token"]},"desc":{"paths":["desc"],"trim":true},"version":{"paths":["version"]},"homepage":{"paths":["homepage"],"requireHttps":true},"downloadUrl":{"paths":["url"],"requireHttps":true},"sha256":{"paths":["sha256"]},"autoUpdates":{"paths":["auto_updates"],"format":"bool_map","trueValue":"Yes","falseValue":"No"},"caveats":{"paths":["caveats"],"trim":true},"installs30d":{"dynamicKeyPath":{"base":"analytics.install.30d","keyVar":"id"},"format":"int_comma"},"disabledFlag":{"paths":["disabled"],"format":"bool_map","trueValue":"Disabled","falseValue":""},"disabledReason":{"paths":["disable_reason"]},"disabledDate":{"paths":["disable_date"]},"deprecatedFlag":{"paths":["deprecated"],"format":"bool_map","trueValue":"Deprecated","falseValue":""},"deprecationReason":{"paths":["deprecation_reason"]},"deprecationDate":{"paths":["deprecation_date"]},"replacement":{"paths":["disable_replacement_cask","disable_replacement_formula","deprecation_replacement_cask","deprecation_replacement_formula"]},"disabledSummary":{"template":"Disabled ({disabledReason}, {disabledDate})","whenVars":["disabledFlag","disabledReason","disabledDate"],"fallbackVar":"disabledFlag"},"deprecatedSummary":{"template":"Deprecated ({deprecationReason}, {deprecationDate})","whenVars":["deprecatedFlag","deprecationReason","deprecationDate"],"fallbackVar":"deprecatedFlag"},"statusNotice":{"template":"{disabledSummary}","whenVars":["disabledSummary"],"fallbackVar":"deprecatedSummary"}},"titleTemplate":"{displayName} (Homebrew Cask)","descriptionVar":"desc","blockquoteTemplate":"> **Notice**: {statusNotice}","blockquoteWhenVar":"statusNotice","introVar":"desc","bullets":[{"label":"Install","template":"`brew install --cask {token}`"},{"label":"Token","template":"`{token}`"},{"label":"Version","template":"`{version}`","whenVar":"version"},{"label":"Auto Updates","template":"{autoUpdates}","whenVar":"autoUpdates"},{"label":"Replacement","template":"`{replacement}`","whenVar":"replacement"},{"label":"30d Installs","template":"{installs30d}","whenVar":"installs30d"},{"label":"Homepage","template":"{homepage}","whenVar":"homepage"},{"label":"Download URL","template":"{downloadUrl}","whenVar":"downloadUrl"},{"label":"SHA-256","template":"`{sha256}`","whenVar":"sha256"}],"sections":[{"heading":"Caveats","textVar":"caveats"}],"linksVars":["homepage","downloadUrl"]}}]},{"id":"hourly-smb-ats","name":"Hourly & SMB ATS (Hireology, ApplicantPro, Harri, Fountain, ClearCompany, Workstream)","category":"jobs","description":"Extracts JobPosting JSON-LD, Next.js SSR boards, and structured HTML job postings from Hireology, ApplicantPro, Harri, Fountain, ClearCompany, and Workstream.","domains":["www.applicantpro.com","www.clearcompany.com","app.hireology.com","harri.com","web.fountain.com","www.workstream.us"],"universalEngine":true,"auth_mode":"html","exampleUrls":["https://careers.hireology.com/hireology2/2908935/description","https://harri.com/Kitchen-Putters-Cw"],"htmlRoutes":[{"id":"hourly-smb-ats","mode":"hourly_smb_ats_html","match":{"excludeHosts":["recruiting.ultipro.com","recruiting.paylocity.com","app.dover.com","jobs.dover.com","jobs.smartrecruiters.com","*.oraclecloud.com","jobs.jobvite.com","app.clearcompany.com"],"anyOf":[{"hostSubdomain":{"suffix":".applicantpro.com","param":"tenant","reserved":["www","login","admin"]},"exactSegments":false},{"hosts":["www.applicantpro.com"],"pathPrefix":"/careers","exactSegments":false},{"hostSubdomain":{"suffix":".clearcompany.com","param":"tenant","reserved":["app","login","admin"]},"exactSegments":false},{"hosts":["careers.hireology.com","app.hireology.com"],"exactSegments":false},{"hosts":["harri.com","www.harri.com"],"exactSegments":false},{"hosts":["web.fountain.com"],"pathPrefix":"/apply/","exactSegments":false},{"hostSubdomain":{"suffix":".workstream.us","param":"tenant","reserved":["app","login","api"]},"exactSegments":false}]}}]},{"id":"hrsa-samhsa-locator","name":"HRSA & SAMHSA Treatment Locator","category":"research-health","description":"SAMHSA FindTreatment.gov locator JSON export API adapter with HRSA/SAMHSA portal HTML fallback.","domains":["data.hrsa.gov","findahealthcenter.hrsa.gov","findtreatment.gov","www.findtreatment.gov"],"auth_mode":"pub","exampleUrls":["https://findtreatment.gov/locator/exportsAsJson/v2?sAddr=40.7506%2C-73.9972&sType=SA&limitValue=5000&limitType=2&pageSize=2&page=1","https://data.hrsa.gov/tools/web-services"],"routes":[{"match":{"hosts":["findtreatment.gov","www.findtreatment.gov"],"pathPrefix":"/locator/exportsAsJson/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"samhsa_locator_json"}}],"htmlRoutes":[{"id":"hrsa-samhsa-locator","match":{"hosts":["data.hrsa.gov","findahealthcenter.hrsa.gov","findtreatment.gov","www.findtreatment.gov"],"exactSegments":false},"mode":"hrsa_samhsa_html"}]},{"id":"hubspot-cms","name":"HubSpot CMS","category":"developer","description":"Extracts same-origin HubSpot HubDB table rows (/_hcms/api/hubdb/v3/... and /hs/api/hubdb/v2/...) and HubSpot CMS HTML metadata while rejecting page_id:0 404s.","domains":["www.hubspot.com","developers.hubspot.com","www.smartbugmedia.com"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://www.smartbugmedia.com/blog/hubspot-unbound-2026-recap-7-ai-updates-to-turn-on-first-and-what-each-one-costs"],"routes":[{"match":{"exactSegments":true,"pathSegments":["_hcms","api","hubdb","v3","tables",{"param":"tableId","charset":"url_seg","minLen":1,"maxLen":120},"rows"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"hubspot_hubdb_json"}},{"match":{"exactSegments":true,"pathSegments":["hs","api","hubdb","v2","tables",{"param":"tableId","charset":"url_seg","minLen":1,"maxLen":120},"rows"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"hubspot_hubdb_json"}}],"htmlRoutes":[{"id":"hubspot-cms","match":{"exactSegments":false},"mode":"hubspot_cms_html"}]},{"id":"hud-fhfa","name":"HUD User & FHFA House Price Index","category":"public-records","description":"Extracts HUD User Fair Market Rent / Income Limit API JSON (when HUD_API_KEY is configured), FHFA House Price Index JSON & CSV datasets, and FHFA HPI HTML pages.","domains":["huduser.gov","www.huduser.gov","fhfa.gov","www.fhfa.gov"],"auth_mode":"key","exampleUrls":["https://www.huduser.gov/hudapi/public/fmr/listStates","https://www.fhfa.gov/hpi/download/quarterly_datasets/hpi_at_state.csv","https://www.fhfa.gov/data/hpi"],"routes":[{"match":{"hosts":["huduser.gov","www.huduser.gov"],"pathPrefix":"/hudapi/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304,"auth_mode":"key"},"extract":{"jsonMode":"hud_user_json"}},{"match":{"hosts":["fhfa.gov","www.fhfa.gov"],"pathPrefix":"/hpi/download/","pathSuffix":".json"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304,"auth_mode":"pub"},"extract":{"jsonMode":"fhfa_hpi_json"}},{"match":{"hosts":["fhfa.gov","www.fhfa.gov"],"pathPrefix":"/hpi/download/","pathSuffix":".csv"},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"text/plain","maxBytes":4194304,"auth_mode":"pub"},"extract":{"textMode":"fhfa_hpi_csv"}}],"htmlRoutes":[{"id":"hud-fhfa","match":{"hosts":["fhfa.gov","www.fhfa.gov","huduser.gov","www.huduser.gov"],"exactSegments":false},"mode":"hud_fhfa_html"}]},{"id":"huggingface","name":"Hugging Face Models, Datasets & Spaces","category":"genai","description":"Upgrades Hugging Face model/dataset/space pages and file blobs to raw README.md with parsed YAML frontmatter tables.","domains":["huggingface.co","www.huggingface.co"],"exampleUrls":["https://huggingface.co/Qwen/Qwen2.5-Coder-32B-Instruct"],"routes":[{"match":{"anyOf":[{"exactSegments":true,"pathSegments":[{"param":"repoType","allowValues":["datasets","spaces"]},{"param":"org","charset":"pkg"},{"param":"repo","charset":"pkg"}],"defaults":{"rev":"main"}},{"exactSegments":true,"pathSegments":[{"param":"repoType","allowValues":["datasets","spaces"]},{"param":"org","charset":"pkg"},{"param":"repo","charset":"pkg"},"tree",{"param":"rev","charset":"pkg"}]}]},"twin":{"id":"huggingface-card","fetchUrl":"https://huggingface.co/{repoType}/{org}/{repo}/raw/{rev}/README.md","kind":"text","accept":"text/markdown"},"extract":{"textMode":"yaml_frontmatter_card","titleTemplate":"{repoType}/{org}/{repo}"}},{"match":{"anyOf":[{"exactSegments":true,"pathSegments":[{"param":"org","charset":"pkg","reserved":["models","datasets","spaces","docs","blog","papers","posts","tasks","organizations","settings","login","join","pricing"]},{"param":"repo","charset":"pkg"}],"defaults":{"rev":"main"}},{"exactSegments":true,"pathSegments":[{"param":"org","charset":"pkg","reserved":["models","datasets","spaces","docs","blog","papers","posts","tasks","organizations","settings","login","join","pricing"]},{"param":"repo","charset":"pkg"},"tree",{"param":"rev","charset":"pkg"}]}]},"twin":{"id":"huggingface-card","fetchUrl":"https://huggingface.co/{org}/{repo}/raw/{rev}/README.md","kind":"text","accept":"text/markdown"},"extract":{"textMode":"yaml_frontmatter_card","titleTemplate":"{org}/{repo}"}},{"match":{"pathSegments":[{"param":"repoType","allowValues":["datasets","spaces"]},{"param":"org","charset":"pkg"},{"param":"repo","charset":"pkg"},"blob",{"param":"rev","charset":"pkg"},{"param":"filePath","charset":"safe_subpath","greedy":true,"maxLen":240}]},"twin":{"id":"huggingface-blob","fetchUrl":"https://huggingface.co/{repoType}/{org}/{repo}/raw/{rev}/{filePath}","rawPathParams":["filePath"],"kind":"text","accept":"text/plain"},"extract":{"textMode":"code_or_markdown_by_path","pathParam":"filePath","titleTemplate":"{repoType}/{org}/{repo}/{filePath}"}},{"match":{"pathSegments":[{"param":"org","charset":"pkg","reserved":["models","datasets","spaces","docs","blog","papers","posts","tasks","organizations","settings","login","join","pricing"]},{"param":"repo","charset":"pkg"},"blob",{"param":"rev","charset":"pkg"},{"param":"filePath","charset":"safe_subpath","greedy":true,"maxLen":240}]},"twin":{"id":"huggingface-blob","fetchUrl":"https://huggingface.co/{org}/{repo}/raw/{rev}/{filePath}","rawPathParams":["filePath"],"kind":"text","accept":"text/plain"},"extract":{"textMode":"code_or_markdown_by_path","pathParam":"filePath","titleTemplate":"{org}/{repo}/{filePath}"}}]},{"id":"icims","name":"iCIMS Enterprise Career Portals","category":"jobs","description":"Upgrades *.icims.com/jobs/... portals and postings to their server-rendered ?ss=1&in_iframe=1 twin, extracting JobPosting JSON-LD and open role cards without outer iframe shells.","domains":["*.icims.com"],"exampleUrls":["https://careers-compsych.icims.com/jobs/search?ss=1","https://careers-compsych.icims.com/jobs/2526/senior-cloud-architect/job"],"routes":[{"match":{"hostSubdomain":{"suffix":".icims.com","param":"org","reserved":["www","status","support","community","developer","developers","login"]},"exactSegments":true,"pathSegments":[]},"twin":{"id":"icims","fetchUrl":"{requestUrl}","overridePathIf":{"matchPaths":["/"],"newPath":"/jobs/search"},"defaultQueryParams":{"ss":"1"},"setQueryParams":{"in_iframe":"1"},"kind":"text","accept":"text/html"},"extract":{"icimsPortal":true}},{"match":{"hostSubdomain":{"suffix":".icims.com","param":"org","reserved":["www","status","support","community","developer","developers","login"]},"anyOf":[{"exactSegments":true,"pathSegments":["jobs"]},{"exactSegments":true,"pathSegments":["jobs","intro"]},{"exactSegments":true,"pathSegments":["jobs","search"]}]},"twin":{"id":"icims","fetchUrl":"{requestUrl}","overridePathIf":{"matchPaths":["/jobs","/jobs/intro","/jobs/search"],"newPath":"/jobs/search"},"defaultQueryParams":{"ss":"1"},"setQueryParams":{"in_iframe":"1"},"kind":"text","accept":"text/html"},"extract":{"icimsPortal":true}},{"match":{"hostSubdomain":{"suffix":".icims.com","param":"org","reserved":["www","status","support","community","developer","developers","login"]},"exactSegments":false,"pathSegments":["jobs"]},"twin":{"id":"icims","fetchUrl":"{requestUrl}","setQueryParams":{"in_iframe":"1"},"kind":"text","accept":"text/html"},"extract":{"icimsPortal":true}}],"htmlRoutes":[{"id":"icims","mode":"icims_portal","match":{"hostSubdomain":{"suffix":".icims.com","param":"org","reserved":["www","status","support","community","developer","developers","login"]},"exactSegments":false,"pathSegments":["jobs"]}}]},{"id":"ietf-rfc","name":"IETF Datatracker & RFC Editor","category":"developer","description":"Strips ASCII RFC running page headers/footers ([Page N]) and promotes numbered section headings to Markdown headings.","domains":["datatracker.ietf.org","rfc-editor.org","www.rfc-editor.org"],"exampleUrls":["https://datatracker.ietf.org/doc/html/rfc9421","https://www.rfc-editor.org/rfc/rfc9110"],"routes":[{"match":{"hosts":["rfc-editor.org","www.rfc-editor.org"],"pathPrefix":"/rfc/rfc","exactSegments":true,"pathSegments":["rfc",{"param":"rfcId","stripPrefix":"rfc","charset":"digits","minLen":1,"maxLen":6}]},"twin":{"fetchUrl":"https://www.rfc-editor.org/rfc/rfc{rfcId}.html","kind":"text","accept":"text/html","maxBytes":4194304},"extract":{"textMode":"html_document","titleTemplate":"RFC {rfcId}"}}],"htmlRoutes":[{"match":{"anyOf":[{"hosts":["datatracker.ietf.org"],"pathPrefix":"/doc/html/rfc"},{"hosts":["datatracker.ietf.org"],"pathPrefix":"/doc/html/draft-"},{"hosts":["rfc-editor.org","www.rfc-editor.org"],"pathPrefix":"/rfc/rfc","minSegments":2}]},"mode":"markdown_clean","cleanPreset":"ietf_rfc"}]},{"id":"intercom-help","name":"Intercom Help Center","category":"developer","description":"Extracts Intercom Help Center articles and collections from __NEXT_DATA__ hydration, JSON-LD, and semantic HTML.","domains":["support.claude.com","www.intercom.com"],"universalEngine":true,"auth_mode":"html","min_interval_ms":1000,"exampleUrls":["https://support.claude.com/en/articles/7996845-what-are-some-things-i-can-use-claude-for","https://support.claude.com/en/collections/4078531-claude"],"htmlRoutes":[{"id":"intercom-help","match":{"exactSegments":false},"mode":"intercom_help_html"}]},{"id":"internet-archive","name":"Internet Archive Items (archive.org)","category":"genai","description":"Upgrades archive.org/details/ pages to the official /metadata/ JSON feed with creator, license, and downloadable files.","domains":["archive.org","www.archive.org"],"exampleUrls":["https://archive.org/details/07-28-16_Space-to-Grounds.zip"],"match":{"exactSegments":true,"pathSegments":["details",{"param":"identifier","charset":"pkg","minLen":2,"maxLen":120}]},"twin":{"fetchUrl":"https://archive.org/metadata/{identifier}","kind":"json","accept":"application/json"},"extract":{"requireAnyFields":["metadata"],"vars":{"title":{"paths":["metadata.title"],"fallbackTemplate":"{identifier}","trim":true},"creator":{"paths":["metadata.creator"],"join":", "},"mediatype":{"paths":["metadata.mediatype"]},"date":{"paths":["metadata.date","metadata.publicdate"]},"license":{"paths":["metadata.licenseurl"]},"collections":{"paths":["metadata.collection"],"limit":6,"join":", "},"desc":{"paths":["metadata.description"],"join":"\n\n","format":"strip_tags"},"descShort":{"paths":["metadata.description"],"join":"\n\n","format":"strip_tags","sliceMax":260}},"titleTemplate":"{title}","descriptionVar":"descShort","authorVar":"creator","publishedTimeVar":"date","bullets":[{"label":"Identifier","template":"`{identifier}`"},{"label":"Creator","template":"{creator}","whenVar":"creator"},{"label":"Media Type","template":"{mediatype}","whenVar":"mediatype"},{"label":"Date","template":"{date}","whenVar":"date"},{"label":"Collections","template":"{collections}","whenVar":"collections"},{"label":"License","template":"{license}","whenVar":"license"}],"sections":[{"heading":"Description","textVar":"desc"},{"heading":"Files","arrayPath":"files","filter":{"excludeFieldSuffixes":{"field":"name","suffixes":["_meta.xml","_files.xml"]}},"limit":15,"requireItemVar":"fname","collectLinkVars":["dlUrl"],"itemVars":{"fname":{"paths":["name"]},"dlUrl":{"template":"https://archive.org/download/{identifier}/{fname}","whenVars":["fname"],"replaceAll":{"from":" ","to":"%20"}}},"columns":[{"header":"File","template":"[{fname}]({dlUrl})"},{"header":"Format","paths":["format"]},{"header":"Size","paths":["size"],"format":"bytes_human"}]}]}},{"id":"irs-teos","name":"IRS Tax Exempt Organization Search (TEOS)","category":"public-records","description":"Extracts IRS Tax Exempt Organization Search (Pub 78 / Form 990-N) lookup records while respecting robots.txt and strictly rejecting Akamai WAF challenge pages.","domains":["apps.irs.gov"],"auth_mode":"pub","strict_robots":true,"exampleUrls":["https://apps.irs.gov/app/eos/allSearch?ein=521693387","https://apps.irs.gov/app/eos/details/521693387"],"routes":[{"match":{"hosts":["apps.irs.gov"],"pathPrefix":"/app/eos/allSearch"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"pub","maxBytes":2097152},"extract":{"jsonMode":"irs_teos_json"}},{"match":{"hosts":["apps.irs.gov"],"exactSegments":false,"pathSegments":["app","eos","details",{"param":"ein","charset":"alnum_dash","minLen":4,"maxLen":20}]},"twin":{"fetchUrl":"https://apps.irs.gov/app/eos/allSearch?ein={ein}","kind":"json","accept":"application/json","auth_mode":"pub","maxBytes":2097152},"extract":{"jsonMode":"irs_teos_json"}}],"htmlRoutes":[{"id":"irs-teos","match":{"hosts":["apps.irs.gov"],"pathPrefix":"/app/eos/","exactSegments":false},"mode":"irs_teos_html"}]},{"id":"javadoc-dokka","name":"Javadoc & Kotlin Dokka API Docs","category":"developer","description":"Universal extractor for Javadoc and Kotlin Dokka HTML API pages as well as element-list and package-list index manifests.","domains":["docs.oracle.com","kotlinlang.org"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/String.html","https://docs.oracle.com/en/java/javase/21/docs/api/element-list","https://kotlinlang.org/api/core/kotlin-stdlib/kotlin/-string/index.html"],"routes":[{"match":{"anyOf":[{"pathSuffix":"/element-list"},{"pathSuffix":"/package-list"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"text/plain","maxBytes":1048576},"extract":{"textMode":"javadoc_element_list_text"}}],"htmlRoutes":[{"id":"javadoc-dokka","match":{"exactSegments":false},"mode":"javadoc_dokka_html"}]},{"id":"jazzhr","name":"JazzHR Career Boards (applytojob.com)","category":"jobs","description":"Upgrades .applytojob.com boards to app.jazz.co/feeds/export/jobs/ XML export (which includes full job descriptions and returns clean 404 on invalid slugs).","domains":["*.applytojob.com"],"exampleUrls":["https://axiomcloud.applytojob.com/apply"],"match":{"hostSubdomain":{"suffix":".applytojob.com","param":"org","reserved":["www","app"]},"maxSegments":1},"twin":{"id":"jazzhr","fetchUrl":"https://app.jazz.co/feeds/export/jobs/{org}","kind":"text","accept":"application/xml"},"extract":{"xml":{"mode":"items_table","requireAnyTags":["jobs","job"],"itemTag":"job","titleTemplate":"{org} — JazzHR Job Board ({itemCount} open roles)","emptyText":"No open positions currently listed.","limit":100,"requireItemVar":"jTitle","collectLinkVar":"jUrl","itemVars":{"jTitle":{"tags":["title"]},"jUrl":{"tags":["url"]},"dept":{"tags":["department"],"default":"-"},"city":{"tags":["city"]},"state":{"tags":["state"]},"country":{"tags":["country"]},"jType":{"tags":["type"],"default":"-"}},"columns":[{"header":"Role","template":"[{jTitle}]({jUrl})"},{"header":"Department","template":"{dept}"},{"header":"Location","template":"{city} {state} {country}"},{"header":"Type","template":"{jType}"}]}}},{"id":"job-boards-jsonld-pack","name":"Job Boards (CareerArc, Nexxt, Reed, Alljobs)","category":"jobs","description":"Extracts JobPosting JSON-LD from CareerArc, Nexxt, Reed.co.uk, and Alljobs posting pages: title, company, locations, employment type, salary, posting/expiry dates, job ID, and description. Repairs the unescaped quotes CareerArc emits inside descriptions in one linear pass. Honors robots.txt.","domains":["www.careerarc.com","careerarc.com","www.nexxt.com","nexxt.com","www.reed.co.uk","reed.co.uk","www.alljobs.co.il","alljobs.co.il"],"auth_mode":"html","min_interval_ms":3000,"strict_robots":true,"exampleUrls":["https://www.careerarc.com/job-listing/state-of-vermont-jobs-trooper-probationary-53326582","https://www.nexxt.com/jobs/registered-nurse-rn-lebanon-oh-3496987559-job.html","https://www.reed.co.uk/jobs/nurse-wca/57553089","https://www.alljobs.co.il/Search/UploadSingle.aspx?JobID=8822511"],"htmlRoutes":[{"id":"job-boards-jsonld-pack","match":{"hosts":["www.careerarc.com","careerarc.com","www.nexxt.com","nexxt.com","www.reed.co.uk","reed.co.uk","www.alljobs.co.il","alljobs.co.il"],"exactSegments":false},"mode":"job_boards_jsonld_html"}]},{"id":"jsr-io","name":"JSR JavaScript Registry","category":"developer","description":"Strips top-bar navigation and duplicate version/scorecard tabs from jsr.io/@scope/pkg Markdown.","domains":["jsr.io"],"exampleUrls":["https://jsr.io/@std/path"],"htmlRoutes":[{"match":{"exactSegments":false,"pathSegments":[{"param":"scope","charset":"npm_scope"},{"param":"pkg","charset":"npm_pkg"}]},"mode":"markdown_clean","cleanPreset":"jsr_io"}]},{"id":"judge-me","name":"Judge.me Product Reviews","category":"commerce-social","description":"Extracts public Judge.me product reviews widget JSON and HTML-in-JSON payloads without preempting storefront extractors.","domains":["api.judge.me","judge.me","cache.judge.me"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://api.judge.me/reviews/reviews_for_widget?shop_domain=thebraindriver.myshopify.com&platform=shopify&product_id=3946432580&page=1&per_page=10"],"routes":[{"match":{"hosts":["api.judge.me","judge.me","cache.judge.me"],"pathEquals":["/reviews/reviews_for_widget","/api/v1/widgets/product_review","/api/v1/reviews"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"judgeme_reviews"}}],"htmlRoutes":[{"id":"judge-me","match":{"exactSegments":false},"mode":"judgeme_html"}]},{"id":"jwplayer","name":"JW Player Delivery & Previews","category":"commerce-social","description":"Extracts JW Player CDN v2 media/playlist JSON twins, /previews/{mediaId} redirects to v2 media JSON, and JW Platform feeds.","domains":["cdn.jwplayer.com","content.jwplatform.com"],"auth_mode":"pub","exampleUrls":["https://cdn.jwplayer.com/v2/media/1b02B03R","https://cdn.jwplayer.com/previews/1b02B03R"],"routes":[{"match":{"hosts":["cdn.jwplayer.com"],"exactSegments":true,"pathSegments":["v2",{"param":"kind","allowValues":["media","playlists"]},{"param":"mediaId","charset":"alnum","minLen":6,"maxLen":16}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"jwplayer_json"}},{"match":{"hosts":["cdn.jwplayer.com"],"exactSegments":true,"pathSegments":["previews",{"param":"mediaId","charset":"alnum","minLen":6,"maxLen":16}]},"twin":{"fetchUrl":"https://cdn.jwplayer.com/v2/media/{mediaId}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"jwplayer_json"}},{"match":{"hosts":["content.jwplatform.com"],"exactSegments":true,"pathSuffix":".json","pathSegments":["feeds",{"param":"mediaFile","charset":"url_seg","stripSuffix":".json","minLen":4,"maxLen":40}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"jwplayer_json"}}],"htmlRoutes":[{"id":"jwplayer","match":{"exactSegments":false},"mode":"jwplayer_html"}]},{"id":"kaggle","name":"Kaggle Datasets, Models & Competitions","category":"developer","description":"Extracts Kaggle dataset, model, and competition metadata via Kaggle REST API v1 (KAGGLE_API_KEY) with public HTML fallback.","domains":["www.kaggle.com","kaggle.com"],"auth_mode":"key","exampleUrls":["https://www.kaggle.com/api/v1/datasets/view/heptapod/titanic","https://www.kaggle.com/datasets/heptapod/titanic"],"routes":[{"match":{"hosts":["www.kaggle.com","kaggle.com"],"pathPrefix":"/api/v1/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"kaggle_json"}},{"match":{"hosts":["www.kaggle.com","kaggle.com"],"exactSegments":false,"pathSegments":["datasets",{"param":"owner","charset":"pkg","minLen":1,"maxLen":100},{"param":"slug","charset":"pkg","minLen":1,"maxLen":120}]},"twin":{"fetchUrl":"https://www.kaggle.com/api/v1/datasets/view/{owner}/{slug}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"kaggle_json"}}],"htmlRoutes":[{"id":"kaggle","match":{"hosts":["www.kaggle.com","kaggle.com"],"exactSegments":false},"mode":"kaggle_html"}]},{"id":"kb-platform-pack","name":"KB Platform Pack (Document360, Helpjuice, KnowledgeOwl)","category":"developer","description":"Extracts public knowledge base articles and categories across Document360, Helpjuice, and KnowledgeOwl.","domains":["docs.document360.com","help.helpjuice.com","support.knowledgeowl.com"],"universalEngine":true,"auth_mode":"html","exampleUrls":["https://help.helpjuice.com/getting-started/what-is-a-knowledge-base","https://support.knowledgeowl.com/help/enable-single-sign-on-sso"],"htmlRoutes":[{"id":"kb-platform-pack","match":{"exactSegments":false},"mode":"kb_platform_pack_html"}]},{"id":"khoros-lithium","name":"Khoros / Lithium Communities","category":"developer","description":"Upgrades Khoros/Lithium /t5/.../td-p/ community threads to /api/2.0/messages/ JSON twins with HTML fallback.","domains":["community.qlik.com"],"universalEngine":true,"auth_mode":"pub","min_interval_ms":5000,"exampleUrls":["https://community.qlik.com/t5/Product-Innovation/AI-Without-Context-Is-Guessing-With-Confidence-Our-October-Qlik/ba-p/2560737","https://community.qlik.com/api/2.0/messages/2560737"],"routes":[{"match":{"pathPrefix":"/t5/","anyOf":[{"scanSegment":{"afterLiteral":"td-p","param":"msgId","charset":"digits","minLen":1,"maxLen":16}},{"scanSegment":{"afterLiteral":"m-p","param":"msgId","charset":"digits","minLen":1,"maxLen":16}},{"scanSegment":{"afterLiteral":"ba-p","param":"msgId","charset":"digits","minLen":1,"maxLen":16}},{"scanSegment":{"afterLiteral":"ta-p","param":"msgId","charset":"digits","minLen":1,"maxLen":16}}]},"twin":{"fetchUrl":"https://{host}/api/2.0/messages/{msgId}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"khoros_message"}},{"match":{"pathSegments":["api","2.0","messages",{"param":"msgId","charset":"digits","minLen":1,"maxLen":16}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"khoros_message"}}],"htmlRoutes":[{"id":"khoros-lithium","match":{"exactSegments":false},"mode":"khoros_html"}]},{"id":"klevu","name":"Klevu Smart Search","category":"commerce-social","description":"Opt-in page-key adapter for Klevu v2 POST search JSON endpoints; defaults OFF and falls back cleanly to HTML/JSON-LD when disabled.","domains":["eucs15v2.ksearchnet.com"],"universalEngine":true,"auth_mode":"page-key","requires_page_key_opt_in":true,"exampleUrls":["https://eucs15v2.ksearchnet.com/cs/v2/search"],"routes":[{"match":{"hostSubdomain":{"suffix":".ksearchnet.com","param":"clusterHost"},"pathEquals":["/cs/v2/search"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","method":"POST","contentType":"application/json","requestBody":"{\"context\":{\"apiKeys\":[\"klevu-156925593843210765\"]},\"recordQueries\":[{\"id\":\"productList\",\"typeOfRequest\":\"SEARCH\",\"settings\":{\"query\":{\"term\":\"bag\"},\"limit\":10}}]}","requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"jsonMode":"klevu"}}],"htmlRoutes":[{"id":"klevu","match":{"exactSegments":false},"mode":"klevu_html"}]},{"id":"kroger","name":"Kroger Public Products API","category":"commerce-social","description":"Extracts Kroger product UPC/GTIN, brand, size, pricing, and fulfillment metadata via the official Kroger v1 Products API.","domains":["kroger.com","www.kroger.com","api.kroger.com"],"auth_mode":"key","exampleUrls":["https://api.kroger.com/v1/products/0001111085135","https://api.kroger.com/v1/products?filter.term=oats"],"routes":[{"match":{"hosts":["kroger.com","www.kroger.com"],"exactSegments":false,"pathSegments":["p",{"param":"slug","charset":"url_seg","maxLen":200},{"param":"upc","charset":"digits","minLen":8,"maxLen":14}]},"twin":{"fetchUrl":"https://api.kroger.com/v1/products/{upc}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"kroger_json"}},{"match":{"hosts":["api.kroger.com"],"pathPrefix":"/v1/products"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"kroger_json"}}]},{"id":"lang-registry-pack","name":"Language Registry Pack (pub.dev, CRAN, CocoaPods, Anaconda)","category":"developer","description":"Extracts package metadata and newest stable versions from Dart pub.dev, R CRAN HTML, CocoaPods HTML, and Anaconda/conda-forge API.","domains":["pub.dev","cran.r-project.org","cocoapods.org","anaconda.org","api.anaconda.org"],"auth_mode":"pub","exampleUrls":["https://pub.dev/packages/http","https://cocoapods.org/pods/Alamofire","https://anaconda.org/conda-forge/six"],"routes":[{"match":{"hosts":["pub.dev"],"pathPrefix":"/api/packages/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"pubdev_json"}},{"match":{"hosts":["pub.dev"],"exactSegments":false,"pathSegments":["packages",{"param":"pkg","charset":"pkg","minLen":1,"maxLen":120}]},"twin":{"fetchUrl":"https://pub.dev/api/packages/{pkg}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"pubdev_json"}},{"match":{"hosts":["api.anaconda.org"],"pathPrefix":"/package/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"anaconda_json"}},{"match":{"hosts":["anaconda.org"],"exactSegments":true,"reservedFirstSegment":["search","admin","download","static","api","login","signup","docs","pricing","about"],"pathSegments":[{"param":"channel","charset":"pkg","minLen":1,"maxLen":80},{"param":"pkg","charset":"pkg","minLen":1,"maxLen":120}]},"twin":{"fetchUrl":"https://api.anaconda.org/package/{channel}/{pkg}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"anaconda_json"}}],"htmlRoutes":[{"id":"lang-registry-pack","match":{"hosts":["cran.r-project.org"],"pathPrefix":"/web/packages/","exactSegments":false},"mode":"cran_html"},{"id":"lang-registry-pack","match":{"hosts":["cocoapods.org"],"pathPrefix":"/pods/","exactSegments":false},"mode":"cocoapods_html"}]},{"id":"laserfiche-weblink","name":"Laserfiche WebLink Public Document Portals","category":"public-records","description":"Universal Laserfiche WebLink adapter for city and county records portals. DocView.aspx and Browse.aspx links that carry id and repo (as WebLink share links do) upgrade to the anonymous JSON services the viewer itself calls: document name, folder path, template, created/modified dates, page count and metadata fields, or a folder listing with links. No cookies or login are used; the CookieCheck redirect only guards the HTML shell.","domains":["cc-publicdocs.santa-ana.org"],"universalEngine":true,"auth_mode":"pub","min_interval_ms":3000,"strict_robots":true,"exampleUrls":["https://cc-publicdocs.santa-ana.org/WebLink/DocView.aspx?id=82504&dbid=1&repo=Clerk","https://cc-publicdocs.santa-ana.org/WebLink/Browse.aspx?id=82479&dbid=1&repo=Clerk"],"routes":[{"match":{"exactSegments":true,"pathSegments":[{"param":"vdir","charset":"slug","minLen":2,"maxLen":40},"DocView.aspx"],"queryParams":[{"name":"id","param":"id","charset":"digits","minLen":1,"maxLen":12},{"name":"repo","param":"repo","charset":"slug","minLen":1,"maxLen":80}]},"twin":{"fetchUrl":"https://{host}/{vdir}/DocumentService.aspx/GetBasicDocumentInfo","kind":"json","accept":"application/json","method":"POST","contentType":"application/json","requestBody":"{\"repoName\":\"{repo}\",\"entryId\":{id}}","maxBytes":2097152},"extract":{"jsonMode":"laserfiche_doc_json"}},{"match":{"exactSegments":true,"pathSegments":[{"param":"vdir","charset":"slug","minLen":2,"maxLen":40},"Browse.aspx"],"queryParams":[{"name":"id","param":"id","charset":"digits","minLen":1,"maxLen":12},{"name":"repo","param":"repo","charset":"slug","minLen":1,"maxLen":80}]},"twin":{"fetchUrl":"https://{host}/{vdir}/FolderListingService.aspx/GetFolderListing2","kind":"json","accept":"application/json","method":"POST","contentType":"application/json","requestBody":"{\"repoName\":\"{repo}\",\"folderId\":{id},\"getNewListing\":true,\"start\":0,\"end\":50,\"sortColumn\":\"\",\"sortAscending\":true}","maxBytes":4194304},"extract":{"jsonMode":"laserfiche_folder_json"}}],"htmlRoutes":[{"id":"laserfiche-weblink","match":{"exactSegments":false},"mode":"laserfiche_missing_repo_html"}]},{"id":"legacy-cart","name":"Legacy Shopping Carts (OpenCart, nopCommerce, Shift4Shop, Volusion)","category":"commerce-social","description":"Extracts OpenCart, nopCommerce, Shift4Shop, and Volusion product JSON-LD, Microdata, and spec-table DOM while filtering template noise.","domains":["www.eurekagolf.co.uk","www.sturdybuiltonline.com","www.cctvcamerapros.com"],"universalEngine":true,"auth_mode":"html","exampleUrls":["https://www.eurekagolf.co.uk/oakley-standard-polo-shirt-pacific-blue","https://www.sturdybuiltonline.com/Steel-Diamond-Plate-Utility-Trailer-Fender-Single-Axle-10-in-x-32-in-x-13-in_p_215.html","https://www.cctvcamerapros.com/HDMI-to-USB-Converter-p/hdmi-u3.htm"],"htmlRoutes":[{"id":"legacy-cart","match":{"exactSegments":false},"mode":"legacy_cart_html"}]},{"id":"legistar","name":"Legistar Municipal Council Legislation & Meetings","category":"public-records","description":"Upgrades .legistar.com municipal council portals to the keyless webapi.legistar.com REST API for ordinances, resolutions, and meetings.","domains":["*.legistar.com"],"exampleUrls":["https://seattle.legistar.com/Legislation.aspx","https://seattle.legistar.com/Calendar.aspx"],"routes":[{"match":{"anyOf":[{"hostSubdomain":{"suffix":".legistar.com","param":"client","reserved":["www","webapi"]},"pathSuffix":"calendar.aspx","derivedParams":{"clientUpper":{"fromParam":"client","transform":"upper"}}},{"hostSubdomain":{"suffix":".legistar.com","param":"client","reserved":["www","webapi"]},"pathContainsSegment":"calendar","derivedParams":{"clientUpper":{"fromParam":"client","transform":"upper"}}}]},"twin":{"fetchUrl":"https://webapi.legistar.com/v1/{client}/events?$top=20&$orderby=EventDate%20desc","kind":"json","accept":"application/json"},"extract":{"wrapRootArrayAs":"items","requireAnyFields":["items"],"titleTemplate":"{clientUpper} Municipal Council — Recent Meetings (Legistar)","sections":[{"heading":"","arrayPath":"items","limit":20,"itemVars":{"agendaUrl":{"paths":["EventInSiteURL"],"requireHttps":true},"linkCell":{"template":"[Agenda]({agendaUrl})","whenVars":["agendaUrl"],"default":"-"}},"columns":[{"header":"Date","paths":["EventDate"],"sliceMax":10},{"header":"Body / Committee","paths":["EventBodyName"]},{"header":"Location","paths":["EventLocation"]},{"header":"Link","template":"{linkCell}"}]}]}},{"match":{"hostSubdomain":{"suffix":".legistar.com","param":"client","reserved":["www","webapi"]},"derivedParams":{"clientUpper":{"fromParam":"client","transform":"upper"}}},"twin":{"fetchUrl":"https://webapi.legistar.com/v1/{client}/matters?$top=25&$orderby=MatterIntroDate%20desc","kind":"json","accept":"application/json"},"extract":{"wrapRootArrayAs":"items","requireAnyFields":["items"],"titleTemplate":"{clientUpper} Municipal Legislation — Recent Matters (Legistar)","sections":[{"heading":"","arrayPath":"items","limit":25,"columns":[{"header":"File #","paths":["MatterFile"],"code":true},{"header":"Type","paths":["MatterTypeName"]},{"header":"Status","paths":["MatterStatusName"]},{"header":"Introduced","paths":["MatterIntroDate"],"sliceMax":10},{"header":"Title","paths":["MatterTitle","MatterName"]}]}]}}]},{"id":"libraries-io","name":"Libraries.io Package Metadata API","category":"developer","description":"Extracts cross-ecosystem package metadata, latest stable release, dependents, and repository signals via the official Libraries.io API (LIBRARIES_IO_API_KEY).","domains":["libraries.io"],"auth_mode":"key","exampleUrls":["https://libraries.io/api/npm/express"],"routes":[{"match":{"hosts":["libraries.io"],"pathPrefix":"/api/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"libraries_io_json"}},{"match":{"hosts":["libraries.io"],"exactSegments":false,"pathSegments":["npm",{"param":"scope","charset":"npm_scope","minLen":2,"maxLen":80},{"param":"pkg","charset":"npm_pkg","minLen":1,"maxLen":120}]},"twin":{"fetchUrl":"https://libraries.io/api/npm/{scope}%2F{pkg}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"libraries_io_json"}},{"match":{"hosts":["libraries.io"],"exactSegments":false,"pathSegments":[{"param":"platform","allowValues":["npm","pypi","rubygems","cargo","go","nuget","packagist","hex","maven","pub","cran","cocoapods","conda"]},{"param":"pkg","charset":"url_seg","minLen":1,"maxLen":160}]},"twin":{"fetchUrl":"https://libraries.io/api/{platform}/{pkg}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"libraries_io_json"}}]},{"id":"lightspeed-ecom","name":"Lightspeed eCom (C-Series)","category":"commerce-social","description":"Extracts Lightspeed eCom C-Series ?format=json product and collection twins plus custom-domain storefront HTML/companion discovery.","domains":["www.kayasieraden.nl"],"universalEngine":true,"auth_mode":"pub","min_interval_ms":2000,"exampleUrls":["https://www.kayasieraden.nl/nl/feestdagen-actie-gratis-armband.html","https://www.kayasieraden.nl/nl/feestdagen-actie-gratis-armband.html?format=json"],"routes":[{"match":{"hosts":["www.kayasieraden.nl"],"pathSuffix":".html"},"twin":{"fetchUrl":"{requestUrl}","setQueryParams":{"format":"json"},"kind":"json","accept":"application/json"},"extract":{"commerceMode":"lightspeed_ecom_json"}}],"htmlRoutes":[{"id":"lightspeed-ecom","match":{"exactSegments":false},"mode":"lightspeed_ecom_html"}]},{"id":"lobsters","name":"Lobste.rs Computing Stories","category":"commerce-social","description":"Upgrades lobste.rs/s/ story pages to their .json feed with nested plain-text comments.","domains":["lobste.rs"],"exampleUrls":["https://lobste.rs/s/abc123/zero_alloc_go_parsers"],"match":{"exactSegments":false,"pathSegments":["s",{"param":"shortId","charset":"alnum","minLen":4,"maxLen":12}]},"twin":{"fetchUrl":"https://lobste.rs/s/{shortId}.json","kind":"json","accept":"application/json"},"extract":{"requireFields":["title"],"vars":{"title":{"paths":["title"],"trim":true},"storyUrl":{"paths":["url"]},"score":{"paths":["score"],"default":"0"},"user":{"paths":["submitter_user"]},"created":{"paths":["created_at"]},"tags":{"paths":["tags"],"itemWrap":"`","join":", "},"descPlain":{"paths":["description_plain"],"trim":true}},"titleTemplate":"{title}","authorVar":"user","publishedTimeVar":"created","metaLine":[{"label":"Score","template":"{score}"},{"label":"By","template":"@{user}","whenVar":"user"},{"label":"Tags","template":"{tags}","whenVar":"tags"},{"label":"Link","template":"{storyUrl}","whenVar":"storyUrl"}],"introVar":"descPlain","sections":[{"heading":"Comments","listArrayPath":"comments","limit":40,"indentField":"indent_level","indentOffset":-1,"maxIndent":6,"itemTemplate":"**@{user}** ({score} pts): {body}","requireItemVar":"body","itemVars":{"user":{"paths":["commenting_user"],"default":"user"},"score":{"paths":["score"],"default":"0"},"body":{"paths":["comment_plain"],"trim":true}}}],"linksVars":["storyUrl"]}},{"id":"loc-gov","name":"Library of Congress (loc.gov)","category":"public-records","description":"Library of Congress JSON (?fo=json) adapter for items, resources, and collections (excluding Chronicling America and disallowed search paths).","domains":["loc.gov","www.loc.gov"],"auth_mode":"pub","min_interval_ms":5000,"strict_robots":true,"exampleUrls":["https://www.loc.gov/item/2014645520/","https://www.loc.gov/item/2014645520/?fo=json","https://www.loc.gov/resource/ds.05251/?fo=json"],"routes":[{"match":{"hosts":["loc.gov","www.loc.gov"],"exactSegments":false,"reservedFirstSegment":["chroniclingamerica","search","fedsearch","cgi-bin","web_arch","myloc","nationalfilmregistry"],"pathSegments":["item",{"param":"itemId","charset":"url_seg","minLen":2,"maxLen":80}]},"twin":{"fetchUrl":"https://www.loc.gov/item/{itemId}/?fo=json","kind":"json","accept":"application/json","maxBytes":4194304,"auth_mode":"pub"},"extract":{"jsonMode":"loc_gov_json"}},{"match":{"hosts":["loc.gov","www.loc.gov"],"exactSegments":false,"reservedFirstSegment":["chroniclingamerica","search","fedsearch","cgi-bin","web_arch","myloc","nationalfilmregistry"],"pathSegments":["resource",{"param":"resourceId","charset":"url_seg","minLen":2,"maxLen":120}]},"twin":{"fetchUrl":"https://www.loc.gov/resource/{resourceId}/?fo=json","kind":"json","accept":"application/json","maxBytes":4194304,"auth_mode":"pub"},"extract":{"jsonMode":"loc_gov_json"}},{"match":{"hosts":["loc.gov","www.loc.gov"],"exactSegments":false,"reservedFirstSegment":["chroniclingamerica","search","fedsearch","cgi-bin","web_arch","myloc","nationalfilmregistry"],"pathSegments":["collections",{"param":"collectionId","charset":"alnum_dash","reserved":["chronicling-america"],"minLen":2,"maxLen":100}]},"twin":{"fetchUrl":"https://www.loc.gov/collections/{collectionId}/?fo=json","kind":"json","accept":"application/json","maxBytes":4194304,"auth_mode":"pub"},"extract":{"jsonMode":"loc_gov_json"}}],"htmlRoutes":[{"id":"loc-gov","match":{"anyOf":[{"hosts":["loc.gov","www.loc.gov"],"pathPrefix":"/item/"},{"hosts":["loc.gov","www.loc.gov"],"pathPrefix":"/resource/"},{"hosts":["loc.gov","www.loc.gov"],"exactSegments":false,"pathSegments":["collections",{"param":"collectionId","charset":"alnum_dash","reserved":["chronicling-america"],"minLen":2,"maxLen":100}]}]},"mode":"loc_gov_html"}]},{"id":"mastodon-status","name":"Mastodon & Fediverse Statuses (Universal Engine)","category":"commerce-social","description":"Upgrades Fediverse status permalinks (/@/) on any Mastodon instance to /api/v1/statuses/ JSON.","domains":["mastodon.social","fosstodon.org","hachyderm.io"],"universalEngine":true,"exampleUrls":["https://fosstodon.org/@realpython/117694898741277050"],"match":{"excludeHosts":["medium.com","*.medium.com","tiktok.com","*.tiktok.com","threads.net","*.threads.net"],"exactSegments":true,"pathSegments":[{"param":"userHandle","charset":"at_handle"},{"param":"statusId","charset":"digits","minLen":15,"maxLen":24}]},"twin":{"id":"mastodon-status","fetchUrl":"https://{host}/api/v1/statuses/{statusId}","kind":"json","accept":"application/json"},"extract":{"requireFields":["content","account.acct"],"vars":{"acct":{"paths":["account.acct"]},"displayName":{"paths":["account.display_name"],"fallbackTemplate":"{acct}"},"createdAt":{"paths":["created_at"]},"spoiler":{"paths":["spoiler_text"],"trim":true},"body":{"paths":["content"],"format":"html_to_md"}},"titleTemplate":"{displayName} (@{acct}@{host})","authorTemplate":"@{acct}@{host}","publishedTimeVar":"createdAt","blockquoteTemplate":"> [!NOTE]\n> **Content Note**: {spoiler}","blockquoteWhenVar":"spoiler","bodyVar":"body","sections":[{"heading":"","listArrayPath":"media_attachments","limit":16,"requireItemVar":"mediaDesc","itemVars":{"mediaDesc":{"paths":["description"],"trim":true}},"itemTemplate":"*Media description*: {mediaDesc}"}]}},{"id":"maven-central","name":"Maven Central","category":"developer","description":"Upgrades central.sonatype.com/artifact//[/] pages to the keyless Maven Central Solr JSON API (central.sonatype.com for versioned artifacts, search.maven.org for artifact summaries) with Maven/Gradle coordinates and artifact metadata.","domains":["central.sonatype.com"],"exampleUrls":["https://central.sonatype.com/artifact/com.fasterxml.jackson.core/jackson-databind","https://central.sonatype.com/artifact/com.fasterxml.jackson.core/jackson-databind/2.18.2"],"routes":[{"match":{"exactSegments":true,"pathSegments":["artifact",{"param":"g","charset":"pkg","minLen":1,"maxLen":160},{"param":"a","charset":"pkg","minLen":1,"maxLen":160},{"param":"v","charset":"pkg","reserved":["versions","overview","dependencies","dependents","jar"],"minLen":1,"maxLen":80}]},"twin":{"fetchUrl":"https://central.sonatype.com/solrsearch/select?q=g:{g}+AND+a:{a}+AND+v:{v}&core=gav&rows=20&wt=json","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"rootPath":"response.docs.0","requireFields":["id","g","a"],"vars":{"groupId":{"paths":["g"]},"artifactId":{"paths":["a"]},"ver":{"paths":["v","latestVersion"]},"packaging":{"paths":["p"]},"published":{"paths":["timestamp"],"format":"epoch_ms_date"},"artifacts":{"paths":["ec"],"itemWrap":"`","join":", ","limit":12},"centralUrl":{"template":"https://central.sonatype.com/artifact/{groupId}/{artifactId}/{ver}","requireHttps":true}},"titleTemplate":"{groupId}:{artifactId}:{ver} (Maven Central)","publishedTimeVar":"published","bullets":[{"label":"Maven Coordinate","template":"`{groupId}:{artifactId}:{ver}`"},{"label":"Gradle","template":"`implementation(\"{groupId}:{artifactId}:{ver}\")`"},{"label":"Packaging","template":"{packaging}","whenVar":"packaging"},{"label":"Published","template":"{published}","whenVar":"published"},{"label":"Classifiers / Files","template":"{artifacts}","whenVar":"artifacts"}],"linksVars":["centralUrl"]}},{"match":{"exactSegments":true,"pathSegments":["artifact",{"param":"g","charset":"pkg","minLen":1,"maxLen":160},{"param":"a","charset":"pkg","minLen":1,"maxLen":160}]},"twin":{"fetchUrl":"https://search.maven.org/solrsearch/select?q=g:{g}+AND+a:{a}&rows=20&wt=json","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"rootPath":"response.docs.0","requireFields":["id","g","a"],"vars":{"groupId":{"paths":["g"]},"artifactId":{"paths":["a"]},"ver":{"paths":["latestVersion","v"]},"packaging":{"paths":["p"]},"versionCount":{"paths":["versionCount"],"format":"int_comma"},"published":{"paths":["timestamp"],"format":"epoch_ms_date"},"artifacts":{"paths":["ec"],"itemWrap":"`","join":", ","limit":12},"centralUrl":{"template":"https://central.sonatype.com/artifact/{groupId}/{artifactId}","requireHttps":true}},"titleTemplate":"{groupId}:{artifactId}:{ver} (Maven Central)","titleWhenVar":"ver","titleFallbackTemplate":"{groupId}:{artifactId} (Maven Central)","publishedTimeVar":"published","bullets":[{"label":"Maven Coordinate","template":"`{groupId}:{artifactId}:{ver}`","whenVar":"ver"},{"label":"Gradle","template":"`implementation(\"{groupId}:{artifactId}:{ver}\")`","whenVar":"ver"},{"label":"Packaging","template":"{packaging}","whenVar":"packaging"},{"label":"Published","template":"{published}","whenVar":"published"},{"label":"Versions","template":"{versionCount}","whenVar":"versionCount"},{"label":"Classifiers / Files","template":"{artifacts}","whenVar":"artifacts"}],"linksVars":["centralUrl"]}}]},{"id":"mcp-directories","name":"Community MCP Directories (Smithery, Glama, PulseMCP)","category":"developer","description":"Extracts community MCP directory listings from Smithery Registry API and public Glama/PulseMCP HTML pages, tagging every record trustTier=community, untrusted=true.","domains":["smithery.ai","registry.smithery.ai","glama.ai","pulsemcp.com","www.pulsemcp.com"],"auth_mode":"pub","exampleUrls":["https://registry.smithery.ai/servers?pageSize=5","https://www.pulsemcp.com/servers?q=github","https://glama.ai/mcp/servers?query=github"],"routes":[{"match":{"hosts":["registry.smithery.ai"],"pathPrefix":"/servers"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"smithery_registry_json"}},{"match":{"hosts":["smithery.ai"],"exactSegments":true,"pathSegments":["server",{"param":"ns","charset":"pkg","minLen":1,"maxLen":80},{"param":"slug","charset":"url_seg","minLen":1,"maxLen":120}]},"twin":{"fetchUrl":"https://registry.smithery.ai/servers/{ns}/{slug}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"smithery_registry_json"}},{"match":{"hosts":["smithery.ai"],"exactSegments":true,"pathSegments":["server",{"param":"slug","charset":"url_seg","minLen":1,"maxLen":120}]},"twin":{"fetchUrl":"https://registry.smithery.ai/servers/{slug}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"smithery_registry_json"}}],"htmlRoutes":[{"id":"mcp-directories","match":{"hosts":["glama.ai"],"pathPrefix":"/mcp/servers","exactSegments":false},"mode":"mcp_directory_html"},{"id":"mcp-directories","match":{"hosts":["pulsemcp.com","www.pulsemcp.com"],"pathPrefix":"/servers","exactSegments":false},"mode":"mcp_directory_html"},{"id":"mcp-directories","match":{"hosts":["smithery.ai"],"exactSegments":false},"mode":"mcp_directory_html"}]},{"id":"mcp-registry","name":"Official Model Context Protocol (MCP) Registry","category":"developer","description":"Extracts official MCP server listings, remotes, and packages from registry.modelcontextprotocol.io tagged trustTier=official, untrusted=false.","domains":["registry.modelcontextprotocol.io"],"auth_mode":"pub","exampleUrls":["https://registry.modelcontextprotocol.io/v0/servers?limit=5"],"routes":[{"match":{"hosts":["registry.modelcontextprotocol.io"],"anyOf":[{"pathPrefix":"/v0/"},{"pathPrefix":"/v0.1/"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"mcp_registry_json"}}]},{"id":"mediawiki","name":"Wikipedia & MediaWiki Encyclopedias","category":"commerce-social","description":"Robots-compliant Wikipedia & MediaWiki adapter: strips [ ], Edit links, [n] citation markers, [edit], and navigation chrome with 24h article caching; pair with search({ query, wikipedia: true, lang }) for Special:Search-free article discovery and Wikimedia Enterprise or dumps.wikimedia.org for bulk corpus access.","domains":["*.wikipedia.org","wiki.archlinux.org"],"universalEngine":true,"exampleUrls":["https://en.wikipedia.org/wiki/HTTP/2"],"htmlRoutes":[{"id":"mediawiki","match":{"exactSegments":false},"mode":"markdown_clean","cleanPreset":"mediawiki"}]},{"id":"medium","name":"Medium","category":"commerce-social","description":"Extracts Medium ?format=json responses with linear anti-XSSI prefix stripping, Medium RSS feeds, and Medium article HTML.","domains":["medium.com"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://medium.com/p/62edea66ffa4?format=json","https://medium.com/@medium/updating-our-rules-june-2023-62edea66ffa4","https://medium.com/feed/@medium"],"routes":[{"match":{"hosts":["medium.com"],"exactSegments":false,"queryParams":[{"name":"format","param":"fmt","allowValues":["json"]}]},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"application/json"},"extract":{"textMode":"medium_xssi_json"}},{"match":{"hosts":["medium.com"],"exactSegments":true,"pathSegments":["p",{"param":"postId","charset":"alnum","minLen":8,"maxLen":20}]},"twin":{"fetchUrl":"https://medium.com/p/{postId}?format=json","kind":"text","accept":"application/json"},"extract":{"textMode":"medium_xssi_json"}},{"match":{"hosts":["medium.com"],"exactSegments":true,"pathSegments":[{"param":"userHandle","charset":"at_handle","minLen":2,"maxLen":80},{"param":"slugId","charset":"slug","minLen":10,"maxLen":200}]},"twin":{"fetchUrl":"{requestUrl}","setQueryParams":{"format":"json"},"kind":"text","accept":"application/json"},"extract":{"textMode":"medium_xssi_json"}},{"match":{"hosts":["medium.com"],"pathPrefix":"/feed/","exactSegments":false},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"application/rss+xml"},"extract":{"textMode":"medium_rss_xml"}}],"htmlRoutes":[{"id":"medium","match":{"exactSegments":false},"mode":"medium_html"}]},{"id":"medlineplus","name":"NLM MedlinePlus","category":"research-health","description":"MedlinePlus Health Topics XML web service, MedlinePlus Connect JSON API, and medlineplus.gov topic HTML extractor.","domains":["medlineplus.gov","www.medlineplus.gov","wsearch.nlm.nih.gov","connect.medlineplus.gov"],"auth_mode":"pub","exampleUrls":["https://wsearch.nlm.nih.gov/ws/query?db=healthTopics&term=diabetes&retmax=2","https://medlineplus.gov/diabetes.html"],"routes":[{"match":{"hosts":["wsearch.nlm.nih.gov"],"pathEquals":["/ws/query"]},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"text/xml","maxBytes":2097152},"extract":{"textMode":"medlineplus_xml"}},{"match":{"hosts":["connect.medlineplus.gov"],"pathEquals":["/service"]},"twin":{"fetchUrl":"{requestUrl}","setQueryParams":{"knowledgeResponseType":"application/json"},"kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"medlineplus_connect_json"}}],"htmlRoutes":[{"id":"medlineplus","match":{"hosts":["medlineplus.gov","www.medlineplus.gov"],"exactSegments":false},"mode":"medlineplus_html"}]},{"id":"medusa","name":"Medusa Storefront & Store API","category":"commerce-social","description":"Opt-in page-key adapter for Medusa /store/products API twins with Next.js RSC, JSON-LD, and DOM storefront HTML fallback when disabled.","domains":["next.medusajs.com","www.mattsleeps.com"],"universalEngine":true,"auth_mode":"page-key","requires_page_key_opt_in":true,"exampleUrls":["https://next.medusajs.com/dk/products/hoodie","https://www.mattsleeps.com/en/beds"],"routes":[{"match":{"optionalLeadingLocale":true,"exactSegments":true,"pathSegments":["store","products"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"commerceMode":"medusa_product"}},{"match":{"optionalLeadingLocale":true,"pathSegments":["store","products",{"param":"id","charset":"url_seg","minLen":1,"maxLen":160}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"commerceMode":"medusa_product"}}],"htmlRoutes":[{"id":"medusa","match":{"exactSegments":false},"mode":"medusa_html"}]},{"id":"meetup-luma","name":"Meetup & Luma Events","category":"commerce-social","description":"Extracts event title, schedule, venue/location, organizer, and description from Meetup and Luma (lu.ma / luma.com) via Schema.org Event JSON-LD and __NEXT_DATA__ hydration.","domains":["meetup.com","www.meetup.com","lu.ma","www.lu.ma","luma.com","www.luma.com"],"auth_mode":"html","exampleUrls":["https://www.meetup.com/lawofattractioncentre/events/317269557/","https://luma.com/8jye50v0"],"htmlRoutes":[{"id":"meetup-luma","match":{"exactSegments":false},"mode":"meetup_luma_html"}]},{"id":"midmarket-career-portals","name":"Mid-Market Career Portals (Paycom, Paycor, ADP)","category":"jobs","description":"Extracts structured open roles from Paycom (/v4/ats/web.php/portal/ & /api/ats/job-postings/), ADP Workforce Now (/mascsr/default/careercenter/), and public Paycor career pages.","domains":["pc00.paycomonline.com","www.paycomonline.net","workforcenow.adp.com","recruiting.adp.com","www.paycor.com"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://workforcenow.adp.com/mascsr/default/careercenter/public/events/staffing/v1/job-requisitions?cid=7a48330e-b9d5-4122-9051-71a47afa46d5"],"routes":[{"match":{"hostSubdomain":{"suffix":".paycomonline.net","param":"tenant","reserved":["login","auth","static","assets"]},"pathPrefix":"/api/ats/job-postings/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"paycom_json"}},{"match":{"hostSubdomain":{"suffix":".paycomonline.com","param":"tenant","reserved":["login","auth","static","assets"]},"pathPrefix":"/api/ats/job-postings/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"paycom_json"}},{"match":{"hosts":["workforcenow.adp.com","recruiting.adp.com"],"pathPrefix":"/mascsr/default/careercenter/public/events/staffing/v1/job-requisitions"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"adp_wfn_json"}}],"htmlRoutes":[{"id":"midmarket-career-portals","mode":"midmarket_career_html","match":{"excludeHosts":["recruiting.ultipro.com","recruiting.paylocity.com","app.dover.com","jobs.dover.com","jobs.smartrecruiters.com","*.oraclecloud.com","jobs.jobvite.com","recruitingbypaycor.com"],"anyOf":[{"hostSubdomain":{"suffix":".paycomonline.net","param":"tenant","reserved":["login","auth","static","assets"]},"pathPrefix":"/v4/ats/web.php/portal/"},{"hostSubdomain":{"suffix":".paycomonline.com","param":"tenant","reserved":["login","auth","static","assets"]},"pathPrefix":"/v4/ats/web.php/portal/"},{"hosts":["workforcenow.adp.com","recruiting.adp.com"],"exactSegments":false},{"hosts":["www.paycor.com"],"pathPrefix":"/company/careers","exactSegments":false}]}}]},{"id":"mlb-statsapi","name":"MLB Stats API","category":"commerce-social","description":"Extracts public MLB schedule, team, game linescore, standings, and player data from statsapi.mlb.com JSON endpoints with mlb.com HTML/JSON-LD fallback.","domains":["statsapi.mlb.com","mlb.com","www.mlb.com"],"auth_mode":"pub","exampleUrls":["https://statsapi.mlb.com/api/v1/schedule?sportId=1&date=2024-10-30","https://statsapi.mlb.com/api/v1/teams/119","https://statsapi.mlb.com/api/v1/game/775296/linescore","https://www.mlb.com/dodgers"],"routes":[{"match":{"hosts":["statsapi.mlb.com"],"anyOf":[{"pathPrefix":"/api/v1/schedule"},{"pathPrefix":"/api/v1/teams"},{"pathPrefix":"/api/v1/game/"},{"pathPrefix":"/api/v1/standings"},{"pathPrefix":"/api/v1/people"}],"exactSegments":false},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"mlb_statsapi_json"}}],"htmlRoutes":[{"id":"mlb-statsapi","mode":"mlb_statsapi_html","match":{"hosts":["mlb.com","www.mlb.com"],"exactSegments":false}}]},{"id":"model-hub-pack","name":"Model Hub Pack (Replicate & Civitai)","category":"genai","description":"Extracts ML model metadata, versions, hardware, and descriptions from Replicate and Civitai SSR/Next.js HTML pages while honoring robots.txt.","domains":["replicate.com","www.replicate.com","civitai.com","www.civitai.com"],"auth_mode":"pub","exampleUrls":["https://replicate.com/meta/meta-llama-3-8b-instruct","https://civitai.com/models/4201/realistic-vision-v60-b1"],"htmlRoutes":[{"id":"model-hub-pack","match":{"hosts":["replicate.com","www.replicate.com"],"exactSegments":false},"mode":"replicate_html"},{"id":"model-hub-pack","match":{"hosts":["civitai.com","www.civitai.com"],"exactSegments":false},"mode":"civitai_html"}]},{"id":"modern-community-pack","name":"Modern Community Pack","category":"commerce-social","description":"Extracts community discussions, authors, and timestamps from Higher Logic, Bettermode (rendered SSR DOM only), and Circle HTML while rejecting soft-404s and empty shells.","domains":["community.broadcom.com","community.flutterflow.io","community.xano.com"],"universalEngine":true,"auth_mode":"html","exampleUrls":["https://community.broadcom.com/vmware-cloud-foundation/discussion/black-screen-after-upgrading-opensuse-leap-16-0-to-16-1-disabling-vmware-graphics-driver-restores-desktop","https://community.flutterflow.io/discussions/post/how-to-build-a-browser-based-instagram-story-viewer-with-flutterflow-lldyNB3IG314wPU","https://community.xano.com/ask-the-community/post/api-cache-bug-0GJQtNpHlTb471k"],"htmlRoutes":[{"id":"modern-community-pack","match":{"exactSegments":false},"mode":"modern_community_pack_html"}]},{"id":"municode","name":"Municode Municipal Codes","category":"public-records","description":"Municode API JSON and municipal code library HTML adapter for city and county ordinances.","domains":["library.municode.com","api.municode.com"],"auth_mode":"pub","exampleUrls":["https://library.municode.com/tx/austin/codes/code_of_ordinances","https://api.municode.com/States"],"routes":[{"match":{"hosts":["api.municode.com"],"pathPrefix":"/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"municode_json"}}],"htmlRoutes":[{"id":"municode","match":{"hosts":["library.municode.com"],"exactSegments":false},"mode":"municode_html"}]},{"id":"nasa-apis","name":"NASA Open APIs & Image Library","category":"research-health","description":"NASA api.nasa.gov (APOD, NeoWs, EPIC with DEMO_KEY fallback or configured NASA_API_KEY) and keyless images-api.nasa.gov search.","domains":["api.nasa.gov","images-api.nasa.gov"],"auth_mode":"key","exampleUrls":["https://api.nasa.gov/neo/rest/v1/feed/today?detailed=false","https://api.nasa.gov/planetary/apod?date=2024-07-04","https://images-api.nasa.gov/search?q=apollo+11&page_size=2"],"routes":[{"match":{"hosts":["api.nasa.gov"],"anyOf":[{"pathPrefix":"/planetary/apod"},{"pathPrefix":"/neo/"},{"pathPrefix":"/EPIC/"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":4194304},"extract":{"jsonMode":"nasa_apis_json"}},{"match":{"hosts":["images-api.nasa.gov"],"anyOf":[{"pathPrefix":"/search"},{"pathPrefix":"/asset/"},{"pathPrefix":"/metadata/"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"pub","maxBytes":4194304},"extract":{"jsonMode":"nasa_apis_json"}}]},{"id":"national-archives","name":"U.S. National Archives (NARA Catalog)","category":"public-records","description":"National Archives and Records Administration (NARA) Catalog API v2 adapter (catalog.archives.gov/api/v2) with HTML fallback.","domains":["catalog.archives.gov"],"auth_mode":"key","min_interval_ms":1000,"exampleUrls":["https://catalog.archives.gov/api/v2/records/search?q=constitution","https://catalog.archives.gov/id/1667751"],"routes":[{"match":{"hosts":["catalog.archives.gov"],"pathPrefix":"/api/v2/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"key"},"extract":{"jsonMode":"national_archives_json"}},{"match":{"hosts":["catalog.archives.gov"],"exactSegments":false,"pathSegments":["id",{"param":"naId","charset":"digits","minLen":1,"maxLen":20}]},"twin":{"fetchUrl":"https://catalog.archives.gov/api/v2/records/search?naId={naId}","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"key"},"extract":{"jsonMode":"national_archives_json"}}],"htmlRoutes":[{"id":"national-archives","match":{"hosts":["catalog.archives.gov"],"exactSegments":false},"mode":"national_archives_html"}]},{"id":"ncaa-espn","name":"NCAA & ESPN","category":"commerce-social","description":"Extracts NCAA and ESPN sports articles, scoreboards, standings, and public sports API JSON plus HTML JSON-LD and __espnfitt__ / turner_metadata hydration.","domains":["ncaa.com","www.ncaa.com","espn.com","www.espn.com","site.api.espn.com","sports.core.api.espn.com","site.web.api.espn.com","data.ncaa.com","sdataprod.ncaa.com"],"auth_mode":"pub","strict_robots":true,"exampleUrls":["https://www.espn.com/mlb/story/_/id/50328768/free-agency-tracker-offseason-trades-moves-2026-2027","https://www.espn.com/nfl/scoreboard","https://www.ncaa.com/news/football/article/2026-11-25/4-games-storylines-rivalry-week-could-impact-college-football-playoff-bracket","https://sports.core.api.espn.com/v2/sports/football/leagues/nfl"],"routes":[{"match":{"hosts":["sports.core.api.espn.com"],"pathPrefix":"/v2/sports/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"ncaa_espn_json"}},{"match":{"hosts":["site.web.api.espn.com"],"pathPrefix":"/apis/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"ncaa_espn_json"}},{"match":{"hosts":["site.api.espn.com"],"pathPrefix":"/apis/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"ncaa_espn_json"}},{"match":{"hosts":["data.ncaa.com"],"pathPrefix":"/cas/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"ncaa_espn_json"}}],"htmlRoutes":[{"id":"ncaa-espn","match":{"hosts":["espn.com","www.espn.com","ncaa.com","www.ncaa.com"]},"mode":"ncaa_espn_html"}]},{"id":"nces-ipeds","name":"NCES IPEDS & Urban Institute Education Data","category":"public-records","description":"NCES IPEDS and Digest of Education Statistics HTML adapter with Urban Institute Education Data API JSON support (strict robots).","domains":["nces.ed.gov","educationdata.urban.org"],"auth_mode":"pub","strict_robots":true,"min_interval_ms":1000,"exampleUrls":["https://nces.ed.gov/ipeds/use-the-data","https://nces.ed.gov/programs/digest/current_tables.asp"],"routes":[{"match":{"hosts":["educationdata.urban.org"],"exactSegments":false,"pathPrefix":"/api/v1/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"pub"},"extract":{"jsonMode":"nces_ipeds_json"}}],"htmlRoutes":[{"id":"nces-ipeds","match":{"hosts":["nces.ed.gov","educationdata.urban.org"],"exactSegments":false},"mode":"nces_ipeds_html"}]},{"id":"ncua-credit-unions","name":"NCUA Credit Union Lookup","category":"finance","description":"Extracts NCUA credit union details and call report pages with strict robots.txt enforcement (honoring mapping.ncua.gov Disallow /) and ncua.gov HTML fallback.","domains":["mapping.ncua.gov","ncua.gov","www.ncua.gov"],"auth_mode":"pub","strict_robots":true,"exampleUrls":["https://ncua.gov/analysis/credit-union-corporate-call-report-data","https://mapping.ncua.gov/CreditUnionDetails/60006"],"routes":[{"match":{"hosts":["mapping.ncua.gov"],"exactSegments":false,"pathSegments":["CreditUnionDetails",{"param":"charter","charset":"digits","minLen":1,"maxLen":12}]},"twin":{"fetchUrl":"https://mapping.ncua.gov/api/CreditUnionDetails/{charter}","kind":"json","accept":"application/json","auth_mode":"pub","maxBytes":2097152},"extract":{"jsonMode":"ncua_json"}},{"match":{"hosts":["mapping.ncua.gov"],"pathPrefix":"/api/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"pub","maxBytes":2097152},"extract":{"jsonMode":"ncua_json"}}],"htmlRoutes":[{"id":"ncua-credit-unions","match":{"hosts":["ncua.gov","www.ncua.gov","mapping.ncua.gov"],"exactSegments":false},"mode":"ncua_html"}]},{"id":"newsletter-archives","name":"Newsletter Archives (Beehiiv / Ghost / Buttondown / Kit)","category":"commerce-social","description":"Extracts Ghost Content API posts, scoped Beehiiv/Ghost/Buttondown RSS feeds, and newsletter archive HTML pages.","domains":["ghost.org","buttondown.com","rss.beehiiv.com","aibrews.beehiiv.com"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://ghost.org/changelog/rss/","https://ghost.org/changelog/","https://buttondown.com/hillelwayne/rss","https://aibrews.beehiiv.com/"],"routes":[{"match":{"pathPrefix":"/ghost/api/content/posts","exactSegments":false},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"newsletter_ghost_json"}},{"match":{"hosts":["rss.beehiiv.com"],"exactSegments":false},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"application/rss+xml"},"extract":{"textMode":"newsletter_rss_xml"}},{"match":{"hosts":["buttondown.com"],"exactSegments":true,"pathSegments":[{"param":"pub","charset":"slug","minLen":1,"maxLen":80},"rss"]},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"application/rss+xml"},"extract":{"textMode":"newsletter_rss_xml"}},{"match":{"hosts":["ghost.org"],"pathEquals":["/changelog/rss","/changelog/rss/"]},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"application/rss+xml"},"extract":{"textMode":"newsletter_rss_xml"}},{"match":{"hostSubdomain":{"suffix":".beehiiv.com","param":"pub"},"pathEquals":["/feed","/rss"]},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"application/rss+xml"},"extract":{"textMode":"newsletter_rss_xml"}},{"match":{"hostSubdomain":{"suffix":".ghost.io","param":"pub"},"pathEquals":["/rss","/rss/","/feed","/feed/"]},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"application/rss+xml"},"extract":{"textMode":"newsletter_rss_xml"}}],"htmlRoutes":[{"id":"newsletter-archives","match":{"exactSegments":false},"mode":"newsletter_archives_html"}]},{"id":"newswire-pack","name":"Newswire Pack (PR Newswire / Business Wire / GlobeNewswire)","category":"commerce-social","description":"Extracts PR Newswire, Business Wire, and GlobeNewswire RSS feeds and NewsArticle HTML press releases.","domains":["www.prnewswire.com","prnewswire.com","www.businesswire.com","businesswire.com","www.globenewswire.com","globenewswire.com"],"auth_mode":"pub","exampleUrls":["https://www.prnewswire.com/rss/news-releases-list.rss","https://www.prnewswire.com/news-releases/binance-secures-in-principle-approval-in-gelephu-mindfulness-city-plans-asia-hub-in-bhutan-302951995.html"],"routes":[{"match":{"anyOf":[{"pathPrefix":"/rss/"},{"pathPrefix":"/RssFeed/"},{"pathPrefix":"/feed/"},{"pathSuffix":".rss"}],"exactSegments":false},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"application/rss+xml"},"extract":{"textMode":"newswire_rss_xml"}}],"htmlRoutes":[{"id":"newswire-pack","match":{"exactSegments":false},"mode":"newswire_html"}]},{"id":"nfpa","name":"NFPA Standards & Codes (www.nfpa.org)","category":"public-records","description":"Unpacks Sitecore JSS __NEXT_DATA__ storefront-main placeholders (PageTitle, ContentBlock, SplitScreenCalloutComponent, Accordion, TwoColumnVideo) on www.nfpa.org without headless browser rendering, never touching link.nfpa.org or robots-disallowed /en/ and /-/media/.","domains":["www.nfpa.org"],"exampleUrls":["https://www.nfpa.org/codes-and-standards/nfpa-70-standard-development/70","https://www.nfpa.org/for-professionals/codes-and-standards/list-of-codes-and-standards/free-access"],"htmlRoutes":[{"id":"nfpa","mode":"sitecore_jss_html","match":{"exactSegments":false,"reservedFirstSegment":["-","ar","en","data","standard_items"]}}]},{"id":"nhl-api","name":"NHL Web API","category":"commerce-social","description":"Extracts public NHL standings, schedule, club stats, and gamecenter landing JSON from api-web.nhle.com with nhl.com HTML/JSON-LD fallback.","domains":["api-web.nhle.com","nhl.com","www.nhl.com"],"auth_mode":"pub","exampleUrls":["https://api-web.nhle.com/v1/standings/now","https://api-web.nhle.com/v1/schedule/now","https://api-web.nhle.com/v1/club-stats/TOR/now","https://api-web.nhle.com/v1/gamecenter/2024020001/landing"],"routes":[{"match":{"hosts":["api-web.nhle.com"],"anyOf":[{"pathPrefix":"/v1/standings"},{"pathPrefix":"/v1/schedule"},{"pathPrefix":"/v1/club-stats/"},{"pathPrefix":"/v1/gamecenter/"},{"pathPrefix":"/v1/player/"},{"pathPrefix":"/v1/roster/"}],"exactSegments":false},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"nhl_api_json"}}],"htmlRoutes":[{"id":"nhl-api","mode":"nhl_api_html","match":{"hosts":["nhl.com","www.nhl.com"],"exactSegments":false}}]},{"id":"nhtsa-vpic-recalls","name":"NHTSA vPIC & Safety Recalls API","category":"public-records","description":"Formats keyless vpic.nhtsa.dot.gov VIN decode and api.nhtsa.gov vehicle recalls & complaints JSON endpoints into structured Markdown tables (respecting HTTP 403/robots.txt without bypass).","domains":["vpic.nhtsa.dot.gov","api.nhtsa.gov"],"exampleUrls":["https://vpic.nhtsa.dot.gov/api/vehicles/decodevinvalues/1HGCM82633A004352?format=json","https://api.nhtsa.gov/recalls/recallsByVehicle?make=honda&model=accord&modelYear=2020"],"routes":[{"match":{"hosts":["vpic.nhtsa.dot.gov"],"exactSegments":true,"pathSegments":["api","vehicles",{"param":"endpoint","allowValues":["decodevinvalues","decodevinvaluesextended"]},{"param":"vin","charset":"alnum","minLen":3,"maxLen":32}]},"twin":{"fetchUrl":"https://vpic.nhtsa.dot.gov/api/vehicles/{endpoint}/{vin}?format=json","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"requireAnyFields":["Results","Message"],"vars":{"vinOut":{"paths":["Results.0.VIN"],"fallbackTemplate":"{vin}"},"make":{"paths":["Results.0.Make"],"trim":true},"model":{"paths":["Results.0.Model"],"trim":true},"modelYear":{"paths":["Results.0.ModelYear"],"trim":true},"vehicleType":{"paths":["Results.0.VehicleType"],"trim":true},"bodyClass":{"paths":["Results.0.BodyClass"],"trim":true},"plantCountry":{"paths":["Results.0.PlantCountry"],"trim":true},"engineCylinders":{"paths":["Results.0.EngineCylinders"],"trim":true},"displacementL":{"paths":["Results.0.DisplacementL"],"trim":true},"fuelType":{"paths":["Results.0.FuelTypePrimary"],"trim":true},"errorCode":{"paths":["Results.0.ErrorCode"],"trim":true},"errorText":{"paths":["Results.0.ErrorText"],"trim":true},"message":{"paths":["Message"],"trim":true}},"titleTemplate":"{modelYear} {make} {model} — VIN {vinOut}","titleWhenVar":"make","titleFallbackTemplate":"NHTSA vPIC VIN Decode ({vinOut})","bullets":[{"label":"VIN","template":"`{vinOut}`"},{"label":"Make","template":"{make}","whenVar":"make"},{"label":"Model","template":"{model}","whenVar":"model"},{"label":"Model Year","template":"{modelYear}","whenVar":"modelYear"},{"label":"Vehicle Type","template":"{vehicleType}","whenVar":"vehicleType"},{"label":"Body Class","template":"{bodyClass}","whenVar":"bodyClass"},{"label":"Plant Country","template":"{plantCountry}","whenVar":"plantCountry"},{"label":"Engine Cylinders","template":"{engineCylinders}","whenVar":"engineCylinders"},{"label":"Displacement (L)","template":"{displacementL}","whenVar":"displacementL"},{"label":"Fuel Type","template":"{fuelType}","whenVar":"fuelType"},{"label":"Error Code","template":"`{errorCode}`","whenVar":"errorCode"},{"label":"Error Text","template":"{errorText}","whenVar":"errorText"},{"label":"Message","template":"{message}","whenVar":"message"}]}},{"match":{"hosts":["api.nhtsa.gov"],"pathEquals":["/recalls/recallsByVehicle","/recalls/recallsByVehicle/"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"requireAnyFields":["results","Results"],"vars":{"count":{"paths":["Count","count"],"format":"int_comma","default":"0"},"message":{"paths":["Message","message"],"trim":true}},"titleTemplate":"NHTSA Vehicle Recalls ({count} found)","introVar":"message","sections":[{"heading":"Recalls","arrayPath":"results","limit":50,"emptyText":"No recalls found.","columns":[{"header":"Campaign","paths":["NHTSACampaignNumber"],"code":true},{"header":"Date","paths":["ReportReceivedDate"]},{"header":"Component","paths":["Component"]},{"header":"Summary","paths":["Summary"],"sliceMax":240},{"header":"Consequence","paths":["Consequence"],"sliceMax":240},{"header":"Remedy","paths":["Remedy"],"sliceMax":240}]}]}},{"match":{"hosts":["api.nhtsa.gov"],"pathEquals":["/complaints/complaintsByVehicle","/complaints/complaintsByVehicle/"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"requireAnyFields":["results","Results"],"vars":{"count":{"paths":["count","Count"],"format":"int_comma","default":"0"},"message":{"paths":["message","Message"],"trim":true}},"titleTemplate":"NHTSA Vehicle Complaints ({count} found)","introVar":"message","sections":[{"heading":"Complaints","arrayPath":"results","limit":50,"emptyText":"No complaints found.","columns":[{"header":"ODI Number","paths":["odiNumber"],"code":true},{"header":"Date","paths":["dateOfIncident"]},{"header":"Components","paths":["components"]},{"header":"Summary","paths":["summary"],"sliceMax":240},{"header":"Crash","paths":["crash"]},{"header":"Fire","paths":["fire"]}]}]}}]},{"id":"nist-nvd","name":"NIST National Vulnerability Database (NVD)","category":"developer","description":"Upgrades nvd.nist.gov CVE pages to the keyless NVD REST v2 JSON API with CVSS scores, CWEs, and vendor advisories.","domains":["nvd.nist.gov","www.nvd.nist.gov"],"exampleUrls":["https://nvd.nist.gov/vuln/detail/CVE-2024-3094"],"match":{"exactSegments":false,"pathSegments":["vuln","detail",{"param":"cveId","charset":"cve_id","transform":"upper"}]},"twin":{"fetchUrl":"https://services.nvd.nist.gov/rest/json/cves/2.0?cveId={cveId}","kind":"json","accept":"application/json"},"extract":{"rootPath":"vulnerabilities.0.cve","requireFields":["id"],"vars":{"id":{"paths":["id"]},"desc":{"findInArrayLang":{"arrayPath":"descriptions","langField":"lang","langValue":"en","valueField":"value"},"trim":true},"descShort":{"template":"{desc}","whenVars":["desc"],"sliceMax":260},"baseScore":{"paths":["metrics.cvssMetricV40.0.cvssData.baseScore","metrics.cvssMetricV31.0.cvssData.baseScore","metrics.cvssMetricV30.0.cvssData.baseScore"]},"severity":{"paths":["metrics.cvssMetricV40.0.cvssData.baseSeverity","metrics.cvssMetricV40.0.baseSeverity","metrics.cvssMetricV31.0.cvssData.baseSeverity","metrics.cvssMetricV31.0.baseSeverity","metrics.cvssMetricV30.0.cvssData.baseSeverity","metrics.cvssMetricV30.0.baseSeverity"]},"vector":{"paths":["metrics.cvssMetricV40.0.cvssData.vectorString","metrics.cvssMetricV31.0.cvssData.vectorString","metrics.cvssMetricV30.0.cvssData.vectorString"]},"titleWithScore":{"template":"{id} ({severity} {baseScore})","whenVars":["severity","baseScore"]},"titleSevOnly":{"template":"{id} ({severity})","whenVars":["severity"]},"titleFull":{"template":"{titleWithScore}","whenVars":["titleWithScore"],"fallbackVar":"titleSevOnly"},"cvssScoreOnly":{"template":"**{baseScore}**","whenVars":["baseScore"]},"cvssScoreVec":{"template":"**{baseScore}** — `{vector}`","whenVars":["baseScore","vector"],"fallbackVar":"cvssScoreOnly"},"cvssScoreSev":{"template":"**{baseScore}** ({severity})","whenVars":["baseScore","severity"],"fallbackVar":"cvssScoreVec"},"cvssDisplay":{"template":"**{baseScore}** ({severity}) — `{vector}`","whenVars":["baseScore","severity","vector"],"fallbackVar":"cvssScoreSev"},"cwes":{"nestedSubValues":{"arrayPath":"weaknesses","subArrayField":"description","valueField":"value","excludeValues":["NVD-CWE-noinfo"],"join":", "}},"published":{"paths":["published"]},"publishedDate":{"paths":["published"],"sliceMax":10},"vulnStatus":{"paths":["vulnStatus"]},"cisaExploit":{"paths":["cisaExploitAdd"]}},"titleTemplate":"{titleFull}","titleWhenVar":"severity","titleFallbackTemplate":"{id}","descriptionVar":"descShort","publishedTimeVar":"published","bullets":[{"label":"CVSS Score","template":"{cvssDisplay}","whenVar":"cvssDisplay"},{"label":"Status","template":"{vulnStatus}","whenVar":"vulnStatus"},{"label":"Published","template":"{publishedDate}","whenVar":"publishedDate"},{"label":"Weaknesses (CWE)","template":"{cwes}","whenVar":"cwes"},{"label":"CISA KEV (Known Exploited)","template":"Added {cisaExploit}","whenVar":"cisaExploit"}],"sections":[{"heading":"Summary","textVar":"desc"},{"heading":"References & Advisories","arrayPath":"references","limit":15,"requireItemVar":"refUrl","collectLinkVars":["refUrl"],"itemVars":{"refUrl":{"paths":["url"],"requireHttps":true},"refTags":{"paths":["tags"],"join":", "}},"columns":[{"header":"URL","template":"{refUrl}"},{"header":"Tags","template":"{refTags}"}]}]}},{"id":"noaa-ncei-cdo","name":"NOAA NCEI Climate Data Online (CDO)","category":"research-health","description":"NOAA National Centers for Environmental Information CDO API v2 (token header) on www.ncei.noaa.gov with HTML fallback.","domains":["www.ncei.noaa.gov","ncei.noaa.gov","www.ncdc.noaa.gov"],"auth_mode":"key","exampleUrls":["https://www.ncei.noaa.gov/cdo-web/api/v2/datasets?limit=2","https://www.ncei.noaa.gov/cdo-web/"],"routes":[{"match":{"hosts":["www.ncei.noaa.gov","ncei.noaa.gov"],"pathPrefix":"/cdo-web/api/v2/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"noaa_ncei_cdo_json"}}],"htmlRoutes":[{"id":"noaa-ncei-cdo","match":{"hosts":["www.ncei.noaa.gov","ncei.noaa.gov","www.ncdc.noaa.gov"],"exactSegments":false},"mode":"noaa_ncei_html"}]},{"id":"noaa-tides-currents","name":"NOAA Tides & Currents (CO-OPS)","category":"research-health","description":"NOAA Center for Operational Oceanographic Products and Services (CO-OPS) DataGetter and station metadata JSON APIs with stationhome HTML fallback.","domains":["tidesandcurrents.noaa.gov","api.tidesandcurrents.noaa.gov"],"auth_mode":"pub","exampleUrls":["https://api.tidesandcurrents.noaa.gov/api/prod/datagetter?date=latest&station=8518750&product=water_level&datum=MLLW&time_zone=gmt&units=english&format=json","https://api.tidesandcurrents.noaa.gov/mdapi/prod/webapi/stations/8518750.json","https://tidesandcurrents.noaa.gov/stationhome.html?id=8518750"],"routes":[{"match":{"hosts":["api.tidesandcurrents.noaa.gov"],"pathEquals":["/api/prod/datagetter"]},"twin":{"fetchUrl":"{requestUrl}","setQueryParams":{"format":"json"},"kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"noaa_tides_json"}},{"match":{"hosts":["api.tidesandcurrents.noaa.gov"],"pathPrefix":"/mdapi/prod/webapi/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"noaa_tides_json"}},{"match":{"hosts":["tidesandcurrents.noaa.gov"],"pathEquals":["/stationhome.html"],"queryParams":[{"name":"id","param":"stationId","charset":"digits","minLen":5,"maxLen":12}]},"twin":{"fetchUrl":"https://api.tidesandcurrents.noaa.gov/mdapi/prod/webapi/stations/{stationId}.json","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"noaa_tides_json"}}],"htmlRoutes":[{"id":"noaa-tides-currents","match":{"hosts":["tidesandcurrents.noaa.gov"],"exactSegments":false},"mode":"noaa_tides_html"}]},{"id":"notion-public-site","name":"Notion Public Sites","category":"developer","description":"Extracts public Notion site pages (*.notion.site and www.notion.so) via POST /api/v3/loadCachedPageChunk with fail-closed SSR HTML fallback.","domains":["www.notion.so"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://matt-mike.notion.site/Matt-Mike-Data-Analyst-Portfolio-201029b2366680969986e484d1aa4373"],"routes":[{"match":{"hostSubdomain":{"suffix":".notion.site","param":"siteSub"},"scanSegment":{"scanLast":true,"param":"pageUuid","charset":"notion_page_id","minLen":32,"maxLen":200,"transform":"notion_uuid"}},"twin":{"fetchUrl":"https://{host}/api/v3/loadCachedPageChunk","kind":"json","accept":"application/json","method":"POST","contentType":"application/json","requestBody":"{\"page\":{\"id\":\"{pageUuid}\"},\"limit\":50,\"cursor\":{\"stack\":[]},\"chunkNumber\":0,\"verticalColumns\":false}"},"extract":{"jsonMode":"notion_public_site"}},{"match":{"hosts":["www.notion.so","notion.so"],"scanSegment":{"scanLast":true,"param":"pageUuid","charset":"notion_page_id","minLen":32,"maxLen":200,"transform":"notion_uuid"}},"twin":{"fetchUrl":"https://{host}/api/v3/loadCachedPageChunk","kind":"json","accept":"application/json","method":"POST","contentType":"application/json","requestBody":"{\"page\":{\"id\":\"{pageUuid}\"},\"limit\":50,\"cursor\":{\"stack\":[]},\"chunkNumber\":0,\"verticalColumns\":false}"},"extract":{"jsonMode":"notion_public_site"}}],"htmlRoutes":[{"id":"notion-public-site","match":{"exactSegments":false},"mode":"notion_public_site_html"}]},{"id":"npm-registry","name":"npm Package Registry","category":"developer","description":"Upgrades npmjs.com package pages to registry.npmjs.org JSON metadata, TypeScript declarations, dependency list, and README.","domains":["npmjs.com","www.npmjs.com"],"exampleUrls":["https://www.npmjs.com/package/@cfworker/json-schema"],"routes":[{"match":{"anyOf":[{"pathPrefix":"/package/@","exactSegments":false,"pathSegments":["package",{"param":"scopeNoAt","stripPrefix":"@","charset":"npm_pkg"},{"param":"pkg","charset":"npm_pkg"},"v",{"param":"requestedVer","charset":"url_seg"}]},{"pathPrefix":"/package/@","exactSegments":false,"pathSegments":["package",{"param":"scopeNoAt","stripPrefix":"@","charset":"npm_pkg"},{"param":"pkg","charset":"npm_pkg"}]}]},"twin":{"fetchUrl":"https://registry.npmjs.org/@{scopeNoAt}%2F{pkg}","kind":"json","accept":"application/json"},"extract":{"requireFields":["name"],"vars":{"name":{"paths":["name"]},"latestTag":{"paths":["dist-tags.latest"]},"ver":{"template":"{requestedVer}","whenVars":["requestedVer"],"fallbackVar":"latestTag"},"verDesc":{"dynamicKeyPath":{"base":"versions","keyVar":"ver","subPath":"description"},"trim":true},"rootDesc":{"paths":["description"],"trim":true},"desc":{"template":"{verDesc}","whenVars":["verDesc"],"fallbackVar":"rootDesc"},"verLicense":{"dynamicKeyPath":{"base":"versions","keyVar":"ver","subPath":"license"}},"rootLicense":{"paths":["license"]},"license":{"template":"{verLicense}","whenVars":["verLicense"],"fallbackVar":"rootLicense"},"verHomepage":{"dynamicKeyPath":{"base":"versions","keyVar":"ver","subPath":"homepage"}},"rootHomepage":{"paths":["homepage"]},"homepage":{"template":"{verHomepage}","whenVars":["verHomepage"],"fallbackVar":"rootHomepage"},"verRepoUrl":{"dynamicKeyPath":{"base":"versions","keyVar":"ver","subPath":"repository.url"}},"verRepoStr":{"dynamicKeyPath":{"base":"versions","keyVar":"ver","subPath":"repository"}},"verRepo":{"template":"{verRepoUrl}","whenVars":["verRepoUrl"],"fallbackVar":"verRepoStr"},"rootRepo":{"paths":["repository.url","repository"]},"repoClean":{"template":"{verRepo}","whenVars":["verRepo"],"fallbackVar":"rootRepo","stripPrefix":"git+","stripSuffix":".git","requireHttpPrefix":true},"verTypes":{"dynamicKeyPath":{"base":"versions","keyVar":"ver","subPath":"types"}},"verTypings":{"dynamicKeyPath":{"base":"versions","keyVar":"ver","subPath":"typings"}},"hasTypes":{"template":"Bundled declarations included","whenAnyVars":["verTypes","verTypings"]},"depsDisplay":{"dynamicKeyPath":{"base":"versions","keyVar":"ver","subPath":"dependencies"},"format":"object_keys","limit":10,"join":", ","default":"0 (zero dependencies)"},"readme":{"paths":["readme"],"excludeEquals":"ERROR: No README data found!","format":"strip_leading_h1","trim":true}},"titleTemplate":"{name}@{ver}","titleWhenVar":"ver","titleFallbackTemplate":"{name}","descriptionVar":"desc","introVar":"desc","bullets":[{"label":"Install","template":"`npm install {name}`"},{"label":"Latest Version","template":"`{ver}`","whenVar":"ver"},{"label":"License","template":"{license}","whenVar":"license"},{"label":"TypeScript","template":"{hasTypes}","whenVar":"hasTypes"},{"label":"Runtime Dependencies","template":"{depsDisplay}","whenVar":"depsDisplay"},{"label":"Homepage","template":"{homepage}","whenVar":"homepage"},{"label":"Repository","template":"{repoClean}","whenVar":"repoClean"}],"bodyVar":"readme"}},{"match":{"anyOf":[{"exactSegments":false,"pathSegments":["package",{"param":"pkg","charset":"npm_pkg"},"v",{"param":"requestedVer","charset":"url_seg"}]},{"exactSegments":false,"pathSegments":["package",{"param":"pkg","charset":"npm_pkg"}]}]},"twin":{"fetchUrl":"https://registry.npmjs.org/{pkg}","kind":"json","accept":"application/json"},"extract":{"requireFields":["name"],"vars":{"name":{"paths":["name"]},"latestTag":{"paths":["dist-tags.latest"]},"ver":{"template":"{requestedVer}","whenVars":["requestedVer"],"fallbackVar":"latestTag"},"verDesc":{"dynamicKeyPath":{"base":"versions","keyVar":"ver","subPath":"description"},"trim":true},"rootDesc":{"paths":["description"],"trim":true},"desc":{"template":"{verDesc}","whenVars":["verDesc"],"fallbackVar":"rootDesc"},"verLicense":{"dynamicKeyPath":{"base":"versions","keyVar":"ver","subPath":"license"}},"rootLicense":{"paths":["license"]},"license":{"template":"{verLicense}","whenVars":["verLicense"],"fallbackVar":"rootLicense"},"verHomepage":{"dynamicKeyPath":{"base":"versions","keyVar":"ver","subPath":"homepage"}},"rootHomepage":{"paths":["homepage"]},"homepage":{"template":"{verHomepage}","whenVars":["verHomepage"],"fallbackVar":"rootHomepage"},"verRepoUrl":{"dynamicKeyPath":{"base":"versions","keyVar":"ver","subPath":"repository.url"}},"verRepoStr":{"dynamicKeyPath":{"base":"versions","keyVar":"ver","subPath":"repository"}},"verRepo":{"template":"{verRepoUrl}","whenVars":["verRepoUrl"],"fallbackVar":"verRepoStr"},"rootRepo":{"paths":["repository.url","repository"]},"repoClean":{"template":"{verRepo}","whenVars":["verRepo"],"fallbackVar":"rootRepo","stripPrefix":"git+","stripSuffix":".git","requireHttpPrefix":true},"verTypes":{"dynamicKeyPath":{"base":"versions","keyVar":"ver","subPath":"types"}},"verTypings":{"dynamicKeyPath":{"base":"versions","keyVar":"ver","subPath":"typings"}},"hasTypes":{"template":"Bundled declarations included","whenAnyVars":["verTypes","verTypings"]},"depsDisplay":{"dynamicKeyPath":{"base":"versions","keyVar":"ver","subPath":"dependencies"},"format":"object_keys","limit":10,"join":", ","default":"0 (zero dependencies)"},"readme":{"paths":["readme"],"excludeEquals":"ERROR: No README data found!","format":"strip_leading_h1","trim":true}},"titleTemplate":"{name}@{ver}","titleWhenVar":"ver","titleFallbackTemplate":"{name}","descriptionVar":"desc","introVar":"desc","bullets":[{"label":"Install","template":"`npm install {name}`"},{"label":"Latest Version","template":"`{ver}`","whenVar":"ver"},{"label":"License","template":"{license}","whenVar":"license"},{"label":"TypeScript","template":"{hasTypes}","whenVar":"hasTypes"},{"label":"Runtime Dependencies","template":"{depsDisplay}","whenVar":"depsDisplay"},{"label":"Homepage","template":"{homepage}","whenVar":"homepage"},{"label":"Repository","template":"{repoClean}","whenVar":"repoClean"}],"bodyVar":"readme"}}]},{"id":"nppes-npi","name":"NPPES NPI Registry","category":"research-health","description":"CMS National Plan and Provider Enumeration System (NPPES) NPI Registry v2.1 JSON API adapter with Angular SPA shell rejection.","domains":["npiregistry.cms.hhs.gov"],"auth_mode":"pub","exampleUrls":["https://npiregistry.cms.hhs.gov/api/?version=2.1&number=1003000126","https://npiregistry.cms.hhs.gov/provider-view/1003000126"],"routes":[{"match":{"pathEquals":["/api","/api/"]},"twin":{"fetchUrl":"{requestUrl}","defaultQueryParams":{"version":"2.1"},"kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"nppes_npi_json"}},{"match":{"exactSegments":true,"pathSegments":["provider-view",{"param":"npi","charset":"digits","minLen":10,"maxLen":10}]},"twin":{"fetchUrl":"https://npiregistry.cms.hhs.gov/api/?version=2.1&number={npi}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"nppes_npi_json"}}],"htmlRoutes":[{"id":"nppes-npi","match":{"pathPrefix":"/provider-view/","exactSegments":false},"mode":"nppes_npi_html"}]},{"id":"npr-pbs","name":"NPR & PBS NewsHour","category":"commerce-social","description":"Extracts NPR/PBS RSS XML feeds, text.npr.org stories, and NPR/PBS article HTML.","domains":["www.npr.org","npr.org","text.npr.org","feeds.npr.org","www.pbs.org","pbs.org"],"auth_mode":"html","exampleUrls":["https://feeds.npr.org/1001/rss.xml","https://www.pbs.org/newshour/feeds/rss/headlines","https://www.pbs.org/newshour/nation"],"routes":[{"match":{"hosts":["feeds.npr.org"],"pathSuffix":".xml","exactSegments":false},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"application/rss+xml","auth_mode":"pub"},"extract":{"textMode":"npr_pbs_rss_xml"}},{"match":{"hosts":["www.pbs.org","pbs.org"],"pathPrefix":"/newshour/feeds/rss/","exactSegments":false},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"application/rss+xml","auth_mode":"pub"},"extract":{"textMode":"npr_pbs_rss_xml"}}],"htmlRoutes":[{"id":"npr-pbs","match":{"exactSegments":false},"mode":"npr_pbs_html"}]},{"id":"nps","name":"National Park Service (NPS)","category":"public-records","description":"National Park Service developer.nps.gov v1 JSON API (via DATA_GOV_API_KEY) with www.nps.gov HTML fallback.","domains":["developer.nps.gov","www.nps.gov","nps.gov"],"auth_mode":"key","exampleUrls":["https://www.nps.gov/yell/index.htm","https://developer.nps.gov/api/v1/parks?parkCode=yell&limit=1"],"routes":[{"match":{"hosts":["developer.nps.gov"],"pathPrefix":"/api/v1/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":4194304},"extract":{"jsonMode":"nps_json"}},{"match":{"hosts":["www.nps.gov","nps.gov"],"exactSegments":true,"pathSegments":[{"param":"parkCode","charset":"alnum","minLen":4,"maxLen":4,"reserved":["news","plan","maps","fees","find","jobs","kids","faqs","more","docs","help","info","blog","home","data","form","apps","page"],"transform":"lower"},"index.htm"]},"twin":{"fetchUrl":"https://developer.nps.gov/api/v1/parks?parkCode={parkCode}&limit=5","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"nps_json"}}],"htmlRoutes":[{"id":"nps","match":{"hosts":["www.nps.gov","nps.gov"],"exactSegments":false},"mode":"nps_html"}]},{"id":"nuget-gallery","name":"NuGet Gallery","category":"developer","description":"Upgrades nuget.org/packages/[/] pages to the official api.nuget.org v3 registration JSON API (supporting both inlined catalogEntry pages and un-inlined CatalogPage stubs).","domains":["www.nuget.org","nuget.org"],"exampleUrls":["https://www.nuget.org/packages/Newtonsoft.Json","https://www.nuget.org/packages/Newtonsoft.Json/13.0.3"],"routes":[{"match":{"exactSegments":true,"pathSegments":["packages",{"param":"pkgId","charset":"pkg","minLen":1,"maxLen":128,"transform":"lower"},{"param":"ver","charset":"url_seg","reserved":["ReportAbuse","ContactOwners","versions"],"minLen":1,"maxLen":64}]},"twin":{"fetchUrl":"https://api.nuget.org/v3/registration5-gz-semver2/{pkgId}/index.json","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"nuget_registration"}},{"match":{"exactSegments":true,"pathSegments":["packages",{"param":"pkgId","charset":"pkg","minLen":1,"maxLen":128,"transform":"lower"}]},"twin":{"fetchUrl":"https://api.nuget.org/v3/registration5-gz-semver2/{pkgId}/index.json","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"nuget_registration"}}]},{"id":"nyt-api","name":"New York Times API & News","category":"commerce-social","description":"Official NYT Developer API (Article Search, Top Stories, Most Popular) with NYT_API_KEY and NewsArticle HTML fallback.","domains":["api.nytimes.com","www.nytimes.com","nytimes.com"],"auth_mode":"key","exampleUrls":["https://api.nytimes.com/svc/topstories/v2/home.json","https://www.nytimes.com/"],"routes":[{"match":{"hosts":["api.nytimes.com"],"exactSegments":true,"pathSegments":["svc","search","v2","articlesearch.json"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key"},"extract":{"jsonMode":"nyt_api_json"}},{"match":{"hosts":["api.nytimes.com"],"exactSegments":true,"pathSuffix":".json","pathSegments":["svc","topstories","v2",{"param":"section","charset":"slug","stripSuffix":".json","minLen":2,"maxLen":40}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key"},"extract":{"jsonMode":"nyt_api_json"}},{"match":{"hosts":["api.nytimes.com"],"exactSegments":true,"pathSuffix":".json","pathSegments":["svc","mostpopular","v2",{"param":"kind","allowValues":["emailed","shared","viewed"]},{"param":"period","charset":"digits","stripSuffix":".json","allowValues":["1","7","30"]}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key"},"extract":{"jsonMode":"nyt_api_json"}}],"htmlRoutes":[{"id":"nyt-api","match":{"hosts":["www.nytimes.com","nytimes.com"],"exactSegments":false},"mode":"nyt_html"}]},{"id":"okendo","name":"Okendo Product Reviews","category":"commerce-social","description":"Extracts public Okendo product review and review aggregate JSON payloads without preempting storefront HTML extractors.","domains":["api.okendo.io"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://api.okendo.io/v1/stores/892ce72b-10d2-4dd3-a7ab-e2dfdee9d001/products/shopify-6861943013449/reviews?limit=10"],"routes":[{"match":{"anyOf":[{"hosts":["api.okendo.io"],"pathSegments":["v1","stores",{"param":"subscriberId","charset":"alnum_dash","minLen":4,"maxLen":80},"products",{"param":"productId","charset":"pkg","minLen":1,"maxLen":120},{"param":"endpoint","allowValues":["reviews","review_aggregate"]}]},{"hosts":["api.okendo.io"],"pathSegments":["v1","stores",{"param":"subscriberId","charset":"alnum_dash","minLen":4,"maxLen":80},"reviews"]}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"okendo_reviews"}}],"htmlRoutes":[{"id":"okendo","match":{"exactSegments":false},"mode":"okendo_html"}]},{"id":"openalex","name":"OpenAlex Scholarly Works","category":"research-health","description":"Upgrades openalex.org work URLs to api.openalex.org JSON with reconstructed abstracts, citations, open-access PDF links, and topics.","domains":["openalex.org","www.openalex.org","api.openalex.org"],"exampleUrls":["https://openalex.org/W2741809807","https://openalex.org/works/W2741809807"],"match":{"anyOf":[{"exactSegments":false,"pathSegments":["works",{"param":"workId","charset":"openalex_work","transform":"upper"}]},{"exactSegments":false,"pathSegments":[{"param":"workId","charset":"openalex_work","transform":"upper"}]}]},"twin":{"fetchUrl":"https://api.openalex.org/works/{workId}","kind":"json","accept":"application/json"},"extract":{"requireAnyFields":["display_name","title"],"requireVars":["title"],"vars":{"title":{"paths":["display_name","title"],"trim":true},"pubDate":{"paths":["publication_date"]},"citedBy":{"paths":["cited_by_count"],"format":"int_comma"},"doi":{"paths":["doi"]},"oaUrl":{"paths":["open_access.oa_url"],"requireHttps":true},"authors":{"paths":["authorships"],"subField":"author.display_name","limit":15,"join":", "},"authorsShort":{"paths":["authorships"],"subField":"author.display_name","limit":4,"join":", "},"abstract":{"paths":["abstract_inverted_index"],"format":"inverted_abstract"},"abstractShort":{"paths":["abstract_inverted_index"],"format":"inverted_abstract","sliceMax":260}},"titleTemplate":"{title}","descriptionVar":"abstractShort","authorVar":"authorsShort","publishedTimeVar":"pubDate","bullets":[{"label":"OpenAlex ID","template":"`{workId}`"},{"label":"Authors","template":"{authors}","whenVar":"authors"},{"label":"Published","template":"{pubDate}","whenVar":"pubDate"},{"label":"Citations","template":"{citedBy}","whenVar":"citedBy"},{"label":"DOI","template":"{doi}","whenVar":"doi"},{"label":"Open Access PDF","template":"{oaUrl}","whenVar":"oaUrl"}],"sections":[{"heading":"Abstract","textVar":"abstract"}],"linksVars":["doi","oaUrl"]}},{"id":"opencorporates","name":"OpenCorporates Company Registry","category":"public-records","description":"Upgrades opencorporates.com company pages to key-authenticated OpenCorporates API v0.4 JSON with clean public HTML attributes fallback when unconfigured.","domains":["opencorporates.com","www.opencorporates.com","api.opencorporates.com"],"auth_mode":"key","exampleUrls":["https://opencorporates.com/companies/us_de/3857729","https://api.opencorporates.com/v0.4/companies/us_de/3857729"],"routes":[{"match":{"hosts":["opencorporates.com","www.opencorporates.com"],"exactSegments":false,"pathSegments":["companies",{"param":"jurisdiction","charset":"alnum_dash","minLen":2,"maxLen":16},{"param":"companyNumber","charset":"url_seg","minLen":1,"maxLen":64}]},"twin":{"fetchUrl":"https://api.opencorporates.com/v0.4/companies/{jurisdiction}/{companyNumber}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"opencorporates_json"}},{"match":{"hosts":["api.opencorporates.com"],"pathPrefix":"/v0.4/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"opencorporates_json"}}],"htmlRoutes":[{"id":"opencorporates","match":{"hosts":["opencorporates.com","www.opencorporates.com"],"pathPrefix":"/companies/","exactSegments":false},"mode":"opencorporates_html"}]},{"id":"opendatasoft","name":"Opendatasoft Open Data Portals (Explore API v2.1)","category":"public-records","description":"Universal Opendatasoft adapter: /explore/dataset// pages and /api/explore/v2.1/catalog/datasets/ upgrade to dataset metadata (publisher, license, record count, field schema, records/CSV API links); /records URLs render rows as a table.","domains":["public.opendatasoft.com"],"universalEngine":true,"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://public.opendatasoft.com/explore/dataset/us-state-boundaries/","https://public.opendatasoft.com/api/explore/v2.1/catalog/datasets/us-state-boundaries/records?limit=3&select=name,stusab,region,division"],"routes":[{"match":{"exactSegments":true,"pathSegments":["api","explore","v2.1","catalog","datasets",{"param":"datasetId","charset":"pkg","minLen":2,"maxLen":160},"records"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"opendatasoft_records_json"}},{"match":{"exactSegments":true,"pathSegments":["api","explore","v2.1","catalog","datasets",{"param":"datasetId","charset":"pkg","minLen":2,"maxLen":160}]},"twin":{"fetchUrl":"https://{host}/api/explore/v2.1/catalog/datasets/{datasetId}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"opendatasoft_dataset_json"}},{"match":{"exactSegments":false,"pathSegments":["explore","dataset",{"param":"datasetId","charset":"pkg","minLen":2,"maxLen":160}]},"twin":{"fetchUrl":"https://{host}/api/explore/v2.1/catalog/datasets/{datasetId}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"opendatasoft_dataset_json"}}]},{"id":"openfda","name":"openFDA Recalls, Labels & Adverse Events API","category":"research-health","description":"Formats keyless api.fda.gov JSON endpoints (drug/food/device enforcement recalls, drug labels, and adverse events) into clean Markdown tables.","domains":["api.fda.gov"],"exampleUrls":["https://api.fda.gov/food/enforcement.json?limit=5"],"match":{"pathSuffix":".json","pathSegments":[{"param":"endpointLabel","charset":"safe_subpath","greedy":true,"stripSuffix":".json"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"requireAnyFields":["results"],"vars":{"resultsCount":{"paths":["results"],"format":"array_len"},"total":{"paths":["meta.results.total"],"format":"int_comma","fallbackTemplate":"{resultsCount}"},"isRecall":{"paths":["results.0.recall_number","results.0.reason_for_recall"]}},"titleTemplate":"openFDA {endpointLabel} ({resultsCount} of {total} records)","sections":[{"heading":"","whenVar":"isRecall","arrayPath":"results","limit":25,"columns":[{"header":"Recall #","paths":["recall_number"],"code":true},{"header":"Class","paths":["classification"]},{"header":"Status","paths":["status"]},{"header":"Firm","paths":["recalling_firm"]},{"header":"Reason","paths":["reason_for_recall"]}]},{"heading":"","unlessVar":"isRecall","subsectionsArrayPath":"results","limit":10,"subsectionHeadingTemplate":"{recHeading}","subsectionSubkeys":["indications_and_usage","warnings","boxed_warning","dosage_and_administration","adverse_reactions"],"itemVars":{"brand":{"paths":["openfda.brand_name.0"]},"generic":{"paths":["openfda.generic_name.0"]},"genericParens":{"template":"({generic})","whenVars":["generic"]},"brandAndGeneric":{"template":"{brand} {genericParens}","whenVars":["brand","genericParens"],"fallbackVar":"brand"},"brandOrGeneric":{"template":"{brandAndGeneric}","whenVars":["brandAndGeneric"],"fallbackVar":"genericParens"},"recFallback":{"template":"Record #{index1}"},"recHeading":{"template":"{brandOrGeneric}","whenVars":["brandOrGeneric"],"fallbackVar":"recFallback"}}}]}},{"id":"openfoodfacts","name":"Open Food Facts Products","category":"commerce-social","description":"Extracts barcode, brand, Nutri-Score, NOVA group, ingredients, and nutrition facts from world.openfoodfacts.org/product/ (respecting robots.txt on /api).","domains":["world.openfoodfacts.org","openfoodfacts.org","*.openfoodfacts.org"],"exampleUrls":["https://world.openfoodfacts.org/product/3017620422003"],"htmlRoutes":[{"id":"openfoodfacts","match":{"exactSegments":false,"pathSegments":["product",{"param":"barcode","charset":"digits","minLen":6,"maxLen":16}]},"mode":"dom","jsonLdTypes":["Product"],"requireVars":["title"],"vars":{"title":{"jsonLdPaths":["name"],"metaKeys":["og:title"],"cssText":["h1"]},"brand":{"jsonLdPaths":["brand.name","brand"]},"nutriscore":{"regexExtract":{"source":"doc_text_and_img_alts","pattern":"Nutri-Score\\s*([A-E])\\b","group":1,"transform":"upper"}},"nova":{"regexExtract":{"source":"doc_text_and_img_alts","pattern":"NOVA\\s*([1-4])\\b","group":1}},"ingredientsLd":{"jsonLdPaths":["description"]},"ingredients":{"cssText":["#panel_ingredients_content"],"fallbackVar":"ingredientsLd"},"descShort":{"fallbackVar":"ingredients","sliceMax":260}},"titleTemplate":"{title}","descriptionVar":"descShort","bullets":[{"label":"Barcode (GTIN)","template":"`{barcode}`"},{"label":"Brand","template":"{brand}","whenVar":"brand"},{"label":"Nutri-Score","template":"**{nutriscore}**","whenVar":"nutriscore"},{"label":"NOVA Food Processing Group","template":"{nova}","whenVar":"nova"}],"sections":[{"heading":"Ingredients & Summary","textVar":"ingredients"}],"appendCurrentMdDelta":{"baseVar":"ingredients","minExtraChars":120}}]},{"id":"openrouter","name":"OpenRouter AI Model Catalog","category":"genai","description":"Upgrades OpenRouter model pages to keyless /api/v1/models specs (context window, token pricing, modalities, and tool support).","domains":["openrouter.ai"],"exampleUrls":["https://openrouter.ai/anthropic/claude-sonnet-5.5","https://openrouter.ai/models/qwen/qwen4-max"],"match":{"anyOf":[{"exactSegments":true,"pathSegments":["models",{"param":"org","charset":"pkg"},{"param":"slug","charset":"model_slug"}]},{"exactSegments":true,"pathSegments":[{"param":"org","charset":"pkg","reserved":["docs","rankings","chat","activity","settings","keys","credits","privacy","terms","about","blog","pricing","providers"]},{"param":"slug","charset":"model_slug"}]}]},"twin":{"fetchUrl":"https://openrouter.ai/api/v1/models","kind":"json","accept":"application/json"},"extract":{"findInArray":{"arrayPath":"data","matchField":"id","matchTemplate":"{org}/{slug}","ignoreCase":true},"vars":{"id":{"paths":["id"]},"name":{"paths":["name"],"fallbackTemplate":"{org}/{slug}","trim":true},"ctxLen":{"paths":["context_length"],"format":"int_comma"},"maxOut":{"paths":["top_provider.max_completion_tokens"],"format":"int_comma"},"promptPrice":{"paths":["pricing.prompt"],"format":"usd_per_million_tokens"},"compPrice":{"paths":["pricing.completion"],"format":"usd_per_million_tokens"},"modality":{"paths":["architecture.modality"]},"params":{"paths":["supported_parameters"],"join":"`, `","limit":14},"desc":{"paths":["description"],"trim":true},"descShort":{"paths":["description"],"trim":true,"sliceMax":260}},"titleTemplate":"{name}","descriptionVar":"descShort","bullets":[{"label":"Model ID","template":"`{id}`"},{"label":"Context Window","template":"{ctxLen} tokens","whenVar":"ctxLen"},{"label":"Max Output","template":"{maxOut} tokens","whenVar":"maxOut"},{"label":"Input Pricing","template":"{promptPrice}","whenVar":"promptPrice"},{"label":"Output Pricing","template":"{compPrice}","whenVar":"compPrice"},{"label":"Modality","template":"`{modality}`","whenVar":"modality"},{"label":"Supported Parameters","template":"`{params}`","whenVar":"params"}],"sections":[{"heading":"Description","textVar":"desc"}]}},{"id":"openstreetmap","name":"OpenStreetMap (Nominatim & Overpass)","category":"public-records","description":"OpenStreetMap Nominatim geocoding and Overpass API JSON adapter enforcing strict 1 req/s pacing, identifying User-Agent, and strict robots.txt politeness.","domains":["www.openstreetmap.org","openstreetmap.org","nominatim.openstreetmap.org","overpass-api.de"],"auth_mode":"pub","user_agent_profile":"openstreetmap","min_interval_ms":1000,"strict_robots":true,"exampleUrls":["https://www.openstreetmap.org/about","https://www.openstreetmap.org/copyright"],"routes":[{"match":{"hosts":["nominatim.openstreetmap.org"],"anyOf":[{"pathPrefix":"/search"},{"pathPrefix":"/reverse"},{"pathPrefix":"/lookup"}]},"twin":{"fetchUrl":"{requestUrl}","setQueryParams":{"format":"jsonv2"},"kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"openstreetmap_json"}},{"match":{"hosts":["overpass-api.de"],"pathPrefix":"/api/interpreter"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"openstreetmap_json"}}],"htmlRoutes":[{"id":"openstreetmap","match":{"hosts":["www.openstreetmap.org","openstreetmap.org"],"exactSegments":false},"mode":"openstreetmap_html"}]},{"id":"oracle-commerce","name":"Oracle Commerce Cloud (ccstore)","category":"commerce-social","description":"Extracts Oracle Commerce Cloud /ccstore/v1 and /ccstoreui/v1 product and search JSON endpoints plus storefront HTML/companion twins.","domains":["www.dollartree.com"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://www.dollartree.com/ccstore/v1/products/805937","https://www.dollartree.com/ccstore/v1/search?Ntt=bag"],"routes":[{"match":{"pathSegments":["ccstore","v1","products",{"param":"productId","charset":"pkg","minLen":1,"maxLen":120}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"commerceMode":"oracle_commerce_product"}},{"match":{"pathSegments":["ccstoreui","v1","products",{"param":"productId","charset":"pkg","minLen":1,"maxLen":120}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"commerceMode":"oracle_commerce_product"}},{"match":{"pathEquals":["/ccstore/v1/search"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"commerceMode":"oracle_commerce_product"}}],"htmlRoutes":[{"id":"oracle-commerce","match":{"exactSegments":false},"mode":"oracle_commerce_html"}]},{"id":"os-package-pack","name":"OS Package Pack (Flathub, Snapcraft, AUR, Winget, Chocolatey)","category":"developer","description":"Extracts OS package metadata and newest stable versions from Flathub, Snapcraft (Snap-Device-Series: 16), Arch AUR RPC v5, Winget, and Chocolatey.","domains":["flathub.org","snapcraft.io","api.snapcraft.io","aur.archlinux.org","winget.run","api.winget.run","community.chocolatey.org"],"auth_mode":"pub","min_interval_ms":2000,"exampleUrls":["https://flathub.org/apps/org.mozilla.firefox","https://snapcraft.io/firefox","https://aur.archlinux.org/packages/yay","https://winget.run/pkg/Microsoft/PowerToys"],"routes":[{"match":{"hosts":["flathub.org"],"pathPrefix":"/api/v2/appstream/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"flathub_json"}},{"match":{"hosts":["flathub.org"],"exactSegments":false,"pathSegments":["apps",{"param":"appId","charset":"pkg","minLen":3,"maxLen":160}]},"twin":{"fetchUrl":"https://flathub.org/api/v2/appstream/{appId}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"flathub_json"}},{"match":{"hosts":["api.snapcraft.io"],"pathPrefix":"/v2/snaps/info/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","headers":{"Snap-Device-Series":"16"},"maxBytes":2097152},"extract":{"jsonMode":"snapcraft_json"}},{"match":{"hosts":["snapcraft.io"],"exactSegments":true,"reservedFirstSegment":["account","admin","login","logout","store","docs","blog","about","publisher","search","first-snap","build"],"pathSegments":[{"param":"snap","charset":"pkg","minLen":1,"maxLen":80}]},"twin":{"fetchUrl":"https://api.snapcraft.io/v2/snaps/info/{snap}","kind":"json","accept":"application/json","headers":{"Snap-Device-Series":"16"},"maxBytes":2097152},"extract":{"jsonMode":"snapcraft_json"}},{"match":{"hosts":["aur.archlinux.org"],"pathPrefix":"/rpc/v5/info"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"aur_json"}},{"match":{"hosts":["aur.archlinux.org"],"exactSegments":true,"pathSegments":["packages",{"param":"pkg","charset":"pkg","minLen":1,"maxLen":120}]},"twin":{"fetchUrl":"https://aur.archlinux.org/rpc/v5/info?arg[]={pkg}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"aur_json"}},{"match":{"hosts":["api.winget.run"],"pathPrefix":"/v2/packages/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"winget_json"}},{"match":{"hosts":["winget.run"],"exactSegments":false,"pathSegments":["pkg",{"param":"publisher","charset":"pkg","minLen":1,"maxLen":120},{"param":"pkg","charset":"pkg","minLen":1,"maxLen":120}]},"twin":{"fetchUrl":"https://api.winget.run/v2/packages/{publisher}/{pkg}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"winget_json"}},{"match":{"hosts":["community.chocolatey.org"],"pathPrefix":"/api/v2/Packages"},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"application/atom+xml","maxBytes":2097152},"extract":{"textMode":"chocolatey_xml"}}],"htmlRoutes":[{"id":"os-package-pack","match":{"hosts":["snapcraft.io"],"exactSegments":true,"reservedFirstSegment":["account","admin","login","logout","store","docs","blog","about","publisher","search","first-snap","build"],"pathSegments":[{"param":"snap","charset":"pkg","minLen":1,"maxLen":80}]},"mode":"snapcraft_html"},{"id":"os-package-pack","match":{"hosts":["community.chocolatey.org"],"pathPrefix":"/packages/","exactSegments":false},"mode":"chocolatey_html"}]},{"id":"osv-ghsa","name":"OSV & GitHub Security Advisories","category":"developer","description":"Upgrades osv.dev/vulnerability/ and github.com/advisories/GHSA-* pages to the keyless api.osv.dev/v1/vulns JSON API with canonical lowercase GHSA IDs and bounded affected-version slices.","domains":["osv.dev","www.osv.dev","github.com"],"exampleUrls":["https://osv.dev/vulnerability/GHSA-jfh8-c2jp-5v3q","https://github.com/advisories/GHSA-jfh8-c2jp-5v3q"],"routes":[{"match":{"hosts":["osv.dev","www.osv.dev"],"exactSegments":false,"pathSegments":["vulnerability",{"param":"vulnId","charset":"url_seg","minLen":4,"maxLen":80}]},"twin":{"fetchUrl":"https://api.osv.dev/v1/vulns/{vulnId}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"requireFields":["id"],"vars":{"id":{"paths":["id"]},"summary":{"paths":["summary"],"trim":true},"details":{"paths":["details"],"trim":true},"summaryShort":{"paths":["summary","details"],"trim":true,"sliceMax":260},"aliases":{"paths":["aliases"],"itemWrap":"`","join":", ","limit":12},"severityScore":{"paths":["severity.0.score"]},"severityType":{"paths":["severity.0.type"]},"published":{"paths":["published"],"sliceMax":10},"modified":{"paths":["modified"],"sliceMax":10},"osvUrl":{"template":"https://osv.dev/vulnerability/{id}","requireHttps":true}},"titleTemplate":"{id} — {summary}","titleWhenVar":"summary","titleFallbackTemplate":"{id} (OSV Advisory)","descriptionVar":"summaryShort","publishedTimeVar":"published","introVar":"summary","bullets":[{"label":"Advisory ID","template":"`{id}`"},{"label":"Aliases","template":"{aliases}","whenVar":"aliases"},{"label":"Severity","template":"`{severityScore}` ({severityType})","whenVar":"severityScore"},{"label":"Published","template":"{published}","whenVar":"published"},{"label":"Modified","template":"{modified}","whenVar":"modified"},{"label":"OSV URL","template":"{osvUrl}","whenVar":"osvUrl"}],"bodyVar":"details","sections":[{"heading":"Affected Packages","arrayPath":"affected","limit":20,"itemVars":{"versionsCount":{"paths":["versions"],"format":"array_len_comma"},"versionsSample":{"paths":["versions"],"limit":12,"itemWrap":"`","join":", "},"fixedVersions":{"nestedSubValues":{"arrayPath":"ranges","subArrayField":"events","valueField":"fixed","limit":12,"join":", "}}},"columns":[{"header":"Ecosystem","paths":["package.ecosystem"]},{"header":"Package","paths":["package.name"],"code":true},{"header":"Affected Count","template":"{versionsCount}"},{"header":"Sample Versions","template":"{versionsSample}"},{"header":"Fixed","template":"{fixedVersions}"}]},{"heading":"References","arrayPath":"references","limit":20,"requireItemVar":"refUrl","collectLinkVars":["refUrl"],"itemVars":{"refUrl":{"paths":["url"],"requireHttps":true},"refType":{"paths":["type"]}},"columns":[{"header":"Type","template":"{refType}"},{"header":"URL","template":"{refUrl}"}]}],"linksVars":["osvUrl"]}},{"match":{"hosts":["github.com"],"exactSegments":true,"pathPrefix":"/advisories/GHSA-","pathSegments":["advisories",{"param":"ghsaBody","stripPrefix":"GHSA-","charset":"alnum_dash","minLen":14,"maxLen":14,"transform":"lower"}]},"twin":{"fetchUrl":"https://api.osv.dev/v1/vulns/GHSA-{ghsaBody}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"requireFields":["id"],"vars":{"id":{"paths":["id"]},"summary":{"paths":["summary"],"trim":true},"details":{"paths":["details"],"trim":true},"summaryShort":{"paths":["summary","details"],"trim":true,"sliceMax":260},"aliases":{"paths":["aliases"],"itemWrap":"`","join":", ","limit":12},"severityScore":{"paths":["severity.0.score"]},"severityType":{"paths":["severity.0.type"]},"published":{"paths":["published"],"sliceMax":10},"modified":{"paths":["modified"],"sliceMax":10},"ghsaUrl":{"template":"https://github.com/advisories/GHSA-{ghsaBody}","requireHttps":true},"osvUrl":{"template":"https://osv.dev/vulnerability/{id}","requireHttps":true}},"titleTemplate":"{id} — {summary}","titleWhenVar":"summary","titleFallbackTemplate":"{id} (GitHub Advisory)","descriptionVar":"summaryShort","publishedTimeVar":"published","introVar":"summary","bullets":[{"label":"Advisory ID","template":"`{id}`"},{"label":"Aliases","template":"{aliases}","whenVar":"aliases"},{"label":"Severity","template":"`{severityScore}` ({severityType})","whenVar":"severityScore"},{"label":"Published","template":"{published}","whenVar":"published"},{"label":"Modified","template":"{modified}","whenVar":"modified"},{"label":"OSV URL","template":"{osvUrl}","whenVar":"osvUrl"}],"bodyVar":"details","sections":[{"heading":"Affected Packages","arrayPath":"affected","limit":20,"itemVars":{"versionsCount":{"paths":["versions"],"format":"array_len_comma"},"versionsSample":{"paths":["versions"],"limit":12,"itemWrap":"`","join":", "},"fixedVersions":{"nestedSubValues":{"arrayPath":"ranges","subArrayField":"events","valueField":"fixed","limit":12,"join":", "}}},"columns":[{"header":"Ecosystem","paths":["package.ecosystem"]},{"header":"Package","paths":["package.name"],"code":true},{"header":"Affected Count","template":"{versionsCount}"},{"header":"Sample Versions","template":"{versionsSample}"},{"header":"Fixed","template":"{fixedVersions}"}]},{"heading":"References","arrayPath":"references","limit":20,"requireItemVar":"refUrl","collectLinkVars":["refUrl"],"itemVars":{"refUrl":{"paths":["url"],"requireHttps":true},"refType":{"paths":["type"]}},"columns":[{"header":"Type","template":"{refType}"},{"header":"URL","template":"{refUrl}"}]}],"linksVars":["osvUrl","ghsaUrl"]}}]},{"id":"outdoor-retail-specs","name":"Outdoor & Cycling Retail Spec Extractor","category":"commerce-social","description":"Strictly rate-limited and robots-enforced HTML adapter for REI, Backcountry, and Competitive Cyclist product pages and technical specification tables.","domains":["rei.com","www.rei.com","backcountry.com","www.backcountry.com","competitivecyclist.com","www.competitivecyclist.com"],"auth_mode":"html","min_interval_ms":5000,"max_concurrent":1,"strict_robots":true,"exampleUrls":["https://www.rei.com/product/230456/co-op-cycles-adv-22-bike","https://www.backcountry.com/santa-cruz-bicycles-hightower-c-s-mountain-bike","https://www.competitivecyclist.com/cervelo-caledonia-105-road-bike"],"htmlRoutes":[{"id":"outdoor-retail-specs","match":{"exactSegments":false},"mode":"outdoor_retail_specs_html"}]},{"id":"pacer-case-locator","name":"PACER Case Locator","category":"public-records","description":"Extracts public PACER informational and case-finder pages on pacer.uscourts.gov while honestly classifying login-gated portals (pcl.uscourts.gov, pacer.login.uscourts.gov) as login_wall.","domains":["pcl.uscourts.gov","pacer.uscourts.gov","ecf.dcd.uscourts.gov","pacer.login.uscourts.gov"],"auth_mode":"html","min_interval_ms":1500,"strict_robots":true,"exampleUrls":["https://pacer.uscourts.gov/find-case","https://pacer.uscourts.gov/","https://pcl.uscourts.gov/pcl/index.jsf"],"htmlRoutes":[{"id":"pacer-case-locator","match":{"hosts":["pcl.uscourts.gov","pacer.uscourts.gov","ecf.dcd.uscourts.gov","pacer.login.uscourts.gov"]},"mode":"pacer_case_locator_html"}]},{"id":"packagist","name":"Packagist PHP Composer Registry","category":"developer","description":"Upgrades packagist.org PHP Composer package pages to their official .json metadata feed.","domains":["packagist.org","www.packagist.org"],"exampleUrls":["https://packagist.org/packages/monolog/monolog"],"match":{"exactSegments":true,"pathSegments":["packages",{"param":"vendor","charset":"pkg"},{"param":"pkg","charset":"pkg"}]},"twin":{"fetchUrl":"https://packagist.org/packages/{vendor}/{pkg}.json","kind":"json","accept":"application/json"},"extract":{"rootPath":"package","requireFields":["name"],"vars":{"name":{"paths":["name"]},"desc":{"paths":["description"],"trim":true},"repo":{"paths":["repository"]},"stableVer":{"paths":["versions"],"firstNonMatchingKey":"dev"},"license":{"dynamicKeyPath":{"base":"versions","keyVar":"stableVer","subPath":"license"},"join":", "}},"titleTemplate":"{name} {stableVer} (Composer)","titleWhenVar":"stableVer","titleFallbackTemplate":"{name}","descriptionVar":"desc","introVar":"desc","bullets":[{"label":"Install","template":"`composer require {name}`"},{"label":"Latest Version","template":"`{stableVer}`","whenVar":"stableVer"},{"label":"License","template":"{license}","whenVar":"license"},{"label":"Repository","template":"{repo}","whenVar":"repo"}]}},{"id":"pinpoint","name":"Pinpoint ATS Job Boards","category":"jobs","description":"Upgrades .pinpointhq.com career portals to /postings.json with compensation, responsibilities, and workplace types.","domains":["*.pinpointhq.com"],"exampleUrls":["https://workwithus.pinpointhq.com/"],"routes":[{"match":{"hostSubdomain":{"suffix":".pinpointhq.com","param":"org","reserved":["www","app"]},"exactSegments":false,"pathSegments":["postings",{"param":"postId","charset":"pkg"}]},"twin":{"id":"pinpoint","fetchUrl":"https://{host}/postings.json","kind":"json","accept":"application/json"},"extract":{"findInArray":{"arrayPath":"data","matchField":"id","matchTemplate":"{postId}","endsWithField":"url","endsWithTemplate":"{postId}"},"vars":{"jobTitle":{"paths":["title"],"trim":true,"default":"Job Posting"},"loc":{"paths":["location.name"],"trim":true},"wp":{"paths":["workplace_type_text","workplace_type"],"trim":true},"cur":{"paths":["compensation_currency"],"trim":true,"default":"USD"},"compMin":{"paths":["compensation_minimum"],"excludeEquals":"0"},"compMax":{"paths":["compensation_maximum"],"excludeEquals":"0"},"compRange":{"template":"{cur} {compMin} – {compMax}","whenVars":["compMin","compMax"]},"compMinOnly":{"template":"{cur} {compMin}","whenVars":["compMin"]},"compMaxOnly":{"template":"{cur} – {compMax}","whenVars":["compMax"]},"compSub":{"template":"{compRange}","whenVars":["compRange"],"fallbackVar":"compMinOnly"},"comp":{"template":"{compSub}","whenVars":["compSub"],"fallbackVar":"compMaxOnly"},"desc":{"paths":["description"],"format":"html_to_md"},"resp":{"paths":["key_responsibilities"],"format":"html_to_md"},"skills":{"paths":["skills_knowledge_expertise"],"format":"html_to_md"},"benefits":{"paths":["benefits"],"format":"html_to_md"}},"titleTemplate":"{jobTitle} @ {org}","bullets":[{"label":"Company","template":"{org}"},{"label":"Location","template":"{loc}","whenVar":"loc"},{"label":"Workplace","template":"{wp}","whenVar":"wp"},{"label":"Compensation","template":"{comp}","whenVar":"comp"}],"sections":[{"heading":"Description","textVar":"desc"},{"heading":"Key Responsibilities","textVar":"resp"},{"heading":"Skills & Expertise","textVar":"skills"},{"heading":"Benefits","textVar":"benefits"}],"fallbackExtract":{"vars":{"count":{"paths":["data"],"format":"array_len"}},"requireVars":["count"],"titleTemplate":"{org} — Pinpoint Job Board ({count} open roles)","sections":[{"heading":"","arrayPath":"data","limit":100,"emptyText":"No open positions currently listed.","itemVars":{"pTitle":{"paths":["title"],"trim":true,"default":"Role"},"id":{"paths":["id"]},"rawUrl":{"paths":["url"],"requireHttps":true},"pUrl":{"template":"{rawUrl}","whenVars":["rawUrl"],"fallbackTemplate":"https://{host}/postings/{id}"},"loc":{"paths":["location.name"],"trim":true,"default":"-"},"wp":{"paths":["workplace_type_text","workplace_type"],"trim":true,"default":"-"},"cur":{"paths":["compensation_currency"],"trim":true,"default":"USD"},"compMin":{"paths":["compensation_minimum"],"excludeEquals":"0"},"compMax":{"paths":["compensation_maximum"],"excludeEquals":"0"},"compRange":{"template":"{cur} {compMin}–{compMax}","whenVars":["compMin","compMax"]},"compMinOnly":{"template":"{cur} {compMin}","whenVars":["compMin"]},"comp":{"template":"{compRange}","whenVars":["compRange"],"fallbackVar":"compMinOnly","default":"-"}},"collectLinkVars":["pUrl"],"columns":[{"header":"Role","template":"[{pTitle}]({pUrl})"},{"header":"Location","template":"{loc}"},{"header":"Workplace","template":"{wp}"},{"header":"Compensation","template":"{comp}"}]}]}}},{"match":{"hostSubdomain":{"suffix":".pinpointhq.com","param":"org","reserved":["www","app"]},"pathSegments":[{"param":"jobsLit","charset":"alnum","allowValues":["jobs","postings"],"optional":true}]},"twin":{"id":"pinpoint","fetchUrl":"https://{host}/postings.json","kind":"json","accept":"application/json"},"extract":{"vars":{"count":{"paths":["data"],"format":"array_len"}},"requireVars":["count"],"titleTemplate":"{org} — Pinpoint Job Board ({count} open roles)","sections":[{"heading":"","arrayPath":"data","limit":100,"emptyText":"No open positions currently listed.","itemVars":{"pTitle":{"paths":["title"],"trim":true,"default":"Role"},"id":{"paths":["id"]},"rawUrl":{"paths":["url"],"requireHttps":true},"pUrl":{"template":"{rawUrl}","whenVars":["rawUrl"],"fallbackTemplate":"https://{host}/postings/{id}"},"loc":{"paths":["location.name"],"trim":true,"default":"-"},"wp":{"paths":["workplace_type_text","workplace_type"],"trim":true,"default":"-"},"cur":{"paths":["compensation_currency"],"trim":true,"default":"USD"},"compMin":{"paths":["compensation_minimum"],"excludeEquals":"0"},"compMax":{"paths":["compensation_maximum"],"excludeEquals":"0"},"compRange":{"template":"{cur} {compMin}–{compMax}","whenVars":["compMin","compMax"]},"compMinOnly":{"template":"{cur} {compMin}","whenVars":["compMin"]},"comp":{"template":"{compRange}","whenVars":["compRange"],"fallbackVar":"compMinOnly","default":"-"}},"collectLinkVars":["pUrl"],"columns":[{"header":"Role","template":"[{pTitle}]({pUrl})"},{"header":"Location","template":"{loc}"},{"header":"Workplace","template":"{wp}"},{"header":"Compensation","template":"{comp}"}]}]}}]},{"id":"pkg-go-dev","name":"Go Packages (pkg.go.dev)","category":"developer","description":"Extracts Go module README and API documentation sections cleanly from pkg.go.dev.","domains":["pkg.go.dev"],"exampleUrls":["https://pkg.go.dev/github.com/coder/websocket"],"htmlRoutes":[{"match":{"minSegments":1},"mode":"dom","vars":{"title":{"cssText":["title"],"stripSuffix":"- Go Packages"},"readme":{"cssHtmlToMd":["div.UnitReadme-content"]},"docs":{"cssHtmlToMd":["div.Documentation-content"],"replaceAll":{"from":"¶","to":""}}},"requireBulletsOrVars":["readme","docs"],"titleTemplate":"{title}","sections":[{"heading":"Overview / README","textVar":"readme"},{"heading":"Documentation","textVar":"docs"}]}]},{"id":"podcasts-apple-lookup","name":"Apple Podcasts & iTunes Lookup","category":"commerce-social","description":"Extracts iTunes Lookup JSON for podcast metadata and Apple Podcasts HTML schema:show + serialized-server-data without cross-domain twins.","domains":["podcasts.apple.com","itunes.apple.com"],"auth_mode":"pub","exampleUrls":["https://itunes.apple.com/lookup?id=1200361736&entity=podcast","https://podcasts.apple.com/us/podcast/the-daily/id1200361736"],"routes":[{"match":{"hosts":["itunes.apple.com"],"pathEquals":["/lookup"],"queryParams":[{"name":"id","param":"itunesId","charset":"digits","minLen":3,"maxLen":20}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"apple_podcast_lookup_json"}}],"htmlRoutes":[{"id":"podcasts-apple-lookup","match":{"hosts":["podcasts.apple.com"],"exactSegments":false},"mode":"podcasts_apple_html"}]},{"id":"polymarket","name":"Polymarket Prediction Markets","category":"finance","description":"Upgrades polymarket.com/event/ pages to gamma-api.polymarket.com JSON with live outcome probabilities, volume, and liquidity.","domains":["polymarket.com","www.polymarket.com"],"exampleUrls":["https://polymarket.com/event/fed-decision-in-december"],"match":{"exactSegments":false,"pathSegments":["event",{"param":"slug","charset":"alnum_dash","minLen":2,"maxLen":140}]},"twin":{"fetchUrl":"https://gamma-api.polymarket.com/events?slug={slug}","kind":"json","accept":"application/json"},"extract":{"unwrapFirstArrayElement":true,"requireFields":["title"],"vars":{"title":{"paths":["title"],"trim":true},"desc":{"paths":["description"],"trim":true},"descShort":{"paths":["description"],"trim":true,"sliceMax":260},"vol":{"paths":["volume"],"format":"usd_compact"},"liq":{"paths":["liquidity"],"format":"usd_compact"},"endDate":{"paths":["endDate"],"sliceMax":10},"status":{"paths":["closed"],"format":"bool_map","trueValue":"Closed / Resolved","falseValue":"Active"}},"titleTemplate":"{title}","descriptionVar":"descShort","bullets":[{"label":"Status","template":"{status}"},{"label":"Total Volume","template":"{vol}","whenVar":"vol"},{"label":"Liquidity","template":"{liq}","whenVar":"liq"},{"label":"End Date","template":"{endDate}","whenVar":"endDate"}],"sections":[{"heading":"Market Odds","arrayPath":"markets","limit":25,"columns":[{"header":"Market / Outcome","paths":["groupItemTitle","question"],"fallbackVar":"title"},{"header":"Implied Probability","format":"paired_percent","outcomesField":"outcomes","pricesField":"outcomePrices","defaultOutcomes":["Yes","No"]},{"header":"Volume","paths":["volume"],"format":"usd_compact"}]},{"heading":"Resolution Rules","textVar":"desc"}]}},{"id":"powerreviews","name":"PowerReviews Product Reviews","category":"commerce-social","description":"Opt-in page-key adapter for PowerReviews Read API reviews; defaults OFF and falls back cleanly to HTML/JSON-LD when disabled.","domains":["readservices-b2c.powerreviews.com","www.skechers.com"],"universalEngine":true,"auth_mode":"page-key","requires_page_key_opt_in":true,"exampleUrls":["https://readservices-b2c.powerreviews.com/m/8162/l/en_US/product/177197/reviews?apikey=412df53d-8be4-4d9e-8657-e8c846f08b1d"],"routes":[{"match":{"hosts":["readservices-b2c.powerreviews.com"],"pathSegments":["m",{"param":"merchantId","charset":"alnum_dash","minLen":1,"maxLen":40},"l",{"param":"locale","charset":"alnum_dash","minLen":2,"maxLen":24},"product",{"param":"pageId","charset":"pkg","minLen":1,"maxLen":120},"reviews"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"jsonMode":"powerreviews_reviews"}}],"htmlRoutes":[{"id":"powerreviews","match":{"exactSegments":false},"mode":"powerreviews_html"}]},{"id":"prestashop","name":"PrestaShop Storefronts","category":"commerce-social","description":"Extracts PrestaShop storefront JSON-LD, data-product attributes, features tables, and ?action=quickview AJAX JSON payloads.","domains":["www.esprit-barbecue.fr"],"universalEngine":true,"auth_mode":"html","exampleUrls":["https://www.esprit-barbecue.fr/barbecues/3364-master-touch-gbs-premium-e-5770-noir-weber-0077924129551.html"],"routes":[{"match":{"anyOf":[{"hosts":["www.esprit-barbecue.fr"],"queryParams":[{"name":"action","param":"action","allowValues":["quickview"],"charset":"alnum"}]},{"pathSuffix":".html","queryParams":[{"name":"action","param":"action","allowValues":["quickview"],"charset":"alnum"},{"name":"ajax","param":"ajax","allowValues":["1"],"charset":"digits"}]}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"commerceMode":"prestashop_quickview"}}],"htmlRoutes":[{"id":"prestashop","match":{"exactSegments":false},"mode":"prestashop_html"}]},{"id":"product-feed-discovery","name":"Storefront Product Feed Discovery","category":"commerce-social","description":"Universal XML/Atom/RSS parser for storefront product discovery endpoints (/products.atom, /feed/, and /sitemap_products_*.xml).","domains":["www.gymshark.com","henryrose.com","janji.com"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://www.gymshark.com/sitemap_products_1.xml","https://henryrose.com/sitemap_products_1.xml?from=1645692747866&to=15498254843994","https://janji.com/sitemap_products_1.xml?from=310052787&to=15293477683563"],"routes":[{"match":{"excludeHosts":["feeds.npr.org","npr.org","www.npr.org","pbs.org","www.pbs.org","prnewswire.com","www.prnewswire.com","businesswire.com","www.businesswire.com","globenewswire.com","www.globenewswire.com","medium.com","www.medium.com","*.medium.com","ghost.org","www.ghost.org","*.ghost.io","buttondown.com","www.buttondown.com","buttondown.email","rss.beehiiv.com","milkroad.beehiiv.com","*.beehiiv.com","wordpress.org","www.wordpress.org","*.wordpress.com","weworkremotely.com","www.weworkremotely.com","bicycleretailer.com","www.bicycleretailer.com","earthquake.usgs.gov","api.nasa.gov","recruiting.paylocity.com","app.jazz.co","*.applytojob.com","www.fpds.gov","fpds.gov","*.substack.com","substack.com","careers.*.com","jobs.*.com"],"anyOf":[{"pathEquals":["/products.atom","/feed","/feed/"]},{"pathPrefix":"/sitemap_products_","pathSuffix":".xml"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"application/atom+xml","maxBytes":4194304},"extract":{"textMode":"product_feed_discovery_xml"}}]},{"id":"propublica-nonprofits","name":"ProPublica Nonprofit Explorer","category":"public-records","description":"Upgrades ProPublica Nonprofit Explorer organization pages to keyless Form 990 JSON API v2 with HTML fallback.","domains":["projects.propublica.org"],"auth_mode":"pub","exampleUrls":["https://projects.propublica.org/nonprofits/organizations/521693387","https://projects.propublica.org/nonprofits/api/v2/organizations/521693387.json"],"routes":[{"match":{"hosts":["projects.propublica.org"],"exactSegments":false,"pathSegments":["nonprofits","organizations",{"param":"ein","charset":"digits","minLen":8,"maxLen":10}]},"twin":{"fetchUrl":"https://projects.propublica.org/nonprofits/api/v2/organizations/{ein}.json","kind":"json","accept":"application/json","auth_mode":"pub","maxBytes":2097152},"extract":{"jsonMode":"propublica_nonprofit_json"}},{"match":{"hosts":["projects.propublica.org"],"pathPrefix":"/nonprofits/api/v2/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"pub","maxBytes":2097152},"extract":{"jsonMode":"propublica_nonprofit_json"}}],"htmlRoutes":[{"id":"propublica-nonprofits","match":{"hosts":["projects.propublica.org"],"pathPrefix":"/nonprofits/","exactSegments":false},"mode":"propublica_nonprofit_html"}]},{"id":"pubchem","name":"PubChem Chemical Compounds (NCBI)","category":"research-health","description":"Upgrades pubchem.ncbi.nlm.nih.gov/compound/ to NCBI PUG-REST compound properties + pharmacological descriptions (with HTML JSON-LD fallback).","domains":["pubchem.ncbi.nlm.nih.gov"],"exampleUrls":["https://pubchem.ncbi.nlm.nih.gov/compound/2244"],"routes":[{"match":{"exactSegments":false,"pathSegments":["compound",{"param":"cid","charset":"digits","minLen":1,"maxLen":12}]},"twin":{"fetchUrl":"https://pubchem.ncbi.nlm.nih.gov/rest/pug_view/data/compound/{cid}/JSON/?heading=Names+and+Identifiers","kind":"json","accept":"application/json"},"extract":{"rootPath":"Record","requireFields":["RecordTitle"],"vars":{"cidVal":{"paths":["RecordNumber"],"fallbackTemplate":"{cid}"},"recTitle":{"paths":["RecordTitle"],"trim":true,"fallbackTemplate":"Compound {cidVal}"},"formula":{"format":"pubchem_toc","tocHeading":"Molecular Formula"},"iupac":{"format":"pubchem_toc","tocHeading":"IUPAC Name"},"inchiKey":{"format":"pubchem_toc","tocHeading":"InChIKey"},"canonicalSmiles":{"format":"pubchem_toc","tocHeading":"Canonical SMILES"},"smilesRaw":{"format":"pubchem_toc","tocHeading":"SMILES"},"smiles":{"template":"{smilesRaw}","whenVars":["smilesRaw"],"fallbackVar":"canonicalSmiles"},"cas":{"format":"pubchem_toc","tocHeading":"CAS"},"desc":{"format":"pubchem_toc","tocHeading":"Record Description"},"descShort":{"format":"pubchem_toc","tocHeading":"Record Description","sliceMax":260}},"titleTemplate":"{recTitle} (PubChem CID {cidVal})","descriptionVar":"descShort","bullets":[{"label":"PubChem CID","template":"`{cidVal}`"},{"label":"Molecular Formula","template":"`{formula}`","whenVar":"formula"},{"label":"CAS Number","template":"`{cas}`","whenVar":"cas"},{"label":"IUPAC Name","template":"`{iupac}`","whenVar":"iupac"},{"label":"InChIKey","template":"`{inchiKey}`","whenVar":"inchiKey"},{"label":"SMILES","template":"`{smiles}`","whenVar":"smiles"}],"sections":[{"heading":"Summary","textVar":"desc"}],"linkTemplates":["https://pubchem.ncbi.nlm.nih.gov/compound/{cidVal}"]}}],"htmlRoutes":[{"match":{"exactSegments":false,"pathSegments":["compound",{"param":"slug","charset":"url_seg"}]},"mode":"dom","jsonLdTypes":["MolecularEntity","ChemicalSubstance"],"requireVars":["title"],"requireBulletsOrVars":["desc"],"vars":{"title":{"jsonLdPaths":["name"],"metaKeys":["og:title"],"stripRegexSuffix":"\\s*\\|\\s*C\\d+.*?\\s*-\\s*PubChem$"},"formula":{"jsonLdPaths":["molecularFormula"]},"weightValObj":{"jsonLdPaths":["molecularWeight.value"]},"weightFromObj":{"template":"{weightValObj} g/mol","whenVars":["weightValObj"]},"weight":{"jsonLdPaths":["molecularWeight"],"fallbackVar":"weightFromObj"},"iupac":{"jsonLdPaths":["iupacName"]},"inchiKey":{"jsonLdPaths":["inChIKey"]},"smiles":{"jsonLdPaths":["smiles"],"limit":1},"desc":{"metaKeys":["description"]},"descShort":{"metaKeys":["description"],"sliceMax":260}},"titleTemplate":"{title} (PubChem)","descriptionVar":"descShort","bullets":[{"label":"Molecular Formula","template":"`{formula}`","whenVar":"formula"},{"label":"Molecular Weight","template":"{weight}","whenVar":"weight"},{"label":"IUPAC Name","template":"`{iupac}`","whenVar":"iupac"},{"label":"InChIKey","template":"`{inchiKey}`","whenVar":"inchiKey"},{"label":"SMILES","template":"`{smiles}`","whenVar":"smiles"}],"sections":[{"heading":"Summary","textVar":"desc"}],"appendCurrentMdDelta":{"minExtraChars":200}}]},{"id":"public-booking","name":"Public Booking (Calendly & Acuity Scheduling)","category":"commerce-social","description":"Extracts public Calendly event types via queryless /api/booking/profiles/{profile}/event_types (honoring Disallow: /*?*) and Calendly/Acuity HTML booking pages, rejecting unavailability_reason error-only payloads.","domains":["calendly.com","www.calendly.com","acuityscheduling.com","app.acuityscheduling.com"],"auth_mode":"pub","strict_robots":true,"exampleUrls":["https://calendly.com/api/booking/profiles/demo/event_types","https://calendly.com/demo","https://calendly.com/calendly-sales"],"routes":[{"match":{"hosts":["calendly.com","www.calendly.com"],"exactSegments":true,"pathSegments":[{"param":"profile","charset":"slug","minLen":2,"maxLen":80,"reserved":["app","api","d","s","login","signup","pricing","features","solutions","enterprise","integrations","resources","blog","about","careers","legal","privacy","terms","help","abuse_reports","error","404","not-found"]}]},"twin":{"fetchUrl":"https://calendly.com/api/booking/profiles/{profile}/event_types","kind":"json","accept":"application/json","maxBytes":1048576},"extract":{"jsonMode":"calendly_booking_json"}},{"match":{"hosts":["calendly.com","www.calendly.com"],"pathPrefix":"/api/booking/profiles/","exactSegments":false},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":1048576},"extract":{"jsonMode":"calendly_booking_json"}}],"htmlRoutes":[{"id":"public-booking","mode":"booking_html","match":{"hosts":["calendly.com","www.calendly.com","acuityscheduling.com","app.acuityscheduling.com"],"exactSegments":false}}]},{"id":"public-forms","name":"Public Forms (Typeform & Jotform)","category":"commerce-social","description":"Extracts public Typeform field definitions via api.typeform.com/forms/{formId} or window.rendererData HTML and Jotform forms via HTML field labels/configs, rejecting typeform-incorrectURL soft-404 redirects.","domains":["typeform.com","www.typeform.com","form.typeform.com","api.typeform.com","jotform.com","www.jotform.com","form.jotform.com"],"universalEngine":true,"auth_mode":"pub","strict_robots":true,"exampleUrls":["https://tfsales.typeform.com/to/PxcVKQGb","https://api.typeform.com/forms/PxcVKQGb","https://form.jotform.com/240912145384959"],"routes":[{"match":{"hostSubdomain":{"suffix":".typeform.com","param":"org","reserved":["www","api","admin","help","developer","login","auth"]},"exactSegments":true,"pathSegments":["to",{"param":"formId","charset":"slug","minLen":4,"maxLen":32}]},"twin":{"fetchUrl":"https://api.typeform.com/forms/{formId}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"typeform_json"}},{"match":{"hosts":["typeform.com","www.typeform.com"],"exactSegments":true,"pathSegments":["to",{"param":"formId","charset":"slug","minLen":4,"maxLen":32}]},"twin":{"fetchUrl":"https://api.typeform.com/forms/{formId}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"typeform_json"}},{"match":{"hosts":["api.typeform.com"],"exactSegments":true,"pathSegments":["forms",{"param":"formId","charset":"slug","minLen":4,"maxLen":32}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"typeform_json"}}],"htmlRoutes":[{"id":"public-forms","mode":"typeform_html","match":{"anyOf":[{"hostSubdomain":{"suffix":".typeform.com","param":"org","reserved":["api","admin","login","auth"]},"exactSegments":false},{"hosts":["typeform.com","www.typeform.com","form.typeform.com"],"exactSegments":false}]}},{"id":"public-forms","mode":"jotform_html","match":{"anyOf":[{"hosts":["jotform.com","www.jotform.com","form.jotform.com"],"exactSegments":false},{"hostSubdomain":{"suffix":".jotform.com","param":"org","reserved":["api","www","form","login","auth"]},"exactSegments":false}]}}]},{"id":"public-job-feeds","name":"Public Open Job Feeds (WWR, Himalayas, Working Nomads, The Muse, Jobicy, Arbeitnow & RemoteOK)","category":"jobs","description":"Formats robots.txt-allowed keyless public job feeds (We Work Remotely RSS, Himalayas, Working Nomads, The Muse, Jobicy, Arbeitnow, and RemoteOK) into clean job tables.","domains":["weworkremotely.com","www.weworkremotely.com","himalayas.app","www.himalayas.app","www.workingnomads.com","workingnomads.com","www.themuse.com","themuse.com","jobicy.com","www.arbeitnow.com","arbeitnow.com","remoteok.com"],"exampleUrls":["https://weworkremotely.com/remote-jobs.rss","https://himalayas.app/jobs/api?limit=50","https://www.workingnomads.com/api/exposed_jobs/","https://www.themuse.com/api/public/jobs?page=1","https://jobicy.com/api/v2/remote-jobs?count=20","https://remoteok.com/api"],"routes":[{"match":{"hosts":["weworkremotely.com","www.weworkremotely.com"],"pathSuffix":".rss"},"twin":{"id":"weworkremotely-feed","fetchUrl":"{requestUrl}","kind":"text","accept":"application/rss+xml"},"extract":{"xml":{"mode":"items_table","requireAnyTags":["rss","channel"],"itemTag":"item","titleTemplate":"We Work Remotely Jobs ({itemCount})","limit":50,"collectLinkVar":"jLink","emitTotals":true,"itemVars":{"company":{"tags":["title"],"splitColonPart":0,"default":"We Work Remotely"},"role":{"tags":["title"],"splitColonPart":1,"default":"Role"},"jLink":{"tags":["link"]},"region":{"tags":["region"],"default":"Remote"},"category":{"tags":["category"],"default":"-"},"pubDate":{"tags":["pubDate"]},"pubDisplay":{"tags":["pubDate","category"],"sliceMax":16,"default":"-"}},"recordFields":{"title":"{role}","company":"{company}","url":"{jLink}","region":"{region}","category":"{category}","postedAt":"{pubDate}","source":"weworkremotely"},"columns":[{"header":"Role","template":"[{role}]({jLink})"},{"header":"Company","template":"{company}"},{"header":"Region","template":"{region}"},{"header":"Published","template":"{pubDisplay}"}]}}},{"match":{"hosts":["weworkremotely.com","www.weworkremotely.com"],"pathEquals":["/remote-jobs","/remote-jobs/"]},"twin":{"id":"weworkremotely-feed","fetchUrl":"https://weworkremotely.com/remote-jobs.rss","kind":"text","accept":"application/rss+xml"},"extract":{"xml":{"mode":"items_table","requireAnyTags":["rss","channel"],"itemTag":"item","titleTemplate":"We Work Remotely Jobs ({itemCount})","limit":50,"collectLinkVar":"jLink","emitTotals":true,"itemVars":{"company":{"tags":["title"],"splitColonPart":0,"default":"We Work Remotely"},"role":{"tags":["title"],"splitColonPart":1,"default":"Role"},"jLink":{"tags":["link"]},"region":{"tags":["region"],"default":"Remote"},"category":{"tags":["category"],"default":"-"},"pubDate":{"tags":["pubDate"]},"pubDisplay":{"tags":["pubDate","category"],"sliceMax":16,"default":"-"}},"recordFields":{"title":"{role}","company":"{company}","url":"{jLink}","region":"{region}","category":"{category}","postedAt":"{pubDate}","source":"weworkremotely"},"columns":[{"header":"Role","template":"[{role}]({jLink})"},{"header":"Company","template":"{company}"},{"header":"Region","template":"{region}"},{"header":"Published","template":"{pubDisplay}"}]}}},{"match":{"hosts":["himalayas.app","www.himalayas.app"],"pathPrefix":"/jobs/api"},"twin":{"id":"himalayas-feed","fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"vars":{"jobCount":{"paths":["jobs"],"format":"array_len"},"totalFmt":{"paths":["totalCount"],"format":"int_comma","fallbackTemplate":"{jobCount}"}},"requireVars":["jobCount"],"titleTemplate":"Himalayas Remote Jobs ({jobCount} of {totalFmt})","sections":[{"heading":"","arrayPath":"jobs","limit":50,"emptyText":"No open positions currently listed.","paginationMeta":{"totalPath":"totalCount","cursorMode":"offset"},"itemVars":{"jTitle":{"paths":["title"],"trim":true,"default":"Role"},"company":{"paths":["companyName"],"trim":true,"default":"-"},"appUrl":{"paths":["applicationLink"],"requireHttps":true},"guidUrl":{"paths":["guid"],"requireHttps":true},"jUrl":{"template":"{appUrl}","whenVars":["appUrl"],"fallbackVar":"guidUrl"},"locs":{"paths":["locationRestrictions"],"join":", ","default":"Worldwide"},"cur":{"paths":["currency"],"trim":true,"default":"USD"},"minSal":{"paths":["minSalary"],"format":"int_comma","excludeEquals":"0"},"maxSal":{"paths":["maxSalary"],"format":"int_comma","excludeEquals":"0"},"salRange":{"template":"{cur} {minSal}–{maxSal}","whenVars":["minSal","maxSal"]},"salMinOnly":{"template":"{cur} {minSal}","whenVars":["minSal"]},"sal":{"template":"{salRange}","whenVars":["salRange"],"fallbackVar":"salMinOnly","default":"-"},"roleCell":{"template":"[{jTitle}]({jUrl})","whenVars":["jUrl"],"fallbackVar":"jTitle"}},"collectLinkVars":["jUrl"],"recordFields":{"title":"{jTitle}","company":"{company}","url":"{jUrl}","locations":"{locs}","salary":"{sal}","source":"himalayas"},"columns":[{"header":"Role","template":"{roleCell}"},{"header":"Company","template":"{company}"},{"header":"Region","template":"{locs}"},{"header":"Salary","template":"{sal}"}]}]}},{"match":{"hosts":["himalayas.app","www.himalayas.app"],"pathPrefix":"/jobs"},"twin":{"id":"himalayas-feed","fetchUrl":"https://himalayas.app/jobs/api?limit=50","kind":"json","accept":"application/json"},"extract":{"vars":{"jobCount":{"paths":["jobs"],"format":"array_len"},"totalFmt":{"paths":["totalCount"],"format":"int_comma","fallbackTemplate":"{jobCount}"}},"requireVars":["jobCount"],"titleTemplate":"Himalayas Remote Jobs ({jobCount} of {totalFmt})","sections":[{"heading":"","arrayPath":"jobs","limit":50,"emptyText":"No open positions currently listed.","paginationMeta":{"totalPath":"totalCount","cursorMode":"offset"},"itemVars":{"jTitle":{"paths":["title"],"trim":true,"default":"Role"},"company":{"paths":["companyName"],"trim":true,"default":"-"},"appUrl":{"paths":["applicationLink"],"requireHttps":true},"guidUrl":{"paths":["guid"],"requireHttps":true},"jUrl":{"template":"{appUrl}","whenVars":["appUrl"],"fallbackVar":"guidUrl"},"locs":{"paths":["locationRestrictions"],"join":", ","default":"Worldwide"},"cur":{"paths":["currency"],"trim":true,"default":"USD"},"minSal":{"paths":["minSalary"],"format":"int_comma","excludeEquals":"0"},"maxSal":{"paths":["maxSalary"],"format":"int_comma","excludeEquals":"0"},"salRange":{"template":"{cur} {minSal}–{maxSal}","whenVars":["minSal","maxSal"]},"salMinOnly":{"template":"{cur} {minSal}","whenVars":["minSal"]},"sal":{"template":"{salRange}","whenVars":["salRange"],"fallbackVar":"salMinOnly","default":"-"},"roleCell":{"template":"[{jTitle}]({jUrl})","whenVars":["jUrl"],"fallbackVar":"jTitle"}},"collectLinkVars":["jUrl"],"recordFields":{"title":"{jTitle}","company":"{company}","url":"{jUrl}","locations":"{locs}","salary":"{sal}","source":"himalayas"},"columns":[{"header":"Role","template":"{roleCell}"},{"header":"Company","template":"{company}"},{"header":"Region","template":"{locs}"},{"header":"Salary","template":"{sal}"}]}]}},{"match":{"hosts":["www.workingnomads.com","workingnomads.com"],"pathPrefix":"/api/exposed_jobs"},"twin":{"id":"workingnomads-feed","fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"wrapRootArrayAs":"jobs","vars":{"jobCount":{"paths":["jobs"],"format":"array_len"}},"requireVars":["jobCount"],"titleTemplate":"Working Nomads Remote Jobs ({jobCount})","sections":[{"heading":"","arrayPath":"jobs","limit":50,"emptyText":"No open positions currently listed.","paginationMeta":{"cursorMode":"offset"},"itemVars":{"jTitle":{"paths":["title"],"trim":true,"default":"Role"},"company":{"paths":["company_name"],"trim":true,"default":"-"},"jUrl":{"paths":["url"],"requireHttps":true},"loc":{"paths":["location"],"trim":true,"default":"Remote"},"pub":{"paths":["pub_date"],"sliceMax":10,"trim":true,"default":"-"},"roleCell":{"template":"[{jTitle}]({jUrl})","whenVars":["jUrl"],"fallbackVar":"jTitle"}},"collectLinkVars":["jUrl"],"recordFields":{"title":"{jTitle}","company":"{company}","url":"{jUrl}","location":"{loc}","postedAt":"{pub}","source":"workingnomads"},"columns":[{"header":"Role","template":"{roleCell}"},{"header":"Company","template":"{company}"},{"header":"Location","template":"{loc}"},{"header":"Published","template":"{pub}"}]}]}},{"match":{"hosts":["www.workingnomads.com","workingnomads.com"],"pathEquals":["/jobs","/jobs/"]},"twin":{"id":"workingnomads-feed","fetchUrl":"https://www.workingnomads.com/api/exposed_jobs/","kind":"json","accept":"application/json"},"extract":{"wrapRootArrayAs":"jobs","vars":{"jobCount":{"paths":["jobs"],"format":"array_len"}},"requireVars":["jobCount"],"titleTemplate":"Working Nomads Remote Jobs ({jobCount})","sections":[{"heading":"","arrayPath":"jobs","limit":50,"emptyText":"No open positions currently listed.","paginationMeta":{"cursorMode":"offset"},"itemVars":{"jTitle":{"paths":["title"],"trim":true,"default":"Role"},"company":{"paths":["company_name"],"trim":true,"default":"-"},"jUrl":{"paths":["url"],"requireHttps":true},"loc":{"paths":["location"],"trim":true,"default":"Remote"},"pub":{"paths":["pub_date"],"sliceMax":10,"trim":true,"default":"-"},"roleCell":{"template":"[{jTitle}]({jUrl})","whenVars":["jUrl"],"fallbackVar":"jTitle"}},"collectLinkVars":["jUrl"],"recordFields":{"title":"{jTitle}","company":"{company}","url":"{jUrl}","location":"{loc}","postedAt":"{pub}","source":"workingnomads"},"columns":[{"header":"Role","template":"{roleCell}"},{"header":"Company","template":"{company}"},{"header":"Location","template":"{loc}"},{"header":"Published","template":"{pub}"}]}]}},{"match":{"hosts":["www.themuse.com","themuse.com"],"pathPrefix":"/api/public/jobs"},"twin":{"id":"themuse-feed","fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"vars":{"resCount":{"paths":["results"],"format":"array_len"},"totalFmt":{"paths":["total"],"format":"int_comma","fallbackTemplate":"{resCount}"}},"requireVars":["resCount"],"titleTemplate":"The Muse Public Jobs ({resCount} of {totalFmt})","sections":[{"heading":"","arrayPath":"results","limit":50,"emptyText":"No open positions currently listed.","itemVars":{"jTitle":{"paths":["name"],"trim":true,"default":"Role"},"co":{"paths":["company.name"],"trim":true,"default":"-"},"locs":{"paths":["locations"],"subField":"name","join":"; ","default":"-"},"lUrl":{"paths":["refs.landing_page"],"requireHttps":true},"pub":{"paths":["publication_date"],"sliceMax":10,"trim":true,"default":"-"},"roleCell":{"template":"[{jTitle}]({lUrl})","whenVars":["lUrl"],"fallbackVar":"jTitle"}},"collectLinkVars":["lUrl"],"columns":[{"header":"Role","template":"{roleCell}"},{"header":"Company","template":"{co}"},{"header":"Locations","template":"{locs}"},{"header":"Published","template":"{pub}"}]}]}},{"match":{"hosts":["jobicy.com"],"pathPrefix":"/api/v2/remote-jobs"},"twin":{"id":"jobicy-feed","fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"vars":{"jobCount":{"paths":["jobs"],"format":"array_len"}},"requireVars":["jobCount"],"titleTemplate":"Jobicy Remote Jobs ({jobCount})","sections":[{"heading":"","arrayPath":"jobs","limit":50,"emptyText":"No open positions currently listed.","itemVars":{"jTitle":{"paths":["jobTitle"],"format":"strip_tags","trim":true,"default":"Role"},"jUrl":{"paths":["url"],"requireHttps":true},"company":{"paths":["companyName"],"trim":true,"default":"-"},"geo":{"paths":["jobGeo"],"trim":true,"default":"Remote"},"cur":{"paths":["salaryCurrency"],"trim":true,"default":"USD"},"salMin":{"paths":["annualSalaryMin"],"excludeEquals":"0"},"salMax":{"paths":["annualSalaryMax"],"excludeEquals":"0"},"salRange":{"template":"{cur} {salMin}–{salMax}","whenVars":["salMin","salMax"]},"salMinOnly":{"template":"{cur} {salMin}","whenVars":["salMin"]},"sal":{"template":"{salRange}","whenVars":["salRange"],"fallbackVar":"salMinOnly","default":"-"},"roleCell":{"template":"[{jTitle}]({jUrl})","whenVars":["jUrl"],"fallbackVar":"jTitle"}},"collectLinkVars":["jUrl"],"columns":[{"header":"Role","template":"{roleCell}"},{"header":"Company","template":"{company}"},{"header":"Region","template":"{geo}"},{"header":"Annual Salary","template":"{sal}"}]}]}},{"match":{"anyOf":[{"hosts":["jobicy.com"],"pathEquals":["/jobs-rss-feed","/jobs-rss-feed/"]},{"hosts":["jobicy.com"],"pathPrefix":"/remote-"}]},"twin":{"id":"jobicy-feed","fetchUrl":"https://jobicy.com/api/v2/remote-jobs?count=30","kind":"json","accept":"application/json"},"extract":{"vars":{"jobCount":{"paths":["jobs"],"format":"array_len"}},"requireVars":["jobCount"],"titleTemplate":"Jobicy Remote Jobs ({jobCount})","sections":[{"heading":"","arrayPath":"jobs","limit":50,"emptyText":"No open positions currently listed.","itemVars":{"jTitle":{"paths":["jobTitle"],"format":"strip_tags","trim":true,"default":"Role"},"jUrl":{"paths":["url"],"requireHttps":true},"company":{"paths":["companyName"],"trim":true,"default":"-"},"geo":{"paths":["jobGeo"],"trim":true,"default":"Remote"},"cur":{"paths":["salaryCurrency"],"trim":true,"default":"USD"},"salMin":{"paths":["annualSalaryMin"],"excludeEquals":"0"},"salMax":{"paths":["annualSalaryMax"],"excludeEquals":"0"},"salRange":{"template":"{cur} {salMin}–{salMax}","whenVars":["salMin","salMax"]},"salMinOnly":{"template":"{cur} {salMin}","whenVars":["salMin"]},"sal":{"template":"{salRange}","whenVars":["salRange"],"fallbackVar":"salMinOnly","default":"-"},"roleCell":{"template":"[{jTitle}]({jUrl})","whenVars":["jUrl"],"fallbackVar":"jTitle"}},"collectLinkVars":["jUrl"],"columns":[{"header":"Role","template":"{roleCell}"},{"header":"Company","template":"{company}"},{"header":"Region","template":"{geo}"},{"header":"Annual Salary","template":"{sal}"}]}]}},{"match":{"hosts":["www.arbeitnow.com","arbeitnow.com"],"pathPrefix":"/api/job-board-api"},"twin":{"id":"arbeitnow-feed","fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"vars":{"jobCount":{"paths":["data"],"format":"array_len"}},"requireVars":["jobCount"],"titleTemplate":"Arbeitnow Job Feed ({jobCount})","sections":[{"heading":"","arrayPath":"data","limit":50,"emptyText":"No open positions currently listed.","itemVars":{"jTitle":{"paths":["title"],"trim":true,"default":"Role"},"jUrl":{"paths":["url"],"requireHttps":true},"company":{"paths":["company_name"],"trim":true,"default":"-"},"loc":{"paths":["location"],"trim":true,"default":"-"},"wp":{"paths":["remote"],"format":"bool_map","trueValue":"Remote","falseValue":"On-site"},"roleCell":{"template":"[{jTitle}]({jUrl})","whenVars":["jUrl"],"fallbackVar":"jTitle"}},"collectLinkVars":["jUrl"],"columns":[{"header":"Role","template":"{roleCell}"},{"header":"Company","template":"{company}"},{"header":"Location","template":"{loc}"},{"header":"Workplace","template":"{wp}"}]}]}},{"match":{"hosts":["www.arbeitnow.com","arbeitnow.com"],"pathEquals":["/jobs","/jobs/"]},"twin":{"id":"arbeitnow-feed","fetchUrl":"https://www.arbeitnow.com/api/job-board-api","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"vars":{"jobCount":{"paths":["data"],"format":"array_len"}},"requireVars":["jobCount"],"titleTemplate":"Arbeitnow Job Feed ({jobCount})","sections":[{"heading":"","arrayPath":"data","limit":50,"emptyText":"No open positions currently listed.","itemVars":{"jTitle":{"paths":["title"],"trim":true,"default":"Role"},"jUrl":{"paths":["url"],"requireHttps":true},"company":{"paths":["company_name"],"trim":true,"default":"-"},"loc":{"paths":["location"],"trim":true,"default":"-"},"wp":{"paths":["remote"],"format":"bool_map","trueValue":"Remote","falseValue":"On-site"},"roleCell":{"template":"[{jTitle}]({jUrl})","whenVars":["jUrl"],"fallbackVar":"jTitle"}},"collectLinkVars":["jUrl"],"columns":[{"header":"Role","template":"{roleCell}"},{"header":"Company","template":"{company}"},{"header":"Location","template":"{loc}"},{"header":"Workplace","template":"{wp}"}]}]}},{"match":{"anyOf":[{"hosts":["remoteok.com"],"pathSegments":[]},{"hosts":["remoteok.com"],"pathSegments":["api"]},{"hosts":["remoteok.com"],"pathPrefix":"/remote-","pathSuffix":"-jobs","pathSegments":[{"param":"catTag","charset":"alnum_dash","stripPrefix":"remote-","stripSuffix":"-jobs","transform":"lower"}]},{"hosts":["remoteok.com"],"pathPrefix":"/remote-","pathSuffix":"-jobs/","pathSegments":[{"param":"catTag","charset":"alnum_dash","stripPrefix":"remote-","stripSuffix":"-jobs","transform":"lower"}]}]},"twin":{"id":"remoteok-feed","fetchUrl":"https://remoteok.com/api","kind":"json","accept":"application/json"},"extract":{"wrapRootArrayAs":"jobs","vars":{"rawCount":{"paths":["jobs"],"format":"array_len"},"dedupCount":{"default":"{dedupCount}"}},"requireVars":["rawCount"],"titleTemplate":"RemoteOK Remote Jobs ({dedupCount})","sections":[{"heading":"","arrayPath":"jobs","limit":50,"emptyText":"No open positions currently listed.","filter":{"requireField":"position","tagFilterParam":{"param":"catTag","skipIfEquals":"dev","tagsField":"tags"}},"itemVars":{"pos":{"paths":["position"],"trim":true,"default":"Role"},"jUrl":{"paths":["url"],"requireHttps":true},"company":{"paths":["company"],"trim":true,"default":"-"},"loc":{"paths":["location"],"trim":true,"default":"Remote"},"salMin":{"paths":["salary_min"],"excludeEquals":"0"},"salMax":{"paths":["salary_max"],"excludeEquals":"0"},"salRange":{"template":"${salMin}–${salMax}","whenVars":["salMin","salMax"]},"salMinOnly":{"template":"${salMin}","whenVars":["salMin"]},"sal":{"template":"{salRange}","whenVars":["salRange"],"fallbackVar":"salMinOnly","default":"-"},"roleCell":{"template":"[{pos}]({jUrl})","whenVars":["jUrl"],"fallbackVar":"pos"}},"collectLinkVars":["jUrl"],"columns":[{"header":"Role","template":"{roleCell}"},{"header":"Company","template":"{company}"},{"header":"Location","template":"{loc}"},{"header":"Salary","template":"{sal}"}]}]}}]},{"id":"public-share-links","name":"Public Share Links (Google Docs/Sheets, OneDrive, Dropbox, Box)","category":"commerce-social","description":"Extracts public Google Sheets via same-origin /gviz/tq?tqx=out:csv (avoiding 307 cross-domain /export redirects) and public Google Docs /pub, OneDrive /embed, Dropbox, and Box share links while strictly enforcing robots.txt.","domains":["docs.google.com","dropbox.com","www.dropbox.com","box.com","app.box.com","onedrive.live.com","1drv.ms"],"auth_mode":"pub","strict_robots":true,"min_interval_ms":1000,"exampleUrls":["https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit","https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/gviz/tq?tqx=out:csv","https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/htmlview"],"routes":[{"match":{"hosts":["docs.google.com"],"anyOf":[{"exactSegments":true,"pathSegments":["spreadsheets","d",{"param":"sheetId","charset":"slug","minLen":12,"maxLen":128,"reserved":["e"]}]},{"exactSegments":true,"pathSegments":["spreadsheets","d",{"param":"sheetId","charset":"slug","minLen":12,"maxLen":128,"reserved":["e"]},{"param":"view","allowValues":["edit","view","htmlview","preview","copy"]}]}]},"twin":{"fetchUrl":"https://docs.google.com/spreadsheets/d/{sheetId}/gviz/tq?tqx=out:csv","kind":"text","accept":"text/plain","maxBytes":2097152},"extract":{"textMode":"public_share_csv"}},{"match":{"hosts":["docs.google.com"],"exactSegments":true,"pathSegments":["spreadsheets","d",{"param":"sheetId","charset":"slug","minLen":12,"maxLen":128,"reserved":["e"]},"gviz","tq"],"queryParams":[{"name":"tqx","param":"tqx","charset":"url_seg","allowValues":["out:csv"]}]},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"text/plain","maxBytes":2097152},"extract":{"textMode":"public_share_csv"}}],"htmlRoutes":[{"id":"public-share-links","mode":"public_share_html","match":{"hosts":["docs.google.com","dropbox.com","www.dropbox.com","box.com","app.box.com","onedrive.live.com","1drv.ms"],"exactSegments":false}}]},{"id":"pubmed-pmc","name":"PubMed & PubMed Central (NCBI / Europe PMC)","category":"research-health","description":"Upgrades PubMed & PMC URLs to robots.txt-allowed Europe PMC REST JSON/JATS XML (with NCBI HTML fallback).","domains":["pubmed.ncbi.nlm.nih.gov","pmc.ncbi.nlm.nih.gov"],"exampleUrls":["https://pubmed.ncbi.nlm.nih.gov/31452104/","https://pmc.ncbi.nlm.nih.gov/articles/PMC7095418/"],"routes":[{"match":{"hosts":["pubmed.ncbi.nlm.nih.gov"],"exactSegments":true,"pathSegments":[{"param":"pmid","charset":"digits"}]},"twin":{"id":"pubmed-europepmc","fetchUrl":"https://www.ebi.ac.uk/europepmc/webservices/rest/search?query=EXT_ID:{pmid}%20AND%20SRC:MED&resultType=core&format=json","kind":"json","accept":"application/json"},"extract":{"rootPath":"resultList.result.0","requireFields":["title"],"vars":{"title":{"paths":["title"],"format":"strip_tags","stripSuffix":".","trim":true},"authorString":{"paths":["authorString"],"trim":true},"journalTitle":{"paths":["journalInfo.journal.title"]},"pubYear":{"paths":["pubYear"]},"journalFull":{"template":"{journalTitle} ({pubYear})","whenVars":["journalTitle","pubYear"],"fallbackVar":"journalTitle"},"doi":{"paths":["doi"]},"doiUrl":{"template":"https://doi.org/{doi}","whenVars":["doi"]},"pmcid":{"paths":["pmcid"]},"pmcUrl":{"template":"https://pmc.ncbi.nlm.nih.gov/articles/{pmcid}/","whenVars":["pmcid"]},"citedBy":{"paths":["citedByCount"],"format":"int_comma"},"abstractText":{"paths":["abstractText"],"format":"strip_tags"}},"titleTemplate":"{title}","authorVar":"authorString","publishedTimeVar":"pubYear","bullets":[{"label":"PMID","template":"`{pmid}`"},{"label":"Authors","template":"{authorString}","whenVar":"authorString"},{"label":"Journal","template":"{journalFull}","whenVar":"journalFull"},{"label":"DOI","template":"`{doi}`","whenVar":"doi"},{"label":"Full Text (PMC)","template":"[{pmcid}]({pmcUrl})","whenVar":"pmcid"},{"label":"Cited By","template":"{citedBy}","whenVar":"citedBy"}],"sections":[{"heading":"Abstract","textVar":"abstractText"}],"linksVars":["doiUrl","pmcUrl"]}},{"match":{"hosts":["pmc.ncbi.nlm.nih.gov"],"exactSegments":false,"pathSegments":["articles",{"param":"pmcid","charset":"pmc_id","transform":"upper"}]},"twin":{"id":"pmc-europepmc","fetchUrl":"https://www.ebi.ac.uk/europepmc/webservices/rest/{pmcid}/fullTextXML","kind":"text","accept":"application/xml"},"extract":{"xml":{"mode":"jats_article"}}}],"htmlRoutes":[{"match":{"anyOf":[{"hosts":["pubmed.ncbi.nlm.nih.gov"],"exactSegments":true,"pathSegments":[{"param":"pmid","charset":"digits"}]},{"hosts":["pmc.ncbi.nlm.nih.gov"],"exactSegments":false,"pathSegments":["articles",{"param":"pmcid","charset":"pmc_id","transform":"upper"}]}]},"mode":"dom","requireVars":["title","body"],"vars":{"title":{"cssText":["h1.heading-title","h1"]},"authors":{"cssAllText":{"selector":"a.full-name","limit":20,"dedupe":true,"join":", "},"limit":15},"authorsShort":{"cssAllText":{"selector":"a.full-name","limit":20,"dedupe":true,"join":", "},"limit":4},"doi":{"cssText":["span.citation-doi"]},"body":{"cssHtmlToMd":["article.article","div#abstract","div#eng-abstract","section.abstract"]}},"titleTemplate":"{title}","authorVar":"authorsShort","bullets":[{"label":"Authors","template":"{authors}","whenVar":"authors"},{"label":"Citation","template":"{doi}","whenVar":"doi"}],"bodyVar":"body","bodyFallbackHeading":"Abstract"}]},{"id":"pypi-project","name":"PyPI Python Package Index","category":"developer","description":"Extracts PyPI package install command, summary, and project README from pypi.org/project// (respecting robots.txt on /json).","domains":["pypi.org","www.pypi.org"],"exampleUrls":["https://pypi.org/project/httpx/"],"htmlRoutes":[{"match":{"exactSegments":false,"pathSegments":["project",{"param":"pkg","charset":"pkg"}]},"mode":"dom","vars":{"headerName":{"cssText":["h1.project-header__name","h1.package-header__name"]},"pipCmd":{"cssText":["#pip-command"]},"summary":{"cssText":["p.project-header__summary","p.package-description__summary"]},"readme":{"cssHtmlToMd":["#description","div.project-description"],"format":"strip_leading_h1"}},"requireVars":["headerName","readme"],"titleTemplate":"{headerName}","descriptionVar":"summary","introVar":"summary","bullets":[{"label":"Install","template":"`{pipCmd}`","whenVar":"pipCmd"}],"bodyVar":"readme"}]},{"id":"readthedocs-sphinx","name":"Read the Docs & Sphinx Documentation","category":"developer","description":"Universal HTML extractor for Sphinx and Read the Docs documentation sites (requests.readthedocs.io, docs.python.org, and Sphinx-themed portals).","domains":["docs.python.org","numpy.org","matplotlib.org"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://numpy.org/doc/stable/user/absolute_beginners.html","https://docs.python.org/3/library/json.html"],"htmlRoutes":[{"id":"readthedocs-sphinx","match":{"exactSegments":false},"mode":"readthedocs_sphinx_html"}]},{"id":"recreation-gov-ridb","name":"Recreation.gov & RIDB API","category":"public-records","description":"Recreation Information Database (RIDB) v1 API (apikey header) with Recreation.gov Campground JSON-LD / SSR HTML fallback and strict robots politeness.","domains":["ridb.recreation.gov","www.recreation.gov","recreation.gov"],"auth_mode":"key","strict_robots":true,"min_interval_ms":10000,"exampleUrls":["https://www.recreation.gov/camping/campgrounds/232447","https://ridb.recreation.gov/api/v1/facilities/232447"],"routes":[{"match":{"hosts":["ridb.recreation.gov"],"pathPrefix":"/api/v1/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":4194304},"extract":{"jsonMode":"ridb_json"}},{"match":{"hosts":["www.recreation.gov","recreation.gov"],"exactSegments":true,"pathSegments":["camping","campgrounds",{"param":"facilityId","charset":"digits","minLen":1,"maxLen":12}]},"twin":{"fetchUrl":"https://ridb.recreation.gov/api/v1/facilities/{facilityId}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"ridb_json"}}],"htmlRoutes":[{"id":"recreation-gov-ridb","match":{"hosts":["www.recreation.gov","recreation.gov"],"exactSegments":false},"mode":"recreation_gov_html"}]},{"id":"reddit-thread","name":"Reddit Threads & Comments","category":"commerce-social","description":"Extracts shreddit-post prose, subreddit/author/score metadata, and nested shreddit-comment trees.","domains":["reddit.com","*.reddit.com"],"exampleUrls":["https://www.reddit.com/r/golang/comments/1abc123/single_binary_deployments/"],"htmlRoutes":[{"id":"reddit-thread","match":{"pathContainsSegment":"comments"},"mode":"reddit_shreddit"}]},{"id":"regulations-gov","name":"Regulations.gov Federal Rulemaking","category":"public-records","description":"Official api.regulations.gov v4 JSON:API adapter for federal rulemaking documents, dockets, and public comments with HTML fallback.","domains":["regulations.gov","www.regulations.gov","api.regulations.gov"],"auth_mode":"key","exampleUrls":["https://api.regulations.gov/v4/documents/FTC-2023-0007-0001","https://api.regulations.gov/v4/dockets/FTC-2023-0007","https://www.regulations.gov/document/FTC-2023-0007-0001"],"routes":[{"match":{"hosts":["api.regulations.gov"],"pathPrefix":"/v4/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":4194304},"extract":{"jsonMode":"regulations_gov_json"}},{"match":{"hosts":["regulations.gov","www.regulations.gov"],"exactSegments":false,"pathSegments":["document",{"param":"docId","charset":"alnum_dash","minLen":4,"maxLen":80}]},"twin":{"fetchUrl":"https://api.regulations.gov/v4/documents/{docId}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":4194304},"extract":{"jsonMode":"regulations_gov_json"}},{"match":{"hosts":["regulations.gov","www.regulations.gov"],"exactSegments":false,"pathSegments":["docket",{"param":"docketId","charset":"alnum_dash","minLen":4,"maxLen":80}]},"twin":{"fetchUrl":"https://api.regulations.gov/v4/dockets/{docketId}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":4194304},"extract":{"jsonMode":"regulations_gov_json"}},{"match":{"hosts":["regulations.gov","www.regulations.gov"],"exactSegments":false,"pathSegments":["comment",{"param":"commentId","charset":"alnum_dash","minLen":4,"maxLen":80}]},"twin":{"fetchUrl":"https://api.regulations.gov/v4/comments/{commentId}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":4194304},"extract":{"jsonMode":"regulations_gov_json"}}],"htmlRoutes":[{"id":"regulations-gov","match":{"hosts":["regulations.gov","www.regulations.gov"],"exactSegments":false},"mode":"regulations_gov_html"}]},{"id":"repology","name":"Repology Package Version Matrix","category":"developer","description":"Extracts cross-distribution package versions from Repology API v1 and project HTML pages, prioritizing status == newest rows.","domains":["repology.org"],"auth_mode":"pub","exampleUrls":["https://repology.org/api/v1/project/python","https://repology.org/project/python/versions"],"routes":[{"match":{"hosts":["repology.org"],"pathPrefix":"/api/v1/project/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"repology_json"}},{"match":{"hosts":["repology.org"],"exactSegments":false,"pathSegments":["project",{"param":"project","charset":"pkg","minLen":1,"maxLen":160}]},"twin":{"fetchUrl":"https://repology.org/api/v1/project/{project}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"repology_json"}}],"htmlRoutes":[{"id":"repology","match":{"hosts":["repology.org"],"exactSegments":false},"mode":"repology_html"}]},{"id":"rippling","name":"Rippling ATS Career Boards","category":"jobs","description":"Upgrades ats.rippling.com/[locale/]/jobs to api.rippling.com (merging multi-location rows by uuid) and extracts __NEXT_DATA__ jobPost on detail pages.","domains":["ats.rippling.com"],"exampleUrls":["https://ats.rippling.com/rippling/jobs","https://ats.rippling.com/rippling/jobs/96601a74-e7b6-469d-8c69-6fdfd1c83bc0"],"match":{"optionalLeadingLocale":true,"pathSegments":[{"param":"org","charset":"slug","maxLen":80},{"param":"jobsLit","charset":"alnum","allowValues":["jobs"],"optional":true}]},"twin":{"id":"rippling-board","fetchUrl":"https://api.rippling.com/platform/api/ats/v1/board/{org}/jobs","kind":"json","accept":"application/json"},"extract":{"wrapRootArrayAs":"results","vars":{"rawCount":{"paths":["results"],"format":"array_len"},"dedupCount":{"default":"{dedupCount}"}},"requireVars":["rawCount"],"titleTemplate":"{org} — Rippling Job Board ({dedupCount} open roles)","sections":[{"heading":"","arrayPath":"results","limit":100,"linkScanLimit":2000,"emptyText":"No open positions currently listed.","dedupeBy":{"keyPaths":["uuid","id"],"mergeTextPaths":["workLocation.label","workLocation"],"mergeTargetVar":"_mergedLocs","mergeSep":"; ","mergeLimit":4},"requireItemVar":"jName","itemVars":{"uuid":{"paths":["uuid","id"],"trim":true},"jName":{"paths":["name","title"],"trim":true},"rawUrl":{"paths":["url"],"requireHttps":true},"jUrl":{"template":"{rawUrl}","whenVars":["rawUrl"],"fallbackTemplate":"https://ats.rippling.com/{org}/jobs/{uuid}"},"dept":{"paths":["department.label","department"],"trim":true,"default":"-"},"locs":{"paths":["_mergedLocs"],"trim":true,"default":"-"}},"collectLinkVars":["jUrl"],"columns":[{"header":"Role","template":"[{jName}]({jUrl})"},{"header":"Department","template":"{dept}"},{"header":"Locations","template":"{locs}"}]}]},"htmlRoutes":[{"id":"rippling-job","mode":"embedded_json","scriptId":"__NEXT_DATA__","match":{"hosts":["ats.rippling.com"]},"extract":{"vars":{"jobTitle":{"paths":["props.pageProps.apiData.jobPost.name","props.pageProps.apiData.jobPost.title","props.pageProps.jobPost.name","props.pageProps.jobPost.title"],"trim":true},"company":{"paths":["props.pageProps.apiData.jobPost.companyName","props.pageProps.jobPost.companyName"],"trim":true,"default":"Company"},"descDirect":{"paths":["props.pageProps.apiData.jobPost.description","props.pageProps.jobPost.description"],"format":"html_to_md"},"descCompany":{"paths":["props.pageProps.apiData.jobPost.description.company","props.pageProps.jobPost.description.company"],"format":"html_to_md"},"descRole":{"paths":["props.pageProps.apiData.jobPost.description.role","props.pageProps.jobPost.description.role"],"format":"html_to_md"},"descReqs":{"paths":["props.pageProps.apiData.jobPost.description.requirements","props.pageProps.jobPost.description.requirements"],"format":"html_to_md"},"descBenefits":{"paths":["props.pageProps.apiData.jobPost.description.benefits","props.pageProps.jobPost.description.benefits"],"format":"html_to_md"},"hasAnyBody":{"template":"ok","whenAnyVars":["descDirect","descCompany","descRole","descReqs","descBenefits"]}},"requireVars":["jobTitle","hasAnyBody"],"titleTemplate":"{jobTitle} @ {company}","bodyVar":"descDirect","sections":[{"heading":"","unlessVar":"descDirect","textVar":"descCompany"},{"heading":"","unlessVar":"descDirect","textVar":"descRole"},{"heading":"","unlessVar":"descDirect","textVar":"descReqs"},{"heading":"","unlessVar":"descDirect","textVar":"descBenefits"}]}}]},{"id":"rubygems","name":"RubyGems Registry","category":"developer","description":"Upgrades rubygems.org gem pages to /api/v1/gems/.json metadata.","domains":["rubygems.org","www.rubygems.org"],"exampleUrls":["https://rubygems.org/gems/rails"],"match":{"exactSegments":false,"pathSegments":["gems",{"param":"gem","charset":"pkg","minLen":1,"maxLen":80}]},"twin":{"fetchUrl":"https://rubygems.org/api/v1/gems/{gem}.json","kind":"json","accept":"application/json"},"extract":{"requireFields":["name"],"vars":{"name":{"paths":["name"]},"version":{"paths":["version"]},"info":{"paths":["info"],"trim":true},"infoShort":{"paths":["info"],"trim":true,"sliceMax":260},"licenses":{"paths":["licenses"],"join":", "},"authors":{"paths":["authors"]},"repo":{"paths":["source_code_uri","homepage_uri"]},"docs":{"paths":["documentation_uri"]}},"titleTemplate":"{name} {version} (RubyGem)","titleWhenVar":"version","titleFallbackTemplate":"{name} (RubyGem)","descriptionVar":"infoShort","authorVar":"authors","introVar":"info","bullets":[{"label":"Install","template":"`gem install {name}`"},{"label":"Version","template":"`{version}`","whenVar":"version"},{"label":"License","template":"{licenses}","whenVar":"licenses"},{"label":"Authors","template":"{authors}","whenVar":"authors"},{"label":"Documentation","template":"{docs}","whenVar":"docs"},{"label":"Repository","template":"{repo}","whenVar":"repo"}]}},{"id":"rumble-odysee","name":"Rumble & Odysee Video","category":"commerce-social","description":"Extracts Odysee video claim oEmbed and LBRY JSON-RPC metadata plus Rumble/Odysee HTML without hitting disallowed rumble.com/api/* routes.","domains":["rumble.com","www.rumble.com","odysee.com","www.odysee.com","api.na-backend.odysee.com"],"auth_mode":"pub","exampleUrls":["https://odysee.com/@Odysee:8/channel-roundup-may-2026:e","https://odysee.com/$/oembed?url=https%3A%2F%2Fodysee.com%2F%40Odysee%3A8%2Fchannel-roundup-may-2026%3Ae&format=json","https://www.rumble.com/c/Rumble"],"routes":[{"match":{"hosts":["odysee.com","www.odysee.com"],"pathEquals":["/$/oembed"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"rumble_odysee_json"}},{"match":{"hosts":["odysee.com","www.odysee.com"],"exactSegments":true,"pathSegments":[{"param":"chan","charset":"at_handle","minLen":2,"maxLen":100},{"param":"claimSlug","charset":"url_seg","minLen":2,"maxLen":180}]},"twin":{"fetchUrl":"https://{host}/$/oembed?url=https%3A%2F%2F{host}%2F{chan}%2F{claimSlug}&format=json","kind":"json","accept":"application/json"},"extract":{"jsonMode":"rumble_odysee_json"}},{"match":{"hosts":["api.na-backend.odysee.com"],"pathEquals":["/api/v1/proxy"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"rumble_odysee_json"}}],"htmlRoutes":[{"id":"rumble-odysee","match":{"exactSegments":false},"mode":"rumble_odysee_html"}]},{"id":"rxnorm-rxnav","name":"NLM RxNorm / RxNav","category":"research-health","description":"National Library of Medicine RxNav REST JSON API adapter for RxCUI lookups, concept properties, drug groups, and approximate term matches.","domains":["rxnav.nlm.nih.gov"],"auth_mode":"pub","exampleUrls":["https://rxnav.nlm.nih.gov/REST/rxcui.json?name=lipitor","https://rxnav.nlm.nih.gov/REST/rxcui/153165/properties.json","https://rxnav.nlm.nih.gov/REST/drugs.json?name=acetaminophen"],"routes":[{"match":{"pathPrefix":"/REST/","pathSuffix":".json"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"rxnorm_json"}}]},{"id":"saleor","name":"Saleor Storefront & GraphQL API","category":"commerce-social","description":"Extracts Saleor Storefront bounded /graphql/ product queries (including EditorJS descriptions) and post-HTML JSON-LD/Microdata product pages.","domains":["demo.saleor.io","storefront1.saleor.cloud"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://storefront1.saleor.cloud/graphql/"],"routes":[{"match":{"pathEquals":["/graphql","/graphql/"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","method":"POST","contentType":"application/json","requestBody":"{\"query\":\"query EdgeFetchProducts { products(first: 25, channel: \\\"default\\\") { pageInfo { hasNextPage endCursor } edges { node { id slug name description category { name slug } thumbnail { url alt } pricing { priceRange { start { gross { amount currency } } stop { gross { amount currency } } } } variants { id name sku quantityAvailable pricing { price { gross { amount currency } } } } } } } }\"}"},"extract":{"commerceMode":"saleor_graphql"}}],"htmlRoutes":[{"id":"saleor","match":{"exactSegments":false},"mode":"saleor_html"}]},{"id":"salesforce-knowledge","name":"Salesforce Knowledge (Experience Cloud)","category":"developer","description":"Extracts public Salesforce Knowledge and Experience Cloud articles when SSR/hydrated DOM or TechArticle JSON-LD is present; rejects unhydrated Aura error shells and login redirects.","domains":["help.salesforce.com","help.mulesoft.com"],"universalEngine":true,"auth_mode":"html","exampleUrls":["https://help.salesforce.com/s/articleView?language=en_US&id=000391748&type=1"],"htmlRoutes":[{"id":"salesforce-knowledge","match":{"exactSegments":false},"mode":"salesforce_knowledge_html"}]},{"id":"sam-gov","name":"SAM.gov Opportunities & Entities","category":"public-records","description":"Extracts SAM.gov contract opportunities and entity registrations via official SAM.gov v2/v3 APIs (excluding /contract-awards handled by fpds-sam-contract-awards) with HTML fallback.","domains":["sam.gov","www.sam.gov","api.sam.gov"],"auth_mode":"key","exampleUrls":["https://sam.gov/contracting","https://sam.gov/help","https://api.sam.gov/opportunities/v2/search?limit=1"],"routes":[{"match":{"hosts":["sam.gov","www.sam.gov"],"exactSegments":false,"pathSegments":["opp",{"param":"noticeId","charset":"url_seg","minLen":4,"maxLen":120},"view"]},"twin":{"fetchUrl":"https://api.sam.gov/opportunities/v2/search?noticeid={noticeId}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"sam_gov_json"}},{"match":{"hosts":["api.sam.gov"],"pathPrefix":"/opportunities/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"sam_gov_json"}},{"match":{"hosts":["api.sam.gov"],"pathPrefix":"/prod/opportunities/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"sam_gov_json"}},{"match":{"hosts":["api.sam.gov"],"pathPrefix":"/entity-information/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"sam_gov_json"}},{"match":{"hosts":["api.sam.gov"],"pathPrefix":"/prod/entity-information/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"sam_gov_json"}}],"htmlRoutes":[{"id":"sam-gov","match":{"hosts":["sam.gov","www.sam.gov"],"exactSegments":false},"mode":"sam_gov_html"}]},{"id":"sap-commerce-occ","name":"SAP Commerce Cloud (OCC v2)","category":"commerce-social","description":"Extracts SAP Commerce Cloud OCC v2 /rest/v2 product and search JSON endpoints plus Spartacus storefront HTML/companion twins.","domains":["www.kay.com"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://www.kay.com/kay-labgrown-diamonds-large-small-link-bracelet-14-ct-tw-sterling-silver-8/p/V-238867701"],"routes":[{"match":{"pathSegments":["occ","v2",{"param":"site","charset":"slug","minLen":2,"maxLen":64},"products","search"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"commerceMode":"sap_occ_product"}},{"match":{"pathSegments":["occ","v2",{"param":"site","charset":"slug","minLen":2,"maxLen":64},"products",{"param":"code","charset":"pkg","reserved":["search"],"minLen":1,"maxLen":120}]},"twin":{"fetchUrl":"{requestUrl}","defaultQueryParams":{"fields":"FULL"},"kind":"json","accept":"application/json"},"extract":{"commerceMode":"sap_occ_product"}},{"match":{"pathSegments":["rest","v2",{"param":"site","charset":"slug","minLen":2,"maxLen":64},"products",{"param":"code","charset":"pkg","reserved":["search"],"minLen":1,"maxLen":120}]},"twin":{"fetchUrl":"{requestUrl}","defaultQueryParams":{"fields":"FULL"},"kind":"json","accept":"application/json"},"extract":{"commerceMode":"sap_occ_product"}}],"htmlRoutes":[{"id":"sap-commerce-occ","match":{"exactSegments":false},"mode":"sap_occ_html"}]},{"id":"sap-rmk-jibe","name":"SAP SuccessFactors RMK & Jibe Enterprise Career Feeds","category":"jobs","description":"Formats Jibe /api/jobs JSON feeds and SAP SuccessFactors Recruiting Marketing (RMK) /sitemap.xml RSS job feeds.","domains":["careers.*.com","jobs.*.com"],"universalEngine":true,"exampleUrls":["https://careers.rivian.com/api/jobs?page=1&limit=25","https://jobs.eastman.com/sitemap.xml"],"routes":[{"match":{"pathEquals":["/api/jobs"],"excludeHosts":["jobs.dover.com","app.dover.com","*.dover.com"]},"twin":{"id":"jibe-careers","fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"requireArrayItemField":{"arrayPath":"jobs","field":"data"},"vars":{"jobCount":{"paths":["jobs"],"format":"array_len"},"total":{"paths":["totalCount"],"fallbackTemplate":"{jobCount}"}},"requireVars":["jobCount"],"titleTemplate":"{host} — Jibe Career Feed ({jobCount} of {total} open roles)","sections":[{"heading":"","arrayPath":"jobs","limit":80,"emptyText":"No open positions currently listed.","itemVars":{"jTitle":{"paths":["data.title","title"],"trim":true,"default":"Role"},"reqId":{"paths":["data.req_id","data.slug","req_id","slug"],"trim":true},"reqCell":{"template":"`{reqId}`","whenVars":["reqId"],"default":"-"},"catArr":{"paths":["data.categories"],"subField":"name","join":", "},"catStr":{"paths":["data.category","category"],"trim":true},"cat":{"template":"{catArr}","whenVars":["catArr"],"fallbackVar":"catStr","default":"-"},"fullLoc":{"paths":["data.full_location","full_location"],"trim":true},"city":{"paths":["data.city","city"],"trim":true},"state":{"paths":["data.state","state"],"trim":true},"country":{"paths":["data.country","country"],"trim":true},"csc3":{"template":"{city}, {state}, {country}","whenVars":["city","state","country"]},"csc2a":{"template":"{city}, {state}","whenVars":["city","state"]},"csc2b":{"template":"{city}, {country}","whenVars":["city","country"]},"csc1":{"paths":["data.city","data.state","data.country"],"trim":true},"locSub1":{"template":"{csc3}","whenVars":["csc3"],"fallbackVar":"csc2a"},"locSub2":{"template":"{locSub1}","whenVars":["locSub1"],"fallbackVar":"csc2b"},"locSub3":{"template":"{locSub2}","whenVars":["locSub2"],"fallbackVar":"csc1"},"loc":{"template":"{fullLoc}","whenVars":["fullLoc"],"fallbackVar":"locSub3","default":"-"},"canonUrl":{"paths":["data.meta_data.canonical_url"],"requireHttps":true},"appUrl":{"paths":["data.apply_url","apply_url"],"requireHttps":true},"finalUrl":{"template":"{canonUrl}","whenVars":["canonUrl"],"fallbackVar":"appUrl"},"roleCell":{"template":"[{jTitle}]({finalUrl})","whenVars":["finalUrl"],"fallbackVar":"jTitle"}},"collectLinkVars":["finalUrl"],"columns":[{"header":"Role","template":"{roleCell}"},{"header":"Req ID","template":"{reqCell}"},{"header":"Category","template":"{cat}"},{"header":"Location","template":"{loc}"}]}]}},{"match":{"pathSuffix":"sitemap.xml","excludeHosts":["jobs.dover.com","app.dover.com","*.dover.com"]},"twin":{"id":"sap-rmk-jibe","fetchUrl":"{requestUrl}","kind":"text","accept":"application/xml"},"extract":{"xml":{"mode":"items_table","requireAnyTags":["g:location","g:employer"],"itemTag":"item","firstItemVars":{"employer":["g:employer"]},"titleTemplate":"{employer} — SAP RMK Job Feed ({itemCount} open roles)","limit":100,"collectLinkVar":"jLink","itemVars":{"jTitle":{"tags":["title"],"default":"Role"},"jLink":{"tags":["link"]},"jId":{"tags":["g:id"],"default":"-"},"loc":{"tags":["g:location"],"default":"-"}},"columns":[{"header":"Role","template":"[{jTitle}]({jLink})"},{"header":"Req ID","template":"{jId}"},{"header":"Location","template":"{loc}"}]}}}],"htmlRoutes":[{"id":"sap-rmk-jibe","mode":"xml_items_table","match":{"pathSuffix":"sitemap.xml","excludeHosts":["jobs.dover.com","app.dover.com","*.dover.com"]},"xml":{"mode":"items_table","requireAnyTags":["g:location","g:employer"],"itemTag":"item","firstItemVars":{"employer":["g:employer"]},"titleTemplate":"{employer} — SAP RMK Job Feed ({itemCount} open roles)","limit":100,"collectLinkVar":"jLink","itemVars":{"jTitle":{"tags":["title"],"default":"Role"},"jLink":{"tags":["link"]},"jId":{"tags":["g:id"],"default":"-"},"loc":{"tags":["g:location"],"default":"-"}},"columns":[{"header":"Role","template":"[{jTitle}]({jLink})"},{"header":"Req ID","template":"{jId}"},{"header":"Location","template":"{loc}"}]}}]},{"id":"schema-event","name":"Schema.org Event (Universal)","category":"commerce-social","description":"Universal Schema.org Event JSON-LD extractor for venues, parks departments, clubs, and event calendars: name, start/end, venue and address, organizer, performer, offers/price, status, and attendance mode. Lists every Event on series and calendar pages.","domains":["neworleanscitypark.org"],"universalEngine":true,"auth_mode":"html","exampleUrls":["https://neworleanscitypark.org/series/crescent-city-farmers-market-2/"],"htmlRoutes":[{"id":"schema-event","match":{"exactSegments":false},"mode":"schema_event_html"}]},{"id":"schema-localbusiness","name":"Schema.org LocalBusiness (Universal)","category":"commerce-social","description":"Universal Schema.org LocalBusiness JSON-LD extractor (Restaurant, Store, AutoDealer, BikeStore and every *Business/*Store subtype) for location, dealer, and shop pages: name, address, phone, geo, opening hours, price range, rating, and amenities. Skips pages whose main entity is an article, product, recipe, job, or event.","domains":["www.chipotle.com"],"universalEngine":true,"auth_mode":"html","exampleUrls":["https://locations.chipotle.com/co/boulder/1650-28th-st"],"htmlRoutes":[{"id":"schema-localbusiness","match":{"exactSegments":false},"mode":"schema_localbusiness_html"}]},{"id":"schema-recipe","name":"Schema.org Recipe (Universal)","category":"commerce-social","description":"Universal Schema.org Recipe JSON-LD extractor for any recipe site: ingredients, numbered steps (HowToStep/HowToSection), prep/cook/total times, yield, cuisine, rating, and nutrition. Resolves @graph @id author references.","domains":["www.budgetbytes.com"],"universalEngine":true,"auth_mode":"html","exampleUrls":["https://www.budgetbytes.com/one-pot-creamy-cajun-chicken-pasta/"],"htmlRoutes":[{"id":"schema-recipe","match":{"exactSegments":false},"mode":"schema_recipe_html"}]},{"id":"searchspring","name":"Searchspring On-Site Search","category":"commerce-social","description":"Extracts public Searchspring JSON search API payloads and discovers siteId markers from storefront HTML.","domains":["api.searchspring.net","www.searchspring.com"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://api.searchspring.net/api/search/search.json?siteId=rn129l&q=router&resultsFormat=native"],"routes":[{"match":{"pathEquals":["/api/search/search.json"],"queryParams":[{"name":"siteId","param":"siteId","charset":"alnum_dash","minLen":2,"maxLen":32}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"searchspring_search"}}],"htmlRoutes":[{"id":"searchspring","match":{"exactSegments":false},"mode":"searchspring_html"}]},{"id":"sec-edgar","name":"SEC EDGAR Company Submissions & Filings","category":"finance","description":"Upgrades sec.gov EDGAR company browse pages and CIK URLs to keyless data.sec.gov JSON submissions (10-K, 10-Q, 8-K, DEF 14A, Form 4, 13F).","domains":["www.sec.gov","sec.gov","data.sec.gov"],"exampleUrls":["https://www.sec.gov/edgar/browse/?CIK=0001477333","https://data.sec.gov/submissions/CIK0000320193.json"],"match":{"anyOf":[{"hosts":["www.sec.gov","sec.gov"],"exactSegments":false,"pathSegments":["edgar","browse"],"queryParams":[{"names":["CIK","cik"],"param":"rawCik","charset":"digits","minLen":1,"maxLen":10}],"derivedParams":{"paddedCik":{"fromParam":"rawCik","transform":"pad10_zero"},"numericCik":{"fromParam":"rawCik","transform":"strip_leading_zeros"}}},{"hosts":["www.sec.gov","sec.gov"],"exactSegments":true,"pathSegments":["cgi-bin","browse-edgar"],"queryParams":[{"names":["CIK","cik"],"param":"rawCik","charset":"digits","minLen":1,"maxLen":10}],"derivedParams":{"paddedCik":{"fromParam":"rawCik","transform":"pad10_zero"},"numericCik":{"fromParam":"rawCik","transform":"strip_leading_zeros"}}},{"hosts":["data.sec.gov"],"exactSegments":true,"pathSuffix":".json","pathSegments":["submissions",{"param":"rawCik","stripPrefix":"CIK","stripSuffix":".json","charset":"digits","minLen":1,"maxLen":10}],"derivedParams":{"paddedCik":{"fromParam":"rawCik","transform":"pad10_zero"},"numericCik":{"fromParam":"rawCik","transform":"strip_leading_zeros"}}}]},"twin":{"fetchUrl":"https://data.sec.gov/submissions/CIK{paddedCik}.json","kind":"json","accept":"application/json"},"extract":{"requireFields":["name"],"vars":{"name":{"paths":["name"],"trim":true},"tickersPlain":{"paths":["tickers"],"join":", "},"tickersCode":{"paths":["tickers"],"itemWrap":"`","join":", "},"exchanges":{"paths":["exchanges"],"join":", "},"tickersBullet":{"template":"{tickersCode} ({exchanges})","whenVars":["tickersCode","exchanges"],"fallbackVar":"tickersCode"},"sic":{"paths":["sic"]},"sicDesc":{"paths":["sicDescription"]},"sicOrDesc":{"paths":["sic","sicDescription"]},"sicFull":{"template":"{sic} — {sicDesc}","whenVars":["sic","sicDesc"],"fallbackVar":"sicOrDesc"},"category":{"paths":["category"]},"stateInc":{"paths":["stateOfIncorporation"]},"fye":{"paths":["fiscalYearEnd"],"format":"fiscal_mmdd"},"descTickerOrCik":{"paths":["tickers"],"join":", ","fallbackTemplate":"CIK {paddedCik}"}},"titleTemplate":"{name} ({tickersPlain}) — SEC EDGAR","titleWhenVar":"tickersPlain","titleFallbackTemplate":"{name} (CIK {paddedCik}) — SEC EDGAR","descriptionTemplate":"{name} SEC EDGAR filings ({descTickerOrCik})","bullets":[{"label":"CIK","template":"`{paddedCik}`"},{"label":"Tickers","template":"{tickersBullet}","whenVar":"tickersBullet"},{"label":"SIC Industry","template":"{sicFull}","whenVar":"sicFull"},{"label":"Filer Category","template":"{category}","whenVar":"category"},{"label":"Incorporation","template":"{stateInc}","whenVar":"stateInc"},{"label":"Fiscal Year End","template":"{fye}","whenVar":"fye"}],"sections":[{"heading":"Recent SEC Filings","parallelArrays":{"basePath":"filings.recent","fields":{"form":"form","filingDate":"filingDate","reportDate":"reportDate","accessionNumber":"accessionNumber","primaryDocument":"primaryDocument","items":"items"},"priorityFilterAfter":{"index":12,"field":"form","allowValues":["10-K","10-K/A","10-Q","10-Q/A","8-K","DEF 14A","20-F","S-1","13F-HR","4"]}},"limit":25,"requireItemVar":"form","collectLinkVars":["docUrl"],"itemVars":{"form":{"paths":["form"]},"accRaw":{"paths":["accessionNumber"]},"accNoDash":{"paths":["accessionNumber"],"replaceAll":{"from":"-","to":""}},"primaryDocument":{"paths":["primaryDocument"]},"indexUrl":{"template":"https://www.sec.gov/Archives/edgar/data/{numericCik}/{accNoDash}/{accRaw}-index.htm","whenVars":["accRaw","accNoDash"]},"docUrl":{"template":"https://www.sec.gov/Archives/edgar/data/{numericCik}/{accNoDash}/{primaryDocument}","whenVars":["accNoDash","primaryDocument"],"fallbackVar":"indexUrl"},"formBold":{"template":"**{form}**","whenVars":["form"]},"formCell":{"template":"[**{form}**]({docUrl})","whenVars":["form","docUrl"],"fallbackVar":"formBold"}},"columns":[{"header":"Form","template":"{formCell}"},{"header":"Filed","paths":["filingDate"]},{"header":"Period","paths":["reportDate"]},{"header":"8-K Items","paths":["items"]}]}]}},{"id":"senate-lda","name":"Senate Lobbying Disclosures (LDA)","category":"public-records","description":"Extracts Senate Lobbying Disclosure Act filings from lda.gov (and lda.senate.gov) REST API v1 JSON with Crawl-delay 4s politeness and HTML fallback.","domains":["lda.gov","lda.senate.gov"],"auth_mode":"pub","min_interval_ms":4000,"strict_robots":true,"exampleUrls":["https://lda.gov/api/v1/filings/a934e791-d564-4fd3-8b78-041f8cfcf115/","https://lda.gov/filings/public/filing/a934e791-d564-4fd3-8b78-041f8cfcf115/"],"routes":[{"match":{"hosts":["lda.gov","lda.senate.gov"],"exactSegments":false,"pathSegments":["filings","public","filing",{"param":"filingId","charset":"alnum_dash","minLen":4,"maxLen":64}]},"twin":{"fetchUrl":"https://{host}/api/v1/filings/{filingId}/","kind":"json","accept":"application/json","auth_mode":"pub","maxBytes":2097152},"extract":{"jsonMode":"senate_lda_json"}},{"match":{"hosts":["lda.gov","lda.senate.gov"],"pathPrefix":"/api/v1/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"pub","maxBytes":2097152},"extract":{"jsonMode":"senate_lda_json"}}],"htmlRoutes":[{"id":"senate-lda","match":{"hosts":["lda.gov","lda.senate.gov"],"exactSegments":false},"mode":"senate_lda_html"}]},{"id":"servicenow-kb","name":"ServiceNow Knowledge Base","category":"developer","description":"Extracts public ServiceNow Knowledge Base articles from TechArticle JSON-LD and Service Portal KB DOM while rejecting soft-404 shells.","domains":["support.servicenow.com"],"universalEngine":true,"auth_mode":"html","exampleUrls":["https://support.servicenow.com/kb?id=kb_article_view&sysparm_article=KB0963589"],"htmlRoutes":[{"id":"servicenow-kb","match":{"exactSegments":false},"mode":"servicenow_kb_html"}]},{"id":"sfcc-demandware","name":"Salesforce Commerce Cloud (Demandware) Storefronts","category":"commerce-social","description":"Structurally detects Salesforce Commerce Cloud storefronts and extracts Product-Variation twins, JSON-LD, variation options, and product geometry/specification tables.","domains":["www.demandware.com"],"universalEngine":true,"exampleUrls":["https://www.demandware.com/product/sample"],"htmlRoutes":[{"id":"sfcc-demandware","match":{"exactSegments":false},"mode":"sfcc_html"}]},{"id":"shopify-storefront-graphql","name":"Shopify Storefront API (Tokenless GraphQL)","category":"commerce-social","description":"Queries any Shopify store's public Storefront API (/api//graphql.json) with Shopify's documented tokenless access for one product by handle: shop name, vendor, type, price range, options, every variant (SKU, price, compare-at price, availability), and collections. No access token is read from the page or sent.","domains":["www.tentree.com"],"universalEngine":true,"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://henryrose.com/api/2025-07/graphql.json?handle=the-layering-collection","https://www.tentree.com/api/2025-07/graphql.json?handle=e-gift-code"],"routes":[{"match":{"exactSegments":true,"pathSegments":["api",{"param":"apiVersion","charset":"slug","minLen":7,"maxLen":10},"graphql.json"],"queryParams":[{"name":"handle","param":"handle","charset":"slug","minLen":1,"maxLen":160}]},"twin":{"fetchUrl":"https://{host}/api/{apiVersion}/graphql.json","kind":"json","accept":"application/json","method":"POST","contentType":"application/json","requestBody":"{\"query\":\"query EdgeFetchProduct { shop { name } product(handle: \\\"{handle}\\\") { id handle title vendor productType description onlineStoreUrl availableForSale priceRange { minVariantPrice { amount currencyCode } maxVariantPrice { amount currencyCode } } options { name optionValues { name } } variants(first: 100) { nodes { id title sku availableForSale price { amount currencyCode } compareAtPrice { amount currencyCode } } } collections(first: 20) { nodes { handle title } } } }\"}","maxBytes":2097152},"extract":{"jsonMode":"shopify_storefront_graphql_json"}}]},{"id":"shopify","name":"Shopify Universal Storefront & Catalogs","category":"commerce-social","description":"Formats /products.json and /collections//products.json store inventories, upgrades *.myshopify.com and custom-domain /products/ pages, and implements polite full-store catalog pulls.","domains":["*.myshopify.com"],"universalEngine":true,"exampleUrls":["https://www.henryrose.com/products/the-layering-collection","https://www.henryrose.com/products.json?limit=30&page=1"],"catalog":{"platform":"shopify","pauseMs":1000,"pageCap":200,"firstPageTemplate":"{origin}/products.json?limit=250&page=1","collectionPageTemplate":"{origin}/collections/{collection}/products.json?limit=250&page=1","perPage":250,"maxVariantsPerProduct":250,"maxImagesPerProduct":250},"routes":[{"match":{"excludeHosts":["bigcartel.com","www.bigcartel.com","my.bigcartel.com","api.bigcartel.com","assets.bigcartel.com","help.bigcartel.com","developers.bigcartel.com","blog.bigcartel.com"],"anyOf":[{"pathEquals":["/products.json"]},{"exactSegments":true,"pathSegments":["collections",{"param":"col","charset":"slug","maxLen":160},"products.json"]}]},"twin":{"id":"shopify-catalog-page","fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"commerceMode":"shopify_catalog_page"}},{"match":{"pathSuffix":".js","scanSegment":{"afterLiteral":"products","param":"handle","charset":"slug","stripSuffix":".js","maxLen":160}},"twin":{"id":"shopify","fetchUrl":"https://{host}/products/{handle}.js","kind":"json","accept":"application/json"},"extract":{"commerceMode":"shopify_product_js"}},{"match":{"anyOf":[{"pathSuffix":".json","scanSegment":{"afterLiteral":"products","param":"handle","charset":"slug","stripSuffix":".json","maxLen":160}},{"hosts":["*.myshopify.com"],"scanSegment":{"afterLiteral":"products","param":"handle","charset":"slug","stripSuffix":".json","maxLen":160}}]},"twin":{"id":"shopify","fetchUrl":"https://{host}/products/{handle}.json","kind":"json","accept":"application/json"},"extract":{"commerceMode":"shopify_product"}},{"match":{"hosts":["*.myshopify.com"],"optionalLeadingLocale":true,"exactSegments":true,"pathSegments":["collections",{"param":"handle","charset":"slug","maxLen":160}]},"twin":{"id":"shopify","fetchUrl":"https://{host}/collections/{handle}/products.json?limit=50","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"commerceMode":"shopify_catalog_page"}}],"htmlRoutes":[{"id":"shopify","match":{"pathContainsSegment":"products"},"mode":"shopify_html"}]},{"id":"shopware-magento","name":"Magento 2 & Shopware 6 Storefronts","category":"commerce-social","description":"Structurally detects Magento 2 (text/x-magento-init swatches and bounded products-render-info) and Shopware 6 (sw-product-detail and property tables) storefronts.","domains":["www.shopware.com","business.adobe.com"],"universalEngine":true,"exampleUrls":["https://frontends-demo.vercel.app/Pepper-white-Muntok-pearl/SW10095"],"htmlRoutes":[{"id":"shopware-magento","match":{"exactSegments":false},"mode":"shopware_magento_html"}]},{"id":"slide-decks","name":"Slide Decks (SlideShare & SpeakerDeck)","category":"commerce-social","description":"Extracts SpeakerDeck presentations via public oEmbed JSON and slide transcripts HTML, and SlideShare decks via __NEXT_DATA__ HTML (no /api/ twin per robots.txt).","domains":["slideshare.net","www.slideshare.net","speakerdeck.com","www.speakerdeck.com"],"auth_mode":"pub","strict_robots":true,"exampleUrls":["https://www.slideshare.net/slideshow/slideshare-rebrand-announcement-deck-2025/283262633","https://speakerdeck.com/csswizardry/well-thats-weird"],"routes":[{"match":{"hosts":["speakerdeck.com","www.speakerdeck.com"],"exactSegments":true,"pathSegments":[{"param":"user","charset":"slug","minLen":1,"maxLen":80,"reserved":["search","signup","login","categories","features","pro","terms","privacy","about","jobs","assets","users","oembed.json"]},{"param":"deck","charset":"slug","minLen":1,"maxLen":160}]},"twin":{"fetchUrl":"https://speakerdeck.com/oembed.json?url=https%3A%2F%2Fspeakerdeck.com%2F{user}%2F{deck}","kind":"json","accept":"application/json","maxBytes":1048576},"extract":{"jsonMode":"speakerdeck_oembed_json"}},{"match":{"hosts":["speakerdeck.com","www.speakerdeck.com"],"pathEquals":["/oembed.json"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":1048576},"extract":{"jsonMode":"speakerdeck_oembed_json"}}],"htmlRoutes":[{"id":"slide-decks","mode":"slideshare_html","match":{"hosts":["slideshare.net","www.slideshare.net"],"exactSegments":false}},{"id":"slide-decks","mode":"speakerdeck_html","match":{"hosts":["speakerdeck.com","www.speakerdeck.com"],"exactSegments":false}}]},{"id":"small-search","name":"Searchanise, Doofinder, Findify & Nosto Search","category":"commerce-social","description":"Opt-in page-key adapter pack for Searchanise, Doofinder, Findify, and Nosto search APIs; defaults OFF and falls back to HTML/JSON-LD.","domains":["searchserverapi1.com","eu1-search.doofinder.com","api-v3.findify.io","api.nosto.com"],"universalEngine":true,"auth_mode":"page-key","requires_page_key_opt_in":true,"exampleUrls":["https://searchserverapi1.com/getresults?apiKey=3O4A8B9F4q&q=brew&output=json&maxResults=10"],"routes":[{"match":{"hosts":["searchserverapi1.com","www.searchserverapi1.com"],"pathEquals":["/getresults","/getwidgets"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"jsonMode":"small_search"}},{"match":{"anyOf":[{"hostSubdomain":{"suffix":"-search.doofinder.com","param":"zone"},"pathEquals":["/5/search"]},{"hostSubdomain":{"suffix":"-search.doofinder.com","param":"zone"},"pathSegments":["6",{"param":"hashid","charset":"alnum_dash","minLen":8,"maxLen":64},"_search"]}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"jsonMode":"small_search"}},{"match":{"hosts":["api-v3.findify.io"],"pathEquals":["/v3/search","/v3/autocomplete"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"jsonMode":"small_search"}},{"match":{"hosts":["api.nosto.com"],"pathEquals":["/v1/graphql"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","method":"POST","contentType":"application/json","requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"jsonMode":"small_search"}}],"htmlRoutes":[{"id":"small-search","match":{"exactSegments":false},"mode":"small_search_html"}]},{"id":"smartetailing","name":"SmartEtailing IBD Storefronts","category":"commerce-social","description":"Structurally detects SmartEtailing independent bicycle dealer storefronts and extracts Product JSON-LD, spec tables, and dealer pickup info.","domains":["www.trekchicago.com"],"universalEngine":true,"auth_mode":"html","exampleUrls":["https://www.trekchicago.com/product/trek-precaliber-16-556127-1.htm"],"htmlRoutes":[{"id":"smartetailing","match":{"exactSegments":false},"mode":"smartetailing_html"}]},{"id":"smithsonian-open-access","name":"Smithsonian Open Access","category":"public-records","description":"Smithsonian Open Access API v1.0 adapter (api.si.edu/openaccess) via api.data.gov key helper with HTML fallback.","domains":["si.edu","www.si.edu","api.si.edu"],"auth_mode":"key","min_interval_ms":1000,"exampleUrls":["https://api.si.edu/openaccess/api/v1.0/search?q=apollo","https://api.si.edu/openaccess/api/v1.0/content/edanmdm:nasm_A19700102000","https://www.si.edu/object/apollo-11-command-module-columbia:nasm_A19700102000"],"routes":[{"match":{"hosts":["api.si.edu"],"pathPrefix":"/openaccess/api/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"key"},"extract":{"jsonMode":"smithsonian_open_access_json"}},{"match":{"hosts":["si.edu","www.si.edu"],"exactSegments":false,"pathSegments":["object",{"param":"objectSlug","charset":"url_seg","minLen":4,"maxLen":160}]},"twin":{"fetchUrl":"https://api.si.edu/openaccess/api/v1.0/search?q={objectSlug}","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"key"},"extract":{"jsonMode":"smithsonian_open_access_json"}}],"htmlRoutes":[{"id":"smithsonian-open-access","match":{"hosts":["si.edu","www.si.edu"],"exactSegments":false,"reservedFirstSegment":["search","admin","core"]},"mode":"smithsonian_open_access_html"}]},{"id":"socrata","name":"Socrata Open Data Portals (SODA Universal Engine)","category":"public-records","description":"Upgrades city, state, and federal Socrata open-data dataset URLs (/d/<4x4-id> or /dataset/.../<4x4-id>) to /api/views/.json column schemas and SODA endpoints.","domains":["data.cityofnewyork.us","data.sfgov.org","data.sf.gov","data.seattle.gov","data.cityofchicago.org","data.lacity.org","data.wa.gov","data.nj.gov","data.colorado.gov","data.texas.gov","data.ny.gov","data.cdc.gov","*.socrata.com"],"universalEngine":true,"exampleUrls":["https://data.cityofnewyork.us/Housing-Development/DOB-Job-Application-Filings/ic3t-wcy2","https://data.sf.gov/d/i98e-djp9"],"match":{"socrataHost":true,"minSegments":2,"anyOf":[{"socrataHost":true,"minSegments":2,"exactSegments":false,"pathSegments":["d",{"param":"viewId","charset":"socrata_4x4","transform":"lower"}]},{"socrataHost":true,"minSegments":2,"scanSegment":{"lastOrBeforeLiteral":"about_data","param":"viewId","charset":"socrata_4x4","transform":"lower"}}]},"twin":{"fetchUrl":"https://{host}/api/views/{viewId}.json","kind":"json","accept":"application/json"},"extract":{"requireFields":["name","id"],"vars":{"name":{"paths":["name"],"trim":true},"desc":{"paths":["description"],"trim":true},"descShort":{"paths":["description"],"trim":true,"sliceMax":260},"attribution":{"paths":["attribution"]},"category":{"paths":["category"]},"license":{"paths":["license.name"]},"updatedDate":{"paths":["rowsUpdatedAt"],"format":"epoch_sec_date"},"sodaJsonUrl":{"template":"https://{host}/resource/{viewId}.json?$limit=50"},"csvExportUrl":{"template":"https://{host}/api/views/{viewId}/rows.csv?accessType=DOWNLOAD"}},"titleTemplate":"{name} ({host})","descriptionVar":"descShort","publishedTimeVar":"updatedDate","bullets":[{"label":"Dataset ID","template":"`{viewId}` ({host})"},{"label":"SODA JSON API","template":"`{sodaJsonUrl}`"},{"label":"CSV Download","template":"{csvExportUrl}"},{"label":"Agency / Attribution","template":"{attribution}","whenVar":"attribution"},{"label":"Category","template":"{category}","whenVar":"category"},{"label":"Rows Last Updated","template":"{updatedDate}","whenVar":"updatedDate"},{"label":"License","template":"{license}","whenVar":"license"}],"sections":[{"heading":"Description","textVar":"desc"},{"heading":"Schema","headingTemplate":"Schema ({shownCount} Columns)","arrayPath":"columns","filter":{"excludeFieldPrefix":{"field":"fieldName","prefix":":@"}},"limit":40,"columns":[{"header":"Field Name","paths":["fieldName"],"code":true},{"header":"Label","paths":["name"]},{"header":"Type","paths":["dataTypeName"]},{"header":"Description","paths":["description"]}]}],"linksVars":["sodaJsonUrl","csvExportUrl"]}},{"id":"specialized","name":"Specialized Bicycles & Geometry Specs","category":"commerce-social","description":"Polite HTML adapter for Specialized product pages extracting technical specifications, frame geometry tables, pricing, availability, and manual downloads.","domains":["specialized.com","www.specialized.com"],"auth_mode":"html","min_interval_ms":2000,"strict_robots":true,"exampleUrls":["https://www.specialized.com/us/en/s-works-tarmac-sl9-sram-red-axs/p/4293533"],"htmlRoutes":[{"id":"specialized","match":{"exactSegments":false},"mode":"specialized_html"}]},{"id":"spree-solidus","name":"Spree Commerce & Solidus","category":"commerce-social","description":"Extracts Spree/Solidus JSON:API /api/v2/storefront/products twins and post-HTML JSON-LD/Microdata product pages.","domains":["demo.spreecommerce.org","demo.solidus.io"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://demo.spreecommerce.org/us/en/products/espresso-barista-kit","https://demo.solidus.io/products/solidus-hoodie"],"routes":[{"match":{"pathEquals":["/api/v2/storefront/products"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"commerceMode":"spree_solidus_json"}},{"match":{"pathSegments":["api","v2","storefront","products",{"param":"id","charset":"url_seg","minLen":1,"maxLen":160}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"commerceMode":"spree_solidus_json"}}],"htmlRoutes":[{"id":"spree-solidus","match":{"exactSegments":false},"mode":"spree_solidus_html"}]},{"id":"square-online","name":"Square Online Storefronts","category":"commerce-social","description":"Extracts Square Online storefront product JSON-LD, Microdata, and __BOOTSTRAP_STATE__ storeInfo/commerceLinks hydration while rejecting empty SPA shells.","domains":["www.pessosices.com"],"universalEngine":true,"auth_mode":"html","exampleUrls":["https://www.pessosices.com/product/ice-cream-gelato/92"],"htmlRoutes":[{"id":"square-online","match":{"exactSegments":false},"mode":"square_online_html"}]},{"id":"squarespace-commerce","name":"Squarespace Commerce Storefronts","category":"commerce-social","description":"Detects Squarespace Commerce storefronts structurally and formats ?format=json-pretty product/collection payloads and HTML fallback into GFM tables and normalized CatalogRecord arrays.","domains":["commerce.squarespace.com"],"universalEngine":true,"exampleUrls":["https://www.trice-co.com/shop/p/pink-flare-leggings"],"htmlRoutes":[{"id":"squarespace-commerce","match":{"exactSegments":false},"mode":"squarespace_html"}]},{"id":"sram-docs","name":"SRAM Technical Documentation (Fluid Topics)","category":"developer","description":"Extracts bounded Fluid Topics SSR HTML documentation from docs.sram.com, stripping inline data:image base64 blobs and error chrome while preserving breadcrumbs, model codes, and PDF manual links.","domains":["docs.sram.com"],"exampleUrls":["https://docs.sram.com/en-US/publications/2eIzVnWuTRM7vhoKQjadQr"],"htmlRoutes":[{"id":"sram-docs","match":{"exactSegments":false},"mode":"sram_docs_html"}]},{"id":"sram-models","name":"SRAM Component Models (www.sram.com)","category":"commerce-social","description":"Extracts structured Product JSON-LD and technical component specification tables from www.sram.com/*/sram/models/* pages.","domains":["www.sram.com","sram.com"],"exampleUrls":["https://www.sram.com/en/sram/models/rd-xx-e-b1","https://www.sram.com/en/service/models/rd-gx-1-b1"],"htmlRoutes":[{"id":"sram-models","mode":"dom","match":{"optionalLeadingLocale":true,"exactSegments":false,"anyOf":[{"pathSegments":["sram","models",{"param":"modelSlug","charset":"url_seg","minLen":1,"maxLen":140}]},{"pathSegments":["service","models",{"param":"modelSlug","charset":"url_seg","minLen":1,"maxLen":140}]}]},"jsonLdTypes":["Product"],"vars":{"title":{"jsonLdPaths":["name"],"cssText":[".product-detail h1","h1","title"],"trim":true},"sku":{"jsonLdPaths":["sku"],"trim":true},"brand":{"jsonLdPaths":["brand.name","brand"],"trim":true},"body":{"cssHtmlToMd":["main.product-detail",".product-detail","main"],"format":"strip_leading_h1","trim":true}},"requireVars":["title","body"],"titleTemplate":"{title}","bullets":[{"label":"Brand","template":"{brand}","whenVar":"brand"},{"label":"SKU","template":"`{sku}`","whenVar":"sku"}],"bodyVar":"body","preserveBodyLinksFromVar":"body"}]},{"id":"stackexchange-qa","name":"Stack Overflow & Stack Exchange Q&A","category":"developer","description":"Upgrades Stack Overflow / Stack Exchange URLs to keyless API v2.3 native Markdown (with HTML fallback), sorting the Accepted Answer first.","domains":["stackoverflow.com","www.stackoverflow.com","serverfault.com","superuser.com","askubuntu.com","mathoverflow.net","stackapps.com","*.stackexchange.com"],"exampleUrls":["https://stackoverflow.com/questions/11227809/why-is-processing-a-sorted-array-faster-than-processing-an-unsorted-array"],"match":{"hostMap":{"param":"siteParam","stripWww":true,"exact":{"stackoverflow.com":"stackoverflow","serverfault.com":"serverfault","superuser.com":"superuser","askubuntu.com":"askubuntu","mathoverflow.net":"mathoverflow","stackapps.com":"stackapps"},"suffixSubdomain":".stackexchange.com"},"exactSegments":false,"pathSegments":[{"param":"qPrefix","allowValues":["questions","q"]},{"param":"qid","charset":"digits"}]},"twin":{"fetchUrl":"https://api.stackexchange.com/2.3/questions/{qid}?site={siteParam}&filter=%2120aKG._8Oscv%2A6dguVOli","kind":"json","accept":"application/json"},"extract":{"rootPath":"items.0","requireFields":["title"],"vars":{"title":{"paths":["title"],"format":"strip_tags"},"score":{"paths":["score"],"default":"0"},"tags":{"paths":["tags"],"limit":8,"itemWrap":"`","join":", "},"qMdRaw":{"paths":["body_markdown"],"format":"se_markdown"},"qHtmlMd":{"paths":["body"],"format":"html_to_md"},"qMd":{"template":"{qMdRaw}","whenVars":["qMdRaw"],"fallbackVar":"qHtmlMd"},"link":{"paths":["link"],"requireHttps":true}},"requireVars":["qMd"],"titleTemplate":"{title}","metaLine":[{"label":"Votes","template":"{score}"},{"label":"Tags","template":"{tags}","whenVar":"tags"}],"sections":[{"heading":"Question","textVar":"qMd"},{"heading":"","subsectionsArrayPath":"answers","sortBy":{"boolDescField":"is_accepted","numDescField":"score"},"limit":8,"requireItemVar":"ansMd","subsectionHeadingTemplate":"Answer {index1} (Score: {scoreLabel})","subsectionAltWhenVar":"acceptedFlag","subsectionAltHeadingTemplate":"✅ Accepted Answer (Score: {scoreLabel})","subsectionBodyVar":"ansMd","itemVars":{"ansMdRaw":{"paths":["body_markdown"],"format":"se_markdown"},"ansHtmlMd":{"paths":["body"],"format":"html_to_md"},"ansMd":{"template":"{ansMdRaw}","whenVars":["ansMdRaw"],"fallbackVar":"ansHtmlMd"},"ansScore":{"paths":["score"],"default":"0"},"ansAuthor":{"paths":["owner.display_name"],"format":"strip_tags"},"scoreLabel":{"template":"{ansScore} — by {ansAuthor}","whenVars":["ansAuthor"],"fallbackVar":"ansScore"},"acceptedFlag":{"paths":["is_accepted"],"format":"bool_map","trueValue":"1","falseValue":""}}}],"linksVars":["link"]},"htmlRoutes":[{"match":{"exactSegments":false,"pathSegments":["questions",{"param":"qid","charset":"digits"}]},"mode":"stackexchange_html"}]},{"id":"stamped-loox-junip","name":"Stamped, Loox & Junip Product Reviews","category":"commerce-social","description":"Extracts public Stamped, Junip, and Loox storefront API review JSON payloads without hitting disallowed loox.io/widget paths.","domains":["stamped.io","api.juniphq.com","apid.juniphq.com","storefront-api.loox.io"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://stamped.io/api/widget/reviews?sId=291293&apiKey=a23ad1ea-e527-4a21-9a95-37fefe0ff5cd&productId=8317758832957&page=1&take=10"],"routes":[{"match":{"hosts":["stamped.io"],"pathEquals":["/api/widget/reviews","/api/widget/reviews/"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"stamped_loox_junip_reviews"}},{"match":{"anyOf":[{"hosts":["api.juniphq.com","apid.juniphq.com"],"pathEquals":["/v1/product_reviews","/v1/display_settings"]},{"hosts":["api.juniphq.com","apid.juniphq.com"],"pathSegments":["v1","products",{"param":"productId","charset":"pkg","minLen":1,"maxLen":120}]}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"stamped_loox_junip_reviews"}},{"match":{"hosts":["storefront-api.loox.io"],"pathSegments":["storefront","v1","store",{"param":"storeId","charset":"alnum_dash","minLen":2,"maxLen":80},{"param":"endpoint","allowValues":["product-reviews","bottomline"]}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"stamped_loox_junip_reviews"}}],"htmlRoutes":[{"id":"stamped-loox-junip","match":{"exactSegments":false},"mode":"stamped_loox_junip_html"}]},{"id":"state-court-portals","name":"State Court Portals","category":"public-records","description":"Extracts public state court appellate pages, orders, and opinions (www.txcourts.gov) while honestly detecting WAF, login, and SPA barriers on research.txcourts.gov.","domains":["research.txcourts.gov","www.txcourts.gov"],"auth_mode":"html","min_interval_ms":2000,"max_concurrent":1,"strict_robots":true,"exampleUrls":["https://www.txcourts.gov/supreme/orders-opinions/","https://research.txcourts.gov/CourtRecordsSearch/#!/home"],"htmlRoutes":[{"id":"state-court-portals","match":{"hosts":["research.txcourts.gov","www.txcourts.gov"]},"mode":"state_court_portals_html"}]},{"id":"state-legislatures","name":"State Legislatures (Open States & LegiScan)","category":"public-records","description":"Official Open States v3 API and LegiScan API adapter for state bills, sessions, legislators, and jurisdictions with HTML fallback.","domains":["openstates.org","www.openstates.org","v3.openstates.org","legiscan.com","www.legiscan.com","api.legiscan.com"],"auth_mode":"key","exampleUrls":["https://v3.openstates.org/bills/tx/89/HB%201","https://api.legiscan.com/?op=getBill&id=1167968"],"routes":[{"match":{"hosts":["v3.openstates.org"],"anyOf":[{"pathPrefix":"/bills"},{"pathPrefix":"/jurisdictions"},{"pathPrefix":"/people"},{"pathPrefix":"/events"},{"pathPrefix":"/committees"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":4194304},"extract":{"jsonMode":"state_legislatures_json"}},{"match":{"hosts":["openstates.org","www.openstates.org"],"exactSegments":false,"pathSegments":[{"param":"state","charset":"alnum","minLen":2,"maxLen":2,"transform":"lower"},"bills",{"param":"session","charset":"url_seg","minLen":1,"maxLen":40},{"param":"billId","charset":"url_seg","minLen":1,"maxLen":40}]},"twin":{"fetchUrl":"https://v3.openstates.org/bills/{state}/{session}/{billId}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":4194304},"extract":{"jsonMode":"state_legislatures_json"}},{"match":{"hosts":["api.legiscan.com"],"queryParams":[{"name":"op","param":"op","charset":"alnum","minLen":3,"maxLen":40}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":4194304},"extract":{"jsonMode":"state_legislatures_json"}}],"htmlRoutes":[{"id":"state-legislatures","match":{"hosts":["openstates.org","www.openstates.org","legiscan.com","www.legiscan.com"],"exactSegments":false},"mode":"state_legislatures_html"}]},{"id":"state-sos-business","name":"State Secretary of State Business Registries","category":"public-records","description":"Extracts public state business registry filings (DE, CA, FL, TX) with strict robots.txt enforcement, rate pacing, and WAF/Incapsula/Cloudflare rejection.","domains":["icis.corp.delaware.gov","bizfileonline.sos.ca.gov","search.sunbiz.org","mycpa.cpa.state.tx.us","comptroller.texas.gov"],"auth_mode":"pub","strict_robots":true,"min_interval_ms":2000,"max_concurrent":1,"exampleUrls":["https://comptroller.texas.gov/taxes/franchise/"],"routes":[{"match":{"hosts":["bizfileonline.sos.ca.gov"],"exactSegments":false,"pathSegments":["search","business",{"param":"recordId","charset":"url_seg","minLen":1,"maxLen":64}]},"twin":{"fetchUrl":"https://bizfileonline.sos.ca.gov/api/Records/businesssearch/{recordId}","kind":"json","accept":"application/json","auth_mode":"pub","maxBytes":2097152},"extract":{"jsonMode":"state_sos_json"}},{"match":{"hosts":["bizfileonline.sos.ca.gov"],"pathPrefix":"/api/Records/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"pub","maxBytes":2097152},"extract":{"jsonMode":"state_sos_json"}}],"htmlRoutes":[{"id":"state-sos-business","match":{"hosts":["icis.corp.delaware.gov","bizfileonline.sos.ca.gov","search.sunbiz.org","mycpa.cpa.state.tx.us","comptroller.texas.gov"],"exactSegments":false},"mode":"state_sos_html"}]},{"id":"state-workforce-boards","name":"State Workforce & Public Job Boards","category":"jobs","description":"Extracts structured public job postings from state workforce portals (jobs.myflorida.com, statejobs.ny.gov, calcareers.ca.gov, usnlx.com) with Rule 5 honest fallbacks.","domains":["statejobs.ny.gov","calcareers.ca.gov","usnlx.com"],"universalEngine":true,"auth_mode":"html","strict_robots":true,"exampleUrls":["https://jobs.myflorida.com/job/TALLAHASSEE-Attorney-FL-32301/1425569100/","https://statejobs.ny.gov/public/vacancyDetailsView.cfm?id=229697"],"htmlRoutes":[{"id":"state-workforce-boards","mode":"state_workforce_boards_html","match":{"excludeHosts":["governmentjobs.com","*.governmentjobs.com","workintexas.com","*.workintexas.com"],"anyOf":[{"hosts":["jobs.myflorida.com","statejobs.ny.gov","calcareers.ca.gov","www.calcareers.ca.gov","usnlx.com","www.usnlx.com"],"exactSegments":false},{"hostSubdomain":{"suffix":".usnlx.com","param":"state","reserved":["www","api","login"]},"exactSegments":false}]}}]},{"id":"status-page-pack","name":"Status Page Pack","category":"developer","description":"Extracts service status, components, and incidents from Instatus, Better Stack, Status.io, and Cachet public JSON endpoints and SSR HTML pages.","domains":["deno.instatus.com","status.instatus.com","status.betterstack.com","status.raycast.com","status.gitlab.com","demo.cachethq.io"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://deno.instatus.com/","https://deno.instatus.com/v2/components.json","https://status.betterstack.com/","https://status.gitlab.com/1.0/status/5b36dc6502d06804c08349f7","https://demo.cachethq.io/api/v1/components"],"routes":[{"match":{"pathEquals":["/summary.json","/v2/components.json","/v2/incidents.json","/index.json","/api/v1/components","/api/v1/incidents","/api/v1/status"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"status_page_pack"}},{"match":{"exactSegments":true,"pathSegments":["1.0","status",{"param":"statusId","charset":"alnum","minLen":16,"maxLen":48}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"status_page_pack"}}],"htmlRoutes":[{"id":"status-page-pack","match":{"exactSegments":false},"mode":"status_page_pack_html"}]},{"id":"stockist","name":"Stockist Dealer Locator","category":"commerce-social","description":"Extracts public Stockist store/dealer locator JSON payloads and discovers Stockist widget tags on merchant HTML pages.","domains":["stockist.co","www.stockist.co"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://stockist.co/api/v1/map_93wm75n3/locations/all"],"routes":[{"match":{"hosts":["stockist.co","www.stockist.co"],"pathSegments":["api","v1",{"param":"tag","charset":"alnum_dash","minLen":2,"maxLen":64},"locations.json"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"stockist_locations"}},{"match":{"hosts":["stockist.co","www.stockist.co"],"pathSegments":["api","v1",{"param":"tag","charset":"alnum_dash","minLen":2,"maxLen":64},"locations","all"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"stockist_locations"}}],"htmlRoutes":[{"id":"stockist","match":{"exactSegments":false},"mode":"stockist_html"}]},{"id":"storemapper","name":"Storemapper Dealer Locator","category":"commerce-social","description":"Extracts public Storemapper store locator JSON feeds and discovers Storemapper widget IDs on merchant HTML pages.","domains":["www.storemapper.co","storemapper.co"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://www.storemapper.co/api/users/12873/stores.json"],"routes":[{"match":{"hosts":["www.storemapper.co","storemapper.co"],"pathSegments":["api","users",{"param":"userId","charset":"alnum_dash","minLen":1,"maxLen":64},"stores.json"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"storemapper_locations"}}],"htmlRoutes":[{"id":"storemapper","match":{"exactSegments":false},"mode":"storemapper_html"}]},{"id":"storerocket","name":"StoreRocket Dealer Locator","category":"commerce-social","description":"Extracts public StoreRocket store locator JSON payloads and discovers StoreRocket widget IDs on merchant HTML pages.","domains":["storerocket.io","www.storerocket.io"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://storerocket.io/api/user/OdJERNO8WE/locations"],"routes":[{"match":{"hosts":["storerocket.io","www.storerocket.io"],"pathSegments":["api","user",{"param":"userId","charset":"alnum_dash","minLen":2,"maxLen":64},"locations"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"storerocket_locations"}}],"htmlRoutes":[{"id":"storerocket","match":{"exactSegments":false},"mode":"storerocket_html"}]},{"id":"strava-segments","name":"Strava Public Segments","category":"commerce-social","description":"Extracts Strava segments via authenticated API v3 (/api/v3/segments/* with STRAVA_ACCESS_TOKEN or Part 2 strava Virtual OAuth MCP) and public /segments/* __NEXT_DATA__ HTML fallback, rejecting /register/free authwalls.","domains":["www.strava.com","strava.com"],"auth_mode":"key","strict_robots":true,"exampleUrls":["https://www.strava.com/segments/229781","https://www.strava.com/api/v3/segments/229781"],"routes":[{"match":{"hosts":["www.strava.com","strava.com"],"exactSegments":true,"pathSegments":["api","v3","segments",{"param":"segmentId","charset":"digits","minLen":1,"maxLen":16}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":1048576,"auth_mode":"key"},"extract":{"jsonMode":"strava_segments_json"}}],"htmlRoutes":[{"id":"strava-segments","mode":"strava_segments_html","match":{"hosts":["www.strava.com","strava.com"],"pathPrefix":"/segments/","exactSegments":false}}]},{"id":"supremecourt-gov","name":"U.S. Supreme Court Opinions, Dockets & Orders","category":"public-records","description":"Robots-enforced HTML adapter for Supreme Court slip opinions, public docket files, and orders of the Court.","domains":["supremecourt.gov","www.supremecourt.gov"],"auth_mode":"html","min_interval_ms":1000,"strict_robots":true,"exampleUrls":["https://www.supremecourt.gov/opinions/slipopinion/24","https://www.supremecourt.gov/docket/docketfiles/html/public/23-939.html","https://www.supremecourt.gov/orders/ordersofthecourt/24"],"htmlRoutes":[{"id":"supremecourt-gov","match":{"anyOf":[{"pathPrefix":"/opinions/"},{"pathPrefix":"/docket/"},{"pathPrefix":"/orders/"}]},"mode":"supremecourt_html"}]},{"id":"taleo-full","name":"Oracle Taleo Career Section Job Search","category":"jobs","description":"Formats Oracle Taleo career-section job boards via the public /careersection/rest/jobboard/searchjobs endpoint the career page itself calls (portal id from the page): title, location, posted date, contest number, total open requisitions. Add §ion= to get job-detail links.","domains":["hdr.taleo.net"],"universalEngine":true,"auth_mode":"pub","min_interval_ms":3000,"strict_robots":true,"exampleUrls":["https://hdr.taleo.net/careersection/rest/jobboard/searchjobs?lang=en&portal=101430233§ion=ex"],"routes":[{"match":{"hostSubdomain":{"suffix":".taleo.net","param":"tenant","reserved":["www"]},"pathEquals":["/careersection/rest/jobboard/searchjobs"],"queryParams":[{"name":"portal","param":"portal","charset":"digits","minLen":4,"maxLen":20},{"name":"section","param":"section","charset":"slug","minLen":1,"maxLen":40,"optional":true}]},"twin":{"fetchUrl":"https://{host}/careersection/rest/jobboard/searchjobs?lang=en&portal={portal}","kind":"json","accept":"application/json","method":"POST","contentType":"application/json","headers":{"tz":"GMT-06:00","tzname":"America/Chicago"},"requestBody":"{\"multilineEnabled\":false,\"sortingSelection\":{\"sortBySelectionParam\":\"3\",\"ascendingSortingOrder\":\"false\"},\"fieldData\":{\"fields\":{\"KEYWORD\":\"\",\"LOCATION\":\"\"},\"valid\":true},\"filterSelectionParam\":{\"searchFilterSelections\":[]},\"advancedSearchFiltersSelectionParam\":{\"searchFilterSelections\":[]},\"pageNo\":1}","maxBytes":4194304},"extract":{"jsonMode":"taleo_searchjobs_json"}}]},{"id":"target","name":"Target","category":"commerce-social","description":"Extracts Target product pages from schema.org Product JSON-LD (including entity-encoded ld+json) and live Target SSR HTML metadata without calling disallowed redsky endpoints.","domains":["target.com","www.target.com","redsky.target.com"],"auth_mode":"html","min_interval_ms":2000,"max_concurrent":1,"strict_robots":true,"exampleUrls":["https://www.target.com/p/campus-lab-university-of-arkansas-at-monticello-official-uam-boll-weevils-logo-unisex-adult-pull-over-hoodie/-/A-1000000076"],"htmlRoutes":[{"id":"target","match":{"hosts":["target.com","www.target.com"]},"mode":"target_html"}]},{"id":"teamtailor","name":"Teamtailor Career Portals","category":"jobs","description":"Upgrades [.na].teamtailor.com career roots to their /jobs.rss feed with locations and departments.","domains":["*.teamtailor.com"],"exampleUrls":["https://stratio.teamtailor.com/","https://stratio.teamtailor.com/jobs"],"match":{"hostSubdomain":{"suffix":".teamtailor.com","param":"org","stripOptional2LetterRegion":true,"reserved":["www","app","career"]},"pathSegments":[{"param":"jobsLit","charset":"alnum","allowValues":["jobs"],"optional":true}]},"twin":{"id":"teamtailor","fetchUrl":"https://{host}/jobs.rss","kind":"text","accept":"application/rss+xml"},"extract":{"xml":{"mode":"items_table","requireAnyTags":["rss","channel"],"itemTag":"item","channelTitleFallbackParam":"org","titleTemplate":"{channelTitle} — Open Roles ({itemCount})","emptyText":"No open positions currently listed.","limit":100,"requireItemVar":"jTitle","collectLinkVar":"jLink","itemVars":{"jTitle":{"tags":["title"]},"jLink":{"tags":["link"]},"dept":{"tags":["tt:department","category"],"default":"-"},"loc":{"tags":["tt:location","g:location","location"],"default":"-"},"pubDate":{"tags":["pubDate"],"sliceMax":16,"default":"-"}},"columns":[{"header":"Role","template":"[{jTitle}]({jLink})"},{"header":"Department","template":"{dept}"},{"header":"Location","template":"{loc}"},{"header":"Published","template":"{pubDate}"}]}}},{"id":"tech-job-boards-jsonld","name":"Tech Job Boards (BuiltIn, Wellfound, Dice)","category":"jobs","description":"Extracts JobPosting JSON-LD (including HTML-entity-encoded application/ld+json) from BuiltIn, Wellfound, and Dice while honoring robots.txt and rejecting Cloudflare Turnstile/SPA shells.","domains":["builtin.com","www.builtin.com","wellfound.com","www.wellfound.com","dice.com","www.dice.com"],"auth_mode":"html","strict_robots":true,"exampleUrls":["https://builtin.com/job/executive-employee-social-media-vice-president/12592638"],"htmlRoutes":[{"id":"tech-job-boards-jsonld","mode":"tech_job_boards_jsonld_html","match":{"hosts":["builtin.com","www.builtin.com","wellfound.com","www.wellfound.com","dice.com","www.dice.com"],"exactSegments":false}}]},{"id":"terraform-registry","name":"Terraform Registry","category":"developer","description":"Upgrades registry.terraform.io provider and module pages to the official keyless /v1/ JSON API with versions, documentation entries, inputs, outputs, and README.","domains":["registry.terraform.io"],"exampleUrls":["https://registry.terraform.io/providers/hashicorp/random","https://registry.terraform.io/providers/hashicorp/random/3.8.1","https://registry.terraform.io/modules/terraform-aws-modules/vpc/aws","https://registry.terraform.io/modules/terraform-aws-modules/vpc/aws/5.1.0"],"routes":[{"match":{"exactSegments":true,"pathSegments":["providers",{"param":"ns","charset":"pkg","minLen":1,"maxLen":80},{"param":"name","charset":"pkg","minLen":1,"maxLen":80},{"param":"ver","charset":"url_seg","reserved":["latest","docs"],"minLen":1,"maxLen":64}]},"twin":{"fetchUrl":"https://registry.terraform.io/v1/providers/{ns}/{name}/{ver}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"requireFields":["namespace","name","version"],"vars":{"namespace":{"paths":["namespace"]},"name":{"paths":["name"]},"version":{"paths":["version"]},"tier":{"paths":["tier"]},"downloads":{"paths":["downloads"],"format":"int_comma"},"publishedAt":{"paths":["published_at"],"sliceMax":10},"desc":{"paths":["description"],"trim":true},"source":{"paths":["source"],"requireHttps":true},"versionCount":{"paths":["versions"],"format":"array_len_comma"}},"titleTemplate":"{namespace}/{name} v{version} (Terraform Provider)","descriptionVar":"desc","publishedTimeVar":"publishedAt","introVar":"desc","bullets":[{"label":"Provider","template":"`{namespace}/{name}`"},{"label":"Version","template":"`{version}`"},{"label":"Tier","template":"{tier}","whenVar":"tier"},{"label":"Downloads","template":"{downloads}","whenVar":"downloads"},{"label":"Published","template":"{publishedAt}","whenVar":"publishedAt"},{"label":"Available Versions","template":"{versionCount}","whenVar":"versionCount"},{"label":"Source","template":"{source}","whenVar":"source"}],"sections":[{"heading":"Documentation Entries","arrayPath":"docs","limit":40,"columns":[{"header":"Title","paths":["title"]},{"header":"Category","paths":["category"]},{"header":"Language","paths":["language"]},{"header":"Path","paths":["path"],"code":true}]}],"linksVars":["source"]}},{"match":{"exactSegments":true,"pathSegments":["providers",{"param":"ns","charset":"pkg","minLen":1,"maxLen":80},{"param":"name","charset":"pkg","minLen":1,"maxLen":80},{"param":"ver","charset":"alnum","allowValues":["latest"],"minLen":6,"maxLen":6}]},"twin":{"fetchUrl":"https://registry.terraform.io/v1/providers/{ns}/{name}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"requireFields":["namespace","name","version"],"vars":{"namespace":{"paths":["namespace"]},"name":{"paths":["name"]},"version":{"paths":["version"]},"tier":{"paths":["tier"]},"downloads":{"paths":["downloads"],"format":"int_comma"},"publishedAt":{"paths":["published_at"],"sliceMax":10},"desc":{"paths":["description"],"trim":true},"source":{"paths":["source"],"requireHttps":true},"versionCount":{"paths":["versions"],"format":"array_len_comma"}},"titleTemplate":"{namespace}/{name} v{version} (Terraform Provider)","descriptionVar":"desc","publishedTimeVar":"publishedAt","introVar":"desc","bullets":[{"label":"Provider","template":"`{namespace}/{name}`"},{"label":"Version","template":"`{version}`"},{"label":"Tier","template":"{tier}","whenVar":"tier"},{"label":"Downloads","template":"{downloads}","whenVar":"downloads"},{"label":"Published","template":"{publishedAt}","whenVar":"publishedAt"},{"label":"Available Versions","template":"{versionCount}","whenVar":"versionCount"},{"label":"Source","template":"{source}","whenVar":"source"}],"sections":[{"heading":"Documentation Entries","arrayPath":"docs","limit":40,"columns":[{"header":"Title","paths":["title"]},{"header":"Category","paths":["category"]},{"header":"Language","paths":["language"]},{"header":"Path","paths":["path"],"code":true}]}],"linksVars":["source"]}},{"match":{"exactSegments":true,"pathSegments":["providers",{"param":"ns","charset":"pkg","minLen":1,"maxLen":80},{"param":"name","charset":"pkg","minLen":1,"maxLen":80}]},"twin":{"fetchUrl":"https://registry.terraform.io/v1/providers/{ns}/{name}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"requireFields":["namespace","name","version"],"vars":{"namespace":{"paths":["namespace"]},"name":{"paths":["name"]},"version":{"paths":["version"]},"tier":{"paths":["tier"]},"downloads":{"paths":["downloads"],"format":"int_comma"},"publishedAt":{"paths":["published_at"],"sliceMax":10},"desc":{"paths":["description"],"trim":true},"source":{"paths":["source"],"requireHttps":true},"versionCount":{"paths":["versions"],"format":"array_len_comma"}},"titleTemplate":"{namespace}/{name} v{version} (Terraform Provider)","descriptionVar":"desc","publishedTimeVar":"publishedAt","introVar":"desc","bullets":[{"label":"Provider","template":"`{namespace}/{name}`"},{"label":"Version","template":"`{version}`"},{"label":"Tier","template":"{tier}","whenVar":"tier"},{"label":"Downloads","template":"{downloads}","whenVar":"downloads"},{"label":"Published","template":"{publishedAt}","whenVar":"publishedAt"},{"label":"Available Versions","template":"{versionCount}","whenVar":"versionCount"},{"label":"Source","template":"{source}","whenVar":"source"}],"sections":[{"heading":"Documentation Entries","arrayPath":"docs","limit":40,"columns":[{"header":"Title","paths":["title"]},{"header":"Category","paths":["category"]},{"header":"Language","paths":["language"]},{"header":"Path","paths":["path"],"code":true}]}],"linksVars":["source"]}},{"match":{"exactSegments":true,"pathSegments":["modules",{"param":"ns","charset":"pkg","minLen":1,"maxLen":80},{"param":"name","charset":"pkg","minLen":1,"maxLen":80},{"param":"provider","charset":"pkg","minLen":1,"maxLen":80},{"param":"ver","charset":"url_seg","reserved":["latest","submodules","examples"],"minLen":1,"maxLen":64}]},"twin":{"fetchUrl":"https://registry.terraform.io/v1/modules/{ns}/{name}/{provider}/{ver}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"requireFields":["namespace","name","provider","version"],"vars":{"namespace":{"paths":["namespace"]},"name":{"paths":["name"]},"provider":{"paths":["provider"]},"version":{"paths":["version"]},"verified":{"paths":["verified"],"format":"bool_map","trueValue":"Verified","falseValue":"Unverified"},"downloads":{"paths":["downloads"],"format":"int_comma"},"publishedAt":{"paths":["published_at"],"sliceMax":10},"desc":{"paths":["description"],"trim":true},"source":{"paths":["source"],"requireHttps":true},"readme":{"paths":["root.readme"],"format":"demote_h1","trim":true}},"titleTemplate":"{namespace}/{name}/{provider} v{version} (Terraform Module)","descriptionVar":"desc","publishedTimeVar":"publishedAt","introVar":"desc","bullets":[{"label":"Module","template":"`{namespace}/{name}/{provider}`"},{"label":"Version","template":"`{version}`"},{"label":"Status","template":"{verified}","whenVar":"verified"},{"label":"Downloads","template":"{downloads}","whenVar":"downloads"},{"label":"Published","template":"{publishedAt}","whenVar":"publishedAt"},{"label":"Source","template":"{source}","whenVar":"source"}],"bodyVar":"readme","sections":[{"heading":"Inputs","arrayPath":"root.inputs","limit":60,"columns":[{"header":"Name","paths":["name"],"code":true},{"header":"Type","paths":["type"],"code":true},{"header":"Required","paths":["required"]},{"header":"Description","paths":["description"]}]},{"heading":"Outputs","arrayPath":"root.outputs","limit":40,"columns":[{"header":"Name","paths":["name"],"code":true},{"header":"Description","paths":["description"]}]},{"heading":"Submodules","arrayPath":"submodules","limit":30,"columns":[{"header":"Name","paths":["name"],"code":true},{"header":"Path","paths":["path"],"code":true}]}],"linksVars":["source"]}},{"match":{"exactSegments":true,"pathSegments":["modules",{"param":"ns","charset":"pkg","minLen":1,"maxLen":80},{"param":"name","charset":"pkg","minLen":1,"maxLen":80},{"param":"provider","charset":"pkg","minLen":1,"maxLen":80},{"param":"ver","charset":"alnum","allowValues":["latest"],"minLen":6,"maxLen":6}]},"twin":{"fetchUrl":"https://registry.terraform.io/v1/modules/{ns}/{name}/{provider}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"requireFields":["namespace","name","provider","version"],"vars":{"namespace":{"paths":["namespace"]},"name":{"paths":["name"]},"provider":{"paths":["provider"]},"version":{"paths":["version"]},"verified":{"paths":["verified"],"format":"bool_map","trueValue":"Verified","falseValue":"Unverified"},"downloads":{"paths":["downloads"],"format":"int_comma"},"publishedAt":{"paths":["published_at"],"sliceMax":10},"desc":{"paths":["description"],"trim":true},"source":{"paths":["source"],"requireHttps":true},"readme":{"paths":["root.readme"],"format":"demote_h1","trim":true}},"titleTemplate":"{namespace}/{name}/{provider} v{version} (Terraform Module)","descriptionVar":"desc","publishedTimeVar":"publishedAt","introVar":"desc","bullets":[{"label":"Module","template":"`{namespace}/{name}/{provider}`"},{"label":"Version","template":"`{version}`"},{"label":"Status","template":"{verified}","whenVar":"verified"},{"label":"Downloads","template":"{downloads}","whenVar":"downloads"},{"label":"Published","template":"{publishedAt}","whenVar":"publishedAt"},{"label":"Source","template":"{source}","whenVar":"source"}],"bodyVar":"readme","sections":[{"heading":"Inputs","arrayPath":"root.inputs","limit":60,"columns":[{"header":"Name","paths":["name"],"code":true},{"header":"Type","paths":["type"],"code":true},{"header":"Required","paths":["required"]},{"header":"Description","paths":["description"]}]},{"heading":"Outputs","arrayPath":"root.outputs","limit":40,"columns":[{"header":"Name","paths":["name"],"code":true},{"header":"Description","paths":["description"]}]},{"heading":"Submodules","arrayPath":"submodules","limit":30,"columns":[{"header":"Name","paths":["name"],"code":true},{"header":"Path","paths":["path"],"code":true}]}],"linksVars":["source"]}},{"match":{"exactSegments":true,"pathSegments":["modules",{"param":"ns","charset":"pkg","minLen":1,"maxLen":80},{"param":"name","charset":"pkg","minLen":1,"maxLen":80},{"param":"provider","charset":"pkg","minLen":1,"maxLen":80}]},"twin":{"fetchUrl":"https://registry.terraform.io/v1/modules/{ns}/{name}/{provider}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"requireFields":["namespace","name","provider","version"],"vars":{"namespace":{"paths":["namespace"]},"name":{"paths":["name"]},"provider":{"paths":["provider"]},"version":{"paths":["version"]},"verified":{"paths":["verified"],"format":"bool_map","trueValue":"Verified","falseValue":"Unverified"},"downloads":{"paths":["downloads"],"format":"int_comma"},"publishedAt":{"paths":["published_at"],"sliceMax":10},"desc":{"paths":["description"],"trim":true},"source":{"paths":["source"],"requireHttps":true},"readme":{"paths":["root.readme"],"format":"demote_h1","trim":true}},"titleTemplate":"{namespace}/{name}/{provider} v{version} (Terraform Module)","descriptionVar":"desc","publishedTimeVar":"publishedAt","introVar":"desc","bullets":[{"label":"Module","template":"`{namespace}/{name}/{provider}`"},{"label":"Version","template":"`{version}`"},{"label":"Status","template":"{verified}","whenVar":"verified"},{"label":"Downloads","template":"{downloads}","whenVar":"downloads"},{"label":"Published","template":"{publishedAt}","whenVar":"publishedAt"},{"label":"Source","template":"{source}","whenVar":"source"}],"bodyVar":"readme","sections":[{"heading":"Inputs","arrayPath":"root.inputs","limit":60,"columns":[{"header":"Name","paths":["name"],"code":true},{"header":"Type","paths":["type"],"code":true},{"header":"Required","paths":["required"]},{"header":"Description","paths":["description"]}]},{"heading":"Outputs","arrayPath":"root.outputs","limit":40,"columns":[{"header":"Name","paths":["name"],"code":true},{"header":"Description","paths":["description"]}]},{"heading":"Submodules","arrayPath":"submodules","limit":30,"columns":[{"header":"Name","paths":["name"],"code":true},{"header":"Path","paths":["path"],"code":true}]}],"linksVars":["source"]}}]},{"id":"ticketmaster-discovery","name":"Ticketmaster Discovery API","category":"commerce-social","description":"Extracts Ticketmaster events, venues, and attractions via the official Ticketmaster Discovery API v2 with Schema.org Event JSON-LD HTML fallback.","domains":["ticketmaster.com","www.ticketmaster.com","app.ticketmaster.com"],"auth_mode":"key","exampleUrls":["https://app.ticketmaster.com/discovery/v2/events.json?keyword=concert&countryCode=US","https://www.ticketmaster.com/demo-tour-los-angeles-california-12-01-2026/event/3C006457CF441F75"],"routes":[{"match":{"hosts":["app.ticketmaster.com"],"pathPrefix":"/discovery/v2/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"key"},"extract":{"jsonMode":"ticketmaster_json"}},{"match":{"hosts":["ticketmaster.com","www.ticketmaster.com"],"scanSegment":{"afterLiteral":"event","param":"eventId","charset":"alnum","minLen":6,"maxLen":32}},"twin":{"fetchUrl":"https://app.ticketmaster.com/discovery/v2/events/{eventId}.json","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"key"},"extract":{"jsonMode":"ticketmaster_json"}}],"htmlRoutes":[{"id":"ticketmaster-discovery","match":{"hosts":["ticketmaster.com","www.ticketmaster.com"],"exactSegments":false},"mode":"ticketmaster_html"}]},{"id":"townnews-blox","name":"TownNews BLOX CMS","category":"commerce-social","description":"Extracts TownNews BLOX ?f=json news asset twins and discovers tncms/bloxcms markers on local publisher HTML pages.","domains":["lancasteronline.com"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://lancasteronline.com/sports/highschool/football/district-3-gold-piaa-glory-up-for-grabs-for-4-l-l-league-football-teams/article_a6f1fede-b459-44f2-a5cd-8224c48f76a8.html"],"routes":[{"match":{"hosts":["lancasteronline.com"],"pathSuffix":".html"},"twin":{"fetchUrl":"{requestUrl}","setQueryParams":{"f":"json"},"kind":"json","accept":"application/json"},"extract":{"jsonMode":"townnews_blox_json"}}],"htmlRoutes":[{"id":"townnews-blox","match":{"exactSegments":false},"mode":"townnews_blox_html"}]},{"id":"tq-ebike","name":"TQ e-Mobility Products & Support","category":"commerce-social","description":"Extracts Product JSON-LD, drive system technical specs, and support documentation from www.tq-ebike.com product and help-support pages.","domains":["www.tq-ebike.com","tq-ebike.com"],"exampleUrls":["https://www.tq-ebike.com/en/e-bike-system/hpr50/"],"htmlRoutes":[{"id":"tq-ebike","mode":"dom","match":{"optionalLeadingLocale":true,"exactSegments":false,"anyOf":[{"pathSegments":["products",{"param":"slug","charset":"safe_subpath","greedy":true,"minLen":1,"maxLen":160}]},{"pathSegments":["e-bike-system",{"param":"slug","charset":"safe_subpath","greedy":true,"minLen":1,"maxLen":160}]},{"pathSegments":["help-support",{"param":"slug","charset":"safe_subpath","greedy":true,"minLen":1,"maxLen":160}]}]},"jsonLdTypes":["Product"],"vars":{"title":{"jsonLdPaths":["name"],"cssText":["main h1","h1","title"],"trim":true},"sku":{"jsonLdPaths":["sku"],"trim":true},"brand":{"jsonLdPaths":["brand.name","brand"],"trim":true},"body":{"cssHtmlToMd":["main","article",".tx-specs",".site-content","body"],"format":"strip_leading_h1","trim":true}},"requireVars":["title","body"],"titleTemplate":"{title}","bullets":[{"label":"Brand","template":"{brand}","whenVar":"brand"},{"label":"SKU","template":"`{sku}`","whenVar":"sku"}],"bodyVar":"body","preserveBodyLinksFromVar":"body"}]},{"id":"trailforks-mtb-project","name":"Trailforks & MTB Project Trail Intelligence","category":"commerce-social","description":"Official Trailforks API v1 key-authenticated twin + HTML fallback for Trailforks and MTB Project trail reports (honoring mtbproject.com Crawl-delay: 60 and Disallow: /data*).","domains":["trailforks.com","www.trailforks.com","mtbproject.com","www.mtbproject.com"],"auth_mode":"key","min_interval_ms":1000,"strict_robots":true,"exampleUrls":["https://www.trailforks.com/trails/betasso-preserve-canyon-loop/","https://www.trailforks.com/api/1/trail?id=40401","https://www.mtbproject.com/trail/12376/buffehr-creek-trail"],"routes":[{"match":{"hosts":["trailforks.com","www.trailforks.com"],"pathEquals":["/api/1/trail","/api/1/trail/","/api/1/trails","/api/1/trails/"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"trailforks_api_json"}},{"match":{"hosts":["trailforks.com","www.trailforks.com"],"pathSegments":["trails",{"param":"slug","charset":"url_seg","minLen":1,"maxLen":160}],"exactSegments":false},"twin":{"fetchUrl":"https://www.trailforks.com/api/1/trail?id={slug}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"trailforks_api_json"}}],"htmlRoutes":[{"id":"trailforks-mtb-project","match":{"exactSegments":false},"mode":"trailforks_mtb_html"}]},{"id":"transitland-gtfs","name":"Transitland GTFS Registry","category":"public-records","description":"Transitland v2 REST API (apikey header on apex transit.land) for GTFS feeds/operators/routes/stops with www.transit.land/data/feeds HTML fallback.","domains":["transit.land","www.transit.land"],"auth_mode":"key","exampleUrls":["https://transit.land/api/v2/rest/feeds?limit=1","https://www.transit.land/data/feeds/f-9q9-bart"],"routes":[{"match":{"hosts":["transit.land"],"pathPrefix":"/api/v2/rest/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"transitland_json"}},{"match":{"hosts":["www.transit.land","transit.land"],"exactSegments":true,"pathSegments":["data","feeds",{"param":"feedId","charset":"alnum_dash","minLen":2,"maxLen":80}]},"twin":{"fetchUrl":"https://transit.land/api/v2/rest/feeds/{feedId}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"transitland_json"}}],"htmlRoutes":[{"id":"transitland-gtfs","match":{"hosts":["www.transit.land","transit.land"],"exactSegments":false},"mode":"transitland_html"}]},{"id":"treasury-fiscal-data","name":"U.S. Treasury Fiscal Data","category":"finance","description":"Upgrades fiscaldata.treasury.gov dataset pages to keyless api.fiscaldata.treasury.gov JSON endpoints with metadata-labeled GFM tables and HTML fallback.","domains":["fiscaldata.treasury.gov","api.fiscaldata.treasury.gov"],"auth_mode":"pub","exampleUrls":["https://fiscaldata.treasury.gov/datasets/debt-to-the-penny/debt-to-the-penny","https://api.fiscaldata.treasury.gov/services/api/fiscal_service/v2/accounting/od/debt_to_penny?page[size]=1"],"routes":[{"match":{"hosts":["api.fiscaldata.treasury.gov"],"pathPrefix":"/services/api/fiscal_service/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"pub","maxBytes":2097152},"extract":{"jsonMode":"treasury_fiscal_json"}},{"match":{"hosts":["fiscaldata.treasury.gov"],"pathPrefix":"/datasets/debt-to-the-penny"},"twin":{"fetchUrl":"https://api.fiscaldata.treasury.gov/services/api/fiscal_service/v2/accounting/od/debt_to_penny?sort=-record_date&page[size]=1","kind":"json","accept":"application/json","auth_mode":"pub","maxBytes":2097152},"extract":{"jsonMode":"treasury_fiscal_json"}}],"htmlRoutes":[{"id":"treasury-fiscal-data","match":{"hosts":["fiscaldata.treasury.gov"],"exactSegments":false},"mode":"treasury_fiscal_html"}]},{"id":"trustpilot","name":"Trustpilot Business Reviews","category":"commerce-social","description":"Extracts Trustpilot business summary and review records from __NEXT_DATA__ or JSON-LD while honoring robots.txt policies.","domains":["trustpilot.com","www.trustpilot.com"],"auth_mode":"html","exampleUrls":["https://www.trustpilot.com/review/shopify.com"],"htmlRoutes":[{"id":"trustpilot","match":{"hosts":["trustpilot.com","www.trustpilot.com"],"exactSegments":false},"mode":"trustpilot_html"}]},{"id":"twitch-kick","name":"Twitch & Kick Streaming","category":"commerce-social","description":"Extracts Twitch Helix (Bearer + Client-Id) and Kick public v1/v2 channel APIs plus Twitch/Kick channel HTML.","domains":["api.twitch.tv","www.twitch.tv","twitch.tv","api.kick.com","kick.com","www.kick.com"],"auth_mode":"key","exampleUrls":["https://kick.com/api/v2/channels/kick","https://www.twitch.tv/twitch","https://kick.com/kick","https://api.twitch.tv/helix/users?login=twitch"],"routes":[{"match":{"hosts":["api.twitch.tv"],"pathPrefix":"/helix/","exactSegments":false},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key"},"extract":{"jsonMode":"twitch_kick_json"}},{"match":{"hosts":["api.kick.com"],"pathPrefix":"/public/v1/","exactSegments":false},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key"},"extract":{"jsonMode":"twitch_kick_json"}},{"match":{"hosts":["kick.com","www.kick.com"],"exactSegments":true,"pathSegments":["api","v2","channels",{"param":"slug","charset":"slug","minLen":1,"maxLen":80}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"pub"},"extract":{"jsonMode":"twitch_kick_json"}}],"htmlRoutes":[{"id":"twitch-kick","match":{"hosts":["www.twitch.tv","twitch.tv","kick.com","www.kick.com"],"exactSegments":false},"mode":"twitch_kick_html"}]},{"id":"ukg-paylocity-dover","name":"UKG Pro, Paylocity & Dover Job Boards","category":"jobs","description":"Extracts structured open roles from Paylocity (/recruiting/api/feed/jobs & window.pageData), UKG Pro (*/JobBoard/* only, never / or */JobBoardView), and Dover HTML/SSR __NEXT_DATA__ (never /api/).","domains":["recruiting.ultipro.com","recruiting.paylocity.com","app.dover.com","jobs.dover.com"],"exampleUrls":["https://recruiting.paylocity.com/Recruiting/Jobs/All/cfe0e892-760a-4f34-b732-e6d0be968d4f"],"routes":[{"match":{"hosts":["recruiting.paylocity.com"],"pathPrefix":"/recruiting/jobs/all/","scanSegment":{"afterLiteral":"all","param":"guid","charset":"slug","minLen":4,"maxLen":80}},"twin":{"fetchUrl":"https://recruiting.paylocity.com/recruiting/api/feed/jobs/{guid}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"paylocity_feed"}},{"match":{"hosts":["recruiting.paylocity.com"],"pathPrefix":"/recruiting/api/feed/jobs/","scanSegment":{"afterLiteral":"jobs","param":"guid","charset":"slug","minLen":4,"maxLen":80}},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"paylocity_feed"}}],"htmlRoutes":[{"id":"ukg-paylocity-dover","mode":"ukg_pro_html","match":{"hosts":["recruiting.ultipro.com"],"pathContainsSegment":"JobBoard","minSegments":3}},{"id":"ukg-paylocity-dover","mode":"paylocity_html","match":{"hosts":["recruiting.paylocity.com"],"pathPrefix":"/recruiting/jobs/"}},{"id":"ukg-paylocity-dover","mode":"dover_html","match":{"anyOf":[{"hosts":["app.dover.com"],"exactSegments":false,"pathSegments":["jobs",{"param":"org","charset":"slug","minLen":1,"maxLen":120}]},{"hosts":["jobs.dover.com"],"minSegments":1,"reservedFirstSegment":["api","apply","static","assets","_next","login"]}]}}]},{"id":"us-cfr-govinfo","name":"U.S. CFR & GovInfo","category":"public-records","description":"Bypasses the empty Angular /app/details/ SPA on govinfo.gov by fetching static /content/pkg//html/*.htm documents or /wssearch/getContentDetail summary JSON.","domains":["www.govinfo.gov","govinfo.gov"],"exampleUrls":["https://www.govinfo.gov/app/details/CFR-2023-title16-vol2/CFR-2023-title16-vol2-part1500","https://www.govinfo.gov/app/details/CFR-2023-title16-vol2","https://www.govinfo.gov/wssearch/getContentDetail?packageId=CFR-2023-title16-vol2"],"routes":[{"match":{"exactSegments":true,"pathSegments":["app","details",{"param":"pkgId","charset":"pkg","minLen":4,"maxLen":120},{"param":"granuleId","charset":"pkg","minLen":4,"maxLen":160}]},"twin":{"fetchUrl":"https://www.govinfo.gov/content/pkg/{pkgId}/html/{granuleId}.htm","kind":"text","accept":"text/html","maxBytes":4194304},"extract":{"textMode":"html_document","titleTemplate":"{granuleId} ({pkgId})"}},{"match":{"exactSegments":true,"pathSegments":["app","details",{"param":"pkgId","charset":"pkg","minLen":4,"maxLen":120}]},"twin":{"fetchUrl":"https://www.govinfo.gov/content/pkg/{pkgId}/html/{pkgId}.htm","kind":"text","accept":"text/html","maxBytes":4194304},"extract":{"textMode":"html_document","titleTemplate":"{pkgId}"}},{"match":{"pathEquals":["/wssearch/getContentDetail"],"queryParams":[{"name":"packageId","param":"pkgId","charset":"pkg","minLen":4,"maxLen":120},{"name":"granuleId","param":"granuleId","charset":"pkg","optional":true,"maxLen":160}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"requireAnyFields":["title","packageId"],"vars":{"title":{"paths":["title"],"fallbackTemplate":"{pkgId}","trim":true},"packageId":{"paths":["packageId"],"fallbackTemplate":"{pkgId}"},"collection":{"paths":["collectionName","collection","collectionCode"]},"category":{"paths":["category"]},"dateIssued":{"paths":["dateIssued"]},"lastModified":{"paths":["lastModified"],"sliceMax":10},"authors":{"paths":["governmentAuthor","metadata.agency"],"join":", ","limit":10},"granuleCount":{"paths":["granuleCount"],"format":"int_comma"},"pdfLink":{"paths":["download.pdfLink"],"requireHttps":true},"htmlLink":{"paths":["download.htmlLink","download.htmLink"],"requireHttps":true},"xmlLink":{"paths":["download.xmlLink"],"requireHttps":true},"txtLink":{"paths":["download.txtLink"],"requireHttps":true},"zipLink":{"paths":["download.zipLink"],"requireHttps":true},"modsLink":{"paths":["download.modsLink"],"requireHttps":true}},"titleTemplate":"{title}","authorVar":"authors","publishedTimeVar":"dateIssued","bullets":[{"label":"Package ID","template":"`{packageId}`","whenVar":"packageId"},{"label":"Collection","template":"{collection}","whenVar":"collection"},{"label":"Category","template":"{category}","whenVar":"category"},{"label":"Date Issued","template":"{dateIssued}","whenVar":"dateIssued"},{"label":"Last Modified","template":"{lastModified}","whenVar":"lastModified"},{"label":"Government Author","template":"{authors}","whenVar":"authors"},{"label":"Granules","template":"{granuleCount}","whenVar":"granuleCount"},{"label":"PDF Download","template":"{pdfLink}","whenVar":"pdfLink"},{"label":"HTML Download","template":"{htmlLink}","whenVar":"htmlLink"},{"label":"XML Download","template":"{xmlLink}","whenVar":"xmlLink"},{"label":"Text Download","template":"{txtLink}","whenVar":"txtLink"},{"label":"ZIP Archive","template":"{zipLink}","whenVar":"zipLink"}],"linksVars":["pdfLink","htmlLink","xmlLink","txtLink","zipLink","modsLink"]}}]},{"id":"usajobs","name":"USAJOBS Federal Jobs","category":"jobs","description":"Extracts federal job search listings and codelists from data.usajobs.gov (with Authorization-Key + User-Agent) and JobPosting/HTML job details from www.usajobs.gov.","domains":["data.usajobs.gov","www.usajobs.gov","usajobs.gov"],"auth_mode":"key","user_agent_profile":"usajobs","strict_robots":true,"exampleUrls":["https://data.usajobs.gov/api/search?Keyword=software","https://www.usajobs.gov/job/893002300"],"routes":[{"match":{"hosts":["data.usajobs.gov"],"anyOf":[{"pathPrefix":"/api/search"},{"pathPrefix":"/api/codelist/"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304,"auth_mode":"key"},"extract":{"jsonMode":"usajobs_json"}}],"htmlRoutes":[{"id":"usajobs","mode":"usajobs_html","match":{"hosts":["www.usajobs.gov","usajobs.gov"],"exactSegments":false}}]},{"id":"usaspending","name":"USAspending.gov Federal Awards","category":"public-records","description":"Upgrades usaspending.gov/award/ pages to api.usaspending.gov/api/v2/awards// JSON details.","domains":["www.usaspending.gov","usaspending.gov"],"exampleUrls":["https://www.usaspending.gov/award/CONT_AWD_ZSMG_9700_HTC71114DR027_9700"],"match":{"exactSegments":false,"pathSegments":["award",{"param":"awardId","charset":"pkg","minLen":4,"maxLen":140}]},"twin":{"fetchUrl":"https://api.usaspending.gov/api/v2/awards/{awardId}/","kind":"json","accept":"application/json"},"extract":{"requireAnyFields":["generated_unique_award_id","piid","fain"],"vars":{"idLabel":{"paths":["piid","fain","uri"],"fallbackTemplate":"{awardId}"},"category":{"paths":["category"],"default":"Federal Award"},"recipient":{"paths":["recipient.recipient_name"]},"awardingAgency":{"paths":["awarding_agency.toptier_agency.name"]},"fundingAgency":{"paths":["funding_agency.toptier_agency.name"]},"obligation":{"paths":["total_obligation"],"format":"usd_compact"},"desc":{"paths":["description"],"trim":true},"descShort":{"paths":["description"],"trim":true,"sliceMax":260},"startDate":{"paths":["period_of_performance.start_date"]},"hasPop":{"paths":["period_of_performance.start_date","period_of_performance.end_date"]},"startOrQ":{"paths":["period_of_performance.start_date"],"default":"?"},"endOrQ":{"paths":["period_of_performance.end_date"],"default":"?"}},"titleTemplate":"{idLabel} — {recipient} (USAspending)","titleWhenVar":"recipient","titleFallbackTemplate":"{idLabel} (USAspending)","descriptionVar":"descShort","publishedTimeVar":"startDate","bullets":[{"label":"Award ID","template":"`{idLabel}` ({category})"},{"label":"Recipient","template":"{recipient}","whenVar":"recipient"},{"label":"Total Obligation","template":"{obligation}","whenVar":"obligation"},{"label":"Awarding Agency","template":"{awardingAgency}","whenVar":"awardingAgency"},{"label":"Funding Agency","template":"{fundingAgency}","whenVar":"fundingAgency"},{"label":"Period of Performance","template":"{startOrQ} → {endOrQ}","whenVar":"hasPop"}],"sections":[{"heading":"Award Description","textVar":"desc"}]}},{"id":"uscode-house","name":"U.S. Code (House OLRC)","category":"public-records","description":"HTML extractor for U.S. House Office of the Law Revision Counsel United States Code sections, title browse trees, and legacy /view.xhtml pages.","domains":["uscode.house.gov"],"auth_mode":"pub","exampleUrls":["https://uscode.house.gov/us/usc/t17/s107/","https://uscode.house.gov/browse.html","https://uscode.house.gov/us/usc/t17/frontmatter/"],"htmlRoutes":[{"id":"uscode-house","match":{"anyOf":[{"pathPrefix":"/us/usc/"},{"pathEquals":["/browse.html"]},{"pathPrefix":"/browse-tree/"},{"pathEquals":["/view.xhtml"]}]},"mode":"uscode_house_html"}]},{"id":"usda-nass-fdc","name":"USDA FoodData Central & NASS QuickStats","category":"research-health","description":"USDA FoodData Central REST API v1 (/fdc/v1/...) and NASS QuickStats (/api/api_GET/) adapter with Angular SPA shell guard.","domains":["quickstats.nass.usda.gov","fdc.nal.usda.gov","api.nal.usda.gov"],"auth_mode":"key","strict_robots":true,"exampleUrls":["https://api.nal.usda.gov/fdc/v1/food/171705","https://api.nal.usda.gov/fdc/v1/foods/search?query=avocado&pageSize=3","https://quickstats.nass.usda.gov/api/api_GET/?commodity_desc=CORN&year=2023&state_alpha=IA"],"routes":[{"match":{"hosts":["api.nal.usda.gov"],"exactSegments":true,"pathSegments":["fdc","v1","food",{"param":"fdcId","charset":"digits","minLen":1,"maxLen":16}]},"twin":{"fetchUrl":"https://api.nal.usda.gov/fdc/v1/food/{fdcId}","kind":"json","accept":"application/json","maxBytes":4194304,"auth_mode":"key"},"extract":{"jsonMode":"usda_fdc_json"}},{"match":{"hosts":["api.nal.usda.gov"],"exactSegments":false,"pathPrefix":"/fdc/v1/foods"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304,"auth_mode":"key"},"extract":{"jsonMode":"usda_fdc_json"}},{"match":{"hosts":["quickstats.nass.usda.gov"],"exactSegments":false,"pathEquals":["/api/api_GET","/api/api_GET/"]},"twin":{"fetchUrl":"{requestUrl}","defaultQueryParams":{"format":"JSON"},"kind":"json","accept":"application/json","maxBytes":4194304,"auth_mode":"key"},"extract":{"jsonMode":"usda_nass_json"}}],"htmlRoutes":[{"id":"usda-nass-fdc","match":{"hosts":["fdc.nal.usda.gov"],"exactSegments":false},"mode":"usda_fdc_html"}]},{"id":"usfs-blm-trails","name":"USFS & BLM Trails ArcGIS Services","category":"public-records","description":"US Forest Service (apps.fs.usda.gov) and BLM (gis.blm.gov) ArcGIS MapServer/FeatureServer layer metadata and /query feature adapter, scoped off *.arcgis.com.","domains":["apps.fs.usda.gov","gis.blm.gov"],"auth_mode":"pub","exampleUrls":["https://gis.blm.gov/arcgis/rest/services/recreation/BLM_Natl_Recreation_Offline/FeatureServer/0/query?where=1%3D1&outFields=*&resultRecordCount=1&f=json","https://gis.blm.gov/arcgis/rest/services/recreation/BLM_Natl_Recs_pts/MapServer/0?f=json","https://gis.blm.gov/arcgis/rest/services/transportation/BLM_Natl_GTLF_Public_Display/MapServer?f=json"],"routes":[{"match":{"anyOf":[{"hosts":["apps.fs.usda.gov"],"pathPrefix":"/arcx/rest/services/","pathSuffix":"/query"},{"hosts":["gis.blm.gov"],"pathPrefix":"/arcgis/rest/services/","pathSuffix":"/query"}]},"twin":{"fetchUrl":"{requestUrl}","setQueryParams":{"f":"json"},"defaultQueryParams":{"where":"1=1","outFields":"*","returnGeometry":"false","resultRecordCount":"25"},"kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"usfs_blm_trails_json"}},{"match":{"anyOf":[{"hosts":["apps.fs.usda.gov"],"pathPrefix":"/arcx/rest/services/","arcgisRestLayer":true},{"hosts":["gis.blm.gov"],"pathPrefix":"/arcgis/rest/services/","arcgisRestLayer":true}]},"twin":{"fetchUrl":"{requestUrl}","setQueryParams":{"f":"json"},"kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"usfs_blm_trails_json"}}]},{"id":"usgs-earthquakes","name":"USGS Earthquake Hazards Program","category":"research-health","description":"USGS GeoJSON earthquake summary feeds, FDSNWS Event Query API, and eventpage JSON twins.","domains":["earthquake.usgs.gov"],"auth_mode":"pub","exampleUrls":["https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/4.5_day.geojson","https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&limit=5&minmagnitude=4.5","https://earthquake.usgs.gov/earthquakes/eventpage/us6000ue1k/executive"],"routes":[{"match":{"hosts":["earthquake.usgs.gov"],"anyOf":[{"pathPrefix":"/earthquakes/feed/"},{"pathPrefix":"/fdsnws/event/"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"usgs_earthquakes_json"}},{"match":{"hosts":["earthquake.usgs.gov"],"exactSegments":false,"pathSegments":["earthquakes","eventpage",{"param":"eventId","charset":"alnum_dash","minLen":4,"maxLen":40}]},"twin":{"fetchUrl":"https://earthquake.usgs.gov/fdsnws/event/1/query?eventid={eventId}&format=geojson","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"usgs_earthquakes_json"}}]},{"id":"usgs-water","name":"USGS Water Services & OGC API","category":"research-health","description":"USGS NWIS Water Services (WaterML JSON and tab-delimited RDB) and api.waterdata.usgs.gov OGC API GeoJSON adapter.","domains":["waterservices.usgs.gov","api.waterdata.usgs.gov","waterdata.usgs.gov"],"auth_mode":"pub","exampleUrls":["https://api.waterdata.usgs.gov/ogcapi/v0/collections/monitoring-locations?f=json","https://api.waterdata.usgs.gov/ogcapi/v0/collections?f=json"],"routes":[{"match":{"hosts":["waterservices.usgs.gov"],"pathPrefix":"/nwis/","queryParams":[{"name":"format","param":"fmt","allowValues":["rdb","rdb,1.0"]}]},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"text/plain","maxBytes":2097152},"extract":{"textMode":"usgs_water_rdb"}},{"match":{"hosts":["waterservices.usgs.gov"],"pathPrefix":"/nwis/"},"twin":{"fetchUrl":"{requestUrl}","setQueryParams":{"format":"json"},"kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"usgs_water_json"}},{"match":{"hosts":["api.waterdata.usgs.gov"],"pathPrefix":"/ogcapi/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"usgs_water_json"}},{"match":{"hosts":["waterdata.usgs.gov"],"exactSegments":false,"pathSegments":["monitoring-location",{"param":"siteNo","charset":"digits","minLen":5,"maxLen":15}]},"twin":{"fetchUrl":"https://waterservices.usgs.gov/nwis/iv/?format=json&sites={siteNo}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"usgs_water_json"}}]},{"id":"uspto-patentsview","name":"USPTO PatentsView & Open Data Portal","category":"public-records","description":"USPTO Open Data Portal (api.uspto.gov) patent application and PatentsView API JSON adapter with HTML fallback.","domains":["patentsview.org","www.patentsview.org","search.patentsview.org","api.patentsview.org","api.uspto.gov","data.uspto.gov"],"auth_mode":"key","min_interval_ms":1000,"exampleUrls":["https://api.uspto.gov/api/v1/patent/applications/16330077","https://api.uspto.gov/api/v1/patent/applications/search?q=16330077"],"routes":[{"match":{"hosts":["api.uspto.gov"],"pathPrefix":"/api/v1/patent/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"key"},"extract":{"jsonMode":"uspto_patentsview_json"}},{"match":{"hosts":["api.patentsview.org"],"pathPrefix":"/api/v1/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"key"},"extract":{"jsonMode":"uspto_patentsview_json"}},{"match":{"hosts":["patentsview.org","www.patentsview.org","search.patentsview.org","data.uspto.gov"],"exactSegments":false,"pathSegments":["patent",{"param":"patentId","charset":"alnum_dash","minLen":5,"maxLen":24}]},"twin":{"fetchUrl":"https://api.uspto.gov/api/v1/patent/applications/search?q={patentId}","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"key"},"extract":{"jsonMode":"uspto_patentsview_json"}},{"match":{"hosts":["patentsview.org","www.patentsview.org","search.patentsview.org","data.uspto.gov"],"exactSegments":false,"pathSegments":["patents",{"param":"patentId","charset":"alnum_dash","minLen":5,"maxLen":24}]},"twin":{"fetchUrl":"https://api.uspto.gov/api/v1/patent/applications/search?q={patentId}","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"key"},"extract":{"jsonMode":"uspto_patentsview_json"}}],"htmlRoutes":[{"id":"uspto-patentsview","match":{"hosts":["patentsview.org","www.patentsview.org","search.patentsview.org","data.uspto.gov"],"exactSegments":false},"mode":"uspto_patentsview_html"}]},{"id":"uspto-ppubs","name":"USPTO Patent Public Search (PPUBS)","category":"public-records","description":"USPTO Patent Public Search (ppubs.uspto.gov) HTML adapter rejecting empty SPA shells.","domains":["ppubs.uspto.gov","patft.uspto.gov"],"auth_mode":"html","min_interval_ms":1000,"exampleUrls":["https://ppubs.uspto.gov/basic/"],"htmlRoutes":[{"id":"uspto-ppubs","match":{"hosts":["ppubs.uspto.gov","patft.uspto.gov"],"exactSegments":false},"mode":"uspto_ppubs_html"}]},{"id":"uspto-tsdr","name":"USPTO TSDR Trademark Status","category":"public-records","description":"USPTO Trademark Status & Document Retrieval (TSDR) API JSON adapter with keyless tsdr.uspto.gov/statusview HTML fallback.","domains":["tsdr.uspto.gov","tsdrapi.uspto.gov"],"auth_mode":"key","min_interval_ms":1000,"exampleUrls":["https://tsdrapi.uspto.gov/ts/cd/casestatus/sn78787878/info.json","https://tsdr.uspto.gov/statusview/sn78787878"],"routes":[{"match":{"hosts":["tsdrapi.uspto.gov"],"pathPrefix":"/ts/cd/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"key"},"extract":{"jsonMode":"uspto_tsdr_json"}},{"match":{"hosts":["tsdr.uspto.gov"],"exactSegments":false,"pathSegments":["statusview",{"param":"caseNum","charset":"alnum","minLen":6,"maxLen":20}]},"twin":{"fetchUrl":"https://tsdrapi.uspto.gov/ts/cd/casestatus/{caseNum}/info.json","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"key"},"extract":{"jsonMode":"uspto_tsdr_json"}}],"htmlRoutes":[{"id":"uspto-tsdr","match":{"hosts":["tsdr.uspto.gov"],"exactSegments":false},"mode":"uspto_tsdr_html"}]},{"id":"vanilla-forums","name":"Vanilla Forums","category":"commerce-social","description":"Upgrades Vanilla Forums /discussion/{discussionID} URLs to same-origin /api/v2/discussions/{discussionID} JSON twins with HTML fallback.","domains":["forum.onshape.com","forum.polkaudio.com","forum.linuxfoundation.org"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://forum.onshape.com/discussion/32195/new-feature-codes","https://forum.onshape.com/api/v2/discussions/32195","https://forum.polkaudio.com/api/v2/discussions/163343"],"routes":[{"match":{"exactSegments":false,"pathSegments":["discussion",{"param":"discussionID","charset":"digits","minLen":1,"maxLen":16},{"param":"slug","charset":"safe_subpath","optional":true,"greedy":true}]},"twin":{"fetchUrl":"https://{host}/api/v2/discussions/{discussionID}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"vanilla_forums"}},{"match":{"exactSegments":true,"pathSegments":["api","v2","discussions"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"vanilla_forums"}},{"match":{"exactSegments":true,"pathSegments":["api","v2","discussions",{"param":"discussionID","charset":"digits","minLen":1,"maxLen":16}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"vanilla_forums"}}],"htmlRoutes":[{"id":"vanilla-forums","match":{"exactSegments":false},"mode":"vanilla_forums_html"}]},{"id":"vimeo","name":"Vimeo Video & oEmbed","category":"commerce-social","description":"Extracts Vimeo video and player embed metadata via Vimeo oEmbed JSON and VideoObject HTML fallback.","domains":["vimeo.com","www.vimeo.com","player.vimeo.com"],"auth_mode":"pub","exampleUrls":["https://vimeo.com/76979871","https://vimeo.com/api/oembed.json?url=https%3A%2F%2Fvimeo.com%2F76979871","https://player.vimeo.com/video/76979871"],"routes":[{"match":{"hosts":["vimeo.com","www.vimeo.com"],"pathEquals":["/api/oembed.json"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"vimeo_oembed_json"}},{"match":{"hosts":["vimeo.com","www.vimeo.com"],"exactSegments":true,"pathSegments":[{"param":"videoId","charset":"digits","minLen":4,"maxLen":15}]},"twin":{"fetchUrl":"https://vimeo.com/api/oembed.json?url=https%3A%2F%2Fvimeo.com%2F{videoId}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"vimeo_oembed_json"}},{"match":{"hosts":["player.vimeo.com"],"exactSegments":true,"pathSegments":["video",{"param":"videoId","charset":"digits","minLen":4,"maxLen":15}]},"twin":{"fetchUrl":"https://vimeo.com/api/oembed.json?url=https%3A%2F%2Fvimeo.com%2F{videoId}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"vimeo_oembed_json"}}],"htmlRoutes":[{"id":"vimeo","match":{"exactSegments":false},"mode":"vimeo_html"}]},{"id":"vtex","name":"VTEX Storefronts & Catalog API","category":"commerce-social","description":"Extracts VTEX storefront product JSON from /api/catalog_system/pub/products/search and /variations endpoints, plus post-HTML storefront JSON-LD and companion discovery.","domains":["www.motorola.com.br"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://www.motorola.com.br/api/catalog_system/pub/products/search?fq=productId:488"],"routes":[{"match":{"pathEquals":["/api/catalog_system/pub/products/search"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"commerceMode":"vtex_product"}},{"match":{"pathPrefix":"/api/catalog_system/pub/products/search/","pathSuffix":"/p"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"commerceMode":"vtex_product"}},{"match":{"pathSegments":["api","catalog_system","pub","products","variations",{"param":"productId","charset":"pkg","minLen":1,"maxLen":64}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"commerceMode":"vtex_product"}}],"htmlRoutes":[{"id":"vtex","match":{"exactSegments":false},"mode":"vtex_html"}]},{"id":"walmart","name":"Walmart Official Affiliate/IO API","category":"commerce-social","description":"Official Walmart Affiliate/IO API product lookup only (zero HTML scraping of walmart.com).","domains":["walmart.com","www.walmart.com","developer.api.walmart.com"],"auth_mode":"key","exampleUrls":["https://www.walmart.com/ip/132000132","https://developer.api.walmart.com/api-proxy/service/affil/product/v2/items/132000132"],"routes":[{"match":{"hosts":["walmart.com","www.walmart.com"],"anyOf":[{"exactSegments":true,"pathSegments":["ip",{"param":"itemId","charset":"digits","minLen":4,"maxLen":16}]},{"exactSegments":false,"pathSegments":["ip",{"param":"slug","charset":"url_seg","maxLen":200},{"param":"itemId","charset":"digits","minLen":4,"maxLen":16}]}]},"twin":{"fetchUrl":"https://developer.api.walmart.com/api-proxy/service/affil/product/v2/items/{itemId}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"walmart_json"}},{"match":{"hosts":["developer.api.walmart.com"],"pathPrefix":"/api-proxy/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"walmart_json"}}]},{"id":"weather-gov","name":"National Weather Service (weather.gov)","category":"research-health","description":"NOAA National Weather Service GeoJSON API (points, gridpoint forecasts, active alerts, observations) and forecast.weather.gov HTML extractor with identifying User-Agent.","domains":["weather.gov","www.weather.gov","api.weather.gov","forecast.weather.gov"],"auth_mode":"pub","user_agent_profile":"weather-gov","strict_robots":true,"exampleUrls":["https://forecast.weather.gov/MapClick.php?lat=39.7456&lon=-97.0892","https://forecast.weather.gov/MapClick.php?lat=40.7128&lon=-74.0060"],"routes":[{"match":{"hosts":["api.weather.gov"],"anyOf":[{"pathPrefix":"/points/"},{"pathPrefix":"/gridpoints/"},{"pathPrefix":"/alerts"},{"pathPrefix":"/stations/"},{"pathPrefix":"/zones/"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/geo+json","maxBytes":2097152},"extract":{"jsonMode":"weather_gov_json"}}],"htmlRoutes":[{"id":"weather-gov","match":{"hosts":["weather.gov","www.weather.gov","forecast.weather.gov"],"exactSegments":false},"mode":"weather_gov_html"}]},{"id":"wikidata-openlibrary","name":"Wikidata & Open Library","category":"research-health","description":"Upgrades wikidata.org/wiki/Q* to Special:EntityData/Q*.json (handling labels.en, labels.mul, and sitelinks.enwiki fallbacks) and openlibrary.org/isbn/* to /isbn/*.json (never calling disallowed /api/*).","domains":["www.wikidata.org","wikidata.org","openlibrary.org","www.openlibrary.org"],"exampleUrls":["https://www.wikidata.org/wiki/Q42","https://openlibrary.org/isbn/9780140328721"],"routes":[{"match":{"hosts":["www.wikidata.org","wikidata.org"],"exactSegments":true,"pathPrefix":"/wiki/Q","pathSegments":["wiki",{"param":"qidNum","stripPrefix":"Q","charset":"digits","minLen":1,"maxLen":15}]},"twin":{"fetchUrl":"https://www.wikidata.org/wiki/Special:EntityData/Q{qidNum}.json","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"requireAnyFields":["entities"],"vars":{"qid":{"template":"Q{qidNum}"},"labelEn":{"dynamicKeyPath":{"base":"entities","keyVar":"qid","subPath":"labels.en.value"},"trim":true},"labelMul":{"dynamicKeyPath":{"base":"entities","keyVar":"qid","subPath":"labels.mul.value"},"trim":true},"labelEnwiki":{"dynamicKeyPath":{"base":"entities","keyVar":"qid","subPath":"sitelinks.enwiki.title"},"trim":true},"labelMulOrEnwiki":{"template":"{labelMul}","whenVars":["labelMul"],"fallbackVar":"labelEnwiki"},"label":{"template":"{labelEn}","whenVars":["labelEn"],"fallbackVar":"labelMulOrEnwiki"},"descEn":{"dynamicKeyPath":{"base":"entities","keyVar":"qid","subPath":"descriptions.en.value"},"trim":true},"descMul":{"dynamicKeyPath":{"base":"entities","keyVar":"qid","subPath":"descriptions.mul.value"},"trim":true},"desc":{"template":"{descEn}","whenVars":["descEn"],"fallbackVar":"descMul"},"aliasesEn":{"dynamicKeyPath":{"base":"entities","keyVar":"qid","subPath":"aliases.en"},"subField":"value","join":", ","limit":10},"aliasesMul":{"dynamicKeyPath":{"base":"entities","keyVar":"qid","subPath":"aliases.mul"},"subField":"value","join":", ","limit":10},"aliases":{"template":"{aliasesEn}","whenVars":["aliasesEn"],"fallbackVar":"aliasesMul"},"modified":{"dynamicKeyPath":{"base":"entities","keyVar":"qid","subPath":"modified"},"sliceMax":10},"claimProps":{"dynamicKeyPath":{"base":"entities","keyVar":"qid","subPath":"claims"},"format":"object_keys","limit":25,"itemWrap":"`","join":", "},"instanceOf":{"dynamicKeyPath":{"base":"entities","keyVar":"qid","subPath":"claims.P31"},"subField":"mainsnak.datavalue.value.id","itemWrap":"`","join":", ","limit":8},"sexOrGender":{"dynamicKeyPath":{"base":"entities","keyVar":"qid","subPath":"claims.P21"},"subField":"mainsnak.datavalue.value.id","itemWrap":"`","join":", ","limit":3},"citizenship":{"dynamicKeyPath":{"base":"entities","keyVar":"qid","subPath":"claims.P27"},"subField":"mainsnak.datavalue.value.id","itemWrap":"`","join":", ","limit":5},"occupation":{"dynamicKeyPath":{"base":"entities","keyVar":"qid","subPath":"claims.P106"},"subField":"mainsnak.datavalue.value.id","itemWrap":"`","join":", ","limit":8},"birthDate":{"dynamicKeyPath":{"base":"entities","keyVar":"qid","subPath":"claims.P569"},"preferWhere":{"path":"rank","equals":"preferred","fallbackEquals":"normal"},"subField":"mainsnak.datavalue.value.time","stripPrefix":"+","stripSuffix":"T00:00:00Z","replaceAll":{"from":"-00","to":""},"sliceMax":10},"deathDate":{"dynamicKeyPath":{"base":"entities","keyVar":"qid","subPath":"claims.P570"},"preferWhere":{"path":"rank","equals":"preferred","fallbackEquals":"normal"},"subField":"mainsnak.datavalue.value.time","stripPrefix":"+","stripSuffix":"T00:00:00Z","replaceAll":{"from":"-00","to":""},"sliceMax":10},"inception":{"dynamicKeyPath":{"base":"entities","keyVar":"qid","subPath":"claims.P571"},"preferWhere":{"path":"rank","equals":"preferred","fallbackEquals":"normal"},"subField":"mainsnak.datavalue.value.time","stripPrefix":"+","stripSuffix":"T00:00:00Z","replaceAll":{"from":"-00","to":""},"sliceMax":10},"population":{"dynamicKeyPath":{"base":"entities","keyVar":"qid","subPath":"claims.P1082"},"preferWhere":{"path":"rank","equals":"preferred","fallbackEquals":"normal","fallbackLast":true},"subField":"mainsnak.datavalue.value.amount","format":"int_comma"},"officialWebsite":{"dynamicKeyPath":{"base":"entities","keyVar":"qid","subPath":"claims.P856.0.mainsnak.datavalue.value"},"trim":true,"requireHttpPrefix":true},"enwikiSlug":{"dynamicKeyPath":{"base":"entities","keyVar":"qid","subPath":"sitelinks.enwiki.title"},"replaceAll":{"from":" ","to":"_"}},"enwikiUrl":{"template":"https://en.wikipedia.org/wiki/{enwikiSlug}","whenVars":["enwikiSlug"],"requireHttps":true},"wikidataUrl":{"template":"https://www.wikidata.org/wiki/{qid}","requireHttps":true}},"requireVars":["label"],"titleTemplate":"{label} ({qid})","descriptionVar":"desc","publishedTimeVar":"modified","introVar":"desc","bullets":[{"label":"Wikidata ID","template":"`{qid}`"},{"label":"Also Known As","template":"{aliases}","whenVar":"aliases"},{"label":"Modified","template":"{modified}","whenVar":"modified"},{"label":"Instance Of","template":"{instanceOf}","whenVar":"instanceOf"},{"label":"Sex or Gender","template":"{sexOrGender}","whenVar":"sexOrGender"},{"label":"Country of Citizenship","template":"{citizenship}","whenVar":"citizenship"},{"label":"Occupation","template":"{occupation}","whenVar":"occupation"},{"label":"Date of Birth","template":"{birthDate}","whenVar":"birthDate"},{"label":"Date of Death","template":"{deathDate}","whenVar":"deathDate"},{"label":"Inception","template":"{inception}","whenVar":"inception"},{"label":"Population","template":"{population}","whenVar":"population"},{"label":"Official Website","template":"{officialWebsite}","whenVar":"officialWebsite"},{"label":"Claim Properties","template":"{claimProps}","whenVar":"claimProps"},{"label":"English Wikipedia","template":"{enwikiUrl}","whenVar":"enwikiUrl"},{"label":"Wikidata URL","template":"{wikidataUrl}","whenVar":"wikidataUrl"}],"linksVars":["wikidataUrl","enwikiUrl","officialWebsite"]}},{"match":{"hosts":["openlibrary.org","www.openlibrary.org"],"exactSegments":true,"pathSegments":["isbn",{"param":"isbn","stripSuffix":".json","charset":"alnum_dash","minLen":10,"maxLen":17}]},"twin":{"fetchUrl":"https://openlibrary.org/isbn/{isbn}.json","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"requireFields":["title"],"vars":{"title":{"paths":["title"],"trim":true},"subtitle":{"paths":["subtitle"],"trim":true},"isbn13":{"paths":["isbn_13"],"itemWrap":"`","join":", "},"isbn10":{"paths":["isbn_10"],"itemWrap":"`","join":", "},"publishers":{"paths":["publishers"],"join":", ","limit":8},"publishDate":{"paths":["publish_date"],"trim":true},"pages":{"paths":["number_of_pages"],"format":"int_comma"},"contributions":{"paths":["contributions"],"join":", ","limit":8},"byStatement":{"paths":["by_statement"],"trim":true,"sliceMax":200},"authorLine":{"template":"{byStatement}","whenVars":["byStatement"],"fallbackVar":"contributions"},"authors":{"paths":["authors"],"subField":"key","join":", ","limit":8},"works":{"paths":["works"],"subField":"key","join":", ","limit":5},"olKey":{"paths":["key"]},"olUrl":{"template":"https://openlibrary.org{olKey}","whenVars":["olKey"],"requireHttps":true},"desc":{"paths":["description.value","description","first_sentence.value","first_sentence"],"trim":true},"descShort":{"paths":["description.value","description","first_sentence.value","first_sentence"],"trim":true,"sliceMax":260}},"titleTemplate":"{title}","descriptionVar":"descShort","authorVar":"authorLine","publishedTimeVar":"publishDate","bullets":[{"label":"Subtitle","template":"{subtitle}","whenVar":"subtitle"},{"label":"ISBN-13","template":"{isbn13}","whenVar":"isbn13"},{"label":"ISBN-10","template":"{isbn10}","whenVar":"isbn10"},{"label":"Publishers","template":"{publishers}","whenVar":"publishers"},{"label":"Published","template":"{publishDate}","whenVar":"publishDate"},{"label":"Pages","template":"{pages}","whenVar":"pages"},{"label":"By","template":"{byStatement}","whenVar":"byStatement"},{"label":"Contributors","template":"{contributions}","whenVar":"contributions"},{"label":"Author Keys","template":"{authors}","whenVar":"authors"},{"label":"Work Keys","template":"{works}","whenVar":"works"},{"label":"Open Library URL","template":"{olUrl}","whenVar":"olUrl"}],"sections":[{"heading":"Description","textVar":"desc"}],"linksVars":["olUrl"]}}]},{"id":"wistia","name":"Wistia Video Hosting","category":"commerce-social","description":"Extracts Wistia /embed/medias/{mediaId}.json twins and Wistia video HTML while respecting robots.txt /oembed disallow and rejecting login walls.","domains":["fast.wistia.com","fast.wistia.net","home.wistia.com","wistia.com","www.wistia.com"],"auth_mode":"pub","exampleUrls":["https://fast.wistia.com/embed/medias/29b0fbf547.json","https://fast.wistia.com/embed/iframe/29b0fbf547","https://wistia.com/blog/video-marketing-statistics"],"routes":[{"match":{"hosts":["fast.wistia.com","fast.wistia.net"],"exactSegments":true,"pathSuffix":".json","pathSegments":["embed","medias",{"param":"mediaId","charset":"alnum","stripSuffix":".json","minLen":6,"maxLen":20}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"wistia_media_json"}},{"match":{"hosts":["fast.wistia.com","fast.wistia.net"],"exactSegments":true,"pathSegments":["embed","iframe",{"param":"mediaId","charset":"alnum","minLen":6,"maxLen":20}]},"twin":{"fetchUrl":"https://{host}/embed/medias/{mediaId}.json","kind":"json","accept":"application/json"},"extract":{"jsonMode":"wistia_media_json"}}],"htmlRoutes":[{"id":"wistia","match":{"exactSegments":false},"mode":"wistia_html"}]},{"id":"wix-stores","name":"Wix Stores","category":"commerce-social","description":"Extracts Wix Stores product details, pricing, stock, options, and media from wix-warmup-data hydration and JSON-LD/Microdata.","domains":["www.vivietmargot.com"],"universalEngine":true,"auth_mode":"html","exampleUrls":["https://www.vivietmargot.com/product-page/bon-appetit-linen-napkin-lin-bleu"],"htmlRoutes":[{"id":"wix-stores","match":{"exactSegments":false},"mode":"wix_stores_html"}]},{"id":"woocommerce","name":"WooCommerce Store API & Storefronts","category":"commerce-social","description":"Formats public WooCommerce Store API (/wp-json/wc/store/v1/products) feeds, extracts WooCommerce product pages, and implements polite full-store catalog pulls.","domains":["woocommerce.com"],"universalEngine":true,"exampleUrls":["https://yithemes.com/wp-json/wc/store/v1/products?per_page=20&page=1"],"catalog":{"platform":"woocommerce","pauseMs":2000,"pageCap":200,"firstPageTemplate":"{origin}/wp-json/wc/store/v1/products?per_page=100&page=1","perPage":100,"maxVariantsPerProduct":250,"maxImagesPerProduct":250},"routes":[{"match":{"exactSegments":true,"pathSegments":["wp-json","wc","store","v1","products"]},"twin":{"id":"woocommerce-catalog-page","fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"commerceMode":"woocommerce_catalog_page"}},{"match":{"exactSegments":true,"pathSegments":["wp-json","wc","store","v1","products",{"param":"pid","charset":"digits"}]},"twin":{"id":"woocommerce-product","fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"commerceMode":"woocommerce_product"}}],"htmlRoutes":[{"id":"woocommerce","match":{"exactSegments":false},"mode":"woocommerce_html"}]},{"id":"wordpress-vip-newspack","name":"WordPress VIP & Newspack","category":"commerce-social","description":"Extracts WP REST v2 posts/pages JSON twins and Newspack/WP-VIP article HTML without colliding with WooCommerce or standard WordPress blogs.","domains":["calmatters.org","missionlocal.org","www.berkeleyside.org"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://calmatters.org/wp-json/wp/v2/posts/516249","https://calmatters.org/commentary/2026/11/californias-philanthropic-funders-give-bravely/"],"routes":[{"match":{"exactSegments":true,"pathSegments":["wp-json","wp","v2","posts"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"wp_vip_posts_json"}},{"match":{"exactSegments":true,"pathSegments":["wp-json","wp","v2","posts",{"param":"postId","charset":"digits","minLen":1,"maxLen":16}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"wp_vip_posts_json"}},{"match":{"exactSegments":true,"pathSegments":["wp-json","wp","v2","pages",{"param":"pageId","charset":"digits","minLen":1,"maxLen":16}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"wp_vip_posts_json"}}],"htmlRoutes":[{"id":"wordpress-vip-newspack","match":{"exactSegments":false},"mode":"wp_vip_newspack_html"}]},{"id":"workable","name":"Workable Job Boards & Postings","category":"jobs","description":"Upgrades apply.workable.com boards to /api/v1/widget/accounts/?details=true (merging multi-location rows on shortcode) and single jobs to /api/v2/accounts//jobs/.","domains":["apply.workable.com"],"exampleUrls":["https://apply.workable.com/huggingface/","https://apply.workable.com/huggingface/j/81B46579FE/"],"routes":[{"match":{"exactSegments":false,"pathSegments":[{"param":"org","charset":"slug","maxLen":80,"reserved":["api","j","assets","static","favicon.ico","robots.txt"]},"j",{"param":"code","charset":"slug","minLen":4,"maxLen":24}]},"twin":{"id":"workable-job","fetchUrl":"https://apply.workable.com/api/v2/accounts/{org}/jobs/{code}","kind":"json","accept":"application/json"},"extract":{"requireFields":["title"],"vars":{"jobTitle":{"paths":["title"],"trim":true},"city":{"paths":["location.city"],"trim":true},"region":{"paths":["location.region"],"trim":true},"country":{"paths":["location.country"],"trim":true},"loc3":{"template":"{city}, {region}, {country}","whenVars":["city","region","country"]},"loc2a":{"template":"{city}, {region}","whenVars":["city","region"]},"loc2b":{"template":"{city}, {country}","whenVars":["city","country"]},"loc2c":{"template":"{region}, {country}","whenVars":["region","country"]},"loc1":{"paths":["location.city","location.region","location.country"],"trim":true},"locSub1":{"template":"{loc3}","whenVars":["loc3"],"fallbackVar":"loc2a"},"locSub2":{"template":"{locSub1}","whenVars":["locSub1"],"fallbackVar":"loc2b"},"locSub3":{"template":"{locSub2}","whenVars":["locSub2"],"fallbackVar":"loc2c"},"locStr":{"template":"{locSub3}","whenVars":["locSub3"],"fallbackVar":"loc1"},"teleRemote":{"paths":["location.telecommuting"],"format":"bool_map","trueValue":"remote","falseValue":""},"workplace":{"paths":["workplace"],"trim":true,"fallbackTemplate":"{teleRemote}"},"dept":{"paths":["department"],"join":", ","trim":true},"empType":{"paths":["type"],"trim":true},"published":{"paths":["published"],"sliceMax":10,"trim":true},"salCur":{"paths":["salary.salary_currency"],"upper":true,"trim":true,"default":"USD"},"salFrom":{"paths":["salary.salary_from"],"excludeEquals":"0"},"salTo":{"paths":["salary.salary_to"],"excludeEquals":"0"},"salRange":{"template":"{salCur} {salFrom} – {salTo}","whenVars":["salFrom","salTo"]},"salFromOnly":{"template":"{salCur} {salFrom}","whenVars":["salFrom"]},"salToOnly":{"template":"{salCur} – {salTo}","whenVars":["salTo"]},"salSub":{"template":"{salCur} {salFrom} – {salTo}","whenVars":["salFrom","salTo"],"fallbackVar":"salFromOnly"},"salStr":{"template":"{salSub}","whenVars":["salSub"],"fallbackVar":"salToOnly"},"desc":{"paths":["description"],"format":"html_to_md"},"reqs":{"paths":["requirements"],"format":"html_to_md"},"benefits":{"paths":["benefits"],"format":"html_to_md"}},"titleTemplate":"{jobTitle} @ {org}","publishedTimeVar":"published","bullets":[{"label":"Company","template":"{org}"},{"label":"Location","template":"{locStr}","whenVar":"locStr"},{"label":"Workplace","template":"{workplace}","whenVar":"workplace"},{"label":"Department","template":"{dept}","whenVar":"dept"},{"label":"Type","template":"{empType}","whenVar":"empType"},{"label":"Salary","template":"{salStr}","whenVar":"salStr"},{"label":"Published","template":"{published}","whenVar":"published"}],"sections":[{"heading":"Description","textVar":"desc"},{"heading":"Requirements","textVar":"reqs"},{"heading":"Benefits","textVar":"benefits"}],"linkTemplates":["https://apply.workable.com/{org}/j/{code}/apply/"]}},{"match":{"pathSegments":[{"param":"org","charset":"slug","maxLen":80,"reserved":["api","j","assets","static","favicon.ico","robots.txt"]}]},"twin":{"id":"workable-board","fetchUrl":"https://apply.workable.com/api/v1/widget/accounts/{org}?details=true","kind":"json","accept":"application/json"},"extract":{"vars":{"rawCount":{"paths":["jobs"],"format":"array_len"},"dedupCount":{"default":"{dedupCount}"},"orgName":{"paths":["name"],"trim":true,"fallbackTemplate":"{org}"}},"requireVars":["rawCount"],"titleTemplate":"{orgName} — Open Roles ({dedupCount})","sections":[{"heading":"","arrayPath":"jobs","limit":100,"linkScanLimit":2000,"emptyText":"No open positions are currently listed on this Workable board.","filter":{"requireField":"title"},"dedupeBy":{"keyPaths":["shortcode"],"mergeTextPaths":["city+state+country"],"mergeTargetVar":"_mergedLocs","mergeSep":"; ","mergeLimit":4,"orBoolPaths":["telecommuting","workplace_type"],"orBoolTargetField":"_isRemote"},"itemVars":{"code":{"paths":["shortcode"],"trim":true},"jTitle":{"paths":["title"],"trim":true},"rawUrl":{"paths":["url"],"requireHttps":true},"jUrl":{"template":"{rawUrl}","whenVars":["rawUrl"],"fallbackTemplate":"https://apply.workable.com/{org}/j/{code}/"},"dept":{"paths":["department"],"trim":true,"default":"-"},"remoteLocFallback":{"paths":["_isRemote"],"format":"bool_map","trueValue":"Remote","falseValue":"-"},"locs":{"paths":["_mergedLocs"],"trim":true,"fallbackTemplate":"{remoteLocFallback}"},"workplace":{"paths":["_isRemote"],"format":"bool_map","trueValue":"Remote","falseValue":"On-site / Hybrid"},"published":{"paths":["published_on"],"sliceMax":10,"trim":true,"default":"-"}},"collectLinkVars":["jUrl"],"columns":[{"header":"Role","template":"[{jTitle}]({jUrl})"},{"header":"Department","template":"{dept}"},{"header":"Locations","template":"{locs}"},{"header":"Workplace","template":"{workplace}"},{"header":"Published","template":"{published}"}]}]}}]},{"id":"xenforo-thread","name":"XenForo 2 Forum Threads","category":"commerce-social","description":"Extracts structured forum posts, authors, timestamps, and clean quote blocks from XenForo 2 thread HTML (article.message--post) while stripping signatures and sidebar chrome.","domains":["forums.electricbikereview.com","mtbr.com","www.mtbr.com","endless-sphere.com"],"universalEngine":true,"exampleUrls":["https://forums.electricbikereview.com/threads/where-we-are-in-2026.59397/","https://www.mtbr.com/threads/ozark-trail-fs-2-slalom-for-a-kid.1249288/","https://endless-sphere.com/sphere/threads/es-2-0-forum-updates-and-tribulations.119104/"],"htmlRoutes":[{"id":"xenforo-thread","match":{"pathContainsSegment":"threads"},"mode":"xenforo_html"}]},{"id":"ycombinator","name":"Y Combinator Directory & Work at a Startup","category":"finance","description":"Extracts YC company profiles, founders, batches, and open roles from ycombinator.com/companies/ (and upgrades login-gated workatastartup.com company pages to their public YC mirror).","domains":["www.ycombinator.com","ycombinator.com","www.workatastartup.com","workatastartup.com"],"exampleUrls":["https://www.ycombinator.com/companies/supabase","https://www.workatastartup.com/companies/supabase"],"routes":[{"match":{"hosts":["www.workatastartup.com","workatastartup.com"],"exactSegments":false,"pathSegments":["companies",{"param":"slug","charset":"alnum_dash","minLen":1,"maxLen":80}]},"twin":{"id":"workatastartup-yc-mirror","fetchUrl":"https://www.ycombinator.com/companies/{slug}/jobs","kind":"text","accept":"text/html"},"extract":{"jsonSource":"inertia_data_page","rootPath":"props","requireFields":["company.name"],"vars":{"name":{"paths":["company.name"],"trim":true},"oneLiner":{"paths":["company.one_liner"],"trim":true},"longDesc":{"paths":["company.long_description"],"trim":true},"batch":{"paths":["company.batch_name","company.batch"]},"status":{"paths":["company.ycdc_status","company.status"]},"teamSize":{"paths":["company.team_size"]},"location":{"paths":["company.location","company.city"]},"website":{"paths":["company.website"]},"websiteHttps":{"paths":["company.website"],"requireHttps":true},"yearFounded":{"paths":["company.year_founded"]},"tags":{"paths":["company.tags"],"join":", "},"hasRootJobsArr":{"paths":["jobPostings"],"format":"array_len"}},"titleTemplate":"{name} (YC {batch})","titleWhenVar":"batch","titleFallbackTemplate":"{name} (Y Combinator)","descriptionVar":"oneLiner","blockquoteTemplate":"> {oneLiner}","blockquoteWhenVar":"oneLiner","bullets":[{"label":"YC Batch","template":"{batch}","whenVar":"batch"},{"label":"Status","template":"{status}","whenVar":"status"},{"label":"Founded","template":"{yearFounded}","whenVar":"yearFounded"},{"label":"Team Size","template":"{teamSize}","whenVar":"teamSize"},{"label":"Location","template":"{location}","whenVar":"location"},{"label":"Website","template":"{website}","whenVar":"website"},{"label":"Tags","template":"{tags}","whenVar":"tags"}],"sections":[{"heading":"About","headingTemplate":"About {name}","textVar":"longDesc"},{"heading":"Founders","listArrayPath":"company.founders","requireItemVar":"fName","collectLinkVars":["linkedin"],"itemVars":{"fName":{"paths":["full_name"],"trim":true},"fTitle":{"paths":["title"],"trim":true,"default":"Founder"},"fBio":{"paths":["founder_bio"],"format":"strip_tags"},"fBioSuffix":{"template":" — {fBio}","whenVars":["fBio"]},"linkedin":{"paths":["linkedin_url"],"requireHttps":true},"fLabel":{"template":"[{fName}]({linkedin})","whenVars":["fName","linkedin"],"fallbackVar":"fName"}},"itemTemplate":"**{fLabel}** ({fTitle}){fBioSuffix}"},{"heading":"Open Roles","headingTemplate":"Open Roles ({count})","arrayPath":"jobPostings","limit":30,"requireItemVar":"jTitle","collectLinkVars":["jUrl"],"itemVars":{"jTitle":{"paths":["title"],"trim":true},"urlHttp":{"paths":["url"],"requireHttpPrefix":true},"urlRelPart":{"paths":["url"],"stripPrefix":"/"},"urlFromRel":{"template":"https://www.ycombinator.com/{urlRelPart}","whenVars":["urlRelPart"]},"urlDefault":{"template":"https://www.ycombinator.com/companies/{slug}/jobs"},"urlRelOrDefault":{"template":"{urlFromRel}","whenVars":["urlFromRel"],"fallbackVar":"urlDefault"},"jUrl":{"template":"{urlHttp}","whenVars":["urlHttp"],"fallbackVar":"urlRelOrDefault"}},"columns":[{"header":"Role","template":"[{jTitle}]({jUrl})"},{"header":"Location","paths":["location","pretty_location"]},{"header":"Salary","paths":["salary_range","pretty_salary_range"]},{"header":"Type","paths":["role","type"]}]},{"heading":"Open Roles","headingTemplate":"Open Roles ({count})","unlessVar":"hasRootJobsArr","arrayPath":"company.jobPostings","limit":30,"requireItemVar":"jTitle","collectLinkVars":["jUrl"],"itemVars":{"jTitle":{"paths":["title"],"trim":true},"urlHttp":{"paths":["url"],"requireHttpPrefix":true},"urlRelPart":{"paths":["url"],"stripPrefix":"/"},"urlFromRel":{"template":"https://www.ycombinator.com/{urlRelPart}","whenVars":["urlRelPart"]},"urlDefault":{"template":"https://www.ycombinator.com/companies/{slug}/jobs"},"urlRelOrDefault":{"template":"{urlFromRel}","whenVars":["urlFromRel"],"fallbackVar":"urlDefault"},"jUrl":{"template":"{urlHttp}","whenVars":["urlHttp"],"fallbackVar":"urlRelOrDefault"}},"columns":[{"header":"Role","template":"[{jTitle}]({jUrl})"},{"header":"Location","paths":["location","pretty_location"]},{"header":"Salary","paths":["salary_range","pretty_salary_range"]},{"header":"Type","paths":["role","type"]}]}],"linksVars":["websiteHttps"]}}],"htmlRoutes":[{"match":{"hosts":["www.ycombinator.com","ycombinator.com"],"exactSegments":false,"pathSegments":["companies",{"param":"slug","charset":"alnum_dash","minLen":1,"maxLen":80}]},"mode":"embedded_json","dataAttr":"data-page","extract":{"jsonSource":"inertia_data_page","rootPath":"props","requireFields":["company.name"],"vars":{"name":{"paths":["company.name"],"trim":true},"oneLiner":{"paths":["company.one_liner"],"trim":true},"longDesc":{"paths":["company.long_description"],"trim":true},"batch":{"paths":["company.batch_name","company.batch"]},"status":{"paths":["company.ycdc_status","company.status"]},"teamSize":{"paths":["company.team_size"]},"location":{"paths":["company.location","company.city"]},"website":{"paths":["company.website"]},"websiteHttps":{"paths":["company.website"],"requireHttps":true},"yearFounded":{"paths":["company.year_founded"]},"tags":{"paths":["company.tags"],"join":", "},"hasRootJobsArr":{"paths":["jobPostings"],"format":"array_len"}},"titleTemplate":"{name} (YC {batch})","titleWhenVar":"batch","titleFallbackTemplate":"{name} (Y Combinator)","descriptionVar":"oneLiner","blockquoteTemplate":"> {oneLiner}","blockquoteWhenVar":"oneLiner","bullets":[{"label":"YC Batch","template":"{batch}","whenVar":"batch"},{"label":"Status","template":"{status}","whenVar":"status"},{"label":"Founded","template":"{yearFounded}","whenVar":"yearFounded"},{"label":"Team Size","template":"{teamSize}","whenVar":"teamSize"},{"label":"Location","template":"{location}","whenVar":"location"},{"label":"Website","template":"{website}","whenVar":"website"},{"label":"Tags","template":"{tags}","whenVar":"tags"}],"sections":[{"heading":"About","headingTemplate":"About {name}","textVar":"longDesc"},{"heading":"Founders","listArrayPath":"company.founders","requireItemVar":"fName","collectLinkVars":["linkedin"],"itemVars":{"fName":{"paths":["full_name"],"trim":true},"fTitle":{"paths":["title"],"trim":true,"default":"Founder"},"fBio":{"paths":["founder_bio"],"format":"strip_tags"},"fBioSuffix":{"template":" — {fBio}","whenVars":["fBio"]},"linkedin":{"paths":["linkedin_url"],"requireHttps":true},"fLabel":{"template":"[{fName}]({linkedin})","whenVars":["fName","linkedin"],"fallbackVar":"fName"}},"itemTemplate":"**{fLabel}** ({fTitle}){fBioSuffix}"},{"heading":"Open Roles","headingTemplate":"Open Roles ({count})","arrayPath":"jobPostings","limit":30,"requireItemVar":"jTitle","collectLinkVars":["jUrl"],"itemVars":{"jTitle":{"paths":["title"],"trim":true},"urlHttp":{"paths":["url"],"requireHttpPrefix":true},"urlRelPart":{"paths":["url"],"stripPrefix":"/"},"urlFromRel":{"template":"https://www.ycombinator.com/{urlRelPart}","whenVars":["urlRelPart"]},"urlDefault":{"template":"https://www.ycombinator.com/companies/{slug}/jobs"},"urlRelOrDefault":{"template":"{urlFromRel}","whenVars":["urlFromRel"],"fallbackVar":"urlDefault"},"jUrl":{"template":"{urlHttp}","whenVars":["urlHttp"],"fallbackVar":"urlRelOrDefault"}},"columns":[{"header":"Role","template":"[{jTitle}]({jUrl})"},{"header":"Location","paths":["location","pretty_location"]},{"header":"Salary","paths":["salary_range","pretty_salary_range"]},{"header":"Type","paths":["role","type"]}]},{"heading":"Open Roles","headingTemplate":"Open Roles ({count})","unlessVar":"hasRootJobsArr","arrayPath":"company.jobPostings","limit":30,"requireItemVar":"jTitle","collectLinkVars":["jUrl"],"itemVars":{"jTitle":{"paths":["title"],"trim":true},"urlHttp":{"paths":["url"],"requireHttpPrefix":true},"urlRelPart":{"paths":["url"],"stripPrefix":"/"},"urlFromRel":{"template":"https://www.ycombinator.com/{urlRelPart}","whenVars":["urlRelPart"]},"urlDefault":{"template":"https://www.ycombinator.com/companies/{slug}/jobs"},"urlRelOrDefault":{"template":"{urlFromRel}","whenVars":["urlFromRel"],"fallbackVar":"urlDefault"},"jUrl":{"template":"{urlHttp}","whenVars":["urlHttp"],"fallbackVar":"urlRelOrDefault"}},"columns":[{"header":"Role","template":"[{jTitle}]({jUrl})"},{"header":"Location","paths":["location","pretty_location"]},{"header":"Salary","paths":["salary_range","pretty_salary_range"]},{"header":"Type","paths":["role","type"]}]}],"linksVars":["websiteHttps"]}}]},{"id":"yelp-fusion","name":"Yelp Fusion API v3","category":"commerce-social","description":"Extracts business search results, single business profiles, and reviews from the official Yelp Fusion v3 API (api.yelp.com) with a strict 24-hour max cache TTL; yelp.com HTML stays detect-only.","domains":["api.yelp.com"],"auth_mode":"key","max_cache_ttl_ms":86400000,"exampleUrls":["https://api.yelp.com/v3/businesses/search?term=coffee&location=San+Francisco","https://api.yelp.com/v3/businesses/gary-danko-san-francisco"],"routes":[{"match":{"hosts":["api.yelp.com"],"anyOf":[{"pathEquals":["/v3/businesses/search","/v3/businesses/matches"]},{"pathPrefix":"/v3/businesses/"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"key"},"extract":{"jsonMode":"yelp_fusion_json"}}]},{"id":"yext-locator","name":"Yext Store & Dealer Locator","category":"commerce-social","description":"Opt-in page-key adapter for Yext Live/Search API dealer locators; defaults OFF and falls back cleanly to HTML/JSON-LD when disabled.","domains":["liveapi.yext.com","cdn.yextapis.com","locations.chipotle.com"],"universalEngine":true,"auth_mode":"page-key","requires_page_key_opt_in":true,"exampleUrls":["https://cdn.yextapis.com/v2/accounts/me/answers/query?api_key=01db1d1e5ebbaa7ea2e6807ad2196ab3&v=20220511&experienceKey=yext-help-hitchhikers&input=locator"],"routes":[{"match":{"hosts":["liveapi.yext.com","cdn.yextapis.com"],"pathSegments":["v2","accounts",{"param":"accountId","charset":"alnum_dash","minLen":1,"maxLen":64},"entities"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"jsonMode":"yext_locator"}},{"match":{"hosts":["liveapi.yext.com","cdn.yextapis.com"],"pathSegments":["v2","accounts",{"param":"accountId","charset":"alnum_dash","minLen":1,"maxLen":64},"answers","query"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"jsonMode":"yext_locator"}}],"htmlRoutes":[{"id":"yext-locator","match":{"exactSegments":false},"mode":"yext_locator_html"}]},{"id":"yotpo","name":"Yotpo Product Reviews","category":"commerce-social","description":"Extracts public Yotpo reviews widget JSON payloads and discovers Yotpo widget markers on storefront HTML pages.","domains":["api-cdn.yotpo.com","api.yotpo.com"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://api-cdn.yotpo.com/v1/widget/MdtpPOdzecvdDWwA3pFvhLyB6ab4osWf5p8TQHpj/products/8158162911322/reviews.json"],"routes":[{"match":{"hosts":["api-cdn.yotpo.com","api.yotpo.com"],"pathSegments":["v1","widget",{"param":"appKey","charset":"alnum_dash","minLen":4,"maxLen":80},"products",{"param":"productId","charset":"pkg","minLen":1,"maxLen":120},"reviews.json"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"yotpo_reviews"}}],"htmlRoutes":[{"id":"yotpo","match":{"exactSegments":false},"mode":"yotpo_html"}]},{"id":"zendesk-hc","name":"Zendesk Help Center","category":"developer","description":"Upgrades *.zendesk.com Help Center article, section, and category pages to the official Help Center v2 JSON API with breadcrumbs, updated timestamps, and Markdown conversion.","domains":["*.zendesk.com","support.sram.com"],"exampleUrls":["https://support.zendesk.com/hc/en-us/articles/4408885959066-Lesson-4-Business-rules","https://support.zendesk.com/hc/en-us/sections/5634465167514-Business-rules","https://support.zendesk.com/hc/en-us/categories/6191910393754-Product-guides"],"routes":[{"match":{"exactSegments":false,"pathSegments":["hc",{"param":"locale","charset":"alnum_dash","minLen":2,"maxLen":16,"transform":"lower"},"articles",{"param":"articleId","charset":"leading_digits_slug","minLen":1,"maxLen":160,"transform":"leading_digits"}]},"twin":{"fetchUrl":"https://{host}/api/v2/help_center/{locale}/articles/{articleId}.json?include=sections,categories","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"rejectIfFieldTruthy":"article.draft","requireFields":["article.title","article.body"],"vars":{"title":{"paths":["article.title"],"format":"strip_tags","trim":true},"updatedAt":{"paths":["article.updated_at","article.edited_at"]},"htmlUrl":{"paths":["article.html_url"],"requireHttps":true},"sectionName":{"paths":["sections.0.name"],"format":"strip_tags","trim":true},"sectionUrl":{"paths":["sections.0.html_url"],"requireHttps":true},"categoryName":{"paths":["categories.0.name"],"format":"strip_tags","trim":true},"categoryUrl":{"paths":["categories.0.html_url"],"requireHttps":true},"catAndSec":{"template":"{categoryName} › {sectionName}","whenVars":["categoryName","sectionName"],"fallbackVar":"sectionName"},"breadcrumbs":{"template":"{catAndSec}","whenVars":["catAndSec"],"fallbackVar":"categoryName"},"labels":{"paths":["article.label_names"],"itemWrap":"`","join":", ","limit":12},"bodyMd":{"paths":["article.body"],"format":"html_to_md","trim":true}},"requireVars":["title","bodyMd"],"titleTemplate":"{title}","publishedTimeVar":"updatedAt","bullets":[{"label":"Breadcrumbs","template":"{breadcrumbs}","whenVar":"breadcrumbs"},{"label":"Updated","template":"{updatedAt}","whenVar":"updatedAt"},{"label":"Labels","template":"{labels}","whenVar":"labels"},{"label":"Canonical URL","template":"{htmlUrl}","whenVar":"htmlUrl"}],"bodyVar":"bodyMd","linksVars":["htmlUrl","sectionUrl","categoryUrl"]}},{"match":{"exactSegments":false,"pathSegments":["hc",{"param":"locale","charset":"alnum_dash","minLen":2,"maxLen":16,"transform":"lower"},"sections",{"param":"sectionId","charset":"leading_digits_slug","minLen":1,"maxLen":160,"transform":"leading_digits"}]},"twin":{"fetchUrl":"https://{host}/api/v2/help_center/{locale}/sections/{sectionId}/articles.json?per_page=50&include=sections,categories","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"requireAnyFields":["articles","sections"],"vars":{"sectionTitle":{"paths":["sections.0.name"],"format":"strip_tags","trim":true,"fallbackTemplate":"Help Center Section #{sectionId}"},"categoryName":{"paths":["categories.0.name"],"format":"strip_tags","trim":true},"sectionUrl":{"paths":["sections.0.html_url"],"requireHttps":true},"categoryUrl":{"paths":["categories.0.html_url"],"requireHttps":true},"articleCount":{"paths":["articles"],"format":"array_len_comma"}},"titleTemplate":"{sectionTitle}","bullets":[{"label":"Category","template":"{categoryName}","whenVar":"categoryName"},{"label":"Articles","template":"{articleCount}","whenVar":"articleCount"}],"sections":[{"heading":"Articles","arrayPath":"articles","limit":50,"emptyText":"No published articles found in this section.","requireItemVar":"artTitle","collectLinkVars":["artUrl"],"itemVars":{"artTitle":{"paths":["title"],"format":"strip_tags","trim":true},"artUrl":{"paths":["html_url"],"requireHttps":true},"artLabels":{"paths":["label_names"],"join":", ","limit":8},"artUpdated":{"paths":["updated_at"],"sliceMax":10}},"recordFields":{"title":"{artTitle}","url":"{artUrl}","updatedAt":"{artUpdated}","labels":"{artLabels}"},"columns":[{"header":"Article","template":"[{artTitle}]({artUrl})"},{"header":"Updated","paths":["updated_at"],"sliceMax":10},{"header":"Labels","template":"{artLabels}"}]}],"linksVars":["sectionUrl","categoryUrl"]}},{"match":{"exactSegments":false,"pathSegments":["hc",{"param":"locale","charset":"alnum_dash","minLen":2,"maxLen":16,"transform":"lower"},"categories",{"param":"categoryId","charset":"leading_digits_slug","minLen":1,"maxLen":160,"transform":"leading_digits"}]},"twin":{"fetchUrl":"https://{host}/api/v2/help_center/{locale}/categories/{categoryId}/sections.json?per_page=50&include=categories","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"requireAnyFields":["sections","categories"],"vars":{"categoryTitle":{"paths":["categories.0.name"],"format":"strip_tags","trim":true,"fallbackTemplate":"Help Center Category #{categoryId}"},"categoryDesc":{"paths":["categories.0.description"],"format":"strip_tags","trim":true},"categoryUrl":{"paths":["categories.0.html_url"],"requireHttps":true},"sectionCount":{"paths":["sections"],"format":"array_len_comma"}},"titleTemplate":"{categoryTitle}","descriptionVar":"categoryDesc","introVar":"categoryDesc","bullets":[{"label":"Sections","template":"{sectionCount}","whenVar":"sectionCount"}],"sections":[{"heading":"Sections","arrayPath":"sections","limit":50,"emptyText":"No sections found in this category.","requireItemVar":"secName","collectLinkVars":["secUrl"],"itemVars":{"secName":{"paths":["name"],"format":"strip_tags","trim":true},"secUrl":{"paths":["html_url"],"requireHttps":true},"secDesc":{"paths":["description"],"format":"strip_tags","trim":true,"sliceMax":160},"secUpdated":{"paths":["updated_at"],"sliceMax":10}},"recordFields":{"title":"{secName}","url":"{secUrl}","description":"{secDesc}","updatedAt":"{secUpdated}"},"columns":[{"header":"Section","template":"[{secName}]({secUrl})"},{"header":"Description","template":"{secDesc}"},{"header":"Updated","paths":["updated_at"],"sliceMax":10}]}],"linksVars":["categoryUrl"]}}]}]} +{"version":2,"manifests":[{"id":"acalog","name":"Acalog University Course Catalogs","category":"public-records","description":"Extracts Acalog university catalog course descriptions and program pages from preview_course_nopop.php and content.php while strictly honoring robots.txt and crawl delays.","domains":["*.acalog.com","catalog.highline.edu","catalog.missouristate.edu","catalog.purdue.edu","catalog.unlv.edu"],"universalEngine":true,"auth_mode":"html","strict_robots":true,"min_interval_ms":2000,"exampleUrls":["https://csulb.catalog.acalog.com/index.php","https://catalog.highline.edu/"],"htmlRoutes":[{"id":"acalog","match":{"exactSegments":false},"mode":"acalog_html"}]},{"id":"accela-citizen-access","name":"Accela Citizen Access Permitting Portals","category":"public-records","description":"Strictly read-only GET HTML extractor for Accela Citizen Access permit and license CapDetail pages (never submits forms).","domains":["aca-prod.accela.com"],"universalEngine":true,"auth_mode":"html","exampleUrls":["https://aca-prod.accela.com/SANDIEGO/Cap/CapDetail.aspx?Module=DSD&TabName=DSD&capID1=REC26&capID2=00000&capID3=008YQ&agencyCode=SANDIEGO"],"htmlRoutes":[{"id":"accela-citizen-access","match":{"exactSegments":false},"mode":"accela_html"}]},{"id":"aem","name":"Adobe Experience Manager (AEM)","category":"developer","description":"Upgrades AEM /content//...html pages to .model.json / .infinity.json Sling model twins, with clean HTML fallback when disabled or on 404/403.","domains":["wknd.site"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://wknd.site/content/wknd/us/en.html","https://wknd.site/content/wknd/us/en.model.json"],"routes":[{"match":{"excludeHosts":["www.govinfo.gov","govinfo.gov"],"pathSuffix":".model.json"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"aem_model"}},{"match":{"excludeHosts":["www.govinfo.gov","govinfo.gov"],"pathSuffix":".infinity.json"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"aem_model"}},{"match":{"excludeHosts":["www.govinfo.gov","govinfo.gov"],"pathSuffix":".html","pathSegments":["content",{"param":"siteSeg","charset":"url_seg","reserved":["pkg","dam"],"minLen":1,"maxLen":120},{"param":"pagePath","charset":"safe_subpath","stripSuffix":".html","greedy":true,"minLen":1,"maxLen":400}]},"twin":{"fetchUrl":"https://{host}/content/{siteSeg}/{pagePath}.model.json","rawPathParams":["pagePath"],"kind":"json","accept":"application/json"},"extract":{"jsonMode":"aem_model"}}],"htmlRoutes":[{"id":"aem","match":{"exactSegments":false},"mode":"aem_html"}]},{"id":"aftership-tracking-page","name":"AfterShip Order Tracking Pages","category":"commerce-social","description":"Extracts hydrated AfterShip tracking portals and shipment checkpoints while enforcing strict_robots for *.aftership.com and rejecting Cloudflare/empty shells.","domains":["*.aftership.com","www.aftership.com"],"universalEngine":true,"auth_mode":"pub","strict_robots":true,"min_interval_ms":1000,"exampleUrls":["https://nealsyardremedies.aftership.com/"],"htmlRoutes":[{"id":"aftership-tracking-page","match":{"exactSegments":false},"mode":"aftership_tracking_html"}]},{"id":"agenda-portal-pack","name":"Municipal Agenda Portal Pack (eScribe, NovusAgenda, CivicWeb)","category":"public-records","description":"Extracts public meeting lists, agenda links, and documents from eScribe, NovusAgenda, and CivicWeb/iCompass portals.","domains":["*.escribemeetings.com","*.novusagenda.com","*.civicweb.net"],"auth_mode":"html","strict_robots":true,"exampleUrls":["https://pub-london.escribemeetings.com/","https://houston.novusagenda.com/agendapublic/","https://millcreekwa.civicweb.net/Portal/"],"htmlRoutes":[{"id":"agenda-portal-pack","match":{"exactSegments":false},"mode":"agenda_portal_html"}]},{"id":"airnow","name":"AirNow Air Quality API","category":"research-health","description":"US EPA AirNow air quality observation and forecast JSON API (API_KEY query parameter) with airnow.gov HTML fallback.","domains":["www.airnowapi.org","airnowapi.org","www.airnow.gov","airnow.gov","docs.airnowapi.org"],"auth_mode":"key","exampleUrls":["https://www.airnowapi.org/aq/observation/zipCode/current/?format=application/json&zipCode=20002&distance=25","https://www.airnow.gov/?city=Washington&state=DC&country=USA"],"routes":[{"match":{"hosts":["www.airnowapi.org","airnowapi.org"],"pathPrefix":"/aq/"},"twin":{"fetchUrl":"{requestUrl}","setQueryParams":{"format":"application/json"},"kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"airnow_json"}}],"htmlRoutes":[{"id":"airnow","match":{"hosts":["www.airnow.gov","airnow.gov","docs.airnowapi.org"],"exactSegments":false},"mode":"airnow_html"}]},{"id":"algolia","name":"Algolia On-Site Search","category":"developer","description":"Opt-in page-key adapter for Algolia search index JSON twins; defaults OFF and falls back cleanly to HTML/JSON-LD when disabled.","domains":["latency-dsn.algolia.net"],"universalEngine":true,"auth_mode":"page-key","requires_page_key_opt_in":true,"exampleUrls":["https://latency-dsn.algolia.net/1/indexes/instant_search?query=apple"],"routes":[{"match":{"hostSubdomain":{"suffix":".algolia.net","param":"appHost"},"pathSegments":["1","indexes",{"param":"indexName","charset":"url_seg","minLen":1,"maxLen":120},{"param":"op","allowValues":["query"],"optional":true}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"jsonMode":"algolia_search"}}],"htmlRoutes":[{"id":"algolia","match":{"exactSegments":false},"mode":"algolia_html"}]},{"id":"american-legal-publishing","name":"American Legal Publishing Municipal Codes","category":"public-records","description":"HTML extractor for American Legal Publishing Code Library municipal codes and ordinance sections.","domains":["codelibrary.amlegal.com"],"auth_mode":"html","exampleUrls":["https://codelibrary.amlegal.com/codes/san_francisco/latest/overview","https://codelibrary.amlegal.com/codes/chicago/latest/overview"],"htmlRoutes":[{"id":"american-legal-publishing","match":{"exactSegments":false},"mode":"amlegal_html"}]},{"id":"ansible-puppet-forge","name":"Ansible Galaxy & Puppet Forge","category":"developer","description":"Extracts Ansible collection metadata from galaxy.ansible.com v3 JSON API and Puppet module metadata from forge.puppet.com __NEXT_DATA__ HTML without upgrading to robots-disallowed forgeapi.puppet.com.","domains":["galaxy.ansible.com","forge.puppet.com","forgeapi.puppet.com"],"auth_mode":"pub","exampleUrls":["https://galaxy.ansible.com/api/v3/plugin/ansible/content/published/collections/index/community/general/","https://forge.puppet.com/modules/puppetlabs/stdlib"],"routes":[{"match":{"hosts":["galaxy.ansible.com"],"pathPrefix":"/api/v3/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":1048576},"extract":{"jsonMode":"ansible_galaxy_json"}},{"match":{"hosts":["forgeapi.puppet.com"],"pathPrefix":"/v3/modules/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"puppet_forge_json"}}],"htmlRoutes":[{"id":"ansible-puppet-forge","match":{"hosts":["forge.puppet.com"],"pathPrefix":"/modules/"},"mode":"puppet_forge_html"}]},{"id":"ap-news","name":"Associated Press (AP News)","category":"commerce-social","description":"Extracts NewsArticle JSON-LD and RichTextStoryBody from AP News HTML pages while respecting robots.txt feed exclusions.","domains":["apnews.com","www.apnews.com"],"auth_mode":"html","exampleUrls":["https://apnews.com/hub/us-news"],"htmlRoutes":[{"id":"ap-news","match":{"exactSegments":false},"mode":"ap_news_html"}]},{"id":"api-docs-portals","name":"API Docs Portals (OpenAPI, Redocly, Postman, Stoplight)","category":"developer","description":"Universal extractor for OpenAPI 2/3 JSON specs, Postman Collection JSON, and Redocly/Postman/Stoplight API documentation portals.","domains":["petstore3.swagger.io","redocly.com","www.postman.com","learn.openapis.org"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://petstore3.swagger.io/api/v3/openapi.json","https://learn.openapis.org/"],"routes":[{"match":{"anyOf":[{"pathEquals":["/openapi.json","/swagger.json","/api-docs","/v2/api-docs","/v3/api-docs"]},{"pathSuffix":"/openapi.json"},{"pathSuffix":"/swagger.json"},{"pathSuffix":"/collection.json"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"openapi_postman_json"}}],"htmlRoutes":[{"id":"api-docs-portals","match":{"exactSegments":false},"mode":"api_docs_portal_html"}]},{"id":"apis-guru","name":"APIs.guru OpenAPI Directory","category":"developer","description":"Extracts OpenAPI directory metrics, per-provider API specs, and Range-bounded streaming partial-JSON directory entries from api.apis.guru.","domains":["api.apis.guru","apis.guru"],"auth_mode":"pub","exampleUrls":["https://api.apis.guru/v2/metrics.json","https://api.apis.guru/v2/github.com.json","https://api.apis.guru/v2/list.json"],"routes":[{"match":{"hosts":["api.apis.guru"],"exactSegments":true,"pathEquals":["/v2/list.json"]},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"application/json","maxBytes":2097152,"headers":{"Range":"bytes=0-2097151"}},"extract":{"textMode":"apis_guru_list_bounded"}},{"match":{"hosts":["api.apis.guru"],"pathPrefix":"/v2/","pathSuffix":".json"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"apis_guru_json"}}],"htmlRoutes":[{"id":"apis-guru","match":{"hosts":["apis.guru","api.apis.guru"],"exactSegments":false},"mode":"apis_guru_html"}]},{"id":"appfolio-listings","name":"AppFolio Rental Listings","category":"commerce-social","description":"Extracts residential rental listings from AppFolio property management portals while strictly honoring Crawl-delay: 10, robots.txt, and /page-not-found-sub soft-404 rejection.","domains":["*.appfolio.com"],"universalEngine":false,"auth_mode":"pub","strict_robots":true,"min_interval_ms":10000,"max_concurrent":1,"exampleUrls":["https://lapmg.appfolio.com/listings"],"htmlRoutes":[{"id":"appfolio-listings","match":{"exactSegments":false},"mode":"appfolio_listings_html"}]},{"id":"apple-app-store","name":"Apple App Store","category":"developer","description":"Extracts structured iOS/macOS App Store metadata (developer, rating, review count, price, category, version notes, and description).","domains":["apps.apple.com"],"exampleUrls":["https://apps.apple.com/us/app/cloudflare-one-agent/id6443476492"],"htmlRoutes":[{"match":{"pathContainsSegment":"app","minSegments":2},"mode":"dom","jsonLdTypes":["SoftwareApplication","MobileApplication","WebApplication"],"vars":{"title":{"jsonLdPaths":["name"],"metaKeys":["og:title"],"stripRegexSuffix":"\\s+on the App\\s*Store$","cssText":["h1"]},"developer":{"jsonLdPaths":["author.name"],"cssText":["h2.product-header__identity"]},"ratingVal":{"jsonLdPaths":["aggregateRating.ratingValue"]},"ratingCount":{"jsonLdPaths":["aggregateRating.reviewCount","aggregateRating.ratingCount"]},"ratingOnly":{"template":"{ratingVal} / 5","whenVars":["ratingVal"]},"rating":{"template":"{ratingVal} / 5 ({ratingCount} ratings)","whenVars":["ratingVal","ratingCount"],"fallbackVar":"ratingOnly"},"currency":{"jsonLdPaths":["offers.0.priceCurrency","offers.priceCurrency"],"default":"USD"},"price":{"jsonLdPaths":["offers.0.price","offers.price"],"format":"free_or_currency","currencyVar":"currency"},"category":{"jsonLdPaths":["applicationCategory"]},"osSys":{"jsonLdPaths":["operatingSystem"]},"desc":{"jsonLdPaths":["description"],"metaKeys":["description"]},"descShort":{"template":"{desc}","whenVars":["desc"],"sliceMax":260},"version":{"regexExtract":{"source":"clean_html","pattern":"Version\\s+([0-9][0-9A-Za-z._-]*)","group":1}}},"requireVars":["title"],"requireBulletsOrVars":["desc"],"titleTemplate":"{title}","descriptionVar":"descShort","authorVar":"developer","bullets":[{"label":"Developer","template":"{developer}","whenVar":"developer"},{"label":"Category","template":"{category}","whenVar":"category"},{"label":"Rating","template":"{rating}","whenVar":"rating"},{"label":"Price","template":"{price}","whenVar":"price"},{"label":"Platform","template":"{osSys}","whenVar":"osSys"},{"label":"Latest Version","template":"`{version}`","whenVar":"version"}],"sections":[{"heading":"Description","textVar":"desc"}]}]},{"id":"arc-xp","name":"Arc XP Publishing (Fusion / ANS)","category":"commerce-social","description":"Extracts Arc XP /pf/api/v3/content/fetch ANS JSON twins and inline Fusion.globalContent publisher articles.","domains":["www.clickondetroit.com"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://www.clickondetroit.com/news/local/2026/11/27/1-killed-in-shooting-in-downtown-birmingham/"],"routes":[{"match":{"pathPrefix":"/pf/api/v3/content/fetch/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"arc_xp_ans"}}],"htmlRoutes":[{"id":"arc-xp","match":{"exactSegments":false},"mode":"arc_xp_html"}]},{"id":"arcgis-hub","name":"Esri ArcGIS Hub Open Data Portals","category":"public-records","description":"Extracts ArcGIS Hub /api/v3/datasets (with sparse field projection) and /api/search/v1 OGC GeoJSON item collections plus hydrated HTML.","domains":["hub.arcgis.com","*.hub.arcgis.com","*.opendata.arcgis.com","opendata.dc.gov"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://hub.arcgis.com/api/search/v1/collections/all/items?limit=3","https://opendata.dc.gov/api/v3/datasets?page[size]=1"],"routes":[{"match":{"pathPrefix":"/api/v3/datasets"},"twin":{"fetchUrl":"{requestUrl}","defaultQueryParams":{"fields[datasets]":"name,description,owner,modified,created,url,orgName,recordCount,licenseInfo,tags,hubType"},"kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"arcgis_hub_json"}},{"match":{"pathPrefix":"/api/search/v1/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/geo+json, application/json","maxBytes":4194304},"extract":{"jsonMode":"arcgis_hub_json"}}],"htmlRoutes":[{"id":"arcgis-hub","match":{"exactSegments":false},"mode":"arcgis_hub_html"}]},{"id":"arcgis","name":"ArcGIS REST FeatureServer & MapServer Layers","category":"public-records","description":"Upgrades public ArcGIS REST FeatureServer/MapServer layer URLs to ?f=json metadata, geometry type, spatial reference, and field schemas.","domains":["services.arcgis.com"],"universalEngine":true,"exampleUrls":["https://services.arcgis.com/P3ePLMYs2RVChkJx/ArcGIS/rest/services/2020_Census_State_Apportionment/FeatureServer/0"],"match":{"arcgisRestLayer":true,"pathSegments":[{"param":"restPath","charset":"safe_subpath","greedy":true,"maxLen":500}]},"twin":{"fetchUrl":"{requestUrl}","setQueryParams":{"f":"json"},"kind":"json","accept":"application/json"},"extract":{"rejectIfFieldTruthy":"error","vars":{"name":{"paths":["name","mapName","serviceDescription"],"trim":true,"default":"ArcGIS Service"},"desc":{"paths":["description","serviceDescription"],"format":"strip_tags"},"descShort":{"paths":["description","serviceDescription"],"format":"strip_tags","sliceMax":260},"geomType":{"paths":["geometryType"]},"maxRec":{"paths":["maxRecordCount"]},"capabilities":{"paths":["capabilities"]},"wkid":{"paths":["extent.spatialReference.latestWkid","extent.spatialReference.wkid"]},"baseClean":{"template":"https://{host}/{restPath}"},"hasFields":{"paths":["fields"],"format":"array_len","excludeEquals":"0"},"hasLayers":{"paths":["layers"],"format":"array_len","excludeEquals":"0"}},"titleTemplate":"{name}","descriptionVar":"descShort","bullets":[{"label":"REST Endpoint","template":"`{baseClean}`"},{"label":"Geometry Type","template":"`{geomType}`","whenVar":"geomType"},{"label":"Spatial Reference (WKID)","template":"`EPSG:{wkid}`","whenVar":"wkid"},{"label":"Max Record Count / Query","template":"{maxRec}","whenVar":"maxRec"},{"label":"Capabilities","template":"{capabilities}","whenVar":"capabilities"}],"sections":[{"heading":"Description","textVar":"desc"},{"heading":"Layer Fields","headingTemplate":"Layer Fields ({count})","whenVar":"hasFields","arrayPath":"fields","limit":40,"columns":[{"header":"Field","paths":["name"],"code":true},{"header":"Alias","paths":["alias"]},{"header":"Type","paths":["type"],"stripPrefix":"esriFieldType"}]},{"heading":"Sublayers","headingTemplate":"Sublayers ({count})","whenVar":"hasLayers","unlessVar":"hasFields","arrayPath":"layers","limit":30,"itemVars":{"layerId":{"paths":["id"],"default":"0"},"layerName":{"paths":["name"],"default":"Layer"}},"columns":[{"header":"ID","paths":["id"]},{"header":"Layer","template":"[{layerName}]({baseClean}/{layerId})"},{"header":"Geometry","paths":["geometryType"]}]}]}},{"id":"artifact-hub","name":"Artifact Hub","category":"developer","description":"Extracts Kubernetes Helm chart, operator, and CNCF package versions, repositories, security reports, and READMEs from artifacthub.io v1 API and package URLs.","domains":["artifacthub.io"],"auth_mode":"pub","exampleUrls":["https://artifacthub.io/api/v1/packages/helm/ingress-nginx/ingress-nginx","https://artifacthub.io/packages/helm/ingress-nginx/ingress-nginx"],"routes":[{"match":{"hosts":["artifacthub.io"],"pathPrefix":"/api/v1/packages/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":1048576},"extract":{"jsonMode":"artifact_hub_json"}},{"match":{"hosts":["artifacthub.io"],"exactSegments":true,"pathSegments":["packages",{"param":"kind","charset":"slug"},{"param":"repo","charset":"pkg"},{"param":"pkg","charset":"pkg"}]},"twin":{"fetchUrl":"https://artifacthub.io/api/v1/packages/{kind}/{repo}/{pkg}","kind":"json","accept":"application/json","maxBytes":1048576},"extract":{"jsonMode":"artifact_hub_json"}}],"htmlRoutes":[{"id":"artifact-hub","match":{"hosts":["artifacthub.io"],"exactSegments":false},"mode":"artifact_hub_html"}]},{"id":"arxiv","name":"arXiv Preprints","category":"research-health","description":"Extracts arXiv preprint title, authors, submission date, subject classifications, PDF/HTML links, and clean abstract from arxiv.org/abs/ (strictly respecting robots.txt).","domains":["arxiv.org","www.arxiv.org"],"exampleUrls":["https://arxiv.org/abs/1706.03762"],"htmlRoutes":[{"match":{"pathSegments":["abs",{"param":"arxivId","charset":"arxiv_id","greedy":true}]},"mode":"dom","requireVars":["title","abstract"],"vars":{"titleDom":{"cssText":["h1.title"],"stripPrefix":"Title:"},"title":{"metaKeys":["citation_title"],"fallbackVar":"titleDom"},"authors":{"allMetaKey":"citation_author","cssAllText":{"selector":"div.authors a","limit":50,"join":", "},"limit":20,"join":", "},"authorsShort":{"allMetaKey":"citation_author","cssAllText":{"selector":"div.authors a","limit":50,"join":", "},"limit":4,"join":", "},"date":{"metaKeys":["citation_date","citation_online_date"]},"doi":{"metaKeys":["citation_doi"]},"primarySubject":{"cssText":["span.primary-subject"]},"absMeta":{"metaKeys":["citation_abstract"]},"abstract":{"cssText":["blockquote.abstract"],"stripPrefix":"Abstract:","fallbackVar":"absMeta"},"abstractShort":{"template":"{abstract}","whenVars":["abstract"],"sliceMax":260},"pdfUrl":{"template":"https://arxiv.org/pdf/{arxivId}"},"htmlPaperUrl":{"template":"https://arxiv.org/html/{arxivId}"}},"titleTemplate":"{title}","descriptionVar":"abstractShort","authorVar":"authorsShort","publishedTimeVar":"date","bullets":[{"label":"arXiv ID","template":"`{arxivId}`"},{"label":"Authors","template":"{authors}","whenVar":"authors"},{"label":"Submitted","template":"{date}","whenVar":"date"},{"label":"Primary Subject","template":"{primarySubject}","whenVar":"primarySubject"},{"label":"DOI","template":"`{doi}`","whenVar":"doi"},{"label":"Full Text","template":"[PDF]({pdfUrl}) · [ar5iv / HTML]({htmlPaperUrl})"}],"sections":[{"heading":"Abstract","textVar":"abstract"}],"linkTemplates":["https://arxiv.org/pdf/{arxivId}","https://arxiv.org/html/{arxivId}"]}]},{"id":"association-ams-pack","name":"Association AMS Pack (Novi AMS, MemberClicks, YourMembership)","category":"commerce-social","description":"Extracts association events and member directories from Novi AMS, MemberClicks / Personify WebLink, and YourMembership portals while rejecting login gates and error shells.","domains":["www.austinaptassoc.com","web.arlingtonchamber.org","*.memberclicks.net","*.site-ym.com"],"universalEngine":true,"auth_mode":"html","exampleUrls":["https://www.austinaptassoc.com/events","https://web.arlingtonchamber.org/events"],"htmlRoutes":[{"id":"association-ams-pack","match":{"exactSegments":false},"mode":"association_ams_html"}]},{"id":"atlassian-statuspage","name":"Atlassian Statuspage","category":"developer","description":"Extracts Atlassian Statuspage /api/v2/summary.json and incidents.json endpoints (when robots.txt permits) plus Statuspage HTML pages.","domains":["statuspage.io","www.statuspage.io","www.githubstatus.com"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://www.githubstatus.com/","https://discord.statuspage.io/"],"routes":[{"match":{"pathEquals":["/api/v2/summary.json","/api/v2/incidents.json","/api/v2/status.json","/api/v2/components.json"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"statuspage_v2"}}],"htmlRoutes":[{"id":"atlassian-statuspage","match":{"exactSegments":false},"mode":"statuspage_html"}]},{"id":"auto-dealer-inventory","name":"Auto Dealer Inventory (Universal)","category":"commerce-social","description":"Universal automotive dealer SRP/VDP HTML and Schema.org Vehicle/Car JSON-LD extractor for Dealer.com, Dealer Inspire, and DealerOn storefronts.","domains":["www.johneaglehonda.com"],"universalEngine":true,"auth_mode":"html","exampleUrls":["https://www.johneaglehonda.com/used-inventory/index.htm","https://www.johneaglehonda.com/used/Honda/2021-Honda-Accord--for-sale-houston-texas-f65329b9ac180db0f233180fce0b2e1d.htm"],"htmlRoutes":[{"id":"auto-dealer-inventory","match":{"anyOf":[{"pathPrefix":"/used-inventory/"},{"pathPrefix":"/new-inventory/"},{"pathPrefix":"/all-inventory/"},{"pathPrefix":"/certified-inventory/"},{"pathPrefix":"/inventory/"},{"pathPrefix":"/used/"},{"pathPrefix":"/new/"},{"pathPrefix":"/vehicles/"},{"pathPrefix":"/vehicle/"},{"pathPrefix":"/vdp/"},{"pathPrefix":"/srp/"},{"pathEquals":["/searchused.aspx","/searchnew.aspx","/searchall.aspx"]}]},"mode":"auto_dealer_html"}]},{"id":"auto-parts-fitment","name":"Auto Parts Fitment & SKU Extractor","category":"commerce-social","description":"Extracts auto parts SKUs, part numbers, strict GTINs, and explicit vehicle fitment (year, make, model, engine) for AutoZone, O'Reilly, NAPA, and Advance Auto Parts.","domains":["autozone.com","www.autozone.com","oreillyauto.com","www.oreillyauto.com","napaonline.com","www.napaonline.com","shop.advanceautoparts.com","www.advanceautoparts.com"],"auth_mode":"html","min_interval_ms":2000,"strict_robots":true,"exampleUrls":["https://www.autozone.com/brakes-and-traction-control/brake-pads/duralast-gold-ceramic-brake-pads-dg1410/141001_0_0","https://www.napaonline.com/en/p/NAPA1410"],"htmlRoutes":[{"id":"auto-parts-fitment","match":{"exactSegments":false},"mode":"auto_parts_fitment_html"}]},{"id":"back-market-swappa","name":"Back Market & Swappa Refurbished Electronics","category":"commerce-social","description":"Extracts refurbished electronics Product/AggregateOffer JSON-LD and specifications from Back Market and Swappa while rejecting bot-challenge and SPA shells.","domains":["backmarket.com","www.backmarket.com","swappa.com","www.swappa.com"],"auth_mode":"html","min_interval_ms":2000,"strict_robots":true,"exampleUrls":["https://www.backmarket.com/en-us/p/iphone-13-512gb-red-locked-verizon/f600a6e0-4627-4b38-b17d-efa60fed7568","https://swappa.com/buy/apple-iphone-14"],"htmlRoutes":[{"id":"back-market-swappa","match":{"anyOf":[{"pathPrefix":"/en-us/p/"},{"pathPrefix":"/p/"},{"pathPrefix":"/buy/"},{"pathPrefix":"/listing/"},{"pathPrefix":"/listings/"}]},"mode":"back_market_swappa_html"}]},{"id":"bamboohr-breezy-recruitee","name":"BambooHR, Breezy HR, Recruitee & Personio Boards","category":"jobs","description":"Upgrades BambooHR (/careers/list & /detail), Breezy HR (/json), Recruitee (/api/offers), and Personio (/xml) career boards to structured feeds.","domains":["*.bamboohr.com","*.breezy.hr","*.recruitee.com","*.jobs.personio.de","*.jobs.personio.com"],"exampleUrls":["https://posthog.bamboohr.com/careers","https://breezy.breezy.hr/","https://bunq.recruitee.com/","https://personio.jobs.personio.de/"],"routes":[{"match":{"hosts":["*.bamboohr.com"],"hostSubdomain":{"suffix":".bamboohr.com","param":"org","reserved":["www","resources","help","documentation","developers","blog","status","api"]},"pathSegments":[{"param":"boardSection","charset":"alnum","allowValues":["careers","jobs"],"optional":true}]},"twin":{"id":"bamboohr-board","fetchUrl":"https://{host}/careers/list","kind":"json","accept":"application/json"},"extract":{"vars":{"count":{"paths":["result"],"format":"array_len"}},"requireVars":["count"],"titleTemplate":"{org} — BambooHR Careers ({count} open roles)","sections":[{"heading":"","arrayPath":"result","limit":100,"emptyText":"No open positions currently listed.","itemVars":{"id":{"paths":["id"]},"jTitle":{"paths":["jobOpeningName"],"trim":true,"default":"Role"},"jUrl":{"template":"https://{host}/careers/{id}"},"dept":{"paths":["departmentLabel"],"trim":true,"default":"-"},"city":{"paths":["location.city"],"trim":true},"state":{"paths":["location.state"],"trim":true},"bothLoc":{"template":"{city}, {state}","whenVars":["city","state"]},"oneLoc":{"paths":["location.city","location.state"],"trim":true},"remoteLoc":{"paths":["isRemote"],"format":"bool_map","trueValue":"Remote","falseValue":"-"},"loc":{"template":"{bothLoc}","whenVars":["bothLoc"],"fallbackVar":"oneLoc","fallbackTemplate":"{remoteLoc}"}},"collectLinkVars":["jUrl"],"columns":[{"header":"Role","template":"[{jTitle}]({jUrl})"},{"header":"Department","template":"{dept}"},{"header":"Location","template":"{loc}"}]}]}},{"match":{"hosts":["*.bamboohr.com"],"hostSubdomain":{"suffix":".bamboohr.com","param":"org","reserved":["www","resources","help","documentation","developers","blog","status","api"]},"exactSegments":false,"pathSegments":["careers",{"param":"jobId","charset":"digits"}]},"twin":{"id":"bamboohr-job","fetchUrl":"https://{host}/careers/{jobId}/detail","kind":"json","accept":"application/json"},"extract":{"rootPath":"result.jobOpening","requireFields":["jobOpeningName"],"vars":{"jobTitle":{"paths":["jobOpeningName"],"trim":true},"body":{"paths":["description"],"format":"html_to_md"}},"titleTemplate":"{jobTitle} @ {org}","bodyVar":"body"}},{"match":{"hosts":["*.breezy.hr"],"hostSubdomain":{"suffix":".breezy.hr","param":"org","reserved":["www","app"]},"pathSegments":[]},"twin":{"id":"breezy-hr","fetchUrl":"https://{host}/json","kind":"json","accept":"application/json"},"extract":{"wrapRootArrayAs":"jobs","vars":{"count":{"paths":["jobs"],"format":"array_len"}},"requireVars":["count"],"titleTemplate":"{org} — Breezy HR Board ({count} open roles)","sections":[{"heading":"","arrayPath":"jobs","limit":100,"emptyText":"No open positions currently listed.","itemVars":{"jTitle":{"paths":["name"],"trim":true,"default":"Role"},"rawUrl":{"paths":["url"],"requireHttps":true},"jUrl":{"template":"{rawUrl}","whenVars":["rawUrl"],"fallbackTemplate":"https://{host}"},"dept":{"paths":["department"],"trim":true,"default":"-"},"remoteLoc":{"paths":["location.is_remote"],"format":"bool_map","trueValue":"Remote","falseValue":"-"},"loc":{"paths":["location.name"],"trim":true,"fallbackTemplate":"{remoteLoc}"}},"collectLinkVars":["jUrl"],"columns":[{"header":"Role","template":"[{jTitle}]({jUrl})"},{"header":"Department","template":"{dept}"},{"header":"Location","template":"{loc}"}]}]}},{"match":{"hosts":["*.recruitee.com"],"hostSubdomain":{"suffix":".recruitee.com","param":"org","reserved":["www","app"]},"exactSegments":false,"pathSegments":["o",{"param":"targetSlug","charset":"pkg"}]},"twin":{"id":"recruitee","fetchUrl":"https://{host}/api/offers","kind":"json","accept":"application/json"},"extract":{"findInArray":{"arrayPath":"offers","matchField":"slug","matchTemplate":"{targetSlug}"},"vars":{"jobTitle":{"paths":["title"],"trim":true,"default":"Role"},"desc":{"paths":["description"],"format":"html_to_md"},"reqs":{"paths":["requirements"],"format":"html_to_md"}},"titleTemplate":"{jobTitle} @ {org}","bodyVar":"desc","sections":[{"heading":"Requirements","textVar":"reqs"}]}},{"match":{"hosts":["*.recruitee.com"],"hostSubdomain":{"suffix":".recruitee.com","param":"org","reserved":["www","app"]},"pathSegments":[]},"twin":{"id":"recruitee","fetchUrl":"https://{host}/api/offers","kind":"json","accept":"application/json"},"extract":{"vars":{"count":{"paths":["offers"],"format":"array_len"}},"requireVars":["count"],"titleTemplate":"{org} — Recruitee Job Board ({count} open roles)","sections":[{"heading":"","arrayPath":"offers","limit":100,"emptyText":"No open positions currently listed.","itemVars":{"oTitle":{"paths":["title"],"trim":true,"default":"Role"},"slug":{"paths":["slug"]},"rawUrl":{"paths":["careers_url"],"requireHttps":true},"oUrl":{"template":"{rawUrl}","whenVars":["rawUrl"],"fallbackTemplate":"https://{host}/o/{slug}"},"dept":{"paths":["department"],"trim":true,"default":"-"},"remoteLoc":{"paths":["remote"],"format":"bool_map","trueValue":"Remote","falseValue":"-"},"loc":{"paths":["location"],"trim":true,"fallbackTemplate":"{remoteLoc}"},"isRemote":{"paths":["remote"],"format":"bool_map","trueValue":"Remote","falseValue":""},"hybridOrOnsite":{"paths":["hybrid"],"format":"bool_map","trueValue":"Hybrid","falseValue":"On-site"},"workplace":{"template":"{isRemote}","whenVars":["isRemote"],"fallbackVar":"hybridOrOnsite"}},"collectLinkVars":["oUrl"],"columns":[{"header":"Role","template":"[{oTitle}]({oUrl})"},{"header":"Department","template":"{dept}"},{"header":"Location","template":"{loc}"},{"header":"Workplace","template":"{workplace}"}]}]}},{"match":{"anyOf":[{"hosts":["*.jobs.personio.de"],"hostSubdomain":{"suffix":".jobs.personio.de","param":"org"},"pathSegments":[]},{"hosts":["*.jobs.personio.com"],"hostSubdomain":{"suffix":".jobs.personio.com","param":"org"},"pathSegments":[]}]},"twin":{"id":"personio","fetchUrl":"https://{host}/xml?language=en","kind":"text","accept":"application/xml"},"extract":{"xml":{"mode":"items_table","requireAnyTags":["workzag-jobs","position"],"itemTag":"position","titleTemplate":"{org} — Personio Job Board ({itemCount} open roles)","emptyText":"No open positions currently listed.","limit":100,"itemVars":{"id":{"tags":["id"]},"pName":{"tags":["name"],"default":"Role"},"dept":{"tags":["department"],"default":"-"},"office":{"tags":["office"],"default":"-"},"schedule":{"tags":["schedule"],"default":"-"}},"columns":[{"header":"Role","template":"[{pName}](https://{host}/job/{id})"},{"header":"Department","template":"{dept}"},{"header":"Office","template":"{office}"},{"header":"Schedule","template":"{schedule}"}]}}}]},{"id":"bandcamp","name":"Bandcamp Albums, Tracks & Artists","category":"commerce-social","description":"Extracts Bandcamp album, track, pricing, tag, and tracklist metadata from *.bandcamp.com and bandcamp.com via MusicAlbum/MusicRecording JSON-LD and HTML-unescaped data-tralbum attributes.","domains":["*.bandcamp.com","bandcamp.com","www.bandcamp.com"],"auth_mode":"html","min_interval_ms":1000,"strict_robots":true,"exampleUrls":["https://c418.bandcamp.com/album/minecraft-volume-alpha","https://c418.bandcamp.com/track/sweden"],"htmlRoutes":[{"id":"bandcamp","match":{"hosts":["*.bandcamp.com","bandcamp.com","www.bandcamp.com"],"exactSegments":false},"mode":"bandcamp_html"}]},{"id":"bazaarvoice","name":"Bazaarvoice Product Reviews","category":"commerce-social","description":"Opt-in page-key adapter for Bazaarvoice Display API reviews; defaults OFF and falls back cleanly to HTML/JSON-LD when disabled.","domains":["api.bazaarvoice.com","www.bazaarvoice.com"],"universalEngine":true,"auth_mode":"page-key","requires_page_key_opt_in":true,"exampleUrls":["https://api.bazaarvoice.com/data/reviews.json?apiversion=5.4&passkey=lgnkpccztvv6hpje273tu0cx8&Filter=ProductId:YWSHTS&Include=Products&Stats=Reviews&Limit=5"],"routes":[{"match":{"hosts":["api.bazaarvoice.com"],"pathEquals":["/data/reviews.json","/data/display/0.2alpha/product/summary"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"jsonMode":"bazaarvoice_reviews"}}],"htmlRoutes":[{"id":"bazaarvoice","match":{"exactSegments":false},"mode":"bazaarvoice_html"}]},{"id":"bbb","name":"Better Business Bureau (BBB)","category":"commerce-social","description":"Extracts BBB business profile metadata, accreditation status, rating, contact details, and categories from public bbb.org profile pages while strictly honoring robots.txt.","domains":["bbb.org","www.bbb.org"],"auth_mode":"html","strict_robots":true,"exampleUrls":["https://www.bbb.org/us/md/linthicum-heights/profile/property-management/american-community-management-inc-0011-10073"],"htmlRoutes":[{"id":"bbb","match":{"exactSegments":false},"mode":"bbb_html"}]},{"id":"bea","name":"Bureau of Economic Analysis (BEA)","category":"finance","description":"U.S. Bureau of Economic Analysis apps.bea.gov JSON API adapter (NIPA/GDP/Regional/International) with bea.gov HTML fallback.","domains":["bea.gov","www.bea.gov","apps.bea.gov"],"auth_mode":"key","exampleUrls":["https://apps.bea.gov/api/data?method=GetDataSetList&ResultFormat=JSON","https://www.bea.gov/data/gdp/gross-domestic-product"],"routes":[{"match":{"hosts":["apps.bea.gov"],"exactSegments":true,"pathEquals":["/api/data","/API/data","/api/data/","/API/data/"]},"twin":{"fetchUrl":"{requestUrl}","defaultQueryParams":{"ResultFormat":"JSON"},"kind":"json","accept":"application/json","maxBytes":4194304,"auth_mode":"key"},"extract":{"jsonMode":"bea_json"}}],"htmlRoutes":[{"id":"bea","match":{"hosts":["bea.gov","www.bea.gov"],"exactSegments":false},"mode":"bea_html"}]},{"id":"bentobox","name":"BentoBox Restaurant Menus & Venues","category":"commerce-social","description":"Extracts restaurant menus, sections, items, prices, and FoodEstablishment metadata from BentoBox (getbento.com) sites and custom restaurant domains.","domains":["getbento.com","www.getbento.com","*.getbento.com","www.gramercytavern.com"],"universalEngine":true,"auth_mode":"html","strict_robots":true,"min_interval_ms":1000,"exampleUrls":["https://www.gramercytavern.com/dining-room-menu/","https://www.getbento.com/"],"htmlRoutes":[{"id":"bentobox","match":{"exactSegments":false},"mode":"bentobox_html"}]},{"id":"bestbuy","name":"Best Buy Products API","category":"commerce-social","description":"Extracts Best Buy product pricing, SKU, UPC/GTIN, availability, and search results via the official Best Buy Products API.","domains":["bestbuy.com","www.bestbuy.com","api.bestbuy.com"],"auth_mode":"key","exampleUrls":["https://api.bestbuy.com/v1/products/6500131.json","https://api.bestbuy.com/v1/products?format=json"],"routes":[{"match":{"hosts":["bestbuy.com","www.bestbuy.com"],"exactSegments":false,"pathSegments":["site",{"param":"slug","charset":"slug","maxLen":200},{"param":"sku","charset":"digits","stripSuffix":".p","minLen":5,"maxLen":12}]},"twin":{"fetchUrl":"https://api.bestbuy.com/v1/products/{sku}.json","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"bestbuy_json"}},{"match":{"hosts":["api.bestbuy.com"],"pathPrefix":"/v1/products"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"bestbuy_json"}}]},{"id":"bgp-asn","name":"BGP & ASN Intelligence (RIPEstat & bgp.he.net)","category":"developer","description":"Extracts BGP ASN overview and prefix announcements from RIPEstat JSON APIs and Hurricane Electric bgp.he.net pages (bounded to <= 1 MiB before parsing).","domains":["stat.ripe.net","bgp.he.net"],"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://stat.ripe.net/data/as-overview/data.json?resource=AS13335","https://bgp.he.net/AS13335"],"routes":[{"match":{"hosts":["stat.ripe.net"],"exactSegments":false,"pathPrefix":"/data/","pathSuffix":"/data.json"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"bgp_asn_ripe_json"}}],"htmlRoutes":[{"id":"bgp-asn","match":{"hosts":["bgp.he.net"],"exactSegments":false},"mode":"bgp_he_html"}]},{"id":"bicycle-blue-book","name":"Bicycle Blue Book Value Guide","category":"commerce-social","description":"Extracts Bicycle Blue Book original MSRP, private-party used estimate range, trade-in values, 12-month projected trend, and model lists.","domains":["bicyclebluebook.com","www.bicyclebluebook.com"],"auth_mode":"html","min_interval_ms":1000,"strict_robots":true,"exampleUrls":["https://www.bicyclebluebook.com/value-guide/cyclocross/all-city/macho-king-ltd/2017","https://www.bicyclebluebook.com/value-guide/cyclocross/all-city"],"htmlRoutes":[{"id":"bicycle-blue-book","match":{"anyOf":[{"pathEquals":["/value-guide"]},{"pathPrefix":"/value-guide/"},{"pathPrefix":"/marketplace/"},{"pathPrefix":"/listing/"}]},"mode":"bicycle_blue_book_html"}]},{"id":"bicycle-brake-docs","name":"Bicycle Brake Docs & Rotor/Pad Specs","category":"commerce-social","description":"Extracts hydraulic brake fluid type, piston count, rotor diameter/thickness, pad compatibility, and bleed manuals from Magura, Hayes, Tektro, and TRP.","domains":["magura.com","www.magura.com","hayesbicycle.com","www.hayesbicycle.com","tektro.com","www.tektro.com","trpcycling.com","www.trpcycling.com"],"auth_mode":"html","exampleUrls":["https://magura.com/product/mt7-pro/","https://hayesbicycle.com/collections/disc-brakes","https://tektro.com/en/product/315","https://trpcycling.com/collections/brakes"],"htmlRoutes":[{"id":"bicycle-brake-docs","match":{"exactSegments":false},"mode":"bicycle_brake_docs_html"}]},{"id":"bicycle-tire-specs","name":"Bicycle Tire Technical Specifications","category":"commerce-social","description":"Extracts ISO 5775 validated ETRTO sizes, imperial/French tire sizes, TPI, compound, bead, weight, and tubeless specs from Maxxis, Schwalbe, Continental, WTB, Kenda, and Teravail.","domains":["maxxis.com","www.maxxis.com","schwalbe.com","www.schwalbe.com","schwalbetires.com","www.schwalbetires.com","continental-tires.com","www.continental-tires.com","wtb.com","www.wtb.com","kendatire.com","bicycle.kendatire.com","teravail.com","www.teravail.com"],"auth_mode":"html","exampleUrls":["https://www.maxxis.com/us/tire/minion-dhf/","https://www.schwalbetires.com/Magic-Mary-11654598.01","https://www.wtb.com/products/vigilante","https://www.teravail.com/products/cannonball-gen-2-tire","https://www.continental-tires.com/products/bicycle/tires/grand-prix-5000/","https://bicycle.kendatire.com/en-us/find-a-tire/"],"htmlRoutes":[{"id":"bicycle-tire-specs","match":{"exactSegments":false},"mode":"bicycle_tire_specs_html"}]},{"id":"bicycleretailer","name":"Bicycle Retailer & Industry News","category":"commerce-social","description":"Extracts Drupal .node-article body, .view-content listings, and author/publishedTime metadata from bicycleretailer.com while stripping sidebar ads and leaving /rss.xml to feed XML parsing.","domains":["www.bicycleretailer.com","bicycleretailer.com"],"exampleUrls":["https://www.bicycleretailer.com/industry-news/2026/11/25/preliminary-analysis-industry-spared-new-recommended-tariffs","https://www.bicycleretailer.com/industry-news"],"htmlRoutes":[{"id":"bicycleretailer","mode":"dom","match":{"exactSegments":false,"reservedFirstSegment":["admin","user"],"excludeSegmentSuffixes":[".xml",".rss",".atom"]},"vars":{"title":{"cssText":["article.node-article h1","main h1","h1","title"],"metaKeys":["og:title"],"trim":true},"author":{"metaKeys":["author","article:author"],"trim":true},"publishedTime":{"metaKeys":["article:published_time"],"trim":true},"body":{"cssHtmlToMd":["article.node-article .field-name-body",".node-article .field-name-body",".field-name-body",".view-content","article.node-article","main"],"format":"strip_leading_h1","trim":true}},"requireVars":["title"],"titleTemplate":"{title}","authorVar":"author","publishedTimeVar":"publishedTime","bodyVar":"body","preserveBodyLinksFromVar":"body"}]},{"id":"big-cartel","name":"Big Cartel Storefronts & Products","category":"commerce-social","description":"Extracts Big Cartel /products.json catalogs and /product/{slug}.js product twins without colliding with Shopify /products.json, plus storefront HTML/JSON-LD fallback.","domains":["shop.bigcartel.com"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://shop.bigcartel.com/product/buy-from-artists-tote-bag.js","https://shop.bigcartel.com/products.json"],"routes":[{"match":{"anyOf":[{"hosts":["shop.bigcartel.com"],"pathEquals":["/products.json"]},{"hostSubdomain":{"suffix":".bigcartel.com","param":"shopSub","reserved":["www","my","api","developers","blog","assets","help"]},"pathEquals":["/products.json"]}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"commerceMode":"big_cartel_json"}},{"match":{"excludeHosts":["bigcartel.com","www.bigcartel.com","api.bigcartel.com","my.bigcartel.com","developers.bigcartel.com","blog.bigcartel.com","assets.bigcartel.com","help.bigcartel.com"],"exactSegments":true,"pathSuffix":".js","pathSegments":["product",{"param":"slug","charset":"pkg","stripSuffix":".js","minLen":1,"maxLen":160}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"commerceMode":"big_cartel_json"}}],"htmlRoutes":[{"id":"big-cartel","match":{"exactSegments":false},"mode":"big_cartel_html"}]},{"id":"bigcommerce-store","name":"BigCommerce Stencil Storefronts","category":"commerce-social","description":"Extracts BigCommerce Stencil BCData, JSON-LD, Microdata, cart-form options, product specs, category grids, and bounded /xmlsitemap.php product sitemaps.","domains":["*.mybigcommerce.com","www.bigcommerce.com","ascolour.com"],"universalEngine":true,"exampleUrls":["https://ascolour.com/xmlsitemap.php","https://ascolour.com/classic-organic-tee-5026g/"],"routes":[{"match":{"exactSegments":true,"pathEquals":["/xmlsitemap.php"]},"twin":{"id":"bigcommerce-store","fetchUrl":"{requestUrl}","kind":"text","accept":"application/xml","maxBytes":4194304},"extract":{"commerceMode":"bigcommerce_sitemap"}}],"htmlRoutes":[{"id":"bigcommerce-store","match":{"exactSegments":false},"mode":"bigcommerce_html"}]},{"id":"bike-index","name":"Bike Index Registry","category":"public-records","description":"Public Bike Index REST API v3 adapter for bicycle registrations, stolen reports, and search queries with HTML detail fallback.","domains":["bikeindex.org","www.bikeindex.org"],"auth_mode":"pub","exampleUrls":["https://bikeindex.org/api/v3/search?page=1&per_page=5","https://bikeindex.org/api/v3/bikes/3550041","https://bikeindex.org/bikes/3550041"],"routes":[{"match":{"hosts":["bikeindex.org","www.bikeindex.org"],"pathEquals":["/api/v3/search","/api/v3/search/"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"bike_index_json"}},{"match":{"hosts":["bikeindex.org","www.bikeindex.org"],"pathSegments":["api","v3","bikes",{"param":"bikeId","charset":"digits","minLen":1,"maxLen":16}]},"twin":{"fetchUrl":"https://bikeindex.org/api/v3/bikes/{bikeId}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"bike_index_json"}},{"match":{"hosts":["bikeindex.org","www.bikeindex.org"],"pathSegments":["bikes",{"param":"bikeId","charset":"digits","minLen":1,"maxLen":16}]},"twin":{"fetchUrl":"https://bikeindex.org/api/v3/bikes/{bikeId}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"bike_index_json"}}],"htmlRoutes":[{"id":"bike-index","match":{"exactSegments":false},"mode":"bike_index_html"}]},{"id":"bikereg-usacycling","name":"BikeReg & USA Cycling Events & Results","category":"commerce-social","description":"Extracts BikeReg event search JSON (/api/search with ASP.NET /Date()/ timestamps), USA Cycling Sport80 Inertia data-page events and results, and unchallenged BikeReg HTML while rejecting Cloudflare challenges.","domains":["bikereg.com","www.bikereg.com","usacycling.org","www.usacycling.org","usacycling.sport80.com"],"universalEngine":false,"auth_mode":"pub","exampleUrls":["https://www.bikereg.com/api/search?name=Hush%20Money","https://usacycling.sport80.com/pub/e_locator/events/find?from_date=today","https://usacycling.sport80.com/pub/results"],"routes":[{"match":{"hosts":["bikereg.com","www.bikereg.com"],"exactSegments":true,"pathSegments":["api","search"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"bikereg_json"}}],"htmlRoutes":[{"id":"bikereg-usacycling","match":{"hosts":["bikereg.com","www.bikereg.com","usacycling.org","www.usacycling.org","usacycling.sport80.com"],"exactSegments":false},"mode":"bikereg_usacycling_html"}]},{"id":"biorxiv-medrxiv","name":"bioRxiv & medRxiv Preprints","category":"research-health","description":"Extracts bioRxiv and medRxiv preprint metadata, versions, abstracts, and JATS XML links from api.biorxiv.org JSON and bioRxiv/medRxiv HTML (no cross-domain medrxiv.org -> api.biorxiv.org twin).","domains":["api.biorxiv.org","www.biorxiv.org","biorxiv.org","www.medrxiv.org","medrxiv.org"],"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://api.biorxiv.org/details/biorxiv/10.1101/2020.09.02.278911/na/json","https://api.biorxiv.org/details/medrxiv/10.1101/2020.05.28.20116129/na/json","https://www.biorxiv.org/content/10.1101/2020.09.02.278911v1"],"routes":[{"match":{"hosts":["api.biorxiv.org"],"pathPrefix":"/details/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"biorxiv_medrxiv_json"}}],"htmlRoutes":[{"id":"biorxiv-medrxiv","match":{"hosts":["www.biorxiv.org","biorxiv.org","www.medrxiv.org","medrxiv.org"],"exactSegments":false},"mode":"biorxiv_medrxiv_html"}]},{"id":"bis-entity-list","name":"BIS Export Administration Regulations & Entity List","category":"public-records","description":"Extracts Bureau of Industry and Security (BIS) EAR Part 744 / Entity List guidance and enforcement press releases from www.bis.gov, bis.gov, and media.bis.gov.","domains":["www.bis.gov","bis.gov","media.bis.gov"],"auth_mode":"pub","exampleUrls":["https://www.bis.gov/about-bis","https://www.bis.gov/press-release/bis-issues-rule-addressing-remote-access-american-super-intelligence-technology","https://www.bis.gov/press-release/bis-reaches-administrative-enforcement-settlement-lambda-research-corporation"],"htmlRoutes":[{"id":"bis-entity-list","match":{"hosts":["www.bis.gov","bis.gov","media.bis.gov"],"exactSegments":false},"mode":"bis_entity_list_html"}]},{"id":"bitbucket-cloud","name":"Bitbucket Cloud","category":"developer","description":"Extracts repository, pull request, and issue metadata from Bitbucket Cloud REST 2.0 JSON endpoints and bitbucket.org repository URLs with CSR SPA shell guards.","domains":["api.bitbucket.org","bitbucket.org"],"auth_mode":"pub","exampleUrls":["https://api.bitbucket.org/2.0/repositories/atlassian/aui","https://bitbucket.org/atlassian/aui"],"routes":[{"match":{"hosts":["api.bitbucket.org"],"pathPrefix":"/2.0/repositories/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"bitbucket_json"}},{"match":{"hosts":["bitbucket.org"],"exactSegments":true,"pathSegments":[{"param":"ws","charset":"pkg","reserved":["account","dashboard","repo","product","features","enterprise","blog","plans","security","support"]},{"param":"repo","charset":"pkg"}]},"twin":{"fetchUrl":"https://api.bitbucket.org/2.0/repositories/{ws}/{repo}","kind":"json","accept":"application/json","maxBytes":1048576},"extract":{"jsonMode":"bitbucket_json"}}],"htmlRoutes":[{"id":"bitbucket-cloud","match":{"hosts":["bitbucket.org"],"exactSegments":false},"mode":"bitbucket_html"}]},{"id":"blackboard-wcm","name":"Blackboard WCM & SchoolMessenger Presence","category":"public-records","description":"Extracts Blackboard Web Community Manager (Schoolwires) and SchoolMessenger Presence K-12 district news, calendars, and staff directories while excluding Finalsite /fs/ sites.","domains":["www.bhusd.org","bhusd.org","www.neshaminy.org"],"universalEngine":true,"auth_mode":"html","strict_robots":true,"min_interval_ms":2000,"exampleUrls":["https://www.neshaminy.org/our_district/neshaminy_newsroom","https://www.bhusd.org/media/filter/news"],"htmlRoutes":[{"id":"blackboard-wcm","match":{"excludeHosts":["www.finalsite.com","finalsite.com","www.greenwichschools.org","www.choate.edu"],"exactSegments":false},"mode":"blackboard_wcm_html"}]},{"id":"bloomreach-discovery","name":"Bloomreach Discovery On-Site Search","category":"commerce-social","description":"Opt-in page-key adapter for Bloomreach Discovery core search JSON endpoints; defaults OFF and falls back cleanly to HTML/JSON-LD when disabled.","domains":["core.dxpapi.com"],"universalEngine":true,"auth_mode":"page-key","requires_page_key_opt_in":true,"exampleUrls":["https://core.dxpapi.com/api/v1/core/?account_id=6276&auth_key=jazzhands&domain_key=example_com&request_type=search&search_type=keyword&q=shoes&fl=pid,title,price,url&rows=10&start=0&url=https://www.example.com/search"],"routes":[{"match":{"hostSubdomain":{"suffix":".dxpapi.com","param":"apiHost"},"pathEquals":["/api/v1/core","/api/v1/core/"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"jsonMode":"bloomreach_discovery"}}],"htmlRoutes":[{"id":"bloomreach-discovery","match":{"exactSegments":false},"mode":"bloomreach_discovery_html"}]},{"id":"bls","name":"Bureau of Labor Statistics (BLS)","category":"public-records","description":"U.S. Bureau of Labor Statistics publicAPI v1 (pub) and v2 (key) time-series JSON adapter with bls.gov HTML fallback.","domains":["bls.gov","www.bls.gov","data.bls.gov","api.bls.gov"],"auth_mode":"pub","strict_robots":true,"exampleUrls":["https://www.bls.gov/cpi/","https://www.bls.gov/ooh/"],"routes":[{"match":{"hosts":["api.bls.gov"],"exactSegments":false,"pathPrefix":"/publicAPI/v1/timeseries/data"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"pub"},"extract":{"jsonMode":"bls_json"}},{"match":{"hosts":["api.bls.gov"],"exactSegments":false,"pathPrefix":"/publicAPI/v2/timeseries/data"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"key"},"extract":{"jsonMode":"bls_json"}}],"htmlRoutes":[{"id":"bls","match":{"hosts":["bls.gov","www.bls.gov","data.bls.gov"],"exactSegments":false},"mode":"bls_html"}]},{"id":"bluesky-thread","name":"Bluesky ATProto Post Threads","category":"commerce-social","description":"Upgrades bsky.app post URLs to public.api.bsky.app ATProto getPostThread JSON with replies and embeds.","domains":["bsky.app","staging.bsky.app"],"exampleUrls":["https://bsky.app/profile/golang.org/post/3mzyghkrmjh2y"],"match":{"exactSegments":false,"pathSegments":["profile",{"param":"actor","charset":"url_seg"},"post",{"param":"rkey","charset":"pkg"}]},"twin":{"id":"bluesky-thread","fetchUrl":"https://public.api.bsky.app/xrpc/app.bsky.feed.getPostThread?uri=at%3A%2F%2F{actor}%2Fapp.bsky.feed.post%2F{rkey}&depth=6","kind":"json","accept":"application/json"},"extract":{"rootPath":"thread","requireFields":["post.record.text"],"vars":{"handle":{"paths":["post.author.handle"],"fallbackTemplate":"{actor}"},"displayName":{"paths":["post.author.displayName"],"fallbackTemplate":"{handle}"},"text":{"paths":["post.record.text"],"format":"plain_text","trim":true},"desc":{"paths":["post.record.text"],"trim":true,"sliceMax":220},"createdAt":{"paths":["post.record.createdAt"]},"createdAtShort":{"paths":["post.record.createdAt"],"replaceAll":{"from":"T","to":" "},"sliceMax":16},"postedPrefix":{"template":"{createdAtShort} UTC · ","whenVars":["createdAtShort"]},"likes":{"paths":["post.likeCount"],"default":"0"},"reposts":{"paths":["post.repostCount"],"default":"0"},"extUri":{"paths":["post.embed.external.uri"]},"extTitle":{"paths":["post.embed.external.title"],"fallbackTemplate":"{extUri}"},"extDesc":{"paths":["post.embed.external.description"]},"extDescSuffix":{"template":" — {extDesc}","whenVars":["extDesc"]},"linkedEmbed":{"template":"> **Linked**: [{extTitle}]({extUri}){extDescSuffix}","whenVars":["extUri"]}},"titleTemplate":"{displayName} (@{handle}) on Bluesky","descriptionVar":"desc","authorTemplate":"@{handle}","publishedTimeVar":"createdAt","bodyVar":"text","footerItalicTemplate":"Posted {postedPrefix}{likes} likes · {reposts} reposts","sections":[{"heading":"","textVar":"linkedEmbed"},{"heading":"","listArrayPath":"post.embed.images","limit":10,"requireItemVar":"imgAlt","itemVars":{"imgAlt":{"paths":["alt"],"trim":true}},"itemTemplate":"*Image alt*: {imgAlt}"},{"heading":"Replies","listArrayPath":"replies","limit":15,"requireItemVar":"replyText","itemVars":{"replyAuthor":{"paths":["post.author.handle"],"default":"user"},"replyText":{"paths":["post.record.text"],"trim":true,"replaceAll":{"from":"\n","to":" "}}},"itemTemplate":"**@{replyAuthor}**: {replyText}"}]}},{"id":"boarddocs","name":"Diligent BoardDocs Public Meeting Portals","category":"public-records","description":"Extracts public school board and municipal BoardDocs meeting lists, agendas, and HTML views while detecting CloudFront blocks.","domains":["go.boarddocs.com"],"auth_mode":"pub","strict_robots":true,"exampleUrls":["https://go.boarddocs.com/ca/sandi/Board.nsf/BD-GetMeetingsList","https://go.boarddocs.com/ca/sandi/Board.nsf/Public"],"routes":[{"match":{"exactSegments":true,"pathSegments":[{"param":"state","charset":"alnum_dash","minLen":2,"maxLen":8},{"param":"org","charset":"alnum_dash","minLen":2,"maxLen":48},"Board.nsf",{"param":"action","allowValues":["BD-GetMeetingsList","BD-GetAgenda","BD-GetAgendaItem"]}]},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"application/xml","maxBytes":4194304},"extract":{"textMode":"boarddocs_text"}}],"htmlRoutes":[{"id":"boarddocs","match":{"exactSegments":false},"mode":"boarddocs_html"}]},{"id":"bosch-ebike-help","name":"Bosch eBike Systems Help Center","category":"developer","description":"Bosch eBike error codes from help.bosch-ebike.com via the keyless public /v2/error_code JSON endpoint the Help Center SPA renders (code / severity / component / description / remedy per system generation), with a bounded HTML fallback for SSR help articles that strips data:image blobs and dodo-service-include chrome and never presents the loading SPA shell as content. Never calls the robots-disallowed /api/* paths.","domains":["help.bosch-ebike.com"],"auth_mode":"pub","exampleUrls":["https://help.bosch-ebike.com/en/help-center/error/6A0004","https://help.bosch-ebike.com/help-center/error/6A0004"],"routes":[{"match":{"hosts":["help.bosch-ebike.com"],"anyOf":[{"pathSegments":[{"param":"lang","allowValues":["cs","da","de","en","es","fr","it","nl","no","pl","sv"]},"help-center","error",{"param":"code","charset":"hex","minLen":3,"maxLen":6,"transform":"upper"}]},{"optionalLeadingLocale":true,"defaults":{"lang":"en"},"pathSegments":["help-center","error",{"param":"code","charset":"hex","minLen":3,"maxLen":6,"transform":"upper"}]},{"defaults":{"lang":"en"},"pathSegments":["er",{"param":"code","charset":"hex","minLen":3,"maxLen":6,"transform":"upper"}]}]},"twin":{"fetchUrl":"https://help.bosch-ebike.com/v2/error_code?externalID={code}&languageId={lang}","kind":"json","accept":"application/json","maxBytes":524288},"extract":{"jsonMode":"bosch_ebike_error_code_json"}}],"htmlRoutes":[{"id":"bosch-ebike-help","match":{"exactSegments":false},"mode":"bosch_help_html"}]},{"id":"branded-tracking-pack","name":"Branded Tracking Pack (Narvar / Route / ParcelPanel)","category":"commerce-social","description":"Extracts hydrated Narvar, ParcelPanel, Route, Malomo, and Wonderment tracking pages while strictly rejecting empty CSR shells such as unhydrated Route pages.","domains":["*.narvar.com","tracking.route.com"],"universalEngine":true,"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://tracking.narvar.com/asics/tracking"],"htmlRoutes":[{"id":"branded-tracking-pack","match":{"exactSegments":false},"mode":"branded_tracking_pack_html"}]},{"id":"brightcove","name":"Brightcove Playback & Player","category":"commerce-social","description":"Opt-in page-key adapter for Brightcove Playback API v1; defaults OFF and falls back cleanly to Brightcove player HTML extraction.","domains":["edge.api.brightcove.com","players.brightcove.net"],"auth_mode":"page-key","requires_page_key_opt_in":true,"exampleUrls":["https://edge.api.brightcove.com/playback/v1/accounts/1752604059001/videos/4093643993001","https://players.brightcove.net/1752604059001/default_default/index.html?videoId=4093643993001"],"routes":[{"match":{"hosts":["edge.api.brightcove.com"],"exactSegments":true,"pathSegments":["playback","v1","accounts",{"param":"accountId","charset":"digits","minLen":4,"maxLen":24},"videos",{"param":"videoId","charset":"url_seg","minLen":4,"maxLen":64}]},"twin":{"id":"brightcove","fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"jsonMode":"brightcove_playback_json"}}],"htmlRoutes":[{"id":"brightcove","match":{"exactSegments":false},"mode":"brightcove_html"}]},{"id":"brightspot","name":"Brightspot Publishing CMS","category":"commerce-social","description":"Extracts NewsArticle JSON-LD and Brightspot RichText article bodies across Brightspot-powered newsrooms.","domains":["www.latimes.com","news.byu.edu"],"universalEngine":true,"auth_mode":"html","exampleUrls":["https://www.latimes.com/travel/story/2023-10-19/los-angeles-neighborhood-city-guides"],"htmlRoutes":[{"id":"brightspot","match":{"exactSegments":false},"mode":"brightspot_html"}]},{"id":"browser-addons-amo-cws","name":"Firefox AMO & Chrome Web Store","category":"developer","description":"Extracts browser extension metadata, versions, permissions, and user ratings from Firefox Add-ons v5 JSON API and Chrome Web Store detail HTML (full 2 MiB scan).","domains":["addons.mozilla.org","chromewebstore.google.com"],"auth_mode":"pub","exampleUrls":["https://addons.mozilla.org/api/v5/addons/addon/ublock-origin/","https://chromewebstore.google.com/detail/bitwarden-password-manage/nngceckbapebfimnlniiiahkandclblb"],"routes":[{"match":{"hosts":["addons.mozilla.org"],"pathPrefix":"/api/v5/addons/addon/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":1048576},"extract":{"jsonMode":"amo_addon_json"}},{"match":{"hosts":["addons.mozilla.org"],"optionalLeadingLocale":true,"exactSegments":true,"pathSegments":["firefox","addon",{"param":"slug","charset":"pkg"}]},"twin":{"fetchUrl":"https://addons.mozilla.org/api/v5/addons/addon/{slug}/","kind":"json","accept":"application/json","maxBytes":1048576},"extract":{"jsonMode":"amo_addon_json"}}],"htmlRoutes":[{"id":"browser-addons-amo-cws","match":{"hosts":["chromewebstore.google.com"],"pathPrefix":"/detail/"},"mode":"chrome_web_store_html"}]},{"id":"bts-transtats","name":"BTS TranStats & Open Data","category":"public-records","description":"Bureau of Transportation Statistics (data.bts.gov Socrata views/resource/catalog JSON + www.transtats.bts.gov HTML tables with TranStats error page rejection).","domains":["data.bts.gov","transtats.bts.gov","www.transtats.bts.gov"],"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://data.bts.gov/api/views/crem-w557.json","https://data.bts.gov/resource/crem-w557.json?$limit=2","https://www.transtats.bts.gov/Tables.asp?QO_VQ=EFD&QO_anzr=Nv4"],"routes":[{"match":{"hosts":["data.bts.gov"],"anyOf":[{"pathPrefix":"/api/views/","pathSuffix":".json"},{"pathPrefix":"/resource/","pathSuffix":".json"},{"pathEquals":["/api/catalog/v1"]}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"bts_transtats_json"}},{"match":{"hosts":["data.bts.gov"],"minSegments":2,"anyOf":[{"exactSegments":false,"pathSegments":["d",{"param":"viewId","charset":"socrata_4x4","transform":"lower"}]},{"scanSegment":{"lastOrBeforeLiteral":"about_data","param":"viewId","charset":"socrata_4x4","transform":"lower"}}]},"twin":{"fetchUrl":"https://data.bts.gov/api/views/{viewId}.json","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"bts_transtats_json"}}],"htmlRoutes":[{"id":"bts-transtats","match":{"hosts":["transtats.bts.gov","www.transtats.bts.gov"],"exactSegments":false},"mode":"bts_transtats_html"}]},{"id":"bugzilla","name":"Bugzilla Issue Tracker","category":"developer","description":"Universal Bugzilla extractor supporting direct /rest/bug/ JSON endpoints and robots-compliant /show_bug.cgi SSR HTML extraction without rewriting /show_bug.cgi to /rest/.","domains":["bugzilla.kernel.org","bugzilla.mozilla.org"],"universalEngine":true,"auth_mode":"pub","min_interval_ms":3000,"exampleUrls":["https://bugzilla.kernel.org/rest/bug/218000","https://bugzilla.kernel.org/show_bug.cgi?id=218000","https://bugzilla.mozilla.org/show_bug.cgi?id=1800000"],"routes":[{"match":{"anyOf":[{"pathPrefix":"/rest/bug/"},{"pathPrefix":"/bugzilla/rest/bug/"}],"excludeSegmentSuffixes":[".html",".htm"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"bugzilla_json"}}],"htmlRoutes":[{"id":"bugzilla","match":{"anyOf":[{"pathEquals":["/show_bug.cgi","/bugzilla/show_bug.cgi"],"queryParams":[{"name":"id","param":"bugId","charset":"pkg"}]}]},"mode":"bugzilla_html"}]},{"id":"bullhorn-career-portal","name":"Bullhorn Career Portal","category":"jobs","description":"Extracts open JobOrder listings from public-rest*.bullhornstaffing.com REST endpoints and hydrated Bullhorn Career Portal pages while rejecting errors.badCorpToken and empty results.","domains":["*.bullhornstaffing.com"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://public-rest91.bullhornstaffing.com/rest-services/1VCNF4/search/JobOrder?query=(isOpen:1)&fields=id,title,publishedCategory,address,employmentType,dateLastPublished&count=25"],"routes":[{"match":{"hostSubdomain":{"suffix":".bullhornstaffing.com","param":"cluster","reserved":["www","login","auth","static"]},"pathPrefix":"/rest-services/","pathContainsSegment":"JobOrder","exactSegments":false},"twin":{"id":"bullhorn-career-portal","fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"bullhorn_joborder_json"}}],"htmlRoutes":[{"id":"bullhorn-career-portal","mode":"bullhorn_portal_html","match":{"exactSegments":false}}]},{"id":"bumm-de","name":"Busch & Mueller (bumm.de)","category":"commerce-social","description":"Extracts TYPO3 JSON-LD Product metadata, table.attributes-table technical specs, and PDF mounting manual links from bumm.de product pages.","domains":["bumm.de","www.bumm.de"],"exampleUrls":["https://bumm.de/en/product-detail/iq-xl-highbeam/","https://bumm.de/de/produktdetail/briq-s/"],"htmlRoutes":[{"id":"bumm-de","mode":"dom","match":{"optionalLeadingLocale":true,"exactSegments":false,"reservedFirstSegment":["typo3"],"anyOf":[{"pathSegments":["product-detail",{"param":"slug","charset":"url_seg","minLen":1,"maxLen":160}]},{"pathSegments":["produktdetail",{"param":"slug","charset":"url_seg","minLen":1,"maxLen":160}]},{"pathSegments":["products","detail",{"param":"slug","charset":"url_seg","minLen":1,"maxLen":160}]}]},"jsonLdTypes":["Product"],"vars":{"title":{"jsonLdPaths":["name"],"cssText":["main h1","h1","title"],"trim":true},"brand":{"jsonLdPaths":["brand.name","brand"],"trim":true},"sku":{"jsonLdPaths":["sku"],"trim":true},"price":{"jsonLdPaths":["offers.price","offers.0.price"],"trim":true},"currency":{"jsonLdPaths":["offers.priceCurrency","offers.0.priceCurrency"],"trim":true},"body":{"cssHtmlToMd":["main",".product-detail","body"],"format":"strip_leading_h1","trim":true}},"requireVars":["title"],"titleTemplate":"{title}","bullets":[{"label":"Brand","template":"{brand}","whenVar":"brand"},{"label":"SKU","template":"`{sku}`","whenVar":"sku"},{"label":"Price","template":"{price} {currency}","whenVar":"price"}],"bodyVar":"body","preserveBodyLinksFromVar":"body"}]},{"id":"bundlephobia-packagephobia","name":"Bundlephobia & Packagephobia","category":"developer","description":"Extracts npm bundle minified/gzip sizes and install size metrics from bundlephobia.com and packagephobia.com with Vercel Security Checkpoint / 429 HTML shell rejection.","domains":["bundlephobia.com","packagephobia.com"],"auth_mode":"pub","exampleUrls":["https://bundlephobia.com/api/size?package=lodash@4.17.21","https://bundlephobia.com/package/lodash@4.17.21"],"routes":[{"match":{"hosts":["bundlephobia.com"],"exactSegments":true,"pathEquals":["/api/size"],"queryParams":[{"name":"package","param":"pkg","charset":"safe_subpath","minLen":1,"maxLen":214}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":1048576},"extract":{"jsonMode":"bundlephobia_json"}},{"match":{"hosts":["bundlephobia.com"],"pathPrefix":"/package/","pathSegments":["package",{"param":"pkg","charset":"safe_subpath","greedy":true}]},"twin":{"fetchUrl":"https://bundlephobia.com/api/size?package={pkg}","kind":"json","accept":"application/json","maxBytes":1048576},"extract":{"jsonMode":"bundlephobia_json"}},{"match":{"hosts":["packagephobia.com"],"exactSegments":true,"pathEquals":["/v2/api.json"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":1048576},"extract":{"jsonMode":"packagephobia_json"}}],"htmlRoutes":[{"id":"bundlephobia-packagephobia","match":{"hosts":["bundlephobia.com","packagephobia.com"],"exactSegments":false},"mode":"bundle_packagephobia_html"}]},{"id":"canvas-public-courses","name":"Canvas LMS Public Courses","category":"public-records","description":"Extracts public Instructure Canvas LMS courses via /api/v1/courses JSON and public syllabus HTML while classifying SAML SSO redirects as login_wall and 503 maintenance shells as non-active.","domains":["*.instructure.com"],"universalEngine":true,"auth_mode":"pub","strict_robots":true,"min_interval_ms":1000,"exampleUrls":["https://mit.instructure.com/search/all_courses","https://mit.instructure.com/api/v1/courses/694"],"routes":[{"match":{"pathPrefix":"/api/v1/courses"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"canvas_course_json"}}],"htmlRoutes":[{"id":"canvas-public-courses","match":{"exactSegments":false},"mode":"canvas_public_html"}]},{"id":"cargo-ebike-oems","name":"Cargo E-Bike OEMs (Yuba, Xtracycle, Tern, Riese & Muller)","category":"commerce-social","description":"Extracts cargo e-bike payload, GVWR, battery Wh, motor torque/power, and product specifications from Yuba, Xtracycle, Tern, and Riese & Muller.","domains":["yubabikes.com","www.yubabikes.com","xtracycle.com","www.xtracycle.com","ternbicycles.com","www.ternbicycles.com","r-m.de","www.r-m.de"],"auth_mode":"html","min_interval_ms":1000,"exampleUrls":["https://yubabikes.com/shop/bikes/longtail/","https://xtracycle.com/products/swoop-asm-family-cargo","https://www.ternbicycles.com/en/bikes/473/gsd","https://www.r-m.de/en-en/bikes/nevo5/"],"htmlRoutes":[{"id":"cargo-ebike-oems","match":{"exactSegments":false},"mode":"cargo_ebike_oems_html"}]},{"id":"carrier-tracking-official","name":"Official Carrier Tracking APIs (USPS, UPS, FedEx)","category":"commerce-social","description":"Keyed OAuth Bearer official tracking APIs for USPS (/tracking/), UPS (/api/track/v1/details with transactionSrc/transId), and FedEx (POST /track/v1/trackingnumbers).","domains":["onlinetools.ups.com","wwwcie.ups.com","apis.fedex.com","apis-sandbox.fedex.com"],"universalEngine":true,"auth_mode":"key","min_interval_ms":1000,"exampleUrls":["https://apis.usps.com/tracking/v3/tracking/9400111899223344556677","https://onlinetools.ups.com/api/track/v1/details/1Z999AA10123456784","https://apis.fedex.com/track/v1/trackingnumbers"],"routes":[{"match":{"hosts":["apis.usps.com","apis-tem.usps.com"],"pathPrefix":"/tracking/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","method":"GET","auth_mode":"key","maxBytes":1048576},"extract":{"jsonMode":"carrier_tracking_json"}},{"match":{"hosts":["onlinetools.ups.com","wwwcie.ups.com"],"pathPrefix":"/api/track/v1/details"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","method":"GET","headers":{"transactionSrc":"edgefetch"},"auth_mode":"key","maxBytes":1048576},"extract":{"jsonMode":"carrier_tracking_json"}},{"match":{"hosts":["apis.fedex.com","apis-sandbox.fedex.com"],"pathPrefix":"/track/v1/trackingnumbers","queryParams":[{"name":"trackingNumber","param":"trackingNumber","charset":"alnum_dash","optional":true,"default":"784592018372"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","method":"POST","contentType":"application/json","requestBody":"{\"includeDetailedScans\":true,\"trackingInfo\":[{\"trackingNumberInfo\":{\"trackingNumber\":\"{trackingNumber}\"}}]}","auth_mode":"key","maxBytes":1048576},"extract":{"jsonMode":"carrier_tracking_json"}}]},{"id":"cbo","name":"Congressional Budget Office (CBO)","category":"public-records","description":"Extracts CBO publication and cost-estimate RSS feeds and HTML publication pages while cleanly classifying DataDome JS challenges as non-active.","domains":["www.cbo.gov","cbo.gov"],"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://www.cbo.gov/publications/all/rss.xml","https://www.cbo.gov/publication/62899"],"routes":[{"match":{"pathPrefix":"/publications/","pathSuffix":".xml"},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"application/rss+xml","maxBytes":1048576},"extract":{"textMode":"cbo_rss_xml"}}],"htmlRoutes":[{"id":"cbo","match":{"exactSegments":false},"mode":"cbo_html"}]},{"id":"cbp-cross-rulings","name":"CBP CROSS Customs Rulings","category":"public-records","description":"Extracts U.S. Customs and Border Protection CROSS ruling search and ruling detail JSON endpoints while rejecting unhydrated Angular CSR shells and security-parameter 403 blocks.","domains":["rulings.cbp.gov"],"auth_mode":"pub","exampleUrls":["https://rulings.cbp.gov/api/ruling/N310000","https://rulings.cbp.gov/api/ruling/N310001"],"routes":[{"match":{"hosts":["rulings.cbp.gov"],"pathPrefix":"/api/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"cbp_cross_json"}}],"htmlRoutes":[{"id":"cbp-cross-rulings","match":{"hosts":["rulings.cbp.gov"],"exactSegments":false},"mode":"cbp_cross_html"}]},{"id":"cdc-wonder-healthdata","name":"CDC WONDER & HealthData.gov","category":"research-health","description":"HealthData.gov and data.cdc.gov Socrata views/resource/catalog JSON adapter (coexisting cleanly with socrata.yaml) plus CDC WONDER HTML.","domains":["healthdata.gov","www.healthdata.gov","wonder.cdc.gov"],"universalEngine":true,"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://healthdata.gov/api/views/j8mb-icvb.json","https://data.cdc.gov/api/views/9bhg-hcku.json","https://wonder.cdc.gov/ucd-icd10.html"],"routes":[{"match":{"hosts":["healthdata.gov","www.healthdata.gov","data.cdc.gov"],"anyOf":[{"pathPrefix":"/api/views/","pathSuffix":".json"},{"pathPrefix":"/resource/","pathSuffix":".json"},{"pathEquals":["/api/catalog/v1"]}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"cdc_healthdata_json"}},{"match":{"hosts":["healthdata.gov","www.healthdata.gov"],"minSegments":2,"anyOf":[{"exactSegments":false,"pathSegments":["d",{"param":"viewId","charset":"socrata_4x4","transform":"lower"}]},{"scanSegment":{"lastOrBeforeLiteral":"about_data","param":"viewId","charset":"socrata_4x4","transform":"lower"}}]},"twin":{"fetchUrl":"https://{host}/api/views/{viewId}.json","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"cdc_healthdata_json"}}],"htmlRoutes":[{"id":"cdc-wonder-healthdata","match":{"hosts":["wonder.cdc.gov","healthdata.gov","www.healthdata.gov"],"exactSegments":false},"mode":"cdc_wonder_html"}]},{"id":"census-foreign-trade","name":"U.S. Census Foreign Trade (USA Trade Online)","category":"public-records","description":"Covers USA Trade Online portal pages (usatradeonline.census.gov, usatrade.census.gov) disjoint from census.yaml, which handles api.census.gov/data/timeseries/intltrade/* via census_json.","domains":["usatradeonline.census.gov","usatrade.census.gov"],"auth_mode":"pub","exampleUrls":["https://usatradeonline.census.gov/"],"htmlRoutes":[{"id":"census-foreign-trade","match":{"hosts":["usatradeonline.census.gov","usatrade.census.gov"],"exactSegments":false},"mode":"census_foreign_trade_html"}]},{"id":"census","name":"U.S. Census Bureau Data API","category":"public-records","description":"U.S. Census Bureau Data API (/data/{year}/... keyed JSON matrix) and /data.json DCAT catalog adapter with data.census.gov fallback.","domains":["data.census.gov","api.census.gov","census.gov","www.census.gov"],"auth_mode":"key","exampleUrls":["https://api.census.gov/data/2023/acs/acs1?get=NAME,B01001_001E&for=state:06","https://api.census.gov/data/2023/acs/acs1.json","https://www.census.gov/topics/population.html"],"routes":[{"match":{"hosts":["api.census.gov"],"exactSegments":false,"pathPrefix":"/data/","pathSuffix":".json"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304,"auth_mode":"pub"},"extract":{"jsonMode":"census_json"}},{"match":{"hosts":["api.census.gov"],"exactSegments":false,"pathPrefix":"/data/","excludeSegmentSuffixes":[".html",".htm"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304,"auth_mode":"key"},"extract":{"jsonMode":"census_json"}},{"match":{"hosts":["api.census.gov"],"exactSegments":true,"pathEquals":["/data.json"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304,"auth_mode":"pub"},"extract":{"jsonMode":"census_json"}}],"htmlRoutes":[{"id":"census","match":{"hosts":["data.census.gov","census.gov","www.census.gov"],"exactSegments":false},"mode":"census_html"}]},{"id":"certificate-transparency","name":"Certificate Transparency (Cert Spotter & crt.sh)","category":"developer","description":"Extracts Certificate Transparency log issuances from api.certspotter.com and crt.sh JSON/HTML endpoints with bounded records and negative shell guards.","domains":["api.certspotter.com","crt.sh"],"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://api.certspotter.com/v1/issuances?domain=example.com"],"routes":[{"match":{"hosts":["api.certspotter.com"],"exactSegments":false,"pathPrefix":"/v1/issuances"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"cert_transparency_json"}},{"match":{"hosts":["crt.sh"],"exactSegments":false,"queryParams":[{"name":"output","param":"out","allowValues":["json"]}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"cert_transparency_json"}}],"htmlRoutes":[{"id":"certificate-transparency","match":{"hosts":["crt.sh"],"exactSegments":false},"mode":"cert_transparency_html"}]},{"id":"cfpb-complaints","name":"CFPB Consumer Complaint Database","category":"finance","description":"Upgrades consumerfinance.gov complaint detail URLs to keyless CFPB Consumer Complaint Database JSON API v1 with HTML fallback.","domains":["www.consumerfinance.gov","consumerfinance.gov"],"auth_mode":"pub","exampleUrls":["https://www.consumerfinance.gov/data-research/consumer-complaints/search/detail/3204968","https://www.consumerfinance.gov/data-research/consumer-complaints/search/api/v1/3204968"],"routes":[{"match":{"hosts":["www.consumerfinance.gov","consumerfinance.gov"],"exactSegments":false,"pathSegments":["data-research","consumer-complaints","search","detail",{"param":"complaintId","charset":"digits","minLen":1,"maxLen":20}]},"twin":{"fetchUrl":"https://www.consumerfinance.gov/data-research/consumer-complaints/search/api/v1/{complaintId}","kind":"json","accept":"application/json","auth_mode":"pub","maxBytes":2097152},"extract":{"jsonMode":"cfpb_complaints_json"}},{"match":{"hosts":["www.consumerfinance.gov","consumerfinance.gov"],"pathPrefix":"/data-research/consumer-complaints/search/api/v1/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"pub","maxBytes":2097152},"extract":{"jsonMode":"cfpb_complaints_json"}}],"htmlRoutes":[{"id":"cfpb-complaints","match":{"hosts":["www.consumerfinance.gov","consumerfinance.gov"],"pathPrefix":"/data-research/consumer-complaints/","exactSegments":false},"mode":"cfpb_complaints_html"}]},{"id":"chairish-1stdibs","name":"Chairish & 1stDibs Vintage Design Marketplaces","category":"commerce-social","description":"Extracts vintage and luxury furniture/design Product and multi-currency Offer[] JSON-LD along with dimensions and condition attributes from Chairish and 1stDibs.","domains":["chairish.com","www.chairish.com","1stdibs.com","www.1stdibs.com"],"auth_mode":"html","min_interval_ms":1500,"strict_robots":true,"exampleUrls":["https://www.chairish.com/product/194022/early-c1920s-liberty-co-attr-anglo-english-egyptian-revival-thebes-stool-original-ebony-finish","https://www.1stdibs.com/furniture/seating/armchairs/pair-vintage-red-1970s-vico-magistretti-carimate-armchairs-chair-cassina-2pc/id-f_53095452/"],"htmlRoutes":[{"id":"chairish-1stdibs","match":{"anyOf":[{"pathPrefix":"/product/"},{"pathPrefix":"/furniture/"},{"pathPrefix":"/art/"},{"pathPrefix":"/jewelry/"},{"pathPrefix":"/fashion/"},{"pathPrefix":"/creators/"}]},"mode":"chairish_1stdibs_html"}]},{"id":"chambermaster-growthzone","name":"ChamberMaster / GrowthZone Chamber Directories","category":"commerce-social","description":"Universal extractor for chamber-of-commerce member directories and event calendars hosted on ChamberMaster / GrowthZone (/list/ category and search pages, /list/member/ detail pages, and /events/ calendars): member name, address, phone, website, hours, categories, events, and description.","domains":["business.fortworthchamber.com","www.brownstownchamber.org","*.chambermaster.com","*.growthzoneapp.com"],"universalEngine":true,"auth_mode":"html","min_interval_ms":2000,"strict_robots":true,"exampleUrls":["https://business.fortworthchamber.com/list/category/apartments-25","https://business.fortworthchamber.com/list/member/the-harden-at-public-market-50786","https://www.brownstownchamber.org/events/"],"htmlRoutes":[{"id":"chambermaster-growthzone","match":{"exactSegments":false},"mode":"chambermaster_html"}]},{"id":"changelog-roadmap-pack","name":"Changelog & Roadmap Pack","category":"developer","description":"Extracts changelog releases and roadmap items from Canny, Productboard Portal, Headway, Beamer (via /loadMoreNews companion), and LaunchNotes.","domains":["feedback.canny.io","portal.productboard.com","headwayapp.co","app.getbeamer.com","updates.launchnotes.io"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://feedback.canny.io/changelog","https://portal.productboard.com/pb/1-productboard-portal/tabs/7-under-consideration","https://app.getbeamer.com/beamer/changelog","https://updates.launchnotes.io/"],"routes":[{"match":{"pathEquals":["/changelog.json","/releases.json","/updates.json"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"changelog_roadmap_json"}}],"htmlRoutes":[{"id":"changelog-roadmap-pack","match":{"exactSegments":false},"mode":"changelog_roadmap_html"}]},{"id":"chronicling-america","name":"Chronicling America (Historic American Newspapers)","category":"public-records","description":"Library of Congress Chronicling America historic newspapers adapter rewriting legacy chroniclingamerica.loc.gov and collection URLs directly to www.loc.gov ?fo=json.","domains":["chroniclingamerica.loc.gov"],"universalEngine":true,"auth_mode":"pub","min_interval_ms":5000,"strict_robots":true,"exampleUrls":["https://www.loc.gov/collections/chronicling-america/?fo=json","https://chroniclingamerica.loc.gov/lccn/sn83030214.json","https://www.loc.gov/collections/chronicling-america/"],"routes":[{"match":{"hosts":["chroniclingamerica.loc.gov"],"exactSegments":false,"pathSegments":["lccn",{"param":"lccn","charset":"url_seg","stripSuffix":".json","minLen":4,"maxLen":32}]},"twin":{"fetchUrl":"https://www.loc.gov/item/{lccn}/?fo=json","kind":"json","accept":"application/json","maxBytes":4194304,"auth_mode":"pub"},"extract":{"jsonMode":"chronicling_america_json"}},{"match":{"hosts":["chroniclingamerica.loc.gov"],"anyOf":[{"pathEquals":["/","/newspapers.json"]},{"pathPrefix":"/search/"}]},"twin":{"fetchUrl":"https://www.loc.gov/collections/chronicling-america/?fo=json","kind":"json","accept":"application/json","maxBytes":4194304,"auth_mode":"pub"},"extract":{"jsonMode":"chronicling_america_json"}},{"match":{"hosts":["www.loc.gov","loc.gov"],"exactSegments":false,"pathSegments":["chroniclingamerica","lccn",{"param":"lccn","charset":"url_seg","stripSuffix":".json","minLen":4,"maxLen":32}]},"twin":{"fetchUrl":"https://www.loc.gov/item/{lccn}/?fo=json","kind":"json","accept":"application/json","maxBytes":4194304,"auth_mode":"pub"},"extract":{"jsonMode":"chronicling_america_json"}},{"match":{"hosts":["www.loc.gov","loc.gov"],"anyOf":[{"pathPrefix":"/collections/chronicling-america"},{"pathPrefix":"/chroniclingamerica"}]},"twin":{"fetchUrl":"https://www.loc.gov/collections/chronicling-america/?fo=json","kind":"json","accept":"application/json","maxBytes":4194304,"auth_mode":"pub"},"extract":{"jsonMode":"chronicling_america_json"}}],"htmlRoutes":[{"id":"chronicling-america","match":{"anyOf":[{"hosts":["chroniclingamerica.loc.gov"],"exactSegments":false},{"hosts":["www.loc.gov","loc.gov"],"pathPrefix":"/collections/chronicling-america"},{"hosts":["www.loc.gov","loc.gov"],"pathPrefix":"/chroniclingamerica"}]},"mode":"chronicling_america_html"}]},{"id":"cisa-advisories-ics","name":"CISA Cybersecurity & ICS Advisories","category":"developer","description":"Extracts CISA cybersecurity and ICS advisory RSS feeds (with embedded CVE and CSAF links) and Drupal 11 SSR advisory/alert HTML pages on www.cisa.gov.","domains":["www.cisa.gov"],"universalEngine":true,"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://www.cisa.gov/cybersecurity-advisories/ics-advisories.xml","https://www.cisa.gov/cybersecurity-advisories/all.xml","https://www.cisa.gov/news-events/ics-advisories/icsa-26-328-01"],"routes":[{"match":{"hosts":["www.cisa.gov","cisa.gov"],"exactSegments":false,"pathPrefix":"/cybersecurity-advisories/","pathSuffix":".xml"},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"application/rss+xml","maxBytes":2097152},"extract":{"textMode":"cisa_advisories_rss"}}],"htmlRoutes":[{"id":"cisa-advisories-ics","match":{"hosts":["www.cisa.gov","cisa.gov"],"exactSegments":false,"anyOf":[{"pathPrefix":"/news-events/"},{"pathPrefix":"/cybersecurity-advisories"}]},"mode":"cisa_advisories_html"}]},{"id":"cisa-kev","name":"CISA Known Exploited Vulnerabilities (KEV) Catalog","category":"developer","description":"Bounded JSON/CSV extractor for CISA's Known Exploited Vulnerabilities (KEV) catalog with optional ?cve= filtering plus SSR catalog HTML extraction.","domains":["cisa.gov"],"universalEngine":true,"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json","https://www.cisa.gov/known-exploited-vulnerabilities-catalog"],"routes":[{"match":{"hosts":["www.cisa.gov","cisa.gov"],"exactSegments":true,"pathEquals":["/sites/default/files/feeds/known_exploited_vulnerabilities.json"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"cisa_kev_json"}},{"match":{"hosts":["www.cisa.gov","cisa.gov"],"exactSegments":true,"pathEquals":["/sites/default/files/csv/known_exploited_vulnerabilities.csv"]},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"text/plain","maxBytes":4194304},"extract":{"textMode":"cisa_kev_csv"}}],"htmlRoutes":[{"id":"cisa-kev","match":{"hosts":["www.cisa.gov","cisa.gov"],"exactSegments":true,"pathEquals":["/known-exploited-vulnerabilities-catalog"]},"mode":"cisa_kev_html"}]},{"id":"civicclerk","name":"CivicPlus CivicClerk Agenda Portals","category":"public-records","description":"Extracts municipal meeting events and agendas via CivicClerk OData v1 API with portal-to-API same-eTLD+1 twin upgrades.","domains":["*.civicclerk.com"],"auth_mode":"pub","exampleUrls":["https://mauicounty.api.civicclerk.com/v1/Events?$top=3","https://mauicounty.api.civicclerk.com/v1/Events/1023","https://mauicounty.portal.civicclerk.com/"],"routes":[{"match":{"hostSubdomain":{"suffix":".api.civicclerk.com","param":"tenant","reserved":["www","api","auth","login","admin"]},"pathPrefix":"/v1/Events"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"civicclerk_json"}},{"match":{"hostSubdomain":{"suffix":".portal.civicclerk.com","param":"tenant","reserved":["www","api","auth","login","admin"]},"exactSegments":false,"pathSegments":["event",{"param":"eventId","charset":"digits","minLen":1,"maxLen":16}]},"twin":{"fetchUrl":"https://{tenant}.api.civicclerk.com/v1/Events/{eventId}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"civicclerk_json"}},{"match":{"hostSubdomain":{"suffix":".portal.civicclerk.com","param":"tenant","reserved":["www","api","auth","login","admin"]},"pathEquals":["/","/events"]},"twin":{"fetchUrl":"https://{tenant}.api.civicclerk.com/v1/Events?$top=25","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"civicclerk_json"}}],"htmlRoutes":[{"id":"civicclerk","match":{"exactSegments":false},"mode":"civicclerk_html"}]},{"id":"civicplus","name":"CivicPlus CivicEngage Agenda & Document Portals","category":"public-records","description":"Universal extractor for CivicPlus CivicEngage /AgendaCenter, /DocumentCenter, and /CivicAlerts.aspx pages on city and county domains: meeting dates, agenda titles, agenda/HTML/packet/minutes links, public document directories, and municipal alerts. Fingerprint-gated; never touches robots.txt-disallowed /RSSFeed.aspx.","domains":["www.gulfshoresal.gov","www.ankenyiowa.gov","www.springfieldmo.gov","www.brownwoodtexas.gov","www.fayetteville-ar.gov"],"universalEngine":true,"auth_mode":"html","min_interval_ms":2000,"strict_robots":true,"exampleUrls":["https://www.gulfshoresal.gov/AgendaCenter","https://www.brownwoodtexas.gov/DocumentCenter","https://www.springfieldmo.gov/CivicAlerts.aspx"],"htmlRoutes":[{"id":"civicplus","match":{"anyOf":[{"pathPrefix":"/AgendaCenter","exactSegments":false},{"pathPrefix":"/DocumentCenter","exactSegments":false},{"pathEquals":["/CivicAlerts.aspx"]}]},"mode":"civicplus_agenda_html"}]},{"id":"ckan","name":"CKAN Open Data Portals (Data.gov, UK, AU, Canada & City Portals)","category":"public-records","description":"Upgrades CKAN open-data portal dataset pages to /api/3/action/package_show JSON with organization, license, and downloadable resources.","domains":["catalog.data.gov","data.boston.gov","data.sanantonio.gov","data.sanjoseca.gov","data.wprdc.org","data.gov.uk","www.data.gov.uk","data.gov.au","open.canada.ca"],"exampleUrls":["https://open.canada.ca/data/en/dataset/0032ce54-c5dd-4b66-99a0-320a7b5e99f2"],"routes":[{"match":{"hosts":["catalog.data.gov","data.boston.gov","data.sanantonio.gov","data.sanjoseca.gov","data.wprdc.org"],"exactSegments":true,"pathSegments":["dataset",{"param":"pkgId","charset":"pkg","minLen":2,"maxLen":160}]},"twin":{"fetchUrl":"https://{host}/api/3/action/package_show?id={pkgId}","kind":"json","accept":"application/json"},"extract":{"requireFieldEquals":{"path":"success","value":"true"},"requireAnyFields":["result"],"vars":{"title":{"paths":["result.title","result.title.en"],"trim":true,"fallbackTemplate":"{pkgId}"},"orgTitle":{"paths":["result.organization.title"]},"license":{"paths":["result.license_title"]},"modified":{"paths":["result.metadata_modified"],"sliceMax":10},"notes":{"paths":["result.notes"],"format":"strip_tags"},"notesShort":{"paths":["result.notes"],"format":"strip_tags","sliceMax":260},"tags":{"paths":["result.tags"],"subFieldsJoin":{"fields":["display_name"],"sep":"","fallbackField":"name"},"limit":12,"join":", "}},"titleTemplate":"{title}","descriptionVar":"notesShort","authorVar":"orgTitle","publishedTimeVar":"modified","bullets":[{"label":"Portal","template":"`{host}`"},{"label":"Publisher","template":"{orgTitle}","whenVar":"orgTitle"},{"label":"License","template":"{license}","whenVar":"license"},{"label":"Last Updated","template":"{modified}","whenVar":"modified"},{"label":"Tags","template":"{tags}","whenVar":"tags"}],"sections":[{"heading":"Description","textVar":"notes"},{"heading":"Data Resources","headingTemplate":"Data Resources ({count})","arrayPath":"result.resources","limit":20,"collectLinkVars":["rUrl"],"itemVars":{"rName":{"paths":["name","description","format"],"trim":true,"default":"Resource"},"rUrl":{"paths":["url"],"requireHttps":true},"rCell":{"template":"[{rName}]({rUrl})","whenVars":["rName","rUrl"],"fallbackVar":"rName"},"rFmt":{"paths":["format"],"upper":true,"default":"-"}},"columns":[{"header":"Resource","template":"{rCell}"},{"header":"Format","template":"{rFmt}"}]}]}},{"match":{"hosts":["data.gov.uk","www.data.gov.uk"],"exactSegments":true,"pathSegments":["dataset",{"param":"pkgId","charset":"pkg","minLen":2,"maxLen":160}]},"twin":{"fetchUrl":"https://data.gov.uk/api/action/package_show?id={pkgId}","kind":"json","accept":"application/json"},"extract":{"requireFieldEquals":{"path":"success","value":"true"},"requireAnyFields":["result"],"vars":{"title":{"paths":["result.title","result.title.en"],"trim":true,"fallbackTemplate":"{pkgId}"},"orgTitle":{"paths":["result.organization.title"]},"license":{"paths":["result.license_title"]},"modified":{"paths":["result.metadata_modified"],"sliceMax":10},"notes":{"paths":["result.notes"],"format":"strip_tags"},"notesShort":{"paths":["result.notes"],"format":"strip_tags","sliceMax":260},"tags":{"paths":["result.tags"],"subFieldsJoin":{"fields":["display_name"],"sep":"","fallbackField":"name"},"limit":12,"join":", "}},"titleTemplate":"{title}","descriptionVar":"notesShort","authorVar":"orgTitle","publishedTimeVar":"modified","bullets":[{"label":"Portal","template":"`{host}`"},{"label":"Publisher","template":"{orgTitle}","whenVar":"orgTitle"},{"label":"License","template":"{license}","whenVar":"license"},{"label":"Last Updated","template":"{modified}","whenVar":"modified"},{"label":"Tags","template":"{tags}","whenVar":"tags"}],"sections":[{"heading":"Description","textVar":"notes"},{"heading":"Data Resources","headingTemplate":"Data Resources ({count})","arrayPath":"result.resources","limit":20,"collectLinkVars":["rUrl"],"itemVars":{"rName":{"paths":["name","description","format"],"trim":true,"default":"Resource"},"rUrl":{"paths":["url"],"requireHttps":true},"rCell":{"template":"[{rName}]({rUrl})","whenVars":["rName","rUrl"],"fallbackVar":"rName"},"rFmt":{"paths":["format"],"upper":true,"default":"-"}},"columns":[{"header":"Resource","template":"{rCell}"},{"header":"Format","template":"{rFmt}"}]}]}},{"match":{"hosts":["data.gov.au"],"exactSegments":true,"pathSegments":["data","dataset",{"param":"pkgId","charset":"pkg","minLen":2,"maxLen":160}]},"twin":{"fetchUrl":"https://data.gov.au/data/api/3/action/package_show?id={pkgId}","kind":"json","accept":"application/json"},"extract":{"requireFieldEquals":{"path":"success","value":"true"},"requireAnyFields":["result"],"vars":{"title":{"paths":["result.title","result.title.en"],"trim":true,"fallbackTemplate":"{pkgId}"},"orgTitle":{"paths":["result.organization.title"]},"license":{"paths":["result.license_title"]},"modified":{"paths":["result.metadata_modified"],"sliceMax":10},"notes":{"paths":["result.notes"],"format":"strip_tags"},"notesShort":{"paths":["result.notes"],"format":"strip_tags","sliceMax":260},"tags":{"paths":["result.tags"],"subFieldsJoin":{"fields":["display_name"],"sep":"","fallbackField":"name"},"limit":12,"join":", "}},"titleTemplate":"{title}","descriptionVar":"notesShort","authorVar":"orgTitle","publishedTimeVar":"modified","bullets":[{"label":"Portal","template":"`{host}`"},{"label":"Publisher","template":"{orgTitle}","whenVar":"orgTitle"},{"label":"License","template":"{license}","whenVar":"license"},{"label":"Last Updated","template":"{modified}","whenVar":"modified"},{"label":"Tags","template":"{tags}","whenVar":"tags"}],"sections":[{"heading":"Description","textVar":"notes"},{"heading":"Data Resources","headingTemplate":"Data Resources ({count})","arrayPath":"result.resources","limit":20,"collectLinkVars":["rUrl"],"itemVars":{"rName":{"paths":["name","description","format"],"trim":true,"default":"Resource"},"rUrl":{"paths":["url"],"requireHttps":true},"rCell":{"template":"[{rName}]({rUrl})","whenVars":["rName","rUrl"],"fallbackVar":"rName"},"rFmt":{"paths":["format"],"upper":true,"default":"-"}},"columns":[{"header":"Resource","template":"{rCell}"},{"header":"Format","template":"{rFmt}"}]}]}},{"match":{"hosts":["open.canada.ca"],"exactSegments":true,"pathSegments":["data","en","dataset",{"param":"pkgId","charset":"pkg","minLen":2,"maxLen":160}]},"twin":{"fetchUrl":"https://open.canada.ca/data/api/action/package_show?id={pkgId}","kind":"json","accept":"application/json"},"extract":{"requireFieldEquals":{"path":"success","value":"true"},"requireAnyFields":["result"],"vars":{"title":{"paths":["result.title","result.title.en"],"trim":true,"fallbackTemplate":"{pkgId}"},"orgTitle":{"paths":["result.organization.title"]},"license":{"paths":["result.license_title"]},"modified":{"paths":["result.metadata_modified"],"sliceMax":10},"notes":{"paths":["result.notes"],"format":"strip_tags"},"notesShort":{"paths":["result.notes"],"format":"strip_tags","sliceMax":260},"tags":{"paths":["result.tags"],"subFieldsJoin":{"fields":["display_name"],"sep":"","fallbackField":"name"},"limit":12,"join":", "}},"titleTemplate":"{title}","descriptionVar":"notesShort","authorVar":"orgTitle","publishedTimeVar":"modified","bullets":[{"label":"Portal","template":"`{host}`"},{"label":"Publisher","template":"{orgTitle}","whenVar":"orgTitle"},{"label":"License","template":"{license}","whenVar":"license"},{"label":"Last Updated","template":"{modified}","whenVar":"modified"},{"label":"Tags","template":"{tags}","whenVar":"tags"}],"sections":[{"heading":"Description","textVar":"notes"},{"heading":"Data Resources","headingTemplate":"Data Resources ({count})","arrayPath":"result.resources","limit":20,"collectLinkVars":["rUrl"],"itemVars":{"rName":{"paths":["name","description","format"],"trim":true,"default":"Resource"},"rUrl":{"paths":["url"],"requireHttps":true},"rCell":{"template":"[{rName}]({rUrl})","whenVars":["rName","rUrl"],"fallbackVar":"rName"},"rFmt":{"paths":["format"],"upper":true,"default":"-"}},"columns":[{"header":"Resource","template":"{rCell}"},{"header":"Format","template":"{rFmt}"}]}]}}]},{"id":"classic-forum-pack","name":"Classic Forum Pack","category":"commerce-social","description":"Extracts structured posts, authors, timestamps, and quote blocks from Invision Community, vBulletin (vB3/4 & vB5), and phpBB thread HTML while rejecting HTTP 200 soft-404s.","domains":["gtaforums.com","forum.doom9.org","forum.image-line.com"],"universalEngine":true,"auth_mode":"html","exampleUrls":["https://gtaforums.com/topic/1007946-gtao-event-12th-nov-2026-as-the-trip-to-leonida-approaches-go-back-to-the-basics-w-bonuses-on-all-contact-missions-free-mode-challenges-stunt-race-series-more/","https://forum.doom9.org/showthread.php?t=187224","https://forum.image-line.com/viewtopic.php?t=343634"],"htmlRoutes":[{"id":"classic-forum-pack","match":{"exactSegments":false},"mode":"classic_forum_pack_html"}]},{"id":"clinicaltrials","name":"ClinicalTrials.gov Studies","category":"research-health","description":"Extracts clinical trial NCT ID, recruitment status, phase, conditions, interventions, sponsor, and summary from rendered clinicaltrials.gov/study/NCT... pages (strictly respecting robots.txt).","domains":["clinicaltrials.gov","www.clinicaltrials.gov"],"exampleUrls":["https://clinicaltrials.gov/study/NCT04280705"],"htmlRoutes":[{"match":{"scanSegment":{"param":"nctId","charset":"nct_id","transform":"upper"}},"mode":"dom","jsonLdTypes":["MedicalStudy","MedicalTrial","ClinicalTrial"],"embeddedBalancedKey":"protocolSection","requireVars":["title","hasAnyDetail"],"vars":{"title":{"embeddedPaths":["identificationModule.briefTitle"],"jsonLdPaths":["name"],"metaKeys":["og:title"]},"overallStatus":{"embeddedPaths":["statusModule.overallStatus"],"jsonLdPaths":["status"]},"phases":{"embeddedPaths":["designModule.phases"],"join":", "},"leadSponsor":{"embeddedPaths":["sponsorCollaboratorsModule.leadSponsor.name"],"jsonLdPaths":["sponsor.name"]},"conditions":{"embeddedPaths":["conditionsModule.conditions"],"jsonLdPaths":["healthCondition"],"limit":10,"join":", "},"summary":{"embeddedPaths":["descriptionModule.briefSummary"],"jsonLdPaths":["description"],"metaKeys":["description"]},"summaryShort":{"template":"{summary}","whenVars":["summary"],"sliceMax":260},"hasAnyDetail":{"template":"1","whenAnyVars":["overallStatus","phases","leadSponsor","conditions","summary"]}},"titleTemplate":"{title} ({nctId})","descriptionVar":"summaryShort","bullets":[{"label":"NCT Number","template":"`{nctId}`"},{"label":"Status","template":"{overallStatus}","whenVar":"overallStatus"},{"label":"Phase","template":"{phases}","whenVar":"phases"},{"label":"Lead Sponsor","template":"{leadSponsor}","whenVar":"leadSponsor"},{"label":"Conditions","template":"{conditions}","whenVar":"conditions"}],"sections":[{"heading":"Brief Summary","textVar":"summary"}],"appendCurrentMdDelta":{"baseVar":"summary","minExtraChars":120}}]},{"id":"cms-data","name":"CMS Data & Provider Data Catalog","category":"research-health","description":"Centers for Medicare & Medicaid Services (CMS) DKAN metastore, datastore query, and data-api v1 adapter enforcing 10s crawl-delay.","domains":["data.cms.gov"],"auth_mode":"pub","min_interval_ms":10000,"strict_robots":true,"exampleUrls":["https://data.cms.gov/provider-data/api/1/metastore/schemas/dataset/items/mj5m-pzi6","https://data.cms.gov/provider-data/api/1/datastore/query/mj5m-pzi6/0?limit=2","https://data.cms.gov/data-api/v1/dataset/9767cb68-8ea9-4f0b-8179-9431abc89f11/data?size=2"],"routes":[{"match":{"anyOf":[{"pathPrefix":"/provider-data/api/"},{"pathPrefix":"/data-api/v1/"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"cms_data_json"}},{"match":{"exactSegments":true,"pathSegments":["provider-data","dataset",{"param":"datasetId","charset":"alnum_dash","minLen":4,"maxLen":64}]},"twin":{"fetchUrl":"https://data.cms.gov/provider-data/api/1/metastore/schemas/dataset/items/{datasetId}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"cms_data_json"}}],"htmlRoutes":[{"id":"cms-data","match":{"exactSegments":false},"mode":"cms_data_html"}]},{"id":"cms-price-transparency","name":"CMS Hospital & Payer Price Transparency (HPT & MRF)","category":"research-health","description":"Universal engine for hospital /cms-hpt.txt discovery files, bounded Range-streaming MRF JSON/CSV charge files, ZIP/gzip archive detection, and payer TiC index feeds.","domains":["stanfordhealthcare.org","www.mountsinai.org","nyulangone.org","www.ucsfhealth.org","transparency-in-coverage.uhc.com"],"universalEngine":true,"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://stanfordhealthcare.org/cms-hpt.txt","https://nyulangone.org/cms-hpt.txt","https://stanfordhealthcare.org/content/dam/SHC/patientsandvisitors/pricingtransparency/946174066_stanford-health-care_standardcharges.json","https://transparency-in-coverage.uhc.com/api/v1/uhc/blobs/"],"routes":[{"match":{"pathEquals":["/cms-hpt.txt"]},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"text/plain","maxBytes":524288},"extract":{"textMode":"cms_hpt_txt"}},{"match":{"pathSuffix":"standardcharges.json"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","headers":{"Range":"bytes=0-2097151"},"maxBytes":2097152},"extract":{"jsonMode":"cms_mrf_json"}},{"match":{"pathSuffix":"standardcharges.csv"},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"text/plain","headers":{"Range":"bytes=0-2097151"},"maxBytes":2097152},"extract":{"textMode":"cms_mrf_csv"}},{"match":{"hosts":["transparency-in-coverage.uhc.com"],"pathPrefix":"/api/v1/uhc/blobs"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"cms_mrf_json"}},{"match":{"anyOf":[{"pathSuffix":"table-of-contents.json"},{"pathSuffix":"_index.json"},{"pathSuffix":"-index.json"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","headers":{"Range":"bytes=0-2097151"},"maxBytes":2097152},"extract":{"jsonMode":"cms_mrf_json"}}],"htmlRoutes":[{"id":"cms-price-transparency","match":{"exactSegments":false},"mode":"cms_price_transparency_html"}]},{"id":"college-scorecard","name":"College Scorecard (U.S. Department of Education)","category":"public-records","description":"U.S. Department of Education College Scorecard API adapter scoped to api.data.gov/ed/collegescorecard with compact default fields.","domains":["collegescorecard.ed.gov","api.data.gov"],"auth_mode":"key","exampleUrls":["https://api.data.gov/ed/collegescorecard/v1/schools?id=166027","https://collegescorecard.ed.gov/school/?166027-Harvard-University"],"routes":[{"match":{"hosts":["api.data.gov"],"exactSegments":false,"pathPrefix":"/ed/collegescorecard"},"twin":{"fetchUrl":"{requestUrl}","defaultQueryParams":{"fields":"id,school.name,school.city,school.state,school.school_url,latest.student.size,latest.admissions.admission_rate.overall,latest.cost.tuition.in_state,latest.cost.tuition.out_of_state,latest.earnings.10_yrs_after_entry.median","per_page":"10"},"kind":"json","accept":"application/json","maxBytes":4194304,"auth_mode":"key"},"extract":{"jsonMode":"college_scorecard_json"}}],"htmlRoutes":[{"id":"college-scorecard","match":{"hosts":["collegescorecard.ed.gov"],"exactSegments":false},"mode":"college_scorecard_html"}]},{"id":"company-newsrooms","name":"Company Newsrooms (Prowly / Prezly / Cision)","category":"commerce-social","description":"Extracts corporate newsrooms and RSS/Atom press release feeds from Prowly, Prezly, and Cision PR portals.","domains":["news.cision.com","multimedia.cision.com","*.prowly.com","*.prezly.com","press.brusselsairlines.com"],"universalEngine":true,"auth_mode":"pub","strict_robots":true,"min_interval_ms":1000,"exampleUrls":["https://residence.prowly.com/rss","https://residence.prowly.com/","https://press.brusselsairlines.com/feed","https://news.cision.com/tietoevry"],"routes":[{"match":{"hosts":["news.cision.com","multimedia.cision.com","*.prowly.com","*.prezly.com","press.brusselsairlines.com"],"anyOf":[{"pathEquals":["/rss","/feed","/rss.xml","/feed.xml"]},{"pathSuffix":"/rss"},{"pathSuffix":"/feed"},{"pathSuffix":".rss"}],"exactSegments":false},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"application/rss+xml","maxBytes":2097152},"extract":{"textMode":"company_newsroom_rss_xml"}}],"htmlRoutes":[{"id":"company-newsrooms","match":{"exactSegments":false},"mode":"company_newsrooms_html"}]},{"id":"confluence-public","name":"Confluence Public Spaces","category":"developer","description":"Upgrades public Confluence /wiki/spaces/.../pages/{pageId} URLs to same-origin REST content API JSON twins with SSR HTML fallback; keyless public spaces only.","domains":["openmrs.atlassian.net","ecosystem.atlassian.net"],"universalEngine":true,"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://openmrs.atlassian.net/wiki/spaces/docs/pages/25462110/Reporting+Module","https://openmrs.atlassian.net/wiki/spaces/docs/overview"],"routes":[{"match":{"pathPrefix":"/wiki/spaces/","exactSegments":false,"pathSegments":["wiki","spaces",{"param":"space","charset":"url_seg","minLen":1,"maxLen":80},"pages",{"param":"pageId","charset":"digits","minLen":1,"maxLen":20},{"param":"slug","charset":"safe_subpath","optional":true,"greedy":true}]},"twin":{"fetchUrl":"https://{host}/wiki/rest/api/content/{pageId}?expand=body.view,space,version,ancestors","kind":"json","accept":"application/json"},"extract":{"jsonMode":"confluence_public"}},{"match":{"exactSegments":true,"pathSegments":["wiki","rest","api","content",{"param":"pageId","charset":"digits","minLen":1,"maxLen":20}]},"twin":{"fetchUrl":"{requestUrl}","defaultQueryParams":{"expand":"body.view,space,version,ancestors"},"kind":"json","accept":"application/json"},"extract":{"jsonMode":"confluence_public"}},{"match":{"exactSegments":true,"pathSegments":["wiki","api","v2","pages",{"param":"pageId","charset":"digits","minLen":1,"maxLen":20}]},"twin":{"fetchUrl":"{requestUrl}","defaultQueryParams":{"body-format":"view"},"kind":"json","accept":"application/json"},"extract":{"jsonMode":"confluence_public"}}],"htmlRoutes":[{"id":"confluence-public","match":{"exactSegments":false},"mode":"confluence_public_html"}]},{"id":"congress-gov","name":"Congress.gov Federal Legislation","category":"public-records","description":"Official api.congress.gov v3 API adapter for federal bills, amendments, nominations, committees, and members with HTML fallback for www.congress.gov.","domains":["congress.gov","www.congress.gov","api.congress.gov"],"auth_mode":"key","min_interval_ms":2000,"exampleUrls":["https://api.congress.gov/v3/bill/118/hr/815?format=json","https://www.congress.gov/bill/118th-congress/house-bill/815"],"routes":[{"match":{"hosts":["api.congress.gov"],"pathPrefix":"/v3/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":4194304},"extract":{"jsonMode":"congress_gov_json"}},{"match":{"hosts":["congress.gov","www.congress.gov"],"exactSegments":false,"pathSegments":["bill",{"param":"congress","charset":"alnum_dash","minLen":3,"maxLen":20,"transform":"leading_digits"},"house-bill",{"param":"billNumber","charset":"digits","minLen":1,"maxLen":8}]},"twin":{"fetchUrl":"https://api.congress.gov/v3/bill/{congress}/hr/{billNumber}?format=json","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":4194304},"extract":{"jsonMode":"congress_gov_json"}},{"match":{"hosts":["congress.gov","www.congress.gov"],"exactSegments":false,"pathSegments":["bill",{"param":"congress","charset":"alnum_dash","minLen":3,"maxLen":20,"transform":"leading_digits"},"senate-bill",{"param":"billNumber","charset":"digits","minLen":1,"maxLen":8}]},"twin":{"fetchUrl":"https://api.congress.gov/v3/bill/{congress}/s/{billNumber}?format=json","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":4194304},"extract":{"jsonMode":"congress_gov_json"}},{"match":{"hosts":["congress.gov","www.congress.gov"],"exactSegments":false,"pathSegments":["bill",{"param":"congress","charset":"alnum_dash","minLen":3,"maxLen":20,"transform":"leading_digits"},"house-joint-resolution",{"param":"billNumber","charset":"digits","minLen":1,"maxLen":8}]},"twin":{"fetchUrl":"https://api.congress.gov/v3/bill/{congress}/hjres/{billNumber}?format=json","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":4194304},"extract":{"jsonMode":"congress_gov_json"}},{"match":{"hosts":["congress.gov","www.congress.gov"],"exactSegments":false,"pathSegments":["bill",{"param":"congress","charset":"alnum_dash","minLen":3,"maxLen":20,"transform":"leading_digits"},"senate-joint-resolution",{"param":"billNumber","charset":"digits","minLen":1,"maxLen":8}]},"twin":{"fetchUrl":"https://api.congress.gov/v3/bill/{congress}/sjres/{billNumber}?format=json","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":4194304},"extract":{"jsonMode":"congress_gov_json"}},{"match":{"hosts":["congress.gov","www.congress.gov"],"exactSegments":false,"pathSegments":["bill",{"param":"congress","charset":"alnum_dash","minLen":3,"maxLen":20,"transform":"leading_digits"},"house-concurrent-resolution",{"param":"billNumber","charset":"digits","minLen":1,"maxLen":8}]},"twin":{"fetchUrl":"https://api.congress.gov/v3/bill/{congress}/hconres/{billNumber}?format=json","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":4194304},"extract":{"jsonMode":"congress_gov_json"}},{"match":{"hosts":["congress.gov","www.congress.gov"],"exactSegments":false,"pathSegments":["bill",{"param":"congress","charset":"alnum_dash","minLen":3,"maxLen":20,"transform":"leading_digits"},"senate-concurrent-resolution",{"param":"billNumber","charset":"digits","minLen":1,"maxLen":8}]},"twin":{"fetchUrl":"https://api.congress.gov/v3/bill/{congress}/sconres/{billNumber}?format=json","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":4194304},"extract":{"jsonMode":"congress_gov_json"}},{"match":{"hosts":["congress.gov","www.congress.gov"],"exactSegments":false,"pathSegments":["bill",{"param":"congress","charset":"alnum_dash","minLen":3,"maxLen":20,"transform":"leading_digits"},"house-resolution",{"param":"billNumber","charset":"digits","minLen":1,"maxLen":8}]},"twin":{"fetchUrl":"https://api.congress.gov/v3/bill/{congress}/hres/{billNumber}?format=json","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":4194304},"extract":{"jsonMode":"congress_gov_json"}},{"match":{"hosts":["congress.gov","www.congress.gov"],"exactSegments":false,"pathSegments":["bill",{"param":"congress","charset":"alnum_dash","minLen":3,"maxLen":20,"transform":"leading_digits"},"senate-resolution",{"param":"billNumber","charset":"digits","minLen":1,"maxLen":8}]},"twin":{"fetchUrl":"https://api.congress.gov/v3/bill/{congress}/sres/{billNumber}?format=json","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":4194304},"extract":{"jsonMode":"congress_gov_json"}}],"htmlRoutes":[{"id":"congress-gov","match":{"hosts":["congress.gov","www.congress.gov"],"exactSegments":false},"mode":"congress_gov_html"}]},{"id":"constructor-io","name":"Constructor.io On-Site Search","category":"commerce-social","description":"Opt-in page-key adapter for Constructor.io search JSON endpoints; defaults OFF and falls back cleanly to HTML/JSON-LD when disabled.","domains":["ac.cnstrc.com"],"universalEngine":true,"auth_mode":"page-key","requires_page_key_opt_in":true,"exampleUrls":["https://ac.cnstrc.com/search/shirt?key=key_kUTI6qLxMCLBIaN9&num_results_per_page=10"],"routes":[{"match":{"anyOf":[{"hostSubdomain":{"suffix":".cnstrc.com","param":"regionHost"},"pathSegments":["search",{"param":"query","charset":"url_seg","minLen":1,"maxLen":200}]},{"hostSubdomain":{"suffix":".cnstrc.com","param":"regionHost"},"pathSegments":["v1","search",{"param":"query","charset":"url_seg","minLen":1,"maxLen":200}]}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"jsonMode":"constructor_io"}}],"htmlRoutes":[{"id":"constructor-io","match":{"exactSegments":false},"mode":"constructor_io_html"}]},{"id":"copyright-office","name":"U.S. Copyright Office Public Records","category":"public-records","description":"U.S. Copyright Office Public Records System (publicrecords.copyright.gov) keyless JSON API adapter with HTML fallback.","domains":["publicrecords.copyright.gov","api.publicrecords.copyright.gov","cocatalog.loc.gov"],"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://api.publicrecords.copyright.gov/search_service_external/simple_search_dsl?query=TX0009000001&page_number=1&records_per_page=5","https://publicrecords.copyright.gov/detailed-record/voyager_32941460"],"routes":[{"match":{"hosts":["api.publicrecords.copyright.gov"],"pathPrefix":"/search_service_external/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"pub"},"extract":{"jsonMode":"copyright_office_json"}},{"match":{"hosts":["publicrecords.copyright.gov"],"exactSegments":false,"pathSegments":["detailed-record",{"param":"recordId","charset":"alnum_dash","minLen":3,"maxLen":80}]},"twin":{"fetchUrl":"https://api.publicrecords.copyright.gov/search_service_external/simple_search_dsl?query={recordId}&page_number=1&records_per_page=5","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"pub"},"extract":{"jsonMode":"copyright_office_json"}}],"htmlRoutes":[{"id":"copyright-office","match":{"hosts":["publicrecords.copyright.gov","cocatalog.loc.gov"],"exactSegments":false},"mode":"copyright_office_html"}]},{"id":"core-ac","name":"CORE Open Access Research Papers","category":"research-health","description":"Official keyed CORE v3 API adapter (CORE_AC_API_KEY via Authorization: Bearer) for open-access scholarly works and search, with core.ac.uk HTML fallback and Cloudflare challenge guard.","domains":["api.core.ac.uk","core.ac.uk","www.core.ac.uk"],"auth_mode":"key","min_interval_ms":1000,"exampleUrls":["https://api.core.ac.uk/v3/works/11689643","https://api.core.ac.uk/v3/search/works?q=solar&limit=1","https://core.ac.uk/works/11689643"],"routes":[{"match":{"hosts":["api.core.ac.uk"],"pathPrefix":"/v3/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"core_ac_json"}},{"match":{"hosts":["core.ac.uk","www.core.ac.uk"],"anyOf":[{"exactSegments":true,"pathSegments":["works",{"param":"workId","charset":"digits","minLen":1,"maxLen":20}]},{"exactSegments":true,"pathSegments":["reader",{"param":"workId","charset":"digits","minLen":1,"maxLen":20}]}]},"twin":{"fetchUrl":"https://api.core.ac.uk/v3/works/{workId}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"core_ac_json"}}],"htmlRoutes":[{"id":"core-ac","match":{"hosts":["core.ac.uk","www.core.ac.uk"],"exactSegments":false},"mode":"core_ac_html"}]},{"id":"cornell-lii","name":"Cornell Law LII (CFR & US Code)","category":"public-records","description":"Extracts clean statutory and CFR regulatory text from www.law.cornell.edu/cfr/* and /uscode/* while stripping navigation and donation sidebars.","domains":["www.law.cornell.edu","law.cornell.edu"],"exampleUrls":["https://www.law.cornell.edu/cfr/text/16/part-1512","https://www.law.cornell.edu/uscode/text/15/2051"],"htmlRoutes":[{"id":"cornell-lii","mode":"dom","match":{"anyOf":[{"exactSegments":false,"pathSegments":["cfr",{"param":"rest","charset":"safe_subpath","greedy":true,"minLen":1,"maxLen":200}]},{"exactSegments":false,"pathSegments":["uscode",{"param":"rest","charset":"safe_subpath","greedy":true,"minLen":1,"maxLen":200}]}]},"vars":{"title":{"cssText":["#page-title","main#content h1","#content h1","h1","title"],"trim":true},"body":{"cssHtmlToMd":["#content .tab-pane.active","main#content","#content","main","article"],"format":"strip_leading_h1","trim":true}},"requireVars":["title","body"],"titleTemplate":"{title}","bodyVar":"body","preserveBodyLinksFromVar":"body"}]},{"id":"costco-sams-club","name":"Costco & Sam's Club","category":"commerce-social","description":"Extracts Costco and Sam's Club public product pages from schema.org Product JSON-LD and Sam's Club __NEXT_DATA__ hydration, strictly rejecting Kasada, Akamai, and empty SPA shells.","domains":["costco.com","www.costco.com","costco.ca","www.costco.ca","samsclub.com","www.samsclub.com"],"auth_mode":"html","min_interval_ms":3000,"max_concurrent":1,"strict_robots":true,"exampleUrls":["https://www.costco.com/p/-/costco-shop-card/10024438","https://www.samsclub.com/ip/tnt-fireworks-revolution-rumble/20020700393"],"htmlRoutes":[{"id":"costco-sams-club","match":{"hosts":["costco.com","www.costco.com","costco.ca","www.costco.ca","samsclub.com","www.samsclub.com"]},"mode":"costco_sams_club_html"}]},{"id":"county-assessor","name":"County Assessor & Property Records","category":"public-records","description":"Universal extractor for Vision Government Solutions (VGSI), Tyler Technologies iasWorld, and SchneiderCorp qPublic/Beacon county property assessor portals.","domains":["gis.vgsi.com","icare.fairfaxcounty.gov","property.muni.org","qpublic.schneidercorp.com","beacon.schneidercorp.com"],"universalEngine":true,"auth_mode":"html","strict_robots":true,"exampleUrls":["https://gis.vgsi.com/madisonct/Parcel.aspx?pid=4","https://gis.vgsi.com/madisonct/Parcel.aspx?pid=10","https://gis.vgsi.com/newhavenct/Parcel.aspx?pid=1"],"htmlRoutes":[{"id":"county-assessor","match":{"exactSegments":false},"mode":"county_assessor_html"}]},{"id":"coursedog","name":"Coursedog University Catalogs","category":"public-records","description":"Extracts Coursedog public university catalogs from SSR __NUXT_DATA__ and rendered catalog DOM alongside public Coursedog JSON API routes.","domains":["*.coursedog.com","catalog.pratt.edu","catalogs.umn.edu"],"universalEngine":true,"auth_mode":"pub","strict_robots":true,"min_interval_ms":1000,"exampleUrls":["https://app.coursedog.com/api/v1/cm/umn/courses/search","https://catalog.pratt.edu/courses","https://umtc.catalog.prod.coursedog.com/"],"routes":[{"match":{"hosts":["app.coursedog.com"],"pathPrefix":"/api/v1/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"coursedog_json"}}],"htmlRoutes":[{"id":"coursedog","match":{"exactSegments":false},"mode":"coursedog_html"}]},{"id":"courseleaf","name":"CourseLeaf University Course Catalogs","category":"public-records","description":"Universal extractor for CourseLeaf catalog pages (catalog..edu/courses// and program pages): course code, title, credits, description, requisites, and grading from div.courseblock. Fingerprint-gated; never calls /ribbit/, which CourseLeaf robots.txt files disallow.","domains":["catalog.unc.edu","catalog.colorado.edu","catalog.utexas.edu"],"universalEngine":true,"auth_mode":"html","min_interval_ms":2000,"strict_robots":true,"exampleUrls":["https://catalog.unc.edu/courses/comp/","https://catalog.colorado.edu/courses-a-z/csci/","https://catalog.utexas.edu/courses/acc/"],"htmlRoutes":[{"id":"courseleaf","match":{"exactSegments":false},"mode":"courseleaf_courses_html"}]},{"id":"courtlistener","name":"CourtListener Federal & State Case Law","category":"public-records","description":"Official CourtListener REST API v4 adapter for opinions, clusters, RECAP dockets, and court metadata with HTML fallback.","domains":["courtlistener.com","www.courtlistener.com"],"auth_mode":"key","exampleUrls":["https://www.courtlistener.com/api/rest/v4/courts/scotus/","https://www.courtlistener.com/api/rest/v4/clusters/108713/","https://www.courtlistener.com/opinion/108713/marbury-v-madison/"],"routes":[{"match":{"pathPrefix":"/api/rest/v4/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":4194304},"extract":{"jsonMode":"courtlistener_v4_json"}},{"match":{"exactSegments":false,"pathSegments":["opinion",{"param":"clusterId","charset":"digits","minLen":1,"maxLen":16}]},"twin":{"fetchUrl":"https://www.courtlistener.com/api/rest/v4/clusters/{clusterId}/","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":4194304},"extract":{"jsonMode":"courtlistener_v4_json"}},{"match":{"exactSegments":false,"pathSegments":["docket",{"param":"docketId","charset":"digits","minLen":1,"maxLen":16}]},"twin":{"fetchUrl":"https://www.courtlistener.com/api/rest/v4/dockets/{docketId}/","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":4194304},"extract":{"jsonMode":"courtlistener_v4_json"}}],"htmlRoutes":[{"id":"courtlistener","match":{"exactSegments":false},"mode":"courtlistener_html"}]},{"id":"coveo","name":"Coveo Cloud Search","category":"developer","description":"Opt-in page-key adapter for Coveo /rest/search/v2 endpoints; honors robots.txt Allow /rest/search and defaults OFF.","domains":["platform.cloud.coveo.com"],"universalEngine":true,"auth_mode":"page-key","requires_page_key_opt_in":true,"exampleUrls":["https://platform.cloud.coveo.com/rest/search/v2?organizationId=mycoveocloudv2organizationg8tp8wu3&access_token=xx564559b1-0045-48e1-953c-3addd1ee4457&q=coveo&numberOfResults=10"],"routes":[{"match":{"hostSubdomain":{"suffix":".cloud.coveo.com","param":"regionHost"},"pathEquals":["/rest/search/v2"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"jsonMode":"coveo"}}],"htmlRoutes":[{"id":"coveo","match":{"exactSegments":false},"mode":"coveo_html"}]},{"id":"cpsc-ebike-battery","name":"E-Bike Battery Safety Standards (UL 2849)","category":"public-records","description":"Extracts UL 2849 / UL 2271 e-bike electrical system and battery certification guidance from ul.com (complementing cpsc-recalls and ebike-state-laws).","domains":["ul.com","www.ul.com"],"auth_mode":"html","exampleUrls":["https://www.ul.com/services/e-bikes-certificationevaluating-and-testing-ul-2849","https://www.ul.com/industries/automotive-and-mobility/micromobility-device-evaluation-testing-and-certification","https://www.ul.com/resources/comparison-e-bikes-standards-en-15194-and-ul-2849"],"htmlRoutes":[{"id":"cpsc-ebike-battery","match":{"exactSegments":false},"mode":"cpsc_ebike_battery_html"}]},{"id":"cpsc-ebike-incidents","name":"CPSC SaferProducts E-Bike & Micromobility Incidents","category":"public-records","description":"Bounded SaferProducts.gov ProductType/ProductDescription JSON and PublicSearch HTML extractor for bicycle, e-bike, and battery incidents (path/query-disjoint from cpsc-recalls RecallNumber queries).","domains":["saferproducts.gov","www.saferproducts.gov"],"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://www.saferproducts.gov/RestWebServices/Recall?format=json&ProductType=Bicycle","https://www.saferproducts.gov/RestWebServices/Recall?format=json&ProductType=Scooter"],"routes":[{"match":{"hosts":["www.saferproducts.gov","saferproducts.gov"],"pathEquals":["/RestWebServices/Recall","/RestWebServices/Recall/"],"queryParams":[{"names":["ProductType","productType","producttype","PRODUCTTYPE"],"param":"productType","charset":"cpsc_query_term","minLen":2,"maxLen":60}]},"twin":{"fetchUrl":"https://www.saferproducts.gov/RestWebServices/Recall?format=json&ProductType={productType}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"cpsc_ebike_incidents_json"}},{"match":{"hosts":["www.saferproducts.gov","saferproducts.gov"],"pathEquals":["/RestWebServices/Recall","/RestWebServices/Recall/"],"queryParams":[{"names":["ProductDescription","productDescription","productdescription","PRODUCTDESCRIPTION"],"param":"productDesc","charset":"cpsc_query_term","minLen":2,"maxLen":80}]},"twin":{"fetchUrl":"https://www.saferproducts.gov/RestWebServices/Recall?format=json&ProductDescription={productDesc}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"cpsc_ebike_incidents_json"}}],"htmlRoutes":[{"id":"cpsc-ebike-incidents","match":{"hosts":["www.saferproducts.gov","saferproducts.gov"],"anyOf":[{"pathEquals":["/PublicSearch","/PublicSearch/"]},{"pathPrefix":"/PublicSearch/"}]},"mode":"cpsc_ebike_incidents_html"}]},{"id":"cpsc-recalls","name":"CPSC Recalls & SaferProducts.gov","category":"public-records","description":"Formats bounded saferproducts.gov RecallNumber queries via JSON twin and extracts structured recall details and RecallNumber from cpsc.gov/Recalls pages (never fetching the unfiltered 25 MiB SaferProducts dump).","domains":["www.saferproducts.gov","saferproducts.gov","www.cpsc.gov","cpsc.gov"],"exampleUrls":["https://www.saferproducts.gov/RestWebServices/Recall?format=json&RecallNumber=24123","https://www.cpsc.gov/Recalls/2027/Cipton-Recalls-Bicycle-Helmets-Due-to-Risk-of-Serious-Injury-or-Death-from-Head-Injury-Violate-Mandatory-Standard-for-Bicycle-Helmets"],"routes":[{"match":{"hosts":["www.saferproducts.gov","saferproducts.gov"],"pathEquals":["/RestWebServices/Recall","/RestWebServices/Recall/"],"queryParams":[{"names":["RecallNumber","recallnumber","recallNumber","RECALLNUMBER"],"param":"recallNum","charset":"cpsc_recall_num","minLen":2,"maxLen":24,"transform":"strip_dashes"}]},"twin":{"fetchUrl":"https://www.saferproducts.gov/RestWebServices/Recall?format=json&RecallNumber={recallNum}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"unwrapFirstArrayElement":true,"requireFields":["RecallNumber","Title"],"vars":{"title":{"paths":["Title"],"trim":true},"recallNumber":{"paths":["RecallNumber"],"trim":true},"recallDate":{"paths":["RecallDate"],"sliceMax":10},"lastPublishDate":{"paths":["LastPublishDate"],"sliceMax":10},"description":{"paths":["Description"],"trim":true},"descShort":{"paths":["Description"],"trim":true,"sliceMax":260},"consumerContact":{"paths":["ConsumerContact"],"trim":true},"recallUrl":{"paths":["URL"],"requireHttps":true},"hazards":{"paths":["Hazards"],"subField":"Name","join":"; ","limit":10},"remedies":{"paths":["Remedies"],"subField":"Name","join":"; ","limit":10},"manufacturers":{"paths":["Manufacturers"],"subField":"Name","join":", ","limit":10},"retailers":{"paths":["Retailers"],"subField":"Name","join":", ","limit":10},"injuries":{"paths":["Injuries"],"subField":"Name","join":"; ","limit":10}},"titleTemplate":"{title} (Recall #{recallNumber})","descriptionVar":"descShort","publishedTimeVar":"recallDate","bullets":[{"label":"Recall Number","template":"`{recallNumber}`"},{"label":"Recall Date","template":"{recallDate}","whenVar":"recallDate"},{"label":"Last Published","template":"{lastPublishDate}","whenVar":"lastPublishDate"},{"label":"Hazards","template":"{hazards}","whenVar":"hazards"},{"label":"Remedies","template":"{remedies}","whenVar":"remedies"},{"label":"Injuries / Incidents","template":"{injuries}","whenVar":"injuries"},{"label":"Manufacturers","template":"{manufacturers}","whenVar":"manufacturers"},{"label":"Retailers","template":"{retailers}","whenVar":"retailers"},{"label":"Consumer Contact","template":"{consumerContact}","whenVar":"consumerContact"},{"label":"CPSC URL","template":"{recallUrl}","whenVar":"recallUrl"}],"sections":[{"heading":"Description","textVar":"description"},{"heading":"Products","arrayPath":"Products","limit":25,"columns":[{"header":"Name","paths":["Name"]},{"header":"Model","paths":["Model"],"code":true},{"header":"Units","paths":["NumberOfUnits"]},{"header":"Type","paths":["Type"]}]},{"heading":"Images","arrayPath":"Images","limit":10,"requireItemVar":"imgUrl","collectLinkVars":["imgUrl"],"itemVars":{"imgUrl":{"paths":["URL"],"requireHttps":true},"imgCap":{"paths":["Caption"],"default":"Recall product image"}},"itemTemplate":"[{imgCap}]({imgUrl})"}],"linksVars":["recallUrl"],"recordFields":{"recallNumber":"{recallNumber}","title":"{title}","recallDate":"{recallDate}","url":"{recallUrl}","hazards":"{hazards}","remedies":"{remedies}","manufacturers":"{manufacturers}"}}}],"htmlRoutes":[{"match":{"anyOf":[{"hosts":["www.cpsc.gov","cpsc.gov"],"exactSegments":false,"pathSegments":["Recalls",{"param":"year","charset":"digits","minLen":4,"maxLen":4},{"param":"slug","charset":"url_seg"}]},{"hosts":["www.cpsc.gov","cpsc.gov"],"exactSegments":false,"pathSegments":["recalls",{"param":"year","charset":"digits","minLen":4,"maxLen":4},{"param":"slug","charset":"url_seg"}]}]},"mode":"dom","vars":{"title":{"cssText":["h1"],"metaKeys":["og:title"],"trim":true},"recallNumber":{"regexExtract":{"source":"doc_text_and_img_alts","pattern":"(?i)Recall\\s*(?:Number|No\\.?|#)\\s*:?\\s*([0-9]{2}-?[0-9]{2,5})","group":1},"trim":true},"recallDate":{"metaKeys":["article:published_time"],"cssText":["time",".recall-detail__date"],"trim":true},"summary":{"metaKeys":["description","og:description"],"trim":true},"body":{"cssHtmlToMd":["main article",".recall-detail",".node--type-recall","main","article"],"format":"strip_leading_h1"}},"requireVars":["title","body"],"titleTemplate":"{title}","descriptionVar":"summary","publishedTimeVar":"recallDate","bullets":[{"label":"Recall Number","template":"`{recallNumber}`","whenVar":"recallNumber"},{"label":"Recall Date","template":"{recallDate}","whenVar":"recallDate"}],"bodyVar":"body"}]},{"id":"crates-io","name":"Rust Crates.io","category":"developer","description":"Upgrades crates.io pages to the v1 JSON API with Cargo install command, MSRV, Cargo features, downloads, and release history.","domains":["crates.io","www.crates.io"],"exampleUrls":["https://crates.io/crates/serde"],"match":{"exactSegments":false,"pathSegments":["crates",{"param":"crateName","charset":"alnum_dash","minLen":1,"maxLen":64}]},"twin":{"fetchUrl":"https://crates.io/api/v1/crates/{crateName}","kind":"json","accept":"application/json"},"extract":{"requireFields":["crate.name"],"vars":{"name":{"paths":["crate.name"]},"ver":{"paths":["crate.max_stable_version","crate.max_version","versions.0.num"]},"desc":{"paths":["crate.description"],"trim":true},"license":{"paths":["versions.0.license"]},"msrv":{"paths":["versions.0.rust_version"]},"repo":{"paths":["crate.repository"]},"docs":{"paths":["crate.documentation"],"fallbackTemplate":"https://docs.rs/{name}"},"downloads":{"paths":["crate.downloads"],"format":"int_comma"},"features":{"paths":["versions.0.features"],"format":"object_keys","limit":14,"itemWrap":"`","join":", "},"categories":{"paths":["categories"],"subField":"category","join":", "},"keywords":{"paths":["keywords"],"subField":"keyword","join":", "}},"titleTemplate":"{name} v{ver} (Rust Crate)","titleWhenVar":"ver","titleFallbackTemplate":"{name} (Rust Crate)","descriptionVar":"desc","introVar":"desc","bullets":[{"label":"Cargo","template":"`cargo add {name}`"},{"label":"Version","template":"`{ver}`","whenVar":"ver"},{"label":"MSRV","template":"Rust `{msrv}`","whenVar":"msrv"},{"label":"License","template":"{license}","whenVar":"license"},{"label":"Downloads","template":"{downloads}","whenVar":"downloads"},{"label":"API Docs","template":"{docs}","whenVar":"docs"},{"label":"Repository","template":"{repo}","whenVar":"repo"},{"label":"Cargo Features","template":"{features}","whenVar":"features"},{"label":"Categories","template":"{categories}","whenVar":"categories"},{"label":"Keywords","template":"{keywords}","whenVar":"keywords"}],"sections":[{"heading":"Recent Releases","arrayPath":"versions","minItems":2,"limit":6,"columns":[{"header":"Version","paths":["num"],"code":true},{"header":"Published","paths":["created_at"],"sliceMax":10},{"header":"MSRV","paths":["rust_version"]}]}],"linksVars":["docs","repo"]}},{"id":"creator-digital-stores","name":"Gumroad, Lemon Squeezy, Payhip & Sellfy","category":"commerce-social","description":"Extracts digital product pricing, ratings, creator info, and descriptions from Gumroad, Lemon Squeezy, Payhip, and Sellfy storefronts via JSON-LD, OpenGraph, and DOM fallback.","domains":["gumroad.com","www.gumroad.com","*.gumroad.com","lemonsqueezy.com","www.lemonsqueezy.com","*.lemonsqueezy.com","payhip.com","www.payhip.com","sellfy.com","www.sellfy.com"],"universalEngine":true,"auth_mode":"html","min_interval_ms":1500,"strict_robots":true,"exampleUrls":["https://geoimgr.gumroad.com/l/geoimgr"],"htmlRoutes":[{"id":"creator-digital-stores","match":{"hosts":["gumroad.com","www.gumroad.com","*.gumroad.com","lemonsqueezy.com","www.lemonsqueezy.com","*.lemonsqueezy.com","payhip.com","www.payhip.com","sellfy.com","www.sellfy.com"],"anyOf":[{"pathPrefix":"/l/"},{"pathPrefix":"/buy/"},{"pathPrefix":"/checkout/buy/"},{"pathPrefix":"/b/"},{"pathPrefix":"/p/"},{"pathEquals":["/discover"]},{"pathPrefix":"/discover/"}]},"mode":"creator_digital_stores_html"},{"id":"creator-digital-stores","match":{"anyOf":[{"hostSubdomain":{"suffix":".sellfy.store","param":"storeSub"},"pathPrefix":"/p/"},{"hostSubdomain":{"suffix":".sellfy.store","param":"storeSub"},"pathPrefix":"/buy/"}]},"mode":"creator_digital_stores_html"}]},{"id":"cve-org","name":"CVE.org & CVE Services (CVE JSON 5.x)","category":"developer","description":"Extracts authoritative CVE JSON 5.x records from cveawg.mitre.org/api/cve/ and guards www.cve.org Vue CSR SPA shells.","domains":["cveawg.mitre.org","www.cve.org","cve.org"],"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://cveawg.mitre.org/api/cve/CVE-2024-3094"],"routes":[{"match":{"hosts":["cveawg.mitre.org"],"exactSegments":true,"pathSegments":["api","cve",{"param":"cveId","charset":"cve_id","transform":"upper"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"cve_org_json"}}],"htmlRoutes":[{"id":"cve-org","match":{"hosts":["www.cve.org","cve.org"],"exactSegments":false},"mode":"cve_org_html"}]},{"id":"dailymed","name":"NLM DailyMed Drug Labels","category":"research-health","description":"National Library of Medicine DailyMed v2 REST API adapter for JSON catalog endpoints and HL7 SPL XML documents with drugInfo HTML fallback.","domains":["dailymed.nlm.nih.gov"],"auth_mode":"pub","exampleUrls":["https://dailymed.nlm.nih.gov/dailymed/services/v2/spls.json?pagesize=2","https://dailymed.nlm.nih.gov/dailymed/services/v2/spls/0f3234b2-806e-4fab-99f5-b7d15177565b.xml","https://dailymed.nlm.nih.gov/dailymed/services/v2/drugnames.json?drug_name=lipitor&pagesize=2"],"routes":[{"match":{"pathPrefix":"/dailymed/services/v2/spls/","pathSuffix":".xml"},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"text/html","maxBytes":4194304},"extract":{"textMode":"dailymed_spl_xml"}},{"match":{"pathEquals":["/dailymed/services/v2/spls.json","/dailymed/services/v2/drugnames.json","/dailymed/services/v2/drugclasses.json","/dailymed/services/v2/ndcs.json","/dailymed/services/v2/rxcuis.json","/dailymed/services/v2/uniis.json"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"dailymed_list_json"}},{"match":{"pathEquals":["/dailymed/drugInfo.cfm"],"queryParams":[{"name":"setid","param":"setid","charset":"alnum_dash","minLen":32,"maxLen":40}]},"twin":{"fetchUrl":"https://dailymed.nlm.nih.gov/dailymed/services/v2/spls/{setid}.xml","kind":"text","accept":"text/html","maxBytes":4194304},"extract":{"textMode":"dailymed_spl_xml"}}],"htmlRoutes":[{"id":"dailymed","match":{"pathPrefix":"/dailymed/","exactSegments":false},"mode":"dailymed_html"}]},{"id":"datacite","name":"DataCite DOI & Commons Registry","category":"research-health","description":"Extracts DataCite JSON:API DOI metadata (titles, creators, publisher, resourceType, descriptions) from api.datacite.org and commons.datacite.org (without claiming doi.org).","domains":["api.datacite.org","commons.datacite.org"],"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://api.datacite.org/dois/10.5281/zenodo.24485086","https://api.datacite.org/dois/10.24406/publica-2155"],"routes":[{"match":{"hosts":["api.datacite.org"],"anyOf":[{"pathSegments":["dois",{"param":"doi","charset":"doi_rest","greedy":true,"minLen":8,"maxLen":240}]},{"exactSegments":true,"pathEquals":["/dois"]}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"datacite_json"}},{"match":{"hosts":["commons.datacite.org"],"pathSegments":["doi.org",{"param":"doi","charset":"doi_rest","greedy":true,"minLen":8,"maxLen":240}]},"twin":{"fetchUrl":"https://api.datacite.org/dois/{doi}","rawPathParams":["doi"],"kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"datacite_json"}}],"htmlRoutes":[{"id":"datacite","match":{"hosts":["commons.datacite.org"],"exactSegments":false},"mode":"datacite_html"}]},{"id":"dblp","name":"DBLP Computer Science Bibliography","category":"research-health","description":"Extracts DBLP publication/author search API JSON, direct /rec/*.xml records, and /rec/*.html pages while honoring Crawl-delay: 4 and rejecting Anubis PoW challenges.","domains":["dblp.org","www.dblp.org"],"auth_mode":"pub","min_interval_ms":4000,"max_concurrent":1,"strict_robots":true,"exampleUrls":["https://dblp.org/search/publ/api?q=attention+is+all+you+need&format=json&h=2","https://dblp.org/rec/conf/nips/VaswaniSPUJGKP17.html"],"routes":[{"match":{"hosts":["dblp.org","www.dblp.org"],"anyOf":[{"pathPrefix":"/search/publ/api"},{"pathPrefix":"/search/author/api"},{"pathPrefix":"/search/venue/api"}]},"twin":{"fetchUrl":"{requestUrl}","setQueryParams":{"format":"json"},"kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"dblp_json"}},{"match":{"hosts":["dblp.org","www.dblp.org"],"pathPrefix":"/rec/","pathSuffix":".xml"},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"application/xml","maxBytes":2097152},"extract":{"textMode":"dblp_xml"}}],"htmlRoutes":[{"id":"dblp","match":{"hosts":["dblp.org","www.dblp.org"],"exactSegments":false},"mode":"dblp_html"}]},{"id":"dealer-locator-pack","name":"Dealer Locator Pack (Bullseye, Storepoint, MetaLocator, Where2GetIt)","category":"commerce-social","description":"Opt-in page-key adapter pack for Bullseye, Storepoint, MetaLocator, and Where2GetIt locator APIs; defaults OFF and falls back to HTML/JSON-LD.","domains":["ws.bullseyelocations.com","www.bullseyelocations.com","api.storepoint.co","hosted.where2getit.com","api.metalocator.com"],"universalEngine":true,"auth_mode":"page-key","requires_page_key_opt_in":true,"exampleUrls":["https://api.storepoint.co/v1/169bd80d34b6b7/locations?all=true"],"routes":[{"match":{"anyOf":[{"hosts":["ws.bullseyelocations.com","www.bullseyelocations.com"],"pathEquals":["/RestSearch.svc/DoSearch2","/RestSearch.svc/DoSearch"]},{"hosts":["api.storepoint.co"],"pathPrefix":"/v1/"},{"hosts":["api.storepoint.co"],"pathPrefix":"/public/v1/"},{"hosts":["api.metalocator.com"],"pathPrefix":"/api/"},{"hosts":["hosted.where2getit.com"],"pathSegments":[{"param":"brand","charset":"alnum_dash","minLen":1,"maxLen":64},"responsive","ajax"]},{"hosts":["hosted.where2getit.com"],"pathSegments":[{"param":"brand","charset":"alnum_dash","minLen":1,"maxLen":64},"rest",{"param":"action","charset":"alnum_dash","minLen":1,"maxLen":64}]}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"jsonMode":"dealer_locator_pack"}}],"htmlRoutes":[{"id":"dealer-locator-pack","match":{"exactSegments":false},"mode":"dealer_locator_pack_html"}]},{"id":"deps-dev","name":"Open Source Insights (deps.dev)","category":"developer","description":"Extracts package versions, default/latest stable release, licenses, advisories, and dependencies via the deps.dev v3 JSON API.","domains":["deps.dev","api.deps.dev"],"auth_mode":"pub","exampleUrls":["https://api.deps.dev/v3/systems/npm/packages/express"],"routes":[{"match":{"hosts":["api.deps.dev"],"pathPrefix":"/v3/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"deps_dev_json"}},{"match":{"hosts":["deps.dev"],"exactSegments":false,"pathSegments":["npm",{"param":"scope","charset":"npm_scope","minLen":2,"maxLen":80},{"param":"pkg","charset":"npm_pkg","minLen":1,"maxLen":120}]},"twin":{"fetchUrl":"https://api.deps.dev/v3/systems/npm/packages/{scope}%2F{pkg}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"deps_dev_json"}},{"match":{"hosts":["deps.dev"],"exactSegments":false,"pathSegments":[{"param":"system","allowValues":["npm","pypi","cargo","nuget","go","maven"]},{"param":"pkg","charset":"url_seg","minLen":1,"maxLen":200}]},"twin":{"fetchUrl":"https://api.deps.dev/v3/systems/{system}/packages/{pkg}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"deps_dev_json"}}],"htmlRoutes":[{"id":"deps-dev","match":{"hosts":["deps.dev"],"exactSegments":false},"mode":"deps_dev_html"}]},{"id":"dev-to","name":"DEV Community Articles (dev.to)","category":"commerce-social","description":"Upgrades dev.to// articles to dev.to/api/articles raw body_markdown.","domains":["dev.to","www.dev.to"],"exampleUrls":["https://dev.to/ben/long-live-rails-3p21"],"match":{"exactSegments":true,"pathSegments":[{"param":"author","charset":"alnum_dash","reserved":["t","top","latest","pod","videos","tags","search","settings","enter","new","about","privacy","terms"]},{"param":"slug","charset":"alnum_dash"}]},"twin":{"fetchUrl":"https://dev.to/api/articles/{author}/{slug}","kind":"json","accept":"application/json"},"extract":{"requireFields":["title","body_markdown"],"vars":{"title":{"paths":["title"],"trim":true},"desc":{"paths":["description"],"trim":true},"author":{"paths":["user.name"]},"publishedTime":{"paths":["published_timestamp"]},"body":{"paths":["body_markdown"],"stripFrontmatter":true,"trim":true}},"titleTemplate":"{title}","descriptionVar":"desc","authorVar":"author","publishedTimeVar":"publishedTime","bodyVar":"body"}},{"id":"dining-reservations","name":"Dining Reservations (OpenTable / Resy / ToastTab)","category":"commerce-social","description":"Extracts public restaurant venue metadata from OpenTable, Resy, and ToastTab Local pages via Restaurant/FoodEstablishment JSON-LD and hydrated DOM while rejecting Cloudflare challenges and unhydrated Angular shells.","domains":["opentable.com","www.opentable.com","resy.com","www.resy.com","toasttab.com","www.toasttab.com"],"auth_mode":"html","min_interval_ms":2000,"max_concurrent":1,"strict_robots":true,"exampleUrls":["https://www.opentable.com/r/gary-danko-san-francisco","https://resy.com/cities/new-york-ny/venues/carbone","https://www.toasttab.com/local"],"htmlRoutes":[{"id":"dining-reservations","match":{"hosts":["opentable.com","www.opentable.com","resy.com","www.resy.com","toasttab.com","www.toasttab.com"]},"mode":"dining_reservations_html"}]},{"id":"discogs","name":"Discogs Music Database & Marketplace","category":"commerce-social","description":"Public and optionally keyed Discogs REST API adapter for releases, masters, artists, labels, and catalog search, with www.discogs.com HTML fallback and Cloudflare challenge rejection.","domains":["api.discogs.com","www.discogs.com","discogs.com"],"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://api.discogs.com/releases/249504","https://api.discogs.com/masters/1000","https://www.discogs.com/release/249504-Rick-Astley-Never-Gonna-Give-You-Up"],"routes":[{"match":{"hosts":["api.discogs.com"],"anyOf":[{"pathPrefix":"/releases/"},{"pathPrefix":"/masters/"},{"pathPrefix":"/artists/"},{"pathPrefix":"/labels/"},{"pathPrefix":"/database/search"}],"exactSegments":false},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"discogs_json"}},{"match":{"hosts":["www.discogs.com","discogs.com"],"optionalLeadingLocale":true,"exactSegments":true,"pathSegments":["release",{"param":"discogsId","charset":"leading_digits_slug","transform":"leading_digits","minLen":1,"maxLen":220}]},"twin":{"fetchUrl":"https://api.discogs.com/releases/{discogsId}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"discogs_json"}},{"match":{"hosts":["www.discogs.com","discogs.com"],"optionalLeadingLocale":true,"exactSegments":true,"pathSegments":["master",{"param":"discogsId","charset":"leading_digits_slug","transform":"leading_digits","minLen":1,"maxLen":220}]},"twin":{"fetchUrl":"https://api.discogs.com/masters/{discogsId}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"discogs_json"}},{"match":{"hosts":["www.discogs.com","discogs.com"],"optionalLeadingLocale":true,"exactSegments":true,"pathSegments":["artist",{"param":"discogsId","charset":"leading_digits_slug","transform":"leading_digits","minLen":1,"maxLen":220}]},"twin":{"fetchUrl":"https://api.discogs.com/artists/{discogsId}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"discogs_json"}},{"match":{"hosts":["www.discogs.com","discogs.com"],"optionalLeadingLocale":true,"exactSegments":true,"pathSegments":["label",{"param":"discogsId","charset":"leading_digits_slug","transform":"leading_digits","minLen":1,"maxLen":220}]},"twin":{"fetchUrl":"https://api.discogs.com/labels/{discogsId}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"discogs_json"}}],"htmlRoutes":[{"id":"discogs","match":{"hosts":["www.discogs.com","discogs.com"],"exactSegments":false},"mode":"discogs_html"}]},{"id":"discourse-topic","name":"Discourse Forum Threads (Universal Engine)","category":"commerce-social","description":"Upgrades any Discourse forum thread (/t//) to its .json post_stream with Accepted Solution badges.","domains":["meta.discourse.org","community.home-assistant.io","users.rust-lang.org","discuss.python.org"],"universalEngine":true,"exampleUrls":["https://community.home-assistant.io/t/how-to-help-us-help-you-or-how-to-ask-a-good-question/114371"],"match":{"exactSegments":false,"pathSegments":["t",{"param":"slug","charset":"url_seg"},{"param":"topicId","charset":"digits"}]},"twin":{"id":"discourse-topic","fetchUrl":"https://{host}/t/{slug}/{topicId}.json","kind":"json","accept":"application/json"},"extract":{"requireFields":["title"],"requireAnyFields":["post_stream.posts"],"vars":{"title":{"paths":["title"],"trim":true},"tags":{"paths":["tags"],"itemWrap":"`","join":", ","limit":20},"firstAuthor":{"paths":["post_stream.posts.0.username"]},"firstCreated":{"paths":["post_stream.posts.0.created_at"]},"acceptedPostNum":{"paths":["accepted_answer.post_number"]}},"titleTemplate":"{title}","authorVar":"firstAuthor","publishedTimeVar":"firstCreated","metaLine":[{"label":"Tags","template":"{tags}","whenVar":"tags"}],"sections":[{"heading":"","subsectionsArrayPath":"post_stream.posts","limit":20,"requireItemVar":"body","subsectionHeadingTemplate":"Original Post — {userWithDate}","subsectionAltWhenVar":"nonOpPostNum","subsectionAltHeadingTemplate":"{replyBadge} — {userWithDate}","subsectionBodyVar":"body","itemVars":{"postNum":{"paths":["post_number"],"fallbackTemplate":"{index1}"},"nonOpPostNum":{"paths":["post_number"],"excludeEquals":"1"},"isAcceptedFlag":{"paths":["accepted_answer"],"format":"bool_map","trueValue":"1","falseValue":""},"isAcceptedPostNum":{"paths":["post_number"],"equalsVar":"acceptedPostNum"},"replyBadge":{"template":"✅ Accepted Solution","whenAnyVars":["isAcceptedFlag","isAcceptedPostNum"],"fallbackTemplate":"Reply #{postNum}"},"username":{"paths":["username"]},"userLabel":{"template":"@{username}","whenVars":["username"],"default":"user"},"createdDate":{"paths":["created_at"],"sliceMax":10},"userWithDate":{"template":"{userLabel} ({createdDate})","whenVars":["createdDate"],"fallbackVar":"userLabel"},"body":{"paths":["cooked"],"format":"html_to_md"}}}]}},{"id":"dkan","name":"DKAN Open Data Portals (Metastore & Datastore)","category":"public-records","description":"Universal DKAN 2 adapter (data.medicaid.gov, data.healthcare.gov, and state/city DKAN portals): formats /api/1/metastore/schemas/dataset/items catalogs and single datasets (publisher, modified, keywords, distributions) and /api/1/datastore/query// rows with data-dictionary column labels. Dataset pages on declared portals upgrade to the metastore JSON while respecting dedicated CMS/HealthData adapters.","domains":["data.healthcare.gov"],"universalEngine":true,"auth_mode":"pub","min_interval_ms":2000,"exampleUrls":["https://data.healthcare.gov/api/1/metastore/schemas/dataset/items?show-reference-ids=false","https://data.healthcare.gov/api/1/datastore/query/ae4d5347-5137-5f6c-b66c-3420fa0316d8/0?limit=3","https://data.healthcare.gov/dataset/e4rr-zk4i"],"routes":[{"match":{"excludeHosts":["data.cms.gov","healthdata.gov","www.healthdata.gov"],"pathPrefix":"/api/1/metastore/schemas/dataset/items"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"dkan_metastore_json"}},{"match":{"excludeHosts":["data.cms.gov","healthdata.gov","www.healthdata.gov"],"exactSegments":false,"pathSegments":["api","1","datastore","query",{"param":"datasetId","charset":"slug","minLen":4,"maxLen":80}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"dkan_datastore_json"}},{"match":{"hosts":["data.healthcare.gov"],"exactSegments":true,"pathSegments":["dataset",{"param":"datasetId","charset":"slug","minLen":4,"maxLen":80}]},"twin":{"fetchUrl":"https://{host}/api/1/metastore/schemas/dataset/items/{datasetId}?show-reference-ids=false","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"dkan_metastore_json"}}]},{"id":"docker-hub","name":"Docker Hub","category":"developer","description":"Upgrades hub.docker.com repository and /tags pages (both /_/ official library and /r//) to the keyless Docker Hub v2 JSON API.","domains":["hub.docker.com"],"exampleUrls":["https://hub.docker.com/_/alpine","https://hub.docker.com/_/alpine/tags","https://hub.docker.com/r/library/nginx","https://hub.docker.com/r/library/nginx/tags"],"routes":[{"match":{"defaults":{"ns":"library"},"exactSegments":false,"pathSegments":["_",{"param":"repo","charset":"pkg","minLen":1,"maxLen":128},"tags"]},"twin":{"fetchUrl":"https://hub.docker.com/v2/repositories/library/{repo}/tags?page_size=25","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"requireAnyFields":["results"],"vars":{"totalCount":{"paths":["count"],"format":"int_comma"}},"titleTemplate":"{ns}/{repo} — Docker Tags ({totalCount} total)","titleWhenVar":"totalCount","titleFallbackTemplate":"{ns}/{repo} — Docker Tags","sections":[{"heading":"Recent Tags","arrayPath":"results","limit":25,"itemVars":{"platforms":{"paths":["images"],"subFieldsJoin":{"fields":["os","architecture"],"sep":"/"},"join":", ","limit":8},"sizeHuman":{"paths":["full_size"],"format":"bytes_human"}},"columns":[{"header":"Tag","paths":["name"],"code":true},{"header":"Size","template":"{sizeHuman}"},{"header":"Architectures","template":"{platforms}"},{"header":"Last Updated","paths":["last_updated"],"sliceMax":10}]}]}},{"match":{"exactSegments":false,"pathSegments":["r",{"param":"ns","charset":"pkg","minLen":1,"maxLen":128},{"param":"repo","charset":"pkg","minLen":1,"maxLen":128},"tags"]},"twin":{"fetchUrl":"https://hub.docker.com/v2/repositories/{ns}/{repo}/tags?page_size=25","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"requireAnyFields":["results"],"vars":{"totalCount":{"paths":["count"],"format":"int_comma"}},"titleTemplate":"{ns}/{repo} — Docker Tags ({totalCount} total)","titleWhenVar":"totalCount","titleFallbackTemplate":"{ns}/{repo} — Docker Tags","sections":[{"heading":"Recent Tags","arrayPath":"results","limit":25,"itemVars":{"platforms":{"paths":["images"],"subFieldsJoin":{"fields":["os","architecture"],"sep":"/"},"join":", ","limit":8},"sizeHuman":{"paths":["full_size"],"format":"bytes_human"}},"columns":[{"header":"Tag","paths":["name"],"code":true},{"header":"Size","template":"{sizeHuman}"},{"header":"Architectures","template":"{platforms}"},{"header":"Last Updated","paths":["last_updated"],"sliceMax":10}]}]}},{"match":{"defaults":{"ns":"library"},"exactSegments":false,"pathSegments":["_",{"param":"repo","charset":"pkg","minLen":1,"maxLen":128}]},"twin":{"fetchUrl":"https://hub.docker.com/v2/repositories/library/{repo}/","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"requireFields":["name","namespace"],"vars":{"namespace":{"paths":["namespace"]},"name":{"paths":["name"]},"desc":{"paths":["description"],"trim":true},"pulls":{"paths":["pull_count"],"format":"int_comma"},"stars":{"paths":["star_count"],"format":"int_comma"},"statusDesc":{"paths":["status_description"]},"lastUpdated":{"paths":["last_updated"],"sliceMax":10},"fullDesc":{"paths":["full_description"],"format":"demote_h1","trim":true}},"titleTemplate":"{namespace}/{name} (Docker Hub)","descriptionVar":"desc","publishedTimeVar":"lastUpdated","introVar":"desc","bullets":[{"label":"Pull Command","template":"`docker pull {name}`"},{"label":"Pulls","template":"{pulls}","whenVar":"pulls"},{"label":"Stars","template":"{stars}","whenVar":"stars"},{"label":"Status","template":"{statusDesc}","whenVar":"statusDesc"},{"label":"Last Updated","template":"{lastUpdated}","whenVar":"lastUpdated"}],"bodyVar":"fullDesc"}},{"match":{"exactSegments":false,"pathSegments":["r",{"param":"ns","charset":"pkg","minLen":1,"maxLen":128},{"param":"repo","charset":"pkg","minLen":1,"maxLen":128}]},"twin":{"fetchUrl":"https://hub.docker.com/v2/repositories/{ns}/{repo}/","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"requireFields":["name","namespace"],"vars":{"namespace":{"paths":["namespace"]},"name":{"paths":["name"]},"desc":{"paths":["description"],"trim":true},"pulls":{"paths":["pull_count"],"format":"int_comma"},"stars":{"paths":["star_count"],"format":"int_comma"},"statusDesc":{"paths":["status_description"]},"lastUpdated":{"paths":["last_updated"],"sliceMax":10},"fullDesc":{"paths":["full_description"],"format":"demote_h1","trim":true}},"titleTemplate":"{namespace}/{name} (Docker Hub)","descriptionVar":"desc","publishedTimeVar":"lastUpdated","introVar":"desc","bullets":[{"label":"Pull Command","template":"`docker pull {namespace}/{name}`"},{"label":"Pulls","template":"{pulls}","whenVar":"pulls"},{"label":"Stars","template":"{stars}","whenVar":"stars"},{"label":"Status","template":"{statusDesc}","whenVar":"statusDesc"},{"label":"Last Updated","template":"{lastUpdated}","whenVar":"lastUpdated"}],"bodyVar":"fullDesc"}}]},{"id":"docs-rs","name":"Rust docs.rs Crate Documentation","category":"developer","description":"Extracts Rust crate metadata, version, feature flags, doc coverage, and rustdoc API pages from docs.rs SSR HTML (avoiding /json zstd binary archives).","domains":["docs.rs"],"auth_mode":"pub","exampleUrls":["https://docs.rs/crate/serde/latest","https://docs.rs/serde/latest/serde/"],"htmlRoutes":[{"id":"docs-rs","match":{"hosts":["docs.rs"],"exactSegments":false},"mode":"docs_rs_html"}]},{"id":"doe-osti","name":"DOE OSTI.GOV Technical Reports & Records","category":"research-health","description":"Extracts U.S. Department of Energy scientific and technical records from www.osti.gov/api/v1/records (handling both top-level JSON arrays and objects) and /biblio/ HTML fallback.","domains":["www.osti.gov","osti.gov"],"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://www.osti.gov/api/v1/records/1800000","https://www.osti.gov/api/v1/records?q=solar&rows=2","https://www.osti.gov/biblio/1800000"],"routes":[{"match":{"hosts":["www.osti.gov","osti.gov"],"pathPrefix":"/api/v1/records"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"doe_osti_json"}},{"match":{"hosts":["www.osti.gov","osti.gov"],"exactSegments":true,"pathSegments":["biblio",{"param":"ostiId","charset":"digits","minLen":3,"maxLen":16}]},"twin":{"fetchUrl":"https://www.osti.gov/api/v1/records/{ostiId}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"doe_osti_json"}}],"htmlRoutes":[{"id":"doe-osti","match":{"hosts":["www.osti.gov","osti.gov"],"pathPrefix":"/biblio/","exactSegments":false},"mode":"doe_osti_html"}]},{"id":"doi-crossref","name":"DOI.org & Crossref Bibliographic Resolver","category":"research-health","description":"Upgrades doi.org/10./ links to api.crossref.org/works/ bibliographic JSON (authors, venue, citations, JATS abstract, and publisher URL).","domains":["doi.org","www.doi.org","dx.doi.org"],"exampleUrls":["https://doi.org/10.1038/s41586-021-03819-2"],"match":{"pathSegments":[{"param":"doi","charset":"doi_rest","greedy":true,"minLen":8,"maxLen":240}]},"twin":{"fetchUrl":"https://api.crossref.org/works/{doi}","kind":"json","accept":"application/json"},"extract":{"rootPath":"message","requireVars":["title"],"vars":{"title":{"paths":["title.0"],"fallbackTemplate":"{doi}","format":"strip_tags"},"authors":{"paths":["author"],"subFieldsJoin":{"fields":["given","family"],"sep":" ","fallbackField":"name"},"join":", ","limit":16},"authorsShort":{"paths":["author"],"subFieldsJoin":{"fields":["given","family"],"sep":" ","fallbackField":"name"},"join":", ","limit":4},"venue":{"paths":["container-title.0"]},"publisher":{"paths":["publisher"]},"venueFull":{"template":"{venue} ({publisher})","whenVars":["venue","publisher"],"fallbackVar":"venue"},"citations":{"paths":["is-referenced-by-count"],"format":"int_comma"},"pubUrl":{"paths":["URL"],"fallbackTemplate":"https://doi.org/{doi}","requireHttps":true},"pubDate":{"paths":["issued.date-parts.0"],"format":"date_parts"},"abstract":{"paths":["abstract"],"format":"jats_abstract"},"abstractShort":{"paths":["abstract"],"format":"jats_abstract","sliceMax":260}},"titleTemplate":"{title}","descriptionVar":"abstractShort","authorVar":"authorsShort","publishedTimeVar":"pubDate","bullets":[{"label":"DOI","template":"`{doi}`"},{"label":"Authors","template":"{authors}","whenVar":"authors"},{"label":"Venue / Journal","template":"{venueFull}","whenVar":"venueFull"},{"label":"Published","template":"{pubDate}","whenVar":"pubDate"},{"label":"Cited By (Crossref)","template":"{citations}","whenVar":"citations"},{"label":"Publisher Link","template":"{pubUrl}","whenVar":"pubUrl"}],"sections":[{"heading":"Abstract","textVar":"abstract"}],"linksVars":["pubUrl"]}},{"id":"dol-enforcement","name":"U.S. Department of Labor Enforcement & Data","category":"public-records","description":"Extracts Wage and Hour Division (WHD) and OSHA enforcement records from apiprod.dol.gov v4 APIs (DOL_API_KEY) with HTML fallback for dol.gov and enforcedata/data.dol.gov while rejecting empty data.dol.gov shells.","domains":["apiprod.dol.gov","enforcedata.dol.gov","data.dol.gov","www.dol.gov","dol.gov"],"auth_mode":"key","exampleUrls":["https://apiprod.dol.gov/v4/get/WHD/whd_enforcement/json?limit=2","https://apiprod.dol.gov/v4/get/OSHA/inspection/json?limit=2","https://www.dol.gov/agencies/whd/data"],"routes":[{"match":{"hosts":["apiprod.dol.gov"],"pathPrefix":"/v4/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":4194304},"extract":{"jsonMode":"dol_enforcement_json"}}],"htmlRoutes":[{"id":"dol-enforcement","match":{"hosts":["data.dol.gov","enforcedata.dol.gov","www.dol.gov","dol.gov"],"exactSegments":false},"mode":"dol_enforcement_html"}]},{"id":"dpla","name":"Digital Public Library of America (DPLA)","category":"public-records","description":"Digital Public Library of America (DPLA) API v2 adapter with HTML fallback and 2000ms Crawl-delay politeness.","domains":["dp.la","www.dp.la","api.dp.la"],"auth_mode":"key","min_interval_ms":2000,"exampleUrls":["https://api.dp.la/v2/items?q=kittens","https://dp.la/item/c3e08f4945e5b7d26386942a4a7f24a2"],"routes":[{"match":{"hosts":["api.dp.la"],"pathPrefix":"/v2/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"key"},"extract":{"jsonMode":"dpla_json"}},{"match":{"hosts":["dp.la","www.dp.la"],"exactSegments":false,"pathSegments":["item",{"param":"itemId","charset":"alnum_dash","minLen":4,"maxLen":64}]},"twin":{"fetchUrl":"https://api.dp.la/v2/items/{itemId}","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"key"},"extract":{"jsonMode":"dpla_json"}}],"htmlRoutes":[{"id":"dpla","match":{"hosts":["dp.la","www.dp.la"],"exactSegments":false,"reservedFirstSegment":["search","qa"]},"mode":"dpla_html"}]},{"id":"e-bike-state-laws","name":"E-Bike State Laws & Legislative Citations (NCSL & State Statutes)","category":"public-records","description":"Extracts electric-bicycle state legislation and statutory definitions from NCSL and state statute portals with markdown citations to Cornell LII and LegiScan (disjoint from ebike-state-laws).","domains":["ncsl.org","www.ncsl.org","revisor.mn.gov","www.revisor.mn.gov","app.leg.wa.gov","leg.colorado.gov","www.leg.colorado.gov","content.leg.colorado.gov"],"auth_mode":"html","min_interval_ms":1000,"exampleUrls":["https://www.ncsl.org/transportation/traffic-safety-trends-state-legislative-action-2025","https://www.revisor.mn.gov/statutes/cite/169.222","https://app.leg.wa.gov/RCW/default.aspx?cite=46.61.710","https://leg.colorado.gov/content/electric-bicycles"],"htmlRoutes":[{"id":"e-bike-state-laws","match":{"exactSegments":false},"mode":"e_bike_state_laws_html"}]},{"id":"ebay","name":"eBay Official Browse API","category":"commerce-social","description":"Extracts eBay item pricing, condition, MPN, strict GTIN, and search summaries via the official eBay Browse API.","domains":["ebay.com","www.ebay.com","api.ebay.com"],"auth_mode":"key","exampleUrls":["https://www.ebay.com/itm/133000133001","https://api.ebay.com/buy/browse/v1/item/v1|133000133001|0"],"routes":[{"match":{"hosts":["ebay.com","www.ebay.com"],"anyOf":[{"exactSegments":true,"pathSegments":["itm",{"param":"itemId","charset":"digits","minLen":6,"maxLen":16}]},{"exactSegments":false,"pathSegments":["itm",{"param":"slug","charset":"url_seg","maxLen":200},{"param":"itemId","charset":"digits","minLen":6,"maxLen":16}]}]},"twin":{"fetchUrl":"https://api.ebay.com/buy/browse/v1/item/v1|{itemId}|0","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"ebay_json"}},{"match":{"hosts":["api.ebay.com"],"pathPrefix":"/buy/browse/v1/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"ebay_json"}}]},{"id":"ebike-drive-systems","name":"E-Bike Drive Systems (Yamaha, Brose/QORE, Mahle, Fazua)","category":"commerce-social","description":"Extracts motor torque, watt ratings, battery Wh capacity, and technical specs from Yamaha, Brose/QORE, Mahle SmartBike, and Fazua e-bike drive pages.","domains":["yamahabicycles.com","www.yamahabicycles.com","global.yamaha-motor.com","brose-ebike.com","www.brose-ebike.com","qore-system.de","www.qore-system.de","mahle-smartbike.com","www.mahle-smartbike.com","fazua.com","www.fazua.com"],"auth_mode":"html","exampleUrls":["https://www.yamahabicycles.com/bikes/WabashRT","https://mahle-smartbike.com/x20/","https://fazua.com/en/products/ride-60/","https://www.qore-system.de/"],"htmlRoutes":[{"id":"ebike-drive-systems","match":{"exactSegments":false},"mode":"ebike_drive_systems_html"}]},{"id":"ebike-state-laws","name":"US E-Bike & Bicycle State Laws","category":"public-records","description":"Extracts US state electric bicycle and cycling statutes from PeopleForBikes Prismic/Next.js state tables and League of American Bicyclists state law profiles.","domains":["peopleforbikes.org","www.peopleforbikes.org","bikeleague.org","www.bikeleague.org"],"auth_mode":"html","exampleUrls":["https://www.peopleforbikes.org/electric-bikes/state-laws","https://www.peopleforbikes.org/electric-bikes/policies-and-laws","https://bikeleague.org/bike-laws/state-bike-laws/?bikelaw-by-state=colorado"],"htmlRoutes":[{"id":"ebike-state-laws","match":{"exactSegments":false},"mode":"ebike_state_laws_html"}]},{"id":"ecfr","name":"Electronic Code of Federal Regulations (eCFR)","category":"public-records","description":"Public eCFR Versioner and Search API adapter enforcing strict robots.txt politeness on structure, ancestry, versions, titles, and search endpoints.","domains":["ecfr.gov","www.ecfr.gov"],"auth_mode":"pub","strict_robots":true,"exampleUrls":["https://www.ecfr.gov/api/versioner/v1/titles.json","https://www.ecfr.gov/api/versioner/v1/ancestry/2025-01-01/title-16.json?part=1512","https://www.ecfr.gov/api/search/v1/results?query=bicycle&per_page=2"],"routes":[{"match":{"anyOf":[{"pathEquals":["/api/versioner/v1/titles.json","/api/search/v1/results","/api/admin/v1/agencies.json"]},{"pathPrefix":"/api/versioner/v1/structure/"},{"pathPrefix":"/api/versioner/v1/ancestry/"},{"pathPrefix":"/api/versioner/v1/versions/"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"ecfr_api_json"}},{"match":{"exactSegments":false,"pathSegments":["current",{"param":"title","charset":"alnum_dash","stripPrefix":"title-","minLen":1,"maxLen":12}]},"twin":{"fetchUrl":"https://www.ecfr.gov/api/search/v1/results?query=title+{title}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"ecfr_api_json"}}]},{"id":"ecode360-general-code","name":"eCode360 Municipal Codes","category":"public-records","description":"HTML extractor for General Code eCode360 municipal ordinances, chapters, and statutory sections.","domains":["ecode360.com","www.ecode360.com"],"auth_mode":"html","exampleUrls":["https://ecode360.com/44475260","https://ecode360.com/OR5214"],"htmlRoutes":[{"id":"ecode360-general-code","match":{"exactSegments":false},"mode":"ecode360_html"}]},{"id":"ecwid","name":"Ecwid Storefronts & REST API v3","category":"commerce-social","description":"Opt-in page-key adapter for Ecwid /api/v3/{storeId}/products JSON twins with clean HTML/JSON-LD storefront fallback when disabled.","domains":["app.ecwid.com","www.ecwid.com"],"universalEngine":true,"auth_mode":"page-key","requires_page_key_opt_in":true,"exampleUrls":["https://mdemo.company.site/Black-Tank-p109736045"],"routes":[{"match":{"hosts":["app.ecwid.com"],"pathSegments":["api","v3",{"param":"storeId","charset":"digits","minLen":1,"maxLen":20},"products"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"commerceMode":"ecwid_v3_json"}},{"match":{"hosts":["app.ecwid.com"],"pathSegments":["api","v3",{"param":"storeId","charset":"digits","minLen":1,"maxLen":20},"products",{"param":"productId","charset":"digits","minLen":1,"maxLen":20}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"commerceMode":"ecwid_v3_json"}}],"htmlRoutes":[{"id":"ecwid","match":{"exactSegments":false},"mode":"ecwid_html"}]},{"id":"edge-cloud-changelogs","name":"Edge & Cloud Changelogs (Cloudflare, Vercel, Netlify)","category":"developer","description":"Extracts RSS 2.0 and Atom 1.0 release changelogs from Cloudflare Developers, Vercel, and Netlify with same-origin HTML-to-feed upgrades.","domains":["developers.cloudflare.com","vercel.com","www.vercel.com","netlify.com","www.netlify.com"],"auth_mode":"pub","exampleUrls":["https://developers.cloudflare.com/changelog/rss/d1.xml","https://vercel.com/atom","https://www.netlify.com/changelog/feed.xml"],"routes":[{"match":{"hosts":["developers.cloudflare.com"],"anyOf":[{"pathEquals":["/changelog/rss/index.xml","/changelog/index.xml"]},{"pathPrefix":"/changelog/rss/","pathSuffix":".xml"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"application/xml","maxBytes":2097152},"extract":{"textMode":"edge_cloud_changelog_xml"}},{"match":{"hosts":["developers.cloudflare.com"],"pathEquals":["/changelog","/changelog/"]},"twin":{"fetchUrl":"https://developers.cloudflare.com/changelog/rss/index.xml","kind":"text","accept":"application/xml","maxBytes":2097152},"extract":{"textMode":"edge_cloud_changelog_xml"}},{"match":{"hosts":["vercel.com","www.vercel.com"],"pathEquals":["/atom","/changelog/atom"]},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"application/atom+xml","maxBytes":2097152},"extract":{"textMode":"edge_cloud_changelog_xml"}},{"match":{"hosts":["vercel.com","www.vercel.com"],"pathEquals":["/changelog","/changelog/"]},"twin":{"fetchUrl":"https://vercel.com/atom","kind":"text","accept":"application/atom+xml","maxBytes":2097152},"extract":{"textMode":"edge_cloud_changelog_xml"}},{"match":{"hosts":["netlify.com","www.netlify.com"],"pathEquals":["/changelog/feed.xml","/changelog/rss.xml"]},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"application/xml","maxBytes":2097152},"extract":{"textMode":"edge_cloud_changelog_xml"}},{"match":{"hosts":["netlify.com","www.netlify.com"],"pathEquals":["/changelog","/changelog/"]},"twin":{"fetchUrl":"https://www.netlify.com/changelog/feed.xml","kind":"text","accept":"application/xml","maxBytes":2097152},"extract":{"textMode":"edge_cloud_changelog_xml"}}],"htmlRoutes":[{"id":"edge-cloud-changelogs","match":{"hosts":["developers.cloudflare.com","vercel.com","www.vercel.com","netlify.com","www.netlify.com"],"pathPrefix":"/changelog","exactSegments":false},"mode":"edge_cloud_changelog_html"}]},{"id":"edlio-thrillshare","name":"Edlio & Apptegy Thrillshare","category":"public-records","description":"Extracts K-12 school district news feeds, events, and announcements from Edlio (/apps/news/, /apps/events/) and Apptegy Thrillshare portals.","domains":["*.edlio.com","*.apptegy.us","*.sites.thrillshare.com","www.worldcompassacademy.com","www.windsorc1.com","www.eupschools.org"],"universalEngine":true,"auth_mode":"html","strict_robots":true,"min_interval_ms":2000,"exampleUrls":["https://www.worldcompassacademy.com/apps/news/","https://www.windsorc1.com/o/wcmo/news","https://www.eupschools.org/"],"htmlRoutes":[{"id":"edlio-thrillshare","match":{"exactSegments":false},"mode":"edlio_thrillshare_html"}]},{"id":"edu-job-boards","name":"Education Job Boards (Chronicle Jobs, HigherEdJobs, K12JobSpot, EdJoin)","category":"jobs","description":"Extracts academic and K-12 JobPosting JSON-LD, Chronicle RSS feeds, and job board HTML while rejecting Incapsula/Cloudflare WAF challenges and unhydrated CSR templates.","domains":["jobs.chronicle.com","www.higheredjobs.com","higheredjobs.com","www.k12jobspot.com","k12jobspot.com","www.edjoin.org","edjoin.org"],"auth_mode":"pub","exampleUrls":["https://jobs.chronicle.com/job/38070836/director-of-occupational-therapy/","https://jobs.chronicle.com/jobsrss/?countrycode=US","https://www.k12jobspot.com/en","https://www.edjoin.org/Home/Jobs?keywords=teacher&searchType=all"],"routes":[{"match":{"hosts":["jobs.chronicle.com"],"pathPrefix":"/jobsrss","exactSegments":false},"twin":{"id":"edu-job-boards","fetchUrl":"{requestUrl}","kind":"text","accept":"application/rss+xml"},"extract":{"xml":{"mode":"items_table","requireAnyTags":["rss","channel"],"itemTag":"item","titleTemplate":"Chronicle of Higher Education Jobs ({itemCount})","emptyText":"No open academic positions currently listed.","limit":50,"requireItemVar":"jTitle","collectLinkVar":"jLink","emitTotals":true,"itemVars":{"jTitle":{"tags":["title"]},"jLink":{"tags":["link"]},"dept":{"tags":["category"],"default":"-"},"pubDate":{"tags":["pubDate"],"sliceMax":16,"default":"-"}},"recordFields":{"title":"{jTitle}","url":"{jLink}","category":"{dept}","postedAt":"{pubDate}","source":"chronicle"},"columns":[{"header":"Role","template":"[{jTitle}]({jLink})"},{"header":"Category","template":"{dept}"},{"header":"Published","template":"{pubDate}"}]}}}],"htmlRoutes":[{"id":"edu-job-boards","mode":"edu_job_boards_html","match":{"hosts":["jobs.chronicle.com","www.higheredjobs.com","higheredjobs.com","www.k12jobspot.com","k12jobspot.com","www.edjoin.org","edjoin.org"],"exactSegments":false}}]},{"id":"edx-coursera","name":"edX & Coursera Course Catalog","category":"public-records","description":"Extracts edX course catalog API JSON and Coursera / edX public course landing pages via Course JSON-LD and DOM metadata.","domains":["courses.edx.org","www.edx.org","edx.org","www.coursera.org","coursera.org"],"auth_mode":"pub","strict_robots":true,"min_interval_ms":1000,"exampleUrls":["https://courses.edx.org/api/courses/v1/courses/course-v1:HarvardX+CS50+X/","https://www.coursera.org/learn/machine-learning","https://www.edx.org/learn/python"],"routes":[{"match":{"hosts":["courses.edx.org"],"pathPrefix":"/api/courses/v1/courses"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"edx_course_json"}}],"htmlRoutes":[{"id":"edx-coursera","match":{"hosts":["courses.edx.org","www.edx.org","edx.org","www.coursera.org","coursera.org"],"exactSegments":false},"mode":"edx_coursera_html"}]},{"id":"eeoc-litigation","name":"EEOC Litigation & Enforcement Releases","category":"public-records","description":"Extracts EEOC enforcement press releases, litigation summaries, settlement figures, and district office metadata from eeoc.gov.","domains":["www.eeoc.gov","eeoc.gov"],"auth_mode":"pub","exampleUrls":["https://www.eeoc.gov/newsroom/boss-man-tacos-pay-42000-eeoc-sexual-harassment-suit","https://www.eeoc.gov/eeoc-litigation","https://www.eeoc.gov/newsroom"],"htmlRoutes":[{"id":"eeoc-litigation","match":{"exactSegments":false},"mode":"eeoc_litigation_html"}]},{"id":"eia","name":"U.S. Energy Information Administration (EIA)","category":"public-records","description":"U.S. Energy Information Administration Open Data v2 JSON API adapter with eia.gov HTML table/prose fallback.","domains":["eia.gov","www.eia.gov","api.eia.gov"],"auth_mode":"key","exampleUrls":["https://api.eia.gov/v2/petroleum/pri/gnd/data/?frequency=weekly&data[0]=value&length=10","https://www.eia.gov/opendata/","https://www.eia.gov/petroleum/gasdiesel/"],"routes":[{"match":{"hosts":["api.eia.gov"],"exactSegments":false,"pathPrefix":"/v2/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304,"auth_mode":"key"},"extract":{"jsonMode":"eia_json"}}],"htmlRoutes":[{"id":"eia","match":{"hosts":["eia.gov","www.eia.gov"],"exactSegments":false},"mode":"eia_html"}]},{"id":"electronics-retail-specs","name":"US Electronics Retailers Spec Extractor","category":"commerce-social","description":"Extracts structured Product JSON-LD and technical specification tables for Newegg, B&H Photo Video, and Micro Center.","domains":["newegg.com","www.newegg.com","bhphotovideo.com","www.bhphotovideo.com","microcenter.com","www.microcenter.com"],"auth_mode":"html","min_interval_ms":2000,"strict_robots":true,"exampleUrls":["https://www.microcenter.com/product/678482/amd-ryzen-7-7800x3d-raphael-am5-42ghz-8-core-boxed-processor-heatsink-not-included","https://www.bhphotovideo.com/c/product/1791390-REG/sony_ilce7m4_b.html"],"htmlRoutes":[{"id":"electronics-retail-specs","match":{"exactSegments":false},"mode":"electronics_retail_specs_html"}]},{"id":"endoflife-date","name":"endoflife.date Lifecycle Registry","category":"developer","description":"Extracts product release cycles, EOL dates, LTS windows, and latest versions from endoflife.date v1/legacy JSON APIs and SSR product pages.","domains":["endoflife.date"],"auth_mode":"pub","exampleUrls":["https://endoflife.date/api/python.json","https://endoflife.date/api/v1/products/python/","https://endoflife.date/python"],"routes":[{"match":{"hosts":["endoflife.date"],"pathPrefix":"/api/v1/products/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":1048576},"extract":{"jsonMode":"endoflife_json"}},{"match":{"hosts":["endoflife.date"],"pathPrefix":"/api/","pathSuffix":".json"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":1048576},"extract":{"jsonMode":"endoflife_json"}},{"match":{"hosts":["endoflife.date"],"exactSegments":true,"pathSegments":[{"param":"product","charset":"pkg","reserved":["api","docs","calendar","tags","categories","assets","feed.xml","robots.txt","sitemap.xml"]}]},"twin":{"fetchUrl":"https://endoflife.date/api/v1/products/{product}/","kind":"json","accept":"application/json","maxBytes":1048576},"extract":{"jsonMode":"endoflife_json"}}],"htmlRoutes":[{"id":"endoflife-date","match":{"hosts":["endoflife.date"],"exactSegments":false},"mode":"endoflife_html"}]},{"id":"energy-star","name":"ENERGY STAR Certified Products & Open Data","category":"public-records","description":"Extracts data.energystar.gov Socrata view/resource/catalog JSON datasets and energystar.gov HTML pages while rejecting unhydrated ProductFinder SPA shells.","domains":["data.energystar.gov","www.energystar.gov","energystar.gov"],"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://data.energystar.gov/api/views/7p2p-wkbf.json","https://data.energystar.gov/resource/7p2p-wkbf.json?$limit=5","https://data.energystar.gov/api/catalog/v1?q=certified&limit=3"],"routes":[{"match":{"hosts":["data.energystar.gov"],"anyOf":[{"pathPrefix":"/api/views/","pathSuffix":".json"},{"pathPrefix":"/resource/","pathSuffix":".json"},{"pathEquals":["/api/catalog/v1"]}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"energy_star_json"}},{"match":{"hosts":["data.energystar.gov"],"minSegments":2,"anyOf":[{"exactSegments":false,"pathSegments":["d",{"param":"viewId","charset":"socrata_4x4","transform":"lower"}]},{"scanSegment":{"lastOrBeforeLiteral":"about_data","param":"viewId","charset":"socrata_4x4","transform":"lower"}}]},"twin":{"fetchUrl":"https://data.energystar.gov/api/views/{viewId}.json","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"energy_star_json"}}],"htmlRoutes":[{"id":"energy-star","match":{"hosts":["www.energystar.gov","energystar.gov","data.energystar.gov"],"exactSegments":false},"mode":"energy_star_html"}]},{"id":"enterprise-ats-full","name":"Enterprise ATS Full (Eightfold, Phenom, Avature, Cornerstone)","category":"jobs","description":"Upgrades Eightfold /careers & /careers/job/ to robots-allowed /api/pcsx/search & /api/pcsx/position_details JSON twins, plus Phenom, Avature, and Cornerstone HTML extractors.","domains":["www.phenom.com","eightfold.ai","nvidia.eightfold.ai","paypal.eightfold.ai","bloomberg.avature.net","www.avature.net","www.csod.com","cornerstone.csod.com"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://nvidia.eightfold.ai/careers/job/893391708161","https://cornerstone.csod.com/ux/ats/careersite/2/home/requisition/11818?c=cornerstone","https://bloomberg.avature.net/careers/JobDetail/Senior-Software-Engineer-Electronic-Trading/46354"],"routes":[{"match":{"hostSubdomain":{"suffix":".eightfold.ai","param":"tenant","reserved":["www","api","login","auth","static"]},"pathPrefix":"/careers/job/","scanSegment":{"afterLiteral":"job","param":"jobId","charset":"slug","minLen":1,"maxLen":64}},"twin":{"fetchUrl":"https://{host}/api/pcsx/position_details?position_id={jobId}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"eightfold_job_json"}},{"match":{"hostSubdomain":{"suffix":".eightfold.ai","param":"tenant","reserved":["www","api","login","auth","static"]},"pathEquals":["/api/pcsx/position_details"],"queryParams":[{"name":"position_id","param":"jobId","charset":"slug","minLen":1,"maxLen":64}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"eightfold_job_json"}},{"match":{"hostSubdomain":{"suffix":".eightfold.ai","param":"tenant","reserved":["www","api","login","auth","static"]},"exactSegments":true,"pathSegments":["careers"],"queryParams":[{"name":"domain","param":"domain","charset":"pkg","minLen":3,"maxLen":120}]},"twin":{"fetchUrl":"https://{host}/api/pcsx/search?domain={domain}&query=&start=0","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"eightfold_board_json"}},{"match":{"hostSubdomain":{"suffix":".eightfold.ai","param":"tenant","reserved":["www","api","login","auth","static"]},"exactSegments":true,"pathSegments":["careers"]},"twin":{"fetchUrl":"https://{host}/api/pcsx/search?domain={tenant}.com&query=&start=0","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"eightfold_board_json"}},{"match":{"hostSubdomain":{"suffix":".eightfold.ai","param":"tenant","reserved":["www","api","login","auth","static"]},"pathEquals":["/api/pcsx/search"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"eightfold_board_json"}}],"htmlRoutes":[{"id":"enterprise-ats-full","mode":"enterprise_ats_full_html","match":{"excludeHosts":["recruiting.ultipro.com","recruiting.paylocity.com","app.dover.com","jobs.dover.com","jobs.smartrecruiters.com","*.oraclecloud.com","jobs.jobvite.com"],"anyOf":[{"hostSubdomain":{"suffix":".eightfold.ai","param":"tenant","reserved":["www","api","login","auth","static"]},"exactSegments":false},{"hosts":["careers.phenom.com","www.phenom.com"],"exactSegments":false},{"hostSubdomain":{"suffix":".avature.net","param":"tenant","reserved":["www","login","auth"]},"exactSegments":false},{"hosts":["www.avature.net"],"exactSegments":false},{"hostSubdomain":{"suffix":".csod.com","param":"tenant","reserved":["www","login","auth"]},"pathPrefix":"/ux/ats/careersite/","exactSegments":false},{"hosts":["www.csod.com"],"pathPrefix":"/ux/ats/careersite/","exactSegments":false}]}}]},{"id":"enterprise-ats","name":"SmartRecruiters, Oracle HCM Cloud & Jobvite","category":"jobs","description":"Keyless Oracle HCM Cloud recruitingCEJobRequisitions REST twin + robots.txt-safe SmartRecruiters and Jobvite HTML posting extractors.","domains":["jobs.smartrecruiters.com","*.oraclecloud.com","jobs.jobvite.com"],"exampleUrls":["https://jobs.smartrecruiters.com/Canva/6000000001554828-enterprise-security-manager-","https://eeho.fa.us2.oraclecloud.com/hcmUI/CandidateExperience/en/sites/CX_1001/requisitions","https://jobs.jobvite.com/optimizely/job/oHG8efwt"],"routes":[{"match":{"anyOf":[{"hosts":["*.fa.*oraclecloud.com"],"exactSegments":false,"pathSegments":["hcmUI","CandidateExperience",{"param":"lang","charset":"pkg"},"sites",{"param":"siteNumber","charset":"slug"}],"scanSegment":{"afterLiteral":"job","param":"reqId","charset":"slug"}},{"hosts":["*.fa.*oraclecloud.com"],"exactSegments":false,"pathContainsSegment":"requisitions","pathSegments":["hcmUI","CandidateExperience",{"param":"lang","charset":"pkg"},"sites",{"param":"siteNumber","charset":"slug"}],"scanSegment":{"afterLiteral":"preview","param":"reqId","charset":"slug"}},{"hosts":["*.fa.*oraclecloud.com"],"exactSegments":false,"pathSegments":["hcmUI","CandidateExperience","sites",{"param":"siteNumber","charset":"slug"}],"scanSegment":{"afterLiteral":"job","param":"reqId","charset":"slug"}},{"hosts":["*.fa.*oraclecloud.com"],"exactSegments":false,"pathContainsSegment":"requisitions","pathSegments":["hcmUI","CandidateExperience","sites",{"param":"siteNumber","charset":"slug"}],"scanSegment":{"afterLiteral":"preview","param":"reqId","charset":"slug"}},{"hosts":["*.fa.*oraclecloud.com"],"exactSegments":false,"pathSegments":["sites",{"param":"siteNumber","charset":"slug"}],"scanSegment":{"afterLiteral":"job","param":"reqId","charset":"slug"}},{"hosts":["*.fa.*oraclecloud.com"],"exactSegments":false,"pathContainsSegment":"requisitions","pathSegments":["sites",{"param":"siteNumber","charset":"slug"}],"scanSegment":{"afterLiteral":"preview","param":"reqId","charset":"slug"}}]},"twin":{"id":"oracle-hcm-job","fetchUrl":"https://{host}/hcmRestApi/resources/latest/recruitingCEJobRequisitionDetails?onlyData=true&expand=all&finder=ById;Id=%22{reqId}%22,siteNumber={siteNumber}","kind":"json","accept":"application/json"},"extract":{"rootPath":"items.0","requireFields":["Title"],"vars":{"jobTitle":{"paths":["Title"],"trim":true},"loc":{"paths":["PrimaryLocation"],"trim":true},"wp":{"paths":["WorkplaceType"],"trim":true},"posted":{"paths":["ExternalPostedStartDate"],"sliceMax":10,"trim":true},"extDesc":{"paths":["ExternalDescriptionStr"],"format":"html_to_md"},"extResp":{"paths":["ExternalResponsibilitiesStr"],"format":"html_to_md"},"extQual":{"paths":["ExternalQualificationsStr"],"format":"html_to_md"}},"titleTemplate":"{jobTitle}","publishedTimeVar":"posted","bullets":[{"label":"Requisition ID","template":"`{reqId}`"},{"label":"Primary Location","template":"{loc}","whenVar":"loc"},{"label":"Workplace","template":"{wp}","whenVar":"wp"},{"label":"Posted","template":"{posted}","whenVar":"posted"}],"bodyVar":"extDesc","sections":[{"heading":"Responsibilities","textVar":"extResp"},{"heading":"Qualifications","textVar":"extQual"}]}},{"match":{"anyOf":[{"hosts":["*.fa.*oraclecloud.com"],"pathSuffix":"/requisitions","scanSegment":{"afterLiteral":"sites","param":"siteNumber","charset":"slug"}},{"hosts":["*.fa.*oraclecloud.com"],"pathSuffix":"/requisitions/","scanSegment":{"afterLiteral":"sites","param":"siteNumber","charset":"slug"}},{"hosts":["*.fa.*oraclecloud.com"],"exactSegments":true,"pathSegments":["hcmUI","CandidateExperience",{"param":"lang","charset":"pkg"},"sites",{"param":"siteNumber","charset":"slug"}]},{"hosts":["*.fa.*oraclecloud.com"],"exactSegments":true,"pathSegments":["hcmUI","CandidateExperience","sites",{"param":"siteNumber","charset":"slug"}]},{"hosts":["*.fa.*oraclecloud.com"],"exactSegments":true,"pathSegments":["sites",{"param":"siteNumber","charset":"slug"}]}]},"twin":{"id":"oracle-hcm-board","fetchUrl":"https://{host}/hcmRestApi/resources/latest/recruitingCEJobRequisitions?onlyData=true&expand=requisitionList.secondaryLocations&finder=findReqs;siteNumber={siteNumber},limit=25","kind":"json","accept":"application/json"},"extract":{"rootPath":"items.0","vars":{"reqCount":{"paths":["requisitionList"],"format":"array_len"},"total":{"paths":["TotalJobsCount"],"fallbackTemplate":"{reqCount}"}},"requireVars":["reqCount"],"titleTemplate":"Oracle HCM ({siteNumber}) — Open Requisitions ({total})","sections":[{"heading":"","arrayPath":"requisitionList","limit":50,"emptyText":"No open requisitions currently listed.","itemVars":{"id":{"paths":["Id"]},"rTitle":{"paths":["Title"],"trim":true,"default":"Requisition"},"rUrl":{"template":"https://{host}/hcmUI/CandidateExperience/en/sites/{siteNumber}/job/{id}"},"loc":{"paths":["PrimaryLocation"],"trim":true,"default":"-"},"wp":{"paths":["WorkplaceType"],"trim":true,"default":"-"},"posted":{"paths":["PostedDate"],"sliceMax":10,"trim":true,"default":"-"}},"collectLinkVars":["rUrl"],"columns":[{"header":"Requisition","template":"[{rTitle}]({rUrl})"},{"header":"Location","template":"{loc}"},{"header":"Workplace","template":"{wp}"},{"header":"Posted","template":"{posted}"}]}]}}],"htmlRoutes":[{"id":"smartrecruiters","mode":"dom","match":{"hosts":["jobs.smartrecruiters.com"],"exactSegments":false,"minSegments":2,"pathSegments":[{"param":"org","charset":"pkg"}]},"jsonLdTypes":["JobPosting"],"vars":{"jobTitle":{"jsonLdPaths":["title"],"cssText":["h1.job-title"]},"company":{"jsonLdPaths":["hiringOrganization.name"],"fallbackTemplate":"{org}"},"body":{"cssHtmlToMd":["div[itemprop=\"description\"]","section#st-jobDescription"],"jsonLdPaths":["description"]}},"requireVars":["jobTitle","body"],"titleTemplate":"{jobTitle} @ {company}","bodyVar":"body"},{"id":"jobvite","mode":"dom","match":{"hosts":["jobs.jobvite.com"],"exactSegments":false,"pathSegments":[{"param":"org","charset":"pkg"},"job",{"param":"jobId","charset":"pkg"}]},"vars":{"jobTitle":{"cssText":["h2.jv-header"]},"meta":{"cssText":["p.jv-job-detail-meta"]},"body":{"cssHtmlToMd":["div.jv-job-detail-description"]}},"requireVars":["jobTitle","body"],"titleTemplate":"{jobTitle} @ {org}","metaItalicTemplate":"{meta}","metaItalicWhenVar":"meta","bodyVar":"body"}]},{"id":"epa-envirofacts-echo","name":"EPA Envirofacts & ECHO","category":"research-health","description":"US EPA Envirofacts REST API (data.epa.gov/efservice), ECHO REST services, and echo.epa.gov HTML facility fallback with strict robots.txt politeness.","domains":["data.epa.gov","enviro.epa.gov","echo.epa.gov","echodata.epa.gov"],"auth_mode":"pub","strict_robots":true,"min_interval_ms":10000,"exampleUrls":["https://data.epa.gov/efservice/tri_facility/state_abbr/DC/rows/0:2/JSON","https://echo.epa.gov/detailed-facility-report?fid=110000350174"],"routes":[{"match":{"hosts":["data.epa.gov"],"pathPrefix":"/efservice/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"epa_envirofacts_json"}},{"match":{"hosts":["enviro.epa.gov"],"pathPrefix":"/enviro/efservice/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"epa_envirofacts_json"}},{"match":{"hosts":["echodata.epa.gov"],"pathPrefix":"/echo/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"epa_envirofacts_json"}}],"htmlRoutes":[{"id":"epa-envirofacts-echo","match":{"hosts":["echo.epa.gov"],"exactSegments":false},"mode":"epa_echo_html"}]},{"id":"epa-fueleconomy","name":"EPA FuelEconomy.gov","category":"public-records","description":"U.S. DOE/EPA FuelEconomy.gov /ws/rest/ JSON API adapter for vehicle MPG, range, CO2, and make/model/year menus.","domains":["fueleconomy.gov","www.fueleconomy.gov"],"auth_mode":"pub","exampleUrls":["https://www.fueleconomy.gov/ws/rest/vehicle/41276","https://www.fueleconomy.gov/ws/rest/vehicle/menu/make?year=2024"],"routes":[{"match":{"pathPrefix":"/ws/rest/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"fueleconomy_json"}}]},{"id":"etsy","name":"Etsy Open API v3","category":"commerce-social","description":"Extracts Etsy listing title, converted price, SKU, quantity, state, and shop search results via the official Etsy Open API v3.","domains":["etsy.com","www.etsy.com","openapi.etsy.com"],"auth_mode":"key","exampleUrls":["https://www.etsy.com/listing/134000134/walnut-desk-tray","https://openapi.etsy.com/v3/application/listings/134000134"],"routes":[{"match":{"hosts":["etsy.com","www.etsy.com"],"exactSegments":false,"pathSegments":["listing",{"param":"listingId","charset":"digits","minLen":5,"maxLen":16}]},"twin":{"fetchUrl":"https://openapi.etsy.com/v3/application/listings/{listingId}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"etsy_json"}},{"match":{"hosts":["openapi.etsy.com"],"pathPrefix":"/v3/application/listings"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"etsy_json"}}]},{"id":"eur-lex","name":"EUR-Lex","category":"public-records","description":"Upgrades eur-lex.europa.eu/legal-content//TXT/?uri=* pages to the static /TXT/HTML/?uri=* twin while respecting robots.txt Crawl-delay and never touching disallowed /TXT/DOC/.","domains":["eur-lex.europa.eu"],"exampleUrls":["https://eur-lex.europa.eu/legal-content/EN/TXT/?uri=CELEX:32016R0679"],"match":{"exactSegments":true,"pathSegments":["legal-content",{"param":"lang","charset":"alnum","minLen":2,"maxLen":3,"transform":"upper"},"TXT"],"queryParams":[{"name":"uri","param":"uri","charset":"safe_subpath","minLen":3,"maxLen":200}]},"twin":{"fetchUrl":"https://eur-lex.europa.eu/legal-content/{lang}/TXT/HTML/?uri={uri}","kind":"text","accept":"text/html","maxBytes":4194304},"extract":{"textMode":"html_document","titleTemplate":"EUR-Lex {uri} ({lang})"}},{"id":"eventbrite","name":"Eventbrite Events","category":"commerce-social","description":"Extracts Eventbrite event details via the official Eventbrite v3 API when configured, with Event/Festival JSON-LD and __NEXT_DATA__ HTML fallback.","domains":["eventbrite.com","www.eventbrite.com","www.eventbriteapi.com"],"auth_mode":"key","exampleUrls":["https://www.eventbrite.com/e/music-mimosa-festival-fall-edition-tickets-2004426596909","https://www.eventbriteapi.com/v3/events/2004426596909/"],"routes":[{"match":{"hosts":["www.eventbriteapi.com"],"pathPrefix":"/v3/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"key"},"extract":{"jsonMode":"eventbrite_json"}},{"match":{"hosts":["eventbrite.com","www.eventbrite.com"],"exactSegments":true,"pathSegments":["e",{"param":"eventId","charset":"digits","minLen":6,"maxLen":20}]},"twin":{"fetchUrl":"https://www.eventbriteapi.com/v3/events/{eventId}/","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"key"},"extract":{"jsonMode":"eventbrite_json"}}],"htmlRoutes":[{"id":"eventbrite","match":{"hosts":["eventbrite.com","www.eventbrite.com"],"exactSegments":false},"mode":"eventbrite_html"}]},{"id":"everycrsreport","name":"EveryCRSReport Archive","category":"public-records","description":"Extracts Congressional Research Service reports from EveryCRSReport JSON metadata, /reports/{id}.html JSON twins, and bounded /reports.csv index.","domains":["www.everycrsreport.com","everycrsreport.com"],"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://www.everycrsreport.com/reports/IN11532.json","https://www.everycrsreport.com/reports/IN11532.html","https://www.everycrsreport.com/reports.csv"],"routes":[{"match":{"exactSegments":true,"pathSuffix":".json","pathSegments":["reports",{"param":"reportId","charset":"alnum_dash","stripSuffix":".json","minLen":2,"maxLen":32}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":1048576},"extract":{"jsonMode":"everycrs_json"}},{"match":{"exactSegments":true,"pathSuffix":".html","pathSegments":["reports",{"param":"reportId","charset":"alnum_dash","stripSuffix":".html","minLen":2,"maxLen":32}]},"twin":{"fetchUrl":"https://{host}/reports/{reportId}.json","kind":"json","accept":"application/json","maxBytes":1048576},"extract":{"jsonMode":"everycrs_json"}},{"match":{"exactSegments":true,"pathEquals":["/reports.csv"]},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"text/plain","headers":{"Range":"bytes=0-524287"},"maxBytes":1048576},"extract":{"textMode":"everycrs_csv"}}],"htmlRoutes":[{"id":"everycrsreport","match":{"exactSegments":false},"mode":"everycrs_html"}]},{"id":"exploit-db","name":"Exploit Database (Exploit-DB)","category":"developer","description":"Extracts Exploit-DB SSR exploit pages and RSS feeds on exploit-db.com plus bounded Range-streaming CSV extraction on GitLab exploitdb/files_exploits.csv.","domains":["www.exploit-db.com","exploit-db.com"],"universalEngine":true,"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://www.exploit-db.com/exploits/51000","https://www.exploit-db.com/rss.xml"],"routes":[{"match":{"hosts":["gitlab.com"],"exactSegments":true,"pathEquals":["/exploit-database/exploitdb/-/raw/main/files_exploits.csv"]},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"text/plain","headers":{"Range":"bytes=0-2097151"},"maxBytes":2097152},"extract":{"textMode":"exploit_db_csv"}},{"match":{"hosts":["www.exploit-db.com","exploit-db.com"],"exactSegments":true,"pathEquals":["/rss.xml"]},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"application/rss+xml","maxBytes":2097152},"extract":{"textMode":"exploit_db_rss"}}],"htmlRoutes":[{"id":"exploit-db","match":{"hosts":["www.exploit-db.com","exploit-db.com"],"exactSegments":false},"mode":"exploit_db_html"}]},{"id":"faa-registry","name":"FAA Aircraft Registry","category":"public-records","description":"FAA Civil Aviation Registry HTML extractor for N-Number lookups (/aircraftinquiry/Search/NNumberResult); note origin Akamai may return 403 to non-browser bot UAs.","domains":["registry.faa.gov"],"auth_mode":"html","strict_robots":true,"exampleUrls":["https://registry.faa.gov/aircraftinquiry/Search/NNumberResult?NNumberTxt=N101"],"htmlRoutes":[{"id":"faa-registry","match":{"hosts":["registry.faa.gov"],"pathPrefix":"/aircraftinquiry/search/","excludeSegmentSuffixes":[".asp"],"exactSegments":false},"mode":"faa_registry_html"}]},{"id":"farcaster-hub","name":"Farcaster Hub & Fnames API","category":"commerce-social","description":"Extracts Farcaster casts, user data, and fname transfers from Neynar Hub HTTP API (NEYNAR_API_KEY), public Hubble nodes (/v1/castsByFid, /v1/castById, /v1/userDataByFid), fnames.farcaster.xyz, and farcaster.xyz SSR fallback.","domains":["hub-api.neynar.com","fnames.farcaster.xyz","farcaster.xyz"],"universalEngine":true,"auth_mode":"key","min_interval_ms":500,"exampleUrls":["https://fnames.farcaster.xyz/transfers?fid=3","https://farcaster.xyz/dwr","https://hub-api.neynar.com/v1/castsByFid?fid=3&pageSize=5"],"routes":[{"match":{"hosts":["hub-api.neynar.com"],"pathPrefix":"/v1/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"farcaster_hub_json"}},{"match":{"hosts":["fnames.farcaster.xyz"],"pathPrefix":"/transfers"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"pub","maxBytes":2097152},"extract":{"jsonMode":"farcaster_hub_json"}},{"match":{"excludeHosts":["hub-api.neynar.com","api.farcaster.xyz","client.farcaster.xyz","snapchain.farcaster.xyz"],"pathEquals":["/v1/castsByFid","/v1/castById","/v1/userDataByFid"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"pub","maxBytes":2097152},"extract":{"jsonMode":"farcaster_hub_json"}}],"htmlRoutes":[{"id":"farcaster-hub","match":{"hosts":["farcaster.xyz"],"exactSegments":false},"mode":"farcaster_html"}]},{"id":"fcc-ecfs","name":"FCC Electronic Comment Filing System (ECFS)","category":"public-records","description":"Extracts FCC Electronic Comment Filing System (ECFS) filings, proceedings, filers, and comment text via publicapi.fcc.gov/ecfs/ (api.data.gov key) with HTML fallback on www.fcc.gov/ecfs/.","domains":["publicapi.fcc.gov","www.fcc.gov","fcc.gov"],"auth_mode":"key","exampleUrls":["https://publicapi.fcc.gov/ecfs/filings?limit=2","https://www.fcc.gov/ecfs/search/search-filings"],"routes":[{"match":{"hosts":["publicapi.fcc.gov"],"pathPrefix":"/ecfs/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":4194304},"extract":{"jsonMode":"fcc_ecfs_json"}}],"htmlRoutes":[{"id":"fcc-ecfs","match":{"hosts":["www.fcc.gov","fcc.gov"],"pathPrefix":"/ecfs"},"mode":"fcc_ecfs_html"}]},{"id":"fcc-id","name":"FCC ID Equipment Authorization","category":"public-records","description":"Extracts FCC ID grant metadata, technical frequency/power tables, and exhibit PDF links from fccid.io public HTML pages while respecting robots.txt disallows.","domains":["fccid.io","www.fccid.io"],"exampleUrls":["https://fccid.io/BCG-E3542A"],"htmlRoutes":[{"id":"fcc-id","mode":"fcc_id_html","match":{"exactSegments":false,"reservedFirstSegment":["ViewExhibitReport.cfm","subscribe.php","frequency","search","api"],"pathSegments":[{"param":"grantee","charset":"url_seg","minLen":2,"maxLen":64},{"param":"product","charset":"url_seg","optional":true,"minLen":1,"maxLen":120}]}}]},{"id":"fcc-test-report","name":"FCC OET Equipment Authorization & Test Reports","category":"public-records","description":"Extracts FCC OET Equipment Authorization System (EAS) grant metadata and test-report exhibit links on apps.fcc.gov while strictly rejecting Akamai Access Denied and empty search form shells.","domains":["apps.fcc.gov"],"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://apps.fcc.gov/oetcf/eas/reports/GenericSearch.cfm"],"routes":[{"match":{"hosts":["apps.fcc.gov"],"pathPrefix":"/oetcf/eas/","pathSuffix":".json"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"fcc_test_report_json"}}],"htmlRoutes":[{"id":"fcc-test-report","match":{"hosts":["apps.fcc.gov"],"pathPrefix":"/oetcf/eas/","exactSegments":false},"mode":"fcc_test_report_html"}]},{"id":"fcc-uls","name":"FCC Universal Licensing System (ULS)","category":"public-records","description":"Extracts FCC Universal Licensing System (ULS) Socrata datasets and catalog records on opendata.fcc.gov, legacy License View JSON on data.fcc.gov, and wireless2.fcc.gov HTML pages.","domains":["opendata.fcc.gov","data.fcc.gov","wireless2.fcc.gov"],"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://opendata.fcc.gov/resource/dpvg-tvcx.json?$limit=2","https://opendata.fcc.gov/api/catalog/v1?q=ULS&limit=3","https://opendata.fcc.gov/api/views/dpvg-tvcx.json"],"routes":[{"match":{"hosts":["opendata.fcc.gov"],"pathPrefix":"/resource/","pathSuffix":".json"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"fcc_uls_json"}},{"match":{"hosts":["opendata.fcc.gov"],"pathPrefix":"/api/views/","pathSuffix":".json"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"fcc_uls_json"}},{"match":{"hosts":["opendata.fcc.gov"],"pathPrefix":"/api/catalog/v1"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"fcc_uls_json"}},{"match":{"hosts":["data.fcc.gov"],"pathPrefix":"/api/license-view/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"fcc_uls_json"}}],"htmlRoutes":[{"id":"fcc-uls","match":{"hosts":["wireless2.fcc.gov","opendata.fcc.gov","data.fcc.gov"],"exactSegments":false},"mode":"fcc_uls_html"}]},{"id":"fdic-bankfind","name":"FDIC BankFind Suite","category":"finance","description":"Extracts insured institution profiles and failed bank lists directly from api.fdic.gov/banks/ (avoiding banks.data.fdic.gov/api 301 redirects) with 1 req/s politeness and SPA shell rejection.","domains":["banks.data.fdic.gov","api.fdic.gov","www.fdic.gov","fdic.gov"],"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://api.fdic.gov/banks/institutions?filters=CERT:3511&limit=1","https://www.fdic.gov/resources/resolutions/bank-failures/","https://api.fdic.gov/banks/failures?limit=1"],"routes":[{"match":{"hosts":["api.fdic.gov"],"pathPrefix":"/banks/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"pub","maxBytes":2097152},"extract":{"jsonMode":"fdic_bankfind_json"}},{"match":{"hosts":["banks.data.fdic.gov"],"exactSegments":false,"pathSegments":["api",{"param":"endpoint","charset":"url_seg","minLen":2,"maxLen":64}]},"twin":{"fetchUrl":"https://api.fdic.gov/banks/{endpoint}","kind":"json","accept":"application/json","auth_mode":"pub","maxBytes":2097152},"extract":{"jsonMode":"fdic_bankfind_json"}},{"match":{"hosts":["www.fdic.gov","fdic.gov"],"pathPrefix":"/resources/resolutions/bank-failures"},"twin":{"fetchUrl":"https://api.fdic.gov/banks/failures?sort_by=FAILDATE&sort_order=DESC&limit=25","kind":"json","accept":"application/json","auth_mode":"pub","maxBytes":2097152},"extract":{"jsonMode":"fdic_bankfind_json"}}],"htmlRoutes":[{"id":"fdic-bankfind","match":{"hosts":["banks.data.fdic.gov","www.fdic.gov","fdic.gov"],"exactSegments":false},"mode":"fdic_bankfind_html"}]},{"id":"fec","name":"FEC Campaign Finance","category":"public-records","description":"Upgrades fec.gov candidate and committee pages to official OpenFEC API v1 JSON summaries via api.data.gov key helper with HTML fallback.","domains":["www.fec.gov","fec.gov","api.open.fec.gov"],"auth_mode":"key","exampleUrls":["https://www.fec.gov/data/candidate/S8FL00216/","https://api.open.fec.gov/v1/candidate/S8FL00216/"],"routes":[{"match":{"hosts":["www.fec.gov","fec.gov"],"exactSegments":false,"pathSegments":["data","candidate",{"param":"candId","charset":"alnum","minLen":6,"maxLen":16}]},"twin":{"fetchUrl":"https://api.open.fec.gov/v1/candidate/{candId}/","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"fec_json"}},{"match":{"hosts":["www.fec.gov","fec.gov"],"exactSegments":false,"pathSegments":["data","committee",{"param":"commId","charset":"alnum","minLen":6,"maxLen":16}]},"twin":{"fetchUrl":"https://api.open.fec.gov/v1/committee/{commId}/","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"fec_json"}},{"match":{"hosts":["api.open.fec.gov"],"pathPrefix":"/v1/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"fec_json"}}],"htmlRoutes":[{"id":"fec","match":{"hosts":["www.fec.gov","fec.gov"],"exactSegments":false},"mode":"fec_html"}]},{"id":"fed-h15-datadownload","name":"Federal Reserve H.15 Selected Interest Rates","category":"finance","description":"Extracts Federal Reserve H.15 Selected Interest Rates CSV data downloads and release/selection HTML tables (#h15table).","domains":["www.federalreserve.gov","federalreserve.gov"],"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://www.federalreserve.gov/datadownload/Output.aspx?rel=H15&series=bf17364827e38702b42a58cf8eaa3f78&lastobs=5&from=&to=&filetype=csv&label=include&layout=seriescolumn","https://www.federalreserve.gov/releases/h15/","https://www.federalreserve.gov/datadownload/Choose.aspx?rel=H15"],"routes":[{"match":{"hosts":["www.federalreserve.gov","federalreserve.gov"],"pathPrefix":"/datadownload/Output.aspx"},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"text/plain","maxBytes":2097152},"extract":{"textMode":"fed_h15_csv"}}],"htmlRoutes":[{"id":"fed-h15-datadownload","match":{"hosts":["www.federalreserve.gov","federalreserve.gov"],"pathPrefix":"/releases/h15"},"mode":"fed_h15_html"},{"id":"fed-h15-datadownload","match":{"hosts":["www.federalreserve.gov","federalreserve.gov"],"pathPrefix":"/datadownload/Choose.aspx"},"mode":"fed_h15_html"}]},{"id":"federal-register","name":"Federal Register","category":"public-records","description":"Upgrades federalregister.gov/documents///
//* pages to the official /api/v1/documents/.json twin (strictly excluding disallowed /documents/current).","domains":["www.federalregister.gov","federalregister.gov"],"exampleUrls":["https://www.federalregister.gov/documents/2024/05/07/2024-09171/non-compete-clause-rule"],"match":{"exactSegments":false,"pathSegments":["documents",{"param":"yyyy","charset":"digits","minLen":4,"maxLen":4},{"param":"mm","charset":"digits","minLen":2,"maxLen":2},{"param":"dd","charset":"digits","minLen":2,"maxLen":2},{"param":"docNumber","charset":"alnum_dash","minLen":3,"maxLen":64}]},"twin":{"fetchUrl":"https://www.federalregister.gov/api/v1/documents/{docNumber}.json","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"requireFields":["title","document_number"],"vars":{"title":{"paths":["title"],"trim":true},"docNumber":{"paths":["document_number"]},"docType":{"paths":["type"]},"citation":{"paths":["citation"]},"pubDate":{"paths":["publication_date"]},"urlDate":{"template":"{yyyy}-{mm}-{dd}"},"pubDateMatchesUrl":{"paths":["publication_date"],"equalsVar":"urlDate"},"effectiveOn":{"paths":["effective_on"]},"dates":{"paths":["dates"],"trim":true},"action":{"paths":["action"],"trim":true},"agencies":{"paths":["agencies"],"subField":"name","join":", ","limit":12},"cfrRefs":{"paths":["cfr_references"],"subFieldsJoin":{"fields":["title","part"],"sep":" CFR Part ","fallbackField":"title"},"join":"; ","limit":20},"dockets":{"paths":["docket_ids"],"join":", ","limit":12},"abstract":{"paths":["abstract"],"trim":true},"abstractShort":{"paths":["abstract"],"trim":true,"sliceMax":260},"pdfUrl":{"paths":["pdf_url"],"requireHttps":true},"bodyHtmlUrl":{"paths":["body_html_url"],"requireHttps":true},"xmlUrl":{"paths":["full_text_xml_url"],"requireHttps":true},"htmlUrl":{"paths":["html_url"],"requireHttps":true}},"titleTemplate":"{title}","descriptionVar":"abstractShort","authorVar":"agencies","publishedTimeVar":"pubDate","bullets":[{"label":"Document Number","template":"`{docNumber}`"},{"label":"Type","template":"{docType}","whenVar":"docType"},{"label":"Citation","template":"{citation}","whenVar":"citation"},{"label":"Agencies","template":"{agencies}","whenVar":"agencies"},{"label":"Published","template":"{pubDate}","whenVar":"pubDate"},{"label":"Warning","template":"Publication date {pubDate} does not match the URL date {urlDate}; the URL may point to a different document than its date suggests.","whenVar":"pubDate","unlessVar":"pubDateMatchesUrl"},{"label":"Effective On","template":"{effectiveOn}","whenVar":"effectiveOn"},{"label":"Dates","template":"{dates}","whenVar":"dates"},{"label":"Action","template":"{action}","whenVar":"action"},{"label":"CFR References","template":"{cfrRefs}","whenVar":"cfrRefs"},{"label":"Docket IDs","template":"{dockets}","whenVar":"dockets"},{"label":"PDF","template":"{pdfUrl}","whenVar":"pdfUrl"},{"label":"Body HTML","template":"{bodyHtmlUrl}","whenVar":"bodyHtmlUrl"},{"label":"Full Text XML","template":"{xmlUrl}","whenVar":"xmlUrl"}],"sections":[{"heading":"Abstract","textVar":"abstract"},{"heading":"CFR References","arrayPath":"cfr_references","limit":25,"columns":[{"header":"Title","paths":["title"]},{"header":"Part","paths":["part"]},{"header":"Chapter","paths":["chapter"]}]}],"linksVars":["pdfUrl","htmlUrl","bodyHtmlUrl","xmlUrl"]}},{"id":"fediverse-pack","name":"Fediverse Pack (Misskey, Kbin, Mbin)","category":"commerce-social","description":"Extracts Misskey notes via POST /api/notes/show JSON and Kbin/Mbin threads via ActivityPub JSON or SSR HTML while rejecting Anubis proof-of-work and /login gates.","domains":["kbin.earth","gehirneimer.de","misskey.io"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://misskey.io/notes/au4n1wud00cl0t3s","https://gehirneimer.de/m/fragdeneimer/t/1244377/Spenden-defizit"],"routes":[{"match":{"exactSegments":true,"pathSegments":["notes",{"param":"noteId","charset":"alnum","minLen":8,"maxLen":24}]},"twin":{"fetchUrl":"https://{host}/api/notes/show","method":"POST","contentType":"application/json","requestBody":"{\"noteId\":\"{noteId}\"}","kind":"json","accept":"application/json","maxBytes":1048576},"extract":{"jsonMode":"fediverse_pack_json"}},{"match":{"exactSegments":true,"pathSegments":["api","notes","show"]},"twin":{"fetchUrl":"{requestUrl}","method":"POST","contentType":"application/json","kind":"json","accept":"application/json","maxBytes":1048576},"extract":{"jsonMode":"fediverse_pack_json"}},{"match":{"exactSegments":false,"pathSegments":["m",{"param":"mag","charset":"brew_id","minLen":1,"maxLen":120},"t",{"param":"threadId","charset":"digits","minLen":1,"maxLen":16}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/activity+json","maxBytes":1048576},"extract":{"jsonMode":"fediverse_pack_json"}}],"htmlRoutes":[{"id":"fediverse-pack","match":{"exactSegments":false},"mode":"fediverse_pack_html"}]},{"id":"fema-openfema","name":"FEMA OpenFEMA API v2","category":"public-records","description":"FEMA OpenFEMA v2 JSON dataset API (DisasterDeclarationsSummaries and public datasets) honoring strict robots.txt 15s crawl-delay.","domains":["www.fema.gov","fema.gov"],"auth_mode":"pub","strict_robots":true,"min_interval_ms":15000,"exampleUrls":["https://www.fema.gov/api/open/v2/DisasterDeclarationsSummaries?%24top=2"],"routes":[{"match":{"hosts":["www.fema.gov","fema.gov"],"pathPrefix":"/api/open/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"fema_openfema_json"}}]},{"id":"ferc-nrc-dockets","name":"FERC eLibrary & NRC ADAMS Dockets","category":"public-records","description":"Extracts public FERC eLibrary and NRC ADAMS docket/document pages while strictly honoring robots.txt and rejecting Cloudflare challenges and unhydrated Angular shells.","domains":["elibrary.ferc.gov","www.ferc.gov","ferc.gov","adams.nrc.gov","adams-search.nrc.gov","www.nrc.gov","nrc.gov"],"auth_mode":"pub","strict_robots":true,"exampleUrls":["https://www.nrc.gov/documents-reports/adams-public-documents","https://elibrary.ferc.gov/eLibrary/search","https://adams-search.nrc.gov/"],"htmlRoutes":[{"id":"ferc-nrc-dockets","match":{"exactSegments":false},"mode":"ferc_nrc_dockets_html"}]},{"id":"ffiec-cdr","name":"FFIEC Central Data Repository (CDR)","category":"finance","description":"Extracts FFIEC CDR Call Report and UBPR public web pages on cdr.ffiec.gov/public/ and optional ffieccdr.azure-api.us/public/ JSON metadata (routed via universalEngine so azure-api.us PSL private suffix is never claimed in domains).","domains":["cdr.ffiec.gov"],"universalEngine":true,"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://cdr.ffiec.gov/public/ManageFacsimiles.aspx","https://cdr.ffiec.gov/public/PWS/DownloadBulkData.aspx"],"routes":[{"match":{"hosts":["ffieccdr.azure-api.us"],"pathPrefix":"/public/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"ffiec_cdr_json"}}],"htmlRoutes":[{"id":"ffiec-cdr","match":{"hosts":["cdr.ffiec.gov"],"pathPrefix":"/public/"},"mode":"ffiec_cdr_html"}]},{"id":"finalsite","name":"Finalsite K-12 & Independent Schools","category":"public-records","description":"Extracts Finalsite K-12 school and independent school calendar events, news announcements, and resource blocks from /fs/ and fsElement DOM.","domains":["www.finalsite.com","finalsite.com","www.greenwichschools.org","www.choate.edu"],"universalEngine":true,"auth_mode":"html","strict_robots":true,"min_interval_ms":5000,"exampleUrls":["https://www.greenwichschools.org/calendar","https://www.choate.edu/"],"htmlRoutes":[{"id":"finalsite","match":{"exactSegments":false},"mode":"finalsite_html"}]},{"id":"financial-regulators-enforcement","name":"CFTC, OCC & FinCEN Enforcement & Bulletins","category":"finance","description":"Extracts enforcement actions, press releases, bulletins, and advisories from CFTC, OCC (including occ_news.xml RSS), and FinCEN.","domains":["www.cftc.gov","cftc.gov","www.occ.gov","occ.gov","www.fincen.gov","fincen.gov"],"auth_mode":"pub","exampleUrls":["https://www.cftc.gov/PressRoom/PressReleases/9331-26","https://www.occ.gov/news-issuances/bulletins/2023/bulletin-2023-17.html","https://www.occ.gov/rss/occ_news.xml","https://www.fincen.gov/news/news-releases/fincen-issues-alert-and-notice-support-new-fraud-prevention-measures-minnesota"],"routes":[{"match":{"hosts":["www.occ.gov","occ.gov"],"pathEquals":["/rss/occ_news.xml"]},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"text/xml","maxBytes":2097152},"extract":{"xml":{"mode":"items_table","requireAnyTags":["rss","channel"],"itemTag":"item","channelTitleFallbackParam":"host","titleTemplate":"{channelTitle} ({itemCount})","limit":25,"collectLinkVar":"itemLink","emitTotals":true,"itemVars":{"title":{"tags":["title"],"default":"Release"},"itemLink":{"tags":["link"]},"pubDate":{"tags":["pubDate"],"sliceMax":24,"default":"-"},"desc":{"tags":["description"],"sliceMax":180,"default":"-"}},"recordFields":{"title":"{title}","url":"{itemLink}","publishedAt":"{pubDate}","description":"{desc}","source":"financial-regulators-enforcement"},"columns":[{"header":"Title","template":"[{title}]({itemLink})"},{"header":"Published","template":"{pubDate}"},{"header":"Summary","template":"{desc}"}]}}}],"htmlRoutes":[{"id":"financial-regulators-enforcement","match":{"exactSegments":false},"mode":"financial_regulators_html"}]},{"id":"finra-brokercheck","name":"FINRA BrokerCheck","category":"finance","description":"Extracts FINRA BrokerCheck individual broker and firm registration, employment, exam, and disclosure records via same-eTLD+1 api.brokercheck.finra.org.","domains":["brokercheck.finra.org","api.brokercheck.finra.org"],"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://brokercheck.finra.org/individual/summary/810315","https://brokercheck.finra.org/firm/summary/79","https://api.brokercheck.finra.org/search/firm/79"],"routes":[{"match":{"hosts":["brokercheck.finra.org"],"pathSegments":["individual","summary",{"param":"crd","charset":"digits","minLen":1,"maxLen":12}]},"twin":{"fetchUrl":"https://api.brokercheck.finra.org/search/individual/{crd}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"finra_brokercheck_json"}},{"match":{"hosts":["brokercheck.finra.org"],"pathSegments":["firm","summary",{"param":"crd","charset":"digits","minLen":1,"maxLen":12}]},"twin":{"fetchUrl":"https://api.brokercheck.finra.org/search/firm/{crd}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"finra_brokercheck_json"}},{"match":{"hosts":["api.brokercheck.finra.org"],"pathPrefix":"/search/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"finra_brokercheck_json"}}],"htmlRoutes":[{"id":"finra-brokercheck","match":{"hosts":["brokercheck.finra.org"]},"mode":"finra_brokercheck_html"}]},{"id":"first-epss","name":"FIRST Exploit Prediction Scoring System (EPSS)","category":"developer","description":"Extracts CVE exploit probability scores, percentiles, and scoring dates from FIRST EPSS v1 JSON API.","domains":["api.first.org"],"auth_mode":"pub","exampleUrls":["https://api.first.org/data/v1/epss?cve=CVE-2024-3094"],"routes":[{"match":{"hosts":["api.first.org"],"exactSegments":false,"pathPrefix":"/data/v1/epss"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"first_epss_json"}}]},{"id":"fmcsa-safer","name":"FMCSA SAFER Carrier Registry","category":"public-records","description":"FMCSA QCMobile REST API (webKey) adapter for USDOT/MC carrier lookups with safer.fmcsa.dot.gov Company Snapshot HTML fallback.","domains":["safer.fmcsa.dot.gov","mobile.fmcsa.dot.gov"],"auth_mode":"key","exampleUrls":["https://mobile.fmcsa.dot.gov/qc/services/carriers/44110","https://safer.fmcsa.dot.gov/query.asp?searchtype=ANY&query_type=queryCarrierSnapshot&query_param=USDOT&query_string=44110"],"routes":[{"match":{"hosts":["mobile.fmcsa.dot.gov"],"pathPrefix":"/qc/services/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"fmcsa_safer_json"}},{"match":{"hosts":["safer.fmcsa.dot.gov"],"pathEquals":["/query.asp"],"queryParams":[{"name":"query_param","param":"queryParam","allowValues":["USDOT"]},{"name":"query_string","param":"dotNumber","charset":"digits","minLen":1,"maxLen":12}]},"twin":{"fetchUrl":"https://mobile.fmcsa.dot.gov/qc/services/carriers/{dotNumber}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"fmcsa_safer_json"}}],"htmlRoutes":[{"id":"fmcsa-safer","match":{"hosts":["safer.fmcsa.dot.gov"],"exactSegments":false},"mode":"fmcsa_safer_html"}]},{"id":"foursquare-places","name":"Foursquare Places API v3","category":"commerce-social","description":"Extracts place search results, venue details, and tips from the official Foursquare Places API v3 (api.foursquare.com).","domains":["api.foursquare.com"],"auth_mode":"key","exampleUrls":["https://api.foursquare.com/v3/places/search?query=coffee&near=Seattle","https://api.foursquare.com/v3/places/4b86a9f7f964a520d69331e3"],"routes":[{"match":{"hosts":["api.foursquare.com"],"anyOf":[{"pathEquals":["/v3/places/search"]},{"pathPrefix":"/v3/places/"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"key"},"extract":{"jsonMode":"foursquare_places_json"}}]},{"id":"fox-ridefox","name":"FOX RideFOX Suspension & Tech Docs","category":"developer","description":"Extracts FOX fork and shock specifications, service intervals, 4-char Tune ID codes, and manual PDF links from tech.ridefox.com and ridefox.com.","domains":["tech.ridefox.com","ridefox.com","www.ridefox.com"],"auth_mode":"html","exampleUrls":["https://tech.ridefox.com/bike/search/code/DKC6","https://ridefox.com/pages/bike"],"htmlRoutes":[{"id":"fox-ridefox","match":{"exactSegments":false},"mode":"fox_ridefox_html"}]},{"id":"fpds-sam-contract-awards","name":"FPDS & SAM.gov Contract Awards","category":"public-records","description":"Extracts keyless FPDS Atom XML contract award feeds (FEEDNAME=PUBLIC) and key-authenticated api.sam.gov/contract-awards JSON without colliding with sam-gov.","domains":["fpds.gov","www.fpds.gov"],"universalEngine":true,"auth_mode":"key","exampleUrls":["https://www.fpds.gov/ezsearch/FEEDS/ATOM?FEEDNAME=PUBLIC&q=LAST_MOD_DATE:[2026/06/25,2026/06/26]","https://api.sam.gov/contract-awards/v1/search?limit=1"],"routes":[{"match":{"hosts":["fpds.gov","www.fpds.gov"],"pathEquals":["/ezsearch/FEEDS/ATOM"]},"twin":{"fetchUrl":"{requestUrl}","defaultQueryParams":{"FEEDNAME":"PUBLIC"},"kind":"text","accept":"application/atom+xml","auth_mode":"pub","maxBytes":4194304},"extract":{"textMode":"fpds_atom_xml"}},{"match":{"hosts":["fpds.gov","www.fpds.gov"],"pathEquals":["/ezsearch/search.do"],"queryParams":[{"name":"q","param":"q","charset":"safe_subpath","minLen":1,"maxLen":240}]},"twin":{"fetchUrl":"https://www.fpds.gov/ezsearch/FEEDS/ATOM?FEEDNAME=PUBLIC&q={q}","kind":"text","accept":"application/atom+xml","auth_mode":"pub","maxBytes":4194304},"extract":{"textMode":"fpds_atom_xml"}},{"match":{"hosts":["fpds.gov","www.fpds.gov"],"pathEquals":["/ezsearch/search.do"],"queryParams":[{"name":"s","param":"s","charset":"url_seg","minLen":1,"maxLen":120}]},"twin":{"fetchUrl":"https://www.fpds.gov/ezsearch/FEEDS/ATOM?FEEDNAME=PUBLIC&s={s}","kind":"text","accept":"application/atom+xml","auth_mode":"pub","maxBytes":4194304},"extract":{"textMode":"fpds_atom_xml"}},{"match":{"hosts":["api.sam.gov"],"pathPrefix":"/contract-awards"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"fpds_sam_awards_json"}}],"htmlRoutes":[{"id":"fpds-sam-contract-awards","match":{"hosts":["fpds.gov","www.fpds.gov"],"exactSegments":false},"mode":"fpds_sam_awards_html"}]},{"id":"fred","name":"FRED Economic Data","category":"finance","description":"Federal Reserve Economic Data (FRED) API v1 JSON observations/series adapter with stlouisfed.org HTML series fallback.","domains":["fred.stlouisfed.org","api.stlouisfed.org"],"auth_mode":"key","min_interval_ms":1000,"exampleUrls":["https://fred.stlouisfed.org/series/GDP","https://api.stlouisfed.org/fred/series/observations?series_id=GDP&file_type=json","https://api.stlouisfed.org/fred/series?series_id=GDP&file_type=json"],"routes":[{"match":{"hosts":["api.stlouisfed.org"],"exactSegments":false,"pathPrefix":"/fred/"},"twin":{"fetchUrl":"{requestUrl}","setQueryParams":{"file_type":"json"},"kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"key"},"extract":{"jsonMode":"fred_json"}},{"match":{"hosts":["fred.stlouisfed.org"],"exactSegments":false,"pathSegments":["series",{"param":"seriesId","charset":"alnum_dash","minLen":1,"maxLen":64}]},"twin":{"fetchUrl":"https://api.stlouisfed.org/fred/series/observations?series_id={seriesId}&file_type=json&limit=25&sort_order=desc","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"key"},"extract":{"jsonMode":"fred_json"}}],"htmlRoutes":[{"id":"fred","match":{"hosts":["fred.stlouisfed.org"],"exactSegments":false,"pathSegments":["series",{"param":"seriesId","charset":"alnum_dash","minLen":1,"maxLen":64}]},"mode":"fred_html"}]},{"id":"freshdesk-portal","name":"Freshdesk Support Portal","category":"developer","description":"Extracts Freshdesk support portal articles, folders, and categories from public knowledge base HTML.","domains":["support.freshdesk.com"],"universalEngine":true,"auth_mode":"html","exampleUrls":["https://support.freshdesk.com/support/solutions/articles/240170-setting-up-your-support-email-in-gmail-video-guide","https://support.freshdesk.com/support/solutions/folders/275395"],"htmlRoutes":[{"id":"freshdesk-portal","match":{"exactSegments":false},"mode":"freshdesk_portal_html"}]},{"id":"ftc-cases","name":"FTC Cases, Proceedings & Early Termination Notices","category":"public-records","description":"Extracts FTC Legal Library cases, proceedings, matter numbers, and Hart-Scott-Rodino early termination notices while honoring FTC Crawl-delay: 5.","domains":["www.ftc.gov","ftc.gov"],"auth_mode":"pub","strict_robots":true,"min_interval_ms":5000,"max_concurrent":1,"exampleUrls":["https://www.ftc.gov/legal-library/browse/cases-proceedings/banned-debt-collectors","https://www.ftc.gov/legal-library/browse/cases-proceedings","https://www.ftc.gov/legal-library/browse/early-termination-notices"],"htmlRoutes":[{"id":"ftc-cases","match":{"exactSegments":false},"mode":"ftc_cases_html"}]},{"id":"gannett-usatoday-network","name":"Gannett / USA TODAY Network","category":"commerce-social","description":"Extracts NewsArticle JSON-LD and Gannett story content across USA TODAY and Gannett regional newspapers while rejecting Access Restricted gates.","domains":["www.usatoday.com","usatoday.com","www.azcentral.com","www.freep.com","www.indystar.com","www.cincinnati.com","www.dispatch.com","www.detroitnews.com","www.jsonline.com","www.tennessean.com","www.courier-journal.com"],"auth_mode":"html","exampleUrls":["https://www.usatoday.com/"],"htmlRoutes":[{"id":"gannett-usatoday-network","match":{"exactSegments":false},"mode":"gannett_usatoday_html"}]},{"id":"gao-reports","name":"U.S. GAO Reports & Testimonies","category":"public-records","description":"Extracts U.S. Government Accountability Office RSS report feeds and product detail pages while honoring strict_robots and rejecting Akamai Access Denied shells.","domains":["www.gao.gov","gao.gov"],"auth_mode":"pub","strict_robots":true,"min_interval_ms":1000,"exampleUrls":["https://www.gao.gov/products/gao-27-108423","https://www.gao.gov/rss/reports.xml"],"routes":[{"match":{"pathPrefix":"/rss/","pathSuffix":".xml"},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"application/rss+xml","maxBytes":1048576},"extract":{"textMode":"gao_rss_xml"}}],"htmlRoutes":[{"id":"gao-reports","match":{"exactSegments":false},"mode":"gao_reports_html"}]},{"id":"gem-ats","name":"Gem Job Boards","category":"jobs","description":"Upgrades jobs.gem.com/ boards and job posts to the keyless api.gem.com/job_board/v0//job_posts/ JSON feed.","domains":["jobs.gem.com"],"exampleUrls":["https://jobs.gem.com/gem"],"routes":[{"match":{"exactSegments":false,"pathSegments":[{"param":"org","charset":"slug","maxLen":80},{"param":"postId","charset":"pkg"}]},"twin":{"id":"gem-ats","fetchUrl":"https://api.gem.com/job_board/v0/{org}/job_posts/","kind":"json","accept":"application/json"},"extract":{"wrapRootArrayAs":"posts","findInArray":{"arrayPath":"posts","matchFields":["id","public_id"],"matchTemplate":"{postId}","endsWithField":"absolute_url","endsWithTemplate":"/{postId}"},"vars":{"jobTitle":{"paths":["title"],"trim":true,"default":"Job Posting"},"loc":{"paths":["location.name","location_type"],"trim":true},"depts":{"paths":["departments"],"subField":"name","join":", "},"bodyHtml":{"paths":["content"],"format":"html_to_md"},"bodyPlain":{"paths":["content_plain"],"format":"plain_text","trim":true},"body":{"template":"{bodyHtml}","whenVars":["bodyHtml"],"fallbackVar":"bodyPlain"}},"titleTemplate":"{jobTitle} @ {org}","bullets":[{"label":"Company","template":"{org}"},{"label":"Location","template":"{loc}","whenVar":"loc"},{"label":"Department","template":"{depts}","whenVar":"depts"}],"bodyVar":"body","fallbackExtract":{"wrapRootArrayAs":"posts","vars":{"count":{"paths":["posts"],"format":"array_len"}},"requireVars":["count"],"titleTemplate":"{org} — Gem Job Board ({count} open roles)","sections":[{"heading":"","arrayPath":"posts","limit":100,"emptyText":"No open positions currently listed.","itemVars":{"pTitle":{"paths":["title"],"trim":true,"default":"Role"},"id":{"paths":["id"]},"rawUrl":{"paths":["absolute_url"],"requireHttps":true},"pUrl":{"template":"{rawUrl}","whenVars":["rawUrl"],"fallbackTemplate":"https://jobs.gem.com/{org}/{id}"},"loc":{"paths":["location.name"],"trim":true,"default":"-"},"wp":{"paths":["location_type"],"trim":true,"default":"-"},"created":{"paths":["first_published_at","created_at"],"sliceMax":10,"trim":true,"default":"-"}},"collectLinkVars":["pUrl"],"columns":[{"header":"Role","template":"[{pTitle}]({pUrl})"},{"header":"Location","template":"{loc}"},{"header":"Workplace","template":"{wp}"},{"header":"Published","template":"{created}"}]}]}}},{"match":{"pathSegments":[{"param":"org","charset":"slug","maxLen":80}]},"twin":{"id":"gem-ats","fetchUrl":"https://api.gem.com/job_board/v0/{org}/job_posts/","kind":"json","accept":"application/json"},"extract":{"wrapRootArrayAs":"posts","vars":{"count":{"paths":["posts"],"format":"array_len"}},"requireVars":["count"],"titleTemplate":"{org} — Gem Job Board ({count} open roles)","sections":[{"heading":"","arrayPath":"posts","limit":100,"emptyText":"No open positions currently listed.","itemVars":{"pTitle":{"paths":["title"],"trim":true,"default":"Role"},"id":{"paths":["id"]},"rawUrl":{"paths":["absolute_url"],"requireHttps":true},"pUrl":{"template":"{rawUrl}","whenVars":["rawUrl"],"fallbackTemplate":"https://jobs.gem.com/{org}/{id}"},"loc":{"paths":["location.name"],"trim":true,"default":"-"},"wp":{"paths":["location_type"],"trim":true,"default":"-"},"created":{"paths":["first_published_at","created_at"],"sliceMax":10,"trim":true,"default":"-"}},"collectLinkVars":["pUrl"],"columns":[{"header":"Role","template":"[{pTitle}]({pUrl})"},{"header":"Location","template":"{loc}"},{"header":"Workplace","template":"{wp}"},{"header":"Published","template":"{created}"}]}]}}]},{"id":"genius-lyrics","name":"Genius, AZLyrics, Musixmatch & SongMeanings","category":"commerce-social","description":"Real song lyrics, artist, album, and annotation/meaning HTML extractor across Genius ([data-lyrics-container='true'] / __PRELOADED_STATE__), AZLyrics, Musixmatch (__NEXT_DATA__ / .mxm-lyrics__content), and SongMeanings.","domains":["genius.com","www.genius.com","www.azlyrics.com","azlyrics.com","www.musixmatch.com","musixmatch.com","songmeanings.com","www.songmeanings.com"],"auth_mode":"html","min_interval_ms":1500,"exampleUrls":["https://www.azlyrics.com/lyrics/rickastley/nevergonnagiveyouup.html","https://songmeanings.com/songs/view/3530822107858506064/","https://genius.com/Rick-astley-never-gonna-give-you-up-lyrics"],"htmlRoutes":[{"id":"genius-lyrics","match":{"hosts":["genius.com","www.genius.com","www.azlyrics.com","azlyrics.com","www.musixmatch.com","musixmatch.com","songmeanings.com","www.songmeanings.com"],"exactSegments":false},"mode":"genius_lyrics_html"}]},{"id":"geometrygeeks-99spokes","name":"Geometry Geeks & 99 Spokes","category":"commerce-social","description":"Extracts bicycle geometry tables (reach, stack, HTA, STA, chainstay, wheelbase) and component specs from Geometry Geeks and 99 Spokes while rejecting Cloudflare WAF blocks and empty shells.","domains":["geometrygeeks.bike","www.geometrygeeks.bike","99spokes.com","www.99spokes.com"],"auth_mode":"html","min_interval_ms":1000,"exampleUrls":["https://geometrygeeks.bike/bike/specialized-stumpjumper-evo-2021/"],"htmlRoutes":[{"id":"geometrygeeks-99spokes","match":{"exactSegments":false},"mode":"geometrygeeks_99spokes_html"}]},{"id":"gerrit","name":"Gerrit Code Review","category":"developer","description":"Universal Gerrit Code Review JSON extractor for /changes/ and /r/changes/ endpoints with linear XSSI )]}' prefix stripping and Crawl-delay pacing.","domains":["review.opendev.org","gerrit.wikimedia.org"],"universalEngine":true,"auth_mode":"pub","min_interval_ms":2000,"exampleUrls":["https://review.opendev.org/changes/?q=status:merged&n=2","https://review.opendev.org/changes/1010181/detail","https://gerrit.wikimedia.org/r/changes/?q=status:merged&n=2"],"routes":[{"match":{"anyOf":[{"pathPrefix":"/changes/"},{"pathPrefix":"/r/changes/"},{"pathPrefix":"/gerrit/changes/"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"application/json","maxBytes":2097152},"extract":{"textMode":"gerrit_json"}}]},{"id":"giant-liv-bikes","name":"Giant & Liv Bicycles Specs & Manuals","category":"commerce-social","description":"Extracts bike specifications, geometry GFM tables, and owner manual PDF links from Giant and Liv regional HTML pages while respecting Crawl-delay and never hitting /shop*, /comparison*, /account*, or /apiproxy/*.","domains":["www.giant-bicycles.com","*.giant-bicycles.com","giant-bicycles.com","www.liv-cycling.com","*.liv-cycling.com","liv-cycling.com"],"exampleUrls":["https://www.giant-bicycles.com/us/defy-advanced-pro-0","https://www.liv-cycling.com/us/avail-advanced-pro-0","https://www.giant-bicycles.com/us/manuals"],"htmlRoutes":[{"id":"giant-liv-bikes","mode":"giant_liv_html","match":{"exactSegments":false,"excludeSegmentSuffixes":[".xml",".json"],"anyOf":[{"exactSegments":false,"optionalLeadingLocale":true,"reservedFirstSegment":["shop","comparison","account","apiproxy","int","global"]},{"exactSegments":false,"pathSegments":[{"param":"locale3","allowValues":["int","global"]},{"param":"seg1","charset":"url_seg","minLen":1,"maxLen":160,"reserved":["shop","comparison","account","apiproxy"]}]}]}}]},{"id":"github-gist","name":"GitHub Gists","category":"developer","description":"Extracts multi-file GitHub Gist code blocks with fenced language tags and rendered Markdown.","domains":["gist.github.com"],"exampleUrls":["https://gist.github.com/octocat/6cad326836d38bd3a7ae"],"htmlRoutes":[{"match":{"minSegments":2},"mode":"gist_files"}]},{"id":"gitlab-forgejo","name":"GitLab, Codeberg & Forgejo Twins","category":"developer","description":"Upgrades GitLab repo roots and file blobs via robots.txt-allowed ?format=json&viewer=simple endpoints, and extracts clean README content from Codeberg/Gitea SSR repo pages.","domains":["gitlab.com","gitlab.*","codeberg.org","gitea.com"],"exampleUrls":["https://gitlab.com/gitlab-org/cli","https://gitlab.com/inkscape/inkscape/-/blob/master/CMakeLists.txt","https://codeberg.org/forgejo/forgejo"],"routes":[{"match":{"hosts":["gitlab.com","gitlab.*"],"splitOnSegment":{"delimiter":"-","leftParam":"nsProj","leftMinSegs":2,"afterLiteral":"blob","rightParam":"rawTail","tailParam":"filePath"}},"twin":{"id":"gitlab-blob-json","fetchUrl":"https://{host}/{nsProj}/-/blob/{rawTail}?format=json&viewer=simple","rawPathParams":["nsProj","rawTail"],"kind":"json","accept":"application/json"},"extract":{"vars":{"plain":{"paths":["html"],"format":"gitlab_blob_html"}},"requireVars":["plain"],"titleTemplate":"{nsProj}/{filePath}","codeByPath":{"sourceVar":"plain","pathParam":"filePath","rawIfMarkdown":true}}},{"match":{"hosts":["gitlab.com","gitlab.*"],"minSegments":2,"maxSegments":5,"allSegmentsCharset":"pkg","reservedFirstSegment":["explore","groups","users","dashboard","help","topics","orgs","admin","search","abuse_reports","oauth","snippets","-"],"excludeSegmentSuffixes":[".git",".atom"]},"twin":{"id":"gitlab-readme-json","fetchUrl":"https://{host}/{joinedPath}/-/blob/HEAD/README.md?format=json&viewer=simple","rawPathParams":["joinedPath"],"kind":"json","accept":"application/json"},"extract":{"vars":{"readme":{"paths":["html"],"format":"gitlab_blob_html","trim":true}},"requireVars":["readme"],"titleTemplate":"{joinedPath}","bodyVar":"readme"}}],"htmlRoutes":[{"match":{"hosts":["codeberg.org","gitea.com"],"exactSegments":true,"pathSegments":[{"param":"owner","charset":"pkg"},{"param":"repo","charset":"pkg"}]},"mode":"dom","vars":{"desc":{"metaKeys":["og:description","description"]},"readme":{"cssHtmlToMd":["div.markup"],"minLen":40}},"requireVars":["readme"],"titleTemplate":"{owner}/{repo}","descriptionVar":"desc","blockquoteTemplate":"> **{owner}/{repo}** — {desc}","blockquoteWhenVar":"desc","bodyVar":"readme","preserveBodyLinksFromVar":"readme"}]},{"id":"google-my-maps-kml","name":"Google My Maps KML","category":"commerce-social","description":"Upgrades public Google My Maps /maps/d/ viewer, embed, and KML links to bounded KML placemark extraction with validated coordinates.","domains":["google.com","www.google.com","maps.google.com"],"auth_mode":"pub","exampleUrls":["https://www.google.com/maps/d/viewer?mid=1Mdlz2iXu_iZCPhUhzKvT2B2j-6E"],"routes":[{"match":{"anyOf":[{"hosts":["google.com","www.google.com","maps.google.com"],"pathSegments":["maps","d",{"param":"view","allowValues":["viewer","embed","edit","kml"]}],"queryParams":[{"name":"mid","param":"mid","charset":"alnum_dash","minLen":12,"maxLen":64}]},{"hosts":["google.com","www.google.com","maps.google.com"],"pathSegments":["maps","d","u",{"param":"userIdx","charset":"digits","minLen":1,"maxLen":4},{"param":"view","allowValues":["viewer","embed","edit","kml"]}],"queryParams":[{"name":"mid","param":"mid","charset":"alnum_dash","minLen":12,"maxLen":64}]}]},"twin":{"fetchUrl":"https://www.google.com/maps/d/kml?mid={mid}&forcekml=1","kind":"text","accept":"application/xml"},"extract":{"textMode":"kml_placemarks"}}]},{"id":"google-places","name":"Google Places API (New)","category":"commerce-social","description":"Extracts place details and text/nearby search results from the official Google Places API (New) with required X-Goog-Api-Key and X-Goog-FieldMask headers.","domains":["developers.google.com"],"universalEngine":true,"auth_mode":"key","exampleUrls":["https://places.googleapis.com/v1/places/ChIJj61dQgK6j4AR4GeTYWZsKWw","https://places.googleapis.com/v1/places:searchText?textQuery=coffee"],"routes":[{"match":{"hosts":["places.googleapis.com"],"anyOf":[{"pathEquals":["/v1/places:searchText","/v1/places:searchNearby"]}],"queryParams":[{"name":"textQuery","param":"textQuery","charset":"url_seg","maxLen":120,"optional":true,"default":"coffee"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","method":"POST","contentType":"application/json","requestBody":"{\"textQuery\":\"{textQuery}\"}","headers":{"X-Goog-FieldMask":"places.id,places.displayName,places.formattedAddress,places.rating,places.userRatingCount,places.websiteUri,places.nationalPhoneNumber,places.googleMapsUri,places.primaryType,places.businessStatus,places.priceLevel"},"maxBytes":2097152,"auth_mode":"key"},"extract":{"jsonMode":"google_places_json"}},{"match":{"hosts":["places.googleapis.com"],"pathPrefix":"/v1/places/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","headers":{"X-Goog-FieldMask":"id,displayName,formattedAddress,rating,userRatingCount,websiteUri,nationalPhoneNumber,googleMapsUri,primaryType,businessStatus,priceLevel,regularOpeningHours"},"maxBytes":2097152,"auth_mode":"key"},"extract":{"jsonMode":"google_places_json"}}]},{"id":"google-play","name":"Google Play Store","category":"developer","description":"Extracts structured Google Play app metadata (package ID, developer, rating, downloads/reviews, category, price, and full description).","domains":["play.google.com"],"exampleUrls":["https://play.google.com/store/apps/details?id=com.cloudflare.onedotonedotonedotone"],"htmlRoutes":[{"match":{"pathPrefix":"/store/apps/details","queryParams":[{"name":"id","param":"pkgId","charset":"pkg","optional":true}]},"mode":"dom","jsonLdTypes":["SoftwareApplication","MobileApplication"],"vars":{"title":{"jsonLdPaths":["name"],"metaKeys":["og:title"],"stripRegexSuffix":"\\s*-\\s*Apps on Google Play$"},"developer":{"jsonLdPaths":["author.name"]},"ratingVal":{"jsonLdPaths":["aggregateRating.ratingValue"]},"ratingCount":{"jsonLdPaths":["aggregateRating.ratingCount","aggregateRating.reviewCount"]},"ratingOnly":{"template":"{ratingVal} / 5","whenVars":["ratingVal"]},"rating":{"template":"{ratingVal} / 5 ({ratingCount} reviews)","whenVars":["ratingVal","ratingCount"],"fallbackVar":"ratingOnly"},"currency":{"jsonLdPaths":["offers.0.priceCurrency","offers.priceCurrency"],"default":"USD"},"price":{"jsonLdPaths":["offers.0.price","offers.price"],"format":"free_or_currency","currencyVar":"currency"},"category":{"jsonLdPaths":["applicationCategory"]},"contentRating":{"jsonLdPaths":["contentRating"]},"desc":{"jsonLdPaths":["description"],"metaKeys":["description"]},"descShort":{"template":"{desc}","whenVars":["desc"],"sliceMax":260}},"requireVars":["title"],"requireBulletsOrVars":["desc"],"titleTemplate":"{title}","descriptionVar":"descShort","authorVar":"developer","bullets":[{"label":"Package ID","template":"`{pkgId}`","whenVar":"pkgId"},{"label":"Developer","template":"{developer}","whenVar":"developer"},{"label":"Category","template":"{category}","whenVar":"category"},{"label":"Rating","template":"{rating}","whenVar":"rating"},{"label":"Price","template":"{price}","whenVar":"price"},{"label":"Content Rating","template":"{contentRating}","whenVar":"contentRating"}],"sections":[{"heading":"About This App","textVar":"desc"}]}]},{"id":"google-shopping-feed","name":"Google Shopping Merchant Center XML/Atom Feed","category":"commerce-social","description":"Universal XML/Atom parser for Google Merchant Center RSS 2.0 and Atom 1.0 product feeds with strict GTIN validation and compact records.","domains":["btrsports.co.uk"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://raw.githubusercontent.com/web3at50/btr-feed/main/affiliate-feed.xml"],"routes":[{"match":{"excludeHosts":["feeds.npr.org","npr.org","www.npr.org","pbs.org","www.pbs.org","prnewswire.com","www.prnewswire.com","businesswire.com","www.businesswire.com","globenewswire.com","www.globenewswire.com","medium.com","www.medium.com","*.medium.com","ghost.org","www.ghost.org","*.ghost.io","buttondown.com","www.buttondown.com","buttondown.email","rss.beehiiv.com","milkroad.beehiiv.com","*.beehiiv.com","wordpress.org","www.wordpress.org","*.wordpress.com","weworkremotely.com","www.weworkremotely.com","bicycleretailer.com","www.bicycleretailer.com","earthquake.usgs.gov","api.nasa.gov","recruiting.paylocity.com","app.jazz.co","*.applytojob.com","www.fpds.gov","fpds.gov","*.substack.com","substack.com","careers.*.com","jobs.*.com"],"anyOf":[{"pathEquals":["/google-merchant.xml","/google-shopping.xml","/merchant-feed.xml","/product-feed.xml","/shopping-feed.xml"]},{"pathPrefix":"/feeds/","pathSuffix":".xml"},{"pathPrefix":"/feeds/","pathSuffix":".atom"},{"pathPrefix":"/feeds/","pathSuffix":".rss"},{"pathContainsSegment":"google-merchant","pathSuffix":".xml"},{"pathContainsSegment":"google-shopping","pathSuffix":".xml"},{"hosts":["raw.githubusercontent.com"],"pathEquals":["/web3at50/btr-feed/main/affiliate-feed.xml"]}]},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"application/xml","maxBytes":4194304},"extract":{"textMode":"google_shopping_feed_xml"}}]},{"id":"gorgias-reamaze","name":"Gorgias & Re:amaze Help Centers","category":"commerce-social","description":"Extracts help-center articles, topic indexes, and Q&A content from Gorgias (__NEXT_DATA__) and Re:amaze knowledge base portals.","domains":["*.gorgias.help","*.reamaze.com","support.burga.com"],"universalEngine":true,"auth_mode":"html","exampleUrls":["https://support.burga.com/en-US/articles/contact-us-24868","https://storypod.reamaze.com/kb/all-about-storypod/firmware-update"],"htmlRoutes":[{"id":"gorgias-reamaze","match":{"exactSegments":false},"mode":"gorgias_reamaze_html"}]},{"id":"gov-wordpress-newsrooms","name":"Federal .gov WordPress Newsrooms","category":"public-records","description":"Extracts official federal .gov WordPress REST v2 posts (excluding whitehouse.gov 403 /wp-json/) and briefing/newsroom HTML pages.","domains":["www.whitehouse.gov","whitehouse.gov","news.va.gov","www.nasa.gov","nasa.gov"],"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://news.va.gov/wp-json/wp/v2/posts?per_page=1","https://news.va.gov/151377/memphis-veterans-received-help-claims-clinic/","https://www.whitehouse.gov/presidential-actions/"],"routes":[{"match":{"excludeHosts":["www.whitehouse.gov","whitehouse.gov"],"exactSegments":true,"pathSegments":["wp-json","wp","v2","posts"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"gov_wp_posts_json"}},{"match":{"excludeHosts":["www.whitehouse.gov","whitehouse.gov"],"exactSegments":true,"pathSegments":["wp-json","wp","v2","posts",{"param":"postId","charset":"digits","minLen":1,"maxLen":16}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"gov_wp_posts_json"}}],"htmlRoutes":[{"id":"gov-wordpress-newsrooms","match":{"exactSegments":false},"mode":"gov_wp_newsroom_html"}]},{"id":"granicus-govdelivery","name":"Granicus GovDelivery Public Bulletins","category":"public-records","description":"Extracts public government bulletins and optional RSS feeds from Granicus GovDelivery without rewriting HTML bulletins to .rss.","domains":["content.govdelivery.com","public.govdelivery.com"],"auth_mode":"pub","exampleUrls":["https://content.govdelivery.com/accounts/ILEVANSTON/bulletins/4345149"],"routes":[{"match":{"pathSuffix":".rss","pathPrefix":"/accounts/"},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"application/rss+xml","maxBytes":2097152},"extract":{"xml":{"mode":"items_table","requireAnyTags":["rss","channel"],"itemTag":"item","channelTitleFallbackParam":"host","titleTemplate":"{channelTitle} ({itemCount})","limit":25,"collectLinkVar":"itemLink","emitTotals":true,"itemVars":{"title":{"tags":["title"],"default":"Bulletin"},"itemLink":{"tags":["link"]},"pubDate":{"tags":["pubDate"],"sliceMax":24,"default":"-"},"desc":{"tags":["description"],"sliceMax":180,"default":"-"}},"recordFields":{"title":"{title}","url":"{itemLink}","publishedAt":"{pubDate}","description":"{desc}","source":"granicus-govdelivery"},"columns":[{"header":"Bulletin","template":"[{title}]({itemLink})"},{"header":"Published","template":"{pubDate}"},{"header":"Summary","template":"{desc}"}]}}}],"htmlRoutes":[{"id":"granicus-govdelivery","match":{"exactSegments":false},"mode":"govdelivery_html"}]},{"id":"grants-gov","name":"Grants.gov Federal Grant Opportunities","category":"public-records","description":"Upgrades grants.gov opportunity pages to official keyless POST api.grants.gov/v1/api/fetchOpportunity JSON with HTML fallback.","domains":["grants.gov","www.grants.gov","api.grants.gov"],"auth_mode":"pub","exampleUrls":["https://www.grants.gov/search-results-detail/357601","https://api.grants.gov/v1/api/fetchOpportunity"],"routes":[{"match":{"hosts":["grants.gov","www.grants.gov"],"exactSegments":false,"pathSegments":["search-results-detail",{"param":"oppId","charset":"digits","minLen":1,"maxLen":20}]},"twin":{"fetchUrl":"https://api.grants.gov/v1/api/fetchOpportunity","kind":"json","accept":"application/json","method":"POST","contentType":"application/json","requestBody":"{\"opportunityId\":{oppId}}","auth_mode":"pub","maxBytes":2097152},"extract":{"jsonMode":"grants_gov_json"}},{"match":{"hosts":["api.grants.gov"],"pathPrefix":"/v1/api/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"pub","maxBytes":2097152},"extract":{"jsonMode":"grants_gov_json"}}],"htmlRoutes":[{"id":"grants-gov","match":{"hosts":["grants.gov","www.grants.gov"],"exactSegments":false},"mode":"grants_gov_html"}]},{"id":"greenhouse-lever-boards","name":"Greenhouse & Lever Whole-Board + EU APIs","category":"jobs","description":"Upgrades Greenhouse (US & EU) and Lever (US & EU) board root URLs to their official JSON posting feeds with truncation metadata.","domains":["boards.greenhouse.io","job-boards.greenhouse.io","eu-boards.greenhouse.io","job-boards.eu.greenhouse.io","jobs.lever.co","jobs.eu.lever.co"],"exampleUrls":["https://job-boards.greenhouse.io/anthropic","https://job-boards.greenhouse.io/celonis","https://jobs.lever.co/spotify"],"routes":[{"match":{"hosts":["boards.greenhouse.io","job-boards.greenhouse.io"],"pathSegments":[{"param":"org","charset":"pkg","maxLen":80,"reserved":["embed","v1","api","static","assets","favicon.ico"]}]},"twin":{"id":"greenhouse-board","fetchUrl":"https://boards-api.greenhouse.io/v1/boards/{org}/jobs","kind":"json","accept":"application/json"},"extract":{"vars":{"jobCount":{"paths":["jobs"],"format":"array_len"},"total":{"paths":["meta.total"],"fallbackTemplate":"{jobCount}"}},"requireVars":["jobCount"],"titleTemplate":"{org} — Greenhouse Job Board ({total} open roles)","sections":[{"heading":"","arrayPath":"jobs","limit":120,"linkScanLimit":2000,"emptyText":"No open positions currently listed.","paginationMeta":{"totalPath":"meta.total","cursorMode":"offset"},"itemVars":{"jTitle":{"paths":["title"],"trim":true,"default":"Role"},"id":{"paths":["id"]},"rawUrl":{"paths":["absolute_url"],"requireHttps":true},"jUrl":{"template":"{rawUrl}","whenVars":["rawUrl"],"fallbackTemplate":"https://{host}/{org}/jobs/{id}"},"dept":{"paths":["departments"],"subField":"name","join":", ","default":"-"},"loc":{"paths":["location.name"],"trim":true,"default":"-"},"updated":{"paths":["updated_at"],"sliceMax":10,"trim":true,"default":"-"}},"collectLinkVars":["jUrl"],"columns":[{"header":"Role","template":"[{jTitle}]({jUrl})"},{"header":"Department","template":"{dept}"},{"header":"Location","template":"{loc}"},{"header":"Updated","template":"{updated}"}]}]}},{"match":{"hosts":["eu-boards.greenhouse.io","job-boards.eu.greenhouse.io"],"pathSegments":[{"param":"org","charset":"pkg","maxLen":80,"reserved":["embed","v1","api","static","assets","favicon.ico"]}]},"twin":{"id":"greenhouse-eu-board","fetchUrl":"https://boards-api.eu.greenhouse.io/v1/boards/{org}/jobs","kind":"json","accept":"application/json"},"extract":{"vars":{"jobCount":{"paths":["jobs"],"format":"array_len"},"total":{"paths":["meta.total"],"fallbackTemplate":"{jobCount}"}},"requireVars":["jobCount"],"titleTemplate":"{org} — Greenhouse Job Board ({total} open roles)","sections":[{"heading":"","arrayPath":"jobs","limit":120,"linkScanLimit":2000,"emptyText":"No open positions currently listed.","paginationMeta":{"totalPath":"meta.total","cursorMode":"offset"},"itemVars":{"jTitle":{"paths":["title"],"trim":true,"default":"Role"},"id":{"paths":["id"]},"rawUrl":{"paths":["absolute_url"],"requireHttps":true},"jUrl":{"template":"{rawUrl}","whenVars":["rawUrl"],"fallbackTemplate":"https://{host}/{org}/jobs/{id}"},"dept":{"paths":["departments"],"subField":"name","join":", ","default":"-"},"loc":{"paths":["location.name"],"trim":true,"default":"-"},"updated":{"paths":["updated_at"],"sliceMax":10,"trim":true,"default":"-"}},"collectLinkVars":["jUrl"],"columns":[{"header":"Role","template":"[{jTitle}]({jUrl})"},{"header":"Department","template":"{dept}"},{"header":"Location","template":"{loc}"},{"header":"Updated","template":"{updated}"}]}]}},{"match":{"hosts":["jobs.lever.co"],"pathSegments":[{"param":"org","charset":"pkg","maxLen":80,"reserved":["embed","v1","api","static","assets","favicon.ico"]}]},"twin":{"id":"lever-board","fetchUrl":"https://api.lever.co/v0/postings/{org}?mode=json&limit=100","kind":"json","accept":"application/json"},"extract":{"wrapRootArrayAs":"jobs","vars":{"total":{"paths":["jobs"],"format":"array_len"}},"requireVars":["total"],"titleTemplate":"{org} — Lever Job Board ({total} open roles)","sections":[{"heading":"","arrayPath":"jobs","limit":120,"linkScanLimit":2000,"emptyText":"No open positions currently listed.","paginationMeta":{"cursorMode":"last_id","idField":"id"},"itemVars":{"jTitle":{"paths":["text"],"trim":true,"default":"Role"},"id":{"paths":["id"]},"rawUrl":{"paths":["hostedUrl"],"requireHttps":true},"jUrl":{"template":"{rawUrl}","whenVars":["rawUrl"],"fallbackTemplate":"https://{host}/{org}/{id}"},"team":{"paths":["categories.team","categories.department"],"trim":true,"default":"-"},"loc":{"paths":["categories.location"],"trim":true,"default":"-"},"wp":{"paths":["workplaceType"],"trim":true,"default":"-"}},"collectLinkVars":["jUrl"],"columns":[{"header":"Role","template":"[{jTitle}]({jUrl})"},{"header":"Team","template":"{team}"},{"header":"Location","template":"{loc}"},{"header":"Workplace","template":"{wp}"}]}]}},{"match":{"hosts":["jobs.eu.lever.co"],"pathSegments":[{"param":"org","charset":"pkg","maxLen":80,"reserved":["embed","v1","api","static","assets","favicon.ico"]}]},"twin":{"id":"lever-eu-board","fetchUrl":"https://api.eu.lever.co/v0/postings/{org}?mode=json&limit=100","kind":"json","accept":"application/json"},"extract":{"wrapRootArrayAs":"jobs","vars":{"total":{"paths":["jobs"],"format":"array_len"}},"requireVars":["total"],"titleTemplate":"{org} — Lever Job Board ({total} open roles)","sections":[{"heading":"","arrayPath":"jobs","limit":120,"linkScanLimit":2000,"emptyText":"No open positions currently listed.","paginationMeta":{"cursorMode":"last_id","idField":"id"},"itemVars":{"jTitle":{"paths":["text"],"trim":true,"default":"Role"},"id":{"paths":["id"]},"rawUrl":{"paths":["hostedUrl"],"requireHttps":true},"jUrl":{"template":"{rawUrl}","whenVars":["rawUrl"],"fallbackTemplate":"https://{host}/{org}/{id}"},"team":{"paths":["categories.team","categories.department"],"trim":true,"default":"-"},"loc":{"paths":["categories.location"],"trim":true,"default":"-"},"wp":{"paths":["workplaceType"],"trim":true,"default":"-"}},"collectLinkVars":["jUrl"],"columns":[{"header":"Role","template":"[{jTitle}]({jUrl})"},{"header":"Team","template":"{team}"},{"header":"Location","template":"{loc}"},{"header":"Workplace","template":"{wp}"}]}]}}]},{"id":"gs1-us-datahub","name":"GS1 US Data Hub & Verified by GS1","category":"commerce-social","description":"Extracts Verified by GS1 / GS1 US Data Hub GTIN brand-owner, GLN, company prefix, and GPC metadata via api.gs1us.org (GS1_US_API_KEY) with public HTML fallback on gs1us.org and gs1.org.","domains":["api.gs1us.org","www.gs1us.org","gs1us.org","gepir.gs1.org","www.gs1.org"],"auth_mode":"key","min_interval_ms":1000,"exampleUrls":["https://www.gs1us.org/tools/gs1-company-database-gepir","https://www.gs1.org/services/verified-by-gs1","https://api.gs1us.org/gtins/0012000161155"],"routes":[{"match":{"hosts":["api.gs1us.org"],"minSegments":1},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"gs1_us_json"}}],"htmlRoutes":[{"id":"gs1-us-datahub","match":{"hosts":["www.gs1us.org","gs1us.org","gepir.gs1.org","www.gs1.org"],"exactSegments":false},"mode":"gs1_us_html"}]},{"id":"gsa-site-scanning","name":"GSA Site Scanning API","category":"public-records","description":"GSA Technology Transformation Services Site Scanning API (DATA_GOV_API_KEY) and open.gsa.gov documentation fallback.","domains":["api.gsa.gov","open.gsa.gov"],"auth_mode":"key","min_interval_ms":1000,"exampleUrls":["https://api.gsa.gov/technology/site-scanning/v1/websites?limit=5","https://api.gsa.gov/technology/site-scanning/v1/websites/usa.gov"],"routes":[{"match":{"hosts":["api.gsa.gov"],"pathPrefix":"/technology/site-scanning/v1/websites"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"gsa_site_scanning_json"}}],"htmlRoutes":[{"id":"gsa-site-scanning","match":{"hosts":["open.gsa.gov"],"exactSegments":false},"mode":"gsa_site_scanning_html"}]},{"id":"hackernews","name":"Hacker News Stories & Who is Hiring (Algolia API)","category":"commerce-social","description":"Upgrades news.ycombinator.com/item?id= threads (including monthly Who is Hiring threads) to hn.algolia.com/api/v1/items/ JSON.","domains":["news.ycombinator.com"],"exampleUrls":["https://news.ycombinator.com/item?id=41000000"],"match":{"exactSegments":true,"pathSegments":["item"],"queryParams":[{"name":"id","param":"itemId","charset":"digits","minLen":1,"maxLen":12}]},"twin":{"id":"hackernews","fetchUrl":"https://hn.algolia.com/api/v1/items/{itemId}","kind":"json","accept":"application/json"},"extract":{"requireFields":["id"],"vars":{"title":{"paths":["title"],"trim":true,"fallbackTemplate":"HN Comment #{itemId}"},"author":{"paths":["author"]},"points":{"paths":["points"]},"createdAt":{"paths":["created_at"]},"postedDate":{"paths":["created_at"],"sliceMax":10},"storyUrl":{"paths":["url"]},"storyText":{"paths":["text"],"format":"html_to_md"}},"titleTemplate":"{title}","authorVar":"author","publishedTimeVar":"createdAt","metaLine":[{"label":"Points","template":"{points}","whenVar":"points"},{"label":"By","template":"{author}","whenVar":"author"},{"label":"Posted","template":"{postedDate}","whenVar":"postedDate"},{"label":"URL","template":"{storyUrl}","whenVar":"storyUrl"}],"bodyVar":"storyText","linksVars":["storyUrl"],"sections":[{"heading":"Comments","headingTemplate":"Comments ({topCount} top-level)","treeComments":{"childrenPath":"children","authorPath":"author","htmlTextPath":"text","maxDepth":2,"maxItems":60}}]}},{"id":"hardware-farm-specs","name":"Hardware & Farm Supply Spec Extractor","category":"commerce-social","description":"Extracts Product JSON-LD, specification tables, and Apollo SimpleProduct metadata for Tractor Supply and Harbor Freight.","domains":["tractorsupply.com","www.tractorsupply.com","harborfreight.com","www.harborfreight.com"],"auth_mode":"html","min_interval_ms":2000,"strict_robots":true,"exampleUrls":["https://www.harborfreight.com/20v-brushless-cordless-12-in-drilldriver-tool-only-59420.html"],"htmlRoutes":[{"id":"hardware-farm-specs","match":{"exactSegments":false},"mode":"hardware_farm_specs_html"}]},{"id":"hathitrust","name":"HathiTrust Digital Library","category":"public-records","description":"HathiTrust Bibliographic API (catalog.hathitrust.org/api/volumes) adapter for OCLC, ISBN, LCCN, ISSN, and Record IDs.","domains":["catalog.hathitrust.org","babel.hathitrust.org"],"auth_mode":"pub","min_interval_ms":1000,"strict_robots":false,"exampleUrls":["https://catalog.hathitrust.org/api/volumes/brief/oclc/424023.json","https://catalog.hathitrust.org/api/volumes/brief/isbn/9780030110405.json","https://catalog.hathitrust.org/Record/000578050"],"routes":[{"match":{"hosts":["catalog.hathitrust.org"],"pathPrefix":"/api/volumes/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"pub"},"extract":{"jsonMode":"hathitrust_json"}},{"match":{"hosts":["catalog.hathitrust.org"],"exactSegments":false,"pathSegments":["Record",{"param":"recordId","charset":"digits","minLen":5,"maxLen":20}]},"twin":{"fetchUrl":"https://catalog.hathitrust.org/api/volumes/brief/recordnumber/{recordId}.json","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"pub"},"extract":{"jsonMode":"hathitrust_json"}}]},{"id":"hcl-websphere-commerce","name":"HCL / WebSphere Commerce (WCS)","category":"commerce-social","description":"Extracts HCL/IBM WebSphere Commerce /wcs/resources/store//productview REST JSON and storefront HTML/companion twins.","domains":["www.childrensplace.com"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://www.childrensplace.com/us/p/Girls-Basic-Super-Skinny-Jeans-3044219-33C4"],"routes":[{"match":{"pathSegments":["wcs","resources","store",{"param":"storeId","charset":"digits","minLen":2,"maxLen":16},"productview","byPartNumber",{"param":"partNumber","charset":"pkg","minLen":1,"maxLen":120}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"commerceMode":"hcl_wcs_product"}},{"match":{"pathSegments":["wcs","resources","store",{"param":"storeId","charset":"digits","minLen":2,"maxLen":16},"productview","byId",{"param":"productId","charset":"pkg","minLen":1,"maxLen":120}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"commerceMode":"hcl_wcs_product"}}],"htmlRoutes":[{"id":"hcl-websphere-commerce","match":{"exactSegments":false},"mode":"hcl_wcs_html"}]},{"id":"headless-cms-delivery","name":"Headless CMS Delivery","category":"developer","description":"Opt-in single-page doc delivery twin for Sanity, Storyblok, Prismic, Contentful, Builder.io, and Strapi (gated by allowPageKeyTwins; falls back to HTML/JSON-LD when OFF).","domains":["3do82whm.apicdn.sanity.io","www.sanity.io","api.storyblok.com","www.storyblok.com","nextjs-starter-prismic-blog.cdn.prismic.io","prismic.io","cdn.contentful.com","cdn.builder.io","www.builder.io","strapi.io"],"universalEngine":true,"auth_mode":"page-key","requires_page_key_opt_in":true,"exampleUrls":["https://3do82whm.apicdn.sanity.io/v2021-10-21/data/query/next?query=*%5Bslug.current%20%3D%3D%20%22content-lake%22%5D%5B0%5D%7B_id%2C_type%2Ctitle%2Cslug%7D","https://nextjs-starter-prismic-blog.cdn.prismic.io/api/v2/documents/search?ref=ZuGtnBkAAEcAW15g&q=%5B%5B%3Ad+%3D+at%28document.id%2C+%22YlcmoRMAACMAI0gs%22%29+%5D%5D","https://cdn.builder.io/api/v3/content/docs/9f6f5d07-9c2e-4b44-983a-3f065151247f?apiKey=YJIGb4i01jvw0SRdL5Bt","https://www.sanity.io/docs/content-lake"],"routes":[{"match":{"hosts":["cdn.contentful.com"],"exactSegments":true,"pathSegments":["spaces",{"param":"spaceId","charset":"url_seg","minLen":1,"maxLen":64},"environments",{"param":"envId","charset":"url_seg","minLen":1,"maxLen":64},"entries",{"param":"entryId","charset":"url_seg","minLen":1,"maxLen":128}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"jsonMode":"headless_cms_doc"}},{"match":{"hosts":["api.storyblok.com","api-us.storyblok.com"],"exactSegments":false,"pathSegments":["v2","cdn","stories",{"param":"slug","charset":"safe_subpath","minLen":1,"maxLen":200,"greedy":true}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"jsonMode":"headless_cms_doc"}},{"match":{"hosts":["cdn.builder.io"],"exactSegments":true,"pathSegments":["api","v3","content",{"param":"model","charset":"url_seg","minLen":1,"maxLen":80},{"param":"entryId","charset":"url_seg","minLen":1,"maxLen":128}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"jsonMode":"headless_cms_doc"}},{"match":{"hostSubdomain":{"suffix":".apicdn.sanity.io","param":"projectId"},"exactSegments":true,"pathSegments":[{"param":"version","charset":"url_seg","minLen":4,"maxLen":24},"data","query",{"param":"dataset","charset":"url_seg","minLen":1,"maxLen":64}],"queryParams":[{"name":"query","param":"groqQuery","charset":"sanity_single_doc_query","minLen":5,"maxLen":400}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"jsonMode":"headless_cms_doc"}},{"match":{"hostSubdomain":{"suffix":".cdn.prismic.io","param":"repo"},"exactSegments":true,"pathSegments":["api","v2","documents","search"],"queryParams":[{"name":"q","param":"prismicQ","charset":"prismic_single_doc_query","minLen":5,"maxLen":300}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"jsonMode":"headless_cms_doc"}},{"match":{"exactSegments":true,"excludeSegmentSuffixes":[".json",".xml",".csv"],"pathSegments":["api",{"param":"contentType","charset":"strapi_content_type","minLen":1,"maxLen":80,"reserved":["auth","users","upload","graphql","all","list","search","export","v0","v1","v2","v3","v4","v5","v6","v7","v8","v9"]},{"param":"docId","charset":"strapi_doc_id","minLen":1,"maxLen":128,"reserved":["all","list","search","export","graphql","graphql.json","users"]}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"jsonMode":"headless_cms_doc"}}],"htmlRoutes":[{"id":"headless-cms-delivery","match":{"exactSegments":false},"mode":"headless_cms_html"}]},{"id":"headless-commerce","name":"Headless & Enterprise Commerce (commercetools, Elastic Path, Kibo, Optimizely)","category":"commerce-social","description":"Extracts commercetools, Elastic Path, Kibo/Mozu, and Optimizely Configured Commerce JSON-LD (with additionalProperty specs), Microdata, and hydration state.","domains":["www.bang-olufsen.com","www.guestsupply.com"],"universalEngine":true,"auth_mode":"html","exampleUrls":["https://www.bang-olufsen.com/en/us/headphones/beoplay-h100","https://www.guestsupply.com/product/0078423-Keystone-Liquid-Laundry-Built-Detergent-5-Gallon-1602538"],"htmlRoutes":[{"id":"headless-commerce","match":{"exactSegments":false},"mode":"headless_commerce_html"}]},{"id":"healthcare-careers","name":"Healthcare Careers (HealthcareSource & symplr)","category":"jobs","description":"Extracts hospital and clinical job postings from HealthcareSource (*.healthcaresource.com) and symplr career pages while rejecting Application Error and WAF shells and deferring careers.symplr.com to Jibe.","domains":["*.healthcaresource.com","www.symplr.com","symplr.com"],"universalEngine":true,"auth_mode":"html","exampleUrls":["https://pm.healthcaresource.com/cs/stclair"],"htmlRoutes":[{"id":"healthcare-careers","mode":"healthcare_careers_html","match":{"excludeHosts":["careers.symplr.com"],"exactSegments":false}}]},{"id":"healthcare-gov-marketplace","name":"HealthCare.gov Marketplace API","category":"research-health","description":"CMS HealthCare.gov Marketplace Plan Search (POST), States, Counties, and Plan Detail API (HEALTHCARE_GOV_API_KEY) with healthcare.gov HTML fallback.","domains":["marketplace.api.healthcare.gov","www.healthcare.gov","healthcare.gov"],"auth_mode":"key","min_interval_ms":1000,"exampleUrls":["https://marketplace.api.healthcare.gov/api/v1/plans/search","https://marketplace.api.healthcare.gov/api/v1/states","https://www.healthcare.gov/glossary/affordable-care-act/"],"routes":[{"match":{"hosts":["marketplace.api.healthcare.gov"],"pathPrefix":"/api/v1/plans/search"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","method":"POST","contentType":"application/json","requestBody":"{\"household\":{\"income\":52000,\"people\":[{\"age\":30,\"aptc_eligible\":true,\"uses_tobacco\":false}]},\"market\":\"Individual\",\"place\":{\"zipcode\":\"27360\",\"state\":\"NC\",\"countyfips\":\"37057\"},\"year\":2026}","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"healthcare_marketplace_json"}},{"match":{"hosts":["marketplace.api.healthcare.gov"],"anyOf":[{"pathPrefix":"/api/v1/states"},{"pathPrefix":"/api/v1/counties/"},{"pathPrefix":"/api/v1/plans/"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","method":"GET","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"healthcare_marketplace_json"}}],"htmlRoutes":[{"id":"healthcare-gov-marketplace","match":{"hosts":["www.healthcare.gov","healthcare.gov"],"exactSegments":false},"mode":"healthcare_gov_html"}]},{"id":"helpscout-docs","name":"Help Scout Docs","category":"developer","description":"Extracts Help Scout Docs knowledge base articles and collections from server-rendered HTML and BreadcrumbList JSON-LD.","domains":["docs.helpscout.com"],"universalEngine":true,"auth_mode":"html","exampleUrls":["https://docs.helpscout.com/article/666-use-dkim-to-help-with-email-delivery","https://docs.helpscout.com/collection/1543-getting-started"],"htmlRoutes":[{"id":"helpscout-docs","match":{"exactSegments":false},"mode":"helpscout_docs_html"}]},{"id":"hex-pm","name":"Hex.pm Elixir & Erlang Registry","category":"developer","description":"Upgrades hex.pm package pages to /api/packages/ metadata and HexDocs links.","domains":["hex.pm","www.hex.pm"],"exampleUrls":["https://hex.pm/packages/phoenix"],"match":{"exactSegments":true,"pathSegments":["packages",{"param":"pkg","charset":"alnum_dash"}]},"twin":{"fetchUrl":"https://hex.pm/api/packages/{pkg}","kind":"json","accept":"application/json"},"extract":{"requireFields":["name"],"vars":{"name":{"paths":["name"]},"desc":{"paths":["meta.description"],"trim":true},"licenses":{"paths":["meta.licenses"],"join":", "},"ver":{"paths":["releases.0.version"]},"verOrDefault":{"paths":["releases.0.version"],"default":"0.1"},"docsUrl":{"paths":["docs_html_url"],"fallbackTemplate":"https://hexdocs.pm/{name}"}},"titleTemplate":"{name} {ver} (Hex)","titleWhenVar":"ver","titleFallbackTemplate":"{name} (Hex)","descriptionVar":"desc","introVar":"desc","bullets":[{"label":"Mix","template":"`{:{name}, \"~> {verOrDefault}\"}`"},{"label":"HexDocs","template":"{docsUrl}"},{"label":"License","template":"{licenses}","whenVar":"licenses"}],"objectLinksPath":"meta.links"}},{"id":"home-depot-lowes","name":"Home Depot & Lowe's Product JSON-LD","category":"commerce-social","description":"Strictly low-rate, robots-enforced JSON-LD Product/ProductGroup extractor for Home Depot and Lowe's product pages.","domains":["homedepot.com","www.homedepot.com","lowes.com","www.lowes.com"],"auth_mode":"html","min_interval_ms":3000,"max_concurrent":1,"strict_robots":true,"exampleUrls":["https://www.homedepot.com/p/Milwaukee-M18-FUEL-Hammer-Drill-2904-20/320326137","https://www.lowes.com/pd/DEWALT-20V-MAX-Drill/501326137"],"htmlRoutes":[{"id":"home-depot-lowes","match":{"exactSegments":false},"mode":"home_depot_lowes_html"}]},{"id":"home-goods-jsonld","name":"US Home Goods Product JSON-LD","category":"commerce-social","description":"Structured Product and ProductGroup JSON-LD extractor for Wayfair and Overstock.","domains":["wayfair.com","www.wayfair.com","overstock.com","www.overstock.com"],"auth_mode":"html","min_interval_ms":2000,"strict_robots":true,"exampleUrls":["https://www.wayfair.com/furniture/pdp/mercury-row-perdue-815-velvet-square-arm-convertible-sofa-w009315804.html?piid=1134429065","https://www.overstock.com/Home-Garden/accent-chair/1400001/product.html"],"htmlRoutes":[{"id":"home-goods-jsonld","match":{"exactSegments":false},"mode":"home_goods_jsonld_html"}]},{"id":"homebrew-formulae","name":"Homebrew Formulae & Casks","category":"developer","description":"Upgrades formulae.brew.sh/formula/ and /cask/ pages to the official Homebrew JSON API with install commands, dependencies, deprecation/disable notices, and 30-day install analytics.","domains":["formulae.brew.sh"],"exampleUrls":["https://formulae.brew.sh/formula/jq","https://formulae.brew.sh/cask/iterm2"],"routes":[{"match":{"exactSegments":true,"excludeSegmentSuffixes":[".json"],"pathSegments":["formula",{"param":"id","charset":"brew_id","minLen":1,"maxLen":128}]},"twin":{"fetchUrl":"https://formulae.brew.sh/api/formula/{id}.json","rawPathParams":["id"],"kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"requireFields":["name"],"vars":{"name":{"paths":["name"]},"fullName":{"paths":["full_name","name"]},"desc":{"paths":["desc"],"trim":true},"version":{"paths":["versions.stable","versions.head"]},"license":{"paths":["license"]},"homepage":{"paths":["homepage"],"requireHttps":true},"deps":{"paths":["dependencies"],"itemWrap":"`","join":", ","limit":20},"buildDeps":{"paths":["build_dependencies"],"itemWrap":"`","join":", ","limit":15},"caveats":{"paths":["caveats"],"trim":true},"installs30d":{"dynamicKeyPath":{"base":"analytics.install.30d","keyVar":"id"},"format":"int_comma"},"disabledFlag":{"paths":["disabled"],"format":"bool_map","trueValue":"Disabled","falseValue":""},"disabledReason":{"paths":["disable_reason"]},"disabledDate":{"paths":["disable_date"]},"deprecatedFlag":{"paths":["deprecated"],"format":"bool_map","trueValue":"Deprecated","falseValue":""},"deprecationReason":{"paths":["deprecation_reason"]},"deprecationDate":{"paths":["deprecation_date"]},"replacement":{"paths":["disable_replacement_formula","disable_replacement_cask","deprecation_replacement_formula","deprecation_replacement_cask"]},"disabledSummary":{"template":"Disabled ({disabledReason}, {disabledDate})","whenVars":["disabledFlag","disabledReason","disabledDate"],"fallbackVar":"disabledFlag"},"deprecatedSummary":{"template":"Deprecated ({deprecationReason}, {deprecationDate})","whenVars":["deprecatedFlag","deprecationReason","deprecationDate"],"fallbackVar":"deprecatedFlag"},"statusNotice":{"template":"{disabledSummary}","whenVars":["disabledSummary"],"fallbackVar":"deprecatedSummary"}},"titleTemplate":"{fullName} (Homebrew Formula)","descriptionVar":"desc","blockquoteTemplate":"> **Notice**: {statusNotice}","blockquoteWhenVar":"statusNotice","introVar":"desc","bullets":[{"label":"Install","template":"`brew install {name}`"},{"label":"Stable Version","template":"`{version}`","whenVar":"version"},{"label":"License","template":"{license}","whenVar":"license"},{"label":"Replacement","template":"`{replacement}`","whenVar":"replacement"},{"label":"30d Installs","template":"{installs30d}","whenVar":"installs30d"},{"label":"Homepage","template":"{homepage}","whenVar":"homepage"},{"label":"Dependencies","template":"{deps}","whenVar":"deps"},{"label":"Build Dependencies","template":"{buildDeps}","whenVar":"buildDeps"}],"sections":[{"heading":"Caveats","textVar":"caveats"}],"linksVars":["homepage"]}},{"match":{"exactSegments":true,"excludeSegmentSuffixes":[".json"],"pathSegments":["cask",{"param":"id","charset":"brew_id","minLen":1,"maxLen":128}]},"twin":{"fetchUrl":"https://formulae.brew.sh/api/cask/{id}.json","rawPathParams":["id"],"kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"requireFields":["token"],"vars":{"token":{"paths":["token"]},"displayName":{"paths":["name.0","full_token","token"]},"desc":{"paths":["desc"],"trim":true},"version":{"paths":["version"]},"homepage":{"paths":["homepage"],"requireHttps":true},"downloadUrl":{"paths":["url"],"requireHttps":true},"sha256":{"paths":["sha256"]},"autoUpdates":{"paths":["auto_updates"],"format":"bool_map","trueValue":"Yes","falseValue":"No"},"caveats":{"paths":["caveats"],"trim":true},"installs30d":{"dynamicKeyPath":{"base":"analytics.install.30d","keyVar":"id"},"format":"int_comma"},"disabledFlag":{"paths":["disabled"],"format":"bool_map","trueValue":"Disabled","falseValue":""},"disabledReason":{"paths":["disable_reason"]},"disabledDate":{"paths":["disable_date"]},"deprecatedFlag":{"paths":["deprecated"],"format":"bool_map","trueValue":"Deprecated","falseValue":""},"deprecationReason":{"paths":["deprecation_reason"]},"deprecationDate":{"paths":["deprecation_date"]},"replacement":{"paths":["disable_replacement_cask","disable_replacement_formula","deprecation_replacement_cask","deprecation_replacement_formula"]},"disabledSummary":{"template":"Disabled ({disabledReason}, {disabledDate})","whenVars":["disabledFlag","disabledReason","disabledDate"],"fallbackVar":"disabledFlag"},"deprecatedSummary":{"template":"Deprecated ({deprecationReason}, {deprecationDate})","whenVars":["deprecatedFlag","deprecationReason","deprecationDate"],"fallbackVar":"deprecatedFlag"},"statusNotice":{"template":"{disabledSummary}","whenVars":["disabledSummary"],"fallbackVar":"deprecatedSummary"}},"titleTemplate":"{displayName} (Homebrew Cask)","descriptionVar":"desc","blockquoteTemplate":"> **Notice**: {statusNotice}","blockquoteWhenVar":"statusNotice","introVar":"desc","bullets":[{"label":"Install","template":"`brew install --cask {token}`"},{"label":"Token","template":"`{token}`"},{"label":"Version","template":"`{version}`","whenVar":"version"},{"label":"Auto Updates","template":"{autoUpdates}","whenVar":"autoUpdates"},{"label":"Replacement","template":"`{replacement}`","whenVar":"replacement"},{"label":"30d Installs","template":"{installs30d}","whenVar":"installs30d"},{"label":"Homepage","template":"{homepage}","whenVar":"homepage"},{"label":"Download URL","template":"{downloadUrl}","whenVar":"downloadUrl"},{"label":"SHA-256","template":"`{sha256}`","whenVar":"sha256"}],"sections":[{"heading":"Caveats","textVar":"caveats"}],"linksVars":["homepage","downloadUrl"]}}]},{"id":"hourly-smb-ats","name":"Hourly & SMB ATS (Hireology, ApplicantPro, Harri, Fountain, ClearCompany, Workstream)","category":"jobs","description":"Extracts JobPosting JSON-LD, Next.js SSR boards, and structured HTML job postings from Hireology, ApplicantPro, Harri, Fountain, ClearCompany, and Workstream.","domains":["www.applicantpro.com","www.clearcompany.com","app.hireology.com","harri.com","web.fountain.com","www.workstream.us"],"universalEngine":true,"auth_mode":"html","exampleUrls":["https://careers.hireology.com/hireology2/2908935/description","https://harri.com/Kitchen-Putters-Cw"],"htmlRoutes":[{"id":"hourly-smb-ats","mode":"hourly_smb_ats_html","match":{"excludeHosts":["recruiting.ultipro.com","recruiting.paylocity.com","app.dover.com","jobs.dover.com","jobs.smartrecruiters.com","*.oraclecloud.com","jobs.jobvite.com","app.clearcompany.com"],"anyOf":[{"hostSubdomain":{"suffix":".applicantpro.com","param":"tenant","reserved":["www","login","admin"]},"exactSegments":false},{"hosts":["www.applicantpro.com"],"pathPrefix":"/careers","exactSegments":false},{"hostSubdomain":{"suffix":".clearcompany.com","param":"tenant","reserved":["app","login","admin"]},"exactSegments":false},{"hosts":["careers.hireology.com","app.hireology.com"],"exactSegments":false},{"hosts":["harri.com","www.harri.com"],"exactSegments":false},{"hosts":["web.fountain.com"],"pathPrefix":"/apply/","exactSegments":false},{"hostSubdomain":{"suffix":".workstream.us","param":"tenant","reserved":["app","login","api"]},"exactSegments":false}]}}]},{"id":"hrsa-samhsa-locator","name":"HRSA & SAMHSA Treatment Locator","category":"research-health","description":"SAMHSA FindTreatment.gov locator JSON export API adapter with HRSA/SAMHSA portal HTML fallback.","domains":["data.hrsa.gov","findahealthcenter.hrsa.gov","findtreatment.gov","www.findtreatment.gov"],"auth_mode":"pub","exampleUrls":["https://findtreatment.gov/locator/exportsAsJson/v2?sAddr=40.7506%2C-73.9972&sType=SA&limitValue=5000&limitType=2&pageSize=2&page=1","https://data.hrsa.gov/tools/web-services"],"routes":[{"match":{"hosts":["findtreatment.gov","www.findtreatment.gov"],"pathPrefix":"/locator/exportsAsJson/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"samhsa_locator_json"}}],"htmlRoutes":[{"id":"hrsa-samhsa-locator","match":{"hosts":["data.hrsa.gov","findahealthcenter.hrsa.gov","findtreatment.gov","www.findtreatment.gov"],"exactSegments":false},"mode":"hrsa_samhsa_html"}]},{"id":"hubspot-cms","name":"HubSpot CMS","category":"developer","description":"Extracts same-origin HubSpot HubDB table rows (/_hcms/api/hubdb/v3/... and /hs/api/hubdb/v2/...) and HubSpot CMS HTML metadata while rejecting page_id:0 404s.","domains":["www.hubspot.com","developers.hubspot.com","www.smartbugmedia.com"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://www.smartbugmedia.com/blog/hubspot-unbound-2026-recap-7-ai-updates-to-turn-on-first-and-what-each-one-costs"],"routes":[{"match":{"exactSegments":true,"pathSegments":["_hcms","api","hubdb","v3","tables",{"param":"tableId","charset":"url_seg","minLen":1,"maxLen":120},"rows"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"hubspot_hubdb_json"}},{"match":{"exactSegments":true,"pathSegments":["hs","api","hubdb","v2","tables",{"param":"tableId","charset":"url_seg","minLen":1,"maxLen":120},"rows"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"hubspot_hubdb_json"}}],"htmlRoutes":[{"id":"hubspot-cms","match":{"exactSegments":false},"mode":"hubspot_cms_html"}]},{"id":"hud-fhfa","name":"HUD User & FHFA House Price Index","category":"public-records","description":"Extracts HUD User Fair Market Rent / Income Limit API JSON (when HUD_API_KEY is configured), FHFA House Price Index JSON & CSV datasets, and FHFA HPI HTML pages.","domains":["huduser.gov","www.huduser.gov","fhfa.gov","www.fhfa.gov"],"auth_mode":"key","exampleUrls":["https://www.huduser.gov/hudapi/public/fmr/listStates","https://www.fhfa.gov/hpi/download/quarterly_datasets/hpi_at_state.csv","https://www.fhfa.gov/data/hpi"],"routes":[{"match":{"hosts":["huduser.gov","www.huduser.gov"],"pathPrefix":"/hudapi/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304,"auth_mode":"key"},"extract":{"jsonMode":"hud_user_json"}},{"match":{"hosts":["fhfa.gov","www.fhfa.gov"],"pathPrefix":"/hpi/download/","pathSuffix":".json"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304,"auth_mode":"pub"},"extract":{"jsonMode":"fhfa_hpi_json"}},{"match":{"hosts":["fhfa.gov","www.fhfa.gov"],"pathPrefix":"/hpi/download/","pathSuffix":".csv"},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"text/plain","maxBytes":4194304,"auth_mode":"pub"},"extract":{"textMode":"fhfa_hpi_csv"}}],"htmlRoutes":[{"id":"hud-fhfa","match":{"hosts":["fhfa.gov","www.fhfa.gov","huduser.gov","www.huduser.gov"],"exactSegments":false},"mode":"hud_fhfa_html"}]},{"id":"huggingface","name":"Hugging Face Models, Datasets & Spaces","category":"genai","description":"Upgrades Hugging Face model/dataset/space pages and file blobs to raw README.md with parsed YAML frontmatter tables.","domains":["huggingface.co","www.huggingface.co"],"exampleUrls":["https://huggingface.co/Qwen/Qwen2.5-Coder-32B-Instruct"],"routes":[{"match":{"anyOf":[{"exactSegments":true,"pathSegments":[{"param":"repoType","allowValues":["datasets","spaces"]},{"param":"org","charset":"pkg"},{"param":"repo","charset":"pkg"}],"defaults":{"rev":"main"}},{"exactSegments":true,"pathSegments":[{"param":"repoType","allowValues":["datasets","spaces"]},{"param":"org","charset":"pkg"},{"param":"repo","charset":"pkg"},"tree",{"param":"rev","charset":"pkg"}]}]},"twin":{"id":"huggingface-card","fetchUrl":"https://huggingface.co/{repoType}/{org}/{repo}/raw/{rev}/README.md","kind":"text","accept":"text/markdown"},"extract":{"textMode":"yaml_frontmatter_card","titleTemplate":"{repoType}/{org}/{repo}"}},{"match":{"anyOf":[{"exactSegments":true,"pathSegments":[{"param":"org","charset":"pkg","reserved":["models","datasets","spaces","docs","blog","papers","posts","tasks","organizations","settings","login","join","pricing"]},{"param":"repo","charset":"pkg"}],"defaults":{"rev":"main"}},{"exactSegments":true,"pathSegments":[{"param":"org","charset":"pkg","reserved":["models","datasets","spaces","docs","blog","papers","posts","tasks","organizations","settings","login","join","pricing"]},{"param":"repo","charset":"pkg"},"tree",{"param":"rev","charset":"pkg"}]}]},"twin":{"id":"huggingface-card","fetchUrl":"https://huggingface.co/{org}/{repo}/raw/{rev}/README.md","kind":"text","accept":"text/markdown"},"extract":{"textMode":"yaml_frontmatter_card","titleTemplate":"{org}/{repo}"}},{"match":{"pathSegments":[{"param":"repoType","allowValues":["datasets","spaces"]},{"param":"org","charset":"pkg"},{"param":"repo","charset":"pkg"},"blob",{"param":"rev","charset":"pkg"},{"param":"filePath","charset":"safe_subpath","greedy":true,"maxLen":240}]},"twin":{"id":"huggingface-blob","fetchUrl":"https://huggingface.co/{repoType}/{org}/{repo}/raw/{rev}/{filePath}","rawPathParams":["filePath"],"kind":"text","accept":"text/plain"},"extract":{"textMode":"code_or_markdown_by_path","pathParam":"filePath","titleTemplate":"{repoType}/{org}/{repo}/{filePath}"}},{"match":{"pathSegments":[{"param":"org","charset":"pkg","reserved":["models","datasets","spaces","docs","blog","papers","posts","tasks","organizations","settings","login","join","pricing"]},{"param":"repo","charset":"pkg"},"blob",{"param":"rev","charset":"pkg"},{"param":"filePath","charset":"safe_subpath","greedy":true,"maxLen":240}]},"twin":{"id":"huggingface-blob","fetchUrl":"https://huggingface.co/{org}/{repo}/raw/{rev}/{filePath}","rawPathParams":["filePath"],"kind":"text","accept":"text/plain"},"extract":{"textMode":"code_or_markdown_by_path","pathParam":"filePath","titleTemplate":"{org}/{repo}/{filePath}"}}]},{"id":"icims","name":"iCIMS Enterprise Career Portals","category":"jobs","description":"Upgrades *.icims.com/jobs/... portals and postings to their server-rendered ?ss=1&in_iframe=1 twin, extracting JobPosting JSON-LD and open role cards without outer iframe shells.","domains":["*.icims.com"],"exampleUrls":["https://careers-compsych.icims.com/jobs/search?ss=1","https://careers-compsych.icims.com/jobs/2526/senior-cloud-architect/job"],"routes":[{"match":{"hostSubdomain":{"suffix":".icims.com","param":"org","reserved":["www","status","support","community","developer","developers","login"]},"exactSegments":true,"pathSegments":[]},"twin":{"id":"icims","fetchUrl":"{requestUrl}","overridePathIf":{"matchPaths":["/"],"newPath":"/jobs/search"},"defaultQueryParams":{"ss":"1"},"setQueryParams":{"in_iframe":"1"},"kind":"text","accept":"text/html"},"extract":{"icimsPortal":true}},{"match":{"hostSubdomain":{"suffix":".icims.com","param":"org","reserved":["www","status","support","community","developer","developers","login"]},"anyOf":[{"exactSegments":true,"pathSegments":["jobs"]},{"exactSegments":true,"pathSegments":["jobs","intro"]},{"exactSegments":true,"pathSegments":["jobs","search"]}]},"twin":{"id":"icims","fetchUrl":"{requestUrl}","overridePathIf":{"matchPaths":["/jobs","/jobs/intro","/jobs/search"],"newPath":"/jobs/search"},"defaultQueryParams":{"ss":"1"},"setQueryParams":{"in_iframe":"1"},"kind":"text","accept":"text/html"},"extract":{"icimsPortal":true}},{"match":{"hostSubdomain":{"suffix":".icims.com","param":"org","reserved":["www","status","support","community","developer","developers","login"]},"exactSegments":false,"pathSegments":["jobs"]},"twin":{"id":"icims","fetchUrl":"{requestUrl}","setQueryParams":{"in_iframe":"1"},"kind":"text","accept":"text/html"},"extract":{"icimsPortal":true}}],"htmlRoutes":[{"id":"icims","mode":"icims_portal","match":{"hostSubdomain":{"suffix":".icims.com","param":"org","reserved":["www","status","support","community","developer","developers","login"]},"exactSegments":false,"pathSegments":["jobs"]}}]},{"id":"idx-broker-showcase","name":"IDX Broker & Showcase IDX Real Estate Portals","category":"commerce-social","description":"Extracts real estate property listings, MLS numbers, pricing, and RealEstateAgent/RealEstateListing metadata from IDX Broker and Showcase IDX portals while rejecting 403/WAF shells.","domains":["*.idxbroker.com","entityrealty.com","realtorrajaram.com"],"universalEngine":true,"auth_mode":"html","strict_robots":true,"min_interval_ms":2000,"exampleUrls":["https://entityrealty.com/","https://entityrealty.com/properties/"],"htmlRoutes":[{"id":"idx-broker-showcase","match":{"exactSegments":false},"mode":"idx_broker_showcase_html"}]},{"id":"ietf-rfc","name":"IETF Datatracker & RFC Editor","category":"developer","description":"Strips ASCII RFC running page headers/footers ([Page N]) and promotes numbered section headings to Markdown headings.","domains":["datatracker.ietf.org","rfc-editor.org","www.rfc-editor.org"],"exampleUrls":["https://datatracker.ietf.org/doc/html/rfc9421","https://www.rfc-editor.org/rfc/rfc9110"],"routes":[{"match":{"hosts":["rfc-editor.org","www.rfc-editor.org"],"pathPrefix":"/rfc/rfc","exactSegments":true,"pathSegments":["rfc",{"param":"rfcId","stripPrefix":"rfc","charset":"digits","minLen":1,"maxLen":6}]},"twin":{"fetchUrl":"https://www.rfc-editor.org/rfc/rfc{rfcId}.html","kind":"text","accept":"text/html","maxBytes":4194304},"extract":{"textMode":"html_document","titleTemplate":"RFC {rfcId}"}}],"htmlRoutes":[{"match":{"anyOf":[{"hosts":["datatracker.ietf.org"],"pathPrefix":"/doc/html/rfc"},{"hosts":["datatracker.ietf.org"],"pathPrefix":"/doc/html/draft-"},{"hosts":["rfc-editor.org","www.rfc-editor.org"],"pathPrefix":"/rfc/rfc","minSegments":2}]},"mode":"markdown_clean","cleanPreset":"ietf_rfc"}]},{"id":"ifixit","name":"iFixit Repair Guides & Wikis","category":"developer","description":"Extracts repair guides, steps, tools, parts, and category wikis from ifixit.com /api/2.0/ JSON endpoints with HTML fallback.","domains":["ifixit.com","www.ifixit.com"],"auth_mode":"pub","exampleUrls":["https://www.ifixit.com/api/2.0/guides/1","https://www.ifixit.com/api/2.0/wikis/CATEGORY/Bicycle","https://www.ifixit.com/Guide/Bicycle+Chain+Replacement/41537"],"routes":[{"match":{"hosts":["ifixit.com","www.ifixit.com"],"exactSegments":true,"pathSegments":["api","2.0","guides",{"param":"guideId","charset":"digits","minLen":1,"maxLen":16}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"ifixit_json"}},{"match":{"hosts":["ifixit.com","www.ifixit.com"],"exactSegments":false,"pathSegments":["api","2.0","wikis",{"param":"ns","charset":"url_seg","minLen":1,"maxLen":40},{"param":"name","charset":"safe_subpath","greedy":true,"minLen":1,"maxLen":200}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"ifixit_json"}}],"htmlRoutes":[{"id":"ifixit","match":{"hosts":["ifixit.com","www.ifixit.com"],"exactSegments":false},"mode":"ifixit_html"}]},{"id":"igdb","name":"IGDB (Internet Game Database)","category":"commerce-social","description":"Official keyed IGDB v4 APICALYPSE POST API adapter (TWITCH_API_TOKEN + TWITCH_CLIENT_ID) for game metadata, ratings, genres, and platforms, with igdb.com HTML fallback.","domains":["api.igdb.com","www.igdb.com","igdb.com"],"auth_mode":"key","min_interval_ms":1000,"exampleUrls":["https://www.igdb.com/games/portal-2","https://api.igdb.com/v4/games"],"routes":[{"match":{"hosts":["api.igdb.com"],"pathPrefix":"/v4/","exactSegments":false},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","method":"POST","contentType":"text/plain","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"igdb_json"}},{"match":{"hosts":["www.igdb.com","igdb.com"],"exactSegments":true,"pathSegments":["games",{"param":"slug","charset":"slug","minLen":1,"maxLen":160}]},"twin":{"fetchUrl":"https://api.igdb.com/v4/games","kind":"json","accept":"application/json","method":"POST","contentType":"text/plain","requestBody":"fields name,slug,summary,rating,rating_count,first_release_date,genres.name,platforms.name,involved_companies.company.name,url; where slug = \"{slug}\"; limit 1;","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"igdb_json"}}],"htmlRoutes":[{"id":"igdb","match":{"hosts":["www.igdb.com","igdb.com"],"exactSegments":false},"mode":"igdb_html"}]},{"id":"imdb-datasets","name":"IMDb Non-Commercial Datasets","category":"commerce-social","description":"Bounded Range-streaming TSV sample extractor for datasets.imdbws.com *.tsv.gz archives and data.imdb.com / developer.imdb.com documentation, explicitly emitting nonCommercialLicense: true and IMDb Non-Commercial Datasets licensing notice.","domains":["datasets.imdbws.com","developer.imdb.com","data.imdb.com"],"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://datasets.imdbws.com/title.ratings.tsv.gz","https://data.imdb.com/non-commercial-datasets/","https://developer.imdb.com/non-commercial-datasets/"],"routes":[{"match":{"hosts":["datasets.imdbws.com"],"pathSuffix":".tsv.gz","exactSegments":true,"pathSegments":[{"param":"datasetFile","charset":"pkg","minLen":5,"maxLen":80}]},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"text/plain","headers":{"Range":"bytes=0-262143"},"maxBytes":524288},"extract":{"textMode":"imdb_datasets_tsv"}}],"htmlRoutes":[{"id":"imdb-datasets","match":{"hosts":["developer.imdb.com","data.imdb.com"],"exactSegments":false},"mode":"imdb_datasets_html"}]},{"id":"import-alerts-aphis-fda","name":"FDA Import Alerts & USDA APHIS Import Manuals","category":"public-records","description":"Extracts FDA Import Alerts (/cms_ia/* on accessdata.fda.gov) and USDA APHIS import guidance and manuals (aphis.usda.gov).","domains":["www.accessdata.fda.gov","accessdata.fda.gov","www.aphis.usda.gov","aphis.usda.gov"],"auth_mode":"pub","exampleUrls":["https://www.accessdata.fda.gov/cms_ia/importalert_3.html","https://www.accessdata.fda.gov/cms_ia/ialist.html","https://www.aphis.usda.gov/plant-imports","https://www.aphis.usda.gov/trade-management-manuals"],"htmlRoutes":[{"id":"import-alerts-aphis-fda","match":{"hosts":["www.accessdata.fda.gov","accessdata.fda.gov"],"pathPrefix":"/cms_ia/"},"mode":"import_alerts_fda_aphis_html"},{"id":"import-alerts-aphis-fda","match":{"hosts":["www.aphis.usda.gov","aphis.usda.gov"],"exactSegments":false},"mode":"import_alerts_fda_aphis_html"}]},{"id":"intercom-help","name":"Intercom Help Center","category":"developer","description":"Extracts Intercom Help Center articles and collections from __NEXT_DATA__ hydration, JSON-LD, and semantic HTML.","domains":["support.claude.com","www.intercom.com"],"universalEngine":true,"auth_mode":"html","min_interval_ms":1000,"exampleUrls":["https://support.claude.com/en/articles/7996845-what-are-some-things-i-can-use-claude-for","https://support.claude.com/en/collections/4078531-claude"],"htmlRoutes":[{"id":"intercom-help","match":{"exactSegments":false},"mode":"intercom_help_html"}]},{"id":"internet-archive","name":"Internet Archive Items (archive.org)","category":"genai","description":"Upgrades archive.org/details/ pages to the official /metadata/ JSON feed with creator, license, and downloadable files.","domains":["archive.org","www.archive.org"],"exampleUrls":["https://archive.org/details/07-28-16_Space-to-Grounds.zip"],"match":{"exactSegments":true,"pathSegments":["details",{"param":"identifier","charset":"pkg","minLen":2,"maxLen":120}]},"twin":{"fetchUrl":"https://archive.org/metadata/{identifier}","kind":"json","accept":"application/json"},"extract":{"requireAnyFields":["metadata"],"vars":{"title":{"paths":["metadata.title"],"fallbackTemplate":"{identifier}","trim":true},"creator":{"paths":["metadata.creator"],"join":", "},"mediatype":{"paths":["metadata.mediatype"]},"date":{"paths":["metadata.date","metadata.publicdate"]},"license":{"paths":["metadata.licenseurl"]},"collections":{"paths":["metadata.collection"],"limit":6,"join":", "},"desc":{"paths":["metadata.description"],"join":"\n\n","format":"strip_tags"},"descShort":{"paths":["metadata.description"],"join":"\n\n","format":"strip_tags","sliceMax":260}},"titleTemplate":"{title}","descriptionVar":"descShort","authorVar":"creator","publishedTimeVar":"date","bullets":[{"label":"Identifier","template":"`{identifier}`"},{"label":"Creator","template":"{creator}","whenVar":"creator"},{"label":"Media Type","template":"{mediatype}","whenVar":"mediatype"},{"label":"Date","template":"{date}","whenVar":"date"},{"label":"Collections","template":"{collections}","whenVar":"collections"},{"label":"License","template":"{license}","whenVar":"license"}],"sections":[{"heading":"Description","textVar":"desc"},{"heading":"Files","arrayPath":"files","filter":{"excludeFieldSuffixes":{"field":"name","suffixes":["_meta.xml","_files.xml"]}},"limit":15,"requireItemVar":"fname","collectLinkVars":["dlUrl"],"itemVars":{"fname":{"paths":["name"]},"dlUrl":{"template":"https://archive.org/download/{identifier}/{fname}","whenVars":["fname"],"replaceAll":{"from":" ","to":"%20"}}},"columns":[{"header":"File","template":"[{fname}]({dlUrl})"},{"header":"Format","paths":["format"]},{"header":"Size","paths":["size"],"format":"bytes_human"}]}]}},{"id":"ir-portal-pack","name":"Investor Relations Portals (Notified / Equisolve / Nasdaq IR)","category":"finance","description":"Extracts Notified/Intrado (wd_newsfeed), Equisolve, and Nasdaq IR investor relations portals and RSS press release feeds.","domains":["investor.iridium.com","ir.bowheadspecialty.com"],"universalEngine":true,"auth_mode":"pub","strict_robots":true,"min_interval_ms":1000,"exampleUrls":["https://investor.iridium.com/press-releases","https://ir.bowheadspecialty.com/news-events/press-releases/rss","https://ir.bowheadspecialty.com/news-events/press-releases"],"routes":[{"match":{"hosts":["investor.iridium.com","ir.bowheadspecialty.com"],"anyOf":[{"pathSuffix":"/rss"},{"pathSuffix":".rss"},{"pathPrefix":"/rss/"}],"exactSegments":false},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"application/rss+xml","maxBytes":2097152},"extract":{"textMode":"ir_portal_rss_xml"}}],"htmlRoutes":[{"id":"ir-portal-pack","match":{"exactSegments":false},"mode":"ir_portal_pack_html"}]},{"id":"irs-teos","name":"IRS Tax Exempt Organization Search (TEOS)","category":"public-records","description":"Extracts IRS Tax Exempt Organization Search (Pub 78 / Form 990-N) lookup records while respecting robots.txt and strictly rejecting Akamai WAF challenge pages.","domains":["apps.irs.gov"],"auth_mode":"pub","strict_robots":true,"exampleUrls":["https://apps.irs.gov/app/eos/allSearch?ein=521693387","https://apps.irs.gov/app/eos/details/521693387"],"routes":[{"match":{"hosts":["apps.irs.gov"],"pathPrefix":"/app/eos/allSearch"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"pub","maxBytes":2097152},"extract":{"jsonMode":"irs_teos_json"}},{"match":{"hosts":["apps.irs.gov"],"exactSegments":false,"pathSegments":["app","eos","details",{"param":"ein","charset":"alnum_dash","minLen":4,"maxLen":20}]},"twin":{"fetchUrl":"https://apps.irs.gov/app/eos/allSearch?ein={ein}","kind":"json","accept":"application/json","auth_mode":"pub","maxBytes":2097152},"extract":{"jsonMode":"irs_teos_json"}}],"htmlRoutes":[{"id":"irs-teos","match":{"hosts":["apps.irs.gov"],"pathPrefix":"/app/eos/","exactSegments":false},"mode":"irs_teos_html"}]},{"id":"javadoc-dokka","name":"Javadoc & Kotlin Dokka API Docs","category":"developer","description":"Universal extractor for Javadoc and Kotlin Dokka HTML API pages as well as element-list and package-list index manifests.","domains":["docs.oracle.com","kotlinlang.org"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/String.html","https://docs.oracle.com/en/java/javase/21/docs/api/element-list","https://kotlinlang.org/api/core/kotlin-stdlib/kotlin/-string/index.html"],"routes":[{"match":{"anyOf":[{"pathSuffix":"/element-list"},{"pathSuffix":"/package-list"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"text/plain","maxBytes":1048576},"extract":{"textMode":"javadoc_element_list_text"}}],"htmlRoutes":[{"id":"javadoc-dokka","match":{"exactSegments":false},"mode":"javadoc_dokka_html"}]},{"id":"jazzhr","name":"JazzHR Career Boards (applytojob.com)","category":"jobs","description":"Upgrades .applytojob.com boards to app.jazz.co/feeds/export/jobs/ XML export (which includes full job descriptions and returns clean 404 on invalid slugs).","domains":["*.applytojob.com"],"exampleUrls":["https://axiomcloud.applytojob.com/apply"],"match":{"hostSubdomain":{"suffix":".applytojob.com","param":"org","reserved":["www","app"]},"maxSegments":1},"twin":{"id":"jazzhr","fetchUrl":"https://app.jazz.co/feeds/export/jobs/{org}","kind":"text","accept":"application/xml"},"extract":{"xml":{"mode":"items_table","requireAnyTags":["jobs","job"],"itemTag":"job","titleTemplate":"{org} — JazzHR Job Board ({itemCount} open roles)","emptyText":"No open positions currently listed.","limit":100,"requireItemVar":"jTitle","collectLinkVar":"jUrl","itemVars":{"jTitle":{"tags":["title"]},"jUrl":{"tags":["url"]},"dept":{"tags":["department"],"default":"-"},"city":{"tags":["city"]},"state":{"tags":["state"]},"country":{"tags":["country"]},"jType":{"tags":["type"],"default":"-"}},"columns":[{"header":"Role","template":"[{jTitle}]({jUrl})"},{"header":"Department","template":"{dept}"},{"header":"Location","template":"{city} {state} {country}"},{"header":"Type","template":"{jType}"}]}}},{"id":"jira-public","name":"Jira Public Issue Tracker","category":"developer","description":"Universal Jira Server/DC/Cloud extractor supporting direct /rest/api/2|3/issue/ JSON endpoints and robots-compliant /browse/ SSR HTML extraction.","domains":["jira.mariadb.org","jira.atlassian.com"],"universalEngine":true,"auth_mode":"pub","min_interval_ms":2000,"exampleUrls":["https://jira.mariadb.org/rest/api/2/issue/MDEV-30000","https://jira.mariadb.org/browse/MDEV-30000","https://jira.atlassian.com/rest/api/2/issue/JRASERVER-71500"],"routes":[{"match":{"anyOf":[{"pathPrefix":"/rest/api/2/issue/"},{"pathPrefix":"/rest/api/3/issue/"},{"pathPrefix":"/jira/rest/api/2/issue/"},{"pathPrefix":"/jira/rest/api/3/issue/"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"jira_public_json"}}],"htmlRoutes":[{"id":"jira-public","match":{"anyOf":[{"pathPrefix":"/browse/"},{"pathPrefix":"/jira/browse/"}]},"mode":"jira_public_html"}]},{"id":"job-boards-jsonld-pack","name":"Job Boards (CareerArc, Nexxt, Reed, Alljobs)","category":"jobs","description":"Extracts JobPosting JSON-LD from CareerArc, Nexxt, Reed.co.uk, and Alljobs posting pages: title, company, locations, employment type, salary, posting/expiry dates, job ID, and description. Repairs the unescaped quotes CareerArc emits inside descriptions in one linear pass. Honors robots.txt.","domains":["www.careerarc.com","careerarc.com","www.nexxt.com","nexxt.com","www.reed.co.uk","reed.co.uk","www.alljobs.co.il","alljobs.co.il"],"auth_mode":"html","min_interval_ms":3000,"strict_robots":true,"exampleUrls":["https://www.careerarc.com/job-listing/state-of-vermont-jobs-trooper-probationary-53326582","https://www.nexxt.com/jobs/registered-nurse-rn-lebanon-oh-3496987559-job.html","https://www.reed.co.uk/jobs/nurse-wca/57553089","https://www.alljobs.co.il/Search/UploadSingle.aspx?JobID=8822511"],"htmlRoutes":[{"id":"job-boards-jsonld-pack","match":{"hosts":["www.careerarc.com","careerarc.com","www.nexxt.com","nexxt.com","www.reed.co.uk","reed.co.uk","www.alljobs.co.il","alljobs.co.il"],"exactSegments":false},"mode":"job_boards_jsonld_html"}]},{"id":"jsr-io","name":"JSR JavaScript Registry","category":"developer","description":"Strips top-bar navigation and duplicate version/scorecard tabs from jsr.io/@scope/pkg Markdown.","domains":["jsr.io"],"exampleUrls":["https://jsr.io/@std/path"],"htmlRoutes":[{"match":{"exactSegments":false,"pathSegments":[{"param":"scope","charset":"npm_scope"},{"param":"pkg","charset":"npm_pkg"}]},"mode":"markdown_clean","cleanPreset":"jsr_io"}]},{"id":"judge-me","name":"Judge.me Product Reviews","category":"commerce-social","description":"Extracts public Judge.me product reviews widget JSON and HTML-in-JSON payloads without preempting storefront extractors.","domains":["api.judge.me","judge.me","cache.judge.me"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://api.judge.me/reviews/reviews_for_widget?shop_domain=thebraindriver.myshopify.com&platform=shopify&product_id=3946432580&page=1&per_page=10"],"routes":[{"match":{"hosts":["api.judge.me","judge.me","cache.judge.me"],"pathEquals":["/reviews/reviews_for_widget","/api/v1/widgets/product_review","/api/v1/reviews"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"judgeme_reviews"}}],"htmlRoutes":[{"id":"judge-me","match":{"exactSegments":false},"mode":"judgeme_html"}]},{"id":"junar-tyler-data","name":"Junar & Tyler Data & Insights Open Data Portals","category":"public-records","description":"Extracts Junar /dataviews/ HTML and /api/v2/datastreams/ JSON plus Tyler Data & Insights /api/catalog/v1 datasets (without overlapping Socrata claims).","domains":["data.paloalto.gov","*.junar.com","data.tylertech.com"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://data.tylertech.com/api/catalog/v1","https://data.tylertech.com/api/catalog/v1?limit=5","https://data.paloalto.gov/home"],"routes":[{"match":{"anyOf":[{"pathPrefix":"/api/v2/datastreams/"},{"pathPrefix":"/api/catalog/v1"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"junar_tyler_json"}}],"htmlRoutes":[{"id":"junar-tyler-data","match":{"exactSegments":false},"mode":"junar_tyler_html"}]},{"id":"jwplayer","name":"JW Player Delivery & Previews","category":"commerce-social","description":"Extracts JW Player CDN v2 media/playlist JSON twins, /previews/{mediaId} redirects to v2 media JSON, and JW Platform feeds.","domains":["cdn.jwplayer.com","content.jwplatform.com"],"auth_mode":"pub","exampleUrls":["https://cdn.jwplayer.com/v2/media/1b02B03R","https://cdn.jwplayer.com/previews/1b02B03R"],"routes":[{"match":{"hosts":["cdn.jwplayer.com"],"exactSegments":true,"pathSegments":["v2",{"param":"kind","allowValues":["media","playlists"]},{"param":"mediaId","charset":"alnum","minLen":6,"maxLen":16}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"jwplayer_json"}},{"match":{"hosts":["cdn.jwplayer.com"],"exactSegments":true,"pathSegments":["previews",{"param":"mediaId","charset":"alnum","minLen":6,"maxLen":16}]},"twin":{"fetchUrl":"https://cdn.jwplayer.com/v2/media/{mediaId}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"jwplayer_json"}},{"match":{"hosts":["content.jwplatform.com"],"exactSegments":true,"pathSuffix":".json","pathSegments":["feeds",{"param":"mediaFile","charset":"url_seg","stripSuffix":".json","minLen":4,"maxLen":40}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"jwplayer_json"}}],"htmlRoutes":[{"id":"jwplayer","match":{"exactSegments":false},"mode":"jwplayer_html"}]},{"id":"kaggle","name":"Kaggle Datasets, Models & Competitions","category":"developer","description":"Extracts Kaggle dataset, model, and competition metadata via Kaggle REST API v1 (KAGGLE_API_KEY) with public HTML fallback.","domains":["www.kaggle.com","kaggle.com"],"auth_mode":"key","exampleUrls":["https://www.kaggle.com/api/v1/datasets/view/heptapod/titanic","https://www.kaggle.com/datasets/heptapod/titanic"],"routes":[{"match":{"hosts":["www.kaggle.com","kaggle.com"],"pathPrefix":"/api/v1/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"kaggle_json"}},{"match":{"hosts":["www.kaggle.com","kaggle.com"],"exactSegments":false,"pathSegments":["datasets",{"param":"owner","charset":"pkg","minLen":1,"maxLen":100},{"param":"slug","charset":"pkg","minLen":1,"maxLen":120}]},"twin":{"fetchUrl":"https://www.kaggle.com/api/v1/datasets/view/{owner}/{slug}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"kaggle_json"}}],"htmlRoutes":[{"id":"kaggle","match":{"hosts":["www.kaggle.com","kaggle.com"],"exactSegments":false},"mode":"kaggle_html"}]},{"id":"kb-platform-pack","name":"KB Platform Pack (Document360, Helpjuice, KnowledgeOwl)","category":"developer","description":"Extracts public knowledge base articles and categories across Document360, Helpjuice, and KnowledgeOwl.","domains":["docs.document360.com","help.helpjuice.com","support.knowledgeowl.com"],"universalEngine":true,"auth_mode":"html","exampleUrls":["https://help.helpjuice.com/getting-started/what-is-a-knowledge-base","https://support.knowledgeowl.com/help/enable-single-sign-on-sso"],"htmlRoutes":[{"id":"kb-platform-pack","match":{"exactSegments":false},"mode":"kb_platform_pack_html"}]},{"id":"khoros-lithium","name":"Khoros / Lithium Communities","category":"developer","description":"Upgrades Khoros/Lithium /t5/.../td-p/ community threads to /api/2.0/messages/ JSON twins with HTML fallback.","domains":["community.qlik.com"],"universalEngine":true,"auth_mode":"pub","min_interval_ms":5000,"exampleUrls":["https://community.qlik.com/t5/Product-Innovation/AI-Without-Context-Is-Guessing-With-Confidence-Our-October-Qlik/ba-p/2560737","https://community.qlik.com/api/2.0/messages/2560737"],"routes":[{"match":{"pathPrefix":"/t5/","anyOf":[{"scanSegment":{"afterLiteral":"td-p","param":"msgId","charset":"digits","minLen":1,"maxLen":16}},{"scanSegment":{"afterLiteral":"m-p","param":"msgId","charset":"digits","minLen":1,"maxLen":16}},{"scanSegment":{"afterLiteral":"ba-p","param":"msgId","charset":"digits","minLen":1,"maxLen":16}},{"scanSegment":{"afterLiteral":"ta-p","param":"msgId","charset":"digits","minLen":1,"maxLen":16}}]},"twin":{"fetchUrl":"https://{host}/api/2.0/messages/{msgId}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"khoros_message"}},{"match":{"pathSegments":["api","2.0","messages",{"param":"msgId","charset":"digits","minLen":1,"maxLen":16}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"khoros_message"}}],"htmlRoutes":[{"id":"khoros-lithium","match":{"exactSegments":false},"mode":"khoros_html"}]},{"id":"klaviyo-attentive-forms","name":"Klaviyo & Attentive Onsite Forms (Read-Only)","category":"commerce-social","description":"Strictly read-only extractor for Klaviyo onsite company/form IDs, signup offer metadata, and Attentive tag metadata without submitting forms; yields on product/article pages.","domains":["www.getcasely.com","www.klaviyo.com","static.klaviyo.com","cdn.attn.tv"],"universalEngine":true,"auth_mode":"html","exampleUrls":["https://www.klaviyo.com/"],"htmlRoutes":[{"id":"klaviyo-attentive-forms","match":{"exactSegments":false},"mode":"klaviyo_attentive_forms_html"}]},{"id":"klevu","name":"Klevu Smart Search","category":"commerce-social","description":"Opt-in page-key adapter for Klevu v2 POST search JSON endpoints; defaults OFF and falls back cleanly to HTML/JSON-LD when disabled.","domains":["eucs15v2.ksearchnet.com"],"universalEngine":true,"auth_mode":"page-key","requires_page_key_opt_in":true,"exampleUrls":["https://eucs15v2.ksearchnet.com/cs/v2/search"],"routes":[{"match":{"hostSubdomain":{"suffix":".ksearchnet.com","param":"clusterHost"},"pathEquals":["/cs/v2/search"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","method":"POST","contentType":"application/json","requestBody":"{\"context\":{\"apiKeys\":[\"klevu-156925593843210765\"]},\"recordQueries\":[{\"id\":\"productList\",\"typeOfRequest\":\"SEARCH\",\"settings\":{\"query\":{\"term\":\"bag\"},\"limit\":10}}]}","requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"jsonMode":"klevu"}}],"htmlRoutes":[{"id":"klevu","match":{"exactSegments":false},"mode":"klevu_html"}]},{"id":"kroger","name":"Kroger Public Products API","category":"commerce-social","description":"Extracts Kroger product UPC/GTIN, brand, size, pricing, and fulfillment metadata via the official Kroger v1 Products API.","domains":["kroger.com","www.kroger.com","api.kroger.com"],"auth_mode":"key","exampleUrls":["https://api.kroger.com/v1/products/0001111085135","https://api.kroger.com/v1/products?filter.term=oats"],"routes":[{"match":{"hosts":["kroger.com","www.kroger.com"],"exactSegments":false,"pathSegments":["p",{"param":"slug","charset":"url_seg","maxLen":200},{"param":"upc","charset":"digits","minLen":8,"maxLen":14}]},"twin":{"fetchUrl":"https://api.kroger.com/v1/products/{upc}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"kroger_json"}},{"match":{"hosts":["api.kroger.com"],"pathPrefix":"/v1/products"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"kroger_json"}}]},{"id":"lang-registry-pack","name":"Language Registry Pack (pub.dev, CRAN, CocoaPods, Anaconda)","category":"developer","description":"Extracts package metadata and newest stable versions from Dart pub.dev, R CRAN HTML, CocoaPods HTML, and Anaconda/conda-forge API.","domains":["pub.dev","cran.r-project.org","cocoapods.org","anaconda.org","api.anaconda.org"],"auth_mode":"pub","exampleUrls":["https://pub.dev/packages/http","https://cocoapods.org/pods/Alamofire","https://anaconda.org/conda-forge/six"],"routes":[{"match":{"hosts":["pub.dev"],"pathPrefix":"/api/packages/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"pubdev_json"}},{"match":{"hosts":["pub.dev"],"exactSegments":false,"pathSegments":["packages",{"param":"pkg","charset":"pkg","minLen":1,"maxLen":120}]},"twin":{"fetchUrl":"https://pub.dev/api/packages/{pkg}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"pubdev_json"}},{"match":{"hosts":["api.anaconda.org"],"pathPrefix":"/package/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"anaconda_json"}},{"match":{"hosts":["anaconda.org"],"exactSegments":true,"reservedFirstSegment":["search","admin","download","static","api","login","signup","docs","pricing","about"],"pathSegments":[{"param":"channel","charset":"pkg","minLen":1,"maxLen":80},{"param":"pkg","charset":"pkg","minLen":1,"maxLen":120}]},"twin":{"fetchUrl":"https://api.anaconda.org/package/{channel}/{pkg}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"anaconda_json"}}],"htmlRoutes":[{"id":"lang-registry-pack","match":{"hosts":["cran.r-project.org"],"pathPrefix":"/web/packages/","exactSegments":false},"mode":"cran_html"},{"id":"lang-registry-pack","match":{"hosts":["cocoapods.org"],"pathPrefix":"/pods/","exactSegments":false},"mode":"cocoapods_html"}]},{"id":"laserfiche-weblink","name":"Laserfiche WebLink Public Document Portals","category":"public-records","description":"Universal Laserfiche WebLink adapter for city and county records portals. DocView.aspx and Browse.aspx links that carry id and repo (as WebLink share links do) upgrade to the anonymous JSON services the viewer itself calls: document name, folder path, template, created/modified dates, page count and metadata fields, or a folder listing with links. No cookies or login are used; the CookieCheck redirect only guards the HTML shell.","domains":["cc-publicdocs.santa-ana.org","records.hawaiicounty.gov","docs.southbendin.gov","weblink.winterspringsfl.org"],"universalEngine":true,"auth_mode":"pub","min_interval_ms":3000,"strict_robots":true,"exampleUrls":["https://cc-publicdocs.santa-ana.org/WebLink/DocView.aspx?id=82504&dbid=1&repo=Clerk","https://cc-publicdocs.santa-ana.org/WebLink/Browse.aspx?id=82479&dbid=1&repo=Clerk"],"routes":[{"match":{"exactSegments":true,"pathSegments":[{"param":"vdir","charset":"slug","minLen":2,"maxLen":40},"DocView.aspx"],"queryParams":[{"name":"id","param":"id","charset":"digits","minLen":1,"maxLen":12},{"name":"repo","param":"repo","charset":"slug","minLen":1,"maxLen":80}]},"twin":{"fetchUrl":"https://{host}/{vdir}/DocumentService.aspx/GetBasicDocumentInfo","kind":"json","accept":"application/json","method":"POST","contentType":"application/json","requestBody":"{\"repoName\":\"{repo}\",\"entryId\":{id}}","maxBytes":2097152},"extract":{"jsonMode":"laserfiche_doc_json"}},{"match":{"exactSegments":true,"pathSegments":[{"param":"vdir","charset":"slug","minLen":2,"maxLen":40},"Browse.aspx"],"queryParams":[{"name":"id","param":"id","charset":"digits","minLen":1,"maxLen":12},{"name":"repo","param":"repo","charset":"slug","minLen":1,"maxLen":80}]},"twin":{"fetchUrl":"https://{host}/{vdir}/FolderListingService.aspx/GetFolderListing2","kind":"json","accept":"application/json","method":"POST","contentType":"application/json","requestBody":"{\"repoName\":\"{repo}\",\"folderId\":{id},\"getNewListing\":true,\"start\":0,\"end\":50,\"sortColumn\":\"\",\"sortAscending\":true}","maxBytes":4194304},"extract":{"jsonMode":"laserfiche_folder_json"}}],"htmlRoutes":[{"id":"laserfiche-weblink","match":{"exactSegments":false},"mode":"laserfiche_missing_repo_html"}]},{"id":"legacy-cart","name":"Legacy Shopping Carts (OpenCart, nopCommerce, Shift4Shop, Volusion)","category":"commerce-social","description":"Extracts OpenCart, nopCommerce, Shift4Shop, and Volusion product JSON-LD, Microdata, and spec-table DOM while filtering template noise.","domains":["www.eurekagolf.co.uk","www.sturdybuiltonline.com","www.cctvcamerapros.com"],"universalEngine":true,"auth_mode":"html","exampleUrls":["https://www.eurekagolf.co.uk/oakley-standard-polo-shirt-pacific-blue","https://www.sturdybuiltonline.com/Steel-Diamond-Plate-Utility-Trailer-Fender-Single-Axle-10-in-x-32-in-x-13-in_p_215.html","https://www.cctvcamerapros.com/HDMI-to-USB-Converter-p/hdmi-u3.htm"],"htmlRoutes":[{"id":"legacy-cart","match":{"exactSegments":false},"mode":"legacy_cart_html"}]},{"id":"legistar","name":"Legistar Municipal Council Legislation & Meetings","category":"public-records","description":"Upgrades .legistar.com municipal council portals to the keyless webapi.legistar.com REST API for ordinances, resolutions, and meetings.","domains":["*.legistar.com"],"exampleUrls":["https://seattle.legistar.com/Legislation.aspx","https://seattle.legistar.com/Calendar.aspx"],"routes":[{"match":{"anyOf":[{"hostSubdomain":{"suffix":".legistar.com","param":"client","reserved":["www","webapi"]},"pathSuffix":"calendar.aspx","derivedParams":{"clientUpper":{"fromParam":"client","transform":"upper"}}},{"hostSubdomain":{"suffix":".legistar.com","param":"client","reserved":["www","webapi"]},"pathContainsSegment":"calendar","derivedParams":{"clientUpper":{"fromParam":"client","transform":"upper"}}}]},"twin":{"fetchUrl":"https://webapi.legistar.com/v1/{client}/events?$top=20&$orderby=EventDate%20desc","kind":"json","accept":"application/json"},"extract":{"wrapRootArrayAs":"items","requireAnyFields":["items"],"titleTemplate":"{clientUpper} Municipal Council — Recent Meetings (Legistar)","sections":[{"heading":"","arrayPath":"items","limit":20,"itemVars":{"agendaUrl":{"paths":["EventInSiteURL"],"requireHttps":true},"linkCell":{"template":"[Agenda]({agendaUrl})","whenVars":["agendaUrl"],"default":"-"}},"columns":[{"header":"Date","paths":["EventDate"],"sliceMax":10},{"header":"Body / Committee","paths":["EventBodyName"]},{"header":"Location","paths":["EventLocation"]},{"header":"Link","template":"{linkCell}"}]}]}},{"match":{"hostSubdomain":{"suffix":".legistar.com","param":"client","reserved":["www","webapi"]},"derivedParams":{"clientUpper":{"fromParam":"client","transform":"upper"}}},"twin":{"fetchUrl":"https://webapi.legistar.com/v1/{client}/matters?$top=25&$orderby=MatterIntroDate%20desc","kind":"json","accept":"application/json"},"extract":{"wrapRootArrayAs":"items","requireAnyFields":["items"],"titleTemplate":"{clientUpper} Municipal Legislation — Recent Matters (Legistar)","sections":[{"heading":"","arrayPath":"items","limit":25,"columns":[{"header":"File #","paths":["MatterFile"],"code":true},{"header":"Type","paths":["MatterTypeName"]},{"header":"Status","paths":["MatterStatusName"]},{"header":"Introduced","paths":["MatterIntroDate"],"sliceMax":10},{"header":"Title","paths":["MatterTitle","MatterName"]}]}]}}]},{"id":"lemmy","name":"Lemmy Federated Link Aggregator (Universal Engine)","category":"commerce-social","description":"Upgrades Lemmy posts (/post/{id}), communities (/c/{name}), and /api/v3/* endpoints via JSON API with SSR HTML fallback while rejecting Cloudflare challenges.","domains":["lemmy.world","lemmy.ml","programming.dev","sh.itjust.works"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://lemmy.world/api/v3/post?id=54926010","https://lemmy.world/api/v3/community?name=memes","https://lemmy.world/post/54926010","https://lemmy.ml/post/55819348"],"routes":[{"match":{"excludeHosts":["offerup.com","www.offerup.com"],"exactSegments":true,"pathSegments":["api","v3","post"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"lemmy_json"}},{"match":{"excludeHosts":["offerup.com","www.offerup.com"],"exactSegments":true,"pathSegments":["api","v3","comment","list"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"lemmy_json"}},{"match":{"excludeHosts":["offerup.com","www.offerup.com"],"exactSegments":true,"pathSegments":["api","v3","community"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"lemmy_json"}},{"match":{"excludeHosts":["offerup.com","www.offerup.com"],"exactSegments":false,"pathSegments":["post",{"param":"postId","charset":"digits","minLen":1,"maxLen":16}]},"twin":{"fetchUrl":"https://{host}/api/v3/post?id={postId}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"lemmy_json"}},{"match":{"excludeHosts":["offerup.com","www.offerup.com"],"exactSegments":true,"pathSegments":["c",{"param":"communityName","charset":"brew_id","minLen":1,"maxLen":120,"reserved":["api","pictrs","feeds","u","post","search","communities","login","signup"]}]},"twin":{"fetchUrl":"https://{host}/api/v3/community?name={communityName}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"lemmy_json"}}],"htmlRoutes":[{"id":"lemmy","match":{"exactSegments":false},"mode":"lemmy_html"}]},{"id":"libraries-io","name":"Libraries.io Package Metadata API","category":"developer","description":"Extracts cross-ecosystem package metadata, latest stable release, dependents, and repository signals via the official Libraries.io API (LIBRARIES_IO_API_KEY).","domains":["libraries.io"],"auth_mode":"key","exampleUrls":["https://libraries.io/api/npm/express"],"routes":[{"match":{"hosts":["libraries.io"],"pathPrefix":"/api/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"libraries_io_json"}},{"match":{"hosts":["libraries.io"],"exactSegments":false,"pathSegments":["npm",{"param":"scope","charset":"npm_scope","minLen":2,"maxLen":80},{"param":"pkg","charset":"npm_pkg","minLen":1,"maxLen":120}]},"twin":{"fetchUrl":"https://libraries.io/api/npm/{scope}%2F{pkg}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"libraries_io_json"}},{"match":{"hosts":["libraries.io"],"exactSegments":false,"pathSegments":[{"param":"platform","allowValues":["npm","pypi","rubygems","cargo","go","nuget","packagist","hex","maven","pub","cran","cocoapods","conda"]},{"param":"pkg","charset":"url_seg","minLen":1,"maxLen":160}]},"twin":{"fetchUrl":"https://libraries.io/api/{platform}/{pkg}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"libraries_io_json"}}]},{"id":"lightspeed-ecom","name":"Lightspeed eCom (C-Series)","category":"commerce-social","description":"Extracts Lightspeed eCom C-Series ?format=json product and collection twins plus custom-domain storefront HTML/companion discovery.","domains":["www.kayasieraden.nl"],"universalEngine":true,"auth_mode":"pub","min_interval_ms":2000,"exampleUrls":["https://www.kayasieraden.nl/nl/feestdagen-actie-gratis-armband.html","https://www.kayasieraden.nl/nl/feestdagen-actie-gratis-armband.html?format=json"],"routes":[{"match":{"hosts":["www.kayasieraden.nl"],"pathSuffix":".html"},"twin":{"fetchUrl":"{requestUrl}","setQueryParams":{"format":"json"},"kind":"json","accept":"application/json"},"extract":{"commerceMode":"lightspeed_ecom_json"}}],"htmlRoutes":[{"id":"lightspeed-ecom","match":{"exactSegments":false},"mode":"lightspeed_ecom_html"}]},{"id":"lobsters","name":"Lobste.rs Computing Stories","category":"commerce-social","description":"Upgrades lobste.rs/s/ story pages to their .json feed with nested plain-text comments.","domains":["lobste.rs"],"exampleUrls":["https://lobste.rs/s/abc123/zero_alloc_go_parsers"],"match":{"exactSegments":false,"pathSegments":["s",{"param":"shortId","charset":"alnum","minLen":4,"maxLen":12}]},"twin":{"fetchUrl":"https://lobste.rs/s/{shortId}.json","kind":"json","accept":"application/json"},"extract":{"requireFields":["title"],"vars":{"title":{"paths":["title"],"trim":true},"storyUrl":{"paths":["url"]},"score":{"paths":["score"],"default":"0"},"user":{"paths":["submitter_user"]},"created":{"paths":["created_at"]},"tags":{"paths":["tags"],"itemWrap":"`","join":", "},"descPlain":{"paths":["description_plain"],"trim":true}},"titleTemplate":"{title}","authorVar":"user","publishedTimeVar":"created","metaLine":[{"label":"Score","template":"{score}"},{"label":"By","template":"@{user}","whenVar":"user"},{"label":"Tags","template":"{tags}","whenVar":"tags"},{"label":"Link","template":"{storyUrl}","whenVar":"storyUrl"}],"introVar":"descPlain","sections":[{"heading":"Comments","listArrayPath":"comments","limit":40,"indentField":"indent_level","indentOffset":-1,"maxIndent":6,"itemTemplate":"**@{user}** ({score} pts): {body}","requireItemVar":"body","itemVars":{"user":{"paths":["commenting_user"],"default":"user"},"score":{"paths":["score"],"default":"0"},"body":{"paths":["comment_plain"],"trim":true}}}],"linksVars":["storyUrl"]}},{"id":"loc-gov","name":"Library of Congress (loc.gov)","category":"public-records","description":"Library of Congress JSON (?fo=json) adapter for items, resources, and collections (excluding Chronicling America and disallowed search paths).","domains":["loc.gov","www.loc.gov"],"auth_mode":"pub","min_interval_ms":5000,"strict_robots":true,"exampleUrls":["https://www.loc.gov/item/2014645520/","https://www.loc.gov/item/2014645520/?fo=json","https://www.loc.gov/resource/ds.05251/?fo=json"],"routes":[{"match":{"hosts":["loc.gov","www.loc.gov"],"exactSegments":false,"reservedFirstSegment":["chroniclingamerica","search","fedsearch","cgi-bin","web_arch","myloc","nationalfilmregistry"],"pathSegments":["item",{"param":"itemId","charset":"url_seg","minLen":2,"maxLen":80}]},"twin":{"fetchUrl":"https://www.loc.gov/item/{itemId}/?fo=json","kind":"json","accept":"application/json","maxBytes":4194304,"auth_mode":"pub"},"extract":{"jsonMode":"loc_gov_json"}},{"match":{"hosts":["loc.gov","www.loc.gov"],"exactSegments":false,"reservedFirstSegment":["chroniclingamerica","search","fedsearch","cgi-bin","web_arch","myloc","nationalfilmregistry"],"pathSegments":["resource",{"param":"resourceId","charset":"url_seg","minLen":2,"maxLen":120}]},"twin":{"fetchUrl":"https://www.loc.gov/resource/{resourceId}/?fo=json","kind":"json","accept":"application/json","maxBytes":4194304,"auth_mode":"pub"},"extract":{"jsonMode":"loc_gov_json"}},{"match":{"hosts":["loc.gov","www.loc.gov"],"exactSegments":false,"reservedFirstSegment":["chroniclingamerica","search","fedsearch","cgi-bin","web_arch","myloc","nationalfilmregistry"],"pathSegments":["collections",{"param":"collectionId","charset":"alnum_dash","reserved":["chronicling-america"],"minLen":2,"maxLen":100}]},"twin":{"fetchUrl":"https://www.loc.gov/collections/{collectionId}/?fo=json","kind":"json","accept":"application/json","maxBytes":4194304,"auth_mode":"pub"},"extract":{"jsonMode":"loc_gov_json"}}],"htmlRoutes":[{"id":"loc-gov","match":{"anyOf":[{"hosts":["loc.gov","www.loc.gov"],"pathPrefix":"/item/"},{"hosts":["loc.gov","www.loc.gov"],"pathPrefix":"/resource/"},{"hosts":["loc.gov","www.loc.gov"],"exactSegments":false,"pathSegments":["collections",{"param":"collectionId","charset":"alnum_dash","reserved":["chronicling-america"],"minLen":2,"maxLen":100}]}]},"mode":"loc_gov_html"}]},{"id":"local-classifieds-marketplaces","name":"Craigslist, OfferUp & Facebook Marketplace","category":"commerce-social","description":"Extracts local classifieds listings and search feeds from Craigslist, OfferUp, and public Facebook Marketplace metadata while strictly honoring robots.txt and classifying login walls, blocks, and empty CSR shells.","domains":["craigslist.org","www.craigslist.org","*.craigslist.org","offerup.com","www.offerup.com","facebook.com","www.facebook.com","m.facebook.com"],"auth_mode":"html","min_interval_ms":2000,"strict_robots":true,"exampleUrls":["https://www.craigslist.org/view/d/san-francisco-wahoo-kickr-core-bike/rv3daGwPjNSovN5fQ4JpLk","https://sfbay.craigslist.org/search/bik","https://offerup.com/c/bikes-and-cycling","https://www.facebook.com/marketplace/sanfrancisco/bicycles"],"htmlRoutes":[{"id":"local-classifieds-marketplaces","match":{"anyOf":[{"pathPrefix":"/view/d/"},{"pathPrefix":"/search/"},{"pathPrefix":"/c/"},{"pathPrefix":"/explore/"},{"pathPrefix":"/item/detail/"},{"pathEquals":["/marketplace"]},{"pathPrefix":"/marketplace/"},{"pathContainsSegment":"d"}]},"mode":"local_classifieds_html"}]},{"id":"market-quotes-pack","name":"Market Quotes Pack (Alpha Vantage, Polygon/Massive, Tiingo)","category":"finance","description":"Extracts equity, FX, and market quote JSON feeds from Alpha Vantage, Polygon/Massive, and Tiingo official keyed APIs.","domains":["www.alphavantage.co","alphavantage.co","api.polygon.io","api.massive.com","api.tiingo.com"],"auth_mode":"key","min_interval_ms":1000,"exampleUrls":["https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=IBM","https://api.polygon.io/v2/aggs/ticker/AAPL/prev","https://api.massive.com/v2/aggs/ticker/AAPL/prev","https://api.tiingo.com/tiingo/daily/aapl/prices"],"routes":[{"match":{"hosts":["www.alphavantage.co","alphavantage.co"],"pathEquals":["/query"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"market_quotes_json"}},{"match":{"hosts":["api.polygon.io","api.massive.com"],"anyOf":[{"pathPrefix":"/v2/"},{"pathPrefix":"/v3/"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"market_quotes_json"}},{"match":{"hosts":["api.tiingo.com"],"pathPrefix":"/tiingo/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"market_quotes_json"}}]},{"id":"mastodon-status","name":"Mastodon & Fediverse Statuses (Universal Engine)","category":"commerce-social","description":"Upgrades Fediverse status permalinks (/@/) on any Mastodon instance to /api/v1/statuses/ JSON.","domains":["mastodon.social","fosstodon.org","hachyderm.io"],"universalEngine":true,"exampleUrls":["https://fosstodon.org/@realpython/117694898741277050"],"match":{"excludeHosts":["medium.com","*.medium.com","tiktok.com","*.tiktok.com","threads.net","*.threads.net"],"exactSegments":true,"pathSegments":[{"param":"userHandle","charset":"at_handle"},{"param":"statusId","charset":"digits","minLen":15,"maxLen":24}]},"twin":{"id":"mastodon-status","fetchUrl":"https://{host}/api/v1/statuses/{statusId}","kind":"json","accept":"application/json"},"extract":{"requireFields":["content","account.acct"],"vars":{"acct":{"paths":["account.acct"]},"displayName":{"paths":["account.display_name"],"fallbackTemplate":"{acct}"},"createdAt":{"paths":["created_at"]},"spoiler":{"paths":["spoiler_text"],"trim":true},"body":{"paths":["content"],"format":"html_to_md"}},"titleTemplate":"{displayName} (@{acct}@{host})","authorTemplate":"@{acct}@{host}","publishedTimeVar":"createdAt","blockquoteTemplate":"> [!NOTE]\n> **Content Note**: {spoiler}","blockquoteWhenVar":"spoiler","bodyVar":"body","sections":[{"heading":"","listArrayPath":"media_attachments","limit":16,"requireItemVar":"mediaDesc","itemVars":{"mediaDesc":{"paths":["description"],"trim":true}},"itemTemplate":"*Media description*: {mediaDesc}"}]}},{"id":"maven-central","name":"Maven Central","category":"developer","description":"Upgrades central.sonatype.com/artifact//[/] pages to the keyless Maven Central Solr JSON API (central.sonatype.com for versioned artifacts, search.maven.org for artifact summaries) with Maven/Gradle coordinates and artifact metadata.","domains":["central.sonatype.com"],"exampleUrls":["https://central.sonatype.com/artifact/com.fasterxml.jackson.core/jackson-databind","https://central.sonatype.com/artifact/com.fasterxml.jackson.core/jackson-databind/2.18.2"],"routes":[{"match":{"exactSegments":true,"pathSegments":["artifact",{"param":"g","charset":"pkg","minLen":1,"maxLen":160},{"param":"a","charset":"pkg","minLen":1,"maxLen":160},{"param":"v","charset":"pkg","reserved":["versions","overview","dependencies","dependents","jar"],"minLen":1,"maxLen":80}]},"twin":{"fetchUrl":"https://central.sonatype.com/solrsearch/select?q=g:{g}+AND+a:{a}+AND+v:{v}&core=gav&rows=20&wt=json","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"rootPath":"response.docs.0","requireFields":["id","g","a"],"vars":{"groupId":{"paths":["g"]},"artifactId":{"paths":["a"]},"ver":{"paths":["v","latestVersion"]},"packaging":{"paths":["p"]},"published":{"paths":["timestamp"],"format":"epoch_ms_date"},"artifacts":{"paths":["ec"],"itemWrap":"`","join":", ","limit":12},"centralUrl":{"template":"https://central.sonatype.com/artifact/{groupId}/{artifactId}/{ver}","requireHttps":true}},"titleTemplate":"{groupId}:{artifactId}:{ver} (Maven Central)","publishedTimeVar":"published","bullets":[{"label":"Maven Coordinate","template":"`{groupId}:{artifactId}:{ver}`"},{"label":"Gradle","template":"`implementation(\"{groupId}:{artifactId}:{ver}\")`"},{"label":"Packaging","template":"{packaging}","whenVar":"packaging"},{"label":"Published","template":"{published}","whenVar":"published"},{"label":"Classifiers / Files","template":"{artifacts}","whenVar":"artifacts"}],"linksVars":["centralUrl"]}},{"match":{"exactSegments":true,"pathSegments":["artifact",{"param":"g","charset":"pkg","minLen":1,"maxLen":160},{"param":"a","charset":"pkg","minLen":1,"maxLen":160}]},"twin":{"fetchUrl":"https://search.maven.org/solrsearch/select?q=g:{g}+AND+a:{a}&rows=20&wt=json","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"rootPath":"response.docs.0","requireFields":["id","g","a"],"vars":{"groupId":{"paths":["g"]},"artifactId":{"paths":["a"]},"ver":{"paths":["latestVersion","v"]},"packaging":{"paths":["p"]},"versionCount":{"paths":["versionCount"],"format":"int_comma"},"published":{"paths":["timestamp"],"format":"epoch_ms_date"},"artifacts":{"paths":["ec"],"itemWrap":"`","join":", ","limit":12},"centralUrl":{"template":"https://central.sonatype.com/artifact/{groupId}/{artifactId}","requireHttps":true}},"titleTemplate":"{groupId}:{artifactId}:{ver} (Maven Central)","titleWhenVar":"ver","titleFallbackTemplate":"{groupId}:{artifactId} (Maven Central)","publishedTimeVar":"published","bullets":[{"label":"Maven Coordinate","template":"`{groupId}:{artifactId}:{ver}`","whenVar":"ver"},{"label":"Gradle","template":"`implementation(\"{groupId}:{artifactId}:{ver}\")`","whenVar":"ver"},{"label":"Packaging","template":"{packaging}","whenVar":"packaging"},{"label":"Published","template":"{published}","whenVar":"published"},{"label":"Versions","template":"{versionCount}","whenVar":"versionCount"},{"label":"Classifiers / Files","template":"{artifacts}","whenVar":"artifacts"}],"linksVars":["centralUrl"]}}]},{"id":"mcp-directories","name":"Community MCP Directories (Smithery, Glama, PulseMCP)","category":"developer","description":"Extracts community MCP directory listings from Smithery Registry API and public Glama/PulseMCP HTML pages, tagging every record trustTier=community, untrusted=true.","domains":["smithery.ai","registry.smithery.ai","glama.ai","pulsemcp.com","www.pulsemcp.com"],"auth_mode":"pub","exampleUrls":["https://registry.smithery.ai/servers?pageSize=5","https://www.pulsemcp.com/servers?q=github","https://glama.ai/mcp/servers?query=github"],"routes":[{"match":{"hosts":["registry.smithery.ai"],"pathPrefix":"/servers"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"smithery_registry_json"}},{"match":{"hosts":["smithery.ai"],"exactSegments":true,"pathSegments":["server",{"param":"ns","charset":"pkg","minLen":1,"maxLen":80},{"param":"slug","charset":"url_seg","minLen":1,"maxLen":120}]},"twin":{"fetchUrl":"https://registry.smithery.ai/servers/{ns}/{slug}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"smithery_registry_json"}},{"match":{"hosts":["smithery.ai"],"exactSegments":true,"pathSegments":["server",{"param":"slug","charset":"url_seg","minLen":1,"maxLen":120}]},"twin":{"fetchUrl":"https://registry.smithery.ai/servers/{slug}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"smithery_registry_json"}}],"htmlRoutes":[{"id":"mcp-directories","match":{"hosts":["glama.ai"],"pathPrefix":"/mcp/servers","exactSegments":false},"mode":"mcp_directory_html"},{"id":"mcp-directories","match":{"hosts":["pulsemcp.com","www.pulsemcp.com"],"pathPrefix":"/servers","exactSegments":false},"mode":"mcp_directory_html"},{"id":"mcp-directories","match":{"hosts":["smithery.ai"],"exactSegments":false},"mode":"mcp_directory_html"}]},{"id":"mcp-registry","name":"Official Model Context Protocol (MCP) Registry","category":"developer","description":"Extracts official MCP server listings, remotes, and packages from registry.modelcontextprotocol.io tagged trustTier=official, untrusted=false.","domains":["registry.modelcontextprotocol.io"],"auth_mode":"pub","exampleUrls":["https://registry.modelcontextprotocol.io/v0/servers?limit=5"],"routes":[{"match":{"hosts":["registry.modelcontextprotocol.io"],"anyOf":[{"pathPrefix":"/v0/"},{"pathPrefix":"/v0.1/"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"mcp_registry_json"}}]},{"id":"mediawiki","name":"Wikipedia & MediaWiki Encyclopedias","category":"commerce-social","description":"Robots-compliant Wikipedia & MediaWiki adapter: strips [ ], Edit links, [n] citation markers, [edit], and navigation chrome with 24h article caching; pair with search({ query, wikipedia: true, lang }) for Special:Search-free article discovery and Wikimedia Enterprise or dumps.wikimedia.org for bulk corpus access.","domains":["*.wikipedia.org","wiki.archlinux.org"],"universalEngine":true,"exampleUrls":["https://en.wikipedia.org/wiki/HTTP/2"],"htmlRoutes":[{"id":"mediawiki","match":{"exactSegments":false},"mode":"markdown_clean","cleanPreset":"mediawiki"}]},{"id":"medicaid-nadac","name":"Medicaid NADAC Drug Pricing (DKAN)","category":"research-health","description":"Extracts data.medicaid.gov NADAC drug pricing DKAN metastore datasets, datastore queries, and /dataset/{id} twins while rejecting empty CMS Medicaid Data React shells.","domains":["data.medicaid.gov"],"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://data.medicaid.gov/api/1/metastore/schemas/dataset/items/fbb83258-11c7-47f5-8b18-5f8e79f7e704","https://data.medicaid.gov/api/1/datastore/query/e3af839d-8175-5be0-b94e-4a302ed7a035/0?limit=5","https://data.medicaid.gov/dataset/fbb83258-11c7-47f5-8b18-5f8e79f7e704"],"routes":[{"match":{"pathPrefix":"/api/1/metastore/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"medicaid_nadac_json"}},{"match":{"pathPrefix":"/api/1/datastore/query/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"medicaid_nadac_json"}},{"match":{"exactSegments":false,"pathSegments":["dataset",{"param":"datasetId","charset":"alnum_dash","minLen":8,"maxLen":64}]},"twin":{"fetchUrl":"https://data.medicaid.gov/api/1/metastore/schemas/dataset/items/{datasetId}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"medicaid_nadac_json"}}],"htmlRoutes":[{"id":"medicaid-nadac","match":{"exactSegments":false},"mode":"medicaid_nadac_html"}]},{"id":"medium","name":"Medium","category":"commerce-social","description":"Extracts Medium ?format=json responses with linear anti-XSSI prefix stripping, Medium RSS feeds, and Medium article HTML.","domains":["medium.com"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://medium.com/p/62edea66ffa4?format=json","https://medium.com/@medium/updating-our-rules-june-2023-62edea66ffa4","https://medium.com/feed/@medium"],"routes":[{"match":{"hosts":["medium.com"],"exactSegments":false,"queryParams":[{"name":"format","param":"fmt","allowValues":["json"]}]},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"application/json"},"extract":{"textMode":"medium_xssi_json"}},{"match":{"hosts":["medium.com"],"exactSegments":true,"pathSegments":["p",{"param":"postId","charset":"alnum","minLen":8,"maxLen":20}]},"twin":{"fetchUrl":"https://medium.com/p/{postId}?format=json","kind":"text","accept":"application/json"},"extract":{"textMode":"medium_xssi_json"}},{"match":{"hosts":["medium.com"],"exactSegments":true,"pathSegments":[{"param":"userHandle","charset":"at_handle","minLen":2,"maxLen":80},{"param":"slugId","charset":"slug","minLen":10,"maxLen":200}]},"twin":{"fetchUrl":"{requestUrl}","setQueryParams":{"format":"json"},"kind":"text","accept":"application/json"},"extract":{"textMode":"medium_xssi_json"}},{"match":{"hosts":["medium.com"],"pathPrefix":"/feed/","exactSegments":false},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"application/rss+xml"},"extract":{"textMode":"medium_rss_xml"}}],"htmlRoutes":[{"id":"medium","match":{"exactSegments":false},"mode":"medium_html"}]},{"id":"medlineplus","name":"NLM MedlinePlus","category":"research-health","description":"MedlinePlus Health Topics XML web service, MedlinePlus Connect JSON API, and medlineplus.gov topic HTML extractor.","domains":["medlineplus.gov","www.medlineplus.gov","wsearch.nlm.nih.gov","connect.medlineplus.gov"],"auth_mode":"pub","exampleUrls":["https://wsearch.nlm.nih.gov/ws/query?db=healthTopics&term=diabetes&retmax=2","https://medlineplus.gov/diabetes.html"],"routes":[{"match":{"hosts":["wsearch.nlm.nih.gov"],"pathEquals":["/ws/query"]},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"text/xml","maxBytes":2097152},"extract":{"textMode":"medlineplus_xml"}},{"match":{"hosts":["connect.medlineplus.gov"],"pathEquals":["/service"]},"twin":{"fetchUrl":"{requestUrl}","setQueryParams":{"knowledgeResponseType":"application/json"},"kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"medlineplus_connect_json"}}],"htmlRoutes":[{"id":"medlineplus","match":{"hosts":["medlineplus.gov","www.medlineplus.gov"],"exactSegments":false},"mode":"medlineplus_html"}]},{"id":"medusa","name":"Medusa Storefront & Store API","category":"commerce-social","description":"Opt-in page-key adapter for Medusa /store/products API twins with Next.js RSC, JSON-LD, and DOM storefront HTML fallback when disabled.","domains":["next.medusajs.com","www.mattsleeps.com"],"universalEngine":true,"auth_mode":"page-key","requires_page_key_opt_in":true,"exampleUrls":["https://next.medusajs.com/dk/products/hoodie","https://www.mattsleeps.com/en/beds"],"routes":[{"match":{"optionalLeadingLocale":true,"exactSegments":true,"pathSegments":["store","products"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"commerceMode":"medusa_product"}},{"match":{"optionalLeadingLocale":true,"pathSegments":["store","products",{"param":"id","charset":"url_seg","minLen":1,"maxLen":160}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"commerceMode":"medusa_product"}}],"htmlRoutes":[{"id":"medusa","match":{"exactSegments":false},"mode":"medusa_html"}]},{"id":"meetup-luma","name":"Meetup & Luma Events","category":"commerce-social","description":"Extracts event title, schedule, venue/location, organizer, and description from Meetup and Luma (lu.ma / luma.com) via Schema.org Event JSON-LD and __NEXT_DATA__ hydration.","domains":["meetup.com","www.meetup.com","lu.ma","www.lu.ma","luma.com","www.luma.com"],"auth_mode":"html","exampleUrls":["https://www.meetup.com/lawofattractioncentre/events/317269557/","https://luma.com/8jye50v0"],"htmlRoutes":[{"id":"meetup-luma","match":{"exactSegments":false},"mode":"meetup_luma_html"}]},{"id":"midmarket-career-portals","name":"Mid-Market Career Portals (Paycom, Paycor, ADP)","category":"jobs","description":"Extracts structured open roles from Paycom (/v4/ats/web.php/portal/ & /api/ats/job-postings/), ADP Workforce Now (/mascsr/default/careercenter/), and public Paycor career pages.","domains":["pc00.paycomonline.com","www.paycomonline.net","workforcenow.adp.com","recruiting.adp.com","www.paycor.com"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://workforcenow.adp.com/mascsr/default/careercenter/public/events/staffing/v1/job-requisitions?cid=7a48330e-b9d5-4122-9051-71a47afa46d5"],"routes":[{"match":{"hostSubdomain":{"suffix":".paycomonline.net","param":"tenant","reserved":["login","auth","static","assets"]},"pathPrefix":"/api/ats/job-postings/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"paycom_json"}},{"match":{"hostSubdomain":{"suffix":".paycomonline.com","param":"tenant","reserved":["login","auth","static","assets"]},"pathPrefix":"/api/ats/job-postings/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"paycom_json"}},{"match":{"hosts":["workforcenow.adp.com","recruiting.adp.com"],"pathPrefix":"/mascsr/default/careercenter/public/events/staffing/v1/job-requisitions"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"adp_wfn_json"}}],"htmlRoutes":[{"id":"midmarket-career-portals","mode":"midmarket_career_html","match":{"excludeHosts":["recruiting.ultipro.com","recruiting.paylocity.com","app.dover.com","jobs.dover.com","jobs.smartrecruiters.com","*.oraclecloud.com","jobs.jobvite.com","recruitingbypaycor.com"],"anyOf":[{"hostSubdomain":{"suffix":".paycomonline.net","param":"tenant","reserved":["login","auth","static","assets"]},"pathPrefix":"/v4/ats/web.php/portal/"},{"hostSubdomain":{"suffix":".paycomonline.com","param":"tenant","reserved":["login","auth","static","assets"]},"pathPrefix":"/v4/ats/web.php/portal/"},{"hosts":["workforcenow.adp.com","recruiting.adp.com"],"exactSegments":false},{"hosts":["www.paycor.com"],"pathPrefix":"/company/careers","exactSegments":false}]}}]},{"id":"mitre-attack","name":"MITRE ATT&CK STIX & Knowledge Base","category":"developer","description":"Range-bounded linear STIX 2.1 bundle prefix scanner on GitHub raw attack-stix-data plus static HTML extractor for attack.mitre.org techniques, tactics, groups, and software.","domains":["attack.mitre.org","www.attack.mitre.org"],"universalEngine":true,"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://attack.mitre.org/techniques/T1059/","https://raw.githubusercontent.com/mitre-attack/attack-stix-data/master/index.json","https://raw.githubusercontent.com/mitre-attack/attack-stix-data/master/enterprise-attack/enterprise-attack.json"],"routes":[{"match":{"hosts":["raw.githubusercontent.com"],"exactSegments":true,"pathEquals":["/mitre-attack/attack-stix-data/master/index.json"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":1048576},"extract":{"jsonMode":"mitre_attack_index_json"}},{"match":{"hosts":["raw.githubusercontent.com"],"exactSegments":false,"pathPrefix":"/mitre-attack/attack-stix-data/","pathSuffix":".json"},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"application/json","headers":{"Range":"bytes=0-524287"},"maxBytes":1048576},"extract":{"textMode":"mitre_attack_stix_bundle"}}],"htmlRoutes":[{"id":"mitre-attack","match":{"hosts":["attack.mitre.org","www.attack.mitre.org"],"exactSegments":false},"mode":"mitre_attack_html"}]},{"id":"mitre-cwe-capec","name":"MITRE CWE & CAPEC Weaknesses and Attack Patterns","category":"developer","description":"Extracts Common Weakness Enumeration (CWE) JSON from cwe-api.mitre.org and XHTML definitions from cwe.mitre.org and capec.mitre.org.","domains":["cwe-api.mitre.org","cwe.mitre.org","capec.mitre.org"],"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://cwe-api.mitre.org/api/v1/cwe/weakness/79","https://cwe.mitre.org/data/definitions/79.html","https://capec.mitre.org/data/definitions/1.html"],"routes":[{"match":{"hosts":["cwe-api.mitre.org"],"exactSegments":false,"pathPrefix":"/api/v1/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"mitre_cwe_json"}},{"match":{"hosts":["cwe.mitre.org"],"exactSegments":true,"pathSegments":["data","definitions",{"param":"cweId","charset":"digits","stripSuffix":".html","minLen":1,"maxLen":8}]},"twin":{"fetchUrl":"https://cwe-api.mitre.org/api/v1/cwe/weakness/{cweId}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"mitre_cwe_json"}}],"htmlRoutes":[{"id":"mitre-cwe-capec","match":{"hosts":["cwe.mitre.org","capec.mitre.org"],"exactSegments":false},"mode":"mitre_cwe_capec_html"}]},{"id":"mlb-statsapi","name":"MLB Stats API","category":"commerce-social","description":"Extracts public MLB schedule, team, game linescore, standings, and player data from statsapi.mlb.com JSON endpoints with mlb.com HTML/JSON-LD fallback.","domains":["statsapi.mlb.com","mlb.com","www.mlb.com"],"auth_mode":"pub","exampleUrls":["https://statsapi.mlb.com/api/v1/schedule?sportId=1&date=2024-10-30","https://statsapi.mlb.com/api/v1/teams/119","https://statsapi.mlb.com/api/v1/game/775296/linescore","https://www.mlb.com/dodgers"],"routes":[{"match":{"hosts":["statsapi.mlb.com"],"anyOf":[{"pathPrefix":"/api/v1/schedule"},{"pathPrefix":"/api/v1/teams"},{"pathPrefix":"/api/v1/game/"},{"pathPrefix":"/api/v1/standings"},{"pathPrefix":"/api/v1/people"}],"exactSegments":false},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"mlb_statsapi_json"}}],"htmlRoutes":[{"id":"mlb-statsapi","mode":"mlb_statsapi_html","match":{"hosts":["mlb.com","www.mlb.com"],"exactSegments":false}}]},{"id":"model-hub-pack","name":"Model Hub Pack (Replicate & Civitai)","category":"genai","description":"Extracts ML model metadata, versions, hardware, and descriptions from Replicate and Civitai SSR/Next.js HTML pages while honoring robots.txt.","domains":["replicate.com","www.replicate.com","civitai.com","www.civitai.com"],"auth_mode":"pub","exampleUrls":["https://replicate.com/meta/meta-llama-3-8b-instruct","https://civitai.com/models/4201/realistic-vision-v60-b1"],"htmlRoutes":[{"id":"model-hub-pack","match":{"hosts":["replicate.com","www.replicate.com"],"exactSegments":false},"mode":"replicate_html"},{"id":"model-hub-pack","match":{"hosts":["civitai.com","www.civitai.com"],"exactSegments":false},"mode":"civitai_html"}]},{"id":"modern-community-pack","name":"Modern Community Pack","category":"commerce-social","description":"Extracts community discussions, authors, and timestamps from Higher Logic, Bettermode (rendered SSR DOM only), and Circle HTML while rejecting soft-404s and empty shells.","domains":["community.broadcom.com","community.flutterflow.io","community.xano.com"],"universalEngine":true,"auth_mode":"html","exampleUrls":["https://community.broadcom.com/vmware-cloud-foundation/discussion/black-screen-after-upgrading-opensuse-leap-16-0-to-16-1-disabling-vmware-graphics-driver-restores-desktop","https://community.flutterflow.io/discussions/post/how-to-build-a-browser-based-instagram-story-viewer-with-flutterflow-lldyNB3IG314wPU","https://community.xano.com/ask-the-community/post/api-cache-bug-0GJQtNpHlTb471k"],"htmlRoutes":[{"id":"modern-community-pack","match":{"exactSegments":false},"mode":"modern_community_pack_html"}]},{"id":"msrb-emma","name":"MSRB EMMA Municipal Bond Disclosures","category":"finance","description":"Extracts municipal bond CUSIP, issue disclosure, and market activity HTML pages from emma.msrb.org while strictly rejecting 403/awselb WAF and empty shells.","domains":["emma.msrb.org","emmalabs.msrb.org"],"auth_mode":"html","min_interval_ms":1500,"strict_robots":true,"exampleUrls":["https://emma.msrb.org/Home/Index","https://emma.msrb.org/Security/Details/A1B2C3D4E5"],"htmlRoutes":[{"id":"msrb-emma","match":{"exactSegments":false},"mode":"msrb_emma_html"}]},{"id":"mtb-geometry-brands","name":"MTB Geometry Brands (Yeti, Ibis, Pivot, Transition, Revel)","category":"commerce-social","description":"Extracts mountain bike geometry tables, Nuxt hydration data, suspension travel, and build kits from Yeti, Ibis, Pivot, Transition, and Revel.","domains":["yeticycles.com","www.yeticycles.com","ibiscycles.com","www.ibiscycles.com","pivotcycles.com","www.pivotcycles.com","transitionbikes.com","www.transitionbikes.com","revelbikes.com","www.revelbikes.com"],"auth_mode":"html","min_interval_ms":1000,"exampleUrls":["https://yeticycles.com/en-us/bikes/sb140","https://www.ibiscycles.com/bikes/ripmo","https://www.pivotcycles.com/en/bikes/shuttle-ampd","https://www.transitionbikes.com/Bikes/Sentinel","https://revelbikes.com/products/rascal-sram-eagle-90-kit-2026"],"htmlRoutes":[{"id":"mtb-geometry-brands","match":{"exactSegments":false},"mode":"mtb_geometry_brands_html"}]},{"id":"multifamily-portals","name":"Multifamily Apartment Portals (RentCafe / Entrata / RealPage / Jonah)","category":"commerce-social","description":"Extracts apartment floor plans, square footage, and lease pricing from RentCafe, Entrata, RealPage, and Jonah Systems multifamily portals while honoring Disallow: /*.ashx.","domains":["*.rentcafe.com","*.entrata.com","*.realpage.com","www.canvasatmidlothian.com","canvasatmidlothian.com","www.junction49.com"],"universalEngine":true,"auth_mode":"html","strict_robots":true,"min_interval_ms":1000,"exampleUrls":["https://www.junction49.com/floor-plans/"],"htmlRoutes":[{"id":"multifamily-portals","match":{"exactSegments":false},"mode":"multifamily_portals_html"}]},{"id":"municipal-cms-pack","name":"Municipal CMS Pack (Revize & OpenCities)","category":"public-records","description":"Universal HTML extractor for Revize and Granicus OpenCities (formerly Vision Internet) municipal government portals.","domains":["www.maplevalleywa.gov","www.reno.gov","www.culvercity.gov","www.glendaleaz.gov"],"universalEngine":true,"auth_mode":"html","exampleUrls":["https://www.maplevalleywa.gov/government/city_council_meetings_agendas_and_minutes.php","https://www.culvercity.gov/Home","https://www.glendaleaz.gov/Home"],"htmlRoutes":[{"id":"municipal-cms-pack","match":{"exactSegments":false},"mode":"municipal_cms_html"}]},{"id":"municode","name":"Municode Municipal Codes","category":"public-records","description":"Municode API JSON and municipal code library HTML adapter for city and county ordinances.","domains":["library.municode.com","api.municode.com"],"auth_mode":"pub","exampleUrls":["https://library.municode.com/tx/austin/codes/code_of_ordinances","https://api.municode.com/States"],"routes":[{"match":{"hosts":["api.municode.com"],"pathPrefix":"/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"municode_json"}}],"htmlRoutes":[{"id":"municode","match":{"hosts":["library.municode.com"],"exactSegments":false},"mode":"municode_html"}]},{"id":"musicbrainz-coverart","name":"MusicBrainz & Cover Art Archive","category":"commerce-social","description":"Polite MusicBrainz WS2 JSON and Cover Art Archive release JSON adapter (1 req/s+ pacing, max_concurrent: 1, musicbrainz User-Agent profile) with MusicBrainz HTML fallback and PoW challenge rejection.","domains":["musicbrainz.org","coverartarchive.org"],"auth_mode":"pub","user_agent_profile":"musicbrainz","min_interval_ms":2000,"max_concurrent":1,"exampleUrls":["https://coverartarchive.org/release/76df3287-6cda-33eb-8e9a-044b5e15ffdd","https://musicbrainz.org/ws/2/artist/5b11f4ce-a62d-471e-81fc-a69a8278c7da?fmt=json","https://musicbrainz.org/release/76df3287-6cda-33eb-8e9a-044b5e15ffdd"],"routes":[{"match":{"hosts":["musicbrainz.org"],"pathPrefix":"/ws/2/","exactSegments":false},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","setQueryParams":{"fmt":"json"},"maxBytes":2097152},"extract":{"jsonMode":"musicbrainz_json"}},{"match":{"hosts":["coverartarchive.org"],"anyOf":[{"exactSegments":true,"pathSegments":["release",{"param":"mbid","charset":"alnum_dash","minLen":36,"maxLen":36}]},{"exactSegments":true,"pathSegments":["release-group",{"param":"mbid","charset":"alnum_dash","minLen":36,"maxLen":36}]}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"coverart_archive_json"}}],"htmlRoutes":[{"id":"musicbrainz-coverart","match":{"hosts":["musicbrainz.org"],"exactSegments":false},"mode":"musicbrainz_html"}]},{"id":"nasa-ads","name":"NASA Astrophysics Data System (ADS)","category":"research-health","description":"Official keyed NASA ADS API adapter (NASA_ADS_API_KEY via Authorization: Bearer) for astronomy/physics literature search and bibcodes, with ui.adsabs.harvard.edu HTML fallback and AWS WAF shell guard.","domains":["api.adsabs.harvard.edu","ui.adsabs.harvard.edu"],"auth_mode":"key","min_interval_ms":1000,"exampleUrls":["https://api.adsabs.harvard.edu/v1/search/query?q=bibcode:2017arXiv170603762V&fl=bibcode,title,author","https://ui.adsabs.harvard.edu/abs/2017arXiv170603762V/abstract"],"routes":[{"match":{"hosts":["api.adsabs.harvard.edu"],"pathPrefix":"/v1/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"nasa_ads_json"}},{"match":{"hosts":["ui.adsabs.harvard.edu"],"exactSegments":false,"pathSegments":["abs",{"param":"bibcode","charset":"url_seg","minLen":10,"maxLen":32}]},"twin":{"fetchUrl":"https://api.adsabs.harvard.edu/v1/search/query?q=bibcode:{bibcode}&fl=bibcode,title,author,pub,year,pubdate,abstract,citation_count,doi,identifier","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"nasa_ads_json"}}],"htmlRoutes":[{"id":"nasa-ads","match":{"hosts":["ui.adsabs.harvard.edu"],"exactSegments":false},"mode":"nasa_ads_html"}]},{"id":"nasa-apis","name":"NASA Open APIs & Image Library","category":"research-health","description":"NASA api.nasa.gov (APOD, NeoWs, EPIC with DEMO_KEY fallback or configured NASA_API_KEY) and keyless images-api.nasa.gov search.","domains":["api.nasa.gov","images-api.nasa.gov"],"auth_mode":"key","exampleUrls":["https://api.nasa.gov/neo/rest/v1/feed/today?detailed=false","https://api.nasa.gov/planetary/apod?date=2024-07-04","https://images-api.nasa.gov/search?q=apollo+11&page_size=2"],"routes":[{"match":{"hosts":["api.nasa.gov"],"anyOf":[{"pathPrefix":"/planetary/apod"},{"pathPrefix":"/neo/"},{"pathPrefix":"/EPIC/"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":4194304},"extract":{"jsonMode":"nasa_apis_json"}},{"match":{"hosts":["images-api.nasa.gov"],"anyOf":[{"pathPrefix":"/search"},{"pathPrefix":"/asset/"},{"pathPrefix":"/metadata/"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"pub","maxBytes":4194304},"extract":{"jsonMode":"nasa_apis_json"}}]},{"id":"nasdaq-data-link","name":"Nasdaq Data Link","category":"finance","description":"Extracts Nasdaq Data Link (v3) time-series datasets and datatables JSON feeds via official API key authentication.","domains":["data.nasdaq.com"],"auth_mode":"key","min_interval_ms":1000,"exampleUrls":["https://data.nasdaq.com/api/v3/datasets/FRED/GDP.json?rows=5","https://data.nasdaq.com/api/v3/datatables/ZACKS/FC.json?ticker=AAPL"],"routes":[{"match":{"hosts":["data.nasdaq.com"],"anyOf":[{"pathPrefix":"/api/v3/datasets/"},{"pathPrefix":"/api/v3/datatables/"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"nasdaq_data_link_json"}}]},{"id":"national-archives","name":"U.S. National Archives (NARA Catalog)","category":"public-records","description":"National Archives and Records Administration (NARA) Catalog API v2 adapter (catalog.archives.gov/api/v2) with HTML fallback.","domains":["catalog.archives.gov"],"auth_mode":"key","min_interval_ms":1000,"exampleUrls":["https://catalog.archives.gov/api/v2/records/search?q=constitution","https://catalog.archives.gov/id/1667751"],"routes":[{"match":{"hosts":["catalog.archives.gov"],"pathPrefix":"/api/v2/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"key"},"extract":{"jsonMode":"national_archives_json"}},{"match":{"hosts":["catalog.archives.gov"],"exactSegments":false,"pathSegments":["id",{"param":"naId","charset":"digits","minLen":1,"maxLen":20}]},"twin":{"fetchUrl":"https://catalog.archives.gov/api/v2/records/search?naId={naId}","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"key"},"extract":{"jsonMode":"national_archives_json"}}],"htmlRoutes":[{"id":"national-archives","match":{"hosts":["catalog.archives.gov"],"exactSegments":false},"mode":"national_archives_html"}]},{"id":"ncaa-espn","name":"NCAA & ESPN","category":"commerce-social","description":"Extracts NCAA and ESPN sports articles, scoreboards, standings, and public sports API JSON plus HTML JSON-LD and __espnfitt__ / turner_metadata hydration.","domains":["ncaa.com","www.ncaa.com","espn.com","www.espn.com","site.api.espn.com","sports.core.api.espn.com","site.web.api.espn.com","data.ncaa.com","sdataprod.ncaa.com"],"auth_mode":"pub","strict_robots":true,"exampleUrls":["https://www.espn.com/mlb/story/_/id/50328768/free-agency-tracker-offseason-trades-moves-2026-2027","https://www.espn.com/nfl/scoreboard","https://www.ncaa.com/news/football/article/2026-11-25/4-games-storylines-rivalry-week-could-impact-college-football-playoff-bracket","https://sports.core.api.espn.com/v2/sports/football/leagues/nfl"],"routes":[{"match":{"hosts":["sports.core.api.espn.com"],"pathPrefix":"/v2/sports/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"ncaa_espn_json"}},{"match":{"hosts":["site.web.api.espn.com"],"pathPrefix":"/apis/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"ncaa_espn_json"}},{"match":{"hosts":["site.api.espn.com"],"pathPrefix":"/apis/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"ncaa_espn_json"}},{"match":{"hosts":["data.ncaa.com"],"pathPrefix":"/cas/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"ncaa_espn_json"}}],"htmlRoutes":[{"id":"ncaa-espn","match":{"hosts":["espn.com","www.espn.com","ncaa.com","www.ncaa.com"]},"mode":"ncaa_espn_html"}]},{"id":"nces-ipeds","name":"NCES IPEDS & Urban Institute Education Data","category":"public-records","description":"NCES IPEDS and Digest of Education Statistics HTML adapter with Urban Institute Education Data API JSON support (strict robots).","domains":["nces.ed.gov","educationdata.urban.org"],"auth_mode":"pub","strict_robots":true,"min_interval_ms":1000,"exampleUrls":["https://nces.ed.gov/ipeds/use-the-data","https://nces.ed.gov/programs/digest/current_tables.asp"],"routes":[{"match":{"hosts":["educationdata.urban.org"],"exactSegments":false,"pathPrefix":"/api/v1/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"pub"},"extract":{"jsonMode":"nces_ipeds_json"}}],"htmlRoutes":[{"id":"nces-ipeds","match":{"hosts":["nces.ed.gov","educationdata.urban.org"],"exactSegments":false},"mode":"nces_ipeds_html"}]},{"id":"ncua-credit-unions","name":"NCUA Credit Union Lookup","category":"finance","description":"Extracts NCUA credit union details and call report pages with strict robots.txt enforcement (honoring mapping.ncua.gov Disallow /) and ncua.gov HTML fallback.","domains":["mapping.ncua.gov","ncua.gov","www.ncua.gov"],"auth_mode":"pub","strict_robots":true,"exampleUrls":["https://ncua.gov/analysis/credit-union-corporate-call-report-data","https://mapping.ncua.gov/CreditUnionDetails/60006"],"routes":[{"match":{"hosts":["mapping.ncua.gov"],"exactSegments":false,"pathSegments":["CreditUnionDetails",{"param":"charter","charset":"digits","minLen":1,"maxLen":12}]},"twin":{"fetchUrl":"https://mapping.ncua.gov/api/CreditUnionDetails/{charter}","kind":"json","accept":"application/json","auth_mode":"pub","maxBytes":2097152},"extract":{"jsonMode":"ncua_json"}},{"match":{"hosts":["mapping.ncua.gov"],"pathPrefix":"/api/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"pub","maxBytes":2097152},"extract":{"jsonMode":"ncua_json"}}],"htmlRoutes":[{"id":"ncua-credit-unions","match":{"hosts":["ncua.gov","www.ncua.gov","mapping.ncua.gov"],"exactSegments":false},"mode":"ncua_html"}]},{"id":"neogov","name":"NeoGov GovernmentJobs & SchoolJobs","category":"jobs","description":"Extracts structured public-sector job feeds and postings from NeoGov GovernmentJobs and SchoolJobs RSS/JSON/HTML while strictly honoring robots.txt.","domains":["governmentjobs.com","www.governmentjobs.com","*.governmentjobs.com","schooljobs.com","www.schooljobs.com","*.schooljobs.com"],"auth_mode":"pub","strict_robots":true,"exampleUrls":["https://www.governmentjobs.com/careers/lacounty/rss","https://www.governmentjobs.com/careers/lacounty","https://www.schooljobs.com/careers/lausd"],"routes":[{"match":{"anyOf":[{"hosts":["governmentjobs.com","www.governmentjobs.com","*.governmentjobs.com","schooljobs.com","www.schooljobs.com","*.schooljobs.com"],"pathSuffix":"/rss","exactSegments":false},{"hosts":["governmentjobs.com","www.governmentjobs.com","*.governmentjobs.com","schooljobs.com","www.schooljobs.com","*.schooljobs.com"],"pathSuffix":".rss","exactSegments":false}]},"twin":{"id":"neogov-rss","fetchUrl":"{requestUrl}","kind":"text","accept":"application/rss+xml"},"extract":{"xml":{"mode":"items_table","requireAnyTags":["rss","channel"],"itemTag":"item","titleTemplate":"NeoGov Public Sector Jobs ({itemCount})","emptyText":"No open positions currently listed.","limit":50,"requireItemVar":"jTitle","collectLinkVar":"jLink","emitTotals":true,"itemVars":{"jTitle":{"tags":["title"]},"jLink":{"tags":["link"]},"dept":{"tags":["category","department"],"default":"-"},"loc":{"tags":["location"],"default":"-"},"pubDate":{"tags":["pubDate"],"sliceMax":16,"default":"-"}},"recordFields":{"title":"{jTitle}","url":"{jLink}","department":"{dept}","location":"{loc}","postedAt":"{pubDate}","source":"neogov"},"columns":[{"header":"Role","template":"[{jTitle}]({jLink})"},{"header":"Department","template":"{dept}"},{"header":"Location","template":"{loc}"},{"header":"Published","template":"{pubDate}"}]}}},{"match":{"anyOf":[{"hosts":["governmentjobs.com","www.governmentjobs.com","*.governmentjobs.com","schooljobs.com","www.schooljobs.com","*.schooljobs.com"],"pathPrefix":"/api/","exactSegments":false},{"hosts":["governmentjobs.com","www.governmentjobs.com","*.governmentjobs.com","schooljobs.com","www.schooljobs.com","*.schooljobs.com"],"pathSuffix":".json","exactSegments":false}]},"twin":{"id":"neogov-json","fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"neogov_json"}}],"htmlRoutes":[{"id":"neogov","mode":"neogov_html","match":{"hosts":["governmentjobs.com","www.governmentjobs.com","*.governmentjobs.com","schooljobs.com","www.schooljobs.com","*.schooljobs.com"],"exactSegments":false}}]},{"id":"newsletter-archives","name":"Newsletter Archives (Beehiiv / Ghost / Buttondown / Kit)","category":"commerce-social","description":"Extracts Ghost Content API posts, scoped Beehiiv/Ghost/Buttondown RSS feeds, and newsletter archive HTML pages.","domains":["ghost.org","buttondown.com","rss.beehiiv.com","aibrews.beehiiv.com"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://ghost.org/changelog/rss/","https://ghost.org/changelog/","https://buttondown.com/hillelwayne/rss","https://aibrews.beehiiv.com/"],"routes":[{"match":{"pathPrefix":"/ghost/api/content/posts","exactSegments":false},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"newsletter_ghost_json"}},{"match":{"hosts":["rss.beehiiv.com"],"exactSegments":false},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"application/rss+xml"},"extract":{"textMode":"newsletter_rss_xml"}},{"match":{"hosts":["buttondown.com"],"exactSegments":true,"pathSegments":[{"param":"pub","charset":"slug","minLen":1,"maxLen":80},"rss"]},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"application/rss+xml"},"extract":{"textMode":"newsletter_rss_xml"}},{"match":{"hosts":["ghost.org"],"pathEquals":["/changelog/rss","/changelog/rss/"]},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"application/rss+xml"},"extract":{"textMode":"newsletter_rss_xml"}},{"match":{"hostSubdomain":{"suffix":".beehiiv.com","param":"pub"},"pathEquals":["/feed","/rss"]},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"application/rss+xml"},"extract":{"textMode":"newsletter_rss_xml"}},{"match":{"hostSubdomain":{"suffix":".ghost.io","param":"pub"},"pathEquals":["/rss","/rss/","/feed","/feed/"]},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"application/rss+xml"},"extract":{"textMode":"newsletter_rss_xml"}}],"htmlRoutes":[{"id":"newsletter-archives","match":{"exactSegments":false},"mode":"newsletter_archives_html"}]},{"id":"newswire-pack","name":"Newswire Pack (PR Newswire / Business Wire / GlobeNewswire)","category":"commerce-social","description":"Extracts PR Newswire, Business Wire, and GlobeNewswire RSS feeds and NewsArticle HTML press releases.","domains":["www.prnewswire.com","prnewswire.com","www.businesswire.com","businesswire.com","www.globenewswire.com","globenewswire.com"],"auth_mode":"pub","exampleUrls":["https://www.prnewswire.com/rss/news-releases-list.rss","https://www.prnewswire.com/news-releases/binance-secures-in-principle-approval-in-gelephu-mindfulness-city-plans-asia-hub-in-bhutan-302951995.html"],"routes":[{"match":{"anyOf":[{"pathPrefix":"/rss/"},{"pathPrefix":"/RssFeed/"},{"pathPrefix":"/feed/"},{"pathSuffix":".rss"}],"exactSegments":false},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"application/rss+xml"},"extract":{"textMode":"newswire_rss_xml"}}],"htmlRoutes":[{"id":"newswire-pack","match":{"exactSegments":false},"mode":"newswire_html"}]},{"id":"nfpa","name":"NFPA Standards & Codes (www.nfpa.org)","category":"public-records","description":"Unpacks Sitecore JSS __NEXT_DATA__ storefront-main placeholders (PageTitle, ContentBlock, SplitScreenCalloutComponent, Accordion, TwoColumnVideo) on www.nfpa.org without headless browser rendering, never touching link.nfpa.org or robots-disallowed /en/ and /-/media/.","domains":["www.nfpa.org"],"exampleUrls":["https://www.nfpa.org/codes-and-standards/nfpa-70-standard-development/70","https://www.nfpa.org/for-professionals/codes-and-standards/list-of-codes-and-standards/free-access"],"htmlRoutes":[{"id":"nfpa","mode":"sitecore_jss_html","match":{"exactSegments":false,"reservedFirstSegment":["-","ar","en","data","standard_items"]}}]},{"id":"nhl-api","name":"NHL Web API","category":"commerce-social","description":"Extracts public NHL standings, schedule, club stats, and gamecenter landing JSON from api-web.nhle.com with nhl.com HTML/JSON-LD fallback.","domains":["api-web.nhle.com","nhl.com","www.nhl.com"],"auth_mode":"pub","exampleUrls":["https://api-web.nhle.com/v1/standings/now","https://api-web.nhle.com/v1/schedule/now","https://api-web.nhle.com/v1/club-stats/TOR/now","https://api-web.nhle.com/v1/gamecenter/2024020001/landing"],"routes":[{"match":{"hosts":["api-web.nhle.com"],"anyOf":[{"pathPrefix":"/v1/standings"},{"pathPrefix":"/v1/schedule"},{"pathPrefix":"/v1/club-stats/"},{"pathPrefix":"/v1/gamecenter/"},{"pathPrefix":"/v1/player/"},{"pathPrefix":"/v1/roster/"}],"exactSegments":false},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"nhl_api_json"}}],"htmlRoutes":[{"id":"nhl-api","mode":"nhl_api_html","match":{"hosts":["nhl.com","www.nhl.com"],"exactSegments":false}}]},{"id":"nhtsa-vpic-recalls","name":"NHTSA vPIC & Safety Recalls API","category":"public-records","description":"Formats keyless vpic.nhtsa.dot.gov VIN decode and api.nhtsa.gov vehicle recalls & complaints JSON endpoints into structured Markdown tables (respecting HTTP 403/robots.txt without bypass).","domains":["vpic.nhtsa.dot.gov","api.nhtsa.gov"],"exampleUrls":["https://vpic.nhtsa.dot.gov/api/vehicles/decodevinvalues/1HGCM82633A004352?format=json","https://api.nhtsa.gov/recalls/recallsByVehicle?make=honda&model=accord&modelYear=2020"],"routes":[{"match":{"hosts":["vpic.nhtsa.dot.gov"],"exactSegments":true,"pathSegments":["api","vehicles",{"param":"endpoint","allowValues":["decodevinvalues","decodevinvaluesextended"]},{"param":"vin","charset":"alnum","minLen":3,"maxLen":32}]},"twin":{"fetchUrl":"https://vpic.nhtsa.dot.gov/api/vehicles/{endpoint}/{vin}?format=json","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"requireAnyFields":["Results","Message"],"vars":{"vinOut":{"paths":["Results.0.VIN"],"fallbackTemplate":"{vin}"},"make":{"paths":["Results.0.Make"],"trim":true},"model":{"paths":["Results.0.Model"],"trim":true},"modelYear":{"paths":["Results.0.ModelYear"],"trim":true},"vehicleType":{"paths":["Results.0.VehicleType"],"trim":true},"bodyClass":{"paths":["Results.0.BodyClass"],"trim":true},"plantCountry":{"paths":["Results.0.PlantCountry"],"trim":true},"engineCylinders":{"paths":["Results.0.EngineCylinders"],"trim":true},"displacementL":{"paths":["Results.0.DisplacementL"],"trim":true},"fuelType":{"paths":["Results.0.FuelTypePrimary"],"trim":true},"errorCode":{"paths":["Results.0.ErrorCode"],"trim":true},"errorText":{"paths":["Results.0.ErrorText"],"trim":true},"message":{"paths":["Message"],"trim":true}},"titleTemplate":"{modelYear} {make} {model} — VIN {vinOut}","titleWhenVar":"make","titleFallbackTemplate":"NHTSA vPIC VIN Decode ({vinOut})","bullets":[{"label":"VIN","template":"`{vinOut}`"},{"label":"Make","template":"{make}","whenVar":"make"},{"label":"Model","template":"{model}","whenVar":"model"},{"label":"Model Year","template":"{modelYear}","whenVar":"modelYear"},{"label":"Vehicle Type","template":"{vehicleType}","whenVar":"vehicleType"},{"label":"Body Class","template":"{bodyClass}","whenVar":"bodyClass"},{"label":"Plant Country","template":"{plantCountry}","whenVar":"plantCountry"},{"label":"Engine Cylinders","template":"{engineCylinders}","whenVar":"engineCylinders"},{"label":"Displacement (L)","template":"{displacementL}","whenVar":"displacementL"},{"label":"Fuel Type","template":"{fuelType}","whenVar":"fuelType"},{"label":"Error Code","template":"`{errorCode}`","whenVar":"errorCode"},{"label":"Error Text","template":"{errorText}","whenVar":"errorText"},{"label":"Message","template":"{message}","whenVar":"message"}]}},{"match":{"hosts":["api.nhtsa.gov"],"pathEquals":["/recalls/recallsByVehicle","/recalls/recallsByVehicle/"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"requireAnyFields":["results","Results"],"vars":{"count":{"paths":["Count","count"],"format":"int_comma","default":"0"},"message":{"paths":["Message","message"],"trim":true}},"titleTemplate":"NHTSA Vehicle Recalls ({count} found)","introVar":"message","sections":[{"heading":"Recalls","arrayPath":"results","limit":50,"emptyText":"No recalls found.","columns":[{"header":"Campaign","paths":["NHTSACampaignNumber"],"code":true},{"header":"Date","paths":["ReportReceivedDate"]},{"header":"Component","paths":["Component"]},{"header":"Summary","paths":["Summary"],"sliceMax":240},{"header":"Consequence","paths":["Consequence"],"sliceMax":240},{"header":"Remedy","paths":["Remedy"],"sliceMax":240}]}]}},{"match":{"hosts":["api.nhtsa.gov"],"pathEquals":["/complaints/complaintsByVehicle","/complaints/complaintsByVehicle/"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"requireAnyFields":["results","Results"],"vars":{"count":{"paths":["count","Count"],"format":"int_comma","default":"0"},"message":{"paths":["message","Message"],"trim":true}},"titleTemplate":"NHTSA Vehicle Complaints ({count} found)","introVar":"message","sections":[{"heading":"Complaints","arrayPath":"results","limit":50,"emptyText":"No complaints found.","columns":[{"header":"ODI Number","paths":["odiNumber"],"code":true},{"header":"Date","paths":["dateOfIncident"]},{"header":"Components","paths":["components"]},{"header":"Summary","paths":["summary"],"sliceMax":240},{"header":"Crash","paths":["crash"]},{"header":"Fire","paths":["fire"]}]}]}}]},{"id":"nih-reporter","name":"NIH RePORTER Funded Projects","category":"research-health","description":"Upgrades reporter.nih.gov/project-details/ URLs to api.reporter.nih.gov/v2/projects/search POST JSON with strict CSR SPA shell rejection on HTML fallback.","domains":["api.reporter.nih.gov","reporter.nih.gov"],"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://reporter.nih.gov/project-details/10476325","https://api.reporter.nih.gov/v2/projects/search"],"routes":[{"match":{"hosts":["api.reporter.nih.gov"],"pathPrefix":"/v2/projects/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","method":"POST","contentType":"application/json","requestBody":"{\"criteria\":{\"project_nums\":[\"5R01CA242003-04\"]},\"limit\":5}","maxBytes":2097152},"extract":{"jsonMode":"nih_reporter_json"}},{"match":{"hosts":["reporter.nih.gov"],"exactSegments":false,"pathSegments":["project-details",{"param":"applId","charset":"digits","minLen":4,"maxLen":16}]},"twin":{"fetchUrl":"https://api.reporter.nih.gov/v2/projects/search","kind":"json","accept":"application/json","method":"POST","contentType":"application/json","requestBody":"{\"criteria\":{\"appl_ids\":[{applId}]},\"limit\":1}","maxBytes":2097152},"extract":{"jsonMode":"nih_reporter_json"}}],"htmlRoutes":[{"id":"nih-reporter","match":{"hosts":["reporter.nih.gov"],"exactSegments":false},"mode":"nih_reporter_html"}]},{"id":"nist-nvd","name":"NIST National Vulnerability Database (NVD)","category":"developer","description":"Upgrades nvd.nist.gov CVE pages to the keyless NVD REST v2 JSON API with CVSS scores, CWEs, and vendor advisories.","domains":["nvd.nist.gov","www.nvd.nist.gov"],"exampleUrls":["https://nvd.nist.gov/vuln/detail/CVE-2024-3094"],"match":{"exactSegments":false,"pathSegments":["vuln","detail",{"param":"cveId","charset":"cve_id","transform":"upper"}]},"twin":{"fetchUrl":"https://services.nvd.nist.gov/rest/json/cves/2.0?cveId={cveId}","kind":"json","accept":"application/json"},"extract":{"rootPath":"vulnerabilities.0.cve","requireFields":["id"],"vars":{"id":{"paths":["id"]},"desc":{"findInArrayLang":{"arrayPath":"descriptions","langField":"lang","langValue":"en","valueField":"value"},"trim":true},"descShort":{"template":"{desc}","whenVars":["desc"],"sliceMax":260},"baseScore":{"paths":["metrics.cvssMetricV40.0.cvssData.baseScore","metrics.cvssMetricV31.0.cvssData.baseScore","metrics.cvssMetricV30.0.cvssData.baseScore"]},"severity":{"paths":["metrics.cvssMetricV40.0.cvssData.baseSeverity","metrics.cvssMetricV40.0.baseSeverity","metrics.cvssMetricV31.0.cvssData.baseSeverity","metrics.cvssMetricV31.0.baseSeverity","metrics.cvssMetricV30.0.cvssData.baseSeverity","metrics.cvssMetricV30.0.baseSeverity"]},"vector":{"paths":["metrics.cvssMetricV40.0.cvssData.vectorString","metrics.cvssMetricV31.0.cvssData.vectorString","metrics.cvssMetricV30.0.cvssData.vectorString"]},"titleWithScore":{"template":"{id} ({severity} {baseScore})","whenVars":["severity","baseScore"]},"titleSevOnly":{"template":"{id} ({severity})","whenVars":["severity"]},"titleFull":{"template":"{titleWithScore}","whenVars":["titleWithScore"],"fallbackVar":"titleSevOnly"},"cvssScoreOnly":{"template":"**{baseScore}**","whenVars":["baseScore"]},"cvssScoreVec":{"template":"**{baseScore}** — `{vector}`","whenVars":["baseScore","vector"],"fallbackVar":"cvssScoreOnly"},"cvssScoreSev":{"template":"**{baseScore}** ({severity})","whenVars":["baseScore","severity"],"fallbackVar":"cvssScoreVec"},"cvssDisplay":{"template":"**{baseScore}** ({severity}) — `{vector}`","whenVars":["baseScore","severity","vector"],"fallbackVar":"cvssScoreSev"},"cwes":{"nestedSubValues":{"arrayPath":"weaknesses","subArrayField":"description","valueField":"value","excludeValues":["NVD-CWE-noinfo"],"join":", "}},"published":{"paths":["published"]},"publishedDate":{"paths":["published"],"sliceMax":10},"vulnStatus":{"paths":["vulnStatus"]},"cisaExploit":{"paths":["cisaExploitAdd"]}},"titleTemplate":"{titleFull}","titleWhenVar":"severity","titleFallbackTemplate":"{id}","descriptionVar":"descShort","publishedTimeVar":"published","bullets":[{"label":"CVSS Score","template":"{cvssDisplay}","whenVar":"cvssDisplay"},{"label":"Status","template":"{vulnStatus}","whenVar":"vulnStatus"},{"label":"Published","template":"{publishedDate}","whenVar":"publishedDate"},{"label":"Weaknesses (CWE)","template":"{cwes}","whenVar":"cwes"},{"label":"CISA KEV (Known Exploited)","template":"Added {cisaExploit}","whenVar":"cisaExploit"}],"sections":[{"heading":"Summary","textVar":"desc"},{"heading":"References & Advisories","arrayPath":"references","limit":15,"requireItemVar":"refUrl","collectLinkVars":["refUrl"],"itemVars":{"refUrl":{"paths":["url"],"requireHttps":true},"refTags":{"paths":["tags"],"join":", "}},"columns":[{"header":"URL","template":"{refUrl}"},{"header":"Tags","template":"{refTags}"}]}]}},{"id":"nlrb-cases","name":"National Labor Relations Board Cases & Dockets","category":"public-records","description":"Extracts NLRB unfair labor practice and representation case metadata, docket activity rows, and decision links from nlrb.gov.","domains":["www.nlrb.gov","nlrb.gov"],"auth_mode":"pub","exampleUrls":["https://www.nlrb.gov/case/13-CA-394913","https://www.nlrb.gov/case/10-CA-400063"],"htmlRoutes":[{"id":"nlrb-cases","match":{"exactSegments":false},"mode":"nlrb_cases_html"}]},{"id":"noaa-ncei-cdo","name":"NOAA NCEI Climate Data Online (CDO)","category":"research-health","description":"NOAA National Centers for Environmental Information CDO API v2 (token header) on www.ncei.noaa.gov with HTML fallback.","domains":["www.ncei.noaa.gov","ncei.noaa.gov","www.ncdc.noaa.gov"],"auth_mode":"key","exampleUrls":["https://www.ncei.noaa.gov/cdo-web/api/v2/datasets?limit=2","https://www.ncei.noaa.gov/cdo-web/"],"routes":[{"match":{"hosts":["www.ncei.noaa.gov","ncei.noaa.gov"],"pathPrefix":"/cdo-web/api/v2/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"noaa_ncei_cdo_json"}}],"htmlRoutes":[{"id":"noaa-ncei-cdo","match":{"hosts":["www.ncei.noaa.gov","ncei.noaa.gov","www.ncdc.noaa.gov"],"exactSegments":false},"mode":"noaa_ncei_html"}]},{"id":"noaa-tides-currents","name":"NOAA Tides & Currents (CO-OPS)","category":"research-health","description":"NOAA Center for Operational Oceanographic Products and Services (CO-OPS) DataGetter and station metadata JSON APIs with stationhome HTML fallback.","domains":["tidesandcurrents.noaa.gov","api.tidesandcurrents.noaa.gov"],"auth_mode":"pub","exampleUrls":["https://api.tidesandcurrents.noaa.gov/api/prod/datagetter?date=latest&station=8518750&product=water_level&datum=MLLW&time_zone=gmt&units=english&format=json","https://api.tidesandcurrents.noaa.gov/mdapi/prod/webapi/stations/8518750.json","https://tidesandcurrents.noaa.gov/stationhome.html?id=8518750"],"routes":[{"match":{"hosts":["api.tidesandcurrents.noaa.gov"],"pathEquals":["/api/prod/datagetter"]},"twin":{"fetchUrl":"{requestUrl}","setQueryParams":{"format":"json"},"kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"noaa_tides_json"}},{"match":{"hosts":["api.tidesandcurrents.noaa.gov"],"pathPrefix":"/mdapi/prod/webapi/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"noaa_tides_json"}},{"match":{"hosts":["tidesandcurrents.noaa.gov"],"pathEquals":["/stationhome.html"],"queryParams":[{"name":"id","param":"stationId","charset":"digits","minLen":5,"maxLen":12}]},"twin":{"fetchUrl":"https://api.tidesandcurrents.noaa.gov/mdapi/prod/webapi/stations/{stationId}.json","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"noaa_tides_json"}}],"htmlRoutes":[{"id":"noaa-tides-currents","match":{"hosts":["tidesandcurrents.noaa.gov"],"exactSegments":false},"mode":"noaa_tides_html"}]},{"id":"nostr-relays","name":"Nostr Relays (NIP-11 / NIP-01) & njump Gateway","category":"commerce-social","description":"Extracts Nostr relay NIP-11 metadata and bounded read-only NIP-01 event envelopes on relay roots, plus njump.me public gateway HTML notes/profiles.","domains":["relay.damus.io","nos.lol","purplepag.es","relay.primal.net","njump.me"],"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://nos.lol/","https://purplepag.es/","https://relay.damus.io/","https://njump.me/nevent1qqsyt343xphyh8txwnqyh7jgynl345f35uh5mqnmuedm7uaszclkh7svenvty"],"routes":[{"match":{"hosts":["relay.damus.io","nos.lol","purplepag.es","relay.primal.net"],"maxSegments":0},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/nostr+json","maxBytes":1048576},"extract":{"jsonMode":"nostr_relay_json"}}],"htmlRoutes":[{"id":"nostr-relays","match":{"hosts":["njump.me"],"exactSegments":false},"mode":"nostr_njump_html"}]},{"id":"notion-public-site","name":"Notion Public Sites","category":"developer","description":"Extracts public Notion site pages (*.notion.site and www.notion.so) via POST /api/v3/loadCachedPageChunk with fail-closed SSR HTML fallback.","domains":["www.notion.so"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://matt-mike.notion.site/Matt-Mike-Data-Analyst-Portfolio-201029b2366680969986e484d1aa4373"],"routes":[{"match":{"hostSubdomain":{"suffix":".notion.site","param":"siteSub"},"scanSegment":{"scanLast":true,"param":"pageUuid","charset":"notion_page_id","minLen":32,"maxLen":200,"transform":"notion_uuid"}},"twin":{"fetchUrl":"https://{host}/api/v3/loadCachedPageChunk","kind":"json","accept":"application/json","method":"POST","contentType":"application/json","requestBody":"{\"page\":{\"id\":\"{pageUuid}\"},\"limit\":50,\"cursor\":{\"stack\":[]},\"chunkNumber\":0,\"verticalColumns\":false}"},"extract":{"jsonMode":"notion_public_site"}},{"match":{"hosts":["www.notion.so","notion.so"],"scanSegment":{"scanLast":true,"param":"pageUuid","charset":"notion_page_id","minLen":32,"maxLen":200,"transform":"notion_uuid"}},"twin":{"fetchUrl":"https://{host}/api/v3/loadCachedPageChunk","kind":"json","accept":"application/json","method":"POST","contentType":"application/json","requestBody":"{\"page\":{\"id\":\"{pageUuid}\"},\"limit\":50,\"cursor\":{\"stack\":[]},\"chunkNumber\":0,\"verticalColumns\":false}"},"extract":{"jsonMode":"notion_public_site"}}],"htmlRoutes":[{"id":"notion-public-site","match":{"exactSegments":false},"mode":"notion_public_site_html"}]},{"id":"npm-registry","name":"npm Package Registry","category":"developer","description":"Upgrades npmjs.com package pages to registry.npmjs.org JSON metadata, TypeScript declarations, dependency list, and README.","domains":["npmjs.com","www.npmjs.com"],"exampleUrls":["https://www.npmjs.com/package/@cfworker/json-schema"],"routes":[{"match":{"anyOf":[{"pathPrefix":"/package/@","exactSegments":false,"pathSegments":["package",{"param":"scopeNoAt","stripPrefix":"@","charset":"npm_pkg"},{"param":"pkg","charset":"npm_pkg"},"v",{"param":"requestedVer","charset":"url_seg"}]},{"pathPrefix":"/package/@","exactSegments":false,"pathSegments":["package",{"param":"scopeNoAt","stripPrefix":"@","charset":"npm_pkg"},{"param":"pkg","charset":"npm_pkg"}]}]},"twin":{"fetchUrl":"https://registry.npmjs.org/@{scopeNoAt}%2F{pkg}","kind":"json","accept":"application/json"},"extract":{"requireFields":["name"],"vars":{"name":{"paths":["name"]},"latestTag":{"paths":["dist-tags.latest"]},"ver":{"template":"{requestedVer}","whenVars":["requestedVer"],"fallbackVar":"latestTag"},"verDesc":{"dynamicKeyPath":{"base":"versions","keyVar":"ver","subPath":"description"},"trim":true},"rootDesc":{"paths":["description"],"trim":true},"desc":{"template":"{verDesc}","whenVars":["verDesc"],"fallbackVar":"rootDesc"},"verLicense":{"dynamicKeyPath":{"base":"versions","keyVar":"ver","subPath":"license"}},"rootLicense":{"paths":["license"]},"license":{"template":"{verLicense}","whenVars":["verLicense"],"fallbackVar":"rootLicense"},"verHomepage":{"dynamicKeyPath":{"base":"versions","keyVar":"ver","subPath":"homepage"}},"rootHomepage":{"paths":["homepage"]},"homepage":{"template":"{verHomepage}","whenVars":["verHomepage"],"fallbackVar":"rootHomepage"},"verRepoUrl":{"dynamicKeyPath":{"base":"versions","keyVar":"ver","subPath":"repository.url"}},"verRepoStr":{"dynamicKeyPath":{"base":"versions","keyVar":"ver","subPath":"repository"}},"verRepo":{"template":"{verRepoUrl}","whenVars":["verRepoUrl"],"fallbackVar":"verRepoStr"},"rootRepo":{"paths":["repository.url","repository"]},"repoClean":{"template":"{verRepo}","whenVars":["verRepo"],"fallbackVar":"rootRepo","stripPrefix":"git+","stripSuffix":".git","requireHttpPrefix":true},"verTypes":{"dynamicKeyPath":{"base":"versions","keyVar":"ver","subPath":"types"}},"verTypings":{"dynamicKeyPath":{"base":"versions","keyVar":"ver","subPath":"typings"}},"hasTypes":{"template":"Bundled declarations included","whenAnyVars":["verTypes","verTypings"]},"depsDisplay":{"dynamicKeyPath":{"base":"versions","keyVar":"ver","subPath":"dependencies"},"format":"object_keys","limit":10,"join":", ","default":"0 (zero dependencies)"},"readme":{"paths":["readme"],"excludeEquals":"ERROR: No README data found!","format":"strip_leading_h1","trim":true}},"titleTemplate":"{name}@{ver}","titleWhenVar":"ver","titleFallbackTemplate":"{name}","descriptionVar":"desc","introVar":"desc","bullets":[{"label":"Install","template":"`npm install {name}`"},{"label":"Latest Version","template":"`{ver}`","whenVar":"ver"},{"label":"License","template":"{license}","whenVar":"license"},{"label":"TypeScript","template":"{hasTypes}","whenVar":"hasTypes"},{"label":"Runtime Dependencies","template":"{depsDisplay}","whenVar":"depsDisplay"},{"label":"Homepage","template":"{homepage}","whenVar":"homepage"},{"label":"Repository","template":"{repoClean}","whenVar":"repoClean"}],"bodyVar":"readme"}},{"match":{"anyOf":[{"exactSegments":false,"pathSegments":["package",{"param":"pkg","charset":"npm_pkg"},"v",{"param":"requestedVer","charset":"url_seg"}]},{"exactSegments":false,"pathSegments":["package",{"param":"pkg","charset":"npm_pkg"}]}]},"twin":{"fetchUrl":"https://registry.npmjs.org/{pkg}","kind":"json","accept":"application/json"},"extract":{"requireFields":["name"],"vars":{"name":{"paths":["name"]},"latestTag":{"paths":["dist-tags.latest"]},"ver":{"template":"{requestedVer}","whenVars":["requestedVer"],"fallbackVar":"latestTag"},"verDesc":{"dynamicKeyPath":{"base":"versions","keyVar":"ver","subPath":"description"},"trim":true},"rootDesc":{"paths":["description"],"trim":true},"desc":{"template":"{verDesc}","whenVars":["verDesc"],"fallbackVar":"rootDesc"},"verLicense":{"dynamicKeyPath":{"base":"versions","keyVar":"ver","subPath":"license"}},"rootLicense":{"paths":["license"]},"license":{"template":"{verLicense}","whenVars":["verLicense"],"fallbackVar":"rootLicense"},"verHomepage":{"dynamicKeyPath":{"base":"versions","keyVar":"ver","subPath":"homepage"}},"rootHomepage":{"paths":["homepage"]},"homepage":{"template":"{verHomepage}","whenVars":["verHomepage"],"fallbackVar":"rootHomepage"},"verRepoUrl":{"dynamicKeyPath":{"base":"versions","keyVar":"ver","subPath":"repository.url"}},"verRepoStr":{"dynamicKeyPath":{"base":"versions","keyVar":"ver","subPath":"repository"}},"verRepo":{"template":"{verRepoUrl}","whenVars":["verRepoUrl"],"fallbackVar":"verRepoStr"},"rootRepo":{"paths":["repository.url","repository"]},"repoClean":{"template":"{verRepo}","whenVars":["verRepo"],"fallbackVar":"rootRepo","stripPrefix":"git+","stripSuffix":".git","requireHttpPrefix":true},"verTypes":{"dynamicKeyPath":{"base":"versions","keyVar":"ver","subPath":"types"}},"verTypings":{"dynamicKeyPath":{"base":"versions","keyVar":"ver","subPath":"typings"}},"hasTypes":{"template":"Bundled declarations included","whenAnyVars":["verTypes","verTypings"]},"depsDisplay":{"dynamicKeyPath":{"base":"versions","keyVar":"ver","subPath":"dependencies"},"format":"object_keys","limit":10,"join":", ","default":"0 (zero dependencies)"},"readme":{"paths":["readme"],"excludeEquals":"ERROR: No README data found!","format":"strip_leading_h1","trim":true}},"titleTemplate":"{name}@{ver}","titleWhenVar":"ver","titleFallbackTemplate":"{name}","descriptionVar":"desc","introVar":"desc","bullets":[{"label":"Install","template":"`npm install {name}`"},{"label":"Latest Version","template":"`{ver}`","whenVar":"ver"},{"label":"License","template":"{license}","whenVar":"license"},{"label":"TypeScript","template":"{hasTypes}","whenVar":"hasTypes"},{"label":"Runtime Dependencies","template":"{depsDisplay}","whenVar":"depsDisplay"},{"label":"Homepage","template":"{homepage}","whenVar":"homepage"},{"label":"Repository","template":"{repoClean}","whenVar":"repoClean"}],"bodyVar":"readme"}}]},{"id":"nppes-npi","name":"NPPES NPI Registry","category":"research-health","description":"CMS National Plan and Provider Enumeration System (NPPES) NPI Registry v2.1 JSON API adapter with Angular SPA shell rejection.","domains":["npiregistry.cms.hhs.gov"],"auth_mode":"pub","exampleUrls":["https://npiregistry.cms.hhs.gov/api/?version=2.1&number=1003000126","https://npiregistry.cms.hhs.gov/provider-view/1003000126"],"routes":[{"match":{"pathEquals":["/api","/api/"]},"twin":{"fetchUrl":"{requestUrl}","defaultQueryParams":{"version":"2.1"},"kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"nppes_npi_json"}},{"match":{"exactSegments":true,"pathSegments":["provider-view",{"param":"npi","charset":"digits","minLen":10,"maxLen":10}]},"twin":{"fetchUrl":"https://npiregistry.cms.hhs.gov/api/?version=2.1&number={npi}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"nppes_npi_json"}}],"htmlRoutes":[{"id":"nppes-npi","match":{"pathPrefix":"/provider-view/","exactSegments":false},"mode":"nppes_npi_html"}]},{"id":"npr-pbs","name":"NPR & PBS NewsHour","category":"commerce-social","description":"Extracts NPR/PBS RSS XML feeds, text.npr.org stories, and NPR/PBS article HTML.","domains":["www.npr.org","npr.org","text.npr.org","feeds.npr.org","www.pbs.org","pbs.org"],"auth_mode":"html","exampleUrls":["https://feeds.npr.org/1001/rss.xml","https://www.pbs.org/newshour/feeds/rss/headlines","https://www.pbs.org/newshour/nation"],"routes":[{"match":{"hosts":["feeds.npr.org"],"pathSuffix":".xml","exactSegments":false},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"application/rss+xml","auth_mode":"pub"},"extract":{"textMode":"npr_pbs_rss_xml"}},{"match":{"hosts":["www.pbs.org","pbs.org"],"pathPrefix":"/newshour/feeds/rss/","exactSegments":false},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"application/rss+xml","auth_mode":"pub"},"extract":{"textMode":"npr_pbs_rss_xml"}}],"htmlRoutes":[{"id":"npr-pbs","match":{"exactSegments":false},"mode":"npr_pbs_html"}]},{"id":"nps","name":"National Park Service (NPS)","category":"public-records","description":"National Park Service developer.nps.gov v1 JSON API (via DATA_GOV_API_KEY) with www.nps.gov HTML fallback.","domains":["developer.nps.gov","www.nps.gov","nps.gov"],"auth_mode":"key","exampleUrls":["https://www.nps.gov/yell/index.htm","https://developer.nps.gov/api/v1/parks?parkCode=yell&limit=1"],"routes":[{"match":{"hosts":["developer.nps.gov"],"pathPrefix":"/api/v1/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":4194304},"extract":{"jsonMode":"nps_json"}},{"match":{"hosts":["www.nps.gov","nps.gov"],"exactSegments":true,"pathSegments":[{"param":"parkCode","charset":"alnum","minLen":4,"maxLen":4,"reserved":["news","plan","maps","fees","find","jobs","kids","faqs","more","docs","help","info","blog","home","data","form","apps","page"],"transform":"lower"},"index.htm"]},"twin":{"fetchUrl":"https://developer.nps.gov/api/v1/parks?parkCode={parkCode}&limit=5","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"nps_json"}}],"htmlRoutes":[{"id":"nps","match":{"hosts":["www.nps.gov","nps.gov"],"exactSegments":false},"mode":"nps_html"}]},{"id":"nsf-awards","name":"National Science Foundation (NSF) Awards","category":"research-health","description":"Extracts NSF grant awards, PIs, institutions, obligated amounts, and abstracts from api.nsf.gov JSON with awardsearch SPA shell guards.","domains":["api.nsf.gov","www.nsf.gov","nsf.gov"],"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://api.nsf.gov/services/v1/awards/2535346.json","https://api.nsf.gov/services/v1/awards.json?keyword=quantum&rpp=2","https://www.nsf.gov/awardsearch/show-award?AWD_ID=2535346"],"routes":[{"match":{"hosts":["api.nsf.gov"],"pathPrefix":"/services/v1/awards"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"nsf_awards_json"}},{"match":{"hosts":["www.nsf.gov","nsf.gov"],"exactSegments":true,"pathEquals":["/awardsearch/showAward","/awardsearch/showAward/","/awardsearch/show-award","/awardsearch/show-award/"],"queryParams":[{"name":"AWD_ID","param":"awardId","charset":"digits","minLen":5,"maxLen":12}]},"twin":{"fetchUrl":"https://api.nsf.gov/services/v1/awards/{awardId}.json","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"nsf_awards_json"}}],"htmlRoutes":[{"id":"nsf-awards","match":{"hosts":["www.nsf.gov","nsf.gov"],"pathPrefix":"/awardsearch/","exactSegments":false},"mode":"nsf_awards_html"}]},{"id":"nuget-gallery","name":"NuGet Gallery","category":"developer","description":"Upgrades nuget.org/packages/[/] pages to the official api.nuget.org v3 registration JSON API (supporting both inlined catalogEntry pages and un-inlined CatalogPage stubs).","domains":["www.nuget.org","nuget.org"],"exampleUrls":["https://www.nuget.org/packages/Newtonsoft.Json","https://www.nuget.org/packages/Newtonsoft.Json/13.0.3"],"routes":[{"match":{"exactSegments":true,"pathSegments":["packages",{"param":"pkgId","charset":"pkg","minLen":1,"maxLen":128,"transform":"lower"},{"param":"ver","charset":"url_seg","reserved":["ReportAbuse","ContactOwners","versions"],"minLen":1,"maxLen":64}]},"twin":{"fetchUrl":"https://api.nuget.org/v3/registration5-gz-semver2/{pkgId}/index.json","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"nuget_registration"}},{"match":{"exactSegments":true,"pathSegments":["packages",{"param":"pkgId","charset":"pkg","minLen":1,"maxLen":128,"transform":"lower"}]},"twin":{"fetchUrl":"https://api.nuget.org/v3/registration5-gz-semver2/{pkgId}/index.json","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"nuget_registration"}}]},{"id":"nyt-api","name":"New York Times API & News","category":"commerce-social","description":"Official NYT Developer API (Article Search, Top Stories, Most Popular) with NYT_API_KEY and NewsArticle HTML fallback.","domains":["api.nytimes.com","www.nytimes.com","nytimes.com"],"auth_mode":"key","exampleUrls":["https://api.nytimes.com/svc/topstories/v2/home.json","https://www.nytimes.com/"],"routes":[{"match":{"hosts":["api.nytimes.com"],"exactSegments":true,"pathSegments":["svc","search","v2","articlesearch.json"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key"},"extract":{"jsonMode":"nyt_api_json"}},{"match":{"hosts":["api.nytimes.com"],"exactSegments":true,"pathSuffix":".json","pathSegments":["svc","topstories","v2",{"param":"section","charset":"slug","stripSuffix":".json","minLen":2,"maxLen":40}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key"},"extract":{"jsonMode":"nyt_api_json"}},{"match":{"hosts":["api.nytimes.com"],"exactSegments":true,"pathSuffix":".json","pathSegments":["svc","mostpopular","v2",{"param":"kind","allowValues":["emailed","shared","viewed"]},{"param":"period","charset":"digits","stripSuffix":".json","allowValues":["1","7","30"]}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key"},"extract":{"jsonMode":"nyt_api_json"}}],"htmlRoutes":[{"id":"nyt-api","match":{"hosts":["www.nytimes.com","nytimes.com"],"exactSegments":false},"mode":"nyt_html"}]},{"id":"ofac-sdn","name":"OFAC SDN Sanctions List & Actions","category":"public-records","description":"Bounded Range-streaming XML scanner for OFAC SDN.XML (<= 2 MiB) plus recent-actions and sanctions program HTML extraction on ofac.treasury.gov.","domains":["sanctionslistservice.ofac.treas.gov","ofac.treasury.gov"],"auth_mode":"pub","exampleUrls":["https://sanctionslistservice.ofac.treas.gov/api/PublicationPreview/exports/SDN.XML","https://ofac.treasury.gov/recent-actions"],"routes":[{"match":{"hosts":["sanctionslistservice.ofac.treas.gov"],"exactSegments":true,"pathEquals":["/api/PublicationPreview/exports/SDN.XML","/api/PublicationPreview/exports/CONS_PRIM.XML","/api/PublicationPreview/exports/SDN_ENHANCED.XML"]},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"application/xml","headers":{"Range":"bytes=0-2097151"},"maxBytes":2097152},"extract":{"textMode":"ofac_sdn_xml"}}],"htmlRoutes":[{"id":"ofac-sdn","match":{"hosts":["ofac.treasury.gov"],"exactSegments":false},"mode":"ofac_html"}]},{"id":"okendo","name":"Okendo Product Reviews","category":"commerce-social","description":"Extracts public Okendo product review and review aggregate JSON payloads without preempting storefront HTML extractors.","domains":["api.okendo.io"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://api.okendo.io/v1/stores/892ce72b-10d2-4dd3-a7ab-e2dfdee9d001/products/shopify-6861943013449/reviews?limit=10"],"routes":[{"match":{"anyOf":[{"hosts":["api.okendo.io"],"pathSegments":["v1","stores",{"param":"subscriberId","charset":"alnum_dash","minLen":4,"maxLen":80},"products",{"param":"productId","charset":"pkg","minLen":1,"maxLen":120},{"param":"endpoint","allowValues":["reviews","review_aggregate"]}]},{"hosts":["api.okendo.io"],"pathSegments":["v1","stores",{"param":"subscriberId","charset":"alnum_dash","minLen":4,"maxLen":80},"reviews"]}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"okendo_reviews"}}],"htmlRoutes":[{"id":"okendo","match":{"exactSegments":false},"mode":"okendo_html"}]},{"id":"open-icecat","name":"Open Icecat Product Datasheets","category":"commerce-social","description":"Extracts Open Icecat live API JSON product datasheets (strict 8/12/13/14-digit GTIN or Icecat ID validation) and Icecat HTML product pages while rejecting brand-restricted/missing error envelopes.","domains":["live.icecat.biz","data.icecat.biz","icecat.biz","www.icecat.biz","icecat.us"],"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://live.icecat.biz/api?shopname=openicecat-live&lang=en>IN=8710103792772","https://icecat.biz/en/p/saeco/ca6705-60/water-care-32928991.html"],"routes":[{"match":{"hosts":["live.icecat.biz"],"pathEquals":["/api","/api/"],"anyOf":[{"queryParams":[{"name":"GTIN","param":"gtin","charset":"digits","minLen":8,"maxLen":8}]},{"queryParams":[{"name":"GTIN","param":"gtin","charset":"digits","minLen":12,"maxLen":14}]},{"queryParams":[{"name":"icecat_id","param":"icecatId","charset":"digits","minLen":1,"maxLen":18}]}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"pub","maxBytes":4194304},"extract":{"jsonMode":"open_icecat_json"}}],"htmlRoutes":[{"id":"open-icecat","match":{"hosts":["icecat.biz","www.icecat.biz","icecat.us","data.icecat.biz"],"exactSegments":false},"mode":"open_icecat_html"}]},{"id":"open-product-wikidata-gtin","name":"Open Product Data & Wikidata GTIN Lookup","category":"commerce-social","description":"Extracts OpenGTINdb key=value product records (?ean=) and Wikidata P3962 SPARQL JSON bindings with strict 8/12/13/14-digit GTIN validation (without overlapping wikidata-openlibrary or opendatasoft domains).","domains":["opengtindb.org","www.opengtindb.org","query.wikidata.org"],"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://query.wikidata.org/sparql?query=SELECT%20%3Fitem%20%3FitemLabel%20%3Fgtin%20WHERE%20%7B%20%3Fitem%20wdt%3AP3962%20%3Fgtin%20.%20SERVICE%20wikibase%3Alabel%20%7B%20bd%3AserviceParam%20wikibase%3Alanguage%20%22en%22.%20%7D%20%7D%20LIMIT%205"],"routes":[{"match":{"hosts":["opengtindb.org","www.opengtindb.org"],"pathEquals":["/"],"anyOf":[{"queryParams":[{"name":"ean","param":"ean","charset":"digits","minLen":8,"maxLen":8}]},{"queryParams":[{"name":"ean","param":"ean","charset":"digits","minLen":12,"maxLen":14}]}]},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"text/plain","maxBytes":262144},"extract":{"textMode":"opengtindb_text"}},{"match":{"hosts":["query.wikidata.org"],"pathEquals":["/sparql"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/sparql-results+json","maxBytes":2097152},"extract":{"jsonMode":"wikidata_gtin_sparql_json"}}],"htmlRoutes":[{"id":"open-product-wikidata-gtin","match":{"hosts":["opengtindb.org","www.opengtindb.org","query.wikidata.org"],"exactSegments":false},"mode":"open_product_wikidata_html"}]},{"id":"openalex","name":"OpenAlex Scholarly Works","category":"research-health","description":"Upgrades openalex.org work URLs to api.openalex.org JSON with reconstructed abstracts, citations, open-access PDF links, and topics.","domains":["openalex.org","www.openalex.org","api.openalex.org"],"exampleUrls":["https://openalex.org/W2741809807","https://openalex.org/works/W2741809807"],"match":{"anyOf":[{"exactSegments":false,"pathSegments":["works",{"param":"workId","charset":"openalex_work","transform":"upper"}]},{"exactSegments":false,"pathSegments":[{"param":"workId","charset":"openalex_work","transform":"upper"}]}]},"twin":{"fetchUrl":"https://api.openalex.org/works/{workId}","kind":"json","accept":"application/json"},"extract":{"requireAnyFields":["display_name","title"],"requireVars":["title"],"vars":{"title":{"paths":["display_name","title"],"trim":true},"pubDate":{"paths":["publication_date"]},"citedBy":{"paths":["cited_by_count"],"format":"int_comma"},"doi":{"paths":["doi"]},"oaUrl":{"paths":["open_access.oa_url"],"requireHttps":true},"authors":{"paths":["authorships"],"subField":"author.display_name","limit":15,"join":", "},"authorsShort":{"paths":["authorships"],"subField":"author.display_name","limit":4,"join":", "},"abstract":{"paths":["abstract_inverted_index"],"format":"inverted_abstract"},"abstractShort":{"paths":["abstract_inverted_index"],"format":"inverted_abstract","sliceMax":260}},"titleTemplate":"{title}","descriptionVar":"abstractShort","authorVar":"authorsShort","publishedTimeVar":"pubDate","bullets":[{"label":"OpenAlex ID","template":"`{workId}`"},{"label":"Authors","template":"{authors}","whenVar":"authors"},{"label":"Published","template":"{pubDate}","whenVar":"pubDate"},{"label":"Citations","template":"{citedBy}","whenVar":"citedBy"},{"label":"DOI","template":"{doi}","whenVar":"doi"},{"label":"Open Access PDF","template":"{oaUrl}","whenVar":"oaUrl"}],"sections":[{"heading":"Abstract","textVar":"abstract"}],"linksVars":["doi","oaUrl"]}},{"id":"opencorporates","name":"OpenCorporates Company Registry","category":"public-records","description":"Upgrades opencorporates.com company pages to key-authenticated OpenCorporates API v0.4 JSON with clean public HTML attributes fallback when unconfigured.","domains":["opencorporates.com","www.opencorporates.com","api.opencorporates.com"],"auth_mode":"key","exampleUrls":["https://opencorporates.com/companies/us_de/3857729","https://api.opencorporates.com/v0.4/companies/us_de/3857729"],"routes":[{"match":{"hosts":["opencorporates.com","www.opencorporates.com"],"exactSegments":false,"pathSegments":["companies",{"param":"jurisdiction","charset":"alnum_dash","minLen":2,"maxLen":16},{"param":"companyNumber","charset":"url_seg","minLen":1,"maxLen":64}]},"twin":{"fetchUrl":"https://api.opencorporates.com/v0.4/companies/{jurisdiction}/{companyNumber}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"opencorporates_json"}},{"match":{"hosts":["api.opencorporates.com"],"pathPrefix":"/v0.4/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"opencorporates_json"}}],"htmlRoutes":[{"id":"opencorporates","match":{"hosts":["opencorporates.com","www.opencorporates.com"],"pathPrefix":"/companies/","exactSegments":false},"mode":"opencorporates_html"}]},{"id":"opendatasoft","name":"Opendatasoft Open Data Portals (Explore API v2.1)","category":"public-records","description":"Universal Opendatasoft adapter: /explore/dataset// pages and /api/explore/v2.1/catalog/datasets(/) upgrade to dataset metadata (publisher, license, record count, field schema, records/CSV API links); /records URLs render rows as a table while enforcing strict robots.txt compliance.","domains":["public.opendatasoft.com","*.opendatasoft.com","data.townofcary.org","data.jerseycitynj.gov"],"universalEngine":true,"auth_mode":"pub","strict_robots":true,"min_interval_ms":1000,"exampleUrls":["https://public.opendatasoft.com/explore/dataset/us-state-boundaries/","https://public.opendatasoft.com/api/explore/v2.1/catalog/datasets/us-state-boundaries/records?limit=3&select=name,stusab,region,division","https://data.townofcary.org/api/explore/v2.1/catalog/datasets?limit=3"],"routes":[{"match":{"exactSegments":true,"pathSegments":["api","explore","v2.1","catalog","datasets",{"param":"datasetId","charset":"pkg","minLen":2,"maxLen":160},"records"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"opendatasoft_records_json"}},{"match":{"pathEquals":["/api/explore/v2.1/catalog/datasets"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"opendatasoft_dataset_json"}},{"match":{"exactSegments":true,"pathSegments":["api","explore","v2.1","catalog","datasets",{"param":"datasetId","charset":"pkg","minLen":2,"maxLen":160}]},"twin":{"fetchUrl":"https://{host}/api/explore/v2.1/catalog/datasets/{datasetId}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"opendatasoft_dataset_json"}},{"match":{"exactSegments":false,"pathSegments":["explore","dataset",{"param":"datasetId","charset":"pkg","minLen":2,"maxLen":160}]},"twin":{"fetchUrl":"https://{host}/api/explore/v2.1/catalog/datasets/{datasetId}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"opendatasoft_dataset_json"}}]},{"id":"openfda","name":"openFDA Recalls, Labels & Adverse Events API","category":"research-health","description":"Formats keyless api.fda.gov JSON endpoints (drug/food/device enforcement recalls, drug labels, and adverse events) into clean Markdown tables.","domains":["api.fda.gov"],"exampleUrls":["https://api.fda.gov/food/enforcement.json?limit=5"],"match":{"pathSuffix":".json","pathSegments":[{"param":"endpointLabel","charset":"safe_subpath","greedy":true,"stripSuffix":".json"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"requireAnyFields":["results"],"vars":{"resultsCount":{"paths":["results"],"format":"array_len"},"total":{"paths":["meta.results.total"],"format":"int_comma","fallbackTemplate":"{resultsCount}"},"isRecall":{"paths":["results.0.recall_number","results.0.reason_for_recall"]}},"titleTemplate":"openFDA {endpointLabel} ({resultsCount} of {total} records)","sections":[{"heading":"","whenVar":"isRecall","arrayPath":"results","limit":25,"columns":[{"header":"Recall #","paths":["recall_number"],"code":true},{"header":"Class","paths":["classification"]},{"header":"Status","paths":["status"]},{"header":"Firm","paths":["recalling_firm"]},{"header":"Reason","paths":["reason_for_recall"]}]},{"heading":"","unlessVar":"isRecall","subsectionsArrayPath":"results","limit":10,"subsectionHeadingTemplate":"{recHeading}","subsectionSubkeys":["indications_and_usage","warnings","boxed_warning","dosage_and_administration","adverse_reactions"],"itemVars":{"brand":{"paths":["openfda.brand_name.0"]},"generic":{"paths":["openfda.generic_name.0"]},"genericParens":{"template":"({generic})","whenVars":["generic"]},"brandAndGeneric":{"template":"{brand} {genericParens}","whenVars":["brand","genericParens"],"fallbackVar":"brand"},"brandOrGeneric":{"template":"{brandAndGeneric}","whenVars":["brandAndGeneric"],"fallbackVar":"genericParens"},"recFallback":{"template":"Record #{index1}"},"recHeading":{"template":"{brandOrGeneric}","whenVars":["brandOrGeneric"],"fallbackVar":"recFallback"}}}]}},{"id":"openfoodfacts","name":"Open Food Facts Products","category":"commerce-social","description":"Extracts barcode, brand, Nutri-Score, NOVA group, ingredients, and nutrition facts from world.openfoodfacts.org/product/ (respecting robots.txt on /api).","domains":["world.openfoodfacts.org","openfoodfacts.org","*.openfoodfacts.org"],"exampleUrls":["https://world.openfoodfacts.org/product/3017620422003"],"htmlRoutes":[{"id":"openfoodfacts","match":{"exactSegments":false,"pathSegments":["product",{"param":"barcode","charset":"digits","minLen":6,"maxLen":16}]},"mode":"dom","jsonLdTypes":["Product"],"requireVars":["title"],"vars":{"title":{"jsonLdPaths":["name"],"metaKeys":["og:title"],"cssText":["h1"]},"brand":{"jsonLdPaths":["brand.name","brand"]},"nutriscore":{"regexExtract":{"source":"doc_text_and_img_alts","pattern":"Nutri-Score\\s*([A-E])\\b","group":1,"transform":"upper"}},"nova":{"regexExtract":{"source":"doc_text_and_img_alts","pattern":"NOVA\\s*([1-4])\\b","group":1}},"ingredientsLd":{"jsonLdPaths":["description"]},"ingredients":{"cssText":["#panel_ingredients_content"],"fallbackVar":"ingredientsLd"},"descShort":{"fallbackVar":"ingredients","sliceMax":260}},"titleTemplate":"{title}","descriptionVar":"descShort","bullets":[{"label":"Barcode (GTIN)","template":"`{barcode}`"},{"label":"Brand","template":"{brand}","whenVar":"brand"},{"label":"Nutri-Score","template":"**{nutriscore}**","whenVar":"nutriscore"},{"label":"NOVA Food Processing Group","template":"{nova}","whenVar":"nova"}],"sections":[{"heading":"Ingredients & Summary","textVar":"ingredients"}],"appendCurrentMdDelta":{"baseVar":"ingredients","minExtraChars":120}}]},{"id":"opengov-portals","name":"OpenGov Transparency & Procurement Portals","category":"public-records","description":"Extracts fiscal transparency datasets, window.gon/Zeus hydration, and public API data from OpenGov portals while classifying Cloudflare challenges honestly.","domains":["*.opengov.com"],"auth_mode":"pub","exampleUrls":["https://torranceca.opengov.com/api/v1/reports","https://torranceca.opengov.com/transparency","https://sanbernardinoca.opengov.com/transparency"],"routes":[{"match":{"anyOf":[{"pathPrefix":"/api/v1/"},{"pathPrefix":"/api/v2/"},{"pathPrefix":"/transparency/api/"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"opengov_json"}}],"htmlRoutes":[{"id":"opengov-portals","match":{"exactSegments":false},"mode":"opengov_html"}]},{"id":"openrouter","name":"OpenRouter AI Model Catalog","category":"genai","description":"Upgrades OpenRouter model pages to keyless /api/v1/models specs (context window, token pricing, modalities, and tool support).","domains":["openrouter.ai"],"exampleUrls":["https://openrouter.ai/anthropic/claude-sonnet-5.5","https://openrouter.ai/models/qwen/qwen4-max"],"match":{"anyOf":[{"exactSegments":true,"pathSegments":["models",{"param":"org","charset":"pkg"},{"param":"slug","charset":"model_slug"}]},{"exactSegments":true,"pathSegments":[{"param":"org","charset":"pkg","reserved":["docs","rankings","chat","activity","settings","keys","credits","privacy","terms","about","blog","pricing","providers"]},{"param":"slug","charset":"model_slug"}]}]},"twin":{"fetchUrl":"https://openrouter.ai/api/v1/models","kind":"json","accept":"application/json"},"extract":{"findInArray":{"arrayPath":"data","matchField":"id","matchTemplate":"{org}/{slug}","ignoreCase":true},"vars":{"id":{"paths":["id"]},"name":{"paths":["name"],"fallbackTemplate":"{org}/{slug}","trim":true},"ctxLen":{"paths":["context_length"],"format":"int_comma"},"maxOut":{"paths":["top_provider.max_completion_tokens"],"format":"int_comma"},"promptPrice":{"paths":["pricing.prompt"],"format":"usd_per_million_tokens"},"compPrice":{"paths":["pricing.completion"],"format":"usd_per_million_tokens"},"modality":{"paths":["architecture.modality"]},"params":{"paths":["supported_parameters"],"join":"`, `","limit":14},"desc":{"paths":["description"],"trim":true},"descShort":{"paths":["description"],"trim":true,"sliceMax":260}},"titleTemplate":"{name}","descriptionVar":"descShort","bullets":[{"label":"Model ID","template":"`{id}`"},{"label":"Context Window","template":"{ctxLen} tokens","whenVar":"ctxLen"},{"label":"Max Output","template":"{maxOut} tokens","whenVar":"maxOut"},{"label":"Input Pricing","template":"{promptPrice}","whenVar":"promptPrice"},{"label":"Output Pricing","template":"{compPrice}","whenVar":"compPrice"},{"label":"Modality","template":"`{modality}`","whenVar":"modality"},{"label":"Supported Parameters","template":"`{params}`","whenVar":"params"}],"sections":[{"heading":"Description","textVar":"desc"}]}},{"id":"openstreetmap","name":"OpenStreetMap (Nominatim & Overpass)","category":"public-records","description":"OpenStreetMap Nominatim geocoding and Overpass API JSON adapter enforcing strict 1 req/s pacing, identifying User-Agent, and strict robots.txt politeness.","domains":["www.openstreetmap.org","openstreetmap.org","nominatim.openstreetmap.org","overpass-api.de"],"auth_mode":"pub","user_agent_profile":"openstreetmap","min_interval_ms":1000,"strict_robots":true,"exampleUrls":["https://www.openstreetmap.org/about","https://www.openstreetmap.org/copyright"],"routes":[{"match":{"hosts":["nominatim.openstreetmap.org"],"anyOf":[{"pathPrefix":"/search"},{"pathPrefix":"/reverse"},{"pathPrefix":"/lookup"}]},"twin":{"fetchUrl":"{requestUrl}","setQueryParams":{"format":"jsonv2"},"kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"openstreetmap_json"}},{"match":{"hosts":["overpass-api.de"],"pathPrefix":"/api/interpreter"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"openstreetmap_json"}}],"htmlRoutes":[{"id":"openstreetmap","match":{"hosts":["www.openstreetmap.org","openstreetmap.org"],"exactSegments":false},"mode":"openstreetmap_html"}]},{"id":"oracle-commerce","name":"Oracle Commerce Cloud (ccstore)","category":"commerce-social","description":"Extracts Oracle Commerce Cloud /ccstore/v1 and /ccstoreui/v1 product and search JSON endpoints plus storefront HTML/companion twins.","domains":["www.dollartree.com"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://www.dollartree.com/ccstore/v1/products/805937","https://www.dollartree.com/ccstore/v1/search?Ntt=bag"],"routes":[{"match":{"pathSegments":["ccstore","v1","products",{"param":"productId","charset":"pkg","minLen":1,"maxLen":120}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"commerceMode":"oracle_commerce_product"}},{"match":{"pathSegments":["ccstoreui","v1","products",{"param":"productId","charset":"pkg","minLen":1,"maxLen":120}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"commerceMode":"oracle_commerce_product"}},{"match":{"pathEquals":["/ccstore/v1/search"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"commerceMode":"oracle_commerce_product"}}],"htmlRoutes":[{"id":"oracle-commerce","match":{"exactSegments":false},"mode":"oracle_commerce_html"}]},{"id":"orcid","name":"ORCID Researcher Registry","category":"research-health","description":"Extracts ORCID researcher profiles, affiliations, and works via pub.orcid.org v3.0 JSON API with orcid.org Angular CSR shell guard.","domains":["pub.orcid.org","orcid.org","www.orcid.org"],"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://pub.orcid.org/v3.0/0000-0002-1825-0097/record","https://orcid.org/0000-0002-1825-0097"],"routes":[{"match":{"hosts":["pub.orcid.org"],"pathPrefix":"/v3.0/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"orcid_json"}},{"match":{"hosts":["orcid.org","www.orcid.org"],"exactSegments":true,"pathSegments":[{"param":"orcidId","charset":"cpsc_recall_num","minLen":19,"maxLen":19,"transform":"upper"}]},"twin":{"fetchUrl":"https://pub.orcid.org/v3.0/{orcidId}/record","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"orcid_json"}}],"htmlRoutes":[{"id":"orcid","match":{"hosts":["orcid.org","www.orcid.org"],"exactSegments":false},"mode":"orcid_html"}]},{"id":"os-package-pack","name":"OS Package Pack (Flathub, Snapcraft, AUR, Winget, Chocolatey)","category":"developer","description":"Extracts OS package metadata and newest stable versions from Flathub, Snapcraft (Snap-Device-Series: 16), Arch AUR RPC v5, Winget, and Chocolatey.","domains":["flathub.org","snapcraft.io","api.snapcraft.io","aur.archlinux.org","winget.run","api.winget.run","community.chocolatey.org"],"auth_mode":"pub","min_interval_ms":2000,"exampleUrls":["https://flathub.org/apps/org.mozilla.firefox","https://snapcraft.io/firefox","https://aur.archlinux.org/packages/yay","https://winget.run/pkg/Microsoft/PowerToys"],"routes":[{"match":{"hosts":["flathub.org"],"pathPrefix":"/api/v2/appstream/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"flathub_json"}},{"match":{"hosts":["flathub.org"],"exactSegments":false,"pathSegments":["apps",{"param":"appId","charset":"pkg","minLen":3,"maxLen":160}]},"twin":{"fetchUrl":"https://flathub.org/api/v2/appstream/{appId}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"flathub_json"}},{"match":{"hosts":["api.snapcraft.io"],"pathPrefix":"/v2/snaps/info/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","headers":{"Snap-Device-Series":"16"},"maxBytes":2097152},"extract":{"jsonMode":"snapcraft_json"}},{"match":{"hosts":["snapcraft.io"],"exactSegments":true,"reservedFirstSegment":["account","admin","login","logout","store","docs","blog","about","publisher","search","first-snap","build"],"pathSegments":[{"param":"snap","charset":"pkg","minLen":1,"maxLen":80}]},"twin":{"fetchUrl":"https://api.snapcraft.io/v2/snaps/info/{snap}","kind":"json","accept":"application/json","headers":{"Snap-Device-Series":"16"},"maxBytes":2097152},"extract":{"jsonMode":"snapcraft_json"}},{"match":{"hosts":["aur.archlinux.org"],"pathPrefix":"/rpc/v5/info"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"aur_json"}},{"match":{"hosts":["aur.archlinux.org"],"exactSegments":true,"pathSegments":["packages",{"param":"pkg","charset":"pkg","minLen":1,"maxLen":120}]},"twin":{"fetchUrl":"https://aur.archlinux.org/rpc/v5/info?arg[]={pkg}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"aur_json"}},{"match":{"hosts":["api.winget.run"],"pathPrefix":"/v2/packages/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"winget_json"}},{"match":{"hosts":["winget.run"],"exactSegments":false,"pathSegments":["pkg",{"param":"publisher","charset":"pkg","minLen":1,"maxLen":120},{"param":"pkg","charset":"pkg","minLen":1,"maxLen":120}]},"twin":{"fetchUrl":"https://api.winget.run/v2/packages/{publisher}/{pkg}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"winget_json"}},{"match":{"hosts":["community.chocolatey.org"],"pathPrefix":"/api/v2/Packages"},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"application/atom+xml","maxBytes":2097152},"extract":{"textMode":"chocolatey_xml"}}],"htmlRoutes":[{"id":"os-package-pack","match":{"hosts":["snapcraft.io"],"exactSegments":true,"reservedFirstSegment":["account","admin","login","logout","store","docs","blog","about","publisher","search","first-snap","build"],"pathSegments":[{"param":"snap","charset":"pkg","minLen":1,"maxLen":80}]},"mode":"snapcraft_html"},{"id":"os-package-pack","match":{"hosts":["community.chocolatey.org"],"pathPrefix":"/packages/","exactSegments":false},"mode":"chocolatey_html"}]},{"id":"osha-establishment","name":"OSHA Establishment Inspections & Injury Data","category":"public-records","description":"Extracts OSHA IMIS/ORDS establishment inspection records and ITA injury/illness data pages from osha.gov while honoring robots.txt and detecting CloudFront 403 blocks.","domains":["www.osha.gov","osha.gov"],"auth_mode":"pub","strict_robots":true,"min_interval_ms":1500,"exampleUrls":["https://www.osha.gov/pls/imis/establishment.html","https://www.osha.gov/Establishment-Specific-Injury-and-Illness-Data"],"htmlRoutes":[{"id":"osha-establishment","match":{"exactSegments":false},"mode":"osha_establishment_html"}]},{"id":"osv-ghsa","name":"OSV & GitHub Security Advisories","category":"developer","description":"Upgrades osv.dev/vulnerability/ and github.com/advisories/GHSA-* pages to the keyless api.osv.dev/v1/vulns JSON API with canonical lowercase GHSA IDs and bounded affected-version slices.","domains":["osv.dev","www.osv.dev","github.com"],"exampleUrls":["https://osv.dev/vulnerability/GHSA-jfh8-c2jp-5v3q","https://github.com/advisories/GHSA-jfh8-c2jp-5v3q"],"routes":[{"match":{"hosts":["osv.dev","www.osv.dev"],"exactSegments":false,"pathSegments":["vulnerability",{"param":"vulnId","charset":"url_seg","minLen":4,"maxLen":80}]},"twin":{"fetchUrl":"https://api.osv.dev/v1/vulns/{vulnId}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"requireFields":["id"],"vars":{"id":{"paths":["id"]},"summary":{"paths":["summary"],"trim":true},"details":{"paths":["details"],"trim":true},"summaryShort":{"paths":["summary","details"],"trim":true,"sliceMax":260},"aliases":{"paths":["aliases"],"itemWrap":"`","join":", ","limit":12},"severityScore":{"paths":["severity.0.score"]},"severityType":{"paths":["severity.0.type"]},"published":{"paths":["published"],"sliceMax":10},"modified":{"paths":["modified"],"sliceMax":10},"osvUrl":{"template":"https://osv.dev/vulnerability/{id}","requireHttps":true}},"titleTemplate":"{id} — {summary}","titleWhenVar":"summary","titleFallbackTemplate":"{id} (OSV Advisory)","descriptionVar":"summaryShort","publishedTimeVar":"published","introVar":"summary","bullets":[{"label":"Advisory ID","template":"`{id}`"},{"label":"Aliases","template":"{aliases}","whenVar":"aliases"},{"label":"Severity","template":"`{severityScore}` ({severityType})","whenVar":"severityScore"},{"label":"Published","template":"{published}","whenVar":"published"},{"label":"Modified","template":"{modified}","whenVar":"modified"},{"label":"OSV URL","template":"{osvUrl}","whenVar":"osvUrl"}],"bodyVar":"details","sections":[{"heading":"Affected Packages","arrayPath":"affected","limit":20,"itemVars":{"versionsCount":{"paths":["versions"],"format":"array_len_comma"},"versionsSample":{"paths":["versions"],"limit":12,"itemWrap":"`","join":", "},"fixedVersions":{"nestedSubValues":{"arrayPath":"ranges","subArrayField":"events","valueField":"fixed","limit":12,"join":", "}}},"columns":[{"header":"Ecosystem","paths":["package.ecosystem"]},{"header":"Package","paths":["package.name"],"code":true},{"header":"Affected Count","template":"{versionsCount}"},{"header":"Sample Versions","template":"{versionsSample}"},{"header":"Fixed","template":"{fixedVersions}"}]},{"heading":"References","arrayPath":"references","limit":20,"requireItemVar":"refUrl","collectLinkVars":["refUrl"],"itemVars":{"refUrl":{"paths":["url"],"requireHttps":true},"refType":{"paths":["type"]}},"columns":[{"header":"Type","template":"{refType}"},{"header":"URL","template":"{refUrl}"}]}],"linksVars":["osvUrl"]}},{"match":{"hosts":["github.com"],"exactSegments":true,"pathPrefix":"/advisories/GHSA-","pathSegments":["advisories",{"param":"ghsaBody","stripPrefix":"GHSA-","charset":"alnum_dash","minLen":14,"maxLen":14,"transform":"lower"}]},"twin":{"fetchUrl":"https://api.osv.dev/v1/vulns/GHSA-{ghsaBody}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"requireFields":["id"],"vars":{"id":{"paths":["id"]},"summary":{"paths":["summary"],"trim":true},"details":{"paths":["details"],"trim":true},"summaryShort":{"paths":["summary","details"],"trim":true,"sliceMax":260},"aliases":{"paths":["aliases"],"itemWrap":"`","join":", ","limit":12},"severityScore":{"paths":["severity.0.score"]},"severityType":{"paths":["severity.0.type"]},"published":{"paths":["published"],"sliceMax":10},"modified":{"paths":["modified"],"sliceMax":10},"ghsaUrl":{"template":"https://github.com/advisories/GHSA-{ghsaBody}","requireHttps":true},"osvUrl":{"template":"https://osv.dev/vulnerability/{id}","requireHttps":true}},"titleTemplate":"{id} — {summary}","titleWhenVar":"summary","titleFallbackTemplate":"{id} (GitHub Advisory)","descriptionVar":"summaryShort","publishedTimeVar":"published","introVar":"summary","bullets":[{"label":"Advisory ID","template":"`{id}`"},{"label":"Aliases","template":"{aliases}","whenVar":"aliases"},{"label":"Severity","template":"`{severityScore}` ({severityType})","whenVar":"severityScore"},{"label":"Published","template":"{published}","whenVar":"published"},{"label":"Modified","template":"{modified}","whenVar":"modified"},{"label":"OSV URL","template":"{osvUrl}","whenVar":"osvUrl"}],"bodyVar":"details","sections":[{"heading":"Affected Packages","arrayPath":"affected","limit":20,"itemVars":{"versionsCount":{"paths":["versions"],"format":"array_len_comma"},"versionsSample":{"paths":["versions"],"limit":12,"itemWrap":"`","join":", "},"fixedVersions":{"nestedSubValues":{"arrayPath":"ranges","subArrayField":"events","valueField":"fixed","limit":12,"join":", "}}},"columns":[{"header":"Ecosystem","paths":["package.ecosystem"]},{"header":"Package","paths":["package.name"],"code":true},{"header":"Affected Count","template":"{versionsCount}"},{"header":"Sample Versions","template":"{versionsSample}"},{"header":"Fixed","template":"{fixedVersions}"}]},{"heading":"References","arrayPath":"references","limit":20,"requireItemVar":"refUrl","collectLinkVars":["refUrl"],"itemVars":{"refUrl":{"paths":["url"],"requireHttps":true},"refType":{"paths":["type"]}},"columns":[{"header":"Type","template":"{refType}"},{"header":"URL","template":"{refUrl}"}]}],"linksVars":["osvUrl","ghsaUrl"]}}]},{"id":"outdoor-retail-specs","name":"Outdoor & Cycling Retail Spec Extractor","category":"commerce-social","description":"Strictly rate-limited and robots-enforced HTML adapter for REI, Backcountry, and Competitive Cyclist product pages and technical specification tables.","domains":["rei.com","www.rei.com","backcountry.com","www.backcountry.com","competitivecyclist.com","www.competitivecyclist.com"],"auth_mode":"html","min_interval_ms":5000,"max_concurrent":1,"strict_robots":true,"exampleUrls":["https://www.rei.com/product/230456/co-op-cycles-adv-22-bike","https://www.backcountry.com/santa-cruz-bicycles-hightower-c-s-mountain-bike","https://www.competitivecyclist.com/cervelo-caledonia-105-road-bike"],"htmlRoutes":[{"id":"outdoor-retail-specs","match":{"exactSegments":false},"mode":"outdoor_retail_specs_html"}]},{"id":"oversight-gov","name":"Oversight.gov Inspector General Reports","category":"public-records","description":"Extracts Council of the Inspectors General on Integrity and Efficiency (CIGIE) Inspector General reports and metadata from oversight.gov while rejecting Azure App Gateway 406 shells.","domains":["www.oversight.gov","oversight.gov"],"auth_mode":"pub","exampleUrls":["https://www.oversight.gov/reports"],"htmlRoutes":[{"id":"oversight-gov","match":{"exactSegments":false},"mode":"oversight_gov_html"}]},{"id":"pacer-case-locator","name":"PACER Case Locator","category":"public-records","description":"Extracts public PACER informational and case-finder pages on pacer.uscourts.gov while honestly classifying login-gated portals (pcl.uscourts.gov, pacer.login.uscourts.gov) as login_wall.","domains":["pcl.uscourts.gov","pacer.uscourts.gov","ecf.dcd.uscourts.gov","pacer.login.uscourts.gov"],"auth_mode":"html","min_interval_ms":1500,"strict_robots":true,"exampleUrls":["https://pacer.uscourts.gov/find-case","https://pacer.uscourts.gov/","https://pcl.uscourts.gov/pcl/index.jsf"],"htmlRoutes":[{"id":"pacer-case-locator","match":{"hosts":["pcl.uscourts.gov","pacer.uscourts.gov","ecf.dcd.uscourts.gov","pacer.login.uscourts.gov"]},"mode":"pacer_case_locator_html"}]},{"id":"packagist","name":"Packagist PHP Composer Registry","category":"developer","description":"Upgrades packagist.org PHP Composer package pages to their official .json metadata feed.","domains":["packagist.org","www.packagist.org"],"exampleUrls":["https://packagist.org/packages/monolog/monolog"],"match":{"exactSegments":true,"pathSegments":["packages",{"param":"vendor","charset":"pkg"},{"param":"pkg","charset":"pkg"}]},"twin":{"fetchUrl":"https://packagist.org/packages/{vendor}/{pkg}.json","kind":"json","accept":"application/json"},"extract":{"rootPath":"package","requireFields":["name"],"vars":{"name":{"paths":["name"]},"desc":{"paths":["description"],"trim":true},"repo":{"paths":["repository"]},"stableVer":{"paths":["versions"],"firstNonMatchingKey":"dev"},"license":{"dynamicKeyPath":{"base":"versions","keyVar":"stableVer","subPath":"license"},"join":", "}},"titleTemplate":"{name} {stableVer} (Composer)","titleWhenVar":"stableVer","titleFallbackTemplate":"{name}","descriptionVar":"desc","introVar":"desc","bullets":[{"label":"Install","template":"`composer require {name}`"},{"label":"Latest Version","template":"`{stableVer}`","whenVar":"stableVer"},{"label":"License","template":"{license}","whenVar":"license"},{"label":"Repository","template":"{repo}","whenVar":"repo"}]}},{"id":"paradox-olivia","name":"Paradox Olivia Career Sites","category":"jobs","description":"Extracts JobPosting JSON-LD and __NEXT_DATA__ hydration job listings from Paradox Olivia career sites (*.paradox.ai, jobs.mchire.com, and custom brand portals via universalEngine).","domains":["*.paradox.ai","jobs.mchire.com","www.mchire.com"],"universalEngine":true,"auth_mode":"html","exampleUrls":["https://careers.fedex.com/account-manager-ii/job/P25-397759-1"],"htmlRoutes":[{"id":"paradox-olivia","mode":"paradox_olivia_html","match":{"exactSegments":false}}]},{"id":"park-tool","name":"Park Tool Repair Help & Tool Specs","category":"developer","description":"Extracts ordered bicycle repair steps, required tools, HowTo JSON-LD, and tool specification tables from parktool.com repair help and product pages.","domains":["parktool.com","www.parktool.com"],"auth_mode":"html","exampleUrls":["https://www.parktool.com/en-us/blog/repair-help/rear-derailleur-adjustment","https://www.parktool.com/en-us/product/chain-checker-cc-4"],"htmlRoutes":[{"id":"park-tool","match":{"exactSegments":false},"mode":"park_tool_html"}]},{"id":"patreon-public","name":"Patreon Public Creator & Post Pages","category":"commerce-social","description":"Extracts public Patreon creator profiles, membership tiers, and public posts from HTML structured-data JSON-LD and Next.js RSC payloads while honoring robots.txt disallows on /api/ and /rss/.","domains":["www.patreon.com","patreon.com"],"auth_mode":"html","min_interval_ms":1500,"strict_robots":true,"exampleUrls":["https://www.patreon.com/cw/Kurzgesagt","https://www.patreon.com/posts/behind-the-scenes-12345678"],"htmlRoutes":[{"id":"patreon-public","match":{"hosts":["www.patreon.com","patreon.com"],"reservedFirstSegment":["api","rss","login","signup","oauth2","settings","user","checkout","pledge","search"],"anyOf":[{"pathPrefix":"/cw/"},{"pathPrefix":"/c/"},{"pathPrefix":"/posts/"},{"exactSegments":true,"pathSegments":[{"param":"creator","charset":"url_seg","minLen":1,"maxLen":120}]}]},"mode":"patreon_public_html"}]},{"id":"peer-resale-fashion","name":"Mercari, Poshmark, Depop & Grailed Resale","category":"commerce-social","description":"Extracts public peer-to-peer fashion and secondhand listings from Poshmark, Mercari, Depop, and Grailed via JSON-LD, hydration state, and DOM fallback with strict WAF/404 guards.","domains":["mercari.com","www.mercari.com","poshmark.com","www.poshmark.com","depop.com","www.depop.com","grailed.com","www.grailed.com"],"auth_mode":"html","min_interval_ms":2000,"strict_robots":true,"exampleUrls":["https://poshmark.com/listing/ANTHROPOLOGIE-Saturday-Sunday-Annika-2Piece-Waffle-Knit-Lounge-Set-2X-6a67deaeb6af921bbc5288a4","https://poshmark.com/category/Women","https://www.mercari.com/us/category/1/"],"htmlRoutes":[{"id":"peer-resale-fashion","match":{"anyOf":[{"pathPrefix":"/listing/"},{"pathPrefix":"/category/"},{"pathPrefix":"/brand/"},{"pathPrefix":"/us/item/"},{"pathPrefix":"/us/category/"},{"pathPrefix":"/products/"},{"pathPrefix":"/listings/"},{"pathPrefix":"/shop/"}]},"mode":"peer_resale_fashion_html"}]},{"id":"peertube","name":"PeerTube Federated Video Platform (Universal Engine)","category":"commerce-social","description":"Upgrades PeerTube video permalinks (/w/{videoId} and /videos/watch/{videoId}) and /api/v1/videos/* endpoints via JSON API with VideoObject HTML fallback.","domains":["video.blender.org","tilvids.com","framatube.org"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://video.blender.org/w/v3kudnbEWnLVG5Fzormny6","https://video.blender.org/api/v1/videos/v3kudnbEWnLVG5Fzormny6","https://tilvids.com/api/v1/videos/6PsLUGoGiV9isoaHmht6Eu"],"routes":[{"match":{"exactSegments":true,"pathSegments":["api","v1","videos",{"param":"videoId","charset":"url_seg","minLen":8,"maxLen":64}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"peertube_json"}},{"match":{"exactSegments":true,"pathSegments":["api","v1","videos",{"param":"videoId","charset":"url_seg","minLen":8,"maxLen":64},"captions"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":1048576},"extract":{"jsonMode":"peertube_json"}},{"match":{"exactSegments":true,"pathSegments":["w",{"param":"videoId","charset":"url_seg","minLen":8,"maxLen":64}]},"twin":{"fetchUrl":"https://{host}/api/v1/videos/{videoId}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"peertube_json"}},{"match":{"exactSegments":true,"pathSegments":["videos","watch",{"param":"videoId","charset":"url_seg","minLen":8,"maxLen":64}]},"twin":{"fetchUrl":"https://{host}/api/v1/videos/{videoId}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"peertube_json"}}],"htmlRoutes":[{"id":"peertube","match":{"exactSegments":false},"mode":"peertube_html"}]},{"id":"pinkbike-buysell","name":"Pinkbike BuySell Marketplace","category":"commerce-social","description":"Extracts bicycle classified listings and category search results from Pinkbike BuySell while strictly rejecting Cloudflare challenge shells.","domains":["pinkbike.com","www.pinkbike.com"],"auth_mode":"html","min_interval_ms":2000,"max_concurrent":1,"strict_robots":true,"exampleUrls":["https://www.pinkbike.com/buysell/","https://www.pinkbike.com/buysell/list/?category=2"],"htmlRoutes":[{"id":"pinkbike-buysell","match":{"anyOf":[{"pathEquals":["/buysell"]},{"pathPrefix":"/buysell/"}]},"mode":"pinkbike_buysell_html"}]},{"id":"pinpoint","name":"Pinpoint ATS Job Boards","category":"jobs","description":"Upgrades .pinpointhq.com career portals to /postings.json with compensation, responsibilities, and workplace types.","domains":["*.pinpointhq.com"],"exampleUrls":["https://workwithus.pinpointhq.com/"],"routes":[{"match":{"hostSubdomain":{"suffix":".pinpointhq.com","param":"org","reserved":["www","app"]},"exactSegments":false,"pathSegments":["postings",{"param":"postId","charset":"pkg"}]},"twin":{"id":"pinpoint","fetchUrl":"https://{host}/postings.json","kind":"json","accept":"application/json"},"extract":{"findInArray":{"arrayPath":"data","matchField":"id","matchTemplate":"{postId}","endsWithField":"url","endsWithTemplate":"{postId}"},"vars":{"jobTitle":{"paths":["title"],"trim":true,"default":"Job Posting"},"loc":{"paths":["location.name"],"trim":true},"wp":{"paths":["workplace_type_text","workplace_type"],"trim":true},"cur":{"paths":["compensation_currency"],"trim":true,"default":"USD"},"compMin":{"paths":["compensation_minimum"],"excludeEquals":"0"},"compMax":{"paths":["compensation_maximum"],"excludeEquals":"0"},"compRange":{"template":"{cur} {compMin} – {compMax}","whenVars":["compMin","compMax"]},"compMinOnly":{"template":"{cur} {compMin}","whenVars":["compMin"]},"compMaxOnly":{"template":"{cur} – {compMax}","whenVars":["compMax"]},"compSub":{"template":"{compRange}","whenVars":["compRange"],"fallbackVar":"compMinOnly"},"comp":{"template":"{compSub}","whenVars":["compSub"],"fallbackVar":"compMaxOnly"},"desc":{"paths":["description"],"format":"html_to_md"},"resp":{"paths":["key_responsibilities"],"format":"html_to_md"},"skills":{"paths":["skills_knowledge_expertise"],"format":"html_to_md"},"benefits":{"paths":["benefits"],"format":"html_to_md"}},"titleTemplate":"{jobTitle} @ {org}","bullets":[{"label":"Company","template":"{org}"},{"label":"Location","template":"{loc}","whenVar":"loc"},{"label":"Workplace","template":"{wp}","whenVar":"wp"},{"label":"Compensation","template":"{comp}","whenVar":"comp"}],"sections":[{"heading":"Description","textVar":"desc"},{"heading":"Key Responsibilities","textVar":"resp"},{"heading":"Skills & Expertise","textVar":"skills"},{"heading":"Benefits","textVar":"benefits"}],"fallbackExtract":{"vars":{"count":{"paths":["data"],"format":"array_len"}},"requireVars":["count"],"titleTemplate":"{org} — Pinpoint Job Board ({count} open roles)","sections":[{"heading":"","arrayPath":"data","limit":100,"emptyText":"No open positions currently listed.","itemVars":{"pTitle":{"paths":["title"],"trim":true,"default":"Role"},"id":{"paths":["id"]},"rawUrl":{"paths":["url"],"requireHttps":true},"pUrl":{"template":"{rawUrl}","whenVars":["rawUrl"],"fallbackTemplate":"https://{host}/postings/{id}"},"loc":{"paths":["location.name"],"trim":true,"default":"-"},"wp":{"paths":["workplace_type_text","workplace_type"],"trim":true,"default":"-"},"cur":{"paths":["compensation_currency"],"trim":true,"default":"USD"},"compMin":{"paths":["compensation_minimum"],"excludeEquals":"0"},"compMax":{"paths":["compensation_maximum"],"excludeEquals":"0"},"compRange":{"template":"{cur} {compMin}–{compMax}","whenVars":["compMin","compMax"]},"compMinOnly":{"template":"{cur} {compMin}","whenVars":["compMin"]},"comp":{"template":"{compRange}","whenVars":["compRange"],"fallbackVar":"compMinOnly","default":"-"}},"collectLinkVars":["pUrl"],"columns":[{"header":"Role","template":"[{pTitle}]({pUrl})"},{"header":"Location","template":"{loc}"},{"header":"Workplace","template":"{wp}"},{"header":"Compensation","template":"{comp}"}]}]}}},{"match":{"hostSubdomain":{"suffix":".pinpointhq.com","param":"org","reserved":["www","app"]},"pathSegments":[{"param":"jobsLit","charset":"alnum","allowValues":["jobs","postings"],"optional":true}]},"twin":{"id":"pinpoint","fetchUrl":"https://{host}/postings.json","kind":"json","accept":"application/json"},"extract":{"vars":{"count":{"paths":["data"],"format":"array_len"}},"requireVars":["count"],"titleTemplate":"{org} — Pinpoint Job Board ({count} open roles)","sections":[{"heading":"","arrayPath":"data","limit":100,"emptyText":"No open positions currently listed.","itemVars":{"pTitle":{"paths":["title"],"trim":true,"default":"Role"},"id":{"paths":["id"]},"rawUrl":{"paths":["url"],"requireHttps":true},"pUrl":{"template":"{rawUrl}","whenVars":["rawUrl"],"fallbackTemplate":"https://{host}/postings/{id}"},"loc":{"paths":["location.name"],"trim":true,"default":"-"},"wp":{"paths":["workplace_type_text","workplace_type"],"trim":true,"default":"-"},"cur":{"paths":["compensation_currency"],"trim":true,"default":"USD"},"compMin":{"paths":["compensation_minimum"],"excludeEquals":"0"},"compMax":{"paths":["compensation_maximum"],"excludeEquals":"0"},"compRange":{"template":"{cur} {compMin}–{compMax}","whenVars":["compMin","compMax"]},"compMinOnly":{"template":"{cur} {compMin}","whenVars":["compMin"]},"comp":{"template":"{compRange}","whenVars":["compRange"],"fallbackVar":"compMinOnly","default":"-"}},"collectLinkVars":["pUrl"],"columns":[{"header":"Role","template":"[{pTitle}]({pUrl})"},{"header":"Location","template":"{loc}"},{"header":"Workplace","template":"{wp}"},{"header":"Compensation","template":"{comp}"}]}]}}]},{"id":"pkg-go-dev","name":"Go Packages (pkg.go.dev)","category":"developer","description":"Extracts Go module README and API documentation sections cleanly from pkg.go.dev.","domains":["pkg.go.dev"],"exampleUrls":["https://pkg.go.dev/github.com/coder/websocket"],"htmlRoutes":[{"match":{"minSegments":1},"mode":"dom","vars":{"title":{"cssText":["title"],"stripSuffix":"- Go Packages"},"readme":{"cssHtmlToMd":["div.UnitReadme-content"]},"docs":{"cssHtmlToMd":["div.Documentation-content"],"replaceAll":{"from":"¶","to":""}}},"requireBulletsOrVars":["readme","docs"],"titleTemplate":"{title}","sections":[{"heading":"Overview / README","textVar":"readme"},{"heading":"Documentation","textVar":"docs"}]}]},{"id":"pm-listing-widgets","name":"Property Management Listing Widgets (Buildium / Propertyware / RentManager)","category":"commerce-social","description":"Extracts public rental unit listings, rent pricing, bed/bath counts, and detail links from Buildium (managebuilding.com), Propertyware, and RentManager portals.","domains":["*.managebuilding.com","*.propertyware.com","*.rentmanager.com"],"universalEngine":true,"auth_mode":"html","strict_robots":true,"min_interval_ms":1000,"exampleUrls":["https://portland.managebuilding.com/Resident/public/rentals","https://hannibalrentals.managebuilding.com/Resident/public/rentals"],"htmlRoutes":[{"id":"pm-listing-widgets","match":{"exactSegments":false},"mode":"pm_listing_widgets_html"}]},{"id":"podcast-index","name":"Podcast Index Directory","category":"commerce-social","description":"Official keyed Podcast Index v1.0 API adapter (PODCASTINDEX_API_KEY + PODCASTINDEX_API_SECRET SHA-1 auth) for podcast feeds, episodes, and search, with podcastindex.org HTML fallback.","domains":["api.podcastindex.org","podcastindex.org","www.podcastindex.org"],"auth_mode":"key","min_interval_ms":1000,"exampleUrls":["https://api.podcastindex.org/api/1.0/podcasts/byfeedid?id=920666","https://api.podcastindex.org/api/1.0/episodes/byfeedid?id=920666"],"routes":[{"match":{"hosts":["api.podcastindex.org"],"pathPrefix":"/api/1.0/","exactSegments":false},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"podcast_index_json"}},{"match":{"hosts":["podcastindex.org","www.podcastindex.org"],"exactSegments":true,"pathSegments":["podcast",{"param":"feedId","charset":"digits","minLen":1,"maxLen":16}]},"twin":{"fetchUrl":"https://api.podcastindex.org/api/1.0/podcasts/byfeedid?id={feedId}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"podcast_index_json"}}],"htmlRoutes":[{"id":"podcast-index","match":{"hosts":["podcastindex.org","www.podcastindex.org"],"exactSegments":false},"mode":"podcast_index_html"}]},{"id":"podcasts-apple-lookup","name":"Apple Podcasts & iTunes Lookup","category":"commerce-social","description":"Extracts iTunes Lookup JSON for podcast metadata and Apple Podcasts HTML schema:show + serialized-server-data without cross-domain twins.","domains":["podcasts.apple.com","itunes.apple.com"],"auth_mode":"pub","exampleUrls":["https://itunes.apple.com/lookup?id=1200361736&entity=podcast","https://podcasts.apple.com/us/podcast/the-daily/id1200361736"],"routes":[{"match":{"hosts":["itunes.apple.com"],"pathEquals":["/lookup"],"queryParams":[{"name":"id","param":"itunesId","charset":"digits","minLen":3,"maxLen":20}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"apple_podcast_lookup_json"}}],"htmlRoutes":[{"id":"podcasts-apple-lookup","match":{"hosts":["podcasts.apple.com"],"exactSegments":false},"mode":"podcasts_apple_html"}]},{"id":"polymarket","name":"Polymarket Prediction Markets","category":"finance","description":"Upgrades polymarket.com/event/ pages to gamma-api.polymarket.com JSON with live outcome probabilities, volume, and liquidity.","domains":["polymarket.com","www.polymarket.com"],"exampleUrls":["https://polymarket.com/event/fed-decision-in-december"],"match":{"exactSegments":false,"pathSegments":["event",{"param":"slug","charset":"alnum_dash","minLen":2,"maxLen":140}]},"twin":{"fetchUrl":"https://gamma-api.polymarket.com/events?slug={slug}","kind":"json","accept":"application/json"},"extract":{"unwrapFirstArrayElement":true,"requireFields":["title"],"vars":{"title":{"paths":["title"],"trim":true},"desc":{"paths":["description"],"trim":true},"descShort":{"paths":["description"],"trim":true,"sliceMax":260},"vol":{"paths":["volume"],"format":"usd_compact"},"liq":{"paths":["liquidity"],"format":"usd_compact"},"endDate":{"paths":["endDate"],"sliceMax":10},"status":{"paths":["closed"],"format":"bool_map","trueValue":"Closed / Resolved","falseValue":"Active"}},"titleTemplate":"{title}","descriptionVar":"descShort","bullets":[{"label":"Status","template":"{status}"},{"label":"Total Volume","template":"{vol}","whenVar":"vol"},{"label":"Liquidity","template":"{liq}","whenVar":"liq"},{"label":"End Date","template":"{endDate}","whenVar":"endDate"}],"sections":[{"heading":"Market Odds","arrayPath":"markets","limit":25,"columns":[{"header":"Market / Outcome","paths":["groupItemTitle","question"],"fallbackVar":"title"},{"header":"Implied Probability","format":"paired_percent","outcomesField":"outcomes","pricesField":"outcomePrices","defaultOutcomes":["Yes","No"]},{"header":"Volume","paths":["volume"],"format":"usd_compact"}]},{"heading":"Resolution Rules","textVar":"desc"}]}},{"id":"popmenu","name":"Popmenu Restaurant Menus","category":"commerce-social","description":"Extracts restaurant menu sections, dishes, descriptions, and prices from Popmenu DOM, Apollo state, and Menu JSON-LD while rejecting Cloudflare challenge interstitials.","domains":["popmenu.com","www.popmenu.com","*.popmenu.com"],"universalEngine":true,"auth_mode":"html","strict_robots":true,"min_interval_ms":2000,"exampleUrls":["https://www.popmenu.com/"],"htmlRoutes":[{"id":"popmenu","match":{"exactSegments":false},"mode":"popmenu_html"}]},{"id":"powerreviews","name":"PowerReviews Product Reviews","category":"commerce-social","description":"Opt-in page-key adapter for PowerReviews Read API reviews; defaults OFF and falls back cleanly to HTML/JSON-LD when disabled.","domains":["readservices-b2c.powerreviews.com","www.skechers.com"],"universalEngine":true,"auth_mode":"page-key","requires_page_key_opt_in":true,"exampleUrls":["https://readservices-b2c.powerreviews.com/m/8162/l/en_US/product/177197/reviews?apikey=412df53d-8be4-4d9e-8657-e8c846f08b1d"],"routes":[{"match":{"hosts":["readservices-b2c.powerreviews.com"],"pathSegments":["m",{"param":"merchantId","charset":"alnum_dash","minLen":1,"maxLen":40},"l",{"param":"locale","charset":"alnum_dash","minLen":2,"maxLen":24},"product",{"param":"pageId","charset":"pkg","minLen":1,"maxLen":120},"reviews"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"jsonMode":"powerreviews_reviews"}}],"htmlRoutes":[{"id":"powerreviews","match":{"exactSegments":false},"mode":"powerreviews_html"}]},{"id":"prestashop","name":"PrestaShop Storefronts","category":"commerce-social","description":"Extracts PrestaShop storefront JSON-LD, data-product attributes, features tables, and ?action=quickview AJAX JSON payloads.","domains":["www.esprit-barbecue.fr"],"universalEngine":true,"auth_mode":"html","exampleUrls":["https://www.esprit-barbecue.fr/barbecues/3364-master-touch-gbs-premium-e-5770-noir-weber-0077924129551.html"],"routes":[{"match":{"anyOf":[{"hosts":["www.esprit-barbecue.fr"],"queryParams":[{"name":"action","param":"action","allowValues":["quickview"],"charset":"alnum"}]},{"pathSuffix":".html","queryParams":[{"name":"action","param":"action","allowValues":["quickview"],"charset":"alnum"},{"name":"ajax","param":"ajax","allowValues":["1"],"charset":"digits"}]}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"commerceMode":"prestashop_quickview"}}],"htmlRoutes":[{"id":"prestashop","match":{"exactSegments":false},"mode":"prestashop_html"}]},{"id":"primegov","name":"Rock Solid / Granicus PrimeGov Portals","category":"public-records","description":"Extracts upcoming municipal meetings and agendas from PrimeGov PublicPortal API and HTML views while strictly honoring robots.txt.","domains":["*.primegov.com"],"auth_mode":"pub","strict_robots":true,"exampleUrls":["https://okc.primegov.com/api/v2/PublicPortal/ListUpcomingMeetings","https://okc.primegov.com/public/portal"],"routes":[{"match":{"pathPrefix":"/api/v2/PublicPortal/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"primegov_json"}},{"match":{"pathEquals":["/public/portal","/public/portal/"]},"twin":{"fetchUrl":"https://{host}/api/v2/PublicPortal/ListUpcomingMeetings","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"primegov_json"}}],"htmlRoutes":[{"id":"primegov","match":{"exactSegments":false},"mode":"primegov_html"}]},{"id":"product-feed-discovery","name":"Storefront Product Feed Discovery","category":"commerce-social","description":"Universal XML/Atom/RSS parser for storefront product discovery endpoints (/products.atom, /feed/, and /sitemap_products_*.xml).","domains":["www.gymshark.com","henryrose.com","janji.com"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://www.gymshark.com/sitemap_products_1.xml","https://henryrose.com/sitemap_products_1.xml?from=1645692747866&to=15498254843994","https://janji.com/sitemap_products_1.xml?from=310052787&to=15293477683563"],"routes":[{"match":{"excludeHosts":["feeds.npr.org","npr.org","www.npr.org","pbs.org","www.pbs.org","prnewswire.com","www.prnewswire.com","businesswire.com","www.businesswire.com","globenewswire.com","www.globenewswire.com","medium.com","www.medium.com","*.medium.com","ghost.org","www.ghost.org","*.ghost.io","buttondown.com","www.buttondown.com","buttondown.email","rss.beehiiv.com","milkroad.beehiiv.com","*.beehiiv.com","wordpress.org","www.wordpress.org","*.wordpress.com","weworkremotely.com","www.weworkremotely.com","bicycleretailer.com","www.bicycleretailer.com","earthquake.usgs.gov","api.nasa.gov","recruiting.paylocity.com","app.jazz.co","*.applytojob.com","www.fpds.gov","fpds.gov","*.substack.com","substack.com","careers.*.com","jobs.*.com"],"anyOf":[{"pathEquals":["/products.atom","/feed","/feed/"]},{"pathPrefix":"/sitemap_products_","pathSuffix":".xml"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"application/atom+xml","maxBytes":4194304},"extract":{"textMode":"product_feed_discovery_xml"}}]},{"id":"product-hunt","name":"Product Hunt API & Launches","category":"commerce-social","description":"Extracts Product Hunt launches, makers, topics, and vote counts via official GraphQL v2 API (PRODUCTHUNT_API_TOKEN) with www.producthunt.com HTML fallback and strict Cloudflare challenge guard.","domains":["api.producthunt.com","www.producthunt.com","producthunt.com"],"auth_mode":"key","min_interval_ms":1000,"strict_robots":true,"exampleUrls":["https://api.producthunt.com/v2/api/graphql","https://www.producthunt.com/posts/claude-3-5-sonnet"],"routes":[{"match":{"hosts":["api.producthunt.com"],"pathEquals":["/v2/api/graphql"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","method":"POST","contentType":"application/json","requestBody":"{\"query\":\"{ posts(first: 10) { edges { node { id name tagline description votesCount commentsCount url website createdAt topics { edges { node { name } } } makers { name username } } } } }\"}","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"product_hunt_json"}}],"htmlRoutes":[{"id":"product-hunt","match":{"hosts":["www.producthunt.com","producthunt.com"],"anyOf":[{"pathPrefix":"/posts/"},{"pathPrefix":"/products/"}]},"mode":"product_hunt_html"}]},{"id":"prop65-warnings","name":"California Proposition 65 Chemical List & Warnings","category":"public-records","description":"Extracts California OEHHA Proposition 65 chemical lists and p65warnings.ca.gov chemical fact sheets while rejecting Incapsula WAF challenge shells and error pages.","domains":["oehha.ca.gov","www.oehha.ca.gov","p65warnings.ca.gov","www.p65warnings.ca.gov"],"auth_mode":"html","min_interval_ms":1500,"strict_robots":true,"exampleUrls":["https://oehha.ca.gov/proposition-65/proposition-65-list","https://www.p65warnings.ca.gov/fact-sheets/acrylamide"],"htmlRoutes":[{"id":"prop65-warnings","match":{"exactSegments":false},"mode":"prop65_warnings_html"}]},{"id":"propublica-nonprofits","name":"ProPublica Nonprofit Explorer","category":"public-records","description":"Upgrades ProPublica Nonprofit Explorer organization pages to keyless Form 990 JSON API v2 with HTML fallback.","domains":["projects.propublica.org"],"auth_mode":"pub","exampleUrls":["https://projects.propublica.org/nonprofits/organizations/521693387","https://projects.propublica.org/nonprofits/api/v2/organizations/521693387.json"],"routes":[{"match":{"hosts":["projects.propublica.org"],"exactSegments":false,"pathSegments":["nonprofits","organizations",{"param":"ein","charset":"digits","minLen":8,"maxLen":10}]},"twin":{"fetchUrl":"https://projects.propublica.org/nonprofits/api/v2/organizations/{ein}.json","kind":"json","accept":"application/json","auth_mode":"pub","maxBytes":2097152},"extract":{"jsonMode":"propublica_nonprofit_json"}},{"match":{"hosts":["projects.propublica.org"],"pathPrefix":"/nonprofits/api/v2/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"pub","maxBytes":2097152},"extract":{"jsonMode":"propublica_nonprofit_json"}}],"htmlRoutes":[{"id":"propublica-nonprofits","match":{"hosts":["projects.propublica.org"],"pathPrefix":"/nonprofits/","exactSegments":false},"mode":"propublica_nonprofit_html"}]},{"id":"pubchem","name":"PubChem Chemical Compounds (NCBI)","category":"research-health","description":"Upgrades pubchem.ncbi.nlm.nih.gov/compound/ to NCBI PUG-REST compound properties + pharmacological descriptions (with HTML JSON-LD fallback).","domains":["pubchem.ncbi.nlm.nih.gov"],"exampleUrls":["https://pubchem.ncbi.nlm.nih.gov/compound/2244"],"routes":[{"match":{"exactSegments":false,"pathSegments":["compound",{"param":"cid","charset":"digits","minLen":1,"maxLen":12}]},"twin":{"fetchUrl":"https://pubchem.ncbi.nlm.nih.gov/rest/pug_view/data/compound/{cid}/JSON/?heading=Names+and+Identifiers","kind":"json","accept":"application/json"},"extract":{"rootPath":"Record","requireFields":["RecordTitle"],"vars":{"cidVal":{"paths":["RecordNumber"],"fallbackTemplate":"{cid}"},"recTitle":{"paths":["RecordTitle"],"trim":true,"fallbackTemplate":"Compound {cidVal}"},"formula":{"format":"pubchem_toc","tocHeading":"Molecular Formula"},"iupac":{"format":"pubchem_toc","tocHeading":"IUPAC Name"},"inchiKey":{"format":"pubchem_toc","tocHeading":"InChIKey"},"canonicalSmiles":{"format":"pubchem_toc","tocHeading":"Canonical SMILES"},"smilesRaw":{"format":"pubchem_toc","tocHeading":"SMILES"},"smiles":{"template":"{smilesRaw}","whenVars":["smilesRaw"],"fallbackVar":"canonicalSmiles"},"cas":{"format":"pubchem_toc","tocHeading":"CAS"},"desc":{"format":"pubchem_toc","tocHeading":"Record Description"},"descShort":{"format":"pubchem_toc","tocHeading":"Record Description","sliceMax":260}},"titleTemplate":"{recTitle} (PubChem CID {cidVal})","descriptionVar":"descShort","bullets":[{"label":"PubChem CID","template":"`{cidVal}`"},{"label":"Molecular Formula","template":"`{formula}`","whenVar":"formula"},{"label":"CAS Number","template":"`{cas}`","whenVar":"cas"},{"label":"IUPAC Name","template":"`{iupac}`","whenVar":"iupac"},{"label":"InChIKey","template":"`{inchiKey}`","whenVar":"inchiKey"},{"label":"SMILES","template":"`{smiles}`","whenVar":"smiles"}],"sections":[{"heading":"Summary","textVar":"desc"}],"linkTemplates":["https://pubchem.ncbi.nlm.nih.gov/compound/{cidVal}"]}}],"htmlRoutes":[{"match":{"exactSegments":false,"pathSegments":["compound",{"param":"slug","charset":"url_seg"}]},"mode":"dom","jsonLdTypes":["MolecularEntity","ChemicalSubstance"],"requireVars":["title"],"requireBulletsOrVars":["desc"],"vars":{"title":{"jsonLdPaths":["name"],"metaKeys":["og:title"],"stripRegexSuffix":"\\s*\\|\\s*C\\d+.*?\\s*-\\s*PubChem$"},"formula":{"jsonLdPaths":["molecularFormula"]},"weightValObj":{"jsonLdPaths":["molecularWeight.value"]},"weightFromObj":{"template":"{weightValObj} g/mol","whenVars":["weightValObj"]},"weight":{"jsonLdPaths":["molecularWeight"],"fallbackVar":"weightFromObj"},"iupac":{"jsonLdPaths":["iupacName"]},"inchiKey":{"jsonLdPaths":["inChIKey"]},"smiles":{"jsonLdPaths":["smiles"],"limit":1},"desc":{"metaKeys":["description"]},"descShort":{"metaKeys":["description"],"sliceMax":260}},"titleTemplate":"{title} (PubChem)","descriptionVar":"descShort","bullets":[{"label":"Molecular Formula","template":"`{formula}`","whenVar":"formula"},{"label":"Molecular Weight","template":"{weight}","whenVar":"weight"},{"label":"IUPAC Name","template":"`{iupac}`","whenVar":"iupac"},{"label":"InChIKey","template":"`{inchiKey}`","whenVar":"inchiKey"},{"label":"SMILES","template":"`{smiles}`","whenVar":"smiles"}],"sections":[{"heading":"Summary","textVar":"desc"}],"appendCurrentMdDelta":{"minExtraChars":200}}]},{"id":"public-bid-portals","name":"Public Procurement & Bid Portals (Bonfire, BidNet, Periscope)","category":"public-records","description":"Extracts public municipal solicitations and RFPs from BidNet Direct, Bonfire, and Periscope S2G while classifying login-gated bid details as login_wall.","domains":["*.bonfirehub.com","www.bidnetdirect.com","bidnetdirect.com","www.bidsync.com","app.periscopeholdings.com"],"auth_mode":"html","strict_robots":true,"exampleUrls":["https://www.bidnetdirect.com/colorado/cityandcountyofdenverdoti/solicitations/open-bids?selectedContent=BUYER","https://www.bidnetdirect.com/colorado/solicitations/open-bids/W-38th-Ave-Multimodal-Improvements-Design-Services/0000443656?purchasingGroupId=8409951&origin=2"],"htmlRoutes":[{"id":"public-bid-portals","match":{"exactSegments":false},"mode":"public_bid_html"}]},{"id":"public-booking","name":"Public Booking (Calendly & Acuity Scheduling)","category":"commerce-social","description":"Extracts public Calendly event types via queryless /api/booking/profiles/{profile}/event_types (honoring Disallow: /*?*) and Calendly/Acuity HTML booking pages, rejecting unavailability_reason error-only payloads.","domains":["calendly.com","www.calendly.com","acuityscheduling.com","app.acuityscheduling.com"],"auth_mode":"pub","strict_robots":true,"exampleUrls":["https://calendly.com/api/booking/profiles/demo/event_types","https://calendly.com/demo","https://calendly.com/calendly-sales"],"routes":[{"match":{"hosts":["calendly.com","www.calendly.com"],"exactSegments":true,"pathSegments":[{"param":"profile","charset":"slug","minLen":2,"maxLen":80,"reserved":["app","api","d","s","login","signup","pricing","features","solutions","enterprise","integrations","resources","blog","about","careers","legal","privacy","terms","help","abuse_reports","error","404","not-found"]}]},"twin":{"fetchUrl":"https://calendly.com/api/booking/profiles/{profile}/event_types","kind":"json","accept":"application/json","maxBytes":1048576},"extract":{"jsonMode":"calendly_booking_json"}},{"match":{"hosts":["calendly.com","www.calendly.com"],"pathPrefix":"/api/booking/profiles/","exactSegments":false},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":1048576},"extract":{"jsonMode":"calendly_booking_json"}}],"htmlRoutes":[{"id":"public-booking","mode":"booking_html","match":{"hosts":["calendly.com","www.calendly.com","acuityscheduling.com","app.acuityscheduling.com"],"exactSegments":false}}]},{"id":"public-forms","name":"Public Forms (Typeform & Jotform)","category":"commerce-social","description":"Extracts public Typeform field definitions via api.typeform.com/forms/{formId} or window.rendererData HTML and Jotform forms via HTML field labels/configs, rejecting typeform-incorrectURL soft-404 redirects.","domains":["typeform.com","www.typeform.com","form.typeform.com","api.typeform.com","jotform.com","www.jotform.com","form.jotform.com"],"universalEngine":true,"auth_mode":"pub","strict_robots":true,"exampleUrls":["https://tfsales.typeform.com/to/PxcVKQGb","https://api.typeform.com/forms/PxcVKQGb","https://form.jotform.com/240912145384959"],"routes":[{"match":{"hostSubdomain":{"suffix":".typeform.com","param":"org","reserved":["www","api","admin","help","developer","login","auth"]},"exactSegments":true,"pathSegments":["to",{"param":"formId","charset":"slug","minLen":4,"maxLen":32}]},"twin":{"fetchUrl":"https://api.typeform.com/forms/{formId}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"typeform_json"}},{"match":{"hosts":["typeform.com","www.typeform.com"],"exactSegments":true,"pathSegments":["to",{"param":"formId","charset":"slug","minLen":4,"maxLen":32}]},"twin":{"fetchUrl":"https://api.typeform.com/forms/{formId}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"typeform_json"}},{"match":{"hosts":["api.typeform.com"],"exactSegments":true,"pathSegments":["forms",{"param":"formId","charset":"slug","minLen":4,"maxLen":32}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"typeform_json"}}],"htmlRoutes":[{"id":"public-forms","mode":"typeform_html","match":{"anyOf":[{"hostSubdomain":{"suffix":".typeform.com","param":"org","reserved":["api","admin","login","auth"]},"exactSegments":false},{"hosts":["typeform.com","www.typeform.com","form.typeform.com"],"exactSegments":false}]}},{"id":"public-forms","mode":"jotform_html","match":{"anyOf":[{"hosts":["jotform.com","www.jotform.com","form.jotform.com"],"exactSegments":false},{"hostSubdomain":{"suffix":".jotform.com","param":"org","reserved":["api","www","form","login","auth"]},"exactSegments":false}]}}]},{"id":"public-job-feeds","name":"Public Open Job Feeds (WWR, Himalayas, Working Nomads, The Muse, Jobicy, Arbeitnow & RemoteOK)","category":"jobs","description":"Formats robots.txt-allowed keyless public job feeds (We Work Remotely RSS, Himalayas, Working Nomads, The Muse, Jobicy, Arbeitnow, and RemoteOK) into clean job tables.","domains":["weworkremotely.com","www.weworkremotely.com","himalayas.app","www.himalayas.app","www.workingnomads.com","workingnomads.com","www.themuse.com","themuse.com","jobicy.com","www.arbeitnow.com","arbeitnow.com","remoteok.com"],"exampleUrls":["https://weworkremotely.com/remote-jobs.rss","https://himalayas.app/jobs/api?limit=50","https://www.workingnomads.com/api/exposed_jobs/","https://www.themuse.com/api/public/jobs?page=1","https://jobicy.com/api/v2/remote-jobs?count=20","https://remoteok.com/api"],"routes":[{"match":{"hosts":["weworkremotely.com","www.weworkremotely.com"],"pathSuffix":".rss"},"twin":{"id":"weworkremotely-feed","fetchUrl":"{requestUrl}","kind":"text","accept":"application/rss+xml"},"extract":{"xml":{"mode":"items_table","requireAnyTags":["rss","channel"],"itemTag":"item","titleTemplate":"We Work Remotely Jobs ({itemCount})","limit":50,"collectLinkVar":"jLink","emitTotals":true,"itemVars":{"company":{"tags":["title"],"splitColonPart":0,"default":"We Work Remotely"},"role":{"tags":["title"],"splitColonPart":1,"default":"Role"},"jLink":{"tags":["link"]},"region":{"tags":["region"],"default":"Remote"},"category":{"tags":["category"],"default":"-"},"pubDate":{"tags":["pubDate"]},"pubDisplay":{"tags":["pubDate","category"],"sliceMax":16,"default":"-"}},"recordFields":{"title":"{role}","company":"{company}","url":"{jLink}","region":"{region}","category":"{category}","postedAt":"{pubDate}","source":"weworkremotely"},"columns":[{"header":"Role","template":"[{role}]({jLink})"},{"header":"Company","template":"{company}"},{"header":"Region","template":"{region}"},{"header":"Published","template":"{pubDisplay}"}]}}},{"match":{"hosts":["weworkremotely.com","www.weworkremotely.com"],"pathEquals":["/remote-jobs","/remote-jobs/"]},"twin":{"id":"weworkremotely-feed","fetchUrl":"https://weworkremotely.com/remote-jobs.rss","kind":"text","accept":"application/rss+xml"},"extract":{"xml":{"mode":"items_table","requireAnyTags":["rss","channel"],"itemTag":"item","titleTemplate":"We Work Remotely Jobs ({itemCount})","limit":50,"collectLinkVar":"jLink","emitTotals":true,"itemVars":{"company":{"tags":["title"],"splitColonPart":0,"default":"We Work Remotely"},"role":{"tags":["title"],"splitColonPart":1,"default":"Role"},"jLink":{"tags":["link"]},"region":{"tags":["region"],"default":"Remote"},"category":{"tags":["category"],"default":"-"},"pubDate":{"tags":["pubDate"]},"pubDisplay":{"tags":["pubDate","category"],"sliceMax":16,"default":"-"}},"recordFields":{"title":"{role}","company":"{company}","url":"{jLink}","region":"{region}","category":"{category}","postedAt":"{pubDate}","source":"weworkremotely"},"columns":[{"header":"Role","template":"[{role}]({jLink})"},{"header":"Company","template":"{company}"},{"header":"Region","template":"{region}"},{"header":"Published","template":"{pubDisplay}"}]}}},{"match":{"hosts":["himalayas.app","www.himalayas.app"],"pathPrefix":"/jobs/api"},"twin":{"id":"himalayas-feed","fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"vars":{"jobCount":{"paths":["jobs"],"format":"array_len"},"totalFmt":{"paths":["totalCount"],"format":"int_comma","fallbackTemplate":"{jobCount}"}},"requireVars":["jobCount"],"titleTemplate":"Himalayas Remote Jobs ({jobCount} of {totalFmt})","sections":[{"heading":"","arrayPath":"jobs","limit":50,"emptyText":"No open positions currently listed.","paginationMeta":{"totalPath":"totalCount","cursorMode":"offset"},"itemVars":{"jTitle":{"paths":["title"],"trim":true,"default":"Role"},"company":{"paths":["companyName"],"trim":true,"default":"-"},"appUrl":{"paths":["applicationLink"],"requireHttps":true},"guidUrl":{"paths":["guid"],"requireHttps":true},"jUrl":{"template":"{appUrl}","whenVars":["appUrl"],"fallbackVar":"guidUrl"},"locs":{"paths":["locationRestrictions"],"join":", ","default":"Worldwide"},"cur":{"paths":["currency"],"trim":true,"default":"USD"},"minSal":{"paths":["minSalary"],"format":"int_comma","excludeEquals":"0"},"maxSal":{"paths":["maxSalary"],"format":"int_comma","excludeEquals":"0"},"salRange":{"template":"{cur} {minSal}–{maxSal}","whenVars":["minSal","maxSal"]},"salMinOnly":{"template":"{cur} {minSal}","whenVars":["minSal"]},"sal":{"template":"{salRange}","whenVars":["salRange"],"fallbackVar":"salMinOnly","default":"-"},"roleCell":{"template":"[{jTitle}]({jUrl})","whenVars":["jUrl"],"fallbackVar":"jTitle"}},"collectLinkVars":["jUrl"],"recordFields":{"title":"{jTitle}","company":"{company}","url":"{jUrl}","locations":"{locs}","salary":"{sal}","source":"himalayas"},"columns":[{"header":"Role","template":"{roleCell}"},{"header":"Company","template":"{company}"},{"header":"Region","template":"{locs}"},{"header":"Salary","template":"{sal}"}]}]}},{"match":{"hosts":["himalayas.app","www.himalayas.app"],"pathPrefix":"/jobs"},"twin":{"id":"himalayas-feed","fetchUrl":"https://himalayas.app/jobs/api?limit=50","kind":"json","accept":"application/json"},"extract":{"vars":{"jobCount":{"paths":["jobs"],"format":"array_len"},"totalFmt":{"paths":["totalCount"],"format":"int_comma","fallbackTemplate":"{jobCount}"}},"requireVars":["jobCount"],"titleTemplate":"Himalayas Remote Jobs ({jobCount} of {totalFmt})","sections":[{"heading":"","arrayPath":"jobs","limit":50,"emptyText":"No open positions currently listed.","paginationMeta":{"totalPath":"totalCount","cursorMode":"offset"},"itemVars":{"jTitle":{"paths":["title"],"trim":true,"default":"Role"},"company":{"paths":["companyName"],"trim":true,"default":"-"},"appUrl":{"paths":["applicationLink"],"requireHttps":true},"guidUrl":{"paths":["guid"],"requireHttps":true},"jUrl":{"template":"{appUrl}","whenVars":["appUrl"],"fallbackVar":"guidUrl"},"locs":{"paths":["locationRestrictions"],"join":", ","default":"Worldwide"},"cur":{"paths":["currency"],"trim":true,"default":"USD"},"minSal":{"paths":["minSalary"],"format":"int_comma","excludeEquals":"0"},"maxSal":{"paths":["maxSalary"],"format":"int_comma","excludeEquals":"0"},"salRange":{"template":"{cur} {minSal}–{maxSal}","whenVars":["minSal","maxSal"]},"salMinOnly":{"template":"{cur} {minSal}","whenVars":["minSal"]},"sal":{"template":"{salRange}","whenVars":["salRange"],"fallbackVar":"salMinOnly","default":"-"},"roleCell":{"template":"[{jTitle}]({jUrl})","whenVars":["jUrl"],"fallbackVar":"jTitle"}},"collectLinkVars":["jUrl"],"recordFields":{"title":"{jTitle}","company":"{company}","url":"{jUrl}","locations":"{locs}","salary":"{sal}","source":"himalayas"},"columns":[{"header":"Role","template":"{roleCell}"},{"header":"Company","template":"{company}"},{"header":"Region","template":"{locs}"},{"header":"Salary","template":"{sal}"}]}]}},{"match":{"hosts":["www.workingnomads.com","workingnomads.com"],"pathPrefix":"/api/exposed_jobs"},"twin":{"id":"workingnomads-feed","fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"wrapRootArrayAs":"jobs","vars":{"jobCount":{"paths":["jobs"],"format":"array_len"}},"requireVars":["jobCount"],"titleTemplate":"Working Nomads Remote Jobs ({jobCount})","sections":[{"heading":"","arrayPath":"jobs","limit":50,"emptyText":"No open positions currently listed.","paginationMeta":{"cursorMode":"offset"},"itemVars":{"jTitle":{"paths":["title"],"trim":true,"default":"Role"},"company":{"paths":["company_name"],"trim":true,"default":"-"},"jUrl":{"paths":["url"],"requireHttps":true},"loc":{"paths":["location"],"trim":true,"default":"Remote"},"pub":{"paths":["pub_date"],"sliceMax":10,"trim":true,"default":"-"},"roleCell":{"template":"[{jTitle}]({jUrl})","whenVars":["jUrl"],"fallbackVar":"jTitle"}},"collectLinkVars":["jUrl"],"recordFields":{"title":"{jTitle}","company":"{company}","url":"{jUrl}","location":"{loc}","postedAt":"{pub}","source":"workingnomads"},"columns":[{"header":"Role","template":"{roleCell}"},{"header":"Company","template":"{company}"},{"header":"Location","template":"{loc}"},{"header":"Published","template":"{pub}"}]}]}},{"match":{"hosts":["www.workingnomads.com","workingnomads.com"],"pathEquals":["/jobs","/jobs/"]},"twin":{"id":"workingnomads-feed","fetchUrl":"https://www.workingnomads.com/api/exposed_jobs/","kind":"json","accept":"application/json"},"extract":{"wrapRootArrayAs":"jobs","vars":{"jobCount":{"paths":["jobs"],"format":"array_len"}},"requireVars":["jobCount"],"titleTemplate":"Working Nomads Remote Jobs ({jobCount})","sections":[{"heading":"","arrayPath":"jobs","limit":50,"emptyText":"No open positions currently listed.","paginationMeta":{"cursorMode":"offset"},"itemVars":{"jTitle":{"paths":["title"],"trim":true,"default":"Role"},"company":{"paths":["company_name"],"trim":true,"default":"-"},"jUrl":{"paths":["url"],"requireHttps":true},"loc":{"paths":["location"],"trim":true,"default":"Remote"},"pub":{"paths":["pub_date"],"sliceMax":10,"trim":true,"default":"-"},"roleCell":{"template":"[{jTitle}]({jUrl})","whenVars":["jUrl"],"fallbackVar":"jTitle"}},"collectLinkVars":["jUrl"],"recordFields":{"title":"{jTitle}","company":"{company}","url":"{jUrl}","location":"{loc}","postedAt":"{pub}","source":"workingnomads"},"columns":[{"header":"Role","template":"{roleCell}"},{"header":"Company","template":"{company}"},{"header":"Location","template":"{loc}"},{"header":"Published","template":"{pub}"}]}]}},{"match":{"hosts":["www.themuse.com","themuse.com"],"pathPrefix":"/api/public/jobs"},"twin":{"id":"themuse-feed","fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"vars":{"resCount":{"paths":["results"],"format":"array_len"},"totalFmt":{"paths":["total"],"format":"int_comma","fallbackTemplate":"{resCount}"}},"requireVars":["resCount"],"titleTemplate":"The Muse Public Jobs ({resCount} of {totalFmt})","sections":[{"heading":"","arrayPath":"results","limit":50,"emptyText":"No open positions currently listed.","itemVars":{"jTitle":{"paths":["name"],"trim":true,"default":"Role"},"co":{"paths":["company.name"],"trim":true,"default":"-"},"locs":{"paths":["locations"],"subField":"name","join":"; ","default":"-"},"lUrl":{"paths":["refs.landing_page"],"requireHttps":true},"pub":{"paths":["publication_date"],"sliceMax":10,"trim":true,"default":"-"},"roleCell":{"template":"[{jTitle}]({lUrl})","whenVars":["lUrl"],"fallbackVar":"jTitle"}},"collectLinkVars":["lUrl"],"columns":[{"header":"Role","template":"{roleCell}"},{"header":"Company","template":"{co}"},{"header":"Locations","template":"{locs}"},{"header":"Published","template":"{pub}"}]}]}},{"match":{"hosts":["jobicy.com"],"pathPrefix":"/api/v2/remote-jobs"},"twin":{"id":"jobicy-feed","fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"vars":{"jobCount":{"paths":["jobs"],"format":"array_len"}},"requireVars":["jobCount"],"titleTemplate":"Jobicy Remote Jobs ({jobCount})","sections":[{"heading":"","arrayPath":"jobs","limit":50,"emptyText":"No open positions currently listed.","itemVars":{"jTitle":{"paths":["jobTitle"],"format":"strip_tags","trim":true,"default":"Role"},"jUrl":{"paths":["url"],"requireHttps":true},"company":{"paths":["companyName"],"trim":true,"default":"-"},"geo":{"paths":["jobGeo"],"trim":true,"default":"Remote"},"cur":{"paths":["salaryCurrency"],"trim":true,"default":"USD"},"salMin":{"paths":["annualSalaryMin"],"excludeEquals":"0"},"salMax":{"paths":["annualSalaryMax"],"excludeEquals":"0"},"salRange":{"template":"{cur} {salMin}–{salMax}","whenVars":["salMin","salMax"]},"salMinOnly":{"template":"{cur} {salMin}","whenVars":["salMin"]},"sal":{"template":"{salRange}","whenVars":["salRange"],"fallbackVar":"salMinOnly","default":"-"},"roleCell":{"template":"[{jTitle}]({jUrl})","whenVars":["jUrl"],"fallbackVar":"jTitle"}},"collectLinkVars":["jUrl"],"columns":[{"header":"Role","template":"{roleCell}"},{"header":"Company","template":"{company}"},{"header":"Region","template":"{geo}"},{"header":"Annual Salary","template":"{sal}"}]}]}},{"match":{"anyOf":[{"hosts":["jobicy.com"],"pathEquals":["/jobs-rss-feed","/jobs-rss-feed/"]},{"hosts":["jobicy.com"],"pathPrefix":"/remote-"}]},"twin":{"id":"jobicy-feed","fetchUrl":"https://jobicy.com/api/v2/remote-jobs?count=30","kind":"json","accept":"application/json"},"extract":{"vars":{"jobCount":{"paths":["jobs"],"format":"array_len"}},"requireVars":["jobCount"],"titleTemplate":"Jobicy Remote Jobs ({jobCount})","sections":[{"heading":"","arrayPath":"jobs","limit":50,"emptyText":"No open positions currently listed.","itemVars":{"jTitle":{"paths":["jobTitle"],"format":"strip_tags","trim":true,"default":"Role"},"jUrl":{"paths":["url"],"requireHttps":true},"company":{"paths":["companyName"],"trim":true,"default":"-"},"geo":{"paths":["jobGeo"],"trim":true,"default":"Remote"},"cur":{"paths":["salaryCurrency"],"trim":true,"default":"USD"},"salMin":{"paths":["annualSalaryMin"],"excludeEquals":"0"},"salMax":{"paths":["annualSalaryMax"],"excludeEquals":"0"},"salRange":{"template":"{cur} {salMin}–{salMax}","whenVars":["salMin","salMax"]},"salMinOnly":{"template":"{cur} {salMin}","whenVars":["salMin"]},"sal":{"template":"{salRange}","whenVars":["salRange"],"fallbackVar":"salMinOnly","default":"-"},"roleCell":{"template":"[{jTitle}]({jUrl})","whenVars":["jUrl"],"fallbackVar":"jTitle"}},"collectLinkVars":["jUrl"],"columns":[{"header":"Role","template":"{roleCell}"},{"header":"Company","template":"{company}"},{"header":"Region","template":"{geo}"},{"header":"Annual Salary","template":"{sal}"}]}]}},{"match":{"hosts":["www.arbeitnow.com","arbeitnow.com"],"pathPrefix":"/api/job-board-api"},"twin":{"id":"arbeitnow-feed","fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"vars":{"jobCount":{"paths":["data"],"format":"array_len"}},"requireVars":["jobCount"],"titleTemplate":"Arbeitnow Job Feed ({jobCount})","sections":[{"heading":"","arrayPath":"data","limit":50,"emptyText":"No open positions currently listed.","itemVars":{"jTitle":{"paths":["title"],"trim":true,"default":"Role"},"jUrl":{"paths":["url"],"requireHttps":true},"company":{"paths":["company_name"],"trim":true,"default":"-"},"loc":{"paths":["location"],"trim":true,"default":"-"},"wp":{"paths":["remote"],"format":"bool_map","trueValue":"Remote","falseValue":"On-site"},"roleCell":{"template":"[{jTitle}]({jUrl})","whenVars":["jUrl"],"fallbackVar":"jTitle"}},"collectLinkVars":["jUrl"],"columns":[{"header":"Role","template":"{roleCell}"},{"header":"Company","template":"{company}"},{"header":"Location","template":"{loc}"},{"header":"Workplace","template":"{wp}"}]}]}},{"match":{"hosts":["www.arbeitnow.com","arbeitnow.com"],"pathEquals":["/jobs","/jobs/"]},"twin":{"id":"arbeitnow-feed","fetchUrl":"https://www.arbeitnow.com/api/job-board-api","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"vars":{"jobCount":{"paths":["data"],"format":"array_len"}},"requireVars":["jobCount"],"titleTemplate":"Arbeitnow Job Feed ({jobCount})","sections":[{"heading":"","arrayPath":"data","limit":50,"emptyText":"No open positions currently listed.","itemVars":{"jTitle":{"paths":["title"],"trim":true,"default":"Role"},"jUrl":{"paths":["url"],"requireHttps":true},"company":{"paths":["company_name"],"trim":true,"default":"-"},"loc":{"paths":["location"],"trim":true,"default":"-"},"wp":{"paths":["remote"],"format":"bool_map","trueValue":"Remote","falseValue":"On-site"},"roleCell":{"template":"[{jTitle}]({jUrl})","whenVars":["jUrl"],"fallbackVar":"jTitle"}},"collectLinkVars":["jUrl"],"columns":[{"header":"Role","template":"{roleCell}"},{"header":"Company","template":"{company}"},{"header":"Location","template":"{loc}"},{"header":"Workplace","template":"{wp}"}]}]}},{"match":{"anyOf":[{"hosts":["remoteok.com"],"pathSegments":[]},{"hosts":["remoteok.com"],"pathSegments":["api"]},{"hosts":["remoteok.com"],"pathPrefix":"/remote-","pathSuffix":"-jobs","pathSegments":[{"param":"catTag","charset":"alnum_dash","stripPrefix":"remote-","stripSuffix":"-jobs","transform":"lower"}]},{"hosts":["remoteok.com"],"pathPrefix":"/remote-","pathSuffix":"-jobs/","pathSegments":[{"param":"catTag","charset":"alnum_dash","stripPrefix":"remote-","stripSuffix":"-jobs","transform":"lower"}]}]},"twin":{"id":"remoteok-feed","fetchUrl":"https://remoteok.com/api","kind":"json","accept":"application/json"},"extract":{"wrapRootArrayAs":"jobs","vars":{"rawCount":{"paths":["jobs"],"format":"array_len"},"dedupCount":{"default":"{dedupCount}"}},"requireVars":["rawCount"],"titleTemplate":"RemoteOK Remote Jobs ({dedupCount})","sections":[{"heading":"","arrayPath":"jobs","limit":50,"emptyText":"No open positions currently listed.","filter":{"requireField":"position","tagFilterParam":{"param":"catTag","skipIfEquals":"dev","tagsField":"tags"}},"itemVars":{"pos":{"paths":["position"],"trim":true,"default":"Role"},"jUrl":{"paths":["url"],"requireHttps":true},"company":{"paths":["company"],"trim":true,"default":"-"},"loc":{"paths":["location"],"trim":true,"default":"Remote"},"salMin":{"paths":["salary_min"],"excludeEquals":"0"},"salMax":{"paths":["salary_max"],"excludeEquals":"0"},"salRange":{"template":"${salMin}–${salMax}","whenVars":["salMin","salMax"]},"salMinOnly":{"template":"${salMin}","whenVars":["salMin"]},"sal":{"template":"{salRange}","whenVars":["salRange"],"fallbackVar":"salMinOnly","default":"-"},"roleCell":{"template":"[{pos}]({jUrl})","whenVars":["jUrl"],"fallbackVar":"pos"}},"collectLinkVars":["jUrl"],"columns":[{"header":"Role","template":"{roleCell}"},{"header":"Company","template":"{company}"},{"header":"Location","template":"{loc}"},{"header":"Salary","template":"{sal}"}]}]}}]},{"id":"public-share-links","name":"Public Share Links (Google Docs/Sheets, OneDrive, Dropbox, Box)","category":"commerce-social","description":"Extracts public Google Sheets via same-origin /gviz/tq?tqx=out:csv (avoiding 307 cross-domain /export redirects) and public Google Docs /pub, OneDrive /embed, Dropbox, and Box share links while strictly enforcing robots.txt.","domains":["docs.google.com","dropbox.com","www.dropbox.com","box.com","app.box.com","onedrive.live.com","1drv.ms"],"auth_mode":"pub","strict_robots":true,"min_interval_ms":1000,"exampleUrls":["https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit","https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/gviz/tq?tqx=out:csv","https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/htmlview"],"routes":[{"match":{"hosts":["docs.google.com"],"anyOf":[{"exactSegments":true,"pathSegments":["spreadsheets","d",{"param":"sheetId","charset":"slug","minLen":12,"maxLen":128,"reserved":["e"]}]},{"exactSegments":true,"pathSegments":["spreadsheets","d",{"param":"sheetId","charset":"slug","minLen":12,"maxLen":128,"reserved":["e"]},{"param":"view","allowValues":["edit","view","htmlview","preview","copy"]}]}]},"twin":{"fetchUrl":"https://docs.google.com/spreadsheets/d/{sheetId}/gviz/tq?tqx=out:csv","kind":"text","accept":"text/plain","maxBytes":2097152},"extract":{"textMode":"public_share_csv"}},{"match":{"hosts":["docs.google.com"],"exactSegments":true,"pathSegments":["spreadsheets","d",{"param":"sheetId","charset":"slug","minLen":12,"maxLen":128,"reserved":["e"]},"gviz","tq"],"queryParams":[{"name":"tqx","param":"tqx","charset":"url_seg","allowValues":["out:csv"]}]},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"text/plain","maxBytes":2097152},"extract":{"textMode":"public_share_csv"}}],"htmlRoutes":[{"id":"public-share-links","mode":"public_share_html","match":{"hosts":["docs.google.com","dropbox.com","www.dropbox.com","box.com","app.box.com","onedrive.live.com","1drv.ms"],"exactSegments":false}}]},{"id":"pubmed-pmc","name":"PubMed & PubMed Central (NCBI / Europe PMC)","category":"research-health","description":"Upgrades PubMed & PMC URLs to robots.txt-allowed Europe PMC REST JSON/JATS XML (with NCBI HTML fallback).","domains":["pubmed.ncbi.nlm.nih.gov","pmc.ncbi.nlm.nih.gov"],"exampleUrls":["https://pubmed.ncbi.nlm.nih.gov/31452104/","https://pmc.ncbi.nlm.nih.gov/articles/PMC7095418/"],"routes":[{"match":{"hosts":["pubmed.ncbi.nlm.nih.gov"],"exactSegments":true,"pathSegments":[{"param":"pmid","charset":"digits"}]},"twin":{"id":"pubmed-europepmc","fetchUrl":"https://www.ebi.ac.uk/europepmc/webservices/rest/search?query=EXT_ID:{pmid}%20AND%20SRC:MED&resultType=core&format=json","kind":"json","accept":"application/json"},"extract":{"rootPath":"resultList.result.0","requireFields":["title"],"vars":{"title":{"paths":["title"],"format":"strip_tags","stripSuffix":".","trim":true},"authorString":{"paths":["authorString"],"trim":true},"journalTitle":{"paths":["journalInfo.journal.title"]},"pubYear":{"paths":["pubYear"]},"journalFull":{"template":"{journalTitle} ({pubYear})","whenVars":["journalTitle","pubYear"],"fallbackVar":"journalTitle"},"doi":{"paths":["doi"]},"doiUrl":{"template":"https://doi.org/{doi}","whenVars":["doi"]},"pmcid":{"paths":["pmcid"]},"pmcUrl":{"template":"https://pmc.ncbi.nlm.nih.gov/articles/{pmcid}/","whenVars":["pmcid"]},"citedBy":{"paths":["citedByCount"],"format":"int_comma"},"abstractText":{"paths":["abstractText"],"format":"strip_tags"}},"titleTemplate":"{title}","authorVar":"authorString","publishedTimeVar":"pubYear","bullets":[{"label":"PMID","template":"`{pmid}`"},{"label":"Authors","template":"{authorString}","whenVar":"authorString"},{"label":"Journal","template":"{journalFull}","whenVar":"journalFull"},{"label":"DOI","template":"`{doi}`","whenVar":"doi"},{"label":"Full Text (PMC)","template":"[{pmcid}]({pmcUrl})","whenVar":"pmcid"},{"label":"Cited By","template":"{citedBy}","whenVar":"citedBy"}],"sections":[{"heading":"Abstract","textVar":"abstractText"}],"linksVars":["doiUrl","pmcUrl"]}},{"match":{"hosts":["pmc.ncbi.nlm.nih.gov"],"exactSegments":false,"pathSegments":["articles",{"param":"pmcid","charset":"pmc_id","transform":"upper"}]},"twin":{"id":"pmc-europepmc","fetchUrl":"https://www.ebi.ac.uk/europepmc/webservices/rest/{pmcid}/fullTextXML","kind":"text","accept":"application/xml"},"extract":{"xml":{"mode":"jats_article"}}}],"htmlRoutes":[{"match":{"anyOf":[{"hosts":["pubmed.ncbi.nlm.nih.gov"],"exactSegments":true,"pathSegments":[{"param":"pmid","charset":"digits"}]},{"hosts":["pmc.ncbi.nlm.nih.gov"],"exactSegments":false,"pathSegments":["articles",{"param":"pmcid","charset":"pmc_id","transform":"upper"}]}]},"mode":"dom","requireVars":["title","body"],"vars":{"title":{"cssText":["h1.heading-title","h1"]},"authors":{"cssAllText":{"selector":"a.full-name","limit":20,"dedupe":true,"join":", "},"limit":15},"authorsShort":{"cssAllText":{"selector":"a.full-name","limit":20,"dedupe":true,"join":", "},"limit":4},"doi":{"cssText":["span.citation-doi"]},"body":{"cssHtmlToMd":["article.article","div#abstract","div#eng-abstract","section.abstract"]}},"titleTemplate":"{title}","authorVar":"authorsShort","bullets":[{"label":"Authors","template":"{authors}","whenVar":"authors"},{"label":"Citation","template":"{doi}","whenVar":"doi"}],"bodyVar":"body","bodyFallbackHeading":"Abstract"}]},{"id":"pypi-project","name":"PyPI Python Package Index","category":"developer","description":"Extracts PyPI package install command, summary, and project README from pypi.org/project// (respecting robots.txt on /json).","domains":["pypi.org","www.pypi.org"],"exampleUrls":["https://pypi.org/project/httpx/"],"htmlRoutes":[{"match":{"exactSegments":false,"pathSegments":["project",{"param":"pkg","charset":"pkg"}]},"mode":"dom","vars":{"headerName":{"cssText":["h1.project-header__name","h1.package-header__name"]},"pipCmd":{"cssText":["#pip-command"]},"summary":{"cssText":["p.project-header__summary","p.package-description__summary"]},"readme":{"cssHtmlToMd":["#description","div.project-description"],"format":"strip_leading_h1"}},"requireVars":["headerName","readme"],"titleTemplate":"{headerName}","descriptionVar":"summary","introVar":"summary","bullets":[{"label":"Install","template":"`{pipCmd}`","whenVar":"pipCmd"}],"bodyVar":"readme"}]},{"id":"q4-ir","name":"Q4 Inc. Investor Relations Portals","category":"finance","description":"Extracts Q4 Investor Relations /feed/PressRelease.svc and /feed/Event.svc JSON endpoints plus HTML press release and event pages while rejecting Cloudflare challenges.","domains":["*.q4web.com","investors.braze.com"],"universalEngine":true,"auth_mode":"pub","strict_robots":true,"min_interval_ms":1000,"exampleUrls":["https://mtr.q4web.com/feed/PressRelease.svc/GetPressReleaseList?LanguageId=1&bodyType=0&pressReleaseDateFilter=3&pageSize=5&pageNumber=0","https://investors.braze.com/feed/Event.svc/GetEventList?apiKey=BF185719B0464B3AB809D2E68A89D240&LanguageId=1&eventDateFilter=3&pageSize=5&pageNumber=0"],"routes":[{"match":{"pathPrefix":"/feed/PressRelease.svc/","exactSegments":false},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"q4_ir_json"}},{"match":{"pathPrefix":"/feed/Event.svc/","exactSegments":false},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"q4_ir_json"}}],"htmlRoutes":[{"id":"q4-ir","match":{"exactSegments":false},"mode":"q4_ir_html"}]},{"id":"qbp-frame-brands","name":"Frame & Touring Bike Brands (Surly, Salsa, All-City)","category":"commerce-social","description":"Extracts public bicycle frame specifications, axle/tire clearance, and geometry tables from Surly, Salsa, and All-City public brand sites.","domains":["surlybikes.com","www.surlybikes.com","salsacycles.com","www.salsacycles.com","allcitycycles.com","www.allcitycycles.com"],"auth_mode":"html","min_interval_ms":1000,"exampleUrls":["https://surlybikes.com/collections/karate-monkey","https://www.salsacycles.com/products/fargo-32-steel-frameset"],"htmlRoutes":[{"id":"qbp-frame-brands","match":{"exactSegments":false},"mode":"qbp_frame_brands_html"}]},{"id":"race-results-pack","name":"Race Results Pack (Athlinks, Race Roster, ACTIVE)","category":"commerce-social","description":"Extracts endurance race events and results from Athlinks, Race Roster, and ACTIVE JSON-LD, hydration JSON, and results tables while strictly rejecting empty CSR SPA shells.","domains":["athlinks.com","www.athlinks.com","results.athlinks.com","raceroster.com","www.raceroster.com","results.raceroster.com","active.com","www.active.com","resultscui.active.com"],"universalEngine":false,"auth_mode":"html","exampleUrls":["https://www.active.com/baltimore-md/running/distance-running-races/9th-annual-homewood-holiday-5k-2026"],"htmlRoutes":[{"id":"race-results-pack","match":{"hosts":["athlinks.com","www.athlinks.com","results.athlinks.com","raceroster.com","www.raceroster.com","results.raceroster.com","active.com","www.active.com","resultscui.active.com"],"exactSegments":false},"mode":"race_results_pack_html"}]},{"id":"rdap","name":"RDAP (Registration Data Access Protocol)","category":"developer","description":"Universal RFC 9083 RDAP JSON extractor for domain, IP, autnum, and entity lookups across RIRs/registries plus IANA RDAP bootstrap registries.","domains":["rdap.verisign.com","rdap.arin.net","rdap.apnic.net","rdap.db.ripe.net","rdap.ripe.net","rdap.lacnic.net","rdap.afrinic.net","data.iana.org","rdap.org"],"universalEngine":true,"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://rdap.verisign.com/com/v1/domain/example.com","https://rdap.arin.net/registry/autnum/13335","https://rdap.apnic.net/ip/1.1.1.1","https://rdap.db.ripe.net/ip/193.0.0.193","https://data.iana.org/rdap/dns.json"],"routes":[{"match":{"hosts":["data.iana.org"],"exactSegments":false,"pathPrefix":"/rdap/","pathSuffix":".json"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"rdap_bootstrap_json"}},{"match":{"hosts":["rdap.verisign.com","rdap.arin.net","rdap.apnic.net","rdap.db.ripe.net","rdap.ripe.net","rdap.lacnic.net","rdap.afrinic.net","rdap.org","rdap.*","*.rdap.org","pubapi.registry.google"],"exactSegments":false,"anyOf":[{"pathPrefix":"/domain/"},{"pathPrefix":"/ip/"},{"pathPrefix":"/autnum/"},{"pathPrefix":"/entity/"},{"pathContainsSegment":"domain"},{"pathContainsSegment":"ip"},{"pathContainsSegment":"autnum"},{"pathContainsSegment":"entity"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/rdap+json, application/json","maxBytes":1048576},"extract":{"jsonMode":"rdap_json"}},{"match":{"excludeHosts":["data.iana.org"],"exactSegments":false,"pathPrefix":"/rdap/","anyOf":[{"pathContainsSegment":"domain"},{"pathContainsSegment":"ip"},{"pathContainsSegment":"autnum"},{"pathContainsSegment":"entity"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/rdap+json, application/json","maxBytes":1048576},"extract":{"jsonMode":"rdap_json"}}]},{"id":"readthedocs-sphinx","name":"Read the Docs & Sphinx Documentation","category":"developer","description":"Universal HTML extractor for Sphinx and Read the Docs documentation sites (requests.readthedocs.io, docs.python.org, and Sphinx-themed portals).","domains":["docs.python.org","numpy.org","matplotlib.org"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://numpy.org/doc/stable/user/absolute_beginners.html","https://docs.python.org/3/library/json.html"],"htmlRoutes":[{"id":"readthedocs-sphinx","match":{"exactSegments":false},"mode":"readthedocs_sphinx_html"}]},{"id":"rebuy-searchanise","name":"Rebuy & Searchanise Storefront APIs","category":"commerce-social","description":"Page-key adapter for Rebuy recommendation APIs and Searchanise searchserverapi.com JSON results; companion HTML mode yields so shopify_html is never preempted.","domains":["rebuyengine.com","www.rebuyengine.com","searchserverapi.com","www.searchserverapi.com"],"universalEngine":true,"auth_mode":"page-key","requires_page_key_opt_in":true,"exampleUrls":["https://www.searchserverapi.com/getresults?apiKey=1Q7P8A7s4h&q=&output=json&maxResults=3"],"routes":[{"match":{"anyOf":[{"hosts":["rebuyengine.com","www.rebuyengine.com"],"pathPrefix":"/api/v1/"},{"hosts":["searchserverapi.com","www.searchserverapi.com"],"pathEquals":["/getresults","/getwidgets"]}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152,"requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"jsonMode":"rebuy_searchanise_json"}}],"htmlRoutes":[{"id":"rebuy-searchanise","match":{"exactSegments":false},"mode":"rebuy_searchanise_html"}]},{"id":"recharge-bold-subscriptions","name":"Recharge & Bold Subscriptions","category":"commerce-social","description":"Extracts product and recurring selling-plan subscription metadata from storefronts powered by Recharge or Bold Subscriptions; yields on non-subscription PDPs so shopify_html is not preempted.","domains":["us.whogivesacrap.org"],"universalEngine":true,"auth_mode":"html","exampleUrls":["https://us.whogivesacrap.org/products/100-recycled-toilet-paper-jumbo-rolls"],"htmlRoutes":[{"id":"recharge-bold-subscriptions","match":{"exactSegments":false},"mode":"recharge_bold_subscriptions_html"}]},{"id":"recreation-gov-ridb","name":"Recreation.gov & RIDB API","category":"public-records","description":"Recreation Information Database (RIDB) v1 API (apikey header) with Recreation.gov Campground JSON-LD / SSR HTML fallback and strict robots politeness.","domains":["ridb.recreation.gov","www.recreation.gov","recreation.gov"],"auth_mode":"key","strict_robots":true,"min_interval_ms":10000,"exampleUrls":["https://www.recreation.gov/camping/campgrounds/232447","https://ridb.recreation.gov/api/v1/facilities/232447"],"routes":[{"match":{"hosts":["ridb.recreation.gov"],"pathPrefix":"/api/v1/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":4194304},"extract":{"jsonMode":"ridb_json"}},{"match":{"hosts":["www.recreation.gov","recreation.gov"],"exactSegments":true,"pathSegments":["camping","campgrounds",{"param":"facilityId","charset":"digits","minLen":1,"maxLen":12}]},"twin":{"fetchUrl":"https://ridb.recreation.gov/api/v1/facilities/{facilityId}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"ridb_json"}}],"htmlRoutes":[{"id":"recreation-gov-ridb","match":{"hosts":["www.recreation.gov","recreation.gov"],"exactSegments":false},"mode":"recreation_gov_html"}]},{"id":"reddit-thread","name":"Reddit Threads & Comments","category":"commerce-social","description":"Extracts shreddit-post prose, subreddit/author/score metadata, and nested shreddit-comment trees.","domains":["reddit.com","*.reddit.com"],"exampleUrls":["https://www.reddit.com/r/golang/comments/1abc123/single_binary_deployments/"],"htmlRoutes":[{"id":"reddit-thread","match":{"pathContainsSegment":"comments"},"mode":"reddit_shreddit"}]},{"id":"regulations-gov","name":"Regulations.gov Federal Rulemaking","category":"public-records","description":"Official api.regulations.gov v4 JSON:API adapter for federal rulemaking documents, dockets, and public comments with HTML fallback.","domains":["regulations.gov","www.regulations.gov","api.regulations.gov"],"auth_mode":"key","exampleUrls":["https://api.regulations.gov/v4/documents/FTC-2023-0007-0001","https://api.regulations.gov/v4/dockets/FTC-2023-0007","https://www.regulations.gov/document/FTC-2023-0007-0001"],"routes":[{"match":{"hosts":["api.regulations.gov"],"pathPrefix":"/v4/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":4194304},"extract":{"jsonMode":"regulations_gov_json"}},{"match":{"hosts":["regulations.gov","www.regulations.gov"],"exactSegments":false,"pathSegments":["document",{"param":"docId","charset":"alnum_dash","minLen":4,"maxLen":80}]},"twin":{"fetchUrl":"https://api.regulations.gov/v4/documents/{docId}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":4194304},"extract":{"jsonMode":"regulations_gov_json"}},{"match":{"hosts":["regulations.gov","www.regulations.gov"],"exactSegments":false,"pathSegments":["docket",{"param":"docketId","charset":"alnum_dash","minLen":4,"maxLen":80}]},"twin":{"fetchUrl":"https://api.regulations.gov/v4/dockets/{docketId}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":4194304},"extract":{"jsonMode":"regulations_gov_json"}},{"match":{"hosts":["regulations.gov","www.regulations.gov"],"exactSegments":false,"pathSegments":["comment",{"param":"commentId","charset":"alnum_dash","minLen":4,"maxLen":80}]},"twin":{"fetchUrl":"https://api.regulations.gov/v4/comments/{commentId}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":4194304},"extract":{"jsonMode":"regulations_gov_json"}}],"htmlRoutes":[{"id":"regulations-gov","match":{"hosts":["regulations.gov","www.regulations.gov"],"exactSegments":false},"mode":"regulations_gov_html"}]},{"id":"repology","name":"Repology Package Version Matrix","category":"developer","description":"Extracts cross-distribution package versions from Repology API v1 and project HTML pages, prioritizing status == newest rows.","domains":["repology.org"],"auth_mode":"pub","exampleUrls":["https://repology.org/api/v1/project/python","https://repology.org/project/python/versions"],"routes":[{"match":{"hosts":["repology.org"],"pathPrefix":"/api/v1/project/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"repology_json"}},{"match":{"hosts":["repology.org"],"exactSegments":false,"pathSegments":["project",{"param":"project","charset":"pkg","minLen":1,"maxLen":160}]},"twin":{"fetchUrl":"https://repology.org/api/v1/project/{project}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"repology_json"}}],"htmlRoutes":[{"id":"repology","match":{"hosts":["repology.org"],"exactSegments":false},"mode":"repology_html"}]},{"id":"research-repo-pack","name":"Open Research Repositories (Zenodo, Figshare, Dryad, OSF)","category":"research-health","description":"Extracts open datasets and research artifacts from Zenodo (/records HTML, direct /api/records), Figshare (API + /articles upgrade), Dryad (API + /dataset HTML), and OSF (HTML + direct api.osf.io) while honoring robots.txt disallows.","domains":["zenodo.org","www.zenodo.org","api.figshare.com","figshare.com","www.figshare.com","datadryad.org","www.datadryad.org","api.osf.io","osf.io","www.osf.io"],"auth_mode":"pub","min_interval_ms":5000,"strict_robots":true,"exampleUrls":["https://zenodo.org/records/24485086","https://api.figshare.com/v2/articles/35148283","https://datadryad.org/api/v2/datasets/doi%3A10.5061%2Fdryad.7rh4625","https://datadryad.org/dataset/doi:10.5061/dryad.7rh4625"],"routes":[{"match":{"hosts":["zenodo.org","www.zenodo.org"],"pathPrefix":"/api/records/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"research_repo_pack_json"}},{"match":{"hosts":["api.figshare.com"],"pathPrefix":"/v2/articles/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"research_repo_pack_json"}},{"match":{"hosts":["figshare.com","www.figshare.com"],"pathPrefix":"/articles/","scanSegment":{"scanLast":true,"param":"articleId","charset":"digits","minLen":4,"maxLen":16}},"twin":{"fetchUrl":"https://api.figshare.com/v2/articles/{articleId}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"research_repo_pack_json"}},{"match":{"hosts":["datadryad.org","www.datadryad.org"],"pathPrefix":"/api/v2/datasets/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"research_repo_pack_json"}},{"match":{"hosts":["api.osf.io"],"pathPrefix":"/v2/nodes/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"research_repo_pack_json"}}],"htmlRoutes":[{"id":"research-repo-pack","match":{"hosts":["zenodo.org","www.zenodo.org","figshare.com","www.figshare.com","datadryad.org","www.datadryad.org","osf.io","www.osf.io"],"exactSegments":false},"mode":"research_repo_pack_html"}]},{"id":"reverb","name":"Reverb Musical Instruments Marketplace","category":"commerce-social","description":"Extracts Reverb musical instrument listings and catalog search results via api.reverb.com HAL+JSON endpoints with Accept-Version: 3.0.","domains":["reverb.com","www.reverb.com","api.reverb.com"],"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://reverb.com/item/36356670-fender-stratocaster-knob-set-black","https://api.reverb.com/api/listings/36356670","https://api.reverb.com/api/listings?query=fender+stratocaster&per_page=2"],"routes":[{"match":{"hosts":["reverb.com","www.reverb.com"],"optionalLeadingLocale":true,"exactSegments":true,"pathSegments":["item",{"param":"listingId","charset":"leading_digits_slug","transform":"leading_digits","minLen":1,"maxLen":220}]},"twin":{"fetchUrl":"https://api.reverb.com/api/listings/{listingId}","kind":"json","accept":"application/hal+json","headers":{"Accept-Version":"3.0"},"maxBytes":2097152},"extract":{"jsonMode":"reverb_listing_json"}},{"match":{"hosts":["api.reverb.com"],"exactSegments":true,"pathSegments":["api","listings",{"param":"listingId","charset":"digits","minLen":1,"maxLen":24}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/hal+json","headers":{"Accept-Version":"3.0"},"maxBytes":2097152},"extract":{"jsonMode":"reverb_listing_json"}},{"match":{"hosts":["api.reverb.com"],"pathEquals":["/api/listings"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/hal+json","headers":{"Accept-Version":"3.0"},"maxBytes":2097152},"extract":{"jsonMode":"reverb_search_json"}}]},{"id":"rippling","name":"Rippling ATS Career Boards","category":"jobs","description":"Upgrades ats.rippling.com/[locale/]/jobs to api.rippling.com (merging multi-location rows by uuid) and extracts __NEXT_DATA__ jobPost on detail pages.","domains":["ats.rippling.com"],"exampleUrls":["https://ats.rippling.com/rippling/jobs","https://ats.rippling.com/rippling/jobs/96601a74-e7b6-469d-8c69-6fdfd1c83bc0"],"match":{"optionalLeadingLocale":true,"pathSegments":[{"param":"org","charset":"slug","maxLen":80},{"param":"jobsLit","charset":"alnum","allowValues":["jobs"],"optional":true}]},"twin":{"id":"rippling-board","fetchUrl":"https://api.rippling.com/platform/api/ats/v1/board/{org}/jobs","kind":"json","accept":"application/json"},"extract":{"wrapRootArrayAs":"results","vars":{"rawCount":{"paths":["results"],"format":"array_len"},"dedupCount":{"default":"{dedupCount}"}},"requireVars":["rawCount"],"titleTemplate":"{org} — Rippling Job Board ({dedupCount} open roles)","sections":[{"heading":"","arrayPath":"results","limit":100,"linkScanLimit":2000,"emptyText":"No open positions currently listed.","dedupeBy":{"keyPaths":["uuid","id"],"mergeTextPaths":["workLocation.label","workLocation"],"mergeTargetVar":"_mergedLocs","mergeSep":"; ","mergeLimit":4},"requireItemVar":"jName","itemVars":{"uuid":{"paths":["uuid","id"],"trim":true},"jName":{"paths":["name","title"],"trim":true},"rawUrl":{"paths":["url"],"requireHttps":true},"jUrl":{"template":"{rawUrl}","whenVars":["rawUrl"],"fallbackTemplate":"https://ats.rippling.com/{org}/jobs/{uuid}"},"dept":{"paths":["department.label","department"],"trim":true,"default":"-"},"locs":{"paths":["_mergedLocs"],"trim":true,"default":"-"}},"collectLinkVars":["jUrl"],"columns":[{"header":"Role","template":"[{jName}]({jUrl})"},{"header":"Department","template":"{dept}"},{"header":"Locations","template":"{locs}"}]}]},"htmlRoutes":[{"id":"rippling-job","mode":"embedded_json","scriptId":"__NEXT_DATA__","match":{"hosts":["ats.rippling.com"]},"extract":{"vars":{"jobTitle":{"paths":["props.pageProps.apiData.jobPost.name","props.pageProps.apiData.jobPost.title","props.pageProps.jobPost.name","props.pageProps.jobPost.title"],"trim":true},"company":{"paths":["props.pageProps.apiData.jobPost.companyName","props.pageProps.jobPost.companyName"],"trim":true,"default":"Company"},"descDirect":{"paths":["props.pageProps.apiData.jobPost.description","props.pageProps.jobPost.description"],"format":"html_to_md"},"descCompany":{"paths":["props.pageProps.apiData.jobPost.description.company","props.pageProps.jobPost.description.company"],"format":"html_to_md"},"descRole":{"paths":["props.pageProps.apiData.jobPost.description.role","props.pageProps.jobPost.description.role"],"format":"html_to_md"},"descReqs":{"paths":["props.pageProps.apiData.jobPost.description.requirements","props.pageProps.jobPost.description.requirements"],"format":"html_to_md"},"descBenefits":{"paths":["props.pageProps.apiData.jobPost.description.benefits","props.pageProps.jobPost.description.benefits"],"format":"html_to_md"},"hasAnyBody":{"template":"ok","whenAnyVars":["descDirect","descCompany","descRole","descReqs","descBenefits"]}},"requireVars":["jobTitle","hasAnyBody"],"titleTemplate":"{jobTitle} @ {company}","bodyVar":"descDirect","sections":[{"heading":"","unlessVar":"descDirect","textVar":"descCompany"},{"heading":"","unlessVar":"descDirect","textVar":"descRole"},{"heading":"","unlessVar":"descDirect","textVar":"descReqs"},{"heading":"","unlessVar":"descDirect","textVar":"descBenefits"}]}}]},{"id":"ror","name":"Research Organization Registry (ROR)","category":"research-health","description":"Extracts Research Organization Registry (ROR) v2 organization records, domains, locations, and external IDs (GRID, ISNI, Wikidata) with Vercel challenge HTML guard.","domains":["api.ror.org","ror.org","www.ror.org"],"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://api.ror.org/v2/organizations/03yrm5c26","https://api.ror.org/v2/organizations?query=mit","https://ror.org/03yrm5c26"],"routes":[{"match":{"hosts":["api.ror.org"],"pathPrefix":"/v2/organizations"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"ror_json"}},{"match":{"hosts":["ror.org","www.ror.org"],"exactSegments":true,"pathSegments":[{"param":"rorId","charset":"alnum","reserved":["community","resources","changelog"],"minLen":9,"maxLen":9,"transform":"lower"}]},"twin":{"fetchUrl":"https://api.ror.org/v2/organizations/{rorId}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"ror_json"}}],"htmlRoutes":[{"id":"ror","match":{"hosts":["ror.org","www.ror.org"],"exactSegments":false},"mode":"ror_html"}]},{"id":"rubygems","name":"RubyGems Registry","category":"developer","description":"Upgrades rubygems.org gem pages to /api/v1/gems/.json metadata.","domains":["rubygems.org","www.rubygems.org"],"exampleUrls":["https://rubygems.org/gems/rails"],"match":{"exactSegments":false,"pathSegments":["gems",{"param":"gem","charset":"pkg","minLen":1,"maxLen":80}]},"twin":{"fetchUrl":"https://rubygems.org/api/v1/gems/{gem}.json","kind":"json","accept":"application/json"},"extract":{"requireFields":["name"],"vars":{"name":{"paths":["name"]},"version":{"paths":["version"]},"info":{"paths":["info"],"trim":true},"infoShort":{"paths":["info"],"trim":true,"sliceMax":260},"licenses":{"paths":["licenses"],"join":", "},"authors":{"paths":["authors"]},"repo":{"paths":["source_code_uri","homepage_uri"]},"docs":{"paths":["documentation_uri"]}},"titleTemplate":"{name} {version} (RubyGem)","titleWhenVar":"version","titleFallbackTemplate":"{name} (RubyGem)","descriptionVar":"infoShort","authorVar":"authors","introVar":"info","bullets":[{"label":"Install","template":"`gem install {name}`"},{"label":"Version","template":"`{version}`","whenVar":"version"},{"label":"License","template":"{licenses}","whenVar":"licenses"},{"label":"Authors","template":"{authors}","whenVar":"authors"},{"label":"Documentation","template":"{docs}","whenVar":"docs"},{"label":"Repository","template":"{repo}","whenVar":"repo"}]}},{"id":"rumble-odysee","name":"Rumble & Odysee Video","category":"commerce-social","description":"Extracts Odysee video claim oEmbed and LBRY JSON-RPC metadata plus Rumble/Odysee HTML without hitting disallowed rumble.com/api/* routes.","domains":["rumble.com","www.rumble.com","odysee.com","www.odysee.com","api.na-backend.odysee.com"],"auth_mode":"pub","exampleUrls":["https://odysee.com/@Odysee:8/channel-roundup-may-2026:e","https://odysee.com/$/oembed?url=https%3A%2F%2Fodysee.com%2F%40Odysee%3A8%2Fchannel-roundup-may-2026%3Ae&format=json","https://www.rumble.com/c/Rumble"],"routes":[{"match":{"hosts":["odysee.com","www.odysee.com"],"pathEquals":["/$/oembed"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"rumble_odysee_json"}},{"match":{"hosts":["odysee.com","www.odysee.com"],"exactSegments":true,"pathSegments":[{"param":"chan","charset":"at_handle","minLen":2,"maxLen":100},{"param":"claimSlug","charset":"url_seg","minLen":2,"maxLen":180}]},"twin":{"fetchUrl":"https://{host}/$/oembed?url=https%3A%2F%2F{host}%2F{chan}%2F{claimSlug}&format=json","kind":"json","accept":"application/json"},"extract":{"jsonMode":"rumble_odysee_json"}},{"match":{"hosts":["api.na-backend.odysee.com"],"pathEquals":["/api/v1/proxy"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"rumble_odysee_json"}}],"htmlRoutes":[{"id":"rumble-odysee","match":{"exactSegments":false},"mode":"rumble_odysee_html"}]},{"id":"runsignup","name":"RunSignup Races & Events","category":"commerce-social","description":"Extracts RunSignup race listings and single race event details from public /Rest/races and /Rest/race/{raceId} JSON APIs plus /Race/ SportsEvent HTML fallback.","domains":["runsignup.com","www.runsignup.com"],"universalEngine":false,"auth_mode":"pub","exampleUrls":["https://runsignup.com/Rest/races?format=json&events=T&page=1&results_per_page=2","https://runsignup.com/Rest/race/68640?format=json","https://runsignup.com/Race/MI/PortHuron/BaconandBubbles5k1Mile"],"routes":[{"match":{"hosts":["runsignup.com","www.runsignup.com"],"exactSegments":true,"pathSegments":["Rest","races"]},"twin":{"fetchUrl":"{requestUrl}","setQueryParams":{"format":"json"},"kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"runsignup_json"}},{"match":{"hosts":["runsignup.com","www.runsignup.com"],"exactSegments":true,"pathSegments":["Rest","race",{"param":"raceId","charset":"digits","minLen":1,"maxLen":16}]},"twin":{"fetchUrl":"{requestUrl}","setQueryParams":{"format":"json"},"kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"runsignup_json"}}],"htmlRoutes":[{"id":"runsignup","match":{"hosts":["runsignup.com","www.runsignup.com"],"pathPrefix":"/Race/","exactSegments":false},"mode":"runsignup_html"}]},{"id":"rxnorm-rxnav","name":"NLM RxNorm / RxNav","category":"research-health","description":"National Library of Medicine RxNav REST JSON API adapter for RxCUI lookups, concept properties, drug groups, and approximate term matches.","domains":["rxnav.nlm.nih.gov"],"auth_mode":"pub","exampleUrls":["https://rxnav.nlm.nih.gov/REST/rxcui.json?name=lipitor","https://rxnav.nlm.nih.gov/REST/rxcui/153165/properties.json","https://rxnav.nlm.nih.gov/REST/drugs.json?name=acetaminophen"],"routes":[{"match":{"pathPrefix":"/REST/","pathSuffix":".json"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"rxnorm_json"}}]},{"id":"saleor","name":"Saleor Storefront & GraphQL API","category":"commerce-social","description":"Extracts Saleor Storefront bounded /graphql/ product queries (including EditorJS descriptions) and post-HTML JSON-LD/Microdata product pages.","domains":["demo.saleor.io","storefront1.saleor.cloud"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://storefront1.saleor.cloud/graphql/"],"routes":[{"match":{"pathEquals":["/graphql","/graphql/"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","method":"POST","contentType":"application/json","requestBody":"{\"query\":\"query EdgeFetchProducts { products(first: 25, channel: \\\"default\\\") { pageInfo { hasNextPage endCursor } edges { node { id slug name description category { name slug } thumbnail { url alt } pricing { priceRange { start { gross { amount currency } } stop { gross { amount currency } } } } variants { id name sku quantityAvailable pricing { price { gross { amount currency } } } } } } } }\"}"},"extract":{"commerceMode":"saleor_graphql"}}],"htmlRoutes":[{"id":"saleor","match":{"exactSegments":false},"mode":"saleor_html"}]},{"id":"salesforce-knowledge","name":"Salesforce Knowledge (Experience Cloud)","category":"developer","description":"Extracts public Salesforce Knowledge and Experience Cloud articles when SSR/hydrated DOM or TechArticle JSON-LD is present; rejects unhydrated Aura error shells and login redirects.","domains":["help.salesforce.com","help.mulesoft.com"],"universalEngine":true,"auth_mode":"html","exampleUrls":["https://help.salesforce.com/s/articleView?language=en_US&id=000391748&type=1"],"htmlRoutes":[{"id":"salesforce-knowledge","match":{"exactSegments":false},"mode":"salesforce_knowledge_html"}]},{"id":"sam-gov","name":"SAM.gov Opportunities & Entities","category":"public-records","description":"Extracts SAM.gov contract opportunities and entity registrations via official SAM.gov v2/v3 APIs (excluding /contract-awards handled by fpds-sam-contract-awards) with HTML fallback.","domains":["sam.gov","www.sam.gov","api.sam.gov"],"auth_mode":"key","exampleUrls":["https://sam.gov/contracting","https://sam.gov/help","https://api.sam.gov/opportunities/v2/search?limit=1"],"routes":[{"match":{"hosts":["sam.gov","www.sam.gov"],"exactSegments":false,"pathSegments":["opp",{"param":"noticeId","charset":"url_seg","minLen":4,"maxLen":120},"view"]},"twin":{"fetchUrl":"https://api.sam.gov/opportunities/v2/search?noticeid={noticeId}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"sam_gov_json"}},{"match":{"hosts":["api.sam.gov"],"pathPrefix":"/opportunities/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"sam_gov_json"}},{"match":{"hosts":["api.sam.gov"],"pathPrefix":"/prod/opportunities/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"sam_gov_json"}},{"match":{"hosts":["api.sam.gov"],"pathPrefix":"/entity-information/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"sam_gov_json"}},{"match":{"hosts":["api.sam.gov"],"pathPrefix":"/prod/entity-information/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"sam_gov_json"}}],"htmlRoutes":[{"id":"sam-gov","match":{"hosts":["sam.gov","www.sam.gov"],"exactSegments":false},"mode":"sam_gov_html"}]},{"id":"sap-commerce-occ","name":"SAP Commerce Cloud (OCC v2)","category":"commerce-social","description":"Extracts SAP Commerce Cloud OCC v2 /rest/v2 product and search JSON endpoints plus Spartacus storefront HTML/companion twins.","domains":["www.kay.com"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://www.kay.com/kay-labgrown-diamonds-large-small-link-bracelet-14-ct-tw-sterling-silver-8/p/V-238867701"],"routes":[{"match":{"pathSegments":["occ","v2",{"param":"site","charset":"slug","minLen":2,"maxLen":64},"products","search"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"commerceMode":"sap_occ_product"}},{"match":{"pathSegments":["occ","v2",{"param":"site","charset":"slug","minLen":2,"maxLen":64},"products",{"param":"code","charset":"pkg","reserved":["search"],"minLen":1,"maxLen":120}]},"twin":{"fetchUrl":"{requestUrl}","defaultQueryParams":{"fields":"FULL"},"kind":"json","accept":"application/json"},"extract":{"commerceMode":"sap_occ_product"}},{"match":{"pathSegments":["rest","v2",{"param":"site","charset":"slug","minLen":2,"maxLen":64},"products",{"param":"code","charset":"pkg","reserved":["search"],"minLen":1,"maxLen":120}]},"twin":{"fetchUrl":"{requestUrl}","defaultQueryParams":{"fields":"FULL"},"kind":"json","accept":"application/json"},"extract":{"commerceMode":"sap_occ_product"}}],"htmlRoutes":[{"id":"sap-commerce-occ","match":{"exactSegments":false},"mode":"sap_occ_html"}]},{"id":"sap-rmk-jibe","name":"SAP SuccessFactors RMK & Jibe Enterprise Career Feeds","category":"jobs","description":"Formats Jibe /api/jobs JSON feeds and SAP SuccessFactors Recruiting Marketing (RMK) /sitemap.xml RSS job feeds.","domains":["careers.*.com","jobs.*.com"],"universalEngine":true,"exampleUrls":["https://careers.rivian.com/api/jobs?page=1&limit=25","https://jobs.eastman.com/sitemap.xml"],"routes":[{"match":{"pathEquals":["/api/jobs"],"excludeHosts":["jobs.dover.com","app.dover.com","*.dover.com","jobs.mchire.com","jobs.crelate.com","jobs.manatal.com","jobs.chronicle.com"]},"twin":{"id":"jibe-careers","fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"requireArrayItemField":{"arrayPath":"jobs","field":"data"},"vars":{"jobCount":{"paths":["jobs"],"format":"array_len"},"total":{"paths":["totalCount"],"fallbackTemplate":"{jobCount}"}},"requireVars":["jobCount"],"titleTemplate":"{host} — Jibe Career Feed ({jobCount} of {total} open roles)","sections":[{"heading":"","arrayPath":"jobs","limit":80,"emptyText":"No open positions currently listed.","itemVars":{"jTitle":{"paths":["data.title","title"],"trim":true,"default":"Role"},"reqId":{"paths":["data.req_id","data.slug","req_id","slug"],"trim":true},"reqCell":{"template":"`{reqId}`","whenVars":["reqId"],"default":"-"},"catArr":{"paths":["data.categories"],"subField":"name","join":", "},"catStr":{"paths":["data.category","category"],"trim":true},"cat":{"template":"{catArr}","whenVars":["catArr"],"fallbackVar":"catStr","default":"-"},"fullLoc":{"paths":["data.full_location","full_location"],"trim":true},"city":{"paths":["data.city","city"],"trim":true},"state":{"paths":["data.state","state"],"trim":true},"country":{"paths":["data.country","country"],"trim":true},"csc3":{"template":"{city}, {state}, {country}","whenVars":["city","state","country"]},"csc2a":{"template":"{city}, {state}","whenVars":["city","state"]},"csc2b":{"template":"{city}, {country}","whenVars":["city","country"]},"csc1":{"paths":["data.city","data.state","data.country"],"trim":true},"locSub1":{"template":"{csc3}","whenVars":["csc3"],"fallbackVar":"csc2a"},"locSub2":{"template":"{locSub1}","whenVars":["locSub1"],"fallbackVar":"csc2b"},"locSub3":{"template":"{locSub2}","whenVars":["locSub2"],"fallbackVar":"csc1"},"loc":{"template":"{fullLoc}","whenVars":["fullLoc"],"fallbackVar":"locSub3","default":"-"},"canonUrl":{"paths":["data.meta_data.canonical_url"],"requireHttps":true},"appUrl":{"paths":["data.apply_url","apply_url"],"requireHttps":true},"finalUrl":{"template":"{canonUrl}","whenVars":["canonUrl"],"fallbackVar":"appUrl"},"roleCell":{"template":"[{jTitle}]({finalUrl})","whenVars":["finalUrl"],"fallbackVar":"jTitle"}},"collectLinkVars":["finalUrl"],"columns":[{"header":"Role","template":"{roleCell}"},{"header":"Req ID","template":"{reqCell}"},{"header":"Category","template":"{cat}"},{"header":"Location","template":"{loc}"}]}]}},{"match":{"pathSuffix":"sitemap.xml","excludeHosts":["jobs.dover.com","app.dover.com","*.dover.com","jobs.mchire.com","jobs.crelate.com","jobs.manatal.com","jobs.chronicle.com"]},"twin":{"id":"sap-rmk-jibe","fetchUrl":"{requestUrl}","kind":"text","accept":"application/xml"},"extract":{"xml":{"mode":"items_table","requireAnyTags":["g:location","g:employer"],"itemTag":"item","firstItemVars":{"employer":["g:employer"]},"titleTemplate":"{employer} — SAP RMK Job Feed ({itemCount} open roles)","limit":100,"collectLinkVar":"jLink","itemVars":{"jTitle":{"tags":["title"],"default":"Role"},"jLink":{"tags":["link"]},"jId":{"tags":["g:id"],"default":"-"},"loc":{"tags":["g:location"],"default":"-"}},"columns":[{"header":"Role","template":"[{jTitle}]({jLink})"},{"header":"Req ID","template":"{jId}"},{"header":"Location","template":"{loc}"}]}}}],"htmlRoutes":[{"id":"sap-rmk-jibe","mode":"xml_items_table","match":{"pathSuffix":"sitemap.xml","excludeHosts":["jobs.dover.com","app.dover.com","*.dover.com","jobs.mchire.com","jobs.crelate.com","jobs.manatal.com","jobs.chronicle.com"]},"xml":{"mode":"items_table","requireAnyTags":["g:location","g:employer"],"itemTag":"item","firstItemVars":{"employer":["g:employer"]},"titleTemplate":"{employer} — SAP RMK Job Feed ({itemCount} open roles)","limit":100,"collectLinkVar":"jLink","itemVars":{"jTitle":{"tags":["title"],"default":"Role"},"jLink":{"tags":["link"]},"jId":{"tags":["g:id"],"default":"-"},"loc":{"tags":["g:location"],"default":"-"}},"columns":[{"header":"Role","template":"[{jTitle}]({jLink})"},{"header":"Req ID","template":"{jId}"},{"header":"Location","template":"{loc}"}]}}]},{"id":"sba-dsbs-loans","name":"SBA DSBS & 7(a)/504 Loan Datasets (DKAN)","category":"finance","description":"Extracts data.sba.gov DKAN 7(a)/504 loan datasets and dataset pages while rejecting empty React SPA shells on search.certifications.sba.gov.","domains":["data.sba.gov","search.certifications.sba.gov","dsbs.sba.gov"],"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://data.sba.gov/api/1/metastore/schemas/dataset/items/SBA-OCA-CKAN-002","https://data.sba.gov/dataset/sba-foia-quarterly-reports"],"routes":[{"match":{"hosts":["data.sba.gov"],"pathPrefix":"/api/1/metastore/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"sba_dkan_json"}},{"match":{"hosts":["data.sba.gov"],"pathPrefix":"/api/1/datastore/query/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"sba_dkan_json"}}],"htmlRoutes":[{"id":"sba-dsbs-loans","match":{"exactSegments":false},"mode":"sba_dsbs_loans_html"}]},{"id":"schema-course","name":"Schema.org Course & Educational Program","category":"public-records","description":"Universal Schema.org extractor for Course, CourseInstance, and EducationalOccupationalProgram JSON-LD running before generic schema_org fallback.","domains":["pll.harvard.edu"],"universalEngine":true,"auth_mode":"html","strict_robots":true,"exampleUrls":["https://pll.harvard.edu/course/cs50-introduction-computer-science"],"htmlRoutes":[{"id":"schema-course","match":{"exactSegments":false},"mode":"schema_course_html"}]},{"id":"schema-dataset","name":"Schema.org Dataset & DataCatalog","category":"research-health","description":"Universal Schema.org extractor for Dataset and DataCatalog JSON-LD including DataDownload distributions, license, creator, and temporal/spatial coverage.","domains":["registry.opendata.aws"],"universalEngine":true,"auth_mode":"html","strict_robots":true,"exampleUrls":["https://registry.opendata.aws/noaa-goes/"],"htmlRoutes":[{"id":"schema-dataset","match":{"exactSegments":false},"mode":"schema_dataset_html"}]},{"id":"schema-event","name":"Schema.org Event (Universal)","category":"commerce-social","description":"Universal Schema.org Event JSON-LD extractor for venues, parks departments, clubs, and event calendars: name, start/end, venue and address, organizer, performer, offers/price, status, and attendance mode. Lists every Event on series and calendar pages while yielding on dedicated ticketing/race platforms.","domains":["neworleanscitypark.org","events.stanford.edu","calendar.mit.edu"],"universalEngine":true,"auth_mode":"html","strict_robots":true,"exampleUrls":["https://neworleanscitypark.org/series/crescent-city-farmers-market-2/","https://events.stanford.edu/"],"htmlRoutes":[{"id":"schema-event","match":{"exactSegments":false,"excludeHosts":["eventbrite.com","www.eventbrite.com","meetup.com","www.meetup.com","lu.ma","www.lu.ma","luma.com","www.luma.com","ticketmaster.com","www.ticketmaster.com","runsignup.com","www.runsignup.com"]},"mode":"schema_event_html"}]},{"id":"schema-faq-howto","name":"Schema.org FAQPage & HowTo","category":"public-records","description":"Universal Schema.org extractor for FAQPage Q&A and HowTo step-by-step instructions, yielding when Recipe, Product, JobPosting, Course, SoftwareApplication, or Medical types are present.","domains":["yoast.com","www.wikihow.com"],"universalEngine":true,"auth_mode":"html","strict_robots":true,"exampleUrls":["https://yoast.com/features/structured-data/faq-block/","https://www.wikihow.com/Tie-a-Tie"],"htmlRoutes":[{"id":"schema-faq-howto","match":{"exactSegments":false},"mode":"schema_faq_howto_html"}]},{"id":"schema-localbusiness","name":"Schema.org LocalBusiness (Universal)","category":"commerce-social","description":"Universal Schema.org LocalBusiness JSON-LD extractor (Restaurant, Store, AutoDealer, BikeStore and every *Business/*Store subtype) for location, dealer, and shop pages: name, address, phone, geo, opening hours, price range, rating, and amenities. Skips pages whose main entity is an article, product, recipe, job, vehicle, medical, or event.","domains":["www.chipotle.com","www.apple.com"],"universalEngine":true,"auth_mode":"html","strict_robots":true,"exampleUrls":["https://locations.chipotle.com/co/boulder/1650-28th-st","https://www.apple.com/retail/fifthavenue/"],"htmlRoutes":[{"id":"schema-localbusiness","match":{"exactSegments":false},"mode":"schema_localbusiness_html"}]},{"id":"schema-medical","name":"Schema.org Medical Entities","category":"research-health","description":"Universal Schema.org extractor for MedicalCondition, Drug, Physician, MedicalClinic, and MedicalWebPage JSON-LD, yielding when Product is present.","domains":["my.clevelandclinic.org","www.nhs.uk"],"universalEngine":true,"auth_mode":"html","strict_robots":true,"exampleUrls":["https://my.clevelandclinic.org/health/diseases/6424-asthma","https://www.nhs.uk/conditions/asthma/"],"htmlRoutes":[{"id":"schema-medical","match":{"exactSegments":false},"mode":"schema_medical_html"}]},{"id":"schema-menu","name":"Schema.org Restaurant Menu (Menu / MenuSection / MenuItem)","category":"commerce-social","description":"Universal Schema.org Menu extractor that matches only when Menu, MenuSection, MenuItem, or hasMenu JSON-LD entities exist, never hijacking plain Restaurant pages.","domains":["www.chilis.com"],"universalEngine":true,"auth_mode":"html","strict_robots":true,"min_interval_ms":1000,"exampleUrls":["https://www.chilis.com/menu"],"htmlRoutes":[{"id":"schema-menu","match":{"exactSegments":false},"mode":"schema_menu_html"}]},{"id":"schema-recipe","name":"Schema.org Recipe (Universal)","category":"commerce-social","description":"Universal Schema.org Recipe JSON-LD extractor for any recipe site: ingredients, numbered steps (HowToStep/HowToSection), prep/cook/total times, yield, cuisine, rating, and nutrition. Resolves @graph @id author references.","domains":["www.budgetbytes.com","sallysbakingaddiction.com"],"universalEngine":true,"auth_mode":"html","strict_robots":true,"exampleUrls":["https://www.budgetbytes.com/one-pot-creamy-cajun-chicken-pasta/","https://sallysbakingaddiction.com/chewy-chocolate-chip-cookies/"],"htmlRoutes":[{"id":"schema-recipe","match":{"exactSegments":false},"mode":"schema_recipe_html"}]},{"id":"schema-software-app","name":"Schema.org SoftwareApplication","category":"developer","description":"Universal Schema.org extractor for SoftwareApplication, WebApplication, and MobileApplication JSON-LD (version, OS, category, offers, rating, and downloadUrl).","domains":["code.visualstudio.com","www.mozilla.org"],"universalEngine":true,"auth_mode":"html","strict_robots":true,"exampleUrls":["https://code.visualstudio.com/","https://www.mozilla.org/en-US/firefox/new/"],"htmlRoutes":[{"id":"schema-software-app","match":{"exactSegments":false},"mode":"schema_software_app_html"}]},{"id":"schema-vehicle","name":"Schema.org Vehicle & Car","category":"commerce-social","description":"Universal Schema.org extractor for Vehicle, Car, Motorcycle, and MotorizedBicycle JSON-LD with strict 17-character VIN validation (excluding I, O, Q).","domains":["www.hondaofseattle.com"],"universalEngine":true,"auth_mode":"html","strict_robots":true,"exampleUrls":["https://www.hondaofseattle.com/viewdetails/used/5tdkdrbh0rs544979/2024-toyota-highlander-sport-utility"],"htmlRoutes":[{"id":"schema-vehicle","match":{"exactSegments":false},"mode":"schema_vehicle_html"}]},{"id":"searchspring","name":"Searchspring On-Site Search","category":"commerce-social","description":"Extracts public Searchspring JSON search API payloads and discovers siteId markers from storefront HTML.","domains":["api.searchspring.net","www.searchspring.com"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://api.searchspring.net/api/search/search.json?siteId=rn129l&q=router&resultsFormat=native"],"routes":[{"match":{"pathEquals":["/api/search/search.json"],"queryParams":[{"name":"siteId","param":"siteId","charset":"alnum_dash","minLen":2,"maxLen":32}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"searchspring_search"}}],"htmlRoutes":[{"id":"searchspring","match":{"exactSegments":false},"mode":"searchspring_html"}]},{"id":"sec-edgar","name":"SEC EDGAR Company Submissions & Filings","category":"finance","description":"Upgrades sec.gov EDGAR company browse pages and CIK URLs to keyless data.sec.gov JSON submissions (10-K, 10-Q, 8-K, DEF 14A, Form 4, 13F).","domains":["www.sec.gov","sec.gov","data.sec.gov"],"exampleUrls":["https://www.sec.gov/edgar/browse/?CIK=0001477333","https://data.sec.gov/submissions/CIK0000320193.json"],"match":{"anyOf":[{"hosts":["www.sec.gov","sec.gov"],"exactSegments":false,"pathSegments":["edgar","browse"],"queryParams":[{"names":["CIK","cik"],"param":"rawCik","charset":"digits","minLen":1,"maxLen":10}],"derivedParams":{"paddedCik":{"fromParam":"rawCik","transform":"pad10_zero"},"numericCik":{"fromParam":"rawCik","transform":"strip_leading_zeros"}}},{"hosts":["www.sec.gov","sec.gov"],"exactSegments":true,"pathSegments":["cgi-bin","browse-edgar"],"queryParams":[{"names":["CIK","cik"],"param":"rawCik","charset":"digits","minLen":1,"maxLen":10}],"derivedParams":{"paddedCik":{"fromParam":"rawCik","transform":"pad10_zero"},"numericCik":{"fromParam":"rawCik","transform":"strip_leading_zeros"}}},{"hosts":["data.sec.gov"],"exactSegments":true,"pathSuffix":".json","pathSegments":["submissions",{"param":"rawCik","stripPrefix":"CIK","stripSuffix":".json","charset":"digits","minLen":1,"maxLen":10}],"derivedParams":{"paddedCik":{"fromParam":"rawCik","transform":"pad10_zero"},"numericCik":{"fromParam":"rawCik","transform":"strip_leading_zeros"}}}]},"twin":{"fetchUrl":"https://data.sec.gov/submissions/CIK{paddedCik}.json","kind":"json","accept":"application/json"},"extract":{"requireFields":["name"],"vars":{"name":{"paths":["name"],"trim":true},"tickersPlain":{"paths":["tickers"],"join":", "},"tickersCode":{"paths":["tickers"],"itemWrap":"`","join":", "},"exchanges":{"paths":["exchanges"],"join":", "},"tickersBullet":{"template":"{tickersCode} ({exchanges})","whenVars":["tickersCode","exchanges"],"fallbackVar":"tickersCode"},"sic":{"paths":["sic"]},"sicDesc":{"paths":["sicDescription"]},"sicOrDesc":{"paths":["sic","sicDescription"]},"sicFull":{"template":"{sic} — {sicDesc}","whenVars":["sic","sicDesc"],"fallbackVar":"sicOrDesc"},"category":{"paths":["category"]},"stateInc":{"paths":["stateOfIncorporation"]},"fye":{"paths":["fiscalYearEnd"],"format":"fiscal_mmdd"},"descTickerOrCik":{"paths":["tickers"],"join":", ","fallbackTemplate":"CIK {paddedCik}"}},"titleTemplate":"{name} ({tickersPlain}) — SEC EDGAR","titleWhenVar":"tickersPlain","titleFallbackTemplate":"{name} (CIK {paddedCik}) — SEC EDGAR","descriptionTemplate":"{name} SEC EDGAR filings ({descTickerOrCik})","bullets":[{"label":"CIK","template":"`{paddedCik}`"},{"label":"Tickers","template":"{tickersBullet}","whenVar":"tickersBullet"},{"label":"SIC Industry","template":"{sicFull}","whenVar":"sicFull"},{"label":"Filer Category","template":"{category}","whenVar":"category"},{"label":"Incorporation","template":"{stateInc}","whenVar":"stateInc"},{"label":"Fiscal Year End","template":"{fye}","whenVar":"fye"}],"sections":[{"heading":"Recent SEC Filings","parallelArrays":{"basePath":"filings.recent","fields":{"form":"form","filingDate":"filingDate","reportDate":"reportDate","accessionNumber":"accessionNumber","primaryDocument":"primaryDocument","items":"items"},"priorityFilterAfter":{"index":12,"field":"form","allowValues":["10-K","10-K/A","10-Q","10-Q/A","8-K","DEF 14A","20-F","S-1","13F-HR","4"]}},"limit":25,"requireItemVar":"form","collectLinkVars":["docUrl"],"itemVars":{"form":{"paths":["form"]},"accRaw":{"paths":["accessionNumber"]},"accNoDash":{"paths":["accessionNumber"],"replaceAll":{"from":"-","to":""}},"primaryDocument":{"paths":["primaryDocument"]},"indexUrl":{"template":"https://www.sec.gov/Archives/edgar/data/{numericCik}/{accNoDash}/{accRaw}-index.htm","whenVars":["accRaw","accNoDash"]},"docUrl":{"template":"https://www.sec.gov/Archives/edgar/data/{numericCik}/{accNoDash}/{primaryDocument}","whenVars":["accNoDash","primaryDocument"],"fallbackVar":"indexUrl"},"formBold":{"template":"**{form}**","whenVars":["form"]},"formCell":{"template":"[**{form}**]({docUrl})","whenVars":["form","docUrl"],"fallbackVar":"formBold"}},"columns":[{"header":"Form","template":"{formCell}"},{"header":"Filed","paths":["filingDate"]},{"header":"Period","paths":["reportDate"]},{"header":"8-K Items","paths":["items"]}]}]}},{"id":"sec-xbrl-frames","name":"SEC EDGAR XBRL Frames & Company Facts","category":"finance","description":"Extracts data.sec.gov XBRL frames, companyconcept, and bounded companyfacts JSON feeds via universalEngine to avoid duplicating sec-edgar.yaml domain claims.","domains":["efts.sec.gov"],"universalEngine":true,"auth_mode":"pub","user_agent_profile":"sec-edgar","min_interval_ms":200,"exampleUrls":["https://data.sec.gov/api/xbrl/frames/us-gaap/AccountsPayableCurrent/USD/CY2023Q4I.json","https://data.sec.gov/api/xbrl/companyconcept/CIK0000320193/us-gaap/AccountsPayableCurrent.json","https://data.sec.gov/api/xbrl/companyfacts/CIK0000320193.json"],"routes":[{"match":{"hosts":["data.sec.gov"],"anyOf":[{"pathPrefix":"/api/xbrl/frames/"},{"pathPrefix":"/api/xbrl/companyconcept/"},{"pathPrefix":"/api/xbrl/companyfacts/"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"sec_xbrl_frames_json"}}]},{"id":"security-txt","name":"RFC 9116 security.txt Vulnerability Disclosure","category":"developer","description":"Universal RFC 9116 /.well-known/security.txt and /security.txt parser extracting Contact, Expires, Encryption, Policy, Canonical, Acknowledgments, and CSAF directives with strict Contact validation.","domains":["www.cloudflare.com"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://www.cloudflare.com/.well-known/security.txt","https://github.com/.well-known/security.txt"],"routes":[{"match":{"exactSegments":true,"pathEquals":["/.well-known/security.txt","/security.txt"]},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"text/plain","maxBytes":262144},"extract":{"textMode":"security_txt_text"}}]},{"id":"semantic-scholar","name":"Semantic Scholar Academic Graph","category":"research-health","description":"Extracts scholarly papers, citation counts, authors, open-access PDFs, and author profiles via api.semanticscholar.org Graph API (keyless + optional SEMANTIC_SCHOLAR_API_KEY) with HTML metadata fallback and AWS WAF shell guard.","domains":["api.semanticscholar.org","www.semanticscholar.org","semanticscholar.org"],"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://api.semanticscholar.org/graph/v1/paper/DOI:10.1038/s41586-021-03819-2?fields=paperId,title,year,authors,abstract,citationCount,openAccessPdf,externalIds","https://www.semanticscholar.org/paper/Attention-is-All-you-Need-Vaswani-Shazeer/204e3073870fae3d05bcbc2f6a8e263d9b72e776"],"routes":[{"match":{"hosts":["api.semanticscholar.org"],"pathPrefix":"/graph/v1/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"semantic_scholar_json"}},{"match":{"hosts":["www.semanticscholar.org","semanticscholar.org"],"anyOf":[{"exactSegments":true,"pathSegments":["paper",{"param":"slug","charset":"url_seg","minLen":1,"maxLen":200},{"param":"paperId","charset":"alnum","minLen":40,"maxLen":40}]},{"exactSegments":true,"pathSegments":["paper",{"param":"paperId","charset":"alnum","minLen":40,"maxLen":40}]}]},"twin":{"fetchUrl":"https://api.semanticscholar.org/graph/v1/paper/{paperId}?fields=paperId,title,year,venue,publicationVenue,authors,abstract,citationCount,referenceCount,influentialCitationCount,openAccessPdf,externalIds,publicationDate,url","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"semantic_scholar_json"}},{"match":{"hosts":["www.semanticscholar.org","semanticscholar.org"],"anyOf":[{"exactSegments":true,"pathSegments":["author",{"param":"slug","charset":"url_seg","minLen":1,"maxLen":200},{"param":"authorId","charset":"digits","minLen":3,"maxLen":20}]},{"exactSegments":true,"pathSegments":["author",{"param":"authorId","charset":"digits","minLen":3,"maxLen":20}]}]},"twin":{"fetchUrl":"https://api.semanticscholar.org/graph/v1/author/{authorId}?fields=authorId,name,affiliations,homepage,paperCount,citationCount,hIndex,url","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"semantic_scholar_json"}}],"htmlRoutes":[{"id":"semantic-scholar","match":{"hosts":["www.semanticscholar.org","semanticscholar.org"],"exactSegments":false},"mode":"semantic_scholar_html"}]},{"id":"senate-lda","name":"Senate Lobbying Disclosures (LDA)","category":"public-records","description":"Extracts Senate Lobbying Disclosure Act filings from lda.gov (and lda.senate.gov) REST API v1 JSON with Crawl-delay 4s politeness and HTML fallback.","domains":["lda.gov","lda.senate.gov"],"auth_mode":"pub","min_interval_ms":4000,"strict_robots":true,"exampleUrls":["https://lda.gov/api/v1/filings/a934e791-d564-4fd3-8b78-041f8cfcf115/","https://lda.gov/filings/public/filing/a934e791-d564-4fd3-8b78-041f8cfcf115/"],"routes":[{"match":{"hosts":["lda.gov","lda.senate.gov"],"exactSegments":false,"pathSegments":["filings","public","filing",{"param":"filingId","charset":"alnum_dash","minLen":4,"maxLen":64}]},"twin":{"fetchUrl":"https://{host}/api/v1/filings/{filingId}/","kind":"json","accept":"application/json","auth_mode":"pub","maxBytes":2097152},"extract":{"jsonMode":"senate_lda_json"}},{"match":{"hosts":["lda.gov","lda.senate.gov"],"pathPrefix":"/api/v1/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"pub","maxBytes":2097152},"extract":{"jsonMode":"senate_lda_json"}}],"htmlRoutes":[{"id":"senate-lda","match":{"hosts":["lda.gov","lda.senate.gov"],"exactSegments":false},"mode":"senate_lda_html"}]},{"id":"servicenow-kb","name":"ServiceNow Knowledge Base","category":"developer","description":"Extracts public ServiceNow Knowledge Base articles from TechArticle JSON-LD and Service Portal KB DOM while rejecting soft-404 shells.","domains":["support.servicenow.com"],"universalEngine":true,"auth_mode":"html","exampleUrls":["https://support.servicenow.com/kb?id=kb_article_view&sysparm_article=KB0963589"],"htmlRoutes":[{"id":"servicenow-kb","match":{"exactSegments":false},"mode":"servicenow_kb_html"}]},{"id":"setlist-lastfm","name":"Setlist.fm & Last.fm Music Metadata","category":"commerce-social","description":"Official keyed Setlist.fm REST 1.0 (SETLISTFM_API_KEY) and Last.fm Audioscrobbler 2.0 (LASTFM_API_KEY) adapters plus Setlist.fm / Last.fm SSR HTML extraction with Fastly challenge rejection.","domains":["api.setlist.fm","www.setlist.fm","setlist.fm","ws.audioscrobbler.com","www.last.fm","last.fm"],"auth_mode":"key","min_interval_ms":1000,"exampleUrls":["https://www.setlist.fm/setlist/motionless-in-white/2023/mobile-civic-center-mobile-al-3ba45068.html","https://api.setlist.fm/rest/1.0/setlist/3ba45068","https://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=Cher&format=json"],"routes":[{"match":{"hosts":["api.setlist.fm"],"pathPrefix":"/rest/1.0/","exactSegments":false},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"setlist_fm_json"}},{"match":{"hosts":["ws.audioscrobbler.com"],"pathPrefix":"/2.0","exactSegments":false},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"lastfm_json"}}],"htmlRoutes":[{"id":"setlist-lastfm","match":{"hosts":["www.setlist.fm","setlist.fm","www.last.fm","last.fm"],"exactSegments":false},"mode":"setlist_lastfm_html"}]},{"id":"sfcc-demandware","name":"Salesforce Commerce Cloud (Demandware) Storefronts","category":"commerce-social","description":"Structurally detects Salesforce Commerce Cloud storefronts and extracts Product-Variation twins, JSON-LD, variation options, and product geometry/specification tables.","domains":["www.demandware.com"],"universalEngine":true,"exampleUrls":["https://www.demandware.com/product/sample"],"htmlRoutes":[{"id":"sfcc-demandware","match":{"exactSegments":false},"mode":"sfcc_html"}]},{"id":"sheldon-brown","name":"Sheldon Brown Bicycle Technical Reference","category":"research-health","description":"Extracts bicycle technical reference articles, gear/ISO tire crib tables, and glossary definitions from sheldonbrown.com.","domains":["sheldonbrown.com","www.sheldonbrown.com"],"auth_mode":"html","min_interval_ms":1000,"exampleUrls":["https://www.sheldonbrown.com/gear-calc.html","https://www.sheldonbrown.com/gloss_e-f.html"],"htmlRoutes":[{"id":"sheldon-brown","match":{"exactSegments":false},"mode":"sheldon_brown_html"}]},{"id":"shopify-filter-apps","name":"Shopify Filter Apps (Boost Commerce / Globo)","category":"commerce-social","description":"Page-key adapter for Boost Commerce (mybcapps.com) and Globo Smart Product Filter JSON endpoints; companion HTML mode yields so shopify_html is never preempted.","domains":["services.mybcapps.com","filter.globo.io"],"universalEngine":true,"auth_mode":"page-key","requires_page_key_opt_in":true,"exampleUrls":["https://services.mybcapps.com/bc-sf-filter/filter?shop=get-casely.myshopify.com&page=1&limit=5"],"routes":[{"match":{"anyOf":[{"hosts":["services.mybcapps.com"],"pathEquals":["/bc-sf-filter/filter","/bc-sf-filter/search"]},{"hosts":["filter.globo.io"],"pathPrefix":"/api/"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152,"requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"jsonMode":"shopify_filter_apps_json"}}],"htmlRoutes":[{"id":"shopify-filter-apps","match":{"exactSegments":false},"mode":"shopify_filter_apps_html"}]},{"id":"shopify-hydrogen","name":"Shopify Hydrogen Storefronts","category":"commerce-social","description":"Page-key adapter extracting Shopify Hydrogen SSR __remixContext loaderData (shop, products, collections) while rejecting non-Shopify Remix apps and empty shells.","domains":["hydrogen.shop"],"universalEngine":true,"auth_mode":"page-key","requires_page_key_opt_in":true,"exampleUrls":["https://hydrogen.shop/"],"htmlRoutes":[{"id":"shopify-hydrogen","match":{"exactSegments":false},"mode":"shopify_hydrogen_html"}]},{"id":"shopify-storefront-graphql","name":"Shopify Storefront API (Tokenless GraphQL)","category":"commerce-social","description":"Queries any Shopify store's public Storefront API (/api//graphql.json) with Shopify's documented tokenless access for one product by handle (plus same-origin page-key companion discovery on storefronts embedding Storefront API tokens): shop name, vendor, type, price range, options, every variant (SKU, price, compare-at price, availability), and collections.","domains":["www.tentree.com","www.henryrose.com"],"universalEngine":true,"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://henryrose.com/api/2025-07/graphql.json?handle=the-layering-collection","https://www.tentree.com/api/2025-07/graphql.json?handle=e-gift-code"],"routes":[{"match":{"exactSegments":true,"pathSegments":["api",{"param":"apiVersion","charset":"slug","minLen":7,"maxLen":10},"graphql.json"],"queryParams":[{"name":"handle","param":"handle","charset":"slug","minLen":1,"maxLen":160}]},"twin":{"fetchUrl":"https://{host}/api/{apiVersion}/graphql.json","kind":"json","accept":"application/json","method":"POST","contentType":"application/json","requestBody":"{\"query\":\"query EdgeFetchProduct { shop { name } product(handle: \\\"{handle}\\\") { id handle title vendor productType description onlineStoreUrl availableForSale priceRange { minVariantPrice { amount currencyCode } maxVariantPrice { amount currencyCode } } options { name optionValues { name } } variants(first: 100) { nodes { id title sku availableForSale price { amount currencyCode } compareAtPrice { amount currencyCode } } } collections(first: 20) { nodes { handle title } } } }\"}","maxBytes":2097152},"extract":{"jsonMode":"shopify_storefront_graphql_json"}}]},{"id":"shopify","name":"Shopify Universal Storefront & Catalogs","category":"commerce-social","description":"Formats /products.json and /collections//products.json store inventories, upgrades *.myshopify.com and custom-domain /products/ pages, and implements polite full-store catalog pulls.","domains":["*.myshopify.com"],"universalEngine":true,"exampleUrls":["https://www.henryrose.com/products/the-layering-collection","https://www.henryrose.com/products.json?limit=30&page=1"],"catalog":{"platform":"shopify","pauseMs":1000,"pageCap":200,"firstPageTemplate":"{origin}/products.json?limit=250&page=1","collectionPageTemplate":"{origin}/collections/{collection}/products.json?limit=250&page=1","perPage":250,"maxVariantsPerProduct":250,"maxImagesPerProduct":250},"routes":[{"match":{"excludeHosts":["bigcartel.com","www.bigcartel.com","my.bigcartel.com","api.bigcartel.com","assets.bigcartel.com","help.bigcartel.com","developers.bigcartel.com","blog.bigcartel.com","upway.co","www.upway.co"],"anyOf":[{"pathEquals":["/products.json"]},{"exactSegments":true,"pathSegments":["collections",{"param":"col","charset":"slug","maxLen":160},"products.json"]}]},"twin":{"id":"shopify-catalog-page","fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"commerceMode":"shopify_catalog_page"}},{"match":{"excludeHosts":["upway.co","www.upway.co"],"pathSuffix":".js","scanSegment":{"afterLiteral":"products","param":"handle","charset":"slug","stripSuffix":".js","maxLen":160}},"twin":{"id":"shopify","fetchUrl":"https://{host}/products/{handle}.js","kind":"json","accept":"application/json"},"extract":{"commerceMode":"shopify_product_js"}},{"match":{"excludeHosts":["upway.co","www.upway.co"],"anyOf":[{"pathSuffix":".json","scanSegment":{"afterLiteral":"products","param":"handle","charset":"slug","stripSuffix":".json","maxLen":160}},{"hosts":["*.myshopify.com"],"scanSegment":{"afterLiteral":"products","param":"handle","charset":"slug","stripSuffix":".json","maxLen":160}}]},"twin":{"id":"shopify","fetchUrl":"https://{host}/products/{handle}.json","kind":"json","accept":"application/json"},"extract":{"commerceMode":"shopify_product"}},{"match":{"hosts":["*.myshopify.com"],"optionalLeadingLocale":true,"exactSegments":true,"pathSegments":["collections",{"param":"handle","charset":"slug","maxLen":160}]},"twin":{"id":"shopify","fetchUrl":"https://{host}/collections/{handle}/products.json?limit=50","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"commerceMode":"shopify_catalog_page"}}],"htmlRoutes":[{"id":"shopify","match":{"pathContainsSegment":"products"},"mode":"shopify_html"}]},{"id":"shopware-magento","name":"Magento 2 & Shopware 6 Storefronts","category":"commerce-social","description":"Structurally detects Magento 2 (text/x-magento-init swatches and bounded products-render-info) and Shopware 6 (sw-product-detail and property tables) storefronts.","domains":["www.shopware.com","business.adobe.com"],"universalEngine":true,"exampleUrls":["https://frontends-demo.vercel.app/Pepper-white-Muntok-pearl/SW10095"],"htmlRoutes":[{"id":"shopware-magento","match":{"exactSegments":false},"mode":"shopware_magento_html"}]},{"id":"slide-decks","name":"Slide Decks (SlideShare & SpeakerDeck)","category":"commerce-social","description":"Extracts SpeakerDeck presentations via public oEmbed JSON and slide transcripts HTML, and SlideShare decks via __NEXT_DATA__ HTML (no /api/ twin per robots.txt).","domains":["slideshare.net","www.slideshare.net","speakerdeck.com","www.speakerdeck.com"],"auth_mode":"pub","strict_robots":true,"exampleUrls":["https://www.slideshare.net/slideshow/slideshare-rebrand-announcement-deck-2025/283262633","https://speakerdeck.com/csswizardry/well-thats-weird"],"routes":[{"match":{"hosts":["speakerdeck.com","www.speakerdeck.com"],"exactSegments":true,"pathSegments":[{"param":"user","charset":"slug","minLen":1,"maxLen":80,"reserved":["search","signup","login","categories","features","pro","terms","privacy","about","jobs","assets","users","oembed.json"]},{"param":"deck","charset":"slug","minLen":1,"maxLen":160}]},"twin":{"fetchUrl":"https://speakerdeck.com/oembed.json?url=https%3A%2F%2Fspeakerdeck.com%2F{user}%2F{deck}","kind":"json","accept":"application/json","maxBytes":1048576},"extract":{"jsonMode":"speakerdeck_oembed_json"}},{"match":{"hosts":["speakerdeck.com","www.speakerdeck.com"],"pathEquals":["/oembed.json"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":1048576},"extract":{"jsonMode":"speakerdeck_oembed_json"}}],"htmlRoutes":[{"id":"slide-decks","mode":"slideshare_html","match":{"hosts":["slideshare.net","www.slideshare.net"],"exactSegments":false}},{"id":"slide-decks","mode":"speakerdeck_html","match":{"hosts":["speakerdeck.com","www.speakerdeck.com"],"exactSegments":false}}]},{"id":"small-search","name":"Searchanise, Doofinder, Findify & Nosto Search","category":"commerce-social","description":"Opt-in page-key adapter pack for Searchanise, Doofinder, Findify, and Nosto search APIs; defaults OFF and falls back to HTML/JSON-LD.","domains":["searchserverapi1.com","eu1-search.doofinder.com","api-v3.findify.io","api.nosto.com"],"universalEngine":true,"auth_mode":"page-key","requires_page_key_opt_in":true,"exampleUrls":["https://searchserverapi1.com/getresults?apiKey=3O4A8B9F4q&q=brew&output=json&maxResults=10"],"routes":[{"match":{"hosts":["searchserverapi1.com","www.searchserverapi1.com"],"pathEquals":["/getresults","/getwidgets"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"jsonMode":"small_search"}},{"match":{"anyOf":[{"hostSubdomain":{"suffix":"-search.doofinder.com","param":"zone"},"pathEquals":["/5/search"]},{"hostSubdomain":{"suffix":"-search.doofinder.com","param":"zone"},"pathSegments":["6",{"param":"hashid","charset":"alnum_dash","minLen":8,"maxLen":64},"_search"]}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"jsonMode":"small_search"}},{"match":{"hosts":["api-v3.findify.io"],"pathEquals":["/v3/search","/v3/autocomplete"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"jsonMode":"small_search"}},{"match":{"hosts":["api.nosto.com"],"pathEquals":["/v1/graphql"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","method":"POST","contentType":"application/json","requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"jsonMode":"small_search"}}],"htmlRoutes":[{"id":"small-search","match":{"exactSegments":false},"mode":"small_search_html"}]},{"id":"smartetailing","name":"SmartEtailing IBD Storefronts","category":"commerce-social","description":"Structurally detects SmartEtailing independent bicycle dealer storefronts and extracts Product JSON-LD, spec tables, and dealer pickup info.","domains":["www.trekchicago.com"],"universalEngine":true,"auth_mode":"html","exampleUrls":["https://www.trekchicago.com/product/trek-precaliber-16-556127-1.htm"],"htmlRoutes":[{"id":"smartetailing","match":{"exactSegments":false},"mode":"smartetailing_html"}]},{"id":"smb-ats-full","name":"SMB ATS Full (Manatal, Homerun, Zoho Recruit, Freshteam)","category":"jobs","description":"Extracts open roles from Manatal career-page JSON API, Homerun JobPosting JSON-LD, Zoho Recruit, and Freshteam portals while rejecting 404.homerun.co and soft errors.","domains":["api.manatal.com","core.api.manatal.com","jobs.manatal.com","*.zohorecruit.com","*.freshteam.com","*.homerun.co"],"auth_mode":"pub","exampleUrls":["https://api.manatal.com/open/v3/career-page/manatal/jobs/","https://jobs.homerun.co/sales-executive-amsterdam"],"routes":[{"match":{"hosts":["api.manatal.com","core.api.manatal.com"],"pathPrefix":"/open/v3/career-page/","exactSegments":false},"twin":{"id":"smb-ats-full","fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"manatal_jobs_json"}},{"match":{"hosts":["jobs.manatal.com"],"exactSegments":true,"pathSegments":[{"param":"slug","charset":"slug","reserved":["api","login","auth","static","assets","robots.txt","sitemap.xml","favicon.ico"],"minLen":1,"maxLen":120}]},"twin":{"id":"smb-ats-full-manatal","fetchUrl":"https://api.manatal.com/open/v3/career-page/{slug}/jobs/","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"manatal_jobs_json"}},{"match":{"anyOf":[{"hosts":["*.freshteam.com"],"pathPrefix":"/api/job_postings","exactSegments":false},{"hosts":["*.zohorecruit.com"],"pathPrefix":"/recruit/v2/","exactSegments":false}]},"twin":{"id":"smb-ats-full-json","fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"smb_ats_json"}}],"htmlRoutes":[{"id":"smb-ats-full","mode":"smb_ats_full_html","match":{"hosts":["*.homerun.co","*.zohorecruit.com","*.freshteam.com","jobs.manatal.com"],"exactSegments":false}}]},{"id":"smithsonian-open-access","name":"Smithsonian Open Access","category":"public-records","description":"Smithsonian Open Access API v1.0 adapter (api.si.edu/openaccess) via api.data.gov key helper with HTML fallback.","domains":["si.edu","www.si.edu","api.si.edu"],"auth_mode":"key","min_interval_ms":1000,"exampleUrls":["https://api.si.edu/openaccess/api/v1.0/search?q=apollo","https://api.si.edu/openaccess/api/v1.0/content/edanmdm:nasm_A19700102000","https://www.si.edu/object/apollo-11-command-module-columbia:nasm_A19700102000"],"routes":[{"match":{"hosts":["api.si.edu"],"pathPrefix":"/openaccess/api/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"key"},"extract":{"jsonMode":"smithsonian_open_access_json"}},{"match":{"hosts":["si.edu","www.si.edu"],"exactSegments":false,"pathSegments":["object",{"param":"objectSlug","charset":"url_seg","minLen":4,"maxLen":160}]},"twin":{"fetchUrl":"https://api.si.edu/openaccess/api/v1.0/search?q={objectSlug}","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"key"},"extract":{"jsonMode":"smithsonian_open_access_json"}}],"htmlRoutes":[{"id":"smithsonian-open-access","match":{"hosts":["si.edu","www.si.edu"],"exactSegments":false,"reservedFirstSegment":["search","admin","core"]},"mode":"smithsonian_open_access_html"}]},{"id":"socrata","name":"Socrata Open Data Portals (SODA Universal Engine)","category":"public-records","description":"Upgrades city, state, and federal Socrata open-data dataset URLs (/d/<4x4-id> or /dataset/.../<4x4-id>) to /api/views/.json column schemas and SODA endpoints.","domains":["data.cityofnewyork.us","data.sfgov.org","data.sf.gov","data.seattle.gov","data.cityofchicago.org","data.lacity.org","data.wa.gov","data.nj.gov","data.colorado.gov","data.texas.gov","data.ny.gov","data.cdc.gov","*.socrata.com"],"universalEngine":true,"exampleUrls":["https://data.cityofnewyork.us/Housing-Development/DOB-Job-Application-Filings/ic3t-wcy2","https://data.sf.gov/d/i98e-djp9"],"match":{"socrataHost":true,"minSegments":2,"anyOf":[{"socrataHost":true,"minSegments":2,"exactSegments":false,"pathSegments":["d",{"param":"viewId","charset":"socrata_4x4","transform":"lower"}]},{"socrataHost":true,"minSegments":2,"scanSegment":{"lastOrBeforeLiteral":"about_data","param":"viewId","charset":"socrata_4x4","transform":"lower"}}]},"twin":{"fetchUrl":"https://{host}/api/views/{viewId}.json","kind":"json","accept":"application/json"},"extract":{"requireFields":["name","id"],"vars":{"name":{"paths":["name"],"trim":true},"desc":{"paths":["description"],"trim":true},"descShort":{"paths":["description"],"trim":true,"sliceMax":260},"attribution":{"paths":["attribution"]},"category":{"paths":["category"]},"license":{"paths":["license.name"]},"updatedDate":{"paths":["rowsUpdatedAt"],"format":"epoch_sec_date"},"sodaJsonUrl":{"template":"https://{host}/resource/{viewId}.json?$limit=50"},"csvExportUrl":{"template":"https://{host}/api/views/{viewId}/rows.csv?accessType=DOWNLOAD"}},"titleTemplate":"{name} ({host})","descriptionVar":"descShort","publishedTimeVar":"updatedDate","bullets":[{"label":"Dataset ID","template":"`{viewId}` ({host})"},{"label":"SODA JSON API","template":"`{sodaJsonUrl}`"},{"label":"CSV Download","template":"{csvExportUrl}"},{"label":"Agency / Attribution","template":"{attribution}","whenVar":"attribution"},{"label":"Category","template":"{category}","whenVar":"category"},{"label":"Rows Last Updated","template":"{updatedDate}","whenVar":"updatedDate"},{"label":"License","template":"{license}","whenVar":"license"}],"sections":[{"heading":"Description","textVar":"desc"},{"heading":"Schema","headingTemplate":"Schema ({shownCount} Columns)","arrayPath":"columns","filter":{"excludeFieldPrefix":{"field":"fieldName","prefix":":@"}},"limit":40,"columns":[{"header":"Field Name","paths":["fieldName"],"code":true},{"header":"Label","paths":["name"]},{"header":"Type","paths":["dataTypeName"]},{"header":"Description","paths":["description"]}]}],"linksVars":["sodaJsonUrl","csvExportUrl"]}},{"id":"sourceforge-launchpad","name":"SourceForge & Launchpad","category":"developer","description":"Extracts open-source project metadata, categories, licenses, and release details from SourceForge REST API/HTML and Launchpad 1.0 REST API/SSR pages.","domains":["sourceforge.net","api.launchpad.net","launchpad.net"],"auth_mode":"pub","exampleUrls":["https://sourceforge.net/rest/p/sevenzip","https://sourceforge.net/projects/sevenzip/","https://api.launchpad.net/1.0/ubuntu","https://launchpad.net/ubuntu"],"routes":[{"match":{"hosts":["sourceforge.net"],"pathPrefix":"/rest/p/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":1048576},"extract":{"jsonMode":"sourceforge_json"}},{"match":{"hosts":["sourceforge.net"],"exactSegments":true,"pathSegments":["projects",{"param":"proj","charset":"pkg"}]},"twin":{"fetchUrl":"https://sourceforge.net/rest/p/{proj}","kind":"json","accept":"application/json","maxBytes":1048576},"extract":{"jsonMode":"sourceforge_json"}},{"match":{"hosts":["api.launchpad.net"],"pathPrefix":"/1.0/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":1048576},"extract":{"jsonMode":"launchpad_json"}}],"htmlRoutes":[{"id":"sourceforge-launchpad","match":{"hosts":["sourceforge.net","launchpad.net"],"exactSegments":false},"mode":"sourceforge_launchpad_html"}]},{"id":"specialized-turbo-support","name":"Specialized Turbo E-Bike Support","category":"developer","description":"Extracts rendered Turbo e-bike support and diagnostic KB articles on support.specialized.com while strictly rejecting unhydrated eGain JS launcher shells and 403 gateway responses.","domains":["support.specialized.com"],"auth_mode":"html","min_interval_ms":2000,"strict_robots":true,"exampleUrls":["https://support.specialized.com/kb/sp_en-us/home"],"htmlRoutes":[{"id":"specialized-turbo-support","match":{"exactSegments":false},"mode":"specialized_turbo_support_html"}]},{"id":"specialized","name":"Specialized Bicycles & Geometry Specs","category":"commerce-social","description":"Polite HTML adapter for Specialized product pages extracting technical specifications, frame geometry tables, pricing, availability, and manual downloads.","domains":["specialized.com","www.specialized.com"],"auth_mode":"html","min_interval_ms":2000,"strict_robots":true,"exampleUrls":["https://www.specialized.com/us/en/s-works-tarmac-sl9-sram-red-axs/p/4293533"],"htmlRoutes":[{"id":"specialized","match":{"exactSegments":false},"mode":"specialized_html"}]},{"id":"spotify-web-api","name":"Spotify Web API & Open oEmbed","category":"commerce-social","description":"Official keyed Spotify Web API v1 adapter (SPOTIFY_ACCESS_TOKEN) plus public open.spotify.com oEmbed JSON and JSON-LD / OpenGraph / music:* HTML extraction.","domains":["api.spotify.com","open.spotify.com"],"auth_mode":"key","min_interval_ms":1000,"exampleUrls":["https://open.spotify.com/oembed?url=https://open.spotify.com/show/4rOoJ6Egrf8K2IrywzwOMk","https://open.spotify.com/track/4cOdK2wGLETKBW3PvgPWqT","https://api.spotify.com/v1/shows/4rOoJ6Egrf8K2IrywzwOMk"],"routes":[{"match":{"hosts":["api.spotify.com"],"pathPrefix":"/v1/","exactSegments":false},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"spotify_api_json"}},{"match":{"hosts":["open.spotify.com"],"pathEquals":["/oembed"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"pub","maxBytes":524288},"extract":{"jsonMode":"spotify_oembed_json"}}],"htmlRoutes":[{"id":"spotify-web-api","match":{"hosts":["open.spotify.com"],"exactSegments":false},"mode":"spotify_html"}]},{"id":"spree-solidus","name":"Spree Commerce & Solidus","category":"commerce-social","description":"Extracts Spree/Solidus JSON:API /api/v2/storefront/products twins and post-HTML JSON-LD/Microdata product pages.","domains":["demo.spreecommerce.org","demo.solidus.io"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://demo.spreecommerce.org/us/en/products/espresso-barista-kit","https://demo.solidus.io/products/solidus-hoodie"],"routes":[{"match":{"pathEquals":["/api/v2/storefront/products"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"commerceMode":"spree_solidus_json"}},{"match":{"pathSegments":["api","v2","storefront","products",{"param":"id","charset":"url_seg","minLen":1,"maxLen":160}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"commerceMode":"spree_solidus_json"}}],"htmlRoutes":[{"id":"spree-solidus","match":{"exactSegments":false},"mode":"spree_solidus_html"}]},{"id":"square-online","name":"Square Online Storefronts","category":"commerce-social","description":"Extracts Square Online storefront product JSON-LD, Microdata, and __BOOTSTRAP_STATE__ storeInfo/commerceLinks hydration while rejecting empty SPA shells.","domains":["www.pessosices.com"],"universalEngine":true,"auth_mode":"html","exampleUrls":["https://www.pessosices.com/product/ice-cream-gelato/92"],"htmlRoutes":[{"id":"square-online","match":{"exactSegments":false},"mode":"square_online_html"}]},{"id":"square-toast-menu","name":"Square Online Restaurant & Toast Online Ordering Menus","category":"commerce-social","description":"Extracts Square Online restaurant __BOOTSTRAP_STATE__ menus and Toast order.toasttab.com online ordering menus while rejecting Cloudflare challenges and empty shells.","domains":["order.toasttab.com"],"universalEngine":true,"auth_mode":"html","strict_robots":true,"min_interval_ms":2000,"max_concurrent":1,"exampleUrls":["https://rinconmx-restaurant.square.site/shop/online-menu/LL5C6YEQHRVCYJVZRVRVY4WR","https://rinconmx-restaurant.square.site/"],"htmlRoutes":[{"id":"square-toast-menu","match":{"exactSegments":false},"mode":"square_toast_menu_html"}]},{"id":"squarespace-commerce","name":"Squarespace Commerce Storefronts","category":"commerce-social","description":"Detects Squarespace Commerce storefronts structurally and formats ?format=json-pretty product/collection payloads and HTML fallback into GFM tables and normalized CatalogRecord arrays.","domains":["commerce.squarespace.com"],"universalEngine":true,"exampleUrls":["https://www.trice-co.com/shop/p/pink-flare-leggings"],"htmlRoutes":[{"id":"squarespace-commerce","match":{"exactSegments":false},"mode":"squarespace_html"}]},{"id":"sram-docs","name":"SRAM Technical Documentation (Fluid Topics)","category":"developer","description":"Extracts bounded Fluid Topics SSR HTML documentation from docs.sram.com, stripping inline data:image base64 blobs and error chrome while preserving breadcrumbs, model codes, and PDF manual links.","domains":["docs.sram.com"],"exampleUrls":["https://docs.sram.com/en-US/publications/2eIzVnWuTRM7vhoKQjadQr"],"htmlRoutes":[{"id":"sram-docs","match":{"exactSegments":false},"mode":"sram_docs_html"}]},{"id":"sram-models","name":"SRAM Component Models (www.sram.com)","category":"commerce-social","description":"Extracts structured Product JSON-LD and technical component specification tables from www.sram.com/*/sram/models/* pages.","domains":["www.sram.com","sram.com"],"exampleUrls":["https://www.sram.com/en/sram/models/rd-xx-e-b1","https://www.sram.com/en/service/models/rd-gx-1-b1"],"htmlRoutes":[{"id":"sram-models","mode":"dom","match":{"optionalLeadingLocale":true,"exactSegments":false,"anyOf":[{"pathSegments":["sram","models",{"param":"modelSlug","charset":"url_seg","minLen":1,"maxLen":140}]},{"pathSegments":["service","models",{"param":"modelSlug","charset":"url_seg","minLen":1,"maxLen":140}]}]},"jsonLdTypes":["Product"],"vars":{"title":{"jsonLdPaths":["name"],"cssText":[".product-detail h1","h1","title"],"trim":true},"sku":{"jsonLdPaths":["sku"],"trim":true},"brand":{"jsonLdPaths":["brand.name","brand"],"trim":true},"body":{"cssHtmlToMd":["main.product-detail",".product-detail","main"],"format":"strip_leading_h1","trim":true}},"requireVars":["title","body"],"titleTemplate":"{title}","bullets":[{"label":"Brand","template":"{brand}","whenVar":"brand"},{"label":"SKU","template":"`{sku}`","whenVar":"sku"}],"bodyVar":"body","preserveBodyLinksFromVar":"body"}]},{"id":"ssrn-nber","name":"NBER Working Papers & SSRN","category":"research-health","description":"Extracts NBER working paper bibliographic metadata and abstracts (citation_* metas + DOM) and SSRN abstract metadata with strict Cloudflare challenge rejection.","domains":["www.nber.org","nber.org","papers.ssrn.com"],"auth_mode":"html","min_interval_ms":1000,"exampleUrls":["https://www.nber.org/papers/w30000","https://papers.ssrn.com/sol3/papers.cfm?abstract_id=4131630"],"htmlRoutes":[{"id":"ssrn-nber","match":{"hosts":["www.nber.org","nber.org","papers.ssrn.com"],"exactSegments":false},"mode":"ssrn_nber_html"}]},{"id":"stackexchange-qa","name":"Stack Overflow & Stack Exchange Q&A","category":"developer","description":"Upgrades Stack Overflow / Stack Exchange URLs to keyless API v2.3 native Markdown (with HTML fallback), sorting the Accepted Answer first.","domains":["stackoverflow.com","www.stackoverflow.com","serverfault.com","superuser.com","askubuntu.com","mathoverflow.net","stackapps.com","*.stackexchange.com"],"exampleUrls":["https://stackoverflow.com/questions/11227809/why-is-processing-a-sorted-array-faster-than-processing-an-unsorted-array"],"match":{"hostMap":{"param":"siteParam","stripWww":true,"exact":{"stackoverflow.com":"stackoverflow","serverfault.com":"serverfault","superuser.com":"superuser","askubuntu.com":"askubuntu","mathoverflow.net":"mathoverflow","stackapps.com":"stackapps"},"suffixSubdomain":".stackexchange.com"},"exactSegments":false,"pathSegments":[{"param":"qPrefix","allowValues":["questions","q"]},{"param":"qid","charset":"digits"}]},"twin":{"fetchUrl":"https://api.stackexchange.com/2.3/questions/{qid}?site={siteParam}&filter=%2120aKG._8Oscv%2A6dguVOli","kind":"json","accept":"application/json"},"extract":{"rootPath":"items.0","requireFields":["title"],"vars":{"title":{"paths":["title"],"format":"strip_tags"},"score":{"paths":["score"],"default":"0"},"tags":{"paths":["tags"],"limit":8,"itemWrap":"`","join":", "},"qMdRaw":{"paths":["body_markdown"],"format":"se_markdown"},"qHtmlMd":{"paths":["body"],"format":"html_to_md"},"qMd":{"template":"{qMdRaw}","whenVars":["qMdRaw"],"fallbackVar":"qHtmlMd"},"link":{"paths":["link"],"requireHttps":true}},"requireVars":["qMd"],"titleTemplate":"{title}","metaLine":[{"label":"Votes","template":"{score}"},{"label":"Tags","template":"{tags}","whenVar":"tags"}],"sections":[{"heading":"Question","textVar":"qMd"},{"heading":"","subsectionsArrayPath":"answers","sortBy":{"boolDescField":"is_accepted","numDescField":"score"},"limit":8,"requireItemVar":"ansMd","subsectionHeadingTemplate":"Answer {index1} (Score: {scoreLabel})","subsectionAltWhenVar":"acceptedFlag","subsectionAltHeadingTemplate":"✅ Accepted Answer (Score: {scoreLabel})","subsectionBodyVar":"ansMd","itemVars":{"ansMdRaw":{"paths":["body_markdown"],"format":"se_markdown"},"ansHtmlMd":{"paths":["body"],"format":"html_to_md"},"ansMd":{"template":"{ansMdRaw}","whenVars":["ansMdRaw"],"fallbackVar":"ansHtmlMd"},"ansScore":{"paths":["score"],"default":"0"},"ansAuthor":{"paths":["owner.display_name"],"format":"strip_tags"},"scoreLabel":{"template":"{ansScore} — by {ansAuthor}","whenVars":["ansAuthor"],"fallbackVar":"ansScore"},"acceptedFlag":{"paths":["is_accepted"],"format":"bool_map","trueValue":"1","falseValue":""}}}],"linksVars":["link"]},"htmlRoutes":[{"match":{"exactSegments":false,"pathSegments":["questions",{"param":"qid","charset":"digits"}]},"mode":"stackexchange_html"}]},{"id":"staffing-ats-pack","name":"Staffing ATS Pack (Crelate, JobDiva, Ceipal)","category":"jobs","description":"Extracts public staffing job boards and postings from Crelate, JobDiva, and Ceipal while rejecting disabled portals (Organization Portal Disabled) and error shells.","domains":["jobs.crelate.com","app.crelate.com","*.jobdiva.com","*.ceipal.com"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://jobs.crelate.com/portal/promotive/rss"],"routes":[{"match":{"hosts":["jobs.crelate.com","app.crelate.com"],"pathPrefix":"/portal/","pathSuffix":"/rss","exactSegments":false},"twin":{"id":"staffing-ats-pack-crelate-rss","fetchUrl":"{requestUrl}","kind":"text","accept":"application/rss+xml"},"extract":{"xml":{"mode":"items_table","requireAnyTags":["rss","channel"],"itemTag":"item","titleTemplate":"Crelate Staffing Jobs ({itemCount})","emptyText":"No open positions currently listed.","limit":50,"requireItemVar":"jTitle","collectLinkVar":"jLink","emitTotals":true,"itemVars":{"jTitle":{"tags":["title"]},"jLink":{"tags":["link"]},"loc":{"tags":["location"],"default":"-"},"pubDate":{"tags":["pubDate"],"sliceMax":16,"default":"-"}},"recordFields":{"title":"{jTitle}","url":"{jLink}","location":"{loc}","postedAt":"{pubDate}","source":"crelate"},"columns":[{"header":"Role","template":"[{jTitle}]({jLink})"},{"header":"Location","template":"{loc}"},{"header":"Published","template":"{pubDate}"}]}}},{"match":{"anyOf":[{"hosts":["jobs.crelate.com","app.crelate.com"],"pathPrefix":"/api/","exactSegments":false},{"hosts":["*.ceipal.com"],"anyOf":[{"pathPrefix":"/jobs/api/","exactSegments":false},{"pathPrefix":"/api/","exactSegments":false}]},{"hosts":["*.jobdiva.com"],"pathPrefix":"/portal/api/","exactSegments":false}]},"twin":{"id":"staffing-ats-pack","fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"staffing_ats_json"}}],"htmlRoutes":[{"id":"staffing-ats-pack","mode":"staffing_ats_pack_html","match":{"exactSegments":false}}]},{"id":"stamped-loox-junip","name":"Stamped, Loox & Junip Product Reviews","category":"commerce-social","description":"Extracts public Stamped, Junip, and Loox storefront API review JSON payloads without hitting disallowed loox.io/widget paths.","domains":["stamped.io","api.juniphq.com","apid.juniphq.com","storefront-api.loox.io"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://stamped.io/api/widget/reviews?sId=291293&apiKey=a23ad1ea-e527-4a21-9a95-37fefe0ff5cd&productId=8317758832957&page=1&take=10"],"routes":[{"match":{"hosts":["stamped.io"],"pathEquals":["/api/widget/reviews","/api/widget/reviews/"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"stamped_loox_junip_reviews"}},{"match":{"anyOf":[{"hosts":["api.juniphq.com","apid.juniphq.com"],"pathEquals":["/v1/product_reviews","/v1/display_settings"]},{"hosts":["api.juniphq.com","apid.juniphq.com"],"pathSegments":["v1","products",{"param":"productId","charset":"pkg","minLen":1,"maxLen":120}]}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"stamped_loox_junip_reviews"}},{"match":{"hosts":["storefront-api.loox.io"],"pathSegments":["storefront","v1","store",{"param":"storeId","charset":"alnum_dash","minLen":2,"maxLen":80},{"param":"endpoint","allowValues":["product-reviews","bottomline"]}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"stamped_loox_junip_reviews"}}],"htmlRoutes":[{"id":"stamped-loox-junip","match":{"exactSegments":false},"mode":"stamped_loox_junip_html"}]},{"id":"state-court-portals","name":"State Court Portals","category":"public-records","description":"Extracts public state court appellate pages, orders, and opinions (www.txcourts.gov) while honestly detecting WAF, login, and SPA barriers on research.txcourts.gov.","domains":["research.txcourts.gov","www.txcourts.gov"],"auth_mode":"html","min_interval_ms":2000,"max_concurrent":1,"strict_robots":true,"exampleUrls":["https://www.txcourts.gov/supreme/orders-opinions/","https://research.txcourts.gov/CourtRecordsSearch/#!/home"],"htmlRoutes":[{"id":"state-court-portals","match":{"hosts":["research.txcourts.gov","www.txcourts.gov"]},"mode":"state_court_portals_html"}]},{"id":"state-legislatures","name":"State Legislatures (Open States & LegiScan)","category":"public-records","description":"Official Open States v3 API and LegiScan API adapter for state bills, sessions, legislators, and jurisdictions with HTML fallback.","domains":["openstates.org","www.openstates.org","v3.openstates.org","legiscan.com","www.legiscan.com","api.legiscan.com"],"auth_mode":"key","exampleUrls":["https://v3.openstates.org/bills/tx/89/HB%201","https://api.legiscan.com/?op=getBill&id=1167968"],"routes":[{"match":{"hosts":["v3.openstates.org"],"anyOf":[{"pathPrefix":"/bills"},{"pathPrefix":"/jurisdictions"},{"pathPrefix":"/people"},{"pathPrefix":"/events"},{"pathPrefix":"/committees"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":4194304},"extract":{"jsonMode":"state_legislatures_json"}},{"match":{"hosts":["openstates.org","www.openstates.org"],"exactSegments":false,"pathSegments":[{"param":"state","charset":"alnum","minLen":2,"maxLen":2,"transform":"lower"},"bills",{"param":"session","charset":"url_seg","minLen":1,"maxLen":40},{"param":"billId","charset":"url_seg","minLen":1,"maxLen":40}]},"twin":{"fetchUrl":"https://v3.openstates.org/bills/{state}/{session}/{billId}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":4194304},"extract":{"jsonMode":"state_legislatures_json"}},{"match":{"hosts":["api.legiscan.com"],"queryParams":[{"name":"op","param":"op","charset":"alnum","minLen":3,"maxLen":40}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":4194304},"extract":{"jsonMode":"state_legislatures_json"}}],"htmlRoutes":[{"id":"state-legislatures","match":{"hosts":["openstates.org","www.openstates.org","legiscan.com","www.legiscan.com"],"exactSegments":false},"mode":"state_legislatures_html"}]},{"id":"state-sos-business","name":"State Secretary of State Business Registries","category":"public-records","description":"Extracts public state business registry filings (DE, CA, FL, TX) with strict robots.txt enforcement, rate pacing, and WAF/Incapsula/Cloudflare rejection.","domains":["icis.corp.delaware.gov","bizfileonline.sos.ca.gov","search.sunbiz.org","mycpa.cpa.state.tx.us","comptroller.texas.gov"],"auth_mode":"pub","strict_robots":true,"min_interval_ms":2000,"max_concurrent":1,"exampleUrls":["https://comptroller.texas.gov/taxes/franchise/"],"routes":[{"match":{"hosts":["bizfileonline.sos.ca.gov"],"exactSegments":false,"pathSegments":["search","business",{"param":"recordId","charset":"url_seg","minLen":1,"maxLen":64}]},"twin":{"fetchUrl":"https://bizfileonline.sos.ca.gov/api/Records/businesssearch/{recordId}","kind":"json","accept":"application/json","auth_mode":"pub","maxBytes":2097152},"extract":{"jsonMode":"state_sos_json"}},{"match":{"hosts":["bizfileonline.sos.ca.gov"],"pathPrefix":"/api/Records/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"pub","maxBytes":2097152},"extract":{"jsonMode":"state_sos_json"}}],"htmlRoutes":[{"id":"state-sos-business","match":{"hosts":["icis.corp.delaware.gov","bizfileonline.sos.ca.gov","search.sunbiz.org","mycpa.cpa.state.tx.us","comptroller.texas.gov"],"exactSegments":false},"mode":"state_sos_html"}]},{"id":"state-workforce-boards","name":"State Workforce & Public Job Boards","category":"jobs","description":"Extracts structured public job postings from state workforce portals (jobs.myflorida.com, statejobs.ny.gov, calcareers.ca.gov, usnlx.com) with Rule 5 honest fallbacks.","domains":["statejobs.ny.gov","calcareers.ca.gov","usnlx.com"],"universalEngine":true,"auth_mode":"html","strict_robots":true,"exampleUrls":["https://jobs.myflorida.com/job/TALLAHASSEE-Attorney-FL-32301/1425569100/","https://statejobs.ny.gov/public/vacancyDetailsView.cfm?id=229697"],"htmlRoutes":[{"id":"state-workforce-boards","mode":"state_workforce_boards_html","match":{"excludeHosts":["governmentjobs.com","*.governmentjobs.com","workintexas.com","*.workintexas.com"],"anyOf":[{"hosts":["jobs.myflorida.com","statejobs.ny.gov","calcareers.ca.gov","www.calcareers.ca.gov","usnlx.com","www.usnlx.com"],"exactSegments":false},{"hostSubdomain":{"suffix":".usnlx.com","param":"state","reserved":["www","api","login"]},"exactSegments":false}]}}]},{"id":"status-page-pack","name":"Status Page Pack","category":"developer","description":"Extracts service status, components, and incidents from Instatus, Better Stack, Status.io, and Cachet public JSON endpoints and SSR HTML pages.","domains":["deno.instatus.com","status.instatus.com","status.betterstack.com","status.raycast.com","status.gitlab.com","demo.cachethq.io"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://deno.instatus.com/","https://deno.instatus.com/v2/components.json","https://status.betterstack.com/","https://status.gitlab.com/1.0/status/5b36dc6502d06804c08349f7","https://demo.cachethq.io/api/v1/components"],"routes":[{"match":{"pathEquals":["/summary.json","/v2/components.json","/v2/incidents.json","/index.json","/api/v1/components","/api/v1/incidents","/api/v1/status"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"status_page_pack"}},{"match":{"exactSegments":true,"pathSegments":["1.0","status",{"param":"statusId","charset":"alnum","minLen":16,"maxLen":48}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"status_page_pack"}}],"htmlRoutes":[{"id":"status-page-pack","match":{"exactSegments":false},"mode":"status_page_pack_html"}]},{"id":"steam-store","name":"Steam Store & App News","category":"commerce-social","description":"Public Steam Store appdetails, appreviews (with HTML homepage redirect rejection), ISteamNews GetNewsForApp v2 JSON, and store.steampowered.com/app/ HTML fallback.","domains":["store.steampowered.com","api.steampowered.com"],"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://store.steampowered.com/api/appdetails?appids=620","https://store.steampowered.com/app/620/Portal_2/","https://api.steampowered.com/ISteamNews/GetNewsForApp/v2/?appid=620&count=2"],"routes":[{"match":{"hosts":["store.steampowered.com"],"pathEquals":["/api/appdetails"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"steam_store_json"}},{"match":{"hosts":["store.steampowered.com"],"exactSegments":false,"pathSegments":["app",{"param":"appId","charset":"digits","minLen":1,"maxLen":12}]},"twin":{"fetchUrl":"https://store.steampowered.com/api/appdetails?appids={appId}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"steam_store_json"}},{"match":{"hosts":["store.steampowered.com"],"exactSegments":false,"pathSegments":["appreviews",{"param":"appId","charset":"digits","minLen":1,"maxLen":12}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","setQueryParams":{"json":"1"},"maxBytes":2097152},"extract":{"jsonMode":"steam_store_json"}},{"match":{"hosts":["api.steampowered.com"],"pathPrefix":"/ISteamNews/GetNewsForApp/","exactSegments":false},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"steam_store_json"}}],"htmlRoutes":[{"id":"steam-store","match":{"hosts":["store.steampowered.com"],"exactSegments":false},"mode":"steam_store_html"}]},{"id":"stockist","name":"Stockist Dealer Locator","category":"commerce-social","description":"Extracts public Stockist store/dealer locator JSON payloads and discovers Stockist widget tags on merchant HTML pages.","domains":["stockist.co","www.stockist.co"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://stockist.co/api/v1/map_93wm75n3/locations/all"],"routes":[{"match":{"hosts":["stockist.co","www.stockist.co"],"pathSegments":["api","v1",{"param":"tag","charset":"alnum_dash","minLen":2,"maxLen":64},"locations.json"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"stockist_locations"}},{"match":{"hosts":["stockist.co","www.stockist.co"],"pathSegments":["api","v1",{"param":"tag","charset":"alnum_dash","minLen":2,"maxLen":64},"locations","all"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"stockist_locations"}}],"htmlRoutes":[{"id":"stockist","match":{"exactSegments":false},"mode":"stockist_html"}]},{"id":"storemapper","name":"Storemapper Dealer Locator","category":"commerce-social","description":"Extracts public Storemapper store locator JSON feeds and discovers Storemapper widget IDs on merchant HTML pages.","domains":["www.storemapper.co","storemapper.co"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://www.storemapper.co/api/users/12873/stores.json"],"routes":[{"match":{"hosts":["www.storemapper.co","storemapper.co"],"pathSegments":["api","users",{"param":"userId","charset":"alnum_dash","minLen":1,"maxLen":64},"stores.json"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"storemapper_locations"}}],"htmlRoutes":[{"id":"storemapper","match":{"exactSegments":false},"mode":"storemapper_html"}]},{"id":"storerocket","name":"StoreRocket Dealer Locator","category":"commerce-social","description":"Extracts public StoreRocket store locator JSON payloads and discovers StoreRocket widget IDs on merchant HTML pages.","domains":["storerocket.io","www.storerocket.io"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://storerocket.io/api/user/OdJERNO8WE/locations"],"routes":[{"match":{"hosts":["storerocket.io","www.storerocket.io"],"pathSegments":["api","user",{"param":"userId","charset":"alnum_dash","minLen":2,"maxLen":64},"locations"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"storerocket_locations"}}],"htmlRoutes":[{"id":"storerocket","match":{"exactSegments":false},"mode":"storerocket_html"}]},{"id":"strava-segments","name":"Strava Public Segments","category":"commerce-social","description":"Extracts Strava segments via authenticated API v3 (/api/v3/segments/* with STRAVA_ACCESS_TOKEN or Part 2 strava Virtual OAuth MCP) and public /segments/* __NEXT_DATA__ HTML fallback, rejecting /register/free authwalls.","domains":["www.strava.com","strava.com"],"auth_mode":"key","strict_robots":true,"exampleUrls":["https://www.strava.com/segments/229781","https://www.strava.com/api/v3/segments/229781"],"routes":[{"match":{"hosts":["www.strava.com","strava.com"],"exactSegments":true,"pathSegments":["api","v3","segments",{"param":"segmentId","charset":"digits","minLen":1,"maxLen":16}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":1048576,"auth_mode":"key"},"extract":{"jsonMode":"strava_segments_json"}}],"htmlRoutes":[{"id":"strava-segments","mode":"strava_segments_html","match":{"hosts":["www.strava.com","strava.com"],"pathPrefix":"/segments/","exactSegments":false}}]},{"id":"substack-notes-beehiiv","name":"Substack Notes & Beehiiv v2 API","category":"commerce-social","description":"Extracts Beehiiv v2 publication/post feeds on api.beehiiv.com (BEEHIIV_API_KEY) and Substack creator profiles/notes on substack.com (preloads-json), avoiding *.beehiiv.com overlap with newsletter-archives.","domains":["api.beehiiv.com","substack.com","www.substack.com"],"auth_mode":"key","min_interval_ms":1000,"strict_robots":true,"exampleUrls":["https://substack.com/@hamish","https://api.beehiiv.com/v2/publications/pub_00000000-0000-0000-0000-000000000000/posts"],"routes":[{"match":{"hosts":["api.beehiiv.com"],"pathPrefix":"/v2/publications/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"beehiiv_api_json"}}],"htmlRoutes":[{"id":"substack-notes-beehiiv","match":{"hosts":["substack.com","www.substack.com"],"anyOf":[{"exactSegments":true,"pathSegments":[{"param":"handle","charset":"at_handle","minLen":2,"maxLen":80}]},{"exactSegments":true,"pathSegments":[{"param":"handle","charset":"at_handle","minLen":2,"maxLen":80},"note",{"param":"noteId","charset":"url_seg","minLen":1,"maxLen":80}]},{"pathEquals":["/notes","/notes/"]}]},"mode":"substack_notes_html"}]},{"id":"supremecourt-gov","name":"U.S. Supreme Court Opinions, Dockets & Orders","category":"public-records","description":"Robots-enforced HTML adapter for Supreme Court slip opinions, public docket files, and orders of the Court.","domains":["supremecourt.gov","www.supremecourt.gov"],"auth_mode":"html","min_interval_ms":1000,"strict_robots":true,"exampleUrls":["https://www.supremecourt.gov/opinions/slipopinion/24","https://www.supremecourt.gov/docket/docketfiles/html/public/23-939.html","https://www.supremecourt.gov/orders/ordersofthecourt/24"],"htmlRoutes":[{"id":"supremecourt-gov","match":{"anyOf":[{"pathPrefix":"/opinions/"},{"pathPrefix":"/docket/"},{"pathPrefix":"/orders/"}]},"mode":"supremecourt_html"}]},{"id":"suspension-cockpit-compat","name":"Suspension & Cockpit Compatibility Specs","category":"commerce-social","description":"Extracts SHIS headset codes, chainring BCD/mount standards, rear shock sizing, and fitment tables from Wolf Tooth, Ohlins, PUSH Industries, and Cane Creek.","domains":["wolftoothcomponents.com","www.wolftoothcomponents.com","ohlins.com","www.ohlins.com","pushindustries.com","www.pushindustries.com","canecreek.com","www.canecreek.com"],"auth_mode":"html","exampleUrls":["https://www.wolftoothcomponents.com/collections/chainrings","https://www.ohlins.com/en-us/bicycle","https://www.pushindustries.com/products/elevensix","https://www.canecreek.com/collections/headsets"],"htmlRoutes":[{"id":"suspension-cockpit-compat","match":{"exactSegments":false},"mode":"suspension_cockpit_compat_html"}]},{"id":"taleo-full","name":"Oracle Taleo Career Section Job Search","category":"jobs","description":"Formats Oracle Taleo career-section job boards via the public /careersection/rest/jobboard/searchjobs endpoint (portal id from the page: title, location, posted date, contest number, total open requisitions) plus SSR FreeMarker /careersection/
/jobsearch.ftl and jobdetail.ftl HTML fallbacks.","domains":["hdr.taleo.net","*.taleo.net"],"universalEngine":true,"auth_mode":"pub","min_interval_ms":3000,"strict_robots":true,"exampleUrls":["https://hdr.taleo.net/careersection/rest/jobboard/searchjobs?lang=en&portal=101430233§ion=ex","https://chicago.taleo.net/careersection/100/jobsearch.ftl"],"routes":[{"match":{"hostSubdomain":{"suffix":".taleo.net","param":"tenant","reserved":["www"]},"pathEquals":["/careersection/rest/jobboard/searchjobs"],"queryParams":[{"name":"portal","param":"portal","charset":"digits","minLen":4,"maxLen":20},{"name":"section","param":"section","charset":"slug","minLen":1,"maxLen":40,"optional":true}]},"twin":{"fetchUrl":"https://{host}/careersection/rest/jobboard/searchjobs?lang=en&portal={portal}","kind":"json","accept":"application/json","method":"POST","contentType":"application/json","headers":{"tz":"GMT-06:00","tzname":"America/Chicago"},"requestBody":"{\"multilineEnabled\":false,\"sortingSelection\":{\"sortBySelectionParam\":\"3\",\"ascendingSortingOrder\":\"false\"},\"fieldData\":{\"fields\":{\"KEYWORD\":\"\",\"LOCATION\":\"\"},\"valid\":true},\"filterSelectionParam\":{\"searchFilterSelections\":[]},\"advancedSearchFiltersSelectionParam\":{\"searchFilterSelections\":[]},\"pageNo\":1}","maxBytes":4194304},"extract":{"jsonMode":"taleo_searchjobs_json"}}],"htmlRoutes":[{"id":"taleo-full","mode":"taleo_full_html","match":{"pathPrefix":"/careersection/","exactSegments":false}}]},{"id":"target","name":"Target","category":"commerce-social","description":"Extracts Target product pages from schema.org Product JSON-LD (including entity-encoded ld+json) and live Target SSR HTML metadata without calling disallowed redsky endpoints.","domains":["target.com","www.target.com","redsky.target.com"],"auth_mode":"html","min_interval_ms":2000,"max_concurrent":1,"strict_robots":true,"exampleUrls":["https://www.target.com/p/campus-lab-university-of-arkansas-at-monticello-official-uam-boll-weevils-logo-unisex-adult-pull-over-hoodie/-/A-1000000076"],"htmlRoutes":[{"id":"target","match":{"hosts":["target.com","www.target.com"]},"mode":"target_html"}]},{"id":"teamtailor","name":"Teamtailor Career Portals","category":"jobs","description":"Upgrades [.na].teamtailor.com career roots to their /jobs.rss feed with locations and departments.","domains":["*.teamtailor.com"],"exampleUrls":["https://stratio.teamtailor.com/","https://stratio.teamtailor.com/jobs"],"match":{"hostSubdomain":{"suffix":".teamtailor.com","param":"org","stripOptional2LetterRegion":true,"reserved":["www","app","career"]},"pathSegments":[{"param":"jobsLit","charset":"alnum","allowValues":["jobs"],"optional":true}]},"twin":{"id":"teamtailor","fetchUrl":"https://{host}/jobs.rss","kind":"text","accept":"application/rss+xml"},"extract":{"xml":{"mode":"items_table","requireAnyTags":["rss","channel"],"itemTag":"item","channelTitleFallbackParam":"org","titleTemplate":"{channelTitle} — Open Roles ({itemCount})","emptyText":"No open positions currently listed.","limit":100,"requireItemVar":"jTitle","collectLinkVar":"jLink","itemVars":{"jTitle":{"tags":["title"]},"jLink":{"tags":["link"]},"dept":{"tags":["tt:department","category"],"default":"-"},"loc":{"tags":["tt:location","g:location","location"],"default":"-"},"pubDate":{"tags":["pubDate"],"sliceMax":16,"default":"-"}},"columns":[{"header":"Role","template":"[{jTitle}]({jLink})"},{"header":"Department","template":"{dept}"},{"header":"Location","template":"{loc}"},{"header":"Published","template":"{pubDate}"}]}}},{"id":"tech-job-boards-jsonld","name":"Tech Job Boards (BuiltIn, Wellfound, Dice)","category":"jobs","description":"Extracts JobPosting JSON-LD (including HTML-entity-encoded application/ld+json) from BuiltIn, Wellfound, and Dice while honoring robots.txt and rejecting Cloudflare Turnstile/SPA shells.","domains":["builtin.com","www.builtin.com","wellfound.com","www.wellfound.com","dice.com","www.dice.com"],"auth_mode":"html","strict_robots":true,"exampleUrls":["https://builtin.com/job/executive-employee-social-media-vice-president/12592638"],"htmlRoutes":[{"id":"tech-job-boards-jsonld","mode":"tech_job_boards_jsonld_html","match":{"hosts":["builtin.com","www.builtin.com","wellfound.com","www.wellfound.com","dice.com","www.dice.com"],"exactSegments":false}}]},{"id":"terraform-registry","name":"Terraform Registry","category":"developer","description":"Upgrades registry.terraform.io provider and module pages to the official keyless /v1/ JSON API with versions, documentation entries, inputs, outputs, and README.","domains":["registry.terraform.io"],"exampleUrls":["https://registry.terraform.io/providers/hashicorp/random","https://registry.terraform.io/providers/hashicorp/random/3.8.1","https://registry.terraform.io/modules/terraform-aws-modules/vpc/aws","https://registry.terraform.io/modules/terraform-aws-modules/vpc/aws/5.1.0"],"routes":[{"match":{"exactSegments":true,"pathSegments":["providers",{"param":"ns","charset":"pkg","minLen":1,"maxLen":80},{"param":"name","charset":"pkg","minLen":1,"maxLen":80},{"param":"ver","charset":"url_seg","reserved":["latest","docs"],"minLen":1,"maxLen":64}]},"twin":{"fetchUrl":"https://registry.terraform.io/v1/providers/{ns}/{name}/{ver}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"requireFields":["namespace","name","version"],"vars":{"namespace":{"paths":["namespace"]},"name":{"paths":["name"]},"version":{"paths":["version"]},"tier":{"paths":["tier"]},"downloads":{"paths":["downloads"],"format":"int_comma"},"publishedAt":{"paths":["published_at"],"sliceMax":10},"desc":{"paths":["description"],"trim":true},"source":{"paths":["source"],"requireHttps":true},"versionCount":{"paths":["versions"],"format":"array_len_comma"}},"titleTemplate":"{namespace}/{name} v{version} (Terraform Provider)","descriptionVar":"desc","publishedTimeVar":"publishedAt","introVar":"desc","bullets":[{"label":"Provider","template":"`{namespace}/{name}`"},{"label":"Version","template":"`{version}`"},{"label":"Tier","template":"{tier}","whenVar":"tier"},{"label":"Downloads","template":"{downloads}","whenVar":"downloads"},{"label":"Published","template":"{publishedAt}","whenVar":"publishedAt"},{"label":"Available Versions","template":"{versionCount}","whenVar":"versionCount"},{"label":"Source","template":"{source}","whenVar":"source"}],"sections":[{"heading":"Documentation Entries","arrayPath":"docs","limit":40,"columns":[{"header":"Title","paths":["title"]},{"header":"Category","paths":["category"]},{"header":"Language","paths":["language"]},{"header":"Path","paths":["path"],"code":true}]}],"linksVars":["source"]}},{"match":{"exactSegments":true,"pathSegments":["providers",{"param":"ns","charset":"pkg","minLen":1,"maxLen":80},{"param":"name","charset":"pkg","minLen":1,"maxLen":80},{"param":"ver","charset":"alnum","allowValues":["latest"],"minLen":6,"maxLen":6}]},"twin":{"fetchUrl":"https://registry.terraform.io/v1/providers/{ns}/{name}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"requireFields":["namespace","name","version"],"vars":{"namespace":{"paths":["namespace"]},"name":{"paths":["name"]},"version":{"paths":["version"]},"tier":{"paths":["tier"]},"downloads":{"paths":["downloads"],"format":"int_comma"},"publishedAt":{"paths":["published_at"],"sliceMax":10},"desc":{"paths":["description"],"trim":true},"source":{"paths":["source"],"requireHttps":true},"versionCount":{"paths":["versions"],"format":"array_len_comma"}},"titleTemplate":"{namespace}/{name} v{version} (Terraform Provider)","descriptionVar":"desc","publishedTimeVar":"publishedAt","introVar":"desc","bullets":[{"label":"Provider","template":"`{namespace}/{name}`"},{"label":"Version","template":"`{version}`"},{"label":"Tier","template":"{tier}","whenVar":"tier"},{"label":"Downloads","template":"{downloads}","whenVar":"downloads"},{"label":"Published","template":"{publishedAt}","whenVar":"publishedAt"},{"label":"Available Versions","template":"{versionCount}","whenVar":"versionCount"},{"label":"Source","template":"{source}","whenVar":"source"}],"sections":[{"heading":"Documentation Entries","arrayPath":"docs","limit":40,"columns":[{"header":"Title","paths":["title"]},{"header":"Category","paths":["category"]},{"header":"Language","paths":["language"]},{"header":"Path","paths":["path"],"code":true}]}],"linksVars":["source"]}},{"match":{"exactSegments":true,"pathSegments":["providers",{"param":"ns","charset":"pkg","minLen":1,"maxLen":80},{"param":"name","charset":"pkg","minLen":1,"maxLen":80}]},"twin":{"fetchUrl":"https://registry.terraform.io/v1/providers/{ns}/{name}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"requireFields":["namespace","name","version"],"vars":{"namespace":{"paths":["namespace"]},"name":{"paths":["name"]},"version":{"paths":["version"]},"tier":{"paths":["tier"]},"downloads":{"paths":["downloads"],"format":"int_comma"},"publishedAt":{"paths":["published_at"],"sliceMax":10},"desc":{"paths":["description"],"trim":true},"source":{"paths":["source"],"requireHttps":true},"versionCount":{"paths":["versions"],"format":"array_len_comma"}},"titleTemplate":"{namespace}/{name} v{version} (Terraform Provider)","descriptionVar":"desc","publishedTimeVar":"publishedAt","introVar":"desc","bullets":[{"label":"Provider","template":"`{namespace}/{name}`"},{"label":"Version","template":"`{version}`"},{"label":"Tier","template":"{tier}","whenVar":"tier"},{"label":"Downloads","template":"{downloads}","whenVar":"downloads"},{"label":"Published","template":"{publishedAt}","whenVar":"publishedAt"},{"label":"Available Versions","template":"{versionCount}","whenVar":"versionCount"},{"label":"Source","template":"{source}","whenVar":"source"}],"sections":[{"heading":"Documentation Entries","arrayPath":"docs","limit":40,"columns":[{"header":"Title","paths":["title"]},{"header":"Category","paths":["category"]},{"header":"Language","paths":["language"]},{"header":"Path","paths":["path"],"code":true}]}],"linksVars":["source"]}},{"match":{"exactSegments":true,"pathSegments":["modules",{"param":"ns","charset":"pkg","minLen":1,"maxLen":80},{"param":"name","charset":"pkg","minLen":1,"maxLen":80},{"param":"provider","charset":"pkg","minLen":1,"maxLen":80},{"param":"ver","charset":"url_seg","reserved":["latest","submodules","examples"],"minLen":1,"maxLen":64}]},"twin":{"fetchUrl":"https://registry.terraform.io/v1/modules/{ns}/{name}/{provider}/{ver}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"requireFields":["namespace","name","provider","version"],"vars":{"namespace":{"paths":["namespace"]},"name":{"paths":["name"]},"provider":{"paths":["provider"]},"version":{"paths":["version"]},"verified":{"paths":["verified"],"format":"bool_map","trueValue":"Verified","falseValue":"Unverified"},"downloads":{"paths":["downloads"],"format":"int_comma"},"publishedAt":{"paths":["published_at"],"sliceMax":10},"desc":{"paths":["description"],"trim":true},"source":{"paths":["source"],"requireHttps":true},"readme":{"paths":["root.readme"],"format":"demote_h1","trim":true}},"titleTemplate":"{namespace}/{name}/{provider} v{version} (Terraform Module)","descriptionVar":"desc","publishedTimeVar":"publishedAt","introVar":"desc","bullets":[{"label":"Module","template":"`{namespace}/{name}/{provider}`"},{"label":"Version","template":"`{version}`"},{"label":"Status","template":"{verified}","whenVar":"verified"},{"label":"Downloads","template":"{downloads}","whenVar":"downloads"},{"label":"Published","template":"{publishedAt}","whenVar":"publishedAt"},{"label":"Source","template":"{source}","whenVar":"source"}],"bodyVar":"readme","sections":[{"heading":"Inputs","arrayPath":"root.inputs","limit":60,"columns":[{"header":"Name","paths":["name"],"code":true},{"header":"Type","paths":["type"],"code":true},{"header":"Required","paths":["required"]},{"header":"Description","paths":["description"]}]},{"heading":"Outputs","arrayPath":"root.outputs","limit":40,"columns":[{"header":"Name","paths":["name"],"code":true},{"header":"Description","paths":["description"]}]},{"heading":"Submodules","arrayPath":"submodules","limit":30,"columns":[{"header":"Name","paths":["name"],"code":true},{"header":"Path","paths":["path"],"code":true}]}],"linksVars":["source"]}},{"match":{"exactSegments":true,"pathSegments":["modules",{"param":"ns","charset":"pkg","minLen":1,"maxLen":80},{"param":"name","charset":"pkg","minLen":1,"maxLen":80},{"param":"provider","charset":"pkg","minLen":1,"maxLen":80},{"param":"ver","charset":"alnum","allowValues":["latest"],"minLen":6,"maxLen":6}]},"twin":{"fetchUrl":"https://registry.terraform.io/v1/modules/{ns}/{name}/{provider}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"requireFields":["namespace","name","provider","version"],"vars":{"namespace":{"paths":["namespace"]},"name":{"paths":["name"]},"provider":{"paths":["provider"]},"version":{"paths":["version"]},"verified":{"paths":["verified"],"format":"bool_map","trueValue":"Verified","falseValue":"Unverified"},"downloads":{"paths":["downloads"],"format":"int_comma"},"publishedAt":{"paths":["published_at"],"sliceMax":10},"desc":{"paths":["description"],"trim":true},"source":{"paths":["source"],"requireHttps":true},"readme":{"paths":["root.readme"],"format":"demote_h1","trim":true}},"titleTemplate":"{namespace}/{name}/{provider} v{version} (Terraform Module)","descriptionVar":"desc","publishedTimeVar":"publishedAt","introVar":"desc","bullets":[{"label":"Module","template":"`{namespace}/{name}/{provider}`"},{"label":"Version","template":"`{version}`"},{"label":"Status","template":"{verified}","whenVar":"verified"},{"label":"Downloads","template":"{downloads}","whenVar":"downloads"},{"label":"Published","template":"{publishedAt}","whenVar":"publishedAt"},{"label":"Source","template":"{source}","whenVar":"source"}],"bodyVar":"readme","sections":[{"heading":"Inputs","arrayPath":"root.inputs","limit":60,"columns":[{"header":"Name","paths":["name"],"code":true},{"header":"Type","paths":["type"],"code":true},{"header":"Required","paths":["required"]},{"header":"Description","paths":["description"]}]},{"heading":"Outputs","arrayPath":"root.outputs","limit":40,"columns":[{"header":"Name","paths":["name"],"code":true},{"header":"Description","paths":["description"]}]},{"heading":"Submodules","arrayPath":"submodules","limit":30,"columns":[{"header":"Name","paths":["name"],"code":true},{"header":"Path","paths":["path"],"code":true}]}],"linksVars":["source"]}},{"match":{"exactSegments":true,"pathSegments":["modules",{"param":"ns","charset":"pkg","minLen":1,"maxLen":80},{"param":"name","charset":"pkg","minLen":1,"maxLen":80},{"param":"provider","charset":"pkg","minLen":1,"maxLen":80}]},"twin":{"fetchUrl":"https://registry.terraform.io/v1/modules/{ns}/{name}/{provider}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"requireFields":["namespace","name","provider","version"],"vars":{"namespace":{"paths":["namespace"]},"name":{"paths":["name"]},"provider":{"paths":["provider"]},"version":{"paths":["version"]},"verified":{"paths":["verified"],"format":"bool_map","trueValue":"Verified","falseValue":"Unverified"},"downloads":{"paths":["downloads"],"format":"int_comma"},"publishedAt":{"paths":["published_at"],"sliceMax":10},"desc":{"paths":["description"],"trim":true},"source":{"paths":["source"],"requireHttps":true},"readme":{"paths":["root.readme"],"format":"demote_h1","trim":true}},"titleTemplate":"{namespace}/{name}/{provider} v{version} (Terraform Module)","descriptionVar":"desc","publishedTimeVar":"publishedAt","introVar":"desc","bullets":[{"label":"Module","template":"`{namespace}/{name}/{provider}`"},{"label":"Version","template":"`{version}`"},{"label":"Status","template":"{verified}","whenVar":"verified"},{"label":"Downloads","template":"{downloads}","whenVar":"downloads"},{"label":"Published","template":"{publishedAt}","whenVar":"publishedAt"},{"label":"Source","template":"{source}","whenVar":"source"}],"bodyVar":"readme","sections":[{"heading":"Inputs","arrayPath":"root.inputs","limit":60,"columns":[{"header":"Name","paths":["name"],"code":true},{"header":"Type","paths":["type"],"code":true},{"header":"Required","paths":["required"]},{"header":"Description","paths":["description"]}]},{"heading":"Outputs","arrayPath":"root.outputs","limit":40,"columns":[{"header":"Name","paths":["name"],"code":true},{"header":"Description","paths":["description"]}]},{"heading":"Submodules","arrayPath":"submodules","limit":30,"columns":[{"header":"Name","paths":["name"],"code":true},{"header":"Path","paths":["path"],"code":true}]}],"linksVars":["source"]}}]},{"id":"threads-api","name":"Meta Threads Graph API","category":"commerce-social","description":"Extracts Threads profiles, posts, replies, and search results via official graph.threads.net v1.0 JSON endpoints (THREADS_ACCESS_TOKEN) with threads.net / threads.com public HTML fallback.","domains":["graph.threads.net","www.threads.net","threads.net","www.threads.com","threads.com"],"auth_mode":"key","min_interval_ms":1000,"strict_robots":true,"exampleUrls":["https://graph.threads.net/v1.0/me?fields=id,username,name,threads_biography","https://www.threads.net/@threads"],"routes":[{"match":{"hosts":["graph.threads.net"],"pathPrefix":"/v1.0/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"threads_api_json"}}],"htmlRoutes":[{"id":"threads-api","match":{"hosts":["www.threads.net","threads.net","www.threads.com","threads.com"],"exactSegments":false},"mode":"threads_html"}]},{"id":"ticketmaster-discovery","name":"Ticketmaster Discovery API","category":"commerce-social","description":"Extracts Ticketmaster events, venues, and attractions via the official Ticketmaster Discovery API v2 with Schema.org Event JSON-LD HTML fallback.","domains":["ticketmaster.com","www.ticketmaster.com","app.ticketmaster.com"],"auth_mode":"key","exampleUrls":["https://app.ticketmaster.com/discovery/v2/events.json?keyword=concert&countryCode=US","https://www.ticketmaster.com/demo-tour-los-angeles-california-12-01-2026/event/3C006457CF441F75"],"routes":[{"match":{"hosts":["app.ticketmaster.com"],"pathPrefix":"/discovery/v2/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"key"},"extract":{"jsonMode":"ticketmaster_json"}},{"match":{"hosts":["ticketmaster.com","www.ticketmaster.com"],"scanSegment":{"afterLiteral":"event","param":"eventId","charset":"alnum","minLen":6,"maxLen":32}},"twin":{"fetchUrl":"https://app.ticketmaster.com/discovery/v2/events/{eventId}.json","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"key"},"extract":{"jsonMode":"ticketmaster_json"}}],"htmlRoutes":[{"id":"ticketmaster-discovery","match":{"hosts":["ticketmaster.com","www.ticketmaster.com"],"exactSegments":false},"mode":"ticketmaster_html"}]},{"id":"tmdb","name":"The Movie Database (TMDB)","category":"commerce-social","description":"Official keyed TMDB v3 API adapter (TMDB_API_KEY) for movies, TV series, people, and collections, with public themoviedb.org JSON-LD and DOM fallback.","domains":["api.themoviedb.org","www.themoviedb.org","themoviedb.org"],"auth_mode":"key","min_interval_ms":1000,"exampleUrls":["https://www.themoviedb.org/movie/550","https://api.themoviedb.org/3/movie/550","https://www.themoviedb.org/tv/1396"],"routes":[{"match":{"hosts":["api.themoviedb.org"],"pathPrefix":"/3/","exactSegments":false},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"tmdb_json"}},{"match":{"hosts":["www.themoviedb.org","themoviedb.org"],"optionalLeadingLocale":true,"exactSegments":true,"pathSegments":[{"param":"entityType","allowValues":["movie","tv","person","collection"]},{"param":"tmdbId","charset":"leading_digits_slug","transform":"leading_digits","minLen":1,"maxLen":220}]},"twin":{"fetchUrl":"https://api.themoviedb.org/3/{entityType}/{tmdbId}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"tmdb_json"}}],"htmlRoutes":[{"id":"tmdb","match":{"hosts":["www.themoviedb.org","themoviedb.org"],"exactSegments":false},"mode":"tmdb_html"}]},{"id":"townnews-blox","name":"TownNews BLOX CMS","category":"commerce-social","description":"Extracts TownNews BLOX ?f=json news asset twins and discovers tncms/bloxcms markers on local publisher HTML pages.","domains":["lancasteronline.com"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://lancasteronline.com/sports/highschool/football/district-3-gold-piaa-glory-up-for-grabs-for-4-l-l-league-football-teams/article_a6f1fede-b459-44f2-a5cd-8224c48f76a8.html"],"routes":[{"match":{"hosts":["lancasteronline.com"],"pathSuffix":".html"},"twin":{"fetchUrl":"{requestUrl}","setQueryParams":{"f":"json"},"kind":"json","accept":"application/json"},"extract":{"jsonMode":"townnews_blox_json"}}],"htmlRoutes":[{"id":"townnews-blox","match":{"exactSegments":false},"mode":"townnews_blox_html"}]},{"id":"tq-ebike","name":"TQ e-Mobility Products & Support","category":"commerce-social","description":"Extracts Product JSON-LD, drive system technical specs, and support documentation from www.tq-ebike.com product and help-support pages.","domains":["www.tq-ebike.com","tq-ebike.com"],"exampleUrls":["https://www.tq-ebike.com/en/e-bike-system/hpr50/"],"htmlRoutes":[{"id":"tq-ebike","mode":"dom","match":{"optionalLeadingLocale":true,"exactSegments":false,"anyOf":[{"pathSegments":["products",{"param":"slug","charset":"safe_subpath","greedy":true,"minLen":1,"maxLen":160}]},{"pathSegments":["e-bike-system",{"param":"slug","charset":"safe_subpath","greedy":true,"minLen":1,"maxLen":160}]},{"pathSegments":["help-support",{"param":"slug","charset":"safe_subpath","greedy":true,"minLen":1,"maxLen":160}]}]},"jsonLdTypes":["Product"],"vars":{"title":{"jsonLdPaths":["name"],"cssText":["main h1","h1","title"],"trim":true},"sku":{"jsonLdPaths":["sku"],"trim":true},"brand":{"jsonLdPaths":["brand.name","brand"],"trim":true},"body":{"cssHtmlToMd":["main","article",".tx-specs",".site-content","body"],"format":"strip_leading_h1","trim":true}},"requireVars":["title","body"],"titleTemplate":"{title}","bullets":[{"label":"Brand","template":"{brand}","whenVar":"brand"},{"label":"SKU","template":"`{sku}`","whenVar":"sku"}],"bodyVar":"body","preserveBodyLinksFromVar":"body"}]},{"id":"trade-gov-csl","name":"Trade.gov Consolidated Screening List","category":"public-records","description":"Official keyed Trade.gov Consolidated Screening List (CSL) API adapter (TRADE_GOV_CSL_API_KEY via subscription-key header) with HTML fallback on www.trade.gov.","domains":["data.trade.gov","api.trade.gov","www.trade.gov","trade.gov"],"auth_mode":"key","exampleUrls":["https://data.trade.gov/consolidated_screening_list/v1/search?q=huawei","https://www.trade.gov/consolidated-screening-list"],"routes":[{"match":{"hosts":["data.trade.gov","api.trade.gov"],"pathPrefix":"/consolidated_screening_list/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":4194304},"extract":{"jsonMode":"trade_gov_csl_json"}}],"htmlRoutes":[{"id":"trade-gov-csl","match":{"hosts":["www.trade.gov","trade.gov"],"exactSegments":false},"mode":"trade_gov_csl_html"}]},{"id":"trailforks-mtb-project","name":"Trailforks & MTB Project Trail Intelligence","category":"commerce-social","description":"Official Trailforks API v1 key-authenticated twin + HTML fallback for Trailforks and MTB Project trail reports (honoring mtbproject.com Crawl-delay: 60 and Disallow: /data*).","domains":["trailforks.com","www.trailforks.com","mtbproject.com","www.mtbproject.com"],"auth_mode":"key","min_interval_ms":1000,"strict_robots":true,"exampleUrls":["https://www.trailforks.com/trails/betasso-preserve-canyon-loop/","https://www.trailforks.com/api/1/trail?id=40401","https://www.mtbproject.com/trail/12376/buffehr-creek-trail"],"routes":[{"match":{"hosts":["trailforks.com","www.trailforks.com"],"pathEquals":["/api/1/trail","/api/1/trail/","/api/1/trails","/api/1/trails/"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"trailforks_api_json"}},{"match":{"hosts":["trailforks.com","www.trailforks.com"],"pathSegments":["trails",{"param":"slug","charset":"url_seg","minLen":1,"maxLen":160}],"exactSegments":false},"twin":{"fetchUrl":"https://www.trailforks.com/api/1/trail?id={slug}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"trailforks_api_json"}}],"htmlRoutes":[{"id":"trailforks-mtb-project","match":{"exactSegments":false},"mode":"trailforks_mtb_html"}]},{"id":"transitland-gtfs","name":"Transitland GTFS Registry","category":"public-records","description":"Transitland v2 REST API (apikey header on apex transit.land) for GTFS feeds/operators/routes/stops with www.transit.land/data/feeds HTML fallback.","domains":["transit.land","www.transit.land"],"auth_mode":"key","exampleUrls":["https://transit.land/api/v2/rest/feeds?limit=1","https://www.transit.land/data/feeds/f-9q9-bart"],"routes":[{"match":{"hosts":["transit.land"],"pathPrefix":"/api/v2/rest/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"transitland_json"}},{"match":{"hosts":["www.transit.land","transit.land"],"exactSegments":true,"pathSegments":["data","feeds",{"param":"feedId","charset":"alnum_dash","minLen":2,"maxLen":80}]},"twin":{"fetchUrl":"https://transit.land/api/v2/rest/feeds/{feedId}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"transitland_json"}}],"htmlRoutes":[{"id":"transitland-gtfs","match":{"hosts":["www.transit.land","transit.land"],"exactSegments":false},"mode":"transitland_html"}]},{"id":"treasury-fiscal-data","name":"U.S. Treasury Fiscal Data","category":"finance","description":"Upgrades fiscaldata.treasury.gov dataset pages to keyless api.fiscaldata.treasury.gov JSON endpoints with metadata-labeled GFM tables and HTML fallback.","domains":["fiscaldata.treasury.gov","api.fiscaldata.treasury.gov"],"auth_mode":"pub","exampleUrls":["https://fiscaldata.treasury.gov/datasets/debt-to-the-penny/debt-to-the-penny","https://api.fiscaldata.treasury.gov/services/api/fiscal_service/v2/accounting/od/debt_to_penny?page[size]=1"],"routes":[{"match":{"hosts":["api.fiscaldata.treasury.gov"],"pathPrefix":"/services/api/fiscal_service/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"pub","maxBytes":2097152},"extract":{"jsonMode":"treasury_fiscal_json"}},{"match":{"hosts":["fiscaldata.treasury.gov"],"pathPrefix":"/datasets/debt-to-the-penny"},"twin":{"fetchUrl":"https://api.fiscaldata.treasury.gov/services/api/fiscal_service/v2/accounting/od/debt_to_penny?sort=-record_date&page[size]=1","kind":"json","accept":"application/json","auth_mode":"pub","maxBytes":2097152},"extract":{"jsonMode":"treasury_fiscal_json"}}],"htmlRoutes":[{"id":"treasury-fiscal-data","match":{"hosts":["fiscaldata.treasury.gov"],"exactSegments":false},"mode":"treasury_fiscal_html"}]},{"id":"trustpilot","name":"Trustpilot Business Reviews","category":"commerce-social","description":"Extracts Trustpilot business summary and review records from __NEXT_DATA__ or JSON-LD while honoring robots.txt policies.","domains":["trustpilot.com","www.trustpilot.com"],"auth_mode":"html","exampleUrls":["https://www.trustpilot.com/review/shopify.com"],"htmlRoutes":[{"id":"trustpilot","match":{"hosts":["trustpilot.com","www.trustpilot.com"],"exactSegments":false},"mode":"trustpilot_html"}]},{"id":"tumblr","name":"Tumblr Blogs & Posts","category":"commerce-social","description":"Extracts Tumblr blog info and posts via official api.tumblr.com/v2/blog/ JSON (TUMBLR_API_KEY) and www.tumblr.com SSR HTML (___INITIAL_STATE___ + og:*), avoiding PoW-gated *.tumblr.com subdomains.","domains":["api.tumblr.com","www.tumblr.com"],"auth_mode":"key","min_interval_ms":1000,"strict_robots":true,"exampleUrls":["https://www.tumblr.com/staff","https://www.tumblr.com/staff/828009069026721792/premium-just-got-better","https://api.tumblr.com/v2/blog/staff.tumblr.com/posts"],"routes":[{"match":{"hosts":["api.tumblr.com"],"pathPrefix":"/v2/blog/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"tumblr_api_json"}}],"htmlRoutes":[{"id":"tumblr","match":{"hosts":["www.tumblr.com"],"reservedFirstSegment":["dashboard","liked","search","login","register","settings","explore","following","activity","inbox","help","policy","privacy","terms"],"exactSegments":false},"mode":"tumblr_html"}]},{"id":"tvmaze","name":"TVmaze TV Shows & Episodes","category":"commerce-social","description":"Public TVmaze REST API adapter for TV shows, embedded episodes, people, and schedule data, with www.tvmaze.com HTML fallback.","domains":["api.tvmaze.com","www.tvmaze.com","tvmaze.com"],"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://api.tvmaze.com/shows/1?embed=episodes","https://www.tvmaze.com/shows/1/under-the-dome"],"routes":[{"match":{"hosts":["api.tvmaze.com"],"anyOf":[{"pathPrefix":"/shows/"},{"pathPrefix":"/episodes/"},{"pathPrefix":"/people/"},{"pathPrefix":"/search/"}],"exactSegments":false},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"tvmaze_json"}},{"match":{"hosts":["www.tvmaze.com","tvmaze.com"],"anyOf":[{"exactSegments":true,"pathSegments":["shows",{"param":"showId","charset":"digits","minLen":1,"maxLen":12}]},{"exactSegments":true,"pathSegments":["shows",{"param":"showId","charset":"digits","minLen":1,"maxLen":12},{"param":"showSlug","charset":"url_seg","reserved":["episodes","seasons","cast","crew","characters","gallery","news"],"minLen":1,"maxLen":120}]}]},"twin":{"fetchUrl":"https://api.tvmaze.com/shows/{showId}?embed=episodes","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"tvmaze_json"}}],"htmlRoutes":[{"id":"tvmaze","match":{"hosts":["www.tvmaze.com","tvmaze.com"],"exactSegments":false},"mode":"tvmaze_html"}]},{"id":"twitch-kick","name":"Twitch & Kick Streaming","category":"commerce-social","description":"Extracts Twitch Helix (Bearer + Client-Id) and Kick public v1/v2 channel APIs plus Twitch/Kick channel HTML.","domains":["api.twitch.tv","www.twitch.tv","twitch.tv","api.kick.com","kick.com","www.kick.com"],"auth_mode":"key","exampleUrls":["https://kick.com/api/v2/channels/kick","https://www.twitch.tv/twitch","https://kick.com/kick","https://api.twitch.tv/helix/users?login=twitch"],"routes":[{"match":{"hosts":["api.twitch.tv"],"pathPrefix":"/helix/","exactSegments":false},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key"},"extract":{"jsonMode":"twitch_kick_json"}},{"match":{"hosts":["api.kick.com"],"pathPrefix":"/public/v1/","exactSegments":false},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key"},"extract":{"jsonMode":"twitch_kick_json"}},{"match":{"hosts":["kick.com","www.kick.com"],"exactSegments":true,"pathSegments":["api","v2","channels",{"param":"slug","charset":"slug","minLen":1,"maxLen":80}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"pub"},"extract":{"jsonMode":"twitch_kick_json"}}],"htmlRoutes":[{"id":"twitch-kick","match":{"hosts":["www.twitch.tv","twitch.tv","kick.com","www.kick.com"],"exactSegments":false},"mode":"twitch_kick_html"}]},{"id":"tyler-energov","name":"Tyler Technologies EnerGov SelfService","category":"public-records","description":"Extracts public permit, plan, and license records from Tyler EnerGov SelfService APIs and SSR HTML while rejecting empty AngularJS shells and WAF challenges.","domains":["energovweb.capecoral.gov","energovcss.miamibeachfl.gov"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://energovweb.capecoral.gov/EnerGovProd/selfservice","https://energovcss.miamibeachfl.gov/energovprod/selfservice/"],"routes":[{"match":{"anyOf":[{"pathPrefix":"/EnerGov_Prod/SelfService/api/"},{"pathPrefix":"/EnerGovProd/selfservice/api/"},{"pathPrefix":"/energovprod/selfservice/api/"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"tyler_energov_json"}}],"htmlRoutes":[{"id":"tyler-energov","match":{"exactSegments":false},"mode":"tyler_energov_html"}]},{"id":"ukg-paylocity-dover","name":"UKG Pro, Paylocity & Dover Job Boards","category":"jobs","description":"Extracts structured open roles from Paylocity (/recruiting/api/feed/jobs & window.pageData), UKG Pro (*/JobBoard/* only, never / or */JobBoardView), and Dover HTML/SSR __NEXT_DATA__ (never /api/).","domains":["recruiting.ultipro.com","recruiting.paylocity.com","app.dover.com","jobs.dover.com"],"exampleUrls":["https://recruiting.paylocity.com/Recruiting/Jobs/All/cfe0e892-760a-4f34-b732-e6d0be968d4f"],"routes":[{"match":{"hosts":["recruiting.paylocity.com"],"pathPrefix":"/recruiting/jobs/all/","scanSegment":{"afterLiteral":"all","param":"guid","charset":"slug","minLen":4,"maxLen":80}},"twin":{"fetchUrl":"https://recruiting.paylocity.com/recruiting/api/feed/jobs/{guid}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"paylocity_feed"}},{"match":{"hosts":["recruiting.paylocity.com"],"pathPrefix":"/recruiting/api/feed/jobs/","scanSegment":{"afterLiteral":"jobs","param":"guid","charset":"slug","minLen":4,"maxLen":80}},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"paylocity_feed"}}],"htmlRoutes":[{"id":"ukg-paylocity-dover","mode":"ukg_pro_html","match":{"hosts":["recruiting.ultipro.com"],"pathContainsSegment":"JobBoard","minSegments":3}},{"id":"ukg-paylocity-dover","mode":"paylocity_html","match":{"hosts":["recruiting.paylocity.com"],"pathPrefix":"/recruiting/jobs/"}},{"id":"ukg-paylocity-dover","mode":"dover_html","match":{"anyOf":[{"hosts":["app.dover.com"],"exactSegments":false,"pathSegments":["jobs",{"param":"org","charset":"slug","minLen":1,"maxLen":120}]},{"hosts":["jobs.dover.com"],"minSegments":1,"reservedFirstSegment":["api","apply","static","assets","_next","login"]}]}}]},{"id":"ul-product-iq","name":"UL Product iQ & UL iQ Certifications","category":"public-records","description":"Extracts UL 2849 / UL 2271 e-bike and battery certification listings from iq.ul.com and UL Product iQ (disjoint from ul.com owned by cpsc-ebike-battery) while rejecting blocked/WAF shells.","domains":["iq.ul.com","productiq.ulprospector.com","iq.ulprospector.com"],"auth_mode":"html","min_interval_ms":1000,"exampleUrls":["https://iq.ul.com/"],"htmlRoutes":[{"id":"ul-product-iq","match":{"exactSegments":false},"mode":"ul_product_iq_html"}]},{"id":"unpaywall","name":"Unpaywall Open Access Resolver","category":"research-health","description":"Resolves scholarly DOI open-access status, licenses, best OA PDF locations, and author metadata via api.unpaywall.org/v2 (strictly enforcing ?email=bot@edgefetch.dev).","domains":["api.unpaywall.org","unpaywall.org","www.unpaywall.org"],"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://api.unpaywall.org/v2/10.1038/s41586-021-03819-2?email=bot@edgefetch.dev"],"routes":[{"match":{"hosts":["api.unpaywall.org"],"exactSegments":true,"pathEquals":["/v2/search"]},"twin":{"fetchUrl":"{requestUrl}","setQueryParams":{"email":"bot@edgefetch.dev"},"kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"unpaywall_json"}},{"match":{"hosts":["api.unpaywall.org"],"pathSegments":["v2",{"param":"doi","charset":"doi_rest","greedy":true,"minLen":8,"maxLen":240}]},"twin":{"fetchUrl":"{requestUrl}","setQueryParams":{"email":"bot@edgefetch.dev"},"kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"unpaywall_json"}}],"htmlRoutes":[{"id":"unpaywall","match":{"hosts":["unpaywall.org","www.unpaywall.org"],"exactSegments":false},"mode":"unpaywall_html"}]},{"id":"upcitemdb-barcodelookup","name":"UPCitemdb & Barcode Lookup","category":"commerce-social","description":"Extracts GTIN/UPC/EAN product identity, brand, category, and pricing from UPCitemdb (public trial + keyed v1), Barcode Lookup v3 (keyed), and upcitemdb.com HTML with strict 8/12/13/14-digit GTIN validation.","domains":["api.upcitemdb.com","www.upcitemdb.com","upcitemdb.com","api.barcodelookup.com","www.barcodelookup.com","barcodelookup.com"],"auth_mode":"key","min_interval_ms":1000,"exampleUrls":["https://api.upcitemdb.com/prod/trial/lookup?upc=012000161155","https://www.upcitemdb.com/upc/012000161155","https://api.barcodelookup.com/v3/products?barcode=012000161155"],"routes":[{"match":{"hosts":["api.upcitemdb.com"],"pathEquals":["/prod/trial/lookup"],"anyOf":[{"queryParams":[{"name":"upc","param":"upc","charset":"digits","minLen":8,"maxLen":8}]},{"queryParams":[{"name":"upc","param":"upc","charset":"digits","minLen":12,"maxLen":14}]}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"pub","maxBytes":2097152},"extract":{"jsonMode":"upcitemdb_json"}},{"match":{"hosts":["api.upcitemdb.com"],"pathEquals":["/prod/v1/lookup"],"anyOf":[{"queryParams":[{"name":"upc","param":"upc","charset":"digits","minLen":8,"maxLen":8}]},{"queryParams":[{"name":"upc","param":"upc","charset":"digits","minLen":12,"maxLen":14}]}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"upcitemdb_json"}},{"match":{"hosts":["api.barcodelookup.com"],"pathEquals":["/v3/products"],"anyOf":[{"queryParams":[{"name":"barcode","param":"barcode","charset":"digits","minLen":8,"maxLen":8}]},{"queryParams":[{"name":"barcode","param":"barcode","charset":"digits","minLen":12,"maxLen":14}]}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"barcodelookup_json"}}],"htmlRoutes":[{"id":"upcitemdb-barcodelookup","match":{"hosts":["www.upcitemdb.com","upcitemdb.com","www.barcodelookup.com","barcodelookup.com"],"exactSegments":false},"mode":"upcitemdb_barcodelookup_html"}]},{"id":"us-cfr-govinfo","name":"U.S. CFR & GovInfo","category":"public-records","description":"Bypasses the empty Angular /app/details/ SPA on govinfo.gov by fetching static /content/pkg//html/*.htm documents or /wssearch/getContentDetail summary JSON.","domains":["www.govinfo.gov","govinfo.gov"],"exampleUrls":["https://www.govinfo.gov/app/details/CFR-2023-title16-vol2/CFR-2023-title16-vol2-part1500","https://www.govinfo.gov/app/details/CFR-2023-title16-vol2","https://www.govinfo.gov/wssearch/getContentDetail?packageId=CFR-2023-title16-vol2"],"routes":[{"match":{"exactSegments":true,"pathSegments":["app","details",{"param":"pkgId","charset":"pkg","minLen":4,"maxLen":120},{"param":"granuleId","charset":"pkg","minLen":4,"maxLen":160}]},"twin":{"fetchUrl":"https://www.govinfo.gov/content/pkg/{pkgId}/html/{granuleId}.htm","kind":"text","accept":"text/html","maxBytes":4194304},"extract":{"textMode":"html_document","titleTemplate":"{granuleId} ({pkgId})"}},{"match":{"exactSegments":true,"pathSegments":["app","details",{"param":"pkgId","charset":"pkg","minLen":4,"maxLen":120}]},"twin":{"fetchUrl":"https://www.govinfo.gov/content/pkg/{pkgId}/html/{pkgId}.htm","kind":"text","accept":"text/html","maxBytes":4194304},"extract":{"textMode":"html_document","titleTemplate":"{pkgId}"}},{"match":{"pathEquals":["/wssearch/getContentDetail"],"queryParams":[{"name":"packageId","param":"pkgId","charset":"pkg","minLen":4,"maxLen":120},{"name":"granuleId","param":"granuleId","charset":"pkg","optional":true,"maxLen":160}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"requireAnyFields":["title","packageId"],"vars":{"title":{"paths":["title"],"fallbackTemplate":"{pkgId}","trim":true},"packageId":{"paths":["packageId"],"fallbackTemplate":"{pkgId}"},"collection":{"paths":["collectionName","collection","collectionCode"]},"category":{"paths":["category"]},"dateIssued":{"paths":["dateIssued"]},"lastModified":{"paths":["lastModified"],"sliceMax":10},"authors":{"paths":["governmentAuthor","metadata.agency"],"join":", ","limit":10},"granuleCount":{"paths":["granuleCount"],"format":"int_comma"},"pdfLink":{"paths":["download.pdfLink"],"requireHttps":true},"htmlLink":{"paths":["download.htmlLink","download.htmLink"],"requireHttps":true},"xmlLink":{"paths":["download.xmlLink"],"requireHttps":true},"txtLink":{"paths":["download.txtLink"],"requireHttps":true},"zipLink":{"paths":["download.zipLink"],"requireHttps":true},"modsLink":{"paths":["download.modsLink"],"requireHttps":true}},"titleTemplate":"{title}","authorVar":"authors","publishedTimeVar":"dateIssued","bullets":[{"label":"Package ID","template":"`{packageId}`","whenVar":"packageId"},{"label":"Collection","template":"{collection}","whenVar":"collection"},{"label":"Category","template":"{category}","whenVar":"category"},{"label":"Date Issued","template":"{dateIssued}","whenVar":"dateIssued"},{"label":"Last Modified","template":"{lastModified}","whenVar":"lastModified"},{"label":"Government Author","template":"{authors}","whenVar":"authors"},{"label":"Granules","template":"{granuleCount}","whenVar":"granuleCount"},{"label":"PDF Download","template":"{pdfLink}","whenVar":"pdfLink"},{"label":"HTML Download","template":"{htmlLink}","whenVar":"htmlLink"},{"label":"XML Download","template":"{xmlLink}","whenVar":"xmlLink"},{"label":"Text Download","template":"{txtLink}","whenVar":"txtLink"},{"label":"ZIP Archive","template":"{zipLink}","whenVar":"zipLink"}],"linksVars":["pdfLink","htmlLink","xmlLink","txtLink","zipLink","modsLink"]}}]},{"id":"us-ebike-oems","name":"US E-Bike OEMs (Gazelle, Electra, Benno, Pedego, Serial 1)","category":"commerce-social","description":"Extracts Class 1/2/3 ratings, battery Wh, motor specs, and model specifications from Gazelle, Electra, Benno, Pedego, and Serial 1.","domains":["gazellebikes.com","www.gazellebikes.com","electra.trekbikes.com","bennobikes.com","www.bennobikes.com","pedegoelectricbikes.com","www.pedegoelectricbikes.com","serial1.com","www.serial1.com"],"auth_mode":"html","min_interval_ms":1000,"exampleUrls":["https://www.gazellebikes.com/en-us/models/gazelle-arroyo","https://electra.trekbikes.com/us/en_US/bikes/electra-bikes/c/EB100/","https://bennobikes.com/e-bikes/boost/","https://pedegoelectricbikes.com/products/interceptor"],"htmlRoutes":[{"id":"us-ebike-oems","match":{"exactSegments":false},"mode":"us_ebike_oems_html"}]},{"id":"usajobs","name":"USAJOBS Federal Jobs","category":"jobs","description":"Extracts federal job search listings and codelists from data.usajobs.gov (with Authorization-Key + User-Agent) and JobPosting/HTML job details from www.usajobs.gov.","domains":["data.usajobs.gov","www.usajobs.gov","usajobs.gov"],"auth_mode":"key","user_agent_profile":"usajobs","strict_robots":true,"exampleUrls":["https://data.usajobs.gov/api/search?Keyword=software","https://www.usajobs.gov/job/893002300"],"routes":[{"match":{"hosts":["data.usajobs.gov"],"anyOf":[{"pathPrefix":"/api/search"},{"pathPrefix":"/api/codelist/"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304,"auth_mode":"key"},"extract":{"jsonMode":"usajobs_json"}}],"htmlRoutes":[{"id":"usajobs","mode":"usajobs_html","match":{"hosts":["www.usajobs.gov","usajobs.gov"],"exactSegments":false}}]},{"id":"usaspending","name":"USAspending.gov Federal Awards","category":"public-records","description":"Upgrades usaspending.gov/award/ pages to api.usaspending.gov/api/v2/awards// JSON details.","domains":["www.usaspending.gov","usaspending.gov"],"exampleUrls":["https://www.usaspending.gov/award/CONT_AWD_ZSMG_9700_HTC71114DR027_9700"],"match":{"exactSegments":false,"pathSegments":["award",{"param":"awardId","charset":"pkg","minLen":4,"maxLen":140}]},"twin":{"fetchUrl":"https://api.usaspending.gov/api/v2/awards/{awardId}/","kind":"json","accept":"application/json"},"extract":{"requireAnyFields":["generated_unique_award_id","piid","fain"],"vars":{"idLabel":{"paths":["piid","fain","uri"],"fallbackTemplate":"{awardId}"},"category":{"paths":["category"],"default":"Federal Award"},"recipient":{"paths":["recipient.recipient_name"]},"awardingAgency":{"paths":["awarding_agency.toptier_agency.name"]},"fundingAgency":{"paths":["funding_agency.toptier_agency.name"]},"obligation":{"paths":["total_obligation"],"format":"usd_compact"},"desc":{"paths":["description"],"trim":true},"descShort":{"paths":["description"],"trim":true,"sliceMax":260},"startDate":{"paths":["period_of_performance.start_date"]},"hasPop":{"paths":["period_of_performance.start_date","period_of_performance.end_date"]},"startOrQ":{"paths":["period_of_performance.start_date"],"default":"?"},"endOrQ":{"paths":["period_of_performance.end_date"],"default":"?"}},"titleTemplate":"{idLabel} — {recipient} (USAspending)","titleWhenVar":"recipient","titleFallbackTemplate":"{idLabel} (USAspending)","descriptionVar":"descShort","publishedTimeVar":"startDate","bullets":[{"label":"Award ID","template":"`{idLabel}` ({category})"},{"label":"Recipient","template":"{recipient}","whenVar":"recipient"},{"label":"Total Obligation","template":"{obligation}","whenVar":"obligation"},{"label":"Awarding Agency","template":"{awardingAgency}","whenVar":"awardingAgency"},{"label":"Funding Agency","template":"{fundingAgency}","whenVar":"fundingAgency"},{"label":"Period of Performance","template":"{startOrQ} → {endOrQ}","whenVar":"hasPop"}],"sections":[{"heading":"Award Description","textVar":"desc"}]}},{"id":"uscode-house","name":"U.S. Code (House OLRC)","category":"public-records","description":"HTML extractor for U.S. House Office of the Law Revision Counsel United States Code sections, title browse trees, and legacy /view.xhtml pages.","domains":["uscode.house.gov"],"auth_mode":"pub","exampleUrls":["https://uscode.house.gov/us/usc/t17/s107/","https://uscode.house.gov/browse.html","https://uscode.house.gov/us/usc/t17/frontmatter/"],"htmlRoutes":[{"id":"uscode-house","match":{"anyOf":[{"pathPrefix":"/us/usc/"},{"pathEquals":["/browse.html"]},{"pathPrefix":"/browse-tree/"},{"pathEquals":["/view.xhtml"]}]},"mode":"uscode_house_html"}]},{"id":"usda-nass-fdc","name":"USDA FoodData Central & NASS QuickStats","category":"research-health","description":"USDA FoodData Central REST API v1 (/fdc/v1/...) and NASS QuickStats (/api/api_GET/) adapter with Angular SPA shell guard.","domains":["quickstats.nass.usda.gov","fdc.nal.usda.gov","api.nal.usda.gov"],"auth_mode":"key","strict_robots":true,"exampleUrls":["https://api.nal.usda.gov/fdc/v1/food/171705","https://api.nal.usda.gov/fdc/v1/foods/search?query=avocado&pageSize=3","https://quickstats.nass.usda.gov/api/api_GET/?commodity_desc=CORN&year=2023&state_alpha=IA"],"routes":[{"match":{"hosts":["api.nal.usda.gov"],"exactSegments":true,"pathSegments":["fdc","v1","food",{"param":"fdcId","charset":"digits","minLen":1,"maxLen":16}]},"twin":{"fetchUrl":"https://api.nal.usda.gov/fdc/v1/food/{fdcId}","kind":"json","accept":"application/json","maxBytes":4194304,"auth_mode":"key"},"extract":{"jsonMode":"usda_fdc_json"}},{"match":{"hosts":["api.nal.usda.gov"],"exactSegments":false,"pathPrefix":"/fdc/v1/foods"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304,"auth_mode":"key"},"extract":{"jsonMode":"usda_fdc_json"}},{"match":{"hosts":["quickstats.nass.usda.gov"],"exactSegments":false,"pathEquals":["/api/api_GET","/api/api_GET/"]},"twin":{"fetchUrl":"{requestUrl}","defaultQueryParams":{"format":"JSON"},"kind":"json","accept":"application/json","maxBytes":4194304,"auth_mode":"key"},"extract":{"jsonMode":"usda_nass_json"}}],"htmlRoutes":[{"id":"usda-nass-fdc","match":{"hosts":["fdc.nal.usda.gov"],"exactSegments":false},"mode":"usda_fdc_html"}]},{"id":"used-bikes-shopify","name":"The Pro's Closet & Upway Used Bikes","category":"commerce-social","description":"Extracts certified pre-owned bicycle and e-bike listings from The Pro's Closet (Shopify JSON + HTML fallback) and Upway (Hydrogen + JSON-LD HTML) while honoring Upway's Crawl-delay and rejecting 404 homepage shells.","domains":["theproscloset.com","www.theproscloset.com","upway.co","www.upway.co"],"auth_mode":"pub","min_interval_ms":2000,"strict_robots":true,"exampleUrls":["https://www.theproscloset.com/products/10226226168000-cervelo-p-series-red-axs-time-trial-bike-2022-58cm","https://www.theproscloset.com/products.json?limit=5&page=1","https://upway.co/products/lane-lane-express-uaa01"],"routes":[{"match":{"hosts":["theproscloset.com","www.theproscloset.com"],"anyOf":[{"pathEquals":["/products.json"]},{"exactSegments":true,"pathSegments":["collections",{"param":"col","charset":"slug","maxLen":160},"products.json"]}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"commerceMode":"shopify_catalog_page"}},{"match":{"hosts":["theproscloset.com","www.theproscloset.com"],"pathSuffix":".json","scanSegment":{"afterLiteral":"products","param":"handle","charset":"slug","stripSuffix":".json","maxLen":160}},"twin":{"fetchUrl":"https://{host}/products/{handle}.json","kind":"json","accept":"application/json"},"extract":{"commerceMode":"shopify_product"}},{"match":{"hosts":["theproscloset.com","www.theproscloset.com"],"scanSegment":{"afterLiteral":"products","param":"handle","charset":"slug","stripSuffix":".js","maxLen":160}},"twin":{"fetchUrl":"https://{host}/products/{handle}.js","kind":"json","accept":"application/json"},"extract":{"commerceMode":"shopify_product_js"}}],"htmlRoutes":[{"id":"used-bikes-shopify","match":{"anyOf":[{"pathPrefix":"/products/"},{"pathPrefix":"/collections/"}]},"mode":"used_bikes_shopify_html"}]},{"id":"usfs-blm-trails","name":"USFS & BLM Trails ArcGIS Services","category":"public-records","description":"US Forest Service (apps.fs.usda.gov) and BLM (gis.blm.gov) ArcGIS MapServer/FeatureServer layer metadata and /query feature adapter, scoped off *.arcgis.com.","domains":["apps.fs.usda.gov","gis.blm.gov"],"auth_mode":"pub","exampleUrls":["https://gis.blm.gov/arcgis/rest/services/recreation/BLM_Natl_Recreation_Offline/FeatureServer/0/query?where=1%3D1&outFields=*&resultRecordCount=1&f=json","https://gis.blm.gov/arcgis/rest/services/recreation/BLM_Natl_Recs_pts/MapServer/0?f=json","https://gis.blm.gov/arcgis/rest/services/transportation/BLM_Natl_GTLF_Public_Display/MapServer?f=json"],"routes":[{"match":{"anyOf":[{"hosts":["apps.fs.usda.gov"],"pathPrefix":"/arcx/rest/services/","pathSuffix":"/query"},{"hosts":["gis.blm.gov"],"pathPrefix":"/arcgis/rest/services/","pathSuffix":"/query"}]},"twin":{"fetchUrl":"{requestUrl}","setQueryParams":{"f":"json"},"defaultQueryParams":{"where":"1=1","outFields":"*","returnGeometry":"false","resultRecordCount":"25"},"kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"usfs_blm_trails_json"}},{"match":{"anyOf":[{"hosts":["apps.fs.usda.gov"],"pathPrefix":"/arcx/rest/services/","arcgisRestLayer":true},{"hosts":["gis.blm.gov"],"pathPrefix":"/arcgis/rest/services/","arcgisRestLayer":true}]},"twin":{"fetchUrl":"{requestUrl}","setQueryParams":{"f":"json"},"kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"usfs_blm_trails_json"}}]},{"id":"usgs-earthquakes","name":"USGS Earthquake Hazards Program","category":"research-health","description":"USGS GeoJSON earthquake summary feeds, FDSNWS Event Query API, and eventpage JSON twins.","domains":["earthquake.usgs.gov"],"auth_mode":"pub","exampleUrls":["https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/4.5_day.geojson","https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&limit=5&minmagnitude=4.5","https://earthquake.usgs.gov/earthquakes/eventpage/us6000ue1k/executive"],"routes":[{"match":{"hosts":["earthquake.usgs.gov"],"anyOf":[{"pathPrefix":"/earthquakes/feed/"},{"pathPrefix":"/fdsnws/event/"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"usgs_earthquakes_json"}},{"match":{"hosts":["earthquake.usgs.gov"],"exactSegments":false,"pathSegments":["earthquakes","eventpage",{"param":"eventId","charset":"alnum_dash","minLen":4,"maxLen":40}]},"twin":{"fetchUrl":"https://earthquake.usgs.gov/fdsnws/event/1/query?eventid={eventId}&format=geojson","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"usgs_earthquakes_json"}}]},{"id":"usgs-water","name":"USGS Water Services & OGC API","category":"research-health","description":"USGS NWIS Water Services (WaterML JSON and tab-delimited RDB) and api.waterdata.usgs.gov OGC API GeoJSON adapter.","domains":["waterservices.usgs.gov","api.waterdata.usgs.gov","waterdata.usgs.gov"],"auth_mode":"pub","exampleUrls":["https://api.waterdata.usgs.gov/ogcapi/v0/collections/monitoring-locations?f=json","https://api.waterdata.usgs.gov/ogcapi/v0/collections?f=json"],"routes":[{"match":{"hosts":["waterservices.usgs.gov"],"pathPrefix":"/nwis/","queryParams":[{"name":"format","param":"fmt","allowValues":["rdb","rdb,1.0"]}]},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"text/plain","maxBytes":2097152},"extract":{"textMode":"usgs_water_rdb"}},{"match":{"hosts":["waterservices.usgs.gov"],"pathPrefix":"/nwis/"},"twin":{"fetchUrl":"{requestUrl}","setQueryParams":{"format":"json"},"kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"usgs_water_json"}},{"match":{"hosts":["api.waterdata.usgs.gov"],"pathPrefix":"/ogcapi/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"usgs_water_json"}},{"match":{"hosts":["waterdata.usgs.gov"],"exactSegments":false,"pathSegments":["monitoring-location",{"param":"siteNo","charset":"digits","minLen":5,"maxLen":15}]},"twin":{"fetchUrl":"https://waterservices.usgs.gov/nwis/iv/?format=json&sites={siteNo}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"usgs_water_json"}}]},{"id":"usitc-hts","name":"USITC Harmonized Tariff Schedule","category":"public-records","description":"Extracts U.S. Harmonized Tariff Schedule (HTS) tariff lines, duty rates, and Chapter 99 / Section 301 footnotes from hts.usitc.gov reststop JSON endpoints with SPA shell guards.","domains":["hts.usitc.gov"],"auth_mode":"pub","exampleUrls":["https://hts.usitc.gov/reststop/search?keyword=bicycle","https://hts.usitc.gov/reststop/exportList?from=8712.00&to=8712.00&format=JSON&styles=false"],"routes":[{"match":{"hosts":["hts.usitc.gov"],"exactSegments":true,"pathEquals":["/reststop/search"],"queryParams":[{"name":"keyword","param":"keyword","minLen":1,"maxLen":120}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"usitc_hts_json"}},{"match":{"hosts":["hts.usitc.gov"],"exactSegments":true,"pathEquals":["/reststop/exportList"],"queryParams":[{"name":"from","param":"from","minLen":2,"maxLen":16},{"name":"to","param":"to","minLen":2,"maxLen":16},{"name":"format","param":"format","allowValues":["JSON","json"],"optional":true,"default":"JSON"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"usitc_hts_json"}},{"match":{"hosts":["hts.usitc.gov"],"pathPrefix":"/reststop/","excludeSegmentSuffixes":[".csv",".xlsx",".pdf"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"usitc_hts_json"}}],"htmlRoutes":[{"id":"usitc-hts","match":{"hosts":["hts.usitc.gov"],"exactSegments":false},"mode":"usitc_hts_html"}]},{"id":"usps-addresses","name":"USPS Addresses v3 Official API","category":"public-records","description":"USPS Addresses v3 API for address standardization, city/state, and ZIP lookup (USPS_ACCESS_TOKEN) with developers.usps.com HTML fallback.","domains":["apis.usps.com","apis-tem.usps.com","developers.usps.com"],"auth_mode":"key","min_interval_ms":1000,"exampleUrls":["https://apis.usps.com/addresses/v3/address?streetAddress=475%20L%27Enfant%20Plaza%20SW&city=Washington&state=DC","https://apis.usps.com/addresses/v3/city-state?ZIPCode=20260"],"routes":[{"match":{"hosts":["apis.usps.com","apis-tem.usps.com"],"anyOf":[{"pathPrefix":"/addresses/v3/address"},{"pathPrefix":"/addresses/v3/city-state"},{"pathPrefix":"/addresses/v3/zipcode"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":1048576},"extract":{"jsonMode":"usps_addresses_json"}}],"htmlRoutes":[{"id":"usps-addresses","match":{"hosts":["developers.usps.com"],"exactSegments":false},"mode":"usps_docs_html"}]},{"id":"uspto-patentsview","name":"USPTO PatentsView & Open Data Portal","category":"public-records","description":"USPTO Open Data Portal (api.uspto.gov) patent application and PatentsView API JSON adapter with HTML fallback.","domains":["patentsview.org","www.patentsview.org","search.patentsview.org","api.patentsview.org","api.uspto.gov","data.uspto.gov"],"auth_mode":"key","min_interval_ms":1000,"exampleUrls":["https://api.uspto.gov/api/v1/patent/applications/16330077","https://api.uspto.gov/api/v1/patent/applications/search?q=16330077"],"routes":[{"match":{"hosts":["api.uspto.gov"],"pathPrefix":"/api/v1/patent/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"key"},"extract":{"jsonMode":"uspto_patentsview_json"}},{"match":{"hosts":["api.patentsview.org"],"pathPrefix":"/api/v1/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"key"},"extract":{"jsonMode":"uspto_patentsview_json"}},{"match":{"hosts":["patentsview.org","www.patentsview.org","search.patentsview.org","data.uspto.gov"],"exactSegments":false,"pathSegments":["patent",{"param":"patentId","charset":"alnum_dash","minLen":5,"maxLen":24}]},"twin":{"fetchUrl":"https://api.uspto.gov/api/v1/patent/applications/search?q={patentId}","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"key"},"extract":{"jsonMode":"uspto_patentsview_json"}},{"match":{"hosts":["patentsview.org","www.patentsview.org","search.patentsview.org","data.uspto.gov"],"exactSegments":false,"pathSegments":["patents",{"param":"patentId","charset":"alnum_dash","minLen":5,"maxLen":24}]},"twin":{"fetchUrl":"https://api.uspto.gov/api/v1/patent/applications/search?q={patentId}","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"key"},"extract":{"jsonMode":"uspto_patentsview_json"}}],"htmlRoutes":[{"id":"uspto-patentsview","match":{"hosts":["patentsview.org","www.patentsview.org","search.patentsview.org","data.uspto.gov"],"exactSegments":false},"mode":"uspto_patentsview_html"}]},{"id":"uspto-ppubs","name":"USPTO Patent Public Search (PPUBS)","category":"public-records","description":"USPTO Patent Public Search (ppubs.uspto.gov) HTML adapter rejecting empty SPA shells.","domains":["ppubs.uspto.gov","patft.uspto.gov"],"auth_mode":"html","min_interval_ms":1000,"exampleUrls":["https://ppubs.uspto.gov/basic/"],"htmlRoutes":[{"id":"uspto-ppubs","match":{"hosts":["ppubs.uspto.gov","patft.uspto.gov"],"exactSegments":false},"mode":"uspto_ppubs_html"}]},{"id":"uspto-tsdr","name":"USPTO TSDR Trademark Status","category":"public-records","description":"USPTO Trademark Status & Document Retrieval (TSDR) API JSON adapter with keyless tsdr.uspto.gov/statusview HTML fallback.","domains":["tsdr.uspto.gov","tsdrapi.uspto.gov"],"auth_mode":"key","min_interval_ms":1000,"exampleUrls":["https://tsdrapi.uspto.gov/ts/cd/casestatus/sn78787878/info.json","https://tsdr.uspto.gov/statusview/sn78787878"],"routes":[{"match":{"hosts":["tsdrapi.uspto.gov"],"pathPrefix":"/ts/cd/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"key"},"extract":{"jsonMode":"uspto_tsdr_json"}},{"match":{"hosts":["tsdr.uspto.gov"],"exactSegments":false,"pathSegments":["statusview",{"param":"caseNum","charset":"alnum","minLen":6,"maxLen":20}]},"twin":{"fetchUrl":"https://tsdrapi.uspto.gov/ts/cd/casestatus/{caseNum}/info.json","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"key"},"extract":{"jsonMode":"uspto_tsdr_json"}}],"htmlRoutes":[{"id":"uspto-tsdr","match":{"hosts":["tsdr.uspto.gov"],"exactSegments":false},"mode":"uspto_tsdr_html"}]},{"id":"ustr-301","name":"USTR Section 301 Trade Actions","category":"public-records","description":"Extracts U.S. Trade Representative Section 301 investigation actions, tariff lists, exclusion notices, and RSS feeds from ustr.gov.","domains":["ustr.gov","www.ustr.gov"],"auth_mode":"pub","exampleUrls":["https://ustr.gov/issue-areas/enforcement/section-301-investigations/tariff-actions","https://ustr.gov/issue-areas/enforcement/section-301-investigations/section-301-china/investigation","https://ustr.gov/rss.xml"],"routes":[{"match":{"hosts":["ustr.gov","www.ustr.gov"],"pathSuffix":".xml"},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"application/rss+xml","maxBytes":2097152},"extract":{"textMode":"ustr_301_rss_xml"}}],"htmlRoutes":[{"id":"ustr-301","match":{"hosts":["ustr.gov","www.ustr.gov"],"exactSegments":false},"mode":"ustr_301_html"}]},{"id":"va-lighthouse-facilities","name":"VA Lighthouse Facilities API","category":"research-health","description":"U.S. Department of Veterans Affairs Lighthouse Facilities API (VA_LIGHTHOUSE_API_KEY) with www.va.gov / developer.va.gov HTML fallback.","domains":["api.va.gov","sandbox-api.va.gov","www.va.gov","developer.va.gov"],"auth_mode":"key","min_interval_ms":1000,"exampleUrls":["https://api.va.gov/services/va_facilities/v1/facilities?state=TX&per_page=5","https://www.va.gov/boston-health-care/locations/brockton-va-medical-center"],"routes":[{"match":{"hosts":["api.va.gov","sandbox-api.va.gov"],"pathPrefix":"/services/va_facilities/v1/facilities"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"va_facilities_json"}}],"htmlRoutes":[{"id":"va-lighthouse-facilities","match":{"hosts":["www.va.gov","developer.va.gov"],"exactSegments":false},"mode":"va_facilities_html"}]},{"id":"vanilla-forums","name":"Vanilla Forums","category":"commerce-social","description":"Upgrades Vanilla Forums /discussion/{discussionID} URLs to same-origin /api/v2/discussions/{discussionID} JSON twins with HTML fallback.","domains":["forum.onshape.com","forum.polkaudio.com","forum.linuxfoundation.org"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://forum.onshape.com/discussion/32195/new-feature-codes","https://forum.onshape.com/api/v2/discussions/32195","https://forum.polkaudio.com/api/v2/discussions/163343"],"routes":[{"match":{"exactSegments":false,"pathSegments":["discussion",{"param":"discussionID","charset":"digits","minLen":1,"maxLen":16},{"param":"slug","charset":"safe_subpath","optional":true,"greedy":true}]},"twin":{"fetchUrl":"https://{host}/api/v2/discussions/{discussionID}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"vanilla_forums"}},{"match":{"exactSegments":true,"pathSegments":["api","v2","discussions"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"vanilla_forums"}},{"match":{"exactSegments":true,"pathSegments":["api","v2","discussions",{"param":"discussionID","charset":"digits","minLen":1,"maxLen":16}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"vanilla_forums"}}],"htmlRoutes":[{"id":"vanilla-forums","match":{"exactSegments":false},"mode":"vanilla_forums_html"}]},{"id":"vendor-csaf","name":"Vendor CSAF 2.0 Advisories & Provider Metadata","category":"developer","description":"Universal parser for OASIS CSAF 2.0 provider-metadata.json discovery files and CSAF 2.0 security advisory JSON documents across vendor CSIRTs.","domains":["security.access.redhat.com","cert-portal.siemens.com"],"universalEngine":true,"auth_mode":"pub","min_interval_ms":1000,"exampleUrls":["https://security.access.redhat.com/data/csaf/v2/provider-metadata.json","https://security.access.redhat.com/data/csaf/v2/advisories/2026/rhsa-2026_88339.json","https://cert-portal.siemens.com/productcert/csaf/provider-metadata.json"],"routes":[{"match":{"anyOf":[{"exactSegments":true,"pathEquals":["/.well-known/csaf/provider-metadata.json"]},{"pathSuffix":"/provider-metadata.json"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":1048576},"extract":{"jsonMode":"vendor_csaf_json"}},{"match":{"anyOf":[{"pathContainsSegment":"csaf","pathSuffix":".json"},{"pathPrefix":"/data/csaf/","pathSuffix":".json"},{"pathPrefix":"/cisagov/CSAF/","pathSuffix":".json"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"jsonMode":"vendor_csaf_json"}}]},{"id":"vimeo","name":"Vimeo Video & oEmbed","category":"commerce-social","description":"Extracts Vimeo video and player embed metadata via Vimeo oEmbed JSON and VideoObject HTML fallback.","domains":["vimeo.com","www.vimeo.com","player.vimeo.com"],"auth_mode":"pub","exampleUrls":["https://vimeo.com/76979871","https://vimeo.com/api/oembed.json?url=https%3A%2F%2Fvimeo.com%2F76979871","https://player.vimeo.com/video/76979871"],"routes":[{"match":{"hosts":["vimeo.com","www.vimeo.com"],"pathEquals":["/api/oembed.json"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"vimeo_oembed_json"}},{"match":{"hosts":["vimeo.com","www.vimeo.com"],"exactSegments":true,"pathSegments":[{"param":"videoId","charset":"digits","minLen":4,"maxLen":15}]},"twin":{"fetchUrl":"https://vimeo.com/api/oembed.json?url=https%3A%2F%2Fvimeo.com%2F{videoId}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"vimeo_oembed_json"}},{"match":{"hosts":["player.vimeo.com"],"exactSegments":true,"pathSegments":["video",{"param":"videoId","charset":"digits","minLen":4,"maxLen":15}]},"twin":{"fetchUrl":"https://vimeo.com/api/oembed.json?url=https%3A%2F%2Fvimeo.com%2F{videoId}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"vimeo_oembed_json"}}],"htmlRoutes":[{"id":"vimeo","match":{"exactSegments":false},"mode":"vimeo_html"}]},{"id":"vscode-open-vsx","name":"VS Code Marketplace & Open VSX","category":"developer","description":"Extracts IDE extension versions, publishers, licenses, and download metrics from open-vsx.org REST JSON and marketplace.visualstudio.com SSR HTML.","domains":["open-vsx.org","marketplace.visualstudio.com"],"auth_mode":"pub","min_interval_ms":2000,"exampleUrls":["https://open-vsx.org/api/esbenp/prettier-vscode","https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode"],"routes":[{"match":{"hosts":["open-vsx.org"],"pathPrefix":"/api/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":1048576},"extract":{"jsonMode":"open_vsx_json"}}],"htmlRoutes":[{"id":"vscode-open-vsx","match":{"hosts":["marketplace.visualstudio.com"],"pathEquals":["/items"],"queryParams":[{"name":"itemName","param":"itemName","charset":"pkg"}]},"mode":"vscode_marketplace_html"}]},{"id":"vtex","name":"VTEX Storefronts & Catalog API","category":"commerce-social","description":"Extracts VTEX storefront product JSON from /api/catalog_system/pub/products/search and /variations endpoints, plus post-HTML storefront JSON-LD and companion discovery.","domains":["www.motorola.com.br"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://www.motorola.com.br/api/catalog_system/pub/products/search?fq=productId:488"],"routes":[{"match":{"pathEquals":["/api/catalog_system/pub/products/search"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"commerceMode":"vtex_product"}},{"match":{"pathPrefix":"/api/catalog_system/pub/products/search/","pathSuffix":"/p"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"commerceMode":"vtex_product"}},{"match":{"pathSegments":["api","catalog_system","pub","products","variations",{"param":"productId","charset":"pkg","minLen":1,"maxLen":64}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"commerceMode":"vtex_product"}}],"htmlRoutes":[{"id":"vtex","match":{"exactSegments":false},"mode":"vtex_html"}]},{"id":"walmart","name":"Walmart Official Affiliate/IO API","category":"commerce-social","description":"Official Walmart Affiliate/IO API product lookup only (zero HTML scraping of walmart.com).","domains":["walmart.com","www.walmart.com","developer.api.walmart.com"],"auth_mode":"key","exampleUrls":["https://www.walmart.com/ip/132000132","https://developer.api.walmart.com/api-proxy/service/affil/product/v2/items/132000132"],"routes":[{"match":{"hosts":["walmart.com","www.walmart.com"],"anyOf":[{"exactSegments":true,"pathSegments":["ip",{"param":"itemId","charset":"digits","minLen":4,"maxLen":16}]},{"exactSegments":false,"pathSegments":["ip",{"param":"slug","charset":"url_seg","maxLen":200},{"param":"itemId","charset":"digits","minLen":4,"maxLen":16}]}]},"twin":{"fetchUrl":"https://developer.api.walmart.com/api-proxy/service/affil/product/v2/items/{itemId}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"walmart_json"}},{"match":{"hosts":["developer.api.walmart.com"],"pathPrefix":"/api-proxy/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"walmart_json"}}]},{"id":"weather-gov","name":"National Weather Service (weather.gov)","category":"research-health","description":"NOAA National Weather Service GeoJSON API (points, gridpoint forecasts, active alerts, observations) and forecast.weather.gov HTML extractor with identifying User-Agent.","domains":["weather.gov","www.weather.gov","api.weather.gov","forecast.weather.gov"],"auth_mode":"pub","user_agent_profile":"weather-gov","strict_robots":true,"exampleUrls":["https://forecast.weather.gov/MapClick.php?lat=39.7456&lon=-97.0892","https://forecast.weather.gov/MapClick.php?lat=40.7128&lon=-74.0060"],"routes":[{"match":{"hosts":["api.weather.gov"],"anyOf":[{"pathPrefix":"/points/"},{"pathPrefix":"/gridpoints/"},{"pathPrefix":"/alerts"},{"pathPrefix":"/stations/"},{"pathPrefix":"/zones/"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/geo+json","maxBytes":2097152},"extract":{"jsonMode":"weather_gov_json"}}],"htmlRoutes":[{"id":"weather-gov","match":{"hosts":["weather.gov","www.weather.gov","forecast.weather.gov"],"exactSegments":false},"mode":"weather_gov_html"}]},{"id":"web-compat-data","name":"Web Compatibility & Baseline Data","category":"developer","description":"Extracts browser compatibility and Web Platform Baseline data from api.webstatus.dev, @mdn/browser-compat-data, caniuse-db, web-features JSON, and caniuse.com HTML.","domains":["api.webstatus.dev","caniuse.com","www.caniuse.com"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://raw.githubusercontent.com/mdn/browser-compat-data/main/api/AbortController.json","https://raw.githubusercontent.com/Fyrd/caniuse/main/features-json/css-grid.json","https://api.webstatus.dev/v1/features/aborting","https://cdn.jsdelivr.net/npm/web-features/data.json","https://caniuse.com/css-grid"],"routes":[{"match":{"hosts":["api.webstatus.dev"],"pathPrefix":"/v1/features/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":1048576},"extract":{"jsonMode":"web_compat_json"}},{"match":{"hosts":["raw.githubusercontent.com"],"pathPrefix":"/mdn/browser-compat-data/","pathSuffix":".json"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"web_compat_json"}},{"match":{"hosts":["raw.githubusercontent.com"],"pathPrefix":"/Fyrd/caniuse/","pathSuffix":".json"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"web_compat_json"}},{"match":{"hosts":["cdn.jsdelivr.net"],"exactSegments":true,"pathEquals":["/npm/web-features/data.json"]},"twin":{"fetchUrl":"{requestUrl}","kind":"text","accept":"application/json","headers":{"Range":"bytes=0-524287"},"maxBytes":1048576},"extract":{"textMode":"web_compat_json"}}],"htmlRoutes":[{"id":"web-compat-data","match":{"hosts":["caniuse.com","www.caniuse.com"],"exactSegments":true,"pathSegments":[{"param":"feature","charset":"pkg","reserved":["ciu","feeds","about","usage-table","compare","index"]}]},"mode":"caniuse_html"}]},{"id":"wheel-hub-specs","name":"Bicycle Wheel & Hub Technical Specs","category":"commerce-social","description":"Extracts hub axle spacing (O.L.D.), freehub compatibility, engagement, spoke counts, and service manuals from DT Swiss, Industry Nine, Chris King, and Hope Technology.","domains":["dtswiss.com","www.dtswiss.com","industrynine.com","www.industrynine.com","chrisking.com","www.chrisking.com","hopetech.com","www.hopetech.com"],"auth_mode":"html","exampleUrls":["https://www.dtswiss.com/en/components/hubs-and-rws/hubs-mtb/350","https://industrynine.com/products/sector-al","https://chrisking.com/collections/hubs-all","https://www.hopetech.com/products/hubs/mountain-bike/"],"htmlRoutes":[{"id":"wheel-hub-specs","match":{"exactSegments":false},"mode":"wheel_hub_specs_html"}]},{"id":"wikidata-openlibrary","name":"Wikidata & Open Library","category":"research-health","description":"Upgrades wikidata.org/wiki/Q* to Special:EntityData/Q*.json (handling labels.en, labels.mul, and sitelinks.enwiki fallbacks) and openlibrary.org/isbn/* to /isbn/*.json (never calling disallowed /api/*).","domains":["www.wikidata.org","wikidata.org","openlibrary.org","www.openlibrary.org"],"exampleUrls":["https://www.wikidata.org/wiki/Q42","https://openlibrary.org/isbn/9780140328721"],"routes":[{"match":{"hosts":["www.wikidata.org","wikidata.org"],"exactSegments":true,"pathPrefix":"/wiki/Q","pathSegments":["wiki",{"param":"qidNum","stripPrefix":"Q","charset":"digits","minLen":1,"maxLen":15}]},"twin":{"fetchUrl":"https://www.wikidata.org/wiki/Special:EntityData/Q{qidNum}.json","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"requireAnyFields":["entities"],"vars":{"qid":{"template":"Q{qidNum}"},"labelEn":{"dynamicKeyPath":{"base":"entities","keyVar":"qid","subPath":"labels.en.value"},"trim":true},"labelMul":{"dynamicKeyPath":{"base":"entities","keyVar":"qid","subPath":"labels.mul.value"},"trim":true},"labelEnwiki":{"dynamicKeyPath":{"base":"entities","keyVar":"qid","subPath":"sitelinks.enwiki.title"},"trim":true},"labelMulOrEnwiki":{"template":"{labelMul}","whenVars":["labelMul"],"fallbackVar":"labelEnwiki"},"label":{"template":"{labelEn}","whenVars":["labelEn"],"fallbackVar":"labelMulOrEnwiki"},"descEn":{"dynamicKeyPath":{"base":"entities","keyVar":"qid","subPath":"descriptions.en.value"},"trim":true},"descMul":{"dynamicKeyPath":{"base":"entities","keyVar":"qid","subPath":"descriptions.mul.value"},"trim":true},"desc":{"template":"{descEn}","whenVars":["descEn"],"fallbackVar":"descMul"},"aliasesEn":{"dynamicKeyPath":{"base":"entities","keyVar":"qid","subPath":"aliases.en"},"subField":"value","join":", ","limit":10},"aliasesMul":{"dynamicKeyPath":{"base":"entities","keyVar":"qid","subPath":"aliases.mul"},"subField":"value","join":", ","limit":10},"aliases":{"template":"{aliasesEn}","whenVars":["aliasesEn"],"fallbackVar":"aliasesMul"},"modified":{"dynamicKeyPath":{"base":"entities","keyVar":"qid","subPath":"modified"},"sliceMax":10},"claimProps":{"dynamicKeyPath":{"base":"entities","keyVar":"qid","subPath":"claims"},"format":"object_keys","limit":25,"itemWrap":"`","join":", "},"instanceOf":{"dynamicKeyPath":{"base":"entities","keyVar":"qid","subPath":"claims.P31"},"subField":"mainsnak.datavalue.value.id","itemWrap":"`","join":", ","limit":8},"sexOrGender":{"dynamicKeyPath":{"base":"entities","keyVar":"qid","subPath":"claims.P21"},"subField":"mainsnak.datavalue.value.id","itemWrap":"`","join":", ","limit":3},"citizenship":{"dynamicKeyPath":{"base":"entities","keyVar":"qid","subPath":"claims.P27"},"subField":"mainsnak.datavalue.value.id","itemWrap":"`","join":", ","limit":5},"occupation":{"dynamicKeyPath":{"base":"entities","keyVar":"qid","subPath":"claims.P106"},"subField":"mainsnak.datavalue.value.id","itemWrap":"`","join":", ","limit":8},"birthDate":{"dynamicKeyPath":{"base":"entities","keyVar":"qid","subPath":"claims.P569"},"preferWhere":{"path":"rank","equals":"preferred","fallbackEquals":"normal"},"subField":"mainsnak.datavalue.value.time","stripPrefix":"+","stripSuffix":"T00:00:00Z","replaceAll":{"from":"-00","to":""},"sliceMax":10},"deathDate":{"dynamicKeyPath":{"base":"entities","keyVar":"qid","subPath":"claims.P570"},"preferWhere":{"path":"rank","equals":"preferred","fallbackEquals":"normal"},"subField":"mainsnak.datavalue.value.time","stripPrefix":"+","stripSuffix":"T00:00:00Z","replaceAll":{"from":"-00","to":""},"sliceMax":10},"inception":{"dynamicKeyPath":{"base":"entities","keyVar":"qid","subPath":"claims.P571"},"preferWhere":{"path":"rank","equals":"preferred","fallbackEquals":"normal"},"subField":"mainsnak.datavalue.value.time","stripPrefix":"+","stripSuffix":"T00:00:00Z","replaceAll":{"from":"-00","to":""},"sliceMax":10},"population":{"dynamicKeyPath":{"base":"entities","keyVar":"qid","subPath":"claims.P1082"},"preferWhere":{"path":"rank","equals":"preferred","fallbackEquals":"normal","fallbackLast":true},"subField":"mainsnak.datavalue.value.amount","format":"int_comma"},"officialWebsite":{"dynamicKeyPath":{"base":"entities","keyVar":"qid","subPath":"claims.P856.0.mainsnak.datavalue.value"},"trim":true,"requireHttpPrefix":true},"enwikiSlug":{"dynamicKeyPath":{"base":"entities","keyVar":"qid","subPath":"sitelinks.enwiki.title"},"replaceAll":{"from":" ","to":"_"}},"enwikiUrl":{"template":"https://en.wikipedia.org/wiki/{enwikiSlug}","whenVars":["enwikiSlug"],"requireHttps":true},"wikidataUrl":{"template":"https://www.wikidata.org/wiki/{qid}","requireHttps":true}},"requireVars":["label"],"titleTemplate":"{label} ({qid})","descriptionVar":"desc","publishedTimeVar":"modified","introVar":"desc","bullets":[{"label":"Wikidata ID","template":"`{qid}`"},{"label":"Also Known As","template":"{aliases}","whenVar":"aliases"},{"label":"Modified","template":"{modified}","whenVar":"modified"},{"label":"Instance Of","template":"{instanceOf}","whenVar":"instanceOf"},{"label":"Sex or Gender","template":"{sexOrGender}","whenVar":"sexOrGender"},{"label":"Country of Citizenship","template":"{citizenship}","whenVar":"citizenship"},{"label":"Occupation","template":"{occupation}","whenVar":"occupation"},{"label":"Date of Birth","template":"{birthDate}","whenVar":"birthDate"},{"label":"Date of Death","template":"{deathDate}","whenVar":"deathDate"},{"label":"Inception","template":"{inception}","whenVar":"inception"},{"label":"Population","template":"{population}","whenVar":"population"},{"label":"Official Website","template":"{officialWebsite}","whenVar":"officialWebsite"},{"label":"Claim Properties","template":"{claimProps}","whenVar":"claimProps"},{"label":"English Wikipedia","template":"{enwikiUrl}","whenVar":"enwikiUrl"},{"label":"Wikidata URL","template":"{wikidataUrl}","whenVar":"wikidataUrl"}],"linksVars":["wikidataUrl","enwikiUrl","officialWebsite"]}},{"match":{"hosts":["openlibrary.org","www.openlibrary.org"],"exactSegments":true,"pathSegments":["isbn",{"param":"isbn","stripSuffix":".json","charset":"alnum_dash","minLen":10,"maxLen":17}]},"twin":{"fetchUrl":"https://openlibrary.org/isbn/{isbn}.json","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"requireFields":["title"],"vars":{"title":{"paths":["title"],"trim":true},"subtitle":{"paths":["subtitle"],"trim":true},"isbn13":{"paths":["isbn_13"],"itemWrap":"`","join":", "},"isbn10":{"paths":["isbn_10"],"itemWrap":"`","join":", "},"publishers":{"paths":["publishers"],"join":", ","limit":8},"publishDate":{"paths":["publish_date"],"trim":true},"pages":{"paths":["number_of_pages"],"format":"int_comma"},"contributions":{"paths":["contributions"],"join":", ","limit":8},"byStatement":{"paths":["by_statement"],"trim":true,"sliceMax":200},"authorLine":{"template":"{byStatement}","whenVars":["byStatement"],"fallbackVar":"contributions"},"authors":{"paths":["authors"],"subField":"key","join":", ","limit":8},"works":{"paths":["works"],"subField":"key","join":", ","limit":5},"olKey":{"paths":["key"]},"olUrl":{"template":"https://openlibrary.org{olKey}","whenVars":["olKey"],"requireHttps":true},"desc":{"paths":["description.value","description","first_sentence.value","first_sentence"],"trim":true},"descShort":{"paths":["description.value","description","first_sentence.value","first_sentence"],"trim":true,"sliceMax":260}},"titleTemplate":"{title}","descriptionVar":"descShort","authorVar":"authorLine","publishedTimeVar":"publishDate","bullets":[{"label":"Subtitle","template":"{subtitle}","whenVar":"subtitle"},{"label":"ISBN-13","template":"{isbn13}","whenVar":"isbn13"},{"label":"ISBN-10","template":"{isbn10}","whenVar":"isbn10"},{"label":"Publishers","template":"{publishers}","whenVar":"publishers"},{"label":"Published","template":"{publishDate}","whenVar":"publishDate"},{"label":"Pages","template":"{pages}","whenVar":"pages"},{"label":"By","template":"{byStatement}","whenVar":"byStatement"},{"label":"Contributors","template":"{contributions}","whenVar":"contributions"},{"label":"Author Keys","template":"{authors}","whenVar":"authors"},{"label":"Work Keys","template":"{works}","whenVar":"works"},{"label":"Open Library URL","template":"{olUrl}","whenVar":"olUrl"}],"sections":[{"heading":"Description","textVar":"desc"}],"linksVars":["olUrl"]}}]},{"id":"wild-apricot","name":"Wild Apricot Member Associations & Events","category":"commerce-social","description":"Extracts public Wild Apricot association event details, upcoming event schedules, and member directories from WaGadget DOM while rejecting /sys/login and login-only gated shells.","domains":["www.ndshp.org","members.mbbi.org","*.wildapricot.org"],"universalEngine":true,"auth_mode":"html","exampleUrls":["https://www.ndshp.org/event-6925405","https://members.mbbi.org/event-6156275","https://members.mbbi.org/Member-Directory/"],"htmlRoutes":[{"id":"wild-apricot","match":{"exactSegments":false},"mode":"wild_apricot_html"}]},{"id":"wistia","name":"Wistia Video Hosting","category":"commerce-social","description":"Extracts Wistia /embed/medias/{mediaId}.json twins and Wistia video HTML while respecting robots.txt /oembed disallow and rejecting login walls.","domains":["fast.wistia.com","fast.wistia.net","home.wistia.com","wistia.com","www.wistia.com"],"auth_mode":"pub","exampleUrls":["https://fast.wistia.com/embed/medias/29b0fbf547.json","https://fast.wistia.com/embed/iframe/29b0fbf547","https://wistia.com/blog/video-marketing-statistics"],"routes":[{"match":{"hosts":["fast.wistia.com","fast.wistia.net"],"exactSegments":true,"pathSuffix":".json","pathSegments":["embed","medias",{"param":"mediaId","charset":"alnum","stripSuffix":".json","minLen":6,"maxLen":20}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"wistia_media_json"}},{"match":{"hosts":["fast.wistia.com","fast.wistia.net"],"exactSegments":true,"pathSegments":["embed","iframe",{"param":"mediaId","charset":"alnum","minLen":6,"maxLen":20}]},"twin":{"fetchUrl":"https://{host}/embed/medias/{mediaId}.json","kind":"json","accept":"application/json"},"extract":{"jsonMode":"wistia_media_json"}}],"htmlRoutes":[{"id":"wistia","match":{"exactSegments":false},"mode":"wistia_html"}]},{"id":"wix-stores","name":"Wix Stores","category":"commerce-social","description":"Extracts Wix Stores product details, pricing, stock, options, and media from wix-warmup-data hydration and JSON-LD/Microdata.","domains":["www.vivietmargot.com"],"universalEngine":true,"auth_mode":"html","exampleUrls":["https://www.vivietmargot.com/product-page/bon-appetit-linen-napkin-lin-bleu"],"htmlRoutes":[{"id":"wix-stores","match":{"exactSegments":false},"mode":"wix_stores_html"}]},{"id":"woocommerce","name":"WooCommerce Store API & Storefronts","category":"commerce-social","description":"Formats public WooCommerce Store API (/wp-json/wc/store/v1/products) feeds, extracts WooCommerce product pages, and implements polite full-store catalog pulls.","domains":["woocommerce.com"],"universalEngine":true,"exampleUrls":["https://yithemes.com/wp-json/wc/store/v1/products?per_page=20&page=1"],"catalog":{"platform":"woocommerce","pauseMs":2000,"pageCap":200,"firstPageTemplate":"{origin}/wp-json/wc/store/v1/products?per_page=100&page=1","perPage":100,"maxVariantsPerProduct":250,"maxImagesPerProduct":250},"routes":[{"match":{"exactSegments":true,"pathSegments":["wp-json","wc","store","v1","products"]},"twin":{"id":"woocommerce-catalog-page","fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"commerceMode":"woocommerce_catalog_page"}},{"match":{"exactSegments":true,"pathSegments":["wp-json","wc","store","v1","products",{"param":"pid","charset":"digits"}]},"twin":{"id":"woocommerce-product","fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"commerceMode":"woocommerce_product"}}],"htmlRoutes":[{"id":"woocommerce","match":{"exactSegments":false},"mode":"woocommerce_html"}]},{"id":"wordpress-org-plugins","name":"WordPress.org Plugin Directory","category":"developer","description":"Extracts WordPress plugin versions, compatibility, ratings, and descriptions from wordpress.org/plugins/ SoftwareApplication JSON-LD/HTML without cross-upgrading to api.wordpress.org.","domains":["wordpress.org","www.wordpress.org","api.wordpress.org"],"auth_mode":"pub","exampleUrls":["https://wordpress.org/plugins/akismet/","https://api.wordpress.org/plugins/info/1.2/?action=plugin_information&slug=akismet"],"routes":[{"match":{"hosts":["api.wordpress.org"],"pathPrefix":"/plugins/info/"},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152},"extract":{"jsonMode":"wordpress_plugin_json"}}],"htmlRoutes":[{"id":"wordpress-org-plugins","match":{"hosts":["wordpress.org","www.wordpress.org"],"pathPrefix":"/plugins/"},"mode":"wordpress_plugin_html"}]},{"id":"wordpress-vip-newspack","name":"WordPress VIP & Newspack","category":"commerce-social","description":"Extracts WP REST v2 posts/pages JSON twins and Newspack/WP-VIP article HTML without colliding with WooCommerce or standard WordPress blogs.","domains":["calmatters.org","missionlocal.org","www.berkeleyside.org"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://calmatters.org/wp-json/wp/v2/posts/516249","https://calmatters.org/commentary/2026/11/californias-philanthropic-funders-give-bravely/"],"routes":[{"match":{"exactSegments":true,"pathSegments":["wp-json","wp","v2","posts"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"wp_vip_posts_json"}},{"match":{"exactSegments":true,"pathSegments":["wp-json","wp","v2","posts",{"param":"postId","charset":"digits","minLen":1,"maxLen":16}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"wp_vip_posts_json"}},{"match":{"exactSegments":true,"pathSegments":["wp-json","wp","v2","pages",{"param":"pageId","charset":"digits","minLen":1,"maxLen":16}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"wp_vip_posts_json"}}],"htmlRoutes":[{"id":"wordpress-vip-newspack","match":{"exactSegments":false},"mode":"wp_vip_newspack_html"}]},{"id":"workable","name":"Workable Job Boards & Postings","category":"jobs","description":"Upgrades apply.workable.com boards to /api/v1/widget/accounts/?details=true (merging multi-location rows on shortcode) and single jobs to /api/v2/accounts//jobs/.","domains":["apply.workable.com"],"exampleUrls":["https://apply.workable.com/huggingface/","https://apply.workable.com/huggingface/j/81B46579FE/"],"routes":[{"match":{"exactSegments":false,"pathSegments":[{"param":"org","charset":"slug","maxLen":80,"reserved":["api","j","assets","static","favicon.ico","robots.txt"]},"j",{"param":"code","charset":"slug","minLen":4,"maxLen":24}]},"twin":{"id":"workable-job","fetchUrl":"https://apply.workable.com/api/v2/accounts/{org}/jobs/{code}","kind":"json","accept":"application/json"},"extract":{"requireFields":["title"],"vars":{"jobTitle":{"paths":["title"],"trim":true},"city":{"paths":["location.city"],"trim":true},"region":{"paths":["location.region"],"trim":true},"country":{"paths":["location.country"],"trim":true},"loc3":{"template":"{city}, {region}, {country}","whenVars":["city","region","country"]},"loc2a":{"template":"{city}, {region}","whenVars":["city","region"]},"loc2b":{"template":"{city}, {country}","whenVars":["city","country"]},"loc2c":{"template":"{region}, {country}","whenVars":["region","country"]},"loc1":{"paths":["location.city","location.region","location.country"],"trim":true},"locSub1":{"template":"{loc3}","whenVars":["loc3"],"fallbackVar":"loc2a"},"locSub2":{"template":"{locSub1}","whenVars":["locSub1"],"fallbackVar":"loc2b"},"locSub3":{"template":"{locSub2}","whenVars":["locSub2"],"fallbackVar":"loc2c"},"locStr":{"template":"{locSub3}","whenVars":["locSub3"],"fallbackVar":"loc1"},"teleRemote":{"paths":["location.telecommuting"],"format":"bool_map","trueValue":"remote","falseValue":""},"workplace":{"paths":["workplace"],"trim":true,"fallbackTemplate":"{teleRemote}"},"dept":{"paths":["department"],"join":", ","trim":true},"empType":{"paths":["type"],"trim":true},"published":{"paths":["published"],"sliceMax":10,"trim":true},"salCur":{"paths":["salary.salary_currency"],"upper":true,"trim":true,"default":"USD"},"salFrom":{"paths":["salary.salary_from"],"excludeEquals":"0"},"salTo":{"paths":["salary.salary_to"],"excludeEquals":"0"},"salRange":{"template":"{salCur} {salFrom} – {salTo}","whenVars":["salFrom","salTo"]},"salFromOnly":{"template":"{salCur} {salFrom}","whenVars":["salFrom"]},"salToOnly":{"template":"{salCur} – {salTo}","whenVars":["salTo"]},"salSub":{"template":"{salCur} {salFrom} – {salTo}","whenVars":["salFrom","salTo"],"fallbackVar":"salFromOnly"},"salStr":{"template":"{salSub}","whenVars":["salSub"],"fallbackVar":"salToOnly"},"desc":{"paths":["description"],"format":"html_to_md"},"reqs":{"paths":["requirements"],"format":"html_to_md"},"benefits":{"paths":["benefits"],"format":"html_to_md"}},"titleTemplate":"{jobTitle} @ {org}","publishedTimeVar":"published","bullets":[{"label":"Company","template":"{org}"},{"label":"Location","template":"{locStr}","whenVar":"locStr"},{"label":"Workplace","template":"{workplace}","whenVar":"workplace"},{"label":"Department","template":"{dept}","whenVar":"dept"},{"label":"Type","template":"{empType}","whenVar":"empType"},{"label":"Salary","template":"{salStr}","whenVar":"salStr"},{"label":"Published","template":"{published}","whenVar":"published"}],"sections":[{"heading":"Description","textVar":"desc"},{"heading":"Requirements","textVar":"reqs"},{"heading":"Benefits","textVar":"benefits"}],"linkTemplates":["https://apply.workable.com/{org}/j/{code}/apply/"]}},{"match":{"pathSegments":[{"param":"org","charset":"slug","maxLen":80,"reserved":["api","j","assets","static","favicon.ico","robots.txt"]}]},"twin":{"id":"workable-board","fetchUrl":"https://apply.workable.com/api/v1/widget/accounts/{org}?details=true","kind":"json","accept":"application/json"},"extract":{"vars":{"rawCount":{"paths":["jobs"],"format":"array_len"},"dedupCount":{"default":"{dedupCount}"},"orgName":{"paths":["name"],"trim":true,"fallbackTemplate":"{org}"}},"requireVars":["rawCount"],"titleTemplate":"{orgName} — Open Roles ({dedupCount})","sections":[{"heading":"","arrayPath":"jobs","limit":100,"linkScanLimit":2000,"emptyText":"No open positions are currently listed on this Workable board.","filter":{"requireField":"title"},"dedupeBy":{"keyPaths":["shortcode"],"mergeTextPaths":["city+state+country"],"mergeTargetVar":"_mergedLocs","mergeSep":"; ","mergeLimit":4,"orBoolPaths":["telecommuting","workplace_type"],"orBoolTargetField":"_isRemote"},"itemVars":{"code":{"paths":["shortcode"],"trim":true},"jTitle":{"paths":["title"],"trim":true},"rawUrl":{"paths":["url"],"requireHttps":true},"jUrl":{"template":"{rawUrl}","whenVars":["rawUrl"],"fallbackTemplate":"https://apply.workable.com/{org}/j/{code}/"},"dept":{"paths":["department"],"trim":true,"default":"-"},"remoteLocFallback":{"paths":["_isRemote"],"format":"bool_map","trueValue":"Remote","falseValue":"-"},"locs":{"paths":["_mergedLocs"],"trim":true,"fallbackTemplate":"{remoteLocFallback}"},"workplace":{"paths":["_isRemote"],"format":"bool_map","trueValue":"Remote","falseValue":"On-site / Hybrid"},"published":{"paths":["published_on"],"sliceMax":10,"trim":true,"default":"-"}},"collectLinkVars":["jUrl"],"columns":[{"header":"Role","template":"[{jTitle}]({jUrl})"},{"header":"Department","template":"{dept}"},{"header":"Locations","template":"{locs}"},{"header":"Workplace","template":"{workplace}"},{"header":"Published","template":"{published}"}]}]}}]},{"id":"xenforo-thread","name":"XenForo 2 Forum Threads","category":"commerce-social","description":"Extracts structured forum posts, authors, timestamps, and clean quote blocks from XenForo 2 thread HTML (article.message--post) while stripping signatures and sidebar chrome.","domains":["forums.electricbikereview.com","mtbr.com","www.mtbr.com","endless-sphere.com"],"universalEngine":true,"exampleUrls":["https://forums.electricbikereview.com/threads/where-we-are-in-2026.59397/","https://www.mtbr.com/threads/ozark-trail-fs-2-slalom-for-a-kid.1249288/","https://endless-sphere.com/sphere/threads/es-2-0-forum-updates-and-tribulations.119104/"],"htmlRoutes":[{"id":"xenforo-thread","match":{"pathContainsSegment":"threads"},"mode":"xenforo_html"}]},{"id":"ycombinator","name":"Y Combinator Directory & Work at a Startup","category":"finance","description":"Extracts YC company profiles, founders, batches, and open roles from ycombinator.com/companies/ (and upgrades login-gated workatastartup.com company pages to their public YC mirror).","domains":["www.ycombinator.com","ycombinator.com","www.workatastartup.com","workatastartup.com"],"exampleUrls":["https://www.ycombinator.com/companies/supabase","https://www.workatastartup.com/companies/supabase"],"routes":[{"match":{"hosts":["www.workatastartup.com","workatastartup.com"],"exactSegments":false,"pathSegments":["companies",{"param":"slug","charset":"alnum_dash","minLen":1,"maxLen":80}]},"twin":{"id":"workatastartup-yc-mirror","fetchUrl":"https://www.ycombinator.com/companies/{slug}/jobs","kind":"text","accept":"text/html"},"extract":{"jsonSource":"inertia_data_page","rootPath":"props","requireFields":["company.name"],"vars":{"name":{"paths":["company.name"],"trim":true},"oneLiner":{"paths":["company.one_liner"],"trim":true},"longDesc":{"paths":["company.long_description"],"trim":true},"batch":{"paths":["company.batch_name","company.batch"]},"status":{"paths":["company.ycdc_status","company.status"]},"teamSize":{"paths":["company.team_size"]},"location":{"paths":["company.location","company.city"]},"website":{"paths":["company.website"]},"websiteHttps":{"paths":["company.website"],"requireHttps":true},"yearFounded":{"paths":["company.year_founded"]},"tags":{"paths":["company.tags"],"join":", "},"hasRootJobsArr":{"paths":["jobPostings"],"format":"array_len"}},"titleTemplate":"{name} (YC {batch})","titleWhenVar":"batch","titleFallbackTemplate":"{name} (Y Combinator)","descriptionVar":"oneLiner","blockquoteTemplate":"> {oneLiner}","blockquoteWhenVar":"oneLiner","bullets":[{"label":"YC Batch","template":"{batch}","whenVar":"batch"},{"label":"Status","template":"{status}","whenVar":"status"},{"label":"Founded","template":"{yearFounded}","whenVar":"yearFounded"},{"label":"Team Size","template":"{teamSize}","whenVar":"teamSize"},{"label":"Location","template":"{location}","whenVar":"location"},{"label":"Website","template":"{website}","whenVar":"website"},{"label":"Tags","template":"{tags}","whenVar":"tags"}],"sections":[{"heading":"About","headingTemplate":"About {name}","textVar":"longDesc"},{"heading":"Founders","listArrayPath":"company.founders","requireItemVar":"fName","collectLinkVars":["linkedin"],"itemVars":{"fName":{"paths":["full_name"],"trim":true},"fTitle":{"paths":["title"],"trim":true,"default":"Founder"},"fBio":{"paths":["founder_bio"],"format":"strip_tags"},"fBioSuffix":{"template":" — {fBio}","whenVars":["fBio"]},"linkedin":{"paths":["linkedin_url"],"requireHttps":true},"fLabel":{"template":"[{fName}]({linkedin})","whenVars":["fName","linkedin"],"fallbackVar":"fName"}},"itemTemplate":"**{fLabel}** ({fTitle}){fBioSuffix}"},{"heading":"Open Roles","headingTemplate":"Open Roles ({count})","arrayPath":"jobPostings","limit":30,"requireItemVar":"jTitle","collectLinkVars":["jUrl"],"itemVars":{"jTitle":{"paths":["title"],"trim":true},"urlHttp":{"paths":["url"],"requireHttpPrefix":true},"urlRelPart":{"paths":["url"],"stripPrefix":"/"},"urlFromRel":{"template":"https://www.ycombinator.com/{urlRelPart}","whenVars":["urlRelPart"]},"urlDefault":{"template":"https://www.ycombinator.com/companies/{slug}/jobs"},"urlRelOrDefault":{"template":"{urlFromRel}","whenVars":["urlFromRel"],"fallbackVar":"urlDefault"},"jUrl":{"template":"{urlHttp}","whenVars":["urlHttp"],"fallbackVar":"urlRelOrDefault"}},"columns":[{"header":"Role","template":"[{jTitle}]({jUrl})"},{"header":"Location","paths":["location","pretty_location"]},{"header":"Salary","paths":["salary_range","pretty_salary_range"]},{"header":"Type","paths":["role","type"]}]},{"heading":"Open Roles","headingTemplate":"Open Roles ({count})","unlessVar":"hasRootJobsArr","arrayPath":"company.jobPostings","limit":30,"requireItemVar":"jTitle","collectLinkVars":["jUrl"],"itemVars":{"jTitle":{"paths":["title"],"trim":true},"urlHttp":{"paths":["url"],"requireHttpPrefix":true},"urlRelPart":{"paths":["url"],"stripPrefix":"/"},"urlFromRel":{"template":"https://www.ycombinator.com/{urlRelPart}","whenVars":["urlRelPart"]},"urlDefault":{"template":"https://www.ycombinator.com/companies/{slug}/jobs"},"urlRelOrDefault":{"template":"{urlFromRel}","whenVars":["urlFromRel"],"fallbackVar":"urlDefault"},"jUrl":{"template":"{urlHttp}","whenVars":["urlHttp"],"fallbackVar":"urlRelOrDefault"}},"columns":[{"header":"Role","template":"[{jTitle}]({jUrl})"},{"header":"Location","paths":["location","pretty_location"]},{"header":"Salary","paths":["salary_range","pretty_salary_range"]},{"header":"Type","paths":["role","type"]}]}],"linksVars":["websiteHttps"]}}],"htmlRoutes":[{"match":{"hosts":["www.ycombinator.com","ycombinator.com"],"exactSegments":false,"pathSegments":["companies",{"param":"slug","charset":"alnum_dash","minLen":1,"maxLen":80}]},"mode":"embedded_json","dataAttr":"data-page","extract":{"jsonSource":"inertia_data_page","rootPath":"props","requireFields":["company.name"],"vars":{"name":{"paths":["company.name"],"trim":true},"oneLiner":{"paths":["company.one_liner"],"trim":true},"longDesc":{"paths":["company.long_description"],"trim":true},"batch":{"paths":["company.batch_name","company.batch"]},"status":{"paths":["company.ycdc_status","company.status"]},"teamSize":{"paths":["company.team_size"]},"location":{"paths":["company.location","company.city"]},"website":{"paths":["company.website"]},"websiteHttps":{"paths":["company.website"],"requireHttps":true},"yearFounded":{"paths":["company.year_founded"]},"tags":{"paths":["company.tags"],"join":", "},"hasRootJobsArr":{"paths":["jobPostings"],"format":"array_len"}},"titleTemplate":"{name} (YC {batch})","titleWhenVar":"batch","titleFallbackTemplate":"{name} (Y Combinator)","descriptionVar":"oneLiner","blockquoteTemplate":"> {oneLiner}","blockquoteWhenVar":"oneLiner","bullets":[{"label":"YC Batch","template":"{batch}","whenVar":"batch"},{"label":"Status","template":"{status}","whenVar":"status"},{"label":"Founded","template":"{yearFounded}","whenVar":"yearFounded"},{"label":"Team Size","template":"{teamSize}","whenVar":"teamSize"},{"label":"Location","template":"{location}","whenVar":"location"},{"label":"Website","template":"{website}","whenVar":"website"},{"label":"Tags","template":"{tags}","whenVar":"tags"}],"sections":[{"heading":"About","headingTemplate":"About {name}","textVar":"longDesc"},{"heading":"Founders","listArrayPath":"company.founders","requireItemVar":"fName","collectLinkVars":["linkedin"],"itemVars":{"fName":{"paths":["full_name"],"trim":true},"fTitle":{"paths":["title"],"trim":true,"default":"Founder"},"fBio":{"paths":["founder_bio"],"format":"strip_tags"},"fBioSuffix":{"template":" — {fBio}","whenVars":["fBio"]},"linkedin":{"paths":["linkedin_url"],"requireHttps":true},"fLabel":{"template":"[{fName}]({linkedin})","whenVars":["fName","linkedin"],"fallbackVar":"fName"}},"itemTemplate":"**{fLabel}** ({fTitle}){fBioSuffix}"},{"heading":"Open Roles","headingTemplate":"Open Roles ({count})","arrayPath":"jobPostings","limit":30,"requireItemVar":"jTitle","collectLinkVars":["jUrl"],"itemVars":{"jTitle":{"paths":["title"],"trim":true},"urlHttp":{"paths":["url"],"requireHttpPrefix":true},"urlRelPart":{"paths":["url"],"stripPrefix":"/"},"urlFromRel":{"template":"https://www.ycombinator.com/{urlRelPart}","whenVars":["urlRelPart"]},"urlDefault":{"template":"https://www.ycombinator.com/companies/{slug}/jobs"},"urlRelOrDefault":{"template":"{urlFromRel}","whenVars":["urlFromRel"],"fallbackVar":"urlDefault"},"jUrl":{"template":"{urlHttp}","whenVars":["urlHttp"],"fallbackVar":"urlRelOrDefault"}},"columns":[{"header":"Role","template":"[{jTitle}]({jUrl})"},{"header":"Location","paths":["location","pretty_location"]},{"header":"Salary","paths":["salary_range","pretty_salary_range"]},{"header":"Type","paths":["role","type"]}]},{"heading":"Open Roles","headingTemplate":"Open Roles ({count})","unlessVar":"hasRootJobsArr","arrayPath":"company.jobPostings","limit":30,"requireItemVar":"jTitle","collectLinkVars":["jUrl"],"itemVars":{"jTitle":{"paths":["title"],"trim":true},"urlHttp":{"paths":["url"],"requireHttpPrefix":true},"urlRelPart":{"paths":["url"],"stripPrefix":"/"},"urlFromRel":{"template":"https://www.ycombinator.com/{urlRelPart}","whenVars":["urlRelPart"]},"urlDefault":{"template":"https://www.ycombinator.com/companies/{slug}/jobs"},"urlRelOrDefault":{"template":"{urlFromRel}","whenVars":["urlFromRel"],"fallbackVar":"urlDefault"},"jUrl":{"template":"{urlHttp}","whenVars":["urlHttp"],"fallbackVar":"urlRelOrDefault"}},"columns":[{"header":"Role","template":"[{jTitle}]({jUrl})"},{"header":"Location","paths":["location","pretty_location"]},{"header":"Salary","paths":["salary_range","pretty_salary_range"]},{"header":"Type","paths":["role","type"]}]}],"linksVars":["websiteHttps"]}}]},{"id":"yelp-fusion","name":"Yelp Fusion API v3","category":"commerce-social","description":"Extracts business search results, single business profiles, and reviews from the official Yelp Fusion v3 API (api.yelp.com) with a strict 24-hour max cache TTL; yelp.com HTML stays detect-only.","domains":["api.yelp.com"],"auth_mode":"key","max_cache_ttl_ms":86400000,"exampleUrls":["https://api.yelp.com/v3/businesses/search?term=coffee&location=San+Francisco","https://api.yelp.com/v3/businesses/gary-danko-san-francisco"],"routes":[{"match":{"hosts":["api.yelp.com"],"anyOf":[{"pathEquals":["/v3/businesses/search","/v3/businesses/matches"]},{"pathPrefix":"/v3/businesses/"}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","maxBytes":2097152,"auth_mode":"key"},"extract":{"jsonMode":"yelp_fusion_json"}}]},{"id":"yext-locator","name":"Yext Store & Dealer Locator","category":"commerce-social","description":"Opt-in page-key adapter for Yext Live/Search API dealer locators; defaults OFF and falls back cleanly to HTML/JSON-LD when disabled.","domains":["liveapi.yext.com","cdn.yextapis.com","locations.chipotle.com"],"universalEngine":true,"auth_mode":"page-key","requires_page_key_opt_in":true,"exampleUrls":["https://cdn.yextapis.com/v2/accounts/me/answers/query?api_key=01db1d1e5ebbaa7ea2e6807ad2196ab3&v=20220511&experienceKey=yext-help-hitchhikers&input=locator"],"routes":[{"match":{"hosts":["liveapi.yext.com","cdn.yextapis.com"],"pathSegments":["v2","accounts",{"param":"accountId","charset":"alnum_dash","minLen":1,"maxLen":64},"entities"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"jsonMode":"yext_locator"}},{"match":{"hosts":["liveapi.yext.com","cdn.yextapis.com"],"pathSegments":["v2","accounts",{"param":"accountId","charset":"alnum_dash","minLen":1,"maxLen":64},"answers","query"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","requires_page_key_opt_in":true,"auth_mode":"page-key"},"extract":{"jsonMode":"yext_locator"}}],"htmlRoutes":[{"id":"yext-locator","match":{"exactSegments":false},"mode":"yext_locator_html"}]},{"id":"yotpo","name":"Yotpo Product Reviews","category":"commerce-social","description":"Extracts public Yotpo reviews widget JSON payloads and discovers Yotpo widget markers on storefront HTML pages.","domains":["api-cdn.yotpo.com","api.yotpo.com"],"universalEngine":true,"auth_mode":"pub","exampleUrls":["https://api-cdn.yotpo.com/v1/widget/MdtpPOdzecvdDWwA3pFvhLyB6ab4osWf5p8TQHpj/products/8158162911322/reviews.json"],"routes":[{"match":{"hosts":["api-cdn.yotpo.com","api.yotpo.com"],"pathSegments":["v1","widget",{"param":"appKey","charset":"alnum_dash","minLen":4,"maxLen":80},"products",{"param":"productId","charset":"pkg","minLen":1,"maxLen":120},"reviews.json"]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json"},"extract":{"jsonMode":"yotpo_reviews"}}],"htmlRoutes":[{"id":"yotpo","match":{"exactSegments":false},"mode":"yotpo_html"}]},{"id":"youtube-data-api","name":"YouTube Data API v3","category":"commerce-social","description":"Extracts video, channel, playlist, and search metadata from official YouTube Data API v3 endpoints on www.googleapis.com (YOUTUBE_DATA_API_KEY via query key).","domains":["console.cloud.google.com"],"universalEngine":true,"auth_mode":"key","min_interval_ms":250,"exampleUrls":["https://www.googleapis.com/youtube/v3/videos?part=snippet,statistics,contentDetails&id=dQw4w9WgXcQ","https://www.googleapis.com/youtube/v3/channels?part=snippet,statistics&id=UC_x5XG1OV2P6uZZ5FSM9Ttw","https://www.googleapis.com/youtube/v3/search?part=snippet&q=edge+computing&type=video&maxResults=5"],"routes":[{"match":{"hosts":["www.googleapis.com"],"exactSegments":true,"pathSegments":["youtube","v3",{"param":"resource","allowValues":["videos","channels","playlists","search"]}]},"twin":{"fetchUrl":"{requestUrl}","kind":"json","accept":"application/json","auth_mode":"key","maxBytes":2097152},"extract":{"jsonMode":"youtube_data_api_json"}}]},{"id":"zendesk-hc","name":"Zendesk Help Center","category":"developer","description":"Upgrades *.zendesk.com Help Center article, section, and category pages to the official Help Center v2 JSON API with breadcrumbs, updated timestamps, and Markdown conversion.","domains":["*.zendesk.com","support.sram.com"],"exampleUrls":["https://support.zendesk.com/hc/en-us/articles/4408885959066-Lesson-4-Business-rules","https://support.zendesk.com/hc/en-us/sections/5634465167514-Business-rules","https://support.zendesk.com/hc/en-us/categories/6191910393754-Product-guides"],"routes":[{"match":{"exactSegments":false,"pathSegments":["hc",{"param":"locale","charset":"alnum_dash","minLen":2,"maxLen":16,"transform":"lower"},"articles",{"param":"articleId","charset":"leading_digits_slug","minLen":1,"maxLen":160,"transform":"leading_digits"}]},"twin":{"fetchUrl":"https://{host}/api/v2/help_center/{locale}/articles/{articleId}.json?include=sections,categories","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"rejectIfFieldTruthy":"article.draft","requireFields":["article.title","article.body"],"vars":{"title":{"paths":["article.title"],"format":"strip_tags","trim":true},"updatedAt":{"paths":["article.updated_at","article.edited_at"]},"htmlUrl":{"paths":["article.html_url"],"requireHttps":true},"sectionName":{"paths":["sections.0.name"],"format":"strip_tags","trim":true},"sectionUrl":{"paths":["sections.0.html_url"],"requireHttps":true},"categoryName":{"paths":["categories.0.name"],"format":"strip_tags","trim":true},"categoryUrl":{"paths":["categories.0.html_url"],"requireHttps":true},"catAndSec":{"template":"{categoryName} › {sectionName}","whenVars":["categoryName","sectionName"],"fallbackVar":"sectionName"},"breadcrumbs":{"template":"{catAndSec}","whenVars":["catAndSec"],"fallbackVar":"categoryName"},"labels":{"paths":["article.label_names"],"itemWrap":"`","join":", ","limit":12},"bodyMd":{"paths":["article.body"],"format":"html_to_md","trim":true}},"requireVars":["title","bodyMd"],"titleTemplate":"{title}","publishedTimeVar":"updatedAt","bullets":[{"label":"Breadcrumbs","template":"{breadcrumbs}","whenVar":"breadcrumbs"},{"label":"Updated","template":"{updatedAt}","whenVar":"updatedAt"},{"label":"Labels","template":"{labels}","whenVar":"labels"},{"label":"Canonical URL","template":"{htmlUrl}","whenVar":"htmlUrl"}],"bodyVar":"bodyMd","linksVars":["htmlUrl","sectionUrl","categoryUrl"]}},{"match":{"exactSegments":false,"pathSegments":["hc",{"param":"locale","charset":"alnum_dash","minLen":2,"maxLen":16,"transform":"lower"},"sections",{"param":"sectionId","charset":"leading_digits_slug","minLen":1,"maxLen":160,"transform":"leading_digits"}]},"twin":{"fetchUrl":"https://{host}/api/v2/help_center/{locale}/sections/{sectionId}/articles.json?per_page=50&include=sections,categories","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"requireAnyFields":["articles","sections"],"vars":{"sectionTitle":{"paths":["sections.0.name"],"format":"strip_tags","trim":true,"fallbackTemplate":"Help Center Section #{sectionId}"},"categoryName":{"paths":["categories.0.name"],"format":"strip_tags","trim":true},"sectionUrl":{"paths":["sections.0.html_url"],"requireHttps":true},"categoryUrl":{"paths":["categories.0.html_url"],"requireHttps":true},"articleCount":{"paths":["articles"],"format":"array_len_comma"}},"titleTemplate":"{sectionTitle}","bullets":[{"label":"Category","template":"{categoryName}","whenVar":"categoryName"},{"label":"Articles","template":"{articleCount}","whenVar":"articleCount"}],"sections":[{"heading":"Articles","arrayPath":"articles","limit":50,"emptyText":"No published articles found in this section.","requireItemVar":"artTitle","collectLinkVars":["artUrl"],"itemVars":{"artTitle":{"paths":["title"],"format":"strip_tags","trim":true},"artUrl":{"paths":["html_url"],"requireHttps":true},"artLabels":{"paths":["label_names"],"join":", ","limit":8},"artUpdated":{"paths":["updated_at"],"sliceMax":10}},"recordFields":{"title":"{artTitle}","url":"{artUrl}","updatedAt":"{artUpdated}","labels":"{artLabels}"},"columns":[{"header":"Article","template":"[{artTitle}]({artUrl})"},{"header":"Updated","paths":["updated_at"],"sliceMax":10},{"header":"Labels","template":"{artLabels}"}]}],"linksVars":["sectionUrl","categoryUrl"]}},{"match":{"exactSegments":false,"pathSegments":["hc",{"param":"locale","charset":"alnum_dash","minLen":2,"maxLen":16,"transform":"lower"},"categories",{"param":"categoryId","charset":"leading_digits_slug","minLen":1,"maxLen":160,"transform":"leading_digits"}]},"twin":{"fetchUrl":"https://{host}/api/v2/help_center/{locale}/categories/{categoryId}/sections.json?per_page=50&include=categories","kind":"json","accept":"application/json","maxBytes":4194304},"extract":{"requireAnyFields":["sections","categories"],"vars":{"categoryTitle":{"paths":["categories.0.name"],"format":"strip_tags","trim":true,"fallbackTemplate":"Help Center Category #{categoryId}"},"categoryDesc":{"paths":["categories.0.description"],"format":"strip_tags","trim":true},"categoryUrl":{"paths":["categories.0.html_url"],"requireHttps":true},"sectionCount":{"paths":["sections"],"format":"array_len_comma"}},"titleTemplate":"{categoryTitle}","descriptionVar":"categoryDesc","introVar":"categoryDesc","bullets":[{"label":"Sections","template":"{sectionCount}","whenVar":"sectionCount"}],"sections":[{"heading":"Sections","arrayPath":"sections","limit":50,"emptyText":"No sections found in this category.","requireItemVar":"secName","collectLinkVars":["secUrl"],"itemVars":{"secName":{"paths":["name"],"format":"strip_tags","trim":true},"secUrl":{"paths":["html_url"],"requireHttps":true},"secDesc":{"paths":["description"],"format":"strip_tags","trim":true,"sliceMax":160},"secUpdated":{"paths":["updated_at"],"sliceMax":10}},"recordFields":{"title":"{secName}","url":"{secUrl}","description":"{secDesc}","updatedAt":"{secUpdated}"},"columns":[{"header":"Section","template":"[{secName}]({secUrl})"},{"header":"Description","template":"{secDesc}"},{"header":"Updated","paths":["updated_at"],"sliceMax":10}]}],"linksVars":["categoryUrl"]}}]}]} diff --git a/internal/extract/manifests/core-ac.yaml b/internal/extract/manifests/core-ac.yaml new file mode 100644 index 0000000..7c8014e --- /dev/null +++ b/internal/extract/manifests/core-ac.yaml @@ -0,0 +1,66 @@ +# Shared Go + TypeScript Declarative Site Adapter: CORE.ac.uk (#303) +id: core-ac +name: CORE Open Access Research Papers +category: research-health +description: "Official keyed CORE v3 API adapter (CORE_AC_API_KEY via Authorization: Bearer) for open-access scholarly works and search, with core.ac.uk HTML fallback and Cloudflare challenge guard." +domains: + - api.core.ac.uk + - core.ac.uk + - www.core.ac.uk +auth_mode: key +min_interval_ms: 1000 +exampleUrls: + - "https://api.core.ac.uk/v3/works/11689643" + - "https://api.core.ac.uk/v3/search/works?q=solar&limit=1" + - "https://core.ac.uk/works/11689643" + +routes: + - match: + hosts: + - api.core.ac.uk + pathPrefix: /v3/ + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + auth_mode: key + maxBytes: 2097152 + extract: + jsonMode: core_ac_json + + - match: + hosts: + - core.ac.uk + - www.core.ac.uk + anyOf: + - exactSegments: true + pathSegments: + - works + - param: workId + charset: digits + minLen: 1 + maxLen: 20 + - exactSegments: true + pathSegments: + - reader + - param: workId + charset: digits + minLen: 1 + maxLen: 20 + twin: + fetchUrl: "https://api.core.ac.uk/v3/works/{workId}" + kind: json + accept: application/json + auth_mode: key + maxBytes: 2097152 + extract: + jsonMode: core_ac_json + +htmlRoutes: + - id: core-ac + match: + hosts: + - core.ac.uk + - www.core.ac.uk + exactSegments: false + mode: core_ac_html diff --git a/internal/extract/manifests/coursedog.yaml b/internal/extract/manifests/coursedog.yaml new file mode 100644 index 0000000..807e3c1 --- /dev/null +++ b/internal/extract/manifests/coursedog.yaml @@ -0,0 +1,36 @@ +# Shared Go + TypeScript Declarative Site Adapter: Coursedog (#222) +id: coursedog +name: "Coursedog University Catalogs" +category: public-records +description: "Extracts Coursedog public university catalogs from SSR __NUXT_DATA__ and rendered catalog DOM alongside public Coursedog JSON API routes." +domains: + - "*.coursedog.com" + - catalog.pratt.edu + - catalogs.umn.edu +universalEngine: true +auth_mode: pub +strict_robots: true +min_interval_ms: 1000 +exampleUrls: + - "https://app.coursedog.com/api/v1/cm/umn/courses/search" + - "https://catalog.pratt.edu/courses" + - "https://umtc.catalog.prod.coursedog.com/" + +routes: + - match: + hosts: + - app.coursedog.com + pathPrefix: /api/v1/ + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: coursedog_json + +htmlRoutes: + - id: coursedog + match: + exactSegments: false + mode: coursedog_html diff --git a/internal/extract/manifests/courseleaf.yaml b/internal/extract/manifests/courseleaf.yaml index f9ad5a9..ecba9ba 100644 --- a/internal/extract/manifests/courseleaf.yaml +++ b/internal/extract/manifests/courseleaf.yaml @@ -5,12 +5,16 @@ category: public-records description: "Universal extractor for CourseLeaf catalog pages (catalog..edu/courses// and program pages): course code, title, credits, description, requisites, and grading from div.courseblock. Fingerprint-gated; never calls /ribbit/, which CourseLeaf robots.txt files disallow." domains: - catalog.unc.edu + - catalog.colorado.edu + - catalog.utexas.edu universalEngine: true auth_mode: html min_interval_ms: 2000 strict_robots: true exampleUrls: - "https://catalog.unc.edu/courses/comp/" + - "https://catalog.colorado.edu/courses-a-z/csci/" + - "https://catalog.utexas.edu/courses/acc/" htmlRoutes: - id: courseleaf diff --git a/internal/extract/manifests/cpsc-ebike-incidents.yaml b/internal/extract/manifests/cpsc-ebike-incidents.yaml new file mode 100644 index 0000000..026dc83 --- /dev/null +++ b/internal/extract/manifests/cpsc-ebike-incidents.yaml @@ -0,0 +1,79 @@ +# Shared Go + TypeScript Declarative Site Adapter: CPSC SaferProducts E-Bike & Micromobility Incidents (#358) +id: cpsc-ebike-incidents +name: "CPSC SaferProducts E-Bike & Micromobility Incidents" +category: public-records +description: "Bounded SaferProducts.gov ProductType/ProductDescription JSON and PublicSearch HTML extractor for bicycle, e-bike, and battery incidents (path/query-disjoint from cpsc-recalls RecallNumber queries)." +domains: + - saferproducts.gov + - www.saferproducts.gov +auth_mode: pub +min_interval_ms: 1000 +exampleUrls: + - "https://www.saferproducts.gov/RestWebServices/Recall?format=json&ProductType=Bicycle" + - "https://www.saferproducts.gov/RestWebServices/Recall?format=json&ProductType=Scooter" + +routes: + # Bounded SaferProducts REST lookup by ProductType (disjoint from cpsc-recalls RecallNumber) + - match: + hosts: + - www.saferproducts.gov + - saferproducts.gov + pathEquals: + - /RestWebServices/Recall + - /RestWebServices/Recall/ + queryParams: + - names: + - ProductType + - productType + - producttype + - PRODUCTTYPE + param: productType + charset: cpsc_query_term + minLen: 2 + maxLen: 60 + twin: + fetchUrl: "https://www.saferproducts.gov/RestWebServices/Recall?format=json&ProductType={productType}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: cpsc_ebike_incidents_json + + # Bounded SaferProducts REST lookup by ProductDescription (disjoint from cpsc-recalls RecallNumber) + - match: + hosts: + - www.saferproducts.gov + - saferproducts.gov + pathEquals: + - /RestWebServices/Recall + - /RestWebServices/Recall/ + queryParams: + - names: + - ProductDescription + - productDescription + - productdescription + - PRODUCTDESCRIPTION + param: productDesc + charset: cpsc_query_term + minLen: 2 + maxLen: 80 + twin: + fetchUrl: "https://www.saferproducts.gov/RestWebServices/Recall?format=json&ProductDescription={productDesc}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: cpsc_ebike_incidents_json + +htmlRoutes: + - id: cpsc-ebike-incidents + match: + hosts: + - www.saferproducts.gov + - saferproducts.gov + anyOf: + - pathEquals: + - /PublicSearch + - /PublicSearch/ + - pathPrefix: /PublicSearch/ + mode: cpsc_ebike_incidents_html diff --git a/internal/extract/manifests/creator-digital-stores.yaml b/internal/extract/manifests/creator-digital-stores.yaml new file mode 100644 index 0000000..5b01049 --- /dev/null +++ b/internal/extract/manifests/creator-digital-stores.yaml @@ -0,0 +1,60 @@ +# Shared Go + TypeScript Declarative Site Adapter: Creator Digital Stores (#366) +id: creator-digital-stores +name: Gumroad, Lemon Squeezy, Payhip & Sellfy +category: commerce-social +description: "Extracts digital product pricing, ratings, creator info, and descriptions from Gumroad, Lemon Squeezy, Payhip, and Sellfy storefronts via JSON-LD, OpenGraph, and DOM fallback." +domains: + - gumroad.com + - www.gumroad.com + - "*.gumroad.com" + - lemonsqueezy.com + - www.lemonsqueezy.com + - "*.lemonsqueezy.com" + - payhip.com + - www.payhip.com + - sellfy.com + - www.sellfy.com +universalEngine: true +auth_mode: html +min_interval_ms: 1500 +strict_robots: true +exampleUrls: + - "https://geoimgr.gumroad.com/l/geoimgr" + +htmlRoutes: + - id: creator-digital-stores + match: + hosts: + - gumroad.com + - www.gumroad.com + - "*.gumroad.com" + - lemonsqueezy.com + - www.lemonsqueezy.com + - "*.lemonsqueezy.com" + - payhip.com + - www.payhip.com + - sellfy.com + - www.sellfy.com + anyOf: + - pathPrefix: /l/ + - pathPrefix: /buy/ + - pathPrefix: /checkout/buy/ + - pathPrefix: /b/ + - pathPrefix: /p/ + - pathEquals: + - /discover + - pathPrefix: /discover/ + mode: creator_digital_stores_html + + - id: creator-digital-stores + match: + anyOf: + - hostSubdomain: + suffix: .sellfy.store + param: storeSub + pathPrefix: /p/ + - hostSubdomain: + suffix: .sellfy.store + param: storeSub + pathPrefix: /buy/ + mode: creator_digital_stores_html diff --git a/internal/extract/manifests/cve-org.yaml b/internal/extract/manifests/cve-org.yaml new file mode 100644 index 0000000..accfca3 --- /dev/null +++ b/internal/extract/manifests/cve-org.yaml @@ -0,0 +1,41 @@ +# Shared Go + TypeScript Declarative Site Adapter: CVE.org & CVE Services JSON 5.x (#319) +id: cve-org +name: CVE.org & CVE Services (CVE JSON 5.x) +category: developer +description: "Extracts authoritative CVE JSON 5.x records from cveawg.mitre.org/api/cve/ and guards www.cve.org Vue CSR SPA shells." +domains: + - cveawg.mitre.org + - www.cve.org + - cve.org +auth_mode: pub +min_interval_ms: 1000 +exampleUrls: + - "https://cveawg.mitre.org/api/cve/CVE-2024-3094" + +routes: + - match: + hosts: + - cveawg.mitre.org + exactSegments: true + pathSegments: + - api + - cve + - param: cveId + charset: cve_id + transform: upper + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: cve_org_json + +htmlRoutes: + - id: cve-org + match: + hosts: + - www.cve.org + - cve.org + exactSegments: false + mode: cve_org_html diff --git a/internal/extract/manifests/datacite.yaml b/internal/extract/manifests/datacite.yaml new file mode 100644 index 0000000..01a801c --- /dev/null +++ b/internal/extract/manifests/datacite.yaml @@ -0,0 +1,64 @@ +# Shared Go + TypeScript Declarative Site Adapter: DataCite (#313) +id: datacite +name: DataCite DOI & Commons Registry +category: research-health +description: "Extracts DataCite JSON:API DOI metadata (titles, creators, publisher, resourceType, descriptions) from api.datacite.org and commons.datacite.org (without claiming doi.org)." +domains: + - api.datacite.org + - commons.datacite.org +auth_mode: pub +min_interval_ms: 1000 +exampleUrls: + - "https://api.datacite.org/dois/10.5281/zenodo.24485086" + - "https://api.datacite.org/dois/10.24406/publica-2155" + +routes: + - match: + hosts: + - api.datacite.org + anyOf: + - pathSegments: + - dois + - param: doi + charset: doi_rest + greedy: true + minLen: 8 + maxLen: 240 + - exactSegments: true + pathEquals: + - /dois + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: datacite_json + + - match: + hosts: + - commons.datacite.org + pathSegments: + - doi.org + - param: doi + charset: doi_rest + greedy: true + minLen: 8 + maxLen: 240 + twin: + fetchUrl: "https://api.datacite.org/dois/{doi}" + rawPathParams: + - doi + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: datacite_json + +htmlRoutes: + - id: datacite + match: + hosts: + - commons.datacite.org + exactSegments: false + mode: datacite_html diff --git a/internal/extract/manifests/dblp.yaml b/internal/extract/manifests/dblp.yaml new file mode 100644 index 0000000..811a9f3 --- /dev/null +++ b/internal/extract/manifests/dblp.yaml @@ -0,0 +1,57 @@ +# Shared Go + TypeScript Declarative Site Adapter: DBLP (#306) +id: dblp +name: DBLP Computer Science Bibliography +category: research-health +description: "Extracts DBLP publication/author search API JSON, direct /rec/*.xml records, and /rec/*.html pages while honoring Crawl-delay: 4 and rejecting Anubis PoW challenges." +domains: + - dblp.org + - www.dblp.org +auth_mode: pub +min_interval_ms: 4000 +max_concurrent: 1 +strict_robots: true +exampleUrls: + - "https://dblp.org/search/publ/api?q=attention+is+all+you+need&format=json&h=2" + - "https://dblp.org/rec/conf/nips/VaswaniSPUJGKP17.html" + +routes: + - match: + hosts: + - dblp.org + - www.dblp.org + anyOf: + - pathPrefix: /search/publ/api + - pathPrefix: /search/author/api + - pathPrefix: /search/venue/api + twin: + fetchUrl: "{requestUrl}" + setQueryParams: + format: json + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: dblp_json + + - match: + hosts: + - dblp.org + - www.dblp.org + pathPrefix: /rec/ + pathSuffix: .xml + twin: + fetchUrl: "{requestUrl}" + kind: text + accept: application/xml + maxBytes: 2097152 + extract: + textMode: dblp_xml + +htmlRoutes: + - id: dblp + match: + hosts: + - dblp.org + - www.dblp.org + exactSegments: false + mode: dblp_html diff --git a/internal/extract/manifests/dealer-locator-pack.yaml b/internal/extract/manifests/dealer-locator-pack.yaml index b36959d..2e88789 100644 --- a/internal/extract/manifests/dealer-locator-pack.yaml +++ b/internal/extract/manifests/dealer-locator-pack.yaml @@ -13,7 +13,7 @@ universalEngine: true auth_mode: page-key requires_page_key_opt_in: true exampleUrls: - - "https://www.bullseyelocations.com/" + - "https://api.storepoint.co/v1/169bd80d34b6b7/locations?all=true" routes: - match: diff --git a/internal/extract/manifests/discogs.yaml b/internal/extract/manifests/discogs.yaml new file mode 100644 index 0000000..dfd542b --- /dev/null +++ b/internal/extract/manifests/discogs.yaml @@ -0,0 +1,127 @@ +# Shared Go + TypeScript Declarative Site Adapter: Discogs (#379) +id: discogs +name: Discogs Music Database & Marketplace +category: commerce-social +description: "Public and optionally keyed Discogs REST API adapter for releases, masters, artists, labels, and catalog search, with www.discogs.com HTML fallback and Cloudflare challenge rejection." +domains: + - api.discogs.com + - www.discogs.com + - discogs.com +auth_mode: pub +min_interval_ms: 1000 +exampleUrls: + - "https://api.discogs.com/releases/249504" + - "https://api.discogs.com/masters/1000" + - "https://www.discogs.com/release/249504-Rick-Astley-Never-Gonna-Give-You-Up" + +routes: + - match: + hosts: + - api.discogs.com + anyOf: + - pathPrefix: /releases/ + - pathPrefix: /masters/ + - pathPrefix: /artists/ + - pathPrefix: /labels/ + - pathPrefix: /database/search + exactSegments: false + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: discogs_json + + - match: + hosts: + - www.discogs.com + - discogs.com + optionalLeadingLocale: true + exactSegments: true + pathSegments: + - release + - param: discogsId + charset: leading_digits_slug + transform: leading_digits + minLen: 1 + maxLen: 220 + twin: + fetchUrl: "https://api.discogs.com/releases/{discogsId}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: discogs_json + + - match: + hosts: + - www.discogs.com + - discogs.com + optionalLeadingLocale: true + exactSegments: true + pathSegments: + - master + - param: discogsId + charset: leading_digits_slug + transform: leading_digits + minLen: 1 + maxLen: 220 + twin: + fetchUrl: "https://api.discogs.com/masters/{discogsId}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: discogs_json + + - match: + hosts: + - www.discogs.com + - discogs.com + optionalLeadingLocale: true + exactSegments: true + pathSegments: + - artist + - param: discogsId + charset: leading_digits_slug + transform: leading_digits + minLen: 1 + maxLen: 220 + twin: + fetchUrl: "https://api.discogs.com/artists/{discogsId}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: discogs_json + + - match: + hosts: + - www.discogs.com + - discogs.com + optionalLeadingLocale: true + exactSegments: true + pathSegments: + - label + - param: discogsId + charset: leading_digits_slug + transform: leading_digits + minLen: 1 + maxLen: 220 + twin: + fetchUrl: "https://api.discogs.com/labels/{discogsId}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: discogs_json + +htmlRoutes: + - id: discogs + match: + hosts: + - www.discogs.com + - discogs.com + exactSegments: false + mode: discogs_html diff --git a/internal/extract/manifests/dkan.yaml b/internal/extract/manifests/dkan.yaml index 75e54a7..1f56ddf 100644 --- a/internal/extract/manifests/dkan.yaml +++ b/internal/extract/manifests/dkan.yaml @@ -2,19 +2,23 @@ id: dkan name: DKAN Open Data Portals (Metastore & Datastore) category: public-records -description: "Universal DKAN 2 adapter (data.medicaid.gov and state/city DKAN portals): formats /api/1/metastore/schemas/dataset/items catalogs and single datasets (publisher, modified, keywords, distributions) and /api/1/datastore/query// rows with data-dictionary column labels. Dataset pages on declared portals upgrade to the metastore JSON." +description: "Universal DKAN 2 adapter (data.medicaid.gov, data.healthcare.gov, and state/city DKAN portals): formats /api/1/metastore/schemas/dataset/items catalogs and single datasets (publisher, modified, keywords, distributions) and /api/1/datastore/query// rows with data-dictionary column labels. Dataset pages on declared portals upgrade to the metastore JSON while respecting dedicated CMS/HealthData adapters." domains: - - data.medicaid.gov + - data.healthcare.gov universalEngine: true auth_mode: pub min_interval_ms: 2000 exampleUrls: - - "https://data.medicaid.gov/api/1/metastore/schemas/dataset/items?show-reference-ids=false" - - "https://data.medicaid.gov/api/1/datastore/query/ae4d5347-5137-5f6c-b66c-3420fa0316d8/0?limit=3" - - "https://data.medicaid.gov/dataset/ae4d5347-5137-5f6c-b66c-3420fa0316d8" + - "https://data.healthcare.gov/api/1/metastore/schemas/dataset/items?show-reference-ids=false" + - "https://data.healthcare.gov/api/1/datastore/query/ae4d5347-5137-5f6c-b66c-3420fa0316d8/0?limit=3" + - "https://data.healthcare.gov/dataset/e4rr-zk4i" routes: - match: + excludeHosts: + - data.cms.gov + - healthdata.gov + - www.healthdata.gov pathPrefix: /api/1/metastore/schemas/dataset/items twin: fetchUrl: "{requestUrl}" @@ -25,6 +29,10 @@ routes: jsonMode: dkan_metastore_json - match: + excludeHosts: + - data.cms.gov + - healthdata.gov + - www.healthdata.gov exactSegments: false pathSegments: - api @@ -45,7 +53,7 @@ routes: - match: hosts: - - data.medicaid.gov + - data.healthcare.gov exactSegments: true pathSegments: - dataset diff --git a/internal/extract/manifests/doe-osti.yaml b/internal/extract/manifests/doe-osti.yaml new file mode 100644 index 0000000..83cb19e --- /dev/null +++ b/internal/extract/manifests/doe-osti.yaml @@ -0,0 +1,57 @@ +# Shared Go + TypeScript Declarative Site Adapter: DOE OSTI (#311) +id: doe-osti +name: DOE OSTI.GOV Technical Reports & Records +category: research-health +description: "Extracts U.S. Department of Energy scientific and technical records from www.osti.gov/api/v1/records (handling both top-level JSON arrays and objects) and /biblio/ HTML fallback." +domains: + - www.osti.gov + - osti.gov +auth_mode: pub +min_interval_ms: 1000 +exampleUrls: + - "https://www.osti.gov/api/v1/records/1800000" + - "https://www.osti.gov/api/v1/records?q=solar&rows=2" + - "https://www.osti.gov/biblio/1800000" + +routes: + - match: + hosts: + - www.osti.gov + - osti.gov + pathPrefix: /api/v1/records + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: doe_osti_json + + - match: + hosts: + - www.osti.gov + - osti.gov + exactSegments: true + pathSegments: + - biblio + - param: ostiId + charset: digits + minLen: 3 + maxLen: 16 + twin: + fetchUrl: "https://www.osti.gov/api/v1/records/{ostiId}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: doe_osti_json + +htmlRoutes: + - id: doe-osti + match: + hosts: + - www.osti.gov + - osti.gov + pathPrefix: /biblio/ + exactSegments: false + mode: doe_osti_html diff --git a/internal/extract/manifests/dol-enforcement.yaml b/internal/extract/manifests/dol-enforcement.yaml new file mode 100644 index 0000000..f7e515e --- /dev/null +++ b/internal/extract/manifests/dol-enforcement.yaml @@ -0,0 +1,41 @@ +# Shared Go + TypeScript Declarative Site Adapter: DOL Enforcement (#279) +id: dol-enforcement +name: U.S. Department of Labor Enforcement & Data +category: public-records +description: "Extracts Wage and Hour Division (WHD) and OSHA enforcement records from apiprod.dol.gov v4 APIs (DOL_API_KEY) with HTML fallback for dol.gov and enforcedata/data.dol.gov while rejecting empty data.dol.gov shells." +domains: + - apiprod.dol.gov + - enforcedata.dol.gov + - data.dol.gov + - www.dol.gov + - dol.gov +auth_mode: key +exampleUrls: + - "https://apiprod.dol.gov/v4/get/WHD/whd_enforcement/json?limit=2" + - "https://apiprod.dol.gov/v4/get/OSHA/inspection/json?limit=2" + - "https://www.dol.gov/agencies/whd/data" + +routes: + - match: + hosts: + - apiprod.dol.gov + pathPrefix: /v4/ + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + auth_mode: key + maxBytes: 4194304 + extract: + jsonMode: dol_enforcement_json + +htmlRoutes: + - id: dol-enforcement + match: + hosts: + - data.dol.gov + - enforcedata.dol.gov + - www.dol.gov + - dol.gov + exactSegments: false + mode: dol_enforcement_html diff --git a/internal/extract/manifests/e-bike-state-laws.yaml b/internal/extract/manifests/e-bike-state-laws.yaml new file mode 100644 index 0000000..f1fff53 --- /dev/null +++ b/internal/extract/manifests/e-bike-state-laws.yaml @@ -0,0 +1,27 @@ +# Shared Go + TypeScript Declarative Site Adapter: E-Bike State Laws & Statutes (#357) +id: e-bike-state-laws +name: "E-Bike State Laws & Legislative Citations (NCSL & State Statutes)" +category: public-records +description: "Extracts electric-bicycle state legislation and statutory definitions from NCSL and state statute portals with markdown citations to Cornell LII and LegiScan (disjoint from ebike-state-laws)." +domains: + - ncsl.org + - www.ncsl.org + - revisor.mn.gov + - www.revisor.mn.gov + - app.leg.wa.gov + - leg.colorado.gov + - www.leg.colorado.gov + - content.leg.colorado.gov +auth_mode: html +min_interval_ms: 1000 +exampleUrls: + - "https://www.ncsl.org/transportation/traffic-safety-trends-state-legislative-action-2025" + - "https://www.revisor.mn.gov/statutes/cite/169.222" + - "https://app.leg.wa.gov/RCW/default.aspx?cite=46.61.710" + - "https://leg.colorado.gov/content/electric-bicycles" + +htmlRoutes: + - id: e-bike-state-laws + match: + exactSegments: false + mode: e_bike_state_laws_html diff --git a/internal/extract/manifests/ebike-drive-systems.yaml b/internal/extract/manifests/ebike-drive-systems.yaml new file mode 100644 index 0000000..d421b89 --- /dev/null +++ b/internal/extract/manifests/ebike-drive-systems.yaml @@ -0,0 +1,29 @@ +# Shared Go + TypeScript Declarative Site Adapter: E-Bike Drive Systems (#344) +id: ebike-drive-systems +name: E-Bike Drive Systems (Yamaha, Brose/QORE, Mahle, Fazua) +category: commerce-social +description: "Extracts motor torque, watt ratings, battery Wh capacity, and technical specs from Yamaha, Brose/QORE, Mahle SmartBike, and Fazua e-bike drive pages." +domains: + - yamahabicycles.com + - www.yamahabicycles.com + - global.yamaha-motor.com + - brose-ebike.com + - www.brose-ebike.com + - qore-system.de + - www.qore-system.de + - mahle-smartbike.com + - www.mahle-smartbike.com + - fazua.com + - www.fazua.com +auth_mode: html +exampleUrls: + - "https://www.yamahabicycles.com/bikes/WabashRT" + - "https://mahle-smartbike.com/x20/" + - "https://fazua.com/en/products/ride-60/" + - "https://www.qore-system.de/" + +htmlRoutes: + - id: ebike-drive-systems + match: + exactSegments: false + mode: ebike_drive_systems_html diff --git a/internal/extract/manifests/edlio-thrillshare.yaml b/internal/extract/manifests/edlio-thrillshare.yaml new file mode 100644 index 0000000..ae5a48f --- /dev/null +++ b/internal/extract/manifests/edlio-thrillshare.yaml @@ -0,0 +1,26 @@ +# Shared Go + TypeScript Declarative Site Adapter: Edlio & Apptegy Thrillshare (#219) +id: edlio-thrillshare +name: "Edlio & Apptegy Thrillshare" +category: public-records +description: "Extracts K-12 school district news feeds, events, and announcements from Edlio (/apps/news/, /apps/events/) and Apptegy Thrillshare portals." +domains: + - "*.edlio.com" + - "*.apptegy.us" + - "*.sites.thrillshare.com" + - www.worldcompassacademy.com + - www.windsorc1.com + - www.eupschools.org +universalEngine: true +auth_mode: html +strict_robots: true +min_interval_ms: 2000 +exampleUrls: + - "https://www.worldcompassacademy.com/apps/news/" + - "https://www.windsorc1.com/o/wcmo/news" + - "https://www.eupschools.org/" + +htmlRoutes: + - id: edlio-thrillshare + match: + exactSegments: false + mode: edlio_thrillshare_html diff --git a/internal/extract/manifests/edu-job-boards.yaml b/internal/extract/manifests/edu-job-boards.yaml new file mode 100644 index 0000000..7eaa5b1 --- /dev/null +++ b/internal/extract/manifests/edu-job-boards.yaml @@ -0,0 +1,84 @@ +# Shared Go + TypeScript Declarative Site Adapter: Education Job Boards (#232) +id: edu-job-boards +name: "Education Job Boards (Chronicle Jobs, HigherEdJobs, K12JobSpot, EdJoin)" +category: jobs +description: "Extracts academic and K-12 JobPosting JSON-LD, Chronicle RSS feeds, and job board HTML while rejecting Incapsula/Cloudflare WAF challenges and unhydrated CSR templates." +domains: + - jobs.chronicle.com + - www.higheredjobs.com + - higheredjobs.com + - www.k12jobspot.com + - k12jobspot.com + - www.edjoin.org + - edjoin.org +auth_mode: pub +exampleUrls: + - "https://jobs.chronicle.com/job/38070836/director-of-occupational-therapy/" + - "https://jobs.chronicle.com/jobsrss/?countrycode=US" + - "https://www.k12jobspot.com/en" + - "https://www.edjoin.org/Home/Jobs?keywords=teacher&searchType=all" + +routes: + # Chronicle of Higher Education Jobs RSS feed + - match: + hosts: + - jobs.chronicle.com + pathPrefix: /jobsrss + exactSegments: false + twin: + id: edu-job-boards + fetchUrl: "{requestUrl}" + kind: text + accept: application/rss+xml + extract: + xml: + mode: items_table + requireAnyTags: + - rss + - channel + itemTag: item + titleTemplate: "Chronicle of Higher Education Jobs ({itemCount})" + emptyText: "No open academic positions currently listed." + limit: 50 + requireItemVar: jTitle + collectLinkVar: jLink + emitTotals: true + itemVars: + jTitle: + tags: [title] + jLink: + tags: [link] + dept: + tags: [category] + default: "-" + pubDate: + tags: [pubDate] + sliceMax: 16 + default: "-" + recordFields: + title: "{jTitle}" + url: "{jLink}" + category: "{dept}" + postedAt: "{pubDate}" + source: chronicle + columns: + - header: Role + template: "[{jTitle}]({jLink})" + - header: Category + template: "{dept}" + - header: Published + template: "{pubDate}" + +htmlRoutes: + - id: edu-job-boards + mode: edu_job_boards_html + match: + hosts: + - jobs.chronicle.com + - www.higheredjobs.com + - higheredjobs.com + - www.k12jobspot.com + - k12jobspot.com + - www.edjoin.org + - edjoin.org + exactSegments: false diff --git a/internal/extract/manifests/edx-coursera.yaml b/internal/extract/manifests/edx-coursera.yaml new file mode 100644 index 0000000..c371e1d --- /dev/null +++ b/internal/extract/manifests/edx-coursera.yaml @@ -0,0 +1,43 @@ +# Shared Go + TypeScript Declarative Site Adapter: edX & Coursera (#224) +id: edx-coursera +name: "edX & Coursera Course Catalog" +category: public-records +description: "Extracts edX course catalog API JSON and Coursera / edX public course landing pages via Course JSON-LD and DOM metadata." +domains: + - courses.edx.org + - www.edx.org + - edx.org + - www.coursera.org + - coursera.org +auth_mode: pub +strict_robots: true +min_interval_ms: 1000 +exampleUrls: + - "https://courses.edx.org/api/courses/v1/courses/course-v1:HarvardX+CS50+X/" + - "https://www.coursera.org/learn/machine-learning" + - "https://www.edx.org/learn/python" + +routes: + - match: + hosts: + - courses.edx.org + pathPrefix: /api/courses/v1/courses + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: edx_course_json + +htmlRoutes: + - id: edx-coursera + match: + hosts: + - courses.edx.org + - www.edx.org + - edx.org + - www.coursera.org + - coursera.org + exactSegments: false + mode: edx_coursera_html diff --git a/internal/extract/manifests/eeoc-litigation.yaml b/internal/extract/manifests/eeoc-litigation.yaml new file mode 100644 index 0000000..99556d9 --- /dev/null +++ b/internal/extract/manifests/eeoc-litigation.yaml @@ -0,0 +1,19 @@ +# Shared Go + TypeScript Declarative Site Adapter: EEOC Litigation (#282) +id: eeoc-litigation +name: EEOC Litigation & Enforcement Releases +category: public-records +description: "Extracts EEOC enforcement press releases, litigation summaries, settlement figures, and district office metadata from eeoc.gov." +domains: + - www.eeoc.gov + - eeoc.gov +auth_mode: pub +exampleUrls: + - "https://www.eeoc.gov/newsroom/boss-man-tacos-pay-42000-eeoc-sexual-harassment-suit" + - "https://www.eeoc.gov/eeoc-litigation" + - "https://www.eeoc.gov/newsroom" + +htmlRoutes: + - id: eeoc-litigation + match: + exactSegments: false + mode: eeoc_litigation_html diff --git a/internal/extract/manifests/endoflife-date.yaml b/internal/extract/manifests/endoflife-date.yaml new file mode 100644 index 0000000..e21f35b --- /dev/null +++ b/internal/extract/manifests/endoflife-date.yaml @@ -0,0 +1,71 @@ +# Shared Go + TypeScript Declarative Site Adapter: endoflife.date (#338) +id: endoflife-date +name: endoflife.date Lifecycle Registry +category: developer +description: "Extracts product release cycles, EOL dates, LTS windows, and latest versions from endoflife.date v1/legacy JSON APIs and SSR product pages." +domains: + - endoflife.date +auth_mode: pub +exampleUrls: + - "https://endoflife.date/api/python.json" + - "https://endoflife.date/api/v1/products/python/" + - "https://endoflife.date/python" + +routes: + - match: + hosts: + - endoflife.date + pathPrefix: /api/v1/products/ + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 1048576 + extract: + jsonMode: endoflife_json + + - match: + hosts: + - endoflife.date + pathPrefix: /api/ + pathSuffix: .json + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 1048576 + extract: + jsonMode: endoflife_json + + - match: + hosts: + - endoflife.date + exactSegments: true + pathSegments: + - param: product + charset: pkg + reserved: + - api + - docs + - calendar + - tags + - categories + - assets + - feed.xml + - robots.txt + - sitemap.xml + twin: + fetchUrl: "https://endoflife.date/api/v1/products/{product}/" + kind: json + accept: application/json + maxBytes: 1048576 + extract: + jsonMode: endoflife_json + +htmlRoutes: + - id: endoflife-date + match: + hosts: + - endoflife.date + exactSegments: false + mode: endoflife_html diff --git a/internal/extract/manifests/energy-star.yaml b/internal/extract/manifests/energy-star.yaml new file mode 100644 index 0000000..3cb5551 --- /dev/null +++ b/internal/extract/manifests/energy-star.yaml @@ -0,0 +1,68 @@ +# Shared Go + TypeScript Declarative Site Adapter: ENERGY STAR (#372) +id: energy-star +name: ENERGY STAR Certified Products & Open Data +category: public-records +description: "Extracts data.energystar.gov Socrata view/resource/catalog JSON datasets and energystar.gov HTML pages while rejecting unhydrated ProductFinder SPA shells." +domains: + - data.energystar.gov + - www.energystar.gov + - energystar.gov +auth_mode: pub +min_interval_ms: 1000 +exampleUrls: + - "https://data.energystar.gov/api/views/7p2p-wkbf.json" + - "https://data.energystar.gov/resource/7p2p-wkbf.json?$limit=5" + - "https://data.energystar.gov/api/catalog/v1?q=certified&limit=3" + +routes: + - match: + hosts: + - data.energystar.gov + anyOf: + - pathPrefix: /api/views/ + pathSuffix: .json + - pathPrefix: /resource/ + pathSuffix: .json + - pathEquals: + - /api/catalog/v1 + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 4194304 + extract: + jsonMode: energy_star_json + + - match: + hosts: + - data.energystar.gov + minSegments: 2 + anyOf: + - exactSegments: false + pathSegments: + - d + - param: viewId + charset: socrata_4x4 + transform: lower + - scanSegment: + lastOrBeforeLiteral: about_data + param: viewId + charset: socrata_4x4 + transform: lower + twin: + fetchUrl: "https://data.energystar.gov/api/views/{viewId}.json" + kind: json + accept: application/json + maxBytes: 4194304 + extract: + jsonMode: energy_star_json + +htmlRoutes: + - id: energy-star + match: + hosts: + - www.energystar.gov + - energystar.gov + - data.energystar.gov + exactSegments: false + mode: energy_star_html diff --git a/internal/extract/manifests/everycrsreport.yaml b/internal/extract/manifests/everycrsreport.yaml new file mode 100644 index 0000000..0844093 --- /dev/null +++ b/internal/extract/manifests/everycrsreport.yaml @@ -0,0 +1,71 @@ +# Shared Go + TypeScript Declarative Site Adapter: EveryCRSReport (#291) +id: everycrsreport +name: "EveryCRSReport Archive" +category: public-records +description: "Extracts Congressional Research Service reports from EveryCRSReport JSON metadata, /reports/{id}.html JSON twins, and bounded /reports.csv index." +domains: + - www.everycrsreport.com + - everycrsreport.com +auth_mode: pub +min_interval_ms: 1000 +exampleUrls: + - "https://www.everycrsreport.com/reports/IN11532.json" + - "https://www.everycrsreport.com/reports/IN11532.html" + - "https://www.everycrsreport.com/reports.csv" + +routes: + - match: + exactSegments: true + pathSuffix: .json + pathSegments: + - reports + - param: reportId + charset: alnum_dash + stripSuffix: .json + minLen: 2 + maxLen: 32 + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 1048576 + extract: + jsonMode: everycrs_json + + - match: + exactSegments: true + pathSuffix: .html + pathSegments: + - reports + - param: reportId + charset: alnum_dash + stripSuffix: .html + minLen: 2 + maxLen: 32 + twin: + fetchUrl: "https://{host}/reports/{reportId}.json" + kind: json + accept: application/json + maxBytes: 1048576 + extract: + jsonMode: everycrs_json + + - match: + exactSegments: true + pathEquals: + - /reports.csv + twin: + fetchUrl: "{requestUrl}" + kind: text + accept: text/plain + headers: + Range: bytes=0-524287 + maxBytes: 1048576 + extract: + textMode: everycrs_csv + +htmlRoutes: + - id: everycrsreport + match: + exactSegments: false + mode: everycrs_html diff --git a/internal/extract/manifests/exploit-db.yaml b/internal/extract/manifests/exploit-db.yaml new file mode 100644 index 0000000..720de96 --- /dev/null +++ b/internal/extract/manifests/exploit-db.yaml @@ -0,0 +1,55 @@ +# Shared Go + TypeScript Declarative Site Adapter: Exploit Database (#323) +id: exploit-db +name: Exploit Database (Exploit-DB) +category: developer +description: "Extracts Exploit-DB SSR exploit pages and RSS feeds on exploit-db.com plus bounded Range-streaming CSV extraction on GitLab exploitdb/files_exploits.csv." +domains: + - www.exploit-db.com + - exploit-db.com +universalEngine: true +auth_mode: pub +min_interval_ms: 1000 +exampleUrls: + - "https://www.exploit-db.com/exploits/51000" + - "https://www.exploit-db.com/rss.xml" + +routes: + - match: + hosts: + - gitlab.com + exactSegments: true + pathEquals: + - /exploit-database/exploitdb/-/raw/main/files_exploits.csv + twin: + fetchUrl: "{requestUrl}" + kind: text + accept: text/plain + headers: + Range: bytes=0-2097151 + maxBytes: 2097152 + extract: + textMode: exploit_db_csv + + - match: + hosts: + - www.exploit-db.com + - exploit-db.com + exactSegments: true + pathEquals: + - /rss.xml + twin: + fetchUrl: "{requestUrl}" + kind: text + accept: application/rss+xml + maxBytes: 2097152 + extract: + textMode: exploit_db_rss + +htmlRoutes: + - id: exploit-db + match: + hosts: + - www.exploit-db.com + - exploit-db.com + exactSegments: false + mode: exploit_db_html diff --git a/internal/extract/manifests/farcaster-hub.yaml b/internal/extract/manifests/farcaster-hub.yaml new file mode 100644 index 0000000..61fa09e --- /dev/null +++ b/internal/extract/manifests/farcaster-hub.yaml @@ -0,0 +1,70 @@ +# Shared Go + TypeScript Declarative Site Adapter: Farcaster Hub (#396) +id: farcaster-hub +name: Farcaster Hub & Fnames API +category: commerce-social +description: "Extracts Farcaster casts, user data, and fname transfers from Neynar Hub HTTP API (NEYNAR_API_KEY), public Hubble nodes (/v1/castsByFid, /v1/castById, /v1/userDataByFid), fnames.farcaster.xyz, and farcaster.xyz SSR fallback." +domains: + - hub-api.neynar.com + - fnames.farcaster.xyz + - farcaster.xyz +universalEngine: true +auth_mode: key +min_interval_ms: 500 +exampleUrls: + - "https://fnames.farcaster.xyz/transfers?fid=3" + - "https://farcaster.xyz/dwr" + - "https://hub-api.neynar.com/v1/castsByFid?fid=3&pageSize=5" + +routes: + - match: + hosts: + - hub-api.neynar.com + pathPrefix: /v1/ + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + auth_mode: key + maxBytes: 2097152 + extract: + jsonMode: farcaster_hub_json + + - match: + hosts: + - fnames.farcaster.xyz + pathPrefix: /transfers + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + auth_mode: pub + maxBytes: 2097152 + extract: + jsonMode: farcaster_hub_json + + - match: + excludeHosts: + - hub-api.neynar.com + - api.farcaster.xyz + - client.farcaster.xyz + - snapchain.farcaster.xyz + pathEquals: + - /v1/castsByFid + - /v1/castById + - /v1/userDataByFid + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + auth_mode: pub + maxBytes: 2097152 + extract: + jsonMode: farcaster_hub_json + +htmlRoutes: + - id: farcaster-hub + match: + hosts: + - farcaster.xyz + exactSegments: false + mode: farcaster_html diff --git a/internal/extract/manifests/fcc-ecfs.yaml b/internal/extract/manifests/fcc-ecfs.yaml new file mode 100644 index 0000000..18ea154 --- /dev/null +++ b/internal/extract/manifests/fcc-ecfs.yaml @@ -0,0 +1,36 @@ +# Shared Go + TypeScript Declarative Site Adapter: FCC ECFS (#284) +id: fcc-ecfs +name: FCC Electronic Comment Filing System (ECFS) +category: public-records +description: "Extracts FCC Electronic Comment Filing System (ECFS) filings, proceedings, filers, and comment text via publicapi.fcc.gov/ecfs/ (api.data.gov key) with HTML fallback on www.fcc.gov/ecfs/." +domains: + - publicapi.fcc.gov + - www.fcc.gov + - fcc.gov +auth_mode: key +exampleUrls: + - "https://publicapi.fcc.gov/ecfs/filings?limit=2" + - "https://www.fcc.gov/ecfs/search/search-filings" + +routes: + - match: + hosts: + - publicapi.fcc.gov + pathPrefix: /ecfs/ + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + auth_mode: key + maxBytes: 4194304 + extract: + jsonMode: fcc_ecfs_json + +htmlRoutes: + - id: fcc-ecfs + match: + hosts: + - www.fcc.gov + - fcc.gov + pathPrefix: /ecfs + mode: fcc_ecfs_html diff --git a/internal/extract/manifests/fcc-id.yaml b/internal/extract/manifests/fcc-id.yaml index f1a6758..dc160c5 100644 --- a/internal/extract/manifests/fcc-id.yaml +++ b/internal/extract/manifests/fcc-id.yaml @@ -11,7 +11,7 @@ exampleUrls: htmlRoutes: - id: fcc-id - mode: dom + mode: fcc_id_html match: exactSegments: false reservedFirstSegment: @@ -30,29 +30,3 @@ htmlRoutes: optional: true minLen: 1 maxLen: 120 - vars: - title: - cssText: - - h1 - - title - metaKeys: - - og:title - trim: true - summary: - cssText: - - "main p" - - "article p" - minLen: 20 - sliceMax: 400 - trim: true - requireVars: - - title - - summary - titleTemplate: "{title}" - descriptionVar: summary - introVar: summary - bullets: - - label: FCC ID - template: "`{grantee}`" - appendCurrentMdDelta: - minExtraChars: 0 diff --git a/internal/extract/manifests/fcc-test-report.yaml b/internal/extract/manifests/fcc-test-report.yaml new file mode 100644 index 0000000..fc1c9dd --- /dev/null +++ b/internal/extract/manifests/fcc-test-report.yaml @@ -0,0 +1,34 @@ +# Shared Go + TypeScript Declarative Site Adapter: FCC OET Equipment Authorization & Test Reports (#373) +id: fcc-test-report +name: FCC OET Equipment Authorization & Test Reports +category: public-records +description: "Extracts FCC OET Equipment Authorization System (EAS) grant metadata and test-report exhibit links on apps.fcc.gov while strictly rejecting Akamai Access Denied and empty search form shells." +domains: + - apps.fcc.gov +auth_mode: pub +min_interval_ms: 1000 +exampleUrls: + - "https://apps.fcc.gov/oetcf/eas/reports/GenericSearch.cfm" + +routes: + - match: + hosts: + - apps.fcc.gov + pathPrefix: /oetcf/eas/ + pathSuffix: .json + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: fcc_test_report_json + +htmlRoutes: + - id: fcc-test-report + match: + hosts: + - apps.fcc.gov + pathPrefix: /oetcf/eas/ + exactSegments: false + mode: fcc_test_report_html diff --git a/internal/extract/manifests/fcc-uls.yaml b/internal/extract/manifests/fcc-uls.yaml new file mode 100644 index 0000000..39e2ed2 --- /dev/null +++ b/internal/extract/manifests/fcc-uls.yaml @@ -0,0 +1,76 @@ +# Shared Go + TypeScript Declarative Site Adapter: FCC ULS (#285) +id: fcc-uls +name: FCC Universal Licensing System (ULS) +category: public-records +description: "Extracts FCC Universal Licensing System (ULS) Socrata datasets and catalog records on opendata.fcc.gov, legacy License View JSON on data.fcc.gov, and wireless2.fcc.gov HTML pages." +domains: + - opendata.fcc.gov + - data.fcc.gov + - wireless2.fcc.gov +auth_mode: pub +min_interval_ms: 1000 +exampleUrls: + - "https://opendata.fcc.gov/resource/dpvg-tvcx.json?$limit=2" + - "https://opendata.fcc.gov/api/catalog/v1?q=ULS&limit=3" + - "https://opendata.fcc.gov/api/views/dpvg-tvcx.json" + +routes: + - match: + hosts: + - opendata.fcc.gov + pathPrefix: /resource/ + pathSuffix: .json + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 4194304 + extract: + jsonMode: fcc_uls_json + + - match: + hosts: + - opendata.fcc.gov + pathPrefix: /api/views/ + pathSuffix: .json + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 4194304 + extract: + jsonMode: fcc_uls_json + + - match: + hosts: + - opendata.fcc.gov + pathPrefix: /api/catalog/v1 + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 4194304 + extract: + jsonMode: fcc_uls_json + + - match: + hosts: + - data.fcc.gov + pathPrefix: /api/license-view/ + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 4194304 + extract: + jsonMode: fcc_uls_json + +htmlRoutes: + - id: fcc-uls + match: + hosts: + - wireless2.fcc.gov + - opendata.fcc.gov + - data.fcc.gov + exactSegments: false + mode: fcc_uls_html diff --git a/internal/extract/manifests/fed-h15-datadownload.yaml b/internal/extract/manifests/fed-h15-datadownload.yaml new file mode 100644 index 0000000..e037354 --- /dev/null +++ b/internal/extract/manifests/fed-h15-datadownload.yaml @@ -0,0 +1,45 @@ +# Shared Go + TypeScript Declarative Site Adapter: Federal Reserve H.15 Selected Interest Rates (#387) +id: fed-h15-datadownload +name: Federal Reserve H.15 Selected Interest Rates +category: finance +description: "Extracts Federal Reserve H.15 Selected Interest Rates CSV data downloads and release/selection HTML tables (#h15table)." +domains: + - www.federalreserve.gov + - federalreserve.gov +auth_mode: pub +min_interval_ms: 1000 +exampleUrls: + - "https://www.federalreserve.gov/datadownload/Output.aspx?rel=H15&series=bf17364827e38702b42a58cf8eaa3f78&lastobs=5&from=&to=&filetype=csv&label=include&layout=seriescolumn" + - "https://www.federalreserve.gov/releases/h15/" + - "https://www.federalreserve.gov/datadownload/Choose.aspx?rel=H15" + +routes: + - match: + hosts: + - www.federalreserve.gov + - federalreserve.gov + pathPrefix: /datadownload/Output.aspx + twin: + fetchUrl: "{requestUrl}" + kind: text + accept: text/plain + maxBytes: 2097152 + extract: + textMode: fed_h15_csv + +htmlRoutes: + - id: fed-h15-datadownload + match: + hosts: + - www.federalreserve.gov + - federalreserve.gov + pathPrefix: /releases/h15 + mode: fed_h15_html + + - id: fed-h15-datadownload + match: + hosts: + - www.federalreserve.gov + - federalreserve.gov + pathPrefix: /datadownload/Choose.aspx + mode: fed_h15_html diff --git a/internal/extract/manifests/fediverse-pack.yaml b/internal/extract/manifests/fediverse-pack.yaml new file mode 100644 index 0000000..134b3eb --- /dev/null +++ b/internal/extract/manifests/fediverse-pack.yaml @@ -0,0 +1,75 @@ +# Shared Go + TypeScript Declarative Site Adapter: Fediverse Pack (#250) +id: fediverse-pack +name: "Fediverse Pack (Misskey, Kbin, Mbin)" +category: commerce-social +description: "Extracts Misskey notes via POST /api/notes/show JSON and Kbin/Mbin threads via ActivityPub JSON or SSR HTML while rejecting Anubis proof-of-work and /login gates." +domains: + - kbin.earth + - gehirneimer.de + - misskey.io +universalEngine: true +auth_mode: pub +exampleUrls: + - "https://misskey.io/notes/au4n1wud00cl0t3s" + - "https://gehirneimer.de/m/fragdeneimer/t/1244377/Spenden-defizit" + +routes: + - match: + exactSegments: true + pathSegments: + - notes + - param: noteId + charset: alnum + minLen: 8 + maxLen: 24 + twin: + fetchUrl: "https://{host}/api/notes/show" + method: POST + contentType: application/json + requestBody: "{\"noteId\":\"{noteId}\"}" + kind: json + accept: application/json + maxBytes: 1048576 + extract: + jsonMode: fediverse_pack_json + - match: + exactSegments: true + pathSegments: + - api + - notes + - show + twin: + fetchUrl: "{requestUrl}" + method: POST + contentType: application/json + kind: json + accept: application/json + maxBytes: 1048576 + extract: + jsonMode: fediverse_pack_json + - match: + exactSegments: false + pathSegments: + - m + - param: mag + charset: brew_id + minLen: 1 + maxLen: 120 + - t + - param: threadId + charset: digits + minLen: 1 + maxLen: 16 + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/activity+json + maxBytes: 1048576 + extract: + jsonMode: fediverse_pack_json + +htmlRoutes: + - id: fediverse-pack + match: + exactSegments: false + mode: fediverse_pack_html diff --git a/internal/extract/manifests/ferc-nrc-dockets.yaml b/internal/extract/manifests/ferc-nrc-dockets.yaml new file mode 100644 index 0000000..d91a0df --- /dev/null +++ b/internal/extract/manifests/ferc-nrc-dockets.yaml @@ -0,0 +1,25 @@ +# Shared Go + TypeScript Declarative Site Adapter: FERC & NRC Dockets (#286) +id: ferc-nrc-dockets +name: FERC eLibrary & NRC ADAMS Dockets +category: public-records +description: "Extracts public FERC eLibrary and NRC ADAMS docket/document pages while strictly honoring robots.txt and rejecting Cloudflare challenges and unhydrated Angular shells." +domains: + - elibrary.ferc.gov + - www.ferc.gov + - ferc.gov + - adams.nrc.gov + - adams-search.nrc.gov + - www.nrc.gov + - nrc.gov +auth_mode: pub +strict_robots: true +exampleUrls: + - "https://www.nrc.gov/documents-reports/adams-public-documents" + - "https://elibrary.ferc.gov/eLibrary/search" + - "https://adams-search.nrc.gov/" + +htmlRoutes: + - id: ferc-nrc-dockets + match: + exactSegments: false + mode: ferc_nrc_dockets_html diff --git a/internal/extract/manifests/ffiec-cdr.yaml b/internal/extract/manifests/ffiec-cdr.yaml new file mode 100644 index 0000000..b9950b5 --- /dev/null +++ b/internal/extract/manifests/ffiec-cdr.yaml @@ -0,0 +1,35 @@ +# Shared Go + TypeScript Declarative Site Adapter: FFIEC Central Data Repository (#392) +id: ffiec-cdr +name: FFIEC Central Data Repository (CDR) +category: finance +description: "Extracts FFIEC CDR Call Report and UBPR public web pages on cdr.ffiec.gov/public/ and optional ffieccdr.azure-api.us/public/ JSON metadata (routed via universalEngine so azure-api.us PSL private suffix is never claimed in domains)." +domains: + - cdr.ffiec.gov +universalEngine: true +auth_mode: pub +min_interval_ms: 1000 +exampleUrls: + - "https://cdr.ffiec.gov/public/ManageFacsimiles.aspx" + - "https://cdr.ffiec.gov/public/PWS/DownloadBulkData.aspx" + +routes: + - match: + hosts: + - ffieccdr.azure-api.us + pathPrefix: /public/ + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + auth_mode: key + maxBytes: 2097152 + extract: + jsonMode: ffiec_cdr_json + +htmlRoutes: + - id: ffiec-cdr + match: + hosts: + - cdr.ffiec.gov + pathPrefix: /public/ + mode: ffiec_cdr_html diff --git a/internal/extract/manifests/finalsite.yaml b/internal/extract/manifests/finalsite.yaml new file mode 100644 index 0000000..6ce3d0e --- /dev/null +++ b/internal/extract/manifests/finalsite.yaml @@ -0,0 +1,23 @@ +# Shared Go + TypeScript Declarative Site Adapter: Finalsite (#217) +id: finalsite +name: "Finalsite K-12 & Independent Schools" +category: public-records +description: "Extracts Finalsite K-12 school and independent school calendar events, news announcements, and resource blocks from /fs/ and fsElement DOM." +domains: + - www.finalsite.com + - finalsite.com + - www.greenwichschools.org + - www.choate.edu +universalEngine: true +auth_mode: html +strict_robots: true +min_interval_ms: 5000 +exampleUrls: + - "https://www.greenwichschools.org/calendar" + - "https://www.choate.edu/" + +htmlRoutes: + - id: finalsite + match: + exactSegments: false + mode: finalsite_html diff --git a/internal/extract/manifests/financial-regulators-enforcement.yaml b/internal/extract/manifests/financial-regulators-enforcement.yaml new file mode 100644 index 0000000..f6829c6 --- /dev/null +++ b/internal/extract/manifests/financial-regulators-enforcement.yaml @@ -0,0 +1,76 @@ +# Shared Go + TypeScript Declarative Site Adapter: Financial Regulators Enforcement (#287) +id: financial-regulators-enforcement +name: CFTC, OCC & FinCEN Enforcement & Bulletins +category: finance +description: "Extracts enforcement actions, press releases, bulletins, and advisories from CFTC, OCC (including occ_news.xml RSS), and FinCEN." +domains: + - www.cftc.gov + - cftc.gov + - www.occ.gov + - occ.gov + - www.fincen.gov + - fincen.gov +auth_mode: pub +exampleUrls: + - "https://www.cftc.gov/PressRoom/PressReleases/9331-26" + - "https://www.occ.gov/news-issuances/bulletins/2023/bulletin-2023-17.html" + - "https://www.occ.gov/rss/occ_news.xml" + - "https://www.fincen.gov/news/news-releases/fincen-issues-alert-and-notice-support-new-fraud-prevention-measures-minnesota" + +routes: + - match: + hosts: + - www.occ.gov + - occ.gov + pathEquals: + - /rss/occ_news.xml + twin: + fetchUrl: "{requestUrl}" + kind: text + accept: text/xml + maxBytes: 2097152 + extract: + xml: + mode: items_table + requireAnyTags: + - rss + - channel + itemTag: item + channelTitleFallbackParam: host + titleTemplate: "{channelTitle} ({itemCount})" + limit: 25 + collectLinkVar: itemLink + emitTotals: true + itemVars: + title: + tags: [title] + default: Release + itemLink: + tags: [link] + pubDate: + tags: [pubDate] + sliceMax: 24 + default: "-" + desc: + tags: [description] + sliceMax: 180 + default: "-" + recordFields: + title: "{title}" + url: "{itemLink}" + publishedAt: "{pubDate}" + description: "{desc}" + source: financial-regulators-enforcement + columns: + - header: Title + template: "[{title}]({itemLink})" + - header: Published + template: "{pubDate}" + - header: Summary + template: "{desc}" + +htmlRoutes: + - id: financial-regulators-enforcement + match: + exactSegments: false + mode: financial_regulators_html diff --git a/internal/extract/manifests/first-epss.yaml b/internal/extract/manifests/first-epss.yaml new file mode 100644 index 0000000..9814a7b --- /dev/null +++ b/internal/extract/manifests/first-epss.yaml @@ -0,0 +1,24 @@ +# Shared Go + TypeScript Declarative Site Adapter: FIRST EPSS (#316) +id: first-epss +name: FIRST Exploit Prediction Scoring System (EPSS) +category: developer +description: "Extracts CVE exploit probability scores, percentiles, and scoring dates from FIRST EPSS v1 JSON API." +domains: + - api.first.org +auth_mode: pub +exampleUrls: + - "https://api.first.org/data/v1/epss?cve=CVE-2024-3094" + +routes: + - match: + hosts: + - api.first.org + exactSegments: false + pathPrefix: /data/v1/epss + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: first_epss_json diff --git a/internal/extract/manifests/fox-ridefox.yaml b/internal/extract/manifests/fox-ridefox.yaml new file mode 100644 index 0000000..c863656 --- /dev/null +++ b/internal/extract/manifests/fox-ridefox.yaml @@ -0,0 +1,19 @@ +# Shared Go + TypeScript Declarative Site Adapter: FOX RideFOX Tech & Suspension (#341) +id: fox-ridefox +name: FOX RideFOX Suspension & Tech Docs +category: developer +description: "Extracts FOX fork and shock specifications, service intervals, 4-char Tune ID codes, and manual PDF links from tech.ridefox.com and ridefox.com." +domains: + - tech.ridefox.com + - ridefox.com + - www.ridefox.com +auth_mode: html +exampleUrls: + - "https://tech.ridefox.com/bike/search/code/DKC6" + - "https://ridefox.com/pages/bike" + +htmlRoutes: + - id: fox-ridefox + match: + exactSegments: false + mode: fox_ridefox_html diff --git a/internal/extract/manifests/ftc-cases.yaml b/internal/extract/manifests/ftc-cases.yaml new file mode 100644 index 0000000..70d7d4b --- /dev/null +++ b/internal/extract/manifests/ftc-cases.yaml @@ -0,0 +1,22 @@ +# Shared Go + TypeScript Declarative Site Adapter: FTC Cases & Proceedings (#283) +id: ftc-cases +name: FTC Cases, Proceedings & Early Termination Notices +category: public-records +description: "Extracts FTC Legal Library cases, proceedings, matter numbers, and Hart-Scott-Rodino early termination notices while honoring FTC Crawl-delay: 5." +domains: + - www.ftc.gov + - ftc.gov +auth_mode: pub +strict_robots: true +min_interval_ms: 5000 +max_concurrent: 1 +exampleUrls: + - "https://www.ftc.gov/legal-library/browse/cases-proceedings/banned-debt-collectors" + - "https://www.ftc.gov/legal-library/browse/cases-proceedings" + - "https://www.ftc.gov/legal-library/browse/early-termination-notices" + +htmlRoutes: + - id: ftc-cases + match: + exactSegments: false + mode: ftc_cases_html diff --git a/internal/extract/manifests/gao-reports.yaml b/internal/extract/manifests/gao-reports.yaml new file mode 100644 index 0000000..0aabd52 --- /dev/null +++ b/internal/extract/manifests/gao-reports.yaml @@ -0,0 +1,32 @@ +# Shared Go + TypeScript Declarative Site Adapter: U.S. GAO Reports & Testimonies (#289) +id: gao-reports +name: "U.S. GAO Reports & Testimonies" +category: public-records +description: "Extracts U.S. Government Accountability Office RSS report feeds and product detail pages while honoring strict_robots and rejecting Akamai Access Denied shells." +domains: + - www.gao.gov + - gao.gov +auth_mode: pub +strict_robots: true +min_interval_ms: 1000 +exampleUrls: + - "https://www.gao.gov/products/gao-27-108423" + - "https://www.gao.gov/rss/reports.xml" + +routes: + - match: + pathPrefix: /rss/ + pathSuffix: .xml + twin: + fetchUrl: "{requestUrl}" + kind: text + accept: application/rss+xml + maxBytes: 1048576 + extract: + textMode: gao_rss_xml + +htmlRoutes: + - id: gao-reports + match: + exactSegments: false + mode: gao_reports_html diff --git a/internal/extract/manifests/genius-lyrics.yaml b/internal/extract/manifests/genius-lyrics.yaml new file mode 100644 index 0000000..58e06ec --- /dev/null +++ b/internal/extract/manifests/genius-lyrics.yaml @@ -0,0 +1,35 @@ +# Shared Go + TypeScript Declarative Site Adapter: Genius, AZLyrics, Musixmatch & SongMeanings (#386) +id: genius-lyrics +name: Genius, AZLyrics, Musixmatch & SongMeanings +category: commerce-social +description: "Real song lyrics, artist, album, and annotation/meaning HTML extractor across Genius ([data-lyrics-container='true'] / __PRELOADED_STATE__), AZLyrics, Musixmatch (__NEXT_DATA__ / .mxm-lyrics__content), and SongMeanings." +domains: + - genius.com + - www.genius.com + - www.azlyrics.com + - azlyrics.com + - www.musixmatch.com + - musixmatch.com + - songmeanings.com + - www.songmeanings.com +auth_mode: html +min_interval_ms: 1500 +exampleUrls: + - "https://www.azlyrics.com/lyrics/rickastley/nevergonnagiveyouup.html" + - "https://songmeanings.com/songs/view/3530822107858506064/" + - "https://genius.com/Rick-astley-never-gonna-give-you-up-lyrics" + +htmlRoutes: + - id: genius-lyrics + match: + hosts: + - genius.com + - www.genius.com + - www.azlyrics.com + - azlyrics.com + - www.musixmatch.com + - musixmatch.com + - songmeanings.com + - www.songmeanings.com + exactSegments: false + mode: genius_lyrics_html diff --git a/internal/extract/manifests/geometrygeeks-99spokes.yaml b/internal/extract/manifests/geometrygeeks-99spokes.yaml new file mode 100644 index 0000000..d259d9c --- /dev/null +++ b/internal/extract/manifests/geometrygeeks-99spokes.yaml @@ -0,0 +1,20 @@ +# Shared Go + TypeScript Declarative Site Adapter: Geometry Geeks & 99 Spokes (#354) +id: geometrygeeks-99spokes +name: "Geometry Geeks & 99 Spokes" +category: commerce-social +description: "Extracts bicycle geometry tables (reach, stack, HTA, STA, chainstay, wheelbase) and component specs from Geometry Geeks and 99 Spokes while rejecting Cloudflare WAF blocks and empty shells." +domains: + - geometrygeeks.bike + - www.geometrygeeks.bike + - 99spokes.com + - www.99spokes.com +auth_mode: html +min_interval_ms: 1000 +exampleUrls: + - "https://geometrygeeks.bike/bike/specialized-stumpjumper-evo-2021/" + +htmlRoutes: + - id: geometrygeeks-99spokes + match: + exactSegments: false + mode: geometrygeeks_99spokes_html diff --git a/internal/extract/manifests/gerrit.yaml b/internal/extract/manifests/gerrit.yaml new file mode 100644 index 0000000..1caad70 --- /dev/null +++ b/internal/extract/manifests/gerrit.yaml @@ -0,0 +1,29 @@ +# Shared Go + TypeScript Declarative Site Adapter: Gerrit Code Review (#329) +id: gerrit +name: Gerrit Code Review +category: developer +description: "Universal Gerrit Code Review JSON extractor for /changes/ and /r/changes/ endpoints with linear XSSI )]}' prefix stripping and Crawl-delay pacing." +domains: + - review.opendev.org + - gerrit.wikimedia.org +universalEngine: true +auth_mode: pub +min_interval_ms: 2000 +exampleUrls: + - "https://review.opendev.org/changes/?q=status:merged&n=2" + - "https://review.opendev.org/changes/1010181/detail" + - "https://gerrit.wikimedia.org/r/changes/?q=status:merged&n=2" + +routes: + - match: + anyOf: + - pathPrefix: /changes/ + - pathPrefix: /r/changes/ + - pathPrefix: /gerrit/changes/ + twin: + fetchUrl: "{requestUrl}" + kind: text + accept: application/json + maxBytes: 2097152 + extract: + textMode: gerrit_json diff --git a/internal/extract/manifests/gorgias-reamaze.yaml b/internal/extract/manifests/gorgias-reamaze.yaml new file mode 100644 index 0000000..0ad9ac1 --- /dev/null +++ b/internal/extract/manifests/gorgias-reamaze.yaml @@ -0,0 +1,20 @@ +# Shared Go + TypeScript Declarative Site Adapter: Gorgias & Re:amaze Help Centers (#269) +id: gorgias-reamaze +name: "Gorgias & Re:amaze Help Centers" +category: commerce-social +description: "Extracts help-center articles, topic indexes, and Q&A content from Gorgias (__NEXT_DATA__) and Re:amaze knowledge base portals." +domains: + - "*.gorgias.help" + - "*.reamaze.com" + - support.burga.com +universalEngine: true +auth_mode: html +exampleUrls: + - "https://support.burga.com/en-US/articles/contact-us-24868" + - "https://storypod.reamaze.com/kb/all-about-storypod/firmware-update" + +htmlRoutes: + - id: gorgias-reamaze + match: + exactSegments: false + mode: gorgias_reamaze_html diff --git a/internal/extract/manifests/gov-wordpress-newsrooms.yaml b/internal/extract/manifests/gov-wordpress-newsrooms.yaml new file mode 100644 index 0000000..4c7aab1 --- /dev/null +++ b/internal/extract/manifests/gov-wordpress-newsrooms.yaml @@ -0,0 +1,64 @@ +# Shared Go + TypeScript Declarative Site Adapter: Federal .gov WordPress Newsrooms (#292) +id: gov-wordpress-newsrooms +name: "Federal .gov WordPress Newsrooms" +category: public-records +description: "Extracts official federal .gov WordPress REST v2 posts (excluding whitehouse.gov 403 /wp-json/) and briefing/newsroom HTML pages." +domains: + - www.whitehouse.gov + - whitehouse.gov + - news.va.gov + - www.nasa.gov + - nasa.gov +auth_mode: pub +min_interval_ms: 1000 +exampleUrls: + - "https://news.va.gov/wp-json/wp/v2/posts?per_page=1" + - "https://news.va.gov/151377/memphis-veterans-received-help-claims-clinic/" + - "https://www.whitehouse.gov/presidential-actions/" + +routes: + - match: + excludeHosts: + - www.whitehouse.gov + - whitehouse.gov + exactSegments: true + pathSegments: + - wp-json + - wp + - v2 + - posts + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: gov_wp_posts_json + + - match: + excludeHosts: + - www.whitehouse.gov + - whitehouse.gov + exactSegments: true + pathSegments: + - wp-json + - wp + - v2 + - posts + - param: postId + charset: digits + minLen: 1 + maxLen: 16 + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: gov_wp_posts_json + +htmlRoutes: + - id: gov-wordpress-newsrooms + match: + exactSegments: false + mode: gov_wp_newsroom_html diff --git a/internal/extract/manifests/granicus-govdelivery.yaml b/internal/extract/manifests/granicus-govdelivery.yaml new file mode 100644 index 0000000..e8e6275 --- /dev/null +++ b/internal/extract/manifests/granicus-govdelivery.yaml @@ -0,0 +1,66 @@ +# Shared Go + TypeScript Declarative Site Adapter: Granicus GovDelivery (#202) +id: granicus-govdelivery +name: Granicus GovDelivery Public Bulletins +category: public-records +description: "Extracts public government bulletins and optional RSS feeds from Granicus GovDelivery without rewriting HTML bulletins to .rss." +domains: + - content.govdelivery.com + - public.govdelivery.com +auth_mode: pub +exampleUrls: + - "https://content.govdelivery.com/accounts/ILEVANSTON/bulletins/4345149" + +routes: + - match: + pathSuffix: .rss + pathPrefix: /accounts/ + twin: + fetchUrl: "{requestUrl}" + kind: text + accept: application/rss+xml + maxBytes: 2097152 + extract: + xml: + mode: items_table + requireAnyTags: + - rss + - channel + itemTag: item + channelTitleFallbackParam: host + titleTemplate: "{channelTitle} ({itemCount})" + limit: 25 + collectLinkVar: itemLink + emitTotals: true + itemVars: + title: + tags: [title] + default: Bulletin + itemLink: + tags: [link] + pubDate: + tags: [pubDate] + sliceMax: 24 + default: "-" + desc: + tags: [description] + sliceMax: 180 + default: "-" + recordFields: + title: "{title}" + url: "{itemLink}" + publishedAt: "{pubDate}" + description: "{desc}" + source: granicus-govdelivery + columns: + - header: Bulletin + template: "[{title}]({itemLink})" + - header: Published + template: "{pubDate}" + - header: Summary + template: "{desc}" + +htmlRoutes: + - id: granicus-govdelivery + match: + exactSegments: false + mode: govdelivery_html diff --git a/internal/extract/manifests/gs1-us-datahub.yaml b/internal/extract/manifests/gs1-us-datahub.yaml new file mode 100644 index 0000000..87c4fbd --- /dev/null +++ b/internal/extract/manifests/gs1-us-datahub.yaml @@ -0,0 +1,42 @@ +# Shared Go + TypeScript Declarative Site Adapter: GS1 US Data Hub (#368) +id: gs1-us-datahub +name: GS1 US Data Hub & Verified by GS1 +category: commerce-social +description: "Extracts Verified by GS1 / GS1 US Data Hub GTIN brand-owner, GLN, company prefix, and GPC metadata via api.gs1us.org (GS1_US_API_KEY) with public HTML fallback on gs1us.org and gs1.org." +domains: + - api.gs1us.org + - www.gs1us.org + - gs1us.org + - gepir.gs1.org + - www.gs1.org +auth_mode: key +min_interval_ms: 1000 +exampleUrls: + - "https://www.gs1us.org/tools/gs1-company-database-gepir" + - "https://www.gs1.org/services/verified-by-gs1" + - "https://api.gs1us.org/gtins/0012000161155" + +routes: + - match: + hosts: + - api.gs1us.org + minSegments: 1 + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + auth_mode: key + maxBytes: 2097152 + extract: + jsonMode: gs1_us_json + +htmlRoutes: + - id: gs1-us-datahub + match: + hosts: + - www.gs1us.org + - gs1us.org + - gepir.gs1.org + - www.gs1.org + exactSegments: false + mode: gs1_us_html diff --git a/internal/extract/manifests/gsa-site-scanning.yaml b/internal/extract/manifests/gsa-site-scanning.yaml new file mode 100644 index 0000000..79c697c --- /dev/null +++ b/internal/extract/manifests/gsa-site-scanning.yaml @@ -0,0 +1,35 @@ +# Shared Go + TypeScript Declarative Site Adapter: GSA Site Scanning API (#293) +id: gsa-site-scanning +name: "GSA Site Scanning API" +category: public-records +description: "GSA Technology Transformation Services Site Scanning API (DATA_GOV_API_KEY) and open.gsa.gov documentation fallback." +domains: + - api.gsa.gov + - open.gsa.gov +auth_mode: key +min_interval_ms: 1000 +exampleUrls: + - "https://api.gsa.gov/technology/site-scanning/v1/websites?limit=5" + - "https://api.gsa.gov/technology/site-scanning/v1/websites/usa.gov" + +routes: + - match: + hosts: + - api.gsa.gov + pathPrefix: /technology/site-scanning/v1/websites + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + auth_mode: key + maxBytes: 2097152 + extract: + jsonMode: gsa_site_scanning_json + +htmlRoutes: + - id: gsa-site-scanning + match: + hosts: + - open.gsa.gov + exactSegments: false + mode: gsa_site_scanning_html diff --git a/internal/extract/manifests/healthcare-careers.yaml b/internal/extract/manifests/healthcare-careers.yaml new file mode 100644 index 0000000..be74055 --- /dev/null +++ b/internal/extract/manifests/healthcare-careers.yaml @@ -0,0 +1,21 @@ +# Shared Go + TypeScript Declarative Site Adapter: Healthcare Careers (#233) +id: healthcare-careers +name: "Healthcare Careers (HealthcareSource & symplr)" +category: jobs +description: "Extracts hospital and clinical job postings from HealthcareSource (*.healthcaresource.com) and symplr career pages while rejecting Application Error and WAF shells and deferring careers.symplr.com to Jibe." +domains: + - "*.healthcaresource.com" + - www.symplr.com + - symplr.com +universalEngine: true +auth_mode: html +exampleUrls: + - "https://pm.healthcaresource.com/cs/stclair" + +htmlRoutes: + - id: healthcare-careers + mode: healthcare_careers_html + match: + excludeHosts: + - careers.symplr.com + exactSegments: false diff --git a/internal/extract/manifests/healthcare-gov-marketplace.yaml b/internal/extract/manifests/healthcare-gov-marketplace.yaml new file mode 100644 index 0000000..e6c8073 --- /dev/null +++ b/internal/extract/manifests/healthcare-gov-marketplace.yaml @@ -0,0 +1,58 @@ +# Shared Go + TypeScript Declarative Site Adapter: HealthCare.gov Marketplace API (#295) +id: healthcare-gov-marketplace +name: "HealthCare.gov Marketplace API" +category: research-health +description: "CMS HealthCare.gov Marketplace Plan Search (POST), States, Counties, and Plan Detail API (HEALTHCARE_GOV_API_KEY) with healthcare.gov HTML fallback." +domains: + - marketplace.api.healthcare.gov + - www.healthcare.gov + - healthcare.gov +auth_mode: key +min_interval_ms: 1000 +exampleUrls: + - "https://marketplace.api.healthcare.gov/api/v1/plans/search" + - "https://marketplace.api.healthcare.gov/api/v1/states" + - "https://www.healthcare.gov/glossary/affordable-care-act/" + +routes: + - match: + hosts: + - marketplace.api.healthcare.gov + pathPrefix: /api/v1/plans/search + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + method: POST + contentType: application/json + requestBody: '{"household":{"income":52000,"people":[{"age":30,"aptc_eligible":true,"uses_tobacco":false}]},"market":"Individual","place":{"zipcode":"27360","state":"NC","countyfips":"37057"},"year":2026}' + auth_mode: key + maxBytes: 2097152 + extract: + jsonMode: healthcare_marketplace_json + + - match: + hosts: + - marketplace.api.healthcare.gov + anyOf: + - pathPrefix: /api/v1/states + - pathPrefix: /api/v1/counties/ + - pathPrefix: /api/v1/plans/ + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + method: GET + auth_mode: key + maxBytes: 2097152 + extract: + jsonMode: healthcare_marketplace_json + +htmlRoutes: + - id: healthcare-gov-marketplace + match: + hosts: + - www.healthcare.gov + - healthcare.gov + exactSegments: false + mode: healthcare_gov_html diff --git a/internal/extract/manifests/idx-broker-showcase.yaml b/internal/extract/manifests/idx-broker-showcase.yaml new file mode 100644 index 0000000..b5bf33a --- /dev/null +++ b/internal/extract/manifests/idx-broker-showcase.yaml @@ -0,0 +1,22 @@ +# Shared Go + TypeScript Declarative Site Adapter: IDX Broker & Showcase IDX (#254) +id: idx-broker-showcase +name: "IDX Broker & Showcase IDX Real Estate Portals" +category: commerce-social +description: "Extracts real estate property listings, MLS numbers, pricing, and RealEstateAgent/RealEstateListing metadata from IDX Broker and Showcase IDX portals while rejecting 403/WAF shells." +domains: + - "*.idxbroker.com" + - entityrealty.com + - realtorrajaram.com +universalEngine: true +auth_mode: html +strict_robots: true +min_interval_ms: 2000 +exampleUrls: + - "https://entityrealty.com/" + - "https://entityrealty.com/properties/" + +htmlRoutes: + - id: idx-broker-showcase + match: + exactSegments: false + mode: idx_broker_showcase_html diff --git a/internal/extract/manifests/ifixit.yaml b/internal/extract/manifests/ifixit.yaml new file mode 100644 index 0000000..6516a53 --- /dev/null +++ b/internal/extract/manifests/ifixit.yaml @@ -0,0 +1,70 @@ +# Shared Go + TypeScript Declarative Site Adapter: iFixit Repair Guides & Wikis (#343) +id: ifixit +name: iFixit Repair Guides & Wikis +category: developer +description: "Extracts repair guides, steps, tools, parts, and category wikis from ifixit.com /api/2.0/ JSON endpoints with HTML fallback." +domains: + - ifixit.com + - www.ifixit.com +auth_mode: pub +exampleUrls: + - "https://www.ifixit.com/api/2.0/guides/1" + - "https://www.ifixit.com/api/2.0/wikis/CATEGORY/Bicycle" + - "https://www.ifixit.com/Guide/Bicycle+Chain+Replacement/41537" + +routes: + - match: + hosts: + - ifixit.com + - www.ifixit.com + exactSegments: true + pathSegments: + - api + - "2.0" + - guides + - param: guideId + charset: digits + minLen: 1 + maxLen: 16 + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: ifixit_json + + - match: + hosts: + - ifixit.com + - www.ifixit.com + exactSegments: false + pathSegments: + - api + - "2.0" + - wikis + - param: ns + charset: url_seg + minLen: 1 + maxLen: 40 + - param: name + charset: safe_subpath + greedy: true + minLen: 1 + maxLen: 200 + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: ifixit_json + +htmlRoutes: + - id: ifixit + match: + hosts: + - ifixit.com + - www.ifixit.com + exactSegments: false + mode: ifixit_html diff --git a/internal/extract/manifests/igdb.yaml b/internal/extract/manifests/igdb.yaml new file mode 100644 index 0000000..e9866c1 --- /dev/null +++ b/internal/extract/manifests/igdb.yaml @@ -0,0 +1,63 @@ +# Shared Go + TypeScript Declarative Site Adapter: IGDB (#384) +id: igdb +name: IGDB (Internet Game Database) +category: commerce-social +description: "Official keyed IGDB v4 APICALYPSE POST API adapter (TWITCH_API_TOKEN + TWITCH_CLIENT_ID) for game metadata, ratings, genres, and platforms, with igdb.com HTML fallback." +domains: + - api.igdb.com + - www.igdb.com + - igdb.com +auth_mode: key +min_interval_ms: 1000 +exampleUrls: + - "https://www.igdb.com/games/portal-2" + - "https://api.igdb.com/v4/games" + +routes: + - match: + hosts: + - api.igdb.com + pathPrefix: /v4/ + exactSegments: false + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + method: POST + contentType: text/plain + auth_mode: key + maxBytes: 2097152 + extract: + jsonMode: igdb_json + + - match: + hosts: + - www.igdb.com + - igdb.com + exactSegments: true + pathSegments: + - games + - param: slug + charset: slug + minLen: 1 + maxLen: 160 + twin: + fetchUrl: "https://api.igdb.com/v4/games" + kind: json + accept: application/json + method: POST + contentType: text/plain + requestBody: "fields name,slug,summary,rating,rating_count,first_release_date,genres.name,platforms.name,involved_companies.company.name,url; where slug = \"{slug}\"; limit 1;" + auth_mode: key + maxBytes: 2097152 + extract: + jsonMode: igdb_json + +htmlRoutes: + - id: igdb + match: + hosts: + - www.igdb.com + - igdb.com + exactSegments: false + mode: igdb_html diff --git a/internal/extract/manifests/imdb-datasets.yaml b/internal/extract/manifests/imdb-datasets.yaml new file mode 100644 index 0000000..1ad45fd --- /dev/null +++ b/internal/extract/manifests/imdb-datasets.yaml @@ -0,0 +1,45 @@ +# Shared Go + TypeScript Declarative Site Adapter: IMDb Non-Commercial Datasets (#376) +id: imdb-datasets +name: IMDb Non-Commercial Datasets +category: commerce-social +description: "Bounded Range-streaming TSV sample extractor for datasets.imdbws.com *.tsv.gz archives and data.imdb.com / developer.imdb.com documentation, explicitly emitting nonCommercialLicense: true and IMDb Non-Commercial Datasets licensing notice." +domains: + - datasets.imdbws.com + - developer.imdb.com + - data.imdb.com +auth_mode: pub +min_interval_ms: 1000 +exampleUrls: + - "https://datasets.imdbws.com/title.ratings.tsv.gz" + - "https://data.imdb.com/non-commercial-datasets/" + - "https://developer.imdb.com/non-commercial-datasets/" + +routes: + - match: + hosts: + - datasets.imdbws.com + pathSuffix: .tsv.gz + exactSegments: true + pathSegments: + - param: datasetFile + charset: pkg + minLen: 5 + maxLen: 80 + twin: + fetchUrl: "{requestUrl}" + kind: text + accept: text/plain + headers: + Range: "bytes=0-262143" + maxBytes: 524288 + extract: + textMode: imdb_datasets_tsv + +htmlRoutes: + - id: imdb-datasets + match: + hosts: + - developer.imdb.com + - data.imdb.com + exactSegments: false + mode: imdb_datasets_html diff --git a/internal/extract/manifests/import-alerts-aphis-fda.yaml b/internal/extract/manifests/import-alerts-aphis-fda.yaml new file mode 100644 index 0000000..dc3bc2c --- /dev/null +++ b/internal/extract/manifests/import-alerts-aphis-fda.yaml @@ -0,0 +1,33 @@ +# Shared Go + TypeScript Declarative Site Adapter: FDA Import Alerts & USDA APHIS Import Manuals (#278) +id: import-alerts-aphis-fda +name: FDA Import Alerts & USDA APHIS Import Manuals +category: public-records +description: "Extracts FDA Import Alerts (/cms_ia/* on accessdata.fda.gov) and USDA APHIS import guidance and manuals (aphis.usda.gov)." +domains: + - www.accessdata.fda.gov + - accessdata.fda.gov + - www.aphis.usda.gov + - aphis.usda.gov +auth_mode: pub +exampleUrls: + - "https://www.accessdata.fda.gov/cms_ia/importalert_3.html" + - "https://www.accessdata.fda.gov/cms_ia/ialist.html" + - "https://www.aphis.usda.gov/plant-imports" + - "https://www.aphis.usda.gov/trade-management-manuals" + +htmlRoutes: + - id: import-alerts-aphis-fda + match: + hosts: + - www.accessdata.fda.gov + - accessdata.fda.gov + pathPrefix: /cms_ia/ + mode: import_alerts_fda_aphis_html + + - id: import-alerts-aphis-fda + match: + hosts: + - www.aphis.usda.gov + - aphis.usda.gov + exactSegments: false + mode: import_alerts_fda_aphis_html diff --git a/internal/extract/manifests/ir-portal-pack.yaml b/internal/extract/manifests/ir-portal-pack.yaml new file mode 100644 index 0000000..fc83db9 --- /dev/null +++ b/internal/extract/manifests/ir-portal-pack.yaml @@ -0,0 +1,40 @@ +# Shared Go + TypeScript Declarative Site Adapter: IR Portal Pack (#260) +id: ir-portal-pack +name: "Investor Relations Portals (Notified / Equisolve / Nasdaq IR)" +category: finance +description: "Extracts Notified/Intrado (wd_newsfeed), Equisolve, and Nasdaq IR investor relations portals and RSS press release feeds." +domains: + - investor.iridium.com + - ir.bowheadspecialty.com +universalEngine: true +auth_mode: pub +strict_robots: true +min_interval_ms: 1000 +exampleUrls: + - "https://investor.iridium.com/press-releases" + - "https://ir.bowheadspecialty.com/news-events/press-releases/rss" + - "https://ir.bowheadspecialty.com/news-events/press-releases" + +routes: + - match: + hosts: + - investor.iridium.com + - ir.bowheadspecialty.com + anyOf: + - pathSuffix: /rss + - pathSuffix: .rss + - pathPrefix: /rss/ + exactSegments: false + twin: + fetchUrl: "{requestUrl}" + kind: text + accept: application/rss+xml + maxBytes: 2097152 + extract: + textMode: ir_portal_rss_xml + +htmlRoutes: + - id: ir-portal-pack + match: + exactSegments: false + mode: ir_portal_pack_html diff --git a/internal/extract/manifests/jira-public.yaml b/internal/extract/manifests/jira-public.yaml new file mode 100644 index 0000000..50de2bc --- /dev/null +++ b/internal/extract/manifests/jira-public.yaml @@ -0,0 +1,38 @@ +# Shared Go + TypeScript Declarative Site Adapter: Jira Public (#331) +id: jira-public +name: Jira Public Issue Tracker +category: developer +description: "Universal Jira Server/DC/Cloud extractor supporting direct /rest/api/2|3/issue/ JSON endpoints and robots-compliant /browse/ SSR HTML extraction." +domains: + - jira.mariadb.org + - jira.atlassian.com +universalEngine: true +auth_mode: pub +min_interval_ms: 2000 +exampleUrls: + - "https://jira.mariadb.org/rest/api/2/issue/MDEV-30000" + - "https://jira.mariadb.org/browse/MDEV-30000" + - "https://jira.atlassian.com/rest/api/2/issue/JRASERVER-71500" + +routes: + - match: + anyOf: + - pathPrefix: /rest/api/2/issue/ + - pathPrefix: /rest/api/3/issue/ + - pathPrefix: /jira/rest/api/2/issue/ + - pathPrefix: /jira/rest/api/3/issue/ + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: jira_public_json + +htmlRoutes: + - id: jira-public + match: + anyOf: + - pathPrefix: /browse/ + - pathPrefix: /jira/browse/ + mode: jira_public_html diff --git a/internal/extract/manifests/junar-tyler-data.yaml b/internal/extract/manifests/junar-tyler-data.yaml new file mode 100644 index 0000000..e28e08a --- /dev/null +++ b/internal/extract/manifests/junar-tyler-data.yaml @@ -0,0 +1,34 @@ +# Shared Go + TypeScript Declarative Site Adapter: Junar & Tyler Data & Insights (#216) +id: junar-tyler-data +name: Junar & Tyler Data & Insights Open Data Portals +category: public-records +description: "Extracts Junar /dataviews/ HTML and /api/v2/datastreams/ JSON plus Tyler Data & Insights /api/catalog/v1 datasets (without overlapping Socrata claims)." +domains: + - data.paloalto.gov + - "*.junar.com" + - data.tylertech.com +universalEngine: true +auth_mode: pub +exampleUrls: + - "https://data.tylertech.com/api/catalog/v1" + - "https://data.tylertech.com/api/catalog/v1?limit=5" + - "https://data.paloalto.gov/home" + +routes: + - match: + anyOf: + - pathPrefix: /api/v2/datastreams/ + - pathPrefix: /api/catalog/v1 + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 4194304 + extract: + jsonMode: junar_tyler_json + +htmlRoutes: + - id: junar-tyler-data + match: + exactSegments: false + mode: junar_tyler_html diff --git a/internal/extract/manifests/klaviyo-attentive-forms.yaml b/internal/extract/manifests/klaviyo-attentive-forms.yaml new file mode 100644 index 0000000..92758a1 --- /dev/null +++ b/internal/extract/manifests/klaviyo-attentive-forms.yaml @@ -0,0 +1,20 @@ +# Shared Go + TypeScript Declarative Site Adapter: Klaviyo & Attentive Read-Only Forms (#270) +id: klaviyo-attentive-forms +name: "Klaviyo & Attentive Onsite Forms (Read-Only)" +category: commerce-social +description: "Strictly read-only extractor for Klaviyo onsite company/form IDs, signup offer metadata, and Attentive tag metadata without submitting forms; yields on product/article pages." +domains: + - www.getcasely.com + - www.klaviyo.com + - static.klaviyo.com + - cdn.attn.tv +universalEngine: true +auth_mode: html +exampleUrls: + - "https://www.klaviyo.com/" + +htmlRoutes: + - id: klaviyo-attentive-forms + match: + exactSegments: false + mode: klaviyo_attentive_forms_html diff --git a/internal/extract/manifests/laserfiche-weblink.yaml b/internal/extract/manifests/laserfiche-weblink.yaml index 54036de..7a1c282 100644 --- a/internal/extract/manifests/laserfiche-weblink.yaml +++ b/internal/extract/manifests/laserfiche-weblink.yaml @@ -5,6 +5,9 @@ category: public-records description: "Universal Laserfiche WebLink adapter for city and county records portals. DocView.aspx and Browse.aspx links that carry id and repo (as WebLink share links do) upgrade to the anonymous JSON services the viewer itself calls: document name, folder path, template, created/modified dates, page count and metadata fields, or a folder listing with links. No cookies or login are used; the CookieCheck redirect only guards the HTML shell." domains: - cc-publicdocs.santa-ana.org + - records.hawaiicounty.gov + - docs.southbendin.gov + - weblink.winterspringsfl.org universalEngine: true auth_mode: pub min_interval_ms: 3000 diff --git a/internal/extract/manifests/lemmy.yaml b/internal/extract/manifests/lemmy.yaml new file mode 100644 index 0000000..d6585d3 --- /dev/null +++ b/internal/extract/manifests/lemmy.yaml @@ -0,0 +1,120 @@ +# Shared Go + TypeScript Declarative Site Adapter: Lemmy (#248) +id: lemmy +name: "Lemmy Federated Link Aggregator (Universal Engine)" +category: commerce-social +description: "Upgrades Lemmy posts (/post/{id}), communities (/c/{name}), and /api/v3/* endpoints via JSON API with SSR HTML fallback while rejecting Cloudflare challenges." +domains: + - lemmy.world + - lemmy.ml + - programming.dev + - sh.itjust.works +universalEngine: true +auth_mode: pub +exampleUrls: + - "https://lemmy.world/api/v3/post?id=54926010" + - "https://lemmy.world/api/v3/community?name=memes" + - "https://lemmy.world/post/54926010" + - "https://lemmy.ml/post/55819348" + +routes: + - match: + excludeHosts: + - offerup.com + - www.offerup.com + exactSegments: true + pathSegments: + - api + - v3 + - post + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: lemmy_json + - match: + excludeHosts: + - offerup.com + - www.offerup.com + exactSegments: true + pathSegments: + - api + - v3 + - comment + - list + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: lemmy_json + - match: + excludeHosts: + - offerup.com + - www.offerup.com + exactSegments: true + pathSegments: + - api + - v3 + - community + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: lemmy_json + - match: + excludeHosts: + - offerup.com + - www.offerup.com + exactSegments: false + pathSegments: + - post + - param: postId + charset: digits + minLen: 1 + maxLen: 16 + twin: + fetchUrl: "https://{host}/api/v3/post?id={postId}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: lemmy_json + - match: + excludeHosts: + - offerup.com + - www.offerup.com + exactSegments: true + pathSegments: + - c + - param: communityName + charset: brew_id + minLen: 1 + maxLen: 120 + reserved: + - api + - pictrs + - feeds + - u + - post + - search + - communities + - login + - signup + twin: + fetchUrl: "https://{host}/api/v3/community?name={communityName}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: lemmy_json + +htmlRoutes: + - id: lemmy + match: + exactSegments: false + mode: lemmy_html diff --git a/internal/extract/manifests/local-classifieds-marketplaces.yaml b/internal/extract/manifests/local-classifieds-marketplaces.yaml new file mode 100644 index 0000000..33fe278 --- /dev/null +++ b/internal/extract/manifests/local-classifieds-marketplaces.yaml @@ -0,0 +1,37 @@ +# Shared Go + TypeScript Declarative Site Adapter: Local Classifieds Marketplaces (#365) +id: local-classifieds-marketplaces +name: Craigslist, OfferUp & Facebook Marketplace +category: commerce-social +description: "Extracts local classifieds listings and search feeds from Craigslist, OfferUp, and public Facebook Marketplace metadata while strictly honoring robots.txt and classifying login walls, blocks, and empty CSR shells." +domains: + - craigslist.org + - www.craigslist.org + - "*.craigslist.org" + - offerup.com + - www.offerup.com + - facebook.com + - www.facebook.com + - m.facebook.com +auth_mode: html +min_interval_ms: 2000 +strict_robots: true +exampleUrls: + - "https://www.craigslist.org/view/d/san-francisco-wahoo-kickr-core-bike/rv3daGwPjNSovN5fQ4JpLk" + - "https://sfbay.craigslist.org/search/bik" + - "https://offerup.com/c/bikes-and-cycling" + - "https://www.facebook.com/marketplace/sanfrancisco/bicycles" + +htmlRoutes: + - id: local-classifieds-marketplaces + match: + anyOf: + - pathPrefix: /view/d/ + - pathPrefix: /search/ + - pathPrefix: /c/ + - pathPrefix: /explore/ + - pathPrefix: /item/detail/ + - pathEquals: + - /marketplace + - pathPrefix: /marketplace/ + - pathContainsSegment: d + mode: local_classifieds_html diff --git a/internal/extract/manifests/market-quotes-pack.yaml b/internal/extract/manifests/market-quotes-pack.yaml new file mode 100644 index 0000000..0d3bdc5 --- /dev/null +++ b/internal/extract/manifests/market-quotes-pack.yaml @@ -0,0 +1,63 @@ +# Shared Go + TypeScript Declarative Site Adapter: Market Quotes Pack (#389) +id: market-quotes-pack +name: "Market Quotes Pack (Alpha Vantage, Polygon/Massive, Tiingo)" +category: finance +description: "Extracts equity, FX, and market quote JSON feeds from Alpha Vantage, Polygon/Massive, and Tiingo official keyed APIs." +domains: + - www.alphavantage.co + - alphavantage.co + - api.polygon.io + - api.massive.com + - api.tiingo.com +auth_mode: key +min_interval_ms: 1000 +exampleUrls: + - "https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=IBM" + - "https://api.polygon.io/v2/aggs/ticker/AAPL/prev" + - "https://api.massive.com/v2/aggs/ticker/AAPL/prev" + - "https://api.tiingo.com/tiingo/daily/aapl/prices" + +routes: + - match: + hosts: + - www.alphavantage.co + - alphavantage.co + pathEquals: + - /query + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + auth_mode: key + maxBytes: 2097152 + extract: + jsonMode: market_quotes_json + + - match: + hosts: + - api.polygon.io + - api.massive.com + anyOf: + - pathPrefix: /v2/ + - pathPrefix: /v3/ + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + auth_mode: key + maxBytes: 2097152 + extract: + jsonMode: market_quotes_json + + - match: + hosts: + - api.tiingo.com + pathPrefix: /tiingo/ + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + auth_mode: key + maxBytes: 2097152 + extract: + jsonMode: market_quotes_json diff --git a/internal/extract/manifests/medicaid-nadac.yaml b/internal/extract/manifests/medicaid-nadac.yaml new file mode 100644 index 0000000..6541038 --- /dev/null +++ b/internal/extract/manifests/medicaid-nadac.yaml @@ -0,0 +1,56 @@ +# Shared Go + TypeScript Declarative Site Adapter: Medicaid NADAC Drug Pricing (#297) +id: medicaid-nadac +name: "Medicaid NADAC Drug Pricing (DKAN)" +category: research-health +description: "Extracts data.medicaid.gov NADAC drug pricing DKAN metastore datasets, datastore queries, and /dataset/{id} twins while rejecting empty CMS Medicaid Data React shells." +domains: + - data.medicaid.gov +auth_mode: pub +min_interval_ms: 1000 +exampleUrls: + - "https://data.medicaid.gov/api/1/metastore/schemas/dataset/items/fbb83258-11c7-47f5-8b18-5f8e79f7e704" + - "https://data.medicaid.gov/api/1/datastore/query/e3af839d-8175-5be0-b94e-4a302ed7a035/0?limit=5" + - "https://data.medicaid.gov/dataset/fbb83258-11c7-47f5-8b18-5f8e79f7e704" + +routes: + - match: + pathPrefix: /api/1/metastore/ + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: medicaid_nadac_json + + - match: + pathPrefix: /api/1/datastore/query/ + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: medicaid_nadac_json + + - match: + exactSegments: false + pathSegments: + - dataset + - param: datasetId + charset: alnum_dash + minLen: 8 + maxLen: 64 + twin: + fetchUrl: "https://data.medicaid.gov/api/1/metastore/schemas/dataset/items/{datasetId}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: medicaid_nadac_json + +htmlRoutes: + - id: medicaid-nadac + match: + exactSegments: false + mode: medicaid_nadac_html diff --git a/internal/extract/manifests/mitre-attack.yaml b/internal/extract/manifests/mitre-attack.yaml new file mode 100644 index 0000000..074b1d2 --- /dev/null +++ b/internal/extract/manifests/mitre-attack.yaml @@ -0,0 +1,55 @@ +# Shared Go + TypeScript Declarative Site Adapter: MITRE ATT&CK (#317) +id: mitre-attack +name: MITRE ATT&CK STIX & Knowledge Base +category: developer +description: "Range-bounded linear STIX 2.1 bundle prefix scanner on GitHub raw attack-stix-data plus static HTML extractor for attack.mitre.org techniques, tactics, groups, and software." +domains: + - attack.mitre.org + - www.attack.mitre.org +universalEngine: true +auth_mode: pub +min_interval_ms: 1000 +exampleUrls: + - "https://attack.mitre.org/techniques/T1059/" + - "https://raw.githubusercontent.com/mitre-attack/attack-stix-data/master/index.json" + - "https://raw.githubusercontent.com/mitre-attack/attack-stix-data/master/enterprise-attack/enterprise-attack.json" + +routes: + - match: + hosts: + - raw.githubusercontent.com + exactSegments: true + pathEquals: + - /mitre-attack/attack-stix-data/master/index.json + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 1048576 + extract: + jsonMode: mitre_attack_index_json + + - match: + hosts: + - raw.githubusercontent.com + exactSegments: false + pathPrefix: /mitre-attack/attack-stix-data/ + pathSuffix: .json + twin: + fetchUrl: "{requestUrl}" + kind: text + accept: application/json + headers: + Range: bytes=0-524287 + maxBytes: 1048576 + extract: + textMode: mitre_attack_stix_bundle + +htmlRoutes: + - id: mitre-attack + match: + hosts: + - attack.mitre.org + - www.attack.mitre.org + exactSegments: false + mode: mitre_attack_html diff --git a/internal/extract/manifests/mitre-cwe-capec.yaml b/internal/extract/manifests/mitre-cwe-capec.yaml new file mode 100644 index 0000000..2028611 --- /dev/null +++ b/internal/extract/manifests/mitre-cwe-capec.yaml @@ -0,0 +1,58 @@ +# Shared Go + TypeScript Declarative Site Adapter: MITRE CWE & CAPEC (#318) +id: mitre-cwe-capec +name: MITRE CWE & CAPEC Weaknesses and Attack Patterns +category: developer +description: "Extracts Common Weakness Enumeration (CWE) JSON from cwe-api.mitre.org and XHTML definitions from cwe.mitre.org and capec.mitre.org." +domains: + - cwe-api.mitre.org + - cwe.mitre.org + - capec.mitre.org +auth_mode: pub +min_interval_ms: 1000 +exampleUrls: + - "https://cwe-api.mitre.org/api/v1/cwe/weakness/79" + - "https://cwe.mitre.org/data/definitions/79.html" + - "https://capec.mitre.org/data/definitions/1.html" + +routes: + - match: + hosts: + - cwe-api.mitre.org + exactSegments: false + pathPrefix: /api/v1/ + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: mitre_cwe_json + + - match: + hosts: + - cwe.mitre.org + exactSegments: true + pathSegments: + - data + - definitions + - param: cweId + charset: digits + stripSuffix: .html + minLen: 1 + maxLen: 8 + twin: + fetchUrl: "https://cwe-api.mitre.org/api/v1/cwe/weakness/{cweId}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: mitre_cwe_json + +htmlRoutes: + - id: mitre-cwe-capec + match: + hosts: + - cwe.mitre.org + - capec.mitre.org + exactSegments: false + mode: mitre_cwe_capec_html diff --git a/internal/extract/manifests/msrb-emma.yaml b/internal/extract/manifests/msrb-emma.yaml new file mode 100644 index 0000000..410a8cf --- /dev/null +++ b/internal/extract/manifests/msrb-emma.yaml @@ -0,0 +1,20 @@ +# Shared Go + TypeScript Declarative Site Adapter: MSRB EMMA Municipal Bond Disclosures (#391) +id: msrb-emma +name: MSRB EMMA Municipal Bond Disclosures +category: finance +description: "Extracts municipal bond CUSIP, issue disclosure, and market activity HTML pages from emma.msrb.org while strictly rejecting 403/awselb WAF and empty shells." +domains: + - emma.msrb.org + - emmalabs.msrb.org +auth_mode: html +min_interval_ms: 1500 +strict_robots: true +exampleUrls: + - "https://emma.msrb.org/Home/Index" + - "https://emma.msrb.org/Security/Details/A1B2C3D4E5" + +htmlRoutes: + - id: msrb-emma + match: + exactSegments: false + mode: msrb_emma_html diff --git a/internal/extract/manifests/mtb-geometry-brands.yaml b/internal/extract/manifests/mtb-geometry-brands.yaml new file mode 100644 index 0000000..bb8730e --- /dev/null +++ b/internal/extract/manifests/mtb-geometry-brands.yaml @@ -0,0 +1,30 @@ +# Shared Go + TypeScript Declarative Site Adapter: MTB Geometry Brands (#353) +id: mtb-geometry-brands +name: "MTB Geometry Brands (Yeti, Ibis, Pivot, Transition, Revel)" +category: commerce-social +description: "Extracts mountain bike geometry tables, Nuxt hydration data, suspension travel, and build kits from Yeti, Ibis, Pivot, Transition, and Revel." +domains: + - yeticycles.com + - www.yeticycles.com + - ibiscycles.com + - www.ibiscycles.com + - pivotcycles.com + - www.pivotcycles.com + - transitionbikes.com + - www.transitionbikes.com + - revelbikes.com + - www.revelbikes.com +auth_mode: html +min_interval_ms: 1000 +exampleUrls: + - "https://yeticycles.com/en-us/bikes/sb140" + - "https://www.ibiscycles.com/bikes/ripmo" + - "https://www.pivotcycles.com/en/bikes/shuttle-ampd" + - "https://www.transitionbikes.com/Bikes/Sentinel" + - "https://revelbikes.com/products/rascal-sram-eagle-90-kit-2026" + +htmlRoutes: + - id: mtb-geometry-brands + match: + exactSegments: false + mode: mtb_geometry_brands_html diff --git a/internal/extract/manifests/multifamily-portals.yaml b/internal/extract/manifests/multifamily-portals.yaml new file mode 100644 index 0000000..65ab132 --- /dev/null +++ b/internal/extract/manifests/multifamily-portals.yaml @@ -0,0 +1,24 @@ +# Shared Go + TypeScript Declarative Site Adapter: Multifamily Portals (#253) +id: multifamily-portals +name: "Multifamily Apartment Portals (RentCafe / Entrata / RealPage / Jonah)" +category: commerce-social +description: "Extracts apartment floor plans, square footage, and lease pricing from RentCafe, Entrata, RealPage, and Jonah Systems multifamily portals while honoring Disallow: /*.ashx." +domains: + - "*.rentcafe.com" + - "*.entrata.com" + - "*.realpage.com" + - www.canvasatmidlothian.com + - canvasatmidlothian.com + - www.junction49.com +universalEngine: true +auth_mode: html +strict_robots: true +min_interval_ms: 1000 +exampleUrls: + - "https://www.junction49.com/floor-plans/" + +htmlRoutes: + - id: multifamily-portals + match: + exactSegments: false + mode: multifamily_portals_html diff --git a/internal/extract/manifests/municipal-cms-pack.yaml b/internal/extract/manifests/municipal-cms-pack.yaml new file mode 100644 index 0000000..842f071 --- /dev/null +++ b/internal/extract/manifests/municipal-cms-pack.yaml @@ -0,0 +1,22 @@ +# Shared Go + TypeScript Declarative Site Adapter: Municipal CMS Pack (#203) +id: municipal-cms-pack +name: Municipal CMS Pack (Revize & OpenCities) +category: public-records +description: "Universal HTML extractor for Revize and Granicus OpenCities (formerly Vision Internet) municipal government portals." +domains: + - www.maplevalleywa.gov + - www.reno.gov + - www.culvercity.gov + - www.glendaleaz.gov +universalEngine: true +auth_mode: html +exampleUrls: + - "https://www.maplevalleywa.gov/government/city_council_meetings_agendas_and_minutes.php" + - "https://www.culvercity.gov/Home" + - "https://www.glendaleaz.gov/Home" + +htmlRoutes: + - id: municipal-cms-pack + match: + exactSegments: false + mode: municipal_cms_html diff --git a/internal/extract/manifests/musicbrainz-coverart.yaml b/internal/extract/manifests/musicbrainz-coverart.yaml new file mode 100644 index 0000000..4daec10 --- /dev/null +++ b/internal/extract/manifests/musicbrainz-coverart.yaml @@ -0,0 +1,66 @@ +# Shared Go + TypeScript Declarative Site Adapter: MusicBrainz & Cover Art Archive (#378) +id: musicbrainz-coverart +name: MusicBrainz & Cover Art Archive +category: commerce-social +description: "Polite MusicBrainz WS2 JSON and Cover Art Archive release JSON adapter (1 req/s+ pacing, max_concurrent: 1, musicbrainz User-Agent profile) with MusicBrainz HTML fallback and PoW challenge rejection." +domains: + - musicbrainz.org + - coverartarchive.org +auth_mode: pub +user_agent_profile: musicbrainz +min_interval_ms: 2000 +max_concurrent: 1 +exampleUrls: + - "https://coverartarchive.org/release/76df3287-6cda-33eb-8e9a-044b5e15ffdd" + - "https://musicbrainz.org/ws/2/artist/5b11f4ce-a62d-471e-81fc-a69a8278c7da?fmt=json" + - "https://musicbrainz.org/release/76df3287-6cda-33eb-8e9a-044b5e15ffdd" + +routes: + - match: + hosts: + - musicbrainz.org + pathPrefix: /ws/2/ + exactSegments: false + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + setQueryParams: + fmt: json + maxBytes: 2097152 + extract: + jsonMode: musicbrainz_json + + - match: + hosts: + - coverartarchive.org + anyOf: + - exactSegments: true + pathSegments: + - release + - param: mbid + charset: alnum_dash + minLen: 36 + maxLen: 36 + - exactSegments: true + pathSegments: + - release-group + - param: mbid + charset: alnum_dash + minLen: 36 + maxLen: 36 + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: coverart_archive_json + +htmlRoutes: + - id: musicbrainz-coverart + match: + hosts: + - musicbrainz.org + exactSegments: false + mode: musicbrainz_html diff --git a/internal/extract/manifests/nasa-ads.yaml b/internal/extract/manifests/nasa-ads.yaml new file mode 100644 index 0000000..8f83cec --- /dev/null +++ b/internal/extract/manifests/nasa-ads.yaml @@ -0,0 +1,54 @@ +# Shared Go + TypeScript Declarative Site Adapter: NASA ADS (#308) +id: nasa-ads +name: NASA Astrophysics Data System (ADS) +category: research-health +description: "Official keyed NASA ADS API adapter (NASA_ADS_API_KEY via Authorization: Bearer) for astronomy/physics literature search and bibcodes, with ui.adsabs.harvard.edu HTML fallback and AWS WAF shell guard." +domains: + - api.adsabs.harvard.edu + - ui.adsabs.harvard.edu +auth_mode: key +min_interval_ms: 1000 +exampleUrls: + - "https://api.adsabs.harvard.edu/v1/search/query?q=bibcode:2017arXiv170603762V&fl=bibcode,title,author" + - "https://ui.adsabs.harvard.edu/abs/2017arXiv170603762V/abstract" + +routes: + - match: + hosts: + - api.adsabs.harvard.edu + pathPrefix: /v1/ + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + auth_mode: key + maxBytes: 2097152 + extract: + jsonMode: nasa_ads_json + + - match: + hosts: + - ui.adsabs.harvard.edu + exactSegments: false + pathSegments: + - abs + - param: bibcode + charset: url_seg + minLen: 10 + maxLen: 32 + twin: + fetchUrl: "https://api.adsabs.harvard.edu/v1/search/query?q=bibcode:{bibcode}&fl=bibcode,title,author,pub,year,pubdate,abstract,citation_count,doi,identifier" + kind: json + accept: application/json + auth_mode: key + maxBytes: 2097152 + extract: + jsonMode: nasa_ads_json + +htmlRoutes: + - id: nasa-ads + match: + hosts: + - ui.adsabs.harvard.edu + exactSegments: false + mode: nasa_ads_html diff --git a/internal/extract/manifests/nasdaq-data-link.yaml b/internal/extract/manifests/nasdaq-data-link.yaml new file mode 100644 index 0000000..b7cab7a --- /dev/null +++ b/internal/extract/manifests/nasdaq-data-link.yaml @@ -0,0 +1,28 @@ +# Shared Go + TypeScript Declarative Site Adapter: Nasdaq Data Link (#388) +id: nasdaq-data-link +name: Nasdaq Data Link +category: finance +description: "Extracts Nasdaq Data Link (v3) time-series datasets and datatables JSON feeds via official API key authentication." +domains: + - data.nasdaq.com +auth_mode: key +min_interval_ms: 1000 +exampleUrls: + - "https://data.nasdaq.com/api/v3/datasets/FRED/GDP.json?rows=5" + - "https://data.nasdaq.com/api/v3/datatables/ZACKS/FC.json?ticker=AAPL" + +routes: + - match: + hosts: + - data.nasdaq.com + anyOf: + - pathPrefix: /api/v3/datasets/ + - pathPrefix: /api/v3/datatables/ + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + auth_mode: key + maxBytes: 2097152 + extract: + jsonMode: nasdaq_data_link_json diff --git a/internal/extract/manifests/neogov.yaml b/internal/extract/manifests/neogov.yaml new file mode 100644 index 0000000..8a9b17b --- /dev/null +++ b/internal/extract/manifests/neogov.yaml @@ -0,0 +1,133 @@ +# Shared Go + TypeScript Declarative Site Adapter: NeoGov GovernmentJobs & SchoolJobs (#226) +id: neogov +name: "NeoGov GovernmentJobs & SchoolJobs" +category: jobs +description: "Extracts structured public-sector job feeds and postings from NeoGov GovernmentJobs and SchoolJobs RSS/JSON/HTML while strictly honoring robots.txt." +domains: + - governmentjobs.com + - www.governmentjobs.com + - "*.governmentjobs.com" + - schooljobs.com + - www.schooljobs.com + - "*.schooljobs.com" +auth_mode: pub +strict_robots: true +exampleUrls: + - "https://www.governmentjobs.com/careers/lacounty/rss" + - "https://www.governmentjobs.com/careers/lacounty" + - "https://www.schooljobs.com/careers/lausd" + +routes: + # 1. NeoGov RSS job feeds (/careers//rss or *.rss) + - match: + anyOf: + - hosts: + - governmentjobs.com + - www.governmentjobs.com + - "*.governmentjobs.com" + - schooljobs.com + - www.schooljobs.com + - "*.schooljobs.com" + pathSuffix: /rss + exactSegments: false + - hosts: + - governmentjobs.com + - www.governmentjobs.com + - "*.governmentjobs.com" + - schooljobs.com + - www.schooljobs.com + - "*.schooljobs.com" + pathSuffix: .rss + exactSegments: false + twin: + id: neogov-rss + fetchUrl: "{requestUrl}" + kind: text + accept: application/rss+xml + extract: + xml: + mode: items_table + requireAnyTags: + - rss + - channel + itemTag: item + titleTemplate: "NeoGov Public Sector Jobs ({itemCount})" + emptyText: "No open positions currently listed." + limit: 50 + requireItemVar: jTitle + collectLinkVar: jLink + emitTotals: true + itemVars: + jTitle: + tags: [title] + jLink: + tags: [link] + dept: + tags: [category, department] + default: "-" + loc: + tags: [location] + default: "-" + pubDate: + tags: [pubDate] + sliceMax: 16 + default: "-" + recordFields: + title: "{jTitle}" + url: "{jLink}" + department: "{dept}" + location: "{loc}" + postedAt: "{pubDate}" + source: neogov + columns: + - header: Role + template: "[{jTitle}]({jLink})" + - header: Department + template: "{dept}" + - header: Location + template: "{loc}" + - header: Published + template: "{pubDate}" + + # 2. NeoGov JSON endpoints (/api/... or *.json) + - match: + anyOf: + - hosts: + - governmentjobs.com + - www.governmentjobs.com + - "*.governmentjobs.com" + - schooljobs.com + - www.schooljobs.com + - "*.schooljobs.com" + pathPrefix: /api/ + exactSegments: false + - hosts: + - governmentjobs.com + - www.governmentjobs.com + - "*.governmentjobs.com" + - schooljobs.com + - www.schooljobs.com + - "*.schooljobs.com" + pathSuffix: .json + exactSegments: false + twin: + id: neogov-json + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 4194304 + extract: + jsonMode: neogov_json + +htmlRoutes: + - id: neogov + mode: neogov_html + match: + hosts: + - governmentjobs.com + - www.governmentjobs.com + - "*.governmentjobs.com" + - schooljobs.com + - www.schooljobs.com + - "*.schooljobs.com" + exactSegments: false diff --git a/internal/extract/manifests/nih-reporter.yaml b/internal/extract/manifests/nih-reporter.yaml new file mode 100644 index 0000000..77af493 --- /dev/null +++ b/internal/extract/manifests/nih-reporter.yaml @@ -0,0 +1,58 @@ +# Shared Go + TypeScript Declarative Site Adapter: NIH RePORTER (#309) +id: nih-reporter +name: NIH RePORTER Funded Projects +category: research-health +description: "Upgrades reporter.nih.gov/project-details/ URLs to api.reporter.nih.gov/v2/projects/search POST JSON with strict CSR SPA shell rejection on HTML fallback." +domains: + - api.reporter.nih.gov + - reporter.nih.gov +auth_mode: pub +min_interval_ms: 1000 +exampleUrls: + - "https://reporter.nih.gov/project-details/10476325" + - "https://api.reporter.nih.gov/v2/projects/search" + +routes: + - match: + hosts: + - api.reporter.nih.gov + pathPrefix: /v2/projects/ + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + method: POST + contentType: application/json + requestBody: '{"criteria":{"project_nums":["5R01CA242003-04"]},"limit":5}' + maxBytes: 2097152 + extract: + jsonMode: nih_reporter_json + + - match: + hosts: + - reporter.nih.gov + exactSegments: false + pathSegments: + - project-details + - param: applId + charset: digits + minLen: 4 + maxLen: 16 + twin: + fetchUrl: "https://api.reporter.nih.gov/v2/projects/search" + kind: json + accept: application/json + method: POST + contentType: application/json + requestBody: '{"criteria":{"appl_ids":[{applId}]},"limit":1}' + maxBytes: 2097152 + extract: + jsonMode: nih_reporter_json + +htmlRoutes: + - id: nih-reporter + match: + hosts: + - reporter.nih.gov + exactSegments: false + mode: nih_reporter_html diff --git a/internal/extract/manifests/nlrb-cases.yaml b/internal/extract/manifests/nlrb-cases.yaml new file mode 100644 index 0000000..ade1972 --- /dev/null +++ b/internal/extract/manifests/nlrb-cases.yaml @@ -0,0 +1,18 @@ +# Shared Go + TypeScript Declarative Site Adapter: NLRB Cases (#281) +id: nlrb-cases +name: National Labor Relations Board Cases & Dockets +category: public-records +description: "Extracts NLRB unfair labor practice and representation case metadata, docket activity rows, and decision links from nlrb.gov." +domains: + - www.nlrb.gov + - nlrb.gov +auth_mode: pub +exampleUrls: + - "https://www.nlrb.gov/case/13-CA-394913" + - "https://www.nlrb.gov/case/10-CA-400063" + +htmlRoutes: + - id: nlrb-cases + match: + exactSegments: false + mode: nlrb_cases_html diff --git a/internal/extract/manifests/nostr-relays.yaml b/internal/extract/manifests/nostr-relays.yaml new file mode 100644 index 0000000..020b141 --- /dev/null +++ b/internal/extract/manifests/nostr-relays.yaml @@ -0,0 +1,42 @@ +# Shared Go + TypeScript Declarative Site Adapter: Nostr Relays & Public Gateways (#397) +id: nostr-relays +name: Nostr Relays (NIP-11 / NIP-01) & njump Gateway +category: commerce-social +description: "Extracts Nostr relay NIP-11 metadata and bounded read-only NIP-01 event envelopes on relay roots, plus njump.me public gateway HTML notes/profiles." +domains: + - relay.damus.io + - nos.lol + - purplepag.es + - relay.primal.net + - njump.me +auth_mode: pub +min_interval_ms: 1000 +exampleUrls: + - "https://nos.lol/" + - "https://purplepag.es/" + - "https://relay.damus.io/" + - "https://njump.me/nevent1qqsyt343xphyh8txwnqyh7jgynl345f35uh5mqnmuedm7uaszclkh7svenvty" + +routes: + - match: + hosts: + - relay.damus.io + - nos.lol + - purplepag.es + - relay.primal.net + maxSegments: 0 + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/nostr+json + maxBytes: 1048576 + extract: + jsonMode: nostr_relay_json + +htmlRoutes: + - id: nostr-relays + match: + hosts: + - njump.me + exactSegments: false + mode: nostr_njump_html diff --git a/internal/extract/manifests/nsf-awards.yaml b/internal/extract/manifests/nsf-awards.yaml new file mode 100644 index 0000000..3a50912 --- /dev/null +++ b/internal/extract/manifests/nsf-awards.yaml @@ -0,0 +1,62 @@ +# Shared Go + TypeScript Declarative Site Adapter: NSF Awards (#310) +id: nsf-awards +name: National Science Foundation (NSF) Awards +category: research-health +description: "Extracts NSF grant awards, PIs, institutions, obligated amounts, and abstracts from api.nsf.gov JSON with awardsearch SPA shell guards." +domains: + - api.nsf.gov + - www.nsf.gov + - nsf.gov +auth_mode: pub +min_interval_ms: 1000 +exampleUrls: + - "https://api.nsf.gov/services/v1/awards/2535346.json" + - "https://api.nsf.gov/services/v1/awards.json?keyword=quantum&rpp=2" + - "https://www.nsf.gov/awardsearch/show-award?AWD_ID=2535346" + +routes: + - match: + hosts: + - api.nsf.gov + pathPrefix: /services/v1/awards + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: nsf_awards_json + + - match: + hosts: + - www.nsf.gov + - nsf.gov + exactSegments: true + pathEquals: + - /awardsearch/showAward + - /awardsearch/showAward/ + - /awardsearch/show-award + - /awardsearch/show-award/ + queryParams: + - name: AWD_ID + param: awardId + charset: digits + minLen: 5 + maxLen: 12 + twin: + fetchUrl: "https://api.nsf.gov/services/v1/awards/{awardId}.json" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: nsf_awards_json + +htmlRoutes: + - id: nsf-awards + match: + hosts: + - www.nsf.gov + - nsf.gov + pathPrefix: /awardsearch/ + exactSegments: false + mode: nsf_awards_html diff --git a/internal/extract/manifests/ofac-sdn.yaml b/internal/extract/manifests/ofac-sdn.yaml new file mode 100644 index 0000000..9726294 --- /dev/null +++ b/internal/extract/manifests/ofac-sdn.yaml @@ -0,0 +1,39 @@ +# Shared Go + TypeScript Declarative Site Adapter: OFAC SDN Sanctions List & Actions (#276) +id: ofac-sdn +name: OFAC SDN Sanctions List & Actions +category: public-records +description: "Bounded Range-streaming XML scanner for OFAC SDN.XML (<= 2 MiB) plus recent-actions and sanctions program HTML extraction on ofac.treasury.gov." +domains: + - sanctionslistservice.ofac.treas.gov + - ofac.treasury.gov +auth_mode: pub +exampleUrls: + - "https://sanctionslistservice.ofac.treas.gov/api/PublicationPreview/exports/SDN.XML" + - "https://ofac.treasury.gov/recent-actions" + +routes: + - match: + hosts: + - sanctionslistservice.ofac.treas.gov + exactSegments: true + pathEquals: + - /api/PublicationPreview/exports/SDN.XML + - /api/PublicationPreview/exports/CONS_PRIM.XML + - /api/PublicationPreview/exports/SDN_ENHANCED.XML + twin: + fetchUrl: "{requestUrl}" + kind: text + accept: application/xml + headers: + Range: bytes=0-2097151 + maxBytes: 2097152 + extract: + textMode: ofac_sdn_xml + +htmlRoutes: + - id: ofac-sdn + match: + hosts: + - ofac.treasury.gov + exactSegments: false + mode: ofac_html diff --git a/internal/extract/manifests/open-icecat.yaml b/internal/extract/manifests/open-icecat.yaml new file mode 100644 index 0000000..0e65d5b --- /dev/null +++ b/internal/extract/manifests/open-icecat.yaml @@ -0,0 +1,62 @@ +# Shared Go + TypeScript Declarative Site Adapter: Open Icecat (#369) +id: open-icecat +name: Open Icecat Product Datasheets +category: commerce-social +description: "Extracts Open Icecat live API JSON product datasheets (strict 8/12/13/14-digit GTIN or Icecat ID validation) and Icecat HTML product pages while rejecting brand-restricted/missing error envelopes." +domains: + - live.icecat.biz + - data.icecat.biz + - icecat.biz + - www.icecat.biz + - icecat.us +auth_mode: pub +min_interval_ms: 1000 +exampleUrls: + - "https://live.icecat.biz/api?shopname=openicecat-live&lang=en>IN=8710103792772" + - "https://icecat.biz/en/p/saeco/ca6705-60/water-care-32928991.html" + +routes: + - match: + hosts: + - live.icecat.biz + pathEquals: + - /api + - /api/ + anyOf: + - queryParams: + - name: GTIN + param: gtin + charset: digits + minLen: 8 + maxLen: 8 + - queryParams: + - name: GTIN + param: gtin + charset: digits + minLen: 12 + maxLen: 14 + - queryParams: + - name: icecat_id + param: icecatId + charset: digits + minLen: 1 + maxLen: 18 + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + auth_mode: pub + maxBytes: 4194304 + extract: + jsonMode: open_icecat_json + +htmlRoutes: + - id: open-icecat + match: + hosts: + - icecat.biz + - www.icecat.biz + - icecat.us + - data.icecat.biz + exactSegments: false + mode: open_icecat_html diff --git a/internal/extract/manifests/open-product-wikidata-gtin.yaml b/internal/extract/manifests/open-product-wikidata-gtin.yaml new file mode 100644 index 0000000..409e92d --- /dev/null +++ b/internal/extract/manifests/open-product-wikidata-gtin.yaml @@ -0,0 +1,64 @@ +# Shared Go + TypeScript Declarative Site Adapter: Open Product Data & Wikidata GTIN (#371) +id: open-product-wikidata-gtin +name: Open Product Data & Wikidata GTIN Lookup +category: commerce-social +description: "Extracts OpenGTINdb key=value product records (?ean=) and Wikidata P3962 SPARQL JSON bindings with strict 8/12/13/14-digit GTIN validation (without overlapping wikidata-openlibrary or opendatasoft domains)." +domains: + - opengtindb.org + - www.opengtindb.org + - query.wikidata.org +auth_mode: pub +min_interval_ms: 1000 +exampleUrls: + - "https://query.wikidata.org/sparql?query=SELECT%20%3Fitem%20%3FitemLabel%20%3Fgtin%20WHERE%20%7B%20%3Fitem%20wdt%3AP3962%20%3Fgtin%20.%20SERVICE%20wikibase%3Alabel%20%7B%20bd%3AserviceParam%20wikibase%3Alanguage%20%22en%22.%20%7D%20%7D%20LIMIT%205" + +routes: + - match: + hosts: + - opengtindb.org + - www.opengtindb.org + pathEquals: + - / + anyOf: + - queryParams: + - name: ean + param: ean + charset: digits + minLen: 8 + maxLen: 8 + - queryParams: + - name: ean + param: ean + charset: digits + minLen: 12 + maxLen: 14 + twin: + fetchUrl: "{requestUrl}" + kind: text + accept: text/plain + maxBytes: 262144 + extract: + textMode: opengtindb_text + + - match: + hosts: + - query.wikidata.org + pathEquals: + - /sparql + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/sparql-results+json + maxBytes: 2097152 + extract: + jsonMode: wikidata_gtin_sparql_json + +htmlRoutes: + - id: open-product-wikidata-gtin + match: + hosts: + - opengtindb.org + - www.opengtindb.org + - query.wikidata.org + exactSegments: false + mode: open_product_wikidata_html diff --git a/internal/extract/manifests/opendatasoft.yaml b/internal/extract/manifests/opendatasoft.yaml index 7581d1e..3047586 100644 --- a/internal/extract/manifests/opendatasoft.yaml +++ b/internal/extract/manifests/opendatasoft.yaml @@ -2,15 +2,20 @@ id: opendatasoft name: Opendatasoft Open Data Portals (Explore API v2.1) category: public-records -description: "Universal Opendatasoft adapter: /explore/dataset// pages and /api/explore/v2.1/catalog/datasets/ upgrade to dataset metadata (publisher, license, record count, field schema, records/CSV API links); /records URLs render rows as a table." +description: "Universal Opendatasoft adapter: /explore/dataset// pages and /api/explore/v2.1/catalog/datasets(/) upgrade to dataset metadata (publisher, license, record count, field schema, records/CSV API links); /records URLs render rows as a table while enforcing strict robots.txt compliance." domains: - public.opendatasoft.com + - "*.opendatasoft.com" + - data.townofcary.org + - data.jerseycitynj.gov universalEngine: true auth_mode: pub +strict_robots: true min_interval_ms: 1000 exampleUrls: - "https://public.opendatasoft.com/explore/dataset/us-state-boundaries/" - "https://public.opendatasoft.com/api/explore/v2.1/catalog/datasets/us-state-boundaries/records?limit=3&select=name,stusab,region,division" + - "https://data.townofcary.org/api/explore/v2.1/catalog/datasets?limit=3" routes: - match: @@ -34,6 +39,17 @@ routes: extract: jsonMode: opendatasoft_records_json + - match: + pathEquals: + - /api/explore/v2.1/catalog/datasets + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 4194304 + extract: + jsonMode: opendatasoft_dataset_json + - match: exactSegments: true pathSegments: diff --git a/internal/extract/manifests/opengov-portals.yaml b/internal/extract/manifests/opengov-portals.yaml new file mode 100644 index 0000000..47118aa --- /dev/null +++ b/internal/extract/manifests/opengov-portals.yaml @@ -0,0 +1,32 @@ +# Shared Go + TypeScript Declarative Site Adapter: OpenGov Portals (#211) +id: opengov-portals +name: OpenGov Transparency & Procurement Portals +category: public-records +description: "Extracts fiscal transparency datasets, window.gon/Zeus hydration, and public API data from OpenGov portals while classifying Cloudflare challenges honestly." +domains: + - "*.opengov.com" +auth_mode: pub +exampleUrls: + - "https://torranceca.opengov.com/api/v1/reports" + - "https://torranceca.opengov.com/transparency" + - "https://sanbernardinoca.opengov.com/transparency" + +routes: + - match: + anyOf: + - pathPrefix: /api/v1/ + - pathPrefix: /api/v2/ + - pathPrefix: /transparency/api/ + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 4194304 + extract: + jsonMode: opengov_json + +htmlRoutes: + - id: opengov-portals + match: + exactSegments: false + mode: opengov_html diff --git a/internal/extract/manifests/orcid.yaml b/internal/extract/manifests/orcid.yaml new file mode 100644 index 0000000..e454869 --- /dev/null +++ b/internal/extract/manifests/orcid.yaml @@ -0,0 +1,55 @@ +# Shared Go + TypeScript Declarative Site Adapter: ORCID (#304) +id: orcid +name: ORCID Researcher Registry +category: research-health +description: "Extracts ORCID researcher profiles, affiliations, and works via pub.orcid.org v3.0 JSON API with orcid.org Angular CSR shell guard." +domains: + - pub.orcid.org + - orcid.org + - www.orcid.org +auth_mode: pub +min_interval_ms: 1000 +exampleUrls: + - "https://pub.orcid.org/v3.0/0000-0002-1825-0097/record" + - "https://orcid.org/0000-0002-1825-0097" + +routes: + - match: + hosts: + - pub.orcid.org + pathPrefix: /v3.0/ + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: orcid_json + + - match: + hosts: + - orcid.org + - www.orcid.org + exactSegments: true + pathSegments: + - param: orcidId + charset: cpsc_recall_num + minLen: 19 + maxLen: 19 + transform: upper + twin: + fetchUrl: "https://pub.orcid.org/v3.0/{orcidId}/record" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: orcid_json + +htmlRoutes: + - id: orcid + match: + hosts: + - orcid.org + - www.orcid.org + exactSegments: false + mode: orcid_html diff --git a/internal/extract/manifests/osha-establishment.yaml b/internal/extract/manifests/osha-establishment.yaml new file mode 100644 index 0000000..2beb010 --- /dev/null +++ b/internal/extract/manifests/osha-establishment.yaml @@ -0,0 +1,20 @@ +# Shared Go + TypeScript Declarative Site Adapter: OSHA Establishment Search & ITA (#280) +id: osha-establishment +name: OSHA Establishment Inspections & Injury Data +category: public-records +description: "Extracts OSHA IMIS/ORDS establishment inspection records and ITA injury/illness data pages from osha.gov while honoring robots.txt and detecting CloudFront 403 blocks." +domains: + - www.osha.gov + - osha.gov +auth_mode: pub +strict_robots: true +min_interval_ms: 1500 +exampleUrls: + - "https://www.osha.gov/pls/imis/establishment.html" + - "https://www.osha.gov/Establishment-Specific-Injury-and-Illness-Data" + +htmlRoutes: + - id: osha-establishment + match: + exactSegments: false + mode: osha_establishment_html diff --git a/internal/extract/manifests/oversight-gov.yaml b/internal/extract/manifests/oversight-gov.yaml new file mode 100644 index 0000000..46b1a05 --- /dev/null +++ b/internal/extract/manifests/oversight-gov.yaml @@ -0,0 +1,17 @@ +# Shared Go + TypeScript Declarative Site Adapter: Oversight.gov IG Reports (#288) +id: oversight-gov +name: Oversight.gov Inspector General Reports +category: public-records +description: "Extracts Council of the Inspectors General on Integrity and Efficiency (CIGIE) Inspector General reports and metadata from oversight.gov while rejecting Azure App Gateway 406 shells." +domains: + - www.oversight.gov + - oversight.gov +auth_mode: pub +exampleUrls: + - "https://www.oversight.gov/reports" + +htmlRoutes: + - id: oversight-gov + match: + exactSegments: false + mode: oversight_gov_html diff --git a/internal/extract/manifests/paradox-olivia.yaml b/internal/extract/manifests/paradox-olivia.yaml new file mode 100644 index 0000000..cbc7e2b --- /dev/null +++ b/internal/extract/manifests/paradox-olivia.yaml @@ -0,0 +1,19 @@ +# Shared Go + TypeScript Declarative Site Adapter: Paradox Olivia Career Sites (#229) +id: paradox-olivia +name: "Paradox Olivia Career Sites" +category: jobs +description: "Extracts JobPosting JSON-LD and __NEXT_DATA__ hydration job listings from Paradox Olivia career sites (*.paradox.ai, jobs.mchire.com, and custom brand portals via universalEngine)." +domains: + - "*.paradox.ai" + - jobs.mchire.com + - www.mchire.com +universalEngine: true +auth_mode: html +exampleUrls: + - "https://careers.fedex.com/account-manager-ii/job/P25-397759-1" + +htmlRoutes: + - id: paradox-olivia + mode: paradox_olivia_html + match: + exactSegments: false diff --git a/internal/extract/manifests/park-tool.yaml b/internal/extract/manifests/park-tool.yaml new file mode 100644 index 0000000..e326a5a --- /dev/null +++ b/internal/extract/manifests/park-tool.yaml @@ -0,0 +1,18 @@ +# Shared Go + TypeScript Declarative Site Adapter: Park Tool Repair Help & Specs (#342) +id: park-tool +name: Park Tool Repair Help & Tool Specs +category: developer +description: "Extracts ordered bicycle repair steps, required tools, HowTo JSON-LD, and tool specification tables from parktool.com repair help and product pages." +domains: + - parktool.com + - www.parktool.com +auth_mode: html +exampleUrls: + - "https://www.parktool.com/en-us/blog/repair-help/rear-derailleur-adjustment" + - "https://www.parktool.com/en-us/product/chain-checker-cc-4" + +htmlRoutes: + - id: park-tool + match: + exactSegments: false + mode: park_tool_html diff --git a/internal/extract/manifests/patreon-public.yaml b/internal/extract/manifests/patreon-public.yaml new file mode 100644 index 0000000..c953bf9 --- /dev/null +++ b/internal/extract/manifests/patreon-public.yaml @@ -0,0 +1,43 @@ +# Shared Go + TypeScript Declarative Site Adapter: Patreon Public Creator Pages (#400) +id: patreon-public +name: Patreon Public Creator & Post Pages +category: commerce-social +description: "Extracts public Patreon creator profiles, membership tiers, and public posts from HTML structured-data JSON-LD and Next.js RSC payloads while honoring robots.txt disallows on /api/ and /rss/." +domains: + - www.patreon.com + - patreon.com +auth_mode: html +min_interval_ms: 1500 +strict_robots: true +exampleUrls: + - "https://www.patreon.com/cw/Kurzgesagt" + - "https://www.patreon.com/posts/behind-the-scenes-12345678" + +htmlRoutes: + - id: patreon-public + match: + hosts: + - www.patreon.com + - patreon.com + reservedFirstSegment: + - api + - rss + - login + - signup + - oauth2 + - settings + - user + - checkout + - pledge + - search + anyOf: + - pathPrefix: /cw/ + - pathPrefix: /c/ + - pathPrefix: /posts/ + - exactSegments: true + pathSegments: + - param: creator + charset: url_seg + minLen: 1 + maxLen: 120 + mode: patreon_public_html diff --git a/internal/extract/manifests/peer-resale-fashion.yaml b/internal/extract/manifests/peer-resale-fashion.yaml new file mode 100644 index 0000000..a69d2bb --- /dev/null +++ b/internal/extract/manifests/peer-resale-fashion.yaml @@ -0,0 +1,35 @@ +# Shared Go + TypeScript Declarative Site Adapter: Peer Resale Fashion (#364) +id: peer-resale-fashion +name: Mercari, Poshmark, Depop & Grailed Resale +category: commerce-social +description: "Extracts public peer-to-peer fashion and secondhand listings from Poshmark, Mercari, Depop, and Grailed via JSON-LD, hydration state, and DOM fallback with strict WAF/404 guards." +domains: + - mercari.com + - www.mercari.com + - poshmark.com + - www.poshmark.com + - depop.com + - www.depop.com + - grailed.com + - www.grailed.com +auth_mode: html +min_interval_ms: 2000 +strict_robots: true +exampleUrls: + - "https://poshmark.com/listing/ANTHROPOLOGIE-Saturday-Sunday-Annika-2Piece-Waffle-Knit-Lounge-Set-2X-6a67deaeb6af921bbc5288a4" + - "https://poshmark.com/category/Women" + - "https://www.mercari.com/us/category/1/" + +htmlRoutes: + - id: peer-resale-fashion + match: + anyOf: + - pathPrefix: /listing/ + - pathPrefix: /category/ + - pathPrefix: /brand/ + - pathPrefix: /us/item/ + - pathPrefix: /us/category/ + - pathPrefix: /products/ + - pathPrefix: /listings/ + - pathPrefix: /shop/ + mode: peer_resale_fashion_html diff --git a/internal/extract/manifests/peertube.yaml b/internal/extract/manifests/peertube.yaml new file mode 100644 index 0000000..e785b2c --- /dev/null +++ b/internal/extract/manifests/peertube.yaml @@ -0,0 +1,89 @@ +# Shared Go + TypeScript Declarative Site Adapter: PeerTube (#249) +id: peertube +name: "PeerTube Federated Video Platform (Universal Engine)" +category: commerce-social +description: "Upgrades PeerTube video permalinks (/w/{videoId} and /videos/watch/{videoId}) and /api/v1/videos/* endpoints via JSON API with VideoObject HTML fallback." +domains: + - video.blender.org + - tilvids.com + - framatube.org +universalEngine: true +auth_mode: pub +exampleUrls: + - "https://video.blender.org/w/v3kudnbEWnLVG5Fzormny6" + - "https://video.blender.org/api/v1/videos/v3kudnbEWnLVG5Fzormny6" + - "https://tilvids.com/api/v1/videos/6PsLUGoGiV9isoaHmht6Eu" + +routes: + - match: + exactSegments: true + pathSegments: + - api + - v1 + - videos + - param: videoId + charset: url_seg + minLen: 8 + maxLen: 64 + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: peertube_json + - match: + exactSegments: true + pathSegments: + - api + - v1 + - videos + - param: videoId + charset: url_seg + minLen: 8 + maxLen: 64 + - captions + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 1048576 + extract: + jsonMode: peertube_json + - match: + exactSegments: true + pathSegments: + - w + - param: videoId + charset: url_seg + minLen: 8 + maxLen: 64 + twin: + fetchUrl: "https://{host}/api/v1/videos/{videoId}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: peertube_json + - match: + exactSegments: true + pathSegments: + - videos + - watch + - param: videoId + charset: url_seg + minLen: 8 + maxLen: 64 + twin: + fetchUrl: "https://{host}/api/v1/videos/{videoId}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: peertube_json + +htmlRoutes: + - id: peertube + match: + exactSegments: false + mode: peertube_html diff --git a/internal/extract/manifests/pinkbike-buysell.yaml b/internal/extract/manifests/pinkbike-buysell.yaml new file mode 100644 index 0000000..3bbc030 --- /dev/null +++ b/internal/extract/manifests/pinkbike-buysell.yaml @@ -0,0 +1,24 @@ +# Shared Go + TypeScript Declarative Site Adapter: Pinkbike BuySell (#360) +id: pinkbike-buysell +name: Pinkbike BuySell Marketplace +category: commerce-social +description: "Extracts bicycle classified listings and category search results from Pinkbike BuySell while strictly rejecting Cloudflare challenge shells." +domains: + - pinkbike.com + - www.pinkbike.com +auth_mode: html +min_interval_ms: 2000 +max_concurrent: 1 +strict_robots: true +exampleUrls: + - "https://www.pinkbike.com/buysell/" + - "https://www.pinkbike.com/buysell/list/?category=2" + +htmlRoutes: + - id: pinkbike-buysell + match: + anyOf: + - pathEquals: + - /buysell + - pathPrefix: /buysell/ + mode: pinkbike_buysell_html diff --git a/internal/extract/manifests/pm-listing-widgets.yaml b/internal/extract/manifests/pm-listing-widgets.yaml new file mode 100644 index 0000000..0374976 --- /dev/null +++ b/internal/extract/manifests/pm-listing-widgets.yaml @@ -0,0 +1,22 @@ +# Shared Go + TypeScript Declarative Site Adapter: Property Management Listing Widgets (#252) +id: pm-listing-widgets +name: "Property Management Listing Widgets (Buildium / Propertyware / RentManager)" +category: commerce-social +description: "Extracts public rental unit listings, rent pricing, bed/bath counts, and detail links from Buildium (managebuilding.com), Propertyware, and RentManager portals." +domains: + - "*.managebuilding.com" + - "*.propertyware.com" + - "*.rentmanager.com" +universalEngine: true +auth_mode: html +strict_robots: true +min_interval_ms: 1000 +exampleUrls: + - "https://portland.managebuilding.com/Resident/public/rentals" + - "https://hannibalrentals.managebuilding.com/Resident/public/rentals" + +htmlRoutes: + - id: pm-listing-widgets + match: + exactSegments: false + mode: pm_listing_widgets_html diff --git a/internal/extract/manifests/podcast-index.yaml b/internal/extract/manifests/podcast-index.yaml new file mode 100644 index 0000000..24654b4 --- /dev/null +++ b/internal/extract/manifests/podcast-index.yaml @@ -0,0 +1,58 @@ +# Shared Go + TypeScript Declarative Site Adapter: Podcast Index (#380) +id: podcast-index +name: Podcast Index Directory +category: commerce-social +description: "Official keyed Podcast Index v1.0 API adapter (PODCASTINDEX_API_KEY + PODCASTINDEX_API_SECRET SHA-1 auth) for podcast feeds, episodes, and search, with podcastindex.org HTML fallback." +domains: + - api.podcastindex.org + - podcastindex.org + - www.podcastindex.org +auth_mode: key +min_interval_ms: 1000 +exampleUrls: + - "https://api.podcastindex.org/api/1.0/podcasts/byfeedid?id=920666" + - "https://api.podcastindex.org/api/1.0/episodes/byfeedid?id=920666" + +routes: + - match: + hosts: + - api.podcastindex.org + pathPrefix: /api/1.0/ + exactSegments: false + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + auth_mode: key + maxBytes: 2097152 + extract: + jsonMode: podcast_index_json + + - match: + hosts: + - podcastindex.org + - www.podcastindex.org + exactSegments: true + pathSegments: + - podcast + - param: feedId + charset: digits + minLen: 1 + maxLen: 16 + twin: + fetchUrl: "https://api.podcastindex.org/api/1.0/podcasts/byfeedid?id={feedId}" + kind: json + accept: application/json + auth_mode: key + maxBytes: 2097152 + extract: + jsonMode: podcast_index_json + +htmlRoutes: + - id: podcast-index + match: + hosts: + - podcastindex.org + - www.podcastindex.org + exactSegments: false + mode: podcast_index_html diff --git a/internal/extract/manifests/popmenu.yaml b/internal/extract/manifests/popmenu.yaml new file mode 100644 index 0000000..4df7ce8 --- /dev/null +++ b/internal/extract/manifests/popmenu.yaml @@ -0,0 +1,21 @@ +# Shared Go + TypeScript Declarative Site Adapter: Popmenu (#255) +id: popmenu +name: "Popmenu Restaurant Menus" +category: commerce-social +description: "Extracts restaurant menu sections, dishes, descriptions, and prices from Popmenu DOM, Apollo state, and Menu JSON-LD while rejecting Cloudflare challenge interstitials." +domains: + - popmenu.com + - www.popmenu.com + - "*.popmenu.com" +universalEngine: true +auth_mode: html +strict_robots: true +min_interval_ms: 2000 +exampleUrls: + - "https://www.popmenu.com/" + +htmlRoutes: + - id: popmenu + match: + exactSegments: false + mode: popmenu_html diff --git a/internal/extract/manifests/primegov.yaml b/internal/extract/manifests/primegov.yaml new file mode 100644 index 0000000..80250de --- /dev/null +++ b/internal/extract/manifests/primegov.yaml @@ -0,0 +1,41 @@ +# Shared Go + TypeScript Declarative Site Adapter: PrimeGov (#206) +id: primegov +name: Rock Solid / Granicus PrimeGov Portals +category: public-records +description: "Extracts upcoming municipal meetings and agendas from PrimeGov PublicPortal API and HTML views while strictly honoring robots.txt." +domains: + - "*.primegov.com" +auth_mode: pub +strict_robots: true +exampleUrls: + - "https://okc.primegov.com/api/v2/PublicPortal/ListUpcomingMeetings" + - "https://okc.primegov.com/public/portal" + +routes: + - match: + pathPrefix: /api/v2/PublicPortal/ + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 4194304 + extract: + jsonMode: primegov_json + + - match: + pathEquals: + - /public/portal + - /public/portal/ + twin: + fetchUrl: "https://{host}/api/v2/PublicPortal/ListUpcomingMeetings" + kind: json + accept: application/json + maxBytes: 4194304 + extract: + jsonMode: primegov_json + +htmlRoutes: + - id: primegov + match: + exactSegments: false + mode: primegov_html diff --git a/internal/extract/manifests/product-hunt.yaml b/internal/extract/manifests/product-hunt.yaml new file mode 100644 index 0000000..bb0e2ea --- /dev/null +++ b/internal/extract/manifests/product-hunt.yaml @@ -0,0 +1,44 @@ +# Shared Go + TypeScript Declarative Site Adapter: Product Hunt (#398) +id: product-hunt +name: Product Hunt API & Launches +category: commerce-social +description: "Extracts Product Hunt launches, makers, topics, and vote counts via official GraphQL v2 API (PRODUCTHUNT_API_TOKEN) with www.producthunt.com HTML fallback and strict Cloudflare challenge guard." +domains: + - api.producthunt.com + - www.producthunt.com + - producthunt.com +auth_mode: key +min_interval_ms: 1000 +strict_robots: true +exampleUrls: + - "https://api.producthunt.com/v2/api/graphql" + - "https://www.producthunt.com/posts/claude-3-5-sonnet" + +routes: + - match: + hosts: + - api.producthunt.com + pathEquals: + - /v2/api/graphql + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + method: POST + contentType: application/json + requestBody: "{\"query\":\"{ posts(first: 10) { edges { node { id name tagline description votesCount commentsCount url website createdAt topics { edges { node { name } } } makers { name username } } } } }\"}" + auth_mode: key + maxBytes: 2097152 + extract: + jsonMode: product_hunt_json + +htmlRoutes: + - id: product-hunt + match: + hosts: + - www.producthunt.com + - producthunt.com + anyOf: + - pathPrefix: /posts/ + - pathPrefix: /products/ + mode: product_hunt_html diff --git a/internal/extract/manifests/prop65-warnings.yaml b/internal/extract/manifests/prop65-warnings.yaml new file mode 100644 index 0000000..0aebc12 --- /dev/null +++ b/internal/extract/manifests/prop65-warnings.yaml @@ -0,0 +1,22 @@ +# Shared Go + TypeScript Declarative Site Adapter: California Proposition 65 Warnings (#374) +id: prop65-warnings +name: California Proposition 65 Chemical List & Warnings +category: public-records +description: "Extracts California OEHHA Proposition 65 chemical lists and p65warnings.ca.gov chemical fact sheets while rejecting Incapsula WAF challenge shells and error pages." +domains: + - oehha.ca.gov + - www.oehha.ca.gov + - p65warnings.ca.gov + - www.p65warnings.ca.gov +auth_mode: html +min_interval_ms: 1500 +strict_robots: true +exampleUrls: + - "https://oehha.ca.gov/proposition-65/proposition-65-list" + - "https://www.p65warnings.ca.gov/fact-sheets/acrylamide" + +htmlRoutes: + - id: prop65-warnings + match: + exactSegments: false + mode: prop65_warnings_html diff --git a/internal/extract/manifests/public-bid-portals.yaml b/internal/extract/manifests/public-bid-portals.yaml new file mode 100644 index 0000000..1ea71a5 --- /dev/null +++ b/internal/extract/manifests/public-bid-portals.yaml @@ -0,0 +1,22 @@ +# Shared Go + TypeScript Declarative Site Adapter: Public Bid Portals (#212) +id: public-bid-portals +name: Public Procurement & Bid Portals (Bonfire, BidNet, Periscope) +category: public-records +description: "Extracts public municipal solicitations and RFPs from BidNet Direct, Bonfire, and Periscope S2G while classifying login-gated bid details as login_wall." +domains: + - "*.bonfirehub.com" + - www.bidnetdirect.com + - bidnetdirect.com + - www.bidsync.com + - app.periscopeholdings.com +auth_mode: html +strict_robots: true +exampleUrls: + - "https://www.bidnetdirect.com/colorado/cityandcountyofdenverdoti/solicitations/open-bids?selectedContent=BUYER" + - "https://www.bidnetdirect.com/colorado/solicitations/open-bids/W-38th-Ave-Multimodal-Improvements-Design-Services/0000443656?purchasingGroupId=8409951&origin=2" + +htmlRoutes: + - id: public-bid-portals + match: + exactSegments: false + mode: public_bid_html diff --git a/internal/extract/manifests/q4-ir.yaml b/internal/extract/manifests/q4-ir.yaml new file mode 100644 index 0000000..0483758 --- /dev/null +++ b/internal/extract/manifests/q4-ir.yaml @@ -0,0 +1,44 @@ +# Shared Go + TypeScript Declarative Site Adapter: Q4 Inc. Investor Relations (#259) +id: q4-ir +name: "Q4 Inc. Investor Relations Portals" +category: finance +description: "Extracts Q4 Investor Relations /feed/PressRelease.svc and /feed/Event.svc JSON endpoints plus HTML press release and event pages while rejecting Cloudflare challenges." +domains: + - "*.q4web.com" + - investors.braze.com +universalEngine: true +auth_mode: pub +strict_robots: true +min_interval_ms: 1000 +exampleUrls: + - "https://mtr.q4web.com/feed/PressRelease.svc/GetPressReleaseList?LanguageId=1&bodyType=0&pressReleaseDateFilter=3&pageSize=5&pageNumber=0" + - "https://investors.braze.com/feed/Event.svc/GetEventList?apiKey=BF185719B0464B3AB809D2E68A89D240&LanguageId=1&eventDateFilter=3&pageSize=5&pageNumber=0" + +routes: + - match: + pathPrefix: /feed/PressRelease.svc/ + exactSegments: false + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 4194304 + extract: + jsonMode: q4_ir_json + + - match: + pathPrefix: /feed/Event.svc/ + exactSegments: false + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 4194304 + extract: + jsonMode: q4_ir_json + +htmlRoutes: + - id: q4-ir + match: + exactSegments: false + mode: q4_ir_html diff --git a/internal/extract/manifests/qbp-frame-brands.yaml b/internal/extract/manifests/qbp-frame-brands.yaml new file mode 100644 index 0000000..36e485c --- /dev/null +++ b/internal/extract/manifests/qbp-frame-brands.yaml @@ -0,0 +1,23 @@ +# Shared Go + TypeScript Declarative Site Adapter: Frame & Touring Bike Brands (#352) +id: qbp-frame-brands +name: "Frame & Touring Bike Brands (Surly, Salsa, All-City)" +category: commerce-social +description: "Extracts public bicycle frame specifications, axle/tire clearance, and geometry tables from Surly, Salsa, and All-City public brand sites." +domains: + - surlybikes.com + - www.surlybikes.com + - salsacycles.com + - www.salsacycles.com + - allcitycycles.com + - www.allcitycycles.com +auth_mode: html +min_interval_ms: 1000 +exampleUrls: + - "https://surlybikes.com/collections/karate-monkey" + - "https://www.salsacycles.com/products/fargo-32-steel-frameset" + +htmlRoutes: + - id: qbp-frame-brands + match: + exactSegments: false + mode: qbp_frame_brands_html diff --git a/internal/extract/manifests/race-results-pack.yaml b/internal/extract/manifests/race-results-pack.yaml new file mode 100644 index 0000000..20c4324 --- /dev/null +++ b/internal/extract/manifests/race-results-pack.yaml @@ -0,0 +1,35 @@ +# Shared Go + TypeScript Declarative Site Adapter: Race Results Pack (#247) +id: race-results-pack +name: "Race Results Pack (Athlinks, Race Roster, ACTIVE)" +category: commerce-social +description: "Extracts endurance race events and results from Athlinks, Race Roster, and ACTIVE JSON-LD, hydration JSON, and results tables while strictly rejecting empty CSR SPA shells." +domains: + - athlinks.com + - www.athlinks.com + - results.athlinks.com + - raceroster.com + - www.raceroster.com + - results.raceroster.com + - active.com + - www.active.com + - resultscui.active.com +universalEngine: false +auth_mode: html +exampleUrls: + - "https://www.active.com/baltimore-md/running/distance-running-races/9th-annual-homewood-holiday-5k-2026" + +htmlRoutes: + - id: race-results-pack + match: + hosts: + - athlinks.com + - www.athlinks.com + - results.athlinks.com + - raceroster.com + - www.raceroster.com + - results.raceroster.com + - active.com + - www.active.com + - resultscui.active.com + exactSegments: false + mode: race_results_pack_html diff --git a/internal/extract/manifests/rdap.yaml b/internal/extract/manifests/rdap.yaml new file mode 100644 index 0000000..3790f02 --- /dev/null +++ b/internal/extract/manifests/rdap.yaml @@ -0,0 +1,88 @@ +# Shared Go + TypeScript Declarative Site Adapter: RDAP Registration Data (#325) +id: rdap +name: RDAP (Registration Data Access Protocol) +category: developer +description: "Universal RFC 9083 RDAP JSON extractor for domain, IP, autnum, and entity lookups across RIRs/registries plus IANA RDAP bootstrap registries." +domains: + - rdap.verisign.com + - rdap.arin.net + - rdap.apnic.net + - rdap.db.ripe.net + - rdap.ripe.net + - rdap.lacnic.net + - rdap.afrinic.net + - data.iana.org + - rdap.org +universalEngine: true +auth_mode: pub +min_interval_ms: 1000 +exampleUrls: + - "https://rdap.verisign.com/com/v1/domain/example.com" + - "https://rdap.arin.net/registry/autnum/13335" + - "https://rdap.apnic.net/ip/1.1.1.1" + - "https://rdap.db.ripe.net/ip/193.0.0.193" + - "https://data.iana.org/rdap/dns.json" + +routes: + - match: + hosts: + - data.iana.org + exactSegments: false + pathPrefix: /rdap/ + pathSuffix: .json + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: rdap_bootstrap_json + + - match: + hosts: + - rdap.verisign.com + - rdap.arin.net + - rdap.apnic.net + - rdap.db.ripe.net + - rdap.ripe.net + - rdap.lacnic.net + - rdap.afrinic.net + - rdap.org + - "rdap.*" + - "*.rdap.org" + - pubapi.registry.google + exactSegments: false + anyOf: + - pathPrefix: /domain/ + - pathPrefix: /ip/ + - pathPrefix: /autnum/ + - pathPrefix: /entity/ + - pathContainsSegment: domain + - pathContainsSegment: ip + - pathContainsSegment: autnum + - pathContainsSegment: entity + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/rdap+json, application/json + maxBytes: 1048576 + extract: + jsonMode: rdap_json + + - match: + excludeHosts: + - data.iana.org + exactSegments: false + pathPrefix: /rdap/ + anyOf: + - pathContainsSegment: domain + - pathContainsSegment: ip + - pathContainsSegment: autnum + - pathContainsSegment: entity + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/rdap+json, application/json + maxBytes: 1048576 + extract: + jsonMode: rdap_json diff --git a/internal/extract/manifests/rebuy-searchanise.yaml b/internal/extract/manifests/rebuy-searchanise.yaml new file mode 100644 index 0000000..005f4bc --- /dev/null +++ b/internal/extract/manifests/rebuy-searchanise.yaml @@ -0,0 +1,44 @@ +# Shared Go + TypeScript Declarative Site Adapter: Rebuy & Searchanise (#266) +id: rebuy-searchanise +name: "Rebuy & Searchanise Storefront APIs" +category: commerce-social +description: "Page-key adapter for Rebuy recommendation APIs and Searchanise searchserverapi.com JSON results; companion HTML mode yields so shopify_html is never preempted." +domains: + - rebuyengine.com + - www.rebuyengine.com + - searchserverapi.com + - www.searchserverapi.com +universalEngine: true +auth_mode: page-key +requires_page_key_opt_in: true +exampleUrls: + - "https://www.searchserverapi.com/getresults?apiKey=1Q7P8A7s4h&q=&output=json&maxResults=3" + +routes: + - match: + anyOf: + - hosts: + - rebuyengine.com + - www.rebuyengine.com + pathPrefix: /api/v1/ + - hosts: + - searchserverapi.com + - www.searchserverapi.com + pathEquals: + - /getresults + - /getwidgets + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 2097152 + requires_page_key_opt_in: true + auth_mode: page-key + extract: + jsonMode: rebuy_searchanise_json + +htmlRoutes: + - id: rebuy-searchanise + match: + exactSegments: false + mode: rebuy_searchanise_html diff --git a/internal/extract/manifests/recharge-bold-subscriptions.yaml b/internal/extract/manifests/recharge-bold-subscriptions.yaml new file mode 100644 index 0000000..bc128cd --- /dev/null +++ b/internal/extract/manifests/recharge-bold-subscriptions.yaml @@ -0,0 +1,17 @@ +# Shared Go + TypeScript Declarative Site Adapter: Recharge & Bold Subscriptions (#264) +id: recharge-bold-subscriptions +name: "Recharge & Bold Subscriptions" +category: commerce-social +description: "Extracts product and recurring selling-plan subscription metadata from storefronts powered by Recharge or Bold Subscriptions; yields on non-subscription PDPs so shopify_html is not preempted." +domains: + - us.whogivesacrap.org +universalEngine: true +auth_mode: html +exampleUrls: + - "https://us.whogivesacrap.org/products/100-recycled-toilet-paper-jumbo-rolls" + +htmlRoutes: + - id: recharge-bold-subscriptions + match: + exactSegments: false + mode: recharge_bold_subscriptions_html diff --git a/internal/extract/manifests/research-repo-pack.yaml b/internal/extract/manifests/research-repo-pack.yaml new file mode 100644 index 0000000..a92d1a3 --- /dev/null +++ b/internal/extract/manifests/research-repo-pack.yaml @@ -0,0 +1,109 @@ +# Shared Go + TypeScript Declarative Site Adapter: Research Repository Pack (#312) +id: research-repo-pack +name: Open Research Repositories (Zenodo, Figshare, Dryad, OSF) +category: research-health +description: "Extracts open datasets and research artifacts from Zenodo (/records HTML, direct /api/records), Figshare (API + /articles upgrade), Dryad (API + /dataset HTML), and OSF (HTML + direct api.osf.io) while honoring robots.txt disallows." +domains: + - zenodo.org + - www.zenodo.org + - api.figshare.com + - figshare.com + - www.figshare.com + - datadryad.org + - www.datadryad.org + - api.osf.io + - osf.io + - www.osf.io +auth_mode: pub +min_interval_ms: 5000 +strict_robots: true +exampleUrls: + - "https://zenodo.org/records/24485086" + - "https://api.figshare.com/v2/articles/35148283" + - "https://datadryad.org/api/v2/datasets/doi%3A10.5061%2Fdryad.7rh4625" + - "https://datadryad.org/dataset/doi:10.5061/dryad.7rh4625" + +routes: + - match: + hosts: + - zenodo.org + - www.zenodo.org + pathPrefix: /api/records/ + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: research_repo_pack_json + + - match: + hosts: + - api.figshare.com + pathPrefix: /v2/articles/ + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: research_repo_pack_json + + - match: + hosts: + - figshare.com + - www.figshare.com + pathPrefix: /articles/ + scanSegment: + scanLast: true + param: articleId + charset: digits + minLen: 4 + maxLen: 16 + twin: + fetchUrl: "https://api.figshare.com/v2/articles/{articleId}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: research_repo_pack_json + + - match: + hosts: + - datadryad.org + - www.datadryad.org + pathPrefix: /api/v2/datasets/ + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: research_repo_pack_json + + - match: + hosts: + - api.osf.io + pathPrefix: /v2/nodes/ + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: research_repo_pack_json + +htmlRoutes: + - id: research-repo-pack + match: + hosts: + - zenodo.org + - www.zenodo.org + - figshare.com + - www.figshare.com + - datadryad.org + - www.datadryad.org + - osf.io + - www.osf.io + exactSegments: false + mode: research_repo_pack_html diff --git a/internal/extract/manifests/reverb.yaml b/internal/extract/manifests/reverb.yaml new file mode 100644 index 0000000..45d080a --- /dev/null +++ b/internal/extract/manifests/reverb.yaml @@ -0,0 +1,75 @@ +# Shared Go + TypeScript Declarative Site Adapter: Reverb (#359) +id: reverb +name: Reverb Musical Instruments Marketplace +category: commerce-social +description: "Extracts Reverb musical instrument listings and catalog search results via api.reverb.com HAL+JSON endpoints with Accept-Version: 3.0." +domains: + - reverb.com + - www.reverb.com + - api.reverb.com +auth_mode: pub +min_interval_ms: 1000 +exampleUrls: + - "https://reverb.com/item/36356670-fender-stratocaster-knob-set-black" + - "https://api.reverb.com/api/listings/36356670" + - "https://api.reverb.com/api/listings?query=fender+stratocaster&per_page=2" + +routes: + - match: + hosts: + - reverb.com + - www.reverb.com + optionalLeadingLocale: true + exactSegments: true + pathSegments: + - item + - param: listingId + charset: leading_digits_slug + transform: leading_digits + minLen: 1 + maxLen: 220 + twin: + fetchUrl: "https://api.reverb.com/api/listings/{listingId}" + kind: json + accept: application/hal+json + headers: + Accept-Version: "3.0" + maxBytes: 2097152 + extract: + jsonMode: reverb_listing_json + + - match: + hosts: + - api.reverb.com + exactSegments: true + pathSegments: + - api + - listings + - param: listingId + charset: digits + minLen: 1 + maxLen: 24 + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/hal+json + headers: + Accept-Version: "3.0" + maxBytes: 2097152 + extract: + jsonMode: reverb_listing_json + + - match: + hosts: + - api.reverb.com + pathEquals: + - /api/listings + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/hal+json + headers: + Accept-Version: "3.0" + maxBytes: 2097152 + extract: + jsonMode: reverb_search_json diff --git a/internal/extract/manifests/ror.yaml b/internal/extract/manifests/ror.yaml new file mode 100644 index 0000000..b9d8372 --- /dev/null +++ b/internal/extract/manifests/ror.yaml @@ -0,0 +1,60 @@ +# Shared Go + TypeScript Declarative Site Adapter: ROR (#305) +id: ror +name: Research Organization Registry (ROR) +category: research-health +description: "Extracts Research Organization Registry (ROR) v2 organization records, domains, locations, and external IDs (GRID, ISNI, Wikidata) with Vercel challenge HTML guard." +domains: + - api.ror.org + - ror.org + - www.ror.org +auth_mode: pub +min_interval_ms: 1000 +exampleUrls: + - "https://api.ror.org/v2/organizations/03yrm5c26" + - "https://api.ror.org/v2/organizations?query=mit" + - "https://ror.org/03yrm5c26" + +routes: + - match: + hosts: + - api.ror.org + pathPrefix: /v2/organizations + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: ror_json + + - match: + hosts: + - ror.org + - www.ror.org + exactSegments: true + pathSegments: + - param: rorId + charset: alnum + reserved: + - community + - resources + - changelog + minLen: 9 + maxLen: 9 + transform: lower + twin: + fetchUrl: "https://api.ror.org/v2/organizations/{rorId}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: ror_json + +htmlRoutes: + - id: ror + match: + hosts: + - ror.org + - www.ror.org + exactSegments: false + mode: ror_html diff --git a/internal/extract/manifests/runsignup.yaml b/internal/extract/manifests/runsignup.yaml new file mode 100644 index 0000000..14f0fe5 --- /dev/null +++ b/internal/extract/manifests/runsignup.yaml @@ -0,0 +1,64 @@ +# Shared Go + TypeScript Declarative Site Adapter: RunSignup (#245) +id: runsignup +name: "RunSignup Races & Events" +category: commerce-social +description: "Extracts RunSignup race listings and single race event details from public /Rest/races and /Rest/race/{raceId} JSON APIs plus /Race/ SportsEvent HTML fallback." +domains: + - runsignup.com + - www.runsignup.com +universalEngine: false +auth_mode: pub +exampleUrls: + - "https://runsignup.com/Rest/races?format=json&events=T&page=1&results_per_page=2" + - "https://runsignup.com/Rest/race/68640?format=json" + - "https://runsignup.com/Race/MI/PortHuron/BaconandBubbles5k1Mile" + +routes: + - match: + hosts: + - runsignup.com + - www.runsignup.com + exactSegments: true + pathSegments: + - Rest + - races + twin: + fetchUrl: "{requestUrl}" + setQueryParams: + format: json + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: runsignup_json + - match: + hosts: + - runsignup.com + - www.runsignup.com + exactSegments: true + pathSegments: + - Rest + - race + - param: raceId + charset: digits + minLen: 1 + maxLen: 16 + twin: + fetchUrl: "{requestUrl}" + setQueryParams: + format: json + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: runsignup_json + +htmlRoutes: + - id: runsignup + match: + hosts: + - runsignup.com + - www.runsignup.com + pathPrefix: /Race/ + exactSegments: false + mode: runsignup_html diff --git a/internal/extract/manifests/sap-rmk-jibe.yaml b/internal/extract/manifests/sap-rmk-jibe.yaml index 78a50c9..bbdae9b 100644 --- a/internal/extract/manifests/sap-rmk-jibe.yaml +++ b/internal/extract/manifests/sap-rmk-jibe.yaml @@ -20,6 +20,10 @@ routes: - "jobs.dover.com" - "app.dover.com" - "*.dover.com" + - "jobs.mchire.com" + - "jobs.crelate.com" + - "jobs.manatal.com" + - "jobs.chronicle.com" twin: id: jibe-careers fetchUrl: "{requestUrl}" @@ -142,6 +146,10 @@ routes: - "jobs.dover.com" - "app.dover.com" - "*.dover.com" + - "jobs.mchire.com" + - "jobs.crelate.com" + - "jobs.manatal.com" + - "jobs.chronicle.com" twin: id: sap-rmk-jibe fetchUrl: "{requestUrl}" @@ -190,6 +198,10 @@ htmlRoutes: - "jobs.dover.com" - "app.dover.com" - "*.dover.com" + - "jobs.mchire.com" + - "jobs.crelate.com" + - "jobs.manatal.com" + - "jobs.chronicle.com" xml: mode: items_table requireAnyTags: diff --git a/internal/extract/manifests/sba-dsbs-loans.yaml b/internal/extract/manifests/sba-dsbs-loans.yaml new file mode 100644 index 0000000..ec7dfb6 --- /dev/null +++ b/internal/extract/manifests/sba-dsbs-loans.yaml @@ -0,0 +1,45 @@ +# Shared Go + TypeScript Declarative Site Adapter: SBA DSBS & 7(a)/504 Loans (#300) +id: sba-dsbs-loans +name: "SBA DSBS & 7(a)/504 Loan Datasets (DKAN)" +category: finance +description: "Extracts data.sba.gov DKAN 7(a)/504 loan datasets and dataset pages while rejecting empty React SPA shells on search.certifications.sba.gov." +domains: + - data.sba.gov + - search.certifications.sba.gov + - dsbs.sba.gov +auth_mode: pub +min_interval_ms: 1000 +exampleUrls: + - "https://data.sba.gov/api/1/metastore/schemas/dataset/items/SBA-OCA-CKAN-002" + - "https://data.sba.gov/dataset/sba-foia-quarterly-reports" + +routes: + - match: + hosts: + - data.sba.gov + pathPrefix: /api/1/metastore/ + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: sba_dkan_json + + - match: + hosts: + - data.sba.gov + pathPrefix: /api/1/datastore/query/ + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: sba_dkan_json + +htmlRoutes: + - id: sba-dsbs-loans + match: + exactSegments: false + mode: sba_dsbs_loans_html diff --git a/internal/extract/manifests/schema-course.yaml b/internal/extract/manifests/schema-course.yaml new file mode 100644 index 0000000..6b959f4 --- /dev/null +++ b/internal/extract/manifests/schema-course.yaml @@ -0,0 +1,18 @@ +# Shared Go + TypeScript Declarative Site Adapter: Universal Schema.org Course (#225) +id: schema-course +name: "Schema.org Course & Educational Program" +category: public-records +description: "Universal Schema.org extractor for Course, CourseInstance, and EducationalOccupationalProgram JSON-LD running before generic schema_org fallback." +domains: + - pll.harvard.edu +universalEngine: true +auth_mode: html +strict_robots: true +exampleUrls: + - "https://pll.harvard.edu/course/cs50-introduction-computer-science" + +htmlRoutes: + - id: schema-course + match: + exactSegments: false + mode: schema_course_html diff --git a/internal/extract/manifests/schema-dataset.yaml b/internal/extract/manifests/schema-dataset.yaml new file mode 100644 index 0000000..2fa8a60 --- /dev/null +++ b/internal/extract/manifests/schema-dataset.yaml @@ -0,0 +1,18 @@ +# Shared Go + TypeScript Declarative Site Adapter: Universal Schema.org Dataset (#239) +id: schema-dataset +name: "Schema.org Dataset & DataCatalog" +category: research-health +description: "Universal Schema.org extractor for Dataset and DataCatalog JSON-LD including DataDownload distributions, license, creator, and temporal/spatial coverage." +domains: + - registry.opendata.aws +universalEngine: true +auth_mode: html +strict_robots: true +exampleUrls: + - "https://registry.opendata.aws/noaa-goes/" + +htmlRoutes: + - id: schema-dataset + match: + exactSegments: false + mode: schema_dataset_html diff --git a/internal/extract/manifests/schema-event.yaml b/internal/extract/manifests/schema-event.yaml index 33ecacd..53af8e9 100644 --- a/internal/extract/manifests/schema-event.yaml +++ b/internal/extract/manifests/schema-event.yaml @@ -2,16 +2,33 @@ id: schema-event name: Schema.org Event (Universal) category: commerce-social -description: "Universal Schema.org Event JSON-LD extractor for venues, parks departments, clubs, and event calendars: name, start/end, venue and address, organizer, performer, offers/price, status, and attendance mode. Lists every Event on series and calendar pages." +description: "Universal Schema.org Event JSON-LD extractor for venues, parks departments, clubs, and event calendars: name, start/end, venue and address, organizer, performer, offers/price, status, and attendance mode. Lists every Event on series and calendar pages while yielding on dedicated ticketing/race platforms." domains: - neworleanscitypark.org + - events.stanford.edu + - calendar.mit.edu universalEngine: true auth_mode: html +strict_robots: true exampleUrls: - "https://neworleanscitypark.org/series/crescent-city-farmers-market-2/" + - "https://events.stanford.edu/" htmlRoutes: - id: schema-event match: exactSegments: false + excludeHosts: + - eventbrite.com + - www.eventbrite.com + - meetup.com + - www.meetup.com + - lu.ma + - www.lu.ma + - luma.com + - www.luma.com + - ticketmaster.com + - www.ticketmaster.com + - runsignup.com + - www.runsignup.com mode: schema_event_html diff --git a/internal/extract/manifests/schema-faq-howto.yaml b/internal/extract/manifests/schema-faq-howto.yaml new file mode 100644 index 0000000..afdf20d --- /dev/null +++ b/internal/extract/manifests/schema-faq-howto.yaml @@ -0,0 +1,20 @@ +# Shared Go + TypeScript Declarative Site Adapter: Universal Schema.org FAQPage & HowTo (#238) +id: schema-faq-howto +name: "Schema.org FAQPage & HowTo" +category: public-records +description: "Universal Schema.org extractor for FAQPage Q&A and HowTo step-by-step instructions, yielding when Recipe, Product, JobPosting, Course, SoftwareApplication, or Medical types are present." +domains: + - yoast.com + - www.wikihow.com +universalEngine: true +auth_mode: html +strict_robots: true +exampleUrls: + - "https://yoast.com/features/structured-data/faq-block/" + - "https://www.wikihow.com/Tie-a-Tie" + +htmlRoutes: + - id: schema-faq-howto + match: + exactSegments: false + mode: schema_faq_howto_html diff --git a/internal/extract/manifests/schema-localbusiness.yaml b/internal/extract/manifests/schema-localbusiness.yaml index 481c470..2be4283 100644 --- a/internal/extract/manifests/schema-localbusiness.yaml +++ b/internal/extract/manifests/schema-localbusiness.yaml @@ -2,13 +2,16 @@ id: schema-localbusiness name: Schema.org LocalBusiness (Universal) category: commerce-social -description: "Universal Schema.org LocalBusiness JSON-LD extractor (Restaurant, Store, AutoDealer, BikeStore and every *Business/*Store subtype) for location, dealer, and shop pages: name, address, phone, geo, opening hours, price range, rating, and amenities. Skips pages whose main entity is an article, product, recipe, job, or event." +description: "Universal Schema.org LocalBusiness JSON-LD extractor (Restaurant, Store, AutoDealer, BikeStore and every *Business/*Store subtype) for location, dealer, and shop pages: name, address, phone, geo, opening hours, price range, rating, and amenities. Skips pages whose main entity is an article, product, recipe, job, vehicle, medical, or event." domains: - www.chipotle.com + - www.apple.com universalEngine: true auth_mode: html +strict_robots: true exampleUrls: - "https://locations.chipotle.com/co/boulder/1650-28th-st" + - "https://www.apple.com/retail/fifthavenue/" htmlRoutes: - id: schema-localbusiness diff --git a/internal/extract/manifests/schema-medical.yaml b/internal/extract/manifests/schema-medical.yaml new file mode 100644 index 0000000..8ac4f84 --- /dev/null +++ b/internal/extract/manifests/schema-medical.yaml @@ -0,0 +1,20 @@ +# Shared Go + TypeScript Declarative Site Adapter: Universal Schema.org Medical (#241) +id: schema-medical +name: "Schema.org Medical Entities" +category: research-health +description: "Universal Schema.org extractor for MedicalCondition, Drug, Physician, MedicalClinic, and MedicalWebPage JSON-LD, yielding when Product is present." +domains: + - my.clevelandclinic.org + - www.nhs.uk +universalEngine: true +auth_mode: html +strict_robots: true +exampleUrls: + - "https://my.clevelandclinic.org/health/diseases/6424-asthma" + - "https://www.nhs.uk/conditions/asthma/" + +htmlRoutes: + - id: schema-medical + match: + exactSegments: false + mode: schema_medical_html diff --git a/internal/extract/manifests/schema-menu.yaml b/internal/extract/manifests/schema-menu.yaml new file mode 100644 index 0000000..941192c --- /dev/null +++ b/internal/extract/manifests/schema-menu.yaml @@ -0,0 +1,19 @@ +# Shared Go + TypeScript Declarative Site Adapter: Schema.org Menu (#258) +id: schema-menu +name: "Schema.org Restaurant Menu (Menu / MenuSection / MenuItem)" +category: commerce-social +description: "Universal Schema.org Menu extractor that matches only when Menu, MenuSection, MenuItem, or hasMenu JSON-LD entities exist, never hijacking plain Restaurant pages." +domains: + - www.chilis.com +universalEngine: true +auth_mode: html +strict_robots: true +min_interval_ms: 1000 +exampleUrls: + - "https://www.chilis.com/menu" + +htmlRoutes: + - id: schema-menu + match: + exactSegments: false + mode: schema_menu_html diff --git a/internal/extract/manifests/schema-recipe.yaml b/internal/extract/manifests/schema-recipe.yaml index 2c99bc0..2290d49 100644 --- a/internal/extract/manifests/schema-recipe.yaml +++ b/internal/extract/manifests/schema-recipe.yaml @@ -5,10 +5,13 @@ category: commerce-social description: "Universal Schema.org Recipe JSON-LD extractor for any recipe site: ingredients, numbered steps (HowToStep/HowToSection), prep/cook/total times, yield, cuisine, rating, and nutrition. Resolves @graph @id author references." domains: - www.budgetbytes.com + - sallysbakingaddiction.com universalEngine: true auth_mode: html +strict_robots: true exampleUrls: - "https://www.budgetbytes.com/one-pot-creamy-cajun-chicken-pasta/" + - "https://sallysbakingaddiction.com/chewy-chocolate-chip-cookies/" htmlRoutes: - id: schema-recipe diff --git a/internal/extract/manifests/schema-software-app.yaml b/internal/extract/manifests/schema-software-app.yaml new file mode 100644 index 0000000..9b6f158 --- /dev/null +++ b/internal/extract/manifests/schema-software-app.yaml @@ -0,0 +1,20 @@ +# Shared Go + TypeScript Declarative Site Adapter: Universal Schema.org SoftwareApplication (#240) +id: schema-software-app +name: "Schema.org SoftwareApplication" +category: developer +description: "Universal Schema.org extractor for SoftwareApplication, WebApplication, and MobileApplication JSON-LD (version, OS, category, offers, rating, and downloadUrl)." +domains: + - code.visualstudio.com + - www.mozilla.org +universalEngine: true +auth_mode: html +strict_robots: true +exampleUrls: + - "https://code.visualstudio.com/" + - "https://www.mozilla.org/en-US/firefox/new/" + +htmlRoutes: + - id: schema-software-app + match: + exactSegments: false + mode: schema_software_app_html diff --git a/internal/extract/manifests/schema-vehicle.yaml b/internal/extract/manifests/schema-vehicle.yaml new file mode 100644 index 0000000..83a9f83 --- /dev/null +++ b/internal/extract/manifests/schema-vehicle.yaml @@ -0,0 +1,18 @@ +# Shared Go + TypeScript Declarative Site Adapter: Universal Schema.org Vehicle (#237) +id: schema-vehicle +name: "Schema.org Vehicle & Car" +category: commerce-social +description: "Universal Schema.org extractor for Vehicle, Car, Motorcycle, and MotorizedBicycle JSON-LD with strict 17-character VIN validation (excluding I, O, Q)." +domains: + - www.hondaofseattle.com +universalEngine: true +auth_mode: html +strict_robots: true +exampleUrls: + - "https://www.hondaofseattle.com/viewdetails/used/5tdkdrbh0rs544979/2024-toyota-highlander-sport-utility" + +htmlRoutes: + - id: schema-vehicle + match: + exactSegments: false + mode: schema_vehicle_html diff --git a/internal/extract/manifests/sec-xbrl-frames.yaml b/internal/extract/manifests/sec-xbrl-frames.yaml new file mode 100644 index 0000000..d59a43f --- /dev/null +++ b/internal/extract/manifests/sec-xbrl-frames.yaml @@ -0,0 +1,31 @@ +# Shared Go + TypeScript Declarative Site Adapter: SEC EDGAR XBRL Frames & Company Facts (#390) +id: sec-xbrl-frames +name: "SEC EDGAR XBRL Frames & Company Facts" +category: finance +description: "Extracts data.sec.gov XBRL frames, companyconcept, and bounded companyfacts JSON feeds via universalEngine to avoid duplicating sec-edgar.yaml domain claims." +domains: + - efts.sec.gov +universalEngine: true +auth_mode: pub +user_agent_profile: sec-edgar +min_interval_ms: 200 +exampleUrls: + - "https://data.sec.gov/api/xbrl/frames/us-gaap/AccountsPayableCurrent/USD/CY2023Q4I.json" + - "https://data.sec.gov/api/xbrl/companyconcept/CIK0000320193/us-gaap/AccountsPayableCurrent.json" + - "https://data.sec.gov/api/xbrl/companyfacts/CIK0000320193.json" + +routes: + - match: + hosts: + - data.sec.gov + anyOf: + - pathPrefix: /api/xbrl/frames/ + - pathPrefix: /api/xbrl/companyconcept/ + - pathPrefix: /api/xbrl/companyfacts/ + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 4194304 + extract: + jsonMode: sec_xbrl_frames_json diff --git a/internal/extract/manifests/security-txt.yaml b/internal/extract/manifests/security-txt.yaml new file mode 100644 index 0000000..852aeaa --- /dev/null +++ b/internal/extract/manifests/security-txt.yaml @@ -0,0 +1,26 @@ +# Shared Go + TypeScript Declarative Site Adapter: RFC 9116 security.txt (#322) +id: security-txt +name: RFC 9116 security.txt Vulnerability Disclosure +category: developer +description: "Universal RFC 9116 /.well-known/security.txt and /security.txt parser extracting Contact, Expires, Encryption, Policy, Canonical, Acknowledgments, and CSAF directives with strict Contact validation." +domains: + - www.cloudflare.com +universalEngine: true +auth_mode: pub +exampleUrls: + - "https://www.cloudflare.com/.well-known/security.txt" + - "https://github.com/.well-known/security.txt" + +routes: + - match: + exactSegments: true + pathEquals: + - /.well-known/security.txt + - /security.txt + twin: + fetchUrl: "{requestUrl}" + kind: text + accept: text/plain + maxBytes: 262144 + extract: + textMode: security_txt_text diff --git a/internal/extract/manifests/semantic-scholar.yaml b/internal/extract/manifests/semantic-scholar.yaml new file mode 100644 index 0000000..6bc01c3 --- /dev/null +++ b/internal/extract/manifests/semantic-scholar.yaml @@ -0,0 +1,98 @@ +# Shared Go + TypeScript Declarative Site Adapter: Semantic Scholar (#301) +id: semantic-scholar +name: Semantic Scholar Academic Graph +category: research-health +description: "Extracts scholarly papers, citation counts, authors, open-access PDFs, and author profiles via api.semanticscholar.org Graph API (keyless + optional SEMANTIC_SCHOLAR_API_KEY) with HTML metadata fallback and AWS WAF shell guard." +domains: + - api.semanticscholar.org + - www.semanticscholar.org + - semanticscholar.org +auth_mode: pub +min_interval_ms: 1000 +exampleUrls: + - "https://api.semanticscholar.org/graph/v1/paper/DOI:10.1038/s41586-021-03819-2?fields=paperId,title,year,authors,abstract,citationCount,openAccessPdf,externalIds" + - "https://www.semanticscholar.org/paper/Attention-is-All-you-Need-Vaswani-Shazeer/204e3073870fae3d05bcbc2f6a8e263d9b72e776" + +routes: + - match: + hosts: + - api.semanticscholar.org + pathPrefix: /graph/v1/ + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: semantic_scholar_json + + - match: + hosts: + - www.semanticscholar.org + - semanticscholar.org + anyOf: + - exactSegments: true + pathSegments: + - paper + - param: slug + charset: url_seg + minLen: 1 + maxLen: 200 + - param: paperId + charset: alnum + minLen: 40 + maxLen: 40 + - exactSegments: true + pathSegments: + - paper + - param: paperId + charset: alnum + minLen: 40 + maxLen: 40 + twin: + fetchUrl: "https://api.semanticscholar.org/graph/v1/paper/{paperId}?fields=paperId,title,year,venue,publicationVenue,authors,abstract,citationCount,referenceCount,influentialCitationCount,openAccessPdf,externalIds,publicationDate,url" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: semantic_scholar_json + + - match: + hosts: + - www.semanticscholar.org + - semanticscholar.org + anyOf: + - exactSegments: true + pathSegments: + - author + - param: slug + charset: url_seg + minLen: 1 + maxLen: 200 + - param: authorId + charset: digits + minLen: 3 + maxLen: 20 + - exactSegments: true + pathSegments: + - author + - param: authorId + charset: digits + minLen: 3 + maxLen: 20 + twin: + fetchUrl: "https://api.semanticscholar.org/graph/v1/author/{authorId}?fields=authorId,name,affiliations,homepage,paperCount,citationCount,hIndex,url" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: semantic_scholar_json + +htmlRoutes: + - id: semantic-scholar + match: + hosts: + - www.semanticscholar.org + - semanticscholar.org + exactSegments: false + mode: semantic_scholar_html diff --git a/internal/extract/manifests/setlist-lastfm.yaml b/internal/extract/manifests/setlist-lastfm.yaml new file mode 100644 index 0000000..b08bfb9 --- /dev/null +++ b/internal/extract/manifests/setlist-lastfm.yaml @@ -0,0 +1,58 @@ +# Shared Go + TypeScript Declarative Site Adapter: Setlist.fm & Last.fm (#382) +id: setlist-lastfm +name: Setlist.fm & Last.fm Music Metadata +category: commerce-social +description: "Official keyed Setlist.fm REST 1.0 (SETLISTFM_API_KEY) and Last.fm Audioscrobbler 2.0 (LASTFM_API_KEY) adapters plus Setlist.fm / Last.fm SSR HTML extraction with Fastly challenge rejection." +domains: + - api.setlist.fm + - www.setlist.fm + - setlist.fm + - ws.audioscrobbler.com + - www.last.fm + - last.fm +auth_mode: key +min_interval_ms: 1000 +exampleUrls: + - "https://www.setlist.fm/setlist/motionless-in-white/2023/mobile-civic-center-mobile-al-3ba45068.html" + - "https://api.setlist.fm/rest/1.0/setlist/3ba45068" + - "https://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=Cher&format=json" + +routes: + - match: + hosts: + - api.setlist.fm + pathPrefix: /rest/1.0/ + exactSegments: false + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + auth_mode: key + maxBytes: 2097152 + extract: + jsonMode: setlist_fm_json + + - match: + hosts: + - ws.audioscrobbler.com + pathPrefix: /2.0 + exactSegments: false + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + auth_mode: key + maxBytes: 2097152 + extract: + jsonMode: lastfm_json + +htmlRoutes: + - id: setlist-lastfm + match: + hosts: + - www.setlist.fm + - setlist.fm + - www.last.fm + - last.fm + exactSegments: false + mode: setlist_lastfm_html diff --git a/internal/extract/manifests/sheldon-brown.yaml b/internal/extract/manifests/sheldon-brown.yaml new file mode 100644 index 0000000..0b35d5f --- /dev/null +++ b/internal/extract/manifests/sheldon-brown.yaml @@ -0,0 +1,19 @@ +# Shared Go + TypeScript Declarative Site Adapter: Sheldon Brown Technical Reference (#355) +id: sheldon-brown +name: "Sheldon Brown Bicycle Technical Reference" +category: research-health +description: "Extracts bicycle technical reference articles, gear/ISO tire crib tables, and glossary definitions from sheldonbrown.com." +domains: + - sheldonbrown.com + - www.sheldonbrown.com +auth_mode: html +min_interval_ms: 1000 +exampleUrls: + - "https://www.sheldonbrown.com/gear-calc.html" + - "https://www.sheldonbrown.com/gloss_e-f.html" + +htmlRoutes: + - id: sheldon-brown + match: + exactSegments: false + mode: sheldon_brown_html diff --git a/internal/extract/manifests/shopify-filter-apps.yaml b/internal/extract/manifests/shopify-filter-apps.yaml new file mode 100644 index 0000000..a3acebc --- /dev/null +++ b/internal/extract/manifests/shopify-filter-apps.yaml @@ -0,0 +1,40 @@ +# Shared Go + TypeScript Declarative Site Adapter: Shopify Filter Apps (#265) +id: shopify-filter-apps +name: "Shopify Filter Apps (Boost Commerce / Globo)" +category: commerce-social +description: "Page-key adapter for Boost Commerce (mybcapps.com) and Globo Smart Product Filter JSON endpoints; companion HTML mode yields so shopify_html is never preempted." +domains: + - services.mybcapps.com + - filter.globo.io +universalEngine: true +auth_mode: page-key +requires_page_key_opt_in: true +exampleUrls: + - "https://services.mybcapps.com/bc-sf-filter/filter?shop=get-casely.myshopify.com&page=1&limit=5" + +routes: + - match: + anyOf: + - hosts: + - services.mybcapps.com + pathEquals: + - /bc-sf-filter/filter + - /bc-sf-filter/search + - hosts: + - filter.globo.io + pathPrefix: /api/ + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 2097152 + requires_page_key_opt_in: true + auth_mode: page-key + extract: + jsonMode: shopify_filter_apps_json + +htmlRoutes: + - id: shopify-filter-apps + match: + exactSegments: false + mode: shopify_filter_apps_html diff --git a/internal/extract/manifests/shopify-hydrogen.yaml b/internal/extract/manifests/shopify-hydrogen.yaml new file mode 100644 index 0000000..385f805 --- /dev/null +++ b/internal/extract/manifests/shopify-hydrogen.yaml @@ -0,0 +1,18 @@ +# Shared Go + TypeScript Declarative Site Adapter: Shopify Hydrogen (#263) +id: shopify-hydrogen +name: "Shopify Hydrogen Storefronts" +category: commerce-social +description: "Page-key adapter extracting Shopify Hydrogen SSR __remixContext loaderData (shop, products, collections) while rejecting non-Shopify Remix apps and empty shells." +domains: + - hydrogen.shop +universalEngine: true +auth_mode: page-key +requires_page_key_opt_in: true +exampleUrls: + - "https://hydrogen.shop/" + +htmlRoutes: + - id: shopify-hydrogen + match: + exactSegments: false + mode: shopify_hydrogen_html diff --git a/internal/extract/manifests/shopify-storefront-graphql.yaml b/internal/extract/manifests/shopify-storefront-graphql.yaml index 0e3462f..1013143 100644 --- a/internal/extract/manifests/shopify-storefront-graphql.yaml +++ b/internal/extract/manifests/shopify-storefront-graphql.yaml @@ -2,9 +2,10 @@ id: shopify-storefront-graphql name: Shopify Storefront API (Tokenless GraphQL) category: commerce-social -description: "Queries any Shopify store's public Storefront API (/api//graphql.json) with Shopify's documented tokenless access for one product by handle: shop name, vendor, type, price range, options, every variant (SKU, price, compare-at price, availability), and collections. No access token is read from the page or sent." +description: "Queries any Shopify store's public Storefront API (/api//graphql.json) with Shopify's documented tokenless access for one product by handle (plus same-origin page-key companion discovery on storefronts embedding Storefront API tokens): shop name, vendor, type, price range, options, every variant (SKU, price, compare-at price, availability), and collections." domains: - www.tentree.com + - www.henryrose.com universalEngine: true auth_mode: pub min_interval_ms: 1000 diff --git a/internal/extract/manifests/shopify.yaml b/internal/extract/manifests/shopify.yaml index 277cc4e..3ec5426 100644 --- a/internal/extract/manifests/shopify.yaml +++ b/internal/extract/manifests/shopify.yaml @@ -33,6 +33,8 @@ routes: - help.bigcartel.com - developers.bigcartel.com - blog.bigcartel.com + - upway.co + - www.upway.co anyOf: - pathEquals: - /products.json @@ -53,6 +55,9 @@ routes: # 2. Explicit /products/.js Ajax endpoint on any domain - match: + excludeHosts: + - upway.co + - www.upway.co pathSuffix: .js scanSegment: afterLiteral: products @@ -70,6 +75,9 @@ routes: # 3. Explicit /products/.json on any domain OR /products/ on *.myshopify.com - match: + excludeHosts: + - upway.co + - www.upway.co anyOf: - pathSuffix: .json scanSegment: diff --git a/internal/extract/manifests/smb-ats-full.yaml b/internal/extract/manifests/smb-ats-full.yaml new file mode 100644 index 0000000..ac58d9f --- /dev/null +++ b/internal/extract/manifests/smb-ats-full.yaml @@ -0,0 +1,92 @@ +# Shared Go + TypeScript Declarative Site Adapter: SMB ATS Full (#231) +id: smb-ats-full +name: "SMB ATS Full (Manatal, Homerun, Zoho Recruit, Freshteam)" +category: jobs +description: "Extracts open roles from Manatal career-page JSON API, Homerun JobPosting JSON-LD, Zoho Recruit, and Freshteam portals while rejecting 404.homerun.co and soft errors." +domains: + - api.manatal.com + - core.api.manatal.com + - jobs.manatal.com + - "*.zohorecruit.com" + - "*.freshteam.com" + - "*.homerun.co" +auth_mode: pub +exampleUrls: + - "https://api.manatal.com/open/v3/career-page/manatal/jobs/" + - "https://jobs.homerun.co/sales-executive-amsterdam" + +routes: + # 1. Manatal public career-page JSON API (api.manatal.com / core.api.manatal.com) + - match: + hosts: + - api.manatal.com + - core.api.manatal.com + pathPrefix: /open/v3/career-page/ + exactSegments: false + twin: + id: smb-ats-full + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 4194304 + extract: + jsonMode: manatal_jobs_json + + # 2. Manatal hosted career board (jobs.manatal.com/ -> api.manatal.com/open/v3/career-page//jobs/) + - match: + hosts: + - jobs.manatal.com + exactSegments: true + pathSegments: + - param: slug + charset: slug + reserved: + - api + - login + - auth + - static + - assets + - robots.txt + - sitemap.xml + - favicon.ico + minLen: 1 + maxLen: 120 + twin: + id: smb-ats-full-manatal + fetchUrl: "https://api.manatal.com/open/v3/career-page/{slug}/jobs/" + kind: json + accept: application/json + maxBytes: 4194304 + extract: + jsonMode: manatal_jobs_json + + # 3. Freshteam & Zoho Recruit JSON endpoints + - match: + anyOf: + - hosts: + - "*.freshteam.com" + pathPrefix: /api/job_postings + exactSegments: false + - hosts: + - "*.zohorecruit.com" + pathPrefix: /recruit/v2/ + exactSegments: false + twin: + id: smb-ats-full-json + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 4194304 + extract: + jsonMode: smb_ats_json + +htmlRoutes: + - id: smb-ats-full + mode: smb_ats_full_html + match: + hosts: + - "*.homerun.co" + - "*.zohorecruit.com" + - "*.freshteam.com" + - jobs.manatal.com + exactSegments: false diff --git a/internal/extract/manifests/sourceforge-launchpad.yaml b/internal/extract/manifests/sourceforge-launchpad.yaml new file mode 100644 index 0000000..155d418 --- /dev/null +++ b/internal/extract/manifests/sourceforge-launchpad.yaml @@ -0,0 +1,65 @@ +# Shared Go + TypeScript Declarative Site Adapter: SourceForge & Launchpad (#328) +id: sourceforge-launchpad +name: SourceForge & Launchpad +category: developer +description: "Extracts open-source project metadata, categories, licenses, and release details from SourceForge REST API/HTML and Launchpad 1.0 REST API/SSR pages." +domains: + - sourceforge.net + - api.launchpad.net + - launchpad.net +auth_mode: pub +exampleUrls: + - "https://sourceforge.net/rest/p/sevenzip" + - "https://sourceforge.net/projects/sevenzip/" + - "https://api.launchpad.net/1.0/ubuntu" + - "https://launchpad.net/ubuntu" + +routes: + - match: + hosts: + - sourceforge.net + pathPrefix: /rest/p/ + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 1048576 + extract: + jsonMode: sourceforge_json + + - match: + hosts: + - sourceforge.net + exactSegments: true + pathSegments: + - projects + - param: proj + charset: pkg + twin: + fetchUrl: "https://sourceforge.net/rest/p/{proj}" + kind: json + accept: application/json + maxBytes: 1048576 + extract: + jsonMode: sourceforge_json + + - match: + hosts: + - api.launchpad.net + pathPrefix: /1.0/ + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 1048576 + extract: + jsonMode: launchpad_json + +htmlRoutes: + - id: sourceforge-launchpad + match: + hosts: + - sourceforge.net + - launchpad.net + exactSegments: false + mode: sourceforge_launchpad_html diff --git a/internal/extract/manifests/specialized-turbo-support.yaml b/internal/extract/manifests/specialized-turbo-support.yaml new file mode 100644 index 0000000..113a1bd --- /dev/null +++ b/internal/extract/manifests/specialized-turbo-support.yaml @@ -0,0 +1,18 @@ +# Shared Go + TypeScript Declarative Site Adapter: Specialized Turbo Support (#345) +id: specialized-turbo-support +name: Specialized Turbo E-Bike Support +category: developer +description: "Extracts rendered Turbo e-bike support and diagnostic KB articles on support.specialized.com while strictly rejecting unhydrated eGain JS launcher shells and 403 gateway responses." +domains: + - support.specialized.com +auth_mode: html +min_interval_ms: 2000 +strict_robots: true +exampleUrls: + - "https://support.specialized.com/kb/sp_en-us/home" + +htmlRoutes: + - id: specialized-turbo-support + match: + exactSegments: false + mode: specialized_turbo_support_html diff --git a/internal/extract/manifests/spotify-web-api.yaml b/internal/extract/manifests/spotify-web-api.yaml new file mode 100644 index 0000000..4764be3 --- /dev/null +++ b/internal/extract/manifests/spotify-web-api.yaml @@ -0,0 +1,51 @@ +# Shared Go + TypeScript Declarative Site Adapter: Spotify Web API & Open oEmbed (#381) +id: spotify-web-api +name: Spotify Web API & Open oEmbed +category: commerce-social +description: "Official keyed Spotify Web API v1 adapter (SPOTIFY_ACCESS_TOKEN) plus public open.spotify.com oEmbed JSON and JSON-LD / OpenGraph / music:* HTML extraction." +domains: + - api.spotify.com + - open.spotify.com +auth_mode: key +min_interval_ms: 1000 +exampleUrls: + - "https://open.spotify.com/oembed?url=https://open.spotify.com/show/4rOoJ6Egrf8K2IrywzwOMk" + - "https://open.spotify.com/track/4cOdK2wGLETKBW3PvgPWqT" + - "https://api.spotify.com/v1/shows/4rOoJ6Egrf8K2IrywzwOMk" + +routes: + - match: + hosts: + - api.spotify.com + pathPrefix: /v1/ + exactSegments: false + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + auth_mode: key + maxBytes: 2097152 + extract: + jsonMode: spotify_api_json + + - match: + hosts: + - open.spotify.com + pathEquals: + - /oembed + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + auth_mode: pub + maxBytes: 524288 + extract: + jsonMode: spotify_oembed_json + +htmlRoutes: + - id: spotify-web-api + match: + hosts: + - open.spotify.com + exactSegments: false + mode: spotify_html diff --git a/internal/extract/manifests/square-toast-menu.yaml b/internal/extract/manifests/square-toast-menu.yaml new file mode 100644 index 0000000..8080c7b --- /dev/null +++ b/internal/extract/manifests/square-toast-menu.yaml @@ -0,0 +1,23 @@ +# Shared Go + TypeScript Declarative Site Adapter: Square Online Restaurant & Toast Menus (#257) +# NOTE: Deliberately claims order.toasttab.com (never toasttab.com / www.toasttab.com / *.toasttab.com) +# and runs universally via universalEngine: true for *.square.site restaurant verticals (square.site is a private PSL suffix). +id: square-toast-menu +name: "Square Online Restaurant & Toast Online Ordering Menus" +category: commerce-social +description: "Extracts Square Online restaurant __BOOTSTRAP_STATE__ menus and Toast order.toasttab.com online ordering menus while rejecting Cloudflare challenges and empty shells." +domains: + - order.toasttab.com +universalEngine: true +auth_mode: html +strict_robots: true +min_interval_ms: 2000 +max_concurrent: 1 +exampleUrls: + - "https://rinconmx-restaurant.square.site/shop/online-menu/LL5C6YEQHRVCYJVZRVRVY4WR" + - "https://rinconmx-restaurant.square.site/" + +htmlRoutes: + - id: square-toast-menu + match: + exactSegments: false + mode: square_toast_menu_html diff --git a/internal/extract/manifests/ssrn-nber.yaml b/internal/extract/manifests/ssrn-nber.yaml new file mode 100644 index 0000000..9b64cb8 --- /dev/null +++ b/internal/extract/manifests/ssrn-nber.yaml @@ -0,0 +1,24 @@ +# Shared Go + TypeScript Declarative Site Adapter: NBER & SSRN (#314) +id: ssrn-nber +name: NBER Working Papers & SSRN +category: research-health +description: "Extracts NBER working paper bibliographic metadata and abstracts (citation_* metas + DOM) and SSRN abstract metadata with strict Cloudflare challenge rejection." +domains: + - www.nber.org + - nber.org + - papers.ssrn.com +auth_mode: html +min_interval_ms: 1000 +exampleUrls: + - "https://www.nber.org/papers/w30000" + - "https://papers.ssrn.com/sol3/papers.cfm?abstract_id=4131630" + +htmlRoutes: + - id: ssrn-nber + match: + hosts: + - www.nber.org + - nber.org + - papers.ssrn.com + exactSegments: false + mode: ssrn_nber_html diff --git a/internal/extract/manifests/staffing-ats-pack.yaml b/internal/extract/manifests/staffing-ats-pack.yaml new file mode 100644 index 0000000..341a8e5 --- /dev/null +++ b/internal/extract/manifests/staffing-ats-pack.yaml @@ -0,0 +1,101 @@ +# Shared Go + TypeScript Declarative Site Adapter: Staffing ATS Pack (#230) +id: staffing-ats-pack +name: "Staffing ATS Pack (Crelate, JobDiva, Ceipal)" +category: jobs +description: "Extracts public staffing job boards and postings from Crelate, JobDiva, and Ceipal while rejecting disabled portals (Organization Portal Disabled) and error shells." +domains: + - jobs.crelate.com + - app.crelate.com + - "*.jobdiva.com" + - "*.ceipal.com" +universalEngine: true +auth_mode: pub +exampleUrls: + - "https://jobs.crelate.com/portal/promotive/rss" + +routes: + # 1. Crelate RSS feed (/portal//rss) + - match: + hosts: + - jobs.crelate.com + - app.crelate.com + pathPrefix: /portal/ + pathSuffix: /rss + exactSegments: false + twin: + id: staffing-ats-pack-crelate-rss + fetchUrl: "{requestUrl}" + kind: text + accept: application/rss+xml + extract: + xml: + mode: items_table + requireAnyTags: + - rss + - channel + itemTag: item + titleTemplate: "Crelate Staffing Jobs ({itemCount})" + emptyText: "No open positions currently listed." + limit: 50 + requireItemVar: jTitle + collectLinkVar: jLink + emitTotals: true + itemVars: + jTitle: + tags: [title] + jLink: + tags: [link] + loc: + tags: [location] + default: "-" + pubDate: + tags: [pubDate] + sliceMax: 16 + default: "-" + recordFields: + title: "{jTitle}" + url: "{jLink}" + location: "{loc}" + postedAt: "{pubDate}" + source: crelate + columns: + - header: Role + template: "[{jTitle}]({jLink})" + - header: Location + template: "{loc}" + - header: Published + template: "{pubDate}" + + # 2. Crelate / Ceipal / JobDiva JSON API endpoints + - match: + anyOf: + - hosts: + - jobs.crelate.com + - app.crelate.com + pathPrefix: /api/ + exactSegments: false + - hosts: + - "*.ceipal.com" + anyOf: + - pathPrefix: /jobs/api/ + exactSegments: false + - pathPrefix: /api/ + exactSegments: false + - hosts: + - "*.jobdiva.com" + pathPrefix: /portal/api/ + exactSegments: false + twin: + id: staffing-ats-pack + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 4194304 + extract: + jsonMode: staffing_ats_json + +htmlRoutes: + - id: staffing-ats-pack + mode: staffing_ats_pack_html + match: + exactSegments: false diff --git a/internal/extract/manifests/steam-store.yaml b/internal/extract/manifests/steam-store.yaml new file mode 100644 index 0000000..fe7f7d5 --- /dev/null +++ b/internal/extract/manifests/steam-store.yaml @@ -0,0 +1,87 @@ +# Shared Go + TypeScript Declarative Site Adapter: Steam Store & App News (#383) +id: steam-store +name: Steam Store & App News +category: commerce-social +description: "Public Steam Store appdetails, appreviews (with HTML homepage redirect rejection), ISteamNews GetNewsForApp v2 JSON, and store.steampowered.com/app/ HTML fallback." +domains: + - store.steampowered.com + - api.steampowered.com +auth_mode: pub +min_interval_ms: 1000 +exampleUrls: + - "https://store.steampowered.com/api/appdetails?appids=620" + - "https://store.steampowered.com/app/620/Portal_2/" + - "https://api.steampowered.com/ISteamNews/GetNewsForApp/v2/?appid=620&count=2" + +routes: + - match: + hosts: + - store.steampowered.com + pathEquals: + - /api/appdetails + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: steam_store_json + + - match: + hosts: + - store.steampowered.com + exactSegments: false + pathSegments: + - app + - param: appId + charset: digits + minLen: 1 + maxLen: 12 + twin: + fetchUrl: "https://store.steampowered.com/api/appdetails?appids={appId}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: steam_store_json + + - match: + hosts: + - store.steampowered.com + exactSegments: false + pathSegments: + - appreviews + - param: appId + charset: digits + minLen: 1 + maxLen: 12 + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + setQueryParams: + json: "1" + maxBytes: 2097152 + extract: + jsonMode: steam_store_json + + - match: + hosts: + - api.steampowered.com + pathPrefix: /ISteamNews/GetNewsForApp/ + exactSegments: false + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: steam_store_json + +htmlRoutes: + - id: steam-store + match: + hosts: + - store.steampowered.com + exactSegments: false + mode: steam_store_html diff --git a/internal/extract/manifests/substack-notes-beehiiv.yaml b/internal/extract/manifests/substack-notes-beehiiv.yaml new file mode 100644 index 0000000..ac6fc48 --- /dev/null +++ b/internal/extract/manifests/substack-notes-beehiiv.yaml @@ -0,0 +1,58 @@ +# Shared Go + TypeScript Declarative Site Adapter: Substack Notes & Beehiiv API (#399) +id: substack-notes-beehiiv +name: Substack Notes & Beehiiv v2 API +category: commerce-social +description: "Extracts Beehiiv v2 publication/post feeds on api.beehiiv.com (BEEHIIV_API_KEY) and Substack creator profiles/notes on substack.com (preloads-json), avoiding *.beehiiv.com overlap with newsletter-archives." +domains: + - api.beehiiv.com + - substack.com + - www.substack.com +auth_mode: key +min_interval_ms: 1000 +strict_robots: true +exampleUrls: + - "https://substack.com/@hamish" + - "https://api.beehiiv.com/v2/publications/pub_00000000-0000-0000-0000-000000000000/posts" + +routes: + - match: + hosts: + - api.beehiiv.com + pathPrefix: /v2/publications/ + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + auth_mode: key + maxBytes: 2097152 + extract: + jsonMode: beehiiv_api_json + +htmlRoutes: + - id: substack-notes-beehiiv + match: + hosts: + - substack.com + - www.substack.com + anyOf: + - exactSegments: true + pathSegments: + - param: handle + charset: at_handle + minLen: 2 + maxLen: 80 + - exactSegments: true + pathSegments: + - param: handle + charset: at_handle + minLen: 2 + maxLen: 80 + - note + - param: noteId + charset: url_seg + minLen: 1 + maxLen: 80 + - pathEquals: + - /notes + - /notes/ + mode: substack_notes_html diff --git a/internal/extract/manifests/suspension-cockpit-compat.yaml b/internal/extract/manifests/suspension-cockpit-compat.yaml new file mode 100644 index 0000000..4b5294b --- /dev/null +++ b/internal/extract/manifests/suspension-cockpit-compat.yaml @@ -0,0 +1,26 @@ +# Shared Go + TypeScript Declarative Site Adapter: Suspension & Cockpit Compatibility (#349) +id: suspension-cockpit-compat +name: Suspension & Cockpit Compatibility Specs +category: commerce-social +description: "Extracts SHIS headset codes, chainring BCD/mount standards, rear shock sizing, and fitment tables from Wolf Tooth, Ohlins, PUSH Industries, and Cane Creek." +domains: + - wolftoothcomponents.com + - www.wolftoothcomponents.com + - ohlins.com + - www.ohlins.com + - pushindustries.com + - www.pushindustries.com + - canecreek.com + - www.canecreek.com +auth_mode: html +exampleUrls: + - "https://www.wolftoothcomponents.com/collections/chainrings" + - "https://www.ohlins.com/en-us/bicycle" + - "https://www.pushindustries.com/products/elevensix" + - "https://www.canecreek.com/collections/headsets" + +htmlRoutes: + - id: suspension-cockpit-compat + match: + exactSegments: false + mode: suspension_cockpit_compat_html diff --git a/internal/extract/manifests/taleo-full.yaml b/internal/extract/manifests/taleo-full.yaml index a0b4a64..21e25bc 100644 --- a/internal/extract/manifests/taleo-full.yaml +++ b/internal/extract/manifests/taleo-full.yaml @@ -2,15 +2,17 @@ id: taleo-full name: Oracle Taleo Career Section Job Search category: jobs -description: "Formats Oracle Taleo career-section job boards via the public /careersection/rest/jobboard/searchjobs endpoint the career page itself calls (portal id from the page): title, location, posted date, contest number, total open requisitions. Add §ion= to get job-detail links." +description: "Formats Oracle Taleo career-section job boards via the public /careersection/rest/jobboard/searchjobs endpoint (portal id from the page: title, location, posted date, contest number, total open requisitions) plus SSR FreeMarker /careersection/
/jobsearch.ftl and jobdetail.ftl HTML fallbacks." domains: - hdr.taleo.net + - "*.taleo.net" universalEngine: true auth_mode: pub min_interval_ms: 3000 strict_robots: true exampleUrls: - "https://hdr.taleo.net/careersection/rest/jobboard/searchjobs?lang=en&portal=101430233§ion=ex" + - "https://chicago.taleo.net/careersection/100/jobsearch.ftl" routes: - match: @@ -46,3 +48,10 @@ routes: maxBytes: 4194304 extract: jsonMode: taleo_searchjobs_json + +htmlRoutes: + - id: taleo-full + mode: taleo_full_html + match: + pathPrefix: /careersection/ + exactSegments: false diff --git a/internal/extract/manifests/threads-api.yaml b/internal/extract/manifests/threads-api.yaml new file mode 100644 index 0000000..16f5aee --- /dev/null +++ b/internal/extract/manifests/threads-api.yaml @@ -0,0 +1,42 @@ +# Shared Go + TypeScript Declarative Site Adapter: Threads API (#394) +id: threads-api +name: Meta Threads Graph API +category: commerce-social +description: "Extracts Threads profiles, posts, replies, and search results via official graph.threads.net v1.0 JSON endpoints (THREADS_ACCESS_TOKEN) with threads.net / threads.com public HTML fallback." +domains: + - graph.threads.net + - www.threads.net + - threads.net + - www.threads.com + - threads.com +auth_mode: key +min_interval_ms: 1000 +strict_robots: true +exampleUrls: + - "https://graph.threads.net/v1.0/me?fields=id,username,name,threads_biography" + - "https://www.threads.net/@threads" + +routes: + - match: + hosts: + - graph.threads.net + pathPrefix: /v1.0/ + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + auth_mode: key + maxBytes: 2097152 + extract: + jsonMode: threads_api_json + +htmlRoutes: + - id: threads-api + match: + hosts: + - www.threads.net + - threads.net + - www.threads.com + - threads.com + exactSegments: false + mode: threads_html diff --git a/internal/extract/manifests/tmdb.yaml b/internal/extract/manifests/tmdb.yaml new file mode 100644 index 0000000..29289ba --- /dev/null +++ b/internal/extract/manifests/tmdb.yaml @@ -0,0 +1,66 @@ +# Shared Go + TypeScript Declarative Site Adapter: The Movie Database (TMDB) (#375) +id: tmdb +name: The Movie Database (TMDB) +category: commerce-social +description: "Official keyed TMDB v3 API adapter (TMDB_API_KEY) for movies, TV series, people, and collections, with public themoviedb.org JSON-LD and DOM fallback." +domains: + - api.themoviedb.org + - www.themoviedb.org + - themoviedb.org +auth_mode: key +min_interval_ms: 1000 +exampleUrls: + - "https://www.themoviedb.org/movie/550" + - "https://api.themoviedb.org/3/movie/550" + - "https://www.themoviedb.org/tv/1396" + +routes: + - match: + hosts: + - api.themoviedb.org + pathPrefix: /3/ + exactSegments: false + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + auth_mode: key + maxBytes: 2097152 + extract: + jsonMode: tmdb_json + + - match: + hosts: + - www.themoviedb.org + - themoviedb.org + optionalLeadingLocale: true + exactSegments: true + pathSegments: + - param: entityType + allowValues: + - movie + - tv + - person + - collection + - param: tmdbId + charset: leading_digits_slug + transform: leading_digits + minLen: 1 + maxLen: 220 + twin: + fetchUrl: "https://api.themoviedb.org/3/{entityType}/{tmdbId}" + kind: json + accept: application/json + auth_mode: key + maxBytes: 2097152 + extract: + jsonMode: tmdb_json + +htmlRoutes: + - id: tmdb + match: + hosts: + - www.themoviedb.org + - themoviedb.org + exactSegments: false + mode: tmdb_html diff --git a/internal/extract/manifests/trade-gov-csl.yaml b/internal/extract/manifests/trade-gov-csl.yaml new file mode 100644 index 0000000..24a3172 --- /dev/null +++ b/internal/extract/manifests/trade-gov-csl.yaml @@ -0,0 +1,38 @@ +# Shared Go + TypeScript Declarative Site Adapter: Trade.gov Consolidated Screening List (#275) +id: trade-gov-csl +name: Trade.gov Consolidated Screening List +category: public-records +description: "Official keyed Trade.gov Consolidated Screening List (CSL) API adapter (TRADE_GOV_CSL_API_KEY via subscription-key header) with HTML fallback on www.trade.gov." +domains: + - data.trade.gov + - api.trade.gov + - www.trade.gov + - trade.gov +auth_mode: key +exampleUrls: + - "https://data.trade.gov/consolidated_screening_list/v1/search?q=huawei" + - "https://www.trade.gov/consolidated-screening-list" + +routes: + - match: + hosts: + - data.trade.gov + - api.trade.gov + pathPrefix: /consolidated_screening_list/ + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + auth_mode: key + maxBytes: 4194304 + extract: + jsonMode: trade_gov_csl_json + +htmlRoutes: + - id: trade-gov-csl + match: + hosts: + - www.trade.gov + - trade.gov + exactSegments: false + mode: trade_gov_csl_html diff --git a/internal/extract/manifests/tumblr.yaml b/internal/extract/manifests/tumblr.yaml new file mode 100644 index 0000000..adba823 --- /dev/null +++ b/internal/extract/manifests/tumblr.yaml @@ -0,0 +1,52 @@ +# Shared Go + TypeScript Declarative Site Adapter: Tumblr (#395) +id: tumblr +name: Tumblr Blogs & Posts +category: commerce-social +description: "Extracts Tumblr blog info and posts via official api.tumblr.com/v2/blog/ JSON (TUMBLR_API_KEY) and www.tumblr.com SSR HTML (___INITIAL_STATE___ + og:*), avoiding PoW-gated *.tumblr.com subdomains." +domains: + - api.tumblr.com + - www.tumblr.com +auth_mode: key +min_interval_ms: 1000 +strict_robots: true +exampleUrls: + - "https://www.tumblr.com/staff" + - "https://www.tumblr.com/staff/828009069026721792/premium-just-got-better" + - "https://api.tumblr.com/v2/blog/staff.tumblr.com/posts" + +routes: + - match: + hosts: + - api.tumblr.com + pathPrefix: /v2/blog/ + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + auth_mode: key + maxBytes: 2097152 + extract: + jsonMode: tumblr_api_json + +htmlRoutes: + - id: tumblr + match: + hosts: + - www.tumblr.com + reservedFirstSegment: + - dashboard + - liked + - search + - login + - register + - settings + - explore + - following + - activity + - inbox + - help + - policy + - privacy + - terms + exactSegments: false + mode: tumblr_html diff --git a/internal/extract/manifests/tvmaze.yaml b/internal/extract/manifests/tvmaze.yaml new file mode 100644 index 0000000..eb172c1 --- /dev/null +++ b/internal/extract/manifests/tvmaze.yaml @@ -0,0 +1,80 @@ +# Shared Go + TypeScript Declarative Site Adapter: TVmaze (#377) +id: tvmaze +name: TVmaze TV Shows & Episodes +category: commerce-social +description: "Public TVmaze REST API adapter for TV shows, embedded episodes, people, and schedule data, with www.tvmaze.com HTML fallback." +domains: + - api.tvmaze.com + - www.tvmaze.com + - tvmaze.com +auth_mode: pub +min_interval_ms: 1000 +exampleUrls: + - "https://api.tvmaze.com/shows/1?embed=episodes" + - "https://www.tvmaze.com/shows/1/under-the-dome" + +routes: + - match: + hosts: + - api.tvmaze.com + anyOf: + - pathPrefix: /shows/ + - pathPrefix: /episodes/ + - pathPrefix: /people/ + - pathPrefix: /search/ + exactSegments: false + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: tvmaze_json + + - match: + hosts: + - www.tvmaze.com + - tvmaze.com + anyOf: + - exactSegments: true + pathSegments: + - shows + - param: showId + charset: digits + minLen: 1 + maxLen: 12 + - exactSegments: true + pathSegments: + - shows + - param: showId + charset: digits + minLen: 1 + maxLen: 12 + - param: showSlug + charset: url_seg + reserved: + - episodes + - seasons + - cast + - crew + - characters + - gallery + - news + minLen: 1 + maxLen: 120 + twin: + fetchUrl: "https://api.tvmaze.com/shows/{showId}?embed=episodes" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: tvmaze_json + +htmlRoutes: + - id: tvmaze + match: + hosts: + - www.tvmaze.com + - tvmaze.com + exactSegments: false + mode: tvmaze_html diff --git a/internal/extract/manifests/tyler-energov.yaml b/internal/extract/manifests/tyler-energov.yaml new file mode 100644 index 0000000..a7780b5 --- /dev/null +++ b/internal/extract/manifests/tyler-energov.yaml @@ -0,0 +1,33 @@ +# Shared Go + TypeScript Declarative Site Adapter: Tyler EnerGov (#210) +id: tyler-energov +name: Tyler Technologies EnerGov SelfService +category: public-records +description: "Extracts public permit, plan, and license records from Tyler EnerGov SelfService APIs and SSR HTML while rejecting empty AngularJS shells and WAF challenges." +domains: + - energovweb.capecoral.gov + - energovcss.miamibeachfl.gov +universalEngine: true +auth_mode: pub +exampleUrls: + - "https://energovweb.capecoral.gov/EnerGovProd/selfservice" + - "https://energovcss.miamibeachfl.gov/energovprod/selfservice/" + +routes: + - match: + anyOf: + - pathPrefix: /EnerGov_Prod/SelfService/api/ + - pathPrefix: /EnerGovProd/selfservice/api/ + - pathPrefix: /energovprod/selfservice/api/ + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 4194304 + extract: + jsonMode: tyler_energov_json + +htmlRoutes: + - id: tyler-energov + match: + exactSegments: false + mode: tyler_energov_html diff --git a/internal/extract/manifests/ul-product-iq.yaml b/internal/extract/manifests/ul-product-iq.yaml new file mode 100644 index 0000000..59e2842 --- /dev/null +++ b/internal/extract/manifests/ul-product-iq.yaml @@ -0,0 +1,19 @@ +# Shared Go + TypeScript Declarative Site Adapter: UL Product iQ & UL iQ (#356) +id: ul-product-iq +name: "UL Product iQ & UL iQ Certifications" +category: public-records +description: "Extracts UL 2849 / UL 2271 e-bike and battery certification listings from iq.ul.com and UL Product iQ (disjoint from ul.com owned by cpsc-ebike-battery) while rejecting blocked/WAF shells." +domains: + - iq.ul.com + - productiq.ulprospector.com + - iq.ulprospector.com +auth_mode: html +min_interval_ms: 1000 +exampleUrls: + - "https://iq.ul.com/" + +htmlRoutes: + - id: ul-product-iq + match: + exactSegments: false + mode: ul_product_iq_html diff --git a/internal/extract/manifests/unpaywall.yaml b/internal/extract/manifests/unpaywall.yaml new file mode 100644 index 0000000..0a4488a --- /dev/null +++ b/internal/extract/manifests/unpaywall.yaml @@ -0,0 +1,59 @@ +# Shared Go + TypeScript Declarative Site Adapter: Unpaywall (#302) +id: unpaywall +name: Unpaywall Open Access Resolver +category: research-health +description: "Resolves scholarly DOI open-access status, licenses, best OA PDF locations, and author metadata via api.unpaywall.org/v2 (strictly enforcing ?email=bot@edgefetch.dev)." +domains: + - api.unpaywall.org + - unpaywall.org + - www.unpaywall.org +auth_mode: pub +min_interval_ms: 1000 +exampleUrls: + - "https://api.unpaywall.org/v2/10.1038/s41586-021-03819-2?email=bot@edgefetch.dev" + +routes: + - match: + hosts: + - api.unpaywall.org + exactSegments: true + pathEquals: + - /v2/search + twin: + fetchUrl: "{requestUrl}" + setQueryParams: + email: "bot@edgefetch.dev" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: unpaywall_json + + - match: + hosts: + - api.unpaywall.org + pathSegments: + - v2 + - param: doi + charset: doi_rest + greedy: true + minLen: 8 + maxLen: 240 + twin: + fetchUrl: "{requestUrl}" + setQueryParams: + email: "bot@edgefetch.dev" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: unpaywall_json + +htmlRoutes: + - id: unpaywall + match: + hosts: + - unpaywall.org + - www.unpaywall.org + exactSegments: false + mode: unpaywall_html diff --git a/internal/extract/manifests/upcitemdb-barcodelookup.yaml b/internal/extract/manifests/upcitemdb-barcodelookup.yaml new file mode 100644 index 0000000..cc1dac9 --- /dev/null +++ b/internal/extract/manifests/upcitemdb-barcodelookup.yaml @@ -0,0 +1,111 @@ +# Shared Go + TypeScript Declarative Site Adapter: UPCitemdb & Barcode Lookup (#370) +id: upcitemdb-barcodelookup +name: UPCitemdb & Barcode Lookup +category: commerce-social +description: "Extracts GTIN/UPC/EAN product identity, brand, category, and pricing from UPCitemdb (public trial + keyed v1), Barcode Lookup v3 (keyed), and upcitemdb.com HTML with strict 8/12/13/14-digit GTIN validation." +domains: + - api.upcitemdb.com + - www.upcitemdb.com + - upcitemdb.com + - api.barcodelookup.com + - www.barcodelookup.com + - barcodelookup.com +auth_mode: key +min_interval_ms: 1000 +exampleUrls: + - "https://api.upcitemdb.com/prod/trial/lookup?upc=012000161155" + - "https://www.upcitemdb.com/upc/012000161155" + - "https://api.barcodelookup.com/v3/products?barcode=012000161155" + +routes: + - match: + hosts: + - api.upcitemdb.com + pathEquals: + - /prod/trial/lookup + anyOf: + - queryParams: + - name: upc + param: upc + charset: digits + minLen: 8 + maxLen: 8 + - queryParams: + - name: upc + param: upc + charset: digits + minLen: 12 + maxLen: 14 + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + auth_mode: pub + maxBytes: 2097152 + extract: + jsonMode: upcitemdb_json + + - match: + hosts: + - api.upcitemdb.com + pathEquals: + - /prod/v1/lookup + anyOf: + - queryParams: + - name: upc + param: upc + charset: digits + minLen: 8 + maxLen: 8 + - queryParams: + - name: upc + param: upc + charset: digits + minLen: 12 + maxLen: 14 + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + auth_mode: key + maxBytes: 2097152 + extract: + jsonMode: upcitemdb_json + + - match: + hosts: + - api.barcodelookup.com + pathEquals: + - /v3/products + anyOf: + - queryParams: + - name: barcode + param: barcode + charset: digits + minLen: 8 + maxLen: 8 + - queryParams: + - name: barcode + param: barcode + charset: digits + minLen: 12 + maxLen: 14 + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + auth_mode: key + maxBytes: 2097152 + extract: + jsonMode: barcodelookup_json + +htmlRoutes: + - id: upcitemdb-barcodelookup + match: + hosts: + - www.upcitemdb.com + - upcitemdb.com + - www.barcodelookup.com + - barcodelookup.com + exactSegments: false + mode: upcitemdb_barcodelookup_html diff --git a/internal/extract/manifests/us-ebike-oems.yaml b/internal/extract/manifests/us-ebike-oems.yaml new file mode 100644 index 0000000..4e5eb7e --- /dev/null +++ b/internal/extract/manifests/us-ebike-oems.yaml @@ -0,0 +1,28 @@ +# Shared Go + TypeScript Declarative Site Adapter: US E-Bike OEMs (#351) +id: us-ebike-oems +name: "US E-Bike OEMs (Gazelle, Electra, Benno, Pedego, Serial 1)" +category: commerce-social +description: "Extracts Class 1/2/3 ratings, battery Wh, motor specs, and model specifications from Gazelle, Electra, Benno, Pedego, and Serial 1." +domains: + - gazellebikes.com + - www.gazellebikes.com + - electra.trekbikes.com + - bennobikes.com + - www.bennobikes.com + - pedegoelectricbikes.com + - www.pedegoelectricbikes.com + - serial1.com + - www.serial1.com +auth_mode: html +min_interval_ms: 1000 +exampleUrls: + - "https://www.gazellebikes.com/en-us/models/gazelle-arroyo" + - "https://electra.trekbikes.com/us/en_US/bikes/electra-bikes/c/EB100/" + - "https://bennobikes.com/e-bikes/boost/" + - "https://pedegoelectricbikes.com/products/interceptor" + +htmlRoutes: + - id: us-ebike-oems + match: + exactSegments: false + mode: us_ebike_oems_html diff --git a/internal/extract/manifests/used-bikes-shopify.yaml b/internal/extract/manifests/used-bikes-shopify.yaml new file mode 100644 index 0000000..897acbb --- /dev/null +++ b/internal/extract/manifests/used-bikes-shopify.yaml @@ -0,0 +1,82 @@ +# Shared Go + TypeScript Declarative Site Adapter: Certified Pre-Owned Used Bikes (#361) +id: used-bikes-shopify +name: The Pro's Closet & Upway Used Bikes +category: commerce-social +description: "Extracts certified pre-owned bicycle and e-bike listings from The Pro's Closet (Shopify JSON + HTML fallback) and Upway (Hydrogen + JSON-LD HTML) while honoring Upway's Crawl-delay and rejecting 404 homepage shells." +domains: + - theproscloset.com + - www.theproscloset.com + - upway.co + - www.upway.co +auth_mode: pub +min_interval_ms: 2000 +strict_robots: true +exampleUrls: + - "https://www.theproscloset.com/products/10226226168000-cervelo-p-series-red-axs-time-trial-bike-2022-58cm" + - "https://www.theproscloset.com/products.json?limit=5&page=1" + - "https://upway.co/products/lane-lane-express-uaa01" + +routes: + - match: + hosts: + - theproscloset.com + - www.theproscloset.com + anyOf: + - pathEquals: + - /products.json + - exactSegments: true + pathSegments: + - collections + - param: col + charset: slug + maxLen: 160 + - products.json + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + extract: + commerceMode: shopify_catalog_page + + - match: + hosts: + - theproscloset.com + - www.theproscloset.com + pathSuffix: .json + scanSegment: + afterLiteral: products + param: handle + charset: slug + stripSuffix: .json + maxLen: 160 + twin: + fetchUrl: "https://{host}/products/{handle}.json" + kind: json + accept: application/json + extract: + commerceMode: shopify_product + + - match: + hosts: + - theproscloset.com + - www.theproscloset.com + scanSegment: + afterLiteral: products + param: handle + charset: slug + stripSuffix: .js + maxLen: 160 + twin: + fetchUrl: "https://{host}/products/{handle}.js" + kind: json + accept: application/json + extract: + commerceMode: shopify_product_js + +htmlRoutes: + - id: used-bikes-shopify + match: + anyOf: + - pathPrefix: /products/ + - pathPrefix: /collections/ + mode: used_bikes_shopify_html diff --git a/internal/extract/manifests/usitc-hts.yaml b/internal/extract/manifests/usitc-hts.yaml new file mode 100644 index 0000000..e1cc9e7 --- /dev/null +++ b/internal/extract/manifests/usitc-hts.yaml @@ -0,0 +1,85 @@ +# Shared Go + TypeScript Declarative Site Adapter: USITC Harmonized Tariff Schedule (#271) +id: usitc-hts +name: USITC Harmonized Tariff Schedule +category: public-records +description: "Extracts U.S. Harmonized Tariff Schedule (HTS) tariff lines, duty rates, and Chapter 99 / Section 301 footnotes from hts.usitc.gov reststop JSON endpoints with SPA shell guards." +domains: + - hts.usitc.gov +auth_mode: pub +exampleUrls: + - "https://hts.usitc.gov/reststop/search?keyword=bicycle" + - "https://hts.usitc.gov/reststop/exportList?from=8712.00&to=8712.00&format=JSON&styles=false" + +routes: + - match: + hosts: + - hts.usitc.gov + exactSegments: true + pathEquals: + - /reststop/search + queryParams: + - name: keyword + param: keyword + minLen: 1 + maxLen: 120 + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 4194304 + extract: + jsonMode: usitc_hts_json + + - match: + hosts: + - hts.usitc.gov + exactSegments: true + pathEquals: + - /reststop/exportList + queryParams: + - name: from + param: from + minLen: 2 + maxLen: 16 + - name: to + param: to + minLen: 2 + maxLen: 16 + - name: format + param: format + allowValues: + - JSON + - json + optional: true + default: JSON + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 4194304 + extract: + jsonMode: usitc_hts_json + + - match: + hosts: + - hts.usitc.gov + pathPrefix: /reststop/ + excludeSegmentSuffixes: + - .csv + - .xlsx + - .pdf + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 4194304 + extract: + jsonMode: usitc_hts_json + +htmlRoutes: + - id: usitc-hts + match: + hosts: + - hts.usitc.gov + exactSegments: false + mode: usitc_hts_html diff --git a/internal/extract/manifests/usps-addresses.yaml b/internal/extract/manifests/usps-addresses.yaml new file mode 100644 index 0000000..e047db1 --- /dev/null +++ b/internal/extract/manifests/usps-addresses.yaml @@ -0,0 +1,40 @@ +# Shared Go + TypeScript Declarative Site Adapter: USPS Addresses v3 (#298) +id: usps-addresses +name: "USPS Addresses v3 Official API" +category: public-records +description: "USPS Addresses v3 API for address standardization, city/state, and ZIP lookup (USPS_ACCESS_TOKEN) with developers.usps.com HTML fallback." +domains: + - apis.usps.com + - apis-tem.usps.com + - developers.usps.com +auth_mode: key +min_interval_ms: 1000 +exampleUrls: + - "https://apis.usps.com/addresses/v3/address?streetAddress=475%20L%27Enfant%20Plaza%20SW&city=Washington&state=DC" + - "https://apis.usps.com/addresses/v3/city-state?ZIPCode=20260" + +routes: + - match: + hosts: + - apis.usps.com + - apis-tem.usps.com + anyOf: + - pathPrefix: /addresses/v3/address + - pathPrefix: /addresses/v3/city-state + - pathPrefix: /addresses/v3/zipcode + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + auth_mode: key + maxBytes: 1048576 + extract: + jsonMode: usps_addresses_json + +htmlRoutes: + - id: usps-addresses + match: + hosts: + - developers.usps.com + exactSegments: false + mode: usps_docs_html diff --git a/internal/extract/manifests/ustr-301.yaml b/internal/extract/manifests/ustr-301.yaml new file mode 100644 index 0000000..58b0369 --- /dev/null +++ b/internal/extract/manifests/ustr-301.yaml @@ -0,0 +1,36 @@ +# Shared Go + TypeScript Declarative Site Adapter: USTR Section 301 Trade Actions (#274) +id: ustr-301 +name: USTR Section 301 Trade Actions +category: public-records +description: "Extracts U.S. Trade Representative Section 301 investigation actions, tariff lists, exclusion notices, and RSS feeds from ustr.gov." +domains: + - ustr.gov + - www.ustr.gov +auth_mode: pub +exampleUrls: + - "https://ustr.gov/issue-areas/enforcement/section-301-investigations/tariff-actions" + - "https://ustr.gov/issue-areas/enforcement/section-301-investigations/section-301-china/investigation" + - "https://ustr.gov/rss.xml" + +routes: + - match: + hosts: + - ustr.gov + - www.ustr.gov + pathSuffix: .xml + twin: + fetchUrl: "{requestUrl}" + kind: text + accept: application/rss+xml + maxBytes: 2097152 + extract: + textMode: ustr_301_rss_xml + +htmlRoutes: + - id: ustr-301 + match: + hosts: + - ustr.gov + - www.ustr.gov + exactSegments: false + mode: ustr_301_html diff --git a/internal/extract/manifests/va-lighthouse-facilities.yaml b/internal/extract/manifests/va-lighthouse-facilities.yaml new file mode 100644 index 0000000..2dd2f77 --- /dev/null +++ b/internal/extract/manifests/va-lighthouse-facilities.yaml @@ -0,0 +1,39 @@ +# Shared Go + TypeScript Declarative Site Adapter: VA Lighthouse Facilities API (#294) +id: va-lighthouse-facilities +name: "VA Lighthouse Facilities API" +category: research-health +description: "U.S. Department of Veterans Affairs Lighthouse Facilities API (VA_LIGHTHOUSE_API_KEY) with www.va.gov / developer.va.gov HTML fallback." +domains: + - api.va.gov + - sandbox-api.va.gov + - www.va.gov + - developer.va.gov +auth_mode: key +min_interval_ms: 1000 +exampleUrls: + - "https://api.va.gov/services/va_facilities/v1/facilities?state=TX&per_page=5" + - "https://www.va.gov/boston-health-care/locations/brockton-va-medical-center" + +routes: + - match: + hosts: + - api.va.gov + - sandbox-api.va.gov + pathPrefix: /services/va_facilities/v1/facilities + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + auth_mode: key + maxBytes: 2097152 + extract: + jsonMode: va_facilities_json + +htmlRoutes: + - id: va-lighthouse-facilities + match: + hosts: + - www.va.gov + - developer.va.gov + exactSegments: false + mode: va_facilities_html diff --git a/internal/extract/manifests/vendor-csaf.yaml b/internal/extract/manifests/vendor-csaf.yaml new file mode 100644 index 0000000..25cfb93 --- /dev/null +++ b/internal/extract/manifests/vendor-csaf.yaml @@ -0,0 +1,46 @@ +# Shared Go + TypeScript Declarative Site Adapter: Vendor CSAF 2.0 & Provider Metadata (#321) +id: vendor-csaf +name: Vendor CSAF 2.0 Advisories & Provider Metadata +category: developer +description: "Universal parser for OASIS CSAF 2.0 provider-metadata.json discovery files and CSAF 2.0 security advisory JSON documents across vendor CSIRTs." +domains: + - security.access.redhat.com + - cert-portal.siemens.com +universalEngine: true +auth_mode: pub +min_interval_ms: 1000 +exampleUrls: + - "https://security.access.redhat.com/data/csaf/v2/provider-metadata.json" + - "https://security.access.redhat.com/data/csaf/v2/advisories/2026/rhsa-2026_88339.json" + - "https://cert-portal.siemens.com/productcert/csaf/provider-metadata.json" + +routes: + - match: + anyOf: + - exactSegments: true + pathEquals: + - /.well-known/csaf/provider-metadata.json + - pathSuffix: /provider-metadata.json + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 1048576 + extract: + jsonMode: vendor_csaf_json + + - match: + anyOf: + - pathContainsSegment: csaf + pathSuffix: .json + - pathPrefix: /data/csaf/ + pathSuffix: .json + - pathPrefix: /cisagov/CSAF/ + pathSuffix: .json + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 4194304 + extract: + jsonMode: vendor_csaf_json diff --git a/internal/extract/manifests/vscode-open-vsx.yaml b/internal/extract/manifests/vscode-open-vsx.yaml new file mode 100644 index 0000000..cecc106 --- /dev/null +++ b/internal/extract/manifests/vscode-open-vsx.yaml @@ -0,0 +1,39 @@ +# Shared Go + TypeScript Declarative Site Adapter: VS Code Marketplace & Open VSX (#333) +id: vscode-open-vsx +name: VS Code Marketplace & Open VSX +category: developer +description: "Extracts IDE extension versions, publishers, licenses, and download metrics from open-vsx.org REST JSON and marketplace.visualstudio.com SSR HTML." +domains: + - open-vsx.org + - marketplace.visualstudio.com +auth_mode: pub +min_interval_ms: 2000 +exampleUrls: + - "https://open-vsx.org/api/esbenp/prettier-vscode" + - "https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode" + +routes: + - match: + hosts: + - open-vsx.org + pathPrefix: /api/ + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 1048576 + extract: + jsonMode: open_vsx_json + +htmlRoutes: + - id: vscode-open-vsx + match: + hosts: + - marketplace.visualstudio.com + pathEquals: + - /items + queryParams: + - name: itemName + param: itemName + charset: pkg + mode: vscode_marketplace_html diff --git a/internal/extract/manifests/web-compat-data.yaml b/internal/extract/manifests/web-compat-data.yaml new file mode 100644 index 0000000..d240057 --- /dev/null +++ b/internal/extract/manifests/web-compat-data.yaml @@ -0,0 +1,91 @@ +# Shared Go + TypeScript Declarative Site Adapter: Web Compatibility Data (#339) +id: web-compat-data +name: Web Compatibility & Baseline Data +category: developer +description: "Extracts browser compatibility and Web Platform Baseline data from api.webstatus.dev, @mdn/browser-compat-data, caniuse-db, web-features JSON, and caniuse.com HTML." +domains: + - api.webstatus.dev + - caniuse.com + - www.caniuse.com +universalEngine: true +auth_mode: pub +exampleUrls: + - "https://raw.githubusercontent.com/mdn/browser-compat-data/main/api/AbortController.json" + - "https://raw.githubusercontent.com/Fyrd/caniuse/main/features-json/css-grid.json" + - "https://api.webstatus.dev/v1/features/aborting" + - "https://cdn.jsdelivr.net/npm/web-features/data.json" + - "https://caniuse.com/css-grid" + +routes: + - match: + hosts: + - api.webstatus.dev + pathPrefix: /v1/features/ + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 1048576 + extract: + jsonMode: web_compat_json + + - match: + hosts: + - raw.githubusercontent.com + pathPrefix: /mdn/browser-compat-data/ + pathSuffix: .json + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: web_compat_json + + - match: + hosts: + - raw.githubusercontent.com + pathPrefix: /Fyrd/caniuse/ + pathSuffix: .json + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: web_compat_json + + - match: + hosts: + - cdn.jsdelivr.net + exactSegments: true + pathEquals: + - /npm/web-features/data.json + twin: + fetchUrl: "{requestUrl}" + kind: text + accept: application/json + headers: + Range: bytes=0-524287 + maxBytes: 1048576 + extract: + textMode: web_compat_json + +htmlRoutes: + - id: web-compat-data + match: + hosts: + - caniuse.com + - www.caniuse.com + exactSegments: true + pathSegments: + - param: feature + charset: pkg + reserved: + - ciu + - feeds + - about + - usage-table + - compare + - index + mode: caniuse_html diff --git a/internal/extract/manifests/wheel-hub-specs.yaml b/internal/extract/manifests/wheel-hub-specs.yaml new file mode 100644 index 0000000..e15a73d --- /dev/null +++ b/internal/extract/manifests/wheel-hub-specs.yaml @@ -0,0 +1,26 @@ +# Shared Go + TypeScript Declarative Site Adapter: Wheel & Hub Specs (#347) +id: wheel-hub-specs +name: Bicycle Wheel & Hub Technical Specs +category: commerce-social +description: "Extracts hub axle spacing (O.L.D.), freehub compatibility, engagement, spoke counts, and service manuals from DT Swiss, Industry Nine, Chris King, and Hope Technology." +domains: + - dtswiss.com + - www.dtswiss.com + - industrynine.com + - www.industrynine.com + - chrisking.com + - www.chrisking.com + - hopetech.com + - www.hopetech.com +auth_mode: html +exampleUrls: + - "https://www.dtswiss.com/en/components/hubs-and-rws/hubs-mtb/350" + - "https://industrynine.com/products/sector-al" + - "https://chrisking.com/collections/hubs-all" + - "https://www.hopetech.com/products/hubs/mountain-bike/" + +htmlRoutes: + - id: wheel-hub-specs + match: + exactSegments: false + mode: wheel_hub_specs_html diff --git a/internal/extract/manifests/wild-apricot.yaml b/internal/extract/manifests/wild-apricot.yaml new file mode 100644 index 0000000..e10a49c --- /dev/null +++ b/internal/extract/manifests/wild-apricot.yaml @@ -0,0 +1,21 @@ +# Shared Go + TypeScript Declarative Site Adapter: Wild Apricot (#243) +id: wild-apricot +name: "Wild Apricot Member Associations & Events" +category: commerce-social +description: "Extracts public Wild Apricot association event details, upcoming event schedules, and member directories from WaGadget DOM while rejecting /sys/login and login-only gated shells." +domains: + - www.ndshp.org + - members.mbbi.org + - "*.wildapricot.org" +universalEngine: true +auth_mode: html +exampleUrls: + - "https://www.ndshp.org/event-6925405" + - "https://members.mbbi.org/event-6156275" + - "https://members.mbbi.org/Member-Directory/" + +htmlRoutes: + - id: wild-apricot + match: + exactSegments: false + mode: wild_apricot_html diff --git a/internal/extract/manifests/wordpress-org-plugins.yaml b/internal/extract/manifests/wordpress-org-plugins.yaml new file mode 100644 index 0000000..03b2ca5 --- /dev/null +++ b/internal/extract/manifests/wordpress-org-plugins.yaml @@ -0,0 +1,35 @@ +# Shared Go + TypeScript Declarative Site Adapter: WordPress.org Plugins (#332) +id: wordpress-org-plugins +name: WordPress.org Plugin Directory +category: developer +description: "Extracts WordPress plugin versions, compatibility, ratings, and descriptions from wordpress.org/plugins/ SoftwareApplication JSON-LD/HTML without cross-upgrading to api.wordpress.org." +domains: + - wordpress.org + - www.wordpress.org + - api.wordpress.org +auth_mode: pub +exampleUrls: + - "https://wordpress.org/plugins/akismet/" + - "https://api.wordpress.org/plugins/info/1.2/?action=plugin_information&slug=akismet" + +routes: + - match: + hosts: + - api.wordpress.org + pathPrefix: /plugins/info/ + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + maxBytes: 2097152 + extract: + jsonMode: wordpress_plugin_json + +htmlRoutes: + - id: wordpress-org-plugins + match: + hosts: + - wordpress.org + - www.wordpress.org + pathPrefix: /plugins/ + mode: wordpress_plugin_html diff --git a/internal/extract/manifests/youtube-data-api.yaml b/internal/extract/manifests/youtube-data-api.yaml new file mode 100644 index 0000000..924037e --- /dev/null +++ b/internal/extract/manifests/youtube-data-api.yaml @@ -0,0 +1,37 @@ +# Shared Go + TypeScript Declarative Site Adapter: YouTube Data API v3 (#393) +id: youtube-data-api +name: YouTube Data API v3 +category: commerce-social +description: "Extracts video, channel, playlist, and search metadata from official YouTube Data API v3 endpoints on www.googleapis.com (YOUTUBE_DATA_API_KEY via query key)." +domains: + - console.cloud.google.com +universalEngine: true +auth_mode: key +min_interval_ms: 250 +exampleUrls: + - "https://www.googleapis.com/youtube/v3/videos?part=snippet,statistics,contentDetails&id=dQw4w9WgXcQ" + - "https://www.googleapis.com/youtube/v3/channels?part=snippet,statistics&id=UC_x5XG1OV2P6uZZ5FSM9Ttw" + - "https://www.googleapis.com/youtube/v3/search?part=snippet&q=edge+computing&type=video&maxResults=5" + +routes: + - match: + hosts: + - www.googleapis.com + exactSegments: true + pathSegments: + - youtube + - v3 + - param: resource + allowValues: + - videos + - channels + - playlists + - search + twin: + fetchUrl: "{requestUrl}" + kind: json + accept: application/json + auth_mode: key + maxBytes: 2097152 + extract: + jsonMode: youtube_data_api_json diff --git a/internal/extract/official_api_providers.go b/internal/extract/official_api_providers.go index 56cd179..89d3b1e 100644 --- a/internal/extract/official_api_providers.go +++ b/internal/extract/official_api_providers.go @@ -31,6 +31,8 @@ var dataGovAdapterIDSet = map[string]bool{ "college-scorecard": true, "nps": true, "smithsonian-open-access": true, + "fcc-ecfs": true, + "gsa-site-scanning": true, } // DataGovAdapterIDs returns the sorted list of adapter IDs backed by api.data.gov (`DATA_GOV_API_KEY`). @@ -344,6 +346,195 @@ var officialProviderSpecs = map[string]OfficialAPIKeyProviderSpec{ Aliases: []string{"strava", "STRAVA_ACCESS_TOKEN", "STRAVA_API_KEY"}, DefaultInjection: &OfficialAPIKeyInjection{Kind: "header", Name: "Authorization", Prefix: "Bearer "}, }, + "trade-gov-csl": { + Provider: "trade-gov-csl", + EnvKeyName: "TRADE_GOV_CSL_API_KEY", + VaultProvider: "trade-gov-csl", + Aliases: []string{"TRADE_GOV_CSL_API_KEY"}, + DefaultInjection: &OfficialAPIKeyInjection{Kind: "header", Name: "subscription-key"}, + }, + "dol-enforcement": { + Provider: "dol-enforcement", + EnvKeyName: "DOL_API_KEY", + VaultProvider: "dol-enforcement", + Aliases: []string{"DOL_API_KEY"}, + DefaultInjection: &OfficialAPIKeyInjection{Kind: "header", Name: "X-API-KEY"}, + }, + "va-lighthouse-facilities": { + Provider: "va-lighthouse-facilities", + EnvKeyName: "VA_LIGHTHOUSE_API_KEY", + VaultProvider: "va-lighthouse-facilities", + Aliases: []string{"va-lighthouse", "va-facilities", "VA_LIGHTHOUSE_API_KEY"}, + DefaultInjection: &OfficialAPIKeyInjection{Kind: "header", Name: "apikey"}, + }, + "healthcare-gov-marketplace": { + Provider: "healthcare-gov-marketplace", + EnvKeyName: "HEALTHCARE_GOV_API_KEY", + VaultProvider: "healthcare-gov-marketplace", + Aliases: []string{"healthcare-gov", "cms-marketplace", "HEALTHCARE_GOV_API_KEY"}, + DefaultInjection: &OfficialAPIKeyInjection{Kind: "query", Name: "apikey"}, + }, + "usps-addresses": { + Provider: "usps-addresses", + EnvKeyName: "USPS_ACCESS_TOKEN", + VaultProvider: "usps-addresses", + Aliases: []string{"usps", "USPS_ACCESS_TOKEN", "USPS_API_KEY"}, + DefaultInjection: &OfficialAPIKeyInjection{Kind: "header", Name: "Authorization", Prefix: "Bearer "}, + }, + "carrier-tracking-official": { + Provider: "carrier-tracking-official", + EnvKeyName: "USPS_ACCESS_TOKEN", + VaultProvider: "usps-addresses", + Aliases: []string{"usps", "usps-addresses", "USPS_ACCESS_TOKEN", "USPS_API_KEY"}, + DefaultInjection: &OfficialAPIKeyInjection{Kind: "header", Name: "Authorization", Prefix: "Bearer "}, + }, + "core-ac": { + Provider: "core-ac", + EnvKeyName: "CORE_AC_API_KEY", + VaultProvider: "core-ac", + Aliases: []string{"CORE_AC_API_KEY"}, + DefaultInjection: &OfficialAPIKeyInjection{Kind: "header", Name: "Authorization", Prefix: "Bearer "}, + }, + "nasa-ads": { + Provider: "nasa-ads", + EnvKeyName: "NASA_ADS_API_KEY", + VaultProvider: "nasa-ads", + Aliases: []string{"adsabs", "NASA_ADS_API_KEY"}, + DefaultInjection: &OfficialAPIKeyInjection{Kind: "header", Name: "Authorization", Prefix: "Bearer "}, + }, + "semantic-scholar": { + Provider: "semantic-scholar", + EnvKeyName: "SEMANTIC_SCHOLAR_API_KEY", + VaultProvider: "semantic-scholar", + Aliases: []string{"s2", "SEMANTIC_SCHOLAR_API_KEY"}, + DefaultInjection: &OfficialAPIKeyInjection{Kind: "header", Name: "x-api-key"}, + }, + "gs1-us-datahub": { + Provider: "gs1-us-datahub", + EnvKeyName: "GS1_US_API_KEY", + VaultProvider: "gs1-us-datahub", + Aliases: []string{"gs1-us", "GS1_US_API_KEY"}, + DefaultInjection: &OfficialAPIKeyInjection{Kind: "header", Name: "Authorization", Prefix: "Bearer "}, + }, + "open-icecat": { + Provider: "open-icecat", + EnvKeyName: "ICECAT_API_TOKEN", + VaultProvider: "open-icecat", + Aliases: []string{"icecat", "ICECAT_API_TOKEN", "ICECAT_APP_KEY"}, + DefaultInjection: &OfficialAPIKeyInjection{Kind: "query", Name: "app_key"}, + }, + "upcitemdb-barcodelookup": { + Provider: "upcitemdb-barcodelookup", + EnvKeyName: "UPCITEMDB_API_KEY", + VaultProvider: "upcitemdb-barcodelookup", + Aliases: []string{"upcitemdb", "UPCITEMDB_API_KEY", "barcodelookup", "BARCODELOOKUP_API_KEY"}, + DefaultInjection: &OfficialAPIKeyInjection{Kind: "header", Name: "user_key"}, + }, + "tmdb": { + Provider: "tmdb", + EnvKeyName: "TMDB_API_KEY", + VaultProvider: "tmdb", + Aliases: []string{"TMDB_API_KEY", "TMDB_READ_ACCESS_TOKEN"}, + DefaultInjection: &OfficialAPIKeyInjection{Kind: "query", Name: "api_key"}, + }, + "discogs": { + Provider: "discogs", + EnvKeyName: "DISCOGS_API_TOKEN", + VaultProvider: "discogs", + Aliases: []string{"DISCOGS_API_TOKEN", "DISCOGS_TOKEN"}, + DefaultInjection: &OfficialAPIKeyInjection{Kind: "header", Name: "Authorization", Prefix: "Discogs token="}, + }, + "podcast-index": { + Provider: "podcast-index", + EnvKeyName: "PODCASTINDEX_API_KEY", + VaultProvider: "podcast-index", + Aliases: []string{"podcastindex", "PODCASTINDEX_API_KEY"}, + DefaultInjection: &OfficialAPIKeyInjection{Kind: "header", Name: "X-Auth-Key"}, + }, + "spotify-web-api": { + Provider: "spotify-web-api", + EnvKeyName: "SPOTIFY_ACCESS_TOKEN", + VaultProvider: "spotify-web-api", + Aliases: []string{"spotify", "SPOTIFY_ACCESS_TOKEN", "SPOTIFY_API_TOKEN"}, + DefaultInjection: &OfficialAPIKeyInjection{Kind: "header", Name: "Authorization", Prefix: "Bearer "}, + }, + "setlist-lastfm": { + Provider: "setlist-lastfm", + EnvKeyName: "SETLISTFM_API_KEY", + VaultProvider: "setlist-lastfm", + Aliases: []string{"setlistfm", "setlist.fm", "SETLISTFM_API_KEY", "lastfm", "LASTFM_API_KEY"}, + DefaultInjection: &OfficialAPIKeyInjection{Kind: "header", Name: "x-api-key"}, + }, + "igdb": { + Provider: "igdb", + EnvKeyName: "TWITCH_API_TOKEN", + VaultProvider: "igdb", + Aliases: []string{"TWITCH_API_TOKEN", "IGDB_API_TOKEN", "twitch"}, + DefaultInjection: &OfficialAPIKeyInjection{Kind: "header", Name: "Authorization", Prefix: "Bearer "}, + }, + "nasdaq-data-link": { + Provider: "nasdaq-data-link", + EnvKeyName: "NASDAQ_DATA_LINK_API_KEY", + VaultProvider: "nasdaq-data-link", + Aliases: []string{"quandl", "NASDAQ_DATA_LINK_API_KEY"}, + DefaultInjection: &OfficialAPIKeyInjection{Kind: "query", Name: "api_key"}, + }, + "market-quotes-pack": { + Provider: "market-quotes-pack", + EnvKeyName: "ALPHAVANTAGE_API_KEY", + VaultProvider: "market-quotes-pack", + Aliases: []string{"alphavantage", "ALPHAVANTAGE_API_KEY", "polygon", "POLYGON_API_KEY", "massive", "MASSIVE_API_KEY", "tiingo", "TIINGO_API_KEY"}, + DefaultInjection: &OfficialAPIKeyInjection{Kind: "query", Name: "apikey"}, + }, + "ffiec-cdr": { + Provider: "ffiec-cdr", + EnvKeyName: "FFIEC_CDR_API_TOKEN", + VaultProvider: "ffiec-cdr", + Aliases: []string{"FFIEC_CDR_API_TOKEN", "FFIEC_CDR_API_KEY"}, + DefaultInjection: &OfficialAPIKeyInjection{Kind: "header", Name: "Authorization", Prefix: "Bearer "}, + }, + "youtube-data-api": { + Provider: "youtube-data-api", + EnvKeyName: "YOUTUBE_DATA_API_KEY", + VaultProvider: "youtube-data-api", + Aliases: []string{"youtube", "YOUTUBE_DATA_API_KEY", "YOUTUBE_API_KEY"}, + DefaultInjection: &OfficialAPIKeyInjection{Kind: "query", Name: "key"}, + }, + "threads-api": { + Provider: "threads-api", + EnvKeyName: "THREADS_ACCESS_TOKEN", + VaultProvider: "threads-api", + Aliases: []string{"threads", "THREADS_ACCESS_TOKEN", "THREADS_API_TOKEN"}, + DefaultInjection: &OfficialAPIKeyInjection{Kind: "header", Name: "Authorization", Prefix: "Bearer "}, + }, + "tumblr": { + Provider: "tumblr", + EnvKeyName: "TUMBLR_API_KEY", + VaultProvider: "tumblr", + Aliases: []string{"TUMBLR_API_KEY", "TUMBLR_CONSUMER_KEY"}, + DefaultInjection: &OfficialAPIKeyInjection{Kind: "query", Name: "api_key"}, + }, + "farcaster-hub": { + Provider: "farcaster-hub", + EnvKeyName: "NEYNAR_API_KEY", + VaultProvider: "farcaster-hub", + Aliases: []string{"neynar", "NEYNAR_API_KEY", "FARCASTER_HUB_API_KEY"}, + DefaultInjection: &OfficialAPIKeyInjection{Kind: "header", Name: "x-api-key"}, + }, + "product-hunt": { + Provider: "product-hunt", + EnvKeyName: "PRODUCTHUNT_API_TOKEN", + VaultProvider: "product-hunt", + Aliases: []string{"producthunt", "PRODUCTHUNT_API_TOKEN", "PRODUCT_HUNT_API_TOKEN"}, + DefaultInjection: &OfficialAPIKeyInjection{Kind: "header", Name: "Authorization", Prefix: "Bearer "}, + }, + "substack-notes-beehiiv": { + Provider: "substack-notes-beehiiv", + EnvKeyName: "BEEHIIV_API_KEY", + VaultProvider: "substack-notes-beehiiv", + Aliases: []string{"beehiiv", "BEEHIIV_API_KEY"}, + DefaultInjection: &OfficialAPIKeyInjection{Kind: "header", Name: "Authorization", Prefix: "Bearer "}, + }, } // NormalizeAPIKeyUserID normalizes a Hub API-key vault user identifier. @@ -486,7 +677,92 @@ func ResolveOfficialAPIProviderSpecForURL(providerOrAdapter, targetURL string) O return resolveWave3ProviderSpecForHostGo(base, host) } -func resolveWave3ProviderSpecForHostGo(base OfficialAPIKeyProviderSpec, _ string) OfficialAPIKeyProviderSpec { +func resolveWave3ProviderSpecForHostGo(base OfficialAPIKeyProviderSpec, host string) OfficialAPIKeyProviderSpec { + if base.Provider == "carrier-tracking-official" { + if host == "apis.usps.com" || host == "apis-tem.usps.com" { + return OfficialAPIKeyProviderSpec{ + Provider: "usps-addresses", + EnvKeyName: "USPS_ACCESS_TOKEN", + VaultProvider: "usps-addresses", + Aliases: []string{"usps", "usps-addresses", "USPS_ACCESS_TOKEN", "USPS_API_KEY"}, + DefaultInjection: &OfficialAPIKeyInjection{Kind: "header", Name: "Authorization", Prefix: "Bearer "}, + } + } + if host == "onlinetools.ups.com" || host == "wwwcie.ups.com" { + return OfficialAPIKeyProviderSpec{ + Provider: "ups", + EnvKeyName: "UPS_ACCESS_TOKEN", + VaultProvider: "ups", + Aliases: []string{"ups", "UPS_ACCESS_TOKEN", "UPS_API_KEY"}, + DefaultInjection: &OfficialAPIKeyInjection{Kind: "header", Name: "Authorization", Prefix: "Bearer "}, + } + } + if host == "apis.fedex.com" || host == "apis-sandbox.fedex.com" { + return OfficialAPIKeyProviderSpec{ + Provider: "fedex", + EnvKeyName: "FEDEX_ACCESS_TOKEN", + VaultProvider: "fedex", + Aliases: []string{"fedex", "FEDEX_ACCESS_TOKEN", "FEDEX_API_KEY"}, + DefaultInjection: &OfficialAPIKeyInjection{Kind: "header", Name: "Authorization", Prefix: "Bearer "}, + } + } + } + if base.Provider == "upcitemdb-barcodelookup" && (host == "api.barcodelookup.com" || strings.HasSuffix(host, ".barcodelookup.com")) { + return OfficialAPIKeyProviderSpec{ + Provider: "barcodelookup", + EnvKeyName: "BARCODELOOKUP_API_KEY", + VaultProvider: "barcodelookup", + Aliases: []string{"barcodelookup", "BARCODELOOKUP_API_KEY"}, + DefaultInjection: &OfficialAPIKeyInjection{Kind: "query", Name: "key"}, + } + } + if base.Provider == "setlist-lastfm" && (host == "ws.audioscrobbler.com" || strings.HasSuffix(host, ".audioscrobbler.com")) { + return OfficialAPIKeyProviderSpec{ + Provider: "lastfm", + EnvKeyName: "LASTFM_API_KEY", + VaultProvider: "lastfm", + Aliases: []string{"lastfm", "last.fm", "LASTFM_API_KEY"}, + DefaultInjection: &OfficialAPIKeyInjection{Kind: "query", Name: "api_key"}, + } + } + if base.Provider == "market-quotes-pack" { + if host == "www.alphavantage.co" || host == "alphavantage.co" { + return OfficialAPIKeyProviderSpec{ + Provider: "alphavantage", + EnvKeyName: "ALPHAVANTAGE_API_KEY", + VaultProvider: "alphavantage", + Aliases: []string{"alphavantage", "ALPHAVANTAGE_API_KEY"}, + DefaultInjection: &OfficialAPIKeyInjection{Kind: "query", Name: "apikey"}, + } + } + if host == "api.polygon.io" || host == "api.massive.com" { + return OfficialAPIKeyProviderSpec{ + Provider: "polygon", + EnvKeyName: "POLYGON_API_KEY", + VaultProvider: "polygon", + Aliases: []string{"polygon", "massive", "POLYGON_API_KEY", "MASSIVE_API_KEY"}, + DefaultInjection: &OfficialAPIKeyInjection{Kind: "header", Name: "Authorization", Prefix: "Bearer "}, + } + } + if host == "api.tiingo.com" { + return OfficialAPIKeyProviderSpec{ + Provider: "tiingo", + EnvKeyName: "TIINGO_API_KEY", + VaultProvider: "tiingo", + Aliases: []string{"tiingo", "TIINGO_API_KEY"}, + DefaultInjection: &OfficialAPIKeyInjection{Kind: "header", Name: "Authorization", Prefix: "Token "}, + } + } + } + if base.Provider == "substack-notes-beehiiv" && host == "api.beehiiv.com" { + return OfficialAPIKeyProviderSpec{ + Provider: "beehiiv", + EnvKeyName: "BEEHIIV_API_KEY", + VaultProvider: "beehiiv", + Aliases: []string{"beehiiv", "BEEHIIV_API_KEY"}, + DefaultInjection: &OfficialAPIKeyInjection{Kind: "header", Name: "Authorization", Prefix: "Bearer "}, + } + } return base } @@ -864,6 +1140,28 @@ func encodeURIComponentJSGo(s string) string { return sb.String() } +// encodeURLSearchParamsJSGo implements WHATWG application/x-www-form-urlencoded byte serialization +// matching JavaScript `new URLSearchParams([['k', s]]).toString().slice(2)` (`*` unescaped, `~` -> `%7E`, `' '` -> `+`). +func encodeURLSearchParamsJSGo(s string) string { + const hexUpper = "0123456789ABCDEF" + var sb strings.Builder + sb.Grow(len(s)) + for i := 0; i < len(s); i++ { + b := s[i] + if b == ' ' { + sb.WriteByte('+') + } else if (b >= 'A' && b <= 'Z') || (b >= 'a' && b <= 'z') || (b >= '0' && b <= '9') || + b == '*' || b == '-' || b == '.' || b == '_' { + sb.WriteByte(b) + } else { + sb.WriteByte('%') + sb.WriteByte(hexUpper[b>>4]) + sb.WriteByte(hexUpper[b&0x0F]) + } + } + return sb.String() +} + func isHexByteProviderGo(b byte) bool { return (b >= '0' && b <= '9') || (b >= 'A' && b <= 'F') || (b >= 'a' && b <= 'f') } @@ -962,10 +1260,12 @@ func RedactSecretsInBody(body string, secrets []string) string { } enc := encodeURIComponentJSGo(s) encPlus := strings.ReplaceAll(enc, "%20", "+") - usp := url.QueryEscape(s) + usp := encodeURLSearchParamsJSGo(s) uspSpacePct20 := strings.ReplaceAll(usp, "+", "%20") + goQ := url.QueryEscape(s) + goQSpacePct20 := strings.ReplaceAll(goQ, "+", "%20") seen := map[string]bool{s: true} - for _, v := range []string{enc, encPlus, usp, uspSpacePct20} { + for _, v := range []string{enc, encPlus, usp, uspSpacePct20, goQ, goQSpacePct20} { if v == "" || seen[v] { continue } diff --git a/internal/extract/platform_twins.go b/internal/extract/platform_twins.go index a54f9a0..b43df66 100644 --- a/internal/extract/platform_twins.go +++ b/internal/extract/platform_twins.go @@ -13,45 +13,48 @@ const ( ) var ( - reVTEXProdID = newLazyRegexp(`(?i)"productId"\s*:\s*"?([0-9A-Za-z_-]{1,64})"?`) - reSAPSiteOccBase = newLazyRegexp(`(?i)(?:occ/v2/|baseSite["']?\s*[:=]\s*["'])([a-z0-9_-]{2,40})`) - reSAPBackendBaseURL = newLazyRegexp(`(?i)occ-backend-base-url["']?\s*(?:content\s*=\s*|[:=]\s*)["'](https?://[^"'\s>]+)`) - reSAPBackendMetaRev = newLazyRegexp(`(?i)content\s*=\s*["'](https?://[^"'\s>]+)["'][^>]{0,120}name\s*=\s*["']occ-backend-base-url["']`) - reSAPPathCode = newLazyRegexp(`(?i)/p/([A-Za-z0-9_.-]{2,80})(?:[/?#]|$)`) - reOracleProdPath = newLazyRegexp(`(?i)/product/([A-Za-z0-9_.-]{2,80})(?:[/?#]|$)`) - reOracleRepoID = newLazyRegexp(`(?i)"repositoryId"\s*:\s*"([A-Za-z0-9_.-]{2,80})"`) - reHCLWCSStoreID = newLazyRegexp(`(?i)(?:/wcs/resources/store/|storeId["']?\s*[:=]\s*["']?)(\d{2,12})`) - reHCLWCSPartNum = newLazyRegexp(`(?i)(?:partNumber["']?\s*[:=]\s*["']|/p/)([A-Za-z0-9_.-]{2,80})`) - reSearchspringSite = newLazyRegexp(`(?i)(?:siteId["']?\s*[:=]\s*["']?|data-searchspring-site=["']|searchspring\.net/sites/|searchspring\.net/search/v\d+/js/searchspring\.catalog\.js\?)([a-z0-9_-]{3,32})`) - reYotpoScript = newLazyRegexp(`(?i)(?:staticw2\.yotpo\.com/([A-Za-z0-9]{12,64})/widget\.js|yotpo\.com/v1/loader/([A-Za-z0-9]{12,64}))`) - reYotpoAppKey = newLazyRegexp(`(?i)data-appkey=["']([A-Za-z0-9]{12,64})["']`) - reYotpoProductID = newLazyRegexp(`(?i)data-(?:yotpo-)?product-id=["']([A-Za-z0-9_.-]{1,80})["']`) - reStockistTag = newLazyRegexp(`(?i)(?:stockist\.co/api/v1/|data-stockist-widget-tag=["'])([a-z0-9_-]{2,40})`) - reStoremapperID = newLazyRegexp(`(?i)(?:storemapper\.co/api/users/|data-storemapper-id=["']|storemapper_user_id\s*[:=]\s*["']?)([A-Za-z0-9_-]{2,40})`) - reStoreRocketID = newLazyRegexp(`(?i)(?:storerocket\.io/api/user/|data-storerocket-id=["'])([A-Za-z0-9_-]{2,40})`) - reAlgoliaSearch = newLazyRegexp(`algoliasearch\(\s*["']([A-Za-z0-9]{6,20})["']\s*,\s*["']([a-zA-Z0-9]{16,64})["']`) - reAlgoliaIndex = newLazyRegexp(`(?i)(?:indexName|data-algolia-index)\s*[:=]\s*["']([A-Za-z0-9_.-]{1,80})["']`) - reBVPasskey = newLazyRegexp(`(?i)passkey["']?\s*[:=]\s*["']([A-Za-z0-9_-]{8,80})["']`) - reBVProductID = newLazyRegexp(`(?i)(?:data-bv-product-id=|productId["']?\s*[:=]\s*["'])([A-Za-z0-9_.-]{1,80})`) - rePRApiKey = newLazyRegexp(`(?i)(?:pr_api_key|api_key|apikey)["']?\s*[:=]\s*["']([A-Za-z0-9_-]{8,80})["']`) - rePRMerchantID = newLazyRegexp(`(?i)(?:pr_merchant_id|merchant_id|merchantId)["']?\s*[:=]\s*["']([A-Za-z0-9_-]{2,40})["']`) - rePRPageID = newLazyRegexp(`(?i)(?:pr_page_id|page_id|pageId)["']?\s*[:=]\s*["']([A-Za-z0-9_.-]{1,80})["']`) - reYextApiKey = newLazyRegexp(`(?i)(?:api_key|apiKey)["']?\s*[:=]\s*["']([A-Za-z0-9_-]{8,80})["']`) - reKhorosMsgID = newLazyRegexp(`(?i)/(?:td-p|m-p|ba-p|ta-p)/(\d{1,16})(?:[/?#]|$)`) - reEcwidScriptStore = newLazyRegexp(`(?i)app\.ecwid\.com/script\.js\?(\d{2,16})`) - reEcwidPublicTok = newLazyRegexp(`\b(public_[A-Za-z0-9_-]{12,80})\b`) - reMedusaPubKey = newLazyRegexp(`\b(pk_[A-Za-z0-9]{16,120})\b`) - reMedusaProdSlug = newLazyRegexp(`(?i)/products/([A-Za-z0-9_.-]{1,160})(?:[/?#]|$)`) - reBigCartelProd = newLazyRegexp(`(?i)^/product/([A-Za-z0-9_.-]{1,160})/?$`) - reSpreeProdPath = newLazyRegexp(`(?i)/products/([A-Za-z0-9_.-]{1,160})(?:[/?#]|$)`) - reStatusIOID = newLazyRegexp(`(?i)/pages/(?:history/)?([0-9a-f]{24})(?:[/?#]|$)`) - reBeamerProductID = newLazyRegexp(`(?i)\b_product_id\s*=\s*["']([A-Za-z0-9_-]{4,40})["']`) - reBeamerLanguage = newLazyRegexp(`(?i)\b_language\s*=\s*["']([A-Za-z_-]{2,10})["']`) - reHubSpotHubDBPath = newLazyRegexp(`(?i)(/(?:_hcms/api/hubdb/v3|hs/api/hubdb/v2)/tables/[A-Za-z0-9_.-]{1,120}/rows)(?:[?"'\s<]|$)`) - reCMSContentfulPath = newLazyRegexp(`(?i)^/spaces/[^/]+/environments/[^/]+/entries/[^/]+/?$`) - reCMSStoryblokPath = newLazyRegexp(`(?i)^/v2/cdn/stories/.+`) - reCMSBuilderPath = newLazyRegexp(`(?i)^/api/v3/content/[^/]+/[^/]+/?$`) - reCMSStrapiPath = newLazyRegexp(`(?i)^/api/([A-Za-z0-9_-]{1,64})/([A-Za-z0-9_.-]{1,128})/?$`) + reVTEXProdID = newLazyRegexp(`(?i)"productId"\s*:\s*"?([0-9A-Za-z_-]{1,64})"?`) + reSAPSiteOccBase = newLazyRegexp(`(?i)(?:occ/v2/|baseSite["']?\s*[:=]\s*["'])([a-z0-9_-]{2,40})`) + reSAPBackendBaseURL = newLazyRegexp(`(?i)occ-backend-base-url["']?\s*(?:content\s*=\s*|[:=]\s*)["'](https?://[^"'\s>]+)`) + reSAPBackendMetaRev = newLazyRegexp(`(?i)content\s*=\s*["'](https?://[^"'\s>]+)["'][^>]{0,120}name\s*=\s*["']occ-backend-base-url["']`) + reSAPPathCode = newLazyRegexp(`(?i)/p/([A-Za-z0-9_.-]{2,80})(?:[/?#]|$)`) + reOracleProdPath = newLazyRegexp(`(?i)/product/([A-Za-z0-9_.-]{2,80})(?:[/?#]|$)`) + reOracleRepoID = newLazyRegexp(`(?i)"repositoryId"\s*:\s*"([A-Za-z0-9_.-]{2,80})"`) + reHCLWCSStoreID = newLazyRegexp(`(?i)(?:/wcs/resources/store/|storeId["']?\s*[:=]\s*["']?)(\d{2,12})`) + reHCLWCSPartNum = newLazyRegexp(`(?i)(?:partNumber["']?\s*[:=]\s*["']|/p/)([A-Za-z0-9_.-]{2,80})`) + reSearchspringSite = newLazyRegexp(`(?i)(?:siteId["']?\s*[:=]\s*["']?|data-searchspring-site=["']|searchspring\.net/sites/|searchspring\.net/search/v\d+/js/searchspring\.catalog\.js\?)([a-z0-9_-]{3,32})`) + reYotpoScript = newLazyRegexp(`(?i)(?:staticw2\.yotpo\.com/([A-Za-z0-9]{12,64})/widget\.js|yotpo\.com/v1/loader/([A-Za-z0-9]{12,64}))`) + reYotpoAppKey = newLazyRegexp(`(?i)data-appkey=["']([A-Za-z0-9]{12,64})["']`) + reYotpoProductID = newLazyRegexp(`(?i)data-(?:yotpo-)?product-id=["']([A-Za-z0-9_.-]{1,80})["']`) + reStockistTag = newLazyRegexp(`(?i)(?:stockist\.co/api/v1/|data-stockist-widget-tag=["'])([a-z0-9_-]{2,40})`) + reStoremapperID = newLazyRegexp(`(?i)(?:storemapper\.co/api/users/|data-storemapper-id=["']|storemapper_user_id\s*[:=]\s*["']?)([A-Za-z0-9_-]{2,40})`) + reStoreRocketID = newLazyRegexp(`(?i)(?:storerocket\.io/api/user/|data-storerocket-id=["'])([A-Za-z0-9_-]{2,40})`) + reAlgoliaSearch = newLazyRegexp(`algoliasearch\(\s*["']([A-Za-z0-9]{6,20})["']\s*,\s*["']([a-zA-Z0-9]{16,64})["']`) + reAlgoliaIndex = newLazyRegexp(`(?i)(?:indexName|data-algolia-index)\s*[:=]\s*["']([A-Za-z0-9_.-]{1,80})["']`) + reBVPasskey = newLazyRegexp(`(?i)passkey["']?\s*[:=]\s*["']([A-Za-z0-9_-]{8,80})["']`) + reBVProductID = newLazyRegexp(`(?i)(?:data-bv-product-id=|productId["']?\s*[:=]\s*["'])([A-Za-z0-9_.-]{1,80})`) + rePRApiKey = newLazyRegexp(`(?i)(?:pr_api_key|api_key|apikey)["']?\s*[:=]\s*["']([A-Za-z0-9_-]{8,80})["']`) + rePRMerchantID = newLazyRegexp(`(?i)(?:pr_merchant_id|merchant_id|merchantId)["']?\s*[:=]\s*["']([A-Za-z0-9_-]{2,40})["']`) + rePRPageID = newLazyRegexp(`(?i)(?:pr_page_id|page_id|pageId)["']?\s*[:=]\s*["']([A-Za-z0-9_.-]{1,80})["']`) + reYextApiKey = newLazyRegexp(`(?i)(?:api_key|apiKey)["']?\s*[:=]\s*["']([A-Za-z0-9_-]{8,80})["']`) + reKhorosMsgID = newLazyRegexp(`(?i)/(?:td-p|m-p|ba-p|ta-p)/(\d{1,16})(?:[/?#]|$)`) + reEcwidScriptStore = newLazyRegexp(`(?i)app\.ecwid\.com/script\.js\?(\d{2,16})`) + reEcwidPublicTok = newLazyRegexp(`\b(public_[A-Za-z0-9_-]{12,80})\b`) + reMedusaPubKey = newLazyRegexp(`\b(pk_[A-Za-z0-9]{16,120})\b`) + reMedusaProdSlug = newLazyRegexp(`(?i)/products/([A-Za-z0-9_.-]{1,160})(?:[/?#]|$)`) + reBigCartelProd = newLazyRegexp(`(?i)^/product/([A-Za-z0-9_.-]{1,160})/?$`) + reSpreeProdPath = newLazyRegexp(`(?i)/products/([A-Za-z0-9_.-]{1,160})(?:[/?#]|$)`) + reStatusIOID = newLazyRegexp(`(?i)/pages/(?:history/)?([0-9a-f]{24})(?:[/?#]|$)`) + reBeamerProductID = newLazyRegexp(`(?i)\b_product_id\s*=\s*["']([A-Za-z0-9_-]{4,40})["']`) + reBeamerLanguage = newLazyRegexp(`(?i)\b_language\s*=\s*["']([A-Za-z_-]{2,10})["']`) + reHubSpotHubDBPath = newLazyRegexp(`(?i)(/(?:_hcms/api/hubdb/v3|hs/api/hubdb/v2)/tables/[A-Za-z0-9_.-]{1,120}/rows)(?:[?"'\s<]|$)`) + reCMSContentfulPath = newLazyRegexp(`(?i)^/spaces/[^/]+/environments/[^/]+/entries/[^/]+/?$`) + reCMSStoryblokPath = newLazyRegexp(`(?i)^/v2/cdn/stories/.+`) + reCMSBuilderPath = newLazyRegexp(`(?i)^/api/v3/content/[^/]+/[^/]+/?$`) + reCMSStrapiPath = newLazyRegexp(`(?i)^/api/([A-Za-z0-9_-]{1,64})/([A-Za-z0-9_.-]{1,128})/?$`) + reShopifyStorefrontToken = newLazyRegexp(`(?i)(?:storefrontAccessToken|x-shopify-storefront-access-token)["']?\s*[:=]\s*["']([A-Za-z0-9_-]{16,64})["']`) + reShopifyStorefrontAPIVer = newLazyRegexp(`(?i)/api/(20\d\d-(?:01|04|07|10))/graphql\.json`) + reShopifyProdHandlePath = newLazyRegexp(`(?i)/products/([A-Za-z0-9_.-]{1,160})(?:[/?#]|$)`) ) // PlatformTwinDiscoveryInput configures post-HTML companion twin discovery. @@ -107,7 +110,8 @@ func isAllowedPlatformTwinHost(adapterID, candHost, pageHost string) bool { "stockist", "storemapper", "storerocket", "yext-locator", "constructor-io", "bloomreach-discovery", "klevu", "coveo", "small-search", "okendo", "judge-me", "stamped-loox-junip", "dealer-locator-pack", - "vanilla-forums", "status-page-pack", "changelog-roadmap-pack", "headless-cms-delivery", "hubspot-cms": + "vanilla-forums", "status-page-pack", "changelog-roadmap-pack", "headless-cms-delivery", "hubspot-cms", + "shopify-storefront-graphql": return ch == ph default: return false @@ -160,6 +164,150 @@ func ScrubTwinURLSecrets(rawURL string) string { return u.String() } +func isValidCpscRecallNumGo(s string) bool { + if len(s) < 2 || len(s) > 24 { + return false + } + strippedLen := 0 + for i := 0; i < len(s); i++ { + c := s[i] + if c == '-' { + continue + } + if (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') { + strippedLen++ + continue + } + return false + } + return strippedLen >= 2 && strippedLen <= 24 +} + +func isValidCpscQueryTermGo(s string, maxLen int) bool { + if len(s) < 2 || len(s) > maxLen || strings.Contains(s, "..") { + return false + } + for i := 0; i < len(s); i++ { + c := s[i] + if (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || + c == '.' || c == '_' || c == '~' || c == ' ' || c == '-' { + continue + } + return false + } + return true +} + +func hasInvalidPercentEscapeGo(s string) bool { + for i := 0; i < len(s); i++ { + if s[i] == '%' { + if i+2 >= len(s) || !isHexDigitGo(s[i+1]) || !isHexDigitGo(s[i+2]) { + return true + } + i += 2 + } + } + return false +} + +func isHexDigitGo(b byte) bool { + return (b >= '0' && b <= '9') || (b >= 'a' && b <= 'f') || (b >= 'A' && b <= 'F') +} + +// CheckUnboundedTwinEndpointGuard blocks unfiltered saferproducts.gov/RestWebServices/Recall dumps (> 25 MiB) +// that lack a valid bounded RecallNumber, ProductType, or ProductDescription query parameter. +func CheckUnboundedTwinEndpointGuard(rawURL string) (blocked bool, message string) { + trimmed := strings.TrimSpace(rawURL) + u, err := url.Parse(trimmed) + if err != nil { + if schemeSep := strings.Index(trimmed, "://"); schemeSep > 0 { + rest := trimmed[schemeSep+3:] + slash := strings.IndexAny(rest, "/?#") + auth := rest + pathPart := "/" + if slash >= 0 { + auth = rest[:slash] + pathPart = rest[slash:] + } + if colon := strings.IndexByte(auth, ':'); colon >= 0 { + auth = auth[:colon] + } + h := strings.TrimSuffix(strings.ToLower(auth), ".") + if (h == "www.saferproducts.gov" || h == "saferproducts.gov") && hasInvalidPercentEscapeGo(pathPart) { + return true, "Malformed percent-encoding on saferproducts.gov endpoint." + } + } + return false, "" + } + host := strings.TrimSuffix(strings.ToLower(u.Hostname()), ".") + if host != "www.saferproducts.gov" && host != "saferproducts.gov" { + return false, "" + } + decodedPath := u.EscapedPath() + if decodedPath == "" { + decodedPath = u.Path + } + for pass := 0; pass < 2; pass++ { + next, pErr := url.PathUnescape(decodedPath) + if pErr != nil { + return true, "Malformed percent-encoding on saferproducts.gov endpoint." + } + if next == decodedPath { + break + } + decodedPath = next + } + var normBuf strings.Builder + prevSlash := false + for i := 0; i < len(decodedPath); i++ { + c := decodedPath[i] + if c == '/' || c == '\\' { + if !prevSlash { + normBuf.WriteByte('/') + prevSlash = true + } + continue + } + prevSlash = false + if c >= 'A' && c <= 'Z' { + c += 'a' - 'A' + } + normBuf.WriteByte(c) + } + normPath := normBuf.String() + if normPath != "/restwebservices/recall" && !strings.HasPrefix(normPath, "/restwebservices/recall/") { + return false, "" + } + q, qErr := url.ParseQuery(u.RawQuery) + if qErr != nil { + return true, "Unfiltered saferproducts.gov/RestWebServices/Recall endpoint exceeds 25 MiB and requires a bounded RecallNumber, ProductType, or ProductDescription query parameter (e.g., ?RecallNumber=24123)." + } + var recallMatches, productTypeMatches, productDescMatches []string + for k, vals := range q { + switch strings.ToLower(k) { + case "recallnumber": + for _, v := range vals { + recallMatches = append(recallMatches, strings.TrimSpace(v)) + } + case "producttype": + for _, v := range vals { + productTypeMatches = append(productTypeMatches, strings.TrimSpace(v)) + } + case "productdescription": + for _, v := range vals { + productDescMatches = append(productDescMatches, strings.TrimSpace(v)) + } + } + } + hasValidRecall := len(recallMatches) == 1 && isValidCpscRecallNumGo(recallMatches[0]) + hasValidType := len(recallMatches) == 0 && len(productTypeMatches) == 1 && isValidCpscQueryTermGo(productTypeMatches[0], 60) + hasValidDesc := len(recallMatches) == 0 && len(productDescMatches) == 1 && isValidCpscQueryTermGo(productDescMatches[0], 80) + if !hasValidRecall && !hasValidType && !hasValidDesc { + return true, "Unfiltered saferproducts.gov/RestWebServices/Recall endpoint exceeds 25 MiB and requires a bounded RecallNumber, ProductType, or ProductDescription query parameter (e.g., ?RecallNumber=24123)." + } + return false, "" +} + func validatePlatformCandidateURL(adapterID, rawCandidate, pageHost, selfHost string) string { trimmed := strings.TrimSpace(rawCandidate) if trimmed == "" || !IsSafeDeclarativeTwinURL(trimmed) { @@ -229,13 +377,57 @@ func extractPageKeyEmbeddedConfig(scan string) *pageKeyEmbeddedConfig { return nil } +func isGenericPlatformFallbackForCompanionTwin(existingID string) bool { + if strings.HasPrefix(existingID, "schema-") { + return true + } + switch existingID { + case "shopify", + "woocommerce", + "bigcommerce-store", + "squarespace-commerce", + "sfcc-demandware", + "shopware-magento", + "shopify-hydrogen", + "wix-stores", + "prestashop", + "legacy-cart", + "headless-commerce", + "square-online", + "aem", + "townnews-blox", + "brightspot", + "wordpress-vip-newspack", + "hubspot-cms", + "headless-cms-delivery", + "status-page-pack", + "changelog-roadmap-pack", + "big-cartel", + "lightspeed-ecom", + "medusa", + "saleor", + "vtex", + "sap-commerce-occ", + "oracle-commerce", + "hcl-websphere-commerce", + "spree-solidus", + "ecwid", + "khoros-lithium": + return true + } + return false +} + // DiscoverPlatformCompanionTwin inspects bounded HTML and headers to discover a safe companion twin endpoint. -// When `in.AllowPageKeyTwins` is false (default), `page-key` adapters (`algolia`, `bazaarvoice`, `powerreviews`, -// `yext-locator`) are NEVER scanned or returned. +// 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. func DiscoverPlatformCompanionTwin(rawHTML string, in PlatformTwinDiscoveryInput) PlatformTwinCandidate { - switch strings.ToLower(strings.TrimSpace(in.ExistingExtractorID)) { - case "arc-xp", "smartetailing": - return PlatformTwinCandidate{} + if existingID := strings.ToLower(strings.TrimSpace(in.ExistingExtractorID)); existingID != "" { + if !isGenericPlatformFallbackForCompanionTwin(existingID) { + return PlatformTwinCandidate{} + } } pageU, err := url.Parse(strings.TrimSpace(in.PageURL)) if err != nil || strings.ToLower(pageU.Scheme) != "https" || pageU.User != nil { @@ -493,6 +685,33 @@ func DiscoverPlatformCompanionTwin(rawHTML string, in PlatformTwinDiscoveryInput } } } + case "shopify-storefront-graphql": + var target string + if strings.TrimSpace(cfg.Endpoint) != "" { + target = validatePlatformCandidateURL("shopify-storefront-graphql", cfg.Endpoint, pageHost, in.SelfHost) + } else { + cand := fmt.Sprintf("https://%s/api/2024-10/graphql.json", pageHost) + target = validatePlatformCandidateURL("shopify-storefront-graphql", cand, pageHost, in.SelfHost) + } + if target != "" { + reqBody := buildShopifyStorefrontGraphQLBody(pageU.Path) + var hdrs map[string]string + if tok := strings.TrimSpace(cfg.APIKey); tok != "" { + hdrs = map[string]string{"X-Shopify-Storefront-Access-Token": tok} + } + return PlatformTwinCandidate{ + Matched: true, + AdapterID: "shopify-storefront-graphql", + FetchURL: target, + Method: "POST", + RequestBody: reqBody, + ContentType: "application/json", + Headers: hdrs, + Accept: "application/json", + RequiresPageKeyOptIn: true, + FormatMode: "json:shopify_storefront_graphql_json", + } + } } } @@ -588,6 +807,33 @@ func DiscoverPlatformCompanionTwin(rawHTML string, in PlatformTwinDiscoveryInput } } } + // #262 shopify-storefront-graphql (strictly same-origin per Rule 7; POST /api//graphql.json) + if strings.Contains(markerSlice, "storefrontAccessToken") || + strings.Contains(markerSlice, "StorefrontAccessToken") || + strings.Contains(markerSlice, "x-shopify-storefront-access-token") || + strings.Contains(configSlice, "storefrontAccessToken") { + if tm := reShopifyStorefrontToken.FindStringSubmatch(configSlice); len(tm) == 2 { + apiVer := "2024-10" + if vm := reShopifyStorefrontAPIVer.FindStringSubmatch(configSlice); len(vm) == 2 { + apiVer = vm[1] + } + cand := fmt.Sprintf("https://%s/api/%s/graphql.json", pageHost, apiVer) + if target := validatePlatformCandidateURL("shopify-storefront-graphql", cand, pageHost, in.SelfHost); target != "" { + return PlatformTwinCandidate{ + Matched: true, + AdapterID: "shopify-storefront-graphql", + FetchURL: target, + Method: "POST", + RequestBody: buildShopifyStorefrontGraphQLBody(pageU.Path), + ContentType: "application/json", + Headers: map[string]string{"X-Shopify-Storefront-Access-Token": tm[1]}, + Accept: "application/json", + RequiresPageKeyOptIn: true, + FormatMode: "json:shopify_storefront_graphql_json", + } + } + } + } } // --- Gate 2: Keyless (`pub`) platform multipliers --- @@ -987,3 +1233,21 @@ func isSingleDocHeadlessCMSEndpoint(prov, rawEndpoint string) bool { return isValidStrapiContentType(m[1]) && isValidStrapiDocID(m[2]) } } + +func buildShopifyStorefrontGraphQLBody(urlPath string) string { + if pm := reShopifyProdHandlePath.FindStringSubmatch(urlPath); len(pm) == 2 { + payload := map[string]any{ + "query": `query EdgeFetchStorefrontProduct($handle: String!) { product(handle: $handle) { id handle title description vendor productType onlineStoreUrl priceRange { minVariantPrice { amount currencyCode } maxVariantPrice { amount currencyCode } } images(first: 3) { edges { node { url altText } } } variants(first: 15) { edges { node { id title sku availableForSale price { amount currencyCode } } } } } }`, + "variables": map[string]string{ + "handle": pm[1], + }, + } + b, _ := json.Marshal(payload) + return string(b) + } + payload := map[string]any{ + "query": `query EdgeFetchStorefrontProducts { products(first: 20) { edges { node { id handle title description vendor productType onlineStoreUrl priceRange { minVariantPrice { amount currencyCode } maxVariantPrice { amount currencyCode } } images(first: 1) { edges { node { url altText } } } variants(first: 10) { edges { node { id title sku availableForSale price { amount currencyCode } } } } } } } }`, + } + b, _ := json.Marshal(payload) + return string(b) +} diff --git a/internal/extract/policy.go b/internal/extract/policy.go index ef10040..6ae3576 100644 --- a/internal/extract/policy.go +++ b/internal/extract/policy.go @@ -15,16 +15,19 @@ var AllowlistedUserAgentProfiles = map[string]string{ "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)", } // AdapterPolicy describes per-adapter politeness, User-Agent profile, host pacing, concurrency, strict robots, and cache TTL rules. 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"` + 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"` } // IsValidUserAgentHeaderValue verifies that a User-Agent string is 1..256 printable ASCII characters. @@ -131,6 +134,48 @@ func ResolveHostPolicyDefaults(host string) AdapterPolicy { MinIntervalMs: 2000, StrictRobots: true, } + case h == "dblp.org" || h == "www.dblp.org": + return AdapterPolicy{ + AdapterID: "dblp", + MinIntervalMs: 4000, + MaxConcurrent: 1, + StrictRobots: true, + } + case h == "medrxiv.org" || h == "www.medrxiv.org": + return AdapterPolicy{ + AdapterID: "biorxiv-medrxiv", + MinIntervalMs: 7000, + MaxConcurrent: 1, + StrictRobots: true, + } + case h == "zenodo.org" || h == "www.zenodo.org" || + h == "osf.io" || h == "www.osf.io": + return AdapterPolicy{ + AdapterID: "research-repo-pack", + MinIntervalMs: 10000, + MaxConcurrent: 1, + StrictRobots: true, + } + case h == "datadryad.org" || h == "www.datadryad.org": + return AdapterPolicy{ + AdapterID: "research-repo-pack", + MinIntervalMs: 5000, + MaxConcurrent: 1, + StrictRobots: true, + } + case h == "papers.ssrn.com": + return AdapterPolicy{ + AdapterID: "ssrn-nber", + MinIntervalMs: 5000, + MaxConcurrent: 1, + StrictRobots: true, + } + case h == "bgp.he.net": + return AdapterPolicy{ + AdapterID: "bgp-asn", + MaxFetchBytes: 1_048_576, + AllowTruncatedStream: true, + } default: return AdapterPolicy{} } @@ -249,10 +294,14 @@ func ResolveAdapterPolicyByID(adapterID string) AdapterPolicy { } pol.StrictRobots = true } + if id == "bgp-asn" { + pol.MaxFetchBytes = 1_048_576 + pol.AllowTruncatedStream = true + } return pol } -// ResolveAdapterPolicyForURL resolves merged built-in host policy + non-universal manifest policy for a URL. +// ResolveAdapterPolicyForURL resolves merged built-in host policy + manifest policy (including exact/wildcard universal manifests with explicit policy metadata) for a URL. func ResolveAdapterPolicyForURL(urlStr string) AdapterPolicy { u, err := url.Parse(strings.TrimSpace(urlStr)) if err != nil { @@ -279,22 +328,35 @@ func ResolveAdapterPolicyForURL(urlStr string) AdapterPolicy { cands = append(cands, a) } } + var fallbackAdapterID string for _, a := range reg.byHost[host] { + if fallbackAdapterID == "" && a != nil { + fallbackAdapterID = a.ID + } push(a, true) } for _, w := range reg.wildcards { switch w.kind { case "suffix": if strings.HasSuffix(host, w.pattern) && len(host) > len(w.pattern) { - push(w.adapter, false) + if fallbackAdapterID == "" && w.adapter != nil && !w.adapter.UniversalEngine { + fallbackAdapterID = w.adapter.ID + } + push(w.adapter, true) } case "prefix": if strings.HasPrefix(host, w.pattern) && len(host) > len(w.pattern) { - push(w.adapter, false) + if fallbackAdapterID == "" && w.adapter != nil && !w.adapter.UniversalEngine { + fallbackAdapterID = w.adapter.ID + } + push(w.adapter, true) } case "infix": if matchesHostPatternLinearGo(host, w.pattern) { - push(w.adapter, false) + if fallbackAdapterID == "" && w.adapter != nil && !w.adapter.UniversalEngine { + fallbackAdapterID = w.adapter.ID + } + push(w.adapter, true) } } } @@ -323,6 +385,9 @@ func ResolveAdapterPolicyForURL(urlStr string) AdapterPolicy { merged.StrictRobots = true } } + if merged.AdapterID == "" && fallbackAdapterID != "" { + merged.AdapterID = fallbackAdapterID + } return merged } diff --git a/internal/extract/round2_laserfiche.go b/internal/extract/round2_laserfiche.go index e40953f..1be8e58 100644 --- a/internal/extract/round2_laserfiche.go +++ b/internal/extract/round2_laserfiche.go @@ -215,14 +215,84 @@ func round2FormatLaserficheFolder(parsed any, host string, params map[string]str // WebLink serves only its "Cookies are not enabled" page and the JSON services need the repository // name, so there is no cookieless way to discover it. Return a clear, actionable error instead of // rendering the error page as content. -// round2IsLaserficheCookieError fingerprints WebLink's "Cookies are not enabled" CookieCheck page. +// round2IsLaserficheCookieError fingerprints WebLink's "Cookies are not enabled" CookieCheck page +// across both localized and unlocalized WebLink resource-token shells. func round2IsLaserficheCookieError(rawHTML string) bool { - return round2HasFold(rawHTML, "cookies are not enabled") && round2HasFold(rawHTML, "weblink", "laserfiche") + return (round2HasFold(rawHTML, "cookies are not enabled") && round2HasFold(rawHTML, "weblink", "laserfiche")) || + (round2HasFold(rawHTML, "str_error_page_title") && round2HasFold(rawHTML, "index_cookie_warning")) +} + +var round2RxLaserficheRepoName = newLazyRegexp(`\\?"repoName\\?"\s*:\s*\\?"([^"\\]{1,120})\\?"`) + +func round2RunLaserficheCrawlerPreRender(rawHTML string, base *url.URL, extractorID string) *DeclarativePostFetchResult { + if !round2HasFold(rawHTML, "crawlerprerender") || wave2dDevHasNegativeHTMLShell(rawHTML, base.String()) { + return nil + } + doc := ParseHTMLDoc(rawHTML, round2MaxHTMLBytes) + title := SanitizeSchemaPlainField(doc.Text("title"), 160) + if title != "" && (wave3GovIsNegativeTitle(title) || wave3GovIsGenericTitle(title)) { + return nil + } + if title == "" { + if cfg := wave3GovExtractBalancedJSONAfterNeedle(rawHTML, "str_json:", 8192); cfg != nil { + if rn := wave3GovPlain(cfg["repoName"], 120); rn != "" { + title = rn + } + } + if title == "" { + if m := round2RxLaserficheRepoName.FindStringSubmatch(rawHTML); len(m) >= 2 { + title = SanitizeSchemaPlainField(m[1], 120) + } + } + if title == "" { + title = "Laserfiche WebLink Repository" + } + } + var links []string + var recs []map[string]any + seen := map[string]bool{} + for _, a := range doc.Select("#CrawlerPreRender a[href], span#CrawlerPreRender a[href], a[href]", 80) { + if len(recs) >= round2MaxRecords { + break + } + txt := strings.TrimSpace(SanitizeSchemaPlainField(a.Text(), 240)) + if txt == "" || txt == "STR_HOME" || txt == "STR_SEARCH" || txt == "STR_MY_WEBLINK" || txt == "STR_ABOUT" { + continue + } + href := round2Abs(base, a.AttrOrEmpty("href")) + lowU := strings.ToLower(href) + if href == "" || seen[href] || (!strings.Contains(lowU, "docview.aspx") && !strings.Contains(lowU, "browse.aspx") && !strings.Contains(lowU, "electronicfile.aspx")) { + continue + } + seen[href] = true + links = append(links, href) + recs = append(recs, map[string]any{"source": "laserfiche-weblink", "title": txt, "url": href}) + } + if len(recs) == 0 { + return nil + } + var sb strings.Builder + sb.WriteString("# " + round2Inline(title) + "\n\n") + round2Bullet(&sb, "Platform", "Laserfiche WebLink (`"+base.Hostname()+"`)") + sb.WriteString("\n## Repository Contents\n\n") + for _, r := range recs { + sb.WriteString("- " + round2Link(r["title"].(string), r["url"].(string)) + "\n") + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Markdown: sb.String(), + Links: links, + ReplaceLinks: true, + Records: recs, + Total: round2Total(len(recs)), + Returned: round2Total(len(recs)), + } } func round2RunLaserficheMissingRepo(rawHTML string, base *url.URL, extractorID string) *DeclarativePostFetchResult { if !round2IsLaserficheCookieError(rawHTML) { - return nil + return round2RunLaserficheCrawlerPreRender(rawHTML, base, extractorID) } if base.Query().Get("repo") != "" { return nil @@ -231,6 +301,9 @@ func round2RunLaserficheMissingRepo(rawHTML string, base *url.URL, extractorID s if id == "" { id = base.Query().Get("startid") } + if id == "" { + return nil + } var sb strings.Builder sb.WriteString("# Laserfiche WebLink: missing `repo` parameter\n\n") sb.WriteString("This WebLink portal only serves its records to visitors with a session cookie, which EdgeFetch does not keep. " + diff --git a/internal/extract/round2_platforms.go b/internal/extract/round2_platforms.go index 547ad96..f3161bf 100644 --- a/internal/extract/round2_platforms.go +++ b/internal/extract/round2_platforms.go @@ -158,7 +158,7 @@ func round2Fingerprint(mode, rawHTML string) bool { case "chambermaster_html": return round2IsChamberMaster(rawHTML) case "laserfiche_missing_repo_html": - return round2IsLaserficheCookieError(rawHTML) + return round2IsLaserficheCookieError(rawHTML) || round2HasFold(rawHTML, "crawlerprerender") default: return hasJSONLDScriptToken(rawHTML) } diff --git a/internal/extract/round2_platforms_html.go b/internal/extract/round2_platforms_html.go index 4285f76..8c49713 100644 --- a/internal/extract/round2_platforms_html.go +++ b/internal/extract/round2_platforms_html.go @@ -13,8 +13,89 @@ func round2CleanTitleSuffix(s string) string { // ── #201 CivicPlus CivicEngage AgendaCenter ─────────────────────────────────────────────────── func round2IsCivicPlus(rawHTML string) bool { - return round2HasFold(rawHTML, "catagendarow") && - round2HasFold(rawHTML, "civicplus", "civicengage", "data-cprole", "/agendacenter/viewfile/") + if !round2HasFold(rawHTML, "civicplus", "civicengage", "data-cprole", "/agendacenter/viewfile/") { + return false + } + return round2HasFold(rawHTML, "catagendarow", "/documentcenter/view/", "/civicalerts.aspx") +} + +func round2RunCivicPlusDocsOrAlerts(doc *HTMLDoc, base *url.URL, site, extractorID string) *DeclarativePostFetchResult { + pathLower := strings.ToLower(base.Path) + isDocCenter := strings.HasPrefix(pathLower, "/documentcenter") + isAlerts := strings.HasPrefix(pathLower, "/civicalerts.aspx") + if !isDocCenter && !isAlerts { + return nil + } + var links []string + var recs []map[string]any + seen := map[string]bool{} + for _, a := range doc.Select("a[href]", 400) { + if len(recs) >= round2MaxRecords { + break + } + rawHref := a.AttrOrEmpty("href") + hrefLower := strings.ToLower(rawHref) + if isDocCenter && !strings.Contains(hrefLower, "/documentcenter/view/") { + continue + } + if isAlerts && (!strings.Contains(hrefLower, "/civicalerts.aspx") || !strings.Contains(hrefLower, "aid=")) { + continue + } + abs := round2Abs(base, rawHref) + label := SanitizeSchemaPlainField(a.Text(), 260) + if abs == "" || label == "" || seen[abs] { + continue + } + seen[abs] = true + kind := "Document" + if isAlerts { + kind = "Alert" + } + links = append(links, abs) + recs = append(recs, map[string]any{ + "title": label, + "url": abs, + "category": kind, + }) + } + if len(recs) == 0 { + return nil + } + title := "Document Center" + moduleLabel := "CivicPlus CivicEngage DocumentCenter" + colHeader := "Document" + if isAlerts { + title = "CivicAlerts" + moduleLabel = "CivicPlus CivicEngage CivicAlerts" + colHeader = "Alert" + } + if h1 := SanitizeSchemaPlainField(doc.Text("h1"), 160); h1 != "" { + title = h1 + } else if site != "" { + title += " — " + site + } + var sb strings.Builder + sb.WriteString("# " + round2Inline(title) + "\n\n") + round2Bullet(&sb, "Platform", moduleLabel+" (`"+base.Hostname()+"`)") + round2Bullet(&sb, "Items", round2Countf("%d", len(recs))) + sb.WriteString("\n") + round2TableHeader(&sb, []string{colHeader, "Link"}) + for _, r := range recs { + t := r["title"].(string) + u := r["url"].(string) + round2TableRow(&sb, []string{round2Cell(t), round2Link("View", u)}) + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Markdown: sb.String(), + Links: links, + ReplaceLinks: true, + Records: recs, + Total: round2Total(len(recs)), + Returned: round2Total(len(recs)), + Truncated: wave2dDevBoolPtr(false), + } } func round2RunCivicPlusAgenda(rawHTML string, base *url.URL, extractorID string) *DeclarativePostFetchResult { @@ -83,7 +164,7 @@ func round2RunCivicPlusAgenda(rawHTML string, base *url.URL, extractorID string) } } if len(rows) == 0 { - return nil + return round2RunCivicPlusDocsOrAlerts(doc, base, site, extractorID) } title := "Agenda Center" if site != "" { @@ -255,7 +336,9 @@ func round2RunCourseLeaf(rawHTML string, base *url.URL, extractorID string) *Dec // ── #242 ChamberMaster / GrowthZone member directories ─────────────────────────────────────── func round2IsChamberMaster(rawHTML string) bool { - return round2HasFold(rawHTML, "gz-") && round2HasFold(rawHTML, "chambermaster", "growthzone", "mni.hit.") + return (round2HasFold(rawHTML, "gz-") && round2HasFold(rawHTML, "chambermaster", "growthzone", "mni.hit.")) || + round2HasFold(rawHTML, `class="gz-card`, `class='gz-card`, `class="gz-list-card`, `class="gz-results-card`) || + round2HasFold(rawHTML, "mn-content", "mn-module-content", "mn-directory-list") } func round2ChamberAddress(n *HTMLNode) string { @@ -278,6 +361,9 @@ func round2RunChamberMaster(rawHTML string, base *url.URL, extractorID string) * if !round2IsChamberMaster(rawHTML) { return nil } + if strings.HasPrefix(strings.ToLower(base.Path), "/login") { + return nil + } doc := ParseHTMLDoc(rawHTML, round2MaxHTMLBytes) // Member detail page. if h1 := doc.First("h1.gz-pagetitle"); h1 != nil { @@ -375,6 +461,32 @@ func round2RunChamberMaster(rawHTML string, base *url.URL, extractorID string) * } recs = append(recs, rec) } + if len(recs) == 0 { + for _, sel := range []string{"div.mn-listing", "div.mn-event", "div.gz-events-card", "div.gz-card"} { + for _, m := range doc.Select(sel, 100) { + if len(recs) >= round2MaxRecords { + break + } + a := m.First("a[href]") + if a == nil { + continue + } + name := SanitizeSchemaPlainField(a.Text(), 200) + if name == "" { + continue + } + rec := map[string]any{"name": name} + if href := round2Abs(base, a.AttrOrEmpty("href")); href != "" { + rec["url"] = href + links = append(links, href) + } + if summary := SanitizeSchemaPlainField(m.Text("p"), 240); summary != "" { + rec["address"] = summary + } + recs = append(recs, rec) + } + } + } if len(recs) == 0 { return nil } diff --git a/internal/extract/round2_platforms_json.go b/internal/extract/round2_platforms_json.go index 393fe50..c684484 100644 --- a/internal/extract/round2_platforms_json.go +++ b/internal/extract/round2_platforms_json.go @@ -302,7 +302,61 @@ func round2FormatODSDataset(parsed any, host string) *DeclarativeFormattedDoc { metas, _ := obj["metas"].(map[string]any) def, _ := metas["default"].(map[string]any) if id == "" || def == nil { - return nil + results, hasList := obj["results"].([]any) + if !hasList || len(results) == 0 { + return nil + } + var recs []map[string]any + var sb strings.Builder + totalF, _ := jsonValueToFloat(obj["total_count"]) + total := max(int(totalF), len(results)) + title := host + " Opendatasoft catalog" + sb.WriteString("# " + round2Inline(title) + "\n\n") + round2Bullet(&sb, "Portal", "`"+host+"` (Opendatasoft)") + round2Bullet(&sb, "Datasets", round2Countf("%d total (showing %d)", total, min(len(results), round2MaxRecords))) + sb.WriteString("\n") + round2TableHeader(&sb, []string{"Dataset", "Dataset ID", "Publisher", "Modified"}) + for _, el := range results { + if len(recs) >= round2MaxRecords { + break + } + dm, ok := el.(map[string]any) + if !ok { + continue + } + did := round2Plain(dm["dataset_id"], 160) + dmetas, _ := dm["metas"].(map[string]any) + ddef, _ := dmetas["default"].(map[string]any) + if did == "" || ddef == nil { + continue + } + dt := round2Plain(ddef["title"], 240) + if dt == "" { + dt = did + } + dp := round2Plain(ddef["publisher"], 160) + dmMod := round2Plain(ddef["modified"], 40) + round2TableRow(&sb, []string{round2Cell(dt), "`" + did + "`", round2Cell(dp), round2Cell(sliceRunesMax(dmMod, 10))}) + rec := map[string]any{"datasetId": did, "title": dt} + if dp != "" { + rec["publisher"] = dp + } + if dmMod != "" { + rec["modified"] = dmMod + } + recs = append(recs, rec) + } + if len(recs) == 0 { + return nil + } + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: sb.String(), + Records: recs, + Total: round2Total(total), + Returned: round2Total(len(recs)), + Truncated: wave2dDevBoolPtr(total > len(recs)), + } } title := round2Plain(def["title"], 300) if title == "" { @@ -389,6 +443,9 @@ func round2FormatTaleo(parsed any, host string, params map[string]string) *Decla if unavailable, _ := obj["careerSectionUnAvailable"].(bool); unavailable { return nil } + if len(reqs) == 0 { + return nil + } total := len(reqs) if paging, ok := obj["pagingData"].(map[string]any); ok { if n, ok := jsonValueToFloat(paging["totalCount"]); ok && int(n) > total { @@ -497,7 +554,71 @@ func round2FormatShopifyStorefront(parsed any, host string) *DeclarativeFormatte data, _ := obj["data"].(map[string]any) prod, _ := data["product"].(map[string]any) if prod == nil { - return nil + prodConn, _ := data["products"].(map[string]any) + colTitle := "" + if prodConn == nil { + if col, ok := data["collection"].(map[string]any); ok { + colTitle = round2Plain(col["title"], 200) + prodConn, _ = col["products"].(map[string]any) + } + } + if prodConn == nil { + return nil + } + pNodes := wave3StoreExtractGraphQLNodes(prodConn) + if len(pNodes) == 0 { + return nil + } + var recs []map[string]any + var links []string + var sb strings.Builder + docTitle := "Shopify Storefront Catalog" + if colTitle != "" { + docTitle = colTitle + " — Storefront Catalog" + } + sb.WriteString("# " + round2Inline(docTitle) + "\n\n") + round2Bullet(&sb, "Store", "`"+host+"`") + sb.WriteString("\n") + round2TableHeader(&sb, []string{"Product", "Vendor", "Price", "Handle"}) + for _, p := range pNodes { + if len(recs) >= round2MaxRecords { + break + } + pt := round2Plain(p["title"], 200) + if pt == "" { + continue + } + ph := round2Plain(p["handle"], 160) + pv := round2Plain(p["vendor"], 120) + pu := wave2dDevValidHTTPS(jsonScalarToString(p["onlineStoreUrl"])) + if pu == "" && ph != "" && host != "" { + pu = "https://" + host + "/products/" + url.PathEscape(ph) + } + pp := "" + if pr, ok := p["priceRange"].(map[string]any); ok { + pp = round2Money(pr["minVariantPrice"]) + } + if pu != "" { + links = append(links, pu) + } + round2TableRow(&sb, []string{round2Link(pt, pu), round2Cell(pv), round2Cell(pp), round2Cell(ph)}) + rec := map[string]any{"title": pt, "handle": ph} + if pv != "" { + rec["vendor"] = pv + } + if pp != "" { + rec["price"] = pp + } + if pu != "" { + rec["url"] = pu + } + recs = append(recs, rec) + } + if len(recs) == 0 { + return nil + } + return &DeclarativeFormattedDoc{Title: docTitle, Markdown: sb.String(), Links: links, Records: recs, + Total: round2Total(len(pNodes)), Returned: round2Total(len(recs)), Truncated: wave2dDevBoolPtr(len(pNodes) > len(recs))} } title := round2Plain(prod["title"], 300) if title == "" { @@ -576,14 +697,13 @@ func round2FormatShopifyStorefront(parsed any, host string) *DeclarativeFormatte } var variants []map[string]any if vs, ok := prod["variants"].(map[string]any); ok { - nodes, _ := vs["nodes"].([]any) - if len(nodes) > 0 { + vNodes := wave3StoreExtractGraphQLNodes(vs) + if len(vNodes) > 0 { sb.WriteString("\n## Variants\n\n") round2TableHeader(&sb, []string{"Variant", "SKU", "Price", "Compare At", "Available"}) } - for _, n := range nodes { - vm, ok := n.(map[string]any) - if !ok || len(variants) >= round2MaxRecords { + for _, vm := range vNodes { + if len(variants) >= round2MaxRecords { continue } vt := round2Plain(vm["title"], 160) diff --git a/internal/extract/round2_platforms_schema.go b/internal/extract/round2_platforms_schema.go index 1172f59..cefb276 100644 --- a/internal/extract/round2_platforms_schema.go +++ b/internal/extract/round2_platforms_schema.go @@ -387,8 +387,16 @@ func round2Offers(v any) (string, string) { return strings.Join(prices, "; "), link } +var round2EventExclusive = map[string]bool{"product": true, "productgroup": true, "recipe": true} + func round2RunSchemaEvent(rawHTML string, base *url.URL, extractorID string) *DeclarativePostFetchResult { + if wave3SchemaIsExcludedEventHost(base.String()) { + return nil + } ld := round2CollectLD(rawHTML, false) + if len(ld.ofType(round2EventExclusive)) > 0 { + return nil + } events := ld.ofType(eventTypesSchemaGo) if len(events) == 0 { return nil @@ -477,10 +485,22 @@ func round2RunSchemaEvent(rawHTML string, base *url.URL, extractorID string) *De Total: round2Total(len(events)), Returned: round2Total(len(recs)), Truncated: wave2dDevBoolPtr(len(events) > len(recs))} } -// ── #236 Schema.org LocalBusiness (and subtypes) ───────────────────────────────────────────── +var round2LBExtraSubtypes = map[string]bool{ + "autorepair": true, "foodestablishment": true, "bakery": true, "cafeorcoffeeshop": true, + "barorpub": true, "dentist": true, "attorney": true, "legalservice": true, + "realestateagent": true, "sportsactivitylocation": true, "professionalservice": true, +} -var round2LBExclusive = map[string]bool{"product": true, "jobposting": true, "recipe": true, "newsarticle": true, - "blogposting": true, "article": true, "reportagenewsarticle": true} +var round2LBExclusive = map[string]bool{ + "product": true, "productgroup": true, "jobposting": true, "recipe": true, + "newsarticle": true, "blogposting": true, "article": true, "reportagenewsarticle": true, + "car": true, "vehicle": true, "motorcycle": true, "motorizedbicycle": true, + "course": true, "courseinstance": true, "educationaloccupationalprogram": true, + "dataset": true, "datacatalog": true, + "softwareapplication": true, "webapplication": true, "mobileapplication": true, + "medicalcondition": true, "drug": true, "physician": true, "medicalclinic": true, "medicalwebpage": true, + "menu": true, "menusection": true, "menuitem": true, +} func round2Hours(lb map[string]any) []string { var out []string @@ -507,14 +527,28 @@ func round2Hours(lb map[string]any) []string { } func round2RunSchemaLocalBusiness(rawHTML string, base *url.URL, extractorID string) *DeclarativePostFetchResult { + if wave3SchemaHasCommercePlatformMarkers(rawHTML) { + return nil + } ld := round2CollectLD(rawHTML, false) if len(ld.ofType(round2LBExclusive)) > 0 || len(ld.ofType(eventTypesSchemaGo)) > 0 { return nil } + for _, n := range ld.nodes { + if m, ok := n["hasMenu"].(map[string]any); ok && len(m) > 0 { + return nil + } + if arr, ok := n["hasMenu"].([]any); ok && len(arr) > 0 { + return nil + } + } var lb map[string]any lbType := "" for _, n := range ld.nodes { t := round2HasType(n, localBusinessTypesSchemaGo) + if t == "" { + t = round2HasType(n, round2LBExtraSubtypes) + } if t == "" { for _, raw := range normalizeSchemaTypesSchemaGo(n["@type"]) { low := strings.ToLower(raw) @@ -524,7 +558,8 @@ func round2RunSchemaLocalBusiness(rawHTML string, base *url.URL, extractorID str } } } - if t != "" && round2Plain(n["name"], 10) != "" && n["address"] != nil { + hasContactOrHours := n["address"] != nil || n["telephone"] != nil || n["openingHours"] != nil || n["openingHoursSpecification"] != nil || n["geo"] != nil + if t != "" && round2Plain(n["name"], 10) != "" && hasContactOrHours { lb, lbType = n, t break } diff --git a/internal/extract/round2_platforms_test.go b/internal/extract/round2_platforms_test.go index 36db808..99a77d8 100644 --- a/internal/extract/round2_platforms_test.go +++ b/internal/extract/round2_platforms_test.go @@ -44,22 +44,22 @@ func TestRound2JSONTwins(t *testing.T) { cases := []round2TwinCase{ { name: "dkan-metastore-list", - reqURL: "https://data.medicaid.gov/api/1/metastore/schemas/dataset/items?show-reference-ids=false", + reqURL: "https://data.healthcare.gov/api/1/metastore/schemas/dataset/items?show-reference-ids=false", fixture: "dkan_items.json", wantAdapter: "dkan", wantRecords: 3, - wantTitle: "data.medicaid.gov DKAN datasets", + wantTitle: "data.healthcare.gov DKAN datasets", needles: []string{"State Drug Utilization Data 1991", "`ae4d5347-5137-5f6c-b66c-3420fa0316d8`", "| csv |"}, }, { name: "dkan-dataset-page", - reqURL: "https://data.medicaid.gov/dataset/ae4d5347-5137-5f6c-b66c-3420fa0316d8", + reqURL: "https://data.healthcare.gov/dataset/ae4d5347-5137-5f6c-b66c-3420fa0316d8", wantAdapter: "dkan", - wantFetchURL: "https://data.medicaid.gov/api/1/metastore/schemas/dataset/items/ae4d5347-5137-5f6c-b66c-3420fa0316d8?show-reference-ids=false", + wantFetchURL: "https://data.healthcare.gov/api/1/metastore/schemas/dataset/items/ae4d5347-5137-5f6c-b66c-3420fa0316d8?show-reference-ids=false", }, { name: "dkan-datastore-query", - reqURL: "https://data.medicaid.gov/api/1/datastore/query/ae4d5347-5137-5f6c-b66c-3420fa0316d8/0?limit=3", + reqURL: "https://data.healthcare.gov/api/1/datastore/query/ae4d5347-5137-5f6c-b66c-3420fa0316d8/0?limit=3", fixture: "dkan_query.json", wantAdapter: "dkan", wantRecords: 3, diff --git a/internal/extract/wave2_upgraded_extractors.go b/internal/extract/wave2_upgraded_extractors.go index 9099a83..fed51c2 100644 --- a/internal/extract/wave2_upgraded_extractors.go +++ b/internal/extract/wave2_upgraded_extractors.go @@ -249,9 +249,23 @@ func wave2UpgradedHasCommonNegativeShell(rawHTML, baseURL string) bool { probe = probe[:65536] } lower := asciiLowerExtractString(probe) + hasRealBodyMarkers := hasJSONLDScriptToken(probe) || + strings.Contains(lower, " 65536 { + tail := rawHTML[65536:] + hasRealBodyMarkers = indexFoldASCIIExtract(tail, "= 0 || + indexFoldASCIIExtract(tail, "= 0 || + indexFoldASCIIExtract(tail, "= 0 || + indexFoldASCIIExtract(tail, "application/ld+json") >= 0 + } // WAF / Bot-defense / Challenge gates (Rule 3 & Red Lines) - if strings.Contains(lower, "cf-browser-verification") || - strings.Contains(lower, "challenge-platform") || + if (strings.Contains(lower, "challenge-platform") && len(rawHTML) < 16384 && !hasRealBodyMarkers) || + strings.Contains(lower, "cf-browser-verification") || strings.Contains(lower, "_cf_chl_opt") || strings.Contains(lower, "cf_chl_opt") || strings.Contains(lower, "attention required! | cloudflare") || @@ -1814,7 +1828,6 @@ func wave2UpgradedExtractPacerHTML(rawHTML, baseURL, extractorID string) *Declar strings.Contains(lowProbe, `type='password'`) || strings.Contains(lowProbe, "log in to pacer systems") || strings.Contains(lowProbe, "log in to pcl") || - strings.Contains(lowProbe, "csologin/login.jsf") || wave2UpgradedRxLoginHeading.MatchString(strings.TrimSpace(extractTitleLinearQuick(probe))) { return nil } @@ -1887,14 +1900,16 @@ func wave2UpgradedExtractStateCourtPortalsHTML(rawHTML, baseURL, extractorID str frag := "" if mainInner, ok := findElementInnerLinearDeclHTML(rawHTML, "main", nil, 0); ok { frag = mainInner - } else if divMain, ok := findElementInnerLinearDeclHTML(rawHTML, "div", func(attrStr string) bool { + } else if open, ok := findOpenTagLinearDeclHTML(rawHTML, "div", func(attrStr string) bool { idVal, _ := getAttrValueLinearDeclHTML(attrStr, "id") clsVal, _ := getAttrValueLinearDeclHTML(attrStr, "class") idLow := strings.ToLower(idVal) clsLow := strings.ToLower(clsVal) return idLow == "main" || idLow == "content" || strings.Contains(clsLow, "main-content") }, 0); ok { - frag = divMain + if divMain, okBal := extractBalancedDivAtDeclHTML(rawHTML, open.index); okBal { + frag = divMain + } } if frag != "" { frag = wave2UpgradedRxHeaderStrip.ReplaceAllString(frag, " ") diff --git a/internal/extract/wave2_upgraded_extractors_test.go b/internal/extract/wave2_upgraded_extractors_test.go index e1cc0f1..75cf951 100644 --- a/internal/extract/wave2_upgraded_extractors_test.go +++ b/internal/extract/wave2_upgraded_extractors_test.go @@ -215,6 +215,23 @@ func TestWave2UpgradedHTMLExtractorsAndModeRegistration(t *testing.T) { if csLogin.State != "login_wall" { t.Fatalf("login-gated PACER classified as %q (%s), want login_wall", csLogin.State, csLogin.Reason) } + + // M7: Public pacer.uscourts.gov Drupal page with header nav link to csologin/login.jsf must extract cleanly + pacerHeaderNavHTML := `Find a Case | PACER

Find a Case

Use the PACER Case Locator to search federal appellate, district, and bankruptcy court dockets nationwide.

` + if rawPN, okPN := RunWave2UpgradedHTMLMode("pacer_case_locator_html", pacerHeaderNavHTML, "https://pacer.uscourts.gov/find-case"); !okPN || !strings.Contains(rawPN, "Find a Case") { + t.Fatalf("pacer_case_locator_html must ignore csologin/login.jsf in header nav: ok=%v", okPN) + } + + // M7: txcourts.gov >= 16 KB Umbraco court page with passive challenge-platform script must extract cleanly + txCourtsHTML := `Orders & Opinions | Texas Judicial Branch

Orders & Opinions

` + strings.Repeat("The Supreme Court of Texas issued orders and opinions on pending appellate dockets today. ", 200) + `

` + rawTX, okTX := RunWave2UpgradedHTMLMode("state_court_portals_html", txCourtsHTML, "https://www.txcourts.gov/supreme/orders-opinions/") + if !okTX { + t.Fatalf("state_court_portals_html must not false-positive on passive challenge-platform in >=16KB txcourts.gov page: ok=%v", okTX) + } + resTX := wave2UpgradedDecodeHTML(t, rawTX) + if !strings.Contains(resTX.Markdown, "Orders & Opinions") { + t.Fatalf("expected decoded txcourts.gov markdown to contain Orders & Opinions, got %q", resTX.Markdown) + } } func TestWave2UpgradedJSONFormattersAndNegatives(t *testing.T) { @@ -378,3 +395,15 @@ func TestWave2UpgradedFixturesPositiveAndFourNegatives(t *testing.T) { } } } + +func TestWave2StateCourtPortalsNestedDivContent(t *testing.T) { + txHTML := `TJB | SC | Orders & Opinions
Supreme Court

Orders & Opinions

The Supreme Court of Texas issues weekly orders and opinions on Friday mornings throughout the term.

` + outRaw, ok := RunWave2UpgradedHTMLMode("state_court_portals_html", txHTML, "https://www.txcourts.gov/supreme/orders-opinions/") + if !ok { + t.Fatalf("state_court_portals_html failed on nested div#content (txcourts.gov)") + } + res := wave2UpgradedDecodeHTML(t, outRaw) + if !strings.Contains(res.Markdown, "weekly orders and opinions") { + t.Fatalf("state_court_portals_html truncated nested div#content prematurely: %s", res.Markdown) + } +} diff --git a/internal/extract/wave2a_extractors.go b/internal/extract/wave2a_extractors.go index a367122..9f0cd1b 100644 --- a/internal/extract/wave2a_extractors.go +++ b/internal/extract/wave2a_extractors.go @@ -222,6 +222,12 @@ func FormatWave2aJSONPublic(mode string, rawBytes []byte, origURL string, htmlTo if mode == "changelog_beamer_html" { return formatChangelogBeamerHTML(rawBytes, origURL, htmlToMD) } + if IsRound2JSONMode(mode) { + return FormatRound2JSONDoc(mode, rawBytes, nil, origURL) + } + if IsWave3StoreAddonsJSONMode(mode) { + return FormatWave3StoreAddonsJSONDoc(mode, rawBytes, nil, origURL) + } if !isWave2aOr2bJSONMode(mode) { return nil, false } diff --git a/internal/extract/wave2b_platform_twins_test.go b/internal/extract/wave2b_platform_twins_test.go index e0ae528..3b61243 100644 --- a/internal/extract/wave2b_platform_twins_test.go +++ b/internal/extract/wave2b_platform_twins_test.go @@ -93,4 +93,30 @@ func TestWave2bCommerceRoutingCollisionsAndPlatformTwins(t *testing.T) { if !strings.Contains(scrubbed, "limit=25") { t.Fatalf("ScrubTwinURLSecrets dropped non-secret query param: %q", scrubbed) } + + // 7. M7 preemption guard: domain-specific ExistingExtractorIDs must suppress companion discovery (aem, shopify-storefront-graphql), + // while generic platform fallbacks (shopify, aem, schema-*) continue allowing companion discovery. + aemAndStorefrontHTML := `
` + for _, domainSpecificID := range []string{ + "gs1-us-datahub", + "recharge-bold-subscriptions", + "suspension-cockpit-compat", + "bicycle-brake-docs", + "cargo-ebike-oems", + "arc-xp", + "smartetailing", + } { + if suppressed := DiscoverPlatformCompanionTwin(aemAndStorefrontHTML, PlatformTwinDiscoveryInput{ + PageURL: "https://www.example.com/products/widget", + ExistingExtractorID: domainSpecificID, + }); suppressed.Matched { + t.Fatalf("expected domain-specific ExistingExtractorID=%q to suppress companion twin, got %+v", domainSpecificID, suppressed) + } + } + if genericShopify := DiscoverPlatformCompanionTwin(aemAndStorefrontHTML, PlatformTwinDiscoveryInput{ + PageURL: "https://www.example.com/products/widget", + ExistingExtractorID: "shopify", + }); !genericShopify.Matched || genericShopify.AdapterID != "shopify-storefront-graphql" { + t.Fatalf("expected generic ExistingExtractorID=shopify to keep shopify-storefront-graphql companion discovery working, got %+v", genericShopify) + } } diff --git a/internal/extract/wave2c_econ.go b/internal/extract/wave2c_econ.go index 22b2c1c..5e6d1a3 100644 --- a/internal/extract/wave2c_econ.go +++ b/internal/extract/wave2c_econ.go @@ -1008,19 +1008,28 @@ func wave2cEconFormatCensusJSON(parsed any, origURL string) (*DeclarativeFormatt return nil, false } var headers []string + isIntlTrade := strings.Contains(strings.ToLower(origURL), "/intltrade/") for _, h := range headerRow { col := wave2cEconPlain(h, 64) if col == "" { col = fmt.Sprintf("col_%d", len(headers)) } + switch strings.ToUpper(col) { + case "I_COMMODITY", "E_COMMODITY", "GEN_VAL_MO", "CON_VAL_MO", "ALL_VAL_MO", "CTY_CODE", "CTY_NAME": + isIntlTrade = true + } headers = append(headers, col) if len(headers) >= 12 { break } } tableCols := len(headers) - if tableCols > 6 { - tableCols = 6 + maxTableCols := 6 + if isIntlTrade { + maxTableCols = 8 + } + if tableCols > maxTableCols { + tableCols = maxTableCols } totalRows := len(matrix) - 1 var recs []map[string]any @@ -1034,6 +1043,9 @@ func wave2cEconFormatCensusJSON(parsed any, origURL string) (*DeclarativeFormatt continue } rec := map[string]any{"source": "census"} + if isIntlTrade { + rec["dataset"] = "intltrade" + } tRow := make([]string, tableCols) for c := 0; c < len(headers) && c < len(rowArr); c++ { val := wave2cEconPlain(rowArr[c], 160) @@ -1049,10 +1061,17 @@ func wave2cEconFormatCensusJSON(parsed any, origURL string) (*DeclarativeFormatt return nil, false } title := "U.S. Census Data Query" + if isIntlTrade { + title = "U.S. Census International Trade" + } if u, err := url.Parse(origURL); err == nil { p := strings.Trim(u.Path, "/") if p != "" { - title = "U.S. Census: " + p + if isIntlTrade { + title = "U.S. Census International Trade: " + p + } else { + title = "U.S. Census: " + p + } } } blocks := []string{ @@ -1124,6 +1143,23 @@ func wave2cEconFormatCensusJSON(parsed any, origURL string) (*DeclarativeFormatt links = append(links, lp) } } + if cDS, okCDS := m["c_dataset"].([]any); okCDS && len(cDS) > 0 { + var parts []string + for _, p := range cDS { + if ps := wave2cEconPlain(p, 40); ps != "" { + parts = append(parts, ps) + } + } + if len(parts) > 0 { + rec["datasetPath"] = strings.Join(parts, "/") + } + } + for _, linkKey := range []string{"c_variablesLink", "c_examplesLink"} { + if extraLink := SanitizeSchemaHTTPSURL(m[linkKey], origURL); extraLink != "" && !seen[extraLink] { + seen[extraLink] = true + links = append(links, extraLink) + } + } recs = append(recs, rec) rows = append(rows, []string{dTitle, vintage, mod, ident}) } diff --git a/internal/extract/wave3_community.go b/internal/extract/wave3_community.go new file mode 100644 index 0000000..ce64531 --- /dev/null +++ b/internal/extract/wave3_community.go @@ -0,0 +1,2410 @@ +package extract + +import ( + "bytes" + "encoding/json" + "fmt" + stdhtml "html" + "net/url" + "strconv" + "strings" + "time" +) + +const ( + wave3CommMaxHTMLBytes = 2 * 1024 * 1024 + wave3CommMaxJSONBytes = 4 * 1024 * 1024 + wave3CommMaxRecords = 30 +) + +var ( + wave3CommRxNotFoundTitle = newLazyRegexp(`(?i)(?:^|\b)(?:404|410|page\s+not\s+found|page\s+cannot\s+be\s+found|not\s+found|error\s*404|we\s+couldn'?t\s+find\s+that\s+page|we'?re\s+unable\s+to\s+find\s+the\s+page|access\s+denied|request\s+(?:rejected|blocked)|could\s+not\s+be\s+satisfied|unauthorized|attention\s+required|just\s+a\s+moment|403\s+forbidden|forbidden|making\s+sure\s+you(?:'|'|')?re\s+not\s+a\s+bot!?)(?:\b|$)`) + wave3CommRxMaintTitle = newLazyRegexp(`(?i)(?:scheduled\s+maintenance|temporarily\s+unavailable|service\s+unavailable|site\s+maintenance|under\s+maintenance|502\s+bad\s+gateway|503\s+service|down\s+for\s+maintenance)`) + wave3CommRxErrorTitle = newLazyRegexp(`(?i)^(?:(?:(?:401|403|404|410|429|500|502|503)\s+)?(?:internal\s+)?server\s+error|application\s+error|system\s+error|unexpected\s+error|error\s+page|(?:401|403|404|410|429|500|502|503|http\s+\d{3})\s+error|error\s+(?:401|403|404|410|429|500|502|503)|error)(?:\s*[|\-\x{2013}\x{2014}:]\s*.*)?$|^.*(?:\s*[|\-\x{2013}\x{2014}:]\s*error)$`) + wave3CommRxLoginTitle = newLazyRegexp(`(?i)^(?:log\s*in|sign\s+in|login|member\s+login|authentication\s+required|sso\s+login|single\s+sign[- ]on|web\s+login|account\s+login)(?:\s*[|\-\x{2013}\x{2014}:]\s*.*)?$`) + wave3CommRxGenericHead = newLazyRegexp(`(?i)^(?:loading\.{0,3}|home|welcome|search|calendar|news|events|menu|navigation|wrong\s+document\s+context!?|athlinks|misskey)$`) + wave3CommRxISODate = newLazyRegexp(`^(\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01]))(?:$|T\d{2}:\d{2}| \d{2}:\d{2})`) + wave3CommRxSlashDate = newLazyRegexp(`^(\d{1,2})/(\d{1,2})/(\d{4})(?:\s+(\d{1,2}:\d{2}))?$`) + wave3CommRxASPNetDate = newLazyRegexp(`^/Date\((-?\d+)([+-]\d{4})?\)/$`) + wave3CommRxSpace = newLazyRegexp(`[ \t\r\n]+`) + wave3CommRxTitleSep = newLazyRegexp(`\s*\|\s*|\s+[-\x{2013}\x{2014}]\s+`) +) + +func init() { + for _, mode := range []string{ + "wild_apricot_html", + "association_ams_html", + "runsignup_html", + "bikereg_usacycling_html", + "race_results_pack_html", + "lemmy_html", + "peertube_html", + "fediverse_pack_html", + } { + m := mode + RegisterExternalHTMLModeLazy(m, func(rawHTML, baseURL string, _ func() string, extractorID string) *DeclarativePostFetchResult { + return Wave3CommunityRunHTML(m, rawHTML, baseURL, extractorID) + }) + } +} + +// IsWave3CommunityHTMLMode reports whether mode is handled by Category E Community HTML extractors (#243-#250). +func IsWave3CommunityHTMLMode(mode string) bool { + switch mode { + case "wild_apricot_html", + "association_ams_html", + "runsignup_html", + "bikereg_usacycling_html", + "race_results_pack_html", + "lemmy_html", + "peertube_html", + "fediverse_pack_html": + return true + default: + return false + } +} + +// IsWave3CommunityJSONMode reports whether mode is handled by Category E Community JSON formatters (#245-#250). +func IsWave3CommunityJSONMode(mode string) bool { + switch mode { + case "runsignup_json", + "bikereg_json", + "lemmy_json", + "peertube_json", + "fediverse_pack_json": + return true + default: + return false + } +} + +func wave3CommDefaultExtractorID(mode string) string { + switch mode { + case "wild_apricot_html": + return "wild-apricot" + case "association_ams_html": + return "association-ams-pack" + case "runsignup_html", "runsignup_json": + return "runsignup" + case "bikereg_usacycling_html", "bikereg_json": + return "bikereg-usacycling" + case "race_results_pack_html": + return "race-results-pack" + case "lemmy_html", "lemmy_json": + return "lemmy" + case "peertube_html", "peertube_json": + return "peertube" + case "fediverse_pack_html", "fediverse_pack_json": + return "fediverse-pack" + default: + return "" + } +} + +func wave3CommMatchesModePrefilter(mode, rawHTML string) bool { + probe180K := rawHTML + if len(probe180K) > 180_000 { + probe180K = probe180K[:180_000] + } + switch mode { + case "chambermaster_growthzone_html": + probe160K := rawHTML + if len(probe160K) > 160_000 { + probe160K = probe160K[:160_000] + } + return containsAnyFoldASCIIExtract(probe160K, + "mn-content", "mn-directory-list", "mn-module-content", + "gz-card", "gz-list-card", "gz-directory", "gz-member", "gz-al-", + "cm-cms-", "chambermaster", "growthzone", "cms-members-results", "cms-events-results", + ) + case "wild_apricot_html": + return containsAnyFoldASCIIExtract(probe180K, "wagadget", "wildapricot", `id="idevent`, `id='idevent`, "idevent=", "var idevent") + case "association_ams_html": + return containsAnyFoldASCIIExtract(probe180K, + "noviams", "novi-file-uploads", "novi-core-assets", "novi-content-wrapper", "novicon-", + "personifycorp", "personify.com", "personifycloud", "personify_orig", "memberclicks", "/external/wcpages/", "wc-eventcalendar", + "site-ym", "yourmembership", "ym-event", "ym-directory", + ) + case "runsignup_html": + return hasJSONLDScriptToken(rawHTML) || containsAnyFoldASCIIExtract(rawHTML, "runsignup", "race") + case "bikereg_usacycling_html": + return hasJSONLDScriptToken(rawHTML) || containsAnyFoldASCIIExtract(rawHTML, "data-page", "bikereg", "usacycling", "sport80") + case "lemmy_html": + return containsAnyFoldASCIIExtract(probe180K, "isodata", "lemmy") + case "peertube_html": + return containsAnyFoldASCIIExtract(probe180K, "peertube") + case "fediverse_pack_html": + return containsAnyFoldASCIIExtract(probe180K, "page-entry-single", "entry--single", "entry__meta", "magazine-inline", "comments-tree", "entry-comment") + default: + return true + } +} + +// Wave3CommunityRunHTML executes a Category E Community HTML extractor and returns DeclarativePostFetchResult. +func Wave3CommunityRunHTML(mode, rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + if !IsWave3CommunityHTMLMode(mode) || len(rawHTML) == 0 || strings.IndexByte(rawHTML, '<') < 0 || strings.IndexByte(rawHTML, '>') < 0 { + return nil + } + if len(rawHTML) > wave3CommMaxHTMLBytes { + rawHTML = truncateUTF8SafeFullDocGo(rawHTML, wave3CommMaxHTMLBytes) + } + trimmed := strings.TrimLeft(rawHTML, " \t\r\n") + if trimmed == "" || trimmed[0] == '{' || trimmed[0] == '[' { + return nil + } + if extractorID == "" { + extractorID = wave3CommDefaultExtractorID(mode) + } + if !wave3CommMatchesModePrefilter(mode, rawHTML) { + return nil + } + if wave3CommHasNegativeShell(rawHTML, baseURL) { + return nil + } + var res *DeclarativePostFetchResult + switch mode { + case "wild_apricot_html": + res = wave3CommExtractWildApricotHTML(rawHTML, baseURL, extractorID) + case "association_ams_html": + res = wave3CommExtractAssociationAMSHTML(rawHTML, baseURL, extractorID) + case "runsignup_html": + res = wave3CommExtractRunSignupHTML(rawHTML, baseURL, extractorID) + case "bikereg_usacycling_html": + res = wave3CommExtractBikeRegUSACyclingHTML(rawHTML, baseURL, extractorID) + case "race_results_pack_html": + res = wave3CommExtractRaceResultsPackHTML(rawHTML, baseURL, extractorID) + case "lemmy_html": + res = wave3CommExtractLemmyHTML(rawHTML, baseURL, extractorID) + case "peertube_html": + res = wave3CommExtractPeerTubeHTML(rawHTML, baseURL, extractorID) + case "fediverse_pack_html": + res = wave3CommExtractFediversePackHTML(rawHTML, baseURL, extractorID) + } + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return nil + } + return res +} + +// FormatWave3CommunityJSONDoc formats a Category E Community JSON twin payload into DeclarativeFormattedDoc. +func FormatWave3CommunityJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool) { + if !IsWave3CommunityJSONMode(mode) || len(raw) == 0 || len(raw) > wave3CommMaxJSONBytes { + return nil, false + } + payload := bytes.TrimSpace(bytes.TrimPrefix(raw, []byte("\xEF\xBB\xBF"))) + if len(payload) == 0 || (payload[0] != '{' && payload[0] != '[') { + return nil, false + } + parsed, ok := decodeJSONWithNumbers(payload) + if !ok || parsed == nil { + return nil, false + } + var doc *DeclarativeFormattedDoc + var handled bool + switch mode { + case "runsignup_json": + doc, handled = wave3CommFormatRunSignupJSON(parsed, origURL) + case "bikereg_json": + doc, handled = wave3CommFormatBikeRegJSON(parsed, origURL) + case "lemmy_json": + doc, handled = wave3CommFormatLemmyJSON(parsed, origURL) + case "peertube_json": + doc, handled = wave3CommFormatPeerTubeJSON(parsed, origURL) + case "fediverse_pack_json": + doc, handled = wave3CommFormatFediversePackJSON(parsed, params, origURL) + } + if !handled || doc == nil || strings.TrimSpace(doc.Markdown) == "" { + return nil, false + } + return wave3CommFinalizeDoc(doc), true +} + +// FormatWave3CommunityJSONMode formats a Category E Community JSON payload and returns JSON-marshaled DeclarativeFormattedDoc. +func FormatWave3CommunityJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool) { + doc, ok := FormatWave3CommunityJSONDoc(mode, raw, params, origURL) + if !ok || doc == nil { + return "", false + } + encoded, err := json.Marshal(doc) + if err != nil { + return "", false + } + return string(encoded), true +} + +// ── Shared Hygiene & Parsing Helpers ────────────────────────────────────────────────────────────── + +func wave3CommIntPtr(v int) *int { return &v } +func wave3CommBoolPtr(v bool) *bool { return &v } + +func wave3CommFinalizeDoc(doc *DeclarativeFormattedDoc) *DeclarativeFormattedDoc { + if doc == nil { + return nil + } + if len(doc.Records) > wave3CommMaxRecords { + if doc.Total == nil { + doc.Total = wave3CommIntPtr(len(doc.Records)) + } + doc.Records = doc.Records[:wave3CommMaxRecords] + doc.Returned = wave3CommIntPtr(len(doc.Records)) + doc.Truncated = wave3CommBoolPtr(true) + if doc.NextCursor == "" { + doc.NextCursor = strconv.Itoa(len(doc.Records)) + } + } + if sanitized, ok := sanitizeDeclarativeFormattedDocGo(doc); ok && sanitized != nil { + return sanitized + } + return nil +} + +func wave3CommIsNegativeURL(baseURL string) bool { + uLower := strings.ToLower(strings.TrimSpace(baseURL)) + if uLower == "" { + return false + } + if strings.Contains(uLower, "/404") || + strings.Contains(uLower, "/not-found") || + strings.Contains(uLower, "/maintenance") || + strings.Contains(uLower, "/sys/login") || + strings.Contains(uLower, "error=true") || + strings.Contains(uLower, "error=1") || + strings.Contains(uLower, "404.") { + return true + } + pathOnly := uLower + if idx := strings.Index(pathOnly, "://"); idx >= 0 { + rest := pathOnly[idx+3:] + if slash := strings.IndexByte(rest, '/'); slash >= 0 { + pathOnly = rest[slash:] + } else { + pathOnly = "/" + } + } + if cut := strings.IndexAny(pathOnly, "?#"); cut >= 0 { + pathOnly = pathOnly[:cut] + } + return strings.HasSuffix(pathOnly, "/error") || + strings.Contains(pathOnly, "/error/") || + strings.HasSuffix(pathOnly, "/error.html") || + strings.HasSuffix(pathOnly, "/error.htm") || + strings.HasSuffix(pathOnly, "/error.aspx") || + strings.HasSuffix(pathOnly, "/login") || + strings.HasSuffix(pathOnly, "/signin") || + strings.HasSuffix(pathOnly, "/sign-in") || + strings.Contains(pathOnly, "/login/") +} + +func wave3CommLowerProbe(rawHTML string, maxBytes int) string { + if len(rawHTML) > maxBytes { + rawHTML = rawHTML[:maxBytes] + } + return asciiLowerExtractString(rawHTML) +} + +func wave3CommContainsAny(lower string, needles ...string) bool { + for _, n := range needles { + if strings.Contains(lower, n) { + return true + } + } + return false +} + +func wave3CommHasNegativeShell(rawHTML, baseURL string) bool { + if wave3CommIsNegativeURL(baseURL) { + return true + } + probe := rawHTML + if len(probe) > 65536 { + probe = probe[:65536] + } + lower := asciiLowerExtractString(probe) + // WAF, Cloudflare, Anubis PoW, and access-denied interstitials + if wave3CommContainsAny(lower, + "cf-browser-verification", + "challenge-platform", + "_cf_chl_opt", + "cf_chl_opt", + "attention required! | cloudflare", + "errors.edgesuite.net", + "you don't have permission to access", + "access denied", + "403 forbidden", + "window.kpsdk", + "kp_uidz", + "_incapsula_resource", + "incapsula incident", + `id="anubis_version"`, + `id="anubis_challenge"`, + "/.within.website/x/xess/", + "making sure you're not a bot!", + "making sure you're not a bot!", + ) { + return true + } + if !hasJSONLDScriptToken(probe) && !strings.Contains(lower, "data-page=") && + wave3CommContainsAny(lower, "scheduled maintenance", "down for maintenance", "under maintenance", "temporarily unavailable", "503 service unavailable") && + len(rawHTML) < 48*1024 { + return true + } + title := wave3CommCleanText(extractTitleLinearQuick(probe)) + if title != "" && (wave3CommRxNotFoundTitle.MatchString(title) || wave3CommRxMaintTitle.MatchString(title) || wave3CommRxErrorTitle.MatchString(title)) { + return true + } + if title != "" && wave3CommRxLoginTitle.MatchString(title) && !hasJSONLDScriptToken(probe) && len(rawHTML) < 48*1024 { + return true + } + if len(rawHTML) < 32*1024 && !hasJSONLDScriptToken(probe) && !strings.Contains(lower, "data-page=") && + wave3CommContainsAny(lower, `name="samlrequest"`, `name="samlresponse"`, ` and Misskey SPA shell) + hasInertia := strings.Contains(lower, "data-page=") + hasJSONLD := hasJSONLDScriptToken(probe) + if len(rawHTML) < 24*1024 && !hasJSONLD && !hasInertia { + isSpaShell := wave3CommContainsAny(lower, + `
`, + `
`, + `
`, + `
`, + `
`, + `
`, + `
`, + ``, + ``, + ) || (strings.Contains(lower, `= 0 { + s = stripTagsInlineLinear(s) + } + if strings.IndexByte(s, '&') >= 0 { + s = stdhtml.UnescapeString(s) + } + return strings.TrimSpace(wave3CommRxSpace.ReplaceAllString(s, " ")) +} + +func wave3CommFragToMD(frag, baseURL string) string { + if strings.TrimSpace(frag) == "" { + return "" + } + doc := ExtractHTMLDocumentFull(""+frag+"", FullExtractOptions{ + BaseURL: baseURL, + OnlyMainContent: false, + IncludeImages: false, + IsFragment: true, + SkipUniversalExtractors: true, + SkipPlainText: true, + }) + return strings.TrimSpace(doc.Markdown) +} + +func wave3CommFirstNonEmpty(vals ...string) string { + for _, v := range vals { + if t := strings.TrimSpace(v); t != "" { + return t + } + } + return "" +} + +func wave3CommPlain(v any, maxLen int) string { + return SanitizeSchemaPlainField(jsonScalarToString(v), maxLen) +} + +func wave3CommParseASPNetDate(raw string) string { + s := strings.TrimSpace(raw) + m := wave3CommRxASPNetDate.FindStringSubmatch(s) + if len(m) < 2 { + return "" + } + ms, err := strconv.ParseInt(m[1], 10, 64) + if err != nil { + return "" + } + loc := time.UTC + if len(m) >= 3 && m[2] != "" { + if len(m[2]) != 5 { + return "" + } + sign := 1 + if m[2][0] == '-' { + sign = -1 + } + hh, errH := strconv.Atoi(m[2][1:3]) + mm, errM := strconv.Atoi(m[2][3:5]) + if errH != nil || errM != nil || hh > 14 || mm > 59 { + return "" + } + loc = time.FixedZone("TZ", sign*(hh*3600+mm*60)) + } + t := time.UnixMilli(ms).In(loc) + if t.Year() < 1970 || t.Year() > 2035 { + return "" + } + if t.Hour() == 0 && t.Minute() == 0 && t.Second() == 0 { + return t.Format("2006-01-02") + } + return t.Format(time.RFC3339) +} + +func wave3CommNormalizeDate(raw string) string { + s := strings.TrimSpace(raw) + if s == "" { + return "" + } + if strings.HasPrefix(s, "/Date(") { + return wave3CommParseASPNetDate(s) + } + if m := wave3CommRxISODate.FindStringSubmatch(s); len(m) == 2 { + return m[1] + } + if m := wave3CommRxSlashDate.FindStringSubmatch(s); len(m) >= 4 { + mo, errMo := strconv.Atoi(m[1]) + dy, errDy := strconv.Atoi(m[2]) + yr, errYr := strconv.Atoi(m[3]) + if errMo == nil && errDy == nil && errYr == nil && mo >= 1 && mo <= 12 && dy >= 1 && dy <= 31 { + iso := fmt.Sprintf("%04d-%02d-%02d", yr, mo, dy) + if len(m) >= 5 && m[4] != "" { + return iso + " " + m[4] + } + return iso + } + } + return "" +} + +func wave3CommFormatPrice(raw any) string { + switch v := raw.(type) { + case json.Number: + if f, err := v.Float64(); err == nil && f >= 0 { + return fmt.Sprintf("$%.2f", f) + } + case float64: + if v >= 0 { + return fmt.Sprintf("$%.2f", v) + } + case int: + if v >= 0 { + return fmt.Sprintf("$%d.00", v) + } + case string: + s := strings.TrimSpace(strings.TrimPrefix(v, "$")) + s = strings.ReplaceAll(s, ",", "") + if f, err := strconv.ParseFloat(s, 64); err == nil && f >= 0 { + return fmt.Sprintf("$%.2f", f) + } + } + return "" +} + +func wave3CommResolveURL(rawRef, baseURL string) string { + ref := strings.TrimSpace(stdhtml.UnescapeString(rawRef)) + if ref == "" || strings.HasPrefix(ref, "#") || strings.HasPrefix(strings.ToLower(ref), "javascript:") || strings.HasPrefix(strings.ToLower(ref), "mailto:") { + return "" + } + u, err := url.Parse(ref) + if err != nil { + return "" + } + if u.IsAbs() { + if u.Scheme == "https" || u.Scheme == "http" { + return u.String() + } + return "" + } + if baseURL == "" { + return "" + } + b, err := url.Parse(baseURL) + if err != nil { + return "" + } + res := b.ResolveReference(u) + if res.Scheme == "https" || res.Scheme == "http" { + return res.String() + } + return "" +} + +func wave3CommExtractAttr(tag, attrName string) string { + lowTag := asciiLowerExtractString(tag) + needle := strings.ToLower(attrName) + "=" + idx := strings.Index(lowTag, needle) + for idx > 0 { + prev := lowTag[idx-1] + if prev == ' ' || prev == '\t' || prev == '\n' || prev == '\r' { + break + } + nextIdx := strings.Index(lowTag[idx+len(needle):], needle) + if nextIdx < 0 { + idx = -1 + break + } + idx = idx + len(needle) + nextIdx + } + if idx < 0 { + return "" + } + rest := strings.TrimLeft(tag[idx+len(needle):], " \t\r\n") + if rest == "" { + return "" + } + quote := rest[0] + if quote == '"' || quote == '\'' { + rest = rest[1:] + if end := strings.IndexByte(rest, quote); end >= 0 { + return rest[:end] + } + return "" + } + end := strings.IndexAny(rest, " \t\r\n>") + if end >= 0 { + return rest[:end] + } + return rest +} + +func wave3CommExtractMeta(rawHTML, key string) string { + probe := rawHTML + if len(probe) > 65536 { + probe = probe[:65536] + } + target := strings.ToLower(key) + pos := 0 + for pos < len(probe) { + idx := indexFoldASCIIExtract(probe[pos:], "') + if end < 0 { + break + } + tag := probe[start : start+end+1] + pos = start + end + 1 + lowTag := asciiLowerExtractString(tag) + if !strings.Contains(lowTag, target) { + continue + } + nameVal := wave3CommExtractAttr(tag, "property") + if nameVal == "" { + nameVal = wave3CommExtractAttr(tag, "name") + } + if strings.EqualFold(nameVal, key) { + if content := wave3CommCleanText(wave3CommExtractAttr(tag, "content")); content != "" { + return content + } + } + } + return "" +} + +type wave3CommTagMatch struct { + Tag string + OpenTag string + Inner string +} + +func wave3CommScanTags(htmlStr string, limit int) []wave3CommTagMatch { + var out []wave3CommTagMatch + pos := 0 + for pos < len(htmlStr) && len(out) < limit { + lt := strings.IndexByte(htmlStr[pos:], '<') + if lt < 0 { + break + } + start := pos + lt + if start+2 >= len(htmlStr) { + break + } + if htmlStr[start+1] == '/' || htmlStr[start+1] == '!' || htmlStr[start+1] == '?' { + gt := strings.IndexByte(htmlStr[start:], '>') + if gt < 0 { + break + } + pos = start + gt + 1 + continue + } + gt := strings.IndexByte(htmlStr[start:], '>') + if gt < 0 { + break + } + openTag := htmlStr[start : start+gt+1] + nameEnd := 1 + for nameEnd < len(openTag)-1 { + c := openTag[nameEnd] + if c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '/' || c == '>' { + break + } + nameEnd++ + } + tag := asciiLowerExtractString(openTag[1:nameEnd]) + pos = start + gt + 1 + if tag == "script" || tag == "style" || tag == "noscript" || tag == "svg" { + if closeIdx := indexFoldASCIIExtract(htmlStr[pos:], "= 0 { + if cgt := strings.IndexByte(htmlStr[pos+closeIdx:], '>'); cgt >= 0 { + pos = pos + closeIdx + cgt + 1 + continue + } + } + continue + } + switch tag { + case "h1", "h2", "h3", "p", "li", "tr", "td", "th", "article", "time", "span": + closeTok := "= 0 && closeIdx <= 16384 { + out = append(out, wave3CommTagMatch{ + Tag: tag, + OpenTag: openTag, + Inner: htmlStr[pos : pos+closeIdx], + }) + if tag != "article" && tag != "tr" { + if cgt := strings.IndexByte(htmlStr[pos+closeIdx:], '>'); cgt >= 0 { + pos = pos + closeIdx + cgt + 1 + } + } + } + } + } + return out +} + +func wave3CommExtractBestHeadingAndSite(rawHTML string) (string, string) { + probe := rawHTML + if len(probe) > 128*1024 { + probe = probe[:128*1024] + } + pageTitle := wave3CommCleanText(extractTitleLinearQuick(probe)) + ogTitle := wave3CommExtractMeta(probe, "og:title") + siteName := wave3CommExtractMeta(probe, "og:site_name") + + h1 := "" + for _, m := range wave3CommScanTags(probe, 80) { + if m.Tag == "h1" { + cand := wave3CommCleanText(m.Inner) + if cand != "" && !wave3CommRxGenericHead.MatchString(cand) && len(cand) <= 220 { + h1 = cand + break + } + } + } + + cleanedPage := pageTitle + if cleanedPage != "" { + parts := wave3CommRxTitleSep.Split(cleanedPage, 4) + for _, p := range parts { + cand := strings.TrimSpace(p) + if cand != "" && !wave3CommRxGenericHead.MatchString(cand) { + cleanedPage = cand + break + } + } + } + best := wave3CommFirstNonEmpty(h1, ogTitle, cleanedPage, pageTitle) + return best, siteName +} + +func wave3CommExtractBalancedDivsByClass(rawHTML, classNeedle string, limit int) []string { + var out []string + needleLower := strings.ToLower(classNeedle) + pos := 0 + for pos < len(rawHTML) && len(out) < limit { + idx := indexFoldASCIIExtract(rawHTML[pos:], needleLower) + if idx < 0 { + break + } + hit := pos + idx + openStart := strings.LastIndex(rawHTML[:hit], " 400 { + pos = hit + len(needleLower) + continue + } + gt := strings.IndexByte(rawHTML[openStart:], '>') + if gt < 0 || openStart+gt < hit { + pos = hit + len(needleLower) + continue + } + depth := 1 + cur := openStart + gt + 1 + endPos := -1 + for cur < len(rawHTML) && cur-openStart < 32768 { + nextOpen := indexFoldASCIIExtract(rawHTML[cur:], "= 0 && nextOpen < nextClose { + depth++ + cur += nextOpen + 4 + } else { + depth-- + cur += nextClose + 6 + if depth == 0 { + endPos = cur + break + } + } + } + if endPos > openStart { + out = append(out, rawHTML[openStart:endPos]) + pos = endPos + } else { + pos = hit + len(needleLower) + } + } + return out +} + +func wave3CommExtractAnchorLinks(rawHTML, baseURL string, pathNeedles []string, limit int) []struct{ Text, URL string } { + var out []struct{ Text, URL string } + seen := make(map[string]bool) + scan := rawHTML + if len(scan) > 512*1024 { + scan = scan[:512*1024] + } + pos := 0 + for pos < len(scan) && len(out) < limit { + idx := indexFoldASCIIExtract(scan[pos:], "') + if gt < 0 { + break + } + openTag := scan[start : start+gt+1] + closeIdx := indexFoldASCIIExtract(scan[start+gt+1:], "") + pos = start + gt + 1 + if closeIdx < 0 || closeIdx > 2048 { + continue + } + inner := wave3CommCleanText(scan[pos : pos+closeIdx]) + pos += closeIdx + 4 + href := wave3CommExtractAttr(openTag, "href") + resolved := wave3CommResolveURL(href, baseURL) + if resolved == "" || seen[resolved] { + continue + } + if len(pathNeedles) > 0 { + lowURL := strings.ToLower(resolved) + matched := false + for _, pn := range pathNeedles { + if strings.Contains(lowURL, pn) { + matched = true + break + } + } + if !matched { + continue + } + } + seen[resolved] = true + if inner == "" { + inner = resolved + } + out = append(out, struct{ Text, URL string }{Text: inner, URL: resolved}) + } + return out +} + +func wave3CommExtractDOMSnippets(rawHTML string, maxSnippets int) (headings []string, paragraphs []string, listItems []string) { + scan := rawHTML + if len(scan) > 256*1024 { + scan = scan[:256*1024] + } + lower := asciiLowerExtractString(scan) + if idx := strings.Index(lower, "= 0 { + if end := strings.Index(lower[idx:], ""); end > 0 { + scan = scan[idx : idx+end+7] + } + } + seen := make(map[string]bool) + for _, m := range wave3CommScanTags(scan, 260) { + txt := wave3CommCleanText(m.Inner) + if len(txt) < 4 || len(txt) > 800 || seen[txt] { + continue + } + seen[txt] = true + switch m.Tag { + case "h1", "h2", "h3": + if !wave3CommRxGenericHead.MatchString(txt) && len(headings) < maxSnippets { + headings = append(headings, txt) + } + case "p", "article": + if len(txt) >= 24 && len(paragraphs) < maxSnippets { + paragraphs = append(paragraphs, txt) + } + case "li": + if len(txt) >= 10 && len(listItems) < maxSnippets { + listItems = append(listItems, txt) + } + } + } + return headings, paragraphs, listItems +} + +func wave3CommRenderBulletsAndSections(title string, bullets []string, sections []string) string { + var sb strings.Builder + if title != "" { + sb.WriteString("# ") + sb.WriteString(escapeDeclMarkdownBrackets(title)) + sb.WriteString("\n\n") + } + for _, b := range bullets { + if strings.TrimSpace(b) != "" { + sb.WriteString(b) + sb.WriteByte('\n') + } + } + if len(bullets) > 0 && len(sections) > 0 { + sb.WriteByte('\n') + } + for _, sec := range sections { + if strings.TrimSpace(sec) != "" { + sb.WriteString(sec) + sb.WriteString("\n\n") + } + } + return strings.TrimSpace(sb.String()) +} + +// ── #243 Wild Apricot HTML Extractor ────────────────────────────────────────────────────────────── + +func wave3CommExtractWildApricotHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + lowerProbe := wave3CommLowerProbe(rawHTML, 180_000) + if !wave3CommContainsAny(lowerProbe, "wagadget", "wildapricot", `id="idevent`, `id='idevent`, "idevent=", "var idevent") { + return nil + } + // Reject WaGadgetLoginButton-only gated shells without public event/directory content + hasPublicGadget := wave3CommContainsAny(lowerProbe, + "wagadgetevents", "wagadgetupcomingevents", "wagadgetmemberdirectory", "wagadgetcontent", + ) + if strings.Contains(lowerProbe, "wagadgetloginbutton") && !hasPublicGadget { + return nil + } + if wave3CommContainsAny(lowerProbe, "login to view", "members only", "log in to continue") && + !wave3CommContainsAny(lowerProbe, "wagadgeteventsstatedetails", "wagadgetmemberdirectorystatelist", "wagadgetupcomingevents") { + return nil + } + + title, siteName := wave3CommExtractBestHeadingAndSite(rawHTML) + if title == "" { + title = "Wild Apricot Portal" + } + desc := wave3CommExtractMeta(rawHTML, "description") + + var records []map[string]any + var links []string + var eventLines []string + var memberLines []string + + // Event details or upcoming events + for _, cls := range []string{"WaGadgetEventsStateDetails", "WaGadgetUpcomingEvents", "WaGadgetEvents"} { + for _, blk := range wave3CommExtractBalancedDivsByClass(rawHTML, cls, 10) { + for _, ln := range wave3CommExtractAnchorLinks(blk, baseURL, []string{"/event-", "event"}, 15) { + if len(records) >= wave3CommMaxRecords { + break + } + records = append(records, map[string]any{"kind": "event", "title": ln.Text, "url": ln.URL}) + links = append(links, ln.URL) + eventLines = append(eventLines, fmt.Sprintf("- [%s](%s)", escapeDeclMarkdownBrackets(ln.Text), ln.URL)) + } + for _, m := range wave3CommScanTags(blk, 40) { + if m.Tag == "p" || m.Tag == "li" { + txt := wave3CommCleanText(m.Inner) + if len(txt) >= 18 && len(eventLines) < 20 { + eventLines = append(eventLines, "- "+escapeDeclMarkdownBrackets(txt)) + } + } + } + } + } + + // Member directory + for _, cls := range []string{"WaGadgetMemberDirectory", "memberDirectoryContainer"} { + for _, blk := range wave3CommExtractBalancedDivsByClass(rawHTML, cls, 5) { + for _, m := range wave3CommScanTags(blk, 60) { + if m.Tag == "tr" || m.Tag == "li" || m.Tag == "p" { + txt := wave3CommCleanText(m.Inner) + if len(txt) >= 8 && len(txt) <= 240 && len(records) < wave3CommMaxRecords { + records = append(records, map[string]any{"kind": "member", "entry": txt}) + memberLines = append(memberLines, "- "+escapeDeclMarkdownBrackets(txt)) + } + } + } + } + } + + headings, paras, listItems := wave3CommExtractDOMSnippets(rawHTML, 15) + // Filter out Wild Apricot's hidden "Wrong document context!" heading if present + if title == "" && len(headings) > 0 { + title = headings[0] + } + if len(eventLines) == 0 && len(memberLines) == 0 && len(paras) == 0 && len(listItems) == 0 { + return nil + } + + var bullets []string + bullets = append(bullets, "- **Platform**: Wild Apricot") + if siteName != "" { + bullets = append(bullets, "- **Association**: "+escapeDeclMarkdownBrackets(siteName)) + } + if baseURL != "" { + bullets = append(bullets, "- **Source**: "+baseURL) + } + + var sections []string + if desc != "" { + sections = append(sections, desc) + } + if len(eventLines) > 0 { + sections = append(sections, "## Events\n\n"+strings.Join(eventLines, "\n")) + } + if len(memberLines) > 0 { + sections = append(sections, "## Member Directory\n\n"+strings.Join(memberLines, "\n")) + } + if len(paras) > 0 { + sections = append(sections, "## Details\n\n"+strings.Join(paras, "\n\n")) + } + + md := wave3CommRenderBulletsAndSections(title, bullets, sections) + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: md, + Links: links, + Records: records, + } +} + +// ── #244 Association AMS Pack HTML Extractor (Novi AMS, MemberClicks, YourMembership) ───────────── + +func wave3CommExtractAssociationAMSHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + lowerProbe := wave3CommLowerProbe(rawHTML, 180_000) + isNovi := wave3CommContainsAny(lowerProbe, "noviams", "novi-file-uploads", "novi-core-assets", "novi-content-wrapper", "novicon-") + isMemberClicks := wave3CommContainsAny(lowerProbe, "personifycorp", "personify.com", "personifycloud", "personify_orig", "memberclicks", "/external/wcpages/", "wc-eventcalendar") + isYM := wave3CommContainsAny(lowerProbe, "site-ym", "yourmembership", "ym-event", "ym-directory") + if !isNovi && !isMemberClicks && !isYM { + return nil + } + + platform := "Novi AMS" + if isMemberClicks && !isNovi { + platform = "MemberClicks / Personify" + } else if isYM && !isNovi { + platform = "YourMembership" + } + + title, siteName := wave3CommExtractBestHeadingAndSite(rawHTML) + if title == "" { + title = platform + " Association Portal" + } + desc := wave3CommExtractMeta(rawHTML, "description") + + var records []map[string]any + var links []string + var eventLines []string + + for _, cls := range []string{"event-list-container", "novi-content-wrapper", "wc-EventCalendarSmallBox", "g-events__content"} { + for _, blk := range wave3CommExtractBalancedDivsByClass(rawHTML, cls, 12) { + for _, ln := range wave3CommExtractAnchorLinks(blk, baseURL, []string{"event", "directory", "member", "calendar"}, 20) { + if len(records) >= wave3CommMaxRecords { + break + } + records = append(records, map[string]any{"title": ln.Text, "url": ln.URL}) + links = append(links, ln.URL) + eventLines = append(eventLines, fmt.Sprintf("- [%s](%s)", escapeDeclMarkdownBrackets(ln.Text), ln.URL)) + } + } + } + + headings, paras, listItems := wave3CommExtractDOMSnippets(rawHTML, 15) + if len(eventLines) == 0 { + for _, ln := range wave3CommExtractAnchorLinks(rawHTML, baseURL, []string{"/events/", "/event/", "/directory/", "/external/wcpages/"}, 20) { + if len(records) >= wave3CommMaxRecords { + break + } + records = append(records, map[string]any{"title": ln.Text, "url": ln.URL}) + links = append(links, ln.URL) + eventLines = append(eventLines, fmt.Sprintf("- [%s](%s)", escapeDeclMarkdownBrackets(ln.Text), ln.URL)) + } + } + if len(eventLines) == 0 && len(paras) == 0 && len(listItems) == 0 { + return nil + } + if title == "" && len(headings) > 0 { + title = headings[0] + } + + var bullets []string + bullets = append(bullets, "- **Platform**: "+platform) + if siteName != "" { + bullets = append(bullets, "- **Association**: "+escapeDeclMarkdownBrackets(siteName)) + } + if baseURL != "" { + bullets = append(bullets, "- **Source**: "+baseURL) + } + + var sections []string + if desc != "" { + sections = append(sections, desc) + } + if len(eventLines) > 0 { + sections = append(sections, "## Events & Directory\n\n"+strings.Join(eventLines, "\n")) + } + if len(paras) > 0 { + sections = append(sections, "## Overview\n\n"+strings.Join(paras, "\n\n")) + } else if len(eventLines) == 0 && len(listItems) > 0 { + var lines []string + for _, li := range listItems { + lines = append(lines, "- "+escapeDeclMarkdownBrackets(li)) + } + sections = append(sections, "## Items\n\n"+strings.Join(lines, "\n")) + } + + md := wave3CommRenderBulletsAndSections(title, bullets, sections) + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: md, + Links: links, + Records: records, + } +} + +// ── #245 RunSignup JSON & HTML Extractors ───────────────────────────────────────────────────────── + +func wave3CommFormatRunSignupJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + m, ok := parsed.(map[string]any) + if !ok { + return nil, false + } + if m["error"] != nil { + return nil, false + } + + var races []map[string]any + if rawRaces, ok := m["races"].([]any); ok { + for _, item := range rawRaces { + if im, ok := item.(map[string]any); ok { + if rm, ok := im["race"].(map[string]any); ok { + races = append(races, rm) + } else if im["race_id"] != nil || im["name"] != nil { + races = append(races, im) + } + } + } + } else if rm, ok := m["race"].(map[string]any); ok { + races = append(races, rm) + } + if len(races) == 0 { + return nil, false + } + + var records []map[string]any + var sections []string + var links []string + + for _, r := range races { + name := wave3CommPlain(r["name"], 220) + if name == "" { + continue + } + raceID := wave3CommPlain(r["race_id"], 32) + raceURL := SanitizeSchemaHTTPSURL(r["url"], origURL) + nextDate := wave3CommNormalizeDate(wave3CommPlain(r["next_date"], 64)) + lastDate := wave3CommNormalizeDate(wave3CommPlain(r["last_date"], 64)) + regOpen := wave3CommPlain(r["is_registration_open"], 16) + descRaw := jsonScalarToString(r["description"]) + descMD := wave3CommFragToMD(descRaw, origURL) + if len(descMD) > 1500 { + descMD = descMD[:1500] + } + + locStr := "" + if addr, ok := r["address"].(map[string]any); ok { + city := wave3CommPlain(addr["city"], 80) + state := wave3CommPlain(addr["state"], 40) + zip := wave3CommPlain(addr["zipcode"], 20) + parts := make([]string, 0, 3) + if city != "" { + parts = append(parts, city) + } + if state != "" { + parts = append(parts, state) + } + if zip != "" { + parts = append(parts, zip) + } + locStr = strings.Join(parts, ", ") + } + + rec := map[string]any{"name": name} + if raceID != "" { + rec["raceId"] = raceID + } + if nextDate != "" { + rec["nextDate"] = nextDate + } + if lastDate != "" { + rec["lastDate"] = lastDate + } + if locStr != "" { + rec["location"] = locStr + } + if raceURL != "" { + rec["url"] = raceURL + links = append(links, raceURL) + } + if len(records) < wave3CommMaxRecords { + records = append(records, rec) + } + + var sb strings.Builder + if len(races) > 1 { + sb.WriteString("### " + escapeDeclMarkdownBrackets(name) + "\n\n") + } + if raceID != "" { + sb.WriteString("- **Race ID**: `" + raceID + "`\n") + } + if nextDate != "" { + sb.WriteString("- **Next Date**: " + nextDate + "\n") + } + if lastDate != "" { + sb.WriteString("- **Last Date**: " + lastDate + "\n") + } + if locStr != "" { + sb.WriteString("- **Location**: " + escapeDeclMarkdownBrackets(locStr) + "\n") + } + if regOpen != "" { + sb.WriteString("- **Registration Open**: " + regOpen + "\n") + } + if raceURL != "" { + sb.WriteString("- **Race URL**: " + raceURL + "\n") + } + if evArr, ok := r["events"].([]any); ok && len(evArr) > 0 { + var evRows []string + for _, evEl := range evArr { + em, ok := evEl.(map[string]any) + if !ok { + continue + } + evName := wave3CommPlain(em["name"], 140) + if evName == "" { + continue + } + evDist := wave3CommPlain(em["distance"], 60) + evStart := wave3CommPlain(em["start_time"], 64) + evRows = append(evRows, fmt.Sprintf("| %s | %s | %s |", + escapeDeclMarkdownBrackets(evName), + wave3CommFirstNonEmpty(evDist, "-"), + wave3CommFirstNonEmpty(evStart, "-"), + )) + if len(evRows) >= 15 { + break + } + } + if len(evRows) > 0 { + sb.WriteString("\n| Event | Distance | Start Time |\n|---|---|---|\n" + strings.Join(evRows, "\n") + "\n") + } + } + if descMD != "" { + sb.WriteString("\n" + descMD + "\n") + } + sections = append(sections, strings.TrimSpace(sb.String())) + } + + if len(records) == 0 { + return nil, false + } + title := wave3CommPlain(races[0]["name"], 220) + if len(races) > 1 { + title = fmt.Sprintf("RunSignup Races (%d)", len(races)) + } + bullets := []string{"- **Platform**: RunSignup"} + if origURL != "" { + bullets = append(bullets, "- **Source**: "+origURL) + } + md := wave3CommRenderBulletsAndSections(title, bullets, sections) + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: md, + Links: links, + Records: records, + }, true +} + +func wave3CommExtractRunSignupHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + if !hasJSONLDScriptToken(rawHTML) && !containsAnyFoldASCIIExtract(rawHTML, "runsignup", "race") { + return nil + } + if res := wave3CommExtractSportsEventJSONLD(rawHTML, baseURL, extractorID, "RunSignup"); res != nil { + return res + } + title, _ := wave3CommExtractBestHeadingAndSite(rawHTML) + desc := wave3CommExtractMeta(rawHTML, "description") + _, paras, _ := wave3CommExtractDOMSnippets(rawHTML, 10) + if title == "" || (desc == "" && len(paras) == 0) { + return nil + } + bullets := []string{"- **Platform**: RunSignup"} + if baseURL != "" { + bullets = append(bullets, "- **Source**: "+baseURL) + } + var sections []string + if desc != "" { + sections = append(sections, desc) + } + if len(paras) > 0 { + sections = append(sections, "## Race Info\n\n"+strings.Join(paras, "\n\n")) + } + md := wave3CommRenderBulletsAndSections(title, bullets, sections) + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: md, + } +} + +// ── #246 BikeReg & USA Cycling JSON & HTML Extractors ───────────────────────────────────────────── + +func wave3CommFormatBikeRegJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + m, ok := parsed.(map[string]any) + if !ok { + return nil, false + } + rawEvents, ok := m["MatchingEvents"].([]any) + if !ok || len(rawEvents) == 0 { + return nil, false + } + + var records []map[string]any + var sections []string + var links []string + + for _, el := range rawEvents { + ev, ok := el.(map[string]any) + if !ok { + continue + } + name := wave3CommPlain(ev["EventName"], 220) + if name == "" { + continue + } + evID := wave3CommPlain(ev["EventId"], 32) + evDate := wave3CommNormalizeDate(wave3CommPlain(ev["EventDate"], 64)) + evEndDate := wave3CommNormalizeDate(wave3CommPlain(ev["EventEndDate"], 64)) + city := wave3CommPlain(ev["EventCity"], 80) + state := wave3CommPlain(ev["EventState"], 40) + addr := wave3CommPlain(ev["EventAddress"], 140) + evURL := SanitizeSchemaHTTPSURL(ev["EventUrl"], origURL) + + locParts := make([]string, 0, 3) + if addr != "" { + locParts = append(locParts, addr) + } + if city != "" { + locParts = append(locParts, city) + } + if state != "" { + locParts = append(locParts, state) + } + locStr := strings.Join(locParts, ", ") + + rec := map[string]any{"eventName": name} + if evID != "" { + rec["eventId"] = evID + } + if evDate != "" { + rec["eventDate"] = evDate + } + if evEndDate != "" { + rec["eventEndDate"] = evEndDate + } + if locStr != "" { + rec["location"] = locStr + } + if evURL != "" { + rec["url"] = evURL + links = append(links, evURL) + } + + var catRows []string + if cats, ok := ev["Categories"].([]any); ok { + for _, ce := range cats { + cm, ok := ce.(map[string]any) + if !ok { + continue + } + cName := wave3CommPlain(cm["CategoryName"], 160) + if cName == "" { + continue + } + dist := wave3CommPlain(cm["Distance"], 60) + fee := wave3CommFormatPrice(cm["EntryFee"]) + startTime := wave3CommPlain(cm["StartTime"], 32) + catDate := "" + if cdArr, ok := cm["CategoryDates"].([]any); ok && len(cdArr) > 0 { + catDate = wave3CommNormalizeDate(wave3CommPlain(cdArr[0], 64)) + } + catRows = append(catRows, fmt.Sprintf("| %s | %s | %s | %s | %s |", + escapeDeclMarkdownBrackets(cName), + wave3CommFirstNonEmpty(catDate, "-"), + wave3CommFirstNonEmpty(startTime, "-"), + wave3CommFirstNonEmpty(dist, "-"), + wave3CommFirstNonEmpty(fee, "-"), + )) + if len(catRows) >= 15 { + break + } + } + } + if len(records) < wave3CommMaxRecords { + records = append(records, rec) + } + + var sb strings.Builder + sb.WriteString("### " + escapeDeclMarkdownBrackets(name) + "\n\n") + if evID != "" { + sb.WriteString("- **Event ID**: `" + evID + "`\n") + } + if evDate != "" { + sb.WriteString("- **Event Date**: " + evDate + "\n") + } + if locStr != "" { + sb.WriteString("- **Location**: " + escapeDeclMarkdownBrackets(locStr) + "\n") + } + if evURL != "" { + sb.WriteString("- **URL**: " + evURL + "\n") + } + if len(catRows) > 0 { + sb.WriteString("\n| Category | Date | Start | Distance | Entry Fee |\n|---|---|---|---|---|\n" + strings.Join(catRows, "\n") + "\n") + } + sections = append(sections, strings.TrimSpace(sb.String())) + if len(sections) >= wave3CommMaxRecords { + break + } + } + + if len(records) == 0 { + return nil, false + } + title := wave3CommPlain(records[0]["eventName"], 220) + if len(records) > 1 { + title = fmt.Sprintf("BikeReg Events (%d)", len(records)) + } + bullets := []string{"- **Platform**: BikeReg"} + if origURL != "" { + bullets = append(bullets, "- **Source**: "+origURL) + } + md := wave3CommRenderBulletsAndSections(title, bullets, sections) + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: md, + Links: links, + Records: records, + }, true +} + +func wave3CommExtractBikeRegUSACyclingHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + // 1. Sport80 / USA Cycling Inertia data-page JSON + if jb, ok := extractInertiaDataPageBytesGo(rawHTML); ok { + if parsed, okDec := decodeJSONWithNumbers(jb); okDec { + if root, okMap := parsed.(map[string]any); okMap { + component := wave3CommPlain(root["component"], 120) + props, _ := root["props"].(map[string]any) + if props != nil { + if res := wave3CommExtractSport80Inertia(component, props, baseURL, extractorID); res != nil { + return res + } + } + } + } + } + + // 2. Unchallenged BikeReg / USA Cycling SportsEvent JSON-LD or HTML + if hasJSONLDScriptToken(rawHTML) { + if res := wave3CommExtractSportsEventJSONLD(rawHTML, baseURL, extractorID, "BikeReg / USA Cycling"); res != nil { + return res + } + } + lowerProbe := wave3CommLowerProbe(rawHTML, 128*1024) + if !wave3CommContainsAny(lowerProbe, "bikereg", "usacycling", "sport80") { + return nil + } + title, _ := wave3CommExtractBestHeadingAndSite(rawHTML) + desc := wave3CommExtractMeta(rawHTML, "description") + _, paras, listItems := wave3CommExtractDOMSnippets(rawHTML, 12) + if title == "" || (desc == "" && len(paras) == 0 && len(listItems) == 0) { + return nil + } + bullets := []string{"- **Platform**: BikeReg / USA Cycling"} + if baseURL != "" { + bullets = append(bullets, "- **Source**: "+baseURL) + } + var sections []string + if desc != "" { + sections = append(sections, desc) + } + if len(paras) > 0 { + sections = append(sections, "## Event Details\n\n"+strings.Join(paras, "\n\n")) + } + md := wave3CommRenderBulletsAndSections(title, bullets, sections) + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: md, + } +} + +func wave3CommExtractSport80Inertia(component string, props map[string]any, baseURL, extractorID string) *DeclarativePostFetchResult { + orgName := "USA Cycling" + if shared, ok := props["_shared"].(map[string]any); ok { + if sd, ok := shared["subdomain_data"].(map[string]any); ok { + if n := wave3CommPlain(sd["name"], 120); n != "" { + orgName = n + } + } + } + + var records []map[string]any + var links []string + var sections []string + + // FindEventsPage: props.events[] + if evArr, ok := props["events"].([]any); ok && len(evArr) > 0 { + var rows []string + for _, el := range evArr { + em, ok := el.(map[string]any) + if !ok { + continue + } + evName := wave3CommFirstNonEmpty(wave3CommPlain(em["name"], 180), wave3CommPlain(em["title"], 180)) + if evName == "" { + continue + } + loc := wave3CommPlain(em["location"], 160) + evURL := SanitizeSchemaHTTPSURL(wave3CommFirstNonEmpty(wave3CommPlain(em["full_details_url"], 300), wave3CommPlain(em["main_action_url"], 300)), baseURL) + dateStr := "" + if dm, ok := em["date"].(map[string]any); ok { + dateStr = strings.TrimSpace(wave3CommPlain(dm["month"], 16) + " " + wave3CommPlain(dm["day"], 8) + " " + wave3CommPlain(dm["year"], 8)) + } + if dateStr == "" { + dateStr = wave3CommPlain(em["entry_open_date"], 40) + } + rec := map[string]any{"name": evName} + if dateStr != "" { + rec["date"] = dateStr + } + if loc != "" { + rec["location"] = loc + } + if evURL != "" { + rec["url"] = evURL + links = append(links, evURL) + } + if len(records) < wave3CommMaxRecords { + records = append(records, rec) + } + rows = append(rows, fmt.Sprintf("| %s | %s | %s |", + escapeDeclMarkdownBrackets(evName), + wave3CommFirstNonEmpty(dateStr, "-"), + escapeDeclMarkdownBrackets(wave3CommFirstNonEmpty(loc, "-")), + )) + if len(rows) >= wave3CommMaxRecords { + break + } + } + if len(rows) > 0 { + sections = append(sections, "## Events\n\n| Event | Date | Location |\n|---|---|---|\n"+strings.Join(rows, "\n")) + } + } + + // ResultsPage: props.results_page + if rp, ok := props["results_page"].(map[string]any); ok { + rHead := wave3CommPlain(rp["results_heading"], 180) + rOverview := wave3CommFragToMD(stdhtml.UnescapeString(jsonScalarToString(rp["results_and_rankings_overview_text"])), baseURL) + if rHead != "" || rOverview != "" { + var sb strings.Builder + if rHead != "" { + sb.WriteString("## " + escapeDeclMarkdownBrackets(rHead) + "\n\n") + } + if rOverview != "" { + sb.WriteString(rOverview) + } + sections = append(sections, strings.TrimSpace(sb.String())) + } + if resList, ok := rp["results"].([]any); ok && len(resList) > 0 { + var rRows []string + for _, re := range resList { + rm, ok := re.(map[string]any) + if !ok { + continue + } + rName := wave3CommFirstNonEmpty(wave3CommPlain(rm["name"], 160), wave3CommPlain(rm["event_name"], 160), wave3CommPlain(rm["title"], 160)) + rDate := wave3CommNormalizeDate(wave3CommPlain(rm["date"], 64)) + if rName != "" { + records = append(records, map[string]any{"name": rName, "date": rDate}) + rRows = append(rRows, fmt.Sprintf("- %s (%s)", escapeDeclMarkdownBrackets(rName), wave3CommFirstNonEmpty(rDate, "-"))) + } + } + if len(rRows) > 0 { + sections = append(sections, "## Results\n\n"+strings.Join(rRows, "\n")) + } + } + } + + if len(sections) == 0 { + return nil + } + title := wave3CommFirstNonEmpty(wave3CommPlain(props["title"], 160), orgName+" ("+component+")") + if title == "Events" || title == "Results" { + title = orgName + " " + title + } + bullets := []string{ + "- **Organization**: " + escapeDeclMarkdownBrackets(orgName), + "- **Platform**: Sport80 Inertia", + } + if component != "" { + bullets = append(bullets, "- **View**: `"+component+"`") + } + if rc := wave3CommPlain(props["result_count"], 24); rc != "" { + bullets = append(bullets, "- **Result Count**: "+rc) + } + if baseURL != "" { + bullets = append(bullets, "- **Source**: "+baseURL) + } + md := wave3CommRenderBulletsAndSections(title, bullets, sections) + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Markdown: md, + Links: links, + Records: records, + } +} + +// ── #247 Race Results Pack HTML Extractor (Athlinks, Race Roster, ACTIVE) ───────────────────────── + +func wave3CommExtractRaceResultsPackHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + lowerProbe := wave3CommLowerProbe(rawHTML, 256*1024) + // Strictly reject empty/unhydrated CSR shells even if GTM/favicon is present + if wave3CommContainsAny(lowerProbe, `

`, `
`) { + hasSubstantive := hasJSONLDScriptToken(rawHTML) || + wave3CommContainsAny(lowerProbe, "athlete-result", "race-results", "= 8 && len(txt) <= 260 && len(records) < wave3CommMaxRecords { + records = append(records, map[string]any{"row": txt}) + rowsMD = append(rowsMD, "- "+escapeDeclMarkdownBrackets(txt)) + } + } + } + } + for _, cls := range []string{"athlete-result", "race-results", "event-details"} { + for _, blk := range wave3CommExtractBalancedDivsByClass(rawHTML, cls, 15) { + txt := wave3CommCleanText(blk) + if len(txt) >= 12 && len(txt) <= 300 && len(records) < wave3CommMaxRecords { + records = append(records, map[string]any{"entry": txt}) + rowsMD = append(rowsMD, "- "+escapeDeclMarkdownBrackets(txt)) + } + } + } + if len(rowsMD) == 0 { + return nil + } + + title, siteName := wave3CommExtractBestHeadingAndSite(rawHTML) + if title == "" { + title = "Race Results" + } + desc := wave3CommExtractMeta(rawHTML, "description") + bullets := []string{"- **Platform**: Endurance Race Results"} + if siteName != "" { + bullets = append(bullets, "- **Site**: "+escapeDeclMarkdownBrackets(siteName)) + } + if baseURL != "" { + bullets = append(bullets, "- **Source**: "+baseURL) + } + var sections []string + if desc != "" { + sections = append(sections, desc) + } + sections = append(sections, "## Results & Event Details\n\n"+strings.Join(rowsMD, "\n")) + md := wave3CommRenderBulletsAndSections(title, bullets, sections) + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: md, + Records: records, + } +} + +func wave3CommExtractSportsEventJSONLD(rawHTML, baseURL, extractorID, platform string) *DeclarativePostFetchResult { + if !hasJSONLDScriptToken(rawHTML) { + return nil + } + for _, ent := range flattenJsonLdEntitiesFullDocGo(rawHTML) { + t := strings.ToLower(wave3CommPlain(ent["@type"], 80)) + if !strings.Contains(t, "event") { + continue + } + name := wave3CommPlain(ent["name"], 220) + if name == "" { + continue + } + start := wave3CommNormalizeDate(wave3CommPlain(ent["startDate"], 64)) + end := wave3CommNormalizeDate(wave3CommPlain(ent["endDate"], 64)) + desc := wave3CommPlain(ent["description"], 1200) + evURL := SanitizeSchemaHTTPSURL(ent["url"], baseURL) + + locName := "" + if loc, ok := ent["location"].(map[string]any); ok { + ln := wave3CommPlain(loc["name"], 120) + addrParts := []string{} + if addr, ok := loc["address"].(map[string]any); ok { + for _, k := range []string{"streetAddress", "addressLocality", "addressRegion", "postalCode"} { + if v := wave3CommPlain(addr[k], 80); v != "" { + addrParts = append(addrParts, v) + } + } + } + if ln != "" && len(addrParts) > 0 { + locName = ln + " (" + strings.Join(addrParts, ", ") + ")" + } else { + locName = wave3CommFirstNonEmpty(ln, strings.Join(addrParts, ", ")) + } + } + + bullets := []string{"- **Platform**: " + platform} + if start != "" { + bullets = append(bullets, "- **Start Date**: "+start) + } + if end != "" { + bullets = append(bullets, "- **End Date**: "+end) + } + if locName != "" { + bullets = append(bullets, "- **Location**: "+escapeDeclMarkdownBrackets(locName)) + } + if baseURL != "" { + bullets = append(bullets, "- **Source**: "+baseURL) + } + + rec := map[string]any{"name": name} + if start != "" { + rec["startDate"] = start + } + if locName != "" { + rec["location"] = locName + } + var links []string + if evURL != "" { + rec["url"] = evURL + links = append(links, evURL) + } + + var sections []string + if desc != "" { + sections = append(sections, desc) + } + md := wave3CommRenderBulletsAndSections(name, bullets, sections) + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: name, + Description: desc, + Markdown: md, + Links: links, + Records: []map[string]any{rec}, + } + } + return nil +} + +// ── #248 Lemmy JSON & HTML Extractors ───────────────────────────────────────────────────────────── + +func wave3CommFormatLemmyJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + m, ok := parsed.(map[string]any) + if !ok { + return nil, false + } + if m["error"] != nil { + return nil, false + } + + // 1. Single post_view + if pv, ok := m["post_view"].(map[string]any); ok { + post, _ := pv["post"].(map[string]any) + if post == nil { + return nil, false + } + title := wave3CommPlain(post["name"], 260) + if title == "" { + return nil, false + } + body := strings.TrimSpace(jsonScalarToString(post["body"])) + postURL := SanitizeSchemaHTTPSURL(post["url"], origURL) + published := wave3CommNormalizeDate(wave3CommPlain(post["published"], 64)) + author := "" + if cr, ok := pv["creator"].(map[string]any); ok { + author = wave3CommFirstNonEmpty(wave3CommPlain(cr["display_name"], 80), wave3CommPlain(cr["name"], 80)) + } + commName := "" + if cm, ok := pv["community"].(map[string]any); ok { + commName = wave3CommPlain(cm["name"], 80) + } + bullets := []string{"- **Platform**: Lemmy"} + if commName != "" { + bullets = append(bullets, "- **Community**: `!"+commName+"`") + } + if author != "" { + bullets = append(bullets, "- **Author**: "+escapeDeclMarkdownBrackets(author)) + } + if published != "" { + bullets = append(bullets, "- **Published**: "+published) + } + if counts, ok := pv["counts"].(map[string]any); ok { + score := wave3CommPlain(counts["score"], 20) + cmts := wave3CommPlain(counts["comments"], 20) + if score != "" || cmts != "" { + bullets = append(bullets, fmt.Sprintf("- **Engagement**: score %s, %s comments", wave3CommFirstNonEmpty(score, "0"), wave3CommFirstNonEmpty(cmts, "0"))) + } + } + var links []string + if postURL != "" { + bullets = append(bullets, "- **External Link**: "+postURL) + links = append(links, postURL) + } + if origURL != "" { + bullets = append(bullets, "- **Source**: "+origURL) + } + var sections []string + if body != "" { + sections = append(sections, body) + } + rec := map[string]any{"title": title} + if commName != "" { + rec["community"] = commName + } + if author != "" { + rec["author"] = author + } + if published != "" { + rec["published"] = published + } + md := wave3CommRenderBulletsAndSections(title, bullets, sections) + return &DeclarativeFormattedDoc{ + Title: title, + Author: author, + PublishedTime: published, + Markdown: md, + Links: links, + Records: []map[string]any{rec}, + }, true + } + + // 2. community_view + if cv, ok := m["community_view"].(map[string]any); ok { + comm, _ := cv["community"].(map[string]any) + if comm == nil { + return nil, false + } + cName := wave3CommPlain(comm["name"], 100) + cTitle := wave3CommFirstNonEmpty(wave3CommPlain(comm["title"], 200), cName) + if cTitle == "" { + return nil, false + } + desc := strings.TrimSpace(jsonScalarToString(comm["description"])) + bullets := []string{"- **Platform**: Lemmy Community"} + if cName != "" { + bullets = append(bullets, "- **Handle**: `!"+cName+"`") + } + if counts, ok := cv["counts"].(map[string]any); ok { + subs := wave3CommPlain(counts["subscribers"], 20) + posts := wave3CommPlain(counts["posts"], 20) + if subs != "" { + bullets = append(bullets, "- **Subscribers**: "+subs) + } + if posts != "" { + bullets = append(bullets, "- **Posts**: "+posts) + } + } + if origURL != "" { + bullets = append(bullets, "- **Source**: "+origURL) + } + var sections []string + if desc != "" { + sections = append(sections, desc) + } + md := wave3CommRenderBulletsAndSections(cTitle, bullets, sections) + return &DeclarativeFormattedDoc{ + Title: cTitle, + Markdown: md, + Records: []map[string]any{{"name": cName, "title": cTitle}}, + }, true + } + + // 3. comments[] list + if rawCmts, ok := m["comments"].([]any); ok && len(rawCmts) > 0 { + var records []map[string]any + var cLines []string + postTitle := "" + for _, el := range rawCmts { + cmView, ok := el.(map[string]any) + if !ok { + continue + } + cObj, _ := cmView["comment"].(map[string]any) + if cObj == nil { + continue + } + if postTitle == "" { + if pObj, ok := cmView["post"].(map[string]any); ok { + postTitle = wave3CommPlain(pObj["name"], 200) + } + } + content := strings.TrimSpace(jsonScalarToString(cObj["content"])) + if content == "" { + continue + } + author := "" + if cr, ok := cmView["creator"].(map[string]any); ok { + author = wave3CommPlain(cr["name"], 80) + } + pub := wave3CommNormalizeDate(wave3CommPlain(cObj["published"], 64)) + rec := map[string]any{"author": author, "content": content} + if pub != "" { + rec["published"] = pub + } + if len(records) < wave3CommMaxRecords { + records = append(records, rec) + } + cLines = append(cLines, fmt.Sprintf("### %s (%s)\n\n%s", + wave3CommFirstNonEmpty(escapeDeclMarkdownBrackets(author), "user"), + wave3CommFirstNonEmpty(pub, "-"), + content, + )) + if len(cLines) >= wave3CommMaxRecords { + break + } + } + if len(records) == 0 { + return nil, false + } + title := wave3CommFirstNonEmpty(postTitle, "Lemmy Comments") + bullets := []string{"- **Platform**: Lemmy Comments"} + if origURL != "" { + bullets = append(bullets, "- **Source**: "+origURL) + } + md := wave3CommRenderBulletsAndSections(title, bullets, cLines) + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: md, + Records: records, + }, true + } + + return nil, false +} + +func wave3CommExtractLemmyHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + lowerProbe := wave3CommLowerProbe(rawHTML, 180_000) + hasLemmyApp := strings.Contains(lowerProbe, "isodata") || + (strings.Contains(lowerProbe, "lemmy") && wave3CommContainsAny(lowerProbe, "/pictrs/", "lemmy-ui", "/api/v3/", "join-lemmy", "community_view", "post_view")) + if !hasLemmyApp { + return nil + } + title, siteName := wave3CommExtractBestHeadingAndSite(rawHTML) + if title == "" { + title = "Lemmy Discussion" + } + desc := wave3CommExtractMeta(rawHTML, "description") + _, paras, listItems := wave3CommExtractDOMSnippets(rawHTML, 15) + if desc == "" && len(paras) == 0 && len(listItems) == 0 { + return nil + } + bullets := []string{"- **Platform**: Lemmy"} + if siteName != "" { + bullets = append(bullets, "- **Instance**: "+escapeDeclMarkdownBrackets(siteName)) + } + if baseURL != "" { + bullets = append(bullets, "- **Source**: "+baseURL) + } + var sections []string + if desc != "" { + sections = append(sections, desc) + } + if len(paras) > 0 { + sections = append(sections, "## Content\n\n"+strings.Join(paras, "\n\n")) + } else if len(listItems) > 0 { + var lines []string + for _, li := range listItems { + lines = append(lines, "- "+escapeDeclMarkdownBrackets(li)) + } + sections = append(sections, "## Discussion\n\n"+strings.Join(lines, "\n")) + } + md := wave3CommRenderBulletsAndSections(title, bullets, sections) + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: md, + } +} + +// ── #249 PeerTube JSON & HTML Extractors ────────────────────────────────────────────────────────── + +func wave3CommFormatPeerTubeJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + m, ok := parsed.(map[string]any) + if !ok { + return nil, false + } + if m["error"] != nil { + return nil, false + } + + // 1. /api/v1/videos/{id}/captions -> { total, data: [...] } + if dataArr, hasData := m["data"].([]any); hasData { + if len(dataArr) == 0 { + return nil, false + } + var records []map[string]any + var rows []string + for _, el := range dataArr { + cm, ok := el.(map[string]any) + if !ok { + continue + } + langLabel := "" + if lm, ok := cm["language"].(map[string]any); ok { + langLabel = wave3CommFirstNonEmpty(wave3CommPlain(lm["label"], 60), wave3CommPlain(lm["id"], 24)) + } + capPath := wave3CommPlain(cm["captionPath"], 300) + if langLabel == "" && capPath == "" { + continue + } + rec := map[string]any{"language": langLabel, "captionPath": capPath} + records = append(records, rec) + rows = append(rows, fmt.Sprintf("- **%s**: `%s`", wave3CommFirstNonEmpty(langLabel, "Unknown"), capPath)) + } + if len(records) == 0 { + return nil, false + } + title := "PeerTube Video Captions" + bullets := []string{"- **Platform**: PeerTube"} + if origURL != "" { + bullets = append(bullets, "- **Source**: "+origURL) + } + md := wave3CommRenderBulletsAndSections(title, bullets, []string{"## Captions\n\n" + strings.Join(rows, "\n")}) + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: md, + Records: records, + }, true + } + + // 2. Video detail (/api/v1/videos/{id}) + name := wave3CommPlain(m["name"], 240) + if name == "" { + return nil, false + } + desc := strings.TrimSpace(wave3CommFirstNonEmpty(jsonScalarToString(m["description"]), jsonScalarToString(m["truncatedDescription"]))) + if len(desc) > 2000 { + desc = desc[:2000] + } + shortUUID := wave3CommPlain(m["shortUUID"], 40) + uuid := wave3CommPlain(m["uuid"], 64) + vidURL := SanitizeSchemaHTTPSURL(m["url"], origURL) + published := wave3CommNormalizeDate(wave3CommFirstNonEmpty(wave3CommPlain(m["originallyPublishedAt"], 64), wave3CommPlain(m["publishedAt"], 64))) + dur := wave3CommPlain(m["duration"], 24) + views := wave3CommPlain(m["views"], 24) + likes := wave3CommPlain(m["likes"], 24) + + channelName := "" + if ch, ok := m["channel"].(map[string]any); ok { + channelName = wave3CommFirstNonEmpty(wave3CommPlain(ch["displayName"], 100), wave3CommPlain(ch["name"], 100)) + } + author := channelName + if author == "" { + if acc, ok := m["account"].(map[string]any); ok { + author = wave3CommFirstNonEmpty(wave3CommPlain(acc["displayName"], 100), wave3CommPlain(acc["name"], 100)) + } + } + + bullets := []string{"- **Platform**: PeerTube"} + if channelName != "" { + bullets = append(bullets, "- **Channel**: "+escapeDeclMarkdownBrackets(channelName)) + } + if published != "" { + bullets = append(bullets, "- **Published**: "+published) + } + if dur != "" { + bullets = append(bullets, "- **Duration (s)**: "+dur) + } + if views != "" { + bullets = append(bullets, "- **Views**: "+views) + } + if likes != "" { + bullets = append(bullets, "- **Likes**: "+likes) + } + if cat, ok := m["category"].(map[string]any); ok { + if lbl := wave3CommPlain(cat["label"], 60); lbl != "" && lbl != "Unknown" { + bullets = append(bullets, "- **Category**: "+escapeDeclMarkdownBrackets(lbl)) + } + } + if lic, ok := m["licence"].(map[string]any); ok { + if lbl := wave3CommPlain(lic["label"], 80); lbl != "" && lbl != "Unknown" { + bullets = append(bullets, "- **License**: "+escapeDeclMarkdownBrackets(lbl)) + } + } + var links []string + if vidURL != "" { + bullets = append(bullets, "- **Watch URL**: "+vidURL) + links = append(links, vidURL) + } + if origURL != "" { + bullets = append(bullets, "- **Source**: "+origURL) + } + + rec := map[string]any{"name": name} + if shortUUID != "" { + rec["shortUUID"] = shortUUID + } + if uuid != "" { + rec["uuid"] = uuid + } + if channelName != "" { + rec["channel"] = channelName + } + if published != "" { + rec["publishedAt"] = published + } + + var sections []string + if desc != "" { + sections = append(sections, desc) + } + md := wave3CommRenderBulletsAndSections(name, bullets, sections) + return &DeclarativeFormattedDoc{ + Title: name, + Author: author, + PublishedTime: published, + Markdown: md, + Links: links, + Records: []map[string]any{rec}, + }, true +} + +func wave3CommExtractPeerTubeHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + lowerProbe := wave3CommLowerProbe(rawHTML, 180_000) + if !strings.Contains(lowerProbe, "peertube") || + !wave3CommContainsAny(lowerProbe, "videoobject", "/videos/embed/", "/static/streaming-playlists/", "peertube-", "joinpeertube") { + return nil + } + + if hasJSONLDScriptToken(rawHTML) { + for _, ent := range flattenJsonLdEntitiesFullDocGo(rawHTML) { + t := strings.ToLower(wave3CommPlain(ent["@type"], 80)) + if !strings.Contains(t, "videoobject") { + continue + } + name := wave3CommPlain(ent["name"], 240) + if name == "" { + continue + } + desc := wave3CommPlain(ent["description"], 1200) + dur := wave3CommPlain(ent["duration"], 40) + pub := wave3CommNormalizeDate(wave3CommPlain(ent["uploadDate"], 64)) + author := extractAuthorNameSchemaGo(ent["author"]) + embedURL := SanitizeSchemaHTTPSURL(ent["embedUrl"], baseURL) + + bullets := []string{"- **Platform**: PeerTube"} + if author != "" { + bullets = append(bullets, "- **Author / Channel**: "+escapeDeclMarkdownBrackets(author)) + } + if pub != "" { + bullets = append(bullets, "- **Upload Date**: "+pub) + } + if dur != "" { + bullets = append(bullets, "- **Duration**: "+dur) + } + var links []string + if embedURL != "" { + bullets = append(bullets, "- **Embed URL**: "+embedURL) + links = append(links, embedURL) + } + if baseURL != "" { + bullets = append(bullets, "- **Source**: "+baseURL) + } + var sections []string + if desc != "" { + sections = append(sections, desc) + } + md := wave3CommRenderBulletsAndSections(name, bullets, sections) + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: name, + Description: desc, + Author: author, + PublishedTime: pub, + Markdown: md, + Links: links, + Records: []map[string]any{{"name": name, "duration": dur, "uploadDate": pub}}, + } + } + } + + title, siteName := wave3CommExtractBestHeadingAndSite(rawHTML) + if title == "" { + return nil + } + desc := wave3CommExtractMeta(rawHTML, "description") + if desc == "" { + desc = wave3CommExtractMeta(rawHTML, "og:description") + } + if desc == "" { + return nil + } + bullets := []string{"- **Platform**: PeerTube"} + if siteName != "" { + bullets = append(bullets, "- **Instance**: "+escapeDeclMarkdownBrackets(siteName)) + } + if baseURL != "" { + bullets = append(bullets, "- **Source**: "+baseURL) + } + md := wave3CommRenderBulletsAndSections(title, bullets, []string{desc}) + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: md, + } +} + +// ── #250 Fediverse Pack JSON & HTML Extractors (Misskey, Kbin / Mbin) ──────────────────────────── + +func wave3CommFormatFediversePackJSON(parsed any, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool) { + m, ok := parsed.(map[string]any) + if !ok { + return nil, false + } + if m["error"] != nil { + return nil, false + } + + // 1. ActivityPub JSON (Kbin / Mbin / Federated Page/Note/Article) + if m["@context"] != nil && m["type"] != nil { + apType := wave3CommPlain(m["type"], 60) + apTitle := wave3CommFirstNonEmpty(wave3CommPlain(m["name"], 240), wave3CommPlain(m["summary"], 240)) + apContent := wave3CommFragToMD(jsonScalarToString(m["content"]), origURL) + pub := wave3CommNormalizeDate(wave3CommPlain(m["published"], 64)) + attr := wave3CommPlain(m["attributedTo"], 240) + audience := wave3CommPlain(m["audience"], 240) + if apTitle == "" && apContent == "" { + return nil, false + } + if apTitle == "" { + apTitle = "ActivityPub " + apType + } + bullets := []string{"- **Platform**: Fediverse ActivityPub (" + apType + ")"} + if attr != "" { + bullets = append(bullets, "- **Attributed To**: "+attr) + } + if audience != "" { + bullets = append(bullets, "- **Audience**: "+audience) + } + if pub != "" { + bullets = append(bullets, "- **Published**: "+pub) + } + var links []string + if attArr, ok := m["attachment"].([]any); ok { + for _, a := range attArr { + if am, ok := a.(map[string]any); ok { + if href := SanitizeSchemaHTTPSURL(am["href"], origURL); href != "" { + links = append(links, href) + bullets = append(bullets, "- **Attachment**: "+href) + } + } + } + } + if origURL != "" { + bullets = append(bullets, "- **Source**: "+origURL) + } + var sections []string + if apContent != "" { + sections = append(sections, apContent) + } + md := wave3CommRenderBulletsAndSections(apTitle, bullets, sections) + return &DeclarativeFormattedDoc{ + Title: apTitle, + Author: attr, + PublishedTime: pub, + Markdown: md, + Links: links, + Records: []map[string]any{{"type": apType, "title": apTitle, "published": pub}}, + }, true + } + + // 2. Misskey Note JSON (/api/notes/show) + noteID := wave3CommPlain(m["id"], 40) + text := strings.TrimSpace(jsonScalarToString(m["text"])) + cw := wave3CommPlain(m["cw"], 200) + createdAt := wave3CommNormalizeDate(wave3CommPlain(m["createdAt"], 64)) + userMap, _ := m["user"].(map[string]any) + if noteID == "" || userMap == nil { + return nil, false + } + username := wave3CommPlain(userMap["username"], 80) + displayName := wave3CommFirstNonEmpty(wave3CommPlain(userMap["name"], 100), username) + host := wave3CommPlain(userMap["host"], 120) + if host == "" && origURL != "" { + if u, err := url.Parse(origURL); err == nil { + host = u.Hostname() + } + } + if host == "" { + host = params["host"] + } + handle := "@" + username + if host != "" { + handle += "@" + host + } + title := fmt.Sprintf("%s (%s)", displayName, handle) + + bullets := []string{ + "- **Platform**: Misskey", + "- **Author**: " + escapeDeclMarkdownBrackets(handle), + } + if createdAt != "" { + bullets = append(bullets, "- **Created**: "+createdAt) + } + if vis := wave3CommPlain(m["visibility"], 32); vis != "" { + bullets = append(bullets, "- **Visibility**: "+vis) + } + if cw != "" { + bullets = append(bullets, "- **Content Warning**: "+escapeDeclMarkdownBrackets(cw)) + } + if rc := wave3CommPlain(m["reactionCount"], 20); rc != "" { + bullets = append(bullets, "- **Reactions**: "+rc) + } + if origURL != "" { + bullets = append(bullets, "- **Source**: "+origURL) + } + + var sections []string + if text != "" { + sections = append(sections, text) + } else if renote, ok := m["renote"].(map[string]any); ok { + if rText := strings.TrimSpace(jsonScalarToString(renote["text"])); rText != "" { + sections = append(sections, "## Renote\n\n"+rText) + } + } + if len(sections) == 0 && cw == "" { + return nil, false + } + md := wave3CommRenderBulletsAndSections(title, bullets, sections) + return &DeclarativeFormattedDoc{ + Title: title, + Author: handle, + PublishedTime: createdAt, + Markdown: md, + Records: []map[string]any{{"noteId": noteID, "author": handle, "createdAt": createdAt}}, + }, true +} + +func wave3CommExtractFediversePackHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + lowerProbe := wave3CommLowerProbe(rawHTML, 180_000) + // Reject Misskey empty CSR shell + if strings.Contains(lowerProbe, `content="misskey"`) && !strings.Contains(lowerProbe, "entry--single") { + return nil + } + if !wave3CommContainsAny(lowerProbe, + "page-entry-single", "entry--single", "entry__meta", "magazine-inline", "comments-tree", "entry-comment", + ) { + return nil + } + + title, siteName := wave3CommExtractBestHeadingAndSite(rawHTML) + if title == "" { + title = "Mbin / Kbin Thread" + } + desc := wave3CommExtractMeta(rawHTML, "description") + + var records []map[string]any + var comments []string + for _, blk := range wave3CommExtractBalancedDivsByClass(rawHTML, "entry-comment", 20) { + txt := wave3CommCleanText(blk) + if len(txt) >= 8 && len(txt) <= 600 && len(records) < wave3CommMaxRecords { + records = append(records, map[string]any{"kind": "comment", "text": txt}) + comments = append(comments, "- "+escapeDeclMarkdownBrackets(txt)) + } + } + _, paras, _ := wave3CommExtractDOMSnippets(rawHTML, 12) + if len(paras) == 0 && len(comments) == 0 && desc == "" { + return nil + } + + bullets := []string{"- **Platform**: Mbin / Kbin"} + if siteName != "" { + bullets = append(bullets, "- **Instance**: "+escapeDeclMarkdownBrackets(siteName)) + } + if baseURL != "" { + bullets = append(bullets, "- **Source**: "+baseURL) + } + var sections []string + if desc != "" { + sections = append(sections, desc) + } + if len(paras) > 0 { + sections = append(sections, "## Entry\n\n"+strings.Join(paras, "\n\n")) + } + if len(comments) > 0 { + sections = append(sections, "## Comments\n\n"+strings.Join(comments, "\n")) + } + md := wave3CommRenderBulletsAndSections(title, bullets, sections) + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: md, + Records: records, + } +} diff --git a/internal/extract/wave3_community_test.go b/internal/extract/wave3_community_test.go new file mode 100644 index 0000000..a78116a --- /dev/null +++ b/internal/extract/wave3_community_test.go @@ -0,0 +1,276 @@ +package extract + +import ( + "encoding/json" + "strings" + "testing" + "time" +) + +func TestWave3CommunityHTMLModesPositiveAndNegative(t *testing.T) { + // 1. #242 chambermaster-growthzone (via Round2RunHTML chambermaster_html) + cmHTML := `Business Directory Search | Brownstown Chamber

Business Directory Search

Main Street Bakery

Artisan sourdough and pastries in downtown Brownstown.

` + cmRes := Round2RunHTML("chambermaster_html", cmHTML, "https://www.brownstownchamber.org/list/", "") + if cmRes == nil || cmRes.ExtractorID != "chambermaster-growthzone" { + t.Fatalf("chambermaster positive failed: %+v", cmRes) + } + if !strings.Contains(cmRes.Markdown, "Main Street Bakery") || !strings.Contains(cmRes.Markdown, "Monthly Chamber Networking Mixer") { + t.Fatalf("chambermaster missing expected items:\n%s", cmRes.Markdown) + } + cmEmpty := `Directory
` + if got := Round2RunHTML("chambermaster_html", cmEmpty, "https://www.brownstownchamber.org/list/", ""); got != nil { + t.Fatalf("chambermaster empty mn-content must return nil, got %+v", got) + } + if got := Round2RunHTML("chambermaster_html", cmHTML, "https://example.chambermaster.com/login", ""); got != nil { + t.Fatalf("chambermaster /login must return nil") + } + + // 2. #243 wild-apricot (skips "Wrong document context!" first h1, rejects /sys/login & WaGadgetLoginButton-only shell) + waHTML := `North Dakota Society of Health-System Pharmacists - Dakota Night

Wrong document context!

Dakota Night ASHP Mid-Year Clinical Meeting

Annual clinical networking reception for North Dakota pharmacists and pharmacy residents.

Event Details
` + waRes := Wave3CommunityRunHTML("wild_apricot_html", waHTML, "https://www.ndshp.org/event-6925405", "") + if waRes == nil || waRes.ExtractorID != "wild-apricot" { + t.Fatalf("wild-apricot positive failed: %+v", waRes) + } + if strings.Contains(waRes.Title, "Wrong document context") || !strings.Contains(waRes.Title, "Dakota Night ASHP Mid-Year Clinical Meeting") { + t.Fatalf("wild-apricot must skip Wrong document context h1, got title=%q", waRes.Title) + } + waGated := `Members Only

Members only content. Log in to continue.

` + if got := Wave3CommunityRunHTML("wild_apricot_html", waGated, "https://members.mbbi.org/private", ""); got != nil { + t.Fatalf("wild-apricot WaGadgetLoginButton-only shell must return nil, got %+v", got) + } + if got := Wave3CommunityRunHTML("wild_apricot_html", waHTML, "https://www.ndshp.org/sys/login", ""); got != nil { + t.Fatalf("wild-apricot /sys/login must return nil") + } + + // 3. #244 association-ams-pack (Novi AMS + MemberClicks/Personify) + noviHTML := `Events - Austin Apartment Association

Events

2026 Annual Trade Show & Expo

Connect with multifamily property managers and suppliers across Central Texas.

` + noviRes := Wave3CommunityRunHTML("association_ams_html", noviHTML, "https://www.austinaptassoc.com/events", "") + if noviRes == nil || noviRes.ExtractorID != "association-ams-pack" || !strings.Contains(noviRes.Markdown, "Novi AMS") || !strings.Contains(noviRes.Markdown, "2026 Annual Trade Show") { + t.Fatalf("novi AMS positive failed: %+v", noviRes) + } + mcHTML := `Events | Arlington Chamber of Commerce
Chamber Breakfast Roundtable

Monthly civic and business leadership briefing at Arlington Chamber headquarters.

` + mcRes := Wave3CommunityRunHTML("association_ams_html", mcHTML, "https://web.arlingtonchamber.org/events", "") + if mcRes == nil || mcRes.ExtractorID != "association-ams-pack" || !strings.Contains(mcRes.Markdown, "MemberClicks / Personify") || !strings.Contains(mcRes.Markdown, "Chamber Breakfast Roundtable") { + t.Fatalf("memberclicks positive failed: %+v", mcRes) + } + + // 4. #245 runsignup HTML SportsEvent JSON-LD + rsHTML := `Bacon & Bubbles 5K

Bacon & Bubbles 5K

` + rsRes := Wave3CommunityRunHTML("runsignup_html", rsHTML, "https://runsignup.com/Race/MI/PortHuron/BaconandBubbles5k1Mile", "") + if rsRes == nil || rsRes.ExtractorID != "runsignup" || !strings.Contains(rsRes.Markdown, "2027-06-12") || !strings.Contains(rsRes.Markdown, "Port Huron, MI, 48060") { + t.Fatalf("runsignup HTML positive failed: %+v", rsRes) + } + + // 5. #246 bikereg-usacycling Sport80 Inertia FindEventsPage & ResultsPage + CF rejection + s80EventsHTML := `Events
` + s80EvRes := Wave3CommunityRunHTML("bikereg_usacycling_html", s80EventsHTML, "https://usacycling.sport80.com/pub/e_locator/events/find?from_date=today", "") + if s80EvRes == nil || s80EvRes.ExtractorID != "bikereg-usacycling" || !strings.Contains(s80EvRes.Markdown, "Sunshine State Criterium Series") || !strings.Contains(s80EvRes.Markdown, "USA Cycling") { + t.Fatalf("sport80 FindEventsPage failed: %+v", s80EvRes) + } + s80ResultsHTML := `Results
` + s80ResRes := Wave3CommunityRunHTML("bikereg_usacycling_html", s80ResultsHTML, "https://usacycling.sport80.com/pub/results", "") + if s80ResRes == nil || s80ResRes.ExtractorID != "bikereg-usacycling" || !strings.Contains(s80ResRes.Markdown, "USA Cycling Results") { + t.Fatalf("sport80 ResultsPage failed: %+v", s80ResRes) + } + cfHTML := `Just a moment...
` + if got := Wave3CommunityRunHTML("bikereg_usacycling_html", cfHTML, "https://www.bikereg.com/", ""); got != nil { + t.Fatalf("bikereg CF challenge must return nil, got %+v", got) + } + + // 6. #247 race-results-pack (active.com Event JSON-LD + strict CSR shell rejection) + activeHTML := `9th Annual Homewood Holiday 5k

9th Annual Homewood Holiday 5k

` + rrRes := Wave3CommunityRunHTML("race_results_pack_html", activeHTML, "https://www.active.com/baltimore-md/running/distance-running-races/9th-annual-homewood-holiday-5k-2026", "") + if rrRes == nil || rrRes.ExtractorID != "race-results-pack" || !strings.Contains(rrRes.Markdown, "Homewood Holiday 5k") || !strings.Contains(rrRes.Markdown, "2026-12-06") { + t.Fatalf("race-results-pack positive failed: %+v", rrRes) + } + athlinksCSR := `Athlinks
` + if got := Wave3CommunityRunHTML("race_results_pack_html", athlinksCSR, "https://www.athlinks.com/event/382820", ""); got != nil { + t.Fatalf("race-results-pack must strictly reject Athlinks CSR shell, got %+v", got) + } + + // 7. #248 lemmy HTML fallback + non-Lemmy prefilter + lemmyHTML := `Memes - lemmy.ml

Open Source Weekend Thread

Share the open source projects you have been testing this week across the Fediverse.

` + lemRes := Wave3CommunityRunHTML("lemmy_html", lemmyHTML, "https://lemmy.ml/post/55819348", "") + if lemRes == nil || lemRes.ExtractorID != "lemmy" || !strings.Contains(lemRes.Markdown, "Open Source Weekend Thread") { + t.Fatalf("lemmy_html positive failed: %+v", lemRes) + } + nonLemmyBlog := `Rock History

A tribute article about Lemmy Kilmister and classic rock albums.

` + if got := Wave3CommunityRunHTML("lemmy_html", nonLemmyBlog, "https://blog.example.org/rock", ""); got != nil { + t.Fatalf("lemmy_html must not match unrelated blog mentioning lemmy") + } + + // 8. #249 peertube HTML fallback + ptHTML := `Blender Today LIVE #294 - PeerTube

Blender Today LIVE #294

` + ptRes := Wave3CommunityRunHTML("peertube_html", ptHTML, "https://video.blender.org/w/v3kudnbEWnLVG5Fzormny6", "") + if ptRes == nil || ptRes.ExtractorID != "peertube" || !strings.Contains(ptRes.Markdown, "Pablo Vazquez") { + t.Fatalf("peertube_html positive failed: %+v", ptRes) + } + + // 9. #250 fediverse-pack Mbin/Kbin SSR HTML + Anubis PoW + Misskey CSR rejection + mbinHTML := `Federated Thread | kbin.earth

Open Web Standards Update

news@lemmy.world

New W3C working draft improves interoperable ActivityPub discovery across community servers.

Great progress for federated threads!
` + mbRes := Wave3CommunityRunHTML("fediverse_pack_html", mbinHTML, "https://kbin.earth/m/news@lemmy.world/t/3423982", "") + if mbRes == nil || mbRes.ExtractorID != "fediverse-pack" || !strings.Contains(mbRes.Markdown, "Great progress for federated threads") { + t.Fatalf("fediverse_pack_html positive failed: %+v", mbRes) + } + anubisHTML := `Making sure you're not a bot!

Making sure you're not a bot!

` + if got := Wave3CommunityRunHTML("fediverse_pack_html", anubisHTML, "https://gehirneimer.de/", ""); got != nil { + t.Fatalf("fediverse_pack_html must reject Anubis PoW, got %+v", got) + } + misskeyShell := `Misskey
` + if got := Wave3CommunityRunHTML("fediverse_pack_html", misskeyShell, "https://misskey.io/notes/au4n1wud00cl0t3s", ""); got != nil { + t.Fatalf("fediverse_pack_html must reject Misskey empty CSR shell") + } +} + +func TestWave3CommunityJSONModes(t *testing.T) { + // 1. runsignup_json (single race + list + error rejection) + rsJSON := `{"race":{"race_id":68640,"name":"Bacon & Bubbles 5K or 1 Mile","url":"https://runsignup.com/Race/MI/PortHuron/BaconandBubbles5k1Mile","last_date":"06/13/2026","next_date":"06/12/2027","is_registration_open":"F","address":{"city":"Port Huron","state":"MI","zipcode":"48060"},"description":"

Family-friendly fun run along the St. Clair River.

","events":[{"event_id":1,"name":"5K Run","distance":"5K","start_time":"06/12/2027 09:00"}]}}` + rsDoc, ok := FormatWave3CommunityJSONDoc("runsignup_json", []byte(rsJSON), nil, "https://runsignup.com/Rest/race/68640?format=json") + if !ok || rsDoc == nil || !strings.Contains(rsDoc.Markdown, "2027-06-12") || !strings.Contains(rsDoc.Markdown, "5K Run") { + t.Fatalf("runsignup_json single failed: ok=%v doc=%+v", ok, rsDoc) + } + if _, okErr := FormatWave3CommunityJSONDoc("runsignup_json", []byte(`{"error":{"error_code":404,"error_msg":"Invalid race ID"}}`), nil, "https://runsignup.com/Rest/race/0?format=json"); okErr { + t.Fatalf("runsignup_json must reject error response") + } + + // 2. bikereg_json (ASP.NET /Date(1795755600000-0500)/ timestamp parsing) + brJSON := `{"CompletionTime":0,"MatchingEvents":[{"EventId":77778,"EventName":"Hush Money Gravel Classic","EventUrl":"https://www.bikereg.com/hush-money","EventAddress":"414 N Mary St","EventCity":"Lancaster","EventState":"PA","EventDate":"/Date(1795755600000-0500)/","Categories":[{"CategoryID":980084,"CategoryName":"Both Distances - Open","Distance":"55 miles","EntryFee":25.0,"StartTime":"10:00:00","CategoryDates":["/Date(1795755600000-0500)/"]}]}]}` + brDoc, ok := FormatWave3CommunityJSONDoc("bikereg_json", []byte(brJSON), nil, "https://www.bikereg.com/api/search?name=Hush%20Money") + if !ok || brDoc == nil || !strings.Contains(brDoc.Markdown, "Hush Money Gravel Classic") || !strings.Contains(brDoc.Markdown, "2026-11-27") || !strings.Contains(brDoc.Markdown, "$25.00") { + t.Fatalf("bikereg_json failed: ok=%v doc=%+v", ok, brDoc) + } + if _, okEmpty := FormatWave3CommunityJSONDoc("bikereg_json", []byte(`{"CompletionTime":0,"MatchingEvents":[]}`), nil, "https://www.bikereg.com/api/search?name=none"); okEmpty { + t.Fatalf("bikereg_json must reject empty MatchingEvents") + } + + // 3. lemmy_json (post_view + community_view + comments + error) + lemPostJSON := `{"post_view":{"post":{"id":54926010,"name":"Lost Art","url":"https://example.org/art.webp","body":"Source link inside body.","published":"2026-11-27T19:02:23.319418Z"},"creator":{"name":"Gormadt","display_name":"Gormadt"},"community":{"name":"comics"},"counts":{"score":142,"comments":19}}}` + lemDoc, ok := FormatWave3CommunityJSONDoc("lemmy_json", []byte(lemPostJSON), nil, "https://lemmy.world/api/v3/post?id=54926010") + if !ok || lemDoc == nil || !strings.Contains(lemDoc.Markdown, "Lost Art") || !strings.Contains(lemDoc.Markdown, "!comics") { + t.Fatalf("lemmy_json post_view failed: ok=%v doc=%+v", ok, lemDoc) + } + lemCommJSON := `{"community_view":{"community":{"id":1381,"name":"memes","title":"Memes Community","description":"Community rules and weekly threads."},"counts":{"subscribers":42000,"posts":9100}}}` + if commDoc, okC := FormatWave3CommunityJSONDoc("lemmy_json", []byte(lemCommJSON), nil, "https://lemmy.world/api/v3/community?name=memes"); !okC || !strings.Contains(commDoc.Markdown, "42000") { + t.Fatalf("lemmy_json community_view failed: ok=%v doc=%+v", okC, commDoc) + } + if _, okErr := FormatWave3CommunityJSONDoc("lemmy_json", []byte(`{"error":"couldnt_find_post"}`), nil, "https://lemmy.world/api/v3/post?id=0"); okErr { + t.Fatalf("lemmy_json must reject error") + } + + // 4. peertube_json (video + captions) + ptJSON := `{"id":59309,"uuid":"eb2c8482-d8aa-4e21-893f-868d1df60869","shortUUID":"v3kudnbEWnLVG5Fzormny6","url":"https://video.blender.org/videos/watch/eb2c8482-d8aa-4e21-893f-868d1df60869","name":"PAINT features + Bye 2026 - Blender Today LIVE #294","description":"Weekly Blender development show.","duration":2712,"views":4210,"likes":315,"publishedAt":"2026-11-25T16:00:00.000Z","channel":{"displayName":"Blender Today"},"category":{"label":"Science & Technology"},"licence":{"label":"CC-BY"}}` + ptDoc, ok := FormatWave3CommunityJSONDoc("peertube_json", []byte(ptJSON), nil, "https://video.blender.org/api/v1/videos/v3kudnbEWnLVG5Fzormny6") + if !ok || ptDoc == nil || !strings.Contains(ptDoc.Markdown, "Blender Today") || !strings.Contains(ptDoc.Markdown, "CC-BY") { + t.Fatalf("peertube_json failed: ok=%v doc=%+v", ok, ptDoc) + } + ptCapJSON := `{"total":1,"data":[{"language":{"id":"en","label":"English"},"captionPath":"/lazy-static/video-captions/abc.vtt"}]}` + if capDoc, okCap := FormatWave3CommunityJSONDoc("peertube_json", []byte(ptCapJSON), nil, "https://video.blender.org/api/v1/videos/v3kudnbEWnLVG5Fzormny6/captions"); !okCap || !strings.Contains(capDoc.Markdown, "English") { + t.Fatalf("peertube_json captions failed: ok=%v doc=%+v", okCap, capDoc) + } + if _, okEmptyCap := FormatWave3CommunityJSONDoc("peertube_json", []byte(`{"total":0,"data":[]}`), nil, "https://video.blender.org/api/v1/videos/v3kudnbEWnLVG5Fzormny6/captions"); okEmptyCap { + t.Fatalf("peertube_json empty captions must return false") + } + + // 5. fediverse_pack_json (Misskey note + ActivityPub Page) + mkJSON := `{"id":"au4n1wud00cl0t3s","createdAt":"2026-11-29T00:01:36.133Z","user":{"name":"Test User","username":"testuser","host":null},"text":"Hello from Misskey fediverse note!","visibility":"public","reactionCount":15}` + mkDoc, ok := FormatWave3CommunityJSONDoc("fediverse_pack_json", []byte(mkJSON), map[string]string{"host": "misskey.io"}, "https://misskey.io/notes/au4n1wud00cl0t3s") + if !ok || mkDoc == nil || !strings.Contains(mkDoc.Markdown, "@testuser@misskey.io") || !strings.Contains(mkDoc.Markdown, "Hello from Misskey fediverse note!") { + t.Fatalf("fediverse_pack_json Misskey failed: ok=%v doc=%+v", ok, mkDoc) + } + apJSON := `{"@context":"https://www.w3.org/ns/activitystreams","type":"Page","id":"https://kbin.earth/m/tech/t/123","attributedTo":"https://kbin.earth/u/alice","audience":"https://kbin.earth/m/tech","name":"Federated Thread Title","content":"

Discussion on open standards.

","published":"2026-11-28T23:18:30Z"}` + if apDoc, okAP := FormatWave3CommunityJSONDoc("fediverse_pack_json", []byte(apJSON), nil, "https://kbin.earth/m/tech/t/123"); !okAP || !strings.Contains(apDoc.Markdown, "Federated Thread Title") { + t.Fatalf("fediverse_pack_json ActivityPub failed: ok=%v doc=%+v", okAP, apDoc) + } + if encoded, okEnc := FormatWave3CommunityJSONMode("fediverse_pack_json", []byte(mkJSON), nil, "https://misskey.io/notes/au4n1wud00cl0t3s"); !okEnc || !json.Valid([]byte(encoded)) { + t.Fatalf("FormatWave3CommunityJSONMode failed") + } +} + +func TestWave3CommunityNegativeShellsAndPerfBudget(t *testing.T) { + modes := []string{ + "chambermaster_growthzone_html", + "wild_apricot_html", + "association_ams_html", + "runsignup_html", + "bikereg_usacycling_html", + "race_results_pack_html", + "lemmy_html", + "peertube_html", + "fediverse_pack_html", + } + negShells := []struct { + name string + url string + html string + }{ + {"404", "https://example.org/item", `404 - Page Not Found

Not Found

`}, + {"error-redirect", "https://example.org/error", `Portal
Error
`}, + {"maintenance", "https://example.org/events", `503 Service Unavailable

Site is down for maintenance. Please check back soon.

`}, + {"empty-spa", "https://example.org/app", `Loading...
`}, + {"anubis-pow", "https://example.org/thread", `Making sure you're not a bot!

Making sure you're not a bot!

`}, + } + for _, m := range modes { + for _, ns := range negShells { + if res := Wave3CommunityRunHTML(m, ns.html, ns.url, ""); res != nil { + t.Fatalf("mode %s negative %s returned non-nil: %+v", m, ns.name, res) + } + } + } + + // Prefilter hot-path latency check (< 75ms across all 9 modes on 250KB unrelated HTML) + bigUnrelated := "News" + strings.Repeat("

Community garden notes and local updates.

", 4500) + "" + start := time.Now() + for _, m := range modes { + if res := Wave3CommunityRunHTML(m, bigUnrelated, "https://unrelated.example.org/news", ""); res != nil { + t.Fatalf("mode %s unexpectedly matched unrelated HTML", m) + } + } + if elapsed := time.Since(start); elapsed > 75*time.Millisecond*time.Duration(extractRaceSlowdown) { + t.Fatalf("all 9 modes prefilter scan exceeded 75ms budget: %v", elapsed) + } +} + +func TestWave3CommunityNonHijackAndASPNetDateBounds(t *testing.T) { + // Finding 4: association-ams-pack MUST NOT hijack prose containing "personify" + personifyHTML := `Literary Devices

Personification

Poets often personify nature to convey human emotion in verse.

  • Metaphor
  • Simile
` + if got := Wave3CommunityRunHTML("association_ams_html", personifyHTML, "https://lit.example.org/devices", ""); got != nil { + t.Fatalf("association-ams-pack hijacked unrelated page containing 'personify': %+v", got) + } + + // Finding 5: chambermaster-growthzone MUST NOT hijack "tar-gz-" / "gz-" in generic class/url + gzHTML := `Archive Tools

Download compressed archive packages safely.

  • tar.gz format
` + if got := Round2RunHTML("chambermaster_html", gzHTML, "https://tools.example.org/tar-gz-info", ""); got != nil { + t.Fatalf("chambermaster-growthzone hijacked unrelated page containing 'gz-': %+v", got) + } + // Positive GrowthZone gz-card MUST still match + gzCardHTML := `Members
Acme Co

Local manufacturing partner.

` + if got := Round2RunHTML("chambermaster_html", gzCardHTML, "https://chamber.example.org/list", ""); got == nil || got.ExtractorID != "chambermaster-growthzone" { + t.Fatalf("chambermaster-growthzone gz-card positive failed: %+v", got) + } + + // Finding 5: wild-apricot MUST NOT hijack "validevent", "avoidevent", "gridevent" + gridHTML := `UI Grid Events

Handle validevent and avoidevent callbacks cleanly in JS.

  • onClick
` + if got := Wave3CommunityRunHTML("wild_apricot_html", gridHTML, "https://ui.example.org/events", ""); got != nil { + t.Fatalf("wild-apricot hijacked unrelated page containing 'gridevent'/'validevent': %+v", got) + } + + // Finding 10: #246 bikereg ASP.NET /Date(ms-tz)/ invalid timezone offsets & out-of-range years MUST be rejected + for _, badDate := range []string{ + "/Date(1751328000000+9999)/", + "/Date(1751328000000-0499)/", + "/Date(999999999999999)/", + "/Date(-62135596800000)/", + "/Date(-86400000)/", + "/Date(2524608000000)/", + } { + if parsed := wave3CommParseASPNetDate(badDate); parsed != "" { + t.Fatalf("wave3CommParseASPNetDate(%q) = %q, want empty string", badDate, parsed) + } + if norm := wave3CommNormalizeDate(badDate); norm != "" { + t.Fatalf("wave3CommNormalizeDate(%q) = %q, want empty string", badDate, norm) + } + } + if okDate := wave3CommParseASPNetDate("/Date(1751328000000-0400)/"); okDate != "2025-06-30T20:00:00-04:00" { + t.Fatalf("valid ASP.NET date failed: got %q", okDate) + } +} diff --git a/internal/extract/wave3_cycling_components.go b/internal/extract/wave3_cycling_components.go new file mode 100644 index 0000000..be94a08 --- /dev/null +++ b/internal/extract/wave3_cycling_components.go @@ -0,0 +1,2302 @@ +package extract + +import ( + "bytes" + "encoding/json" + "fmt" + stdhtml "html" + "math" + "sort" + "strconv" + "strings" +) + +const ( + wave3CycMaxHTMLBytes = 2 * 1024 * 1024 + wave3CycStdHTMLMaxBytes = 1 * 1024 * 1024 + wave3CycMaxJSONBytes = 2 * 1024 * 1024 + wave3CycMaxRecords = 25 +) + +var ( + wave3CycRxNotFoundTitle = newLazyRegexp(`(?i)(?:^|\b)(?:404|410|406|429|page\s+not\s+found|not\s+found|error\s*404|we\s+couldn'?t\s+find\s+that\s+page|access\s+denied|request\s+(?:rejected|blocked)|could\s+not\s+be\s+satisfied|unauthorized|attention\s+required|just\s+a\s+moment|403\s+forbidden|forbidden|403\s+error|vercel\s+security\s+checkpoint|security\s+checkpoint)(?:\b|$)`) + wave3CycRxMaintTitle = newLazyRegexp(`(?i)(?:scheduled\s+maintenance|temporarily\s+unavailable|service\s+unavailable|site\s+maintenance|under\s+maintenance|502\s+bad\s+gateway|503\s+service|down\s+for\s+maintenance)`) + wave3CycRxErrorTitle = newLazyRegexp(`(?i)^(?:(?:(?:400|401|403|404|406|410|429|500|502|503)\s+)?(?:internal\s+)?server\s+error|application\s+error|system\s+error|unexpected\s+error|error\s+page|(?:400|401|403|404|406|410|429|500|502|503|http\s+\d{3})\s+error|error\s+(?:400|401|403|404|406|410|429|500|502|503)|error)(?:\s*[|\-\x{2013}\x{2014}:]\s*.*)?$|^.*(?:\s*[|\-\x{2013}\x{2014}:]\s*error)$`) + wave3CycRxGenericTitle = newLazyRegexp(`(?i)^(?:loading\.{0,3}|home|welcome|search|kenda\s+tire\s*\|\s*corporate\s*\|\s*error)$`) + wave3CycRxHTMLTag = newLazyRegexp(`<[^>]+>`) + wave3CycRxSpaceCollapse = newLazyRegexp(`[ \t\r\n]+`) + wave3CycRxPriceNum = newLazyRegexp(`(?:USD|CAD|EUR|GBP|AUD|CHF|\$|€|£)?\s*([0-9][0-9,]*(?:\.[0-9]{1,2})?)`) + wave3CycRxGTIN = newLazyRegexp(`^\d{8}$|^\d{12}$|^\d{13}$|^\d{14}$`) + + // #341 FOX Tune ID / code + wave3CycRxFoxTuneCode = newLazyRegexp(`(?i)\b(?:tune\s*(?:id|code)|id\s*code|4-?digit\s*code)\s*[:#]?\s*([A-Z0-9]{4,8})\b`) + wave3CycRxFoxPathCode = newLazyRegexp(`(?i)/code/([A-Z0-9]{4,8})(?:[/?#]|$)`) + + // #344 E-bike drive system specs + wave3CycRxTorqueNm = newLazyRegexp(`(?i)\b(\d{2,3}(?:\.\d+)?)\s*Nm\b`) + wave3CycRxBatteryWh = newLazyRegexp(`(?i)\b(\d{3,4}(?:\.\d+)?)\s*Wh\b`) + wave3CycRxMotorWatt = newLazyRegexp(`(?i)\b(\d{3,4})\s*W(?:att)?s?\b`) + wave3CycRxDriveVolt = newLazyRegexp(`(?i)\b(24|36|43|48|50\.4|52)\s*V\b`) + wave3CycRxWeightSpec = newLazyRegexp(`(?i)\b(\d{2,4}(?:\.\d+)?)\s*(g|grams|kg)\b`) + + // #346 Tire specs (ETRTO ISO 5775 + imperial/French + TPI + tubeless) + wave3CycRxETRTOCandidate = newLazyRegexp(`(?:^|[^0-9A-Za-z])(\d{2,3})\s*-\s*(\d{3})(?:$|[^0-9A-Za-z])`) + wave3CycRxTireSizeImp = newLazyRegexp(`(?i)\b((?:700|650)\s*[x×]\s*\d{2,3}(?:\s*[bBcC])?|(?:20|24|26|27\.5|29)\s*[x×]\s*\d+(?:\.\d{1,2})?)\b`) + wave3CycRxTPI = newLazyRegexp(`(?i)\b(\d{2,3})\s*TPI\b`) + + // #347 Wheel & hub specs + wave3CycRxHubOLD = newLazyRegexp(`(?i)\b(100|110|130|135|142|148|150|157|177|197)\s*mm\b`) + wave3CycRxHubHoles = newLazyRegexp(`(?i)\b(16|20|24|28|32|36)\s*(?:H|hole|holes|spoke)\b`) + wave3CycRxHubEngagement = newLazyRegexp(`(?i)\b(\d{2,3}\s*(?:T\s*ratchet|POE|points?\s+of\s+engagement)|[0-9]+(?:\.[0-9]+)?\s*(?:deg|degree|°)\s*engagement)\b`) + + // #348 Brake specs + wave3CycRxBrakeRotor = newLazyRegexp(`(?i)\b(140|160|180|200|203|220|223)\s*mm\b`) + wave3CycRxBrakeThick = newLazyRegexp(`(?i)\b(1\.8|2\.0|2\.25|2\.3)\s*mm\b`) + wave3CycRxBrakePistons = newLazyRegexp(`(?i)\b([246])\s*-?\s*piston\b`) + + // #349 Suspension & cockpit compatibility + wave3CycRxSHIS = newLazyRegexp(`(?i)\b((?:IS|ZS|EC)(?:34|41|42|44|49|52|56)(?:/[0-9.]+)?)\b`) + wave3CycRxBCD = newLazyRegexp(`(?i)\b((?:94|96|104|110|130|144)\s*BCD|Direct\s+Mount|3-Bolt|8-Bolt|Cinch)\b`) + wave3CycRxShockSize = newLazyRegexp(`(?i)\b((?:165|185|190|200|205|210|216|225|230|240|250)\s*[x×]\s*(?:38|40|42\.5|45|47\.5|50|52\.5|55|57\.5|60|62\.5|65|70|75)(?:\s*mm)?)\b`) + wave3CycRxClampDiam = newLazyRegexp(`(?i)\b(27\.2|30\.9|31\.6|31\.8|34\.9|35(?:\.0)?)\s*mm\b`) +) + +// Canonical ISO 5775 bicycle rim bead seat diameters (mm). +var wave3CycISO5775BSDs = map[int]bool{ + 203: true, + 254: true, + 305: true, + 349: true, + 355: true, + 406: true, + 451: true, + 507: true, + 540: true, + 559: true, + 571: true, + 584: true, + 590: true, + 622: true, + 630: true, + 635: true, +} + +func init() { + registerWave3CyclingComponentsHTMLModes() +} + +// RegisterWave3CyclingComponentsHTMLModes registers all Category O1 Bike Components & Help HTML modes lazily. +func RegisterWave3CyclingComponentsHTMLModes() { + registerWave3CyclingComponentsHTMLModes() +} + +func registerWave3CyclingComponentsHTMLModes() { + for _, mode := range []string{ + "fox_ridefox_html", + "park_tool_html", + "ifixit_html", + "ebike_drive_systems_html", + "specialized_turbo_support_html", + "bicycle_tire_specs_html", + "wheel_hub_specs_html", + "bicycle_brake_docs_html", + "suspension_cockpit_compat_html", + } { + m := mode + RegisterExternalHTMLModeLazy(m, func(rawHTML, baseURL string, _ func() string, extractorID string) *DeclarativePostFetchResult { + return Wave3CyclingComponentsRunHTML(m, rawHTML, baseURL, extractorID) + }) + } +} + +// IsWave3CyclingComponentsHTMLMode reports whether mode is one of the 9 Category O1 HTML modes (#341-#349). +func IsWave3CyclingComponentsHTMLMode(mode string) bool { + switch mode { + case "fox_ridefox_html", + "park_tool_html", + "ifixit_html", + "ebike_drive_systems_html", + "specialized_turbo_support_html", + "bicycle_tire_specs_html", + "wheel_hub_specs_html", + "bicycle_brake_docs_html", + "suspension_cockpit_compat_html": + return true + default: + return false + } +} + +// IsWave3CyclingComponentsJSONMode reports whether mode is handled by Category O1 JSON formatters (`ifixit_json`). +func IsWave3CyclingComponentsJSONMode(mode string) bool { + return mode == "ifixit_json" +} + +func wave3CycDefaultExtractorID(mode string) string { + switch mode { + case "fox_ridefox_html": + return "fox-ridefox" + case "park_tool_html": + return "park-tool" + case "ifixit_html", "ifixit_json": + return "ifixit" + case "ebike_drive_systems_html": + return "ebike-drive-systems" + case "specialized_turbo_support_html": + return "specialized-turbo-support" + case "bicycle_tire_specs_html": + return "bicycle-tire-specs" + case "wheel_hub_specs_html": + return "wheel-hub-specs" + case "bicycle_brake_docs_html": + return "bicycle-brake-docs" + case "suspension_cockpit_compat_html": + return "suspension-cockpit-compat" + default: + return "" + } +} + +// Wave3CyclingComponentsRunHTML executes a Category O1 HTML extractor and returns DeclarativePostFetchResult. +func Wave3CyclingComponentsRunHTML(mode, rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + if !IsWave3CyclingComponentsHTMLMode(mode) || len(rawHTML) == 0 || strings.IndexByte(rawHTML, '<') < 0 || strings.IndexByte(rawHTML, '>') < 0 { + return nil + } + maxHTML := wave3CycStdHTMLMaxBytes + if mode == "bicycle_tire_specs_html" || mode == "wheel_hub_specs_html" || mode == "suspension_cockpit_compat_html" || mode == "ebike_drive_systems_html" { + maxHTML = wave3CycMaxHTMLBytes + } + if len(rawHTML) > maxHTML { + rawHTML = truncateUTF8SafeFullDocGo(rawHTML, maxHTML) + } + trimmedStart := strings.TrimLeft(rawHTML, " \t\r\n") + if trimmedStart == "" || trimmedStart[0] == '{' || trimmedStart[0] == '[' { + return nil + } + probe := rawHTML + if len(probe) > 65536 { + probe = probe[:65536] + } + probeLower := asciiLowerExtractString(probe) + urlLower := asciiLowerExtractString(baseURL) + + // Cheap byte prefilter BEFORE common negative-shell checks or DOM parsing. + if !wave3CycMatchesPrefilter(mode, rawHTML, probeLower, urlLower) { + return nil + } + if wave3CycHasNegativeShell(mode, rawHTML, probeLower, urlLower) { + return nil + } + if extractorID == "" { + extractorID = wave3CycDefaultExtractorID(mode) + } + + var res *DeclarativePostFetchResult + switch mode { + case "fox_ridefox_html": + res = wave3CycExtractFoxRidefoxHTML(rawHTML, baseURL, extractorID) + case "park_tool_html": + res = wave3CycExtractParkToolHTML(rawHTML, baseURL, extractorID) + case "ifixit_html": + res = wave3CycExtractIFixitHTML(rawHTML, baseURL, extractorID) + case "ebike_drive_systems_html": + res = wave3CycExtractEBikeDriveHTML(rawHTML, baseURL, extractorID) + case "specialized_turbo_support_html": + res = wave3CycExtractSpecializedTurboSupportHTML(rawHTML, baseURL, extractorID) + case "bicycle_tire_specs_html": + res = wave3CycExtractBicycleTireSpecsHTML(rawHTML, baseURL, extractorID) + case "wheel_hub_specs_html": + res = wave3CycExtractWheelHubSpecsHTML(rawHTML, baseURL, extractorID) + case "bicycle_brake_docs_html": + res = wave3CycExtractBicycleBrakeDocsHTML(rawHTML, baseURL, extractorID) + case "suspension_cockpit_compat_html": + res = wave3CycExtractSuspensionCockpitHTML(rawHTML, baseURL, extractorID) + } + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return nil + } + return wave3CycFinalizePostFetch(res) +} + +// RunWave3CyclingComponentsHTMLMode executes a Category O1 HTML extractor and returns JSON-marshaled DeclarativePostFetchResult. +func RunWave3CyclingComponentsHTMLMode(mode, rawHTML, baseURL string) (string, bool) { + res := Wave3CyclingComponentsRunHTML(mode, rawHTML, baseURL, wave3CycDefaultExtractorID(mode)) + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return "", false + } + res = sanitizePostFetchResultDeclHTML(res) + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return "", false + } + encoded, err := json.Marshal(res) + if err != nil { + return "", false + } + return string(encoded), true +} + +// FormatWave3CyclingComponentsJSONDoc formats a Category O1 JSON twin payload (`ifixit_json`) into DeclarativeFormattedDoc. +func FormatWave3CyclingComponentsJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool) { + return formatWave3CyclingComponentsJSON(mode, raw, params, origURL) +} + +// FormatWave3CyclingComponentsJSONMode formats a Category O1 JSON payload and returns JSON-marshaled DeclarativeFormattedDoc. +func FormatWave3CyclingComponentsJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool) { + doc, ok := formatWave3CyclingComponentsJSON(mode, raw, params, origURL) + if !ok || doc == nil { + return "", false + } + encoded, err := json.Marshal(doc) + if err != nil { + return "", false + } + return string(encoded), true +} + +func formatWave3CyclingComponentsJSON(mode string, raw []byte, _ map[string]string, origURL string) (*DeclarativeFormattedDoc, bool) { + if !IsWave3CyclingComponentsJSONMode(mode) || len(raw) == 0 || len(raw) > wave3CycMaxJSONBytes { + return nil, false + } + trimmed := bytes.TrimSpace(bytes.TrimPrefix(raw, []byte("\xEF\xBB\xBF"))) + if len(trimmed) == 0 || trimmed[0] != '{' { + return nil, false + } + parsed, ok := decodeJSONWithNumbers(trimmed) + if !ok || parsed == nil { + return nil, false + } + doc, handled := wave3CycFormatIFixitJSON(parsed, origURL) + if !handled || doc == nil || strings.TrimSpace(doc.Markdown) == "" { + return nil, false + } + return wave3CycFinalizeDoc(doc), true +} + +// ── Prefilters & Negative-Shell Guards ─────────────────────────────────────────────────────────── + +func wave3CycMatchesPrefilter(mode, rawHTML, probeLower, urlLower string) bool { + if strings.Contains(probeLower, " 65536 { + tail := rawHTML[65536:] + return indexFoldASCIIExtract(tail, "tpi") >= 0 || + indexFoldASCIIExtract(tail, "= 0 || + indexFoldASCIIExtract(tail, "application/ld+json") >= 0 + } + return false + case "wheel_hub_specs_html": + if strings.Contains(probeLower, "hub") || strings.Contains(probeLower, "boost") || strings.Contains(probeLower, "148") || strings.Contains(probeLower, "142") || strings.Contains(probeLower, "engagement") || strings.Contains(probeLower, "bearing") { + return true + } + if len(rawHTML) > 65536 { + tail := rawHTML[65536:] + return indexFoldASCIIExtract(tail, "= 0 || + indexFoldASCIIExtract(tail, "= 0 || + indexFoldASCIIExtract(tail, "application/ld+json") >= 0 + } + return false + case "bicycle_brake_docs_html": + if strings.Contains(probeLower, "rotor") || strings.Contains(probeLower, "caliper") || strings.Contains(probeLower, "brake") || strings.Contains(probeLower, "mineral oil") || strings.Contains(probeLower, "dot ") { + return true + } + if len(rawHTML) > 65536 { + tail := rawHTML[65536:] + return indexFoldASCIIExtract(tail, "= 0 || + indexFoldASCIIExtract(tail, "= 0 || + indexFoldASCIIExtract(tail, "application/ld+json") >= 0 + } + return false + case "suspension_cockpit_compat_html": + if strings.Contains(probeLower, "shis") || strings.Contains(probeLower, "bcd") || strings.Contains(probeLower, "headset") || strings.Contains(probeLower, "chainring") || strings.Contains(probeLower, "shock") || strings.Contains(probeLower, "compat") { + return true + } + if len(rawHTML) > 65536 { + tail := rawHTML[65536:] + return indexFoldASCIIExtract(tail, "= 0 || + indexFoldASCIIExtract(tail, "= 0 || + indexFoldASCIIExtract(tail, "application/ld+json") >= 0 + } + return false + default: + return false + } +} + +func wave3CycIsNegativeURL(urlLower string) bool { + if urlLower == "" { + return false + } + if strings.Contains(urlLower, "/404") || + strings.Contains(urlLower, "/not-found") || + strings.Contains(urlLower, "/page-not-found") || + strings.Contains(urlLower, "/maintenance") || + strings.Contains(urlLower, "error=true") || + strings.Contains(urlLower, "error=1") { + return true + } + pathOnly := urlLower + if idx := strings.Index(pathOnly, "://"); idx >= 0 { + rest := pathOnly[idx+3:] + if slash := strings.IndexByte(rest, '/'); slash >= 0 { + pathOnly = rest[slash:] + } else { + pathOnly = "/" + } + } + if cut := strings.IndexAny(pathOnly, "?#"); cut >= 0 { + pathOnly = pathOnly[:cut] + } + return strings.HasSuffix(pathOnly, "/error") || + strings.Contains(pathOnly, "/error/") || + strings.HasSuffix(pathOnly, "/error.html") || + strings.HasSuffix(pathOnly, "/error.htm") || + strings.HasSuffix(pathOnly, "/error.aspx") || + strings.HasSuffix(pathOnly, "/login") || + strings.Contains(pathOnly, "/login/") +} + +func wave3CycIsNegativeTitle(title string) bool { + t := strings.TrimSpace(title) + if t == "" { + return false + } + return wave3CycRxNotFoundTitle.MatchString(t) || + wave3CycRxMaintTitle.MatchString(t) || + wave3CycRxErrorTitle.MatchString(t) +} + +func wave3CycIsGenericTitle(title string) bool { + return wave3CycRxGenericTitle.MatchString(strings.TrimSpace(title)) +} + +func wave3CycHasNegativeShell(mode, rawHTML, probeLower, urlLower string) bool { + if wave3CycIsNegativeURL(urlLower) { + return true + } + if mode == "ifixit_html" && strings.Contains(urlLower, "/embed/") { + return true + } + for _, marker := range []string{ + "cf-browser-verification", + "_cf_chl_opt", + "cf_chl_opt", + "attention required! | cloudflare", + "just a moment...", + "sorry, you have been blocked", + "enable javascript and cookies to continue", + "errors.edgesuite.net", + "error from cloudfront", + "the request could not be satisfied", + "you don't have permission to access", + "the requested url was rejected", + "your support id is", + "geo.captcha-delivery.com", + "captcha-delivery.com", + "vercel security checkpoint", + "failed to verify your browser", + "scheduled maintenance", + "down for maintenance", + "temporarily unavailable", + "missing authentication token", + "whoops, we couldn't find that page", + "kenda tire | corporate | error", + } { + if strings.Contains(probeLower, marker) { + return true + } + } + + title := extractTitleLinearQuick(probeLower) + if title == "" { + title = extractTitleLinearQuick(rawHTML) + } + if wave3CycIsNegativeTitle(title) { + return true + } + + rawLower := probeLower + if len(rawHTML) > len(probeLower) && len(rawHTML) <= 256*1024 { + rawLower = asciiLowerExtractString(rawHTML) + } + hasRealBodyMarkers := hasJSONLDScriptToken(rawLower) || + strings.Contains(rawLower, " 65536 { + tail := rawHTML[65536:] + hasRealBodyMarkers = indexFoldASCIIExtract(tail, "= 0 || + indexFoldASCIIExtract(tail, "= 0 || + indexFoldASCIIExtract(tail, "application/ld+json") >= 0 + } + + // Cloudflare Turnstile / challenge-platform script tags: many valid 200 product pages + // (industrynine.com, tektro.com, wolftoothcomponents.com) embed CF script tags. + // Only reject if the page is small and lacks product/article body markers. + if (strings.Contains(probeLower, "challenge-platform") || strings.Contains(probeLower, "cf-turnstile")) && + len(rawHTML) < 16384 && !hasRealBodyMarkers { + return true + } + + // #345 specialized-turbo-support eGain JS launcher shell rejection. + if mode == "specialized_turbo_support_html" { + isEGainLauncher := strings.Contains(probeLower, "loading_container") || + strings.Contains(probeLower, "parselaunchparams") || + strings.Contains(probeLower, "saveparamsandloadpage") || + strings.Contains(probeLower, "egglobal") + hasRenderedKB := strings.Contains(rawLower, "`)) + if isEGainLauncher && !hasRenderedKB { + return true + } + } + + // Empty SPA / Aura / Nuxt / Next.js shells. + if (strings.Contains(rawLower, "") || + strings.Contains(rawLower, "salesforce/aura") || + wave3HasEmptyRootDivShell(rawHTML, probeLower, true)) && !hasRealBodyMarkers { + return true + } + return false +} + +// ── Shared Extraction & Hygiene Helpers ────────────────────────────────────────────────────────── + +func wave3CycCleanText(s string) string { + if s == "" { + return "" + } + if strings.IndexByte(s, '<') >= 0 { + s = wave3CycRxHTMLTag.ReplaceAllString(s, " ") + } + if strings.IndexByte(s, '&') >= 0 { + s = stdhtml.UnescapeString(s) + if strings.IndexByte(s, '<') >= 0 { + s = wave3CycRxHTMLTag.ReplaceAllString(s, " ") + } + } + if !strings.ContainsAny(s, "\t\r\n") && !strings.Contains(s, " ") { + return strings.TrimSpace(s) + } + return strings.TrimSpace(wave3CycRxSpaceCollapse.ReplaceAllString(s, " ")) +} + +func wave3CycStringVal(v any) string { + switch tv := v.(type) { + case string: + return strings.TrimSpace(tv) + case json.Number: + return tv.String() + case float64: + if math.IsNaN(tv) || math.IsInf(tv, 0) { + return "" + } + if tv == math.Trunc(tv) { + return strconv.FormatInt(int64(tv), 10) + } + return strconv.FormatFloat(tv, 'f', -1, 64) + case int: + return strconv.Itoa(tv) + case int64: + return strconv.FormatInt(tv, 10) + case bool: + if tv { + return "true" + } + return "false" + default: + return "" + } +} + +func wave3CycPlain(v any, maxLen int) string { + return SanitizeSchemaPlainField(wave3CycStringVal(v), maxLen) +} + +func wave3CycFirstNonEmpty(vals ...string) string { + for _, v := range vals { + if t := strings.TrimSpace(v); t != "" { + return t + } + } + return "" +} + +func wave3CycIntPtr(n int) *int { return &n } +func wave3CycBoolPtr(b bool) *bool { return &b } + +func wave3CycFinalizeDoc(doc *DeclarativeFormattedDoc) *DeclarativeFormattedDoc { + if doc == nil { + return nil + } + if len(doc.Records) > wave3CycMaxRecords { + if doc.Total == nil { + doc.Total = wave3CycIntPtr(len(doc.Records)) + } + doc.Records = doc.Records[:wave3CycMaxRecords] + doc.Returned = wave3CycIntPtr(len(doc.Records)) + doc.Truncated = wave3CycBoolPtr(true) + if doc.NextCursor == "" { + doc.NextCursor = strconv.Itoa(len(doc.Records)) + } + } + if sanitized, ok := sanitizeDeclarativeFormattedDocGo(doc); ok && sanitized != nil { + return sanitized + } + return nil +} + +func wave3CycFinalizePostFetch(res *DeclarativePostFetchResult) *DeclarativePostFetchResult { + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return nil + } + if len(res.Records) > wave3CycMaxRecords { + if res.Total == nil { + res.Total = wave3CycIntPtr(len(res.Records)) + } + res.Records = res.Records[:wave3CycMaxRecords] + res.Returned = wave3CycIntPtr(len(res.Records)) + res.Truncated = wave3CycBoolPtr(true) + if res.NextCursor == "" { + res.NextCursor = strconv.Itoa(len(res.Records)) + } + } + return res +} + +func wave3CycAddLink(links *[]string, seen map[string]bool, raw, base string) { + u := SanitizeSchemaHTTPSURL(raw, base) + if u != "" && !seen[u] { + seen[u] = true + *links = append(*links, u) + } +} + +func wave3CycExtractTitle(doc *HTMLDoc, rawHTML string) string { + if doc != nil { + if h1 := SanitizeSchemaPlainField(wave3CycCleanText(doc.Text("h1")), 240); h1 != "" && !wave3CycIsGenericTitle(h1) && !wave3CycIsNegativeTitle(h1) { + return h1 + } + } + if og := SanitizeSchemaPlainField(extractMetaContentDeclHTML(rawHTML, "og:title"), 240); og != "" && !wave3CycIsGenericTitle(og) && !wave3CycIsNegativeTitle(og) { + return og + } + if t := SanitizeSchemaPlainField(extractTitleLinearQuick(rawHTML), 240); t != "" && !wave3CycIsGenericTitle(t) && !wave3CycIsNegativeTitle(t) { + return t + } + return "" +} + +func wave3CycExtractMetaDesc(rawHTML string) string { + return wave3CycFirstNonEmpty( + SanitizeSchemaPlainField(extractMetaContentDeclHTML(rawHTML, "og:description"), 600), + SanitizeSchemaPlainField(extractMetaContentDeclHTML(rawHTML, "description"), 600), + ) +} + +func wave3CycSlimHTMLForDOM(rawHTML string, maxBytes int) string { + slim := stripScriptsAndStylesDeclHTML(rawHTML) + if maxBytes > 0 && len(slim) > maxBytes { + slim = truncateUTF8SafeFullDocGo(slim, maxBytes) + } + return slim +} + +func wave3CycFragToMD(frag, baseURL string) string { + if strings.TrimSpace(frag) == "" { + return "" + } + if len(frag) > 128*1024 { + frag = truncateUTF8SafeFullDocGo(frag, 128*1024) + } + doc := ExtractHTMLDocumentFull(""+frag+"", FullExtractOptions{ + BaseURL: baseURL, + OnlyMainContent: false, + IncludeImages: false, + IsFragment: true, + SkipUniversalExtractors: true, + SkipPlainText: true, + }) + return strings.TrimSpace(doc.Markdown) +} + +func wave3CycParseStrictPrice(raw string) (string, string) { + cleaned := strings.ReplaceAll(strings.TrimSpace(raw), "$$", "$") + if cleaned == "" || strings.HasPrefix(cleaned, "-") { + return "", "" + } + var currency string + upper := strings.ToUpper(cleaned) + switch { + case strings.Contains(upper, "USD") || strings.Contains(cleaned, "$"): + currency = "USD" + case strings.Contains(upper, "EUR") || strings.Contains(cleaned, "€"): + currency = "EUR" + case strings.Contains(upper, "GBP") || strings.Contains(cleaned, "£"): + currency = "GBP" + case strings.Contains(upper, "CAD"): + currency = "CAD" + case strings.Contains(upper, "AUD"): + currency = "AUD" + } + m := wave3CycRxPriceNum.FindStringSubmatch(cleaned) + if len(m) < 2 { + return "", "" + } + numStr := strings.ReplaceAll(m[1], ",", "") + val, err := strconv.ParseFloat(numStr, 64) + if err != nil || val <= 0 || val > 1_000_000 { + return "", "" + } + return strconv.FormatFloat(val, 'f', 2, 64), currency +} + +func wave3CycValidGTIN(raw string) string { + s := strings.TrimSpace(raw) + if wave3CycRxGTIN.MatchString(s) { + return s + } + return "" +} + +type wave3CycProductMeta struct { + Name string + Brand string + SKU string + MPN string + GTIN string + Price string + Currency string + Availability string + Description string +} + +func wave3CycExtractProductJSONLD(rawHTML string) wave3CycProductMeta { + var out wave3CycProductMeta + for _, ld := range extractJSONLDObjectsDeclHTML(rawHTML, 32) { + if !jsonLDHasType(ld, "Product") && !jsonLDHasType(ld, "ProductGroup") { + continue + } + if out.Name == "" { + out.Name = wave3CycPlain(ld["name"], 220) + } + if out.Description == "" { + out.Description = wave3CycPlain(ld["description"], 800) + } + if out.Brand == "" { + switch br := ld["brand"].(type) { + case map[string]any: + out.Brand = wave3CycPlain(br["name"], 100) + case string: + out.Brand = wave3CycPlain(br, 100) + } + } + if out.SKU == "" { + out.SKU = wave3CycPlain(ld["sku"], 80) + } + if out.MPN == "" { + out.MPN = wave3CycPlain(ld["mpn"], 80) + } + if out.GTIN == "" { + for _, gk := range []string{"gtin14", "gtin13", "gtin12", "gtin8", "gtin"} { + if g := wave3CycValidGTIN(wave3CycStringVal(ld[gk])); g != "" { + out.GTIN = g + break + } + } + } + parseOffer := func(o map[string]any) { + if out.Price == "" { + p, c := wave3CycParseStrictPrice(wave3CycStringVal(o["price"])) + if p != "" { + out.Price = p + if nc := normalizeCurrencyWave2b(o["priceCurrency"]); nc != "" { + out.Currency = nc + } else if c != "" { + out.Currency = c + } + } + } + if out.Availability == "" { + out.Availability = normalizeAvailabilityDeclHTML(wave3CycStringVal(o["availability"])) + } + } + switch off := ld["offers"].(type) { + case map[string]any: + parseOffer(off) + case []any: + for _, elem := range off { + if om, ok := elem.(map[string]any); ok { + parseOffer(om) + if out.Price != "" { + break + } + } + } + } + } + return out +} + +func wave3CycAppendProductBullets(bullets *[]string, pm wave3CycProductMeta) { + if pm.Brand != "" { + *bullets = append(*bullets, "- **Brand**: "+pm.Brand) + } + if pm.SKU != "" { + *bullets = append(*bullets, "- **SKU**: `"+pm.SKU+"`") + } + if pm.MPN != "" && pm.MPN != pm.SKU { + *bullets = append(*bullets, "- **MPN**: `"+pm.MPN+"`") + } + if pm.GTIN != "" { + *bullets = append(*bullets, "- **GTIN**: `"+pm.GTIN+"`") + } + if pm.Price != "" { + if pm.Currency != "" { + *bullets = append(*bullets, "- **Price**: "+pm.Price+" "+pm.Currency) + } else { + *bullets = append(*bullets, "- **Price**: "+pm.Price) + } + } + if pm.Availability != "" { + *bullets = append(*bullets, "- **Availability**: "+pm.Availability) + } +} + +func wave3CycApplyProductToRecord(rec map[string]any, pm wave3CycProductMeta) { + if pm.Brand != "" { + rec["brand"] = pm.Brand + } + if pm.SKU != "" { + rec["sku"] = pm.SKU + } + if pm.MPN != "" { + rec["mpn"] = pm.MPN + } + if pm.GTIN != "" { + rec["gtin"] = pm.GTIN + } + if pm.Price != "" { + rec["price"] = pm.Price + } + if pm.Currency != "" { + rec["currency"] = pm.Currency + } + if pm.Availability != "" { + rec["availability"] = pm.Availability + } +} + +func wave3CycExtractTablesMarkdown(doc *HTMLDoc, maxTables int) (string, [][][]string) { + if doc == nil { + return "", nil + } + tables := doc.Select("table", maxTables) + if len(tables) == 0 { + return "", nil + } + var sections []string + var parsedTables [][][]string + for _, tbl := range tables { + rows := tbl.TableRows() + if len(rows) < 2 || len(rows[0]) == 0 { + continue + } + cols := len(rows[0]) + if cols > 10 { + cols = 10 + } + headers := make([]string, cols) + for c := 0; c < cols; c++ { + headers[c] = SanitizeSchemaPlainField(rows[0][c], 80) + if headers[c] == "" { + headers[c] = fmt.Sprintf("Col %d", c+1) + } + } + var dataRows [][]string + for rIdx := 1; rIdx < len(rows) && len(dataRows) < wave3CycMaxRecords; rIdx++ { + r := rows[rIdx] + dr := make([]string, cols) + nonEmpty := false + for c := 0; c < cols; c++ { + if c < len(r) { + dr[c] = SanitizeSchemaPlainField(r[c], 140) + if dr[c] != "" { + nonEmpty = true + } + } + } + if nonEmpty { + dataRows = append(dataRows, dr) + } + } + if len(dataRows) == 0 { + continue + } + sections = append(sections, formatDeclarativeGFMTable(headers, dataRows)) + parsedTables = append(parsedTables, append([][]string{headers}, dataRows...)) + } + return strings.Join(sections, "\n\n"), parsedTables +} + +func wave3CycExtractDLSpecs(doc *HTMLDoc) ([][]string, map[string]string) { + if doc == nil { + return nil, nil + } + dl := doc.DLMap("dl") + if len(dl) == 0 { + return nil, nil + } + keys := make([]string, 0, len(dl)) + for k := range dl { + keys = append(keys, k) + } + sort.Strings(keys) + var rows [][]string + clean := make(map[string]string, len(dl)) + for _, k := range keys { + ck := SanitizeSchemaPlainField(k, 80) + cv := SanitizeSchemaPlainField(dl[k], 240) + if ck == "" || cv == "" { + continue + } + clean[ck] = cv + if len(rows) < wave3CycMaxRecords { + rows = append(rows, []string{ck, cv}) + } + } + return rows, clean +} + +func wave3CycExtractManualLinks(doc *HTMLDoc, baseURL string, extraKeywords ...string) ([]string, []string) { + if doc == nil { + return nil, nil + } + var mdLines []string + var rawLinks []string + seen := make(map[string]bool) + for _, a := range doc.Select("a[href]", 150) { + href := SanitizeSchemaHTTPSURL(a.AttrOrEmpty("href"), baseURL) + if href == "" || seen[href] { + continue + } + hl := strings.ToLower(href) + txt := SanitizeSchemaPlainField(a.Text(), 120) + tl := strings.ToLower(txt) + matched := strings.Contains(hl, ".pdf") || + strings.Contains(hl, "manual") || + strings.Contains(hl, "service") || + strings.Contains(hl, "datasheet") || + strings.Contains(hl, "tech") || + strings.Contains(tl, "manual") || + strings.Contains(tl, "service guide") || + strings.Contains(tl, "bleed") || + strings.Contains(tl, "datasheet") || + strings.Contains(tl, "pdf") + if !matched { + for _, kw := range extraKeywords { + if kw != "" && (strings.Contains(hl, kw) || strings.Contains(tl, kw)) { + matched = true + break + } + } + } + if !matched { + continue + } + seen[href] = true + rawLinks = append(rawLinks, href) + label := txt + if label == "" { + label = href + } + mdLines = append(mdLines, fmt.Sprintf("- [%s](%s)", escapeDeclMarkdownBrackets(label), href)) + if len(rawLinks) >= 12 { + break + } + } + return mdLines, rawLinks +} + +func wave3CycExtractMainMarkdown(doc *HTMLDoc, baseURL string, selectors ...string) string { + if doc == nil { + return "" + } + for _, sel := range selectors { + frag := doc.HTML(sel) + if strings.TrimSpace(frag) == "" { + continue + } + if md := wave3CycFragToMD(frag, baseURL); md != "" { + return md + } + } + return "" +} + +func wave3CycFindAllUnique(rx *lazyRegexp, text string, limit int) []string { + if rx == nil || text == "" || limit <= 0 { + return nil + } + matches := rx.FindAllStringSubmatch(text, limit*3) + var out []string + seen := make(map[string]bool) + for _, m := range matches { + val := "" + if len(m) >= 2 && strings.TrimSpace(m[1]) != "" { + val = strings.TrimSpace(m[1]) + } else if len(m) >= 1 { + val = strings.TrimSpace(m[0]) + } + if val == "" { + continue + } + key := strings.ToLower(val) + if seen[key] { + continue + } + seen[key] = true + out = append(out, val) + if len(out) >= limit { + break + } + } + return out +} + +// ── #341 FOX RideFOX ───────────────────────────────────────────────────────────────────────────── + +func wave3CycExtractFoxRidefoxHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + doc := ParseHTMLDoc(rawHTML, wave3CycStdHTMLMaxBytes) + if doc == nil { + return nil + } + title := wave3CycExtractTitle(doc, rawHTML) + if title == "" { + return nil + } + pm := wave3CycExtractProductJSONLD(rawHTML) + desc := wave3CycFirstNonEmpty(wave3CycExtractMetaDesc(rawHTML), pm.Description) + + // Extract FOX Tune ID / 4-char code from URL or page text + tuneCode := "" + if m := wave3CycRxFoxPathCode.FindStringSubmatch(baseURL); len(m) >= 2 { + tuneCode = strings.ToUpper(m[1]) + } + bodyText := doc.Text("main, article, body") + if tuneCode == "" { + if m := wave3CycRxFoxTuneCode.FindStringSubmatch(bodyText); len(m) >= 2 { + tuneCode = strings.ToUpper(m[1]) + } + } + + dlRows, dlMap := wave3CycExtractDLSpecs(doc) + tablesMD, _ := wave3CycExtractTablesMarkdown(doc, 6) + manualLines, manualLinks := wave3CycExtractManualLinks(doc, baseURL, "tune", "interval", "chart", "oil") + mainMD := wave3CycExtractMainMarkdown(doc, baseURL, "main", "article", ".help-content", ".tech-content", ".product__description") + + if len(dlRows) == 0 && tablesMD == "" && len(manualLines) == 0 && mainMD == "" && desc == "" && tuneCode == "" { + return nil + } + + var bullets []string + if tuneCode != "" { + bullets = append(bullets, "- **FOX Tune ID**: `"+tuneCode+"`") + } + wave3CycAppendProductBullets(&bullets, pm) + for _, k := range []string{"model year", "year", "chassis", "travel", "wheel size", "damper", "air spring", "rake", "offset", "service interval", "serial"} { + if v := dlMap[k]; v != "" { + bullets = append(bullets, "- **"+escapeDeclMarkdownBrackets(k)+"**: "+v) + } + } + + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + if desc != "" { + blocks = append(blocks, desc) + } + if len(dlRows) > 0 { + blocks = append(blocks, "## Specifications\n\n"+formatDeclarativeGFMTable([]string{"Specification", "Value"}, dlRows)) + } + if tablesMD != "" { + blocks = append(blocks, "## Technical & Service Tables\n\n"+tablesMD) + } + if len(manualLines) > 0 { + blocks = append(blocks, "## Service Docs & Manuals\n\n"+strings.Join(manualLines, "\n")) + } + if mainMD != "" && tablesMD == "" && len(dlRows) == 0 { + blocks = append(blocks, mainMD) + } else if mainMD != "" && len(mainMD) <= 2000 { + blocks = append(blocks, "## Details\n\n"+mainMD) + } + + rec := map[string]any{ + "source": "fox-ridefox", + "title": title, + "url": baseURL, + } + if tuneCode != "" { + rec["tuneCode"] = tuneCode + } + wave3CycApplyProductToRecord(rec, pm) + if len(dlMap) > 0 { + rec["specs"] = dlMap + } + + var links []string + seenLinks := make(map[string]bool) + wave3CycAddLink(&links, seenLinks, baseURL, baseURL) + for _, ml := range manualLinks { + wave3CycAddLink(&links, seenLinks, ml, baseURL) + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: []map[string]any{rec}, + } +} + +// ── #342 Park Tool ─────────────────────────────────────────────────────────────────────────────── + +func wave3CycExtractParkToolHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + doc := ParseHTMLDoc(rawHTML, wave3CycStdHTMLMaxBytes) + if doc == nil { + return nil + } + title := wave3CycExtractTitle(doc, rawHTML) + if title == "" { + return nil + } + pm := wave3CycExtractProductJSONLD(rawHTML) + desc := wave3CycFirstNonEmpty(wave3CycExtractMetaDesc(rawHTML), pm.Description) + + var ldTools []string + var ldSteps []string + var ldTime string + for _, ld := range extractJSONLDObjectsDeclHTML(rawHTML, 24) { + if !jsonLDHasType(ld, "HowTo") && !jsonLDHasType(ld, "TechArticle") && !jsonLDHasType(ld, "Article") { + continue + } + if t := wave3CycPlain(ld["totalTime"], 64); t != "" && ldTime == "" { + ldTime = t + } + for _, toolKey := range []string{"tool", "supply"} { + if arr, ok := ld[toolKey].([]any); ok { + for _, item := range arr { + if m, okM := item.(map[string]any); okM { + if nm := wave3CycPlain(m["name"], 120); nm != "" { + ldTools = append(ldTools, nm) + } + } else if s := wave3CycPlain(item, 120); s != "" { + ldTools = append(ldTools, s) + } + } + } + } + if steps, ok := ld["step"].([]any); ok { + for _, st := range steps { + if sm, okS := st.(map[string]any); okS { + txt := wave3CycFirstNonEmpty(wave3CycPlain(sm["text"], 500), wave3CycPlain(sm["name"], 240)) + if txt != "" { + ldSteps = append(ldSteps, txt) + } + } + } + } + } + + // DOM tools needed & ordered repair steps + var domTools []string + for _, node := range doc.Select(".tools-needed li, #tools-needed li, [data-tools] li", 30) { + if t := SanitizeSchemaPlainField(node.Text(), 140); t != "" { + domTools = append(domTools, t) + } + } + if len(domTools) == 0 { + domTools = ldTools + } + + var domSteps []string + for _, node := range doc.Select("article ol li, main ol li, .repair-steps li, .article-body ol li", 40) { + if t := SanitizeSchemaPlainField(node.Text(), 500); t != "" { + domSteps = append(domSteps, t) + } + } + if len(domSteps) == 0 { + domSteps = ldSteps + } + + dlRows, _ := wave3CycExtractDLSpecs(doc) + tablesMD, _ := wave3CycExtractTablesMarkdown(doc, 6) + manualLines, manualLinks := wave3CycExtractManualLinks(doc, baseURL, "repair", "instruction") + mainMD := wave3CycExtractMainMarkdown(doc, baseURL, "article", "main", ".article-body", ".product-description") + + if len(domTools) == 0 && len(domSteps) == 0 && len(dlRows) == 0 && tablesMD == "" && mainMD == "" && desc == "" { + return nil + } + + var bullets []string + wave3CycAppendProductBullets(&bullets, pm) + if ldTime != "" { + bullets = append(bullets, "- **Estimated Time**: "+ldTime) + } + if len(domTools) > 0 { + bullets = append(bullets, fmt.Sprintf("- **Tools Needed**: %d", len(domTools))) + } + if len(domSteps) > 0 { + bullets = append(bullets, fmt.Sprintf("- **Repair Steps**: %d", len(domSteps))) + } + + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + if desc != "" { + blocks = append(blocks, desc) + } + if len(domTools) > 0 { + var tLines []string + for _, t := range domTools { + tLines = append(tLines, "- "+escapeDeclMarkdownBrackets(t)) + } + blocks = append(blocks, "## Tools Needed\n\n"+strings.Join(tLines, "\n")) + } + if len(domSteps) > 0 { + var sLines []string + for i, st := range domSteps { + if i >= wave3CycMaxRecords { + break + } + sLines = append(sLines, fmt.Sprintf("%d. %s", i+1, st)) + } + blocks = append(blocks, "## Repair Steps\n\n"+strings.Join(sLines, "\n")) + } + if len(dlRows) > 0 { + blocks = append(blocks, "## Specifications\n\n"+formatDeclarativeGFMTable([]string{"Specification", "Value"}, dlRows)) + } + if tablesMD != "" { + blocks = append(blocks, "## Specification Tables\n\n"+tablesMD) + } + if len(manualLines) > 0 { + blocks = append(blocks, "## Manuals & Instructions\n\n"+strings.Join(manualLines, "\n")) + } + if len(domSteps) == 0 && mainMD != "" { + blocks = append(blocks, mainMD) + } + + var recs []map[string]any + if len(domSteps) > 0 { + for i, st := range domSteps { + if i >= wave3CycMaxRecords { + break + } + recs = append(recs, map[string]any{ + "source": "park-tool", + "step": i + 1, + "text": st, + }) + } + } else { + rec := map[string]any{ + "source": "park-tool", + "title": title, + "url": baseURL, + } + wave3CycApplyProductToRecord(rec, pm) + recs = append(recs, rec) + } + + var links []string + seenLinks := make(map[string]bool) + wave3CycAddLink(&links, seenLinks, baseURL, baseURL) + for _, ml := range manualLinks { + wave3CycAddLink(&links, seenLinks, ml, baseURL) + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: recs, + } +} + +// ── #343 iFixit (JSON + HTML) ──────────────────────────────────────────────────────────────────── + +func wave3CycFormatIFixitJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + obj, ok := parsed.(map[string]any) + if !ok || obj == nil { + return nil, false + } + if errFlag, isErr := obj["error"].(bool); isErr && errFlag { + return nil, false + } + if msg := wave3CycPlain(obj["message"], 200); msg != "" && obj["guideid"] == nil && obj["wikiid"] == nil { + return nil, false + } + + var links []string + seenLinks := make(map[string]bool) + canonURL := SanitizeSchemaHTTPSURL(obj["url"], origURL) + wave3CycAddLink(&links, seenLinks, canonURL, origURL) + + // Case 1: Guide JSON (`/api/2.0/guides/{id}`) + if obj["guideid"] != nil { + guideID := wave3CycPlain(obj["guideid"], 32) + title := wave3CycPlain(obj["title"], 240) + if title == "" { + return nil, false + } + subject := wave3CycPlain(obj["subject"], 160) + category := wave3CycPlain(obj["category"], 120) + difficulty := wave3CycPlain(obj["difficulty"], 64) + timeReq := wave3CycPlain(obj["time_required"], 64) + summary := wave3CycPlain(obj["summary"], 1000) + intro := wave3CycPlain(obj["introduction_raw"], 1600) + if intro == "" { + intro = wave3CycCleanText(wave3CycStringVal(obj["introduction_rendered"])) + } + conclusion := wave3CycPlain(obj["conclusion_raw"], 1000) + + var bullets []string + bullets = append(bullets, "- **Guide ID**: `"+guideID+"`") + if category != "" { + bullets = append(bullets, "- **Category**: "+category) + } + if subject != "" { + bullets = append(bullets, "- **Subject**: "+subject) + } + if difficulty != "" { + bullets = append(bullets, "- **Difficulty**: "+difficulty) + } + if timeReq != "" { + bullets = append(bullets, "- **Time Required**: "+timeReq) + } + if canonURL != "" { + bullets = append(bullets, "- **URL**: "+canonURL) + } + + var tools []string + if arr, okT := obj["tools"].([]any); okT { + for _, it := range arr { + if m, okM := it.(map[string]any); okM { + nm := wave3CycFirstNonEmpty(wave3CycPlain(m["text"], 160), wave3CycPlain(m["title"], 160), wave3CycPlain(m["name"], 160)) + if nm != "" { + tools = append(tools, "- "+escapeDeclMarkdownBrackets(nm)) + } + wave3CycAddLink(&links, seenLinks, wave3CycStringVal(m["url"]), origURL) + } + } + } + + var parts []string + if arr, okP := obj["parts"].([]any); okP { + for _, it := range arr { + if m, okM := it.(map[string]any); okM { + nm := wave3CycFirstNonEmpty(wave3CycPlain(m["text"], 160), wave3CycPlain(m["title"], 160), wave3CycPlain(m["name"], 160)) + if nm != "" { + parts = append(parts, "- "+escapeDeclMarkdownBrackets(nm)) + } + wave3CycAddLink(&links, seenLinks, wave3CycStringVal(m["url"]), origURL) + } + } + } + + var stepsMD []string + var recs []map[string]any + if arr, okS := obj["steps"].([]any); okS { + for idx, rawStep := range arr { + sm, okM := rawStep.(map[string]any) + if !okM { + continue + } + stepTitle := wave3CycPlain(sm["title"], 160) + var lineTexts []string + if linesArr, okL := sm["lines"].([]any); okL { + for _, rl := range linesArr { + if lm, okLM := rl.(map[string]any); okLM { + txt := wave3CycFirstNonEmpty(wave3CycPlain(lm["text_raw"], 600), wave3CycCleanText(wave3CycStringVal(lm["text_rendered"]))) + if txt != "" { + lineTexts = append(lineTexts, txt) + } + } + } + } + joined := strings.Join(lineTexts, " ") + if stepTitle == "" && joined == "" { + continue + } + stepLabel := fmt.Sprintf("Step %d", idx+1) + if stepTitle != "" { + stepLabel += ": " + stepTitle + } + if idx < wave3CycMaxRecords { + if joined != "" { + stepsMD = append(stepsMD, fmt.Sprintf("%d. **%s** — %s", idx+1, escapeDeclMarkdownBrackets(stepLabel), joined)) + } else { + stepsMD = append(stepsMD, fmt.Sprintf("%d. **%s**", idx+1, escapeDeclMarkdownBrackets(stepLabel))) + } + } + recs = append(recs, map[string]any{ + "guideId": guideID, + "stepNumber": idx + 1, + "title": stepTitle, + "text": sliceRunesMax(joined, 400), + }) + } + } + + blocks := []string{"# " + escapeDeclMarkdownBrackets(title), strings.Join(bullets, "\n")} + if summary != "" { + blocks = append(blocks, summary) + } + if intro != "" && intro != summary { + blocks = append(blocks, "## Introduction\n\n"+intro) + } + if len(tools) > 0 { + blocks = append(blocks, "## Tools\n\n"+strings.Join(tools, "\n")) + } + if len(parts) > 0 { + blocks = append(blocks, "## Parts\n\n"+strings.Join(parts, "\n")) + } + if len(stepsMD) > 0 { + blocks = append(blocks, "## Steps\n\n"+strings.Join(stepsMD, "\n")) + } + if conclusion != "" { + blocks = append(blocks, "## Conclusion\n\n"+conclusion) + } + if len(recs) == 0 { + recs = append(recs, map[string]any{ + "guideId": guideID, + "title": title, + "difficulty": difficulty, + "time": timeReq, + }) + } + + return &DeclarativeFormattedDoc{ + Title: title, + Description: sliceRunesMax(wave3CycFirstNonEmpty(summary, intro), 260), + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: recs, + }, true + } + + // Case 2: Wiki JSON (`/api/2.0/wikis/{ns}/{name}`) + if obj["wikiid"] != nil { + wikiID := wave3CycPlain(obj["wikiid"], 32) + ns := wave3CycPlain(obj["namespace"], 64) + title := wave3CycFirstNonEmpty(wave3CycPlain(obj["display_title"], 240), wave3CycPlain(obj["title"], 240)) + if title == "" { + return nil, false + } + desc := wave3CycPlain(obj["description"], 800) + contentsMD := "" + if rendered := wave3CycStringVal(obj["contents_rendered"]); rendered != "" { + contentsMD = wave3CycFragToMD(rendered, origURL) + } + if contentsMD == "" { + contentsMD = wave3CycPlain(obj["contents_raw"], 4000) + } + if contentsMD == "" && desc == "" { + return nil, false + } + var bullets []string + bullets = append(bullets, "- **Wiki ID**: `"+wikiID+"`") + if ns != "" { + bullets = append(bullets, "- **Namespace**: `"+ns+"`") + } + if anc, okA := obj["ancestors"].([]any); okA && len(anc) > 0 { + var crumb []string + for _, a := range anc { + if s := wave3CycPlain(a, 64); s != "" { + crumb = append(crumb, s) + } + } + if len(crumb) > 0 { + bullets = append(bullets, "- **Ancestors**: "+strings.Join(crumb, " > ")) + } + } + if canonURL != "" { + bullets = append(bullets, "- **URL**: "+canonURL) + } + + blocks := []string{"# " + escapeDeclMarkdownBrackets(title), strings.Join(bullets, "\n")} + if desc != "" { + blocks = append(blocks, desc) + } + if contentsMD != "" { + blocks = append(blocks, contentsMD) + } + return &DeclarativeFormattedDoc{ + Title: title, + Description: sliceRunesMax(desc, 260), + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: []map[string]any{{ + "wikiId": wikiID, + "namespace": ns, + "title": title, + }}, + }, true + } + + return nil, false +} + +func wave3CycExtractIFixitHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + doc := ParseHTMLDoc(rawHTML, wave3CycStdHTMLMaxBytes) + if doc == nil { + return nil + } + title := wave3CycExtractTitle(doc, rawHTML) + if title == "" { + return nil + } + desc := wave3CycExtractMetaDesc(rawHTML) + var steps []string + for _, s := range doc.Select(".stepLines li, .step-lines li, ol.steps li, [itemprop='step'] [itemprop='text']", 40) { + if t := SanitizeSchemaPlainField(s.Text(), 500); t != "" { + steps = append(steps, t) + } + } + var tools []string + for _, t := range doc.Select(".tools-list li, #tools li, [itemprop='tool']", 25) { + if txt := SanitizeSchemaPlainField(t.Text(), 140); txt != "" { + tools = append(tools, txt) + } + } + mainMD := wave3CycExtractMainMarkdown(doc, baseURL, "main", "article", ".guide-body", ".wiki-content") + if len(steps) == 0 && len(tools) == 0 && mainMD == "" && desc == "" { + return nil + } + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if desc != "" { + blocks = append(blocks, desc) + } + if len(tools) > 0 { + var tl []string + for _, t := range tools { + tl = append(tl, "- "+escapeDeclMarkdownBrackets(t)) + } + blocks = append(blocks, "## Tools\n\n"+strings.Join(tl, "\n")) + } + if len(steps) > 0 { + var sl []string + for i, st := range steps { + if i >= wave3CycMaxRecords { + break + } + sl = append(sl, fmt.Sprintf("%d. %s", i+1, st)) + } + blocks = append(blocks, "## Steps\n\n"+strings.Join(sl, "\n")) + } else if mainMD != "" { + blocks = append(blocks, mainMD) + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: strings.Join(blocks, "\n\n"), + Links: []string{baseURL}, + Records: []map[string]any{{"source": "ifixit", "title": title, "url": baseURL}}, + } +} + +// ── #344 E-Bike Drive Systems ──────────────────────────────────────────────────────────────────── + +func wave3CycExtractEBikeDriveHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + doc := ParseHTMLDoc(rawHTML, wave3CycMaxHTMLBytes) + if doc == nil { + return nil + } + title := wave3CycExtractTitle(doc, rawHTML) + if title == "" { + return nil + } + pm := wave3CycExtractProductJSONLD(rawHTML) + desc := wave3CycFirstNonEmpty(wave3CycExtractMetaDesc(rawHTML), pm.Description) + bodyText := doc.Text("main, article, body") + + torques := wave3CycFindAllUnique(wave3CycRxTorqueNm, bodyText, 6) + batteries := wave3CycFindAllUnique(wave3CycRxBatteryWh, bodyText, 6) + powers := wave3CycFindAllUnique(wave3CycRxMotorWatt, bodyText, 6) + volts := wave3CycFindAllUnique(wave3CycRxDriveVolt, bodyText, 4) + + dlRows, dlMap := wave3CycExtractDLSpecs(doc) + tablesMD, _ := wave3CycExtractTablesMarkdown(doc, 6) + manualLines, manualLinks := wave3CycExtractManualLinks(doc, baseURL, "drive", "battery", "motor", "system") + mainMD := wave3CycExtractMainMarkdown(doc, baseURL, "main", "article", ".specs", ".technical-data") + + if len(torques) == 0 && len(batteries) == 0 && len(powers) == 0 && len(dlRows) == 0 && tablesMD == "" && mainMD == "" && desc == "" { + return nil + } + + var bullets []string + wave3CycAppendProductBullets(&bullets, pm) + if len(torques) > 0 { + bullets = append(bullets, "- **Torque**: "+strings.Join(torques, ", ")+" Nm") + } + if len(powers) > 0 { + bullets = append(bullets, "- **Motor Power**: "+strings.Join(powers, ", ")+" W") + } + if len(batteries) > 0 { + bullets = append(bullets, "- **Battery Capacity**: "+strings.Join(batteries, ", ")+" Wh") + } + if len(volts) > 0 { + bullets = append(bullets, "- **System Voltage**: "+strings.Join(volts, ", ")+" V") + } + + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + if desc != "" { + blocks = append(blocks, desc) + } + if len(dlRows) > 0 { + blocks = append(blocks, "## Drive System Specifications\n\n"+formatDeclarativeGFMTable([]string{"Specification", "Value"}, dlRows)) + } + if tablesMD != "" { + blocks = append(blocks, "## Specification Tables\n\n"+tablesMD) + } + if len(manualLines) > 0 { + blocks = append(blocks, "## Manuals & Datasheets\n\n"+strings.Join(manualLines, "\n")) + } + if mainMD != "" && tablesMD == "" && len(dlRows) == 0 { + blocks = append(blocks, mainMD) + } + + rec := map[string]any{ + "source": "ebike-drive-systems", + "title": title, + "url": baseURL, + } + wave3CycApplyProductToRecord(rec, pm) + if len(torques) > 0 { + rec["torqueNm"] = torques + } + if len(batteries) > 0 { + rec["batteryWh"] = batteries + } + if len(powers) > 0 { + rec["motorWatts"] = powers + } + if len(dlMap) > 0 { + rec["specs"] = dlMap + } + + var links []string + seenLinks := make(map[string]bool) + wave3CycAddLink(&links, seenLinks, baseURL, baseURL) + for _, ml := range manualLinks { + wave3CycAddLink(&links, seenLinks, ml, baseURL) + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: []map[string]any{rec}, + } +} + +// ── #345 Specialized Turbo Support ─────────────────────────────────────────────────────────────── + +func wave3CycExtractSpecializedTurboSupportHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + doc := ParseHTMLDoc(rawHTML, wave3CycStdHTMLMaxBytes) + if doc == nil { + return nil + } + title := wave3CycExtractTitle(doc, rawHTML) + if title == "" { + return nil + } + desc := wave3CycExtractMetaDesc(rawHTML) + + // Extract Article / TechArticle / FAQPage JSON-LD if rendered + var ldAuthor, ldUpdated, ldBody string + var qaLines []string + for _, ld := range extractJSONLDObjectsDeclHTML(rawHTML, 24) { + if jsonLDHasType(ld, "Article") || jsonLDHasType(ld, "TechArticle") || jsonLDHasType(ld, "WebPage") { + if ldAuthor == "" { + ldAuthor = extractJSONLDAuthorName(ld["author"]) + } + if ldUpdated == "" { + ldUpdated = wave3CycPlain(ld["dateModified"], 32) + } + if ldBody == "" { + ldBody = wave3CycPlain(ld["articleBody"], 2400) + } + } + if jsonLDHasType(ld, "FAQPage") { + if mainEnt, ok := ld["mainEntity"].([]any); ok { + for _, rq := range mainEnt { + if qm, okQ := rq.(map[string]any); okQ { + q := wave3CycPlain(qm["name"], 240) + a := "" + if am, okA := qm["acceptedAnswer"].(map[string]any); okA { + a = wave3CycPlain(am["text"], 800) + } + if q != "" && a != "" { + qaLines = append(qaLines, fmt.Sprintf("### %s\n\n%s", escapeDeclMarkdownBrackets(q), a)) + } + } + } + } + } + } + + var breadcrumbs []string + for _, b := range doc.Select("nav[aria-label*='breadcrumb'] a, .breadcrumb a, .breadcrumbs a", 12) { + if bt := SanitizeSchemaPlainField(b.Text(), 64); bt != "" { + breadcrumbs = append(breadcrumbs, bt) + } + } + + tablesMD, _ := wave3CycExtractTablesMarkdown(doc, 6) + manualLines, manualLinks := wave3CycExtractManualLinks(doc, baseURL, "turbo", "firmware", "diagnostic", "battery") + mainMD := wave3CycExtractMainMarkdown(doc, baseURL, "article", ".kb-article", ".article-body", "main") + if mainMD == "" && ldBody != "" { + mainMD = ldBody + } + if mainMD == "" && len(qaLines) == 0 && tablesMD == "" { + return nil + } + + var bullets []string + if len(breadcrumbs) > 0 { + bullets = append(bullets, "- **Breadcrumbs**: "+strings.Join(breadcrumbs, " > ")) + } + if ldAuthor != "" { + bullets = append(bullets, "- **Author**: "+ldAuthor) + } + if ldUpdated != "" { + bullets = append(bullets, "- **Updated**: "+ldUpdated) + } + + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + if desc != "" { + blocks = append(blocks, desc) + } + if mainMD != "" { + blocks = append(blocks, mainMD) + } + if len(qaLines) > 0 { + blocks = append(blocks, "## Diagnostic Q&A\n\n"+strings.Join(qaLines, "\n\n")) + } + if tablesMD != "" { + blocks = append(blocks, "## Diagnostic & Error Code Tables\n\n"+tablesMD) + } + if len(manualLines) > 0 { + blocks = append(blocks, "## Related Manuals & Support Links\n\n"+strings.Join(manualLines, "\n")) + } + + var links []string + seenLinks := make(map[string]bool) + wave3CycAddLink(&links, seenLinks, baseURL, baseURL) + for _, ml := range manualLinks { + wave3CycAddLink(&links, seenLinks, ml, baseURL) + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Author: ldAuthor, + PublishedTime: ldUpdated, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: []map[string]any{{ + "source": "specialized-turbo-support", + "title": title, + "url": baseURL, + }}, + } +} + +// ── #346 Bicycle Tire Specs (Strict ISO 5775 ETRTO Validator) ──────────────────────────────────── + +// IsValidISO5775ETRTO validates an ETRTO NN-NNN tire size against ISO 5775 rim bead seat +// diameters and realistic bicycle tire widths (18..130 mm). +func IsValidISO5775ETRTO(raw string) (string, bool) { + s := strings.TrimSpace(raw) + parts := strings.Split(s, "-") + if len(parts) != 2 { + return "", false + } + width, errW := strconv.Atoi(strings.TrimSpace(parts[0])) + bsd, errB := strconv.Atoi(strings.TrimSpace(parts[1])) + if errW != nil || errB != nil { + return "", false + } + if width < 18 || width > 130 || !wave3CycISO5775BSDs[bsd] { + return "", false + } + return fmt.Sprintf("%d-%d", width, bsd), true +} + +func wave3CycExtractValidatedETRTOTokens(text string, limit int) []string { + if text == "" || limit <= 0 { + return nil + } + matches := wave3CycRxETRTOCandidate.FindAllStringSubmatch(text, -1) + var out []string + seen := make(map[string]bool) + for _, m := range matches { + if len(m) < 3 { + continue + } + norm, ok := IsValidISO5775ETRTO(m[1] + "-" + m[2]) + if !ok || seen[norm] { + continue + } + seen[norm] = true + out = append(out, norm) + if len(out) >= limit { + break + } + } + return out +} + +func wave3CycExtractBicycleTireSpecsHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + pm := wave3CycExtractProductJSONLD(rawHTML) + desc := wave3CycFirstNonEmpty(wave3CycExtractMetaDesc(rawHTML), pm.Description) + slimHTML := wave3CycSlimHTMLForDOM(rawHTML, 512*1024) + doc := ParseHTMLDoc(slimHTML, 512*1024) + if doc == nil { + return nil + } + title := wave3CycExtractTitle(doc, rawHTML) + if title == "" { + return nil + } + + // Collect text from body AND data-row attributes (used by Teravail/Shopify variant tables). + var scanBuf strings.Builder + scanBuf.WriteString(doc.Text("main, article, body")) + for _, rowNode := range doc.Select("[data-row]", 40) { + if dr := SanitizeSchemaPlainField(rowNode.AttrOrEmpty("data-row"), 160); dr != "" { + scanBuf.WriteByte(' ') + scanBuf.WriteString(dr) + } + } + scanText := scanBuf.String() + if len(scanText) > 128*1024 { + scanText = scanText[:128*1024] + } + + etrtoList := wave3CycExtractValidatedETRTOTokens(scanText, 25) + impSizes := wave3CycFindAllUnique(wave3CycRxTireSizeImp, scanText, 12) + tpis := wave3CycFindAllUnique(wave3CycRxTPI, scanText, 8) + weights := wave3CycFindAllUnique(wave3CycRxWeightSpec, scanText, 8) + + lowerScan := strings.ToLower(scanText) + var compounds []string + for _, comp := range []string{"3C MaxxTerra", "3C MaxxGrip", "3C MaxxSpeed", "ADDIX Speedgrip", "ADDIX Soft", "ADDIX Ultra Soft", "ADDIX Race", "BlackChili", "Light & Supple", "Durable", "Dual Compound", "SG2"} { + if strings.Contains(lowerScan, strings.ToLower(comp)) { + compounds = append(compounds, comp) + } + } + var beads []string + for _, bead := range []string{"Foldable", "Folding", "Wire", "Aramid", "Kevlar"} { + if strings.Contains(lowerScan, strings.ToLower(bead)) { + beads = append(beads, bead) + } + } + var tubeless []string + for _, tl := range []string{"Tubeless Ready", "TLR", "TLE", "TCS", "TR", "Hookless"} { + if tl == "TR" { + if strings.Contains(scanText, " TR ") || strings.Contains(scanText, "(TR)") || strings.Contains(scanText, "/TR") { + tubeless = append(tubeless, tl) + } + continue + } + if strings.Contains(lowerScan, strings.ToLower(tl)) { + tubeless = append(tubeless, tl) + } + } + + dlRows, _ := wave3CycExtractDLSpecs(doc) + tablesMD, _ := wave3CycExtractTablesMarkdown(doc, 6) + mainMD := "" + if tablesMD == "" && len(dlRows) == 0 { + mainMD = wave3CycExtractMainMarkdown(doc, baseURL, "main", "article", ".product__description") + } + + if len(etrtoList) == 0 && len(impSizes) == 0 && len(tpis) == 0 && len(dlRows) == 0 && tablesMD == "" && mainMD == "" && desc == "" { + return nil + } + + var bullets []string + wave3CycAppendProductBullets(&bullets, pm) + if len(etrtoList) > 0 { + bullets = append(bullets, "- **ETRTO (ISO 5775)**: "+strings.Join(etrtoList, ", ")) + } + if len(impSizes) > 0 { + bullets = append(bullets, "- **Wheel / Tire Sizes**: "+strings.Join(impSizes, ", ")) + } + if len(tpis) > 0 { + bullets = append(bullets, "- **TPI**: "+strings.Join(tpis, ", ")) + } + if len(compounds) > 0 { + bullets = append(bullets, "- **Compound**: "+strings.Join(compounds, ", ")) + } + if len(beads) > 0 { + bullets = append(bullets, "- **Bead**: "+strings.Join(beads, ", ")) + } + if len(tubeless) > 0 { + bullets = append(bullets, "- **Tubeless**: "+strings.Join(tubeless, ", ")) + } + if len(weights) > 0 { + bullets = append(bullets, "- **Weights**: "+strings.Join(weights, ", ")) + } + + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + if desc != "" { + blocks = append(blocks, desc) + } + if len(dlRows) > 0 { + blocks = append(blocks, "## Tire Specifications\n\n"+formatDeclarativeGFMTable([]string{"Specification", "Value"}, dlRows)) + } + if tablesMD != "" { + blocks = append(blocks, "## Size & Spec Tables\n\n"+tablesMD) + } + if mainMD != "" && tablesMD == "" && len(dlRows) == 0 { + blocks = append(blocks, mainMD) + } + + rec := map[string]any{ + "source": "bicycle-tire-specs", + "title": title, + "url": baseURL, + } + wave3CycApplyProductToRecord(rec, pm) + if len(etrtoList) > 0 { + rec["etrtoSizes"] = etrtoList + } + if len(impSizes) > 0 { + rec["tireSizes"] = impSizes + } + if len(tpis) > 0 { + rec["tpi"] = tpis + } + if len(compounds) > 0 { + rec["compounds"] = compounds + } + if len(beads) > 0 { + rec["beads"] = beads + } + if len(tubeless) > 0 { + rec["tubeless"] = tubeless + } + + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: strings.Join(blocks, "\n\n"), + Links: []string{baseURL}, + Records: []map[string]any{rec}, + } +} + +// ── #347 Wheel & Hub Specs ─────────────────────────────────────────────────────────────────────── + +func wave3CycExtractWheelHubSpecsHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + doc := ParseHTMLDoc(rawHTML, wave3CycMaxHTMLBytes) + if doc == nil { + return nil + } + title := wave3CycExtractTitle(doc, rawHTML) + if title == "" { + return nil + } + pm := wave3CycExtractProductJSONLD(rawHTML) + desc := wave3CycFirstNonEmpty(wave3CycExtractMetaDesc(rawHTML), pm.Description) + bodyText := doc.Text("main, article, body") + lowerText := strings.ToLower(bodyText) + + olds := wave3CycFindAllUnique(wave3CycRxHubOLD, bodyText, 8) + holes := wave3CycFindAllUnique(wave3CycRxHubHoles, bodyText, 6) + engagements := wave3CycFindAllUnique(wave3CycRxHubEngagement, bodyText, 6) + + var freehubs []string + for _, fh := range []string{"XD", "XDR", "Micro Spline", "HG", "Shimano HG", "Campagnolo", "N3W"} { + if strings.Contains(lowerText, strings.ToLower(fh)) { + freehubs = append(freehubs, fh) + } + } + var mounts []string + for _, mt := range []string{"Center Lock", "Centerlock", "6-Bolt", "IS 6-Bolt"} { + if strings.Contains(lowerText, strings.ToLower(mt)) { + mounts = append(mounts, mt) + } + } + + dlRows, dlMap := wave3CycExtractDLSpecs(doc) + tablesMD, _ := wave3CycExtractTablesMarkdown(doc, 6) + manualLines, manualLinks := wave3CycExtractManualLinks(doc, baseURL, "hub", "wheel", "ratchet", "bearing") + mainMD := wave3CycExtractMainMarkdown(doc, baseURL, "main", "article", ".product__description", ".collection-products") + + if len(olds) == 0 && len(holes) == 0 && len(engagements) == 0 && len(freehubs) == 0 && len(dlRows) == 0 && tablesMD == "" && mainMD == "" && desc == "" { + return nil + } + + var bullets []string + wave3CycAppendProductBullets(&bullets, pm) + if len(olds) > 0 { + bullets = append(bullets, "- **Axle Spacing (O.L.D.)**: "+strings.Join(olds, ", ")+" mm") + } + if len(holes) > 0 { + bullets = append(bullets, "- **Spoke Drilling**: "+strings.Join(holes, ", ")+"H") + } + if len(engagements) > 0 { + bullets = append(bullets, "- **Engagement**: "+strings.Join(engagements, ", ")) + } + if len(freehubs) > 0 { + bullets = append(bullets, "- **Freehub Bodies**: "+strings.Join(freehubs, ", ")) + } + if len(mounts) > 0 { + bullets = append(bullets, "- **Rotor Mount**: "+strings.Join(mounts, ", ")) + } + + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + if desc != "" { + blocks = append(blocks, desc) + } + if len(dlRows) > 0 { + blocks = append(blocks, "## Hub & Wheel Specifications\n\n"+formatDeclarativeGFMTable([]string{"Specification", "Value"}, dlRows)) + } + if tablesMD != "" { + blocks = append(blocks, "## Technical Tables\n\n"+tablesMD) + } + if len(manualLines) > 0 { + blocks = append(blocks, "## Service Manuals & Exploded Views\n\n"+strings.Join(manualLines, "\n")) + } + if mainMD != "" && tablesMD == "" && len(dlRows) == 0 { + blocks = append(blocks, mainMD) + } + + rec := map[string]any{ + "source": "wheel-hub-specs", + "title": title, + "url": baseURL, + } + wave3CycApplyProductToRecord(rec, pm) + if len(olds) > 0 { + rec["axleSpacingMm"] = olds + } + if len(freehubs) > 0 { + rec["freehubs"] = freehubs + } + if len(engagements) > 0 { + rec["engagement"] = engagements + } + if len(dlMap) > 0 { + rec["specs"] = dlMap + } + + var links []string + seenLinks := make(map[string]bool) + wave3CycAddLink(&links, seenLinks, baseURL, baseURL) + for _, ml := range manualLinks { + wave3CycAddLink(&links, seenLinks, ml, baseURL) + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: []map[string]any{rec}, + } +} + +// ── #348 Bicycle Brake Docs ────────────────────────────────────────────────────────────────────── + +func wave3CycExtractBicycleBrakeDocsHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + doc := ParseHTMLDoc(rawHTML, wave3CycStdHTMLMaxBytes) + if doc == nil { + return nil + } + title := wave3CycExtractTitle(doc, rawHTML) + if title == "" { + return nil + } + pm := wave3CycExtractProductJSONLD(rawHTML) + desc := wave3CycFirstNonEmpty(wave3CycExtractMetaDesc(rawHTML), pm.Description) + bodyText := doc.Text("main, article, body") + lowerText := strings.ToLower(bodyText) + + rotors := wave3CycFindAllUnique(wave3CycRxBrakeRotor, bodyText, 8) + thicknesses := wave3CycFindAllUnique(wave3CycRxBrakeThick, bodyText, 4) + pistons := wave3CycFindAllUnique(wave3CycRxBrakePistons, bodyText, 4) + + var fluids []string + for _, fl := range []string{"Mineral Oil", "Royal Blood", "DOT 5.1", "DOT 4"} { + if strings.Contains(lowerText, strings.ToLower(fl)) { + fluids = append(fluids, fl) + } + } + var mounts []string + for _, mt := range []string{"Post Mount", "Flat Mount", "IS Mount", "Center Lock", "6-Bolt"} { + if strings.Contains(lowerText, strings.ToLower(mt)) { + mounts = append(mounts, mt) + } + } + + dlRows, dlMap := wave3CycExtractDLSpecs(doc) + tablesMD, _ := wave3CycExtractTablesMarkdown(doc, 6) + manualLines, manualLinks := wave3CycExtractManualLinks(doc, baseURL, "brake", "bleed", "rotor", "pad") + mainMD := wave3CycExtractMainMarkdown(doc, baseURL, "main", "article", ".product__description", ".woocommerce-product-details__short-description") + + if len(rotors) == 0 && len(fluids) == 0 && len(pistons) == 0 && len(dlRows) == 0 && tablesMD == "" && mainMD == "" && desc == "" { + return nil + } + + var bullets []string + wave3CycAppendProductBullets(&bullets, pm) + if len(pistons) > 0 { + bullets = append(bullets, "- **Caliper Pistons**: "+strings.Join(pistons, ", ")+"-piston") + } + if len(fluids) > 0 { + bullets = append(bullets, "- **Brake Fluid**: "+strings.Join(fluids, ", ")) + } + if len(rotors) > 0 { + bullets = append(bullets, "- **Rotor Sizes**: "+strings.Join(rotors, ", ")+" mm") + } + if len(thicknesses) > 0 { + bullets = append(bullets, "- **Rotor Thickness**: "+strings.Join(thicknesses, ", ")+" mm") + } + if len(mounts) > 0 { + bullets = append(bullets, "- **Mount Standard**: "+strings.Join(mounts, ", ")) + } + + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + if desc != "" { + blocks = append(blocks, desc) + } + if len(dlRows) > 0 { + blocks = append(blocks, "## Brake Specifications\n\n"+formatDeclarativeGFMTable([]string{"Specification", "Value"}, dlRows)) + } + if tablesMD != "" { + blocks = append(blocks, "## Rotor & Pad Compatibility Tables\n\n"+tablesMD) + } + if len(manualLines) > 0 { + blocks = append(blocks, "## Service & Bleed Manuals\n\n"+strings.Join(manualLines, "\n")) + } + if mainMD != "" && tablesMD == "" && len(dlRows) == 0 { + blocks = append(blocks, mainMD) + } + + rec := map[string]any{ + "source": "bicycle-brake-docs", + "title": title, + "url": baseURL, + } + wave3CycApplyProductToRecord(rec, pm) + if len(fluids) > 0 { + rec["fluid"] = fluids + } + if len(rotors) > 0 { + rec["rotorSizesMm"] = rotors + } + if len(pistons) > 0 { + rec["pistons"] = pistons + } + if len(dlMap) > 0 { + rec["specs"] = dlMap + } + + var links []string + seenLinks := make(map[string]bool) + wave3CycAddLink(&links, seenLinks, baseURL, baseURL) + for _, ml := range manualLinks { + wave3CycAddLink(&links, seenLinks, ml, baseURL) + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: []map[string]any{rec}, + } +} + +// ── #349 Suspension & Cockpit Compatibility ────────────────────────────────────────────────────── + +func wave3CycExtractSuspensionCockpitHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + pm := wave3CycExtractProductJSONLD(rawHTML) + desc := wave3CycFirstNonEmpty(wave3CycExtractMetaDesc(rawHTML), pm.Description) + slimHTML := wave3CycSlimHTMLForDOM(rawHTML, 512*1024) + doc := ParseHTMLDoc(slimHTML, 512*1024) + if doc == nil { + return nil + } + title := wave3CycExtractTitle(doc, rawHTML) + if title == "" { + return nil + } + bodyText := doc.Text("main, article, body") + if len(bodyText) > 128*1024 { + bodyText = bodyText[:128*1024] + } + + shisCodes := wave3CycFindAllUnique(wave3CycRxSHIS, bodyText, 12) + bcds := wave3CycFindAllUnique(wave3CycRxBCD, bodyText, 8) + shockSizes := wave3CycFindAllUnique(wave3CycRxShockSize, bodyText, 8) + clamps := wave3CycFindAllUnique(wave3CycRxClampDiam, bodyText, 6) + + dlRows, dlMap := wave3CycExtractDLSpecs(doc) + tablesMD, _ := wave3CycExtractTablesMarkdown(doc, 8) + manualLines, manualLinks := wave3CycExtractManualLinks(doc, baseURL, "fit", "compat", "shis", "spring", "headset", "shock") + mainMD := "" + if tablesMD == "" && len(dlRows) == 0 { + mainMD = wave3CycExtractMainMarkdown(doc, baseURL, "main", "article", ".product__description") + } + + hasStructuredProduct := pm.Name != "" && (pm.Price != "" || pm.Brand != "") + shopifyProductType := "" + if hasStructuredProduct { + if idx := indexFoldASCIIExtract(rawHTML, "var meta"); idx >= 0 { + if rawMeta, _, okMeta := ExtractBalancedJSONAt(rawHTML, idx+len("var meta"), 65536); okMeta { + if metaObj, okObj := parseJSONObjectDeclHTML(rawMeta); okObj && metaObj != nil { + if pObj, okP := metaObj["product"].(map[string]any); okP { + shopifyProductType = wave3CycPlain(pObj["type"], 120) + } + } + } + } + } + + if len(shisCodes) == 0 && len(bcds) == 0 && len(shockSizes) == 0 && len(clamps) == 0 && len(dlRows) == 0 && tablesMD == "" && mainMD == "" && desc == "" && !hasStructuredProduct { + return nil + } + + var bullets []string + wave3CycAppendProductBullets(&bullets, pm) + if shopifyProductType != "" { + bullets = append(bullets, "- **Product Type**: "+shopifyProductType) + } + if len(shisCodes) > 0 { + bullets = append(bullets, "- **SHIS Headset Standards**: "+strings.Join(shisCodes, ", ")) + } + if len(bcds) > 0 { + bullets = append(bullets, "- **Chainring Mount / BCD**: "+strings.Join(bcds, ", ")) + } + if len(shockSizes) > 0 { + bullets = append(bullets, "- **Shock Eye-to-Eye x Stroke**: "+strings.Join(shockSizes, ", ")) + } + if len(clamps) > 0 { + bullets = append(bullets, "- **Clamp / Post Diameters**: "+strings.Join(clamps, ", ")+" mm") + } + + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + if desc != "" { + blocks = append(blocks, desc) + } + if len(dlRows) > 0 { + blocks = append(blocks, "## Compatibility & Fitment Specs\n\n"+formatDeclarativeGFMTable([]string{"Specification", "Value"}, dlRows)) + } + if tablesMD != "" { + blocks = append(blocks, "## Compatibility Charts\n\n"+tablesMD) + } + if len(manualLines) > 0 { + blocks = append(blocks, "## Fitment & Tuning Manuals\n\n"+strings.Join(manualLines, "\n")) + } + if mainMD != "" && tablesMD == "" && len(dlRows) == 0 { + blocks = append(blocks, mainMD) + } + + rec := map[string]any{ + "source": "suspension-cockpit-compat", + "title": title, + "url": baseURL, + } + wave3CycApplyProductToRecord(rec, pm) + if shopifyProductType != "" { + rec["productType"] = shopifyProductType + } + if len(shisCodes) > 0 { + rec["shis"] = shisCodes + } + if len(bcds) > 0 { + rec["bcd"] = bcds + } + if len(shockSizes) > 0 { + rec["shockSizes"] = shockSizes + } + if len(clamps) > 0 { + rec["diametersMm"] = clamps + } + if len(dlMap) > 0 { + rec["specs"] = dlMap + } + + var links []string + seenLinks := make(map[string]bool) + wave3CycAddLink(&links, seenLinks, baseURL, baseURL) + for _, ml := range manualLinks { + wave3CycAddLink(&links, seenLinks, ml, baseURL) + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: []map[string]any{rec}, + } +} diff --git a/internal/extract/wave3_cycling_components_test.go b/internal/extract/wave3_cycling_components_test.go new file mode 100644 index 0000000..6bc0cd8 --- /dev/null +++ b/internal/extract/wave3_cycling_components_test.go @@ -0,0 +1,449 @@ +package extract + +import ( + "encoding/json" + "net/url" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func wave3CycDecodeDoc(t *testing.T, raw string) *DeclarativeFormattedDoc { + t.Helper() + var doc DeclarativeFormattedDoc + if err := json.Unmarshal([]byte(raw), &doc); err != nil { + t.Fatalf("unmarshal DeclarativeFormattedDoc: %v\nraw=%s", err, raw) + } + return &doc +} + +func wave3CycResolveManifest(t *testing.T, m *DeclarativeAdapterManifest, rawURL string) (*DeclarativeTwinMatch, bool) { + t.Helper() + u, err := url.Parse(rawURL) + if err != nil { + t.Fatalf("url.Parse(%q): %v", rawURL, err) + } + host := strings.TrimSuffix(strings.ToLower(u.Hostname()), ".") + rawParts := splitNonEmptyEscapedSegments(u.EscapedPath()) + return resolveManifestTwinOnParsedURL(m, u, host, rawParts, DeclarativeResolveOptions{}) +} + +func TestWave3CyclingComponentsManifestsAndRouting(t *testing.T) { + catO1IDs := []string{ + "fox-ridefox", + "park-tool", + "ifixit", + "ebike-drive-systems", + "specialized-turbo-support", + "bicycle-tire-specs", + "wheel-hub-specs", + "bicycle-brake-docs", + "suspension-cockpit-compat", + } + + byID := make(map[string]*DeclarativeAdapterManifest) + claimedDomains := make(map[string]string) + for _, id := range catO1IDs { + raw, err := os.ReadFile(filepath.Join("manifests", id+".yaml")) + if err != nil { + t.Fatalf("read %s.yaml: %v", id, err) + } + m, err := ParseDeclarativeYAMLManifest(raw) + if err != nil { + t.Fatalf("ParseDeclarativeYAMLManifest(%s.yaml): %v", id, err) + } + if m.ID != id { + t.Fatalf("%s.yaml has mismatched id=%q", id, m.ID) + } + if m.AuthMode == "detect-only" || m.DetectOnly != nil { + t.Fatalf("%s.yaml uses retired detect-only", id) + } + if len(m.ExampleURLs) == 0 { + t.Fatalf("%s.yaml missing exampleUrls", id) + } + for _, d := range m.Domains { + ld := strings.ToLower(strings.TrimSpace(d)) + if prev, exists := claimedDomains[ld]; exists { + t.Fatalf("duplicate domain %q across %s and %s", ld, prev, id) + } + claimedDomains[ld] = id + } + for _, hr := range m.HTMLRoutes { + for _, b := range hr.Bullets { + if strings.ContainsAny(b.Label, "{}") { + t.Fatalf("%s.yaml bullet label contains {}: %q", id, b.Label) + } + } + } + byID[id] = m + } + + // Verify strict disjointness from existing cycling/help manifests + for _, existingID := range []string{ + "specialized", "sram-docs", "sram-models", "bosch-ebike-help", + "giant-liv-bikes", "tq-ebike", "ebike-state-laws", "cpsc-ebike-battery", + } { + raw, err := os.ReadFile(filepath.Join("manifests", existingID+".yaml")) + if err != nil { + t.Fatalf("read %s.yaml: %v", existingID, err) + } + em, err := ParseDeclarativeYAMLManifest(raw) + if err != nil { + t.Fatalf("ParseDeclarativeYAMLManifest(%s.yaml): %v", existingID, err) + } + for _, d := range em.Domains { + ld := strings.ToLower(strings.TrimSpace(d)) + if catOwner, overlap := claimedDomains[ld]; overlap { + t.Fatalf("Cat O1 %s overlaps %s domain %q", catOwner, existingID, ld) + } + } + } + + // #347 owns hopetech.com / www.hopetech.com exclusively; #348 must NOT claim it + if owner := claimedDomains["hopetech.com"]; owner != "wheel-hub-specs" { + t.Fatalf("expected hopetech.com owner wheel-hub-specs, got %q", owner) + } + if owner := claimedDomains["www.hopetech.com"]; owner != "wheel-hub-specs" { + t.Fatalf("expected www.hopetech.com owner wheel-hub-specs, got %q", owner) + } + for _, d := range byID["bicycle-brake-docs"].Domains { + if strings.Contains(strings.ToLower(d), "hopetech") { + t.Fatalf("bicycle-brake-docs must not claim %q", d) + } + } + + // #345 specialized-turbo-support claims support.specialized.com ONLY + sts := byID["specialized-turbo-support"] + if len(sts.Domains) != 1 || sts.Domains[0] != "support.specialized.com" { + t.Fatalf("specialized-turbo-support must claim support.specialized.com only, got %v", sts.Domains) + } + + // #343 ifixit twin route resolution for guides & wikis + ifx := byID["ifixit"] + if tm, ok := wave3CycResolveManifest(t, ifx, "https://www.ifixit.com/api/2.0/guides/1"); !ok || tm.route.Extract.JSONMode != "ifixit_json" { + t.Fatalf("ifixit /api/2.0/guides/1 route failed: ok=%v tm=%+v", ok, tm) + } + if tm, ok := wave3CycResolveManifest(t, ifx, "https://www.ifixit.com/api/2.0/wikis/CATEGORY/Bicycle"); !ok || tm.route.Extract.JSONMode != "ifixit_json" { + t.Fatalf("ifixit /api/2.0/wikis/CATEGORY/Bicycle route failed: ok=%v tm=%+v", ok, tm) + } + if tm, ok := wave3CycResolveManifest(t, ifx, "https://www.ifixit.com/Guide/Bicycle+Chain+Replacement/41537"); ok || tm != nil { + t.Fatalf("ifixit HTML guide URL should fall through to htmlRoutes: %+v", tm) + } +} + +func TestWave3CyclingComponentsModeRegistrationAndIFixitJSON(t *testing.T) { + registerWave3CyclingComponentsHTMLModes() + RegisterWave3CyclingComponentsHTMLModes() + + htmlModes := []string{ + "fox_ridefox_html", + "park_tool_html", + "ifixit_html", + "ebike_drive_systems_html", + "specialized_turbo_support_html", + "bicycle_tire_specs_html", + "wheel_hub_specs_html", + "bicycle_brake_docs_html", + "suspension_cockpit_compat_html", + } + for _, hm := range htmlModes { + if !IsWave3CyclingComponentsHTMLMode(hm) { + t.Fatalf("IsWave3CyclingComponentsHTMLMode(%q) = false", hm) + } + if getExternalHTMLModeLazy(hm) == nil { + t.Fatalf("RegisterExternalHTMLModeLazy missing %q", hm) + } + } + if !IsWave3CyclingComponentsJSONMode("ifixit_json") || IsWave3CyclingComponentsJSONMode("unknown_json") { + t.Fatalf("IsWave3CyclingComponentsJSONMode check failed") + } + + // Guide JSON + guidePayload := `{"guideid":41537,"title":"Bicycle Chain Replacement","category":"Bicycle","subject":"Chain","difficulty":"Moderate","time_required":"15 - 30 minutes","summary":"Replace a worn chain.","url":"https://www.ifixit.com/Guide/Bicycle+Chain+Replacement/41537","tools":[{"text":"Chain Tool"}],"parts":[{"text":"11-Speed Chain"}],"steps":[{"stepid":1,"title":"Break Chain","lines":[{"text_raw":"Use chain tool to push pin."}]}]}` + rawDoc, ok := FormatWave3CyclingComponentsJSONMode("ifixit_json", []byte(guidePayload), nil, "https://www.ifixit.com/api/2.0/guides/41537") + if !ok { + t.Fatalf("ifixit_json guide formatting failed") + } + doc := wave3CycDecodeDoc(t, rawDoc) + if doc.Title != "Bicycle Chain Replacement" || !strings.Contains(doc.Markdown, "Chain Tool") || !strings.Contains(doc.Markdown, "Break Chain") { + t.Fatalf("unexpected ifixit guide output: %+v", doc) + } + + // Wiki JSON + wikiPayload := `{"wikiid":12,"namespace":"CATEGORY","title":"Bicycle","description":"Bicycle repair hub","ancestors":["Root"],"contents_rendered":"

Maintain drivetrains, brakes, and wheels.

","url":"https://www.ifixit.com/Wiki/Bicycle"}` + wikiRaw, okW := FormatWave3CyclingComponentsJSONMode("ifixit_json", []byte(wikiPayload), nil, "https://www.ifixit.com/api/2.0/wikis/CATEGORY/Bicycle") + if !okW || !strings.Contains(wikiRaw, "Maintain drivetrains") { + t.Fatalf("ifixit_json wiki formatting failed: ok=%v raw=%s", okW, wikiRaw) + } + + // Error JSON rejection + if _, negOK := FormatWave3CyclingComponentsJSONMode("ifixit_json", []byte(`{"error":true,"message":"Guide not found"}`), nil, "https://www.ifixit.com/api/2.0/guides/99999999"); negOK { + t.Fatalf("ifixit_json must reject error JSON") + } +} + +func TestWave3CyclingComponentsETRTOAndAllNineHTMLExtractors(t *testing.T) { + // 1. Strict ISO 5775 ETRTO validation unit checks + validETRTOTests := []string{"23-622", "28-622", "40-622", "63-622", "58-584", "63-584", "57-559", "61-406", "37-349", "42-635"} + for _, tc := range validETRTOTests { + if norm, ok := IsValidISO5775ETRTO(tc); !ok || norm != tc { + t.Fatalf("expected valid ISO 5775 ETRTO %q, got ok=%v norm=%q", tc, ok, norm) + } + } + invalidETRTOTests := []string{"25-145", "96-160", "40-700", "45-700", "11-654", "17-622", "131-622", "19-999", "60-600"} + for _, tc := range invalidETRTOTests { + if norm, ok := IsValidISO5775ETRTO(tc); ok { + t.Fatalf("expected invalid ETRTO %q to be rejected, got %q", tc, norm) + } + } + + // 2. #346 Teravail data-row ("700 x 40-700") & Maxxis false-positive ETRTO rejection + teravailHTML := `Cannonball Gen 2 Tire | Teravail

Cannonball Gen 2

60 TPI / Light & Supple / Tubeless Ready

Valid ETRTO 42-622, non-ETRTO SKU 25-145.

` + tRes := Wave3CyclingComponentsRunHTML("bicycle_tire_specs_html", teravailHTML, "https://www.teravail.com/products/cannonball-gen-2-tire", "bicycle-tire-specs") + if tRes == nil { + t.Fatalf("teravail bicycle_tire_specs_html returned nil") + } + if !strings.Contains(tRes.Markdown, "42-622") || strings.Contains(tRes.Markdown, "ETRTO (ISO 5775): 40-700") || strings.Contains(tRes.Markdown, "25-145,") { + t.Fatalf("unexpected ETRTO filtering in teravail output: %s", tRes.Markdown) + } + if !strings.Contains(tRes.Markdown, "700 x 40") || !strings.Contains(tRes.Markdown, "60 TPI") || !strings.Contains(tRes.Markdown, "Light & Supple") { + t.Fatalf("missing Teravail imperial/TPI/compound specs: %s", tRes.Markdown) + } + if tRes.Records[0]["gtin"] != "708752291100" { + t.Fatalf("expected strict 12-digit GTIN fallback (ignoring 7-digit), got %+v", tRes.Records[0]) + } + + // 3. #341 FOX RideFOX + foxHTML := `2019 FACTORY SERIES FLOAT

2019 FACTORY SERIES FLOAT

Tune ID: DKC6, GRIP2 damper, 160 mm travel.

Service Interval
125 hours
` + foxRes, okFox := RunWave3CyclingComponentsHTMLMode("fox_ridefox_html", foxHTML, "https://tech.ridefox.com/bike/search/code/DKC6") + if !okFox || !strings.Contains(foxRes, "DKC6") || !strings.Contains(foxRes, "125 hours") { + t.Fatalf("fox_ridefox_html failed: ok=%v res=%s", okFox, foxRes) + } + + // 4. #342 Park Tool + ptHTML := `Rear Derailleur Adjustment

Rear Derailleur Adjustment

  • 4mm Hex
  1. Shift to smallest cog.
  2. Set H-limit screw.
` + ptRes, okPT := RunWave3CyclingComponentsHTMLMode("park_tool_html", ptHTML, "https://www.parktool.com/en-us/blog/repair-help/rear-derailleur-adjustment") + if !okPT || !strings.Contains(ptRes, "4mm Hex") || !strings.Contains(ptRes, "H-limit screw") { + t.Fatalf("park_tool_html failed: ok=%v res=%s", okPT, ptRes) + } + + // 5. #343 iFixit HTML fallback + ifxHTML := `Chain Replacement - iFixit

Bicycle Chain Replacement

  • Chain Tool
  1. Open quick link.
` + if ifxRes, okIfx := RunWave3CyclingComponentsHTMLMode("ifixit_html", ifxHTML, "https://www.ifixit.com/Guide/Bicycle+Chain+Replacement/41537"); !okIfx || !strings.Contains(ifxRes, "Chain Tool") { + t.Fatalf("ifixit_html failed: ok=%v res=%s", okIfx, ifxRes) + } + + // 6. #344 E-Bike Drive Systems (including QORE with salesforce/aura + valid JSON-LD & content) + qoreHTML := `QORE by YMESG Drive System

QORE Drive Unit

95 Nm torque, 36 V, 725 Wh battery integration.

` + if qRes, okQ := RunWave3CyclingComponentsHTMLMode("ebike_drive_systems_html", qoreHTML, "https://www.qore-system.de/"); !okQ || !strings.Contains(qRes, "95") || !strings.Contains(qRes, "725") { + t.Fatalf("ebike_drive_systems_html QORE failed: ok=%v res=%s", okQ, qRes) + } + + // 7. #345 Specialized Turbo Support (rendered KB article succeeds; eGain launcher & API-GW 403 fail) + stsHTML := `Turbo Diagnostic Codes

Turbo Diagnostic Codes

Inspect MasterMind TCU battery LED codes.

` + if stsRes, okSTS := RunWave3CyclingComponentsHTMLMode("specialized_turbo_support_html", stsHTML, "https://support.specialized.com/kb/sp_en-us/diagnostics"); !okSTS || !strings.Contains(stsRes, "MasterMind TCU") { + t.Fatalf("specialized_turbo_support_html failed: ok=%v res=%s", okSTS, stsRes) + } + egainShell := `

.

` + if bad := Wave3CyclingComponentsRunHTML("specialized_turbo_support_html", egainShell, "https://support.specialized.com/kb/sp_en-us/home", "specialized-turbo-support"); bad != nil { + t.Fatalf("specialized_turbo_support_html must reject eGain launcher shell, got %+v", bad) + } + if badGW := Wave3CyclingComponentsRunHTML("specialized_turbo_support_html", `{"message":"Missing Authentication Token"}`, "https://support.specialized.com/home", "specialized-turbo-support"); badGW != nil { + t.Fatalf("specialized_turbo_support_html must reject API Gateway 403 JSON, got %+v", badGW) + } + + // 8. #347, #348, #349 Cloudflare Turnstile script tag inside valid 200 product page MUST succeed, + // while minimal "Just a moment..." challenge page MUST be rejected. + i9WithCF := `Sector AL | Industry Nine

Industry Nine Hydra Sector AL

148 mm Boost spacing, 690 POE engagement, 28H, XD and Micro Spline freehubs.

` + if i9Res, okI9 := RunWave3CyclingComponentsHTMLMode("wheel_hub_specs_html", i9WithCF, "https://industrynine.com/products/sector-al"); !okI9 || !strings.Contains(i9Res, "148") || !strings.Contains(i9Res, "Micro Spline") { + t.Fatalf("wheel_hub_specs_html must allow valid 200 product page with CF script tags: ok=%v res=%s", okI9, i9Res) + } + + tektroWithCF := `Tektro HD-M275

Tektro HD-M275 Hydraulic Disc Brake

2-piston caliper, Mineral Oil, 160 mm and 180 mm rotors (1.8 mm thickness).

` + if tkRes, okTK := RunWave3CyclingComponentsHTMLMode("bicycle_brake_docs_html", tektroWithCF, "https://tektro.com/en/product/315"); !okTK || !strings.Contains(tkRes, "Mineral Oil") || !strings.Contains(tkRes, "180") { + t.Fatalf("bicycle_brake_docs_html must allow valid 200 product page with CF script tags: ok=%v res=%s", okTK, tkRes) + } + + wtWithCF := `Drop-Stop Chainrings | Wolf Tooth

Direct Mount Drop-Stop Chainring

Compatible with 104 BCD, 110 BCD, and Cinch cranks; SHIS IS41 headset spacers.

` + if wtRes, okWT := RunWave3CyclingComponentsHTMLMode("suspension_cockpit_compat_html", wtWithCF, "https://www.wolftoothcomponents.com/collections/chainrings"); !okWT || !strings.Contains(wtRes, "104 BCD") || !strings.Contains(wtRes, "IS41") { + t.Fatalf("suspension_cockpit_compat_html must allow valid 200 product page with CF script tags: ok=%v res=%s", okWT, wtRes) + } + + cfChallenge := `Just a moment...
Checking your browser
` + for _, hm := range []string{"wheel_hub_specs_html", "bicycle_brake_docs_html", "suspension_cockpit_compat_html"} { + if badCF := Wave3CyclingComponentsRunHTML(hm, cfChallenge, "https://example.com/", ""); badCF != nil { + t.Fatalf("%s must reject minimal Cloudflare challenge page, got %+v", hm, badCF) + } + } + + // 9. Adversarial 100 KB HTML latency check (<50ms across all 9 HTML modes) + adv := `Home` + strings.Repeat("
noise
", 4500) + `` + for _, hm := range []string{ + "fox_ridefox_html", + "park_tool_html", + "ifixit_html", + "ebike_drive_systems_html", + "specialized_turbo_support_html", + "bicycle_tire_specs_html", + "wheel_hub_specs_html", + "bicycle_brake_docs_html", + "suspension_cockpit_compat_html", + } { + t0 := time.Now() + if got := Wave3CyclingComponentsRunHTML(hm, adv, "https://example.org/", ""); got != nil { + t.Fatalf("%s adversarial noise shell returned non-nil: %+v", hm, got) + } + if elapsed := time.Since(t0); elapsed > 50*time.Millisecond*time.Duration(extractRaceSlowdown) { + t.Fatalf("%s adversarial 100KB payload took %v (>50ms)", hm, elapsed) + } + } +} + +func TestWave3CyclingComponentsFixturesParity(t *testing.T) { + type fixtureNegative struct { + Name string `json:"name"` + Status int `json:"status"` + InputURL string `json:"inputUrl"` + FinalURL string `json:"finalUrl"` + Payload string `json:"payload"` + } + type adapterFixture struct { + AdapterID string `json:"adapterId"` + Mode string `json:"mode"` + InputURL string `json:"inputUrl"` + ExpectedFetchURL string `json:"expectedFetchUrl"` + MockPayload string `json:"mockPayload"` + ExpectTitleIncludes string `json:"expectTitleIncludes"` + ExpectMarkdownIncludes []string `json:"expectMarkdownIncludes"` + NegativeCases []fixtureNegative `json:"negativeCases"` + } + + modeByID := map[string]string{ + "fox-ridefox": "fox_ridefox_html", + "park-tool": "park_tool_html", + "ifixit": "ifixit_json", + "ebike-drive-systems": "ebike_drive_systems_html", + "specialized-turbo-support": "specialized_turbo_support_html", + "bicycle-tire-specs": "bicycle_tire_specs_html", + "wheel-hub-specs": "wheel_hub_specs_html", + "bicycle-brake-docs": "bicycle_brake_docs_html", + "suspension-cockpit-compat": "suspension_cockpit_compat_html", + } + + for id, mode := range modeByID { + fxPath := filepath.Join("..", "..", "hub", "test", "fixtures", "adapters", id+".json") + raw, err := os.ReadFile(fxPath) + if err != nil { + t.Fatalf("read fixture %s: %v", fxPath, err) + } + var fx adapterFixture + if err := json.Unmarshal(raw, &fx); err != nil { + t.Fatalf("unmarshal fixture %s: %v", fxPath, err) + } + if fx.AdapterID != id { + t.Fatalf("%s: adapterId=%q want %q", fxPath, fx.AdapterID, id) + } + if len(fx.NegativeCases) < 4 { + t.Fatalf("%s: expected >= 4 negativeCases, got %d", fxPath, len(fx.NegativeCases)) + } + + if fx.Mode == "twin" { + docRaw, ok := FormatWave3CyclingComponentsJSONMode(mode, []byte(fx.MockPayload), nil, fx.InputURL) + if !ok { + t.Fatalf("%s: golden twin format failed", id) + } + doc := wave3CycDecodeDoc(t, docRaw) + if fx.ExpectTitleIncludes != "" && !strings.Contains(doc.Title, fx.ExpectTitleIncludes) { + t.Fatalf("%s: title %q missing %q", id, doc.Title, fx.ExpectTitleIncludes) + } + for _, needle := range fx.ExpectMarkdownIncludes { + if !strings.Contains(doc.Markdown, needle) { + t.Fatalf("%s: markdown missing %q\nmd=%s", id, needle, doc.Markdown) + } + } + } else { + res := Wave3CyclingComponentsRunHTML(mode, fx.MockPayload, fx.InputURL, id) + if res == nil { + t.Fatalf("%s: golden HTML extraction returned nil", id) + } + if fx.ExpectTitleIncludes != "" && !strings.Contains(res.Title, fx.ExpectTitleIncludes) { + t.Fatalf("%s: title %q missing %q", id, res.Title, fx.ExpectTitleIncludes) + } + for _, needle := range fx.ExpectMarkdownIncludes { + if !strings.Contains(res.Markdown, needle) { + t.Fatalf("%s: markdown missing %q\nmd=%s", id, needle, res.Markdown) + } + } + } + + for _, nc := range fx.NegativeCases { + ncURL := nc.FinalURL + if ncURL == "" { + ncURL = nc.InputURL + } + if ncURL == "" { + ncURL = fx.InputURL + } + if fx.Mode == "twin" { + if _, ok := FormatWave3CyclingComponentsJSONMode(mode, []byte(nc.Payload), nil, ncURL); ok { + t.Fatalf("%s negativeCase %q must not succeed as JSON", id, nc.Name) + } + if bad := Wave3CyclingComponentsRunHTML("ifixit_html", nc.Payload, ncURL, id); bad != nil { + t.Fatalf("%s negativeCase %q must not succeed as HTML", id, nc.Name) + } + } else { + if bad := Wave3CyclingComponentsRunHTML(mode, nc.Payload, ncURL, id); bad != nil { + t.Fatalf("%s negativeCase %q must not succeed, got %+v", id, nc.Name, bad) + } + } + } + } +} + +func TestWave3CyclingComponentsM7PerfBudget(t *testing.T) { + registerWave3CyclingComponentsHTMLModes() + scriptBloat := `` + styleBloat := `` + svgBloat := `` + strings.Repeat(``, 15000) + `` + + // 1. suspension-cockpit-compat (wolftoothcomponents.com ~1.6MB bloated HTML) -> < 25ms + wtBloated := `Drop-Stop Chainrings | Wolf Tooth` + styleBloat + `` + svgBloat + scriptBloat + `

Wolf Tooth Drop-Stop Chainrings

Fits 104 BCD and 110 BCD cranks; IS41 headset compatibility.

` + t0 := time.Now() + wtRes := Wave3CyclingComponentsRunHTML("suspension_cockpit_compat_html", wtBloated, "https://www.wolftoothcomponents.com/collections/chainrings", "suspension-cockpit-compat") + wtElapsed := time.Since(t0) + if wtRes == nil || !strings.Contains(wtRes.Markdown, "104 BCD") || !strings.Contains(wtRes.Markdown, "IS41") { + t.Fatalf("wolftooth bloated HTML extraction failed: %+v", wtRes) + } + if wtElapsed > 25*time.Millisecond*time.Duration(extractRaceSlowdown) { + t.Fatalf("wolftooth bloated HTML took %v (>25ms budget)", wtElapsed) + } + + // 2. bicycle-tire-specs (continental-tires.com bloated HTML) -> < 25ms + contiBloated := `Grand Prix 5000 S TR | Continental` + styleBloat + `` + svgBloat + scriptBloat + `

Grand Prix 5000 S TR

BlackChili compound, 220 TPI, Tubeless Ready, ETRTO 28-622 (700x28C).

` + t1 := time.Now() + ctRes := Wave3CyclingComponentsRunHTML("bicycle_tire_specs_html", contiBloated, "https://www.continental-tires.com/products/b2c/bicycle/tires/grand-prix-5000-s-tr/", "bicycle-tire-specs") + ctElapsed := time.Since(t1) + if ctRes == nil || !strings.Contains(ctRes.Markdown, "28-622") || !strings.Contains(ctRes.Markdown, "BlackChili") { + t.Fatalf("continental bloated HTML extraction failed: %+v", ctRes) + } + if ctElapsed > 25*time.Millisecond*time.Duration(extractRaceSlowdown) { + t.Fatalf("continental bloated HTML took %v (>25ms budget)", ctElapsed) + } + + // 3. suspension-cockpit-compat (pushindustries.com Shopify+Shogun shell with Product JSON-LD + var meta) + pushHTML := `ELEVENSIX (S-Series) | PUSH Industries

ELEVENSIX (S-Series)

` + pushRes := Wave3CyclingComponentsRunHTML("suspension_cockpit_compat_html", pushHTML, "https://www.pushindustries.com/products/elevensix", "suspension-cockpit-compat") + if pushRes == nil || pushRes.ExtractorID != "suspension-cockpit-compat" || + !strings.Contains(pushRes.Markdown, "PUSH Industries") || + !strings.Contains(pushRes.Markdown, "1300.00") || + !strings.Contains(pushRes.Markdown, "ELEVENSIX Rear Shock") { + t.Fatalf("suspension-cockpit-compat failed on Shopify+Shogun Product JSON-LD page: %+v", pushRes) + } + // Negative page without Product JSON-LD / specs MUST still return nil + pushEmpty := `Empty Page

Empty Page

` + if negPush := Wave3CyclingComponentsRunHTML("suspension_cockpit_compat_html", pushEmpty, "https://www.pushindustries.com/products/empty", "suspension-cockpit-compat"); negPush != nil { + t.Fatalf("suspension-cockpit-compat must return nil without Product JSON-LD or specs, got: %+v", negPush) + } +} diff --git a/internal/extract/wave3_cycling_oems.go b/internal/extract/wave3_cycling_oems.go new file mode 100644 index 0000000..77142c5 --- /dev/null +++ b/internal/extract/wave3_cycling_oems.go @@ -0,0 +1,2474 @@ +package extract + +import ( + "bytes" + "encoding/json" + "fmt" + stdhtml "html" + "math" + "strconv" + "strings" +) + +const ( + wave3CyclingMaxHTMLBytes = 2 * 1024 * 1024 + wave3CyclingStdHTMLMaxBytes = 1 * 1024 * 1024 + wave3CyclingMaxJSONBytes = 2 * 1024 * 1024 + wave3CyclingMaxRecords = 25 + wave3CyclingMaxBodyChars = 32000 +) + +var ( + wave3CyclingRxNotFoundTitle = newLazyRegexp(`(?i)(?:^|\b)(?:404|403|410|429|page\s+not\s+found|not\s+found|error\s*404|404\s+error\s+page|we\s+couldn'?t\s+find\s+that\s+page|access\s+denied|request\s+(?:rejected|blocked)|could\s+not\s+be\s+satisfied|unauthorized|attention\s+required|just\s+a\s+moment|403\s+forbidden|forbidden|403\s+error|warning:\s*blocked|cname\s+cross-user\s+banned|uh\s+oh!)(?:\b|$)`) + wave3CyclingRxMaintTitle = newLazyRegexp(`(?i)(?:scheduled\s+maintenance|temporarily\s+unavailable|service\s+unavailable|site\s+maintenance|under\s+maintenance|502\s+bad\s+gateway|503\s+service|down\s+for\s+maintenance)`) + wave3CyclingRxErrorTitle = newLazyRegexp(`(?i)^(?:(?:(?:400|401|403|404|406|410|429|500|502|503)\s+)?(?:internal\s+)?server\s+error|application\s+error|system\s+error|unexpected\s+error|error\s+page|404\s+error\s+page|(?:400|401|403|404|406|410|429|500|502|503|http\s+\d{3})\s+error|error\s+(?:400|401|403|404|406|410|429|500|502|503)|error)(?:\s*[|\-\x{2013}\x{2014}:]\s*.*)?$|^.*(?:\s*[|\-\x{2013}\x{2014}:]\s*error)$`) + wave3CyclingRxGenericTitle = newLazyRegexp(`(?i)^(?:loading\.{0,3}|home|welcome|search|99\s*spokes|geometry\s*geeks|ul\s*product\s*iq|saferproducts)$`) + wave3CyclingRxHTMLTag = newLazyRegexp(`<[^>]+>`) + wave3CyclingRxSpaceCollapse = newLazyRegexp(`[ \t\r\n]+`) + wave3CyclingRxISODate = newLazyRegexp(`^(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])(?:$|T\d{2}:\d{2}| \d{2}:\d{2})`) + wave3CyclingRxNextData = newLazyRegexp(`(?is)]*\bid\s*=\s*["']__NEXT_DATA__["'][^>]*>(.*?)`) + wave3CyclingRxPriceNum = newLazyRegexp(`(?:USD|CAD|EUR|GBP|AUD|\$|€|£)?\s*([0-9][0-9,]*(?:\.[0-9]{1,2})?)`) + wave3CyclingRxBatteryWh = newLazyRegexp(`(?i)\b(\d{3,4}(?:\.\d+)?)\s*Wh\b`) + wave3CyclingRxMotorWatts = newLazyRegexp(`(?i)\b(\d{3,4})\s*W\b(?:\s*(?:motor|hub|mid-?drive|Bosch|Shimano|Bafang))?|\b(Bosch\s+[A-Za-z0-9 +\-]{2,40}|Shimano\s+(?:EP\d|STEPS\s+[A-Za-z0-9]+)|Bafang\s+[A-Za-z0-9 \-]+|Brose\s+[A-Za-z0-9 \-]+)`) + wave3CyclingRxTorqueNm = newLazyRegexp(`(?i)\b(\d{2,3})\s*Nm\b`) + wave3CyclingRxPayloadCap = newLazyRegexp(`(?i)(?:GVWR|gross\s+vehicle\s+weight(?:\s+rating)?|max(?:imum)?\s+(?:payload|load|capacity|weight)|payload(?:\s+capacity)?|cargo\s+capacity)\s*[:\-]?\s*(\d{2,4}\s*(?:kg|lbs?|pounds))`) + wave3CyclingRxEbikeClass = newLazyRegexp(`(?i)\b(Class\s*[123](?:\s*/\s*[123])?)\b`) + wave3CyclingRxULStandard = newLazyRegexp(`(?i)\b((?:ANSI/CAN/)?UL\s*(?:2849|2271|2272|2580|1642|2054|94))\b`) + wave3CyclingRxULFileNum = newLazyRegexp(`\b(E\d{5,7})\b`) + wave3CyclingRxULCCN = newLazyRegexp(`(?i)\b(?:CCN|Category\s*Control\s*Number)\s*[:\-]?\s*([A-Z]{4}\d?)\b`) + wave3CyclingRxStatuteCite = newLazyRegexp(`(?i)\b(Minn\.\s*Stat\.\s*§?\s*\d+\.\d+|RCW\s+\d+\.\d+\.\d+|C\.R\.S\.?\s*§?\s*\d+-\d+-\d+|Cal\.\s*Veh\.\s*Code\s*§?\s*\d+(?:\.\d+)?|\d+\s+U\.S\.C\.\s*§?\s*\d+|16\s+CFR\s+(?:Part\s+)?\d+)\b`) + wave3CyclingRxStateName = newLazyRegexp(`\b(Alabama|Alaska|Arizona|Arkansas|California|Colorado|Connecticut|Delaware|Florida|Georgia|Hawaii|Idaho|Illinois|Indiana|Iowa|Kansas|Kentucky|Louisiana|Maine|Maryland|Massachusetts|Michigan|Minnesota|Mississippi|Missouri|Montana|Nebraska|Nevada|New Hampshire|New Jersey|New Mexico|New York|North Carolina|North Dakota|Ohio|Oklahoma|Oregon|Pennsylvania|Rhode Island|South Carolina|South Dakota|Tennessee|Texas|Utah|Vermont|Virginia|Washington|West Virginia|Wisconsin|Wyoming)\b`) +) + +func init() { + registerWave3CyclingOEMsHTMLModes() +} + +// RegisterWave3CyclingOEMsHTMLModes registers all Category O2 HTML modes (#350-#358) lazily. +func RegisterWave3CyclingOEMsHTMLModes() { + registerWave3CyclingOEMsHTMLModes() +} + +func registerWave3CyclingOEMsHTMLModes() { + for _, mode := range []string{ + "cargo_ebike_oems_html", + "us_ebike_oems_html", + "qbp_frame_brands_html", + "mtb_geometry_brands_html", + "geometrygeeks_99spokes_html", + "sheldon_brown_html", + "ul_product_iq_html", + "e_bike_state_laws_html", + "cpsc_ebike_incidents_html", + } { + m := mode + RegisterExternalHTMLModeLazy(m, func(rawHTML, baseURL string, _ func() string, extractorID string) *DeclarativePostFetchResult { + return Wave3CyclingOEMsRunHTML(m, rawHTML, baseURL, extractorID) + }) + } +} + +// IsWave3CyclingOEMsHTMLMode reports whether mode is one of the 9 Category O2 HTML modes (#350-#358). +func IsWave3CyclingOEMsHTMLMode(mode string) bool { + switch mode { + case "cargo_ebike_oems_html", + "us_ebike_oems_html", + "qbp_frame_brands_html", + "mtb_geometry_brands_html", + "geometrygeeks_99spokes_html", + "sheldon_brown_html", + "ul_product_iq_html", + "e_bike_state_laws_html", + "cpsc_ebike_incidents_html": + return true + default: + return false + } +} + +// IsWave3CyclingOEMsJSONMode reports whether mode is handled by Category O2 JSON formatters (`cpsc_ebike_incidents_json`). +func IsWave3CyclingOEMsJSONMode(mode string) bool { + return mode == "cpsc_ebike_incidents_json" +} + +func wave3CyclingDefaultExtractorID(mode string) string { + switch mode { + case "cargo_ebike_oems_html": + return "cargo-ebike-oems" + case "us_ebike_oems_html": + return "us-ebike-oems" + case "qbp_frame_brands_html": + return "qbp-frame-brands" + case "mtb_geometry_brands_html": + return "mtb-geometry-brands" + case "geometrygeeks_99spokes_html": + return "geometrygeeks-99spokes" + case "sheldon_brown_html": + return "sheldon-brown" + case "ul_product_iq_html": + return "ul-product-iq" + case "e_bike_state_laws_html": + return "e-bike-state-laws" + case "cpsc_ebike_incidents_html", "cpsc_ebike_incidents_json": + return "cpsc-ebike-incidents" + default: + return "" + } +} + +// Wave3CyclingOEMsRunHTML executes a Category O2 HTML extractor and returns DeclarativePostFetchResult. +func Wave3CyclingOEMsRunHTML(mode, rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + if !IsWave3CyclingOEMsHTMLMode(mode) || len(rawHTML) == 0 || strings.IndexByte(rawHTML, '<') < 0 || strings.IndexByte(rawHTML, '>') < 0 { + return nil + } + maxHTML := wave3CyclingStdHTMLMaxBytes + switch mode { + case "cargo_ebike_oems_html", "us_ebike_oems_html", "qbp_frame_brands_html", "mtb_geometry_brands_html", "e_bike_state_laws_html": + maxHTML = wave3CyclingMaxHTMLBytes + } + if len(rawHTML) > maxHTML { + rawHTML = truncateUTF8SafeFullDocGo(rawHTML, maxHTML) + } + trimmedStart := strings.TrimLeft(rawHTML, " \t\r\n") + if trimmedStart == "" || trimmedStart[0] == '{' || trimmedStart[0] == '[' { + return nil + } + probe := rawHTML + if len(probe) > 65536 { + probe = probe[:65536] + } + probeLower := asciiLowerExtractString(probe) + urlLower := asciiLowerExtractString(baseURL) + + if !wave3CyclingMatchesModePrefilter(mode, rawHTML, probeLower, urlLower) { + return nil + } + if wave3CyclingHasNegativeShell(mode, rawHTML, probeLower, urlLower) { + return nil + } + if extractorID == "" { + extractorID = wave3CyclingDefaultExtractorID(mode) + } + + var res *DeclarativePostFetchResult + switch mode { + case "cargo_ebike_oems_html": + res = wave3CyclingExtractCargoOEMHTML(rawHTML, baseURL, extractorID) + case "us_ebike_oems_html": + res = wave3CyclingExtractUSEbikeOEMHTML(rawHTML, baseURL, extractorID) + case "qbp_frame_brands_html": + res = wave3CyclingExtractQBPFrameHTML(rawHTML, probeLower, baseURL, urlLower, extractorID) + case "mtb_geometry_brands_html": + res = wave3CyclingExtractMTBGeometryHTML(rawHTML, probeLower, baseURL, urlLower, extractorID) + case "geometrygeeks_99spokes_html": + res = wave3CyclingExtractGeometryGeeks99SpokesHTML(rawHTML, probeLower, baseURL, urlLower, extractorID) + case "sheldon_brown_html": + res = wave3CyclingExtractSheldonBrownHTML(rawHTML, baseURL, extractorID) + case "ul_product_iq_html": + res = wave3CyclingExtractULProductIQHTML(rawHTML, baseURL, extractorID) + case "e_bike_state_laws_html": + res = wave3CyclingExtractEBikeStateLawsHTML(rawHTML, baseURL, urlLower, extractorID) + case "cpsc_ebike_incidents_html": + res = wave3CyclingExtractCPSCPublicSearchHTML(rawHTML, baseURL, extractorID) + } + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return nil + } + return wave3CyclingFinalizePostFetch(res) +} + +// RunWave3CyclingOEMsHTMLMode executes a Category O2 HTML extractor and returns JSON-marshaled DeclarativePostFetchResult. +func RunWave3CyclingOEMsHTMLMode(mode, rawHTML, baseURL string) (string, bool) { + res := Wave3CyclingOEMsRunHTML(mode, rawHTML, baseURL, wave3CyclingDefaultExtractorID(mode)) + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return "", false + } + res = sanitizePostFetchResultDeclHTML(res) + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return "", false + } + encoded, err := json.Marshal(res) + if err != nil { + return "", false + } + return string(encoded), true +} + +// FormatWave3CyclingOEMsJSONDoc formats a Category O2 JSON twin payload into DeclarativeFormattedDoc. +func FormatWave3CyclingOEMsJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool) { + return formatWave3CyclingOEMsJSON(mode, raw, params, origURL) +} + +func formatWave3CyclingOEMsJSON(mode string, raw []byte, _ map[string]string, origURL string) (*DeclarativeFormattedDoc, bool) { + if !IsWave3CyclingOEMsJSONMode(mode) || len(raw) == 0 || len(raw) > wave3CyclingMaxJSONBytes { + return nil, false + } + trimmed := bytes.TrimSpace(bytes.TrimPrefix(raw, []byte("\xEF\xBB\xBF"))) + if len(trimmed) == 0 || (trimmed[0] != '[' && trimmed[0] != '{') { + return nil, false + } + parsed, ok := decodeJSONWithNumbers(trimmed) + if !ok || parsed == nil { + return nil, false + } + doc, handled := wave3CyclingFormatCPSCIncidentsJSON(parsed, origURL) + if !handled || doc == nil || strings.TrimSpace(doc.Markdown) == "" { + return nil, false + } + return wave3CyclingFinalizeDoc(doc), true +} + +// FormatWave3CyclingOEMsJSONMode formats a Category O2 JSON payload and returns JSON-marshaled DeclarativeFormattedDoc. +func FormatWave3CyclingOEMsJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool) { + doc, ok := formatWave3CyclingOEMsJSON(mode, raw, params, origURL) + if !ok || doc == nil { + return "", false + } + encoded, err := json.Marshal(doc) + if err != nil { + return "", false + } + return string(encoded), true +} + +// ── Prefilters & Shared Negative-Shell Guards ─────────────────────────────────────────────────── + +func wave3CyclingMatchesModePrefilter(mode, rawHTML, probeLower, urlLower string) bool { + switch mode { + case "cargo_ebike_oems_html": + return strings.Contains(urlLower, "yubabikes.com") || + strings.Contains(urlLower, "xtracycle.com") || + strings.Contains(urlLower, "ternbicycles.com") || + strings.Contains(urlLower, "r-m.de") || + strings.Contains(probeLower, "yuba") || + strings.Contains(probeLower, "xtracycle") || + strings.Contains(probeLower, "tern") || + strings.Contains(probeLower, "riese") || + strings.Contains(probeLower, "payload") || + strings.Contains(probeLower, "gvwr") || + hasJSONLDScriptToken(probeLower) || + strings.Contains(probeLower, "= 0 { + rest := pathOnly[idx+3:] + if slash := strings.IndexByte(rest, '/'); slash >= 0 { + pathOnly = rest[slash:] + } else { + pathOnly = "/" + } + } + if cut := strings.IndexAny(pathOnly, "?#"); cut >= 0 { + pathOnly = pathOnly[:cut] + } + return strings.HasSuffix(pathOnly, "/error") || + strings.Contains(pathOnly, "/error/") || + strings.HasSuffix(pathOnly, "/error.html") || + strings.HasSuffix(pathOnly, "/error.htm") || + strings.HasSuffix(pathOnly, "/error.aspx") || + strings.HasSuffix(pathOnly, "/login") || + strings.Contains(pathOnly, "/login/") +} + +func wave3CyclingIsNegativeTitle(title string) bool { + t := strings.TrimSpace(title) + if t == "" { + return false + } + return wave3CyclingRxNotFoundTitle.MatchString(t) || + wave3CyclingRxMaintTitle.MatchString(t) || + wave3CyclingRxErrorTitle.MatchString(t) +} + +func wave3CyclingIsGenericTitle(title string) bool { + return wave3CyclingRxGenericTitle.MatchString(strings.TrimSpace(title)) +} + +func wave3CyclingHasNegativeShell(mode, rawHTML, probeLower, urlLower string) bool { + if wave3CyclingIsNegativeURL(urlLower) { + return true + } + for _, marker := range []string{ + "cf-browser-verification", + "cf-mitigated", + "_cf_chl_opt", + "cf_chl_opt", + "attention required! | cloudflare", + "sorry, you have been blocked", + "you have been blocked", + "just a moment...", + "warning: blocked - ul prospector", + "cname cross-user banned", + "errors.edgesuite.net", + "error from cloudfront", + "the request could not be satisfied", + "you don't have permission to access", + "the requested url was rejected", + "your support id is", + "geo.captcha-delivery.com", + "captcha-delivery.com", + "vercel security checkpoint", + "failed to verify your browser", + "scheduled maintenance", + "down for maintenance", + "site is currently under maintenance", + "temporarily unavailable", + "no http resource was found", + "404 error page", + } { + if strings.Contains(probeLower, marker) { + return true + } + } + title := extractTitleLinearQuick(probeLower) + if title == "" { + title = extractTitleLinearQuick(rawHTML) + } + if wave3CyclingIsNegativeTitle(title) { + return true + } + if canon := strings.ToLower(extractMetaContentDeclHTML(rawHTML, "og:url")); strings.HasSuffix(canon, "/404") || strings.Contains(canon, "/404?") { + return true + } + + rawLower := probeLower + hasRealBodyMarkers := hasJSONLDScriptToken(rawLower) || + strings.Contains(rawLower, " 65536 { + tail := rawHTML[65536:] + hasRealBodyMarkers = indexFoldASCIIExtract(tail, "= 0 || + indexFoldASCIIExtract(tail, "= 0 || + indexFoldASCIIExtract(tail, "= 0 || + indexFoldASCIIExtract(tail, "application/ld+json") >= 0 || + indexFoldASCIIExtract(tail, "__next_data__") >= 0 || + indexFoldASCIIExtract(tail, "__nuxt") >= 0 + } + + if !hasRealBodyMarkers { + if strings.Contains(rawLower, "") || + wave3HasEmptyRootDivShell(rawHTML, probeLower, true) { + return true + } + } + if mode == "geometrygeeks_99spokes_html" { + // Reject empty Next.js shell on 99spokes even if __NEXT_DATA__ tag exists without actual bike/geometry payload. + hasEmptyNextDiv := strings.Contains(rawLower, `
`) + if !hasEmptyNextDiv && len(rawHTML) > 65536 { + hasEmptyNextDiv = indexFoldASCIIExtract(rawHTML[65536:], `
`) >= 0 + } + if hasEmptyNextDiv { + hasGeoPayload := strings.Contains(rawLower, " 65536 { + tail := rawHTML[65536:] + hasGeoPayload = indexFoldASCIIExtract(tail, "= 0 || + indexFoldASCIIExtract(tail, "= 0 || + indexFoldASCIIExtract(tail, "bike-geometry-table") >= 0 || + indexFoldASCIIExtract(tail, `"reach"`) >= 0 || + indexFoldASCIIExtract(tail, `"geometry"`) >= 0 + } + if !hasGeoPayload { + return true + } + } + } + return false +} + +// ── Shared Extraction Utilities ───────────────────────────────────────────────────────────────── + +func wave3CyclingCleanText(s string) string { + if s == "" { + return "" + } + if strings.IndexByte(s, '<') >= 0 { + s = wave3CyclingRxHTMLTag.ReplaceAllString(s, " ") + } + if strings.IndexByte(s, '&') >= 0 { + s = stdhtml.UnescapeString(s) + if strings.IndexByte(s, '<') >= 0 { + s = wave3CyclingRxHTMLTag.ReplaceAllString(s, " ") + } + } + if !strings.ContainsAny(s, "\t\r\n") && !strings.Contains(s, " ") { + return strings.TrimSpace(s) + } + return strings.TrimSpace(wave3CyclingRxSpaceCollapse.ReplaceAllString(s, " ")) +} + +func wave3CyclingStringVal(v any) string { + switch tv := v.(type) { + case string: + return strings.TrimSpace(tv) + case json.Number: + return tv.String() + case float64: + if math.IsNaN(tv) || math.IsInf(tv, 0) { + return "" + } + if tv == math.Trunc(tv) { + return strconv.FormatInt(int64(tv), 10) + } + return strconv.FormatFloat(tv, 'f', -1, 64) + case int: + return strconv.Itoa(tv) + case int64: + return strconv.FormatInt(tv, 10) + case bool: + if tv { + return "true" + } + return "false" + default: + return "" + } +} + +func wave3CyclingPlain(v any, maxLen int) string { + return SanitizeSchemaPlainField(wave3CyclingStringVal(v), maxLen) +} + +func wave3CyclingFirstNonEmpty(vals ...string) string { + for _, v := range vals { + if t := strings.TrimSpace(v); t != "" { + return t + } + } + return "" +} + +func wave3CyclingNormalizeISODate(raw string) string { + s := SanitizeSchemaPlainField(raw, 48) + if s == "" { + return "" + } + if m := wave3CyclingRxISODate.FindStringSubmatch(s); len(m) == 4 { + return m[1] + "-" + m[2] + "-" + m[3] + } + return "" +} + +func wave3CyclingAddLink(links *[]string, seen map[string]bool, raw, base string) { + u := SanitizeSchemaHTTPSURL(raw, base) + if u != "" && !seen[u] { + seen[u] = true + *links = append(*links, u) + } +} + +func wave3CyclingExtractTitle(doc *HTMLDoc, rawHTML string) string { + if doc != nil { + if h1 := SanitizeSchemaPlainField(wave3CyclingCleanText(doc.Text("h1")), 240); h1 != "" && !wave3CyclingIsGenericTitle(h1) && !wave3CyclingIsNegativeTitle(h1) { + return h1 + } + } + if og := SanitizeSchemaPlainField(extractMetaContentDeclHTML(rawHTML, "og:title"), 240); og != "" && !wave3CyclingIsGenericTitle(og) && !wave3CyclingIsNegativeTitle(og) { + return og + } + if t := SanitizeSchemaPlainField(extractTitleLinearQuick(rawHTML), 240); t != "" && !wave3CyclingIsGenericTitle(t) && !wave3CyclingIsNegativeTitle(t) { + return t + } + if doc != nil { + if h2 := SanitizeSchemaPlainField(wave3CyclingCleanText(doc.Text("h2")), 240); h2 != "" && !wave3CyclingIsGenericTitle(h2) && !wave3CyclingIsNegativeTitle(h2) { + return h2 + } + } + return "" +} + +func wave3CyclingExtractMetaDesc(rawHTML string) string { + return wave3CyclingFirstNonEmpty( + SanitizeSchemaPlainField(extractMetaContentDeclHTML(rawHTML, "og:description"), 600), + SanitizeSchemaPlainField(extractMetaContentDeclHTML(rawHTML, "description"), 600), + ) +} + +type wave3CyclingProductJSONLD struct { + Name string + Brand string + SKU string + Price string + Currency string + Availability string + Description string + URL string +} + +func wave3CyclingSlimHTMLForDOM(rawHTML string, maxBytes int) string { + slim := stripScriptsAndStylesDeclHTML(rawHTML) + if maxBytes > 0 && len(slim) > maxBytes { + slim = truncateUTF8SafeFullDocGo(slim, maxBytes) + } + return slim +} + +func wave3CyclingExtractJSONLDNodes(rawHTML string) []map[string]any { + return extractJSONLDObjectsDeclHTML(rawHTML, 24) +} + +func wave3CyclingHasJSONLDType(obj map[string]any, wanted ...string) bool { + if obj == nil { + return false + } + check := func(s string) bool { + s = strings.TrimSpace(strings.ToLower(s)) + if idx := strings.LastIndexAny(s, "/:"); idx >= 0 { + s = s[idx+1:] + } + for _, w := range wanted { + if s == strings.ToLower(w) { + return true + } + } + return false + } + switch t := obj["@type"].(type) { + case string: + return check(t) + case []any: + for _, item := range t { + if s, ok := item.(string); ok && check(s) { + return true + } + } + } + return false +} + +func wave3CyclingParsePrice(raw string) string { + cleaned := strings.TrimSpace(raw) + if cleaned == "" || strings.HasPrefix(cleaned, "-") { + return "" + } + m := wave3CyclingRxPriceNum.FindStringSubmatch(cleaned) + if len(m) < 2 { + return "" + } + numStr := strings.ReplaceAll(m[1], ",", "") + val, err := strconv.ParseFloat(numStr, 64) + if err != nil || val <= 0 || val > 1000000 { + return "" + } + return strconv.FormatFloat(val, 'f', 2, 64) +} + +func wave3CyclingExtractProductJSONLD(nodes []map[string]any, baseURL string) *wave3CyclingProductJSONLD { + for _, obj := range nodes { + if !wave3CyclingHasJSONLDType(obj, "Product", "IndividualProduct", "ProductGroup", "Vehicle") { + continue + } + p := &wave3CyclingProductJSONLD{ + Name: wave3CyclingPlain(obj["name"], 240), + SKU: wave3CyclingPlain(obj["sku"], 80), + Description: wave3CyclingPlain(obj["description"], 800), + URL: SanitizeSchemaHTTPSURL(wave3CyclingStringVal(obj["url"]), baseURL), + } + switch b := obj["brand"].(type) { + case string: + p.Brand = wave3CyclingPlain(b, 120) + case map[string]any: + p.Brand = wave3CyclingPlain(b["name"], 120) + } + extractOffer := func(om map[string]any) { + if om == nil { + return + } + if p.Price == "" { + p.Price = wave3CyclingFirstNonEmpty( + wave3CyclingParsePrice(wave3CyclingStringVal(om["price"])), + wave3CyclingParsePrice(wave3CyclingStringVal(om["lowPrice"])), + ) + } + if p.Currency == "" { + cur := strings.ToUpper(wave3CyclingPlain(om["priceCurrency"], 8)) + if len(cur) == 3 { + p.Currency = cur + } + } + if p.Availability == "" { + avail := wave3CyclingStringVal(om["availability"]) + if idx := strings.LastIndexAny(avail, "/:"); idx >= 0 { + avail = avail[idx+1:] + } + p.Availability = wave3CyclingPlain(avail, 48) + } + } + switch off := obj["offers"].(type) { + case map[string]any: + extractOffer(off) + case []any: + for _, item := range off { + if om, ok := item.(map[string]any); ok { + extractOffer(om) + if p.Price != "" { + break + } + } + } + } + if p.Name != "" || p.SKU != "" || p.Price != "" { + return p + } + } + return nil +} + +func wave3CyclingExtractHTMLTables(doc *HTMLDoc, selector string, maxTables, maxRows, maxCols int) ([]string, [][][]string) { + if doc == nil { + return nil, nil + } + tables := doc.Select(selector, maxTables*2) + var rendered []string + var parsed [][][]string + for _, tbl := range tables { + if len(rendered) >= maxTables { + break + } + rows := tbl.TableRows() + if len(rows) < 2 { + continue + } + // Skip single-row noscript warnings or empty layout tables. + var cleanRows [][]string + for _, r := range rows { + if len(r) == 0 { + continue + } + joined := strings.ToLower(strings.Join(r, " ")) + if strings.Contains(joined, "must use a web browser") || strings.Contains(joined, "add to compare") { + continue + } + cleanRows = append(cleanRows, r) + } + if len(cleanRows) < 2 { + continue + } + headers := cleanRows[0] + cols := len(headers) + if cols == 0 { + continue + } + if cols > maxCols { + cols = maxCols + } + cleanHdr := make([]string, cols) + nonEmptyHdr := 0 + for i := 0; i < cols; i++ { + cleanHdr[i] = SanitizeSchemaPlainField(headers[i], 64) + if cleanHdr[i] == "" { + if i == 0 { + cleanHdr[i] = "Metric" + } else { + cleanHdr[i] = fmt.Sprintf("Col %d", i+1) + } + } else { + nonEmptyHdr++ + } + } + if nonEmptyHdr == 0 && cols < 2 { + continue + } + var dataRows [][]string + for i := 1; i < len(cleanRows) && len(dataRows) < maxRows; i++ { + r := cleanRows[i] + dr := make([]string, cols) + nonEmpty := false + for c := 0; c < cols; c++ { + if c < len(r) { + dr[c] = SanitizeSchemaPlainField(r[c], 120) + if dr[c] != "" { + nonEmpty = true + } + } + } + if nonEmpty { + dataRows = append(dataRows, dr) + } + } + if len(dataRows) == 0 { + continue + } + rendered = append(rendered, formatDeclarativeGFMTable(cleanHdr, dataRows)) + allRows := append([][]string{cleanHdr}, dataRows...) + parsed = append(parsed, allRows) + } + return rendered, parsed +} + +func wave3CyclingExtractBodyProse(doc *HTMLDoc, baseURL string) (string, []string) { + if doc == nil { + return "", nil + } + var container *HTMLNode + for _, sel := range []string{"main", "article", "[role='main']", ".article-body", ".content", "body"} { + if c := doc.First(sel); c != nil { + container = c + break + } + } + if container == nil { + container = &doc.HTMLNode + } + + var parts []string + seenText := make(map[string]bool) + totalBytes := 0 + for _, nd := range container.Select("h2, h3, h4, p, li, blockquote, dt, dd", 120) { + txt := wave3CyclingCleanText(nd.Text()) + if txt == "" || seenText[txt] { + continue + } + seenText[txt] = true + var line string + switch nd.Tag() { + case "h2": + line = "## " + escapeDeclMarkdownBrackets(txt) + case "h3", "h4": + line = "### " + escapeDeclMarkdownBrackets(txt) + case "li": + line = "- " + txt + case "blockquote": + line = "> " + txt + case "dt": + line = "**" + txt + "**" + default: + line = txt + } + if totalBytes > 0 && totalBytes+len(line)+2 > 8000 { + break + } + parts = append(parts, line) + totalBytes += len(line) + 2 + } + + md := strings.Join(parts, "\n\n") + if md == "" { + md = wave3CyclingCleanText(container.Text()) + if len(md) > 8000 { + md = truncateUTF8SafeFullDocGo(md, 8000) + } + } + + var links []string + seenLinks := make(map[string]bool) + for _, a := range container.Select("a[href]", 100) { + wave3CyclingAddLink(&links, seenLinks, a.AttrOrEmpty("href"), baseURL) + } + return md, links +} + +func wave3CyclingExtractNextDataObj(rawHTML string) map[string]any { + if indexFoldASCIIExtract(rawHTML, "__next_data__") < 0 { + return nil + } + m := wave3CyclingRxNextData.FindStringSubmatch(rawHTML) + if len(m) < 2 { + return nil + } + raw := strings.TrimSpace(m[1]) + if raw == "" || raw[0] != '{' { + return nil + } + parsed, ok := decodeJSONWithNumbers([]byte(raw)) + if !ok { + return nil + } + obj, _ := parsed.(map[string]any) + return obj +} + +func wave3CyclingNestedMap(obj map[string]any, keys ...string) map[string]any { + cur := obj + for _, k := range keys { + if cur == nil { + return nil + } + next, ok := cur[k].(map[string]any) + if !ok { + return nil + } + cur = next + } + return cur +} + +func wave3CyclingIntPtr(n int) *int { return &n } +func wave3CyclingBoolPtr(b bool) *bool { return &b } + +func wave3CyclingFinalizeDoc(doc *DeclarativeFormattedDoc) *DeclarativeFormattedDoc { + if doc == nil { + return nil + } + if len(doc.Records) > wave3CyclingMaxRecords { + if doc.Total == nil { + doc.Total = wave3CyclingIntPtr(len(doc.Records)) + } + doc.Records = doc.Records[:wave3CyclingMaxRecords] + doc.Returned = wave3CyclingIntPtr(len(doc.Records)) + doc.Truncated = wave3CyclingBoolPtr(true) + if doc.NextCursor == "" { + doc.NextCursor = strconv.Itoa(len(doc.Records)) + } + } + if len(doc.Markdown) > wave3CyclingMaxBodyChars { + doc.Markdown = truncateUTF8SafeFullDocGo(doc.Markdown, wave3CyclingMaxBodyChars) + } + if sanitized, ok := sanitizeDeclarativeFormattedDocGo(doc); ok && sanitized != nil { + return sanitized + } + return nil +} + +func wave3CyclingFinalizePostFetch(res *DeclarativePostFetchResult) *DeclarativePostFetchResult { + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return nil + } + if len(res.Records) > wave3CyclingMaxRecords { + if res.Total == nil { + res.Total = wave3CyclingIntPtr(len(res.Records)) + } + res.Records = res.Records[:wave3CyclingMaxRecords] + res.Returned = wave3CyclingIntPtr(len(res.Records)) + res.Truncated = wave3CyclingBoolPtr(true) + if res.NextCursor == "" { + res.NextCursor = strconv.Itoa(len(res.Records)) + } + } + if len(res.Markdown) > wave3CyclingMaxBodyChars { + res.Markdown = truncateUTF8SafeFullDocGo(res.Markdown, wave3CyclingMaxBodyChars) + } + return res +} + +// ── #350 Cargo E-Bike OEMs ────────────────────────────────────────────────────────────────────── + +func wave3CyclingExtractCargoOEMHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + nodes := wave3CyclingExtractJSONLDNodes(rawHTML) + prod := wave3CyclingExtractProductJSONLD(nodes, baseURL) + desc := wave3CyclingExtractMetaDesc(rawHTML) + if desc == "" && prod != nil { + desc = prod.Description + } + slimFull := wave3CyclingSlimHTMLForDOM(rawHTML, 512*1024) + domTarget := slimFull + inMain := false + if openMain, okOpen := findOpenTagLinearDeclHTML(slimFull, "main", nil, 0); okOpen && !openMain.selfClosing { + var inner string + if closeStart, _, okClose := findCloseTagLinearDeclHTML(slimFull, "main", openMain.openEnd); okClose { + inner = slimFull[openMain.openEnd:closeStart] + } else if openMain.openEnd < len(slimFull) { + inner = slimFull[openMain.openEnd:] + } + if strings.TrimSpace(inner) != "" { + domTarget = "
" + inner + "
" + inMain = true + } + } + const cargoDOMMaxBytes = 128 * 1024 + if len(domTarget) > cargoDOMMaxBytes { + domTarget = truncateUTF8SafeFullDocGo(domTarget, cargoDOMMaxBytes) + } + doc := ParseHTMLDoc(domTarget, cargoDOMMaxBytes) + + title := "" + if inMain && doc != nil { + if h1 := SanitizeSchemaPlainField(wave3CyclingCleanText(doc.Text("h1")), 240); h1 != "" && !wave3CyclingIsGenericTitle(h1) && !wave3CyclingIsNegativeTitle(h1) { + title = h1 + } + } + if title == "" && !inMain { + if og := SanitizeSchemaPlainField(extractMetaContentDeclHTML(rawHTML, "og:title"), 240); og != "" && !wave3CyclingIsGenericTitle(og) && !wave3CyclingIsNegativeTitle(og) { + title = og + } + } + if title == "" { + title = wave3CyclingExtractTitle(doc, rawHTML) + } + if title == "" && prod != nil { + title = prod.Name + } + if title == "" { + return nil + } + + bodyText := "" + if doc != nil { + bodyText = doc.Text("main") + if bodyText == "" { + bodyText = doc.Text("body") + } + if len(bodyText) > 128*1024 { + bodyText = bodyText[:128*1024] + } + } + scanText := title + "\n" + desc + "\n" + bodyText + + payload := "" + if m := wave3CyclingRxPayloadCap.FindStringSubmatch(scanText); len(m) >= 2 { + payload = SanitizeSchemaPlainField(m[1], 48) + } + batteryWh := "" + if m := wave3CyclingRxBatteryWh.FindStringSubmatch(scanText); len(m) >= 2 { + batteryWh = m[1] + " Wh" + } + motor := "" + if m := wave3CyclingRxMotorWatts.FindStringSubmatch(scanText); len(m) >= 3 { + if m[2] != "" { + motor = SanitizeSchemaPlainField(m[2], 64) + } else if m[1] != "" { + motor = m[1] + "W" + } + } + torque := "" + if m := wave3CyclingRxTorqueNm.FindStringSubmatch(scanText); len(m) >= 2 { + torque = m[1] + " Nm" + } + + var tables []string + if indexFoldASCIIExtract(domTarget, "= 0 { + tables, _ = wave3CyclingExtractHTMLTables(doc, "table", 3, 25, 8) + } + dlMap := map[string]string{} + if doc != nil && indexFoldASCIIExtract(domTarget, "= 0 { + dlMap = doc.DLMap("dl") + } + + var bullets []string + rec := map[string]any{"model": title} + if prod != nil && prod.Brand != "" { + bullets = append(bullets, "- **Brand**: "+prod.Brand) + rec["brand"] = prod.Brand + } + if prod != nil && prod.Price != "" { + priceStr := prod.Price + if prod.Currency != "" { + priceStr = prod.Currency + " " + priceStr + } + bullets = append(bullets, "- **Price**: "+priceStr) + rec["price"] = prod.Price + if prod.Currency != "" { + rec["currency"] = prod.Currency + } + } + if payload != "" { + bullets = append(bullets, "- **Payload / GVWR**: "+payload) + rec["payload"] = payload + } + if batteryWh != "" { + bullets = append(bullets, "- **Battery**: "+batteryWh) + rec["batteryWh"] = batteryWh + } + if motor != "" { + motorLine := motor + if torque != "" { + motorLine += " (" + torque + ")" + rec["torque"] = torque + } + bullets = append(bullets, "- **Motor**: "+motorLine) + rec["motor"] = motor + } else if torque != "" { + bullets = append(bullets, "- **Motor Torque**: "+torque) + rec["torque"] = torque + } + + var blocks []string + blocks = append(blocks, "# "+escapeDeclMarkdownBrackets(title)) + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + if len(dlMap) > 0 { + var dlRows [][]string + for k, v := range dlMap { + if len(dlRows) >= 15 { + break + } + dlRows = append(dlRows, []string{SanitizeSchemaPlainField(k, 64), SanitizeSchemaPlainField(v, 140)}) + } + if len(dlRows) > 0 { + blocks = append(blocks, "## Specifications\n\n"+formatDeclarativeGFMTable([]string{"Specification", "Value"}, dlRows)) + } + } + for idx, tbl := range tables { + heading := "## Cargo & Bike Specifications" + if idx > 0 { + heading = fmt.Sprintf("## Specifications Table %d", idx+1) + } + blocks = append(blocks, heading+"\n\n"+tbl) + } + + var links []string + seenLinks := make(map[string]bool) + if prod != nil && prod.URL != "" { + wave3CyclingAddLink(&links, seenLinks, prod.URL, baseURL) + rec["url"] = prod.URL + } + prose, pLinks := wave3CyclingExtractBodyProse(doc, baseURL) + if len(tables) == 0 && len(bullets) <= 1 && prose == "" && desc == "" { + return nil + } + for _, l := range pLinks { + wave3CyclingAddLink(&links, seenLinks, l, baseURL) + } + var overviewParts []string + if desc != "" { + overviewParts = append(overviewParts, desc) + } + if prose != "" && (desc == "" || !strings.Contains(prose, desc)) { + overviewParts = append(overviewParts, prose) + } + if len(overviewParts) > 0 { + blocks = append(blocks, "## Overview\n\n"+strings.Join(overviewParts, "\n\n")) + } + + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: []map[string]any{rec}, + } +} + +// ── #351 US E-Bike OEMs ───────────────────────────────────────────────────────────────────────── + +func wave3CyclingExtractUSEbikeOEMHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + nodes := wave3CyclingExtractJSONLDNodes(rawHTML) + prod := wave3CyclingExtractProductJSONLD(nodes, baseURL) + desc := wave3CyclingExtractMetaDesc(rawHTML) + if desc == "" && prod != nil { + desc = prod.Description + } + slimHTML := wave3CyclingSlimHTMLForDOM(rawHTML, 512*1024) + doc := ParseHTMLDoc(slimHTML, 512*1024) + + title := wave3CyclingExtractTitle(doc, rawHTML) + if title == "" && prod != nil { + title = prod.Name + } + if title == "" { + return nil + } + + bodyText := "" + if doc != nil { + bodyText = doc.Text("main") + if bodyText == "" { + bodyText = doc.Text("body") + } + if len(bodyText) > 128*1024 { + bodyText = bodyText[:128*1024] + } + } + scanText := title + "\n" + desc + "\n" + bodyText + + ebikeClass := "" + if m := wave3CyclingRxEbikeClass.FindStringSubmatch(scanText); len(m) >= 2 { + ebikeClass = SanitizeSchemaPlainField(m[1], 32) + } + batteryWh := "" + if m := wave3CyclingRxBatteryWh.FindStringSubmatch(scanText); len(m) >= 2 { + batteryWh = m[1] + " Wh" + } + motor := "" + if m := wave3CyclingRxMotorWatts.FindStringSubmatch(scanText); len(m) >= 3 { + if m[2] != "" { + motor = SanitizeSchemaPlainField(m[2], 64) + } else if m[1] != "" { + motor = m[1] + "W" + } + } + torque := "" + if m := wave3CyclingRxTorqueNm.FindStringSubmatch(scanText); len(m) >= 2 { + torque = m[1] + " Nm" + } + + tables, _ := wave3CyclingExtractHTMLTables(doc, "table", 3, 25, 8) + var bullets []string + rec := map[string]any{"model": title} + if prod != nil && prod.Brand != "" { + bullets = append(bullets, "- **Brand**: "+prod.Brand) + rec["brand"] = prod.Brand + } + if ebikeClass != "" { + bullets = append(bullets, "- **E-Bike Class**: "+ebikeClass) + rec["ebikeClass"] = ebikeClass + } + if batteryWh != "" { + bullets = append(bullets, "- **Battery**: "+batteryWh) + rec["batteryWh"] = batteryWh + } + if motor != "" { + mStr := motor + if torque != "" { + mStr += " (" + torque + ")" + rec["torque"] = torque + } + bullets = append(bullets, "- **Motor**: "+mStr) + rec["motor"] = motor + } + if prod != nil && prod.Price != "" { + pStr := prod.Price + if prod.Currency != "" { + pStr = prod.Currency + " " + pStr + } + bullets = append(bullets, "- **Price**: "+pStr) + rec["price"] = prod.Price + if prod.Currency != "" { + rec["currency"] = prod.Currency + } + } + if prod != nil && prod.Availability != "" { + bullets = append(bullets, "- **Availability**: "+prod.Availability) + } + + var blocks []string + blocks = append(blocks, "# "+escapeDeclMarkdownBrackets(title)) + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + for idx, tbl := range tables { + heading := "## E-Bike Specifications" + if idx > 0 { + heading = fmt.Sprintf("## Specifications Table %d", idx+1) + } + blocks = append(blocks, heading+"\n\n"+tbl) + } + + var links []string + seenLinks := make(map[string]bool) + if prod != nil && prod.URL != "" { + wave3CyclingAddLink(&links, seenLinks, prod.URL, baseURL) + rec["url"] = prod.URL + } + prose, pLinks := wave3CyclingExtractBodyProse(doc, baseURL) + if len(tables) == 0 && len(bullets) <= 1 && prose == "" && desc == "" { + return nil + } + for _, l := range pLinks { + wave3CyclingAddLink(&links, seenLinks, l, baseURL) + } + var overviewParts []string + if desc != "" { + overviewParts = append(overviewParts, desc) + } + if prose != "" && (desc == "" || !strings.Contains(prose, desc)) { + overviewParts = append(overviewParts, prose) + } + if len(overviewParts) > 0 { + blocks = append(blocks, "## Overview\n\n"+strings.Join(overviewParts, "\n\n")) + } + + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: []map[string]any{rec}, + } +} + +// ── #352 Frame & Touring Bike Brands ──────────────────────────────────────────────────────────── + +func wave3CyclingExtractQBPFrameHTML(rawHTML, probeLower, baseURL, urlLower, extractorID string) *DeclarativePostFetchResult { + // Handle retiredbrandresources.com minimal retirement notice cleanly as non-active when no geometry/product specs exist. + isRetiredBrandNotice := strings.Contains(urlLower, "retiredbrandresources") || strings.Contains(probeLower, "retiredbrandresources") + doc := ParseHTMLDoc(rawHTML, wave3CyclingMaxHTMLBytes) + nodes := wave3CyclingExtractJSONLDNodes(rawHTML) + prod := wave3CyclingExtractProductJSONLD(nodes, baseURL) + tables, parsedTables := wave3CyclingExtractHTMLTables(doc, "table", 4, 25, 10) + + if isRetiredBrandNotice && len(tables) == 0 && prod == nil { + return nil + } + + title := wave3CyclingExtractTitle(doc, rawHTML) + if title == "" && prod != nil { + title = prod.Name + } + if title == "" { + return nil + } + desc := wave3CyclingExtractMetaDesc(rawHTML) + if desc == "" && prod != nil { + desc = prod.Description + } + + var bullets []string + rec := map[string]any{"model": title} + if prod != nil && prod.Brand != "" { + bullets = append(bullets, "- **Brand**: "+prod.Brand) + rec["brand"] = prod.Brand + } + if prod != nil && prod.SKU != "" { + bullets = append(bullets, "- **SKU**: `"+prod.SKU+"`") + rec["sku"] = prod.SKU + } + if prod != nil && prod.Price != "" { + pStr := prod.Price + if prod.Currency != "" { + pStr = prod.Currency + " " + pStr + } + bullets = append(bullets, "- **Price**: "+pStr) + rec["price"] = prod.Price + } + + var blocks []string + blocks = append(blocks, "# "+escapeDeclMarkdownBrackets(title)) + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + + var recs []map[string]any + recs = append(recs, rec) + for idx, tbl := range tables { + heading := "## Frame & Geometry Specifications" + if idx > 0 { + heading = fmt.Sprintf("## Specifications Table %d", idx+1) + } + blocks = append(blocks, heading+"\n\n"+tbl) + if idx < len(parsedTables) && len(parsedTables[idx]) >= 2 { + hdr := parsedTables[idx][0] + for _, r := range parsedTables[idx][1:] { + if len(recs) >= wave3CyclingMaxRecords { + break + } + rowRec := map[string]any{"metric": r[0]} + for c := 1; c < len(r) && c < len(hdr); c++ { + if r[c] != "" { + rowRec[hdr[c]] = r[c] + } + } + recs = append(recs, rowRec) + } + } + } + + var links []string + seenLinks := make(map[string]bool) + if prod != nil && prod.URL != "" { + wave3CyclingAddLink(&links, seenLinks, prod.URL, baseURL) + } + if len(tables) == 0 { + prose, pLinks := wave3CyclingExtractBodyProse(doc, baseURL) + if prose == "" && desc == "" && len(bullets) == 0 { + return nil + } + if prose != "" { + blocks = append(blocks, "## Frame Details\n\n"+prose) + } + for _, l := range pLinks { + wave3CyclingAddLink(&links, seenLinks, l, baseURL) + } + } else if desc != "" { + blocks = append(blocks, "## Frame Overview\n\n"+desc) + } + + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: recs, + } +} + +// ── #353 MTB Geometry Brands ──────────────────────────────────────────────────────────────────── + +func wave3CyclingScanNuxtGeomKVLinear(src string, kv map[string]string, rows *[][]string, seenKeys map[string]bool) { + if src == "" || len(*rows) >= 20 { + return + } + n := len(src) + pos := 0 + visits := 0 + for pos < n && len(*rows) < 20 && visits < 25000 { + rel := strings.IndexByte(src[pos:], ':') + if rel < 0 { + break + } + colon := pos + rel + pos = colon + 1 + visits++ + + // Scan backwards from colon for optional whitespace + optional quote + identifier + kEnd := colon - 1 + for kEnd >= 0 && (src[kEnd] == ' ' || src[kEnd] == '\t') { + kEnd-- + } + if kEnd < 0 { + continue + } + quoteChar := byte(0) + if src[kEnd] == '"' || src[kEnd] == '\'' { + quoteChar = src[kEnd] + kEnd-- + } + kStart := kEnd + for kStart >= 0 && ((src[kStart] >= 'a' && src[kStart] <= 'z') || (src[kStart] >= 'A' && src[kStart] <= 'Z')) { + if kEnd-kStart >= 24 { + break + } + kStart-- + } + kStart++ + if kStart > kEnd { + continue + } + if quoteChar != 0 { + if kStart == 0 || src[kStart-1] != quoteChar { + continue + } + } else if kStart > 0 { + prev := src[kStart-1] + if prev != '{' && prev != ',' && prev != ' ' && prev != '\t' && prev != '\n' && prev != '\r' { + continue + } + } + + rawKey := src[kStart : kEnd+1] + lk := strings.ToLower(rawKey) + switch lk { + case "reach", "stack", "headtubeangle", "seattubeangle", "chainstay", "chainstaylength", "wheelbase", "bbdrop", "standover", "fronttravel", "reartravel": + default: + continue + } + + // Scan forward from colon+1 for optional whitespace + optional quote + numeric value + vStart := colon + 1 + for vStart < n && (src[vStart] == ' ' || src[vStart] == '\t') { + vStart++ + } + if vStart >= n { + continue + } + vQuote := byte(0) + if src[vStart] == '"' || src[vStart] == '\'' { + vQuote = src[vStart] + vStart++ + } + vEnd := vStart + seenDot := false + for vEnd < n && vEnd-vStart < 24 { + c := src[vEnd] + if c >= '0' && c <= '9' { + vEnd++ + continue + } + if c == '.' && !seenDot && vEnd > vStart { + seenDot = true + vEnd++ + continue + } + break + } + if vEnd == vStart || src[vEnd-1] == '.' { + continue + } + if vQuote != 0 { + if vEnd >= n || src[vEnd] != vQuote { + continue + } + } else if vEnd < n { + next := src[vEnd] + if next != ',' && next != '}' && next != ']' && next != ' ' && next != '\t' && next != '\n' && next != '\r' && next != ';' { + continue + } + } + + k := SanitizeSchemaPlainField(rawKey, 40) + v := SanitizeSchemaPlainField(src[vStart:vEnd], 32) + if k == "" || v == "" || seenKeys[lk] { + continue + } + seenKeys[lk] = true + kv[k] = v + *rows = append(*rows, []string{k, v}) + } +} + +func wave3CyclingExtractNuxtGeometry(rawHTML string) (map[string]string, [][]string) { + if indexFoldASCIIExtract(rawHTML, "__nuxt") < 0 { + return nil, nil + } + kv := make(map[string]string) + var rows [][]string + seenKeys := make(map[string]bool) + + // 1. Bounded linear scan of (no full-tree JSON unmarshal) + for _, needle := range []string{`id="__nuxt_data__"`, `id='__nuxt_data__'`} { + if idx := indexFoldASCIIExtract(rawHTML, needle); idx >= 0 { + gt := strings.IndexByte(rawHTML[idx:], '>') + if gt >= 0 { + bodyStart := idx + gt + 1 + maxSlice := bodyStart + 512*1024 + if maxSlice > len(rawHTML) { + maxSlice = len(rawHTML) + } + window := rawHTML[bodyStart:maxSlice] + if endRel := indexFoldASCIIExtract(window, "= 0 { + window = window[:endRel] + } + wave3CyclingScanNuxtGeomKVLinear(window, kv, &rows, seenKeys) + break + } + } + } + + // 2. Bounded linear scan of window.__NUXT__ literals + if len(rows) == 0 { + if idx := indexFoldASCIIExtract(rawHTML, "window.__nuxt__"); idx >= 0 { + maxSlice := idx + 256*1024 + if maxSlice > len(rawHTML) { + maxSlice = len(rawHTML) + } + window := rawHTML[idx:maxSlice] + if endRel := indexFoldASCIIExtract(window, "= 0 { + window = window[:endRel] + } + wave3CyclingScanNuxtGeomKVLinear(window, kv, &rows, seenKeys) + } + } + + return kv, rows +} + +func wave3CyclingExtractMTBGeometryHTML(rawHTML, probeLower, baseURL, urlLower, extractorID string) *DeclarativePostFetchResult { + nodes := wave3CyclingExtractJSONLDNodes(rawHTML) + prod := wave3CyclingExtractProductJSONLD(nodes, baseURL) + desc := wave3CyclingExtractMetaDesc(rawHTML) + if desc == "" && prod != nil { + desc = prod.Description + } + nuxtKV, nuxtRows := wave3CyclingExtractNuxtGeometry(rawHTML) + + slimHTML := wave3CyclingSlimHTMLForDOM(rawHTML, 512*1024) + doc := ParseHTMLDoc(slimHTML, 512*1024) + + title := wave3CyclingExtractTitle(doc, rawHTML) + if title == "" && prod != nil { + title = prod.Name + } + if title == "" { + return nil + } + + tables, parsedTables := wave3CyclingExtractHTMLTables(doc, "table", 4, 25, 10) + + var bullets []string + var recs []map[string]any + if prod != nil { + if prod.Brand != "" { + bullets = append(bullets, "- **Brand**: "+prod.Brand) + } + if prod.Price != "" { + pStr := prod.Price + if prod.Currency != "" { + pStr = prod.Currency + " " + pStr + } + bullets = append(bullets, "- **Price**: "+pStr) + } + } + if strings.Contains(urlLower, "yeticycles.com") || strings.Contains(probeLower, "__nuxt__") { + bullets = append(bullets, "- **Hydration Source**: Nuxt SSR") + } + + var blocks []string + blocks = append(blocks, "# "+escapeDeclMarkdownBrackets(title)) + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + + if len(nuxtRows) > 0 { + blocks = append(blocks, "## Hydration Geometry Specs\n\n"+formatDeclarativeGFMTable([]string{"Parameter", "Value"}, nuxtRows)) + rec := map[string]any{"model": title} + for k, v := range nuxtKV { + rec[k] = v + } + recs = append(recs, rec) + } + + for idx, tbl := range tables { + heading := "## Geometry & Build Kits" + if idx > 0 { + heading = fmt.Sprintf("## Build / Geometry Table %d", idx+1) + } + blocks = append(blocks, heading+"\n\n"+tbl) + if idx < len(parsedTables) && len(parsedTables[idx]) >= 2 { + hdr := parsedTables[idx][0] + for _, r := range parsedTables[idx][1:] { + if len(recs) >= wave3CyclingMaxRecords { + break + } + rowRec := map[string]any{"metric": r[0]} + for c := 1; c < len(r) && c < len(hdr); c++ { + if r[c] != "" { + rowRec[hdr[c]] = r[c] + } + } + recs = append(recs, rowRec) + } + } + } + + var links []string + seenLinks := make(map[string]bool) + if prod != nil && prod.URL != "" { + wave3CyclingAddLink(&links, seenLinks, prod.URL, baseURL) + } + if len(tables) == 0 && len(nuxtRows) == 0 { + prose, pLinks := wave3CyclingExtractBodyProse(doc, baseURL) + if prose == "" && desc == "" { + return nil + } + if prose != "" { + blocks = append(blocks, "## Build Kits & Overview\n\n"+prose) + } + for _, l := range pLinks { + wave3CyclingAddLink(&links, seenLinks, l, baseURL) + } + } else if desc != "" { + blocks = append(blocks, "## Overview\n\n"+desc) + } + + if len(recs) == 0 { + rec := map[string]any{"model": title} + if prod != nil && prod.Price != "" { + rec["price"] = prod.Price + } + recs = append(recs, rec) + } + + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: recs, + } +} + +// ── #354 Geometry Geeks & 99 Spokes (REAL adapter, NEVER detect-only) ─────────────────────────── + +func wave3CyclingExtractGeometryGeeks99SpokesHTML(rawHTML, probeLower, baseURL, urlLower, extractorID string) *DeclarativePostFetchResult { + doc := ParseHTMLDoc(rawHTML, wave3CyclingMaxHTMLBytes) + nodes := wave3CyclingExtractJSONLDNodes(rawHTML) + prod := wave3CyclingExtractProductJSONLD(nodes, baseURL) + + // 1. Check 99spokes __NEXT_DATA__ hydration JSON if present. + nextObj := wave3CyclingExtractNextDataObj(rawHTML) + var nextBike map[string]any + if nextObj != nil { + if pp := wave3CyclingNestedMap(nextObj, "props", "pageProps"); pp != nil { + if b, ok := pp["bike"].(map[string]any); ok { + nextBike = b + } else if pp["geometry"] != nil || pp["specs"] != nil || pp["sizes"] != nil { + nextBike = pp + } + } + } + + title := wave3CyclingExtractTitle(doc, rawHTML) + if title == "" && nextBike != nil { + title = wave3CyclingFirstNonEmpty( + wave3CyclingPlain(nextBike["name"], 200), + wave3CyclingPlain(nextBike["model"], 200), + ) + } + if title == "" && prod != nil { + title = prod.Name + } + if title == "" { + return nil + } + desc := wave3CyclingExtractMetaDesc(rawHTML) + if desc == "" && prod != nil { + desc = prod.Description + } + + var blocks []string + var recs []map[string]any + var links []string + seenLinks := make(map[string]bool) + blocks = append(blocks, "# "+escapeDeclMarkdownBrackets(title)) + + var bullets []string + if prod != nil && prod.Brand != "" { + bullets = append(bullets, "- **Brand**: "+prod.Brand) + } + if nextBike != nil { + if maker := wave3CyclingPlain(nextBike["maker"], 80); maker != "" { + bullets = append(bullets, "- **Maker**: "+maker) + } + if yr := wave3CyclingPlain(nextBike["year"], 16); yr != "" { + bullets = append(bullets, "- **Model Year**: "+yr) + } + if cat := wave3CyclingPlain(nextBike["category"], 64); cat != "" { + bullets = append(bullets, "- **Category**: "+cat) + } + if price := wave3CyclingParsePrice(wave3CyclingStringVal(nextBike["msrp"])); price != "" { + bullets = append(bullets, "- **MSRP**: $"+price) + } + } else if prod != nil && prod.Price != "" { + pStr := prod.Price + if prod.Currency != "" { + pStr = prod.Currency + " " + pStr + } + bullets = append(bullets, "- **MSRP / Price**: "+pStr) + } + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + + // 2. GeometryGeeks `table.bike-geometry-table` or generic HTML geometry tables. + tableSelector := "table.bike-geometry-table, table" + if strings.Contains(probeLower, "bike-geometry-table") { + tableSelector = "table.bike-geometry-table" + } + tables, parsedTables := wave3CyclingExtractHTMLTables(doc, tableSelector, 3, 30, 12) + for idx, tbl := range tables { + heading := "## Geometry Table" + if idx > 0 { + heading = fmt.Sprintf("## Component & Geometry Table %d", idx+1) + } + blocks = append(blocks, heading+"\n\n"+tbl) + if idx < len(parsedTables) && len(parsedTables[idx]) >= 2 { + hdr := parsedTables[idx][0] + for _, r := range parsedTables[idx][1:] { + if len(recs) >= wave3CyclingMaxRecords { + break + } + rowRec := map[string]any{"metric": r[0]} + for c := 1; c < len(r) && c < len(hdr); c++ { + if r[c] != "" { + rowRec[hdr[c]] = r[c] + } + } + recs = append(recs, rowRec) + } + } + } + + // 3. 99spokes __NEXT_DATA__ geometry & component specs. + if nextBike != nil { + if sizesArr, ok := nextBike["sizes"].([]any); ok && len(sizesArr) > 0 { + var geoRows [][]string + for i, rawSz := range sizesArr { + if i >= wave3CyclingMaxRecords { + break + } + sm, okSM := rawSz.(map[string]any) + if !okSM { + continue + } + szName := wave3CyclingFirstNonEmpty(wave3CyclingPlain(sm["name"], 32), wave3CyclingPlain(sm["size"], 32), "-") + reach := wave3CyclingFirstNonEmpty(wave3CyclingPlain(sm["reach"], 24), "-") + stack := wave3CyclingFirstNonEmpty(wave3CyclingPlain(sm["stack"], 24), "-") + hta := wave3CyclingFirstNonEmpty(wave3CyclingPlain(sm["headTubeAngle"], 24), wave3CyclingPlain(sm["hta"], 24), "-") + sta := wave3CyclingFirstNonEmpty(wave3CyclingPlain(sm["seatTubeAngle"], 24), wave3CyclingPlain(sm["sta"], 24), "-") + cs := wave3CyclingFirstNonEmpty(wave3CyclingPlain(sm["chainstayLength"], 24), wave3CyclingPlain(sm["chainstay"], 24), "-") + wb := wave3CyclingFirstNonEmpty(wave3CyclingPlain(sm["wheelbase"], 24), "-") + geoRows = append(geoRows, []string{szName, reach, stack, hta, sta, cs, wb}) + recs = append(recs, map[string]any{ + "size": szName, + "reach": reach, + "stack": stack, + "headTubeAngle": hta, + "seatTubeAngle": sta, + "chainstay": cs, + "wheelbase": wb, + }) + } + if len(geoRows) > 0 { + blocks = append(blocks, "## Geometry by Size\n\n"+formatDeclarativeGFMTable( + []string{"Size", "Reach", "Stack", "HTA", "STA", "Chainstay", "Wheelbase"}, + geoRows, + )) + } + } + if comps, ok := nextBike["components"].(map[string]any); ok && len(comps) > 0 { + var compRows [][]string + for k, v := range comps { + if len(compRows) >= 20 { + break + } + sv := "" + switch tv := v.(type) { + case map[string]any: + sv = wave3CyclingFirstNonEmpty(wave3CyclingPlain(tv["description"], 120), wave3CyclingPlain(tv["model"], 120), wave3CyclingPlain(tv["name"], 120)) + default: + sv = wave3CyclingPlain(tv, 120) + } + if sv != "" { + compRows = append(compRows, []string{SanitizeSchemaPlainField(k, 48), sv}) + } + } + if len(compRows) > 0 { + blocks = append(blocks, "## Components\n\n"+formatDeclarativeGFMTable([]string{"Component", "Specification"}, compRows)) + } + } + } + + if len(tables) == 0 && len(recs) == 0 { + // Must have real geometry/component content; reject bare non-bike shells. + prose, pLinks := wave3CyclingExtractBodyProse(doc, baseURL) + if prose == "" && desc == "" { + return nil + } + if strings.Contains(urlLower, "99spokes.com") && prose == "" { + return nil + } + if prose != "" { + blocks = append(blocks, "## Specifications\n\n"+prose) + } + for _, l := range pLinks { + wave3CyclingAddLink(&links, seenLinks, l, baseURL) + } + } + if prod != nil && prod.URL != "" { + wave3CyclingAddLink(&links, seenLinks, prod.URL, baseURL) + } + if len(recs) == 0 { + recs = append(recs, map[string]any{"bike": title}) + } + + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: recs, + } +} + +// ── #355 Sheldon Brown Technical Reference ────────────────────────────────────────────────────── + +func wave3CyclingExtractSheldonBrownHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + doc := ParseHTMLDoc(rawHTML, wave3CyclingStdHTMLMaxBytes) + title := wave3CyclingExtractTitle(doc, rawHTML) + if title == "" { + return nil + } + desc := wave3CyclingExtractMetaDesc(rawHTML) + tables, parsedTables := wave3CyclingExtractHTMLTables(doc, "table", 3, 25, 8) + dlMap := map[string]string{} + if doc != nil { + dlMap = doc.DLMap("dl") + } + + var blocks []string + var recs []map[string]any + blocks = append(blocks, "# "+escapeDeclMarkdownBrackets(title)) + if desc != "" { + blocks = append(blocks, "> "+desc) + } + + if len(dlMap) > 0 { + var glossRows [][]string + for term, defn := range dlMap { + if len(glossRows) >= wave3CyclingMaxRecords { + break + } + ct := SanitizeSchemaPlainField(term, 80) + cd := SanitizeSchemaPlainField(defn, 220) + if ct != "" && cd != "" { + glossRows = append(glossRows, []string{ct, cd}) + recs = append(recs, map[string]any{"term": ct, "definition": cd}) + } + } + if len(glossRows) > 0 { + blocks = append(blocks, "## Glossary & Definitions\n\n"+formatDeclarativeGFMTable([]string{"Term", "Definition"}, glossRows)) + } + } + + for idx, tbl := range tables { + heading := "## Reference & Crib Table" + if idx > 0 { + heading = fmt.Sprintf("## Technical Table %d", idx+1) + } + blocks = append(blocks, heading+"\n\n"+tbl) + if idx < len(parsedTables) && len(parsedTables[idx]) >= 2 && len(recs) < wave3CyclingMaxRecords { + hdr := parsedTables[idx][0] + for _, r := range parsedTables[idx][1:] { + if len(recs) >= wave3CyclingMaxRecords { + break + } + rowRec := map[string]any{} + for c := 0; c < len(r) && c < len(hdr); c++ { + if r[c] != "" { + rowRec[hdr[c]] = r[c] + } + } + if len(rowRec) > 0 { + recs = append(recs, rowRec) + } + } + } + } + + prose, links := wave3CyclingExtractBodyProse(doc, baseURL) + if prose != "" { + blocks = append(blocks, "## Technical Article\n\n"+prose) + } else if len(tables) == 0 && len(dlMap) == 0 { + return nil + } + + if len(recs) == 0 { + recs = append(recs, map[string]any{"title": title}) + } + + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Author: "Sheldon Brown", + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: recs, + } +} + +// ── #356 UL Product iQ / UL iQ ────────────────────────────────────────────────────────────────── + +func wave3CyclingExtractULProductIQHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + doc := ParseHTMLDoc(rawHTML, wave3CyclingStdHTMLMaxBytes) + title := wave3CyclingExtractTitle(doc, rawHTML) + if title == "" { + return nil + } + desc := wave3CyclingExtractMetaDesc(rawHTML) + + bodyText := "" + if doc != nil { + bodyText = doc.Text("body") + } + scanText := title + "\n" + desc + "\n" + bodyText + + var standards []string + seenStd := make(map[string]bool) + for _, m := range wave3CyclingRxULStandard.FindAllStringSubmatch(scanText, 12) { + if len(m) >= 2 { + stdName := strings.ToUpper(wave3CyclingCleanText(m[1])) + if stdName != "" && !seenStd[stdName] { + seenStd[stdName] = true + standards = append(standards, stdName) + } + } + } + + var fileNums []string + seenFile := make(map[string]bool) + for _, m := range wave3CyclingRxULFileNum.FindAllStringSubmatch(scanText, 12) { + if len(m) >= 2 && !seenFile[m[1]] { + seenFile[m[1]] = true + fileNums = append(fileNums, m[1]) + } + } + + ccn := "" + if m := wave3CyclingRxULCCN.FindStringSubmatch(scanText); len(m) >= 2 { + ccn = m[1] + } + + tables, parsedTables := wave3CyclingExtractHTMLTables(doc, "table", 3, 25, 8) + var dbNames []string + if doc != nil { + for _, inp := range doc.Select(`input[type="submit"], button`, 20) { + val := SanitizeSchemaPlainField(inp.AttrOrEmpty("value"), 80) + if val == "" { + val = SanitizeSchemaPlainField(inp.Text(), 80) + } + if val != "" && !strings.EqualFold(val, "Search") && !strings.EqualFold(val, "Submit") { + dbNames = append(dbNames, val) + } + } + } + + if len(standards) == 0 && len(fileNums) == 0 && len(tables) == 0 && len(dbNames) == 0 && strings.TrimSpace(bodyText) == "" { + return nil + } + + var bullets []string + rec := map[string]any{"title": title} + if len(standards) > 0 { + bullets = append(bullets, "- **UL Standards**: "+strings.Join(standards, ", ")) + rec["standards"] = standards + } + if len(fileNums) > 0 { + bullets = append(bullets, "- **UL File Numbers**: `"+strings.Join(fileNums, "`, `")+"`") + rec["fileNumbers"] = fileNums + } + if ccn != "" { + bullets = append(bullets, "- **Category Control Number (CCN)**: `"+ccn+"`") + rec["ccn"] = ccn + } + + var blocks []string + blocks = append(blocks, "# "+escapeDeclMarkdownBrackets(title)) + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + if len(dbNames) > 0 { + var dbRows [][]string + for _, d := range dbNames { + dbRows = append(dbRows, []string{d}) + } + blocks = append(blocks, "## UL iQ Certification Databases\n\n"+formatDeclarativeGFMTable([]string{"Database"}, dbRows)) + rec["databases"] = dbNames + } + for idx, tbl := range tables { + heading := "## Certification Listings" + if idx > 0 { + heading = fmt.Sprintf("## Certification Table %d", idx+1) + } + blocks = append(blocks, heading+"\n\n"+tbl) + } + + var recs []map[string]any + recs = append(recs, rec) + if len(parsedTables) > 0 && len(parsedTables[0]) >= 2 { + hdr := parsedTables[0][0] + for _, r := range parsedTables[0][1:] { + if len(recs) >= wave3CyclingMaxRecords { + break + } + rowRec := map[string]any{} + for c := 0; c < len(r) && c < len(hdr); c++ { + if r[c] != "" { + rowRec[hdr[c]] = r[c] + } + } + if len(rowRec) > 0 { + recs = append(recs, rowRec) + } + } + } + + prose, links := wave3CyclingExtractBodyProse(doc, baseURL) + if prose != "" && len(tables) == 0 && len(dbNames) == 0 { + blocks = append(blocks, "## Details\n\n"+prose) + } + + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: recs, + } +} + +// ── #357 E-Bike State Laws & Legislative Citations ────────────────────────────────────────────── + +func wave3CyclingStateSlug(stateName string) string { + switch strings.ToLower(strings.TrimSpace(stateName)) { + case "alabama": + return "AL" + case "alaska": + return "AK" + case "arizona": + return "AZ" + case "arkansas": + return "AR" + case "california": + return "CA" + case "colorado": + return "CO" + case "connecticut": + return "CT" + case "delaware": + return "DE" + case "florida": + return "FL" + case "georgia": + return "GA" + case "hawaii": + return "HI" + case "idaho": + return "ID" + case "illinois": + return "IL" + case "indiana": + return "IN" + case "iowa": + return "IA" + case "kansas": + return "KS" + case "kentucky": + return "KY" + case "louisiana": + return "LA" + case "maine": + return "ME" + case "maryland": + return "MD" + case "massachusetts": + return "MA" + case "michigan": + return "MI" + case "minnesota": + return "MN" + case "mississippi": + return "MS" + case "missouri": + return "MO" + case "montana": + return "MT" + case "nebraska": + return "NE" + case "nevada": + return "NV" + case "new hampshire": + return "NH" + case "new jersey": + return "NJ" + case "new mexico": + return "NM" + case "new york": + return "NY" + case "north carolina": + return "NC" + case "north dakota": + return "ND" + case "ohio": + return "OH" + case "oklahoma": + return "OK" + case "oregon": + return "OR" + case "pennsylvania": + return "PA" + case "rhode island": + return "RI" + case "south carolina": + return "SC" + case "south dakota": + return "SD" + case "tennessee": + return "TN" + case "texas": + return "TX" + case "utah": + return "UT" + case "vermont": + return "VT" + case "virginia": + return "VA" + case "washington": + return "WA" + case "west virginia": + return "WV" + case "wisconsin": + return "WI" + case "wyoming": + return "WY" + default: + return "" + } +} + +func wave3CyclingExtractEBikeStateLawsHTML(rawHTML, baseURL, urlLower, extractorID string) *DeclarativePostFetchResult { + desc := wave3CyclingExtractMetaDesc(rawHTML) + slimHTML := wave3CyclingSlimHTMLForDOM(rawHTML, 512*1024) + doc := ParseHTMLDoc(slimHTML, 512*1024) + title := wave3CyclingExtractTitle(doc, rawHTML) + if title == "" { + return nil + } + prose, pLinks := wave3CyclingExtractBodyProse(doc, baseURL) + tables, _ := wave3CyclingExtractHTMLTables(doc, "table", 3, 25, 8) + if prose == "" && len(tables) == 0 && desc == "" { + return nil + } + + scanText := title + "\n" + desc + "\n" + prose + stateName := "" + switch { + case strings.Contains(urlLower, "revisor.mn.gov"): + stateName = "Minnesota" + case strings.Contains(urlLower, "app.leg.wa.gov"): + stateName = "Washington" + case strings.Contains(urlLower, "content.leg.colorado.gov") || strings.Contains(urlLower, "leg.colorado.gov"): + stateName = "Colorado" + default: + if m := wave3CyclingRxStateName.FindStringSubmatch(title + "\n" + desc); len(m) >= 2 { + stateName = m[1] + } + } + + var citations []string + seenCite := make(map[string]bool) + for _, m := range wave3CyclingRxStatuteCite.FindAllStringSubmatch(scanText, 10) { + if len(m) >= 2 { + c := SanitizeSchemaPlainField(m[1], 80) + if c != "" && !seenCite[c] { + seenCite[c] = true + citations = append(citations, c) + } + } + } + + var classes []string + seenClass := make(map[string]bool) + for _, m := range wave3CyclingRxEbikeClass.FindAllStringSubmatch(scanText, 6) { + if len(m) >= 2 { + cl := SanitizeSchemaPlainField(m[1], 24) + if cl != "" && !seenClass[strings.ToLower(cl)] { + seenClass[strings.ToLower(cl)] = true + classes = append(classes, cl) + } + } + } + + cornellRef := "https://www.law.cornell.edu/cfr/text/16/part-1512" + legiscanRef := "https://legiscan.com/" + if code := wave3CyclingStateSlug(stateName); code != "" { + legiscanRef = "https://legiscan.com/" + code + "/legislation" + } + + var bullets []string + rec := map[string]any{"title": title} + if stateName != "" { + bullets = append(bullets, "- **Jurisdiction**: "+stateName) + rec["jurisdiction"] = stateName + } + if len(citations) > 0 { + bullets = append(bullets, "- **Statute Citations**: `"+strings.Join(citations, "`, `")+"`") + rec["citations"] = citations + } + if len(classes) > 0 { + bullets = append(bullets, "- **E-Bike Classes Referenced**: "+strings.Join(classes, ", ")) + rec["ebikeClasses"] = classes + } + bullets = append(bullets, + fmt.Sprintf("- **Federal & Statutory Cross-References**: [Cornell LII 16 CFR Part 1512](%s) · [LegiScan State Legislation](%s)", cornellRef, legiscanRef), + ) + + var blocks []string + blocks = append(blocks, "# "+escapeDeclMarkdownBrackets(title)) + blocks = append(blocks, strings.Join(bullets, "\n")) + for idx, tbl := range tables { + heading := "## State Statute & Legislative Table" + if idx > 0 { + heading = fmt.Sprintf("## Legislative Table %d", idx+1) + } + blocks = append(blocks, heading+"\n\n"+tbl) + } + if prose != "" { + blocks = append(blocks, "## Statutory & Legislative Text\n\n"+prose) + } + + var links []string + seenLinks := make(map[string]bool) + wave3CyclingAddLink(&links, seenLinks, cornellRef, baseURL) + wave3CyclingAddLink(&links, seenLinks, legiscanRef, baseURL) + for _, l := range pLinks { + wave3CyclingAddLink(&links, seenLinks, l, baseURL) + } + + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: []map[string]any{rec}, + } +} + +// ── #358 CPSC SaferProducts E-Bike & Micromobility Incidents ──────────────────────────────────── + +func wave3CyclingJoinSubField(arrAny any, field string, limit int) string { + arr, ok := arrAny.([]any) + if !ok || len(arr) == 0 { + return "" + } + var vals []string + seen := make(map[string]bool) + for _, item := range arr { + if len(vals) >= limit { + break + } + m, okM := item.(map[string]any) + if !okM { + continue + } + s := wave3CyclingPlain(m[field], 160) + if s != "" && !seen[s] { + seen[s] = true + vals = append(vals, s) + } + } + return strings.Join(vals, "; ") +} + +func wave3CyclingFormatCPSCIncidentsJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + items, ok := parsed.([]any) + if !ok { + // Reject error objects like {"Message":"No HTTP resource was found..."}. + return nil, false + } + if len(items) == 0 { + return nil, false + } + + var recs []map[string]any + var rows [][]string + var links []string + seenLinks := make(map[string]bool) + + for _, rawItem := range items { + if len(recs) >= wave3CyclingMaxRecords { + break + } + it, okIt := rawItem.(map[string]any) + if !okIt { + continue + } + recallNum := wave3CyclingPlain(it["RecallNumber"], 32) + recallID := wave3CyclingPlain(it["RecallID"], 32) + title := wave3CyclingPlain(it["Title"], 200) + if recallNum == "" && recallID == "" && title == "" { + continue + } + recallDate := wave3CyclingNormalizeISODate(wave3CyclingStringVal(it["RecallDate"])) + if recallDate == "" { + recallDate = wave3CyclingNormalizeISODate(wave3CyclingStringVal(it["LastPublishDate"])) + } + itemURL := SanitizeSchemaHTTPSURL(wave3CyclingStringVal(it["URL"]), origURL) + hazards := wave3CyclingJoinSubField(it["Hazards"], "Name", 4) + injuries := wave3CyclingJoinSubField(it["Injuries"], "Name", 4) + products := wave3CyclingJoinSubField(it["Products"], "Name", 4) + mfrs := wave3CyclingJoinSubField(it["Manufacturers"], "Name", 4) + desc := wave3CyclingPlain(it["Description"], 320) + + idCell := wave3CyclingFirstNonEmpty(recallNum, recallID, "-") + titleCell := escapeDeclMarkdownBrackets(wave3CyclingFirstNonEmpty(title, products, idCell)) + if itemURL != "" { + titleCell = fmt.Sprintf("[%s](%s)", titleCell, itemURL) + wave3CyclingAddLink(&links, seenLinks, itemURL, origURL) + } + hazardCell := escapeDeclMarkdownBrackets(wave3CyclingFirstNonEmpty(hazards, injuries, desc, "-")) + dateCell := wave3CyclingFirstNonEmpty(recallDate, "-") + mfrCell := escapeDeclMarkdownBrackets(wave3CyclingFirstNonEmpty(mfrs, "-")) + + rows = append(rows, []string{idCell, titleCell, dateCell, mfrCell, hazardCell}) + + rec := map[string]any{ + "recallId": recallID, + "recallNumber": recallNum, + "title": title, + "recallDate": recallDate, + } + if itemURL != "" { + rec["url"] = itemURL + } + if products != "" { + rec["products"] = products + } + if hazards != "" { + rec["hazards"] = hazards + } + if injuries != "" { + rec["injuries"] = injuries + } + if mfrs != "" { + rec["manufacturers"] = mfrs + } + recs = append(recs, rec) + } + + if len(recs) == 0 { + return nil, false + } + + docTitle := fmt.Sprintf("CPSC SaferProducts Micromobility & E-Bike Reports (%d of %d)", len(recs), len(items)) + var blocks []string + blocks = append(blocks, "# "+docTitle) + blocks = append(blocks, formatDeclarativeGFMTable( + []string{"Recall #", "Report / Product", "Date", "Manufacturer", "Hazards / Summary"}, + rows, + )) + + doc := &DeclarativeFormattedDoc{ + Title: docTitle, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: recs, + Total: wave3CyclingIntPtr(len(items)), + Returned: wave3CyclingIntPtr(len(recs)), + } + if len(items) > len(recs) { + doc.Truncated = wave3CyclingBoolPtr(true) + doc.NextCursor = strconv.Itoa(len(recs)) + } + return doc, true +} + +func wave3CyclingExtractCPSCPublicSearchHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + doc := ParseHTMLDoc(rawHTML, wave3CyclingStdHTMLMaxBytes) + title := wave3CyclingExtractTitle(doc, rawHTML) + if title == "" { + return nil + } + desc := wave3CyclingExtractMetaDesc(rawHTML) + + tables, parsedTables := wave3CyclingExtractHTMLTables(doc, "table", 2, 25, 8) + var recs []map[string]any + var blocks []string + blocks = append(blocks, "# "+escapeDeclMarkdownBrackets(title)) + + for idx, tbl := range tables { + heading := "## SaferProducts Incident Results" + if idx > 0 { + heading = fmt.Sprintf("## SaferProducts Table %d", idx+1) + } + blocks = append(blocks, heading+"\n\n"+tbl) + if idx < len(parsedTables) && len(parsedTables[idx]) >= 2 { + hdr := parsedTables[idx][0] + for _, r := range parsedTables[idx][1:] { + if len(recs) >= wave3CyclingMaxRecords { + break + } + rowRec := map[string]any{} + for c := 0; c < len(r) && c < len(hdr); c++ { + if r[c] != "" { + rowRec[hdr[c]] = r[c] + } + } + if len(rowRec) > 0 { + recs = append(recs, rowRec) + } + } + } + } + + // Reject unhydrated PublicSearch shells that contain only the search form & spinner without result rows/cards. + if len(tables) == 0 { + if doc != nil { + reportItems := doc.Select(".search-result-item, .incident-report, .report-detail, article", 25) + var cardRows [][]string + for _, it := range reportItems { + txt := SanitizeSchemaPlainField(it.Text(), 220) + if txt != "" { + cardRows = append(cardRows, []string{txt}) + recs = append(recs, map[string]any{"summary": txt}) + } + } + if len(cardRows) > 0 { + blocks = append(blocks, "## Incident Reports\n\n"+formatDeclarativeGFMTable([]string{"Report"}, cardRows)) + } + } + if len(recs) == 0 { + return nil + } + } + + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: strings.Join(blocks, "\n\n"), + Links: nil, + Records: recs, + } +} diff --git a/internal/extract/wave3_cycling_oems_test.go b/internal/extract/wave3_cycling_oems_test.go new file mode 100644 index 0000000..2ff73cd --- /dev/null +++ b/internal/extract/wave3_cycling_oems_test.go @@ -0,0 +1,498 @@ +package extract + +import ( + "encoding/json" + "net/url" + "os" + "path/filepath" + "strconv" + "strings" + "testing" + "time" + + "github.com/bartrumb/edgefetch/v2/internal/classify" +) + +func wave3CyclingResolveManifest(t *testing.T, m *DeclarativeAdapterManifest, rawURL string) (*DeclarativeTwinMatch, bool) { + t.Helper() + u, err := url.Parse(rawURL) + if err != nil { + t.Fatalf("url.Parse(%q): %v", rawURL, err) + } + host := strings.TrimSuffix(strings.ToLower(u.Hostname()), ".") + rawParts := splitNonEmptyEscapedSegments(u.EscapedPath()) + return resolveManifestTwinOnParsedURL(m, u, host, rawParts, DeclarativeResolveOptions{}) +} + +func TestWave3CyclingOEMsManifestsAndDisjointness(t *testing.T) { + catO2IDs := []struct { + id string + category string + authMode string + }{ + {"cargo-ebike-oems", "commerce-social", "html"}, + {"us-ebike-oems", "commerce-social", "html"}, + {"qbp-frame-brands", "commerce-social", "html"}, + {"mtb-geometry-brands", "commerce-social", "html"}, + {"geometrygeeks-99spokes", "commerce-social", "html"}, + {"sheldon-brown", "research-health", "html"}, + {"ul-product-iq", "public-records", "html"}, + {"e-bike-state-laws", "public-records", "html"}, + {"cpsc-ebike-incidents", "public-records", "pub"}, + } + + byID := make(map[string]*DeclarativeAdapterManifest) + claimed := make(map[string]string) + for _, spec := range catO2IDs { + raw, err := os.ReadFile(filepath.Join("manifests", spec.id+".yaml")) + if err != nil { + t.Fatalf("read %s.yaml: %v", spec.id, err) + } + m, err := ParseDeclarativeYAMLManifest(raw) + if err != nil { + t.Fatalf("ParseDeclarativeYAMLManifest(%s.yaml): %v", spec.id, err) + } + if m.ID != spec.id { + t.Fatalf("%s.yaml id mismatch: got %q", spec.id, m.ID) + } + if m.Category != spec.category { + t.Fatalf("%s.yaml category=%q, want %q", spec.id, m.Category, spec.category) + } + if m.AuthMode != spec.authMode || m.AuthMode == "detect-only" || m.DetectOnly != nil { + t.Fatalf("%s.yaml invalid authMode=%q detectOnly=%v", spec.id, m.AuthMode, m.DetectOnly) + } + for _, d := range m.Domains { + ld := strings.ToLower(strings.TrimSpace(d)) + if prev, exists := claimed[ld]; exists { + t.Fatalf("duplicate domain %q across %s and %s", ld, prev, spec.id) + } + claimed[ld] = spec.id + } + for _, hr := range m.HTMLRoutes { + for _, b := range hr.Bullets { + if strings.ContainsAny(b.Label, "{}") { + t.Fatalf("%s.yaml bullet label contains {}: %q", spec.id, b.Label) + } + } + } + byID[spec.id] = m + } + + // #356 must NEVER claim ul.com / www.ul.com (owned by cpsc-ebike-battery.yaml). + for _, d := range byID["ul-product-iq"].Domains { + ld := strings.ToLower(strings.TrimSpace(d)) + if ld == "ul.com" || ld == "www.ul.com" { + t.Fatalf("ul-product-iq must not claim %q", ld) + } + } + + // Verify strict disjointness of #350-#357 against existing cycling & law manifests. + for _, existingID := range []string{"ebike-state-laws", "cpsc-ebike-battery", "cornell-lii", "state-legislatures", "specialized", "bike-index"} { + raw, err := os.ReadFile(filepath.Join("manifests", existingID+".yaml")) + if err != nil { + t.Fatalf("read %s.yaml: %v", existingID, err) + } + em, err := ParseDeclarativeYAMLManifest(raw) + if err != nil { + t.Fatalf("ParseDeclarativeYAMLManifest(%s.yaml): %v", existingID, err) + } + for _, d := range em.Domains { + ld := strings.ToLower(strings.TrimSpace(d)) + if owner, ok := claimed[ld]; ok { + t.Fatalf("Cat O2 %s overlaps existing %s domain %q", owner, existingID, ld) + } + } + } + + // #358 cpsc-ebike-incidents path/query-disjointness with cpsc-recalls.yaml. + rawRecalls, err := os.ReadFile(filepath.Join("manifests", "cpsc-recalls.yaml")) + if err != nil { + t.Fatalf("read cpsc-recalls.yaml: %v", err) + } + recallsM, err := ParseDeclarativeYAMLManifest(rawRecalls) + if err != nil { + t.Fatalf("parse cpsc-recalls.yaml: %v", err) + } + incM := byID["cpsc-ebike-incidents"] + + if tm, ok := wave3CyclingResolveManifest(t, incM, "https://www.saferproducts.gov/RestWebServices/Recall?format=json&ProductType=Bicycle"); !ok || tm.EffectiveMaxBytes() != 2097152 || tm.route.Extract.JSONMode != "cpsc_ebike_incidents_json" { + t.Fatalf("cpsc-ebike-incidents ProductType route failed: ok=%v tm=%+v", ok, tm) + } + if tm, ok := wave3CyclingResolveManifest(t, incM, "https://www.saferproducts.gov/RestWebServices/Recall?ProductDescription=ebike"); !ok || tm.FetchURL != "https://www.saferproducts.gov/RestWebServices/Recall?format=json&ProductDescription=ebike" { + t.Fatalf("cpsc-ebike-incidents ProductDescription route failed: ok=%v tm=%+v", ok, tm) + } + // RecallNumber must NOT match cpsc-ebike-incidents and MUST match cpsc-recalls. + if tm, ok := wave3CyclingResolveManifest(t, incM, "https://www.saferproducts.gov/RestWebServices/Recall?format=json&RecallNumber=24123"); ok || tm != nil { + t.Fatalf("cpsc-ebike-incidents must NOT match RecallNumber queries: %+v", tm) + } + if tm, ok := wave3CyclingResolveManifest(t, recallsM, "https://www.saferproducts.gov/RestWebServices/Recall?format=json&RecallNumber=24123"); !ok || tm == nil { + t.Fatalf("cpsc-recalls must still match RecallNumber queries") + } + // Unfiltered Recall dump must match NEITHER. + if tm, ok := wave3CyclingResolveManifest(t, incM, "https://www.saferproducts.gov/RestWebServices/Recall?format=json"); ok || tm != nil { + t.Fatalf("cpsc-ebike-incidents must NOT match unfiltered Recall dump: %+v", tm) + } + if tm, ok := wave3CyclingResolveManifest(t, recallsM, "https://www.saferproducts.gov/RestWebServices/Recall?format=json"); ok || tm != nil { + t.Fatalf("cpsc-recalls must NOT match unfiltered Recall dump: %+v", tm) + } +} + +func TestWave3CyclingOEMsModesAndExtractors(t *testing.T) { + registerWave3CyclingOEMsHTMLModes() + RegisterWave3CyclingOEMsHTMLModes() + + expectedHTMLModes := []string{ + "cargo_ebike_oems_html", + "us_ebike_oems_html", + "qbp_frame_brands_html", + "mtb_geometry_brands_html", + "geometrygeeks_99spokes_html", + "sheldon_brown_html", + "ul_product_iq_html", + "e_bike_state_laws_html", + "cpsc_ebike_incidents_html", + } + for _, hm := range expectedHTMLModes { + if !IsWave3CyclingOEMsHTMLMode(hm) { + t.Fatalf("IsWave3CyclingOEMsHTMLMode(%q) = false", hm) + } + if getExternalHTMLModeLazy(hm) == nil { + t.Fatalf("RegisterExternalHTMLModeLazy missing %q", hm) + } + } + + // #353 Yeti __NUXT_DATA__ & window.__NUXT__ hydration extraction + yetiNuxt := `Yeti Cycles SB140 | 140mm All-Mountain Bike

C2 90 $5,000.00 SRAM 90

` + yRes := Wave3CyclingOEMsRunHTML("mtb_geometry_brands_html", yetiNuxt, "https://yeticycles.com/en-us/bikes/sb140", "mtb-geometry-brands") + if yRes == nil || !strings.Contains(yRes.Markdown, "480") || !strings.Contains(yRes.Markdown, "1239") { + t.Fatalf("Yeti __NUXT__ extraction failed: %+v", yRes) + } + + // #354 GeometryGeeks (skipping
`, + `
`, + `
`, + `
`, + ``, + ``, + ) && + !hasJSONLDScriptToken(probe) && + !strings.Contains(lower, "__nuxt_data__") && + !strings.Contains(lower, "= 0 { + s = stripTagsInlineLinear(s) + } + if strings.IndexByte(s, '&') >= 0 { + s = stdhtml.UnescapeString(s) + } + return strings.TrimSpace(wave3EduRxSpace.ReplaceAllString(s, " ")) +} + +func wave3EduFirstNonEmpty(vals ...string) string { + for _, v := range vals { + if t := strings.TrimSpace(v); t != "" { + return t + } + } + return "" +} + +func wave3EduPlain(v any, maxLen int) string { + return SanitizeSchemaPlainField(jsonScalarToString(v), maxLen) +} + +func wave3EduValidateISODate(raw string) string { + s := strings.TrimSpace(raw) + if m := wave3EduRxISODate.FindStringSubmatch(s); len(m) == 2 { + return m[1] + } + return "" +} + +func wave3EduValidateCurrency(raw string) string { + c := strings.ToUpper(strings.TrimSpace(raw)) + if wave3EduRxCurrency3.MatchString(c) { + return c + } + return "" +} + +func wave3EduValidatePrice(raw any) (string, bool) { + switch v := raw.(type) { + case json.Number: + if f, err := v.Float64(); err == nil && f >= 0 { + if f == 0 { + return "0", true + } + return strings.TrimRight(strings.TrimRight(fmt.Sprintf("%.2f", f), "0"), "."), true + } + case float64: + if v >= 0 { + if v == 0 { + return "0", true + } + return strings.TrimRight(strings.TrimRight(fmt.Sprintf("%.2f", v), "0"), "."), true + } + case int: + if v >= 0 { + return strconv.Itoa(v), true + } + case string: + s := strings.TrimSpace(strings.TrimPrefix(v, "$")) + s = strings.ReplaceAll(s, ",", "") + if s == "" { + return "", false + } + if f, err := strconv.ParseFloat(s, 64); err == nil && f >= 0 { + if f == 0 { + return "0", true + } + return strings.TrimRight(strings.TrimRight(fmt.Sprintf("%.2f", f), "0"), "."), true + } + } + return "", false +} + +func wave3EduResolveURL(rawRef, baseURL string) string { + ref := strings.TrimSpace(stdhtml.UnescapeString(rawRef)) + if ref == "" || strings.HasPrefix(ref, "#") || strings.HasPrefix(strings.ToLower(ref), "javascript:") || strings.HasPrefix(strings.ToLower(ref), "mailto:") { + return "" + } + u, err := url.Parse(ref) + if err != nil { + return "" + } + if u.IsAbs() { + if u.Scheme == "https" || u.Scheme == "http" { + return u.String() + } + return "" + } + if baseURL == "" { + return "" + } + b, err := url.Parse(baseURL) + if err != nil { + return "" + } + res := b.ResolveReference(u) + if res.Scheme == "https" || res.Scheme == "http" { + return res.String() + } + return "" +} + +func wave3EduExtractMeta(rawHTML, key string) string { + probe := rawHTML + if len(probe) > 65536 { + probe = probe[:65536] + } + target := strings.ToLower(key) + pos := 0 + for pos < len(probe) { + idx := indexFoldASCIIExtract(probe[pos:], "') + if end < 0 { + break + } + tag := probe[start : start+end+1] + pos = start + end + 1 + lowTag := asciiLowerExtractString(tag) + if !strings.Contains(lowTag, target) { + continue + } + nameVal := wave3EduExtractAttr(tag, "property") + if nameVal == "" { + nameVal = wave3EduExtractAttr(tag, "name") + } + if strings.EqualFold(nameVal, key) { + if content := wave3EduCleanText(wave3EduExtractAttr(tag, "content")); content != "" { + return content + } + } + } + return "" +} + +func wave3EduExtractAttr(tag, attrName string) string { + lowTag := asciiLowerExtractString(tag) + needle := strings.ToLower(attrName) + "=" + idx := strings.Index(lowTag, needle) + for idx > 0 { + prev := lowTag[idx-1] + if prev == ' ' || prev == '\t' || prev == '\n' || prev == '\r' { + break + } + nextIdx := strings.Index(lowTag[idx+len(needle):], needle) + if nextIdx < 0 { + idx = -1 + break + } + idx = idx + len(needle) + nextIdx + } + if idx < 0 { + return "" + } + rest := strings.TrimLeft(tag[idx+len(needle):], " \t\r\n") + if rest == "" { + return "" + } + quote := rest[0] + if quote == '"' || quote == '\'' { + rest = rest[1:] + if end := strings.IndexByte(rest, quote); end >= 0 { + return rest[:end] + } + return "" + } + end := strings.IndexAny(rest, " \t\r\n>") + if end >= 0 { + return rest[:end] + } + return rest +} + +func wave3EduExtractScriptByID(rawHTML, scriptID string) string { + pos := 0 + needle := strings.ToLower(scriptID) + for pos < len(rawHTML) { + idx := indexFoldASCIIExtract(rawHTML[pos:], "') + if gt < 0 { + return "" + } + openTag := rawHTML[start : start+gt+1] + pos = start + gt + 1 + if !strings.Contains(asciiLowerExtractString(openTag), needle) { + continue + } + if strings.EqualFold(wave3EduExtractAttr(openTag, "id"), scriptID) { + closeIdx := indexFoldASCIIExtract(rawHTML[pos:], " 400 { + pos = hit + len(needleLower) + continue + } + gt := strings.IndexByte(rawHTML[openStart:], '>') + if gt < 0 || openStart+gt < hit { + pos = hit + len(needleLower) + continue + } + depth := 1 + cur := openStart + gt + 1 + endPos := -1 + for cur < len(rawHTML) && cur-openStart < 32768 { + nextOpen := indexFoldASCIIExtract(rawHTML[cur:], "= 0 && nextOpen < nextClose { + depth++ + cur += nextOpen + 4 + } else { + depth-- + cur += nextClose + 6 + if depth == 0 { + endPos = cur + break + } + } + } + if endPos > openStart { + out = append(out, rawHTML[openStart:endPos]) + pos = endPos + } else { + pos = hit + len(needleLower) + } + } + return out +} + +type wave3EduTagMatch struct { + Tag string + OpenTag string + Inner string +} + +func wave3EduScanTags(htmlStr string, limit int) []wave3EduTagMatch { + var out []wave3EduTagMatch + pos := 0 + for pos < len(htmlStr) && len(out) < limit { + lt := strings.IndexByte(htmlStr[pos:], '<') + if lt < 0 { + break + } + start := pos + lt + if start+2 >= len(htmlStr) { + break + } + if htmlStr[start+1] == '/' || htmlStr[start+1] == '!' || htmlStr[start+1] == '?' { + gt := strings.IndexByte(htmlStr[start:], '>') + if gt < 0 { + break + } + pos = start + gt + 1 + continue + } + gt := strings.IndexByte(htmlStr[start:], '>') + if gt < 0 { + break + } + openTag := htmlStr[start : start+gt+1] + nameEnd := 1 + for nameEnd < len(openTag)-1 { + c := openTag[nameEnd] + if c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '/' || c == '>' { + break + } + nameEnd++ + } + tag := asciiLowerExtractString(openTag[1:nameEnd]) + pos = start + gt + 1 + if tag == "script" || tag == "style" || tag == "noscript" || tag == "svg" { + if closeIdx := indexFoldASCIIExtract(htmlStr[pos:], "= 0 { + if cgt := strings.IndexByte(htmlStr[pos+closeIdx:], '>'); cgt >= 0 { + pos = pos + closeIdx + cgt + 1 + continue + } + } + continue + } + switch tag { + case "h1", "h2", "h3", "p", "li", "tr", "td", "th", "article", "time": + closeTok := "= 0 && closeIdx <= 16384 { + out = append(out, wave3EduTagMatch{ + Tag: tag, + OpenTag: openTag, + Inner: htmlStr[pos : pos+closeIdx], + }) + if tag != "article" && tag != "tr" { + if cgt := strings.IndexByte(htmlStr[pos+closeIdx:], '>'); cgt >= 0 { + pos = pos + closeIdx + cgt + 1 + } + } + } + } + } + return out +} + +func wave3EduExtractBestHeadingAndPageTitle(rawHTML string) (string, string) { + probe := rawHTML + if len(probe) > 128*1024 { + probe = probe[:128*1024] + } + pageTitle := wave3EduCleanText(extractTitleLinearQuick(probe)) + ogTitle := wave3EduExtractMeta(probe, "og:title") + siteName := wave3EduExtractMeta(probe, "og:site_name") + + h1 := "" + matches := wave3EduScanTags(probe, 60) + for _, m := range matches { + if m.Tag == "h1" { + cand := wave3EduCleanText(m.Inner) + if cand != "" && !wave3EduRxGenericHead.MatchString(cand) && len(cand) <= 220 { + h1 = cand + break + } + } + } + + cleanedPage := pageTitle + if cleanedPage != "" { + parts := wave3EduRxTitleSep.Split(cleanedPage, 4) + for _, p := range parts { + cand := strings.TrimSpace(p) + if cand != "" && !wave3EduRxGenericHead.MatchString(cand) { + cleanedPage = cand + break + } + } + } + best := wave3EduFirstNonEmpty(h1, ogTitle, cleanedPage, pageTitle) + if wave3EduRxGenericHead.MatchString(best) && siteName != "" { + best = siteName + " — " + best + } + return best, siteName +} + +func wave3EduExtractDOMSnippets(rawHTML string, maxSnippets int) (headings []string, paragraphs []string, listItems []string) { + scan := rawHTML + if len(scan) > 256*1024 { + scan = scan[:256*1024] + } + lower := asciiLowerExtractString(scan) + if idx := strings.Index(lower, "= 0 { + if end := strings.Index(lower[idx:], ""); end > 0 { + scan = scan[idx : idx+end+7] + } + } + seen := make(map[string]bool) + matches := wave3EduScanTags(scan, 250) + for _, m := range matches { + txt := wave3EduCleanText(m.Inner) + if len(txt) < 4 || len(txt) > 800 || seen[txt] { + continue + } + seen[txt] = true + switch m.Tag { + case "h1", "h2", "h3": + if !wave3EduRxGenericHead.MatchString(txt) && len(headings) < maxSnippets { + headings = append(headings, txt) + } + case "p", "article": + if len(txt) >= 24 && len(paragraphs) < maxSnippets { + paragraphs = append(paragraphs, txt) + } + case "li": + if len(txt) >= 12 && len(listItems) < maxSnippets { + listItems = append(listItems, txt) + } + } + } + return headings, paragraphs, listItems +} + +func wave3EduExtractAnchorLinks(rawHTML, baseURL string, pathNeedles []string, limit int) []struct{ Text, URL string } { + var out []struct{ Text, URL string } + seen := make(map[string]bool) + scan := rawHTML + if len(scan) > 512*1024 { + scan = scan[:512*1024] + } + pos := 0 + for pos < len(scan) && len(out) < limit { + idx := indexFoldASCIIExtract(scan[pos:], "') + if gt < 0 { + break + } + openTag := scan[start : start+gt+1] + closeIdx := indexFoldASCIIExtract(scan[start+gt+1:], "") + pos = start + gt + 1 + if closeIdx < 0 || closeIdx > 2048 { + continue + } + inner := wave3EduCleanText(scan[pos : pos+closeIdx]) + pos += closeIdx + 4 + href := wave3EduExtractAttr(openTag, "href") + resolved := wave3EduResolveURL(href, baseURL) + if resolved == "" || seen[resolved] { + continue + } + if len(pathNeedles) > 0 { + lowURL := strings.ToLower(resolved) + matched := false + for _, pn := range pathNeedles { + if strings.Contains(lowURL, pn) { + matched = true + break + } + } + if !matched { + continue + } + } + seen[resolved] = true + if inner == "" { + inner = resolved + } + out = append(out, struct{ Text, URL string }{Text: inner, URL: resolved}) + } + return out +} + +func wave3EduRenderBulletsAndSections(title string, bullets []string, sections []string) string { + var sb strings.Builder + if title != "" { + sb.WriteString("# ") + sb.WriteString(escapeDeclMarkdownBrackets(title)) + sb.WriteString("\n\n") + } + for _, b := range bullets { + if strings.TrimSpace(b) != "" { + sb.WriteString(b) + sb.WriteByte('\n') + } + } + if len(bullets) > 0 && len(sections) > 0 { + sb.WriteByte('\n') + } + for _, sec := range sections { + if strings.TrimSpace(sec) != "" { + sb.WriteString(sec) + sb.WriteString("\n\n") + } + } + return strings.TrimSpace(sb.String()) +} + +// ── #217 Finalsite HTML Extractor ───────────────────────────────────────────────────────────────── + +func wave3EduExtractFinalsiteHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + if len(rawHTML) > wave3EduMaxHTMLBytes { + rawHTML = truncateUTF8SafeFullDocGo(rawHTML, wave3EduMaxHTMLBytes) + } + if !containsAnyFoldASCIIExtract(rawHTML, "finalsite", "/fs/", "fselement", "fscalendar", "fsresource", "fsnews", "resources.finalsite.net", "fspage") { + return nil + } + + title, siteName := wave3EduExtractBestHeadingAndPageTitle(rawHTML) + if rawPageTitle := wave3EduCleanText(extractTitleLinearQuick(rawHTML)); rawPageTitle != "" && len(rawPageTitle) <= 220 && + !wave3EduRxGenericHead.MatchString(rawPageTitle) && strings.Contains(rawPageTitle, title) && rawPageTitle != title { + title = rawPageTitle + } + desc := wave3EduExtractMeta(rawHTML, "description") + if desc == "" { + desc = wave3EduExtractMeta(rawHTML, "og:description") + } + + var records []map[string]any + var links []string + var eventLines []string + var newsLines []string + var resourceLines []string + + // 1. JSON-LD events / news / school metadata + if hasJSONLDScriptToken(rawHTML) { + for _, ent := range flattenJsonLdEntitiesFullDocGo(rawHTML) { + t := strings.ToLower(wave3EduPlain(ent["@type"], 80)) + switch { + case strings.Contains(t, "school") || strings.Contains(t, "educationalorganization") || strings.Contains(t, "organization"): + if siteName == "" { + siteName = wave3EduPlain(ent["name"], 160) + } + case strings.Contains(t, "event"): + evName := wave3EduPlain(ent["name"], 180) + evDate := wave3EduFirstNonEmpty(wave3EduValidateISODate(wave3EduPlain(ent["startDate"], 64)), wave3EduPlain(ent["startDate"], 64)) + evURL := SanitizeSchemaHTTPSURL(ent["url"], baseURL) + if evName != "" && len(records) < wave3EduMaxRecords { + rec := map[string]any{"kind": "event", "title": evName} + if evDate != "" { + rec["date"] = evDate + } + if evURL != "" { + rec["url"] = evURL + links = append(links, evURL) + } + records = append(records, rec) + eventLines = append(eventLines, fmt.Sprintf("- **%s**%s", escapeDeclMarkdownBrackets(evName), func() string { + if evDate != "" { + return " (" + evDate + ")" + } + return "" + }())) + } + case strings.Contains(t, "article"): + nTitle := wave3EduPlain(ent["headline"], 180) + if nTitle == "" { + nTitle = wave3EduPlain(ent["name"], 180) + } + nDate := wave3EduValidateISODate(wave3EduPlain(ent["datePublished"], 64)) + if nTitle != "" && len(records) < wave3EduMaxRecords { + rec := map[string]any{"kind": "news", "title": nTitle} + if nDate != "" { + rec["date"] = nDate + } + records = append(records, rec) + newsLines = append(newsLines, "- "+escapeDeclMarkdownBrackets(nTitle)) + } + } + } + } + + // 2. Finalsite Calendar blocks (fsCalendarEvent / fsEvent) + for _, blk := range wave3EduExtractBalancedDivsByClass(rawHTML, "fsCalendarEvent", 20) { + evTitle := "" + for _, m := range wave3EduScanTags(blk, 12) { + txt := wave3EduCleanText(m.Inner) + if txt != "" && len(txt) <= 200 { + evTitle = txt + break + } + } + if evTitle == "" { + evTitle = wave3EduCleanText(blk) + } + if len(evTitle) > 180 { + evTitle = evTitle[:180] + } + evLinks := wave3EduExtractAnchorLinks(blk, baseURL, nil, 1) + evURL := "" + if len(evLinks) > 0 { + evURL = evLinks[0].URL + if evLinks[0].Text != "" && len(evLinks[0].Text) <= 180 { + evTitle = evLinks[0].Text + } + links = append(links, evURL) + } + if evTitle != "" && len(records) < wave3EduMaxRecords { + rec := map[string]any{"kind": "event", "title": evTitle} + if evURL != "" { + rec["url"] = evURL + } + records = append(records, rec) + eventLines = append(eventLines, "- "+escapeDeclMarkdownBrackets(evTitle)) + } + } + + // 3. Finalsite News / Post blocks + for _, blk := range wave3EduExtractBalancedDivsByClass(rawHTML, "fsPost", 15) { + nLinks := wave3EduExtractAnchorLinks(blk, baseURL, nil, 1) + nTitle := "" + nURL := "" + if len(nLinks) > 0 { + nTitle = nLinks[0].Text + nURL = nLinks[0].URL + links = append(links, nURL) + } + if nTitle == "" { + nTitle = wave3EduCleanText(blk) + } + if len(nTitle) > 180 { + nTitle = nTitle[:180] + } + if nTitle != "" && len(records) < wave3EduMaxRecords { + rec := map[string]any{"kind": "news", "title": nTitle} + if nURL != "" { + rec["url"] = nURL + } + records = append(records, rec) + newsLines = append(newsLines, "- "+escapeDeclMarkdownBrackets(nTitle)) + } + } + + // 4. Calendar event & resource links + for _, l := range wave3EduExtractAnchorLinks(rawHTML, baseURL, []string{"/calendar/event-details/", "/fs/resource-manager/view/", "/fs/pages/"}, 25) { + links = append(links, l.URL) + if strings.Contains(strings.ToLower(l.URL), "/resource-manager/") { + resourceLines = append(resourceLines, fmt.Sprintf("- [%s](%s)", escapeDeclMarkdownBrackets(l.Text), l.URL)) + if len(records) < wave3EduMaxRecords { + records = append(records, map[string]any{"kind": "resource", "title": l.Text, "url": l.URL}) + } + } else if strings.Contains(strings.ToLower(l.URL), "/event-details/") && len(eventLines) < 15 { + eventLines = append(eventLines, fmt.Sprintf("- [%s](%s)", escapeDeclMarkdownBrackets(l.Text), l.URL)) + if len(records) < wave3EduMaxRecords { + records = append(records, map[string]any{"kind": "event", "title": l.Text, "url": l.URL}) + } + } + } + + headings, paras, items := wave3EduExtractDOMSnippets(rawHTML, 15) + if title == "" && len(headings) > 0 { + title = headings[0] + } + if title == "" && desc == "" && len(records) == 0 && len(paras) == 0 { + return nil + } + + var bullets []string + if siteName != "" { + bullets = append(bullets, "- **Organization**: "+escapeDeclMarkdownBrackets(siteName)) + } + bullets = append(bullets, "- **Platform**: Finalsite") + if baseURL != "" { + bullets = append(bullets, "- **Source**: "+baseURL) + } + + var sections []string + if desc != "" { + sections = append(sections, desc) + } + if len(eventLines) > 0 { + sections = append(sections, "## Calendar Events\n\n"+strings.Join(eventLines, "\n")) + } + if len(newsLines) > 0 { + sections = append(sections, "## News & Announcements\n\n"+strings.Join(newsLines, "\n")) + } + if len(resourceLines) > 0 { + sections = append(sections, "## Resources\n\n"+strings.Join(resourceLines, "\n")) + } + if len(eventLines) == 0 && len(newsLines) == 0 && len(paras) > 0 { + sections = append(sections, "## Page Content\n\n"+strings.Join(paras, "\n\n")) + } else if len(eventLines) == 0 && len(newsLines) == 0 && len(items) > 0 { + var itemLines []string + for _, it := range items { + itemLines = append(itemLines, "- "+escapeDeclMarkdownBrackets(it)) + } + sections = append(sections, "## Highlights\n\n"+strings.Join(itemLines, "\n")) + } + + md := wave3EduRenderBulletsAndSections(title, bullets, sections) + if md == "" { + return nil + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: md, + Links: links, + Records: records, + } +} + +// ── #218 Blackboard WCM / SchoolMessenger Presence HTML Extractor ───────────────────────────────── + +func wave3EduExtractBlackboardWCMHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + if len(rawHTML) > wave3EduMaxHTMLBytes { + rawHTML = truncateUTF8SafeFullDocGo(rawHTML, wave3EduMaxHTMLBytes) + } + // Strictly exclude Finalsite /fs/ migrated districts across the full bounded HTML to avoid cross-platform collision. + if containsAnyFoldASCIIExtract(rawHTML, "/fs/", "fselement", "fscalendar", "resources.finalsite.net", "finalsite") { + return nil + } + lowerProbe := wave3EduLowerProbe(rawHTML, 180_000) + hasMarker := wave3EduContainsAny(lowerProbe, + "sw-content-layout", + "schoolwires", + "cs-calendar", + "schoolmessenger", + "sw-calendar", + "sw-module", + "ui-article", + "/media/filter/news", + ) || (strings.Contains(lowerProbe, "blackboard") && wave3EduContainsAny(lowerProbe, "wcm", "school", "district", "calendar", "staff")) + if !hasMarker { + return nil + } + + title, siteName := wave3EduExtractBestHeadingAndPageTitle(rawHTML) + if rawPageTitle := wave3EduCleanText(extractTitleLinearQuick(rawHTML)); rawPageTitle != "" && len(rawPageTitle) <= 220 && + !wave3EduRxGenericHead.MatchString(rawPageTitle) && strings.Contains(rawPageTitle, title) && rawPageTitle != title { + title = rawPageTitle + } + desc := wave3EduExtractMeta(rawHTML, "description") + platformLabel := "Blackboard WCM" + if wave3EduContainsAny(lowerProbe, "schoolmessenger", "cs-calendar", "/media/filter/news") { + platformLabel = "SchoolMessenger Presence" + } + + var records []map[string]any + var links []string + var itemLines []string + + if hasJSONLDScriptToken(rawHTML) { + for _, ent := range flattenJsonLdEntitiesFullDocGo(rawHTML) { + t := strings.ToLower(wave3EduPlain(ent["@type"], 80)) + if strings.Contains(t, "educationalorganization") || strings.Contains(t, "school") { + if siteName == "" { + siteName = wave3EduPlain(ent["name"], 160) + } + } else if strings.Contains(t, "event") || strings.Contains(t, "article") { + n := wave3EduFirstNonEmpty(wave3EduPlain(ent["name"], 180), wave3EduPlain(ent["headline"], 180)) + if n != "" && len(records) < wave3EduMaxRecords { + rec := map[string]any{"title": n} + if dt := wave3EduValidateISODate(wave3EduPlain(ent["startDate"], 64)); dt != "" { + rec["date"] = dt + } + records = append(records, rec) + itemLines = append(itemLines, "- "+escapeDeclMarkdownBrackets(n)) + } + } + } + } + + for _, className := range []string{"ui-article", "sw-calendar-block", "cs-calendar", "news-item", "staff-member"} { + for _, blk := range wave3EduExtractBalancedDivsByClass(rawHTML, className, 12) { + txt := wave3EduCleanText(blk) + if len(txt) < 8 { + continue + } + if len(txt) > 220 { + txt = txt[:220] + } + bLinks := wave3EduExtractAnchorLinks(blk, baseURL, nil, 1) + rec := map[string]any{"kind": className, "title": txt} + if len(bLinks) > 0 { + rec["url"] = bLinks[0].URL + links = append(links, bLinks[0].URL) + } + if len(records) < wave3EduMaxRecords { + records = append(records, rec) + } + itemLines = append(itemLines, "- "+escapeDeclMarkdownBrackets(txt)) + } + } + + headings, paras, domItems := wave3EduExtractDOMSnippets(rawHTML, 15) + if title == "" && len(headings) > 0 { + title = headings[0] + } + if title == "" && len(records) == 0 && len(paras) == 0 { + return nil + } + + var bullets []string + if siteName != "" { + bullets = append(bullets, "- **District / School**: "+escapeDeclMarkdownBrackets(siteName)) + } + bullets = append(bullets, "- **Platform**: "+platformLabel) + if baseURL != "" { + bullets = append(bullets, "- **Source**: "+baseURL) + } + + var sections []string + if desc != "" { + sections = append(sections, desc) + } + if len(itemLines) > 0 { + sections = append(sections, "## Announcements & Events\n\n"+strings.Join(itemLines, "\n")) + } else if len(paras) > 0 { + sections = append(sections, "## Page Content\n\n"+strings.Join(paras, "\n\n")) + } else if len(domItems) > 0 { + var dLines []string + for _, di := range domItems { + dLines = append(dLines, "- "+escapeDeclMarkdownBrackets(di)) + } + sections = append(sections, "## Highlights\n\n"+strings.Join(dLines, "\n")) + } + + md := wave3EduRenderBulletsAndSections(title, bullets, sections) + if md == "" { + return nil + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: md, + Links: links, + Records: records, + } +} + +// ── #219 Edlio & Apptegy Thrillshare HTML Extractor ─────────────────────────────────────────────── + +func wave3EduExtractEdlioThrillshareHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + lowerProbe := wave3EduLowerProbe(rawHTML, 180_000) + isEdlio := wave3EduContainsAny(lowerProbe, "edlio", "edliocdn", "/apps/news/", "/apps/events/", "school_news_app") + isApptegy := wave3EduContainsAny(lowerProbe, "apptegy", "thrillshare", "cmsv2-static-cdn-prod.apptegy.net") + if !isEdlio && !isApptegy { + return nil + } + + headProbe := rawHTML + if len(headProbe) > 131_072 { + headProbe = truncateUTF8SafeFullDocGo(headProbe, 131_072) + } + slimHTML := stripScriptsAndStylesDeclHTML(rawHTML) + if len(slimHTML) > 393_216 { + slimHTML = truncateUTF8SafeFullDocGo(slimHTML, 393_216) + } + slimLower := asciiLowerExtractString(slimHTML) + + title, siteName := wave3EduExtractBestHeadingAndPageTitle(headProbe) + if rawPageTitle := wave3EduCleanText(extractTitleLinearQuick(headProbe)); rawPageTitle != "" && len(rawPageTitle) <= 220 && + !wave3EduRxGenericHead.MatchString(rawPageTitle) && strings.Contains(rawPageTitle, title) && rawPageTitle != title { + title = rawPageTitle + } + desc := wave3EduExtractMeta(headProbe, "description") + platformLabel := "Edlio" + if isApptegy && !isEdlio { + platformLabel = "Apptegy Thrillshare" + } else if isApptegy && isEdlio { + platformLabel = "Edlio / Apptegy Thrillshare" + } + + var records []map[string]any + var links []string + var feedLines []string + + for _, className := range []string{"news-article", "article-card", "live-feed", "event-item", "news-item"} { + if !strings.Contains(slimLower, className) { + continue + } + for _, blk := range wave3EduExtractBalancedDivsByClass(slimHTML, className, 15) { + txt := wave3EduCleanText(blk) + if len(txt) < 8 { + continue + } + if len(txt) > 220 { + txt = txt[:220] + } + bLinks := wave3EduExtractAnchorLinks(blk, baseURL, nil, 1) + rec := map[string]any{"kind": className, "title": txt} + if len(bLinks) > 0 { + rec["url"] = bLinks[0].URL + links = append(links, bLinks[0].URL) + if bLinks[0].Text != "" && len(bLinks[0].Text) <= 180 { + rec["title"] = bLinks[0].Text + } + } + if len(records) < wave3EduMaxRecords { + records = append(records, rec) + } + feedLines = append(feedLines, "- "+escapeDeclMarkdownBrackets(txt)) + } + } + + for _, l := range wave3EduExtractAnchorLinks(slimHTML, baseURL, []string{"/apps/news/", "/apps/events/", "/o/", "/article/", "/events"}, 20) { + links = append(links, l.URL) + if len(feedLines) < 20 && len(l.Text) >= 6 { + feedLines = append(feedLines, fmt.Sprintf("- [%s](%s)", escapeDeclMarkdownBrackets(l.Text), l.URL)) + if len(records) < wave3EduMaxRecords { + records = append(records, map[string]any{"kind": "link", "title": l.Text, "url": l.URL}) + } + } + } + + headings, paras, domItems := wave3EduExtractDOMSnippets(slimHTML, 15) + if title == "" && len(headings) > 0 { + title = headings[0] + } + if title == "" && len(records) == 0 && len(paras) == 0 && len(domItems) == 0 { + return nil + } + + var bullets []string + if siteName != "" { + bullets = append(bullets, "- **District / School**: "+escapeDeclMarkdownBrackets(siteName)) + } + bullets = append(bullets, "- **Platform**: "+platformLabel) + if baseURL != "" { + bullets = append(bullets, "- **Source**: "+baseURL) + } + + var sections []string + if desc != "" { + sections = append(sections, desc) + } + if len(feedLines) > 0 { + sections = append(sections, "## News & Feed Items\n\n"+strings.Join(feedLines, "\n")) + } + if len(paras) > 0 { + sections = append(sections, "## Content\n\n"+strings.Join(paras, "\n\n")) + } else if len(feedLines) == 0 && len(domItems) > 0 { + var dLines []string + for _, di := range domItems { + dLines = append(dLines, "- "+escapeDeclMarkdownBrackets(di)) + } + sections = append(sections, "## Items\n\n"+strings.Join(dLines, "\n")) + } + + md := wave3EduRenderBulletsAndSections(title, bullets, sections) + if md == "" { + return nil + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: md, + Links: links, + Records: records, + } +} + +// ── #220 Acalog HTML Extractor ──────────────────────────────────────────────────────────────────── + +func wave3EduExtractAcalogHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + lowURL := strings.ToLower(baseURL) + // Avoid Acalog /ajax/, /portfolio.php, /search_advanced.php routes disallowed by robots.txt + if strings.Contains(lowURL, "/ajax/") || strings.Contains(lowURL, "/portfolio.php") || strings.Contains(lowURL, "/search_advanced.php") { + return nil + } + lowerProbe := wave3EduLowerProbe(rawHTML, 180_000) + if wave3EduContainsAny(lowerProbe, "coursedog", "courseleaf") { + return nil + } + hasMarker := wave3EduContainsAny(lowerProbe, "acalog", "acalog-clients", "preview_course_nopop", "preview_course.php", "preview_program.php", "block_content") || + (strings.Contains(lowerProbe, "catoid=") && wave3EduContainsAny(lowerProbe, "coid=", "navoid=", "poid=")) + if !hasMarker { + return nil + } + if wave3EduContainsAny(lowerProbe, "invalid catoid", "invalid coid", "course could not be found", "catalog could not be found") { + return nil + } + + title, siteName := wave3EduExtractBestHeadingAndPageTitle(rawHTML) + if courseH1 := wave3EduExtractBalancedByIDOrTag(rawHTML, "course_preview_title"); courseH1 != "" { + title = courseH1 + } + + var records []map[string]any + var links []string + var courseLinks []string + for _, l := range wave3EduExtractAnchorLinks(rawHTML, baseURL, []string{"preview_course", "preview_program", "content.php"}, 25) { + links = append(links, l.URL) + if strings.Contains(strings.ToLower(l.URL), "preview_course") && len(l.Text) >= 3 { + courseLinks = append(courseLinks, fmt.Sprintf("- [%s](%s)", escapeDeclMarkdownBrackets(l.Text), l.URL)) + if len(records) < wave3EduMaxRecords { + rec := map[string]any{"kind": "course", "title": l.Text, "url": l.URL} + if cm := wave3EduRxCourseCode.FindStringSubmatch(l.Text); len(cm) == 2 { + rec["courseCode"] = cm[1] + } + records = append(records, rec) + } + } + } + + headings, paras, items := wave3EduExtractDOMSnippets(rawHTML, 20) + if title == "" && len(headings) > 0 { + title = headings[0] + } + if title == "" && len(paras) == 0 && len(courseLinks) == 0 { + return nil + } + + var bullets []string + if siteName != "" { + bullets = append(bullets, "- **Catalog**: "+escapeDeclMarkdownBrackets(siteName)) + } + if cm := wave3EduRxCourseCode.FindStringSubmatch(title); len(cm) == 2 { + bullets = append(bullets, "- **Course Code**: `"+cm[1]+"`") + } + joinedProse := strings.Join(paras, " ") + if cr := wave3EduRxAcalogCredits.FindStringSubmatch(joinedProse); len(cr) == 2 { + bullets = append(bullets, "- **Credits**: "+cr[1]) + } else if cr := wave3EduRxCourseCredits.FindStringSubmatch(title); len(cr) == 2 { + bullets = append(bullets, "- **Credits**: "+cr[1]) + } + bullets = append(bullets, "- **Platform**: Acalog") + + var sections []string + if len(paras) > 0 { + sections = append(sections, "## Description\n\n"+strings.Join(paras, "\n\n")) + } + if len(courseLinks) > 0 { + sections = append(sections, "## Catalog Courses\n\n"+strings.Join(courseLinks, "\n")) + } else if len(items) > 0 { + var iLines []string + for _, it := range items { + iLines = append(iLines, "- "+escapeDeclMarkdownBrackets(it)) + } + sections = append(sections, "## Requirements & Navigation\n\n"+strings.Join(iLines, "\n")) + } + + md := wave3EduRenderBulletsAndSections(title, bullets, sections) + if md == "" { + return nil + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Markdown: md, + Links: links, + Records: records, + } +} + +func wave3EduExtractBalancedByIDOrTag(rawHTML, idAttr string) string { + needle := strings.ToLower(idAttr) + pos := 0 + for pos < len(rawHTML) { + idx := indexFoldASCIIExtract(rawHTML[pos:], needle) + if idx < 0 { + return "" + } + hit := pos + idx + openStart := strings.LastIndexByte(rawHTML[:hit], '<') + if openStart < 0 || hit-openStart > 300 { + pos = hit + len(needle) + continue + } + gt := strings.IndexByte(rawHTML[openStart:], '>') + if gt < 0 || openStart+gt < hit { + pos = hit + len(needle) + continue + } + openTag := rawHTML[openStart : openStart+gt+1] + if !strings.EqualFold(wave3EduExtractAttr(openTag, "id"), idAttr) { + pos = hit + len(needle) + continue + } + // Determine tag name + tagFields := strings.Fields(openTag[1 : len(openTag)-1]) + if len(tagFields) == 0 { + return "" + } + tagName := strings.ToLower(tagFields[0]) + openTok := "<" + tagName + closeTok := "= 0 && nextOpen < nextClose { + // Ensure tag boundary + afterIdx := cur + nextOpen + len(openTok) + if afterIdx < len(rawHTML) && (rawHTML[afterIdx] == ' ' || rawHTML[afterIdx] == '>' || rawHTML[afterIdx] == '\t' || rawHTML[afterIdx] == '\n') { + depth++ + } + cur = afterIdx + } else { + depth-- + if depth == 0 { + endPos = cur + nextClose + break + } + cur += nextClose + len(closeTok) + } + } + if endPos > openStart+gt+1 { + return wave3EduCleanText(rawHTML[openStart+gt+1 : endPos]) + } + return "" + } + return "" +} + +// ── #222 Coursedog JSON & Nuxt SSR HTML Extractor ───────────────────────────────────────────────── + +func wave3EduFormatCoursedogJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + var items []map[string]any + title := "Coursedog Catalog" + switch v := parsed.(type) { + case map[string]any: + if errMsg := wave3EduPlain(v["error"], 120); errMsg != "" { + return nil, false + } + if statusNum, ok := v["statusCode"].(json.Number); ok { + if code, err := statusNum.Int64(); err == nil && code >= 400 { + return nil, false + } + } + for _, arrKey := range []string{"data", "courses", "results", "items"} { + if arr, ok := v[arrKey].([]any); ok { + for _, el := range arr { + if m, ok := el.(map[string]any); ok { + items = append(items, m) + } + } + break + } + } + if len(items) == 0 && (v["code"] != nil || v["name"] != nil || v["courseNumber"] != nil) { + items = append(items, v) + } + case []any: + for _, el := range v { + if m, ok := el.(map[string]any); ok { + items = append(items, m) + } + } + } + if len(items) == 0 { + return nil, false + } + var records []map[string]any + var rows []string + for _, it := range items { + code := wave3EduFirstNonEmpty(wave3EduPlain(it["code"], 40), strings.TrimSpace(wave3EduPlain(it["subjectCode"], 20)+" "+wave3EduPlain(it["courseNumber"], 20))) + name := wave3EduFirstNonEmpty(wave3EduPlain(it["longName"], 180), wave3EduPlain(it["name"], 180), wave3EduPlain(it["title"], 180)) + if name == "" && code == "" { + continue + } + credits := "" + if cMap, ok := it["credits"].(map[string]any); ok { + if numMap, ok := cMap["creditHours"].(map[string]any); ok { + credits = wave3EduFirstNonEmpty(wave3EduPlain(numMap["min"], 20), wave3EduPlain(numMap["value"], 20)) + } else { + credits = wave3EduFirstNonEmpty(wave3EduPlain(cMap["min"], 20), wave3EduPlain(cMap["value"], 20)) + } + } else { + credits = wave3EduPlain(it["credits"], 20) + } + desc := wave3EduPlain(it["description"], 500) + rec := map[string]any{"code": code, "name": name} + if credits != "" { + rec["credits"] = credits + } + if desc != "" { + rec["description"] = desc + } + if len(records) < wave3EduMaxRecords { + records = append(records, rec) + } + rows = append(rows, fmt.Sprintf("| `%s` | %s | %s |", wave3EduFirstNonEmpty(code, "-"), escapeDeclMarkdownBrackets(wave3EduFirstNonEmpty(name, code)), wave3EduFirstNonEmpty(credits, "-"))) + } + if len(records) == 0 { + return nil, false + } + if len(records) == 1 { + title = wave3EduFirstNonEmpty(wave3EduPlain(records[0]["code"], 40)+" — "+wave3EduPlain(records[0]["name"], 180), wave3EduPlain(records[0]["name"], 180)) + } else { + title = fmt.Sprintf("Coursedog Catalog (%d courses)", len(records)) + } + bullets := []string{"- **Platform**: Coursedog"} + if origURL != "" { + bullets = append(bullets, "- **Source**: "+origURL) + } + table := "## Courses\n\n| Code | Name | Credits |\n|---|---|---|\n" + strings.Join(rows, "\n") + md := wave3EduRenderBulletsAndSections(title, bullets, []string{table}) + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: md, + Records: records, + }, true +} + +func wave3EduExtractCoursedogHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + lowerProbe := wave3EduLowerProbe(rawHTML, 256*1024) + if !wave3EduContainsAny(lowerProbe, "coursedog", "static.catalog.prod.coursedog.com", "app.coursedog.com") { + return nil + } + + title, siteName := wave3EduExtractBestHeadingAndPageTitle(rawHTML) + if rawPageTitle := wave3EduCleanText(extractTitleLinearQuick(rawHTML)); rawPageTitle != "" && len(rawPageTitle) <= 220 && + !wave3EduRxGenericHead.MatchString(rawPageTitle) && strings.Contains(rawPageTitle, title) && rawPageTitle != title { + title = rawPageTitle + } + desc := wave3EduExtractMeta(rawHTML, "description") + + var records []map[string]any + var links []string + var courseLines []string + + // 1. Inspect SSR __NUXT_DATA__ payload if present + if nuxtRaw := wave3EduExtractScriptByID(rawHTML, "__NUXT_DATA__"); nuxtRaw != "" && len(nuxtRaw) <= 1024*1024 { + if parsed, ok := decodeJSONWithNumbers([]byte(nuxtRaw)); ok { + if arr, isArr := parsed.([]any); isArr { + wave3EduScanNuxtDataForCoursedog(arr, &records, &courseLines) + } + } + } + + // 2. Rendered catalog DOM (course cards/rows, headings, links) + for _, l := range wave3EduExtractAnchorLinks(rawHTML, baseURL, []string{"/courses/", "/programs/", "/departments/", "/course/"}, 25) { + links = append(links, l.URL) + if len(l.Text) >= 4 && len(records) < wave3EduMaxRecords { + rec := map[string]any{"kind": "catalog_item", "title": l.Text, "url": l.URL} + if cm := wave3EduRxCourseCode.FindStringSubmatch(l.Text); len(cm) == 2 { + rec["courseCode"] = cm[1] + } + records = append(records, rec) + courseLines = append(courseLines, fmt.Sprintf("- [%s](%s)", escapeDeclMarkdownBrackets(l.Text), l.URL)) + } + } + + headings, paras, domItems := wave3EduExtractDOMSnippets(rawHTML, 20) + if title == "" && len(headings) > 0 { + title = headings[0] + } + if len(records) == 0 && len(paras) == 0 && len(domItems) == 0 { + return nil + } + if title == "" { + title = wave3EduFirstNonEmpty(siteName, "Coursedog Catalog") + } + + var bullets []string + if siteName != "" { + bullets = append(bullets, "- **Institution**: "+escapeDeclMarkdownBrackets(siteName)) + } + bullets = append(bullets, "- **Platform**: Coursedog") + if baseURL != "" { + bullets = append(bullets, "- **Source**: "+baseURL) + } + + var sections []string + if desc != "" { + sections = append(sections, desc) + } + if len(courseLines) > 0 { + sections = append(sections, "## Catalog Entries\n\n"+strings.Join(courseLines, "\n")) + } + if len(paras) > 0 { + sections = append(sections, "## Overview\n\n"+strings.Join(paras, "\n\n")) + } else if len(courseLines) == 0 && len(domItems) > 0 { + var dLines []string + for _, di := range domItems { + dLines = append(dLines, "- "+escapeDeclMarkdownBrackets(di)) + } + sections = append(sections, "## Catalog Items\n\n"+strings.Join(dLines, "\n")) + } + + md := wave3EduRenderBulletsAndSections(title, bullets, sections) + if md == "" { + return nil + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: md, + Links: links, + Records: records, + } +} + +func wave3EduScanNuxtDataForCoursedog(arr []any, records *[]map[string]any, lines *[]string) { + resolveStr := func(v any) string { + switch idx := v.(type) { + case json.Number: + if i, err := idx.Int64(); err == nil && i >= 0 && int(i) < len(arr) { + if s, ok := arr[int(i)].(string); ok { + return strings.TrimSpace(s) + } + } + case string: + return strings.TrimSpace(idx) + } + return "" + } + seen := make(map[string]bool) + for _, item := range arr { + if len(*records) >= wave3EduMaxRecords { + break + } + m, ok := item.(map[string]any) + if !ok { + continue + } + code := wave3EduFirstNonEmpty(resolveStr(m["code"]), resolveStr(m["courseNumber"])) + name := wave3EduFirstNonEmpty(resolveStr(m["longName"]), resolveStr(m["name"]), resolveStr(m["title"])) + if code == "" || name == "" || len(code) > 32 || len(name) > 200 { + continue + } + // Ensure code looks like a course code (contains a digit) + hasDigit := false + for i := 0; i < len(code); i++ { + if code[i] >= '0' && code[i] <= '9' { + hasDigit = true + break + } + } + if !hasDigit || seen[code+"|"+name] { + continue + } + seen[code+"|"+name] = true + rec := map[string]any{"kind": "course", "courseCode": code, "title": name} + if desc := resolveStr(m["description"]); desc != "" && len(desc) <= 600 { + rec["description"] = desc + } + *records = append(*records, rec) + *lines = append(*lines, fmt.Sprintf("- **%s** — %s", escapeDeclMarkdownBrackets(code), escapeDeclMarkdownBrackets(name))) + } +} + +// ── #223 Canvas LMS Public Courses JSON & HTML Extractor ────────────────────────────────────────── + +func wave3EduFormatCanvasCourseJSON(parsed any, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool) { + _ = params + var courses []map[string]any + switch v := parsed.(type) { + case map[string]any: + if v["errors"] != nil || strings.EqualFold(wave3EduPlain(v["status"], 40), "unauthorized") { + return nil, false + } + if v["name"] != nil || v["course_code"] != nil { + courses = append(courses, v) + } + case []any: + for _, el := range v { + if m, ok := el.(map[string]any); ok && (m["name"] != nil || m["course_code"] != nil) { + courses = append(courses, m) + } + } + } + if len(courses) == 0 { + return nil, false + } + + var records []map[string]any + var sections []string + for _, c := range courses { + name := wave3EduPlain(c["name"], 200) + code := wave3EduPlain(c["course_code"], 60) + if name == "" && code == "" { + continue + } + rec := map[string]any{"name": name} + if code != "" { + rec["courseCode"] = code + } + if id := wave3EduPlain(c["id"], 40); id != "" { + rec["courseId"] = id + } + if startAt := wave3EduValidateISODate(wave3EduPlain(c["start_at"], 64)); startAt != "" { + rec["startAt"] = startAt + } + if endAt := wave3EduValidateISODate(wave3EduPlain(c["end_at"], 64)); endAt != "" { + rec["endAt"] = endAt + } + if wf := wave3EduPlain(c["workflow_state"], 40); wf != "" { + rec["workflowState"] = wf + } + if len(records) < wave3EduMaxRecords { + records = append(records, rec) + } + + var sb strings.Builder + if len(courses) > 1 { + sb.WriteString("### " + escapeDeclMarkdownBrackets(wave3EduFirstNonEmpty(name, code)) + "\n\n") + } + if code != "" { + sb.WriteString("- **Course Code**: `" + code + "`\n") + } + if term, ok := c["term"].(map[string]any); ok { + if tName := wave3EduPlain(term["name"], 120); tName != "" { + sb.WriteString("- **Term**: " + escapeDeclMarkdownBrackets(tName) + "\n") + } + } + if wf := wave3EduPlain(c["workflow_state"], 40); wf != "" { + sb.WriteString("- **State**: " + wf + "\n") + } + if sylHTML, ok := c["syllabus_body"].(string); ok && strings.TrimSpace(sylHTML) != "" { + if sylClean := wave3EduCleanText(sylHTML); sylClean != "" { + if len(sylClean) > 4000 { + sylClean = sylClean[:4000] + } + sb.WriteString("\n## Syllabus\n\n" + sylClean + "\n") + } + } + sections = append(sections, strings.TrimSpace(sb.String())) + } + if len(records) == 0 { + return nil, false + } + title := wave3EduPlain(courses[0]["name"], 200) + if len(courses) > 1 { + title = fmt.Sprintf("Canvas Public Courses (%d)", len(courses)) + } + bullets := []string{"- **Platform**: Canvas LMS"} + if origURL != "" { + bullets = append(bullets, "- **Source**: "+origURL) + } + md := wave3EduRenderBulletsAndSections(title, bullets, sections) + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: md, + Records: records, + }, true +} + +func wave3EduExtractCanvasPublicHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + lowURL := strings.ToLower(baseURL) + if wave3EduContainsAny(lowURL, "/login/saml", "/login/canvas", "/login/ldap", "/idp/", "/shibboleth", "/adfs/", "/saml2/") { + return nil + } + lowerProbe := wave3EduLowerProbe(rawHTML, 180_000) + if !wave3EduContainsAny(lowerProbe, "instructure", "ic-app-main", `class="ic-app`, `class='ic-app`, "course_syllabus", "env.course", "canvas commons", "lor.instructure.com") { + return nil + } + if wave3EduContainsAny(lowerProbe, "samlrequest", "samlresponse", "log in to canvas", "free-for-teacher platform") { + return nil + } + + title, siteName := wave3EduExtractBestHeadingAndPageTitle(rawHTML) + if rawPageTitle := wave3EduCleanText(extractTitleLinearQuick(rawHTML)); rawPageTitle != "" && len(rawPageTitle) <= 220 && + !wave3EduRxGenericHead.MatchString(rawPageTitle) && strings.Contains(rawPageTitle, title) && rawPageTitle != title { + title = rawPageTitle + } + desc := wave3EduExtractMeta(rawHTML, "description") + syllabus := wave3EduExtractBalancedByIDOrTag(rawHTML, "course_syllabus") + if syllabus == "" { + if divs := wave3EduExtractBalancedDivsByClass(rawHTML, "show-content", 1); len(divs) > 0 { + syllabus = wave3EduCleanText(divs[0]) + } + } + headings, paras, items := wave3EduExtractDOMSnippets(rawHTML, 15) + if title == "" && len(headings) > 0 { + title = headings[0] + } + if title == "" && syllabus == "" && len(paras) == 0 { + return nil + } + + var bullets []string + if siteName != "" { + bullets = append(bullets, "- **Institution / Portal**: "+escapeDeclMarkdownBrackets(siteName)) + } + bullets = append(bullets, "- **Platform**: Canvas LMS") + if baseURL != "" { + bullets = append(bullets, "- **Source**: "+baseURL) + } + + var sections []string + if desc != "" { + sections = append(sections, desc) + } + if syllabus != "" { + sections = append(sections, "## Syllabus\n\n"+syllabus) + } else if len(paras) > 0 { + sections = append(sections, "## Course Overview\n\n"+strings.Join(paras, "\n\n")) + } else if len(items) > 0 { + var iLines []string + for _, it := range items { + iLines = append(iLines, "- "+escapeDeclMarkdownBrackets(it)) + } + sections = append(sections, "## Modules & Resources\n\n"+strings.Join(iLines, "\n")) + } + + md := wave3EduRenderBulletsAndSections(title, bullets, sections) + if md == "" { + return nil + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: md, + } +} + +// ── #224 edX & Coursera JSON & HTML Extractor ───────────────────────────────────────────────────── + +func wave3EduFormatEdxCourseJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + m, ok := parsed.(map[string]any) + if !ok { + return nil, false + } + if m["detail"] != nil || m["error_code"] != nil { + return nil, false + } + var items []map[string]any + if arr, ok := m["results"].([]any); ok { + for _, el := range arr { + if cm, ok := el.(map[string]any); ok { + items = append(items, cm) + } + } + } else if m["name"] != nil || m["id"] != nil { + items = append(items, m) + } + if len(items) == 0 { + return nil, false + } + + var records []map[string]any + var sections []string + for _, c := range items { + name := wave3EduPlain(c["name"], 200) + if name == "" { + continue + } + cid := wave3EduPlain(c["id"], 120) + org := wave3EduPlain(c["org"], 80) + num := wave3EduPlain(c["number"], 60) + effort := wave3EduPlain(c["effort"], 80) + pacing := wave3EduPlain(c["pacing"], 40) + start := wave3EduValidateISODate(wave3EduPlain(c["start"], 64)) + end := wave3EduValidateISODate(wave3EduPlain(c["end"], 64)) + shortDesc := wave3EduPlain(c["short_description"], 800) + + rec := map[string]any{"name": name} + if cid != "" { + rec["courseId"] = cid + } + if org != "" { + rec["org"] = org + } + if num != "" { + rec["courseNumber"] = num + } + if start != "" { + rec["start"] = start + } + if end != "" { + rec["end"] = end + } + if len(records) < wave3EduMaxRecords { + records = append(records, rec) + } + + var sb strings.Builder + if len(items) > 1 { + sb.WriteString("### " + escapeDeclMarkdownBrackets(name) + "\n\n") + } + if cid != "" { + sb.WriteString("- **Course ID**: `" + cid + "`\n") + } + if org != "" { + sb.WriteString("- **Organization**: " + escapeDeclMarkdownBrackets(org) + "\n") + } + if num != "" { + sb.WriteString("- **Number**: `" + num + "`\n") + } + if pacing != "" { + sb.WriteString("- **Pacing**: " + pacing + "\n") + } + if effort != "" { + sb.WriteString("- **Effort**: " + effort + "\n") + } + if start != "" { + sb.WriteString("- **Start**: " + start + "\n") + } + if shortDesc != "" { + sb.WriteString("\n" + shortDesc + "\n") + } + sections = append(sections, strings.TrimSpace(sb.String())) + } + if len(records) == 0 { + return nil, false + } + title := wave3EduPlain(items[0]["name"], 200) + if len(items) > 1 { + title = fmt.Sprintf("edX Courses (%d)", len(items)) + } + bullets := []string{"- **Platform**: edX"} + if origURL != "" { + bullets = append(bullets, "- **Source**: "+origURL) + } + md := wave3EduRenderBulletsAndSections(title, bullets, sections) + return &DeclarativeFormattedDoc{ + Title: title, + Description: wave3EduPlain(items[0]["short_description"], 300), + Markdown: md, + Records: records, + }, true +} + +func wave3EduExtractEdxCourseraHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + lowerProbe := wave3EduLowerProbe(rawHTML, 180_000) + isCoursera := strings.Contains(strings.ToLower(baseURL), "coursera.org") || strings.Contains(lowerProbe, "coursera") + isEdx := strings.Contains(strings.ToLower(baseURL), "edx.org") || strings.Contains(lowerProbe, "edx") + if !isCoursera && !isEdx { + return nil + } + + // Prefer rich Course JSON-LD if present (Coursera & edX) + if hasJSONLDScriptToken(rawHTML) { + if courseRes := wave3EduExtractCourseJSONLDCore(rawHTML, baseURL, extractorID); courseRes != nil { + return courseRes + } + } + + title, siteName := wave3EduExtractBestHeadingAndPageTitle(rawHTML) + if rawPageTitle := wave3EduCleanText(extractTitleLinearQuick(rawHTML)); rawPageTitle != "" && len(rawPageTitle) <= 220 && + !wave3EduRxGenericHead.MatchString(rawPageTitle) && strings.Contains(rawPageTitle, title) && rawPageTitle != title { + title = rawPageTitle + } + desc := wave3EduExtractMeta(rawHTML, "description") + headings, paras, items := wave3EduExtractDOMSnippets(rawHTML, 15) + if title == "" && len(headings) > 0 { + title = headings[0] + } + if title == "" && len(paras) == 0 && len(items) == 0 { + return nil + } + plat := "edX" + if isCoursera && !isEdx { + plat = "Coursera" + } + var bullets []string + if siteName != "" { + bullets = append(bullets, "- **Platform**: "+escapeDeclMarkdownBrackets(siteName)) + } else { + bullets = append(bullets, "- **Platform**: "+plat) + } + if baseURL != "" { + bullets = append(bullets, "- **Source**: "+baseURL) + } + var sections []string + if desc != "" { + sections = append(sections, desc) + } + if len(paras) > 0 { + sections = append(sections, "## Overview\n\n"+strings.Join(paras, "\n\n")) + } else if len(items) > 0 { + var iLines []string + for _, it := range items { + iLines = append(iLines, "- "+escapeDeclMarkdownBrackets(it)) + } + sections = append(sections, "## Highlights\n\n"+strings.Join(iLines, "\n")) + } + md := wave3EduRenderBulletsAndSections(title, bullets, sections) + if md == "" { + return nil + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: md, + } +} + +// ── #225 Universal Schema.org Course / CourseInstance / EducationalOccupationalProgram ──────────── + +func wave3EduExtractSchemaCourseHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + if !hasJSONLDScriptToken(rawHTML) { + return nil + } + lowerProbe := wave3EduLowerProbe(rawHTML, 256*1024) + if !wave3EduContainsAny(lowerProbe, "course", "courseinstance", "educationaloccupationalprogram") { + return nil + } + return wave3EduExtractCourseJSONLDCore(rawHTML, baseURL, extractorID) +} + +func wave3EduNormalizeSchemaTypes(raw any) []string { + var out []string + push := func(s string) { + s = strings.TrimSpace(s) + if idx := strings.LastIndexByte(s, '/'); idx >= 0 { + s = s[idx+1:] + } + if s != "" { + out = append(out, strings.ToLower(s)) + } + } + switch v := raw.(type) { + case string: + push(v) + case []any: + for _, el := range v { + if s, ok := el.(string); ok { + push(s) + } + } + } + return out +} + +func wave3EduExtractCourseJSONLDCore(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + entities := flattenJsonLdEntitiesFullDocGo(rawHTML) + if len(entities) == 0 { + return nil + } + + var primary map[string]any + var primaryKind string + var instances []map[string]any + var programCourses []map[string]any + + for _, ent := range entities { + for _, t := range wave3EduNormalizeSchemaTypes(ent["@type"]) { + switch t { + case "educationaloccupationalprogram": + if primary == nil || primaryKind != "educationaloccupationalprogram" { + primary = ent + primaryKind = "educationaloccupationalprogram" + } + case "course": + if primary == nil { + primary = ent + primaryKind = "course" + } + case "courseinstance": + instances = append(instances, ent) + if primary == nil { + primary = ent + primaryKind = "courseinstance" + } + } + } + } + if primary == nil { + return nil + } + + name := wave3EduPlain(primary["name"], 220) + if name == "" && primaryKind == "courseinstance" { + if cm := wave3EduPlain(primary["courseMode"], 80); cm != "" { + hTitle, _ := wave3EduExtractBestHeadingAndPageTitle(rawHTML) + name = wave3EduFirstNonEmpty(hTitle, "Course Instance ("+cm+")") + } + } + if name == "" { + return nil + } + desc := wave3EduPlain(primary["description"], 1200) + provider := extractPublisherNameSchemaGo(firstNonNilSchemaGo(primary["provider"], primary["publisher"], primary["creator"])) + courseCode := wave3EduPlain(primary["courseCode"], 60) + eduLevel := wave3EduPlain(primary["educationalLevel"], 120) + inLang := wave3EduPlain(primary["inLanguage"], 40) + credential := wave3EduPlain(firstNonNilSchemaGo(primary["educationalCredentialAwarded"], primary["occupationalCredentialAwarded"]), 160) + workload := wave3EduPlain(firstNonNilSchemaGo(primary["courseWorkload"], primary["timeRequired"], primary["timeToComplete"]), 80) + credits := wave3EduPlain(primary["numberOfCredits"], 40) + programType := wave3EduPlain(primary["programType"], 80) + occCategory := wave3EduPlain(primary["occupationalCategory"], 120) + finAid := wave3EduPlain(primary["financialAidEligible"], 40) + + var bullets []string + bullets = append(bullets, "- **Schema Type**: "+primaryKind) + if provider != "" { + bullets = append(bullets, "- **Provider**: "+escapeDeclMarkdownBrackets(provider)) + } + if courseCode != "" { + bullets = append(bullets, "- **Course Code**: `"+courseCode+"`") + } + if eduLevel != "" { + bullets = append(bullets, "- **Level**: "+escapeDeclMarkdownBrackets(eduLevel)) + } + if credential != "" { + bullets = append(bullets, "- **Credential**: "+escapeDeclMarkdownBrackets(credential)) + } + if programType != "" { + bullets = append(bullets, "- **Program Type**: "+escapeDeclMarkdownBrackets(programType)) + } + if occCategory != "" { + bullets = append(bullets, "- **Occupational Category**: "+escapeDeclMarkdownBrackets(occCategory)) + } + if credits != "" { + bullets = append(bullets, "- **Credits**: "+credits) + } + if workload != "" { + bullets = append(bullets, "- **Workload / Duration**: "+escapeDeclMarkdownBrackets(workload)) + } + if inLang != "" { + bullets = append(bullets, "- **Language**: "+inLang) + } + if finAid != "" { + bullets = append(bullets, "- **Financial Aid Eligible**: "+finAid) + } + + // Offers (price + currency validation per Rule 4) + offerObj := wave3EduFirstMap(primary["offers"]) + if offerObj != nil { + if price, ok := wave3EduValidatePrice(offerObj["price"]); ok { + curr := wave3EduValidateCurrency(wave3EduPlain(offerObj["priceCurrency"], 10)) + if curr != "" { + bullets = append(bullets, fmt.Sprintf("- **Price**: %s %s", price, curr)) + } else { + bullets = append(bullets, "- **Price**: "+price) + } + } + } + + // Collect nested hasCourseInstance + if rawInst := primary["hasCourseInstance"]; rawInst != nil { + instances = append(instances, wave3EduAsMapSlice(rawInst)...) + } + // Collect nested hasCourse (EducationalOccupationalProgram) + if rawCourses := primary["hasCourse"]; rawCourses != nil { + programCourses = append(programCourses, wave3EduAsMapSlice(rawCourses)...) + } + + var records []map[string]any + var sections []string + if desc != "" { + sections = append(sections, desc) + } + + if len(instances) > 0 { + var instRows []string + seenInst := make(map[string]bool) + for _, inst := range instances { + mode := wave3EduPlain(inst["courseMode"], 80) + start := wave3EduValidateISODate(wave3EduPlain(inst["startDate"], 64)) + end := wave3EduValidateISODate(wave3EduPlain(inst["endDate"], 64)) + instructor := extractAuthorNameSchemaGo(inst["instructor"]) + if mode == "" && start == "" && end == "" && instructor == "" { + continue + } + key := mode + "|" + start + "|" + end + "|" + instructor + if seenInst[key] { + continue + } + seenInst[key] = true + rec := map[string]any{"kind": "CourseInstance"} + if mode != "" { + rec["courseMode"] = mode + } + if start != "" { + rec["startDate"] = start + } + if end != "" { + rec["endDate"] = end + } + if instructor != "" { + rec["instructor"] = instructor + } + if len(records) < wave3EduMaxRecords { + records = append(records, rec) + } + instRows = append(instRows, fmt.Sprintf("| %s | %s | %s | %s |", + wave3EduFirstNonEmpty(mode, "-"), + wave3EduFirstNonEmpty(start, "-"), + wave3EduFirstNonEmpty(end, "-"), + escapeDeclMarkdownBrackets(wave3EduFirstNonEmpty(instructor, "-")), + )) + } + if len(instRows) > 0 { + sections = append(sections, "## Course Instances\n\n| Mode | Start | End | Instructor |\n|---|---|---|---|\n"+strings.Join(instRows, "\n")) + } + } + + if len(programCourses) > 0 { + var pcRows []string + for _, pc := range programCourses { + cName := wave3EduPlain(pc["name"], 180) + cCode := wave3EduPlain(pc["courseCode"], 40) + if cName == "" { + continue + } + rec := map[string]any{"kind": "Course", "name": cName} + if cCode != "" { + rec["courseCode"] = cCode + } + if len(records) < wave3EduMaxRecords { + records = append(records, rec) + } + pcRows = append(pcRows, fmt.Sprintf("| `%s` | %s |", wave3EduFirstNonEmpty(cCode, "-"), escapeDeclMarkdownBrackets(cName))) + } + if len(pcRows) > 0 { + sections = append(sections, "## Program Courses\n\n| Code | Course |\n|---|---|\n"+strings.Join(pcRows, "\n")) + } + } + + // Standalone CourseInstance top-level bullets when primary is CourseInstance + if primaryKind == "courseinstance" { + if cm := wave3EduPlain(primary["courseMode"], 80); cm != "" { + bullets = append(bullets, "- **Course Mode**: "+cm) + } + if sd := wave3EduValidateISODate(wave3EduPlain(primary["startDate"], 64)); sd != "" { + bullets = append(bullets, "- **Start Date**: "+sd) + } + } + + var links []string + if u := SanitizeSchemaHTTPSURL(primary["url"], baseURL); u != "" { + links = append(links, u) + } + md := wave3EduRenderBulletsAndSections(name, bullets, sections) + if md == "" { + return nil + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: name, + Description: desc, + Markdown: md, + Links: links, + Records: records, + } +} + +func wave3EduFirstMap(v any) map[string]any { + switch x := v.(type) { + case map[string]any: + return x + case []any: + for _, el := range x { + if m, ok := el.(map[string]any); ok { + return m + } + } + } + return nil +} + +func wave3EduAsMapSlice(v any) []map[string]any { + switch x := v.(type) { + case map[string]any: + return []map[string]any{x} + case []any: + var out []map[string]any + for _, el := range x { + if m, ok := el.(map[string]any); ok { + out = append(out, m) + } + } + return out + } + return nil +} diff --git a/internal/extract/wave3_edu_test.go b/internal/extract/wave3_edu_test.go new file mode 100644 index 0000000..983456b --- /dev/null +++ b/internal/extract/wave3_edu_test.go @@ -0,0 +1,245 @@ +package extract + +import ( + "encoding/json" + "strings" + "testing" + "time" + + "github.com/bartrumb/edgefetch/v2/internal/classify" +) + +func TestWave3EduHTMLModesPositiveAndNegative(t *testing.T) { + // 1. #217 finalsite + fsHTML := `Calendar | Greenwich Public Schools

District Calendar

` + fsRes := Wave3EduRunHTML("finalsite_html", fsHTML, "https://www.greenwichschools.org/calendar", "") + if fsRes == nil || fsRes.ExtractorID != "finalsite" { + t.Fatalf("finalsite positive failed: %+v", fsRes) + } + if !strings.Contains(fsRes.Markdown, "Board of Education Regular Meeting") || !strings.Contains(fsRes.Markdown, "2026-27 Academic Calendar PDF") { + t.Fatalf("finalsite missing expected content:\n%s", fsRes.Markdown) + } + if len(fsRes.Records) < 2 { + t.Fatalf("finalsite expected >=2 records, got %d", len(fsRes.Records)) + } + + // 2. #218 blackboard-wcm (SchoolMessenger Presence + Blackboard WCM, and strictly excludes Finalsite /fs/) + bbHTML := `District Calendar | Beverly Hills Unified

Upcoming Events

` + bbRes := Wave3EduRunHTML("blackboard_wcm_html", bbHTML, "https://www.bhusd.org/calendar", "") + if bbRes == nil || bbRes.ExtractorID != "blackboard-wcm" { + t.Fatalf("blackboard-wcm positive failed: %+v", bbRes) + } + if !strings.Contains(bbRes.Markdown, "Winter Robotics Showcase") || !strings.Contains(bbRes.Markdown, "SchoolMessenger Presence") { + t.Fatalf("blackboard-wcm missing expected content:\n%s", bbRes.Markdown) + } + if collision := Wave3EduRunHTML("blackboard_wcm_html", fsHTML, "https://www.greenwichschools.org/calendar", ""); collision != nil { + t.Fatalf("blackboard-wcm must exclude Finalsite /fs/ pages, got %+v", collision) + } + + // 3. #219 edlio-thrillshare (Edlio + Apptegy Thrillshare) + edlioHTML := `News | World Compass Academy

School News

Science Fair Winners Announced

Congratulations to all middle school finalists.

` + edRes := Wave3EduRunHTML("edlio_thrillshare_html", edlioHTML, "https://www.worldcompassacademy.com/apps/news/", "") + if edRes == nil || edRes.ExtractorID != "edlio-thrillshare" || !strings.Contains(edRes.Markdown, "Science Fair Winners Announced") { + t.Fatalf("edlio positive failed: %+v", edRes) + } + apptegyHTML := `News | Windsor C-1

District Feed

` + appRes := Wave3EduRunHTML("edlio_thrillshare_html", apptegyHTML, "https://www.windsorc1.com/o/wcmo/news", "") + if appRes == nil || appRes.ExtractorID != "edlio-thrillshare" || !strings.Contains(appRes.Markdown, "Apptegy Thrillshare") { + t.Fatalf("apptegy positive failed: %+v", appRes) + } + + // 4. #220 acalog (course detail + /ajax/ disallowed guard) + acalogHTML := `Course: CECS 328 - CSULB

CECS 328 - Data Structures and Algorithms

Credits: 3. Prerequisites: CECS 228. Study of trees, graphs, sorting, and algorithm analysis.

CECS 329
` + acRes := Wave3EduRunHTML("acalog_html", acalogHTML, "https://csulb.catalog.acalog.com/preview_course_nopop.php?catoid=12&coid=1397", "") + if acRes == nil || acRes.ExtractorID != "acalog" || !strings.Contains(acRes.Markdown, "CECS 328") || !strings.Contains(acRes.Markdown, "3") { + t.Fatalf("acalog positive failed: %+v", acRes) + } + if ajaxBlocked := Wave3EduRunHTML("acalog_html", acalogHTML, "https://csulb.catalog.acalog.com/ajax/preview_course.php?catoid=12&coid=1397", ""); ajaxBlocked != nil { + t.Fatalf("acalog must reject /ajax/ paths disallowed by robots.txt") + } + + // 5. #221 courseleaf HTML via Round2RunHTML(courseleaf_courses_html) + clHTML := `Computer Science (CSCI) | University of Colorado Boulder

Computer Science (CSCI)

CSCI 1300. Computer Science 1: Starting Computing. 4 Credit Hours.

Teaches techniques for writing computer programs in higher level programming languages.

` + clRes := Round2RunHTML("courseleaf_courses_html", clHTML, "https://catalog.colorado.edu/courses-a-z/csci/", "courseleaf") + if clRes == nil || clRes.ExtractorID != "courseleaf" || !strings.Contains(clRes.Markdown, "CSCI 1300") || len(clRes.Records) != 1 { + t.Fatalf("courseleaf positive failed: %+v", clRes) + } + + // 6. #222 coursedog SSR __NUXT_DATA__ + rendered DOM + cdHTML := `Courses | Pratt Institute Catalog

Courses

ARCH-101 - Architectural Design I

Explore undergraduate and graduate studio offerings.

` + cdRes := Wave3EduRunHTML("coursedog_html", cdHTML, "https://catalog.pratt.edu/courses", "") + if cdRes == nil || cdRes.ExtractorID != "coursedog" || !strings.Contains(cdRes.Markdown, "ARCH-101") || !strings.Contains(cdRes.Markdown, "Architectural Design I") { + t.Fatalf("coursedog positive failed: %+v", cdRes) + } + + // 7. #223 canvas-public-courses HTML (public syllabus vs SAML SSO & 503 maintenance) + canvasHTML := `Introduction to Distributed Systems | Canvas

Introduction to Distributed Systems

Topics include consensus, Raft, Paxos, and fault-tolerant storage.

Weekly lab assignments and readings.

` + cvRes := Wave3EduRunHTML("canvas_public_html", canvasHTML, "https://ocw.instructure.com/courses/44012", "") + if cvRes == nil || cvRes.ExtractorID != "canvas-public-courses" || !strings.Contains(cvRes.Markdown, "Raft, Paxos") { + t.Fatalf("canvas positive failed: %+v", cvRes) + } + samlHTML := `Sign In | University SSO
` + if samlRes := Wave3EduRunHTML("canvas_public_html", samlHTML, "https://canvas.harvard.edu/login/saml", ""); samlRes != nil { + t.Fatalf("canvas SAML redirect must return nil, got %+v", samlRes) + } + csSaml := classify.ClassifyContentStateFull(classify.ContentStateInput{ + Status: 200, + URL: "https://canvas.harvard.edu/courses/101", + FinalURL: "https://fed.harvard.edu/idp/profile/SAML2/Redirect/SSO", + RawHTML: samlHTML, + Markdown: "Sign In", + }) + if csSaml.State != "login_wall" { + t.Fatalf("expected Canvas SAML SSO state login_wall, got %q (%s)", csSaml.State, csSaml.Reason) + } + maint503HTML := `503 Service Unavailable

Free-for-Teacher Platform

This service is temporarily unavailable due to scheduled maintenance. Please check back soon.

` + if mRes := Wave3EduRunHTML("canvas_public_html", maint503HTML, "https://canvas.instructure.com/courses/", ""); mRes != nil { + t.Fatalf("canvas 503 maintenance shell must return nil") + } + cs503 := classify.ClassifyContentStateFull(classify.ContentStateInput{ + Status: 503, + URL: "https://canvas.instructure.com/courses/", + FinalURL: "https://canvas.instructure.com/courses/", + RawHTML: maint503HTML, + Markdown: "Free-for-Teacher Platform temporarily unavailable", + }) + if cs503.State == "active" { + t.Fatalf("canvas 503 maintenance must never classify as active, got %q", cs503.State) + } + + // 8. #224 edx-coursera HTML (Coursera Course JSON-LD) + courseraHTML := `Machine Learning | Coursera

Supervised Machine Learning

` + ecRes := Wave3EduRunHTML("edx_coursera_html", courseraHTML, "https://www.coursera.org/learn/machine-learning", "") + if ecRes == nil || ecRes.ExtractorID != "edx-coursera" || !strings.Contains(ecRes.Markdown, "DeepLearning.AI") { + t.Fatalf("edx-coursera HTML positive failed: %+v", ecRes) + } + + // 9. #225 schema-course (Course, CourseInstance, EducationalOccupationalProgram) + scCourseHTML := `CS50 | Harvard PLL

CS50

` + scRes := Wave3EduRunHTML("schema_course_html", scCourseHTML, "https://pll.harvard.edu/course/cs50-introduction-computer-science", "") + if scRes == nil || scRes.ExtractorID != "schema-course" || !strings.Contains(scRes.Markdown, "Harvard University") || !strings.Contains(scRes.Markdown, "David J. Malan") { + t.Fatalf("schema-course Course failed: %+v", scRes) + } + + scInstHTML := `Spring Cohort

Spring Cohort

` + scInstRes := Wave3EduRunHTML("schema_course_html", scInstHTML, "https://cs.example.edu/instances/spring-2026", "") + if scInstRes == nil || scInstRes.ExtractorID != "schema-course" || !strings.Contains(scInstRes.Markdown, "Hybrid") { + t.Fatalf("schema-course CourseInstance failed: %+v", scInstRes) + } + + scProgHTML := `MS in Computer Science

MSCS

` + scProgRes := Wave3EduRunHTML("schema_course_html", scProgHTML, "https://omscs.gatech.edu/program", "") + if scProgRes == nil || scProgRes.ExtractorID != "schema-course" || !strings.Contains(scProgRes.Markdown, "Georgia Tech") || !strings.Contains(scProgRes.Markdown, "Graduate Algorithms") { + t.Fatalf("schema-course EducationalOccupationalProgram failed: %+v", scProgRes) + } + + // Universal prefilter check: non-Course page must return nil cleanly + nonCourseHTML := `Plain Blog Post

Sunny skies.

` + if got := Wave3EduRunHTML("schema_course_html", nonCourseHTML, "https://news.example.edu/weather", ""); got != nil { + t.Fatalf("schema-course must ignore non-course JSON-LD, got %+v", got) + } +} + +func TestWave3EduJSONAndTextModes(t *testing.T) { + // 1. coursedog_json + cdJSON := `{"data":[{"code":"CSCI 1133","longName":"Introduction to Computing and Programming Concepts","credits":{"creditHours":{"min":4}},"description":"Problem solving and programming principles."}]}` + cdDoc, ok := FormatWave3EduJSONDoc("coursedog_json", []byte(cdJSON), nil, "https://app.coursedog.com/api/v1/cm/umn/courses/search") + if !ok || cdDoc == nil || !strings.Contains(cdDoc.Markdown, "CSCI 1133") { + t.Fatalf("coursedog_json positive failed: ok=%v doc=%+v", ok, cdDoc) + } + if _, okUnauth := FormatWave3EduJSONDoc("coursedog_json", []byte(`{"error":"Unauthenticated"}`), nil, "https://app.coursedog.com/api/v1/cm/umn_umntc/courses/search"); okUnauth { + t.Fatalf("coursedog_json must reject Unauthenticated error") + } + + // 3. canvas_course_json + cvJSON := `{"id":9001,"name":"Linear Algebra","course_code":"MATH 240","workflow_state":"available","term":{"name":"Fall 2026"},"syllabus_body":"

Vector spaces, eigenvalues, and SVD.

"}` + cvDoc, ok := FormatWave3EduJSONDoc("canvas_course_json", []byte(cvJSON), nil, "https://ocw.instructure.com/api/v1/courses/9001") + if !ok || cvDoc == nil || !strings.Contains(cvDoc.Markdown, "MATH 240") || !strings.Contains(cvDoc.Markdown, "Vector spaces") { + t.Fatalf("canvas_course_json positive failed: ok=%v doc=%+v", ok, cvDoc) + } + if _, okErr := FormatWave3EduJSONDoc("canvas_course_json", []byte(`{"errors":[{"message":"user authorization required"}],"status":"unauthorized"}`), nil, "https://canvas.harvard.edu/api/v1/courses/1"); okErr { + t.Fatalf("canvas_course_json must reject unauthorized errors") + } + + // 4. edx_course_json + edxJSON := `{"id":"course-v1:HarvardX+CS50+X","name":"CS50's Introduction to Computer Science","number":"CS50","org":"HarvardX","effort":"10-20 hours per week","pacing":"self","start":"2026-01-01T00:00:00Z","short_description":"An introduction to computer science and the art of programming."}` + edxDoc, ok := FormatWave3EduJSONDoc("edx_course_json", []byte(edxJSON), nil, "https://courses.edx.org/api/courses/v1/courses/course-v1:HarvardX+CS50+X/") + if !ok || edxDoc == nil || !strings.Contains(edxDoc.Markdown, "HarvardX") || !strings.Contains(edxDoc.Markdown, "CS50") { + t.Fatalf("edx_course_json positive failed: ok=%v doc=%+v", ok, edxDoc) + } + // JSON-marshal wrapper smoke check + if encoded, okEnc := FormatWave3EduJSONMode("edx_course_json", []byte(edxJSON), nil, "https://courses.edx.org/api/courses/v1/courses/course-v1:HarvardX+CS50+X/"); !okEnc || !json.Valid([]byte(encoded)) { + t.Fatalf("FormatWave3EduJSONMode failed: ok=%v", okEnc) + } +} + +func TestWave3EduNegativeShellsAcrossAllModes(t *testing.T) { + modes := []string{ + "finalsite_html", + "blackboard_wcm_html", + "edlio_thrillshare_html", + "acalog_html", + "coursedog_html", + "canvas_public_html", + "edx_coursera_html", + "schema_course_html", + } + negShells := []struct { + name string + url string + html string + }{ + {"404-title", "https://school.edu/page", `404 - Page Not Found

Not Found

`}, + {"error-redirect", "https://school.edu/error", `School Portal
Error
`}, + {"maintenance", "https://school.edu/calendar", `Scheduled Maintenance

Site is down for maintenance. Please check back soon.

`}, + {"empty-spa", "https://school.edu/courses", `Loading...
`}, + } + for _, m := range modes { + for _, ns := range negShells { + if res := Wave3EduRunHTML(m, ns.html, ns.url, ""); res != nil { + t.Fatalf("mode %s negative %s returned non-nil: %+v", m, ns.name, res) + } + } + } +} + +func TestWave3EduFinalsiteAfterLargeHeaderExclusion(t *testing.T) { + // #218 blackboard-wcm vs #217 finalsite: >180 KB header padding before /fs/ fsElement markers + pad := strings.Repeat("", 5000) // ~190 KB + html := `District News | Oakridge` + + pad + + `
Header

District News

` + u := "https://www.oakridgek12.org/news" + + if res := Wave3EduRunHTML("blackboard_wcm_html", html, u, ""); res != nil { + t.Fatalf("blackboard_wcm_html must yield to finalsite even when /fs/ appears past 180 KB, got: %+v", res) + } + fsRes := Wave3EduRunHTML("finalsite_html", html, u, "") + if fsRes == nil || fsRes.ExtractorID != "finalsite" { + t.Fatalf("finalsite_html must extract when markers appear past 180 KB, got: %+v", fsRes) + } + declRes, ok := ApplyDeclarativeHTMLExtractor(html, u, "", nil) + if !ok || declRes == nil || declRes.ExtractorID != "finalsite" { + t.Fatalf("ApplyDeclarativeHTMLExtractor expected finalsite, got ok=%v res=%+v", ok, declRes) + } +} + +func TestWave3EduM7CanvasFalsePositiveAndEdlioLatency(t *testing.T) { + // 1. OpenGov /reporting-classic-app/ must NEVER match canvas-public-courses + openGovClassic := `

Financial Transparency

Explore city revenues and expenditures.

` + if res := Wave3EduRunHTML("canvas_public_html", openGovClassic, "https://torranceca.opengov.com/transparency", ""); res != nil { + t.Fatalf("canvas_public_html must NOT false-positive on OpenGov /reporting-classic-app/: %+v", res) + } + + // 2. #219 edlio-thrillshare: 1.5 MiB HTML with heavy

Eastern Upper Peninsula ISD

` + strings.Repeat(``, 10000) + `
Board Meeting Schedule

Serving regional public school districts across the Eastern Upper Peninsula.

` + start := time.Now() + resEd := Wave3EduRunHTML("edlio_thrillshare_html", edlioHTML, "https://www.eupschools.org/", "") + elapsed := time.Since(start) + if resEd == nil || !strings.Contains(resEd.Markdown, "Board Meeting Schedule") { + t.Fatalf("edlio_thrillshare_html 1.5 MiB failed: %+v", resEd) + } + if elapsed > 25*time.Millisecond*time.Duration(extractRaceSlowdown) { + t.Fatalf("edlio_thrillshare_html 1.5 MiB exceeded 25ms latency budget: %v", elapsed) + } +} diff --git a/internal/extract/wave3_finance.go b/internal/extract/wave3_finance.go new file mode 100644 index 0000000..4fc69a6 --- /dev/null +++ b/internal/extract/wave3_finance.go @@ -0,0 +1,2816 @@ +package extract + +import ( + "bytes" + "encoding/csv" + "encoding/json" + "fmt" + stdhtml "html" + "math" + "net/url" + "sort" + "strconv" + "strings" + "time" +) + +const ( + wave3FinanceMaxHTMLBytes = 2 * 1024 * 1024 + wave3FinanceMaxJSONBytes = 4 * 1024 * 1024 + wave3FinanceMaxTextBytes = 2 * 1024 * 1024 + wave3FinanceMaxRecords = 25 +) + +var ( + wave3FinRxNotFoundTitle = newLazyRegexp(`(?i)(?:^|\b)(?:404|410|403\s+forbidden|forbidden|page\s+not\s+found|not\s+found|error\s*404|we\s+couldn'?t\s+find\s+that\s+page|access\s+denied|request\s+(?:rejected|blocked)|could\s+not\s+be\s+satisfied|unauthorized|attention\s+required|just\s+a\s+moment|blocked)(?:\b|$)`) + wave3FinRxMaintTitle = newLazyRegexp(`(?i)(?:scheduled\s+maintenance|temporarily\s+unavailable|service\s+unavailable|site\s+maintenance|under\s+maintenance|502\s+bad\s+gateway|503\s+service|down\s+for\s+maintenance)`) + wave3FinRxErrorTitle = newLazyRegexp(`(?i)^(?:(?:(?:400|401|403|404|406|410|429|500|502|503)\s+)?(?:internal\s+)?server\s+error|runtime\s+error|application\s+error|system\s+error|unexpected\s+error|error\s+page|(?:400|401|403|404|406|410|429|500|502|503|http\s+\d{3})\s+error|error\s+(?:400|401|403|404|406|410|429|500|502|503)|error)(?:\s*[|\-\x{2013}\x{2014}:]\s*.*)?$|^.*(?:\s*[|\-\x{2013}\x{2014}:]\s*error)$`) + wave3FinRxGenericTitle = newLazyRegexp(`(?i)^(?:loading\.{0,3}|home|welcome|search|log\s*in|sign\s*in|emma|msrb\s+emma|ffiec\s+cdr|federal\s+reserve)$`) + wave3FinRxHTMLTag = newLazyRegexp(`<[^>]+>`) + wave3FinRxSpace = newLazyRegexp(`[ \t\r\n]+`) + wave3FinRxTitleTag = newLazyRegexp(`(?is)]*>(.*?)`) + wave3FinRxMetaTag = newLazyRegexp(`(?is)]*>`) + wave3FinRxISODate = newLazyRegexp(`^\d{4}(?:-\d{2}(?:-\d{2})?)?$`) + wave3FinRxSlashDate = newLazyRegexp(`^\d{1,2}/\d{1,2}/\d{4}$`) + wave3FinRxCUSIP = newLazyRegexp(`\b([0-9A-Z]{6}[0-9A-Z*@#]{2}[0-9])\b`) + wave3FinRxCUSIPLabeled = newLazyRegexp(`(?i)\bCUSIP\s*(?:No\.?|Number|#|:)?\s*([0-9A-Za-z]{9})\b`) + wave3FinRxCoupon = newLazyRegexp(`(?i)\b(?:coupon(?:\s+rate)?|interest\s+rate)\s*:?\s*([0-9]+(?:\.[0-9]+)?\s*%)`) + wave3FinRxMaturity = newLazyRegexp(`(?i)\bmaturity\s+date\s*:?\s*([A-Za-z0-9,/\- ]{4,32})`) + wave3FinRxDatedDate = newLazyRegexp(`(?i)\bdated\s+date\s*:?\s*([A-Za-z0-9,/\- ]{4,32})`) + wave3FinRxAmount = newLazyRegexp(`(?i)\b(?:par\s+amount|offering\s+amount|principal\s+amount|issue\s+amount)\s*:?\s*(\$[0-9][0-9,]*(?:\.[0-9]{1,2})?)`) +) + +func init() { + registerWave3FinanceHTMLModes() +} + +// RegisterWave3FinanceHTMLModes registers all Category S Finance & Market Data HTML modes lazily. +func RegisterWave3FinanceHTMLModes() { + registerWave3FinanceHTMLModes() +} + +func registerWave3FinanceHTMLModes() { + for _, mode := range []string{ + "fed_h15_html", + "msrb_emma_html", + "ffiec_cdr_html", + } { + m := mode + RegisterExternalHTMLModeLazy(m, func(rawHTML, baseURL string, _ func() string, extractorID string) *DeclarativePostFetchResult { + return Wave3FinanceRunHTML(m, rawHTML, baseURL, extractorID) + }) + } +} + +// IsWave3FinanceHTMLMode reports whether mode is one of the Category S HTML modes (#387, #391, #392). +func IsWave3FinanceHTMLMode(mode string) bool { + switch mode { + case "fed_h15_html", + "msrb_emma_html", + "ffiec_cdr_html": + return true + default: + return false + } +} + +// IsWave3FinanceJSONMode reports whether mode is one of the Category S JSON formatters (#388, #389, #390, #392). +func IsWave3FinanceJSONMode(mode string) bool { + switch mode { + case "nasdaq_data_link_json", + "market_quotes_json", + "sec_xbrl_frames_json", + "ffiec_cdr_json": + return true + default: + return false + } +} + +// IsWave3FinanceTextMode reports whether mode is one of the Category S text/CSV formatters (#387). +func IsWave3FinanceTextMode(mode string) bool { + return mode == "fed_h15_csv" +} + +func wave3FinDefaultExtractorID(mode string) string { + switch mode { + case "fed_h15_csv", "fed_h15_html": + return "fed-h15-datadownload" + case "nasdaq_data_link_json": + return "nasdaq-data-link" + case "market_quotes_json": + return "market-quotes-pack" + case "sec_xbrl_frames_json": + return "sec-xbrl-frames" + case "msrb_emma_html": + return "msrb-emma" + case "ffiec_cdr_html", "ffiec_cdr_json": + return "ffiec-cdr" + default: + return "" + } +} + +// Wave3FinanceRunHTML executes a Category S HTML extractor and returns DeclarativePostFetchResult. +func Wave3FinanceRunHTML(mode, rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + if !IsWave3FinanceHTMLMode(mode) || len(rawHTML) == 0 || strings.IndexByte(rawHTML, '<') < 0 || strings.IndexByte(rawHTML, '>') < 0 { + return nil + } + if len(rawHTML) > wave3FinanceMaxHTMLBytes { + rawHTML = truncateUTF8SafeFullDocGo(rawHTML, wave3FinanceMaxHTMLBytes) + } + trimmedStart := strings.TrimLeft(rawHTML, " \t\r\n") + if trimmedStart == "" || trimmedStart[0] == '{' || trimmedStart[0] == '[' { + return nil + } + probe := rawHTML + if len(probe) > 65536 { + probe = probe[:65536] + } + probeLower := asciiLowerExtractString(probe) + urlLower := asciiLowerExtractString(baseURL) + + if !wave3FinMatchesModePrefilter(mode, probeLower, urlLower) { + return nil + } + if wave3FinHasCommonNegativeShell(rawHTML, probeLower, urlLower) { + return nil + } + if extractorID == "" { + extractorID = wave3FinDefaultExtractorID(mode) + } + + var res *DeclarativePostFetchResult + switch mode { + case "fed_h15_html": + res = wave3FinExtractFedH15HTML(rawHTML, baseURL, extractorID) + case "msrb_emma_html": + res = wave3FinExtractMSRBEmmaHTML(rawHTML, baseURL, extractorID) + case "ffiec_cdr_html": + res = wave3FinExtractFFIECCDRHTML(rawHTML, baseURL, extractorID) + } + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return nil + } + return wave3FinFinalizePostFetch(res) +} + +// RunWave3FinanceHTMLMode executes a Category S HTML extractor and returns JSON-marshaled DeclarativePostFetchResult. +func RunWave3FinanceHTMLMode(mode, rawHTML, baseURL string) (string, bool) { + res := Wave3FinanceRunHTML(mode, rawHTML, baseURL, wave3FinDefaultExtractorID(mode)) + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return "", false + } + res = sanitizePostFetchResultDeclHTML(res) + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return "", false + } + encoded, err := json.Marshal(res) + if err != nil { + return "", false + } + return string(encoded), true +} + +// FormatWave3FinanceJSONDoc formats a Category S JSON twin payload into DeclarativeFormattedDoc. +func FormatWave3FinanceJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool) { + if !IsWave3FinanceJSONMode(mode) || len(raw) == 0 || len(raw) > wave3FinanceMaxJSONBytes { + return nil, false + } + trimmed := bytes.TrimSpace(bytes.TrimPrefix(raw, []byte("\xEF\xBB\xBF"))) + if len(trimmed) == 0 || (trimmed[0] != '{' && trimmed[0] != '[') { + return nil, false + } + if mode == "sec_xbrl_frames_json" && trimmed[0] == '{' && len(trimmed) > 65_536 { + headProbe := trimmed + if len(headProbe) > 16_384 { + headProbe = headProbe[:16_384] + } + if bytes.Contains(headProbe, []byte(`"facts"`)) && !bytes.Contains(headProbe, []byte(`"data"`)) { + if doc, handled := wave3FinFormatSECCompanyFactsStream(trimmed, origURL); handled && doc != nil && strings.TrimSpace(doc.Markdown) != "" { + return wave3FinFinalizeDoc(doc), true + } + } + } + parsed, ok := decodeJSONWithNumbers(trimmed) + if !ok || parsed == nil { + return nil, false + } + if obj, isObj := parsed.(map[string]any); isObj { + if wave3FinIsGenericJSONError(obj) { + return nil, false + } + } + + var doc *DeclarativeFormattedDoc + var handled bool + switch mode { + case "nasdaq_data_link_json": + doc, handled = wave3FinFormatNasdaqDataLinkJSON(parsed, origURL) + case "market_quotes_json": + doc, handled = wave3FinFormatMarketQuotesJSON(parsed, origURL) + case "sec_xbrl_frames_json": + doc, handled = wave3FinFormatSECXBRLFramesJSON(parsed, origURL) + case "ffiec_cdr_json": + doc, handled = wave3FinFormatFFIECCDRJSON(parsed, origURL) + } + if !handled || doc == nil || strings.TrimSpace(doc.Markdown) == "" { + return nil, false + } + return wave3FinFinalizeDoc(doc), true +} + +// FormatWave3FinanceJSONMode formats a Category S JSON payload and returns JSON-marshaled DeclarativeFormattedDoc. +func FormatWave3FinanceJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool) { + doc, ok := FormatWave3FinanceJSONDoc(mode, raw, params, origURL) + if !ok || doc == nil { + return "", false + } + encoded, err := json.Marshal(doc) + if err != nil { + return "", false + } + return string(encoded), true +} + +// FormatWave3FinanceTextDoc formats a Category S text/CSV twin payload (`fed_h15_csv`). +func FormatWave3FinanceTextDoc(mode, rawBody string, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool) { + if !IsWave3FinanceTextMode(mode) || len(rawBody) == 0 { + return nil, false + } + if len(rawBody) > wave3FinanceMaxTextBytes { + rawBody = truncateUTF8SafeFullDocGo(rawBody, wave3FinanceMaxTextBytes) + } + doc, handled := wave3FinFormatFedH15CSV(rawBody, origURL) + if !handled || doc == nil || strings.TrimSpace(doc.Markdown) == "" { + return nil, false + } + return wave3FinFinalizeDoc(doc), true +} + +// FormatWave3FinanceTextMode formats a Category S text/CSV payload and returns JSON-marshaled DeclarativeFormattedDoc. +func FormatWave3FinanceTextMode(mode, rawBody string, params map[string]string, origURL string) (string, bool) { + doc, ok := FormatWave3FinanceTextDoc(mode, rawBody, params, origURL) + if !ok || doc == nil { + return "", false + } + encoded, err := json.Marshal(doc) + if err != nil { + return "", false + } + return string(encoded), true +} + +// ── Prefilters & Shared Hygiene Helpers ────────────────────────────────────────────────────────── + +func wave3FinMatchesModePrefilter(mode, probeLower, urlLower string) bool { + switch mode { + case "fed_h15_html": + return strings.Contains(urlLower, "federalreserve.gov") || + strings.Contains(probeLower, "h15table") || + strings.Contains(probeLower, "selected interest rates") || + strings.Contains(probeLower, "federal reserve") || + strings.Contains(probeLower, "datadownload") + case "msrb_emma_html": + return strings.Contains(urlLower, "msrb.org") || + strings.Contains(probeLower, "emma.msrb.org") || + strings.Contains(probeLower, "municipal securities rulemaking board") || + strings.Contains(probeLower, "cusip") || + strings.Contains(probeLower, "official statement") + case "ffiec_cdr_html": + return strings.Contains(urlLower, "cdr.ffiec.gov") || + strings.Contains(probeLower, "central data repository") || + strings.Contains(probeLower, "ffiec") || + strings.Contains(probeLower, "managefacsimiles") || + strings.Contains(probeLower, "downloadbulkdata") || + strings.Contains(probeLower, "ubpr") + default: + return false + } +} + +func wave3FinIsNegativeURL(urlLower string) bool { + if urlLower == "" { + return false + } + if strings.Contains(urlLower, "/404") || + strings.Contains(urlLower, "/not-found") || + strings.Contains(urlLower, "/page-not-found") || + strings.Contains(urlLower, "/maintenance") || + strings.Contains(urlLower, "error=true") || + strings.Contains(urlLower, "error=1") { + return true + } + pathOnly := urlLower + if idx := strings.Index(pathOnly, "://"); idx >= 0 { + rest := pathOnly[idx+3:] + if slash := strings.IndexByte(rest, '/'); slash >= 0 { + pathOnly = rest[slash:] + } else { + pathOnly = "/" + } + } + if cut := strings.IndexAny(pathOnly, "?#"); cut >= 0 { + pathOnly = pathOnly[:cut] + } + return strings.HasSuffix(pathOnly, "/error") || + strings.Contains(pathOnly, "/error/") || + strings.HasSuffix(pathOnly, "/error.html") || + strings.HasSuffix(pathOnly, "/error.htm") || + strings.HasSuffix(pathOnly, "/error.aspx") || + strings.HasSuffix(pathOnly, "/login") || + strings.Contains(pathOnly, "/login/") +} + +func wave3FinIsNegativeTitle(title string) bool { + t := strings.TrimSpace(title) + if t == "" { + return false + } + return wave3FinRxNotFoundTitle.MatchString(t) || + wave3FinRxMaintTitle.MatchString(t) || + wave3FinRxErrorTitle.MatchString(t) +} + +func wave3FinExtractTitleBounded(rawHTML string) string { + head := rawHTML + if len(head) > 65536 { + head = head[:65536] + } + if indexFoldASCIIExtract(head, "= 2 { + return wave3FinCleanText(m[1]) + } + return "" +} + +func wave3FinExtractMetaBounded(rawHTML, targetKey string) string { + head := rawHTML + if len(head) > 65536 { + head = head[:65536] + } + if indexFoldASCIIExtract(head, " len(probeLower) && len(rawHTML) <= 256*1024 { + rawLower = asciiLowerExtractString(rawHTML) + } + if (strings.Contains(rawLower, `type="password"`) || strings.Contains(rawLower, `type='password'`)) && + !strings.Contains(rawLower, "h15table") && !strings.Contains(rawLower, "cusip") { + return true + } + + hasRichMarkers := hasJSONLDScriptToken(rawLower) || + strings.Contains(rawLower, " 65536 { + tail := rawHTML[65536:] + hasRichMarkers = indexFoldASCIIExtract(tail, "= 0 || + indexFoldASCIIExtract(tail, "= 0 || + indexFoldASCIIExtract(tail, "application/ld+json") >= 0 + } + if (strings.Contains(probeLower, "challenge-platform") || strings.Contains(probeLower, "cf-turnstile")) && + len(rawHTML) < 16384 && !hasRichMarkers { + return true + } + if wave3HasEmptyRootDivShell(rawHTML, probeLower, true) && !hasRichMarkers { + return true + } + return false +} + +func wave3FinIsGenericJSONError(obj map[string]any) bool { + if len(obj) == 0 { + return true + } + if _, hasQuandlErr := obj["quandl_error"]; hasQuandlErr { + return true + } + if _, hasErrMsg := obj["Error Message"]; hasErrMsg { + return true + } + // Alpha Vantage rate-limit / notice payloads when no data keys exist + if _, hasQuote := obj["Global Quote"]; !hasQuote { + if info := wave3FinPlain(obj["Information"], 240); info != "" && len(obj) <= 2 { + return true + } + if note := wave3FinPlain(obj["Note"], 240); note != "" && len(obj) <= 2 { + return true + } + } + if st := strings.ToUpper(wave3FinPlain(obj["status"], 40)); st == "ERROR" || st == "NOT_AUTHORIZED" || st == "NOT_FOUND" { + return true + } + if succ, ok := obj["success"].(bool); ok && !succ { + return true + } + for _, k := range []string{"error", "errors", "errorMessages", "error_message", "errorMessage", "errorCode", "error_description", "fault"} { + if v, exists := obj[k]; exists && v != nil { + switch tv := v.(type) { + case string: + if strings.TrimSpace(tv) != "" { + return true + } + case []any: + if len(tv) > 0 { + return true + } + case map[string]any: + if len(tv) > 0 { + return true + } + case bool: + if tv { + return true + } + } + } + } + for _, k := range []string{"error_code", "statusCode", "status_code"} { + if f, ok := wave3FinFloatVal(obj[k]); ok && f >= 400 { + return true + } + } + for _, mk := range []string{"message", "detail", "Message"} { + if msg := wave3FinPlain(obj[mk], 240); msg != "" && len(obj) <= 4 { + lm := strings.ToLower(msg) + if strings.Contains(lm, "not found") || + strings.Contains(lm, "unauthorized") || + strings.Contains(lm, "invalid") || + strings.Contains(lm, "forbidden") || + strings.Contains(lm, "supply a token") || + strings.Contains(lm, "not provided") || + strings.Contains(lm, "does not exist") || + strings.Contains(lm, "api key") || + strings.Contains(lm, "subscription") { + return true + } + } + } + return false +} + +func wave3FinIntPtr(n int) *int { return &n } +func wave3FinBoolPtr(b bool) *bool { return &b } + +func wave3FinFinalizeDoc(doc *DeclarativeFormattedDoc) *DeclarativeFormattedDoc { + if doc == nil { + return nil + } + if len(doc.Records) > wave3FinanceMaxRecords { + if doc.Total == nil { + doc.Total = wave3FinIntPtr(len(doc.Records)) + } + doc.Records = doc.Records[:wave3FinanceMaxRecords] + doc.Returned = wave3FinIntPtr(len(doc.Records)) + doc.Truncated = wave3FinBoolPtr(true) + if doc.NextCursor == "" { + doc.NextCursor = strconv.Itoa(len(doc.Records)) + } + } + if sanitized, ok := sanitizeDeclarativeFormattedDocGo(doc); ok && sanitized != nil { + return sanitized + } + return nil +} + +func wave3FinFinalizePostFetch(res *DeclarativePostFetchResult) *DeclarativePostFetchResult { + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return nil + } + if len(res.Records) > wave3FinanceMaxRecords { + if res.Total == nil { + res.Total = wave3FinIntPtr(len(res.Records)) + } + res.Records = res.Records[:wave3FinanceMaxRecords] + res.Returned = wave3FinIntPtr(len(res.Records)) + res.Truncated = wave3FinBoolPtr(true) + if res.NextCursor == "" { + res.NextCursor = strconv.Itoa(len(res.Records)) + } + } + return res +} + +func wave3FinCleanText(s string) string { + if s == "" { + return "" + } + if strings.IndexByte(s, '<') >= 0 { + s = wave3FinRxHTMLTag.ReplaceAllString(s, " ") + } + if strings.IndexByte(s, '&') >= 0 { + s = stdhtml.UnescapeString(s) + } + s = wave3FinRxSpace.ReplaceAllString(s, " ") + return strings.TrimSpace(s) +} + +func wave3FinPlain(v any, maxLen int) string { + switch tv := v.(type) { + case string: + return SanitizeSchemaPlainField(wave3FinCleanText(tv), maxLen) + case json.Number: + return SanitizeSchemaPlainField(tv.String(), maxLen) + case float64: + if math.IsNaN(tv) || math.IsInf(tv, 0) { + return "" + } + return SanitizeSchemaPlainField(strconv.FormatFloat(tv, 'f', -1, 64), maxLen) + case int: + return strconv.Itoa(tv) + case int64: + return strconv.FormatInt(tv, 10) + case bool: + if tv { + return "true" + } + return "false" + default: + return "" + } +} + +func wave3FinFloatVal(v any) (float64, bool) { + switch tv := v.(type) { + case float64: + if math.IsNaN(tv) || math.IsInf(tv, 0) { + return 0, false + } + return tv, true + case int: + return float64(tv), true + case int64: + return float64(tv), true + case json.Number: + f, err := tv.Float64() + if err != nil || math.IsNaN(f) || math.IsInf(f, 0) { + return 0, false + } + return f, true + case string: + s := strings.TrimSpace(strings.ReplaceAll(tv, ",", "")) + if s == "" { + return 0, false + } + f, err := strconv.ParseFloat(s, 64) + if err != nil || math.IsNaN(f) || math.IsInf(f, 0) { + return 0, false + } + return f, true + default: + return 0, false + } +} + +func wave3FinFirstNonEmpty(vals ...string) string { + for _, v := range vals { + if t := strings.TrimSpace(v); t != "" { + return t + } + } + return "" +} + +func wave3FinSafeHTTPSLink(raw, baseURL string) string { + t := strings.TrimSpace(raw) + if t == "" || strings.HasPrefix(t, "#") || strings.HasPrefix(strings.ToLower(t), "javascript:") { + return "" + } + if strings.HasPrefix(t, "https://") { + if isSafePublicTwinURL(t) { + return t + } + return "" + } + if baseURL != "" { + bu, err := url.Parse(baseURL) + if err == nil { + ru, err2 := url.Parse(t) + if err2 == nil { + abs := bu.ResolveReference(ru).String() + if isSafePublicTwinURL(abs) { + return abs + } + } + } + } + return "" +} + +func wave3FinEscapeCell(s string) string { + s = escapeDeclMarkdownBrackets(s) + s = strings.ReplaceAll(s, "\r", " ") + s = strings.ReplaceAll(s, "\n", " ") + s = strings.ReplaceAll(s, "|", "\\|") + return strings.TrimSpace(s) +} + +func wave3FinBuildTable(headers []string, rows [][]string) string { + if len(headers) == 0 || len(rows) == 0 { + return "" + } + var sb strings.Builder + sb.WriteByte('|') + for _, h := range headers { + sb.WriteByte(' ') + sb.WriteString(wave3FinEscapeCell(h)) + sb.WriteString(" |") + } + sb.WriteByte('\n') + sb.WriteByte('|') + for range headers { + sb.WriteString(" --- |") + } + sb.WriteByte('\n') + for _, row := range rows { + sb.WriteByte('|') + for i := range headers { + val := "" + if i < len(row) { + val = wave3FinEscapeCell(row[i]) + } + sb.WriteByte(' ') + sb.WriteString(val) + sb.WriteString(" |") + } + sb.WriteByte('\n') + } + return strings.TrimRight(sb.String(), "\n") +} + +func wave3FinSortedStringKeys(m map[string]any) []string { + keys := make([]string, 0, len(m)) + for k := range m { + keys = append(keys, k) + } + sort.Strings(keys) + return keys +} + +func wave3FinEpochMillisToISO(v any) string { + f, ok := wave3FinFloatVal(v) + if !ok || f <= 0 { + return "" + } + sec := int64(f) + if f > 1e11 { + sec = int64(f / 1000) + } + t := time.Unix(sec, 0).UTC() + if t.Hour() == 0 && t.Minute() == 0 && t.Second() == 0 { + return t.Format("2006-01-02") + } + return t.Format("2006-01-02T15:04:05Z") +} + +func wave3FinIsValidDateToken(s string) bool { + t := strings.TrimSpace(s) + return wave3FinRxISODate.MatchString(t) || wave3FinRxSlashDate.MatchString(t) +} + +// ── #387 Federal Reserve H.15 DataDownload (CSV + HTML) ────────────────────────────────────────── + +func wave3FinFormatFedH15CSV(rawBody, origURL string) (*DeclarativeFormattedDoc, bool) { + trimmed := strings.TrimSpace(strings.TrimPrefix(rawBody, "\xEF\xBB\xBF")) + if trimmed == "" || trimmed[0] == '<' || trimmed[0] == '{' || trimmed[0] == '[' { + return nil, false + } + lowHead := trimmed + if len(lowHead) > 1024 { + lowHead = lowHead[:1024] + } + lowHeadLower := asciiLowerExtractString(lowHead) + if strings.Contains(lowHeadLower, "= 0 { + break + } + } + + if !hasH15Meta || dataStartIdx < 0 || dataStartIdx >= len(records) { + return nil, false + } + + colNames := timeHeaders + if len(colNames) == 0 { + colNames = uniqueIDs + } + if len(colNames) == 0 { + colNames = seriesDescs + } + if len(colNames) == 0 { + return nil, false + } + if len(colNames) > 6 { + colNames = colNames[:6] + } + + type obsRow struct { + date string + vals []string + } + var allObs []obsRow + for _, row := range records[dataStartIdx:] { + if len(row) < 2 { + continue + } + dt := strings.TrimSpace(row[0]) + if !wave3FinIsValidDateToken(dt) { + continue + } + vals := make([]string, len(colNames)) + hasVal := false + for ci := range colNames { + if ci+1 < len(row) { + v := SanitizeSchemaPlainField(row[ci+1], 40) + if v != "" { + vals[ci] = v + hasVal = true + } + } + } + if hasVal { + allObs = append(allObs, obsRow{date: dt, vals: vals}) + } + } + if len(allObs) == 0 { + return nil, false + } + + totalObs := len(allObs) + truncated := false + shownObs := allObs + if len(shownObs) > wave3FinanceMaxRecords { + // Keep the most recent 25 chronological observations. + shownObs = shownObs[len(shownObs)-wave3FinanceMaxRecords:] + truncated = true + } + + title := "Federal Reserve H.15 Selected Interest Rates" + if len(seriesDescs) == 1 && seriesDescs[0] != "" { + title = "Federal Reserve H.15: " + seriesDescs[0] + } else if len(uniqueIDs) == 1 && uniqueIDs[0] != "" { + title = "Federal Reserve H.15: " + uniqueIDs[0] + } + + var md strings.Builder + md.WriteString("# ") + md.WriteString(escapeDeclMarkdownBrackets(title)) + md.WriteString("\n\n") + if len(seriesDescs) > 0 { + var nonEmpty []string + for _, sd := range seriesDescs { + if sd != "" { + nonEmpty = append(nonEmpty, sd) + } + } + if len(nonEmpty) > 0 { + md.WriteString("- **Series:** ") + md.WriteString(escapeDeclMarkdownBrackets(strings.Join(nonEmpty, "; "))) + md.WriteByte('\n') + } + } + if len(uniqueIDs) > 0 { + md.WriteString("- **Unique Identifier:** ") + md.WriteString(escapeDeclMarkdownBrackets(strings.Join(uniqueIDs, ", "))) + md.WriteByte('\n') + } + if len(units) > 0 && units[0] != "" { + md.WriteString("- **Unit:** ") + md.WriteString(escapeDeclMarkdownBrackets(units[0])) + if len(multipliers) > 0 && multipliers[0] != "" && multipliers[0] != "1" { + md.WriteString(" (x") + md.WriteString(escapeDeclMarkdownBrackets(multipliers[0])) + md.WriteByte(')') + } + md.WriteByte('\n') + } + if len(currencies) > 0 && currencies[0] != "" && !strings.EqualFold(currencies[0], "NA") { + md.WriteString("- **Currency:** ") + md.WriteString(escapeDeclMarkdownBrackets(currencies[0])) + md.WriteByte('\n') + } + md.WriteString(fmt.Sprintf("- **Observations:** %d (showing %d)\n\n", totalObs, len(shownObs))) + + headers := append([]string{"Time Period"}, colNames...) + tblRows := make([][]string, 0, len(shownObs)) + outRecords := make([]map[string]any, 0, len(shownObs)) + + for _, o := range shownObs { + rowCells := make([]string, 0, 1+len(colNames)) + rowCells = append(rowCells, o.date) + rec := map[string]any{ + "date": o.date, + } + for ci, cname := range colNames { + val := o.vals[ci] + rowCells = append(rowCells, val) + if len(colNames) == 1 { + rec["value"] = val + rec["series"] = cname + } else { + rec[cname] = val + } + } + if len(uniqueIDs) == 1 && uniqueIDs[0] != "" { + rec["uniqueId"] = uniqueIDs[0] + } + if len(units) == 1 && units[0] != "" { + rec["unit"] = units[0] + } + tblRows = append(tblRows, rowCells) + outRecords = append(outRecords, rec) + } + + md.WriteString("## Observations\n\n") + md.WriteString(wave3FinBuildTable(headers, tblRows)) + + doc := &DeclarativeFormattedDoc{ + Title: title, + Description: fmt.Sprintf("Federal Reserve H.15 interest rate observations (%d records).", totalObs), + Markdown: md.String(), + Records: outRecords, + Total: wave3FinIntPtr(totalObs), + Returned: wave3FinIntPtr(len(outRecords)), + } + if origURL != "" { + if safe := wave3FinSafeHTTPSLink(origURL, ""); safe != "" { + doc.Links = []string{safe} + } + } + if truncated { + doc.Truncated = wave3FinBoolPtr(true) + doc.NextCursor = strconv.Itoa(len(outRecords)) + } + return doc, true +} + +func wave3FinExtractFedH15HTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + doc := ParseHTMLDoc(rawHTML, wave3FinanceMaxHTMLBytes) + if doc == nil { + return nil + } + title := wave3FinFirstNonEmpty( + SanitizeSchemaPlainField(doc.Text("h1"), 200), + wave3FinExtractTitleBounded(rawHTML), + ) + if wave3FinIsNegativeTitle(title) { + return nil + } + + var links []string + seenLinks := make(map[string]bool) + addLink := func(href string) { + if safe := wave3FinSafeHTTPSLink(href, baseURL); safe != "" && !seenLinks[safe] && len(links) < 15 { + seenLinks[safe] = true + links = append(links, safe) + } + } + for _, a := range doc.Select("a", 60) { + href := a.AttrOrEmpty("href") + hl := strings.ToLower(href) + if strings.Contains(hl, "/datadownload/") || strings.Contains(hl, "/releases/h15") { + addLink(href) + } + } + + // Primary path: #h15table on /releases/h15/ + rows := doc.TableRows("#h15table") + if len(rows) < 2 { + rows = doc.TableRows("table") + } + var records []map[string]any + var md strings.Builder + if title == "" { + title = "Federal Reserve H.15 Selected Interest Rates" + } + md.WriteString("# ") + md.WriteString(escapeDeclMarkdownBrackets(title)) + md.WriteString("\n\n") + + totalRows := 0 + if len(rows) >= 2 && len(rows[0]) >= 2 { + hdr := rows[0] + cols := len(hdr) + if cols > 8 { + cols = 8 + } + cleanHdr := make([]string, cols) + for i := 0; i < cols; i++ { + cleanHdr[i] = SanitizeSchemaPlainField(hdr[i], 60) + if cleanHdr[i] == "" { + cleanHdr[i] = fmt.Sprintf("Col %d", i+1) + } + } + var tblRows [][]string + for _, r := range rows[1:] { + if len(r) == 0 { + continue + } + dr := make([]string, cols) + nonEmpty := false + for c := 0; c < cols; c++ { + if c < len(r) { + dr[c] = SanitizeSchemaPlainField(r[c], 120) + if dr[c] != "" { + nonEmpty = true + } + } + } + if !nonEmpty { + continue + } + totalRows++ + if len(tblRows) < wave3FinanceMaxRecords { + tblRows = append(tblRows, dr) + rec := map[string]any{} + for c, hName := range cleanHdr { + key := hName + if c == 0 { + key = "instrument" + } + if dr[c] != "" { + rec[key] = dr[c] + } + } + records = append(records, rec) + } + } + if len(tblRows) > 0 { + md.WriteString("## Selected Interest Rates\n\n") + md.WriteString(wave3FinBuildTable(cleanHdr, tblRows)) + md.WriteString("\n\n") + } + } + + // Secondary path: Choose.aspx selection options + if len(records) == 0 { + var options []string + for _, opt := range doc.Select("select option", 40) { + txt := SanitizeSchemaPlainField(opt.Text(), 140) + val := SanitizeSchemaPlainField(opt.AttrOrEmpty("value"), 80) + if txt != "" { + options = append(options, txt) + if len(records) < wave3FinanceMaxRecords { + rec := map[string]any{"label": txt} + if val != "" { + rec["value"] = val + } + records = append(records, rec) + } + } + } + if len(options) > 0 { + totalRows = len(options) + md.WriteString("## Available Data Download Options\n\n") + for i, o := range options { + if i >= wave3FinanceMaxRecords { + break + } + md.WriteString("- ") + md.WriteString(escapeDeclMarkdownBrackets(o)) + md.WriteByte('\n') + } + md.WriteByte('\n') + } + } + + if len(records) == 0 { + // Require at least meaningful content from H.15 release page if no table/options matched + if !strings.Contains(asciiLowerExtractString(rawHTML), "h15") && !strings.Contains(asciiLowerExtractString(rawHTML), "interest rate") { + return nil + } + ext := ExtractHTMLDocumentFull(rawHTML, FullExtractOptions{ + BaseURL: baseURL, + OnlyMainContent: true, + IncludeImages: false, + SkipUniversalExtractors: true, + SkipPlainText: true, + }) + body := strings.TrimSpace(ext.Markdown) + if len(body) < 80 { + return nil + } + md.WriteString(body) + } + + if len(links) > 0 { + md.WriteString("## Data Download Links\n\n") + for _, l := range links { + md.WriteString("- ") + md.WriteString(l) + md.WriteByte('\n') + } + } + + res := &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Markdown: strings.TrimSpace(md.String()), + Links: links, + Records: records, + } + if totalRows > 0 { + res.Total = wave3FinIntPtr(totalRows) + res.Returned = wave3FinIntPtr(len(records)) + if totalRows > len(records) { + res.Truncated = wave3FinBoolPtr(true) + res.NextCursor = strconv.Itoa(len(records)) + } + } + return res +} + +// ── #388 Nasdaq Data Link JSON ─────────────────────────────────────────────────────────────────── + +func wave3FinFormatNasdaqDataLinkJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + obj, ok := parsed.(map[string]any) + if !ok { + return nil, false + } + + // Case 1: /api/v3/datasets/{db}/{code}.json -> {"dataset": {...}} + // or /api/v3/datasets/{db}/{code}/data.json -> {"dataset_data": {...}} + var ds map[string]any + if m, isMap := obj["dataset"].(map[string]any); isMap { + ds = m + } else if m, isMap := obj["dataset_data"].(map[string]any); isMap { + ds = m + } + if ds != nil { + dbCode := wave3FinPlain(ds["database_code"], 60) + dsCode := wave3FinPlain(ds["dataset_code"], 80) + name := wave3FinPlain(ds["name"], 220) + desc := wave3FinPlain(ds["description"], 400) + freq := wave3FinPlain(ds["frequency"], 40) + newest := wave3FinPlain(ds["newest_available_date"], 30) + oldest := wave3FinPlain(ds["oldest_available_date"], 30) + + rawCols, _ := ds["column_names"].([]any) + rawRows, _ := ds["data"].([]any) + if len(rawCols) == 0 && len(rawRows) == 0 { + return nil, false + } + cols := make([]string, 0, len(rawCols)) + for _, c := range rawCols { + cols = append(cols, wave3FinFirstNonEmpty(wave3FinPlain(c, 60), "Value")) + } + if len(cols) == 0 && len(rawRows) > 0 { + if firstArr, ok := rawRows[0].([]any); ok { + for i := range firstArr { + if i == 0 { + cols = append(cols, "Date") + } else { + cols = append(cols, fmt.Sprintf("Col %d", i)) + } + } + } + } + if len(cols) == 0 { + return nil, false + } + + title := name + if title == "" && dbCode != "" && dsCode != "" { + title = dbCode + "/" + dsCode + } else if title == "" { + title = "Nasdaq Data Link Dataset" + } + if dbCode != "" && dsCode != "" && !strings.Contains(title, dbCode+"/"+dsCode) { + title = fmt.Sprintf("%s (%s/%s)", title, dbCode, dsCode) + } + + var md strings.Builder + md.WriteString("# ") + md.WriteString(escapeDeclMarkdownBrackets(title)) + md.WriteString("\n\n") + if dbCode != "" || dsCode != "" { + md.WriteString("- **Dataset:** `") + md.WriteString(sanitizeDeclInlineCodeVal(wave3FinFirstNonEmpty(dbCode+"/"+dsCode, dsCode))) + md.WriteString("`\n") + } + if freq != "" { + md.WriteString("- **Frequency:** ") + md.WriteString(escapeDeclMarkdownBrackets(freq)) + md.WriteByte('\n') + } + if oldest != "" || newest != "" { + md.WriteString("- **Date Range:** ") + md.WriteString(escapeDeclMarkdownBrackets(wave3FinFirstNonEmpty(oldest, "?"))) + md.WriteString(" to ") + md.WriteString(escapeDeclMarkdownBrackets(wave3FinFirstNonEmpty(newest, "?"))) + md.WriteByte('\n') + } + if desc != "" { + md.WriteString("- **Description:** ") + md.WriteString(escapeDeclMarkdownBrackets(desc)) + md.WriteByte('\n') + } + + maxCols := len(cols) + if maxCols > 8 { + maxCols = 8 + } + hdr := cols[:maxCols] + total := len(rawRows) + var tblRows [][]string + var records []map[string]any + for i, rr := range rawRows { + if i >= wave3FinanceMaxRecords { + break + } + arr, ok := rr.([]any) + if !ok { + continue + } + rowCells := make([]string, maxCols) + rec := map[string]any{} + for c := 0; c < maxCols && c < len(arr); c++ { + val := wave3FinPlain(arr[c], 120) + rowCells[c] = val + rec[hdr[c]] = val + } + tblRows = append(tblRows, rowCells) + records = append(records, rec) + } + if len(tblRows) > 0 { + md.WriteString("\n## Observations\n\n") + md.WriteString(wave3FinBuildTable(hdr, tblRows)) + } + doc := &DeclarativeFormattedDoc{ + Title: title, + Description: desc, + Markdown: md.String(), + Records: records, + Total: wave3FinIntPtr(total), + Returned: wave3FinIntPtr(len(records)), + } + if total > len(records) { + doc.Truncated = wave3FinBoolPtr(true) + doc.NextCursor = strconv.Itoa(len(records)) + } + if safe := wave3FinSafeHTTPSLink(origURL, ""); safe != "" { + doc.Links = []string{safe} + } + return doc, true + } + + // Case 2: /api/v3/datatables/{vendor}/{table}.json -> {"datatable": {"data": [...], "columns": [...]}} + if dt, isDT := obj["datatable"].(map[string]any); isDT { + rawCols, _ := dt["columns"].([]any) + rawRows, _ := dt["data"].([]any) + if len(rawCols) == 0 && len(rawRows) == 0 { + return nil, false + } + cols := make([]string, 0, len(rawCols)) + for _, c := range rawCols { + if cm, ok := c.(map[string]any); ok { + cols = append(cols, wave3FinFirstNonEmpty(wave3FinPlain(cm["name"], 60), "col")) + } + } + if len(cols) == 0 { + return nil, false + } + maxCols := len(cols) + if maxCols > 8 { + maxCols = 8 + } + hdr := cols[:maxCols] + total := len(rawRows) + var tblRows [][]string + var records []map[string]any + for i, rr := range rawRows { + if i >= wave3FinanceMaxRecords { + break + } + arr, ok := rr.([]any) + if !ok { + continue + } + rowCells := make([]string, maxCols) + rec := map[string]any{} + for c := 0; c < maxCols && c < len(arr); c++ { + val := wave3FinPlain(arr[c], 120) + rowCells[c] = val + rec[hdr[c]] = val + } + tblRows = append(tblRows, rowCells) + records = append(records, rec) + } + if len(tblRows) == 0 { + return nil, false + } + title := "Nasdaq Data Link Datatable" + if u, err := url.Parse(origURL); err == nil { + parts := strings.Split(strings.Trim(u.Path, "/"), "/") + if len(parts) >= 5 { + tName := strings.TrimSuffix(parts[4], ".json") + title = fmt.Sprintf("Nasdaq Data Link Datatable: %s/%s", parts[3], tName) + } + } + var md strings.Builder + md.WriteString("# ") + md.WriteString(escapeDeclMarkdownBrackets(title)) + md.WriteString("\n\n") + md.WriteString(fmt.Sprintf("- **Columns:** %s\n", escapeDeclMarkdownBrackets(strings.Join(cols, ", ")))) + md.WriteString(fmt.Sprintf("- **Rows Returned:** %d\n\n", len(records))) + md.WriteString("## Table Rows\n\n") + md.WriteString(wave3FinBuildTable(hdr, tblRows)) + + nextCursor := "" + if meta, ok := obj["meta"].(map[string]any); ok { + nextCursor = wave3FinPlain(meta["next_cursor_id"], 120) + } + doc := &DeclarativeFormattedDoc{ + Title: title, + Markdown: md.String(), + Records: records, + Total: wave3FinIntPtr(total), + Returned: wave3FinIntPtr(len(records)), + } + if total > len(records) || nextCursor != "" { + doc.Truncated = wave3FinBoolPtr(true) + doc.NextCursor = wave3FinFirstNonEmpty(nextCursor, strconv.Itoa(len(records))) + } + if safe := wave3FinSafeHTTPSLink(origURL, ""); safe != "" { + doc.Links = []string{safe} + } + return doc, true + } + + return nil, false +} + +// ── #389 Market Quotes Pack JSON (Alpha Vantage, Polygon/Massive, Tiingo) ──────────────────────── + +func wave3FinFormatMarketQuotesJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + urlLower := asciiLowerExtractString(origURL) + + // Tiingo daily prices / IEX root array + if arr, isArr := parsed.([]any); isArr { + return wave3FinFormatTiingoArrayJSON(arr, origURL) + } + + obj, ok := parsed.(map[string]any) + if !ok { + return nil, false + } + + // 1. Alpha Vantage Global Quote + if gq, ok := obj["Global Quote"].(map[string]any); ok && len(gq) > 0 { + sym := wave3FinPlain(gq["01. symbol"], 32) + open := wave3FinPlain(gq["02. open"], 32) + high := wave3FinPlain(gq["03. high"], 32) + low := wave3FinPlain(gq["04. low"], 32) + price := wave3FinPlain(gq["05. price"], 32) + vol := wave3FinPlain(gq["06. volume"], 32) + day := wave3FinPlain(gq["07. latest trading day"], 32) + prev := wave3FinPlain(gq["08. previous close"], 32) + chg := wave3FinPlain(gq["09. change"], 32) + chgPct := wave3FinPlain(gq["10. change percent"], 32) + if sym == "" || price == "" { + return nil, false + } + title := fmt.Sprintf("%s Global Quote — Alpha Vantage", sym) + var md strings.Builder + md.WriteString("# ") + md.WriteString(escapeDeclMarkdownBrackets(title)) + md.WriteString("\n\n") + md.WriteString(fmt.Sprintf("- **Symbol:** `%s`\n", sanitizeDeclInlineCodeVal(sym))) + md.WriteString(fmt.Sprintf("- **Price:** %s\n", escapeDeclMarkdownBrackets(price))) + if day != "" { + md.WriteString(fmt.Sprintf("- **Latest Trading Day:** %s\n", escapeDeclMarkdownBrackets(day))) + } + if chg != "" || chgPct != "" { + md.WriteString(fmt.Sprintf("- **Change:** %s (%s)\n", escapeDeclMarkdownBrackets(chg), escapeDeclMarkdownBrackets(chgPct))) + } + md.WriteString("\n") + md.WriteString(wave3FinBuildTable( + []string{"Symbol", "Open", "High", "Low", "Price", "Prev Close", "Volume", "Date"}, + [][]string{{sym, open, high, low, price, prev, vol, day}}, + )) + rec := map[string]any{ + "provider": "alphavantage", + "symbol": sym, + "price": price, + "open": open, + "high": high, + "low": low, + "previousClose": prev, + "volume": vol, + "latestTradingDay": day, + "change": chg, + "changePercent": chgPct, + } + return &DeclarativeFormattedDoc{ + Title: title, + Description: fmt.Sprintf("Alpha Vantage global quote for %s: %s", sym, price), + Markdown: md.String(), + Records: []map[string]any{rec}, + Total: wave3FinIntPtr(1), + Returned: wave3FinIntPtr(1), + }, true + } + + // 2. Alpha Vantage Time Series + var tsKey string + var tsMap map[string]any + for k, v := range obj { + if strings.HasPrefix(k, "Time Series") || strings.HasPrefix(k, "Weekly ") || strings.HasPrefix(k, "Monthly ") { + if m, ok := v.(map[string]any); ok && len(m) > 0 { + tsKey = k + tsMap = m + break + } + } + } + if tsMap != nil { + sym := "" + info := "" + lastRef := "" + if meta, ok := obj["Meta Data"].(map[string]any); ok { + sym = wave3FinPlain(meta["2. Symbol"], 32) + info = wave3FinPlain(meta["1. Information"], 120) + lastRef = wave3FinPlain(meta["3. Last Refreshed"], 40) + } + dates := wave3FinSortedStringKeys(tsMap) + // Sort descending so newest bars come first. + sort.Sort(sort.Reverse(sort.StringSlice(dates))) + total := len(dates) + if len(dates) > wave3FinanceMaxRecords { + dates = dates[:wave3FinanceMaxRecords] + } + title := fmt.Sprintf("%s %s — Alpha Vantage", wave3FinFirstNonEmpty(sym, "Market"), tsKey) + var md strings.Builder + md.WriteString("# ") + md.WriteString(escapeDeclMarkdownBrackets(title)) + md.WriteString("\n\n") + if info != "" { + md.WriteString("- **Series:** ") + md.WriteString(escapeDeclMarkdownBrackets(info)) + md.WriteByte('\n') + } + if lastRef != "" { + md.WriteString("- **Last Refreshed:** ") + md.WriteString(escapeDeclMarkdownBrackets(lastRef)) + md.WriteByte('\n') + } + md.WriteByte('\n') + var tblRows [][]string + var records []map[string]any + for _, dt := range dates { + bar, ok := tsMap[dt].(map[string]any) + if !ok { + continue + } + o := wave3FinPlain(bar["1. open"], 24) + h := wave3FinPlain(bar["2. high"], 24) + l := wave3FinPlain(bar["3. low"], 24) + c := wave3FinPlain(bar["4. close"], 24) + v := wave3FinPlain(bar["5. volume"], 32) + tblRows = append(tblRows, []string{dt, o, h, l, c, v}) + records = append(records, map[string]any{ + "provider": "alphavantage", + "symbol": sym, + "date": dt, + "open": o, + "high": h, + "low": l, + "close": c, + "volume": v, + }) + } + if len(records) == 0 { + return nil, false + } + md.WriteString(wave3FinBuildTable([]string{"Date", "Open", "High", "Low", "Close", "Volume"}, tblRows)) + doc := &DeclarativeFormattedDoc{ + Title: title, + Markdown: md.String(), + Records: records, + Total: wave3FinIntPtr(total), + Returned: wave3FinIntPtr(len(records)), + } + if total > len(records) { + doc.Truncated = wave3FinBoolPtr(true) + doc.NextCursor = strconv.Itoa(len(records)) + } + return doc, true + } + + // 3. Polygon / Massive ("results" array or object) + if resRaw, hasRes := obj["results"]; hasRes && resRaw != nil { + provider := "polygon" + if strings.Contains(urlLower, "api.massive.com") { + provider = "massive" + } + providerLabel := "Polygon.io" + if provider == "massive" { + providerLabel = "Massive" + } + + // 3a. Single reference ticker object + if resObj, isResObj := resRaw.(map[string]any); isResObj && len(resObj) > 0 { + tkr := wave3FinPlain(resObj["ticker"], 32) + name := wave3FinPlain(resObj["name"], 200) + if tkr == "" && name == "" { + return nil, false + } + title := fmt.Sprintf("%s (%s) — %s", wave3FinFirstNonEmpty(name, tkr), tkr, providerLabel) + var md strings.Builder + md.WriteString("# ") + md.WriteString(escapeDeclMarkdownBrackets(title)) + md.WriteString("\n\n") + for _, pair := range [][2]string{ + {"Ticker", tkr}, + {"Market", wave3FinPlain(resObj["market"], 40)}, + {"Primary Exchange", wave3FinPlain(resObj["primary_exchange"], 40)}, + {"Currency", strings.ToUpper(wave3FinPlain(resObj["currency_name"], 20))}, + {"Market Cap", wave3FinPlain(resObj["market_cap"], 40)}, + {"SIC Description", wave3FinPlain(resObj["sic_description"], 120)}, + } { + if pair[1] != "" { + md.WriteString("- **") + md.WriteString(pair[0]) + md.WriteString(":** ") + md.WriteString(escapeDeclMarkdownBrackets(pair[1])) + md.WriteByte('\n') + } + } + if desc := wave3FinPlain(resObj["description"], 400); desc != "" { + md.WriteString("\n") + md.WriteString(escapeDeclMarkdownBlock(desc)) + md.WriteByte('\n') + } + rec := map[string]any{ + "provider": provider, + "ticker": tkr, + "name": name, + "market": wave3FinPlain(resObj["market"], 40), + "primaryExchange": wave3FinPlain(resObj["primary_exchange"], 40), + "currency": strings.ToUpper(wave3FinPlain(resObj["currency_name"], 20)), + } + return &DeclarativeFormattedDoc{ + Title: title, + Description: wave3FinPlain(resObj["description"], 300), + Markdown: strings.TrimSpace(md.String()), + Records: []map[string]any{rec}, + Total: wave3FinIntPtr(1), + Returned: wave3FinIntPtr(1), + }, true + } + + // 3b. Aggregate bars or ticker search array + if resArr, isArr := resRaw.([]any); isArr && len(resArr) > 0 { + topTicker := wave3FinPlain(obj["ticker"], 32) + total := len(resArr) + if cnt, ok := wave3FinFloatVal(obj["resultsCount"]); ok && int(cnt) > total { + total = int(cnt) + } + var tblRows [][]string + var records []map[string]any + isAggs := false + for i, item := range resArr { + if i >= wave3FinanceMaxRecords { + break + } + m, ok := item.(map[string]any) + if !ok { + continue + } + if _, hasClose := m["c"]; hasClose { + isAggs = true + dt := wave3FinEpochMillisToISO(m["t"]) + tkr := wave3FinFirstNonEmpty(wave3FinPlain(m["T"], 32), topTicker) + o := wave3FinPlain(m["o"], 24) + h := wave3FinPlain(m["h"], 24) + l := wave3FinPlain(m["l"], 24) + c := wave3FinPlain(m["c"], 24) + v := wave3FinPlain(m["v"], 32) + vw := wave3FinPlain(m["vw"], 24) + tblRows = append(tblRows, []string{dt, o, h, l, c, v, vw}) + records = append(records, map[string]any{ + "provider": provider, + "ticker": tkr, + "date": dt, + "open": o, + "high": h, + "low": l, + "close": c, + "volume": v, + "vwap": vw, + }) + } else if tkr := wave3FinPlain(m["ticker"], 32); tkr != "" { + name := wave3FinPlain(m["name"], 140) + mkt := wave3FinPlain(m["market"], 40) + ex := wave3FinPlain(m["primary_exchange"], 40) + tblRows = append(tblRows, []string{tkr, name, mkt, ex}) + records = append(records, map[string]any{ + "provider": provider, + "ticker": tkr, + "name": name, + "market": mkt, + "primaryExchange": ex, + }) + } + } + if len(records) == 0 { + return nil, false + } + title := fmt.Sprintf("%s Market Results — %s", wave3FinFirstNonEmpty(topTicker, "Reference"), providerLabel) + var md strings.Builder + md.WriteString("# ") + md.WriteString(escapeDeclMarkdownBrackets(title)) + md.WriteString("\n\n") + if topTicker != "" { + md.WriteString(fmt.Sprintf("- **Ticker:** `%s`\n", sanitizeDeclInlineCodeVal(topTicker))) + } + md.WriteString(fmt.Sprintf("- **Results:** %d\n\n", total)) + if isAggs { + md.WriteString(wave3FinBuildTable([]string{"Date", "Open", "High", "Low", "Close", "Volume", "VWAP"}, tblRows)) + } else { + md.WriteString(wave3FinBuildTable([]string{"Ticker", "Name", "Market", "Exchange"}, tblRows)) + } + doc := &DeclarativeFormattedDoc{ + Title: title, + Markdown: md.String(), + Records: records, + Total: wave3FinIntPtr(total), + Returned: wave3FinIntPtr(len(records)), + } + if total > len(records) { + doc.Truncated = wave3FinBoolPtr(true) + doc.NextCursor = strconv.Itoa(len(records)) + } + return doc, true + } + } + + // 4. Tiingo ticker metadata object + if tkr := wave3FinPlain(obj["ticker"], 32); tkr != "" { + name := wave3FinPlain(obj["name"], 200) + ex := wave3FinPlain(obj["exchangeCode"], 40) + start := wave3FinPlain(obj["startDate"], 30) + end := wave3FinPlain(obj["endDate"], 30) + desc := wave3FinPlain(obj["description"], 400) + title := fmt.Sprintf("%s (%s) — Tiingo", wave3FinFirstNonEmpty(name, tkr), strings.ToUpper(tkr)) + var md strings.Builder + md.WriteString("# ") + md.WriteString(escapeDeclMarkdownBrackets(title)) + md.WriteString("\n\n") + for _, pair := range [][2]string{ + {"Ticker", strings.ToUpper(tkr)}, + {"Exchange", ex}, + {"Start Date", start}, + {"End Date", end}, + } { + if pair[1] != "" { + md.WriteString("- **") + md.WriteString(pair[0]) + md.WriteString(":** ") + md.WriteString(escapeDeclMarkdownBrackets(pair[1])) + md.WriteByte('\n') + } + } + if desc != "" { + md.WriteString("\n") + md.WriteString(escapeDeclMarkdownBlock(desc)) + } + return &DeclarativeFormattedDoc{ + Title: title, + Description: desc, + Markdown: strings.TrimSpace(md.String()), + Records: []map[string]any{{ + "provider": "tiingo", + "ticker": strings.ToUpper(tkr), + "name": name, + "exchangeCode": ex, + "startDate": start, + "endDate": end, + }}, + Total: wave3FinIntPtr(1), + Returned: wave3FinIntPtr(1), + }, true + } + + return nil, false +} + +func wave3FinFormatTiingoArrayJSON(arr []any, origURL string) (*DeclarativeFormattedDoc, bool) { + if len(arr) == 0 { + return nil, false + } + inferredTicker := "" + if u, err := url.Parse(origURL); err == nil { + parts := strings.Split(strings.Trim(u.Path, "/"), "/") + if len(parts) >= 3 && strings.EqualFold(parts[0], "tiingo") { + inferredTicker = strings.ToUpper(parts[2]) + } + } + + total := len(arr) + var tblRows [][]string + var records []map[string]any + for i, item := range arr { + if i >= wave3FinanceMaxRecords { + break + } + m, ok := item.(map[string]any) + if !ok { + continue + } + dt := wave3FinFirstNonEmpty(wave3FinPlain(m["date"], 32), wave3FinPlain(m["timestamp"], 32)) + if len(dt) > 10 && strings.HasSuffix(dt, "T00:00:00.000Z") { + dt = dt[:10] + } + tkr := wave3FinFirstNonEmpty(strings.ToUpper(wave3FinPlain(m["ticker"], 32)), inferredTicker) + o := wave3FinPlain(m["open"], 24) + h := wave3FinPlain(m["high"], 24) + l := wave3FinPlain(m["low"], 24) + c := wave3FinFirstNonEmpty(wave3FinPlain(m["close"], 24), wave3FinPlain(m["tngoLast"], 24), wave3FinPlain(m["last"], 24)) + adj := wave3FinPlain(m["adjClose"], 24) + v := wave3FinPlain(m["volume"], 32) + if dt == "" && c == "" { + continue + } + tblRows = append(tblRows, []string{dt, o, h, l, c, adj, v}) + rec := map[string]any{ + "provider": "tiingo", + "date": dt, + "open": o, + "high": h, + "low": l, + "close": c, + "volume": v, + } + if tkr != "" { + rec["ticker"] = tkr + } + if adj != "" { + rec["adjClose"] = adj + } + records = append(records, rec) + } + if len(records) == 0 { + return nil, false + } + + title := fmt.Sprintf("%s Market Prices — Tiingo", wave3FinFirstNonEmpty(inferredTicker, "Tiingo")) + var md strings.Builder + md.WriteString("# ") + md.WriteString(escapeDeclMarkdownBrackets(title)) + md.WriteString("\n\n") + if inferredTicker != "" { + md.WriteString(fmt.Sprintf("- **Ticker:** `%s`\n", sanitizeDeclInlineCodeVal(inferredTicker))) + } + md.WriteString(fmt.Sprintf("- **Observations:** %d\n\n", total)) + md.WriteString(wave3FinBuildTable([]string{"Date", "Open", "High", "Low", "Close", "Adj Close", "Volume"}, tblRows)) + + doc := &DeclarativeFormattedDoc{ + Title: title, + Markdown: md.String(), + Records: records, + Total: wave3FinIntPtr(total), + Returned: wave3FinIntPtr(len(records)), + } + if total > len(records) { + doc.Truncated = wave3FinBoolPtr(true) + doc.NextCursor = strconv.Itoa(len(records)) + } + return doc, true +} + +// ── #390 SEC EDGAR XBRL Frames / CompanyConcept / CompanyFacts JSON ───────────────────────────── + +func wave3FinFormatSECXBRLFramesJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + obj, ok := parsed.(map[string]any) + if !ok { + return nil, false + } + + // 1. /api/xbrl/frames/{taxonomy}/{tag}/{unit}/{period}.json + if dataArr, hasData := obj["data"].([]any); hasData { + taxonomy := wave3FinPlain(obj["taxonomy"], 40) + tag := wave3FinPlain(obj["tag"], 120) + label := wave3FinPlain(obj["label"], 200) + desc := wave3FinPlain(obj["description"], 400) + ccp := wave3FinPlain(obj["ccp"], 40) + uom := wave3FinPlain(obj["uom"], 40) + if tag == "" && len(dataArr) == 0 { + return nil, false + } + totalPts := len(dataArr) + if pts, ok := wave3FinFloatVal(obj["pts"]); ok && int(pts) > totalPts { + totalPts = int(pts) + } + title := fmt.Sprintf("%s (%s) — SEC XBRL Frame %s", wave3FinFirstNonEmpty(label, tag, "XBRL Frame"), tag, ccp) + title = strings.TrimSpace(title) + + var tblRows [][]string + var records []map[string]any + for i, item := range dataArr { + if i >= wave3FinanceMaxRecords { + break + } + m, ok := item.(map[string]any) + if !ok { + continue + } + entity := wave3FinPlain(m["entityName"], 160) + cik := wave3FinPlain(m["cik"], 20) + loc := wave3FinPlain(m["loc"], 20) + end := wave3FinPlain(m["end"], 24) + val := wave3FinPlain(m["val"], 40) + accn := wave3FinPlain(m["accn"], 40) + tblRows = append(tblRows, []string{entity, cik, loc, end, val, accn}) + records = append(records, map[string]any{ + "entityName": entity, + "cik": cik, + "loc": loc, + "end": end, + "val": val, + "accn": accn, + "uom": uom, + "tag": tag, + }) + } + if len(records) == 0 { + return nil, false + } + var md strings.Builder + md.WriteString("# ") + md.WriteString(escapeDeclMarkdownBrackets(title)) + md.WriteString("\n\n") + for _, pair := range [][2]string{ + {"Taxonomy", taxonomy}, + {"Tag", tag}, + {"Period", ccp}, + {"Unit", uom}, + {"Data Points", strconv.Itoa(totalPts)}, + } { + if pair[1] != "" { + md.WriteString("- **") + md.WriteString(pair[0]) + md.WriteString(":** ") + md.WriteString(escapeDeclMarkdownBrackets(pair[1])) + md.WriteByte('\n') + } + } + if desc != "" { + md.WriteString("- **Description:** ") + md.WriteString(escapeDeclMarkdownBrackets(desc)) + md.WriteByte('\n') + } + md.WriteString("\n## Filers (Bounded Sample)\n\n") + md.WriteString(wave3FinBuildTable([]string{"Entity", "CIK", "Location", "Period End", "Value", "Accession"}, tblRows)) + + doc := &DeclarativeFormattedDoc{ + Title: title, + Description: desc, + Markdown: md.String(), + Records: records, + Total: wave3FinIntPtr(totalPts), + Returned: wave3FinIntPtr(len(records)), + } + if totalPts > len(records) { + doc.Truncated = wave3FinBoolPtr(true) + doc.NextCursor = strconv.Itoa(len(records)) + } + return doc, true + } + + // 2. /api/xbrl/companyconcept/CIK{cik}/{taxonomy}/{tag}.json + if unitsMap, hasUnits := obj["units"].(map[string]any); hasUnits && len(unitsMap) > 0 { + entity := wave3FinPlain(obj["entityName"], 160) + cik := wave3FinPlain(obj["cik"], 20) + taxonomy := wave3FinPlain(obj["taxonomy"], 40) + tag := wave3FinPlain(obj["tag"], 120) + label := wave3FinPlain(obj["label"], 200) + desc := wave3FinPlain(obj["description"], 400) + + unitKeys := wave3FinOrderSECUnits(unitsMap) + var totalObs int + var tblRows [][]string + var records []map[string]any + for _, uk := range unitKeys { + obsArr, ok := unitsMap[uk].([]any) + if !ok { + continue + } + totalObs += len(obsArr) + for i := len(obsArr) - 1; i >= 0 && len(records) < wave3FinanceMaxRecords; i-- { + m, ok := obsArr[i].(map[string]any) + if !ok { + continue + } + end := wave3FinPlain(m["end"], 24) + val := wave3FinPlain(m["val"], 40) + fy := wave3FinPlain(m["fy"], 12) + fp := wave3FinPlain(m["fp"], 12) + form := wave3FinPlain(m["form"], 20) + filed := wave3FinPlain(m["filed"], 24) + accn := wave3FinPlain(m["accn"], 40) + tblRows = append(tblRows, []string{uk, end, val, form, fy + " " + fp, filed}) + records = append(records, map[string]any{ + "unit": uk, + "end": end, + "val": val, + "form": form, + "fy": fy, + "fp": fp, + "filed": filed, + "accn": accn, + "tag": tag, + }) + } + } + if len(records) == 0 { + return nil, false + } + title := fmt.Sprintf("%s — %s (%s)", wave3FinFirstNonEmpty(entity, "CIK "+cik), wave3FinFirstNonEmpty(label, tag), tag) + var md strings.Builder + md.WriteString("# ") + md.WriteString(escapeDeclMarkdownBrackets(title)) + md.WriteString("\n\n") + for _, pair := range [][2]string{ + {"Entity", entity}, + {"CIK", cik}, + {"Taxonomy", taxonomy}, + {"Tag", tag}, + {"Total Observations", strconv.Itoa(totalObs)}, + } { + if pair[1] != "" { + md.WriteString("- **") + md.WriteString(pair[0]) + md.WriteString(":** ") + md.WriteString(escapeDeclMarkdownBrackets(pair[1])) + md.WriteByte('\n') + } + } + if desc != "" { + md.WriteString("- **Description:** ") + md.WriteString(escapeDeclMarkdownBrackets(desc)) + md.WriteByte('\n') + } + md.WriteString("\n## Concept Observations\n\n") + md.WriteString(wave3FinBuildTable([]string{"Unit", "Period End", "Value", "Form", "Fiscal", "Filed"}, tblRows)) + + doc := &DeclarativeFormattedDoc{ + Title: title, + Description: desc, + Markdown: md.String(), + Records: records, + Total: wave3FinIntPtr(totalObs), + Returned: wave3FinIntPtr(len(records)), + } + if totalObs > len(records) { + doc.Truncated = wave3FinBoolPtr(true) + doc.NextCursor = strconv.Itoa(len(records)) + } + return doc, true + } + + // 3. /api/xbrl/companyfacts/CIK{cik}.json + if factsMap, hasFacts := obj["facts"].(map[string]any); hasFacts && len(factsMap) > 0 { + entity := wave3FinPlain(obj["entityName"], 160) + cik := wave3FinPlain(obj["cik"], 20) + taxKeys := wave3FinSortedStringKeys(factsMap) + totalConcepts := 0 + var tblRows [][]string + var records []map[string]any + for _, tax := range taxKeys { + conceptsMap, ok := factsMap[tax].(map[string]any) + if !ok { + continue + } + conceptKeys := wave3FinSortedStringKeys(conceptsMap) + totalConcepts += len(conceptKeys) + for _, tag := range conceptKeys { + if len(records) >= wave3FinanceMaxRecords { + continue + } + cObj, ok := conceptsMap[tag].(map[string]any) + if !ok { + continue + } + label := wave3FinPlain(cObj["label"], 160) + unitsMap, _ := cObj["units"].(map[string]any) + unitKeys := wave3FinOrderSECUnits(unitsMap) + unitName, end, val, form := "", "", "", "" + for _, uk := range unitKeys { + obsArr, ok := unitsMap[uk].([]any) + if ok && len(obsArr) > 0 { + if last, ok := obsArr[len(obsArr)-1].(map[string]any); ok { + unitName = uk + end = wave3FinPlain(last["end"], 24) + val = wave3FinPlain(last["val"], 40) + form = wave3FinPlain(last["form"], 20) + break + } + } + } + if unitName == "" { + continue + } + tblRows = append(tblRows, []string{tax, tag, unitName, end, val, form}) + records = append(records, map[string]any{ + "taxonomy": tax, + "tag": tag, + "label": label, + "unit": unitName, + "end": end, + "val": val, + "form": form, + }) + } + } + if len(records) == 0 { + return nil, false + } + title := fmt.Sprintf("%s (CIK %s) — SEC XBRL Company Facts", wave3FinFirstNonEmpty(entity, "Company Facts"), cik) + var md strings.Builder + md.WriteString("# ") + md.WriteString(escapeDeclMarkdownBrackets(title)) + md.WriteString("\n\n") + md.WriteString(fmt.Sprintf("- **Entity:** %s\n", escapeDeclMarkdownBrackets(wave3FinFirstNonEmpty(entity, cik)))) + if cik != "" { + md.WriteString(fmt.Sprintf("- **CIK:** `%s`\n", sanitizeDeclInlineCodeVal(cik))) + } + md.WriteString(fmt.Sprintf("- **Total Concepts:** %d (showing %d)\n\n", totalConcepts, len(records))) + md.WriteString("## Company Facts (Bounded Sample)\n\n") + md.WriteString(wave3FinBuildTable([]string{"Taxonomy", "Tag", "Unit", "Period End", "Latest Value", "Form"}, tblRows)) + + doc := &DeclarativeFormattedDoc{ + Title: title, + Markdown: md.String(), + Records: records, + Total: wave3FinIntPtr(totalConcepts), + Returned: wave3FinIntPtr(len(records)), + } + if totalConcepts > len(records) { + doc.Truncated = wave3FinBoolPtr(true) + doc.NextCursor = strconv.Itoa(len(records)) + } + return doc, true + } + + return nil, false +} + +func wave3FinSkipJSONValue(dec *json.Decoder) error { + tok, err := dec.Token() + if err != nil { + return err + } + if delim, ok := tok.(json.Delim); !ok || (delim != '{' && delim != '[') { + return nil + } + depth := 1 + for depth > 0 { + t, errT := dec.Token() + if errT != nil { + return errT + } + if d, isDelim := t.(json.Delim); isDelim { + switch d { + case '{', '[': + depth++ + case '}', ']': + depth-- + } + } + } + return nil +} + +func wave3FinFormatSECCompanyFactsStream(trimmed []byte, origURL string) (*DeclarativeFormattedDoc, bool) { + dec := json.NewDecoder(bytes.NewReader(trimmed)) + dec.UseNumber() + + tok, err := dec.Token() + if err != nil { + return nil, false + } + if d, ok := tok.(json.Delim); !ok || d != '{' { + return nil, false + } + + var entity, cik string + var tblRows [][]string + var records []map[string]any + totalConcepts := 0 + sawMoreConcepts := false + + for dec.More() { + kt, kErr := dec.Token() + if kErr != nil { + break + } + key, okK := kt.(string) + if !okK { + break + } + switch key { + case "error", "errors", "errorMessage": + var v any + if dec.Decode(&v) != nil { + return nil, false + } + if wave3FinPlain(v, 128) != "" { + return nil, false + } + case "data", "units": + return nil, false + case "cik": + var v any + if dec.Decode(&v) != nil { + goto doneStream + } + cik = wave3FinPlain(v, 20) + case "entityName": + var v any + if dec.Decode(&v) != nil { + goto doneStream + } + entity = wave3FinPlain(v, 160) + case "facts": + fTok, fErr := dec.Token() + if fErr != nil { + goto doneStream + } + if fd, okFD := fTok.(json.Delim); !okFD || fd != '{' { + goto doneStream + } + for dec.More() { + tt, tErr := dec.Token() + if tErr != nil { + goto doneStream + } + tax, okT := tt.(string) + if !okT { + goto doneStream + } + cTok, cErr := dec.Token() + if cErr != nil { + goto doneStream + } + if cd, okCD := cTok.(json.Delim); !okCD || cd != '{' { + if wave3FinSkipJSONValue(dec) != nil { + goto doneStream + } + continue + } + for dec.More() { + if len(records) >= wave3FinanceMaxRecords { + sawMoreConcepts = true + goto doneStream + } + ct, cTErr := dec.Token() + if cTErr != nil { + goto doneStream + } + tag, okTag := ct.(string) + if !okTag { + goto doneStream + } + totalConcepts++ + var cObj map[string]any + if dec.Decode(&cObj) != nil { + goto doneStream + } + if cObj == nil { + continue + } + label := wave3FinPlain(cObj["label"], 160) + unitsMap, _ := cObj["units"].(map[string]any) + unitKeys := wave3FinOrderSECUnits(unitsMap) + unitName, end, val, form := "", "", "", "" + for _, uk := range unitKeys { + obsArr, okObs := unitsMap[uk].([]any) + if okObs && len(obsArr) > 0 { + if last, okL := obsArr[len(obsArr)-1].(map[string]any); okL { + unitName = uk + end = wave3FinPlain(last["end"], 24) + val = wave3FinPlain(last["val"], 40) + form = wave3FinPlain(last["form"], 20) + break + } + } + } + if unitName == "" { + continue + } + tblRows = append(tblRows, []string{tax, tag, unitName, end, val, form}) + records = append(records, map[string]any{ + "taxonomy": tax, + "tag": tag, + "label": label, + "unit": unitName, + "end": end, + "val": val, + "form": form, + }) + } + // Closing '}' of this taxonomy's concept map + if _, errEnd := dec.Token(); errEnd != nil { + goto doneStream + } + } + goto doneStream + default: + if wave3FinSkipJSONValue(dec) != nil { + goto doneStream + } + } + } + +doneStream: + if len(records) == 0 { + return nil, false + } + title := fmt.Sprintf("%s (CIK %s) — SEC XBRL Company Facts", wave3FinFirstNonEmpty(entity, "Company Facts"), cik) + var md strings.Builder + md.WriteString("# ") + md.WriteString(escapeDeclMarkdownBrackets(title)) + md.WriteString("\n\n") + md.WriteString(fmt.Sprintf("- **Entity:** %s\n", escapeDeclMarkdownBrackets(wave3FinFirstNonEmpty(entity, cik)))) + if cik != "" { + md.WriteString(fmt.Sprintf("- **CIK:** `%s`\n", sanitizeDeclInlineCodeVal(cik))) + } + if sawMoreConcepts { + md.WriteString(fmt.Sprintf("- **Returned Concepts:** %d (bounded streaming prefix)\n\n", len(records))) + } else { + md.WriteString(fmt.Sprintf("- **Total Concepts:** %d (showing %d)\n\n", totalConcepts, len(records))) + } + md.WriteString("## Company Facts (Bounded Sample)\n\n") + md.WriteString(wave3FinBuildTable([]string{"Taxonomy", "Tag", "Unit", "Period End", "Latest Value", "Form"}, tblRows)) + + doc := &DeclarativeFormattedDoc{ + Title: title, + Markdown: md.String(), + Records: records, + Returned: wave3FinIntPtr(len(records)), + } + if sawMoreConcepts { + doc.Truncated = wave3FinBoolPtr(true) + doc.NextCursor = strconv.Itoa(len(records)) + } else { + doc.Total = wave3FinIntPtr(totalConcepts) + if totalConcepts > len(records) { + doc.Truncated = wave3FinBoolPtr(true) + doc.NextCursor = strconv.Itoa(len(records)) + } + } + return doc, true +} + +func wave3FinOrderSECUnits(unitsMap map[string]any) []string { + keys := wave3FinSortedStringKeys(unitsMap) + if len(keys) <= 1 { + return keys + } + ordered := make([]string, 0, len(keys)) + for _, pref := range []string{"USD", "shares", "pure"} { + for _, k := range keys { + if k == pref { + ordered = append(ordered, k) + } + } + } + for _, k := range keys { + if k != "USD" && k != "shares" && k != "pure" { + ordered = append(ordered, k) + } + } + return ordered +} + +// ── #391 MSRB EMMA Municipal Bond Disclosures HTML ────────────────────────────────────────────── + +func wave3FinExtractMSRBEmmaHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + doc := ParseHTMLDoc(rawHTML, wave3FinanceMaxHTMLBytes) + if doc == nil { + return nil + } + h1 := SanitizeSchemaPlainField(doc.Text("h1"), 220) + metaTitle := wave3FinExtractTitleBounded(rawHTML) + title := wave3FinFirstNonEmpty(h1, metaTitle) + if wave3FinIsNegativeTitle(title) || wave3FinRxGenericTitle.MatchString(strings.TrimSpace(title)) { + if doc.First("table") == nil && doc.First("dl") == nil { + return nil + } + } + + bodyText := SanitizeSchemaPlainField(doc.Text("main"), 8000) + if bodyText == "" { + bodyText = SanitizeSchemaPlainField(doc.Text("body"), 8000) + } + cusip := "" + if m := wave3FinRxCUSIPLabeled.FindStringSubmatch(bodyText); len(m) >= 2 { + cusip = strings.ToUpper(m[1]) + } else if m := wave3FinRxCUSIP.FindStringSubmatch(strings.ToUpper(baseURL + " " + title + " " + bodyText)); len(m) >= 2 { + cusip = m[1] + } + + dl := doc.DLMap("dl") + rows := doc.TableRows("table") + + var links []string + seenLinks := make(map[string]bool) + for _, a := range doc.Select("a", 60) { + href := a.AttrOrEmpty("href") + hl := strings.ToLower(href) + if strings.Contains(hl, "official") || strings.Contains(hl, "/er/") || strings.Contains(hl, "/security/") || strings.Contains(hl, "/issueview/") || strings.HasSuffix(hl, ".pdf") { + if safe := wave3FinSafeHTTPSLink(href, baseURL); safe != "" && !seenLinks[safe] && len(links) < 15 { + seenLinks[safe] = true + links = append(links, safe) + } + } + } + + coupon := "" + if m := wave3FinRxCoupon.FindStringSubmatch(bodyText); len(m) >= 2 { + coupon = SanitizeSchemaPlainField(m[1], 32) + } + maturity := "" + if m := wave3FinRxMaturity.FindStringSubmatch(bodyText); len(m) >= 2 { + maturity = SanitizeSchemaPlainField(m[1], 40) + } + dated := "" + if m := wave3FinRxDatedDate.FindStringSubmatch(bodyText); len(m) >= 2 { + dated = SanitizeSchemaPlainField(m[1], 40) + } + amount := "" + if m := wave3FinRxAmount.FindStringSubmatch(bodyText); len(m) >= 2 { + amount = SanitizeSchemaPlainField(m[1], 40) + } + + // Require genuine EMMA municipal security / disclosure content + if cusip == "" && len(dl) == 0 && len(rows) < 2 && len(links) == 0 { + return nil + } + + if title == "" { + if cusip != "" { + title = "MSRB EMMA Security " + cusip + } else { + title = "MSRB EMMA Municipal Bond Disclosure" + } + } + + var md strings.Builder + md.WriteString("# ") + md.WriteString(escapeDeclMarkdownBrackets(title)) + md.WriteString("\n\n") + if cusip != "" { + md.WriteString("- **CUSIP:** `") + md.WriteString(sanitizeDeclInlineCodeVal(cusip)) + md.WriteString("`\n") + } + for _, pair := range [][2]string{ + {"Coupon Rate", coupon}, + {"Maturity Date", maturity}, + {"Dated Date", dated}, + {"Amount", amount}, + } { + if pair[1] != "" { + md.WriteString("- **") + md.WriteString(pair[0]) + md.WriteString(":** ") + md.WriteString(escapeDeclMarkdownBrackets(pair[1])) + md.WriteByte('\n') + } + } + if len(dl) > 0 { + dlKeys := make([]string, 0, len(dl)) + for k := range dl { + dlKeys = append(dlKeys, k) + } + sort.Strings(dlKeys) + for _, k := range dlKeys { + ck := SanitizeSchemaPlainField(k, 80) + cv := SanitizeSchemaPlainField(dl[k], 200) + if ck != "" && cv != "" { + md.WriteString("- **") + md.WriteString(escapeDeclMarkdownBrackets(ck)) + md.WriteString(":** ") + md.WriteString(escapeDeclMarkdownBrackets(cv)) + md.WriteByte('\n') + } + } + } + + var records []map[string]any + totalRows := 0 + if len(rows) >= 2 && len(rows[0]) >= 2 { + hdr := rows[0] + cols := len(hdr) + if cols > 6 { + cols = 6 + } + cleanHdr := make([]string, cols) + for i := 0; i < cols; i++ { + cleanHdr[i] = wave3FinFirstNonEmpty(SanitizeSchemaPlainField(hdr[i], 60), fmt.Sprintf("Col %d", i+1)) + } + var tblRows [][]string + for _, r := range rows[1:] { + if len(r) == 0 { + continue + } + dr := make([]string, cols) + nonEmpty := false + for c := 0; c < cols; c++ { + if c < len(r) { + dr[c] = SanitizeSchemaPlainField(r[c], 140) + if dr[c] != "" { + nonEmpty = true + } + } + } + if !nonEmpty { + continue + } + totalRows++ + if len(tblRows) < wave3FinanceMaxRecords { + tblRows = append(tblRows, dr) + rec := map[string]any{} + if cusip != "" { + rec["cusip"] = cusip + } + for c, hName := range cleanHdr { + if dr[c] != "" { + rec[hName] = dr[c] + } + } + records = append(records, rec) + } + } + if len(tblRows) > 0 { + md.WriteString("\n## Securities & Disclosures\n\n") + md.WriteString(wave3FinBuildTable(cleanHdr, tblRows)) + md.WriteByte('\n') + } + } + + if len(records) == 0 && (cusip != "" || len(dl) > 0) { + rec := map[string]any{"title": title} + if cusip != "" { + rec["cusip"] = cusip + } + if coupon != "" { + rec["coupon"] = coupon + } + if maturity != "" { + rec["maturityDate"] = maturity + } + if amount != "" { + rec["amount"] = amount + } + records = append(records, rec) + totalRows = 1 + } + + if len(links) > 0 { + md.WriteString("\n## Disclosure Links\n\n") + for _, l := range links { + md.WriteString("- ") + md.WriteString(l) + md.WriteByte('\n') + } + } + + res := &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: wave3FinExtractMetaBounded(rawHTML, "description"), + Markdown: strings.TrimSpace(md.String()), + Links: links, + Records: records, + } + if totalRows > 0 { + res.Total = wave3FinIntPtr(totalRows) + res.Returned = wave3FinIntPtr(len(records)) + if totalRows > len(records) { + res.Truncated = wave3FinBoolPtr(true) + res.NextCursor = strconv.Itoa(len(records)) + } + } + return res +} + +// ── #392 FFIEC Central Data Repository (HTML + JSON) ──────────────────────────────────────────── + +func wave3FinExtractFFIECCDRHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + doc := ParseHTMLDoc(rawHTML, wave3FinanceMaxHTMLBytes) + if doc == nil { + return nil + } + title := wave3FinFirstNonEmpty( + SanitizeSchemaPlainField(doc.Text("h1"), 200), + SanitizeSchemaPlainField(doc.Text("h2"), 200), + wave3FinExtractTitleBounded(rawHTML), + ) + if wave3FinIsNegativeTitle(title) || wave3FinRxGenericTitle.MatchString(strings.TrimSpace(title)) { + if doc.First("table") == nil && doc.First("select") == nil { + return nil + } + } + + var links []string + seenLinks := make(map[string]bool) + for _, a := range doc.Select("a", 80) { + href := a.AttrOrEmpty("href") + hl := strings.ToLower(href) + if strings.Contains(hl, "/public/") || strings.Contains(hl, "download") || strings.Contains(hl, "facsimile") || strings.Contains(hl, "xbrl") || strings.Contains(hl, "ubpr") { + if safe := wave3FinSafeHTTPSLink(href, baseURL); safe != "" && !seenLinks[safe] && len(links) < 15 { + seenLinks[safe] = true + links = append(links, safe) + } + } + } + + var periods []string + var products []string + for _, sel := range doc.Select("select", 10) { + selName := strings.ToLower(sel.AttrOrEmpty("name") + " " + sel.AttrOrEmpty("id")) + isPeriod := strings.Contains(selName, "period") || strings.Contains(selName, "date") || strings.Contains(selName, "quarter") + for _, opt := range sel.Select("option", 30) { + txt := SanitizeSchemaPlainField(opt.Text(), 140) + if txt == "" || strings.HasPrefix(strings.ToLower(txt), "--") || strings.EqualFold(txt, "select") { + continue + } + if isPeriod || wave3FinIsValidDateToken(txt) { + periods = append(periods, txt) + } else { + products = append(products, txt) + } + } + } + + rows := doc.TableRows("table") + var records []map[string]any + totalRows := 0 + var md strings.Builder + if title == "" { + title = "FFIEC Central Data Repository" + } + md.WriteString("# ") + md.WriteString(escapeDeclMarkdownBrackets(title)) + md.WriteString("\n\n") + + if len(products) > 0 { + md.WriteString("## Data Products & Report Types\n\n") + for i, p := range products { + if i >= wave3FinanceMaxRecords { + break + } + md.WriteString("- ") + md.WriteString(escapeDeclMarkdownBrackets(p)) + md.WriteByte('\n') + } + md.WriteByte('\n') + } + + if len(periods) > 0 { + md.WriteString("## Reporting Periods\n\n") + limit := len(periods) + if limit > 12 { + limit = 12 + } + md.WriteString("- **Available Periods:** ") + md.WriteString(escapeDeclMarkdownBrackets(strings.Join(periods[:limit], ", "))) + md.WriteString("\n\n") + } + + if len(rows) >= 2 && len(rows[0]) >= 2 { + hdr := rows[0] + cols := len(hdr) + if cols > 6 { + cols = 6 + } + cleanHdr := make([]string, cols) + for i := 0; i < cols; i++ { + cleanHdr[i] = wave3FinFirstNonEmpty(SanitizeSchemaPlainField(hdr[i], 60), fmt.Sprintf("Col %d", i+1)) + } + var tblRows [][]string + for _, r := range rows[1:] { + if len(r) == 0 { + continue + } + dr := make([]string, cols) + nonEmpty := false + for c := 0; c < cols; c++ { + if c < len(r) { + dr[c] = SanitizeSchemaPlainField(r[c], 140) + if dr[c] != "" { + nonEmpty = true + } + } + } + if !nonEmpty { + continue + } + totalRows++ + if len(tblRows) < wave3FinanceMaxRecords { + tblRows = append(tblRows, dr) + rec := map[string]any{} + for c, hName := range cleanHdr { + if dr[c] != "" { + rec[hName] = dr[c] + } + } + records = append(records, rec) + } + } + if len(tblRows) > 0 { + md.WriteString("## CDR Records\n\n") + md.WriteString(wave3FinBuildTable(cleanHdr, tblRows)) + md.WriteByte('\n') + } + } + + if len(records) == 0 && (len(products) > 0 || len(periods) > 0) { + for _, p := range products { + if len(records) >= wave3FinanceMaxRecords { + break + } + records = append(records, map[string]any{"product": p}) + totalRows++ + } + if len(records) == 0 { + for _, per := range periods { + if len(records) >= wave3FinanceMaxRecords { + break + } + records = append(records, map[string]any{"reportingPeriod": per}) + totalRows++ + } + } + } + + if len(records) == 0 && len(links) == 0 { + return nil + } + + if len(links) > 0 { + md.WriteString("\n## Public CDR Links\n\n") + for _, l := range links { + md.WriteString("- ") + md.WriteString(l) + md.WriteByte('\n') + } + } + + res := &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Markdown: strings.TrimSpace(md.String()), + Links: links, + Records: records, + } + if totalRows > 0 { + res.Total = wave3FinIntPtr(totalRows) + res.Returned = wave3FinIntPtr(len(records)) + if totalRows > len(records) { + res.Truncated = wave3FinBoolPtr(true) + res.NextCursor = strconv.Itoa(len(records)) + } + } + return res +} + +func wave3FinFormatFFIECCDRJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + if arr, isArr := parsed.([]any); isArr { + if len(arr) == 0 { + return nil, false + } + total := len(arr) + var records []map[string]any + var periodStrs []string + var tblRows [][]string + var tblHeaders []string + + for i, item := range arr { + if i >= wave3FinanceMaxRecords { + break + } + switch tv := item.(type) { + case string: + p := SanitizeSchemaPlainField(tv, 40) + if p != "" { + periodStrs = append(periodStrs, p) + records = append(records, map[string]any{"reportingPeriod": p}) + } + case map[string]any: + if len(tblHeaders) == 0 { + for _, k := range wave3FinSortedStringKeys(tv) { + if len(tblHeaders) < 6 { + tblHeaders = append(tblHeaders, k) + } + } + } + row := make([]string, len(tblHeaders)) + rec := map[string]any{} + for ci, k := range tblHeaders { + v := wave3FinPlain(tv[k], 120) + row[ci] = v + if v != "" { + rec[k] = v + } + } + if len(rec) > 0 { + tblRows = append(tblRows, row) + records = append(records, rec) + } + } + } + if len(records) == 0 { + return nil, false + } + title := "FFIEC CDR Public Web Service" + var md strings.Builder + md.WriteString("# ") + md.WriteString(escapeDeclMarkdownBrackets(title)) + md.WriteString("\n\n") + md.WriteString(fmt.Sprintf("- **Total Items:** %d\n\n", total)) + if len(periodStrs) > 0 { + md.WriteString("## Reporting Periods\n\n") + for _, p := range periodStrs { + md.WriteString("- ") + md.WriteString(escapeDeclMarkdownBrackets(p)) + md.WriteByte('\n') + } + } else if len(tblRows) > 0 { + md.WriteString(wave3FinBuildTable(tblHeaders, tblRows)) + } + doc := &DeclarativeFormattedDoc{ + Title: title, + Markdown: strings.TrimSpace(md.String()), + Records: records, + Total: wave3FinIntPtr(total), + Returned: wave3FinIntPtr(len(records)), + } + if total > len(records) { + doc.Truncated = wave3FinBoolPtr(true) + doc.NextCursor = strconv.Itoa(len(records)) + } + return doc, true + } + + if obj, isObj := parsed.(map[string]any); isObj { + keys := wave3FinSortedStringKeys(obj) + if len(keys) == 0 { + return nil, false + } + title := "FFIEC CDR Public Web Service Record" + var md strings.Builder + md.WriteString("# ") + md.WriteString(title) + md.WriteString("\n\n") + rec := map[string]any{} + for _, k := range keys { + if val := wave3FinPlain(obj[k], 160); val != "" { + md.WriteString("- **") + md.WriteString(escapeDeclMarkdownBrackets(SanitizeSchemaPlainField(k, 60))) + md.WriteString(":** ") + md.WriteString(escapeDeclMarkdownBrackets(val)) + md.WriteByte('\n') + rec[k] = val + } + } + if len(rec) == 0 { + return nil, false + } + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: strings.TrimSpace(md.String()), + Records: []map[string]any{rec}, + Total: wave3FinIntPtr(1), + Returned: wave3FinIntPtr(1), + }, true + } + return nil, false +} diff --git a/internal/extract/wave3_finance_test.go b/internal/extract/wave3_finance_test.go new file mode 100644 index 0000000..f55079e --- /dev/null +++ b/internal/extract/wave3_finance_test.go @@ -0,0 +1,591 @@ +package extract + +import ( + "encoding/base64" + "encoding/json" + "fmt" + "net/url" + "os" + "path/filepath" + "regexp" + "strings" + "testing" + "time" + + "github.com/bartrumb/edgefetch/v2/internal/classify" +) + +func wave3FinResolveManifest(t *testing.T, m *DeclarativeAdapterManifest, rawURL string) (*DeclarativeTwinMatch, bool) { + t.Helper() + u, err := url.Parse(rawURL) + if err != nil { + t.Fatalf("url.Parse(%q): %v", rawURL, err) + } + host := strings.TrimSuffix(strings.ToLower(u.Hostname()), ".") + rawParts := splitNonEmptyEscapedSegments(u.EscapedPath()) + return resolveManifestTwinOnParsedURL(m, u, host, rawParts, DeclarativeResolveOptions{}) +} + +func TestWave3FinanceManifestsAndRouting(t *testing.T) { + catSIDs := []string{ + "fed-h15-datadownload", + "nasdaq-data-link", + "market-quotes-pack", + "sec-xbrl-frames", + "msrb-emma", + "ffiec-cdr", + } + + byID := make(map[string]*DeclarativeAdapterManifest) + claimedDomains := make(map[string]string) + + privPatBytes, _ := base64.StdEncoding.DecodeString("c2hlcGhlcmR8c2hvcGRhd2d8anVpY2Vk") + privTokens := strings.Split(string(privPatBytes), "|") + + for _, id := range catSIDs { + raw, err := os.ReadFile(filepath.Join("manifests", id+".yaml")) + if err != nil { + t.Fatalf("read %s.yaml: %v", id, err) + } + rawLower := strings.ToLower(string(raw)) + for _, tok := range privTokens { + if tok != "" && strings.Contains(rawLower, tok) { + t.Fatalf("Rule 9 violation in %s.yaml: %q", id, tok) + } + } + m, err := ParseDeclarativeYAMLManifest(raw) + if err != nil { + t.Fatalf("ParseDeclarativeYAMLManifest(%s.yaml): %v", id, err) + } + if m.ID != id { + t.Fatalf("%s.yaml has mismatched id=%q", id, m.ID) + } + if m.Category != "finance" { + t.Fatalf("%s.yaml must use category finance, got %q", id, m.Category) + } + if m.AuthMode == "detect-only" || m.DetectOnly != nil { + t.Fatalf("%s.yaml uses retired detect-only", id) + } + for _, d := range m.Domains { + ld := strings.ToLower(strings.TrimSpace(d)) + if prev, exists := claimedDomains[ld]; exists { + t.Fatalf("duplicate domain %q across %s and %s", ld, prev, id) + } + claimedDomains[ld] = id + } + for _, hr := range m.HTMLRoutes { + for _, b := range hr.Bullets { + if strings.ContainsAny(b.Label, "{}") { + t.Fatalf("%s.yaml htmlRoute bullet label contains {}: %q", id, b.Label) + } + } + } + for _, r := range m.Routes { + for _, b := range r.Extract.Bullets { + if strings.ContainsAny(b.Label, "{}") { + t.Fatalf("%s.yaml route bullet label contains {}: %q", id, b.Label) + } + } + } + byID[id] = m + } + + // Disjointness from existing finance manifests (including sec-edgar.yaml data.sec.gov) + for _, existingID := range []string{ + "sec-edgar", + "treasury-fiscal-data", + "fred", + "bls", + "bea", + "cfpb-complaints", + "fdic-bankfind", + "finra-brokercheck", + "ncua-credit-unions", + "financial-regulators-enforcement", + "sba-dsbs-loans", + } { + raw, err := os.ReadFile(filepath.Join("manifests", existingID+".yaml")) + if err != nil { + t.Fatalf("read %s.yaml: %v", existingID, err) + } + em, err := ParseDeclarativeYAMLManifest(raw) + if err != nil { + t.Fatalf("ParseDeclarativeYAMLManifest(%s.yaml): %v", existingID, err) + } + for _, d := range em.Domains { + ld := strings.ToLower(strings.TrimSpace(d)) + if catOwner, overlap := claimedDomains[ld]; overlap { + t.Fatalf("Cat S %s overlaps %s domain %q", catOwner, existingID, ld) + } + } + } + + // Verify #387 fed-h15-datadownload routes + HTML routes + fed := byID["fed-h15-datadownload"] + tmFed, okFed := wave3FinResolveManifest(t, fed, "https://www.federalreserve.gov/datadownload/Output.aspx?rel=H15&series=bf17364827e38702b42a58cf8eaa3f78&lastobs=5&filetype=csv") + if !okFed || tmFed.route.Twin.Kind != "text" || tmFed.route.Extract.TextMode != "fed_h15_csv" || tmFed.route.Twin.MaxBytes != 2097152 { + t.Fatalf("fed-h15-datadownload Output.aspx route failed: ok=%v tm=%+v", okFed, tmFed) + } + + // Verify #388 nasdaq-data-link + ndl := byID["nasdaq-data-link"] + if ndl.AuthMode != "key" { + t.Fatalf("nasdaq-data-link must have auth_mode=key, got %q", ndl.AuthMode) + } + for _, u := range []string{ + "https://data.nasdaq.com/api/v3/datasets/FRED/GDP.json?rows=5", + "https://data.nasdaq.com/api/v3/datatables/ZACKS/FC.json?ticker=AAPL", + } { + tm, ok := wave3FinResolveManifest(t, ndl, u) + if !ok || tm.route.Extract.JSONMode != "nasdaq_data_link_json" || tm.AuthMode != "key" { + t.Fatalf("nasdaq-data-link route failed for %q: ok=%v tm=%+v", u, ok, tm) + } + } + + // Verify #389 market-quotes-pack across all 4 quote hosts + mq := byID["market-quotes-pack"] + if mq.AuthMode != "key" { + t.Fatalf("market-quotes-pack must have auth_mode=key, got %q", mq.AuthMode) + } + for _, u := range []string{ + "https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=IBM", + "https://alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=IBM", + "https://api.polygon.io/v2/aggs/ticker/AAPL/prev", + "https://api.massive.com/v2/aggs/ticker/AAPL/prev", + "https://api.tiingo.com/tiingo/daily/aapl/prices", + } { + tm, ok := wave3FinResolveManifest(t, mq, u) + if !ok || tm.route.Extract.JSONMode != "market_quotes_json" { + t.Fatalf("market-quotes-pack route failed for %q: ok=%v", u, ok) + } + } + + // Verify #390 sec-xbrl-frames collision fix + sec-edgar coexistence + secEdgarRaw, err := os.ReadFile(filepath.Join("manifests", "sec-edgar.yaml")) + if err != nil { + t.Fatalf("read sec-edgar.yaml: %v", err) + } + secEdgar, err := ParseDeclarativeYAMLManifest(secEdgarRaw) + if err != nil { + t.Fatalf("parse sec-edgar.yaml: %v", err) + } + secXBRL := byID["sec-xbrl-frames"] + if !secXBRL.UniversalEngine || secXBRL.UserAgentProfile != "sec-edgar" || secXBRL.MinIntervalMs != 200 { + t.Fatalf("sec-xbrl-frames flags mismatch: %+v", secXBRL) + } + for _, xbrlURL := range []string{ + "https://data.sec.gov/api/xbrl/frames/us-gaap/AccountsPayableCurrent/USD/CY2023Q4I.json", + "https://data.sec.gov/api/xbrl/companyconcept/CIK0000320193/us-gaap/AccountsPayableCurrent.json", + "https://data.sec.gov/api/xbrl/companyfacts/CIK0000320193.json", + } { + // sec-edgar must NOT match /api/xbrl/* so universalEngine falls through to sec-xbrl-frames + if edgarMatch, okEdgar := wave3FinResolveManifest(t, secEdgar, xbrlURL); okEdgar || edgarMatch != nil { + t.Fatalf("sec-edgar must NOT claim %q", xbrlURL) + } + tm, ok := wave3FinResolveManifest(t, secXBRL, xbrlURL) + if !ok || tm.route.Extract.JSONMode != "sec_xbrl_frames_json" || tm.route.Twin.MaxBytes != 4194304 || tm.UserAgentProfile != "sec-edgar" { + t.Fatalf("sec-xbrl-frames route failed for %q: ok=%v tm=%+v", xbrlURL, ok, tm) + } + } + + // Verify #392 ffiec-cdr JSON + HTML + ffiec := byID["ffiec-cdr"] + if tmF, okF := wave3FinResolveManifest(t, ffiec, "https://ffieccdr.azure-api.us/public/v1/RetrieveReportingPeriods"); !okF || tmF.route.Extract.JSONMode != "ffiec_cdr_json" || tmF.AuthMode != "key" { + t.Fatalf("ffiec-cdr azure-api.us route failed: ok=%v tm=%+v", okF, tmF) + } + + // Validate full manifest ruleset coexistence with sec-edgar + our 6 manifests + var set []DeclarativeAdapterManifest + set = append(set, *secEdgar) + for _, id := range catSIDs { + set = append(set, *byID[id]) + } + if err := ValidateDeclarativeManifests(set); err != nil { + t.Fatalf("ValidateDeclarativeManifests failed: %v", err) + } +} + +func TestWave3FinanceModesAndCatS(t *testing.T) { + registerWave3FinanceHTMLModes() + RegisterWave3FinanceHTMLModes() + + for _, hm := range []string{"fed_h15_html", "msrb_emma_html", "ffiec_cdr_html"} { + if getExternalHTMLModeLazy(hm) == nil { + t.Fatalf("RegisterExternalHTMLModeLazy missing %q", hm) + } + if !IsWave3FinanceHTMLMode(hm) { + t.Fatalf("IsWave3FinanceHTMLMode(%q) = false", hm) + } + } + + // 1. #387 fed_h15_csv (multi-series + >25 rows truncation + HTML rejection) + var csvBuf strings.Builder + csvBuf.WriteString("\"Series Description\",\"10-Year Treasury\",\"Federal Funds Effective Rate\"\n") + csvBuf.WriteString("\"Unit:\",\"Percent:_Per_Year\",\"Percent:_Per_Year\"\n") + csvBuf.WriteString("\"Multiplier:\",\"1\",\"1\"\n") + csvBuf.WriteString("\"Currency:\",\"NA\",\"NA\"\n") + csvBuf.WriteString("\"Unique Identifier:\",\"H15/H15/RIFLGFCY10_N.B\",\"H15/H15/RIFSPFF_N.B\"\n") + csvBuf.WriteString("\"Time Period\",\"RIFLGFCY10_N.B\",\"RIFSPFF_N.B\"\n") + for day := 1; day <= 30; day++ { + csvBuf.WriteString(fmt.Sprintf("2026-10-%02d,4.%02d,4.58\n", day, day)) + } + csvDoc, okCSV := FormatWave3FinanceTextDoc("fed_h15_csv", csvBuf.String(), nil, "https://www.federalreserve.gov/datadownload/Output.aspx?rel=H15&filetype=csv") + if !okCSV || csvDoc == nil || len(csvDoc.Records) != 25 || csvDoc.Total == nil || *csvDoc.Total != 30 || csvDoc.Truncated == nil || !*csvDoc.Truncated { + t.Fatalf("fed_h15_csv bounded multi-series failed: ok=%v doc=%+v", okCSV, csvDoc) + } + if !strings.Contains(csvDoc.Markdown, "2026-10-30") || !strings.Contains(csvDoc.Markdown, "RIFSPFF_N.B") { + t.Fatalf("fed_h15_csv missing latest observation or series column: %s", csvDoc.Markdown) + } + if _, negHTML := FormatWave3FinanceTextMode("fed_h15_csv", "Unsupported format", nil, "https://www.federalreserve.gov/datadownload/Output.aspx?filetype=sdmx"); negHTML { + t.Fatalf("fed_h15_csv must reject HTML responses") + } + + // #387 fed_h15_html (#h15table + Choose.aspx) + h15ReleaseHTML := `Selected Interest Rates (Daily) - H.15

Selected Interest Rates - H.15

Instruments2026 Nov 242026 Nov 25
Federal funds (effective)4.584.58
Treasury constant maturities 10-year4.284.22
Data Download Program
` + h15Out := Wave3FinanceRunHTML("fed_h15_html", h15ReleaseHTML, "https://www.federalreserve.gov/releases/h15/", "fed-h15-datadownload") + if h15Out == nil || len(h15Out.Records) != 2 || !strings.Contains(h15Out.Markdown, "Federal funds (effective)") || !strings.Contains(h15Out.Markdown, "4.22") { + t.Fatalf("fed_h15_html #h15table failed: %+v", h15Out) + } + chooseHTML := `Data Download Program - H.15

Federal Reserve Statistical Release H.15 Data Download

` + chooseOut := Wave3FinanceRunHTML("fed_h15_html", chooseHTML, "https://www.federalreserve.gov/datadownload/Choose.aspx?rel=H15", "fed-h15-datadownload") + if chooseOut == nil || len(chooseOut.Records) != 2 || !strings.Contains(chooseOut.Markdown, "Federal Funds Effective Rate") { + t.Fatalf("fed_h15_html Choose.aspx failed: %+v", chooseOut) + } + + // 2. #388 nasdaq_data_link_json (dataset + datatable + error rejection) + dtJSON := []byte(`{"datatable":{"data":[["AAPL","2026-09-30",94930000],["MSFT","2026-09-30",65585000]],"columns":[{"name":"ticker","type":"String"},{"name":"per_end_date","type":"Date"},{"name":"tot_rev","type":"BigDecimal"}]},"meta":{"next_cursor_id":"abc123"}}`) + dtDoc, okDT := FormatWave3FinanceJSONDoc("nasdaq_data_link_json", dtJSON, nil, "https://data.nasdaq.com/api/v3/datatables/ZACKS/FC.json") + if !okDT || dtDoc == nil || len(dtDoc.Records) != 2 || dtDoc.NextCursor != "abc123" || !strings.Contains(dtDoc.Markdown, "ZACKS/FC") { + t.Fatalf("nasdaq_data_link_json datatable failed: ok=%v doc=%+v", okDT, dtDoc) + } + if _, negQ := FormatWave3FinanceJSONMode("nasdaq_data_link_json", []byte(`{"quandl_error":{"code":"QELx01","message":"API key invalid"}}`), nil, "https://data.nasdaq.com/api/v3/datasets/FRED/GDP.json"); negQ { + t.Fatalf("nasdaq_data_link_json must reject quandl_error") + } + + // 3. #389 market_quotes_json (AV Time Series + Polygon + Massive + Tiingo + error rejections) + avTS := []byte(`{"Meta Data":{"1. Information":"Daily Prices","2. Symbol":"MSFT","3. Last Refreshed":"2026-11-27"},"Time Series (Daily)":{"2026-11-27":{"1. open":"420.00","2. high":"425.00","3. low":"418.50","4. close":"424.10","5. volume":"18000000"},"2026-11-26":{"1. open":"415.00","2. high":"421.00","3. low":"414.00","4. close":"420.20","5. volume":"16500000"}}}`) + avDoc, okAV := FormatWave3FinanceJSONDoc("market_quotes_json", avTS, nil, "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT") + if !okAV || avDoc == nil || len(avDoc.Records) != 2 || !strings.Contains(avDoc.Markdown, "424.10") { + t.Fatalf("market_quotes_json AV Time Series failed: ok=%v doc=%+v", okAV, avDoc) + } + + polyAgg := []byte(`{"ticker":"AAPL","queryCount":1,"resultsCount":1,"adjusted":true,"results":[{"v":45120000,"vw":230.12,"o":229.0,"c":230.5,"h":231.8,"l":228.4,"t":1732665600000,"n":412000}],"status":"OK"}`) + massiveDoc, okMassive := FormatWave3FinanceJSONDoc("market_quotes_json", polyAgg, nil, "https://api.massive.com/v2/aggs/ticker/AAPL/prev") + if !okMassive || massiveDoc == nil || !strings.Contains(massiveDoc.Title, "Massive") || !strings.Contains(massiveDoc.Markdown, "230.5") { + t.Fatalf("market_quotes_json Massive aggs failed: ok=%v doc=%+v", okMassive, massiveDoc) + } + + tiingoArr := []byte(`[{"date":"2026-11-27T00:00:00.000Z","close":230.5,"high":231.8,"low":228.4,"open":229.0,"volume":45120000,"adjClose":230.5}]`) + tiingoDoc, okTiingo := FormatWave3FinanceJSONDoc("market_quotes_json", tiingoArr, nil, "https://api.tiingo.com/tiingo/daily/aapl/prices") + if !okTiingo || tiingoDoc == nil || !strings.Contains(tiingoDoc.Markdown, "AAPL") || !strings.Contains(tiingoDoc.Markdown, "230.5") { + t.Fatalf("market_quotes_json Tiingo array failed: ok=%v doc=%+v", okTiingo, tiingoDoc) + } + + for _, badQuote := range []string{ + `{"Note":"Thank you for using Alpha Vantage!"}`, + `{"status":"ERROR","error":"API Key was not provided"}`, + `{"detail":"Please supply a token"}`, + `[]`, + `{}`, + } { + if _, badOK := FormatWave3FinanceJSONMode("market_quotes_json", []byte(badQuote), nil, "https://api.polygon.io/v2/aggs/ticker/AAPL/prev"); badOK { + t.Fatalf("market_quotes_json must reject error/empty payload: %s", badQuote) + } + } + + // 4. #390 sec_xbrl_frames_json (frames + companyconcept + companyfacts bounded <= 25) + var factsItems []string + for i := 0; i < 30; i++ { + factsItems = append(factsItems, fmt.Sprintf(`"Concept%02d":{"label":"Concept %02d","units":{"USD":[{"end":"2025-12-31","val":%d,"form":"10-K"}]}}`, i, i, 1000+i)) + } + cfJSON := fmt.Sprintf(`{"cik":320193,"entityName":"Apple Inc.","facts":{"us-gaap":{%s}}}`, strings.Join(factsItems, ",")) + cfDoc, okCF := FormatWave3FinanceJSONDoc("sec_xbrl_frames_json", []byte(cfJSON), nil, "https://data.sec.gov/api/xbrl/companyfacts/CIK0000320193.json") + if !okCF || cfDoc == nil || len(cfDoc.Records) != 25 || cfDoc.Total == nil || *cfDoc.Total != 30 || cfDoc.Truncated == nil || !*cfDoc.Truncated { + t.Fatalf("sec_xbrl_frames_json companyfacts bounding failed: ok=%v doc=%+v", okCF, cfDoc) + } + + ccJSON := []byte(`{"cik":320193,"taxonomy":"us-gaap","tag":"AccountsPayableCurrent","label":"Accounts Payable, Current","entityName":"Apple Inc.","units":{"USD":[{"end":"2023-12-30","val":58146000000,"accn":"0000320193-24-000006","fy":2024,"fp":"Q1","form":"10-Q","filed":"2024-02-02"}]}}`) + ccDoc, okCC := FormatWave3FinanceJSONDoc("sec_xbrl_frames_json", ccJSON, nil, "https://data.sec.gov/api/xbrl/companyconcept/CIK0000320193/us-gaap/AccountsPayableCurrent.json") + if !okCC || ccDoc == nil || !strings.Contains(ccDoc.Markdown, "58146000000") { + t.Fatalf("sec_xbrl_frames_json companyconcept failed: ok=%v doc=%+v", okCC, ccDoc) + } + + // 5. #391 msrb_emma_html strict 403/awselb rejection + aws403 := `403 Forbidden

403 Forbidden


awselb/2.0
` + if res403 := Wave3FinanceRunHTML("msrb_emma_html", aws403, "https://emma.msrb.org/Home/Index", "msrb-emma"); res403 != nil { + t.Fatalf("msrb_emma_html must reject awselb/2.0 403 Forbidden") + } + + // 6. #392 ffiec_cdr_json + ffiec_cdr_html Error.aspx rejection + cdrPeriods := []byte(`["12/31/2025","09/30/2025","06/30/2025"]`) + cdrDoc, okCDR := FormatWave3FinanceJSONDoc("ffiec_cdr_json", cdrPeriods, nil, "https://ffieccdr.azure-api.us/public/v1/RetrieveReportingPeriods") + if !okCDR || cdrDoc == nil || len(cdrDoc.Records) != 3 || !strings.Contains(cdrDoc.Markdown, "12/31/2025") { + t.Fatalf("ffiec_cdr_json periods failed: ok=%v doc=%+v", okCDR, cdrDoc) + } + if resErrAspx := Wave3FinanceRunHTML("ffiec_cdr_html", `Error

Application Error

`, "https://cdr.ffiec.gov/public/Error.aspx", "ffiec-cdr"); resErrAspx != nil { + t.Fatalf("ffiec_cdr_html must reject Error.aspx") + } +} + +func TestWave3FinanceFixturesGoldenAndNegativeShells(t *testing.T) { + registerWave3FinanceHTMLModes() + + type fixtureNeg struct { + Name string `json:"name"` + Status int `json:"status"` + InputURL string `json:"inputUrl"` + FinalURL string `json:"finalUrl"` + Payload string `json:"payload"` + } + type fixtureDoc struct { + AdapterID string `json:"adapterId"` + Mode string `json:"mode"` + InputURL string `json:"inputUrl"` + ExpectedFetchURL string `json:"expectedFetchUrl"` + MockPayload string `json:"mockPayload"` + ExpectTitleIncludes string `json:"expectTitleIncludes"` + ExpectMarkdownIncludes []string `json:"expectMarkdownIncludes"` + NegativeCases []fixtureNeg `json:"negativeCases"` + } + + ids := []string{ + "fed-h15-datadownload", + "nasdaq-data-link", + "market-quotes-pack", + "sec-xbrl-frames", + "msrb-emma", + "ffiec-cdr", + } + + for _, id := range ids { + fpath := filepath.Join("..", "..", "hub", "test", "fixtures", "adapters", id+".json") + raw, err := os.ReadFile(fpath) + if err != nil { + t.Fatalf("read fixture %s: %v", fpath, err) + } + var fx fixtureDoc + if err := json.Unmarshal(raw, &fx); err != nil { + t.Fatalf("unmarshal %s: %v", fpath, err) + } + if fx.AdapterID != id { + t.Fatalf("%s adapterId mismatch: %q", id, fx.AdapterID) + } + if len(fx.NegativeCases) < 4 { + t.Fatalf("%s must have >= 4 negativeCases, got %d", id, len(fx.NegativeCases)) + } + + if fx.Mode == "twin" { + var doc *DeclarativeFormattedDoc + var ok bool + switch id { + case "fed-h15-datadownload": + doc, ok = FormatWave3FinanceTextDoc("fed_h15_csv", fx.MockPayload, nil, fx.InputURL) + case "nasdaq-data-link": + doc, ok = FormatWave3FinanceJSONDoc("nasdaq_data_link_json", []byte(fx.MockPayload), nil, fx.InputURL) + case "market-quotes-pack": + doc, ok = FormatWave3FinanceJSONDoc("market_quotes_json", []byte(fx.MockPayload), nil, fx.InputURL) + case "sec-xbrl-frames": + doc, ok = FormatWave3FinanceJSONDoc("sec_xbrl_frames_json", []byte(fx.MockPayload), nil, fx.InputURL) + } + if !ok || doc == nil { + t.Fatalf("%s golden twin extraction failed", id) + } + if fx.ExpectTitleIncludes != "" && !strings.Contains(doc.Title, fx.ExpectTitleIncludes) { + t.Fatalf("%s title %q missing %q", id, doc.Title, fx.ExpectTitleIncludes) + } + for _, needle := range fx.ExpectMarkdownIncludes { + if !strings.Contains(doc.Markdown, needle) { + t.Fatalf("%s markdown missing %q\nMarkdown:\n%s", id, needle, doc.Markdown) + } + } + if len(doc.Records) > 25 { + t.Fatalf("%s records > 25: %d", id, len(doc.Records)) + } + } else { + htmlMode := "" + switch id { + case "msrb-emma": + htmlMode = "msrb_emma_html" + case "ffiec-cdr": + htmlMode = "ffiec_cdr_html" + } + res := Wave3FinanceRunHTML(htmlMode, fx.MockPayload, fx.InputURL, id) + if res == nil || strings.TrimSpace(res.Markdown) == "" { + t.Fatalf("%s golden HTML extraction failed", id) + } + if fx.ExpectTitleIncludes != "" && !strings.Contains(res.Title, fx.ExpectTitleIncludes) { + t.Fatalf("%s title %q missing %q", id, res.Title, fx.ExpectTitleIncludes) + } + for _, needle := range fx.ExpectMarkdownIncludes { + if !strings.Contains(res.Markdown, needle) { + t.Fatalf("%s markdown missing %q\nMarkdown:\n%s", id, needle, res.Markdown) + } + } + if len(res.Records) > 25 { + t.Fatalf("%s records > 25: %d", id, len(res.Records)) + } + } + + for _, nc := range fx.NegativeCases { + ncURL := nc.InputURL + if ncURL == "" { + ncURL = fx.InputURL + } + checkURL := ncURL + if nc.FinalURL != "" { + checkURL = nc.FinalURL + } + if fx.Mode == "twin" { + var negOK bool + switch id { + case "fed-h15-datadownload": + _, negOK = FormatWave3FinanceTextMode("fed_h15_csv", nc.Payload, nil, checkURL) + case "nasdaq-data-link": + _, negOK = FormatWave3FinanceJSONMode("nasdaq_data_link_json", []byte(nc.Payload), nil, checkURL) + case "market-quotes-pack": + _, negOK = FormatWave3FinanceJSONMode("market_quotes_json", []byte(nc.Payload), nil, checkURL) + case "sec-xbrl-frames": + _, negOK = FormatWave3FinanceJSONMode("sec_xbrl_frames_json", []byte(nc.Payload), nil, checkURL) + } + if negOK { + t.Fatalf("%s:%s twin formatter must reject negative payload", id, nc.Name) + } + } else { + htmlMode := "msrb_emma_html" + if id == "ffiec-cdr" { + htmlMode = "ffiec_cdr_html" + } + if negRes := Wave3FinanceRunHTML(htmlMode, nc.Payload, checkURL, id); negRes != nil { + t.Fatalf("%s:%s HTML extractor must reject negative payload, got %+v", id, nc.Name, negRes) + } + } + + status := nc.Status + if status == 0 { + status = 200 + } + trimmedPayload := strings.TrimSpace(nc.Payload) + isJSONPayload := strings.HasPrefix(trimmedPayload, "{") || strings.HasPrefix(trimmedPayload, "[") + if status >= 200 && status < 300 && !isJSONPayload { + ext := ExtractHTMLDocumentFull(nc.Payload, FullExtractOptions{ + BaseURL: checkURL, + OnlyMainContent: true, + SkipUniversalExtractors: true, + SkipPlainText: true, + }) + cs := classify.ClassifyContentStateFull(classify.ContentStateInput{ + Status: status, + RawHTML: nc.Payload, + Markdown: ext.Markdown, + URL: ncURL, + FinalURL: nc.FinalURL, + Title: wave3FinExtractTitleBounded(nc.Payload), + }) + if cs.State == "active" { + t.Fatalf("%s:%s negative case must never classify as active (got %+v)", id, nc.Name, cs) + } + } + } + } +} + +func TestWave3FinanceR7MarkdownHardening(t *testing.T) { + registerWave3FinanceHTMLModes() + reInjectedHeading := regexp.MustCompile(`(?m)^#{1,6}[ \t]+.*(?:Injected|Pwned|EvilHeading)`) + + // 1. fed_h15_csv (heading, bullets, table header) + fedCSV := strings.Join([]string{ + `"Series Description","10Y Rate [Phish](https://evil.example/h15)"`, + `"Unit:","Percent"`, + `"Multiplier:","1"`, + `"Currency:","USD"`, + `"Unique Identifier:","H15/[Phish](https://evil.example/h15id)"`, + `"Time Period","Col [Phish](https://evil.example/h15col)"`, + `"2026-10-01","4.25"`, + }, "\n") + fedDoc, okFed := FormatWave3FinanceTextDoc("fed_h15_csv", fedCSV, nil, "https://www.federalreserve.gov/datadownload/Output.aspx?rel=H15&filetype=csv") + if !okFed || fedDoc == nil { + t.Fatal("expected FormatWave3FinanceTextDoc(fed_h15_csv) to succeed") + } + if hasUnescapedClickableEvilLinkR10(fedDoc.Markdown) || strings.Contains(fedDoc.Markdown, "[Phish](") || !strings.Contains(fedDoc.Markdown, `\[Phish\]`) { + t.Fatalf("fed_h15_csv leaked unescaped clickable link in Markdown:\n%s", fedDoc.Markdown) + } + if reInjectedHeading.MatchString(fedDoc.Markdown) { + t.Fatalf("fed_h15_csv allowed injected ATX heading:\n%s", fedDoc.Markdown) + } + if !strings.Contains(fedDoc.Title, "[Phish]") { + t.Fatalf("fed_h15_csv Title must remain unescaped plain text, got %q", fedDoc.Title) + } + + // 2. sec_xbrl_frames_json (Frames label/entityName + CompanyFacts entityName/cik backtick sanitization) + framesJSON := []byte(`{"taxonomy":"us-gaap","tag":"Assets","label":"Assets [Phish](https://evil.example/sec)","description":"Desc [Phish](https://evil.example/secdesc)","ccp":"CY2025Q4I","uom":"USD","pts":1,"data":[{"entityName":"Acme [Phish](https://evil.example/secent)","cik":12345,"loc":"US","end":"2025-12-31","val":1000,"accn":"0001-25-000001"}]}`) + framesDoc, okFrames := FormatWave3FinanceJSONDoc("sec_xbrl_frames_json", framesJSON, nil, "https://data.sec.gov/api/xbrl/frames/us-gaap/Assets/USD/CY2025Q4I.json") + if !okFrames || framesDoc == nil { + t.Fatal("expected FormatWave3FinanceJSONDoc(sec_xbrl_frames_json frames) to succeed") + } + if hasUnescapedClickableEvilLinkR10(framesDoc.Markdown) || strings.Contains(framesDoc.Markdown, "[Phish](") || !strings.Contains(framesDoc.Markdown, `\[Phish\]`) { + t.Fatalf("sec_xbrl_frames_json frames leaked unescaped clickable link:\n%s", framesDoc.Markdown) + } + if !strings.Contains(framesDoc.Title, "[Phish]") { + t.Fatalf("sec_xbrl_frames_json frames Title must remain unescaped plain text, got %q", framesDoc.Title) + } + + factsJSON := []byte(`{"cik":"123` + "`45`" + `","entityName":"Acme [Phish](https://evil.example/secf)","facts":{"us-gaap":{"Assets":{"label":"Assets","units":{"USD":[{"end":"2025-12-31","val":1000,"form":"10-K"}]}}}}}`) + factsDoc, okFacts := FormatWave3FinanceJSONDoc("sec_xbrl_frames_json", factsJSON, nil, "https://data.sec.gov/api/xbrl/companyfacts/CIK0000012345.json") + if !okFacts || factsDoc == nil { + t.Fatal("expected FormatWave3FinanceJSONDoc(sec_xbrl_frames_json companyfacts) to succeed") + } + if hasUnescapedClickableEvilLinkR10(factsDoc.Markdown) || strings.Contains(factsDoc.Markdown, "[Phish](") || !strings.Contains(factsDoc.Markdown, `\[Phish\]`) { + t.Fatalf("sec_xbrl_frames_json companyfacts leaked unescaped clickable link:\n%s", factsDoc.Markdown) + } + if !strings.Contains(factsDoc.Markdown, "`123'45'`") { + t.Fatalf("sec_xbrl_frames_json companyfacts must sanitize backticks in CIK inline code span:\n%s", factsDoc.Markdown) + } + + // 3. msrb_emma_html (h1, dl, table) + emmaHTML := `Bond [Phish](https://evil.example/emma)

Bond [Phish](https://evil.example/emma)

Issuer [Phish](https://evil.example/emmadt)
City [Phish](https://evil.example/emmadd)
Field [Phish](https://evil.example/emmath)Value
Series [Phish](https://evil.example/emmatd)2026A
` + emmaRes := Wave3FinanceRunHTML("msrb_emma_html", emmaHTML, "https://emma.msrb.org/Security/Details/123456789", "msrb-emma") + if emmaRes == nil { + t.Fatal("expected Wave3FinanceRunHTML(msrb_emma_html) to succeed") + } + if hasUnescapedClickableEvilLinkR10(emmaRes.Markdown) || strings.Contains(emmaRes.Markdown, "[Phish](") || !strings.Contains(emmaRes.Markdown, `\[Phish\]`) { + t.Fatalf("msrb_emma_html leaked unescaped clickable link in Markdown:\n%s", emmaRes.Markdown) + } + if reInjectedHeading.MatchString(emmaRes.Markdown) { + t.Fatalf("msrb_emma_html allowed injected ATX heading:\n%s", emmaRes.Markdown) + } + if !strings.Contains(emmaRes.Title, "[Phish]") { + t.Fatalf("msrb_emma_html Title must remain unescaped plain text, got %q", emmaRes.Title) + } +} + +func TestWave3FinanceM7SECCompanyFactsStreamingLatency(t *testing.T) { + // Simulate a 3.86 MiB SEC EDGAR companyfacts JSON payload and verify json.NewDecoder streaming stops after 25 concepts in < 25ms. + var sb strings.Builder + sb.WriteString(`{"cik":320193,"entityName":"Apple Inc.","facts":{"us-gaap":{`) + obsChunk := strings.Repeat(`{"end":"2025-12-31","val":1000000,"accn":"0000320193-26-000001","fy":2025,"fp":"FY","form":"10-K","filed":"2026-01-30"},`, 60) + + `{"end":"2026-03-31","val":1234567,"accn":"0000320193-26-000010","fy":2026,"fp":"Q1","form":"10-Q","filed":"2026-05-01"}` + for i := 0; i < 540; i++ { + if i > 0 { + sb.WriteByte(',') + } + sb.WriteString(fmt.Sprintf(`"Concept%03d":{"label":"Concept %03d","units":{"USD":[%s]}}`, i, i, obsChunk)) + } + sb.WriteString(`}}}`) + payload := []byte(sb.String()) + if len(payload) < 3_500_000 { + t.Fatalf("expected >3.5 MiB test payload, got %d", len(payload)) + } + start := time.Now() + doc, ok := FormatWave3FinanceJSONDoc("sec_xbrl_frames_json", payload, nil, "https://data.sec.gov/api/xbrl/companyfacts/CIK0000320193.json") + elapsed := time.Since(start) + if !ok || doc == nil || len(doc.Records) != 25 || doc.Truncated == nil || !*doc.Truncated { + t.Fatalf("sec_xbrl_frames_json streaming companyfacts failed: ok=%v doc=%+v", ok, doc) + } + if !strings.Contains(doc.Title, "Apple Inc.") || !strings.Contains(doc.Markdown, "320193") || !strings.Contains(doc.Markdown, "Concept000") { + t.Fatalf("unexpected streaming companyfacts doc: title=%q md=\n%s", doc.Title, doc.Markdown) + } + if budget := 25 * time.Millisecond * time.Duration(extractRaceSlowdown); elapsed > budget { + t.Fatalf("sec_xbrl_frames_json 3.86 MiB streaming exceeded %v budget: %v", budget, elapsed) + } +} diff --git a/internal/extract/wave3_gov.go b/internal/extract/wave3_gov.go new file mode 100644 index 0000000..b29db6d --- /dev/null +++ b/internal/extract/wave3_gov.go @@ -0,0 +1,2814 @@ +package extract + +import ( + "bytes" + "encoding/json" + stdhtml "html" + "math" + "net/url" + "strconv" + "strings" +) + +const ( + wave3GovMaxHTMLBytes = 2 * 1024 * 1024 + wave3GovMaxJSONBytes = 4 * 1024 * 1024 + wave3GovMaxTextBytes = 4 * 1024 * 1024 + wave3GovMaxRecords = 25 +) + +var ( + wave3GovRxNotFoundTitle = newLazyRegexp(`(?i)(?:^|\b)(?:404|410|406|page\s+not\s+found|not\s+found|not\s+acceptable|error\s*404|we\s+couldn'?t\s+find\s+that\s+page|access\s+denied|request\s+(?:rejected|blocked)|could\s+not\s+be\s+satisfied|unauthorized|attention\s+required|just\s+a\s+moment|403\s+forbidden|forbidden|403\s+error)(?:\b|$)`) + wave3GovRxMaintTitle = newLazyRegexp(`(?i)(?:scheduled\s+maintenance|temporarily\s+unavailable|service\s+unavailable|site\s+maintenance|under\s+maintenance|502\s+bad\s+gateway|503\s+service|down\s+for\s+maintenance)`) + wave3GovRxErrorTitle = newLazyRegexp(`(?i)^(?:(?:(?:401|403|404|406|410|429|500|502|503)\s+)?(?:internal\s+)?server\s+error|application\s+error|system\s+error|unexpected\s+error|error\s+page|(?:401|403|404|406|410|429|500|502|503|http\s+\d{3})\s+error|error\s+(?:401|403|404|406|410|429|500|502|503)|error|str_error_page_title|opengov\s*[\-\x{2013}\x{2014}]\s*page\s+not\s+found)(?:\s*[|\-\x{2013}\x{2014}:]\s*.*)?$|^.*(?:\s*[|\-\x{2013}\x{2014}:]\s*error)$`) + wave3GovRxGenericTitle = newLazyRegexp(`(?i)^(?:loading\.{0,3}|home|welcome|welcome\s+to\s+portal\s+home|search|message\s+bar|accela\s+citizen\s+access|selfservice\s+public\s+site|arcgis\s+hub|public\s+portal(?:\s*[\|\-\x{2022}]\s*civicclerk)?)$`) + wave3GovRxHTMLTag = newLazyRegexp(`<[^>]+>`) + wave3GovRxSpaceCollapse = newLazyRegexp(`[ \t\r\n]+`) + wave3GovRxHref = newLazyRegexp(`(?i)]*\bhref\s*=\s*["']([^"'#][^"']*)["'][^>]*>(.*?)`) + wave3GovRxTRow = newLazyRegexp(`(?is)]*>(.*?)`) + wave3GovRxTCell = newLazyRegexp(`(?is)]*>(.*?)`) + wave3GovRxDateLike = newLazyRegexp(`\b(?:\d{4}-\d{2}-\d{2}|\d{1,2}/\d{1,2}/\d{2,4}|(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*\s+\d{1,2},\s+\d{4})\b`) +) + +func init() { + for _, mode := range []string{ + "govdelivery_html", + "municipal_cms_html", + "boarddocs_html", + "civicclerk_html", + "primegov_html", + "agenda_portal_html", + "accela_html", + "tyler_energov_html", + "opengov_html", + "public_bid_html", + "arcgis_hub_html", + "junar_tyler_html", + } { + m := mode + RegisterExternalHTMLModeLazy(m, func(rawHTML, baseURL string, _ func() string, extractorID string) *DeclarativePostFetchResult { + return wave3GovRunHTMLModeCore(m, rawHTML, baseURL, extractorID) + }) + } +} + +// IsWave3GovHTMLMode reports whether mode is one of the Category A Local Government HTML extractors (#202-#216). +func IsWave3GovHTMLMode(mode string) bool { + switch mode { + case "govdelivery_html", + "municipal_cms_html", + "boarddocs_html", + "civicclerk_html", + "primegov_html", + "agenda_portal_html", + "accela_html", + "tyler_energov_html", + "opengov_html", + "public_bid_html", + "arcgis_hub_html", + "junar_tyler_html": + return true + default: + return false + } +} + +// RunWave3GovHTMLMode executes a Category A HTML extractor and returns JSON-marshaled DeclarativePostFetchResult. +func RunWave3GovHTMLMode(mode, rawHTML, baseURL string) (string, bool) { + if !IsWave3GovHTMLMode(mode) || strings.TrimSpace(rawHTML) == "" { + return "", false + } + res := wave3GovRunHTMLModeCore(mode, rawHTML, baseURL, wave3GovDefaultExtractorID(mode)) + res = sanitizePostFetchResultDeclHTML(res) + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return "", false + } + encoded, err := json.Marshal(res) + if err != nil { + return "", false + } + return string(encoded), true +} + +// IsWave3GovJSONMode reports whether mode is one of the Category A Local Government JSON formatters. +func IsWave3GovJSONMode(mode string) bool { + switch mode { + case "civicclerk_json", + "primegov_json", + "tyler_energov_json", + "opengov_json", + "arcgis_hub_json", + "junar_tyler_json": + return true + default: + return false + } +} + +// FormatWave3GovJSONDoc formats a Category A JSON twin payload into DeclarativeFormattedDoc. +func FormatWave3GovJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool) { + if !IsWave3GovJSONMode(mode) || len(raw) == 0 || len(raw) > wave3GovMaxJSONBytes { + return nil, false + } + trimmed := bytes.TrimSpace(bytes.TrimPrefix(raw, []byte("\xEF\xBB\xBF"))) + if len(trimmed) == 0 || (trimmed[0] != '{' && trimmed[0] != '[') { + return nil, false + } + parsed, ok := decodeJSONWithNumbers(trimmed) + if !ok || parsed == nil { + return nil, false + } + + var doc *DeclarativeFormattedDoc + var handled bool + switch mode { + case "civicclerk_json": + doc, handled = wave3GovFormatCivicClerkJSON(parsed, origURL) + case "primegov_json": + doc, handled = wave3GovFormatPrimeGovJSON(parsed, origURL) + case "tyler_energov_json": + doc, handled = wave3GovFormatEnerGovJSON(parsed, origURL) + case "opengov_json": + doc, handled = wave3GovFormatOpenGovJSON(parsed, origURL) + case "arcgis_hub_json": + doc, handled = wave3GovFormatArcGISHubJSON(parsed, origURL) + case "junar_tyler_json": + doc, handled = wave3GovFormatJunarTylerJSON(parsed, origURL) + } + if !handled || doc == nil || strings.TrimSpace(doc.Markdown) == "" { + return nil, false + } + return wave3GovFinalizeDoc(doc), true +} + +// FormatWave3GovJSONMode formats a Category A JSON payload and returns JSON-marshaled DeclarativeFormattedDoc. +func FormatWave3GovJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool) { + doc, ok := FormatWave3GovJSONDoc(mode, raw, params, origURL) + if !ok || doc == nil { + return "", false + } + encoded, err := json.Marshal(doc) + if err != nil { + return "", false + } + return string(encoded), true +} + +// IsWave3GovTextMode reports whether mode is handled by Category A text/XML/mixed formatters (`boarddocs_text`). +func IsWave3GovTextMode(mode string) bool { + return mode == "boarddocs_text" +} + +// FormatWave3GovTextDoc formats a Category A text/XML/JSON payload (BoardDocs Domino responses). +func FormatWave3GovTextDoc(mode, rawBody string, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool) { + if !IsWave3GovTextMode(mode) || len(rawBody) == 0 || len(rawBody) > wave3GovMaxTextBytes { + return nil, false + } + doc, ok := wave3GovFormatBoardDocsText(rawBody, params, origURL) + if !ok || doc == nil || strings.TrimSpace(doc.Markdown) == "" { + return nil, false + } + return wave3GovFinalizeDoc(doc), true +} + +// FormatWave3GovTextMode formats a Category A text payload and returns JSON-marshaled DeclarativeFormattedDoc. +func FormatWave3GovTextMode(mode, rawBody string, params map[string]string, origURL string) (string, bool) { + doc, ok := FormatWave3GovTextDoc(mode, rawBody, params, origURL) + if !ok || doc == nil { + return "", false + } + encoded, err := json.Marshal(doc) + if err != nil { + return "", false + } + return string(encoded), true +} + +func wave3GovDefaultExtractorID(mode string) string { + switch mode { + case "govdelivery_html": + return "granicus-govdelivery" + case "municipal_cms_html": + return "municipal-cms-pack" + case "boarddocs_html": + return "boarddocs" + case "civicclerk_html": + return "civicclerk" + case "primegov_html": + return "primegov" + case "agenda_portal_html": + return "agenda-portal-pack" + case "accela_html": + return "accela-citizen-access" + case "tyler_energov_html": + return "tyler-energov" + case "opengov_html": + return "opengov-portals" + case "public_bid_html": + return "public-bid-portals" + case "arcgis_hub_html": + return "arcgis-hub" + case "junar_tyler_html": + return "junar-tyler-data" + default: + return "" + } +} + +func wave3GovRunHTMLModeCore(mode, rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + if len(rawHTML) == 0 || strings.IndexByte(rawHTML, '<') < 0 || strings.IndexByte(rawHTML, '>') < 0 { + return nil + } + if len(rawHTML) > wave3GovMaxHTMLBytes { + rawHTML = truncateUTF8SafeFullDocGo(rawHTML, wave3GovMaxHTMLBytes) + } + trimmedStart := strings.TrimLeft(rawHTML, " \t\r\n") + if trimmedStart == "" || trimmedStart[0] == '{' || trimmedStart[0] == '[' { + return nil + } + probe := rawHTML + if len(probe) > 65536 { + probe = probe[:65536] + } + probeLower := asciiLowerExtractString(probe) + urlLower := asciiLowerExtractString(baseURL) + + // Cheap byte prefilter BEFORE common negative-shell checks or DOM extraction. + if !wave3GovMatchesModePrefilter(mode, probeLower, urlLower) { + return nil + } + if wave3GovHasCommonNegativeShell(rawHTML, probeLower, baseURL, urlLower) { + return nil + } + if extractorID == "" { + extractorID = wave3GovDefaultExtractorID(mode) + } + + switch mode { + case "govdelivery_html": + return wave3GovExtractGovDeliveryHTML(rawHTML, probeLower, baseURL, extractorID) + case "municipal_cms_html": + return wave3GovExtractMunicipalCMSHTML(rawHTML, probeLower, baseURL, extractorID) + case "boarddocs_html": + return wave3GovExtractBoardDocsHTML(rawHTML, probeLower, baseURL, extractorID) + case "civicclerk_html": + return wave3GovExtractCivicClerkHTML(rawHTML, probeLower, baseURL, extractorID) + case "primegov_html": + return wave3GovExtractPrimeGovHTML(rawHTML, probeLower, baseURL, extractorID) + case "agenda_portal_html": + return wave3GovExtractAgendaPortalHTML(rawHTML, probeLower, baseURL, extractorID) + case "accela_html": + return wave3GovExtractAccelaHTML(rawHTML, probeLower, baseURL, extractorID) + case "tyler_energov_html": + return wave3GovExtractEnerGovHTML(rawHTML, probeLower, baseURL, extractorID) + case "opengov_html": + return wave3GovExtractOpenGovHTML(rawHTML, probeLower, baseURL, extractorID) + case "public_bid_html": + return wave3GovExtractPublicBidHTML(rawHTML, probeLower, baseURL, urlLower, extractorID) + case "arcgis_hub_html": + return wave3GovExtractArcGISHubHTML(rawHTML, probeLower, baseURL, extractorID) + case "junar_tyler_html": + return wave3GovExtractJunarTylerHTML(rawHTML, probeLower, baseURL, urlLower, extractorID) + default: + return nil + } +} + +func wave3GovMatchesModePrefilter(mode, probeLower, urlLower string) bool { + switch mode { + case "govdelivery_html": + return strings.Contains(probeLower, "shared_bulletin") || + strings.Contains(probeLower, "bulletin_display") || + strings.Contains(probeLower, "bulletin_content") || + strings.Contains(probeLower, "bulletin_subject") || + strings.Contains(probeLower, "bulletin_body") || + strings.Contains(urlLower, "govdelivery.com") + case "municipal_cms_html": + return strings.Contains(probeLower, "revize") || + strings.Contains(probeLower, "opencities") || + strings.Contains(probeLower, "visioninternet") || + strings.Contains(probeLower, "revizebaseurl") + case "boarddocs_html": + return strings.Contains(probeLower, "boarddocs") || + strings.Contains(probeLower, "board.nsf") || + strings.Contains(probeLower, "bd-get") || + strings.Contains(urlLower, "boarddocs.com") + case "civicclerk_html": + return strings.Contains(probeLower, "civicclerk") || + strings.Contains(urlLower, "civicclerk.com") + case "primegov_html": + return strings.Contains(probeLower, "primegov") || + strings.Contains(probeLower, "publicportal") || + strings.Contains(urlLower, "primegov.com") + case "agenda_portal_html": + return strings.Contains(probeLower, "escribemeetings") || + strings.Contains(probeLower, "novusagenda") || + strings.Contains(probeLower, "civicweb") || + strings.Contains(probeLower, "agendasearch-") || + strings.Contains(probeLower, "meetingtypelistbox") || + strings.Contains(probeLower, "icompass") || + strings.Contains(urlLower, "escribemeetings.com") || + strings.Contains(urlLower, "novusagenda.com") || + strings.Contains(urlLower, "civicweb.net") + case "accela_html": + return strings.Contains(probeLower, "accela") || + strings.Contains(probeLower, "ctl00_placeholdermain_lblpermitnumber") || + strings.Contains(probeLower, "ctl00_placeholdermain_lblpermittype") || + strings.Contains(urlLower, "capdetail.aspx") || + strings.Contains(urlLower, "/citizenaccess/") + case "tyler_energov_html": + return strings.Contains(probeLower, "energov") && + (strings.Contains(probeLower, "selfservice") || + strings.Contains(probeLower, `ng-app="app.main"`) || + strings.Contains(probeLower, "energovprod") || + strings.Contains(urlLower, "selfservice")) + case "opengov_html": + return strings.Contains(probeLower, "opengov") || + strings.Contains(probeLower, "window.__og_zeus") || + strings.Contains(probeLower, "rapp_standalone") || + strings.Contains(urlLower, "opengov.com") + case "public_bid_html": + return strings.Contains(probeLower, "bidnet") || + strings.Contains(probeLower, "bonfirehub") || + strings.Contains(probeLower, "bidsync") || + strings.Contains(probeLower, "periscope") || + strings.Contains(probeLower, "mets-field") || + strings.Contains(urlLower, "bidnetdirect.com") || + strings.Contains(urlLower, "bonfirehub.com") || + strings.Contains(urlLower, "bidsync.com") + case "arcgis_hub_html": + return strings.Contains(probeLower, "arcgis hub") || + strings.Contains(probeLower, "hub.arcgis.com") || + strings.Contains(probeLower, "opendata.arcgis.com") || + strings.Contains(probeLower, "arcgis-hub") || + strings.Contains(urlLower, "hub.arcgis.com") || + strings.Contains(urlLower, "opendata.arcgis.com") || + strings.Contains(urlLower, "opendata.dc.gov") + case "junar_tyler_html": + return strings.Contains(probeLower, "junar") || + strings.Contains(probeLower, "datastreambox") || + strings.Contains(probeLower, "datastream/datatable") || + strings.Contains(probeLower, "dataviews/") || + strings.Contains(urlLower, "junar.com") || + strings.Contains(urlLower, "data.paloalto.gov") || + strings.Contains(urlLower, "data.tylertech.com") + default: + return false + } +} + +// ── Shared Negative-Shell, Sanitizing & DOM Helpers ────────────────────────────────────────────── + +func wave3GovIsNegativeURL(urlLower string) bool { + if urlLower == "" { + return false + } + if strings.Contains(urlLower, "/404") || + strings.Contains(urlLower, "/not-found") || + strings.Contains(urlLower, "/maintenance") || + strings.Contains(urlLower, "error=true") { + return true + } + pathOnly := urlLower + if idx := strings.Index(pathOnly, "://"); idx >= 0 { + rest := pathOnly[idx+3:] + if slash := strings.IndexByte(rest, '/'); slash >= 0 { + pathOnly = rest[slash:] + } else { + pathOnly = "/" + } + } + if cut := strings.IndexAny(pathOnly, "?#"); cut >= 0 { + pathOnly = pathOnly[:cut] + } + return strings.HasSuffix(pathOnly, "/error") || + strings.Contains(pathOnly, "/error/") || + strings.HasSuffix(pathOnly, "/error.html") || + strings.HasSuffix(pathOnly, "/error.htm") || + strings.HasSuffix(pathOnly, "/error.aspx") || + strings.HasSuffix(pathOnly, "/login") || + strings.Contains(pathOnly, "/login/") +} + +func wave3GovIsNegativeTitle(title string) bool { + t := strings.TrimSpace(title) + if t == "" { + return false + } + return wave3GovRxNotFoundTitle.MatchString(t) || + wave3GovRxMaintTitle.MatchString(t) || + wave3GovRxErrorTitle.MatchString(t) +} + +func wave3GovIsGenericTitle(title string) bool { + return wave3GovRxGenericTitle.MatchString(strings.TrimSpace(title)) +} + +func wave3GovHasCommonNegativeShell(rawHTML, probeLower, baseURL, urlLower string) bool { + if wave3GovIsNegativeURL(urlLower) { + return true + } + for _, marker := range []string{ + "cf-browser-verification", + "cf-turnstile", + "challenge-platform", + "_cf_chl_opt", + "cf_chl_opt", + "attention required! | cloudflare", + "just a moment...", + "errors.edgesuite.net", + "error from cloudfront", + "the request could not be satisfied", + "you don't have permission to access", + "access denied", + "403 forbidden", + "not acceptable", + "window.kpsdk", + "kp_uidz", + "_incapsula_resource", + "incapsula incident", + "x-amzn-waf-action", + } { + if strings.Contains(probeLower, marker) { + return true + } + } + title := extractTitleLinearQuick(rawHTML) + if wave3GovIsNegativeTitle(title) { + return true + } + if len(rawHTML) < 8192 && + (strings.Contains(probeLower, `
`) || + strings.Contains(probeLower, `
`) || + strings.Contains(probeLower, `
`) || + strings.Contains(probeLower, ``)) && + !strings.Contains(probeLower, "__og_zeus_global_vars") && + !strings.Contains(probeLower, "reporting-classic-app") && + !strings.Contains(probeLower, "window.gon") && + !hasJSONLDScriptToken(rawHTML) && + !strings.Contains(probeLower, " 0 { + return true + } + case map[string]any: + if len(tv) > 0 { + return true + } + case bool: + if tv { + return true + } + } + } + } + for _, k := range []string{"error_code", "statusCode", "status_code", "status"} { + if f, ok := wave3GovFloatVal(obj[k]); ok && f >= 400 { + return true + } + } + if st := strings.ToUpper(wave3GovPlain(obj["status"], 48)); st == "ERROR" || st == "NOT_FOUND" || st == "PERMISSION_DENIED" || st == "UNAUTHENTICATED" || st == "NOTAUTHENTICATED" { + return true + } + if msg := wave3GovPlain(obj["message"], 200); msg != "" && len(obj) <= 3 { + lm := strings.ToLower(msg) + if strings.Contains(lm, "unauthorized") || strings.Contains(lm, "not found") || + strings.Contains(lm, "invalid") || strings.Contains(lm, "forbidden") || + strings.Contains(lm, "notauthenticated") || strings.Contains(lm, "no http resource") { + return true + } + } + return false +} + +func wave3GovCleanText(s string) string { + if s == "" { + return "" + } + if strings.IndexByte(s, '<') >= 0 { + s = wave3GovRxHTMLTag.ReplaceAllString(s, " ") + } + if strings.IndexByte(s, '&') >= 0 { + s = stdhtml.UnescapeString(s) + } + return strings.TrimSpace(wave3GovRxSpaceCollapse.ReplaceAllString(s, " ")) +} + +func wave3GovPlain(v any, maxLen int) string { + return SanitizeSchemaPlainField(wave3GovStringVal(v), maxLen) +} + +func wave3GovFirstNonEmpty(vals ...string) string { + for _, v := range vals { + if t := strings.TrimSpace(v); t != "" { + return t + } + } + return "" +} + +func wave3GovStringVal(v any) string { + switch tv := v.(type) { + case string: + return strings.TrimSpace(tv) + case json.Number: + return tv.String() + case float64: + if math.IsNaN(tv) || math.IsInf(tv, 0) { + return "" + } + if tv == math.Trunc(tv) { + return strconv.FormatInt(int64(tv), 10) + } + return strconv.FormatFloat(tv, 'f', -1, 64) + case int: + return strconv.Itoa(tv) + case int64: + return strconv.FormatInt(tv, 10) + case bool: + if tv { + return "true" + } + return "false" + default: + return "" + } +} + +func wave3GovFloatVal(v any) (float64, bool) { + switch tv := v.(type) { + case float64: + if math.IsNaN(tv) || math.IsInf(tv, 0) { + return 0, false + } + return tv, true + case int: + return float64(tv), true + case int64: + return float64(tv), true + case json.Number: + f, err := tv.Float64() + if err != nil || math.IsNaN(f) || math.IsInf(f, 0) { + return 0, false + } + return f, true + case string: + s := strings.TrimSpace(strings.ReplaceAll(tv, ",", "")) + if s == "" { + return 0, false + } + f, err := strconv.ParseFloat(s, 64) + if err != nil || math.IsNaN(f) || math.IsInf(f, 0) { + return 0, false + } + return f, true + default: + return 0, false + } +} + +func wave3GovMap(v any) map[string]any { + if m, ok := v.(map[string]any); ok { + return m + } + return nil +} + +func wave3GovSlice(v any) []any { + if s, ok := v.([]any); ok { + return s + } + return nil +} + +func wave3GovIntPtr(n int) *int { + v := n + return &v +} + +func wave3GovBoolPtr(b bool) *bool { + v := b + return &v +} + +func wave3GovAddLink(links *[]string, seen map[string]bool, raw, base string) { + u := SanitizeSchemaHTTPSURL(raw, base) + if u != "" && !seen[u] { + seen[u] = true + *links = append(*links, u) + } +} + +func wave3GovExtractH1(rawHTML string) string { + inner, ok := findElementInnerLinearDeclHTML(rawHTML, "h1", nil, 0) + if !ok { + return "" + } + return wave3GovCleanText(inner) +} + +func wave3GovExtractMeta(rawHTML, key string) string { + target := strings.ToLower(strings.TrimSpace(key)) + pos := 0 + for i := 0; i < 64 && pos < len(rawHTML); i++ { + open, ok := findOpenTagLinearDeclHTML(rawHTML, "meta", nil, pos) + if !ok { + break + } + pos = open.openEnd + nameVal, _ := getAttrValueLinearDeclHTML(open.attrStr, "name") + propVal, _ := getAttrValueLinearDeclHTML(open.attrStr, "property") + if strings.EqualFold(strings.TrimSpace(nameVal), target) || strings.EqualFold(strings.TrimSpace(propVal), target) { + if content, okC := getAttrValueLinearDeclHTML(open.attrStr, "content"); okC { + return wave3GovCleanText(content) + } + } + } + return "" +} + +func wave3GovExtractByID(rawHTML, tagName, id string) string { + if strings.EqualFold(tagName, "div") { + open, ok := findOpenTagLinearDeclHTML(rawHTML, "div", func(attrStr string) bool { + v, okID := getAttrValueLinearDeclHTML(attrStr, "id") + return okID && strings.EqualFold(strings.TrimSpace(v), id) + }, 0) + if !ok { + return "" + } + if inner, okB := extractBalancedDivAtDeclHTML(rawHTML, open.index); okB { + return inner + } + return "" + } + inner, ok := findElementInnerLinearDeclHTML(rawHTML, tagName, func(attrStr string) bool { + v, okID := getAttrValueLinearDeclHTML(attrStr, "id") + return okID && strings.EqualFold(strings.TrimSpace(v), id) + }, 0) + if !ok { + return "" + } + return inner +} + +func wave3GovExtractByClassSub(rawHTML, tagName, classNeedle string) string { + needle := strings.ToLower(classNeedle) + if strings.EqualFold(tagName, "div") { + open, ok := findOpenTagLinearDeclHTML(rawHTML, "div", func(attrStr string) bool { + v, okC := getAttrValueLinearDeclHTML(attrStr, "class") + return okC && strings.Contains(strings.ToLower(v), needle) + }, 0) + if !ok { + return "" + } + if inner, okB := extractBalancedDivAtDeclHTML(rawHTML, open.index); okB { + return inner + } + return "" + } + inner, ok := findElementInnerLinearDeclHTML(rawHTML, tagName, func(attrStr string) bool { + v, okC := getAttrValueLinearDeclHTML(attrStr, "class") + return okC && strings.Contains(strings.ToLower(v), needle) + }, 0) + if !ok { + return "" + } + return inner +} + +func wave3GovFragToMD(frag, baseURL string) string { + if strings.TrimSpace(frag) == "" { + return "" + } + doc := ExtractHTMLDocumentFull(""+frag+"", FullExtractOptions{ + BaseURL: baseURL, + OnlyMainContent: false, + IncludeImages: false, + IsFragment: true, + SkipUniversalExtractors: true, + SkipPlainText: true, + }) + return strings.TrimSpace(doc.Markdown) +} + +func wave3GovExtractLinks(frag, baseURL string, maxLinks int) []struct{ Text, URL string } { + matches := wave3GovRxHref.FindAllStringSubmatch(frag, maxLinks*3) + out := make([]struct{ Text, URL string }, 0, maxLinks) + seen := make(map[string]bool) + for _, m := range matches { + if len(out) >= maxLinks { + break + } + if len(m) < 3 { + continue + } + u := SanitizeSchemaHTTPSURL(stdhtml.UnescapeString(strings.TrimSpace(m[1])), baseURL) + if u == "" || seen[u] { + continue + } + txt := wave3GovCleanText(m[2]) + if txt == "" { + continue + } + seen[u] = true + out = append(out, struct{ Text, URL string }{Text: txt, URL: u}) + } + return out +} + +func wave3GovExtractBalancedJSONAfterNeedle(src, needle string, maxScan int) map[string]any { + var emptyFallback map[string]any + offset := 0 + for attempt := 0; attempt < 6 && offset < len(src); attempt++ { + rel := strings.Index(src[offset:], needle) + if rel < 0 { + break + } + after := offset + rel + len(needle) + openRel := strings.IndexByte(src[after:], '{') + if openRel < 0 { + break + } + openIdx := after + openRel + depth := 0 + inStr := false + esc := false + endCap := openIdx + maxScan + if endCap > len(src) { + endCap = len(src) + } + matchedEnd := -1 + for i := openIdx; i < endCap; i++ { + ch := src[i] + if inStr { + if esc { + esc = false + } else if ch == '\\' { + esc = true + } else if ch == '"' { + inStr = false + } + continue + } + switch ch { + case '"': + inStr = true + case '{': + depth++ + case '}': + depth-- + if depth == 0 { + matchedEnd = i + if parsed, ok := decodeJSONWithNumbers([]byte(src[openIdx : i+1])); ok { + if obj, _ := parsed.(map[string]any); obj != nil { + if len(obj) > 0 { + return obj + } + if emptyFallback == nil { + emptyFallback = obj + } + } + } + } + } + if matchedEnd >= 0 { + break + } + } + offset = after + } + return emptyFallback +} + +func wave3GovHasType(obj map[string]any, wanted ...string) bool { + ts := strings.ToLower(jsonLDTypeStringDeclHTML(obj)) + if ts == "" { + return false + } + for _, part := range strings.Split(ts, ",") { + p := strings.TrimSpace(part) + if idx := strings.LastIndexByte(p, '/'); idx >= 0 { + p = p[idx+1:] + } + if idx := strings.LastIndexByte(p, ':'); idx >= 0 { + p = p[idx+1:] + } + for _, w := range wanted { + if p == strings.ToLower(w) { + return true + } + } + } + return false +} + +func wave3GovNameField(v any) string { + switch tv := v.(type) { + case string: + return wave3GovCleanText(tv) + case map[string]any: + if n := wave3GovCleanText(wave3GovStringVal(tv["name"])); n != "" { + return n + } + if d := wave3GovMap(tv["data"]); d != nil { + return wave3GovCleanText(wave3GovStringVal(d["name"])) + } + return "" + case []any: + var parts []string + for _, el := range tv { + if n := wave3GovNameField(el); n != "" { + parts = append(parts, n) + } + } + return strings.Join(parts, ", ") + default: + return "" + } +} + +func wave3GovStripHeaderChrome(rawHTML string) string { + out := rawHTML + for _, tag := range []string{"header", "nav"} { + for i := 0; i < 6; i++ { + open, ok := findOpenTagLinearDeclHTML(out, tag, nil, 0) + if !ok { + break + } + _, closeEnd, okClose := findCloseTagLinearDeclHTML(out, tag, open.openEnd) + if !okClose { + break + } + out = out[:open.index] + " " + out[closeEnd:] + } + } + return out +} + +func wave3GovFinalizeDoc(doc *DeclarativeFormattedDoc) *DeclarativeFormattedDoc { + if doc == nil { + return nil + } + doc.Title = SanitizeScrapedMeta(doc.Title) + doc.Description = SanitizeScrapedMeta(doc.Description) + doc.Author = SanitizeScrapedMeta(doc.Author) + doc.PublishedTime = SanitizeSchemaPlainField(doc.PublishedTime, 64) + doc.Markdown = SanitizeScrapedMarkdown(escapeDangerousRawHTMLOutsideFencesDeclGo(doc.Markdown)) + if len(doc.Links) > 0 { + clean := make([]string, 0, len(doc.Links)) + seen := make(map[string]bool, len(doc.Links)) + for _, l := range doc.Links { + if u := SanitizeSchemaHTTPSURL(l, ""); u != "" && !seen[u] { + seen[u] = true + clean = append(clean, u) + } + } + doc.Links = clean + } + if len(doc.Records) > wave3GovMaxRecords { + total := len(doc.Records) + if doc.Total != nil && *doc.Total > total { + total = *doc.Total + } + doc.Records = doc.Records[:wave3GovMaxRecords] + doc.Total = wave3GovIntPtr(total) + doc.Returned = wave3GovIntPtr(len(doc.Records)) + doc.Truncated = wave3GovBoolPtr(true) + if doc.NextCursor == "" { + doc.NextCursor = strconv.Itoa(len(doc.Records)) + } + } else if len(doc.Records) > 0 { + if doc.Returned == nil { + doc.Returned = wave3GovIntPtr(len(doc.Records)) + } + if doc.Total == nil { + doc.Total = wave3GovIntPtr(len(doc.Records)) + } + } + return doc +} + +func wave3GovCapRecords(recs []map[string]any, total int) ([]map[string]any, *int, *int, *bool) { + if len(recs) == 0 { + return nil, nil, nil, nil + } + if total < len(recs) { + total = len(recs) + } + if len(recs) > wave3GovMaxRecords { + recs = recs[:wave3GovMaxRecords] + return recs, wave3GovIntPtr(total), wave3GovIntPtr(len(recs)), wave3GovBoolPtr(true) + } + trunc := total > len(recs) + if trunc { + return recs, wave3GovIntPtr(total), wave3GovIntPtr(len(recs)), wave3GovBoolPtr(true) + } + return recs, wave3GovIntPtr(total), wave3GovIntPtr(len(recs)), nil +} + +func wave3GovHostFromURL(rawURL string) string { + u, err := url.Parse(strings.TrimSpace(rawURL)) + if err != nil { + return "" + } + return strings.TrimSuffix(strings.ToLower(u.Hostname()), ".") +} + +func wave3GovMDCell(s string) string { + s = strings.ReplaceAll(s, "|", "\\|") + s = strings.ReplaceAll(s, "\n", " ") + return strings.TrimSpace(s) +} + +// ── #202 Granicus GovDelivery (`govdelivery_html`) ─────────────────────────────────────────────── + +func wave3GovExtractGovDeliveryBodyFrag(slimHTML string) string { + for _, id := range []string{"bulletin_body", "bulletin_content", "shared_bulletin"} { + if frag := wave3GovExtractByID(slimHTML, "div", id); frag != "" { + return frag + } + } + for _, cls := range []string{"bulletin_body", "bulletin_content"} { + if frag := wave3GovExtractByClassSub(slimHTML, "div", cls); frag != "" { + return frag + } + } + // Email HTML inside #bulletin_body / #bulletin_content frequently contains unclosed
tags + // that cause balanced-div depth matching to reach EOF. Slice boundedly up to bulletin_footer / . + for _, id := range []string{"bulletin_body", "bulletin_content", "shared_bulletin"} { + open, ok := findOpenTagLinearDeclHTML(slimHTML, "div", func(attrStr string) bool { + v, okID := getAttrValueLinearDeclHTML(attrStr, "id") + return okID && strings.EqualFold(strings.TrimSpace(v), id) + }, 0) + if !ok || open.selfClosing || open.openEnd >= len(slimHTML) { + continue + } + tail := slimHTML[open.openEnd:] + if len(tail) > 262_144 { + tail = truncateUTF8SafeFullDocGo(tail, 262_144) + } + endIdx := len(tail) + for _, stopNeedle := range []string{`id="bulletin_footer"`, `id='bulletin_footer'`, `class="bulletin_footer"`, `class='bulletin_footer'`, "= 0 && idx < endIdx { + if lt := strings.LastIndexByte(tail[:idx], '<'); lt >= 0 { + endIdx = lt + } else { + endIdx = idx + } + } + } + if endIdx > 0 { + return tail[:endIdx] + } + } + if mFrag, okM := findElementInnerLinearDeclHTML(slimHTML, "main", nil, 0); okM && strings.TrimSpace(mFrag) != "" { + return mFrag + } + if aFrag, okA := findElementInnerLinearDeclHTML(slimHTML, "article", nil, 0); okA && strings.TrimSpace(aFrag) != "" { + return aFrag + } + // Email-style GovDelivery templates wrap the entire bulletin inside a layout . + bestTable := "" + pos := 0 + for i := 0; i < 8 && pos < len(slimHTML); i++ { + openT, okT := findOpenTagLinearDeclHTML(slimHTML, "table", nil, pos) + if !okT { + break + } + if openT.selfClosing { + pos = openT.openEnd + continue + } + innerT, okInner := findElementInnerLinearDeclHTML(slimHTML, "table", nil, openT.index) + if okInner && len(innerT) > len(bestTable) { + bestTable = innerT + } + pos = openT.openEnd + if okInner { + pos = openT.openEnd + len(innerT) + } + } + if len(strings.Fields(wave3GovCleanText(bestTable))) >= 5 { + return bestTable + } + if bFrag, okB := findElementInnerLinearDeclHTML(slimHTML, "body", nil, 0); okB { + return bFrag + } + return "" +} + +func wave3GovExtractGovDeliveryHTML(rawHTML, probeLower, baseURL, extractorID string) *DeclarativePostFetchResult { + headProbe := rawHTML + if len(headProbe) > 131_072 { + headProbe = truncateUTF8SafeFullDocGo(headProbe, 131_072) + } + slimHTML := stripScriptsAndStylesDeclHTML(rawHTML) + if len(slimHTML) > 393_216 { + slimHTML = truncateUTF8SafeFullDocGo(slimHTML, 393_216) + } + + subjFrag := wave3GovFirstNonEmpty( + wave3GovExtractByClassSub(slimHTML, "h1", "bulletin_subject"), + wave3GovExtractByClassSub(slimHTML, "div", "bulletin_subject"), + ) + h1 := wave3GovFirstNonEmpty(wave3GovCleanText(subjFrag), wave3GovExtractH1(slimHTML)) + if h1 != "" && wave3GovIsGenericTitle(h1) { + h1 = "" + } + title := wave3GovFirstNonEmpty(h1, wave3GovExtractMeta(headProbe, "og:title"), wave3GovCleanText(extractTitleLinearQuick(headProbe))) + if title == "" || wave3GovIsNegativeTitle(title) || wave3GovIsGenericTitle(title) { + return nil + } + + bodyFrag := wave3GovExtractGovDeliveryBodyFrag(slimHTML) + var bodyMD string + if strings.TrimSpace(bodyFrag) != "" { + doc := ExtractHTMLDocumentFull(""+bodyFrag+"", FullExtractOptions{ + BaseURL: baseURL, + OnlyMainContent: false, + IncludeImages: false, + IsFragment: false, + SkipUniversalExtractors: true, + SkipPlainText: true, + }) + bodyMD = strings.TrimSpace(doc.Markdown) + } + if len(strings.Fields(bodyMD)) < 5 { + return nil + } + + headerFrag := wave3GovExtractByID(slimHTML, "div", "bulletin_header") + headerTxt := wave3GovCleanText(headerFrag) + pubDate := wave3GovRxDateLike.FindString(headerTxt + " " + wave3GovCleanText(wave3GovExtractByID(slimHTML, "div", "bulletin_footer"))) + + var links []string + seen := make(map[string]bool) + for _, lk := range wave3GovExtractLinks(bodyFrag, baseURL, 25) { + wave3GovAddLink(&links, seen, lk.URL, baseURL) + } + + var md strings.Builder + md.WriteString("# ") + md.WriteString(title) + md.WriteString("\n\n- **Platform**: Granicus GovDelivery\n") + if pubDate != "" { + md.WriteString("- **Date**: ") + md.WriteString(pubDate) + md.WriteByte('\n') + } + if headerTxt != "" && len(headerTxt) <= 180 { + md.WriteString("- **Sender**: ") + md.WriteString(headerTxt) + md.WriteByte('\n') + } + md.WriteString("\n## Bulletin\n\n") + md.WriteString(bodyMD) + md.WriteByte('\n') + + rec := map[string]any{ + "source": "granicus-govdelivery", + "title": title, + "url": baseURL, + } + if pubDate != "" { + rec["date"] = pubDate + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: wave3GovExtractMeta(headProbe, "description"), + PublishedTime: pubDate, + Markdown: md.String(), + Links: links, + Records: []map[string]any{rec}, + Total: wave3GovIntPtr(1), + Returned: wave3GovIntPtr(1), + } +} + +// ── #203 Municipal CMS Pack (`municipal_cms_html`) ─────────────────────────────────────────────── + +func wave3GovExtractMunicipalCMSHTML(rawHTML, probeLower, baseURL, extractorID string) *DeclarativePostFetchResult { + platform := "revize" + if strings.Contains(probeLower, "opencities") || strings.Contains(probeLower, "visioninternet") { + platform = "opencities" + } + headProbe := rawHTML + if len(headProbe) > 131_072 { + headProbe = truncateUTF8SafeFullDocGo(headProbe, 131_072) + } + slimHTML := stripScriptsAndStylesDeclHTML(rawHTML) + if len(slimHTML) > 786_432 { + slimHTML = truncateUTF8SafeFullDocGo(slimHTML, 786_432) + } + + ogTitle := wave3GovExtractMeta(headProbe, "og:title") + pageTitle := wave3GovCleanText(extractTitleLinearQuick(headProbe)) + h1 := wave3GovExtractH1(slimHTML) + if h1 != "" { + if wave3GovIsNegativeTitle(h1) { + return nil + } + if wave3GovIsGenericTitle(h1) { + h1 = "" + } + } + title := wave3GovFirstNonEmpty(h1, ogTitle, pageTitle) + if title == "" || wave3GovIsNegativeTitle(title) || wave3GovIsGenericTitle(title) { + return nil + } + + var bodyFrag string + if bodyFrag = wave3GovExtractByID(slimHTML, "div", "main-content"); bodyFrag == "" { + if bodyFrag = wave3GovExtractByID(slimHTML, "div", "main"); bodyFrag == "" { + if bodyFrag = wave3GovExtractByID(slimHTML, "div", "post"); bodyFrag == "" { + if bodyFrag = wave3GovExtractByID(slimHTML, "main", "main"); bodyFrag == "" { + if bodyFrag = wave3GovExtractByClassSub(slimHTML, "div", "document-center"); bodyFrag == "" { + bodyFrag = wave3GovExtractByClassSub(slimHTML, "div", "main-content") + } + } + } + } + } + if bodyFrag == "" { + if mFrag, okM := findElementInnerLinearDeclHTML(slimHTML, "main", nil, 0); okM { + bodyFrag = mFrag + } else if aFrag, okA := findElementInnerLinearDeclHTML(slimHTML, "article", nil, 0); okA { + bodyFrag = aFrag + } + } + if len(bodyFrag) > 80*1024 { + bodyFrag = truncateUTF8SafeFullDocGo(bodyFrag, 80*1024) + } + bodyMD := wave3GovFragToMD(bodyFrag, baseURL) + + var recs []map[string]any + var links []string + seen := make(map[string]bool) + linkSource := bodyFrag + if linkSource == "" { + linkSource = slimHTML + } + for _, lk := range wave3GovExtractLinks(linkSource, baseURL, 40) { + lowU := strings.ToLower(lk.URL) + if strings.HasSuffix(lowU, ".pdf") || strings.Contains(lowU, "document_center") || + strings.Contains(lowU, "agenda") || strings.Contains(lowU, "minutes") || + strings.Contains(lowU, "revize") { + if !seen[lk.URL] { + wave3GovAddLink(&links, seen, lk.URL, baseURL) + recs = append(recs, map[string]any{ + "source": "municipal-cms-pack", + "platform": platform, + "title": lk.Text, + "url": lk.URL, + }) + } + } + } + if len(recs) == 0 && len(strings.Fields(bodyMD)) < 12 { + return nil + } + + desc := wave3GovExtractMeta(headProbe, "description") + var md strings.Builder + md.WriteString("# ") + md.WriteString(title) + md.WriteString("\n\n- **CMS Platform**: ") + md.WriteString(platform) + md.WriteByte('\n') + if desc != "" { + md.WriteString("- **Summary**: ") + md.WriteString(desc) + md.WriteByte('\n') + } + if len(recs) > 0 { + md.WriteString("\n## Documents & Resources\n\n| Title | URL |\n|---|---|\n") + capN := len(recs) + if capN > wave3GovMaxRecords { + capN = wave3GovMaxRecords + } + for _, r := range recs[:capN] { + md.WriteString("| ") + md.WriteString(wave3GovMDCell(wave3GovStringVal(r["title"]))) + md.WriteString(" | ") + md.WriteString(wave3GovMDCell(wave3GovStringVal(r["url"]))) + md.WriteString(" |\n") + } + } + if bodyMD != "" { + md.WriteString("\n") + md.WriteString(bodyMD) + md.WriteByte('\n') + } + + capped, total, ret, trunc := wave3GovCapRecords(recs, len(recs)) + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: md.String(), + Links: links, + Records: capped, + Total: total, + Returned: ret, + Truncated: trunc, + } +} + +// ── #204 BoardDocs (`boarddocs_text` & `boarddocs_html`) ───────────────────────────────────────── + +func wave3GovFormatBoardDocsText(rawBody string, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool) { + trimmed := strings.TrimSpace(strings.TrimPrefix(rawBody, "\ufeff")) + if trimmed == "" { + return nil, false + } + low := asciiLowerExtractString(trimmed) + if strings.Contains(low, "error from cloudfront") || + strings.Contains(low, "the request could not be satisfied") || + strings.Contains(low, "404") || + strings.Contains(low, "<h1>403") { + return nil, false + } + + orgLabel := wave3GovFirstNonEmpty(params["org"], params["state"], "BoardDocs") + var recs []map[string]any + var links []string + seen := make(map[string]bool) + + if trimmed[0] == '{' || trimmed[0] == '[' { + parsed, ok := decodeJSONWithNumbers([]byte(trimmed)) + if !ok || parsed == nil { + return nil, false + } + var arr []any + if m := wave3GovMap(parsed); m != nil { + if wave3GovIsGenericJSONError(m) { + return nil, false + } + arr = wave3GovSlice(m["meetings"]) + if arr == nil { + arr = wave3GovSlice(m["items"]) + } + if arr == nil { + arr = wave3GovSlice(m["data"]) + } + } else { + arr = wave3GovSlice(parsed) + } + for _, el := range arr { + m := wave3GovMap(el) + if m == nil { + continue + } + name := wave3GovFirstNonEmpty(wave3GovPlain(m["name"], 200), wave3GovPlain(m["title"], 200), wave3GovPlain(m["description"], 200)) + if name == "" { + continue + } + dt := wave3GovFirstNonEmpty(wave3GovPlain(m["date"], 48), wave3GovPlain(m["startDate"], 48)) + u := SanitizeSchemaHTTPSURL(wave3GovStringVal(m["url"]), origURL) + if u != "" { + wave3GovAddLink(&links, seen, u, origURL) + } + rec := map[string]any{"source": "boarddocs", "title": name} + if dt != "" { + rec["date"] = dt + } + if u != "" { + rec["url"] = u + } + recs = append(recs, rec) + } + } else { + // Domino XML (<meetings><meeting>...) or HTML fragment + for _, tag := range []string{"meeting", "agendaitem", "item"} { + blocks := findAllLinearElementInnersGo(trimmed, tag, 60) + if len(blocks) == 0 { + continue + } + for _, b := range blocks { + name := wave3GovFirstNonEmpty( + wave3GovCleanText(extractXMLTagTextGo(b, "name")), + wave3GovCleanText(extractXMLTagTextGo(b, "title")), + wave3GovCleanText(extractXMLTagTextGo(b, "subject")), + ) + if name == "" { + continue + } + dt := wave3GovFirstNonEmpty( + wave3GovCleanText(extractXMLTagTextGo(b, "date")), + wave3GovCleanText(extractXMLTagTextGo(b, "start")), + ) + id := wave3GovCleanText(extractXMLTagTextGo(b, "id")) + rec := map[string]any{"source": "boarddocs", "title": name} + if dt != "" { + rec["date"] = dt + } + if id != "" { + rec["id"] = id + } + recs = append(recs, rec) + } + if len(recs) > 0 { + break + } + } + if len(recs) == 0 { + for _, lk := range wave3GovExtractLinks(trimmed, origURL, 30) { + wave3GovAddLink(&links, seen, lk.URL, origURL) + recs = append(recs, map[string]any{ + "source": "boarddocs", + "title": lk.Text, + "url": lk.URL, + }) + } + } + } + + if len(recs) == 0 { + return nil, false + } + + title := "BoardDocs Meetings: " + strings.ToUpper(orgLabel) + var md strings.Builder + md.WriteString("# ") + md.WriteString(title) + md.WriteString("\n\n| Item | Date | ID / Link |\n|---|---|---|\n") + capped, total, ret, trunc := wave3GovCapRecords(recs, len(recs)) + for _, r := range capped { + md.WriteString("| ") + md.WriteString(wave3GovMDCell(wave3GovStringVal(r["title"]))) + md.WriteString(" | ") + md.WriteString(wave3GovMDCell(wave3GovFirstNonEmpty(wave3GovStringVal(r["date"]), "-"))) + md.WriteString(" | ") + md.WriteString(wave3GovMDCell(wave3GovFirstNonEmpty(wave3GovStringVal(r["url"]), wave3GovStringVal(r["id"]), "-"))) + md.WriteString(" |\n") + } + + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: md.String(), + Links: links, + Records: capped, + Total: total, + Returned: ret, + Truncated: trunc, + }, true +} + +func wave3GovExtractBoardDocsHTML(rawHTML, probeLower, baseURL, extractorID string) *DeclarativePostFetchResult { + title := wave3GovFirstNonEmpty(wave3GovExtractH1(rawHTML), wave3GovCleanText(extractTitleLinearQuick(rawHTML))) + if title == "" || wave3GovIsNegativeTitle(title) || wave3GovIsGenericTitle(title) { + return nil + } + var recs []map[string]any + var links []string + seen := make(map[string]bool) + for _, lk := range wave3GovExtractLinks(rawHTML, baseURL, 35) { + lowU := strings.ToLower(lk.URL) + if strings.Contains(lowU, "board.nsf") || strings.Contains(lowU, "bd-get") || strings.Contains(lowU, "agenda") { + wave3GovAddLink(&links, seen, lk.URL, baseURL) + recs = append(recs, map[string]any{ + "source": "boarddocs", + "title": lk.Text, + "url": lk.URL, + }) + } + } + bodyFrag := wave3GovFirstNonEmpty( + wave3GovExtractByID(rawHTML, "div", "meeting-list"), + wave3GovExtractByID(rawHTML, "div", "agenda-content"), + wave3GovExtractByID(rawHTML, "main", "main"), + ) + bodyMD := wave3GovFragToMD(bodyFrag, baseURL) + if len(recs) == 0 && len(strings.Fields(bodyMD)) < 15 { + return nil + } + + var md strings.Builder + md.WriteString("# ") + md.WriteString(title) + md.WriteString("\n\n- **Platform**: BoardDocs\n") + if bodyMD != "" { + md.WriteByte('\n') + md.WriteString(bodyMD) + md.WriteByte('\n') + } + capped, total, ret, trunc := wave3GovCapRecords(recs, len(recs)) + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Markdown: md.String(), + Links: links, + Records: capped, + Total: total, + Returned: ret, + Truncated: trunc, + } +} + +// ── #205 CivicClerk (`civicclerk_json` & `civicclerk_html`) ────────────────────────────────────── + +func wave3GovFormatCivicClerkJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + obj := wave3GovMap(parsed) + if obj == nil || wave3GovIsGenericJSONError(obj) { + return nil, false + } + + host := wave3GovHostFromURL(origURL) + var items []any + if valArr := wave3GovSlice(obj["value"]); valArr != nil { + items = valArr + } else if obj["eventName"] != nil || obj["id"] != nil { + items = []any{obj} + } + if len(items) == 0 { + return nil, false + } + + var recs []map[string]any + var links []string + seen := make(map[string]bool) + + for _, el := range items { + m := wave3GovMap(el) + if m == nil { + continue + } + if pub, hasPub := m["isPublished"].(bool); hasPub && !pub { + continue + } + name := wave3GovPlain(m["eventName"], 220) + if name == "" { + continue + } + id := wave3GovPlain(m["id"], 32) + start := wave3GovFirstNonEmpty(wave3GovPlain(m["startDateTime"], 40), wave3GovPlain(m["eventDate"], 40)) + cat := wave3GovPlain(m["categoryName"], 120) + desc := wave3GovPlain(m["eventDescription"], 300) + agendaName := wave3GovPlain(m["agendaName"], 160) + mediaURL := SanitizeSchemaHTTPSURL(wave3GovStringVal(m["mediaSourcePath"]), origURL) + if mediaURL != "" { + wave3GovAddLink(&links, seen, mediaURL, origURL) + } + rec := map[string]any{ + "source": "civicclerk", + "title": name, + } + if id != "" { + rec["id"] = id + } + if start != "" { + rec["startDateTime"] = start + } + if cat != "" { + rec["category"] = cat + } + if agendaName != "" { + rec["agendaName"] = agendaName + } + if desc != "" { + rec["description"] = desc + } + if mediaURL != "" { + rec["url"] = mediaURL + } + recs = append(recs, rec) + } + if len(recs) == 0 { + return nil, false + } + + title := "CivicClerk Events" + if host != "" { + title = "CivicClerk Events (" + host + ")" + } + if len(recs) == 1 && wave3GovStringVal(recs[0]["title"]) != "" { + title = wave3GovStringVal(recs[0]["title"]) + } + + var md strings.Builder + md.WriteString("# ") + md.WriteString(title) + md.WriteString("\n\n| Event | Date / Time | Category | Agenda |\n|---|---|---|---|\n") + capped, total, ret, trunc := wave3GovCapRecords(recs, len(items)) + for _, r := range capped { + md.WriteString("| ") + md.WriteString(wave3GovMDCell(wave3GovStringVal(r["title"]))) + md.WriteString(" | ") + md.WriteString(wave3GovMDCell(wave3GovFirstNonEmpty(wave3GovStringVal(r["startDateTime"]), "-"))) + md.WriteString(" | ") + md.WriteString(wave3GovMDCell(wave3GovFirstNonEmpty(wave3GovStringVal(r["category"]), "-"))) + md.WriteString(" | ") + md.WriteString(wave3GovMDCell(wave3GovFirstNonEmpty(wave3GovStringVal(r["agendaName"]), "-"))) + md.WriteString(" |\n") + } + + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: md.String(), + Links: links, + Records: capped, + Total: total, + Returned: ret, + Truncated: trunc, + }, true +} + +func wave3GovExtractCivicClerkHTML(rawHTML, probeLower, baseURL, extractorID string) *DeclarativePostFetchResult { + // Reject unhydrated Vite SPA shell (<div id="root"></div> without event data) + if !strings.Contains(probeLower, "<article") && !strings.Contains(probeLower, "<table") && !hasJSONLDScriptToken(rawHTML) { + return nil + } + h1 := wave3GovExtractH1(rawHTML) + if h1 == "" || wave3GovIsNegativeTitle(h1) || wave3GovIsGenericTitle(h1) { + return nil + } + bodyMD := wave3GovFragToMD(rawHTML, baseURL) + if len(strings.Fields(bodyMD)) < 15 { + return nil + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: h1, + Markdown: "# " + h1 + "\n\n" + bodyMD, + } +} + +// ── #206 PrimeGov (`primegov_json` & `primegov_html`) ──────────────────────────────────────────── + +func wave3GovFormatPrimeGovJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + var arr []any + if a := wave3GovSlice(parsed); a != nil { + arr = a + } else if obj := wave3GovMap(parsed); obj != nil { + if wave3GovIsGenericJSONError(obj) { + return nil, false + } + for _, k := range []string{"value", "data", "meetings", "items"} { + if sub := wave3GovSlice(obj[k]); sub != nil { + arr = sub + break + } + } + } + if len(arr) == 0 { + return nil, false + } + + var recs []map[string]any + var links []string + seen := make(map[string]bool) + for _, el := range arr { + m := wave3GovMap(el) + if m == nil { + continue + } + title := wave3GovFirstNonEmpty( + wave3GovPlain(m["title"], 220), + wave3GovPlain(m["meetingName"], 220), + wave3GovPlain(m["committeeName"], 220), + ) + if title == "" { + continue + } + dt := wave3GovFirstNonEmpty(wave3GovPlain(m["dateTime"], 48), wave3GovPlain(m["meetingDate"], 48), wave3GovPlain(m["date"], 48)) + committee := wave3GovPlain(m["committeeName"], 160) + agendaURL := SanitizeSchemaHTTPSURL(wave3GovStringVal(m["agendaUrl"]), origURL) + if agendaURL != "" { + wave3GovAddLink(&links, seen, agendaURL, origURL) + } + rec := map[string]any{ + "source": "primegov", + "title": title, + } + if id := wave3GovPlain(m["id"], 32); id != "" { + rec["id"] = id + } + if dt != "" { + rec["date"] = dt + } + if committee != "" { + rec["committee"] = committee + } + if agendaURL != "" { + rec["url"] = agendaURL + } + recs = append(recs, rec) + } + if len(recs) == 0 { + return nil, false + } + + host := wave3GovHostFromURL(origURL) + docTitle := "PrimeGov Upcoming Meetings" + if host != "" { + docTitle = "PrimeGov Meetings (" + host + ")" + } + var md strings.Builder + md.WriteString("# ") + md.WriteString(docTitle) + md.WriteString("\n\n| Meeting | Date | Committee |\n|---|---|---|\n") + capped, total, ret, trunc := wave3GovCapRecords(recs, len(arr)) + for _, r := range capped { + md.WriteString("| ") + md.WriteString(wave3GovMDCell(wave3GovStringVal(r["title"]))) + md.WriteString(" | ") + md.WriteString(wave3GovMDCell(wave3GovFirstNonEmpty(wave3GovStringVal(r["date"]), "-"))) + md.WriteString(" | ") + md.WriteString(wave3GovMDCell(wave3GovFirstNonEmpty(wave3GovStringVal(r["committee"]), "-"))) + md.WriteString(" |\n") + } + + return &DeclarativeFormattedDoc{ + Title: docTitle, + Markdown: md.String(), + Links: links, + Records: capped, + Total: total, + Returned: ret, + Truncated: trunc, + }, true +} + +func wave3GovExtractPrimeGovHTML(rawHTML, probeLower, baseURL, extractorID string) *DeclarativePostFetchResult { + h1 := wave3GovExtractH1(rawHTML) + title := wave3GovFirstNonEmpty(h1, wave3GovCleanText(extractTitleLinearQuick(rawHTML))) + if title == "" || wave3GovIsNegativeTitle(title) || wave3GovIsGenericTitle(title) { + return nil + } + var recs []map[string]any + var links []string + seen := make(map[string]bool) + for _, lk := range wave3GovExtractLinks(rawHTML, baseURL, 35) { + lowU := strings.ToLower(lk.URL) + if strings.Contains(lowU, "/portal/meeting") || strings.Contains(lowU, "compileoutput") || strings.Contains(lowU, ".pdf") { + wave3GovAddLink(&links, seen, lk.URL, baseURL) + recs = append(recs, map[string]any{ + "source": "primegov", + "title": lk.Text, + "url": lk.URL, + }) + } + } + if len(recs) == 0 && !strings.Contains(probeLower, "<table") { + return nil + } + bodyMD := wave3GovFragToMD(wave3GovFirstNonEmpty(wave3GovExtractByClassSub(rawHTML, "div", "meeting"), rawHTML), baseURL) + if len(recs) == 0 && len(strings.Fields(bodyMD)) < 15 { + return nil + } + capped, total, ret, trunc := wave3GovCapRecords(recs, len(recs)) + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Markdown: "# " + title + "\n\n" + bodyMD, + Links: links, + Records: capped, + Total: total, + Returned: ret, + Truncated: trunc, + } +} + +// ── #207 Agenda Portal Pack (`agenda_portal_html`) ─────────────────────────────────────────────── + +func wave3GovExtractAgendaPortalHTML(rawHTML, probeLower, baseURL, extractorID string) *DeclarativePostFetchResult { + platform := "civicweb" + if strings.Contains(probeLower, "escribemeetings") || strings.Contains(probeLower, "meetingtypelistbox") { + platform = "escribe" + } else if strings.Contains(probeLower, "novusagenda") || strings.Contains(probeLower, "agendasearch-") { + platform = "novusagenda" + } + + title := wave3GovFirstNonEmpty(wave3GovExtractH1(rawHTML), wave3GovExtractMeta(rawHTML, "og:title"), wave3GovCleanText(extractTitleLinearQuick(rawHTML))) + if title == "" || wave3GovIsNegativeTitle(title) || wave3GovIsGenericTitle(title) { + return nil + } + + var recs []map[string]any + var links []string + seen := make(map[string]bool) + + for _, lk := range wave3GovExtractLinks(rawHTML, baseURL, 60) { + lowU := strings.ToLower(lk.URL) + if strings.Contains(lowU, "meeting.aspx") || + strings.Contains(lowU, "meetinginformation.aspx") || + strings.Contains(lowU, "agendapublic/meetings") || + strings.Contains(lowU, "document.aspx") || + strings.Contains(lowU, "fileopen.aspx") || + strings.HasSuffix(lowU, ".pdf") { + if !seen[lk.URL] { + wave3GovAddLink(&links, seen, lk.URL, baseURL) + rec := map[string]any{ + "source": "agenda-portal-pack", + "platform": platform, + "title": lk.Text, + "url": lk.URL, + } + if dm := wave3GovRxDateLike.FindString(lk.Text); dm != "" { + rec["date"] = dm + } + recs = append(recs, rec) + } + } + } + + // Fallback: check table rows for meeting rows if link paths differ + if len(recs) == 0 { + for _, tr := range wave3GovRxTRow.FindAllStringSubmatch(rawHTML, 40) { + cells := wave3GovRxTCell.FindAllStringSubmatch(tr[1], 8) + if len(cells) < 2 { + continue + } + rowTxt := wave3GovCleanText(cells[0][1]) + if rowTxt == "" || len(rowTxt) < 4 { + continue + } + if dm := wave3GovRxDateLike.FindString(wave3GovCleanText(tr[1])); dm != "" { + recs = append(recs, map[string]any{ + "source": "agenda-portal-pack", + "platform": platform, + "title": rowTxt, + "date": dm, + "url": baseURL, + }) + } + } + } + + // Reject WebForms empty search views without meeting rows/agenda links + if len(recs) == 0 { + return nil + } + + var md strings.Builder + md.WriteString("# ") + md.WriteString(title) + md.WriteString("\n\n- **Agenda Platform**: ") + md.WriteString(platform) + md.WriteString("\n\n## Meetings & Agendas\n\n| Meeting / Document | URL |\n|---|---|\n") + capped, total, ret, trunc := wave3GovCapRecords(recs, len(recs)) + for _, r := range capped { + md.WriteString("| ") + md.WriteString(wave3GovMDCell(wave3GovStringVal(r["title"]))) + md.WriteString(" | ") + md.WriteString(wave3GovMDCell(wave3GovStringVal(r["url"]))) + md.WriteString(" |\n") + } + + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Markdown: md.String(), + Links: links, + Records: capped, + Total: total, + Returned: ret, + Truncated: trunc, + } +} + +// ── #209 Accela Citizen Access (`accela_html`, strictly read-only GET) ─────────────────────────── + +func wave3GovExtractAccelaHTML(rawHTML, probeLower, baseURL, extractorID string) *DeclarativePostFetchResult { + // Extract Accela ASP.NET permit record spans directly; NEVER submit forms. + permitNum := wave3GovCleanText(wave3GovExtractByID(rawHTML, "span", "ctl00_PlaceHolderMain_lblPermitNumber")) + permitType := wave3GovCleanText(wave3GovExtractByID(rawHTML, "span", "ctl00_PlaceHolderMain_lblPermitType")) + status := wave3GovCleanText(wave3GovExtractByID(rawHTML, "span", "ctl00_PlaceHolderMain_lblRecordStatus")) + expDate := wave3GovFirstNonEmpty( + wave3GovCleanText(wave3GovExtractByID(rawHTML, "span", "ctl00_PlaceHolderMain_lblExpirtionDate")), + wave3GovCleanText(wave3GovExtractByID(rawHTML, "span", "ctl00_PlaceHolderMain_lblExpirationDate")), + ) + workLoc := wave3GovCleanText(wave3GovExtractByID(rawHTML, "div", "ctl00_PlaceHolderMain_divWorkLocation")) + projDesc := wave3GovCleanText(wave3GovExtractByID(rawHTML, "div", "ctl00_PlaceHolderMain_divProjectDescription")) + + // Require at least permitNum or permitType (reject generic Default.aspx / "Message Bar" shells) + if permitNum == "" && permitType == "" { + return nil + } + + title := wave3GovFirstNonEmpty( + strings.TrimSpace(permitNum+" - "+permitType), + permitNum, + permitType, + ) + if permitNum == "" || permitType == "" { + title = wave3GovFirstNonEmpty(permitNum, permitType) + } + + var links []string + seen := make(map[string]bool) + if docList := wave3GovExtractByID(rawHTML, "div", "ctl00_PlaceHolderMain_divDocumentlist"); docList != "" { + for _, lk := range wave3GovExtractLinks(docList, baseURL, 20) { + wave3GovAddLink(&links, seen, lk.URL, baseURL) + } + } + + var md strings.Builder + md.WriteString("# ") + md.WriteString(title) + md.WriteString("\n\n- **Platform**: Accela Citizen Access (Read-Only)\n") + if permitNum != "" { + md.WriteString("- **Permit Number**: `") + md.WriteString(permitNum) + md.WriteString("`\n") + } + if permitType != "" { + md.WriteString("- **Record Type**: ") + md.WriteString(permitType) + md.WriteByte('\n') + } + if status != "" { + md.WriteString("- **Record Status**: ") + md.WriteString(status) + md.WriteByte('\n') + } + if expDate != "" { + md.WriteString("- **Expiration Date**: ") + md.WriteString(expDate) + md.WriteByte('\n') + } + if workLoc != "" { + md.WriteString("- **Work Location**: ") + md.WriteString(workLoc) + md.WriteByte('\n') + } + if projDesc != "" { + md.WriteString("\n## Project Description\n\n") + md.WriteString(projDesc) + md.WriteByte('\n') + } + + rec := map[string]any{ + "source": "accela-citizen-access", + "title": title, + "url": baseURL, + } + if permitNum != "" { + rec["permitNumber"] = permitNum + } + if permitType != "" { + rec["permitType"] = permitType + } + if status != "" { + rec["status"] = status + } + if expDate != "" { + rec["expirationDate"] = expDate + } + if workLoc != "" { + rec["workLocation"] = workLoc + } + + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: projDesc, + Markdown: md.String(), + Links: links, + Records: []map[string]any{rec}, + Total: wave3GovIntPtr(1), + Returned: wave3GovIntPtr(1), + } +} + +// ── #210 Tyler EnerGov (`tyler_energov_json` & `tyler_energov_html`) ──────────────────────────── + +func wave3GovFormatEnerGovJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + obj := wave3GovMap(parsed) + if obj == nil || wave3GovIsGenericJSONError(obj) { + return nil, false + } + var items []any + if res := wave3GovMap(obj["Result"]); res != nil { + if arr := wave3GovSlice(res["Entities"]); arr != nil { + items = arr + } else { + items = []any{res} + } + } else if arr := wave3GovSlice(obj["Entities"]); arr != nil { + items = arr + } else if arr := wave3GovSlice(obj["results"]); arr != nil { + items = arr + } else if obj["CaseNumber"] != nil || obj["PermitNumber"] != nil || obj["PlanNumber"] != nil { + items = []any{obj} + } + if len(items) == 0 { + return nil, false + } + + var recs []map[string]any + for _, el := range items { + m := wave3GovMap(el) + if m == nil { + continue + } + num := wave3GovFirstNonEmpty( + wave3GovPlain(m["CaseNumber"], 80), + wave3GovPlain(m["PermitNumber"], 80), + wave3GovPlain(m["PlanNumber"], 80), + wave3GovPlain(m["LicenseNumber"], 80), + ) + typ := wave3GovFirstNonEmpty(wave3GovPlain(m["CaseType"], 120), wave3GovPlain(m["PermitType"], 120), wave3GovPlain(m["Type"], 120)) + status := wave3GovFirstNonEmpty(wave3GovPlain(m["CaseStatus"], 80), wave3GovPlain(m["Status"], 80)) + addr := wave3GovFirstNonEmpty(wave3GovPlain(m["AddressDisplay"], 180), wave3GovPlain(m["MainAddress"], 180)) + if num == "" && typ == "" { + continue + } + rec := map[string]any{ + "source": "tyler-energov", + "title": wave3GovFirstNonEmpty(num, typ), + } + if num != "" { + rec["recordNumber"] = num + } + if typ != "" { + rec["recordType"] = typ + } + if status != "" { + rec["status"] = status + } + if addr != "" { + rec["address"] = addr + } + recs = append(recs, rec) + } + if len(recs) == 0 { + return nil, false + } + + title := "Tyler EnerGov Records" + if len(recs) == 1 { + title = "EnerGov: " + wave3GovStringVal(recs[0]["title"]) + } + var md strings.Builder + md.WriteString("# ") + md.WriteString(title) + md.WriteString("\n\n| Record | Type | Status | Address |\n|---|---|---|---|\n") + capped, total, ret, trunc := wave3GovCapRecords(recs, len(items)) + for _, r := range capped { + md.WriteString("| ") + md.WriteString(wave3GovMDCell(wave3GovStringVal(r["title"]))) + md.WriteString(" | ") + md.WriteString(wave3GovMDCell(wave3GovFirstNonEmpty(wave3GovStringVal(r["recordType"]), "-"))) + md.WriteString(" | ") + md.WriteString(wave3GovMDCell(wave3GovFirstNonEmpty(wave3GovStringVal(r["status"]), "-"))) + md.WriteString(" | ") + md.WriteString(wave3GovMDCell(wave3GovFirstNonEmpty(wave3GovStringVal(r["address"]), "-"))) + md.WriteString(" |\n") + } + + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: md.String(), + Records: capped, + Total: total, + Returned: ret, + Truncated: trunc, + }, true +} + +func wave3GovExtractEnerGovHTML(rawHTML, probeLower, baseURL, extractorID string) *DeclarativePostFetchResult { + // Reject unhydrated AngularJS SelfService SPA shell ("Welcome to portal home") + if strings.Contains(probeLower, "welcome to portal home") && + !strings.Contains(probeLower, "permitnumber") && + !strings.Contains(probeLower, "casenumber") && + !strings.Contains(probeLower, "<table") { + return nil + } + h1 := wave3GovExtractH1(rawHTML) + title := wave3GovFirstNonEmpty(h1, wave3GovCleanText(extractTitleLinearQuick(rawHTML))) + if title == "" || wave3GovIsNegativeTitle(title) || wave3GovIsGenericTitle(title) { + return nil + } + detailFrag := wave3GovFirstNonEmpty( + wave3GovExtractByClassSub(rawHTML, "div", "permit-detail"), + wave3GovExtractByClassSub(rawHTML, "div", "case-detail"), + wave3GovExtractByID(rawHTML, "main", "main"), + ) + bodyMD := wave3GovFragToMD(detailFrag, baseURL) + if len(strings.Fields(bodyMD)) < 12 { + return nil + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Markdown: "# " + title + "\n\n- **Platform**: Tyler EnerGov\n\n" + bodyMD, + Records: []map[string]any{{ + "source": "tyler-energov", + "title": title, + "url": baseURL, + }}, + Total: wave3GovIntPtr(1), + Returned: wave3GovIntPtr(1), + } +} + +// ── #211 OpenGov Portals (`opengov_json` & `opengov_html`) ─────────────────────────────────────── + +func wave3GovFormatOpenGovJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + obj := wave3GovMap(parsed) + if obj == nil || wave3GovIsGenericJSONError(obj) { + return nil, false + } + var arr []any + for _, k := range []string{"data", "results", "items", "reports", "datasets"} { + if sub := wave3GovSlice(obj[k]); sub != nil { + arr = sub + break + } + } + if arr == nil && (obj["title"] != nil || obj["name"] != nil) { + arr = []any{obj} + } + if len(arr) == 0 { + return nil, false + } + var recs []map[string]any + for _, el := range arr { + m := wave3GovMap(el) + if m == nil { + continue + } + name := wave3GovFirstNonEmpty(wave3GovPlain(m["title"], 200), wave3GovPlain(m["name"], 200)) + if name == "" { + continue + } + rec := map[string]any{ + "source": "opengov-portals", + "title": name, + } + if id := wave3GovPlain(m["id"], 64); id != "" { + rec["id"] = id + } + if desc := wave3GovPlain(m["description"], 260); desc != "" { + rec["description"] = desc + } + recs = append(recs, rec) + } + if len(recs) == 0 { + return nil, false + } + title := "OpenGov Transparency (" + wave3GovFirstNonEmpty(wave3GovHostFromURL(origURL), "portal") + ")" + var md strings.Builder + md.WriteString("# ") + md.WriteString(title) + md.WriteString("\n\n| Title | ID |\n|---|---|\n") + capped, total, ret, trunc := wave3GovCapRecords(recs, len(arr)) + for _, r := range capped { + md.WriteString("| ") + md.WriteString(wave3GovMDCell(wave3GovStringVal(r["title"]))) + md.WriteString(" | ") + md.WriteString(wave3GovMDCell(wave3GovFirstNonEmpty(wave3GovStringVal(r["id"]), "-"))) + md.WriteString(" |\n") + } + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: md.String(), + Records: capped, + Total: total, + Returned: ret, + Truncated: trunc, + }, true +} + +func wave3GovExtractOpenGovHTML(rawHTML, probeLower, baseURL, extractorID string) *DeclarativePostFetchResult { + rawTitle := wave3GovCleanText(extractTitleLinearQuick(rawHTML)) + if wave3GovIsNegativeTitle(rawTitle) { + return nil + } + + var entityName, fiscalYear, desc string + var recs []map[string]any + var links []string + seen := make(map[string]bool) + + hasGonAssign := strings.Contains(rawHTML, "window.gon =") || strings.Contains(rawHTML, "window.gon=") + hasOpenGovMarkers := hasGonAssign || + strings.Contains(rawHTML, "window.__data") || + strings.Contains(rawHTML, "__OG_ZEUS_GLOBAL_VARS") || + strings.Contains(rawHTML, "reporting-classic-app") + if hasOpenGovMarkers { + var gon map[string]any + if strings.Contains(rawHTML, "window.gon =") { + gon = wave3GovExtractBalancedJSONAfterNeedle(rawHTML, "window.gon =", 262144) + } + if gon == nil && strings.Contains(rawHTML, "window.gon=") { + gon = wave3GovExtractBalancedJSONAfterNeedle(rawHTML, "window.gon=", 262144) + } + if gon == nil && strings.Contains(rawHTML, "window.__data =") { + gon = wave3GovExtractBalancedJSONAfterNeedle(rawHTML, "window.__data =", 262144) + } + if gon == nil && strings.Contains(rawHTML, "window.__data=") { + gon = wave3GovExtractBalancedJSONAfterNeedle(rawHTML, "window.__data=", 262144) + } + if gon != nil { + entityName = wave3GovFirstNonEmpty( + wave3GovPlain(getByDotPath(gon, "entity.name"), 180), + wave3GovPlain(getByDotPath(gon, "site.name"), 180), + wave3GovPlain(gon["entityName"], 180), + ) + fiscalYear = wave3GovPlain(gon["currentFiscalYear"], 24) + if views := wave3GovSlice(gon["views"]); len(views) > 0 { + for _, v := range views { + vm := wave3GovMap(v) + if vm == nil { + continue + } + vt := wave3GovFirstNonEmpty(wave3GovPlain(vm["title"], 180), wave3GovPlain(vm["name"], 180)) + if vt != "" { + recs = append(recs, map[string]any{ + "source": "opengov-portals", + "title": vt, + "id": wave3GovPlain(vm["id"], 64), + }) + } + } + } + } + if zeus := wave3GovExtractBalancedJSONAfterNeedle(rawHTML, "window.__OG_ZEUS_GLOBAL_VARS", 131072); zeus != nil { + entityName = wave3GovFirstNonEmpty(entityName, wave3GovPlain(zeus["entityName"], 180), wave3GovPlain(zeus["title"], 180)) + } + } + + h1 := wave3GovExtractH1(rawHTML) + if h1 != "" && wave3GovIsNegativeTitle(h1) { + return nil + } + ogTitle := wave3GovExtractMeta(rawHTML, "og:title") + desc = wave3GovExtractMeta(rawHTML, "description") + if wave3GovIsNegativeTitle(ogTitle) || wave3GovIsNegativeTitle(desc) { + return nil + } + title := wave3GovFirstNonEmpty(entityName, h1, ogTitle, rawTitle) + if title == "" && (hasOpenGovMarkers || strings.Contains(strings.ToLower(baseURL), "opengov.com")) { + if descTitle := wave3GovPlain(desc, 140); descTitle != "" && !wave3GovIsGenericTitle(descTitle) { + title = descTitle + } else if host := wave3GovHostFromURL(baseURL); host != "" { + title = "OpenGov Transparency — " + host + } + } + if title == "" || wave3GovIsNegativeTitle(title) || wave3GovIsGenericTitle(title) { + return nil + } + + for _, lk := range wave3GovExtractLinks(rawHTML, baseURL, 25) { + if strings.Contains(strings.ToLower(lk.URL), "opengov.com") { + wave3GovAddLink(&links, seen, lk.URL, baseURL) + } + } + + bodyMD := wave3GovFragToMD(wave3GovFirstNonEmpty(wave3GovExtractByID(rawHTML, "main", "main"), wave3GovExtractByID(rawHTML, "div", "App")), baseURL) + hasTransparencySignal := hasOpenGovMarkers && (desc != "" || len(links) > 0 || strings.Contains(strings.ToLower(baseURL), "/transparency")) + if len(recs) == 0 && entityName == "" && len(strings.Fields(bodyMD)) < 15 && !hasTransparencySignal { + return nil + } + if len(recs) == 0 { + rec := map[string]any{ + "source": "opengov-portals", + "title": title, + "url": baseURL, + } + if desc != "" { + rec["description"] = desc + } + recs = append(recs, rec) + } + + var md strings.Builder + md.WriteString("# ") + md.WriteString(title) + md.WriteString("\n\n- **Platform**: OpenGov Portal\n") + if fiscalYear != "" { + md.WriteString("- **Fiscal Year**: ") + md.WriteString(fiscalYear) + md.WriteByte('\n') + } + if desc != "" { + md.WriteString("- **Description**: ") + md.WriteString(desc) + md.WriteByte('\n') + } + if bodyMD != "" { + md.WriteByte('\n') + md.WriteString(bodyMD) + md.WriteByte('\n') + } + capped, total, ret, trunc := wave3GovCapRecords(recs, len(recs)) + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: md.String(), + Links: links, + Records: capped, + Total: total, + Returned: ret, + Truncated: trunc, + } +} + +// ── #212 Public Bid Portals (`public_bid_html`) ────────────────────────────────────────────────── + +func wave3GovExtractPublicBidHTML(rawHTML, probeLower, baseURL, urlLower, extractorID string) *DeclarativePostFetchResult { + platform := "bidnet" + if strings.Contains(probeLower, "bonfirehub") || strings.Contains(urlLower, "bonfirehub.com") { + platform = "bonfire" + } else if strings.Contains(probeLower, "bidsync") || strings.Contains(probeLower, "periscope") || strings.Contains(urlLower, "bidsync.com") { + platform = "periscope" + } + + // Strip header/nav (including BidNet's header .loginWindow password dropdown!) before checking bid content. + mainSource := wave3GovStripHeaderChrome(rawHTML) + mainLower := asciiLowerExtractString(mainSource) + + // Extract BidNet .mets-field pairs (using balanced div scanner because mets-field contains nested label/body divs) + type kvPair struct{ K, V string } + var fields []kvPair + pos := 0 + for i := 0; i < 60 && pos < len(mainSource); i++ { + open, ok := findOpenTagLinearDeclHTML(mainSource, "div", func(attrStr string) bool { + c, okC := getAttrValueLinearDeclHTML(attrStr, "class") + if !okC { + return false + } + lc := strings.ToLower(c) + return strings.Contains(lc, "mets-field") && !strings.Contains(lc, "mets-field-body") && !strings.Contains(lc, "mets-field-label") + }, pos) + if !ok { + break + } + chunk, okDiv := extractBalancedDivAtDeclHTML(mainSource, open.index) + if !okDiv { + pos = open.openEnd + continue + } + pos = open.openEnd + len(chunk) + lbl := wave3GovCleanText(wave3GovExtractByClassSub(chunk, "div", "mets-field-label")) + if lbl == "" { + lbl = wave3GovCleanText(wave3GovExtractByClassSub(chunk, "span", "mets-field-label")) + } + val := wave3GovCleanText(wave3GovExtractByClassSub(chunk, "div", "mets-field-body")) + if val == "" { + val = wave3GovCleanText(wave3GovExtractByClassSub(chunk, "span", "mets-field-body")) + } + if lbl != "" && val != "" { + fields = append(fields, kvPair{K: strings.TrimSuffix(lbl, ":"), V: val}) + } + } + + var orgName string + for _, obj := range extractJSONLDObjectsDeclHTML(rawHTML, 20) { + if wave3GovHasType(obj, "Organization", "GovernmentOrganization") { + orgName = wave3GovNameField(obj["name"]) + break + } + } + + h1 := wave3GovExtractH1(mainSource) + if h1 == "" { + h1 = wave3GovExtractH1(rawHTML) + } + title := wave3GovFirstNonEmpty(h1, wave3GovExtractMeta(rawHTML, "og:title"), wave3GovCleanText(extractTitleLinearQuick(rawHTML))) + if title == "" || wave3GovIsNegativeTitle(title) || wave3GovIsGenericTitle(title) { + return nil + } + + // Collect solicitation links + var recs []map[string]any + var links []string + seen := make(map[string]bool) + for _, lk := range wave3GovExtractLinks(mainSource, baseURL, 40) { + lowU := strings.ToLower(lk.URL) + if strings.Contains(lowU, "/solicitations/") || + strings.Contains(lowU, "/portal/opportunities/") || + strings.Contains(lowU, "biddetail") { + wave3GovAddLink(&links, seen, lk.URL, baseURL) + recs = append(recs, map[string]any{ + "source": "public-bid-portals", + "platform": platform, + "title": lk.Text, + "url": lk.URL, + }) + } + } + + hasBidData := len(fields) > 0 || len(recs) > 0 + if !hasBidData { + // Genuinely login-gated detail/download pages without bid metadata -> return nil so ClassifyContentState emits login_wall! + if strings.Contains(mainLower, `type="password"`) || + strings.Contains(mainLower, `type='password'`) || + strings.Contains(mainLower, "register to download") || + strings.Contains(mainLower, "must be logged in") || + strings.Contains(mainLower, "sign in to view") || + strings.Contains(mainLower, "log in to view") { + return nil + } + bodyMD := wave3GovFragToMD(mainSource, baseURL) + if len(strings.Fields(bodyMD)) < 25 { + return nil + } + } + + if len(recs) == 0 { + rec := map[string]any{ + "source": "public-bid-portals", + "platform": platform, + "title": title, + "url": baseURL, + } + if orgName != "" { + rec["agency"] = orgName + } + for _, f := range fields { + lk := strings.ToLower(f.K) + switch { + case strings.Contains(lk, "closing") || strings.Contains(lk, "due"): + rec["closingDate"] = f.V + case strings.Contains(lk, "reference") || strings.Contains(lk, "solicitation") || strings.Contains(lk, "bid number"): + rec["solicitationId"] = f.V + case strings.Contains(lk, "location") || strings.Contains(lk, "state"): + rec["location"] = f.V + } + } + recs = append(recs, rec) + } + + var md strings.Builder + md.WriteString("# ") + md.WriteString(title) + md.WriteString("\n\n- **Platform**: ") + md.WriteString(platform) + md.WriteByte('\n') + if orgName != "" { + md.WriteString("- **Agency**: ") + md.WriteString(orgName) + md.WriteByte('\n') + } + for _, f := range fields { + md.WriteString("- **") + md.WriteString(f.K) + md.WriteString("**: ") + md.WriteString(f.V) + md.WriteByte('\n') + } + if desc := wave3GovExtractMeta(rawHTML, "description"); desc != "" { + md.WriteString("\n## Solicitation Summary\n\n") + md.WriteString(desc) + md.WriteByte('\n') + } + if mainFrag, okM := findElementInnerLinearDeclHTML(mainSource, "main", nil, 0); okM { + if mainMD := wave3GovFragToMD(mainFrag, baseURL); mainMD != "" && len(strings.Fields(mainMD)) >= 10 { + md.WriteString("\n## Details\n\n") + md.WriteString(mainMD) + md.WriteByte('\n') + } + } + if len(recs) > 1 { + md.WriteString("\n## Open Solicitations\n\n| Solicitation | URL |\n|---|---|\n") + cappedTmp, _, _, _ := wave3GovCapRecords(recs, len(recs)) + for _, r := range cappedTmp { + md.WriteString("| ") + md.WriteString(wave3GovMDCell(wave3GovStringVal(r["title"]))) + md.WriteString(" | ") + md.WriteString(wave3GovMDCell(wave3GovStringVal(r["url"]))) + md.WriteString(" |\n") + } + } + + capped, total, ret, trunc := wave3GovCapRecords(recs, len(recs)) + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: wave3GovExtractMeta(rawHTML, "description"), + Markdown: md.String(), + Links: links, + Records: capped, + Total: total, + Returned: ret, + Truncated: trunc, + } +} + +// ── #213 ArcGIS Hub (`arcgis_hub_json` & `arcgis_hub_html`) ──────────────────────────────────── + +func wave3GovFormatArcGISHubJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + obj := wave3GovMap(parsed) + if obj == nil || wave3GovIsGenericJSONError(obj) { + return nil, false + } + + var recs []map[string]any + var links []string + seen := make(map[string]bool) + totalCount := 0 + + // 1. OGC Search GeoJSON FeatureCollection (/api/search/v1/collections/all/items) + if features := wave3GovSlice(obj["features"]); features != nil { + if len(features) == 0 { + return nil, false + } + if nm, okN := wave3GovFloatVal(obj["numberMatched"]); okN && int(nm) > len(features) { + totalCount = int(nm) + } else { + totalCount = len(features) + } + for _, el := range features { + fm := wave3GovMap(el) + if fm == nil { + continue + } + props := wave3GovMap(fm["properties"]) + if props == nil { + continue + } + title := wave3GovPlain(props["title"], 220) + if title == "" { + continue + } + id := wave3GovFirstNonEmpty(wave3GovPlain(fm["id"], 96), wave3GovPlain(props["id"], 96)) + owner := wave3GovFirstNonEmpty(wave3GovPlain(props["owner"], 120), wave3GovPlain(props["orgName"], 120)) + mod := wave3GovPlain(props["modified"], 48) + desc := wave3GovPlain(props["description"], 260) + itemURL := SanitizeSchemaHTTPSURL(wave3GovStringVal(props["url"]), origURL) + if itemURL == "" { + if lks := wave3GovSlice(fm["links"]); lks != nil { + for _, lkEl := range lks { + if lm := wave3GovMap(lkEl); lm != nil && wave3GovStringVal(lm["rel"]) == "self" { + itemURL = SanitizeSchemaHTTPSURL(wave3GovStringVal(lm["href"]), origURL) + break + } + } + } + } + if itemURL != "" { + wave3GovAddLink(&links, seen, itemURL, origURL) + } + rec := map[string]any{ + "source": "arcgis-hub", + "title": title, + } + if id != "" { + rec["id"] = id + } + if owner != "" { + rec["owner"] = owner + } + if mod != "" { + rec["modified"] = mod + } + if desc != "" { + rec["description"] = desc + } + if itemURL != "" { + rec["url"] = itemURL + } + recs = append(recs, rec) + } + } else if dataRaw, exists := obj["data"]; exists { + // 2. JSON:API /api/v3/datasets + var items []any + if arr := wave3GovSlice(dataRaw); arr != nil { + items = arr + } else if single := wave3GovMap(dataRaw); single != nil { + items = []any{single} + } + if len(items) == 0 { + return nil, false + } + totalCount = len(items) + if meta := wave3GovMap(obj["meta"]); meta != nil { + if st := wave3GovMap(meta["stats"]); st != nil { + if tc, okT := wave3GovFloatVal(st["totalCount"]); okT && int(tc) > totalCount { + totalCount = int(tc) + } + } + } + for _, el := range items { + dm := wave3GovMap(el) + if dm == nil { + continue + } + attrs := wave3GovMap(dm["attributes"]) + if attrs == nil { + attrs = dm + } + title := wave3GovFirstNonEmpty(wave3GovPlain(attrs["name"], 220), wave3GovPlain(attrs["title"], 220)) + if title == "" { + continue + } + id := wave3GovPlain(dm["id"], 96) + owner := wave3GovFirstNonEmpty(wave3GovPlain(attrs["owner"], 120), wave3GovPlain(attrs["orgName"], 120)) + mod := wave3GovPlain(attrs["modified"], 48) + desc := wave3GovPlain(attrs["description"], 260) + u := SanitizeSchemaHTTPSURL(wave3GovStringVal(attrs["url"]), origURL) + if u != "" { + wave3GovAddLink(&links, seen, u, origURL) + } + rec := map[string]any{ + "source": "arcgis-hub", + "title": title, + } + if id != "" { + rec["id"] = id + } + if owner != "" { + rec["owner"] = owner + } + if mod != "" { + rec["modified"] = mod + } + if desc != "" { + rec["description"] = desc + } + if u != "" { + rec["url"] = u + } + recs = append(recs, rec) + } + } + + if len(recs) == 0 { + return nil, false + } + + host := wave3GovHostFromURL(origURL) + docTitle := "ArcGIS Hub Datasets" + if host != "" { + docTitle = "ArcGIS Hub Datasets (" + host + ")" + } + if len(recs) == 1 { + docTitle = wave3GovStringVal(recs[0]["title"]) + } + + var md strings.Builder + md.WriteString("# ") + md.WriteString(docTitle) + md.WriteString("\n\n| Dataset | Owner | Modified |\n|---|---|---|\n") + capped, total, ret, trunc := wave3GovCapRecords(recs, totalCount) + for _, r := range capped { + md.WriteString("| ") + md.WriteString(wave3GovMDCell(wave3GovStringVal(r["title"]))) + md.WriteString(" | ") + md.WriteString(wave3GovMDCell(wave3GovFirstNonEmpty(wave3GovStringVal(r["owner"]), "-"))) + md.WriteString(" | ") + md.WriteString(wave3GovMDCell(wave3GovFirstNonEmpty(wave3GovStringVal(r["modified"]), "-"))) + md.WriteString(" |\n") + } + + return &DeclarativeFormattedDoc{ + Title: docTitle, + Markdown: md.String(), + Links: links, + Records: capped, + Total: total, + Returned: ret, + Truncated: trunc, + }, true +} + +func wave3GovExtractArcGISHubHTML(rawHTML, probeLower, baseURL, extractorID string) *DeclarativePostFetchResult { + // Reject thin custom-domain ArcGIS Hub SPA roots (<title>ArcGIS Hub without dataset JSON-LD or content) + var dsObj map[string]any + for _, obj := range extractJSONLDObjectsDeclHTML(rawHTML, 20) { + if wave3GovHasType(obj, "Dataset", "DataCatalog") { + dsObj = obj + break + } + } + h1 := wave3GovExtractH1(rawHTML) + title := wave3GovFirstNonEmpty( + wave3GovPlain(dsObj["name"], 220), + h1, + wave3GovExtractMeta(rawHTML, "og:title"), + wave3GovCleanText(extractTitleLinearQuick(rawHTML)), + ) + if title == "" || wave3GovIsNegativeTitle(title) || wave3GovIsGenericTitle(title) { + return nil + } + desc := wave3GovFirstNonEmpty(wave3GovPlain(dsObj["description"], 300), wave3GovExtractMeta(rawHTML, "description")) + bodyMD := wave3GovFragToMD(wave3GovExtractByID(rawHTML, "main", "main"), baseURL) + if dsObj == nil && len(strings.Fields(bodyMD)) < 15 { + return nil + } + var md strings.Builder + md.WriteString("# ") + md.WriteString(title) + md.WriteString("\n\n- **Platform**: ArcGIS Hub\n") + if desc != "" { + md.WriteString("\n## Description\n\n") + md.WriteString(desc) + md.WriteByte('\n') + } + if bodyMD != "" { + md.WriteByte('\n') + md.WriteString(bodyMD) + md.WriteByte('\n') + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: md.String(), + Records: []map[string]any{{ + "source": "arcgis-hub", + "title": title, + "url": baseURL, + }}, + Total: wave3GovIntPtr(1), + Returned: wave3GovIntPtr(1), + } +} + +// ── #216 Junar & Tyler Data & Insights (`junar_tyler_json` & `junar_tyler_html`) ───────────────── + +func wave3GovFormatJunarTylerJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + obj := wave3GovMap(parsed) + if obj == nil || wave3GovIsGenericJSONError(obj) { + return nil, false + } + + var recs []map[string]any + var links []string + seen := make(map[string]bool) + totalCount := 0 + + // 1. Tyler Data & Insights /api/catalog/v1 + if results := wave3GovSlice(obj["results"]); results != nil { + if len(results) == 0 { + return nil, false + } + totalCount = len(results) + if rs, okR := wave3GovFloatVal(obj["resultSetSize"]); okR && int(rs) > totalCount { + totalCount = int(rs) + } + for _, el := range results { + rm := wave3GovMap(el) + if rm == nil { + continue + } + res := wave3GovMap(rm["resource"]) + if res == nil { + res = rm + } + name := wave3GovPlain(res["name"], 220) + if name == "" { + continue + } + id := wave3GovPlain(res["id"], 64) + typ := wave3GovPlain(res["type"], 48) + perm := SanitizeSchemaHTTPSURL(wave3GovStringVal(rm["permalink"]), origURL) + if perm != "" { + wave3GovAddLink(&links, seen, perm, origURL) + } + rec := map[string]any{ + "source": "junar-tyler-data", + "title": name, + } + if id != "" { + rec["id"] = id + } + if typ != "" { + rec["type"] = typ + } + if perm != "" { + rec["url"] = perm + } + recs = append(recs, rec) + } + } else if obj["guid"] != nil || obj["title"] != nil { + // 2. Junar /api/v2/datastreams/ + title := wave3GovFirstNonEmpty(wave3GovPlain(obj["title"], 220), wave3GovPlain(obj["guid"], 80)) + if title == "" { + return nil, false + } + rec := map[string]any{ + "source": "junar-tyler-data", + "title": title, + "id": wave3GovPlain(obj["guid"], 80), + "url": origURL, + } + if desc := wave3GovPlain(obj["description"], 300); desc != "" { + rec["description"] = desc + } + recs = append(recs, rec) + totalCount = 1 + } + + if len(recs) == 0 { + return nil, false + } + + docTitle := "Open Data Catalog (" + wave3GovFirstNonEmpty(wave3GovHostFromURL(origURL), "portal") + ")" + if len(recs) == 1 { + docTitle = wave3GovStringVal(recs[0]["title"]) + } + + var md strings.Builder + md.WriteString("# ") + md.WriteString(docTitle) + md.WriteString("\n\n| Dataset | ID | Type |\n|---|---|---|\n") + capped, total, ret, trunc := wave3GovCapRecords(recs, totalCount) + for _, r := range capped { + md.WriteString("| ") + md.WriteString(wave3GovMDCell(wave3GovStringVal(r["title"]))) + md.WriteString(" | ") + md.WriteString(wave3GovMDCell(wave3GovFirstNonEmpty(wave3GovStringVal(r["id"]), "-"))) + md.WriteString(" | ") + md.WriteString(wave3GovMDCell(wave3GovFirstNonEmpty(wave3GovStringVal(r["type"]), "datastream"))) + md.WriteString(" |\n") + } + + return &DeclarativeFormattedDoc{ + Title: docTitle, + Markdown: md.String(), + Links: links, + Records: capped, + Total: total, + Returned: ret, + Truncated: trunc, + }, true +} + +func wave3GovExtractJunarTylerHTML(rawHTML, probeLower, baseURL, urlLower, extractorID string) *DeclarativePostFetchResult { + h1 := wave3GovExtractH1(rawHTML) + title := wave3GovFirstNonEmpty(h1, wave3GovExtractMeta(rawHTML, "og:title"), wave3GovCleanText(extractTitleLinearQuick(rawHTML))) + if title == "" || wave3GovIsNegativeTitle(title) || wave3GovIsGenericTitle(title) { + return nil + } + + dsFrag := wave3GovFirstNonEmpty( + wave3GovExtractByClassSub(rawHTML, "div", "dataStreamBox"), + wave3GovExtractByClassSub(rawHTML, "div", "datastream"), + wave3GovExtractByID(rawHTML, "main", "main"), + ) + bodyMD := wave3GovFragToMD(dsFrag, baseURL) + + var links []string + seen := make(map[string]bool) + var recs []map[string]any + for _, lk := range wave3GovExtractLinks(wave3GovFirstNonEmpty(dsFrag, rawHTML), baseURL, 35) { + lowU := strings.ToLower(lk.URL) + if strings.Contains(lowU, "/dataviews/") || strings.Contains(lowU, "/datastreams/") || strings.HasSuffix(lowU, ".csv") { + wave3GovAddLink(&links, seen, lk.URL, baseURL) + recs = append(recs, map[string]any{ + "source": "junar-tyler-data", + "title": lk.Text, + "url": lk.URL, + }) + } + } + if len(recs) == 0 && len(strings.Fields(bodyMD)) < 10 && !strings.Contains(probeLower, "datatable") { + return nil + } + if len(recs) == 0 { + recs = append(recs, map[string]any{ + "source": "junar-tyler-data", + "title": title, + "url": baseURL, + }) + } + + var md strings.Builder + md.WriteString("# ") + md.WriteString(title) + md.WriteString("\n\n- **Platform**: Junar / Tyler Open Data\n") + if bodyMD != "" { + md.WriteByte('\n') + md.WriteString(bodyMD) + md.WriteByte('\n') + } + capped, total, ret, trunc := wave3GovCapRecords(recs, len(recs)) + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: wave3GovExtractMeta(rawHTML, "description"), + Markdown: md.String(), + Links: links, + Records: capped, + Total: total, + Returned: ret, + Truncated: trunc, + } +} diff --git a/internal/extract/wave3_gov_test.go b/internal/extract/wave3_gov_test.go new file mode 100644 index 0000000..43d712f --- /dev/null +++ b/internal/extract/wave3_gov_test.go @@ -0,0 +1,486 @@ +package extract + +import ( + "encoding/json" + "fmt" + "net/url" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func wave3GovDecodeDoc(t *testing.T, raw string) *DeclarativeFormattedDoc { + t.Helper() + var doc DeclarativeFormattedDoc + if err := json.Unmarshal([]byte(raw), &doc); err != nil { + t.Fatalf("unmarshal DeclarativeFormattedDoc: %v\nraw=%s", err, raw) + } + return &doc +} + +func wave3GovResolveManifest(t *testing.T, m *DeclarativeAdapterManifest, rawURL string) (*DeclarativeTwinMatch, bool) { + t.Helper() + u, err := url.Parse(rawURL) + if err != nil { + t.Fatalf("url.Parse(%q): %v", rawURL, err) + } + host := strings.TrimSuffix(strings.ToLower(u.Hostname()), ".") + rawParts := splitNonEmptyEscapedSegments(u.EscapedPath()) + return resolveManifestTwinOnParsedURL(m, u, host, rawParts, DeclarativeResolveOptions{}) +} + +func TestWave3GovManifestsOnDiskAndArcGISNarrowed(t *testing.T) { + catAIDs := []string{ + "civicplus", + "granicus-govdelivery", + "municipal-cms-pack", + "boarddocs", + "civicclerk", + "primegov", + "agenda-portal-pack", + "laserfiche-weblink", + "accela-citizen-access", + "tyler-energov", + "opengov-portals", + "public-bid-portals", + "arcgis-hub", + "dkan", + "opendatasoft", + "junar-tyler-data", + } + + byID := make(map[string]*DeclarativeAdapterManifest) + for _, id := range catAIDs { + raw, err := os.ReadFile(filepath.Join("manifests", id+".yaml")) + if err != nil { + t.Fatalf("read %s.yaml: %v", id, err) + } + m, err := ParseDeclarativeYAMLManifest(raw) + if err != nil { + t.Fatalf("ParseDeclarativeYAMLManifest(%s.yaml): %v", id, err) + } + if m.ID != id { + t.Fatalf("%s.yaml has mismatched id=%q", id, m.ID) + } + if m.AuthMode == "detect-only" || m.DetectOnly != nil { + t.Fatalf("%s.yaml uses retired detect-only", id) + } + for _, hr := range m.HTMLRoutes { + for _, b := range hr.Bullets { + if strings.ContainsAny(b.Label, "{}") { + t.Fatalf("%s.yaml bullet label contains {}: %q", id, b.Label) + } + } + } + byID[id] = m + } + + // Verify arcgis.yaml narrowed off *.arcgis.com while keeping universalEngine & arcgisRestLayer intact + rawArc, err := os.ReadFile(filepath.Join("manifests", "arcgis.yaml")) + if err != nil { + t.Fatalf("read arcgis.yaml: %v", err) + } + arcM, err := ParseDeclarativeYAMLManifest(rawArc) + if err != nil { + t.Fatalf("ParseDeclarativeYAMLManifest(arcgis.yaml): %v", err) + } + if !arcM.UniversalEngine || arcM.Match == nil || !arcM.Match.ArcgisRestLayer { + t.Fatalf("arcgis.yaml must preserve universalEngine and arcgisRestLayer: %+v", arcM) + } + for _, d := range arcM.Domains { + if d == "*.arcgis.com" { + t.Fatalf("arcgis.yaml must narrow off *.arcgis.com") + } + } + + // #214 dkan must NOT claim data.cms.gov or healthdata.gov (owned by cms-data & cdc-wonder-healthdata) + dkan := byID["dkan"] + for _, d := range dkan.Domains { + if d == "data.cms.gov" || d == "healthdata.gov" { + t.Fatalf("dkan.yaml must NOT claim %q", d) + } + } + if !dkan.UniversalEngine { + t.Fatalf("dkan.yaml must set universalEngine: true") + } + + // #215 opendatasoft must set strict_robots: true and support direct /api/explore/v2.1/catalog/datasets + ods := byID["opendatasoft"] + if !ods.StrictRobots { + t.Fatalf("opendatasoft.yaml must set strict_robots: true") + } + if tm, ok := wave3GovResolveManifest(t, ods, "https://public.opendatasoft.com/explore/assets/geonames-all-cities-with-a-population-1000/"); ok || tm != nil { + t.Fatalf("opendatasoft must NOT rewrite HTML /explore/assets/ to /api/: %+v", tm) + } + if tm, ok := wave3GovResolveManifest(t, ods, "https://data.townofcary.org/api/explore/v2.1/catalog/datasets?limit=3"); !ok || tm.route.Extract.JSONMode != "opendatasoft_dataset_json" { + t.Fatalf("opendatasoft direct API route failed: ok=%v tm=%+v", ok, tm) + } + + // #202 granicus-govdelivery must NOT rewrite HTML bulletins to .rss + gd := byID["granicus-govdelivery"] + if tm, ok := wave3GovResolveManifest(t, gd, "https://content.govdelivery.com/accounts/ILEVANSTON/bulletins/4345149"); ok || tm != nil { + t.Fatalf("granicus-govdelivery must NOT rewrite HTML bulletin to .rss: %+v", tm) + } + + // #205 civicclerk portal -> same-eTLD+1 api twin + cc := byID["civicclerk"] + if tm, ok := wave3GovResolveManifest(t, cc, "https://mauicounty.portal.civicclerk.com/"); !ok || tm.FetchURL != "https://mauicounty.api.civicclerk.com/v1/Events?$top=25" { + t.Fatalf("civicclerk portal twin mismatch: ok=%v tm=%+v", ok, tm) + } + if tm, ok := wave3GovResolveManifest(t, cc, "https://mauicounty.portal.civicclerk.com/event/1023/overview"); !ok || tm.FetchURL != "https://mauicounty.api.civicclerk.com/v1/Events/1023" { + t.Fatalf("civicclerk event twin mismatch: ok=%v tm=%+v", ok, tm) + } + + // #213 arcgis-hub sparse fields[datasets] defaultQueryParams & 4 MiB maxBytes + ah := byID["arcgis-hub"] + if tm, ok := wave3GovResolveManifest(t, ah, "https://opendata.dc.gov/api/v3/datasets?page[size]=1"); !ok || tm.EffectiveMaxBytes() != 4*1024*1024 || !strings.Contains(tm.FetchURL, "fields%5Bdatasets%5D=") { + t.Fatalf("arcgis-hub /api/v3/datasets twin mismatch: ok=%v tm=%+v", ok, tm) + } + + // #216 junar-tyler-data must NOT claim *.socrata.com + jt := byID["junar-tyler-data"] + for _, d := range jt.Domains { + if strings.Contains(d, "socrata.com") { + t.Fatalf("junar-tyler-data must NOT claim socrata.com: %q", d) + } + } +} + +func TestWave3GovHTMLExtractorsAndGuardrails(t *testing.T) { + modes := []string{ + "govdelivery_html", + "municipal_cms_html", + "boarddocs_html", + "civicclerk_html", + "primegov_html", + "agenda_portal_html", + "accela_html", + "tyler_energov_html", + "opengov_html", + "public_bid_html", + "arcgis_hub_html", + "junar_tyler_html", + } + for _, m := range modes { + if !IsWave3GovHTMLMode(m) { + t.Fatalf("IsWave3GovHTMLMode(%q) = false", m) + } + if getExternalHTMLModeLazy(m) == nil { + t.Fatalf("RegisterExternalHTMLModeLazy missing %q", m) + } + } + + // 1. #201 CivicPlus DocumentCenter & CivicAlerts HTML delta on civicplus_agenda_html + cpDocHTML := `Document Center • Brownwood, TX • CivicEngage` + cpRes := Round2RunHTML("civicplus_agenda_html", cpDocHTML, "https://www.brownwoodtexas.gov/DocumentCenter", "civicplus") + if cpRes == nil || !strings.Contains(cpRes.Markdown, "FY27 Adopted Budget Packet") { + t.Fatalf("civicplus_agenda_html DocumentCenter failed: res=%+v", cpRes) + } + cpAlertsHTML := `CivicAlerts • Springfield, MO • CivicEngage` + cpAlertRes := Round2RunHTML("civicplus_agenda_html", cpAlertsHTML, "https://www.springfieldmo.gov/CivicAlerts.aspx", "civicplus") + if cpAlertRes == nil || !strings.Contains(cpAlertRes.Markdown, "Winter Weather Advisory") { + t.Fatalf("civicplus_agenda_html CivicAlerts failed: res=%+v", cpAlertRes) + } + + // 2. #202 GovDelivery bulletin HTML & 406 negative guard + gdHTML := `Evanston City Updates
City of Evanston • 11/24/2026

Winter Snow Operations Update

Crews are prepared for winter snow clearing operations across municipal arterials and neighborhood routes.

Snow Map
` + rawGD, okGD := RunWave3GovHTMLMode("govdelivery_html", gdHTML, "https://content.govdelivery.com/accounts/ILEVANSTON/bulletins/4345149") + if !okGD || !strings.Contains(rawGD, "Winter Snow Operations Update") { + t.Fatalf("govdelivery_html failed: ok=%v raw=%s", okGD, rawGD) + } + if _, ok406 := RunWave3GovHTMLMode("govdelivery_html", `Not Acceptable

406

`, "https://content.govdelivery.com/accounts/ILEVANSTON/bulletins/4345149"); ok406 { + t.Fatalf("govdelivery_html must reject 406 Not Acceptable") + } + + // 3. #203 Municipal CMS Pack (Revize + OpenCities) + revizeHTML := `Meetings - Maple Valley WA

City Council Agendas and Minutes

Access city council meeting packets and approved minutes.

November 2026 Council Agenda
` + rawMC, okMC := RunWave3GovHTMLMode("municipal_cms_html", revizeHTML, "https://www.maplevalleywa.gov/government/city_council_meetings_agendas_and_minutes.php") + if !okMC || !strings.Contains(rawMC, "revize") { + t.Fatalf("municipal_cms_html failed: ok=%v raw=%s", okMC, rawMC) + } + + // 4. #204 BoardDocs CloudFront 403 rejection + if _, okBD := RunWave3GovHTMLMode("boarddocs_html", `ERROR: The request could not be satisfied

403 ERROR

Error from cloudfront

`, "https://go.boarddocs.com/ca/sandi/Board.nsf/Public"); okBD { + t.Fatalf("boarddocs_html must reject CloudFront 403") + } + + // 5. #208 Laserfiche WebLink missing-repo CookieCheck error guidance + lfMissing := `STR_ERROR_PAGE_TITLE

INDEX_COOKIE_WARNING

` + if lfRes := Round2RunHTML("laserfiche_missing_repo_html", lfMissing, "https://records.hawaiicounty.gov/WebLink/DocView.aspx?id=991357&dbid=1&cr=1", "laserfiche-weblink"); lfRes == nil || !strings.Contains(lfRes.Markdown, "repo=") { + t.Fatalf("laserfiche_missing_repo_html failed: res=%+v", lfRes) + } + + // 6. #209 Accela Citizen Access: extracts CapDetail spans, rejects Default.aspx "Message Bar" without permit fields + accGood := `Accela Citizen Access

Message Bar

PMT-3398658Combination Building PermitClosed
1200 Third Ave, San Diego, CA
` + rawAcc, okAcc := RunWave3GovHTMLMode("accela_html", accGood, "https://aca-prod.accela.com/SANDIEGO/Cap/CapDetail.aspx?Module=DSD&capID1=REC26") + if !okAcc || !strings.Contains(rawAcc, "PMT-3398658") || !strings.Contains(rawAcc, "Combination Building Permit") { + t.Fatalf("accela_html positive failed: ok=%v raw=%s", okAcc, rawAcc) + } + accBad := `Accela Citizen Access

Message Bar

` + if _, ok := RunWave3GovHTMLMode("accela_html", accBad, "https://aca-prod.accela.com/SANDIEGO/Default.aspx"); ok { + t.Fatalf("accela_html must reject Default.aspx without permit fields") + } + + // 7. #210 Tyler EnerGov rejects unhydrated AngularJS SPA shell "Welcome to portal home" + egBad := `SelfService Public Site

Welcome to portal home

` + if _, ok := RunWave3GovHTMLMode("tyler_energov_html", egBad, "https://energovweb.capecoral.gov/EnerGovProd/selfservice"); ok { + t.Fatalf("tyler_energov_html must reject unhydrated AngularJS SelfService shell") + } + + // 8. #211 OpenGov rejects "OpenGov — Page Not Found" and Cloudflare challenge; extracts window.gon + ogBad := `OpenGov — Page Not Found

Page Not Found

` + if _, ok := RunWave3GovHTMLMode("opengov_html", ogBad, "https://stories.opengov.com/missing"); ok { + t.Fatalf("opengov_html must reject OpenGov — Page Not Found") + } + ogGood := `City of Torrance Transparency

Explore annual operating budgets, capital projects, and department expenditures.

` + if rawOG, ok := RunWave3GovHTMLMode("opengov_html", ogGood, "https://torranceca.opengov.com/transparency"); !ok || !strings.Contains(rawOG, "City of Torrance") { + t.Fatalf("opengov_html positive failed: ok=%v raw=%s", ok, rawOG) + } + + // 9. #212 Public Bid Portals: public BidNet page WITH header .loginWindow + real bid fields SUCCEEDS; login-gated page returns nil + bidPublic := `W. 38th Ave Multimodal Improvements

202686685 - W. 38th Ave. Multimodal Improvements Design Services

Reference Number
0000443656
Closing Date
2026-12-15 14:00 MST
` + rawBid, okBid := RunWave3GovHTMLMode("public_bid_html", bidPublic, "https://www.bidnetdirect.com/colorado/solicitations/open-bids/W-38th-Ave-Multimodal-Improvements-Design-Services/0000443656") + if !okBid || !strings.Contains(rawBid, "0000443656") || !strings.Contains(rawBid, "City and County of Denver") { + t.Fatalf("public_bid_html must extract public BidNet page with header loginWindow: ok=%v raw=%s", okBid, rawBid) + } + bidGated := `BidNet Direct

Sign In to View Documents

You must be logged in and register to download solicitation attachments.

` + if _, ok := RunWave3GovHTMLMode("public_bid_html", bidGated, "https://www.bidnetdirect.com/colorado/solicitations/download/0000443656"); ok { + t.Fatalf("public_bid_html must return nil on login-gated download page") + } + + // 11. #207 Agenda Portal Pack (eScribe positive + empty WebForms shell rejected) + escribeHTML := `London City Council - eSCRIBE` + if rawAG, okAG := RunWave3GovHTMLMode("agenda_portal_html", escribeHTML, "https://pub-london.escribemeetings.com/"); !okAG || !strings.Contains(rawAG, "escribe") { + t.Fatalf("agenda_portal_html positive failed: ok=%v raw=%s", okAG, rawAG) + } + if _, okEmptyAG := RunWave3GovHTMLMode("agenda_portal_html", `Search Meetings
Select criteria
`, "https://houston.novusagenda.com/agendapublic/"); okEmptyAG { + t.Fatalf("agenda_portal_html must reject empty search view without meeting rows") + } + + // 12. #205 CivicClerk empty SPA shell rejected vs hydrated article accepted + if _, okCCEmpty := RunWave3GovHTMLMode("civicclerk_html", `Public Portal • CivicClerk
`, "https://mauicounty.portal.civicclerk.com/"); okCCEmpty { + t.Fatalf("civicclerk_html must reject unhydrated Vite SPA shell") + } + + // 13. #213 ArcGIS Hub thin SPA shell rejected vs Dataset JSON-LD accepted + if _, okArcEmpty := RunWave3GovHTMLMode("arcgis_hub_html", `ArcGIS Hub
`, "https://cityofwichita.hub.arcgis.com/"); okArcEmpty { + t.Fatalf("arcgis_hub_html must reject thin ArcGIS Hub SPA shell") + } + arcHTML := `DC Open Data

Street Centerlines

` + if rawArc, okArc := RunWave3GovHTMLMode("arcgis_hub_html", arcHTML, "https://opendata.dc.gov/datasets/street-centerlines"); !okArc || !strings.Contains(rawArc, "Street Centerlines") { + t.Fatalf("arcgis_hub_html positive failed: ok=%v raw=%s", okArc, rawArc) + } + + // 14. #216 Junar HTML + junarHTML := `Business Registry 2018

Business Registry 2018

Municipal business registry records.

CSV
` + if rawJH, okJH := RunWave3GovHTMLMode("junar_tyler_html", junarHTML, "https://data.paloalto.gov/dataviews/251890/business-registry-2018/"); !okJH || !strings.Contains(rawJH, "Business Registry 2018") { + t.Fatalf("junar_tyler_html positive failed: ok=%v raw=%s", okJH, rawJH) + } +} + +func TestWave3GovJSONAndTextFormatters(t *testing.T) { + // 1. #205 CivicClerk OData list & single event + ccList := `{"@odata.context":"https://mauicounty.api.civicclerk.com/v1/$metadata#Events","value":[{"id":1023,"eventName":"County Council Regular Meeting","eventDate":"2026-12-04T09:00:00Z","startDateTime":"2026-12-04T09:00:00Z","isPublished":true,"agendaName":"Regular Agenda","categoryName":"Council"}]}` + rawCC, okCC := FormatWave3GovJSONMode("civicclerk_json", []byte(ccList), nil, "https://mauicounty.api.civicclerk.com/v1/Events?$top=3") + if !okCC || !strings.Contains(rawCC, "County Council Regular Meeting") { + t.Fatalf("civicclerk_json failed: ok=%v raw=%s", okCC, rawCC) + } + + // 2. #206 PrimeGov, #210 EnerGov, #211 OpenGov JSON + if rawPG, okPG := FormatWave3GovJSONMode("primegov_json", []byte(`[{"id":1,"title":"City Council","dateTime":"2026-12-08T09:00:00","committeeName":"Council"}]`), nil, "https://okc.primegov.com/api/v2/PublicPortal/ListUpcomingMeetings"); !okPG || !strings.Contains(rawPG, "City Council") { + t.Fatalf("primegov_json failed: ok=%v raw=%s", okPG, rawPG) + } + if rawEGJ, okEGJ := FormatWave3GovJSONMode("tyler_energov_json", []byte(`{"Result":{"Entities":[{"CaseNumber":"BLDR-2026-0412","CaseType":"Building","CaseStatus":"Issued","AddressDisplay":"1015 Cultural Park Blvd"}]}}`), nil, "https://energovweb.capecoral.gov/EnerGovProd/selfservice/api/energov/permits"); !okEGJ || !strings.Contains(rawEGJ, "BLDR-2026-0412") { + t.Fatalf("tyler_energov_json failed: ok=%v raw=%s", okEGJ, rawEGJ) + } + if rawOGJ, okOGJ := FormatWave3GovJSONMode("opengov_json", []byte(`{"data":[{"id":"b1","title":"FY26 Budget"}]}`), nil, "https://torranceca.opengov.com/api/v1/reports"); !okOGJ || !strings.Contains(rawOGJ, "FY26 Budget") { + t.Fatalf("opengov_json failed: ok=%v raw=%s", okOGJ, rawOGJ) + } + + // 3. #213 ArcGIS Hub OGC GeoJSON & /api/v3/datasets (28 items -> capped at 25) + var dsItems []string + for i := 1; i <= 28; i++ { + dsItems = append(dsItems, fmt.Sprintf(`{"id":"ds-%d","attributes":{"name":"DC Dataset %d","owner":"DCGIS","modified":1732500000}}`, i, i)) + } + ahJSON := `{"data":[` + strings.Join(dsItems, ",") + `],"meta":{"stats":{"totalCount":28}}}` + rawAH, okAH := FormatWave3GovJSONMode("arcgis_hub_json", []byte(ahJSON), nil, "https://opendata.dc.gov/api/v3/datasets?page[size]=28") + if !okAH { + t.Fatalf("arcgis_hub_json failed") + } + docAH := wave3GovDecodeDoc(t, rawAH) + if len(docAH.Records) != 25 || *docAH.Total != 28 || !*docAH.Truncated { + t.Fatalf("arcgis_hub_json cap mismatch: len=%d total=%v trunc=%v", len(docAH.Records), docAH.Total, docAH.Truncated) + } + ogcJSON := `{"type":"FeatureCollection","numberMatched":10,"numberReturned":1,"features":[{"id":"f1","properties":{"title":"Parks Polygons","owner":"ArcGIS"}}],"links":[]}` + if rawOGC, okOGC := FormatWave3GovJSONMode("arcgis_hub_json", []byte(ogcJSON), nil, "https://hub.arcgis.com/api/search/v1/collections/all/items"); !okOGC || !strings.Contains(rawOGC, "Parks Polygons") { + t.Fatalf("arcgis_hub_json OGC GeoJSON failed: ok=%v raw=%s", okOGC, rawOGC) + } + + // 4. #214 DKAN single item & #215 OpenDataSoft catalog list via FormatRound2JSONDoc + dkanItem := `{"@type":"dcat:Dataset","title":"Agent Broker Registration Tracker","identifier":"e4rr-zk4i","description":"Registration tracker.","modified":"2026-11-27T14:43:00+00:00","license":"https://www.usa.gov/publicdomain/label/1.0/","publisher":{"data":{"name":"data.healthcare.gov"}},"distribution":[{"data":{"downloadURL":"https://data.healthcare.gov/sites/default/files/AB.csv"}}]}` + docDK, okDK := FormatRound2JSONDoc("dkan_metastore_json", []byte(dkanItem), nil, "https://data.healthcare.gov/api/1/metastore/schemas/dataset/items/e4rr-zk4i") + if !okDK || docDK == nil || !strings.Contains(docDK.Markdown, "Agent Broker Registration Tracker") { + t.Fatalf("dkan_metastore_json failed: ok=%v doc=%+v", okDK, docDK) + } + odsJSON := `{"total_count":1,"results":[{"dataset_id":"geonames-cities","metas":{"default":{"title":"Geonames Cities","publisher":"OpenDataSoft","modified":"2026-11-01"}}}]}` + if docODS, okODSJ := FormatRound2JSONDoc("opendatasoft_dataset_json", []byte(odsJSON), nil, "https://data.townofcary.org/api/explore/v2.1/catalog/datasets"); !okODSJ || docODS == nil || !strings.Contains(docODS.Markdown, "Geonames Cities") { + t.Fatalf("opendatasoft_dataset_json catalog list failed: ok=%v doc=%+v", okODSJ, docODS) + } + + // 5. #216 Junar NotAuthenticated rejected & Tyler catalog v1 accepted + if _, okJT := FormatWave3GovJSONMode("junar_tyler_json", []byte(`{"status":403,"error":"NotAuthenticated"}`), nil, "https://escazu.cloudapi.junar.com/api/v2/datastreams/"); okJT { + t.Fatalf("junar_tyler_json must reject NotAuthenticated 403") + } + tylerCat := `{"resultSetSize":1,"results":[{"resource":{"id":"abc-123","name":"Tyler Sample Dataset","type":"dataset"},"permalink":"https://data.tylertech.com/d/abc-123"}]}` + if rawTC, okTC := FormatWave3GovJSONMode("junar_tyler_json", []byte(tylerCat), nil, "https://data.tylertech.com/api/catalog/v1"); !okTC || !strings.Contains(rawTC, "Tyler Sample Dataset") { + t.Fatalf("junar_tyler_json Tyler catalog v1 failed: ok=%v raw=%s", okTC, rawTC) + } + + // 6. #204 BoardDocs Domino XML & CloudFront 403 rejection + bdXML := `M1Regular Board Meeting2026-12-10` + if rawBD, okBD := FormatWave3GovTextMode("boarddocs_text", bdXML, map[string]string{"org": "sandi"}, "https://go.boarddocs.com/ca/sandi/Board.nsf/BD-GetMeetingsList"); !okBD || !strings.Contains(rawBD, "Regular Board Meeting") { + t.Fatalf("boarddocs_text XML failed: ok=%v raw=%s", okBD, rawBD) + } + if _, okBD403 := FormatWave3GovTextMode("boarddocs_text", `ERROR: The request could not be satisfied

403 ERROR

Error from cloudfront

`, nil, "https://go.boarddocs.com/ca/sandi/Board.nsf/BD-GetMeetingsList"); okBD403 { + t.Fatalf("boarddocs_text must reject CloudFront 403") + } +} + +func TestWave3GovFixturesJSONValid(t *testing.T) { + catAIDs := []string{ + "civicplus", "granicus-govdelivery", "municipal-cms-pack", "boarddocs", + "civicclerk", "primegov", "agenda-portal-pack", "laserfiche-weblink", + "accela-citizen-access", "tyler-energov", "opengov-portals", "public-bid-portals", + "arcgis-hub", "dkan", "opendatasoft", "junar-tyler-data", + } + for _, id := range catAIDs { + raw, err := os.ReadFile(filepath.Join("..", "..", "hub", "test", "fixtures", "adapters", id+".json")) + if err != nil { + t.Fatalf("read fixture %s.json: %v", id, err) + } + var fx struct { + AdapterID string `json:"adapterId"` + Mode string `json:"mode"` + InputURL string `json:"inputUrl"` + MockPayload string `json:"mockPayload"` + ExpectIncludes []string `json:"expectMarkdownIncludes"` + NegativeCases []struct { + Name string `json:"name"` + Status int `json:"status"` + Payload string `json:"payload"` + } `json:"negativeCases"` + } + if err := json.Unmarshal(raw, &fx); err != nil { + t.Fatalf("invalid JSON in %s.json: %v", id, err) + } + if fx.AdapterID != id || (fx.Mode != "twin" && fx.Mode != "html") || fx.InputURL == "" || fx.MockPayload == "" || len(fx.NegativeCases) < 4 { + t.Fatalf("fixture %s.json contract failed: id=%q mode=%q neg=%d", id, fx.AdapterID, fx.Mode, len(fx.NegativeCases)) + } + } +} + +func TestWave3GovDKANExcludedHostsAndPublicBidHeader(t *testing.T) { + // #214 DKAN must NEVER match data.cms.gov, healthdata.gov, or www.healthdata.gov + excludedTwinURLs := []string{ + "https://data.cms.gov/dataset/mj5m-pzi6", + "https://data.cms.gov/api/1/metastore/schemas/dataset/items/mj5m-pzi6", + "https://healthdata.gov/dataset/my-dataset", + "https://healthdata.gov/api/1/metastore/schemas/dataset/items/my-dataset", + "https://www.healthdata.gov/dataset/my-dataset", + } + for _, u := range excludedTwinURLs { + if m, ok := ResolveDeclarativeTwin(u); ok && m != nil && m.AdapterID == "dkan" { + t.Fatalf("dkan must NEVER match excluded host URL %s (got %+v)", u, m) + } + } + if m, ok := ResolveDeclarativeTwin("https://data.healthcare.gov/dataset/e4rr-zk4i"); !ok || m == nil || m.AdapterID != "dkan" { + t.Fatalf("dkan must match data.healthcare.gov: ok=%v m=%+v", ok, m) + } + if m, ok := ResolveDeclarativeTwin("https://data.medicaid.gov/dataset/ae4d5347-5137-5f6c-b66c-3420fa0316d8"); !ok || m == nil || m.AdapterID != "medicaid-nadac" { + t.Fatalf("medicaid-nadac must match data.medicaid.gov: ok=%v m=%+v", ok, m) + } + + // #212 Public Bid Portals: concise (<65w) BidNet solicitation with header .loginWindow password input extracts cleanly + conciseBidNet := `RFP-2026-101 - Snow Plowing

RFP-2026-101 - Snow Plowing

Reference Number
0000443657
Closing Date
2026-12-20
Location
Denver, CO
` + rawBid, okBid := RunWave3GovHTMLMode("public_bid_html", conciseBidNet, "https://www.bidnetdirect.com/colorado/solicitations/open-bids/rfp/0000443657") + if !okBid || !strings.Contains(rawBid, "0000443657") || !strings.Contains(rawBid, "Snow Plowing") { + t.Fatalf("public_bid_html concise solicitation with header .loginWindow failed: ok=%v raw=%s", okBid, rawBid) + } +} + +func TestWave3GovM7PreemptionsAndLatency(t *testing.T) { + // 1. #211 opengov-portals: -less page with window.gon.launchDarklyKey before window.gon = {...} and /reporting-classic-app/ must match opengov-portals (never canvas-public-courses!) + ogNoTitleHTML := `<!doctype html><html><head><meta name="description" content="City of Torrance Financial Transparency Portal"><script src="/reporting-classic-app/assets/@opengov/ovid/app.js"></script><script>window.gon = window.gon || {}; window.gon.launchDarklyKey = "ld-123"; window.__OG_ZEUS_GLOBAL_VARS = { LAUNCH_DARKLY_ENV_KEY: window.gon.launchDarklyKey }; window.gon = {"entity":{"name":"City of Torrance"},"currentFiscalYear":"2026","views":[{"id":"v1","title":"Annual Budget"}]};</script></head><body><div id="App"></div><a href="https://torranceca.opengov.com/transparency#/1">Budget</a></body></html>` + declOG, okDeclOG := ApplyDeclarativeHTMLExtractor(ogNoTitleHTML, "https://torranceca.opengov.com/transparency", "", nil) + if !okDeclOG || declOG == nil || declOG.ExtractorID != "opengov-portals" { + t.Fatalf("expected opengov-portals without canvas-public-courses preemption, got ok=%v res=%+v", okDeclOG, declOG) + } + // Also test <title>-less page without entity.name falling back cleanly to meta[name="description"] / host + ogHostFallbackHTML := `<!doctype html><html><head><meta name="description" content="Explore San Bernardino municipal budgets and spending."><script src="/reporting-classic-app/assets/app.js"></script><script>window.gon.launchDarklyKey="abc"; window.gon={};</script></head><body><div id="App"></div></body></html>` + if resFB, okFB := ApplyDeclarativeHTMLExtractor(ogHostFallbackHTML, "https://sanbernardinoca.opengov.com/transparency", "", nil); !okFB || resFB == nil || resFB.ExtractorID != "opengov-portals" { + t.Fatalf("expected opengov-portals meta/host fallback to succeed, got ok=%v res=%+v", okFB, resFB) + } + + // 2. #202 granicus-govdelivery: unclosed <div> inside #bulletin_body email HTML still extracts cleanly + gdUnclosedHTML := `<!doctype html><html><head><title>Press Release: Evanston Police Update
City of Evanston

Evanston Police Department issued a community traffic safety advisory for the weekend.

` + if rawGD, okGD := RunWave3GovHTMLMode("govdelivery_html", gdUnclosedHTML, "https://content.govdelivery.com/accounts/ILEVANSTON/bulletins/4345149"); !okGD || !strings.Contains(rawGD, "traffic safety advisory") { + t.Fatalf("govdelivery_html failed on unclosed email div in #bulletin_body: ok=%v raw=%s", okGD, rawGD) + } + + // 3. #203 municipal-cms-pack:

Home

falls back to before wave3GovIsGenericTitle AND 1.4 MiB HTML runs < 25ms + muniHTML := `<!doctype html><html><head><title>City of Culver City - Home

Home

Welcome to Culver City municipal services, agendas, and public notices for residents and businesses.

Council Agenda PDF
` + startM := time.Now() + rawMuni, okMuni := RunWave3GovHTMLMode("municipal_cms_html", muniHTML, "https://www.culvercity.gov/Home") + elapsedM := time.Since(startM) + if !okMuni || !strings.Contains(rawMuni, "City of Culver City") { + t.Fatalf("municipal_cms_html failed on

Home

+ 1.4 MiB HTML: ok=%v", okMuni) + } + if elapsedM > 25*time.Millisecond*time.Duration(extractRaceSlowdown) { + t.Fatalf("municipal_cms_html exceeded 25ms latency budget: %v", elapsedM) + } + + // 4. #202 granicus-govdelivery: email layout wrapping .abe-column-block MUST NOT be dropped + gdFontZeroHTML := `Press Release: Evanston Police Update
City of Evanston • 11/28/2026

Evanston Police Apprehend Suspect

Evanston Police Department detectives apprehended a suspect following a joint regional investigation with neighboring municipalities.

` + if rawGD0, okGD0 := RunWave3GovHTMLMode("govdelivery_html", gdFontZeroHTML, "https://content.govdelivery.com/accounts/ILEVANSTON/bulletins/4345149"); !okGD0 || !strings.Contains(rawGD0, "apprehended a suspect") { + t.Fatalf("govdelivery_html dropped email layout font-size:0 td subtree: ok=%v raw=%s", okGD0, rawGD0) + } + + // 5. #203 municipal-cms-pack: OpenCities
...
on culvercity.gov & >440KB offset on glendaleaz.gov + culverDivHTML := `Home | City of Culver City

City of Culver City

Welcome to Culver City municipal services, city council meetings, building permits, and neighborhood announcements.

Agenda PDF
` + if rawCulver, okCulver := RunWave3GovHTMLMode("municipal_cms_html", culverDivHTML, "https://www.culvercity.gov/Home"); !okCulver || !strings.Contains(rawCulver, "building permits") { + t.Fatalf("municipal_cms_html failed on OpenCities div#main-content: ok=%v raw=%s", okCulver, rawCulver) + } + glendalePad := strings.Repeat(``, 8500) // ~450KB before #main-content + glendaleHTML := `Home | City of Glendale
` + glendalePad + `

City of Glendale

Explore Glendale AZ city services, utility billing, public safety updates, and council meeting agendas online.

Glendale Agenda PDF
` + if rawGlendale, okGlendale := RunWave3GovHTMLMode("municipal_cms_html", glendaleHTML, "https://www.glendaleaz.gov/Home"); !okGlendale || !strings.Contains(rawGlendale, "utility billing") { + t.Fatalf("municipal_cms_html failed on >440KB OpenCities #main-content (glendaleaz.gov): ok=%v raw=%s", okGlendale, rawGlendale) + } + // Large >250KB #main-content body is bounded cleanly so extraction finishes well under 25ms + glendaleLargeBody := strings.Repeat(`

City of Glendale municipal services, public meetings, parks, and neighborhood programs.

`, 2800) + glendaleLargeHTML := `Home | City of Glendale

City of Glendale

` + glendaleLargeBody + `Glendale Agenda PDF
` + startGL := time.Now() + rawGL, okGL := RunWave3GovHTMLMode("municipal_cms_html", glendaleLargeHTML, "https://www.glendaleaz.gov/Home") + elapsedGL := time.Since(startGL) + if !okGL || !strings.Contains(rawGL, "Official City of Glendale portal.") || len(rawGL) > 100_000 { + t.Fatalf("municipal_cms_html large body cap failed: ok=%v len=%d", okGL, len(rawGL)) + } + if elapsedGL > 25*time.Millisecond*time.Duration(extractRaceSlowdown) { + t.Fatalf("municipal_cms_html large body exceeded 25ms budget: %v", elapsedGL) + } + + // 6. #208 laserfiche-weblink: Browse.aspx with empty + CrawlerPreRender + repoName fallback + STR_* nav filtering + lfBrowseHTML := `<!doctype html><html><head><title> +Loading...STR_HOMESTR_SEARCHSTR_MY_WEBLINKSTR_ABOUTAgendas and MinutesOrdinance 26-15` + resLFBrowse, okLFBrowse := ApplyDeclarativeHTMLExtractor(lfBrowseHTML, "https://records.hawaiicounty.gov/WebLink/Browse.aspx?dbid=1", "", nil) + if !okLFBrowse || resLFBrowse == nil || resLFBrowse.ExtractorID != "laserfiche-weblink" || + !strings.Contains(resLFBrowse.Markdown, "PublicDocuments") || !strings.Contains(resLFBrowse.Markdown, "Agendas and Minutes") || + strings.Contains(resLFBrowse.Markdown, "STR_HOME") || strings.Contains(resLFBrowse.Markdown, "STR_SEARCH") { + t.Fatalf("laserfiche-weblink Browse.aspx empty-title/repoName fallback failed: ok=%v res=%+v", okLFBrowse, resLFBrowse) + } + lfBrowseNoRepo := `Public Records Folder` + if resLFNoRepo, okLFNoRepo := ApplyDeclarativeHTMLExtractor(lfBrowseNoRepo, "https://records.hawaiicounty.gov/WebLink/Browse.aspx?dbid=1", "", nil); !okLFNoRepo || resLFNoRepo == nil || !strings.Contains(resLFNoRepo.Markdown, "Laserfiche WebLink Repository") { + t.Fatalf("laserfiche-weblink generic repo fallback failed: ok=%v res=%+v", okLFNoRepo, resLFNoRepo) + } +} diff --git a/internal/extract/wave3_gtin_identity.go b/internal/extract/wave3_gtin_identity.go new file mode 100644 index 0000000..d24e22b --- /dev/null +++ b/internal/extract/wave3_gtin_identity.go @@ -0,0 +1,2680 @@ +package extract + +import ( + "bytes" + "encoding/json" + "fmt" + stdhtml "html" + "net/url" + "sort" + "strconv" + "strings" +) + +const ( + wave3GTINMaxHTMLBytes = 2 * 1024 * 1024 + wave3GTINMaxJSONBytes = 4 * 1024 * 1024 + wave3GTINMaxTextBytes = 2 * 1024 * 1024 + wave3GTINMaxRecords = 25 + wave3GTINMaxLinks = 25 +) + +var ( + wave3GTINRxNotFoundTitle = newLazyRegexp(`(?i)(?:^|\b)(?:404|410|403\s+forbidden|forbidden|page\s+not\s+found|not\s+found|error\s*404|we\s+couldn'?t\s+find\s+that\s+page|access\s+denied|request\s+(?:rejected|blocked)|could\s+not\s+be\s+satisfied|unauthorized|attention\s+required|just\s+a\s+moment|security\s+check|security\s+verification|verifying\s+your\s+browser|upc\s+not\s+found|product\s+not\s+found|chemical\s+not\s+found)(?:\b|$)`) + wave3GTINRxMaintTitle = newLazyRegexp(`(?i)(?:scheduled\s+maintenance|temporarily\s+unavailable|service\s+unavailable|site\s+maintenance|under\s+maintenance|502\s+bad\s+gateway|503\s+service|down\s+for\s+maintenance)`) + wave3GTINRxErrorTitle = newLazyRegexp(`(?i)^(?:(?:(?:400|401|403|404|406|410|429|500|502|503)\s+)?(?:internal\s+)?server\s+error|application\s+error|system\s+error|unexpected\s+error|error\s+page|(?:400|401|403|404|406|410|429|500|502|503|http\s+\d{3})\s+error|error\s+(?:400|401|403|404|406|410|429|500|502|503)|error)(?:\s*[|\-\x{2013}\x{2014}:]\s*.*)?$|^.*(?:\s*[|\-\x{2013}\x{2014}:]\s*error)$`) + wave3GTINRxGenericTitle = newLazyRegexp(`(?i)^(?:loading\.{0,3}|home|welcome|search|log\s*in|sign\s*in|gs1\s*us|icecat|upcitemdb|barcode\s*lookup|energy\s*star|prop\s*65)$`) + wave3GTINRxHTMLTag = newLazyRegexp(`<[^>]+>`) + wave3GTINRxSpace = newLazyRegexp(`[ \t\r\n]+`) + wave3GTINRxTitleTag = newLazyRegexp(`(?is)]*>(.*?)`) + wave3GTINRxMetaTag = newLazyRegexp(`(?is)]*>`) + wave3GTINRxHref = newLazyRegexp(`(?is)]*\bhref\s*=\s*["']([^"'#][^"']*)["'][^>]*>(.*?)`) + wave3GTINRxFCCIDHeading = newLazyRegexp(`(?i)\bFCC\s*ID\s*[:#]?\s*([A-Z0-9][A-Z0-9\-]{2,31})\b`) + wave3GTINRxCASNumber = newLazyRegexp(`\b(\d{2,7}-\d{2}-\d)\b`) +) + +func init() { + registerWave3GTINIdentityHTMLModes() +} + +// RegisterWave3GTINIdentityHTMLModes registers all Category Q Product Identity & Data Pools HTML modes lazily. +func RegisterWave3GTINIdentityHTMLModes() { + registerWave3GTINIdentityHTMLModes() +} + +func registerWave3GTINIdentityHTMLModes() { + for _, mode := range []string{ + "gs1_us_html", + "open_icecat_html", + "upcitemdb_barcodelookup_html", + "open_product_wikidata_html", + "energy_star_html", + "fcc_test_report_html", + "fcc_id_html", + "prop65_warnings_html", + } { + m := mode + RegisterExternalHTMLModeLazy(m, func(rawHTML, baseURL string, _ func() string, extractorID string) *DeclarativePostFetchResult { + return Wave3GTINIdentityRunHTML(m, rawHTML, baseURL, extractorID) + }) + } +} + +// IsWave3GTINIdentityHTMLMode reports whether mode is one of the Category Q HTML modes (#368-#374 + fcc-id). +func IsWave3GTINIdentityHTMLMode(mode string) bool { + switch mode { + case "gs1_us_html", + "open_icecat_html", + "upcitemdb_barcodelookup_html", + "open_product_wikidata_html", + "energy_star_html", + "fcc_test_report_html", + "fcc_id_html", + "prop65_warnings_html": + return true + default: + return false + } +} + +// IsWave3GTINIdentityJSONMode reports whether mode is one of the Category Q JSON formatters. +func IsWave3GTINIdentityJSONMode(mode string) bool { + switch mode { + case "gs1_us_json", + "open_icecat_json", + "upcitemdb_json", + "barcodelookup_json", + "wikidata_gtin_sparql_json", + "energy_star_json", + "fcc_test_report_json": + return true + default: + return false + } +} + +// IsWave3GTINIdentityTextMode reports whether mode is one of the Category Q text formatters. +func IsWave3GTINIdentityTextMode(mode string) bool { + return mode == "opengtindb_text" +} + +func wave3GTINDefaultExtractorID(mode string) string { + switch mode { + case "gs1_us_html", "gs1_us_json": + return "gs1-us-datahub" + case "open_icecat_html", "open_icecat_json": + return "open-icecat" + case "upcitemdb_barcodelookup_html", "upcitemdb_json", "barcodelookup_json": + return "upcitemdb-barcodelookup" + case "open_product_wikidata_html", "wikidata_gtin_sparql_json", "opengtindb_text": + return "open-product-wikidata-gtin" + case "energy_star_html", "energy_star_json": + return "energy-star" + case "fcc_test_report_html", "fcc_test_report_json": + return "fcc-test-report" + case "fcc_id_html": + return "fcc-id" + case "prop65_warnings_html": + return "prop65-warnings" + default: + return "" + } +} + +// Wave3GTINIdentityRunHTML executes a Category Q HTML extractor and returns DeclarativePostFetchResult. +func Wave3GTINIdentityRunHTML(mode, rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + if !IsWave3GTINIdentityHTMLMode(mode) || len(rawHTML) == 0 || strings.IndexByte(rawHTML, '<') < 0 || strings.IndexByte(rawHTML, '>') < 0 { + return nil + } + if len(rawHTML) > wave3GTINMaxHTMLBytes { + rawHTML = truncateUTF8SafeFullDocGo(rawHTML, wave3GTINMaxHTMLBytes) + } + trimmedStart := strings.TrimLeft(rawHTML, " \t\r\n") + if trimmedStart == "" || trimmedStart[0] == '{' || trimmedStart[0] == '[' { + return nil + } + probe := rawHTML + if len(probe) > 65536 { + probe = probe[:65536] + } + probeLower := asciiLowerExtractString(probe) + urlLower := asciiLowerExtractString(baseURL) + + // Cheap byte prefilter BEFORE negative-shell checks or DOM parsing. + if !wave3GTINMatchesModePrefilter(mode, probeLower, urlLower) { + return nil + } + if wave3GTINHasCommonNegativeShell(mode, rawHTML, probeLower, urlLower) { + return nil + } + if extractorID == "" { + extractorID = wave3GTINDefaultExtractorID(mode) + } + + var res *DeclarativePostFetchResult + switch mode { + case "gs1_us_html": + res = wave3GTINExtractGS1USHTML(rawHTML, baseURL, extractorID) + case "open_icecat_html": + res = wave3GTINExtractOpenIcecatHTML(rawHTML, baseURL, extractorID) + case "upcitemdb_barcodelookup_html": + res = wave3GTINExtractUPCItemDBBarcodeLookupHTML(rawHTML, baseURL, extractorID) + case "open_product_wikidata_html": + res = wave3GTINExtractOpenProductWikidataHTML(rawHTML, baseURL, extractorID) + case "energy_star_html": + res = wave3GTINExtractEnergyStarHTML(rawHTML, probeLower, baseURL, extractorID) + case "fcc_test_report_html": + res = wave3GTINExtractFCCTestReportHTML(rawHTML, probeLower, baseURL, extractorID) + case "fcc_id_html": + res = wave3GTINExtractFCCIDHTML(rawHTML, baseURL, extractorID) + case "prop65_warnings_html": + res = wave3GTINExtractProp65WarningsHTML(rawHTML, baseURL, extractorID) + } + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return nil + } + return wave3GTINFinalizePostFetch(res) +} + +// RunWave3GTINIdentityHTMLMode executes a Category Q HTML extractor and returns JSON-marshaled DeclarativePostFetchResult. +func RunWave3GTINIdentityHTMLMode(mode, rawHTML, baseURL string) (string, bool) { + res := Wave3GTINIdentityRunHTML(mode, rawHTML, baseURL, wave3GTINDefaultExtractorID(mode)) + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return "", false + } + res = sanitizePostFetchResultDeclHTML(res) + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return "", false + } + encoded, err := json.Marshal(res) + if err != nil { + return "", false + } + return string(encoded), true +} + +// FormatWave3GTINIdentityJSONDoc formats a Category Q JSON twin payload into DeclarativeFormattedDoc. +func FormatWave3GTINIdentityJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool) { + if !IsWave3GTINIdentityJSONMode(mode) || len(raw) == 0 || len(raw) > wave3GTINMaxJSONBytes { + return nil, false + } + trimmed := bytes.TrimSpace(bytes.TrimPrefix(raw, []byte("\xEF\xBB\xBF"))) + if len(trimmed) == 0 || (trimmed[0] != '{' && trimmed[0] != '[') { + return nil, false + } + parsed, ok := decodeJSONWithNumbers(trimmed) + if !ok || parsed == nil { + return nil, false + } + + var doc *DeclarativeFormattedDoc + var handled bool + switch mode { + case "gs1_us_json": + doc, handled = wave3GTINFormatGS1USJSON(parsed, params, origURL) + case "open_icecat_json": + doc, handled = wave3GTINFormatOpenIcecatJSON(parsed, params, origURL) + case "upcitemdb_json": + doc, handled = wave3GTINFormatUPCItemDBJSON(parsed, params, origURL) + case "barcodelookup_json": + doc, handled = wave3GTINFormatBarcodeLookupJSON(parsed, params, origURL) + case "wikidata_gtin_sparql_json": + doc, handled = wave3GTINFormatWikidataSPARQLJSON(parsed, origURL) + case "energy_star_json": + doc, handled = wave3GTINFormatEnergyStarJSON(parsed, params, origURL) + case "fcc_test_report_json": + doc, handled = wave3GTINFormatFCCTestReportJSON(parsed, origURL) + } + if !handled || doc == nil || strings.TrimSpace(doc.Markdown) == "" { + return nil, false + } + return wave3GTINFinalizeDoc(doc), true +} + +// FormatWave3GTINIdentityJSONMode formats a Category Q JSON payload and returns JSON-marshaled DeclarativeFormattedDoc. +func FormatWave3GTINIdentityJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool) { + doc, ok := FormatWave3GTINIdentityJSONDoc(mode, raw, params, origURL) + if !ok || doc == nil { + return "", false + } + encoded, err := json.Marshal(doc) + if err != nil { + return "", false + } + return string(encoded), true +} + +// FormatWave3GTINIdentityTextDoc formats a Category Q text twin payload (`opengtindb_text`) into DeclarativeFormattedDoc. +func FormatWave3GTINIdentityTextDoc(mode, rawBody string, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool) { + if !IsWave3GTINIdentityTextMode(mode) || len(rawBody) == 0 { + return nil, false + } + if len(rawBody) > wave3GTINMaxTextBytes { + rawBody = truncateUTF8SafeFullDocGo(rawBody, wave3GTINMaxTextBytes) + } + trimmed := strings.TrimSpace(rawBody) + if trimmed == "" || strings.HasPrefix(trimmed, "<") { + return nil, false + } + doc, handled := wave3GTINFormatOpenGTINDBText(trimmed, params, origURL) + if !handled || doc == nil || strings.TrimSpace(doc.Markdown) == "" { + return nil, false + } + return wave3GTINFinalizeDoc(doc), true +} + +// FormatWave3GTINIdentityTextMode formats a Category Q text payload and returns JSON-marshaled DeclarativeFormattedDoc. +func FormatWave3GTINIdentityTextMode(mode, rawBody string, params map[string]string, origURL string) (string, bool) { + doc, ok := FormatWave3GTINIdentityTextDoc(mode, rawBody, params, origURL) + if !ok || doc == nil { + return "", false + } + encoded, err := json.Marshal(doc) + if err != nil { + return "", false + } + return string(encoded), true +} + +// ── Prefilters & Negative Shell Hygiene ────────────────────────────────────────────────────────── + +func wave3GTINMatchesModePrefilter(mode, probeLower, urlLower string) bool { + switch mode { + case "gs1_us_html": + return strings.Contains(urlLower, "gs1us.org") || + strings.Contains(urlLower, "gs1.org") || + strings.Contains(probeLower, "gs1") || + strings.Contains(probeLower, "gepir") || + strings.Contains(probeLower, "gtin") || + strings.Contains(probeLower, "company prefix") + case "open_icecat_html": + return strings.Contains(urlLower, "icecat.biz") || + strings.Contains(urlLower, "icecat.us") || + strings.Contains(probeLower, "icecat") || + strings.Contains(probeLower, "__next_data__") || + strings.Contains(probeLower, "application/ld+json") + case "upcitemdb_barcodelookup_html": + return strings.Contains(urlLower, "upcitemdb.com") || + strings.Contains(urlLower, "barcodelookup.com") || + strings.Contains(probeLower, "upcitemdb") || + strings.Contains(probeLower, "barcodelookup") || + strings.Contains(probeLower, "detail-list") || + strings.Contains(probeLower, "upc-a:") + case "open_product_wikidata_html": + return strings.Contains(urlLower, "opengtindb.org") || + strings.Contains(urlLower, "wikidata.org") || + strings.Contains(probeLower, "opengtindb") || + strings.Contains(probeLower, "wikidata") || + strings.Contains(probeLower, "gtin") + case "energy_star_html": + return strings.Contains(urlLower, "energystar.gov") || + strings.Contains(probeLower, "energystar") || + strings.Contains(probeLower, "energy star") || + strings.Contains(probeLower, "productfinder") + case "fcc_test_report_html": + return strings.Contains(urlLower, "apps.fcc.gov") || + strings.Contains(probeLower, "oetcf") || + strings.Contains(probeLower, "equipment authorization") || + strings.Contains(probeLower, "viewexhibitreport") || + strings.Contains(probeLower, "fcc id") || + strings.Contains(probeLower, "fcc_id") + case "fcc_id_html": + return strings.Contains(urlLower, "fccid.io") || + strings.Contains(probeLower, "fcc id") || + strings.Contains(probeLower, "fccid.io") || + strings.Contains(probeLower, "grantee") + case "prop65_warnings_html": + return strings.Contains(urlLower, "oehha.ca.gov") || + strings.Contains(urlLower, "p65warnings.ca.gov") || + strings.Contains(probeLower, "proposition 65") || + strings.Contains(probeLower, "proposition-65") || + strings.Contains(probeLower, "p65warnings") || + strings.Contains(probeLower, "oehha") + default: + return false + } +} + +func wave3GTINIsNegativeURL(urlLower string) bool { + if urlLower == "" { + return false + } + if strings.Contains(urlLower, "/404") || + strings.Contains(urlLower, "/not-found") || + strings.Contains(urlLower, "/page-not-found") || + strings.Contains(urlLower, "/maintenance") || + strings.Contains(urlLower, "error=true") || + strings.Contains(urlLower, "error=1") { + return true + } + pathOnly := urlLower + if idx := strings.Index(pathOnly, "://"); idx >= 0 { + rest := pathOnly[idx+3:] + if slash := strings.IndexByte(rest, '/'); slash >= 0 { + pathOnly = rest[slash:] + } else { + pathOnly = "/" + } + } + if cut := strings.IndexAny(pathOnly, "?#"); cut >= 0 { + pathOnly = pathOnly[:cut] + } + return strings.HasSuffix(pathOnly, "/error") || + strings.Contains(pathOnly, "/error/") || + strings.HasSuffix(pathOnly, "/error.html") || + strings.HasSuffix(pathOnly, "/error.htm") || + strings.HasSuffix(pathOnly, "/error.aspx") || + strings.HasSuffix(pathOnly, "/login") || + strings.Contains(pathOnly, "/login/") +} + +func wave3GTINIsNegativeTitle(title string) bool { + t := strings.TrimSpace(title) + if t == "" { + return false + } + return wave3GTINRxNotFoundTitle.MatchString(t) || + wave3GTINRxMaintTitle.MatchString(t) || + wave3GTINRxErrorTitle.MatchString(t) +} + +func wave3GTINIsGenericTitle(title string) bool { + return wave3GTINRxGenericTitle.MatchString(strings.TrimSpace(title)) +} + +func wave3GTINExtractTitleBounded(rawHTML string) string { + head := rawHTML + if len(head) > 65536 { + head = head[:65536] + } + m := wave3GTINRxTitleTag.FindStringSubmatch(head) + if len(m) < 2 { + return "" + } + return wave3GTINCleanText(m[1]) +} + +func wave3GTINExtractMetaBounded(rawHTML, targetKey string) string { + head := rawHTML + if len(head) > 65536 { + head = head[:65536] + } + targetLower := strings.ToLower(strings.TrimSpace(targetKey)) + for _, tag := range wave3GTINRxMetaTag.FindAllString(head, 64) { + nameVal, _ := getAttrValueLinearDeclHTML(tag, "name") + propVal, _ := getAttrValueLinearDeclHTML(tag, "property") + if strings.EqualFold(strings.TrimSpace(nameVal), targetLower) || strings.EqualFold(strings.TrimSpace(propVal), targetLower) { + contentVal, ok := getAttrValueLinearDeclHTML(tag, "content") + if ok { + return wave3GTINCleanText(contentVal) + } + } + } + return "" +} + +func wave3GTINVisibleBodyTextLen(rawHTML string) int { + lower := asciiLowerExtractString(rawHTML) + bodySrc := rawHTML + if bIdx := strings.Index(lower, "= 0 { + if gt := strings.IndexByte(rawHTML[bIdx:], '>'); gt >= 0 { + bodySrc = rawHTML[bIdx+gt+1:] + } + } + stripped := stripScriptsStylesNoscriptDeclHTML(bodySrc) + stripped = wave3GTINRxHTMLTag.ReplaceAllString(stripped, " ") + return len(strings.TrimSpace(wave3GTINCleanText(stripped))) +} + +func wave3GTINHasCommonNegativeShell(mode, rawHTML, probeLower, urlLower string) bool { + if wave3GTINIsNegativeURL(urlLower) { + return true + } + if mode == "fcc_id_html" && strings.Contains(urlLower, "/viewexhibitreport.cfm") { + return true + } + // Incapsula WAF challenge (Prop65 / OEHHA & general) + if strings.Contains(probeLower, "/_incapsula_resource") || strings.Contains(probeLower, "incapsula incident id") { + return true + } + // Cloudflare / Akamai / Fastly WAF / PoW challenges + if strings.Contains(probeLower, "cf-mitigated") || + strings.Contains(probeLower, "challenge-platform") || + strings.Contains(probeLower, "/_fs-ch-") || + strings.Contains(probeLower, "/__meb_verify") || + strings.Contains(probeLower, "barcode lookup security verification") || + strings.Contains(probeLower, "security check | fcc id") || + strings.Contains(probeLower, "you don't have permission to access") || + strings.Contains(probeLower, "enable javascript and cookies to continue") || + strings.Contains(probeLower, "__next_error__") { + return true + } + if strings.Contains(probeLower, `name="robots"`) && strings.Contains(probeLower, "noindex") && strings.Contains(probeLower, "nofollow") { + if wave3GTINVisibleBodyTextLen(rawHTML) < 40 { + return true + } + } + title := wave3GTINExtractTitleBounded(rawHTML) + if wave3GTINIsNegativeTitle(title) { + return true + } + if strings.Contains(probeLower, "scheduled maintenance") || + strings.Contains(probeLower, "down for maintenance") || + strings.Contains(probeLower, "this site is undergoing maintenance") || + strings.Contains(probeLower, "temporarily unavailable") { + if wave3GTINVisibleBodyTextLen(rawHTML) < 500 { + return true + } + } + // Energy Star unhydrated ProductFinder SPA shell + if mode == "energy_star_html" && strings.Contains(probeLower, `id="main"`) && strings.Contains(probeLower, `data-basepath="/productfinder`) { + if wave3GTINVisibleBodyTextLen(rawHTML) < 80 { + return true + } + } + // Empty SPA/CSR shell detection when no SSR hydration script is present + hasHydration := strings.Contains(probeLower, "application/ld+json") || strings.Contains(probeLower, "__next_data__") + if !hasHydration { + isEmptyRoot := strings.Contains(probeLower, `
`) || + strings.Contains(probeLower, `
`) || + strings.Contains(probeLower, `
`) || + strings.Contains(probeLower, ``) + if isEmptyRoot && wave3GTINVisibleBodyTextLen(rawHTML) < 80 { + return true + } + } + return false +} + +func wave3GTINIsGenericJSONError(obj map[string]any) bool { + if obj == nil { + return true + } + if errVal, hasErr := obj["error"]; hasErr && errVal != nil { + switch v := errVal.(type) { + case bool: + if v { + return true + } + case string: + if strings.TrimSpace(v) != "" { + return true + } + case map[string]any: + if len(v) > 0 { + return true + } + } + } + for _, k := range []string{"statusCode", "status_code", "status"} { + if n, ok := wave3GTINFloatVal(obj[k]); ok && n >= 400 { + return true + } + } + if msg := strings.ToLower(wave3GTINStringVal(obj["message"])); msg != "" { + if strings.Contains(msg, "not found") || + strings.Contains(msg, "unauthorized") || + strings.Contains(msg, "forbidden") || + strings.Contains(msg, "invalid key") || + strings.Contains(msg, "missing subscription") || + strings.Contains(msg, "access denied") { + if len(obj) <= 4 { + return true + } + } + } + return false +} + +// ── Strict GTIN & Formatting Helpers ───────────────────────────────────────────────────────────── + +// wave3GTINValidStrict validates strictly against NormalizeStrictGTIN (8, 12, 13, or 14 ASCII digits ONLY). +func wave3GTINValidStrict(raw string) string { + return NormalizeStrictGTIN(raw) +} + +// wave3GTINValidStrictFormatted normalizes whitespace/hyphen-grouped barcode strings (e.g. "0 12000 16115 5") +// ONLY if the input contains solely ASCII digits, spaces, and hyphens, then enforces NormalizeStrictGTIN. +// ISBN-10s (10 digits), ASINs, SKUs, hex strings, and 9/11-digit numbers are strictly rejected. +func wave3GTINValidStrictFormatted(raw string) string { + s := strings.TrimSpace(raw) + if s == "" || len(s) > 32 { + return "" + } + var digits strings.Builder + digits.Grow(16) + for i := 0; i < len(s); i++ { + c := s[i] + if c >= '0' && c <= '9' { + digits.WriteByte(c) + } else if c != ' ' && c != '-' { + return "" + } + } + return NormalizeStrictGTIN(digits.String()) +} + +func wave3GTINCleanText(s string) string { + if s == "" { + return "" + } + unesc := stdhtml.UnescapeString(s) + collapsed := strings.TrimSpace(wave3GTINRxSpace.ReplaceAllString(unesc, " ")) + return collapsed +} + +func wave3GTINStripTags(s string) string { + if s == "" { + return "" + } + return wave3GTINCleanText(wave3GTINRxHTMLTag.ReplaceAllString(s, " ")) +} + +func wave3GTINStringVal(v any) string { + switch t := v.(type) { + case nil: + return "" + case string: + return strings.TrimSpace(t) + case json.Number: + return t.String() + case float64: + return strconv.FormatFloat(t, 'f', -1, 64) + case int: + return strconv.Itoa(t) + case int64: + return strconv.FormatInt(t, 10) + case bool: + if t { + return "true" + } + return "false" + default: + return "" + } +} + +func wave3GTINFloatVal(v any) (float64, bool) { + switch t := v.(type) { + case json.Number: + f, err := t.Float64() + return f, err == nil + case float64: + return t, true + case int: + return float64(t), true + case int64: + return float64(t), true + case string: + s := strings.TrimSpace(strings.ReplaceAll(t, ",", "")) + s = strings.TrimPrefix(s, "$") + if s == "" { + return 0, false + } + f, err := strconv.ParseFloat(s, 64) + return f, err == nil + default: + return 0, false + } +} + +func wave3GTINPlain(v any, maxLen int) string { + return SanitizeSchemaPlainField(wave3GTINStripTags(wave3GTINStringVal(v)), maxLen) +} + +func wave3GTINFirstNonEmpty(vals ...string) string { + for _, v := range vals { + if strings.TrimSpace(v) != "" { + return strings.TrimSpace(v) + } + } + return "" +} + +func wave3GTINNestedMap(obj map[string]any, keys ...string) map[string]any { + cur := obj + for _, k := range keys { + if cur == nil { + return nil + } + next, ok := cur[k].(map[string]any) + if !ok { + return nil + } + cur = next + } + return cur +} + +func wave3GTINAddLink(links *[]string, seen map[string]bool, raw, base string) { + if len(*links) >= wave3GTINMaxLinks { + return + } + u := SanitizeSchemaHTTPSURL(raw, base) + if u != "" && !seen[u] { + seen[u] = true + *links = append(*links, u) + } +} + +func wave3GTINExtractTitle(doc *HTMLDoc, rawHTML string) string { + if doc != nil { + if h1 := SanitizeSchemaPlainField(wave3GTINCleanText(doc.Text("h1")), 240); h1 != "" && !wave3GTINIsGenericTitle(h1) && !wave3GTINIsNegativeTitle(h1) { + return h1 + } + } + if og := SanitizeSchemaPlainField(wave3GTINExtractMetaBounded(rawHTML, "og:title"), 240); og != "" && !wave3GTINIsGenericTitle(og) && !wave3GTINIsNegativeTitle(og) { + return og + } + if t := SanitizeSchemaPlainField(wave3GTINExtractTitleBounded(rawHTML), 240); t != "" && !wave3GTINIsGenericTitle(t) && !wave3GTINIsNegativeTitle(t) { + return t + } + return "" +} + +func wave3GTINExtractMetaDesc(rawHTML string) string { + return wave3GTINFirstNonEmpty( + SanitizeSchemaPlainField(wave3GTINExtractMetaBounded(rawHTML, "og:description"), 600), + SanitizeSchemaPlainField(wave3GTINExtractMetaBounded(rawHTML, "description"), 600), + ) +} + +func wave3GTINFinalizeDoc(doc *DeclarativeFormattedDoc) *DeclarativeFormattedDoc { + if doc == nil { + return nil + } + doc.Title = SanitizeSchemaPlainField(doc.Title, 240) + doc.Description = SanitizeSchemaPlainField(doc.Description, 600) + doc.Author = SanitizeSchemaPlainField(doc.Author, 160) + doc.PublishedTime = SanitizeSchemaPlainField(doc.PublishedTime, 64) + if len(doc.Records) > wave3GTINMaxRecords { + doc.Records = doc.Records[:wave3GTINMaxRecords] + } + if len(doc.Links) > wave3GTINMaxLinks { + doc.Links = doc.Links[:wave3GTINMaxLinks] + } + return doc +} + +func wave3GTINFinalizePostFetch(res *DeclarativePostFetchResult) *DeclarativePostFetchResult { + if res == nil { + return nil + } + res.Title = SanitizeSchemaPlainField(res.Title, 240) + res.Description = SanitizeSchemaPlainField(res.Description, 600) + res.Author = SanitizeSchemaPlainField(res.Author, 160) + res.PublishedTime = SanitizeSchemaPlainField(res.PublishedTime, 64) + if len(res.Records) > wave3GTINMaxRecords { + res.Records = res.Records[:wave3GTINMaxRecords] + } + if len(res.Links) > wave3GTINMaxLinks { + res.Links = res.Links[:wave3GTINMaxLinks] + } + return sanitizePostFetchResultDeclHTML(res) +} + +func wave3GTINExtractQueryParam(origURL string, keys ...string) string { + u, err := url.Parse(origURL) + if err != nil { + return "" + } + q := u.Query() + for qk, qvals := range q { + for _, k := range keys { + if strings.EqualFold(qk, k) && len(qvals) > 0 { + return strings.TrimSpace(qvals[0]) + } + } + } + return "" +} + +func wave3GTINCollectStrictGTINs(vals ...any) []string { + seen := make(map[string]bool) + var out []string + add := func(raw string) { + g := wave3GTINValidStrictFormatted(raw) + if g != "" && !seen[g] { + seen[g] = true + out = append(out, g) + } + } + for _, v := range vals { + switch t := v.(type) { + case string: + add(t) + case json.Number: + add(t.String()) + case []any: + for _, el := range t { + add(wave3GTINStringVal(el)) + } + case []string: + for _, el := range t { + add(el) + } + } + } + return out +} + +// ── #368 GS1 US Data Hub (`gs1_us_json` + `gs1_us_html`) ───────────────────────────────────────── + +func wave3GTINFormatGS1USJSON(parsed any, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool) { + var rawItems []any + var rootObj map[string]any + switch t := parsed.(type) { + case map[string]any: + if wave3GTINIsGenericJSONError(t) { + return nil, false + } + rootObj = t + for _, k := range []string{"gtins", "items", "results", "data", "records"} { + if arr, ok := t[k].([]any); ok && len(arr) > 0 { + rawItems = arr + break + } + } + if len(rawItems) == 0 { + rawItems = []any{t} + } + case []any: + if len(t) == 0 { + return nil, false + } + rawItems = t + default: + return nil, false + } + + reqGTIN := wave3GTINValidStrict(wave3GTINFirstNonEmpty(params["gtin"], wave3GTINExtractQueryParam(origURL, "gtin", "GTIN"))) + var records []map[string]any + var rows [][]string + + for _, item := range rawItems { + if len(records) >= wave3GTINMaxRecords { + break + } + m, ok := item.(map[string]any) + if !ok { + continue + } + gtinList := wave3GTINCollectStrictGTINs(m["gtin"], m["gtin14"], m["gtin13"], m["gtin12"], m["gtin8"], m["upc"], m["ean"]) + gtin := "" + if len(gtinList) > 0 { + gtin = gtinList[0] + } else if reqGTIN != "" { + gtin = reqGTIN + } + + company := wave3GTINFirstNonEmpty( + wave3GTINPlain(m["companyName"], 180), + wave3GTINPlain(m["licenseeName"], 180), + wave3GTINPlain(m["brandOwner"], 180), + wave3GTINPlain(m["partyName"], 180), + wave3GTINPlain(wave3GTINNestedMap(m, "licensee")["name"], 180), + ) + gln := wave3GTINValidStrict(wave3GTINFirstNonEmpty(wave3GTINStringVal(m["gln"]), wave3GTINStringVal(m["informationProviderGln"]))) + prefix := wave3GTINPlain(wave3GTINFirstNonEmpty(wave3GTINStringVal(m["gs1CompanyPrefix"]), wave3GTINStringVal(m["companyPrefix"])), 40) + brand := wave3GTINPlain(wave3GTINFirstNonEmpty(wave3GTINStringVal(m["brandName"]), wave3GTINStringVal(m["brand"])), 140) + desc := wave3GTINPlain(wave3GTINFirstNonEmpty( + wave3GTINStringVal(m["productDescription"]), + wave3GTINStringVal(m["gtinName"]), + wave3GTINStringVal(m["description"]), + wave3GTINStringVal(m["title"]), + ), 260) + status := wave3GTINPlain(wave3GTINFirstNonEmpty(wave3GTINStringVal(m["gtinStatus"]), wave3GTINStringVal(m["status"])), 64) + gpc := wave3GTINPlain(wave3GTINFirstNonEmpty(wave3GTINStringVal(m["gpcCategoryName"]), wave3GTINStringVal(m["gpcCategoryCode"])), 120) + country := wave3GTINPlain(wave3GTINFirstNonEmpty(wave3GTINStringVal(m["targetMarket"]), wave3GTINStringVal(m["countryCode"])), 48) + + if gtin == "" && company == "" && gln == "" && desc == "" { + continue + } + + rec := map[string]any{} + if gtin != "" { + rec["gtin"] = gtin + } + if company != "" { + rec["companyName"] = company + } + if brand != "" { + rec["brand"] = brand + } + if gln != "" { + rec["gln"] = gln + } + if prefix != "" { + rec["companyPrefix"] = prefix + } + if status != "" { + rec["status"] = status + } + if gpc != "" { + rec["gpcCategory"] = gpc + } + if desc != "" { + rec["description"] = desc + } + if country != "" { + rec["country"] = country + } + records = append(records, rec) + rows = append(rows, []string{ + wave3GTINFirstNonEmpty(gtin, "-"), + escapeDeclMarkdownBrackets(wave3GTINFirstNonEmpty(company, "-")), + escapeDeclMarkdownBrackets(wave3GTINFirstNonEmpty(brand, "-")), + escapeDeclMarkdownBrackets(wave3GTINFirstNonEmpty(status, "-")), + escapeDeclMarkdownBrackets(wave3GTINFirstNonEmpty(desc, gpc, "-")), + }) + } + + if len(records) == 0 { + return nil, false + } + + first := records[0] + title := "GS1 US Data Hub" + if g := wave3GTINStringVal(first["gtin"]); g != "" { + title = "GS1 US Data Hub: GTIN " + g + } else if c := wave3GTINStringVal(first["companyName"]); c != "" { + title = "GS1 US Data Hub: " + c + } + + var bullets []string + if g := wave3GTINStringVal(first["gtin"]); g != "" { + bullets = append(bullets, "- **GTIN**: `"+g+"`") + } + if c := wave3GTINStringVal(first["companyName"]); c != "" { + bullets = append(bullets, "- **Company / Licensee**: "+escapeDeclMarkdownBrackets(c)) + } + if b := wave3GTINStringVal(first["brand"]); b != "" { + bullets = append(bullets, "- **Brand**: "+escapeDeclMarkdownBrackets(b)) + } + if gln := wave3GTINStringVal(first["gln"]); gln != "" { + bullets = append(bullets, "- **GLN**: `"+gln+"`") + } + if p := wave3GTINStringVal(first["companyPrefix"]); p != "" { + bullets = append(bullets, "- **GS1 Company Prefix**: `"+sanitizeDeclInlineCodeVal(p)+"`") + } + if st := wave3GTINStringVal(first["status"]); st != "" { + bullets = append(bullets, "- **Status**: "+escapeDeclMarkdownBrackets(st)) + } + if gpc := wave3GTINStringVal(first["gpcCategory"]); gpc != "" { + bullets = append(bullets, "- **GPC Category**: "+escapeDeclMarkdownBrackets(gpc)) + } + + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + if len(rows) > 1 || (rootObj != nil && len(rawItems) > 1) { + blocks = append(blocks, "## GS1 Records\n\n"+formatDeclarativeGFMTable([]string{"GTIN", "Licensee", "Brand", "Status", "Description"}, rows)) + } else if d := wave3GTINStringVal(first["description"]); d != "" { + blocks = append(blocks, "## Product Description\n\n"+escapeDeclMarkdownBlock(d)) + } + + return &DeclarativeFormattedDoc{ + Title: title, + Description: wave3GTINPlain(first["description"], 260), + Markdown: strings.Join(blocks, "\n\n"), + Records: records, + }, true +} + +func wave3GTINExtractGS1USHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + doc := ParseHTMLDoc(rawHTML, wave3GTINMaxHTMLBytes) + title := wave3GTINExtractTitle(doc, rawHTML) + if title == "" { + return nil + } + desc := wave3GTINExtractMetaDesc(rawHTML) + + kv := make(map[string]string) + var kvOrder []string + addKV := func(k, v string) { + ck := SanitizeSchemaPlainField(k, 80) + cv := SanitizeSchemaPlainField(v, 240) + if ck == "" || cv == "" { + return + } + lk := strings.ToLower(ck) + if _, exists := kv[lk]; !exists { + kv[lk] = cv + kvOrder = append(kvOrder, ck) + } + } + + var gtin string + if doc != nil { + dl := doc.DLMap("dl") + dlKeys := make([]string, 0, len(dl)) + for k := range dl { + dlKeys = append(dlKeys, k) + } + sort.Strings(dlKeys) + for _, k := range dlKeys { + v := dl[k] + if strings.Contains(k, "gtin") || strings.Contains(k, "upc") || strings.Contains(k, "ean") { + if g := wave3GTINValidStrictFormatted(v); g != "" { + if gtin == "" { + gtin = g + } + addKV(k, g) + } + continue + } + addKV(k, v) + } + for _, row := range doc.TableRows("table") { + if len(row) >= 2 { + lk := strings.ToLower(row[0]) + if strings.Contains(lk, "gtin") || strings.Contains(lk, "upc") || strings.Contains(lk, "ean") { + if g := wave3GTINValidStrictFormatted(row[1]); g != "" { + if gtin == "" { + gtin = g + } + addKV(row[0], g) + } + continue + } + addKV(row[0], row[1]) + } + } + } + + var paras []string + if doc != nil { + for _, pNode := range doc.Select("main p, article p, .cmp-text p, .text p", 8) { + pt := SanitizeSchemaPlainField(wave3GTINCleanText(pNode.Text()), 500) + if len(pt) >= 24 { + paras = append(paras, pt) + } + } + } + if len(paras) == 0 && len(kvOrder) == 0 && desc == "" { + return nil + } + + rec := map[string]any{"title": title} + if gtin != "" { + rec["gtin"] = gtin + } + var bullets []string + if gtin != "" { + bullets = append(bullets, "- **GTIN**: `"+gtin+"`") + } + for _, k := range kvOrder { + v := kv[strings.ToLower(k)] + bullets = append(bullets, fmt.Sprintf("- **%s**: %s", escapeDeclMarkdownBrackets(k), escapeDeclMarkdownBrackets(v))) + if len(bullets) >= 12 { + break + } + } + + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + if len(paras) > 0 { + blocks = append(blocks, "## Overview\n\n"+escapeDeclPlainTextPreservingNewlines(strings.Join(paras, "\n\n"))) + } else if desc != "" { + blocks = append(blocks, "## Overview\n\n"+escapeDeclMarkdownBlock(desc)) + } + + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: wave3GTINFirstNonEmpty(desc, sliceRunesMax(strings.Join(paras, " "), 260)), + Markdown: strings.Join(blocks, "\n\n"), + Records: []map[string]any{rec}, + } +} + +// ── #369 Open Icecat (`open_icecat_json` + `open_icecat_html`) ─────────────────────────────────── + +func wave3GTINFormatOpenIcecatJSON(parsed any, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool) { + obj, ok := parsed.(map[string]any) + if !ok || wave3GTINIsGenericJSONError(obj) { + return nil, false + } + if sc, okSC := wave3GTINFloatVal(obj["StatusCode"]); okSC && sc != 0 { + return nil, false + } + if msg := strings.TrimSpace(wave3GTINStringVal(obj["msg"])); msg != "" && !strings.EqualFold(msg, "OK") { + return nil, false + } + data := wave3GTINNestedMap(obj, "data") + if data == nil { + return nil, false + } + gi := wave3GTINNestedMap(data, "GeneralInfo") + if gi == nil { + return nil, false + } + + icecatID := wave3GTINPlain(gi["IcecatId"], 32) + titleInfo := wave3GTINNestedMap(gi, "TitleInfo") + title := wave3GTINFirstNonEmpty( + wave3GTINPlain(gi["Title"], 240), + wave3GTINPlain(titleInfo["GeneratedIntTitle"], 240), + wave3GTINPlain(gi["ProductName"], 240), + ) + if title == "" { + return nil, false + } + + brandInfo := wave3GTINNestedMap(gi, "BrandInfo") + brand := wave3GTINFirstNonEmpty( + wave3GTINPlain(gi["Brand"], 140), + wave3GTINPlain(brandInfo["BrandName"], 140), + ) + mpn := wave3GTINPlain(gi["BrandPartCode"], 120) + catObj := wave3GTINNestedMap(gi, "Category", "Name") + category := wave3GTINPlain(catObj["Value"], 120) + releaseDate := wave3GTINPlain(gi["ReleaseDate"], 32) + + gtins := wave3GTINCollectStrictGTINs(gi["GTIN"], params["gtin"], wave3GTINExtractQueryParam(origURL, "GTIN", "gtin")) + primaryGTIN := "" + if len(gtins) > 0 { + primaryGTIN = gtins[0] + } + + sumDescObj := wave3GTINNestedMap(gi, "SummaryDescription") + descObj := wave3GTINNestedMap(gi, "Description") + shortDesc := wave3GTINFirstNonEmpty( + wave3GTINPlain(sumDescObj["ShortSummaryDescription"], 600), + wave3GTINPlain(descObj["ShortDesc"], 600), + ) + longDesc := wave3GTINFirstNonEmpty( + wave3GTINPlain(sumDescObj["LongSummaryDescription"], 1600), + wave3GTINPlain(descObj["LongDesc"], 1600), + shortDesc, + ) + + var specRows [][]string + if fGroups, okFG := data["FeaturesGroups"].([]any); okFG { + for _, fgAny := range fGroups { + if len(specRows) >= 25 { + break + } + fg, okFGMap := fgAny.(map[string]any) + if !okFGMap { + continue + } + groupName := wave3GTINPlain(wave3GTINNestedMap(fg, "FeatureGroup", "Name")["Value"], 80) + feats, okFeats := fg["Features"].([]any) + if !okFeats { + continue + } + for _, fAny := range feats { + if len(specRows) >= 25 { + break + } + fMap, okF := fAny.(map[string]any) + if !okF { + continue + } + fname := wave3GTINPlain(wave3GTINNestedMap(fMap, "Feature", "Name")["Value"], 100) + fval := wave3GTINFirstNonEmpty( + wave3GTINPlain(fMap["PresentationValue"], 140), + wave3GTINPlain(fMap["Value"], 140), + ) + if fname != "" && fval != "" { + specRows = append(specRows, []string{ + escapeDeclMarkdownBrackets(wave3GTINFirstNonEmpty(groupName, "-")), + escapeDeclMarkdownBrackets(fname), + escapeDeclMarkdownBrackets(fval), + }) + } + } + } + } + + var links []string + seenLinks := make(map[string]bool) + if pic := wave3GTINNestedMap(gi, "ProductPicture"); pic != nil { + wave3GTINAddLink(&links, seenLinks, wave3GTINStringVal(pic["HighPic"]), origURL) + } + if descObj != nil { + wave3GTINAddLink(&links, seenLinks, wave3GTINStringVal(descObj["URL"]), origURL) + wave3GTINAddLink(&links, seenLinks, wave3GTINStringVal(descObj["PDFURL"]), origURL) + } + + rec := map[string]any{"title": title} + var bullets []string + if icecatID != "" { + rec["icecatId"] = icecatID + bullets = append(bullets, "- **Icecat ID**: `"+sanitizeDeclInlineCodeVal(icecatID)+"`") + } + if primaryGTIN != "" { + rec["gtin"] = primaryGTIN + bullets = append(bullets, "- **GTIN**: `"+strings.Join(gtins, "`, `")+"`") + } + if brand != "" { + rec["brand"] = brand + bullets = append(bullets, "- **Brand**: "+escapeDeclMarkdownBrackets(brand)) + } + if mpn != "" { + rec["mpn"] = mpn + bullets = append(bullets, "- **Part Code (MPN)**: `"+sanitizeDeclInlineCodeVal(mpn)+"`") + } + if category != "" { + rec["category"] = category + bullets = append(bullets, "- **Category**: "+escapeDeclMarkdownBrackets(category)) + } + if releaseDate != "" { + rec["releaseDate"] = releaseDate + bullets = append(bullets, "- **Release Date**: "+escapeDeclMarkdownBrackets(releaseDate)) + } + if shortDesc != "" { + rec["description"] = shortDesc + } + + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + if longDesc != "" { + blocks = append(blocks, "## Summary\n\n"+escapeDeclMarkdownBlock(longDesc)) + } + if len(specRows) > 0 { + blocks = append(blocks, "## Specifications\n\n"+formatDeclarativeGFMTable([]string{"Group", "Feature", "Value"}, specRows)) + } + + return &DeclarativeFormattedDoc{ + Title: title, + Description: sliceRunesMax(shortDesc, 260), + Author: brand, + PublishedTime: releaseDate, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: []map[string]any{rec}, + }, true +} + +func wave3GTINExtractOpenIcecatHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + ldObjs := extractJSONLDObjectsDeclHTML(rawHTML, 16) + var prod map[string]any + for _, o := range ldObjs { + if t, _ := o["@type"].(string); strings.EqualFold(t, "Product") { + prod = o + break + } + } + doc := ParseHTMLDoc(rawHTML, wave3GTINMaxHTMLBytes) + title := wave3GTINExtractTitle(doc, rawHTML) + if prod != nil { + if n := wave3GTINPlain(prod["name"], 240); n != "" { + title = n + } + } + if title == "" { + return nil + } + + var gtin, brand, mpn, desc string + if prod != nil { + gtins := wave3GTINCollectStrictGTINs(prod["gtin14"], prod["gtin13"], prod["gtin12"], prod["gtin8"], prod["gtin"]) + if len(gtins) > 0 { + gtin = gtins[0] + } + if bm, ok := prod["brand"].(map[string]any); ok { + brand = wave3GTINPlain(bm["name"], 120) + } else { + brand = wave3GTINPlain(prod["brand"], 120) + } + mpn = wave3GTINPlain(prod["mpn"], 120) + desc = wave3GTINPlain(prod["description"], 1200) + } + if desc == "" { + desc = wave3GTINExtractMetaDesc(rawHTML) + } + + var rows [][]string + if doc != nil { + for _, r := range doc.TableRows("table") { + if len(r) >= 2 { + if gtin == "" && (strings.Contains(strings.ToLower(r[0]), "gtin") || strings.Contains(strings.ToLower(r[0]), "ean") || strings.Contains(strings.ToLower(r[0]), "upc")) { + gtin = wave3GTINValidStrictFormatted(r[1]) + } + rows = append(rows, []string{ + escapeDeclMarkdownBrackets(SanitizeSchemaPlainField(r[0], 100)), + escapeDeclMarkdownBrackets(SanitizeSchemaPlainField(r[1], 180)), + }) + if len(rows) >= 25 { + break + } + } + } + } + if prod == nil && len(rows) == 0 && desc == "" { + return nil + } + + rec := map[string]any{"title": title} + var bullets []string + if gtin != "" { + rec["gtin"] = gtin + bullets = append(bullets, "- **GTIN**: `"+gtin+"`") + } + if brand != "" { + rec["brand"] = brand + bullets = append(bullets, "- **Brand**: "+escapeDeclMarkdownBrackets(brand)) + } + if mpn != "" { + rec["mpn"] = mpn + bullets = append(bullets, "- **MPN**: `"+sanitizeDeclInlineCodeVal(mpn)+"`") + } + + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + if desc != "" { + blocks = append(blocks, "## Description\n\n"+escapeDeclMarkdownBlock(desc)) + } + if len(rows) > 0 { + blocks = append(blocks, "## Datasheet\n\n"+formatDeclarativeGFMTable([]string{"Attribute", "Value"}, rows)) + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: sliceRunesMax(desc, 260), + Author: brand, + Markdown: strings.Join(blocks, "\n\n"), + Records: []map[string]any{rec}, + } +} + +// ── #370 UPCitemdb & Barcode Lookup (`upcitemdb_json`, `barcodelookup_json`, HTML) ─────────────── + +func wave3GTINFormatUPCItemDBJSON(parsed any, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool) { + obj, ok := parsed.(map[string]any) + if !ok || wave3GTINIsGenericJSONError(obj) { + return nil, false + } + code := strings.ToUpper(wave3GTINStringVal(obj["code"])) + if code != "" && code != "OK" { + return nil, false + } + items, okItems := obj["items"].([]any) + if !okItems || len(items) == 0 { + return nil, false + } + + reqUPC := wave3GTINValidStrict(wave3GTINFirstNonEmpty(params["upc"], wave3GTINExtractQueryParam(origURL, "upc", "ean", "gtin"))) + var records []map[string]any + var offerRows [][]string + var links []string + seenLinks := make(map[string]bool) + + for _, itAny := range items { + if len(records) >= wave3GTINMaxRecords { + break + } + it, okIt := itAny.(map[string]any) + if !okIt { + continue + } + gtins := wave3GTINCollectStrictGTINs(it["ean"], it["upc"], it["gtin"], reqUPC) + gtin := "" + if len(gtins) > 0 { + gtin = gtins[0] + } + title := wave3GTINPlain(it["title"], 240) + brand := wave3GTINPlain(it["brand"], 140) + model := wave3GTINPlain(it["model"], 120) + category := wave3GTINPlain(it["category"], 180) + desc := wave3GTINPlain(it["description"], 1200) + asin := wave3GTINPlain(it["asin"], 32) + if title == "" && gtin == "" { + continue + } + + rec := map[string]any{} + if title != "" { + rec["title"] = title + } + if gtin != "" { + rec["gtin"] = gtin + } + if brand != "" { + rec["brand"] = brand + } + if model != "" { + rec["model"] = model + } + if category != "" { + rec["category"] = category + } + if asin != "" { + rec["asin"] = asin + } + if desc != "" { + rec["description"] = sliceRunesMax(desc, 260) + } + if lowP, okLow := wave3GTINFloatVal(it["lowest_recorded_price"]); okLow && lowP > 0 { + rec["lowestPrice"] = fmt.Sprintf("%.2f", lowP) + } + if highP, okHigh := wave3GTINFloatVal(it["highest_recorded_price"]); okHigh && highP > 0 { + rec["highestPrice"] = fmt.Sprintf("%.2f", highP) + } + records = append(records, rec) + + if offers, okOff := it["offers"].([]any); okOff { + for _, offAny := range offers { + if len(offerRows) >= 15 { + break + } + off, okO := offAny.(map[string]any) + if !okO { + continue + } + merchant := wave3GTINPlain(off["merchant"], 100) + cur := wave3GTINPlain(off["currency"], 8) + if cur == "" { + cur = "USD" + } + priceStr := "-" + if p, okP := wave3GTINFloatVal(off["price"]); okP && p > 0 { + priceStr = fmt.Sprintf("%.2f %s", p, cur) + } + cond := wave3GTINPlain(off["condition"], 48) + wave3GTINAddLink(&links, seenLinks, wave3GTINStringVal(off["link"]), origURL) + if merchant != "" { + offerRows = append(offerRows, []string{ + escapeDeclMarkdownBrackets(merchant), + escapeDeclMarkdownBrackets(priceStr), + escapeDeclMarkdownBrackets(wave3GTINFirstNonEmpty(cond, "-")), + }) + } + } + } + } + + if len(records) == 0 { + return nil, false + } + + first := records[0] + title := wave3GTINFirstNonEmpty(wave3GTINStringVal(first["title"]), "UPCitemdb Product") + var bullets []string + if g := wave3GTINStringVal(first["gtin"]); g != "" { + bullets = append(bullets, "- **GTIN**: `"+g+"`") + } + if b := wave3GTINStringVal(first["brand"]); b != "" { + bullets = append(bullets, "- **Brand**: "+escapeDeclMarkdownBrackets(b)) + } + if m := wave3GTINStringVal(first["model"]); m != "" { + bullets = append(bullets, "- **Model**: "+escapeDeclMarkdownBrackets(m)) + } + if c := wave3GTINStringVal(first["category"]); c != "" { + bullets = append(bullets, "- **Category**: "+escapeDeclMarkdownBrackets(c)) + } + if lp := wave3GTINStringVal(first["lowestPrice"]); lp != "" { + hp := wave3GTINStringVal(first["highestPrice"]) + if hp != "" && hp != lp { + bullets = append(bullets, fmt.Sprintf("- **Recorded Price Range**: $%s - $%s", lp, hp)) + } else { + bullets = append(bullets, fmt.Sprintf("- **Lowest Recorded Price**: $%s", lp)) + } + } + + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + firstItemDesc := "" + if firstMap, okFM := items[0].(map[string]any); okFM { + firstItemDesc = wave3GTINPlain(firstMap["description"], 1200) + } + if firstItemDesc != "" { + blocks = append(blocks, "## Description\n\n"+escapeDeclMarkdownBlock(firstItemDesc)) + } + if len(offerRows) > 0 { + blocks = append(blocks, "## Merchant Offers\n\n"+formatDeclarativeGFMTable([]string{"Merchant", "Price", "Condition"}, offerRows)) + } + + return &DeclarativeFormattedDoc{ + Title: title, + Description: sliceRunesMax(firstItemDesc, 260), + Author: wave3GTINStringVal(first["brand"]), + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: records, + }, true +} + +func wave3GTINFormatBarcodeLookupJSON(parsed any, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool) { + obj, ok := parsed.(map[string]any) + if !ok || wave3GTINIsGenericJSONError(obj) { + return nil, false + } + prods, okProds := obj["products"].([]any) + if !okProds || len(prods) == 0 { + return nil, false + } + + reqBarcode := wave3GTINValidStrict(wave3GTINFirstNonEmpty(params["barcode"], wave3GTINExtractQueryParam(origURL, "barcode", "upc", "gtin"))) + var records []map[string]any + var storeRows [][]string + var links []string + seenLinks := make(map[string]bool) + + for _, pAny := range prods { + if len(records) >= wave3GTINMaxRecords { + break + } + p, okP := pAny.(map[string]any) + if !okP { + continue + } + gtins := wave3GTINCollectStrictGTINs(p["barcode_number"], reqBarcode) + gtin := "" + if len(gtins) > 0 { + gtin = gtins[0] + } + title := wave3GTINFirstNonEmpty(wave3GTINPlain(p["title"], 240), wave3GTINPlain(p["product_name"], 240)) + brand := wave3GTINFirstNonEmpty(wave3GTINPlain(p["brand"], 140), wave3GTINPlain(p["manufacturer"], 140)) + mpn := wave3GTINPlain(p["mpn"], 120) + model := wave3GTINPlain(p["model"], 120) + category := wave3GTINPlain(p["category"], 180) + formats := wave3GTINPlain(p["barcode_formats"], 160) + if title == "" && gtin == "" { + continue + } + + rec := map[string]any{} + if title != "" { + rec["title"] = title + } + if gtin != "" { + rec["gtin"] = gtin + } + if brand != "" { + rec["brand"] = brand + } + if mpn != "" { + rec["mpn"] = mpn + } + if model != "" { + rec["model"] = model + } + if category != "" { + rec["category"] = category + } + if formats != "" { + rec["barcodeFormats"] = formats + } + records = append(records, rec) + + if stores, okSt := p["stores"].([]any); okSt { + for _, stAny := range stores { + if len(storeRows) >= 15 { + break + } + st, okS := stAny.(map[string]any) + if !okS { + continue + } + stName := wave3GTINPlain(wave3GTINFirstNonEmpty(wave3GTINStringVal(st["name"]), wave3GTINStringVal(st["store_name"])), 100) + cur := wave3GTINPlain(wave3GTINFirstNonEmpty(wave3GTINStringVal(st["currency"]), wave3GTINStringVal(st["currency_symbol"])), 8) + price := wave3GTINPlain(wave3GTINFirstNonEmpty(wave3GTINStringVal(st["price"]), wave3GTINStringVal(st["store_price"])), 32) + wave3GTINAddLink(&links, seenLinks, wave3GTINStringVal(st["link"]), origURL) + if stName != "" { + storeRows = append(storeRows, []string{ + escapeDeclMarkdownBrackets(stName), + escapeDeclMarkdownBrackets(strings.TrimSpace(price + " " + cur)), + }) + } + } + } + } + + if len(records) == 0 { + return nil, false + } + + first := records[0] + title := wave3GTINFirstNonEmpty(wave3GTINStringVal(first["title"]), "Barcode Lookup Product") + var bullets []string + if g := wave3GTINStringVal(first["gtin"]); g != "" { + bullets = append(bullets, "- **GTIN**: `"+g+"`") + } + if f := wave3GTINStringVal(first["barcodeFormats"]); f != "" { + bullets = append(bullets, "- **Barcode Formats**: "+escapeDeclMarkdownBrackets(f)) + } + if b := wave3GTINStringVal(first["brand"]); b != "" { + bullets = append(bullets, "- **Brand**: "+escapeDeclMarkdownBrackets(b)) + } + if mpn := wave3GTINStringVal(first["mpn"]); mpn != "" { + bullets = append(bullets, "- **MPN**: `"+sanitizeDeclInlineCodeVal(mpn)+"`") + } + if c := wave3GTINStringVal(first["category"]); c != "" { + bullets = append(bullets, "- **Category**: "+escapeDeclMarkdownBrackets(c)) + } + + firstDesc := "" + if p0, ok0 := prods[0].(map[string]any); ok0 { + firstDesc = wave3GTINPlain(p0["description"], 1200) + } + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + if firstDesc != "" { + blocks = append(blocks, "## Description\n\n"+escapeDeclMarkdownBlock(firstDesc)) + } + if len(storeRows) > 0 { + blocks = append(blocks, "## Store Pricing\n\n"+formatDeclarativeGFMTable([]string{"Store", "Price"}, storeRows)) + } + + return &DeclarativeFormattedDoc{ + Title: title, + Description: sliceRunesMax(firstDesc, 260), + Author: wave3GTINStringVal(first["brand"]), + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: records, + }, true +} + +func wave3GTINExtractUPCItemDBBarcodeLookupHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + doc := ParseHTMLDoc(rawHTML, wave3GTINMaxHTMLBytes) + title := wave3GTINExtractTitle(doc, rawHTML) + if title == "" { + return nil + } + + var gtin, brand, model, category string + var detailRows [][]string + if doc != nil { + for _, row := range doc.TableRows("table.detail-list, table") { + if len(row) < 2 { + continue + } + label := strings.TrimSuffix(SanitizeSchemaPlainField(row[0], 80), ":") + val := SanitizeSchemaPlainField(row[1], 180) + if label == "" || val == "" { + continue + } + ll := strings.ToLower(label) + if strings.Contains(ll, "upc") || strings.Contains(ll, "ean") || strings.Contains(ll, "gtin") { + if g := wave3GTINValidStrictFormatted(val); g != "" { + if gtin == "" { + gtin = g + } + detailRows = append(detailRows, []string{escapeDeclMarkdownBrackets(label), g}) + } + continue + } + if strings.Contains(ll, "brand") && brand == "" { + brand = val + } + if strings.Contains(ll, "model") && model == "" { + model = val + } + if strings.Contains(ll, "category") && category == "" { + category = val + } + detailRows = append(detailRows, []string{escapeDeclMarkdownBrackets(label), escapeDeclMarkdownBrackets(val)}) + if len(detailRows) >= 20 { + break + } + } + } + desc := wave3GTINExtractMetaDesc(rawHTML) + if len(detailRows) == 0 && gtin == "" && desc == "" { + return nil + } + + rec := map[string]any{"title": title} + var bullets []string + if gtin != "" { + rec["gtin"] = gtin + bullets = append(bullets, "- **GTIN**: `"+gtin+"`") + } + if brand != "" { + rec["brand"] = brand + bullets = append(bullets, "- **Brand**: "+escapeDeclMarkdownBrackets(brand)) + } + if model != "" { + rec["model"] = model + bullets = append(bullets, "- **Model**: "+escapeDeclMarkdownBrackets(model)) + } + if category != "" { + rec["category"] = category + bullets = append(bullets, "- **Category**: "+escapeDeclMarkdownBrackets(category)) + } + + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + if len(detailRows) > 0 { + blocks = append(blocks, "## Product Details\n\n"+formatDeclarativeGFMTable([]string{"Field", "Value"}, detailRows)) + } else if desc != "" { + blocks = append(blocks, "## Description\n\n"+escapeDeclMarkdownBlock(desc)) + } + + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: sliceRunesMax(desc, 260), + Author: brand, + Markdown: strings.Join(blocks, "\n\n"), + Records: []map[string]any{rec}, + } +} + +// ── #371 Open Product Data & Wikidata GTIN (`opengtindb_text`, `wikidata_gtin_sparql_json`, HTML) ─ + +func wave3GTINFormatOpenGTINDBText(rawBody string, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool) { + lines := strings.Split(strings.ReplaceAll(rawBody, "\r\n", "\n"), "\n") + fields := make(map[string]string) + sawErrorLine := false + errCode := "" + + for _, rawLine := range lines { + line := strings.TrimSpace(rawLine) + if line == "" || line == "---" { + continue + } + eq := strings.IndexByte(line, '=') + if eq <= 0 { + continue + } + k := strings.ToLower(strings.TrimSpace(line[:eq])) + v := SanitizeSchemaPlainField(strings.TrimSpace(line[eq+1:]), 280) + if k == "error" { + sawErrorLine = true + errCode = v + continue + } + if v != "" { + if _, exists := fields[k]; !exists { + fields[k] = v + } + } + } + + if !sawErrorLine || errCode != "0" { + return nil, false + } + + gtin := wave3GTINValidStrict(wave3GTINFirstNonEmpty( + fields["ean"], + fields["gtin"], + params["ean"], + wave3GTINExtractQueryParam(origURL, "ean", "gtin"), + )) + name := wave3GTINFirstNonEmpty(fields["detailname"], fields["name"]) + if name == "" && gtin == "" { + return nil, false + } + + vendor := fields["vendor"] + mainCat := fields["maincat"] + subCat := fields["subcat"] + origin := fields["origin"] + descr := fields["descr"] + + title := wave3GTINFirstNonEmpty(name, "OpenGTINdb Product") + if gtin != "" && name != "" { + title = fmt.Sprintf("%s (GTIN %s)", name, gtin) + } + + rec := map[string]any{} + var bullets []string + if gtin != "" { + rec["gtin"] = gtin + bullets = append(bullets, "- **GTIN**: `"+gtin+"`") + } + if name != "" { + rec["title"] = name + } + if vendor != "" { + rec["brand"] = vendor + bullets = append(bullets, "- **Vendor / Brand**: "+escapeDeclMarkdownBrackets(vendor)) + } + if mainCat != "" || subCat != "" { + cat := strings.TrimSpace(mainCat) + if subCat != "" { + if cat != "" { + cat += " / " + subCat + } else { + cat = subCat + } + } + rec["category"] = cat + bullets = append(bullets, "- **Category**: "+escapeDeclMarkdownBrackets(cat)) + } + if origin != "" { + rec["origin"] = origin + bullets = append(bullets, "- **Origin**: "+escapeDeclMarkdownBrackets(origin)) + } + + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + if descr != "" { + rec["description"] = descr + blocks = append(blocks, "## Description\n\n"+escapeDeclMarkdownBlock(descr)) + } + + return &DeclarativeFormattedDoc{ + Title: title, + Description: sliceRunesMax(descr, 260), + Author: vendor, + Markdown: strings.Join(blocks, "\n\n"), + Records: []map[string]any{rec}, + }, true +} + +func wave3GTINFormatWikidataSPARQLJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + obj, ok := parsed.(map[string]any) + if !ok || wave3GTINIsGenericJSONError(obj) { + return nil, false + } + resObj := wave3GTINNestedMap(obj, "results") + if resObj == nil { + return nil, false + } + bindings, okB := resObj["bindings"].([]any) + if !okB || len(bindings) == 0 { + return nil, false + } + + readBindingVal := func(b map[string]any, keys ...string) string { + for _, k := range keys { + if cell, okC := b[k].(map[string]any); okC { + if v := wave3GTINPlain(cell["value"], 240); v != "" { + return v + } + } + } + return "" + } + + var records []map[string]any + var rows [][]string + var links []string + seenLinks := make(map[string]bool) + + for _, bAny := range bindings { + if len(records) >= wave3GTINMaxRecords { + break + } + b, okMap := bAny.(map[string]any) + if !okMap { + continue + } + itemURI := readBindingVal(b, "item", "entity", "product") + label := readBindingVal(b, "itemLabel", "label", "productLabel", "name") + gtin := wave3GTINValidStrictFormatted(readBindingVal(b, "gtin", "ean", "upc", "p3962")) + brand := readBindingVal(b, "brandLabel", "manufacturerLabel", "brand") + desc := readBindingVal(b, "itemDescription", "description") + + if label == "" && gtin == "" && itemURI == "" { + continue + } + if itemURI != "" { + wave3GTINAddLink(&links, seenLinks, itemURI, origURL) + } + + rec := map[string]any{} + if label != "" { + rec["title"] = label + } + if gtin != "" { + rec["gtin"] = gtin + } + if brand != "" { + rec["brand"] = brand + } + if itemURI != "" { + rec["url"] = itemURI + } + if desc != "" { + rec["description"] = desc + } + records = append(records, rec) + rows = append(rows, []string{ + escapeDeclMarkdownBrackets(wave3GTINFirstNonEmpty(label, itemURI, "-")), + wave3GTINFirstNonEmpty(gtin, "-"), + escapeDeclMarkdownBrackets(wave3GTINFirstNonEmpty(brand, "-")), + escapeDeclMarkdownBrackets(wave3GTINFirstNonEmpty(desc, "-")), + }) + } + + if len(records) == 0 { + return nil, false + } + + title := "Wikidata GTIN Query Results" + if len(records) == 1 { + if l := wave3GTINStringVal(records[0]["title"]); l != "" { + title = l + " — Wikidata GTIN" + } + } + md := fmt.Sprintf("# %s\n\n%s", escapeDeclMarkdownBrackets(title), formatDeclarativeGFMTable([]string{"Item", "GTIN", "Brand", "Description"}, rows)) + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: md, + Links: links, + Records: records, + }, true +} + +func wave3GTINExtractOpenProductWikidataHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + doc := ParseHTMLDoc(rawHTML, wave3GTINMaxHTMLBytes) + title := wave3GTINExtractTitle(doc, rawHTML) + if title == "" { + return nil + } + var rows [][]string + var gtin string + if doc != nil { + for _, r := range doc.TableRows("table") { + if len(r) >= 2 { + k := SanitizeSchemaPlainField(r[0], 80) + v := SanitizeSchemaPlainField(r[1], 180) + lk := strings.ToLower(k) + if strings.Contains(lk, "gtin") || strings.Contains(lk, "ean") || strings.Contains(lk, "upc") { + if g := wave3GTINValidStrictFormatted(v); g != "" { + if gtin == "" { + gtin = g + } + rows = append(rows, []string{escapeDeclMarkdownBrackets(k), g}) + } + continue + } + if k != "" && v != "" { + rows = append(rows, []string{escapeDeclMarkdownBrackets(k), escapeDeclMarkdownBrackets(v)}) + } + if len(rows) >= 20 { + break + } + } + } + } + desc := wave3GTINExtractMetaDesc(rawHTML) + if len(rows) == 0 && desc == "" { + return nil + } + rec := map[string]any{"title": title} + if gtin != "" { + rec["gtin"] = gtin + } + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if gtin != "" { + blocks = append(blocks, "- **GTIN**: `"+gtin+"`") + } + if len(rows) > 0 { + blocks = append(blocks, "## Attributes\n\n"+formatDeclarativeGFMTable([]string{"Field", "Value"}, rows)) + } else if desc != "" { + blocks = append(blocks, "## Overview\n\n"+escapeDeclMarkdownBlock(desc)) + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: sliceRunesMax(desc, 260), + Markdown: strings.Join(blocks, "\n\n"), + Records: []map[string]any{rec}, + } +} + +// ── #372 ENERGY STAR (`energy_star_json` + `energy_star_html`) ─────────────────────────────────── + +func wave3GTINFormatEnergyStarJSON(parsed any, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool) { + switch t := parsed.(type) { + case []any: + // Socrata /resource/.json array of certified product rows + if len(t) == 0 { + return nil, false + } + var records []map[string]any + var rows [][]string + for _, el := range t { + if len(records) >= wave3GTINMaxRecords { + break + } + m, ok := el.(map[string]any) + if !ok { + continue + } + pdID := wave3GTINPlain(wave3GTINFirstNonEmpty(wave3GTINStringVal(m["pd_id"]), wave3GTINStringVal(m["id"])), 40) + partner := wave3GTINPlain(wave3GTINFirstNonEmpty(wave3GTINStringVal(m["energy_star_partner"]), wave3GTINStringVal(m["partner_name"])), 140) + brand := wave3GTINPlain(m["brand_name"], 120) + modelName := wave3GTINPlain(wave3GTINFirstNonEmpty(wave3GTINStringVal(m["model_name"]), wave3GTINStringVal(m["product_type"])), 140) + modelNum := wave3GTINPlain(m["model_number"], 120) + upc := wave3GTINValidStrictFormatted(wave3GTINStringVal(m["upc"])) + certDate := wave3GTINPlain(m["date_certified"], 32) + energyUse := wave3GTINPlain(wave3GTINFirstNonEmpty( + wave3GTINStringVal(m["annual_energy_use_kwh_yr"]), + wave3GTINStringVal(m["energy_consumption"]), + ), 48) + + if pdID == "" && brand == "" && modelName == "" && modelNum == "" { + continue + } + rec := map[string]any{} + if pdID != "" { + rec["pdId"] = pdID + } + if partner != "" { + rec["partner"] = partner + } + if brand != "" { + rec["brand"] = brand + } + if modelName != "" { + rec["modelName"] = modelName + } + if modelNum != "" { + rec["modelNumber"] = modelNum + } + if upc != "" { + rec["gtin"] = upc + } + if certDate != "" { + rec["dateCertified"] = certDate + } + if energyUse != "" { + rec["annualEnergyUse"] = energyUse + } + records = append(records, rec) + rows = append(rows, []string{ + escapeDeclMarkdownBrackets(wave3GTINFirstNonEmpty(pdID, "-")), + escapeDeclMarkdownBrackets(wave3GTINFirstNonEmpty(brand, "-")), + escapeDeclMarkdownBrackets(wave3GTINFirstNonEmpty(partner, "-")), + escapeDeclMarkdownBrackets(wave3GTINFirstNonEmpty(modelName, modelNum, "-")), + escapeDeclMarkdownBrackets(wave3GTINFirstNonEmpty(modelNum, "-")), + escapeDeclMarkdownBrackets(wave3GTINFirstNonEmpty(certDate, "-")), + }) + } + if len(records) == 0 { + return nil, false + } + title := "ENERGY STAR Certified Products" + if len(records) == 1 { + b := wave3GTINStringVal(records[0]["brand"]) + m := wave3GTINFirstNonEmpty(wave3GTINStringVal(records[0]["modelName"]), wave3GTINStringVal(records[0]["modelNumber"])) + if b != "" || m != "" { + title = strings.TrimSpace("ENERGY STAR: " + b + " " + m) + } + } + md := fmt.Sprintf("# %s\n\n%s", escapeDeclMarkdownBrackets(title), formatDeclarativeGFMTable([]string{"PD ID", "Brand", "Partner", "Model", "Model Number", "Date Certified"}, rows)) + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: md, + Records: records, + }, true + + case map[string]any: + if wave3GTINIsGenericJSONError(t) { + return nil, false + } + // Socrata /api/catalog/v1 + if resArr, okCat := t["results"].([]any); okCat { + if len(resArr) == 0 { + return nil, false + } + var records []map[string]any + var rows [][]string + var links []string + seenLinks := make(map[string]bool) + for _, el := range resArr { + if len(records) >= wave3GTINMaxRecords { + break + } + entry, okE := el.(map[string]any) + if !okE { + continue + } + resMap := wave3GTINNestedMap(entry, "resource") + if resMap == nil { + continue + } + dsID := wave3GTINPlain(resMap["id"], 32) + dsName := wave3GTINPlain(resMap["name"], 180) + dsDesc := wave3GTINPlain(resMap["description"], 260) + updated := wave3GTINPlain(resMap["updatedAt"], 32) + perma := wave3GTINStringVal(entry["permalink"]) + wave3GTINAddLink(&links, seenLinks, perma, origURL) + if dsName == "" && dsID == "" { + continue + } + records = append(records, map[string]any{ + "id": dsID, + "name": dsName, + "description": dsDesc, + "updatedAt": updated, + "url": perma, + }) + rows = append(rows, []string{ + escapeDeclMarkdownBrackets(wave3GTINFirstNonEmpty(dsID, "-")), + escapeDeclMarkdownBrackets(wave3GTINFirstNonEmpty(dsName, "-")), + escapeDeclMarkdownBrackets(wave3GTINFirstNonEmpty(updated, "-")), + }) + } + if len(records) == 0 { + return nil, false + } + title := "ENERGY STAR Open Data Catalog" + md := fmt.Sprintf("# %s\n\n%s", escapeDeclMarkdownBrackets(title), formatDeclarativeGFMTable([]string{"Dataset ID", "Name", "Updated"}, rows)) + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: md, + Links: links, + Records: records, + }, true + } + + // Socrata /api/views/<4x4>.json metadata + viewID := wave3GTINPlain(wave3GTINFirstNonEmpty(wave3GTINStringVal(t["id"]), params["viewId"]), 32) + name := wave3GTINPlain(t["name"], 220) + if viewID == "" || name == "" { + return nil, false + } + attribution := wave3GTINPlain(t["attribution"], 160) + category := wave3GTINPlain(t["category"], 120) + desc := wave3GTINPlain(t["description"], 1200) + sodaURL := fmt.Sprintf("https://data.energystar.gov/resource/%s.json?$limit=50", viewID) + csvURL := fmt.Sprintf("https://data.energystar.gov/api/views/%s/rows.csv?accessType=DOWNLOAD", viewID) + + var colRows [][]string + if cols, okCols := t["columns"].([]any); okCols { + for _, cAny := range cols { + if len(colRows) >= 40 { + break + } + cm, okC := cAny.(map[string]any) + if !okC { + continue + } + fn := wave3GTINPlain(cm["fieldName"], 80) + if fn == "" || strings.HasPrefix(fn, ":@") { + continue + } + colRows = append(colRows, []string{ + "`" + sanitizeDeclInlineCodeVal(fn) + "`", + escapeDeclMarkdownBrackets(wave3GTINFirstNonEmpty(wave3GTINPlain(cm["name"], 100), fn)), + escapeDeclMarkdownBrackets(wave3GTINFirstNonEmpty(wave3GTINPlain(cm["dataTypeName"], 48), "-")), + }) + } + } + + var bullets []string + bullets = append(bullets, "- **Dataset ID**: `"+sanitizeDeclInlineCodeVal(viewID)+"`") + bullets = append(bullets, "- **SODA JSON API**: `"+sanitizeDeclInlineCodeVal(sodaURL)+"`") + if attribution != "" { + bullets = append(bullets, "- **Attribution**: "+escapeDeclMarkdownBrackets(attribution)) + } + if category != "" { + bullets = append(bullets, "- **Category**: "+escapeDeclMarkdownBrackets(category)) + } + + blocks := []string{"# " + escapeDeclMarkdownBrackets(name), strings.Join(bullets, "\n")} + if desc != "" { + blocks = append(blocks, "## Description\n\n"+escapeDeclMarkdownBlock(desc)) + } + if len(colRows) > 0 { + blocks = append(blocks, "## Schema\n\n"+formatDeclarativeGFMTable([]string{"Field Name", "Label", "Type"}, colRows)) + } + + return &DeclarativeFormattedDoc{ + Title: name, + Description: sliceRunesMax(desc, 260), + Author: attribution, + Markdown: strings.Join(blocks, "\n\n"), + Links: []string{sodaURL, csvURL}, + Records: []map[string]any{{ + "id": viewID, + "name": name, + "category": category, + "attribution": attribution, + }}, + }, true + default: + return nil, false + } +} + +func wave3GTINExtractEnergyStarHTML(rawHTML, probeLower, baseURL, extractorID string) *DeclarativePostFetchResult { + doc := ParseHTMLDoc(rawHTML, wave3GTINMaxHTMLBytes) + title := wave3GTINExtractTitle(doc, rawHTML) + if title == "" { + return nil + } + desc := wave3GTINExtractMetaDesc(rawHTML) + + var kvRows [][]string + if doc != nil { + dl := doc.DLMap("dl") + dlKeys := make([]string, 0, len(dl)) + for k := range dl { + dlKeys = append(dlKeys, k) + } + sort.Strings(dlKeys) + for _, k := range dlKeys { + kvRows = append(kvRows, []string{ + escapeDeclMarkdownBrackets(SanitizeSchemaPlainField(k, 80)), + escapeDeclMarkdownBrackets(SanitizeSchemaPlainField(dl[k], 180)), + }) + if len(kvRows) >= 20 { + break + } + } + for _, r := range doc.TableRows("table") { + if len(r) >= 2 { + kvRows = append(kvRows, []string{ + escapeDeclMarkdownBrackets(SanitizeSchemaPlainField(r[0], 80)), + escapeDeclMarkdownBrackets(SanitizeSchemaPlainField(r[1], 180)), + }) + if len(kvRows) >= 25 { + break + } + } + } + } + var paras []string + if doc != nil { + for _, pNode := range doc.Select("main p, article p", 8) { + pt := SanitizeSchemaPlainField(wave3GTINCleanText(pNode.Text()), 500) + if len(pt) >= 24 { + paras = append(paras, pt) + } + } + } + if len(kvRows) == 0 && len(paras) == 0 { + return nil + } + + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if len(kvRows) > 0 { + blocks = append(blocks, "## Certified Specifications\n\n"+formatDeclarativeGFMTable([]string{"Attribute", "Value"}, kvRows)) + } + if len(paras) > 0 { + blocks = append(blocks, "## Summary\n\n"+escapeDeclPlainTextPreservingNewlines(strings.Join(paras, "\n\n"))) + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: wave3GTINFirstNonEmpty(desc, sliceRunesMax(strings.Join(paras, " "), 260)), + Markdown: strings.Join(blocks, "\n\n"), + Records: []map[string]any{{"title": title}}, + } +} + +// ── #373 FCC Test Report & FCC ID (`fcc_test_report_json`, `fcc_test_report_html`, `fcc_id_html`) ─ + +func wave3GTINFormatFCCTestReportJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + var rawItems []any + switch t := parsed.(type) { + case map[string]any: + if wave3GTINIsGenericJSONError(t) { + return nil, false + } + for _, k := range []string{"results", "grants", "applications", "exhibits", "items"} { + if arr, ok := t[k].([]any); ok && len(arr) > 0 { + rawItems = arr + break + } + } + if len(rawItems) == 0 { + rawItems = []any{t} + } + case []any: + if len(t) == 0 { + return nil, false + } + rawItems = t + default: + return nil, false + } + + var records []map[string]any + var rows [][]string + var links []string + seenLinks := make(map[string]bool) + + for _, item := range rawItems { + if len(records) >= wave3GTINMaxRecords { + break + } + m, ok := item.(map[string]any) + if !ok { + continue + } + fccID := wave3GTINPlain(wave3GTINFirstNonEmpty(wave3GTINStringVal(m["fcc_id"]), wave3GTINStringVal(m["fccId"])), 64) + applicant := wave3GTINPlain(wave3GTINFirstNonEmpty(wave3GTINStringVal(m["applicant"]), wave3GTINStringVal(m["grantee_name"]), wave3GTINStringVal(m["granteeName"])), 160) + eqClass := wave3GTINPlain(wave3GTINFirstNonEmpty(wave3GTINStringVal(m["equipment_class"]), wave3GTINStringVal(m["equipmentClass"])), 64) + grantDate := wave3GTINPlain(wave3GTINFirstNonEmpty(wave3GTINStringVal(m["grant_date"]), wave3GTINStringVal(m["grantDate"])), 32) + freq := wave3GTINPlain(wave3GTINFirstNonEmpty(wave3GTINStringVal(m["frequency_range"]), wave3GTINStringVal(m["frequencyRange"])), 80) + if fccID == "" && applicant == "" { + continue + } + rec := map[string]any{} + if fccID != "" { + rec["fccId"] = fccID + } + if applicant != "" { + rec["applicant"] = applicant + } + if eqClass != "" { + rec["equipmentClass"] = eqClass + } + if grantDate != "" { + rec["grantDate"] = grantDate + } + if freq != "" { + rec["frequencyRange"] = freq + } + if exArr, okEx := m["exhibits"].([]any); okEx { + for _, exAny := range exArr { + if exM, okM := exAny.(map[string]any); okM { + wave3GTINAddLink(&links, seenLinks, wave3GTINStringVal(exM["url"]), origURL) + } + } + } + records = append(records, rec) + rows = append(rows, []string{ + escapeDeclMarkdownBrackets(wave3GTINFirstNonEmpty(fccID, "-")), + escapeDeclMarkdownBrackets(wave3GTINFirstNonEmpty(applicant, "-")), + escapeDeclMarkdownBrackets(wave3GTINFirstNonEmpty(eqClass, "-")), + escapeDeclMarkdownBrackets(wave3GTINFirstNonEmpty(freq, "-")), + escapeDeclMarkdownBrackets(wave3GTINFirstNonEmpty(grantDate, "-")), + }) + } + if len(records) == 0 { + return nil, false + } + + title := "FCC OET Equipment Authorization" + if f := wave3GTINStringVal(records[0]["fccId"]); f != "" { + title = "FCC OET Equipment Authorization: " + f + } + md := fmt.Sprintf("# %s\n\n%s", escapeDeclMarkdownBrackets(title), formatDeclarativeGFMTable([]string{"FCC ID", "Applicant", "Class", "Frequency", "Grant Date"}, rows)) + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: md, + Links: links, + Records: records, + }, true +} + +func wave3GTINIsFCCExhibitLink(href, label string) bool { + lh := strings.ToLower(href) + ll := strings.ToLower(label) + if strings.Contains(lh, "/viewexhibitreport.cfm") || strings.Contains(lh, "subscribe.php") || strings.Contains(lh, "/frequency") { + return false + } + if strings.HasSuffix(lh, ".pdf") || strings.Contains(lh, ".pdf?") { + return true + } + for _, kw := range []string{"test-report", "test report", "rf-exposure", "rf exposure", "user-manual", "user manual", "internal-photos", "external-photos", "block-diagram", "schematics", "exhibit", "eas/reports/getapplication"} { + if strings.Contains(lh, kw) || strings.Contains(ll, kw) { + return true + } + } + return false +} + +func wave3GTINExtractFCCTestReportHTML(rawHTML, probeLower, baseURL, extractorID string) *DeclarativePostFetchResult { + doc := ParseHTMLDoc(rawHTML, wave3GTINMaxHTMLBytes) + title := wave3GTINExtractTitle(doc, rawHTML) + if title == "" { + return nil + } + + var tableRows [][]string + if doc != nil { + for _, r := range doc.TableRows("table") { + if len(r) >= 2 { + k := SanitizeSchemaPlainField(r[0], 90) + v := SanitizeSchemaPlainField(r[1], 180) + if k != "" && v != "" { + tableRows = append(tableRows, []string{escapeDeclMarkdownBrackets(k), escapeDeclMarkdownBrackets(v)}) + } + if len(tableRows) >= 25 { + break + } + } + } + } + + var exhibitRows [][]string + var links []string + seenLinks := make(map[string]bool) + for _, m := range wave3GTINRxHref.FindAllStringSubmatch(rawHTML, 250) { + if len(m) < 3 { + continue + } + rawHref := strings.TrimSpace(m[1]) + label := SanitizeSchemaPlainField(wave3GTINStripTags(m[2]), 140) + if !wave3GTINIsFCCExhibitLink(rawHref, label) { + continue + } + abs := SanitizeSchemaHTTPSURL(rawHref, baseURL) + if abs == "" { + continue + } + if !seenLinks[abs] && len(links) < wave3GTINMaxLinks { + seenLinks[abs] = true + links = append(links, abs) + exhibitRows = append(exhibitRows, []string{escapeDeclMarkdownBrackets(wave3GTINFirstNonEmpty(label, "Exhibit")), abs}) + } + } + + // Reject bare empty search form shells (e.g. GenericSearch.cfm without grant/exhibit data) + if len(tableRows) == 0 && len(exhibitRows) == 0 { + return nil + } + + fccID := wave3GTINExtractQueryParam(baseURL, "fcc_id", "fccId") + if fccID == "" { + if m := wave3GTINRxFCCIDHeading.FindStringSubmatch(title); len(m) >= 2 { + fccID = m[1] + } + } + + rec := map[string]any{"title": title} + if fccID != "" { + rec["fccId"] = fccID + } + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if fccID != "" { + blocks = append(blocks, "- **FCC ID**: `"+sanitizeDeclInlineCodeVal(fccID)+"`") + } + if len(tableRows) > 0 { + blocks = append(blocks, "## Equipment Authorization Details\n\n"+formatDeclarativeGFMTable([]string{"Field", "Value"}, tableRows)) + } + if len(exhibitRows) > 0 { + blocks = append(blocks, "## Test Reports & Exhibits\n\n"+formatDeclarativeGFMTable([]string{"Exhibit", "URL"}, exhibitRows)) + } + + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + ReplaceLinks: true, + Records: []map[string]any{rec}, + } +} + +func wave3GTINExtractFCCIDHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + doc := ParseHTMLDoc(rawHTML, wave3GTINMaxHTMLBytes) + title := wave3GTINExtractTitle(doc, rawHTML) + if title == "" { + return nil + } + + fccID := "" + if u, err := url.Parse(baseURL); err == nil { + segs := splitNonEmptyEscapedSegments(u.EscapedPath()) + if len(segs) > 0 { + cand, errUnesc := url.PathUnescape(segs[0]) + if errUnesc == nil && cand != "" && !strings.EqualFold(cand, "ViewExhibitReport.cfm") { + fccID = SanitizeSchemaPlainField(cand, 64) + } + } + } + if fccID == "" { + if m := wave3GTINRxFCCIDHeading.FindStringSubmatch(title); len(m) >= 2 { + fccID = m[1] + } + } + + var paras []string + var tableRows [][]string + if doc != nil { + for _, pNode := range doc.Select("main p, article p", 6) { + pt := SanitizeSchemaPlainField(wave3GTINCleanText(pNode.Text()), 400) + if len(pt) >= 12 { + paras = append(paras, pt) + } + } + for _, r := range doc.TableRows("table") { + if len(r) >= 2 { + k := SanitizeSchemaPlainField(r[0], 90) + v := SanitizeSchemaPlainField(r[1], 180) + if k != "" && v != "" { + tableRows = append(tableRows, []string{escapeDeclMarkdownBrackets(k), escapeDeclMarkdownBrackets(v)}) + } + if len(tableRows) >= 25 { + break + } + } + } + } + + var exhibitRows [][]string + var links []string + seenLinks := make(map[string]bool) + for _, m := range wave3GTINRxHref.FindAllStringSubmatch(rawHTML, 300) { + if len(m) < 3 { + continue + } + rawHref := strings.TrimSpace(m[1]) + label := SanitizeSchemaPlainField(wave3GTINStripTags(m[2]), 140) + if !wave3GTINIsFCCExhibitLink(rawHref, label) { + continue + } + abs := SanitizeSchemaHTTPSURL(rawHref, baseURL) + if abs == "" { + continue + } + if !seenLinks[abs] && len(links) < wave3GTINMaxLinks { + seenLinks[abs] = true + links = append(links, abs) + exhibitRows = append(exhibitRows, []string{escapeDeclMarkdownBrackets(wave3GTINFirstNonEmpty(label, "Exhibit")), abs}) + } + } + + rec := map[string]any{"title": title} + if fccID != "" { + rec["fccId"] = fccID + } + + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if fccID != "" { + blocks = append(blocks, "- **FCC ID**: `"+sanitizeDeclInlineCodeVal(fccID)+"`") + } + desc := "" + if len(paras) > 0 { + desc = sliceRunesMax(paras[0], 260) + blocks = append(blocks, escapeDeclPlainTextPreservingNewlines(strings.Join(paras, "\n\n"))) + } else { + desc = wave3GTINExtractMetaDesc(rawHTML) + if desc != "" { + blocks = append(blocks, escapeDeclMarkdownBlock(desc)) + } + } + if len(tableRows) > 0 { + blocks = append(blocks, "## Technical Specifications\n\n"+formatDeclarativeGFMTable([]string{"Parameter", "Value"}, tableRows)) + } + if len(exhibitRows) > 0 { + blocks = append(blocks, "## Exhibit & Test Report Links\n\n"+formatDeclarativeGFMTable([]string{"Document", "URL"}, exhibitRows)) + } + + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + ReplaceLinks: true, + Records: []map[string]any{rec}, + } +} + +// ── #374 Prop 65 Warnings (`prop65_warnings_html`) ─────────────────────────────────────────────── + +func wave3GTINExtractProp65WarningsHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + doc := ParseHTMLDoc(rawHTML, wave3GTINMaxHTMLBytes) + title := wave3GTINExtractTitle(doc, rawHTML) + if title == "" { + return nil + } + desc := wave3GTINExtractMetaDesc(rawHTML) + + var tableHeaders []string + var tableRows [][]string + var dlRows [][]string + var paras []string + + if doc != nil { + dl := doc.DLMap("dl") + dlKeys := make([]string, 0, len(dl)) + for k := range dl { + dlKeys = append(dlKeys, k) + } + sort.Strings(dlKeys) + for _, k := range dlKeys { + dlRows = append(dlRows, []string{SanitizeSchemaPlainField(k, 80), SanitizeSchemaPlainField(dl[k], 200)}) + if len(dlRows) >= 15 { + break + } + } + rawTable := doc.TableRows("table") + for idx, r := range rawTable { + if idx == 0 && len(r) >= 2 { + for _, h := range r { + tableHeaders = append(tableHeaders, wave3GTINFirstNonEmpty(SanitizeSchemaPlainField(h, 60), "Column")) + } + continue + } + if len(r) >= 2 { + var cleanRow []string + for _, c := range r { + cleanRow = append(cleanRow, wave3GTINFirstNonEmpty(SanitizeSchemaPlainField(c, 160), "-")) + } + tableRows = append(tableRows, cleanRow) + if len(tableRows) >= wave3GTINMaxRecords { + break + } + } + } + for _, pNode := range doc.Select("main p, article p, .field--name-body p", 10) { + pt := SanitizeSchemaPlainField(wave3GTINCleanText(pNode.Text()), 600) + if len(pt) >= 24 { + paras = append(paras, pt) + } + } + } + + if len(tableRows) == 0 && len(dlRows) == 0 && len(paras) == 0 { + return nil + } + + fullText := strings.Join(paras, " ") + cas := "" + if m := wave3GTINRxCASNumber.FindStringSubmatch(fullText + " " + title); len(m) >= 2 { + cas = m[1] + } + if cas == "" { + for _, dr := range dlRows { + if strings.Contains(strings.ToLower(dr[0]), "cas") { + if m := wave3GTINRxCASNumber.FindStringSubmatch(dr[1]); len(m) >= 2 { + cas = m[1] + break + } + } + } + } + + var records []map[string]any + if len(tableRows) > 0 && len(tableHeaders) >= 2 { + for _, row := range tableRows { + rec := map[string]any{} + for ci, val := range row { + if ci >= len(tableHeaders) { + break + } + hk := strings.ToLower(tableHeaders[ci]) + switch { + case strings.Contains(hk, "chemical"): + rec["chemical"] = val + case strings.Contains(hk, "cas"): + rec["casNumber"] = val + case strings.Contains(hk, "toxicity") || strings.Contains(hk, "endpoint"): + rec["toxicity"] = val + case strings.Contains(hk, "date"): + rec["dateListed"] = val + case strings.Contains(hk, "mechanism"): + rec["listingMechanism"] = val + } + } + if len(rec) > 0 { + records = append(records, rec) + } + } + } else { + rec := map[string]any{"title": title} + if cas != "" { + rec["casNumber"] = cas + } + for _, dr := range dlRows { + lk := strings.ToLower(dr[0]) + if strings.Contains(lk, "toxicity") { + rec["toxicity"] = dr[1] + } else if strings.Contains(lk, "date") { + rec["dateListed"] = dr[1] + } + } + records = append(records, rec) + } + + var bullets []string + if cas != "" { + bullets = append(bullets, "- **CAS Number**: `"+cas+"`") + } + for _, dr := range dlRows { + bullets = append(bullets, fmt.Sprintf("- **%s**: %s", escapeDeclMarkdownBrackets(dr[0]), escapeDeclMarkdownBrackets(dr[1]))) + if len(bullets) >= 8 { + break + } + } + + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + if len(tableRows) > 0 && len(tableHeaders) >= 2 { + escapedHeaders := make([]string, len(tableHeaders)) + for i, h := range tableHeaders { + escapedHeaders[i] = escapeDeclMarkdownBrackets(h) + } + // Pad or trim rows to match header count + normRows := make([][]string, 0, len(tableRows)) + for _, r := range tableRows { + nr := make([]string, len(tableHeaders)) + for i := 0; i < len(tableHeaders); i++ { + if i < len(r) { + nr[i] = escapeDeclMarkdownBrackets(r[i]) + } else { + nr[i] = "-" + } + } + normRows = append(normRows, nr) + } + blocks = append(blocks, "## Proposition 65 Chemical Data\n\n"+formatDeclarativeGFMTable(escapedHeaders, normRows)) + } + if len(paras) > 0 { + blocks = append(blocks, "## Summary\n\n"+escapeDeclPlainTextPreservingNewlines(strings.Join(paras, "\n\n"))) + } else if desc != "" { + blocks = append(blocks, "## Summary\n\n"+escapeDeclMarkdownBlock(desc)) + } + + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: wave3GTINFirstNonEmpty(desc, sliceRunesMax(fullText, 260)), + Markdown: strings.Join(blocks, "\n\n"), + Records: records, + } +} diff --git a/internal/extract/wave3_gtin_identity_test.go b/internal/extract/wave3_gtin_identity_test.go new file mode 100644 index 0000000..fdf7efa --- /dev/null +++ b/internal/extract/wave3_gtin_identity_test.go @@ -0,0 +1,517 @@ +package extract + +import ( + "encoding/json" + "net/url" + "os" + "path/filepath" + "regexp" + "strings" + "testing" +) + +func wave3GTINResolveManifest(t *testing.T, m *DeclarativeAdapterManifest, rawURL string) (*DeclarativeTwinMatch, bool) { + t.Helper() + u, err := url.Parse(rawURL) + if err != nil { + t.Fatalf("url.Parse(%q): %v", rawURL, err) + } + host := strings.TrimSuffix(strings.ToLower(u.Hostname()), ".") + rawParts := splitNonEmptyEscapedSegments(u.EscapedPath()) + return resolveManifestTwinOnParsedURL(m, u, host, rawParts, DeclarativeResolveOptions{}) +} + +func TestWave3GTINManifestsAndRouting(t *testing.T) { + catQIDs := []string{ + "gs1-us-datahub", + "open-icecat", + "upcitemdb-barcodelookup", + "open-product-wikidata-gtin", + "energy-star", + "fcc-test-report", + "prop65-warnings", + } + + expectedCats := map[string]string{ + "gs1-us-datahub": "commerce-social", + "open-icecat": "commerce-social", + "upcitemdb-barcodelookup": "commerce-social", + "open-product-wikidata-gtin": "commerce-social", + "energy-star": "public-records", + "fcc-test-report": "public-records", + "prop65-warnings": "public-records", + } + + byID := make(map[string]*DeclarativeAdapterManifest) + claimedDomains := make(map[string]string) + + for _, id := range catQIDs { + raw, err := os.ReadFile(filepath.Join("manifests", id+".yaml")) + if err != nil { + t.Fatalf("read %s.yaml: %v", id, err) + } + m, err := ParseDeclarativeYAMLManifest(raw) + if err != nil { + t.Fatalf("ParseDeclarativeYAMLManifest(%s.yaml): %v", id, err) + } + if m.ID != id { + t.Fatalf("%s.yaml has mismatched id=%q", id, m.ID) + } + if m.Category != expectedCats[id] { + t.Fatalf("%s.yaml category mismatch: got %q want %q", id, m.Category, expectedCats[id]) + } + if m.AuthMode == "detect-only" || m.DetectOnly != nil { + t.Fatalf("%s.yaml uses retired detect-only", id) + } + for _, d := range m.Domains { + ld := strings.ToLower(strings.TrimSpace(d)) + if prev, exists := claimedDomains[ld]; exists { + t.Fatalf("duplicate domain %q across %s and %s", ld, prev, id) + } + claimedDomains[ld] = id + } + for _, hr := range m.HTMLRoutes { + for _, b := range hr.Bullets { + if strings.ContainsAny(b.Label, "{}") { + t.Fatalf("%s.yaml bullet label contains {}: %q", id, b.Label) + } + } + } + byID[id] = m + } + + // Disjointness from existing related manifests (wikidata-openlibrary, fcc-id, fcc-uls, fcc-ecfs, opendatasoft, socrata, openfoodfacts) + for _, existingID := range []string{"wikidata-openlibrary", "fcc-id", "fcc-uls", "fcc-ecfs", "opendatasoft", "socrata", "openfoodfacts"} { + raw, err := os.ReadFile(filepath.Join("manifests", existingID+".yaml")) + if err != nil { + t.Fatalf("read %s.yaml: %v", existingID, err) + } + em, err := ParseDeclarativeYAMLManifest(raw) + if err != nil { + t.Fatalf("ParseDeclarativeYAMLManifest(%s.yaml): %v", existingID, err) + } + for _, d := range em.Domains { + ld := strings.ToLower(strings.TrimSpace(d)) + if catOwner, overlap := claimedDomains[ld]; overlap { + t.Fatalf("Cat Q %s overlaps %s domain %q", catOwner, existingID, ld) + } + } + } + for _, forbidden := range []string{"wikidata.org", "www.wikidata.org", "pod.opendatasoft.com", "fccid.io", "www.fccid.io", "opendata.fcc.gov"} { + if owner, exists := claimedDomains[forbidden]; exists { + t.Fatalf("Cat Q %s must NOT claim colliding/defunct domain %q", owner, forbidden) + } + } + + // #368 gs1-us-datahub + gs1 := byID["gs1-us-datahub"] + if tmGS1, okGS1 := wave3GTINResolveManifest(t, gs1, "https://api.gs1us.org/gtins/0012000161155"); !okGS1 || tmGS1.route.Twin.AuthMode != "key" || tmGS1.route.Extract.JSONMode != "gs1_us_json" { + t.Fatalf("gs1-us-datahub route failed: ok=%v tm=%+v", okGS1, tmGS1) + } + + // #369 open-icecat: strict GTIN lengths (8, 12, 13, 14) accepted; 9/10/11-digit, ASIN, SKU rejected + ice := byID["open-icecat"] + for _, validGTIN := range []string{"12345678", "012000161155", "8710103792772", "00012000161155"} { + u := "https://live.icecat.biz/api?shopname=openicecat-live&lang=en>IN=" + validGTIN + if tm, ok := wave3GTINResolveManifest(t, ice, u); !ok || tm.route.Extract.JSONMode != "open_icecat_json" || tm.route.Twin.AuthMode != "pub" { + t.Fatalf("open-icecat valid GTIN %q failed: ok=%v", validGTIN, ok) + } + } + for _, invalidGTIN := range []string{"B08N5WRWNW", "1234567", "123456789", "1234567890", "12345678901", "SKU-12345678", "0xdeadbeef12"} { + u := "https://live.icecat.biz/api?shopname=openicecat-live&lang=en>IN=" + invalidGTIN + if tm, ok := wave3GTINResolveManifest(t, ice, u); ok || tm != nil { + t.Fatalf("open-icecat must reject invalid GTIN %q, got %+v", invalidGTIN, tm) + } + } + + // #370 upcitemdb-barcodelookup: trial=pub, v1=key, barcodelookup=key, strict GTIN + upc := byID["upcitemdb-barcodelookup"] + if tmTrial, okTrial := wave3GTINResolveManifest(t, upc, "https://api.upcitemdb.com/prod/trial/lookup?upc=012000161155"); !okTrial || tmTrial.route.Twin.AuthMode != "pub" || tmTrial.route.Extract.JSONMode != "upcitemdb_json" { + t.Fatalf("upcitemdb trial failed: ok=%v tm=%+v", okTrial, tmTrial) + } + if tmV1, okV1 := wave3GTINResolveManifest(t, upc, "https://api.upcitemdb.com/prod/v1/lookup?upc=012000161155"); !okV1 || tmV1.route.Twin.AuthMode != "key" || tmV1.route.Extract.JSONMode != "upcitemdb_json" { + t.Fatalf("upcitemdb v1 failed: ok=%v tm=%+v", okV1, tmV1) + } + if tmBL, okBL := wave3GTINResolveManifest(t, upc, "https://api.barcodelookup.com/v3/products?barcode=012000161155"); !okBL || tmBL.route.Twin.AuthMode != "key" || tmBL.route.Extract.JSONMode != "barcodelookup_json" { + t.Fatalf("barcodelookup v3 failed: ok=%v tm=%+v", okBL, tmBL) + } + if tmBad, okBad := wave3GTINResolveManifest(t, upc, "https://api.upcitemdb.com/prod/trial/lookup?upc=0140328726"); okBad || tmBad != nil { + t.Fatalf("upcitemdb must reject 10-digit code: %+v", tmBad) + } + + // #371 open-product-wikidata-gtin + opw := byID["open-product-wikidata-gtin"] + if tmOG, okOG := wave3GTINResolveManifest(t, opw, "https://opengtindb.org/?ean=4006381333931&cmd=query&queryid=400000000"); !okOG || tmOG.route.Extract.TextMode != "opengtindb_text" { + t.Fatalf("opengtindb route failed: ok=%v tm=%+v", okOG, tmOG) + } + if tmWD, okWD := wave3GTINResolveManifest(t, opw, "https://query.wikidata.org/sparql?query=SELECT"); !okWD || tmWD.route.Extract.JSONMode != "wikidata_gtin_sparql_json" { + t.Fatalf("query.wikidata.org/sparql route failed: ok=%v tm=%+v", okWD, tmWD) + } + + // #372 energy-star + es := byID["energy-star"] + if tmES1, okES1 := wave3GTINResolveManifest(t, es, "https://data.energystar.gov/resource/7p2p-wkbf.json?$limit=2"); !okES1 || tmES1.route.Extract.JSONMode != "energy_star_json" { + t.Fatalf("energy-star resource route failed: ok=%v tm=%+v", okES1, tmES1) + } + if tmES2, okES2 := wave3GTINResolveManifest(t, es, "https://data.energystar.gov/d/7p2p-wkbf"); !okES2 || tmES2.FetchURL != "https://data.energystar.gov/api/views/7p2p-wkbf.json" { + t.Fatalf("energy-star /d/<4x4> route failed: ok=%v tm=%+v", okES2, tmES2) + } + + // fcc-id enrichment manifest check + fccRaw, err := os.ReadFile(filepath.Join("manifests", "fcc-id.yaml")) + if err != nil { + t.Fatalf("read fcc-id.yaml: %v", err) + } + fccM, err := ParseDeclarativeYAMLManifest(fccRaw) + if err != nil { + t.Fatalf("ParseDeclarativeYAMLManifest(fcc-id.yaml): %v", err) + } + if len(fccM.HTMLRoutes) != 1 || fccM.HTMLRoutes[0].Mode != "fcc_id_html" { + t.Fatalf("fcc-id.yaml must upgrade htmlRoutes[0].mode to fcc_id_html, got %+v", fccM.HTMLRoutes) + } +} + +func TestStrictGTINValidationAndRejections(t *testing.T) { + validCases := []string{ + "40112002", // GTIN-8 + "012000161155", // GTIN-12 (UPC-A) + "4006381333931", // GTIN-13 (EAN-13) + "00012000161155", // GTIN-14 + } + for _, g := range validCases { + if got := wave3GTINValidStrict(g); got != g { + t.Fatalf("expected valid GTIN %q, got %q", g, got) + } + } + + invalidCases := []string{ + "", + "B08N5WRWNW", // ASIN + "SKU-12345678", // SKU + "0xdeadbeef1234", // hex + "1234567", // 7 digits + "123456789", // 9 digits + "0140328726", // 10 digits / ISBN-10 + "12345678901", // 11 digits + "123456789012345", + "0-14-032872-X", // ISBN-10 with X + } + for _, bad := range invalidCases { + if got := wave3GTINValidStrict(bad); got != "" { + t.Fatalf("expected strict GTIN rejection for %q, got %q", bad, got) + } + if got := wave3GTINValidStrictFormatted(bad); got != "" { + t.Fatalf("expected formatted strict GTIN rejection for %q, got %q", bad, got) + } + } + if got := wave3GTINValidStrictFormatted("0 12000 16115 5"); got != "012000161155" { + t.Fatalf("expected formatted UPC-A '0 12000 16115 5' -> '012000161155', got %q", got) + } + if got := wave3GTINValidStrictFormatted("0-14-032872-6"); got != "" { + t.Fatalf("expected 10-digit hyphenated ISBN-10 rejected, got %q", got) + } + + // Ensure invalid GTINs inside JSON payloads are omitted from records & markdown + gs1Bad := []byte(`{"gtin":"B08N5WRWNW","companyName":"Acme Corp","gln":"0012000000008"}`) + gs1Doc, ok := FormatWave3GTINIdentityJSONDoc("gs1_us_json", gs1Bad, nil, "https://api.gs1us.org/gtins/1") + if !ok || gs1Doc == nil { + t.Fatal("expected gs1_us_json to format valid companyName/gln while stripping invalid GTIN") + } + if _, hasGTIN := gs1Doc.Records[0]["gtin"]; hasGTIN || strings.Contains(gs1Doc.Markdown, "B08N5WRWNW") { + t.Fatalf("gs1_us_json must omit invalid GTIN B08N5WRWNW: %+v", gs1Doc) + } +} + +func TestWave3GTINIdentityJSONTextAndHTMLModes(t *testing.T) { + registerWave3GTINIdentityHTMLModes() + RegisterWave3GTINIdentityHTMLModes() + + expectedHTMLModes := []string{ + "gs1_us_html", + "open_icecat_html", + "upcitemdb_barcodelookup_html", + "open_product_wikidata_html", + "energy_star_html", + "fcc_test_report_html", + "fcc_id_html", + "prop65_warnings_html", + } + for _, hm := range expectedHTMLModes { + if getExternalHTMLModeLazy(hm) == nil { + t.Fatalf("RegisterExternalHTMLModeLazy missing %q", hm) + } + if !IsWave3GTINIdentityHTMLMode(hm) { + t.Fatalf("IsWave3GTINIdentityHTMLMode(%q) = false", hm) + } + } + + // #369 Open Icecat error envelopes rejected + for _, errJSON := range []string{ + `{"StatusCode":14,"Code":404,"Error":"Brand is restricted"}`, + `{"StatusCode":9,"Code":403,"Error":"app_key is required"}`, + `{"StatusCode":16,"Code":400,"Message":"GTIN not found"}`, + } { + if _, ok := FormatWave3GTINIdentityJSONMode("open_icecat_json", []byte(errJSON), nil, "https://live.icecat.biz/api?GTIN=0194252021453"); ok { + t.Fatalf("open_icecat_json must reject error envelope %s", errJSON) + } + } + + // #370 Barcode Lookup v3 JSON + blJSON := []byte(`{"products":[{"barcode_number":"012000161155","barcode_formats":"UPC-A 012000161155, EAN-13 0012000161155","title":"LIFEWTR 700mL","brand":"LIFEWTR","mpn":"LW-700","category":"Beverages","stores":[{"name":"Example Store","price":"1.99","currency":"USD","link":"https://example.com/lifewtr"}]}]}`) + blDoc, okBL := FormatWave3GTINIdentityJSONDoc("barcodelookup_json", blJSON, nil, "https://api.barcodelookup.com/v3/products?barcode=012000161155") + if !okBL || blDoc == nil || blDoc.Records[0]["gtin"] != "012000161155" || !strings.Contains(blDoc.Markdown, "Example Store") { + t.Fatalf("barcodelookup_json failed: ok=%v doc=%+v", okBL, blDoc) + } + + // #370 UPCitemdb HTML table parsing + upcHTML := `UPC 012000161155 - LIFEWTR | UPCitemdb

LIFEWTR Purified Water

UPC-A:0 12000 16115 5
Brand:LIFEWTR
Model:700mL
` + upcRes := Wave3GTINIdentityRunHTML("upcitemdb_barcodelookup_html", upcHTML, "https://www.upcitemdb.com/upc/012000161155", "upcitemdb-barcodelookup") + if upcRes == nil || upcRes.Records[0]["gtin"] != "012000161155" || !strings.Contains(upcRes.Markdown, "012000161155") { + t.Fatalf("upcitemdb_barcodelookup_html failed: %+v", upcRes) + } + + // #371 Wikidata SPARQL JSON + OpenGTINdb error=1 rejection + sparqlJSON := []byte(`{"results":{"bindings":[{"item":{"type":"uri","value":"https://www.wikidata.org/entity/Q2813"},"itemLabel":{"type":"literal","value":"Coca-Cola"},"gtin":{"type":"literal","value":"54491472"},"brandLabel":{"type":"literal","value":"The Coca-Cola Company"}}]}}`) + spDoc, okSP := FormatWave3GTINIdentityJSONDoc("wikidata_gtin_sparql_json", sparqlJSON, nil, "https://query.wikidata.org/sparql") + if !okSP || spDoc == nil || spDoc.Records[0]["gtin"] != "54491472" { + t.Fatalf("wikidata_gtin_sparql_json failed: ok=%v doc=%+v", okSP, spDoc) + } + if _, okEmptySP := FormatWave3GTINIdentityJSONMode("wikidata_gtin_sparql_json", []byte(`{"results":{"bindings":[]}}`), nil, "https://query.wikidata.org/sparql"); okEmptySP { + t.Fatal("wikidata_gtin_sparql_json must reject empty bindings") + } + if _, okOGErr := FormatWave3GTINIdentityTextMode("opengtindb_text", "error=1\n---\n", nil, "https://opengtindb.org/?ean=4006381333931&cmd=query"); okOGErr { + t.Fatal("opengtindb_text must reject error=1") + } + + // #372 ENERGY STAR /api/views/*.json + /api/catalog/v1 + unhydrated SPA rejection + esViewJSON := []byte(`{"id":"7p2p-wkbf","name":"ENERGY STAR Certified Commercial Refrigerators","attribution":"US EPA","category":"Products","description":"Certified commercial refrigerators.","columns":[{"fieldName":":@computed_region","name":"Region","dataTypeName":"number"},{"fieldName":"pd_id","name":"PD ID","dataTypeName":"text"},{"fieldName":"brand_name","name":"Brand","dataTypeName":"text"}]}`) + esViewDoc, okESV := FormatWave3GTINIdentityJSONDoc("energy_star_json", esViewJSON, nil, "https://data.energystar.gov/api/views/7p2p-wkbf.json") + if !okESV || esViewDoc == nil || !strings.Contains(esViewDoc.Markdown, "pd_id") || strings.Contains(esViewDoc.Markdown, ":@computed_region") { + t.Fatalf("energy_star_json view failed: ok=%v doc=%+v", okESV, esViewDoc) + } + esUnhydrated := `ENERGY STAR Product Finder
` + if resESNeg := Wave3GTINIdentityRunHTML("energy_star_html", esUnhydrated, "https://www.energystar.gov/productfinder/product/certified-residential-refrigerators/details/2406498", "energy-star"); resESNeg != nil { + t.Fatalf("energy_star_html must reject unhydrated ProductFinder SPA shell, got %+v", resESNeg) + } + + // #373 fcc_id_html compatibility (F23.4 + F23.T2.5 empty table + exhibit links excluding ViewExhibitReport.cfm) + fccEmptyTable := `FCC ID ABC-123

FCC ID ABC-123

` + resFccEmpty := Wave3GTINIdentityRunHTML("fcc_id_html", fccEmptyTable, "https://fccid.io/ABC-123/empty-table", "fcc-id") + if resFccEmpty == nil || !strings.Contains(resFccEmpty.Markdown, "FCC ID ABC-123") { + t.Fatalf("fcc_id_html F23.T2.5 empty table must succeed: %+v", resFccEmpty) + } + fccFull := `FCC ID BCG-E3542A

FCC ID BCG-E3542A

Grantee: Apple Inc.

Frequency Range2402 - 2480 MHz
User Manual PDFDisallowed Report
` + resFccFull := Wave3GTINIdentityRunHTML("fcc_id_html", fccFull, "https://fccid.io/BCG-E3542A", "fcc-id") + if resFccFull == nil || !strings.Contains(resFccFull.Markdown, "2402 - 2480 MHz") || len(resFccFull.Links) != 1 || !strings.Contains(resFccFull.Links[0], "User-Manual-654321.pdf") { + t.Fatalf("fcc_id_html exhibit extraction failed: %+v", resFccFull) + } + + // #374 prop65-warnings Incapsula WAF shell rejection + OEHHA table extraction + incapsulaShell := ` ` + if resInc := Wave3GTINIdentityRunHTML("prop65_warnings_html", incapsulaShell, "https://oehha.ca.gov/proposition-65/proposition-65-list", "prop65-warnings"); resInc != nil { + t.Fatalf("prop65_warnings_html must reject Incapsula WAF shell, got %+v", resInc) + } + oehhaTableHTML := `The Proposition 65 List - OEHHA

The Proposition 65 List

ChemicalType of ToxicityListing MechanismCAS No.Date Listed
Acrylamidecancer, developmental, maleAB79-06-11990-01-01
` + resOEHHA := Wave3GTINIdentityRunHTML("prop65_warnings_html", oehhaTableHTML, "https://oehha.ca.gov/proposition-65/proposition-65-list", "prop65-warnings") + if resOEHHA == nil || len(resOEHHA.Records) != 1 || resOEHHA.Records[0]["casNumber"] != "79-06-1" { + t.Fatalf("prop65_warnings_html OEHHA table failed: %+v", resOEHHA) + } +} + +type wave3GTINFixture struct { + AdapterID string `json:"adapterId"` + Mode string `json:"mode"` + InputURL string `json:"inputUrl"` + ExpectedFetchURL string `json:"expectedFetchUrl"` + MockPayload string `json:"mockPayload"` + ExpectTitleIncludes string `json:"expectTitleIncludes"` + ExpectMarkdownIncludes []string `json:"expectMarkdownIncludes"` + NegativeCases []struct { + Name string `json:"name"` + Status int `json:"status"` + InputURL string `json:"inputUrl"` + FinalURL string `json:"finalUrl"` + Payload string `json:"payload"` + } `json:"negativeCases"` +} + +func TestWave3GTINFixturesGoldenAndNegative(t *testing.T) { + catQIDs := []string{ + "gs1-us-datahub", + "open-icecat", + "upcitemdb-barcodelookup", + "open-product-wikidata-gtin", + "energy-star", + "fcc-test-report", + "prop65-warnings", + } + for _, id := range catQIDs { + rawFx, err := os.ReadFile(filepath.Join("..", "..", "hub", "test", "fixtures", "adapters", id+".json")) + if err != nil { + t.Fatalf("read fixture %s.json: %v", id, err) + } + var fx wave3GTINFixture + if err := json.Unmarshal(rawFx, &fx); err != nil { + t.Fatalf("unmarshal fixture %s.json: %v", id, err) + } + if fx.AdapterID != id { + t.Fatalf("fixture %s.json adapterId=%q", id, fx.AdapterID) + } + if len(fx.NegativeCases) < 4 { + t.Fatalf("fixture %s.json must have >= 4 negativeCases, got %d", id, len(fx.NegativeCases)) + } + + rawMan, err := os.ReadFile(filepath.Join("manifests", id+".yaml")) + if err != nil { + t.Fatalf("read %s.yaml: %v", id, err) + } + m, err := ParseDeclarativeYAMLManifest(rawMan) + if err != nil { + t.Fatalf("ParseDeclarativeYAMLManifest(%s.yaml): %v", id, err) + } + + if fx.Mode == "twin" { + tm, ok := wave3GTINResolveManifest(t, m, fx.InputURL) + if !ok || tm == nil { + t.Fatalf("%s: expected twin match for %q", id, fx.InputURL) + } + if fx.ExpectedFetchURL != "" && tm.FetchURL != fx.ExpectedFetchURL { + t.Fatalf("%s: expectedFetchUrl=%q got %q", id, fx.ExpectedFetchURL, tm.FetchURL) + } + var doc *DeclarativeFormattedDoc + var okDoc bool + if tm.route.Extract.JSONMode != "" { + doc, okDoc = FormatWave3GTINIdentityJSONDoc(tm.route.Extract.JSONMode, []byte(fx.MockPayload), tm.params, fx.InputURL) + } else if tm.route.Extract.TextMode != "" { + doc, okDoc = FormatWave3GTINIdentityTextDoc(tm.route.Extract.TextMode, fx.MockPayload, tm.params, fx.InputURL) + } + if !okDoc || doc == nil || strings.TrimSpace(doc.Markdown) == "" { + t.Fatalf("%s: golden twin format failed", id) + } + if fx.ExpectTitleIncludes != "" && !strings.Contains(doc.Title, fx.ExpectTitleIncludes) { + t.Fatalf("%s: title %q missing %q", id, doc.Title, fx.ExpectTitleIncludes) + } + for _, needle := range fx.ExpectMarkdownIncludes { + if !strings.Contains(doc.Markdown, needle) { + t.Fatalf("%s: markdown missing %q:\n%s", id, needle, doc.Markdown) + } + } + } else { + if len(m.HTMLRoutes) == 0 { + t.Fatalf("%s: expected htmlRoutes", id) + } + res := Wave3GTINIdentityRunHTML(m.HTMLRoutes[0].Mode, fx.MockPayload, fx.InputURL, id) + if res == nil || strings.TrimSpace(res.Markdown) == "" { + t.Fatalf("%s: golden HTML extraction returned nil/empty", id) + } + if fx.ExpectTitleIncludes != "" && !strings.Contains(res.Title, fx.ExpectTitleIncludes) { + t.Fatalf("%s: title %q missing %q", id, res.Title, fx.ExpectTitleIncludes) + } + for _, needle := range fx.ExpectMarkdownIncludes { + if !strings.Contains(res.Markdown, needle) { + t.Fatalf("%s: markdown missing %q:\n%s", id, needle, res.Markdown) + } + } + } + + for _, nc := range fx.NegativeCases { + ncURL := nc.InputURL + if ncURL == "" { + ncURL = fx.InputURL + } + if nc.FinalURL != "" { + ncURL = nc.FinalURL + } + if tm, ok := wave3GTINResolveManifest(t, m, ncURL); ok && tm != nil { + if tm.route.Extract.JSONMode != "" { + if _, negOK := FormatWave3GTINIdentityJSONDoc(tm.route.Extract.JSONMode, []byte(nc.Payload), tm.params, ncURL); negOK { + t.Fatalf("%s negativeCase %q must NOT succeed in JSON formatter", id, nc.Name) + } + } else if tm.route.Extract.TextMode != "" { + if _, negOK := FormatWave3GTINIdentityTextDoc(tm.route.Extract.TextMode, nc.Payload, tm.params, ncURL); negOK { + t.Fatalf("%s negativeCase %q must NOT succeed in text formatter", id, nc.Name) + } + } + } + if len(m.HTMLRoutes) > 0 { + if resNeg := Wave3GTINIdentityRunHTML(m.HTMLRoutes[0].Mode, nc.Payload, ncURL, id); resNeg != nil { + t.Fatalf("%s negativeCase %q must NOT succeed in HTML extractor, got %+v", id, nc.Name, resNeg) + } + } + } + } +} + +func TestWave3GTINR7MarkdownHardening(t *testing.T) { + registerWave3GTINIdentityHTMLModes() + reInjectedHeading := regexp.MustCompile(`(?m)^#{1,6}[ \t]+.*(?:Injected|Pwned|EvilHeading)`) + + // 1. fcc_id_html (both direct and via ApplyDeclarativeHTMLExtractor) + fccHTML := `FCC [Phish](https://evil.example/dom)

FCC [Phish](https://evil.example/dom)

Details [Phish](https://evil.example/p) for device testing.

# InjectedHeading details [Phish](https://evil.example/p2)

Key [Phish](https://evil.example/th)Val [Phish](https://evil.example/td)
[Phish](https://evil.example/ex)Test Report
` + fccDoc, okFcc := ApplyDeclarativeHTMLExtractor(fccHTML, "https://fccid.io/BCG-E3542A", "", nil) + if !okFcc || fccDoc == nil { + t.Fatal("expected ApplyDeclarativeHTMLExtractor(fcc_id_html) to succeed") + } + if hasUnescapedClickableEvilLinkR10(fccDoc.Markdown) || strings.Contains(fccDoc.Markdown, "[Phish](") || !strings.Contains(fccDoc.Markdown, `\[Phish\]`) { + t.Fatalf("fcc_id_html leaked unescaped clickable link in Markdown:\n%s", fccDoc.Markdown) + } + if reInjectedHeading.MatchString(fccDoc.Markdown) { + t.Fatalf("fcc_id_html allowed injected ATX heading:\n%s", fccDoc.Markdown) + } + if !strings.Contains(fccDoc.Title, "[Phish]") { + t.Fatalf("fcc_id_html Title must remain unescaped plain text, got %q", fccDoc.Title) + } + + // 2. open_icecat_json (Title, Brand, BrandPartCode backtick sanitization, FeaturesGroups) + icePayload := []byte(`{ + "StatusCode": 0, + "msg": "OK", + "data": { + "GeneralInfo": { + "IcecatId": "12345", + "Title": "Monitor [Phish](https://evil.example/ice)", + "Brand": "Acme [Phish](https://evil.example/icebrand)", + "BrandPartCode": "M` + "`bad`" + `", + "GTIN": ["012000161155"], + "Category": {"Name": {"Value": "Displays [Phish](https://evil.example/icecat)"}}, + "SummaryDescription": {"LongSummaryDescription": "Summary [Phish](https://evil.example/icesum)"} + }, + "FeaturesGroups": [{ + "FeatureGroup": {"Name": {"Value": "Group [Phish](https://evil.example/icegrp)"}}, + "Features": [{ + "Feature": {"Name": {"Value": "Feat [Phish](https://evil.example/icefeat)"}}, + "PresentationValue": "Val [Phish](https://evil.example/iceval)" + }] + }] + } + }`) + iceDoc, okIce := FormatWave3GTINIdentityJSONDoc("open_icecat_json", icePayload, nil, "https://live.icecat.biz/api?GTIN=012000161155") + if !okIce || iceDoc == nil { + t.Fatal("expected FormatWave3GTINIdentityJSONDoc(open_icecat_json) to succeed") + } + if hasUnescapedClickableEvilLinkR10(iceDoc.Markdown) || strings.Contains(iceDoc.Markdown, "[Phish](") || !strings.Contains(iceDoc.Markdown, `\[Phish\]`) { + t.Fatalf("open_icecat_json leaked unescaped clickable link in Markdown:\n%s", iceDoc.Markdown) + } + if !strings.Contains(iceDoc.Markdown, "`M'bad'`") { + t.Fatalf("open_icecat_json must sanitize backticks in BrandPartCode inline code span:\n%s", iceDoc.Markdown) + } + if !strings.Contains(iceDoc.Title, "[Phish]") { + t.Fatalf("open_icecat_json Title must remain unescaped plain text, got %q", iceDoc.Title) + } + + // 3. prop65_warnings_html (h1, th, td, dl, multi-p) + p65HTML := `Prop 65 [Phish](https://evil.example/p65)

Prop 65 [Phish](https://evil.example/p65)

Endpoint [Phish](https://evil.example/p65dt)
Toxicity [Phish](https://evil.example/p65dd)
Chemical [Phish](https://evil.example/p65th)CAS No.
Lead [Phish](https://evil.example/p65td)7439-92-1

Proposition 65 warning details for test item.

# InjectedHeading [Phish](https://evil.example/p65p)

` + p65Res := Wave3GTINIdentityRunHTML("prop65_warnings_html", p65HTML, "https://oehha.ca.gov/proposition-65/chemicals/lead", "prop65-warnings") + if p65Res == nil { + t.Fatal("expected Wave3GTINIdentityRunHTML(prop65_warnings_html) to succeed") + } + if hasUnescapedClickableEvilLinkR10(p65Res.Markdown) || strings.Contains(p65Res.Markdown, "[Phish](") || !strings.Contains(p65Res.Markdown, `\[Phish\]`) { + t.Fatalf("prop65_warnings_html leaked unescaped clickable link in Markdown:\n%s", p65Res.Markdown) + } + if reInjectedHeading.MatchString(p65Res.Markdown) { + t.Fatalf("prop65_warnings_html allowed injected ATX heading:\n%s", p65Res.Markdown) + } + if !strings.Contains(p65Res.Title, "[Phish]") { + t.Fatalf("prop65_warnings_html Title must remain unescaped plain text, got %q", p65Res.Title) + } +} diff --git a/internal/extract/wave3_jobs_public.go b/internal/extract/wave3_jobs_public.go new file mode 100644 index 0000000..b12113e --- /dev/null +++ b/internal/extract/wave3_jobs_public.go @@ -0,0 +1,2743 @@ +package extract + +import ( + "encoding/json" + "fmt" + stdhtml "html" + "net/url" + "strconv" + "strings" + "time" +) + +const ( + wave3JobsMaxRecords = 25 + wave3JobsMaxJSONBytes = 4 * 1024 * 1024 + wave3JobsMaxHTMLBytes = 512 * 1024 +) + +var ( + wave3JobsRxNotFoundTitle = newLazyRegexp(`(?i)(?:^|\b)(?:404|410|page\s+not\s+found|not\s+found|error\s*404|we\s+couldn'?t\s+find\s+that\s+page|access\s+denied|request\s+(?:rejected|blocked)|request\s+unsuccessful|could\s+not\s+be\s+satisfied|unauthorized|attention\s+required|just\s+a\s+moment|job\s+not\s+found|position\s+not\s+found|requisition\s+not\s+found|vacancy\s+not\s+found|organization\s+portal\s+disabled)(?:\b|$)`) + wave3JobsRxMaintTitle = newLazyRegexp(`(?i)(?:scheduled\s+maintenance|temporarily\s+unavailable|service\s+unavailable|site\s+maintenance|under\s+maintenance|502\s+bad\s+gateway|503\s+service|down\s+for\s+maintenance)`) + wave3JobsRxErrorTitle = newLazyRegexp(`(?i)^(?:(?:(?:401|403|404|410|429|500|502|503)\s+)?(?:internal\s+)?server\s+error|application\s+error|system\s+error|unexpected\s+error|error\s+page|(?:401|403|404|410|429|500|502|503|http\s+\d{3})\s+error|error\s+(?:401|403|404|410|429|500|502|503)|error)(?:\s*[|\-\x{2013}\x{2014}:]\s*.*)?$`) + wave3JobsRxGenericHead = newLazyRegexp(`(?i)^\s*(?:job\s+details?|job\s+description|job\s+info(?:rmation)?|job\s+posting|careers?(?:\s+(?:home|portal|site|page|center|opportunities))?|career\s+opportunities|review\s+vacancy|search\s+(?:jobs|results|openings|positions|careers)|job\s+search(?:\s*[-|]\s*basic\s+search|\s+results)?|jobs?|job\s+listings?|job\s+openings|job\s+opportunities|current\s+openings|open\s+positions|positions?|roles?|search|home|welcome|apply(?:\s+now)?|join\s+our\s+team|log\s*in|sign\s+in|loading|application\s+error|organization\s+portal\s+disabled)\s*[:.!]?\s*$`) + wave3JobsRxTitleSep = newLazyRegexp(`\s*\|\s*|\s+[-\x{2013}\x{2014}]\s+`) + wave3JobsRxISODate = newLazyRegexp(`^(\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01]))(?:$|T\d{2}:\d{2}| \d{2}:\d{2})`) + wave3JobsRxSlashDate = newLazyRegexp(`^(\d{1,2})/(\d{1,2})/(\d{4})$`) + wave3JobsRxJobPostingTok = newLazyRegexp(`(?i)JobPosting`) + wave3JobsRxHTMLTagProbe = newLazyRegexp(`<[a-zA-Z!/]`) +) + +func init() { + for _, mode := range []string{ + "neogov_html", + "bullhorn_portal_html", + "taleo_full_html", + "paradox_olivia_html", + "staffing_ats_pack_html", + "smb_ats_full_html", + "edu_job_boards_html", + "healthcare_careers_html", + } { + m := mode + RegisterExternalHTMLModeLazy(m, func(rawHTML, baseURL string, _ func() string, extractorID string) *DeclarativePostFetchResult { + return Wave3JobsPublicRunHTML(m, rawHTML, baseURL, extractorID) + }) + } +} + +// IsWave3JobsPublicJSONMode reports whether mode is handled by Category C Public-Sector & Staffing Jobs JSON formatters (#226-#233). +func IsWave3JobsPublicJSONMode(mode string) bool { + switch mode { + case "neogov_json", + "bullhorn_joborder_json", + "staffing_ats_json", + "manatal_jobs_json", + "smb_ats_json": + return true + default: + return false + } +} + +// FormatWave3JobsPublicJSONDoc formats a Category C JSON payload into a DeclarativeFormattedDoc. +func FormatWave3JobsPublicJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool) { + if !IsWave3JobsPublicJSONMode(mode) { + return nil, false + } + if len(raw) == 0 || len(raw) > wave3JobsMaxJSONBytes { + return nil, false + } + trimmed := strings.TrimSpace(strings.TrimPrefix(string(raw), "\xEF\xBB\xBF")) + if trimmed == "" || (trimmed[0] != '{' && trimmed[0] != '[') { + return nil, false + } + parsed, ok := decodeJSONWithNumbers([]byte(trimmed)) + if !ok || parsed == nil { + return nil, false + } + var doc *DeclarativeFormattedDoc + var handled bool + switch mode { + case "neogov_json": + doc, handled = wave3JobsFormatNeoGovJSON(parsed, origURL) + case "bullhorn_joborder_json": + doc, handled = wave3JobsFormatBullhornJSON(parsed, params, origURL) + case "staffing_ats_json": + doc, handled = wave3JobsFormatStaffingJSON(parsed, origURL) + case "manatal_jobs_json": + doc, handled = wave3JobsFormatManatalJSON(parsed, params, origURL) + case "smb_ats_json": + doc, handled = wave3JobsFormatSMBAtsJSON(parsed, origURL) + } + if !handled || doc == nil || strings.TrimSpace(doc.Markdown) == "" { + return nil, false + } + return wave3JobsFinalizeDoc(doc), true +} + +// FormatWave3JobsPublicJSONMode formats a Category C JSON payload and returns JSON-marshaled DeclarativeFormattedDoc. +func FormatWave3JobsPublicJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool) { + doc, ok := FormatWave3JobsPublicJSONDoc(mode, raw, params, origURL) + if !ok || doc == nil || strings.TrimSpace(doc.Markdown) == "" { + return "", false + } + encoded, err := json.Marshal(doc) + if err != nil { + return "", false + } + return string(encoded), true +} + +// IsWave3JobsPublicHTMLMode reports whether mode is handled by Category C Public-Sector & Staffing Jobs HTML extractors (#226-#233). +func IsWave3JobsPublicHTMLMode(mode string) bool { + switch mode { + case "neogov_html", + "bullhorn_portal_html", + "taleo_full_html", + "paradox_olivia_html", + "staffing_ats_pack_html", + "smb_ats_full_html", + "edu_job_boards_html", + "healthcare_careers_html": + return true + default: + return false + } +} + +func wave3JobsMatchesModePrefilter(mode, rawHTML, baseURL string) bool { + probe128K := rawHTML + if len(probe128K) > 131_072 { + probe128K = probe128K[:131_072] + } + switch mode { + case "neogov_html": + return containsAnyFoldASCIIExtract(rawHTML, "governmentjobs", "schooljobs", "neogov", "jobposting", "job-listing") + case "bullhorn_portal_html": + return containsAnyFoldASCIIExtract(baseURL, "bullhornstaffing.com") || + containsAnyFoldASCIIExtract(rawHTML, "bullhorn", "bh-career", "oscp") + case "taleo_full_html": + return containsAnyFoldASCIIExtract(baseURL, "taleo.net", "/careersection/") || + containsAnyFoldASCIIExtract(rawHTML, "taleo", "careersection", "requisitionlist", "jobposting", "ftllist") + case "paradox_olivia_html": + return containsAnyFoldASCIIExtract(baseURL, "paradox.ai", "mchire.com") || + containsAnyFoldASCIIExtract(probe128K, "paradox", "mchire", "olivia") + case "staffing_ats_pack_html": + return containsAnyFoldASCIIExtract(baseURL, "crelate.com", "jobdiva.com", "ceipal.com") || + containsAnyFoldASCIIExtract(rawHTML, "crelate", "jobdiva", "ceipal") + case "healthcare_careers_html": + return containsAnyFoldASCIIExtract(baseURL, "healthcaresource.com", "symplr.com") || + containsAnyFoldASCIIExtract(rawHTML, "healthcaresource", "symplr") + default: + return true + } +} + +// Wave3JobsPublicRunHTML executes a Category C HTML extractor and returns a DeclarativePostFetchResult. +func Wave3JobsPublicRunHTML(mode string, rawHTML string, baseURL string, extractorID string) *DeclarativePostFetchResult { + if !IsWave3JobsPublicHTMLMode(mode) || rawHTML == "" || strings.IndexByte(rawHTML, '<') < 0 || strings.IndexByte(rawHTML, '>') < 0 { + return nil + } + trimmedStart := strings.TrimLeft(rawHTML, " \t\r\n") + if trimmedStart == "" || trimmedStart[0] == '{' || trimmedStart[0] == '[' { + return nil + } + if len(rawHTML) > wave3JobsMaxHTMLBytes*4 { + rawHTML = truncateUTF8SafeFullDocGo(rawHTML, wave3JobsMaxHTMLBytes*4) + } + if !wave3JobsMatchesModePrefilter(mode, rawHTML, baseURL) { + return nil + } + if wave3JobsHasNegativeShell(rawHTML, baseURL) { + return nil + } + if extractorID == "" { + extractorID = wave3JobsDefaultExtractorID(mode) + } + var res *DeclarativePostFetchResult + switch mode { + case "neogov_html": + res = wave3JobsExtractNeoGovHTML(rawHTML, baseURL, extractorID) + case "bullhorn_portal_html": + res = wave3JobsExtractBullhornHTML(rawHTML, baseURL, extractorID) + case "taleo_full_html": + res = wave3JobsExtractTaleoHTML(rawHTML, baseURL, extractorID) + case "paradox_olivia_html": + res = wave3JobsExtractParadoxHTML(rawHTML, baseURL, extractorID) + case "staffing_ats_pack_html": + res = wave3JobsExtractStaffingATSPackHTML(rawHTML, baseURL, extractorID) + case "smb_ats_full_html": + res = wave3JobsExtractSMBAtsFullHTML(rawHTML, baseURL, extractorID) + case "edu_job_boards_html": + res = wave3JobsExtractEduJobBoardsHTML(rawHTML, baseURL, extractorID) + case "healthcare_careers_html": + res = wave3JobsExtractHealthcareCareersHTML(rawHTML, baseURL, extractorID) + } + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return nil + } + if res.Title != "" && wave3JobsIsGenericHeading(res.Title) { + res.Title = "" + } + return res +} + +// RunWave3JobsPublicHTMLMode executes a Category C HTML extractor and returns JSON-marshaled DeclarativePostFetchResult. +func RunWave3JobsPublicHTMLMode(mode string, rawHTML string, baseURL string) (string, bool) { + res := Wave3JobsPublicRunHTML(mode, rawHTML, baseURL, wave3JobsDefaultExtractorID(mode)) + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return "", false + } + res = sanitizePostFetchResultDeclHTML(res) + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return "", false + } + encoded, err := json.Marshal(res) + if err != nil { + return "", false + } + return string(encoded), true +} + +func wave3JobsDefaultExtractorID(mode string) string { + switch mode { + case "neogov_html": + return "neogov" + case "bullhorn_portal_html": + return "bullhorn-career-portal" + case "taleo_full_html": + return "taleo-full" + case "paradox_olivia_html": + return "paradox-olivia" + case "staffing_ats_pack_html": + return "staffing-ats-pack" + case "smb_ats_full_html": + return "smb-ats-full" + case "edu_job_boards_html": + return "edu-job-boards" + case "healthcare_careers_html": + return "healthcare-careers" + default: + return "" + } +} + +// ── Shared Helpers ────────────────────────────────────────────────────────────────────────────── + +func wave3JobsAttr(n *HTMLNode, name string) string { + if n == nil { + return "" + } + v, _ := n.Attr(name) + return v +} + +func wave3JobsContainsASCIIFold(haystack, needle string) bool { + return indexFoldASCIIExtract(haystack, needle) >= 0 +} + +func wave3JobsHostLower(rawURL string) string { + u, err := url.Parse(strings.TrimSpace(rawURL)) + if err != nil { + return "" + } + return strings.TrimSuffix(strings.ToLower(u.Hostname()), ".") +} + +func wave3JobsIsGenericHeading(raw string) bool { + clean := strings.TrimSpace(stripTagsInlineLinear(raw)) + if clean == "" { + return true + } + return wave3JobsRxGenericHead.MatchString(clean) +} + +func wave3JobsCleanJobTitle(raw string) string { + clean := strings.TrimSpace(SanitizeSchemaPlainField(stripTagsInlineLinear(raw), 240)) + if clean == "" || wave3JobsIsGenericHeading(clean) { + return "" + } + return clean +} + +func wave3JobsCleanPageTitle(rawTitle string) string { + clean := strings.TrimSpace(SanitizeSchemaPlainField(stripTagsInlineLinear(rawTitle), 260)) + if clean == "" || wave3JobsIsGenericHeading(clean) { + return "" + } + parts := wave3JobsRxTitleSep.Split(clean, 6) + for _, p := range parts { + cand := strings.TrimSpace(p) + if cand == "" || wave3JobsIsGenericHeading(cand) { + continue + } + return cand + } + return "" +} + +func wave3JobsPlain(v any, maxLen int) string { + return SanitizeSchemaPlainField(jsonScalarToString(v), maxLen) +} + +func wave3JobsFirstNonEmpty(vals ...string) string { + for _, v := range vals { + if t := strings.TrimSpace(v); t != "" { + return t + } + } + return "" +} + +func wave3JobsIntPtr(n int) *int { + v := n + return &v +} + +func wave3JobsBoolPtr(b bool) *bool { + v := b + return &v +} + +func wave3JobsMap(v any) map[string]any { + if m, ok := v.(map[string]any); ok { + return m + } + return nil +} + +func wave3JobsSlice(v any) []any { + if a, ok := v.([]any); ok { + return a + } + return nil +} + +func wave3JobsIntFromAny(v any) (int, bool) { + switch tv := v.(type) { + case json.Number: + if i, err := tv.Int64(); err == nil { + return int(i), true + } + if f, err := tv.Float64(); err == nil { + return int(f), true + } + case float64: + return int(tv), true + case int: + return tv, true + case string: + if i, err := strconv.Atoi(strings.TrimSpace(tv)); err == nil { + return i, true + } + } + return 0, false +} + +func wave3JobsNormalizeDate(raw string) string { + s := strings.TrimSpace(raw) + if s == "" { + return "" + } + if m := wave3JobsRxISODate.FindStringSubmatch(s); len(m) == 2 { + return m[1] + } + if m := wave3JobsRxSlashDate.FindStringSubmatch(s); len(m) == 4 { + mo, _ := strconv.Atoi(m[1]) + dy, _ := strconv.Atoi(m[2]) + yr, _ := strconv.Atoi(m[3]) + if yr >= 1900 && yr <= 2100 && mo >= 1 && mo <= 12 && dy >= 1 && dy <= 31 { + return fmt.Sprintf("%04d-%02d-%02d", yr, mo, dy) + } + } + if len(s) <= 40 { + for _, layout := range []string{time.RFC3339, time.RFC3339Nano, "2006-01-02 15:04:05", "Jan 2, 2006", "January 2, 2006", "Jan 2, 2006, 3:04:05 PM", "January 2, 2006, 3:04:05 PM"} { + if t, err := time.Parse(layout, s); err == nil { + return t.Format("2006-01-02") + } + } + } + return "" +} + +func wave3JobsInt64FromAny(v any) (int64, bool) { + switch tv := v.(type) { + case json.Number: + if i, err := tv.Int64(); err == nil { + return i, true + } + if f, err := tv.Float64(); err == nil { + return int64(f), true + } + case float64: + return int64(tv), true + case int64: + return tv, true + case int: + return int64(tv), true + case string: + if i, err := strconv.ParseInt(strings.TrimSpace(tv), 10, 64); err == nil { + return i, true + } + } + return 0, false +} + +func wave3JobsNormalizeTimestampUnix(v any) string { + sec, ok := wave3JobsInt64FromAny(v) + if !ok || sec <= 0 { + return "" + } + if sec > 10_000_000_000 { + sec = sec / 1000 + } + if sec < 946_684_800 || sec > 4_102_444_800 { + return "" + } + return time.Unix(sec, 0).UTC().Format("2006-01-02") +} + +func wave3JobsEscapeMDCell(s string) string { + clean := SanitizeSchemaPlainField(s, 180) + clean = strings.ReplaceAll(clean, "|", "\\|") + clean = strings.ReplaceAll(clean, "\n", " ") + clean = strings.ReplaceAll(clean, "\r", " ") + return strings.TrimSpace(clean) +} + +func wave3JobsSafeURL(raw, baseURL string) string { + s := strings.TrimSpace(raw) + if s == "" { + return "" + } + if strings.HasPrefix(s, "https://") { + if isSafePublicHTTPSFeedURL(s) { + return s + } + return "" + } + if strings.HasPrefix(s, "/") && baseURL != "" { + if bu, err := url.Parse(baseURL); err == nil && bu.Scheme == "https" && bu.Host != "" { + if rel, rErr := url.Parse(s); rErr == nil { + resolved := bu.ResolveReference(rel).String() + if isSafePublicHTTPSFeedURL(resolved) { + return resolved + } + } + } + } + return "" +} + +func wave3JobsLinearHTMLToText(rawHTMLOrText string, maxChars int) string { + trimmed := strings.TrimSpace(rawHTMLOrText) + if trimmed == "" { + return "" + } + if len(trimmed) > 131_072 { + trimmed = truncateUTF8SafeFullDocGo(trimmed, 131_072) + } + if strings.IndexByte(trimmed, '&') >= 0 { + trimmed = stdhtml.UnescapeString(trimmed) + } + if strings.IndexByte(trimmed, '<') < 0 { + return SanitizeSchemaPlainField(trimmed, maxChars) + } + + var sb strings.Builder + sb.Grow(len(trimmed)) + n := len(trimmed) + pos := 0 + for pos < n { + rel := strings.IndexByte(trimmed[pos:], '<') + if rel < 0 { + sb.WriteString(trimmed[pos:]) + break + } + sb.WriteString(trimmed[pos : pos+rel]) + lt := pos + rel + if lt+1 >= n { + break + } + // Find end of tag (quote-aware) + cur := lt + 1 + var quote byte + tagEnd := -1 + for cur < n { + ch := trimmed[cur] + if quote != 0 { + if ch == quote { + quote = 0 + } + } else if ch == '"' || ch == '\'' { + quote = ch + } else if ch == '>' { + tagEnd = cur + 1 + break + } + cur++ + } + if tagEnd < 0 { + break + } + tagBody := strings.TrimSpace(trimmed[lt+1 : tagEnd-1]) + closing := false + if strings.HasPrefix(tagBody, "/") { + closing = true + tagBody = strings.TrimSpace(tagBody[1:]) + } + nameEnd := 0 + for nameEnd < len(tagBody) { + c := tagBody[nameEnd] + if c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '/' { + break + } + nameEnd++ + } + tagLower := asciiLowerExtractString(tagBody[:nameEnd]) + pos = tagEnd + if !closing && (tagLower == "script" || tagLower == "style" || tagLower == "noscript" || tagLower == "svg") { + if closeIdx := indexFoldASCIIExtract(trimmed[pos:], "= 0 { + if cgt := strings.IndexByte(trimmed[pos+closeIdx:], '>'); cgt >= 0 { + pos += closeIdx + cgt + 1 + continue + } + } + continue + } + switch tagLower { + case "br": + sb.WriteByte('\n') + case "li": + if closing { + sb.WriteByte('\n') + } else { + sb.WriteString("\n- ") + } + case "p", "div", "section", "article", "h1", "h2", "h3", "h4", "h5", "h6", "ul", "ol", "tr": + sb.WriteString("\n\n") + default: + sb.WriteByte(' ') + } + } + + rawText := sb.String() + if strings.IndexByte(rawText, '&') >= 0 { + rawText = stdhtml.UnescapeString(rawText) + } + lines := strings.Split(rawText, "\n") + cleaned := make([]string, 0, len(lines)) + blankRun := 0 + for _, ln := range lines { + fields := strings.Fields(ln) + if len(fields) == 0 { + blankRun++ + if blankRun <= 1 && len(cleaned) > 0 { + cleaned = append(cleaned, "") + } + continue + } + blankRun = 0 + cleaned = append(cleaned, strings.Join(fields, " ")) + } + joined := strings.TrimSpace(strings.Join(cleaned, "\n")) + md := strings.TrimSpace(SanitizeScrapedMarkdown(joined)) + if md != "" { + return sliceRunesMax(md, maxChars) + } + return SanitizeSchemaPlainField(joined, maxChars) +} + +func wave3JobsRichText(rawHTMLOrText string, baseURL string, maxChars int) string { + trimmed := strings.TrimSpace(rawHTMLOrText) + if trimmed == "" { + return "" + } + if wave3JobsRxHTMLTagProbe.MatchString(trimmed) { + ext := ExtractHTMLDocumentFull(""+trimmed+"", FullExtractOptions{ + BaseURL: baseURL, + OnlyMainContent: false, + IncludeImages: false, + IsFragment: true, + SkipUniversalExtractors: true, + SkipPlainText: true, + }) + md := strings.TrimSpace(SanitizeScrapedMarkdown(ext.Markdown)) + if md != "" { + return sliceRunesMax(md, maxChars) + } + } + return SanitizeSchemaPlainField(stripTagsInlineLinear(trimmed), maxChars) +} + +func wave3JobsFinalizeDoc(doc *DeclarativeFormattedDoc) *DeclarativeFormattedDoc { + if doc == nil { + return nil + } + if len(doc.Records) > wave3JobsMaxRecords { + if doc.Total == nil { + doc.Total = wave3JobsIntPtr(len(doc.Records)) + } + doc.Records = doc.Records[:wave3JobsMaxRecords] + doc.Returned = wave3JobsIntPtr(len(doc.Records)) + doc.Truncated = wave3JobsBoolPtr(true) + if doc.NextCursor == "" { + doc.NextCursor = strconv.Itoa(len(doc.Records)) + } + } + if sanitized, ok := sanitizeDeclarativeFormattedDocGo(doc); ok && sanitized != nil { + return sanitized + } + return doc +} + +func wave3JobsDedupLinks(links []string, limit int) []string { + if limit <= 0 { + limit = 30 + } + seen := make(map[string]bool, len(links)) + out := make([]string, 0, len(links)) + for _, l := range links { + if isSafePublicHTTPSFeedURL(l) && !seen[l] { + seen[l] = true + out = append(out, l) + if len(out) >= limit { + break + } + } + } + if len(out) == 0 { + return nil + } + return out +} + +func wave3JobsHasJSONError(m map[string]any) bool { + if m == nil { + return false + } + if emk := strings.TrimSpace(wave3JobsPlain(caseInsensitiveFieldM4(m, "errorMessageKey"), 120)); emk != "" { + return true + } + if em := strings.TrimSpace(wave3JobsPlain(caseInsensitiveFieldM4(m, "errorMessage"), 120)); em != "" { + return true + } + if errVal := caseInsensitiveFieldM4(m, "error"); errVal != nil { + switch tv := errVal.(type) { + case bool: + if tv { + return true + } + case string: + if strings.TrimSpace(tv) != "" { + return true + } + case map[string]any: + if len(tv) > 0 { + return true + } + } + } + if errs := wave3JobsSlice(caseInsensitiveFieldM4(m, "errors")); len(errs) > 0 { + return true + } + if ec, ok := wave3JobsIntFromAny(caseInsensitiveFieldM4(m, "errorCode")); ok && ec != 0 { + return true + } + if st, ok := wave3JobsIntFromAny(caseInsensitiveFieldM4(m, "status")); ok && st >= 400 { + return true + } + if det := strings.ToLower(strings.TrimSpace(wave3JobsPlain(caseInsensitiveFieldM4(m, "detail"), 120))); det == "not found." || det == "not found" { + return true + } + return false +} + +func wave3JobsHasNegativeShell(rawHTML, baseURL string) bool { + uLow := strings.ToLower(strings.TrimSpace(baseURL)) + if uLow != "" { + if strings.Contains(uLow, "/404") || + strings.Contains(uLow, "/not-found") || + strings.Contains(uLow, "/notfound") || + strings.Contains(uLow, "/error") || + strings.Contains(uLow, "/maintenance") || + strings.Contains(uLow, "/public/disabledportal") || + strings.Contains(uLow, "404.homerun.co") || + strings.Contains(uLow, "disabled=1") || + strings.Contains(uLow, "/users/sign_in") || + strings.Contains(uLow, "/cdn-cgi/") || + strings.Contains(uLow, "_incapsula_resource") { + return true + } + } + probe := rawHTML + if len(probe) > 65536 { + probe = probe[:65536] + } + low := asciiLowerExtractString(probe) + // Reject WAF / Cloudflare Turnstile / Imperva Incapsula challenges immediately. + if strings.Contains(low, "_incapsula_resource") || + strings.Contains(low, "incapsula incident id") || + strings.Contains(low, "request unsuccessful. incapsula") || + strings.Contains(low, "turnstileload") || + strings.Contains(low, "cf-turnstile") || + strings.Contains(low, "challenges.cloudflare.com/turnstile") || + strings.Contains(low, "cf-browser-verification") || + strings.Contains(low, "_cf_chl_opt") || + strings.Contains(low, "enable javascript and cookies to continue") || + strings.Contains(low, "checking your browser before accessing") { + return true + } + // Reject ATS soft-404 / disabled portal / application error markers. + if strings.Contains(low, "organization portal disabled") || + strings.Contains(low, "portal is currently disabled") || + strings.Contains(low, "errors.badcorptoken") || + strings.Contains(low, "404.homerun.co") || + strings.Contains(low, "job board does not exist") || + strings.Contains(low, "job board is unavailable") || + strings.Contains(low, "job board is currently disabled") || + strings.Contains(low, "you have encountered a system error") || + strings.Contains(low, "please verify that you have entered the correct url") || + strings.Contains(low, "vacancy not found") || + strings.Contains(low, "this job posting is no longer available") { + return true + } + + doc := ParseHTMLDoc(probe, 65536) + if doc != nil { + for _, t := range doc.Select("title", 4) { + txt := strings.TrimSpace(SanitizeSchemaPlainField(t.Text(), 220)) + if txt != "" && (wave3JobsRxNotFoundTitle.MatchString(txt) || wave3JobsRxMaintTitle.MatchString(txt) || wave3JobsRxErrorTitle.MatchString(txt)) { + return true + } + } + for _, h := range doc.Select("h1", 4) { + txt := strings.TrimSpace(SanitizeSchemaPlainField(h.Text(), 220)) + if txt != "" && (wave3JobsRxNotFoundTitle.MatchString(txt) || wave3JobsRxMaintTitle.MatchString(txt) || wave3JobsRxErrorTitle.MatchString(txt)) { + return true + } + } + } + return false +} + +func wave3JobsIsEmptySPAShell(rawHTML string, doc *HTMLDoc) bool { + probe := rawHTML + if len(probe) > 65536 { + probe = probe[:65536] + } + if wave3JobsContainsASCIIFold(probe, "jobposting") { + return false + } + hasSPAContainer := wave3JobsContainsASCIIFold(probe, `id="root"`) || + wave3JobsContainsASCIIFold(probe, `id="app"`) || + wave3JobsContainsASCIIFold(probe, `id="__next"`) || + wave3JobsContainsASCIIFold(probe, ` len(probe) && wave3JobsRxJobPostingTok.MatchString(rawHTML) { + return false + } + bodyTxt := "" + if b := doc.First("body"); b != nil { + bodyTxt = strings.TrimSpace(SanitizeSchemaPlainField(b.Text(), 400)) + } + if len(bodyTxt) < 60 { + return true + } + lowBody := strings.ToLower(bodyTxt) + if strings.Contains(lowBody, "please enable javascript") && len(bodyTxt) < 160 { + return true + } + return false +} + +// ── Entity-Aware JSON-LD Scanner ──────────────────────────────────────────────────────────────── + +func wave3JobsIsJSONLDScriptAttr(attrStr string) bool { + if attrStr == "" { + return false + } + if IsJSONLDScriptAttr(attrStr) { + return true + } + if strings.IndexByte(attrStr, '&') < 0 { + return false + } + decoded := stdhtml.UnescapeString(attrStr) + return decoded != attrStr && IsJSONLDScriptAttr(decoded) +} + +func wave3JobsExtractJSONLDObjects(rawHTML string, maxEntities int) []map[string]any { + if rawHTML == "" { + return nil + } + if indexFoldASCIIExtract(rawHTML, "ld+json") < 0 && + indexFoldASCIIExtract(rawHTML, "ld+json") < 0 && + indexFoldASCIIExtract(rawHTML, "ld+json") < 0 { + return nil + } + capCount := maxEntities + if capCount <= 0 || capCount > 100 { + capCount = 60 + } + src := rawHTML + if len(src) > 2*1024*1024 { + src = src[:2*1024*1024] + } + var results []map[string]any + var pushItem func(item any, depth int) + pushItem = func(item any, depth int) { + if item == nil || depth > 16 || len(results) >= capCount { + return + } + switch tv := item.(type) { + case []any: + for _, el := range tv { + if len(results) >= capCount { + break + } + pushItem(el, depth+1) + } + case map[string]any: + results = append(results, tv) + if graph, isArr := tv["@graph"].([]any); isArr { + for _, g := range graph { + if len(results) >= capCount { + break + } + pushItem(g, depth+1) + } + } + if items, isArr := tv["itemListElement"].([]any); isArr { + for _, el := range items { + if len(results) >= capCount { + break + } + if elMap, ok := el.(map[string]any); ok { + if inner, hasInner := elMap["item"]; hasInner { + pushItem(inner, depth+1) + continue + } + } + pushItem(el, depth+1) + } + } + } + } + + pos := 0 + for pos < len(src) && len(results) < capCount { + open, ok := findOpenTagLinearDeclHTML(src, "script", wave3JobsIsJSONLDScriptAttr, pos) + if !ok { + break + } + if open.selfClosing { + pos = open.openEnd + continue + } + closeStart, closeEnd, okClose := findCloseTagLinearDeclHTML(src, "script", open.openEnd) + if !okClose { + break + } + raw := strings.TrimSpace(src[open.openEnd:closeStart]) + pos = closeEnd + if raw == "" || len(raw) > 2*1024*1024 || !wave3JobsRxJobPostingTok.MatchString(raw) { + continue + } + parsed, okP := decodeJSONWithNumbers([]byte(raw)) + if !okP && strings.IndexByte(raw, '&') >= 0 { + parsed, okP = decodeJSONWithNumbers([]byte(stdhtml.UnescapeString(raw))) + } + if okP { + pushItem(parsed, 0) + } + } + return results +} + +func wave3JobsExtractJobPostingLDs(rawHTML string) []map[string]any { + all := wave3JobsExtractJSONLDObjects(rawHTML, 60) + var postings []map[string]any + for _, obj := range all { + if strings.Contains(strings.ToLower(jsonLDTypeStringDeclHTML(obj)), "jobposting") { + postings = append(postings, obj) + } + } + return postings +} + +type wave3JobPostingNorm struct { + Title string + Company string + Locations []string + Remote bool + Salary string + EmploymentType string + DatePosted string + ValidThrough string + URL string + Description string +} + +func wave3JobsNormalizeJobPostingLD(obj map[string]any, baseURL string) (wave3JobPostingNorm, bool) { + var out wave3JobPostingNorm + if obj == nil { + return out, false + } + out.Title = wave3JobsCleanJobTitle(wave3JobsPlain(caseInsensitiveFieldM4(obj, "title"), 220)) + if out.Title == "" { + out.Title = wave3JobsCleanJobTitle(wave3JobsPlain(caseInsensitiveFieldM4(obj, "name"), 220)) + } + if out.Title == "" { + return out, false + } + switch org := caseInsensitiveFieldM4(obj, "hiringOrganization").(type) { + case string: + cand := wave3JobsPlain(org, 140) + if !wave3JobsIsGenericHeading(cand) { + out.Company = cand + } + case map[string]any: + cand := wave3JobsPlain(caseInsensitiveFieldM4(org, "name"), 140) + if !wave3JobsIsGenericHeading(cand) { + out.Company = cand + } + } + if strings.EqualFold(wave3JobsPlain(caseInsensitiveFieldM4(obj, "jobLocationType"), 40), "TELECOMMUTE") { + out.Remote = true + } + rawLocVal := caseInsensitiveFieldM4(obj, "jobLocation") + var rawLocs []any + if arr := wave3JobsSlice(rawLocVal); len(arr) > 0 { + rawLocs = arr + } else if rawLocVal != nil { + rawLocs = []any{rawLocVal} + } + seenLoc := make(map[string]bool) + for _, rl := range rawLocs { + switch lv := rl.(type) { + case string: + c := wave3JobsPlain(lv, 120) + if c != "" && !seenLoc[c] { + seenLoc[c] = true + out.Locations = append(out.Locations, c) + } + case map[string]any: + addr := lv + if sub := wave3JobsMap(caseInsensitiveFieldM4(lv, "address")); sub != nil { + addr = sub + } + var parts []string + for _, k := range []string{"addressLocality", "addressRegion", "addressCountry"} { + if p := wave3JobsPlain(caseInsensitiveFieldM4(addr, k), 60); p != "" { + parts = append(parts, p) + } + } + locStr := strings.Join(parts, ", ") + if locStr == "" { + locStr = wave3JobsPlain(caseInsensitiveFieldM4(lv, "name"), 120) + } + if locStr != "" && !seenLoc[locStr] { + seenLoc[locStr] = true + out.Locations = append(out.Locations, locStr) + } + } + } + if sal := wave3JobsFormatBaseSalary(caseInsensitiveFieldM4(obj, "baseSalary")); sal != "" { + out.Salary = sal + } + switch et := caseInsensitiveFieldM4(obj, "employmentType").(type) { + case string: + out.EmploymentType = wave3JobsPlain(et, 80) + case []any: + var ets []string + for _, item := range et { + if s := wave3JobsPlain(item, 40); s != "" { + ets = append(ets, s) + } + } + out.EmploymentType = strings.Join(ets, ", ") + } + out.DatePosted = wave3JobsNormalizeDate(wave3JobsPlain(caseInsensitiveFieldM4(obj, "datePosted"), 40)) + out.ValidThrough = wave3JobsNormalizeDate(wave3JobsPlain(caseInsensitiveFieldM4(obj, "validThrough"), 40)) + out.URL = wave3JobsSafeURL(wave3JobsPlain(caseInsensitiveFieldM4(obj, "url"), 500), baseURL) + if descRaw := jsonScalarToString(caseInsensitiveFieldM4(obj, "description")); descRaw != "" { + out.Description = wave3JobsLinearHTMLToText(descRaw, 16000) + } + return out, true +} + +func wave3JobsFormatBaseSalary(v any) string { + m := wave3JobsMap(v) + if m == nil { + return "" + } + cur := wave3JobsPlain(caseInsensitiveFieldM4(m, "currency"), 8) + val := wave3JobsMap(caseInsensitiveFieldM4(m, "value")) + if val == nil { + val = m + } + minV := wave3JobsPlain(caseInsensitiveFieldM4(val, "minValue"), 24) + maxV := wave3JobsPlain(caseInsensitiveFieldM4(val, "maxValue"), 24) + exactV := wave3JobsPlain(caseInsensitiveFieldM4(val, "value"), 24) + unit := wave3JobsPlain(caseInsensitiveFieldM4(val, "unitText"), 20) + var amt string + if minV != "" && maxV != "" { + amt = minV + " - " + maxV + } else if exactV != "" { + amt = exactV + } else if minV != "" { + amt = minV + } else if maxV != "" { + amt = maxV + } + if amt == "" { + return "" + } + if cur != "" { + amt = cur + " " + amt + } + if unit != "" { + amt += " / " + strings.ToLower(unit) + } + return amt +} + +func wave3JobsBuildPostingResult(jp wave3JobPostingNorm, baseURL, extractorID string) *DeclarativePostFetchResult { + heading := jp.Title + if jp.Company != "" { + heading = jp.Title + " — " + jp.Company + } + var lines []string + lines = append(lines, "# "+heading, "") + if jp.Company != "" { + lines = append(lines, "- **Company**: "+jp.Company) + } + if len(jp.Locations) > 0 { + locText := strings.Join(jp.Locations, "; ") + if jp.Remote && !strings.Contains(strings.ToLower(locText), "remote") { + locText += " (Remote)" + } + lines = append(lines, "- **Location**: "+locText) + } else if jp.Remote { + lines = append(lines, "- **Location**: Remote") + } + if jp.EmploymentType != "" { + lines = append(lines, "- **Employment Type**: "+jp.EmploymentType) + } + if jp.Salary != "" { + lines = append(lines, "- **Compensation**: "+jp.Salary) + } + if jp.DatePosted != "" { + lines = append(lines, "- **Posted**: "+jp.DatePosted) + } + if jp.ValidThrough != "" { + lines = append(lines, "- **Closes**: "+jp.ValidThrough) + } + applyLink := wave3JobsFirstNonEmpty(jp.URL, wave3JobsSafeURL(baseURL, baseURL)) + if applyLink != "" { + lines = append(lines, "- **URL**: "+applyLink) + } + if jp.Description != "" { + lines = append(lines, "", "## Description", "", jp.Description) + } + rec := map[string]any{ + "title": jp.Title, + } + if jp.Company != "" { + rec["company"] = jp.Company + } + if len(jp.Locations) > 0 { + rec["location"] = strings.Join(jp.Locations, "; ") + } else if jp.Remote { + rec["location"] = "Remote" + } + if jp.Salary != "" { + rec["salary"] = jp.Salary + } + if jp.EmploymentType != "" { + rec["employmentType"] = jp.EmploymentType + } + if jp.DatePosted != "" { + rec["datePosted"] = jp.DatePosted + } + if applyLink != "" { + rec["url"] = applyLink + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: heading, + Author: jp.Company, + PublishedTime: jp.DatePosted, + Markdown: strings.Join(lines, "\n"), + Links: wave3JobsDedupLinks([]string{applyLink}, 10), + Records: []map[string]any{rec}, + Total: wave3JobsIntPtr(1), + Returned: wave3JobsIntPtr(1), + Truncated: wave3JobsBoolPtr(false), + } +} + +func wave3JobsBuildListingsResult(title, baseURL, extractorID string, recs []map[string]any, total int, links []string) *DeclarativePostFetchResult { + if len(recs) == 0 { + return nil + } + if total < len(recs) { + total = len(recs) + } + truncated := len(recs) > wave3JobsMaxRecords || total > wave3JobsMaxRecords + if len(recs) > wave3JobsMaxRecords { + recs = recs[:wave3JobsMaxRecords] + } + cleanTitle := wave3JobsCleanJobTitle(title) + if cleanTitle == "" { + cleanTitle = "Open Positions" + } + var lines []string + lines = append(lines, "# "+cleanTitle, "") + lines = append(lines, fmt.Sprintf("Showing %d of %d open roles.", len(recs), total), "") + lines = append(lines, "| Role | Company / Org | Location | Type | Posted |", "| --- | --- | --- | --- | --- |") + var collectedLinks []string + collectedLinks = append(collectedLinks, links...) + for _, r := range recs { + rTitle := wave3JobsEscapeMDCell(wave3JobsPlain(r["title"], 140)) + if rTitle == "" { + rTitle = "Open Role" + } + rURL := wave3JobsSafeURL(wave3JobsPlain(r["url"], 500), baseURL) + roleCell := rTitle + if rURL != "" { + roleCell = "[" + rTitle + "](" + rURL + ")" + collectedLinks = append(collectedLinks, rURL) + } + org := wave3JobsEscapeMDCell(wave3JobsFirstNonEmpty(wave3JobsPlain(r["company"], 100), wave3JobsPlain(r["department"], 100), "-")) + loc := wave3JobsEscapeMDCell(wave3JobsFirstNonEmpty(wave3JobsPlain(r["location"], 100), "-")) + emp := wave3JobsEscapeMDCell(wave3JobsFirstNonEmpty(wave3JobsPlain(r["employmentType"], 60), "-")) + posted := wave3JobsEscapeMDCell(wave3JobsFirstNonEmpty(wave3JobsPlain(r["datePosted"], 32), "-")) + lines = append(lines, fmt.Sprintf("| %s | %s | %s | %s | %s |", roleCell, org, loc, emp, posted)) + } + res := &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: cleanTitle, + Markdown: strings.Join(lines, "\n"), + Links: wave3JobsDedupLinks(collectedLinks, 30), + Records: recs, + Total: wave3JobsIntPtr(total), + Returned: wave3JobsIntPtr(len(recs)), + Truncated: wave3JobsBoolPtr(truncated), + } + if truncated { + res.NextCursor = strconv.Itoa(len(recs)) + } + return res +} + +func wave3JobsBuildListingsDoc(title, origURL string, recs []map[string]any, total int, links []string) *DeclarativeFormattedDoc { + if len(recs) == 0 { + return nil + } + if total < len(recs) { + total = len(recs) + } + truncated := len(recs) > wave3JobsMaxRecords || total > wave3JobsMaxRecords + if len(recs) > wave3JobsMaxRecords { + recs = recs[:wave3JobsMaxRecords] + } + cleanTitle := wave3JobsCleanJobTitle(title) + if cleanTitle == "" { + cleanTitle = "Open Positions" + } + var lines []string + lines = append(lines, "# "+cleanTitle, "") + lines = append(lines, fmt.Sprintf("Showing %d of %d open roles.", len(recs), total), "") + lines = append(lines, "| Role | Company / Org | Location | Type | Posted |", "| --- | --- | --- | --- | --- |") + var collectedLinks []string + collectedLinks = append(collectedLinks, links...) + for _, r := range recs { + rTitle := wave3JobsEscapeMDCell(wave3JobsPlain(r["title"], 140)) + if rTitle == "" { + rTitle = "Open Role" + } + rURL := wave3JobsSafeURL(wave3JobsPlain(r["url"], 500), origURL) + roleCell := rTitle + if rURL != "" { + roleCell = "[" + rTitle + "](" + rURL + ")" + collectedLinks = append(collectedLinks, rURL) + } + org := wave3JobsEscapeMDCell(wave3JobsFirstNonEmpty(wave3JobsPlain(r["company"], 100), wave3JobsPlain(r["department"], 100), "-")) + loc := wave3JobsEscapeMDCell(wave3JobsFirstNonEmpty(wave3JobsPlain(r["location"], 100), "-")) + emp := wave3JobsEscapeMDCell(wave3JobsFirstNonEmpty(wave3JobsPlain(r["employmentType"], 60), "-")) + posted := wave3JobsEscapeMDCell(wave3JobsFirstNonEmpty(wave3JobsPlain(r["datePosted"], 32), "-")) + lines = append(lines, fmt.Sprintf("| %s | %s | %s | %s | %s |", roleCell, org, loc, emp, posted)) + } + doc := &DeclarativeFormattedDoc{ + Title: cleanTitle, + Markdown: strings.Join(lines, "\n"), + Links: wave3JobsDedupLinks(collectedLinks, 30), + Records: recs, + Total: wave3JobsIntPtr(total), + Returned: wave3JobsIntPtr(len(recs)), + Truncated: wave3JobsBoolPtr(truncated), + } + if truncated { + doc.NextCursor = strconv.Itoa(len(recs)) + } + return doc +} + +func wave3JobsIsNextDataScriptAttr(attrStr string) bool { + if !wave3JobsContainsASCIIFold(attrStr, "__next_data__") { + return false + } + idVal, hasID := getAttrValueLinearDeclHTML(attrStr, "id") + return hasID && strings.TrimSpace(idVal) == "__NEXT_DATA__" +} + +func wave3JobsExtractNextData(rawHTML string) map[string]any { + if !wave3JobsContainsASCIIFold(rawHTML, "__next_data__") { + return nil + } + pos := 0 + for pos < len(rawHTML) { + open, ok := findOpenTagLinearDeclHTML(rawHTML, "script", wave3JobsIsNextDataScriptAttr, pos) + if !ok { + break + } + if open.selfClosing { + pos = open.openEnd + continue + } + closeStart, closeEnd, okClose := findCloseTagLinearDeclHTML(rawHTML, "script", open.openEnd) + if !okClose { + break + } + txt := strings.TrimSpace(rawHTML[open.openEnd:closeStart]) + pos = closeEnd + if txt == "" || len(txt) > 2*1024*1024 { + continue + } + parsed, okP := decodeJSONWithNumbers([]byte(txt)) + if okP { + if m := wave3JobsMap(parsed); m != nil { + return m + } + } + } + return nil +} + +func wave3JobsCollectJobArrayFromAny(v any, baseURL string, depth int) []map[string]any { + if v == nil || depth > 8 { + return nil + } + var out []map[string]any + switch tv := v.(type) { + case []any: + for _, el := range tv { + m := wave3JobsMap(el) + if m == nil { + continue + } + t := wave3JobsCleanJobTitle(wave3JobsFirstNonEmpty( + wave3JobsPlain(caseInsensitiveFieldM4(m, "title"), 180), + wave3JobsPlain(caseInsensitiveFieldM4(m, "position_name"), 180), + wave3JobsPlain(caseInsensitiveFieldM4(m, "job_title"), 180), + wave3JobsPlain(caseInsensitiveFieldM4(m, "name"), 180), + )) + if t == "" { + continue + } + rec := map[string]any{"title": t} + if org := wave3JobsFirstNonEmpty( + wave3JobsPlain(caseInsensitiveFieldM4(m, "company"), 100), + wave3JobsPlain(caseInsensitiveFieldM4(m, "organization_name"), 100), + wave3JobsPlain(caseInsensitiveFieldM4(m, "department"), 100), + ); org != "" { + rec["company"] = org + } + if loc := wave3JobsFirstNonEmpty( + wave3JobsPlain(caseInsensitiveFieldM4(m, "location"), 120), + wave3JobsPlain(caseInsensitiveFieldM4(m, "location_name"), 120), + wave3JobsPlain(caseInsensitiveFieldM4(m, "city"), 80), + ); loc != "" { + rec["location"] = loc + } + if emp := wave3JobsFirstNonEmpty( + wave3JobsPlain(caseInsensitiveFieldM4(m, "employmentType"), 60), + wave3JobsPlain(caseInsensitiveFieldM4(m, "employment_type"), 60), + wave3JobsPlain(caseInsensitiveFieldM4(m, "contract_details"), 60), + ); emp != "" { + rec["employmentType"] = emp + } + if dp := wave3JobsNormalizeDate(wave3JobsFirstNonEmpty( + wave3JobsPlain(caseInsensitiveFieldM4(m, "datePosted"), 40), + wave3JobsPlain(caseInsensitiveFieldM4(m, "posted_at"), 40), + wave3JobsPlain(caseInsensitiveFieldM4(m, "created_at"), 40), + )); dp != "" { + rec["datePosted"] = dp + } + if u := wave3JobsSafeURL(wave3JobsFirstNonEmpty( + wave3JobsPlain(caseInsensitiveFieldM4(m, "url"), 500), + wave3JobsPlain(caseInsensitiveFieldM4(m, "apply_url"), 500), + wave3JobsPlain(caseInsensitiveFieldM4(m, "job_url"), 500), + ), baseURL); u != "" { + rec["url"] = u + } + out = append(out, rec) + if len(out) >= 100 { + break + } + } + if len(out) > 0 { + return out + } + case map[string]any: + for _, k := range []string{"jobs", "jobListings", "results", "data", "postings", "openings", "positions", "requisitionList", "items"} { + if sub, ok := tv[k]; ok { + if found := wave3JobsCollectJobArrayFromAny(sub, baseURL, depth+1); len(found) > 0 { + return found + } + } + } + for _, k := range []string{"props", "pageProps", "initialState", "jobBoard", "careerPage", "data"} { + if sub := wave3JobsMap(tv[k]); sub != nil { + if found := wave3JobsCollectJobArrayFromAny(sub, baseURL, depth+1); len(found) > 0 { + return found + } + } + } + } + return nil +} + +// ── #226 NeoGov (`neogov_json` + `neogov_html`) ──────────────────────────────────────────────── + +func wave3JobsFormatNeoGovJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + var arr []any + total := 0 + title := "NeoGov Public Sector Jobs" + if sliceVal := wave3JobsSlice(parsed); sliceVal != nil { + arr = sliceVal + total = len(arr) + } else if m := wave3JobsMap(parsed); m != nil { + if wave3JobsHasJSONError(m) { + return nil, false + } + if ag := wave3JobsPlain(caseInsensitiveFieldM4(m, "agencyName"), 120); ag != "" { + title = ag + " — NeoGov Jobs" + } + for _, k := range []string{"jobs", "results", "data", "items", "jobPostings"} { + if s := wave3JobsSlice(caseInsensitiveFieldM4(m, k)); s != nil { + arr = s + break + } + } + if t, ok := wave3JobsIntFromAny(caseInsensitiveFieldM4(m, "totalCount")); ok && t > 0 { + total = t + } else if t, ok := wave3JobsIntFromAny(caseInsensitiveFieldM4(m, "total")); ok && t > 0 { + total = t + } + } + if len(arr) == 0 { + return nil, false + } + var recs []map[string]any + for _, el := range arr { + jm := wave3JobsMap(el) + if jm == nil { + continue + } + jt := wave3JobsCleanJobTitle(wave3JobsFirstNonEmpty( + wave3JobsPlain(caseInsensitiveFieldM4(jm, "title"), 180), + wave3JobsPlain(caseInsensitiveFieldM4(jm, "jobTitle"), 180), + wave3JobsPlain(caseInsensitiveFieldM4(jm, "Title"), 180), + )) + if jt == "" { + continue + } + rec := map[string]any{"title": jt} + if dept := wave3JobsFirstNonEmpty( + wave3JobsPlain(caseInsensitiveFieldM4(jm, "department"), 120), + wave3JobsPlain(caseInsensitiveFieldM4(jm, "agency"), 120), + ); dept != "" { + rec["company"] = dept + } + if loc := wave3JobsFirstNonEmpty( + wave3JobsPlain(caseInsensitiveFieldM4(jm, "location"), 120), + wave3JobsPlain(caseInsensitiveFieldM4(jm, "city"), 80), + ); loc != "" { + rec["location"] = loc + } + if emp := wave3JobsPlain(caseInsensitiveFieldM4(jm, "jobType"), 60); emp != "" { + rec["employmentType"] = emp + } + if dp := wave3JobsNormalizeDate(wave3JobsFirstNonEmpty( + wave3JobsPlain(caseInsensitiveFieldM4(jm, "postedDate"), 40), + wave3JobsPlain(caseInsensitiveFieldM4(jm, "openingDate"), 40), + )); dp != "" { + rec["datePosted"] = dp + } + if u := wave3JobsSafeURL(wave3JobsFirstNonEmpty( + wave3JobsPlain(caseInsensitiveFieldM4(jm, "url"), 500), + wave3JobsPlain(caseInsensitiveFieldM4(jm, "jobUrl"), 500), + ), origURL); u != "" { + rec["url"] = u + } + recs = append(recs, rec) + } + if len(recs) == 0 { + return nil, false + } + if total < len(recs) { + total = len(recs) + } + return wave3JobsBuildListingsDoc(title, origURL, recs, total, nil), true +} + +func wave3JobsExtractNeoGovHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + if !wave3JobsContainsASCIIFold(rawHTML, "governmentjobs") && + !wave3JobsContainsASCIIFold(rawHTML, "schooljobs") && + !wave3JobsContainsASCIIFold(rawHTML, "neogov") && + !wave3JobsContainsASCIIFold(rawHTML, "jobposting") && + !wave3JobsContainsASCIIFold(rawHTML, "job-listing") { + return nil + } + if postings := wave3JobsExtractJobPostingLDs(rawHTML); len(postings) > 0 { + if len(postings) == 1 { + if jp, ok := wave3JobsNormalizeJobPostingLD(postings[0], baseURL); ok { + return wave3JobsBuildPostingResult(jp, baseURL, extractorID) + } + } + var recs []map[string]any + for _, p := range postings { + if jp, ok := wave3JobsNormalizeJobPostingLD(p, baseURL); ok { + rec := map[string]any{"title": jp.Title} + if jp.Company != "" { + rec["company"] = jp.Company + } + if len(jp.Locations) > 0 { + rec["location"] = strings.Join(jp.Locations, "; ") + } + if jp.EmploymentType != "" { + rec["employmentType"] = jp.EmploymentType + } + if jp.DatePosted != "" { + rec["datePosted"] = jp.DatePosted + } + if jp.URL != "" { + rec["url"] = jp.URL + } + recs = append(recs, rec) + } + } + if len(recs) > 0 { + return wave3JobsBuildListingsResult("NeoGov Public Sector Jobs", baseURL, extractorID, recs, len(recs), nil) + } + } + + doc := ParseHTMLDoc(rawHTML, wave3JobsMaxHTMLBytes*2) + if doc == nil || wave3JobsIsEmptySPAShell(rawHTML, doc) { + return nil + } + + // Single job posting DOM fallback + var h1Title string + if h1 := doc.First("h1"); h1 != nil { + h1Title = wave3JobsCleanJobTitle(h1.Text()) + } + var descMD string + for _, sel := range []string{`#job-description`, `.job-description`, `[itemprop="description"]`, `main`} { + if el := doc.First(sel); el != nil { + cand := wave3JobsRichText(el.OuterHTML(), baseURL, 14000) + if len(cand) >= 40 { + descMD = cand + break + } + } + } + if h1Title != "" && descMD != "" && !wave3JobsContainsASCIIFold(baseURL, "/careers/") { + return wave3JobsBuildPostingResult(wave3JobPostingNorm{ + Title: h1Title, + Description: descMD, + URL: wave3JobsSafeURL(baseURL, baseURL), + }, baseURL, extractorID) + } + + // Board list DOM fallback (`.job-listing`, `li.list-item`, `a.item-details-link`, `[data-job-id]`) + var recs []map[string]any + for _, sel := range []string{`li.list-item`, `.job-listing`, `tr.job-item`, `[data-job-id]`} { + for _, item := range doc.Select(sel, 50) { + var jt, ju string + if a := item.First(`a`); a != nil { + jt = wave3JobsCleanJobTitle(a.Text()) + ju = wave3JobsSafeURL(wave3JobsAttr(a, "href"), baseURL) + } + if jt == "" { + if h := item.First(`h2, h3, .job-title`); h != nil { + jt = wave3JobsCleanJobTitle(h.Text()) + } + } + if jt == "" { + continue + } + rec := map[string]any{"title": jt} + if ju != "" { + rec["url"] = ju + } + if loc := item.First(`.job-location, .location`); loc != nil { + if lt := SanitizeSchemaPlainField(loc.Text(), 100); lt != "" { + rec["location"] = lt + } + } + if dept := item.First(`.department, .agency`); dept != nil { + if dt := SanitizeSchemaPlainField(dept.Text(), 100); dt != "" { + rec["company"] = dt + } + } + recs = append(recs, rec) + } + if len(recs) > 0 { + break + } + } + if len(recs) > 0 { + pageTitle := "" + if tEl := doc.First("title"); tEl != nil { + pageTitle = wave3JobsCleanPageTitle(tEl.Text()) + } + if pageTitle == "" { + pageTitle = wave3JobsFirstNonEmpty(h1Title, "NeoGov Public Sector Jobs") + } + return wave3JobsBuildListingsResult(pageTitle, baseURL, extractorID, recs, len(recs), nil) + } + if h1Title != "" && descMD != "" { + return wave3JobsBuildPostingResult(wave3JobPostingNorm{ + Title: h1Title, + Description: descMD, + URL: wave3JobsSafeURL(baseURL, baseURL), + }, baseURL, extractorID) + } + return nil +} + +// ── #227 Bullhorn Career Portal (`bullhorn_joborder_json` + `bullhorn_portal_html`) ─────────────── + +func wave3JobsFormatBullhornJSON(parsed any, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool) { + m := wave3JobsMap(parsed) + if m == nil || wave3JobsHasJSONError(m) { + return nil, false + } + dataVal := caseInsensitiveFieldM4(m, "data") + // Single JobOrder entity (`{"data": {"id": ..., "title": ...}}`) + if single := wave3JobsMap(dataVal); single != nil { + jt := wave3JobsCleanJobTitle(wave3JobsPlain(caseInsensitiveFieldM4(single, "title"), 200)) + if jt == "" { + return nil, false + } + loc := wave3JobsFormatBullhornAddress(caseInsensitiveFieldM4(single, "address")) + cat := "" + if pc := wave3JobsMap(caseInsensitiveFieldM4(single, "publishedCategory")); pc != nil { + cat = wave3JobsPlain(caseInsensitiveFieldM4(pc, "name"), 100) + } + emp := wave3JobsPlain(caseInsensitiveFieldM4(single, "employmentType"), 60) + posted := wave3JobsNormalizeTimestampUnix(caseInsensitiveFieldM4(single, "dateLastPublished")) + desc := wave3JobsRichText(jsonScalarToString(caseInsensitiveFieldM4(single, "publicDescription")), origURL, 14000) + var lines []string + lines = append(lines, "# "+jt, "") + if cat != "" { + lines = append(lines, "- **Category**: "+cat) + } + if loc != "" { + lines = append(lines, "- **Location**: "+loc) + } + if emp != "" { + lines = append(lines, "- **Employment Type**: "+emp) + } + if posted != "" { + lines = append(lines, "- **Published**: "+posted) + } + if desc != "" { + lines = append(lines, "", "## Description", "", desc) + } + rec := map[string]any{"title": jt} + if idStr := wave3JobsPlain(caseInsensitiveFieldM4(single, "id"), 40); idStr != "" { + rec["id"] = idStr + } + if loc != "" { + rec["location"] = loc + } + if emp != "" { + rec["employmentType"] = emp + } + if posted != "" { + rec["datePosted"] = posted + } + return &DeclarativeFormattedDoc{ + Title: jt, + PublishedTime: posted, + Markdown: strings.Join(lines, "\n"), + Records: []map[string]any{rec}, + Total: wave3JobsIntPtr(1), + Returned: wave3JobsIntPtr(1), + Truncated: wave3JobsBoolPtr(false), + }, true + } + + // Search/Query JobOrder list (`{"total": N, "data": [...]}`) + arr := wave3JobsSlice(dataVal) + if len(arr) == 0 { + return nil, false + } + total, okTot := wave3JobsIntFromAny(caseInsensitiveFieldM4(m, "total")) + if !okTot || total < len(arr) { + total = len(arr) + } + var recs []map[string]any + for _, el := range arr { + jm := wave3JobsMap(el) + if jm == nil { + continue + } + jt := wave3JobsCleanJobTitle(wave3JobsPlain(caseInsensitiveFieldM4(jm, "title"), 200)) + if jt == "" { + continue + } + rec := map[string]any{"title": jt} + if idStr := wave3JobsPlain(caseInsensitiveFieldM4(jm, "id"), 40); idStr != "" { + rec["id"] = idStr + } + if pc := wave3JobsMap(caseInsensitiveFieldM4(jm, "publishedCategory")); pc != nil { + if cn := wave3JobsPlain(caseInsensitiveFieldM4(pc, "name"), 100); cn != "" { + rec["department"] = cn + } + } + if loc := wave3JobsFormatBullhornAddress(caseInsensitiveFieldM4(jm, "address")); loc != "" { + rec["location"] = loc + } + if emp := wave3JobsPlain(caseInsensitiveFieldM4(jm, "employmentType"), 60); emp != "" { + rec["employmentType"] = emp + } + if dp := wave3JobsNormalizeTimestampUnix(caseInsensitiveFieldM4(jm, "dateLastPublished")); dp != "" { + rec["datePosted"] = dp + } + recs = append(recs, rec) + } + if len(recs) == 0 { + return nil, false + } + heading := "Bullhorn Career Portal — Open Jobs" + if cl := strings.TrimSpace(params["cluster"]); cl != "" { + heading = fmt.Sprintf("Bullhorn Career Portal (%s) — Open Jobs", cl) + } + return wave3JobsBuildListingsDoc(heading, origURL, recs, total, nil), true +} + +func wave3JobsFormatBullhornAddress(v any) string { + addr := wave3JobsMap(v) + if addr == nil { + return "" + } + var parts []string + for _, k := range []string{"city", "state", "countryName", "countryCode"} { + if p := wave3JobsPlain(caseInsensitiveFieldM4(addr, k), 60); p != "" { + if k == "countryCode" && len(parts) >= 2 { + continue + } + parts = append(parts, p) + } + } + return strings.Join(parts, ", ") +} + +func wave3JobsExtractBullhornHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + host := wave3JobsHostLower(baseURL) + if !strings.Contains(host, "bullhornstaffing.com") && + !wave3JobsContainsASCIIFold(rawHTML, "bullhorn") && + !wave3JobsContainsASCIIFold(rawHTML, "bh-career") && + !wave3JobsContainsASCIIFold(rawHTML, "oscp") { + return nil + } + if postings := wave3JobsExtractJobPostingLDs(rawHTML); len(postings) > 0 { + if jp, ok := wave3JobsNormalizeJobPostingLD(postings[0], baseURL); ok { + return wave3JobsBuildPostingResult(jp, baseURL, extractorID) + } + } + doc := ParseHTMLDoc(rawHTML, wave3JobsMaxHTMLBytes*2) + if doc == nil || wave3JobsIsEmptySPAShell(rawHTML, doc) { + return nil + } + var recs []map[string]any + for _, card := range doc.Select(`.job-board-card, .job-card, .bhi-job, li.job-item, [data-job-id]`, 40) { + var jt, ju string + if a := card.First(`a`); a != nil { + jt = wave3JobsCleanJobTitle(a.Text()) + ju = wave3JobsSafeURL(wave3JobsAttr(a, "href"), baseURL) + } + if jt == "" { + if h := card.First(`h2, h3, h4, .job-title`); h != nil { + jt = wave3JobsCleanJobTitle(h.Text()) + } + } + if jt == "" { + continue + } + rec := map[string]any{"title": jt} + if ju != "" { + rec["url"] = ju + } + if loc := card.First(`.location, .job-location`); loc != nil { + if lt := SanitizeSchemaPlainField(loc.Text(), 100); lt != "" { + rec["location"] = lt + } + } + recs = append(recs, rec) + } + if len(recs) > 0 { + return wave3JobsBuildListingsResult("Bullhorn Career Portal Jobs", baseURL, extractorID, recs, len(recs), nil) + } + if h1 := doc.First("h1"); h1 != nil { + if jt := wave3JobsCleanJobTitle(h1.Text()); jt != "" { + if descEl := doc.First(`.job-description, [itemprop="description"], main`); descEl != nil { + if desc := wave3JobsRichText(descEl.OuterHTML(), baseURL, 14000); len(desc) >= 40 { + return wave3JobsBuildPostingResult(wave3JobPostingNorm{ + Title: jt, + Description: desc, + URL: wave3JobsSafeURL(baseURL, baseURL), + }, baseURL, extractorID) + } + } + } + } + return nil +} + +// ── #228 Oracle Taleo (`taleo_full_html` SSR FreeMarker fallback) ────────────────────────────── + +func wave3JobsExtractTaleoHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + host := wave3JobsHostLower(baseURL) + if !strings.Contains(host, "taleo.net") && + !wave3JobsContainsASCIIFold(baseURL, "/careersection/") && + !wave3JobsContainsASCIIFold(rawHTML, "taleo") && + !wave3JobsContainsASCIIFold(rawHTML, "careersection") && + !wave3JobsContainsASCIIFold(rawHTML, "requisitionlist") && + !wave3JobsContainsASCIIFold(rawHTML, "jobposting") && + !wave3JobsContainsASCIIFold(rawHTML, "ftllist") { + return nil + } + if postings := wave3JobsExtractJobPostingLDs(rawHTML); len(postings) > 0 { + if jp, ok := wave3JobsNormalizeJobPostingLD(postings[0], baseURL); ok { + return wave3JobsBuildPostingResult(jp, baseURL, extractorID) + } + } + if fillRes := wave3JobsExtractTaleoFillList(rawHTML, baseURL, extractorID); fillRes != nil { + return fillRes + } + doc := ParseHTMLDoc(rawHTML, wave3JobsMaxHTMLBytes*2) + if doc == nil || wave3JobsIsEmptySPAShell(rawHTML, doc) { + return nil + } + + // Taleo FreeMarker job listing table / list (`.ftllist`, `#requisitionListInterface`, `span.titlelink a`) + var recs []map[string]any + for _, row := range doc.Select(`#requisitionListInterface tr.ftlrow, .ftllist tr, li.job-item, div.requisition`, 50) { + var jt, ju string + if a := row.First(`span.titlelink a, a.titlelink, h2 a, h3 a, a`); a != nil { + jt = wave3JobsCleanJobTitle(a.Text()) + ju = wave3JobsSafeURL(wave3JobsAttr(a, "href"), baseURL) + } + if jt == "" { + continue + } + rec := map[string]any{"title": jt} + if ju != "" { + rec["url"] = ju + } + if loc := row.First(`.location, span[id*="location"]`); loc != nil { + if lt := SanitizeSchemaPlainField(loc.Text(), 100); lt != "" { + rec["location"] = lt + } + } + if pd := row.First(`.postingdate, span[id*="postingDate"]`); pd != nil { + if pt := wave3JobsNormalizeDate(SanitizeSchemaPlainField(pd.Text(), 40)); pt != "" { + rec["datePosted"] = pt + } + } + recs = append(recs, rec) + } + if len(recs) > 0 { + host := wave3JobsHostLower(baseURL) + boardTitle := "Oracle Taleo Career Section" + if host != "" { + boardTitle = "Oracle Taleo Career Section — " + host + } + return wave3JobsBuildListingsResult(boardTitle, baseURL, extractorID, recs, len(recs), nil) + } + + // Taleo jobdetail.ftl page + var reqTitle string + for _, sel := range []string{`span#requisitionDescriptionInterface\.reqTitleLinkAction\.row1`, `h1.titlepage`, `.editablesection h1`, `h1`} { + if el := doc.First(sel); el != nil { + if cand := wave3JobsCleanJobTitle(el.Text()); cand != "" { + reqTitle = cand + break + } + } + } + if reqTitle != "" { + var descMD string + for _, sel := range []string{`#requisitionDescriptionInterface\.ID1458\.row1`, `.mastercontentpanel3`, `.contentlinepanel`, `main`} { + if el := doc.First(sel); el != nil { + cand := wave3JobsRichText(el.OuterHTML(), baseURL, 14000) + if len(cand) >= 40 { + descMD = cand + break + } + } + } + if descMD != "" { + return wave3JobsBuildPostingResult(wave3JobPostingNorm{ + Title: reqTitle, + Description: descMD, + URL: wave3JobsSafeURL(baseURL, baseURL), + }, baseURL, extractorID) + } + } + return nil +} + +func wave3JobsIsASCIIDigits(s string) bool { + if len(s) == 0 { + return false + } + for i := 0; i < len(s); i++ { + if s[i] < '0' || s[i] > '9' { + return false + } + } + return true +} + +func wave3JobsExtractFillListArgs(rawHTML, ifaceMarker, listMarker string) []string { + idx := strings.Index(rawHTML, ifaceMarker) + if idx < 0 { + return nil + } + sub := rawHTML[idx+len(ifaceMarker):] + if len(sub) > 256*1024 { + sub = sub[:256*1024] + } + arrStart := strings.IndexByte(sub, '[') + if arrStart < 0 || arrStart > 160 { + return nil + } + if listMarker != "" && !strings.Contains(sub[:arrStart], listMarker) { + return nil + } + s := sub[arrStart+1:] + var args []string + i := 0 + for i < len(s) && len(args) < 4096 { + for i < len(s) && (s[i] == ' ' || s[i] == ',' || s[i] == '\n' || s[i] == '\r' || s[i] == '\t') { + i++ + } + if i >= len(s) || s[i] == ']' { + break + } + q := s[i] + if q != '\'' && q != '"' { + end := strings.IndexAny(s[i:], ",]") + if end < 0 { + break + } + args = append(args, strings.TrimSpace(s[i:i+end])) + i += end + continue + } + i++ + var buf strings.Builder + for i < len(s) { + ch := s[i] + if ch == '\\' && i+1 < len(s) { + next := s[i+1] + switch next { + case 'n': + buf.WriteByte('\n') + case 'r': + buf.WriteByte('\r') + case 't': + buf.WriteByte('\t') + default: + buf.WriteByte(next) + } + i += 2 + continue + } + if ch == q { + i++ + break + } + buf.WriteByte(ch) + i++ + } + rawVal := buf.String() + if unesc, err := url.PathUnescape(rawVal); err == nil { + args = append(args, unesc) + } else { + args = append(args, rawVal) + } + } + return args +} + +func wave3JobsTaleoCareerSectionPrefix(baseURL string) string { + bu, err := url.Parse(baseURL) + if err != nil { + return "/careersection/" + } + lowPath := strings.ToLower(bu.Path) + idx := strings.Index(lowPath, "/careersection/") + if idx < 0 { + return "/careersection/" + } + rest := bu.Path[idx+len("/careersection/"):] + parts := strings.Split(strings.TrimLeft(rest, "/"), "/") + if len(parts) >= 2 && parts[0] != "" && !strings.HasSuffix(strings.ToLower(parts[0]), ".ftl") && !strings.EqualFold(parts[0], "rest") { + return "/careersection/" + parts[0] + "/" + } + return "/careersection/" +} + +func wave3JobsExtractTaleoFillList(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + if !strings.Contains(rawHTML, "fillList(") { + return nil + } + if args := wave3JobsExtractFillListArgs(rawHTML, "fillList('requisitionDescriptionInterface'", "'descRequisition'"); len(args) >= 12 { + var title string + if len(args) > 9 { + title = wave3JobsCleanJobTitle(args[9]) + } + if title == "" { + for _, a := range args { + if strings.HasPrefix(a, "Submission for the position: ") { + cand := strings.TrimPrefix(a, "Submission for the position: ") + if cut := strings.Index(cand, " - (Job Number:"); cut > 0 { + cand = cand[:cut] + } + if t := wave3JobsCleanJobTitle(cand); t != "" { + title = t + break + } + } + } + } + var blocks []string + seenBlocks := make(map[string]bool) + for _, a := range args { + if !strings.HasPrefix(a, "!*!") { + continue + } + frag := strings.TrimSpace(strings.TrimPrefix(a, "!*!")) + if frag == "" || seenBlocks[frag] { + continue + } + seenBlocks[frag] = true + if txt := wave3JobsLinearHTMLToText(frag, 12000); txt != "" { + blocks = append(blocks, txt) + } + if len(blocks) >= 3 { + break + } + } + if title != "" && len(blocks) > 0 { + var datePosted, validThrough, salary, payBasis string + for k := 12; k < len(args); k++ { + a := strings.TrimSpace(args[k]) + if a == "" { + continue + } + if d := wave3JobsNormalizeDate(a); d != "" { + if datePosted == "" { + datePosted = d + } else if validThrough == "" && d != datePosted { + validThrough = d + } + continue + } + if salary == "" && strings.Contains(a, "$") && len(a) <= 60 { + salary = SanitizeSchemaPlainField(a, 60) + continue + } + if salary != "" && payBasis == "" && (a == "Yearly" || a == "Hourly" || a == "Monthly" || a == "Biweekly") { + payBasis = a + } + } + if salary != "" && payBasis != "" && !strings.Contains(strings.ToLower(salary), strings.ToLower(payBasis)) { + salary = salary + " (" + payBasis + ")" + } + return wave3JobsBuildPostingResult(wave3JobPostingNorm{ + Title: title, + Salary: salary, + DatePosted: datePosted, + ValidThrough: validThrough, + URL: wave3JobsSafeURL(baseURL, baseURL), + Description: strings.Join(blocks, "\n\n"), + }, baseURL, extractorID) + } + } + + if args := wave3JobsExtractFillListArgs(rawHTML, "fillList('requisitionListInterface'", "'listRequisition'"); len(args) >= 12 { + csPrefix := wave3JobsTaleoCareerSectionPrefix(baseURL) + bu, _ := url.Parse(baseURL) + var recs []map[string]any + seenJob := make(map[string]bool) + for i := 0; i+11 < len(args); i++ { + jobID := strings.TrimSpace(args[i]) + if len(jobID) < 3 || len(jobID) > 16 || !wave3JobsIsASCIIDigits(jobID) { + continue + } + if strings.TrimSpace(args[i+2]) != jobID || strings.TrimSpace(args[i+1]) == "" || args[i+1] != args[i+3] { + continue + } + if seenJob[jobID] { + continue + } + jt := wave3JobsCleanJobTitle(args[i+1]) + if jt == "" { + continue + } + seenJob[jobID] = true + rec := map[string]any{"title": jt, "id": jobID} + if bu != nil && bu.Host != "" { + rec["url"] = fmt.Sprintf("https://%s%sjobdetail.ftl?job=%s", bu.Host, csPrefix, url.QueryEscape(jobID)) + } + for k := i + 4; k < len(args) && k <= i+18; k++ { + if rec["datePosted"] == nil { + if d := wave3JobsNormalizeDate(args[k]); d != "" { + rec["datePosted"] = d + continue + } + } + if rec["salary"] == nil && strings.Contains(args[k], "$") && len(args[k]) <= 60 { + rec["salary"] = SanitizeSchemaPlainField(args[k], 60) + } + } + recs = append(recs, rec) + if len(recs) >= wave3JobsMaxRecords { + break + } + } + if len(recs) > 0 { + host := wave3JobsHostLower(baseURL) + boardTitle := "Oracle Taleo Career Section" + if host != "" { + boardTitle = "Oracle Taleo Career Section — " + host + } + return wave3JobsBuildListingsResult(boardTitle, baseURL, extractorID, recs, len(recs), nil) + } + } + return nil +} + +// ── #229 Paradox Olivia (`paradox_olivia_html`) ──────────────────────────────────────────────── + +func wave3JobsExtractParadoxHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + host := wave3JobsHostLower(baseURL) + isParadoxHost := strings.Contains(host, "paradox.ai") || strings.Contains(host, "mchire.com") + probe := rawHTML + if len(probe) > 131_072 { + probe = probe[:131_072] + } + probeLower := asciiLowerExtractString(probe) + hasParadoxSig := strings.Contains(probeLower, "paradox.ai") || + strings.Contains(probeLower, "mchire") || + (strings.Contains(probeLower, "olivia") && (strings.Contains(probeLower, "paradox") || strings.Contains(probeLower, "jobposting") || strings.Contains(probeLower, "__next_data__"))) || + (strings.Contains(probeLower, "paradox") && (strings.Contains(probeLower, "jobposting") || strings.Contains(probeLower, "careers"))) + if !isParadoxHost && !hasParadoxSig { + return nil + } + + if postings := wave3JobsExtractJobPostingLDs(rawHTML); len(postings) > 0 { + if len(postings) == 1 { + if jp, ok := wave3JobsNormalizeJobPostingLD(postings[0], baseURL); ok { + return wave3JobsBuildPostingResult(jp, baseURL, extractorID) + } + } + var recs []map[string]any + for _, p := range postings { + if jp, ok := wave3JobsNormalizeJobPostingLD(p, baseURL); ok { + rec := map[string]any{"title": jp.Title} + if jp.Company != "" { + rec["company"] = jp.Company + } + if len(jp.Locations) > 0 { + rec["location"] = strings.Join(jp.Locations, "; ") + } + if jp.EmploymentType != "" { + rec["employmentType"] = jp.EmploymentType + } + if jp.DatePosted != "" { + rec["datePosted"] = jp.DatePosted + } + if jp.URL != "" { + rec["url"] = jp.URL + } + recs = append(recs, rec) + } + } + if len(recs) > 0 { + return wave3JobsBuildListingsResult("Paradox Olivia Career Portal", baseURL, extractorID, recs, len(recs), nil) + } + } + + if nextData := wave3JobsExtractNextData(rawHTML); nextData != nil { + if recs := wave3JobsCollectJobArrayFromAny(nextData, baseURL, 0); len(recs) > 0 { + return wave3JobsBuildListingsResult("Paradox Olivia Career Portal", baseURL, extractorID, recs, len(recs), nil) + } + } + + doc := ParseHTMLDoc(rawHTML, wave3JobsMaxHTMLBytes*2) + if doc == nil || wave3JobsIsEmptySPAShell(rawHTML, doc) { + return nil + } + var recs []map[string]any + for _, card := range doc.Select(`[data-testid*="job"], .job-card, .job-item, li.job-listing`, 40) { + var jt, ju string + if a := card.First(`a`); a != nil { + jt = wave3JobsCleanJobTitle(a.Text()) + ju = wave3JobsSafeURL(wave3JobsAttr(a, "href"), baseURL) + } + if jt == "" { + if h := card.First(`h2, h3, .job-title`); h != nil { + jt = wave3JobsCleanJobTitle(h.Text()) + } + } + if jt == "" { + continue + } + rec := map[string]any{"title": jt} + if ju != "" { + rec["url"] = ju + } + if loc := card.First(`.location, [data-testid*="location"]`); loc != nil { + if lt := SanitizeSchemaPlainField(loc.Text(), 100); lt != "" { + rec["location"] = lt + } + } + recs = append(recs, rec) + } + if len(recs) > 0 { + pageTitle := "" + if tEl := doc.First("title"); tEl != nil { + pageTitle = wave3JobsCleanPageTitle(tEl.Text()) + } + if pageTitle == "" { + pageTitle = "Paradox Olivia Career Portal" + } + return wave3JobsBuildListingsResult(pageTitle, baseURL, extractorID, recs, len(recs), nil) + } + return nil +} + +// ── #230 Staffing ATS Pack (`staffing_ats_json` + `staffing_ats_pack_html`) ──────────────────── + +func wave3JobsFormatStaffingJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + if m := wave3JobsMap(parsed); m != nil && wave3JobsHasJSONError(m) { + return nil, false + } + recs := wave3JobsCollectJobArrayFromAny(parsed, origURL, 0) + if len(recs) == 0 { + return nil, false + } + total := len(recs) + if m := wave3JobsMap(parsed); m != nil { + for _, k := range []string{"total", "totalCount", "count"} { + if t, ok := wave3JobsIntFromAny(caseInsensitiveFieldM4(m, k)); ok && t > total { + total = t + break + } + } + } + return wave3JobsBuildListingsDoc("Staffing ATS Open Roles", origURL, recs, total, nil), true +} + +func wave3JobsExtractStaffingATSPackHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + host := wave3JobsHostLower(baseURL) + isKnownHost := strings.Contains(host, "crelate.com") || strings.Contains(host, "jobdiva.com") || strings.Contains(host, "ceipal.com") + if !isKnownHost && + !wave3JobsContainsASCIIFold(rawHTML, "crelate") && + !wave3JobsContainsASCIIFold(rawHTML, "jobdiva") && + !wave3JobsContainsASCIIFold(rawHTML, "ceipal") { + return nil + } + if postings := wave3JobsExtractJobPostingLDs(rawHTML); len(postings) > 0 { + if len(postings) == 1 { + if jp, ok := wave3JobsNormalizeJobPostingLD(postings[0], baseURL); ok { + return wave3JobsBuildPostingResult(jp, baseURL, extractorID) + } + } + var recs []map[string]any + for _, p := range postings { + if jp, ok := wave3JobsNormalizeJobPostingLD(p, baseURL); ok { + rec := map[string]any{"title": jp.Title} + if jp.Company != "" { + rec["company"] = jp.Company + } + if len(jp.Locations) > 0 { + rec["location"] = strings.Join(jp.Locations, "; ") + } + if jp.EmploymentType != "" { + rec["employmentType"] = jp.EmploymentType + } + if jp.URL != "" { + rec["url"] = jp.URL + } + recs = append(recs, rec) + } + } + if len(recs) > 0 { + return wave3JobsBuildListingsResult("Staffing ATS Open Roles", baseURL, extractorID, recs, len(recs), nil) + } + } + + if nextData := wave3JobsExtractNextData(rawHTML); nextData != nil { + if recs := wave3JobsCollectJobArrayFromAny(nextData, baseURL, 0); len(recs) > 0 { + return wave3JobsBuildListingsResult("Staffing ATS Open Roles", baseURL, extractorID, recs, len(recs), nil) + } + } + + doc := ParseHTMLDoc(rawHTML, wave3JobsMaxHTMLBytes*2) + if doc == nil || wave3JobsIsEmptySPAShell(rawHTML, doc) { + return nil + } + var recs []map[string]any + for _, card := range doc.Select(`.portal-job, .job-listing, .job-item, .job-card, tr.job-row, #openjobs tr`, 50) { + var jt, ju string + if a := card.First(`a`); a != nil { + jt = wave3JobsCleanJobTitle(a.Text()) + ju = wave3JobsSafeURL(wave3JobsAttr(a, "href"), baseURL) + } + if jt == "" { + if h := card.First(`h2, h3, .job-title`); h != nil { + jt = wave3JobsCleanJobTitle(h.Text()) + } + } + if jt == "" { + continue + } + rec := map[string]any{"title": jt} + if ju != "" { + rec["url"] = ju + } + if loc := card.First(`.location, .job-location`); loc != nil { + if lt := SanitizeSchemaPlainField(loc.Text(), 100); lt != "" { + rec["location"] = lt + } + } + recs = append(recs, rec) + } + if len(recs) > 0 { + return wave3JobsBuildListingsResult("Staffing ATS Open Roles", baseURL, extractorID, recs, len(recs), nil) + } + if h1 := doc.First("h1"); h1 != nil { + if jt := wave3JobsCleanJobTitle(h1.Text()); jt != "" { + if descEl := doc.First(`.job-description, [itemprop="description"], main`); descEl != nil { + if desc := wave3JobsRichText(descEl.OuterHTML(), baseURL, 14000); len(desc) >= 40 { + return wave3JobsBuildPostingResult(wave3JobPostingNorm{ + Title: jt, + Description: desc, + URL: wave3JobsSafeURL(baseURL, baseURL), + }, baseURL, extractorID) + } + } + } + } + return nil +} + +// ── #231 SMB ATS Full (`manatal_jobs_json`, `smb_ats_json`, `smb_ats_full_html`) ────────────── + +func wave3JobsFormatManatalJSON(parsed any, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool) { + m := wave3JobsMap(parsed) + if m == nil || wave3JobsHasJSONError(m) { + return nil, false + } + // Single Manatal job object + if posName := wave3JobsCleanJobTitle(wave3JobsPlain(caseInsensitiveFieldM4(m, "position_name"), 200)); posName != "" { + org := wave3JobsPlain(caseInsensitiveFieldM4(m, "organization_name"), 120) + loc := wave3JobsFormatManatalLocation(m) + emp := wave3JobsPlain(caseInsensitiveFieldM4(m, "contract_details"), 60) + posted := wave3JobsNormalizeDate(wave3JobsPlain(caseInsensitiveFieldM4(m, "created_at"), 40)) + desc := wave3JobsRichText(jsonScalarToString(caseInsensitiveFieldM4(m, "description")), origURL, 14000) + heading := posName + if org != "" { + heading = posName + " — " + org + } + var lines []string + lines = append(lines, "# "+heading, "") + if org != "" { + lines = append(lines, "- **Company**: "+org) + } + if loc != "" { + lines = append(lines, "- **Location**: "+loc) + } + if emp != "" { + lines = append(lines, "- **Contract**: "+emp) + } + if posted != "" { + lines = append(lines, "- **Posted**: "+posted) + } + if desc != "" { + lines = append(lines, "", "## Description", "", desc) + } + rec := map[string]any{"title": posName} + if org != "" { + rec["company"] = org + } + if loc != "" { + rec["location"] = loc + } + if emp != "" { + rec["employmentType"] = emp + } + if posted != "" { + rec["datePosted"] = posted + } + return &DeclarativeFormattedDoc{ + Title: heading, + Author: org, + PublishedTime: posted, + Markdown: strings.Join(lines, "\n"), + Records: []map[string]any{rec}, + Total: wave3JobsIntPtr(1), + Returned: wave3JobsIntPtr(1), + Truncated: wave3JobsBoolPtr(false), + }, true + } + + arr := wave3JobsSlice(caseInsensitiveFieldM4(m, "results")) + if len(arr) == 0 { + return nil, false + } + total, okTot := wave3JobsIntFromAny(caseInsensitiveFieldM4(m, "count")) + if !okTot || total < len(arr) { + total = len(arr) + } + var recs []map[string]any + firstOrg := "" + for _, el := range arr { + jm := wave3JobsMap(el) + if jm == nil { + continue + } + jt := wave3JobsCleanJobTitle(wave3JobsFirstNonEmpty( + wave3JobsPlain(caseInsensitiveFieldM4(jm, "position_name"), 200), + wave3JobsPlain(caseInsensitiveFieldM4(jm, "title"), 200), + )) + if jt == "" { + continue + } + rec := map[string]any{"title": jt} + if idStr := wave3JobsPlain(caseInsensitiveFieldM4(jm, "id"), 40); idStr != "" { + rec["id"] = idStr + } + if org := wave3JobsPlain(caseInsensitiveFieldM4(jm, "organization_name"), 120); org != "" { + rec["company"] = org + if firstOrg == "" { + firstOrg = org + } + } + if loc := wave3JobsFormatManatalLocation(jm); loc != "" { + rec["location"] = loc + } + if emp := wave3JobsPlain(caseInsensitiveFieldM4(jm, "contract_details"), 60); emp != "" { + rec["employmentType"] = emp + } + if dp := wave3JobsNormalizeDate(wave3JobsPlain(caseInsensitiveFieldM4(jm, "created_at"), 40)); dp != "" { + rec["datePosted"] = dp + } + if hash := wave3JobsPlain(caseInsensitiveFieldM4(jm, "hash"), 40); hash != "" { + slug := strings.TrimSpace(params["slug"]) + if slug != "" { + rec["url"] = fmt.Sprintf("https://jobs.manatal.com/%s/jobs/%s", url.PathEscape(slug), url.PathEscape(hash)) + } + } + recs = append(recs, rec) + } + if len(recs) == 0 { + return nil, false + } + heading := "Manatal Career Page" + if firstOrg != "" { + heading = firstOrg + " — Open Roles" + } else if slug := strings.TrimSpace(params["slug"]); slug != "" { + heading = slug + " — Open Roles" + } + doc := wave3JobsBuildListingsDoc(heading, origURL, recs, total, nil) + if doc != nil { + if nextURL := wave3JobsSafeURL(wave3JobsPlain(caseInsensitiveFieldM4(m, "next"), 500), origURL); nextURL != "" { + doc.NextCursor = nextURL + doc.Truncated = wave3JobsBoolPtr(true) + } + } + return doc, true +} + +func wave3JobsFormatManatalLocation(jm map[string]any) string { + var parts []string + for _, k := range []string{"city", "state", "country"} { + if p := wave3JobsPlain(caseInsensitiveFieldM4(jm, k), 60); p != "" { + parts = append(parts, p) + } + } + if len(parts) == 0 { + if ld := wave3JobsPlain(caseInsensitiveFieldM4(jm, "location_display"), 120); ld != "" { + parts = append(parts, ld) + } + } + if rem, ok := caseInsensitiveFieldM4(jm, "is_remote").(bool); ok && rem { + if len(parts) > 0 { + return strings.Join(parts, ", ") + " (Remote)" + } + return "Remote" + } + return strings.Join(parts, ", ") +} + +func wave3JobsFormatSMBAtsJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + if m := wave3JobsMap(parsed); m != nil && wave3JobsHasJSONError(m) { + return nil, false + } + recs := wave3JobsCollectJobArrayFromAny(parsed, origURL, 0) + if len(recs) == 0 { + return nil, false + } + return wave3JobsBuildListingsDoc("SMB ATS Open Roles", origURL, recs, len(recs), nil), true +} + +func wave3JobsExtractSMBAtsFullHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + if postings := wave3JobsExtractJobPostingLDs(rawHTML); len(postings) > 0 { + if len(postings) == 1 { + if jp, ok := wave3JobsNormalizeJobPostingLD(postings[0], baseURL); ok { + return wave3JobsBuildPostingResult(jp, baseURL, extractorID) + } + } + var recs []map[string]any + for _, p := range postings { + if jp, ok := wave3JobsNormalizeJobPostingLD(p, baseURL); ok { + rec := map[string]any{"title": jp.Title} + if jp.Company != "" { + rec["company"] = jp.Company + } + if len(jp.Locations) > 0 { + rec["location"] = strings.Join(jp.Locations, "; ") + } + if jp.EmploymentType != "" { + rec["employmentType"] = jp.EmploymentType + } + if jp.URL != "" { + rec["url"] = jp.URL + } + recs = append(recs, rec) + } + } + if len(recs) > 0 { + return wave3JobsBuildListingsResult("Open Positions", baseURL, extractorID, recs, len(recs), nil) + } + } + doc := ParseHTMLDoc(rawHTML, wave3JobsMaxHTMLBytes*2) + if doc == nil || wave3JobsIsEmptySPAShell(rawHTML, doc) { + return nil + } + var recs []map[string]any + for _, card := range doc.Select(`.job-list-item, .vacancy-item, .job-opening, li.job, tr.jobRow`, 50) { + var jt, ju string + if a := card.First(`a`); a != nil { + jt = wave3JobsCleanJobTitle(a.Text()) + ju = wave3JobsSafeURL(wave3JobsAttr(a, "href"), baseURL) + } + if jt == "" { + continue + } + rec := map[string]any{"title": jt} + if ju != "" { + rec["url"] = ju + } + if loc := card.First(`.location, .job-location`); loc != nil { + if lt := SanitizeSchemaPlainField(loc.Text(), 100); lt != "" { + rec["location"] = lt + } + } + recs = append(recs, rec) + } + if len(recs) > 0 { + return wave3JobsBuildListingsResult("Open Positions", baseURL, extractorID, recs, len(recs), nil) + } + if h1 := doc.First("h1"); h1 != nil { + if jt := wave3JobsCleanJobTitle(h1.Text()); jt != "" { + if descEl := doc.First(`.job-description, [itemprop="description"], main`); descEl != nil { + if desc := wave3JobsRichText(descEl.OuterHTML(), baseURL, 14000); len(desc) >= 40 { + return wave3JobsBuildPostingResult(wave3JobPostingNorm{ + Title: jt, + Description: desc, + URL: wave3JobsSafeURL(baseURL, baseURL), + }, baseURL, extractorID) + } + } + } + } + return nil +} + +// ── #232 Education Job Boards (`edu_job_boards_html`) ────────────────────────────────────────── + +func wave3JobsExtractEduJobBoardsHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + if postings := wave3JobsExtractJobPostingLDs(rawHTML); len(postings) > 0 { + if len(postings) == 1 { + if jp, ok := wave3JobsNormalizeJobPostingLD(postings[0], baseURL); ok { + return wave3JobsBuildPostingResult(jp, baseURL, extractorID) + } + } + var recs []map[string]any + for _, p := range postings { + if jp, ok := wave3JobsNormalizeJobPostingLD(p, baseURL); ok { + rec := map[string]any{"title": jp.Title} + if jp.Company != "" { + rec["company"] = jp.Company + } + if len(jp.Locations) > 0 { + rec["location"] = strings.Join(jp.Locations, "; ") + } + if jp.EmploymentType != "" { + rec["employmentType"] = jp.EmploymentType + } + if jp.DatePosted != "" { + rec["datePosted"] = jp.DatePosted + } + if jp.URL != "" { + rec["url"] = jp.URL + } + recs = append(recs, rec) + } + } + if len(recs) > 0 { + return wave3JobsBuildListingsResult("Education Job Board", baseURL, extractorID, recs, len(recs), nil) + } + } + + doc := ParseHTMLDoc(rawHTML, wave3JobsMaxHTMLBytes*2) + if doc == nil || wave3JobsIsEmptySPAShell(rawHTML, doc) { + return nil + } + + // Reject unhydrated EdJoin / K12JobSpot CSR Underscore templates (`<%- item.postingID %>` with no real jobs) + var recs []map[string]any + for _, card := range doc.Select(`.lister__item, .job-listing, .job-card, .posting-card, .job-row, table.jobs tr`, 50) { + txt := card.Text() + if strings.Contains(txt, "<%-") || strings.Contains(txt, "<%=") { + continue + } + var jt, ju string + if a := card.First(`a.lister__view-details, h3 a, h2 a, a.job-title, a`); a != nil { + jt = wave3JobsCleanJobTitle(a.Text()) + ju = wave3JobsSafeURL(wave3JobsAttr(a, "href"), baseURL) + } + if jt == "" { + if h := card.First(`h2, h3, .job-title`); h != nil { + jt = wave3JobsCleanJobTitle(h.Text()) + } + } + if jt == "" || strings.Contains(jt, "<%") { + continue + } + rec := map[string]any{"title": jt} + if ju != "" { + rec["url"] = ju + } + if org := card.First(`.lister__meta-item--recruiter, .employer, .district-name, .company`); org != nil { + if ot := SanitizeSchemaPlainField(org.Text(), 100); ot != "" && !strings.Contains(ot, "<%") { + rec["company"] = ot + } + } + if loc := card.First(`.lister__meta-item--location, .location, .job-location`); loc != nil { + if lt := SanitizeSchemaPlainField(loc.Text(), 100); lt != "" && !strings.Contains(lt, "<%") { + rec["location"] = lt + } + } + recs = append(recs, rec) + } + if len(recs) > 0 { + pageTitle := "" + if tEl := doc.First("title"); tEl != nil { + pageTitle = wave3JobsCleanPageTitle(tEl.Text()) + } + if pageTitle == "" { + pageTitle = "Education Job Board" + } + return wave3JobsBuildListingsResult(pageTitle, baseURL, extractorID, recs, len(recs), nil) + } + + // Single posting DOM fallback (Chronicle / HigherEdJobs / K12JobSpot / EdJoin detail page) + if h1 := doc.First("h1"); h1 != nil { + if jt := wave3JobsCleanJobTitle(h1.Text()); jt != "" && !strings.Contains(jt, "<%") { + for _, sel := range []string{`.mds-prose`, `#jobDesc`, `.job-description`, `[itemprop="description"]`, `main`} { + if el := doc.First(sel); el != nil { + desc := wave3JobsRichText(el.OuterHTML(), baseURL, 14000) + if len(desc) >= 40 && !strings.Contains(desc, "<%- item.") { + return wave3JobsBuildPostingResult(wave3JobPostingNorm{ + Title: jt, + Description: desc, + URL: wave3JobsSafeURL(baseURL, baseURL), + }, baseURL, extractorID) + } + } + } + } + } + return nil +} + +// ── #233 Healthcare Careers (`healthcare_careers_html`) ──────────────────────────────────────── + +func wave3JobsExtractHealthcareCareersHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + host := wave3JobsHostLower(baseURL) + if host == "careers.symplr.com" { + return nil + } + isKnownHost := strings.Contains(host, "healthcaresource.com") || host == "www.symplr.com" || host == "symplr.com" + if !isKnownHost { + // Never hijack Paradox Olivia career portals or arbitrary hosts with a stray symplr/healthcaresource mention. + if strings.Contains(host, "paradox.ai") || + strings.Contains(host, "mchire.com") || + wave3JobsContainsASCIIFold(rawHTML, "paradox.ai") || + wave3JobsContainsASCIIFold(rawHTML, "olivia.js") || + wave3JobsContainsASCIIFold(rawHTML, "mchire") || + (wave3JobsContainsASCIIFold(rawHTML, "olivia") && (wave3JobsContainsASCIIFold(rawHTML, "paradox") || wave3JobsContainsASCIIFold(rawHTML, "__next_data__"))) { + return nil + } + hasPortalDomainRef := wave3JobsContainsASCIIFold(rawHTML, "healthcaresource.com") || + wave3JobsContainsASCIIFold(rawHTML, "symplr.com/") + hasVendorWord := wave3JobsContainsASCIIFold(rawHTML, "healthcaresource") || + wave3JobsContainsASCIIFold(rawHTML, "symplr") + hasPortalDOMSig := wave3JobsContainsASCIIFold(rawHTML, `id="jobtitle"`) || + wave3JobsContainsASCIIFold(rawHTML, `id='jobtitle'`) || + wave3JobsContainsASCIIFold(rawHTML, `id="jobdescription"`) || + wave3JobsContainsASCIIFold(rawHTML, `id='jobdescription'`) || + wave3JobsContainsASCIIFold(rawHTML, "jobrow") || + wave3JobsContainsASCIIFold(rawHTML, "hc-careers") || + wave3JobsContainsASCIIFold(rawHTML, "symplr-careers") || + wave3JobsContainsASCIIFold(rawHTML, "symplr talent") + if !hasPortalDomainRef && !(hasVendorWord && hasPortalDOMSig) { + return nil + } + } + if postings := wave3JobsExtractJobPostingLDs(rawHTML); len(postings) > 0 { + if len(postings) == 1 { + if jp, ok := wave3JobsNormalizeJobPostingLD(postings[0], baseURL); ok { + return wave3JobsBuildPostingResult(jp, baseURL, extractorID) + } + } + var recs []map[string]any + for _, p := range postings { + if jp, ok := wave3JobsNormalizeJobPostingLD(p, baseURL); ok { + rec := map[string]any{"title": jp.Title} + if jp.Company != "" { + rec["company"] = jp.Company + } + if len(jp.Locations) > 0 { + rec["location"] = strings.Join(jp.Locations, "; ") + } + if jp.EmploymentType != "" { + rec["employmentType"] = jp.EmploymentType + } + if jp.URL != "" { + rec["url"] = jp.URL + } + recs = append(recs, rec) + } + } + if len(recs) > 0 { + return wave3JobsBuildListingsResult("Healthcare Career Portal", baseURL, extractorID, recs, len(recs), nil) + } + } + + doc := ParseHTMLDoc(rawHTML, wave3JobsMaxHTMLBytes*2) + if doc == nil || wave3JobsIsEmptySPAShell(rawHTML, doc) { + return nil + } + var recs []map[string]any + for _, card := range doc.Select(`.job-posting, .job-listing, .job-card, tr.jobRow, li.job-item`, 50) { + var jt, ju string + if a := card.First(`a`); a != nil { + jt = wave3JobsCleanJobTitle(a.Text()) + ju = wave3JobsSafeURL(wave3JobsAttr(a, "href"), baseURL) + } + if jt == "" { + if h := card.First(`h2, h3, .job-title, #jobTitle`); h != nil { + jt = wave3JobsCleanJobTitle(h.Text()) + } + } + if jt == "" { + continue + } + rec := map[string]any{"title": jt} + if ju != "" { + rec["url"] = ju + } + if loc := card.First(`.location, .job-location`); loc != nil { + if lt := SanitizeSchemaPlainField(loc.Text(), 100); lt != "" { + rec["location"] = lt + } + } + recs = append(recs, rec) + } + if len(recs) > 0 { + return wave3JobsBuildListingsResult("Healthcare Career Portal", baseURL, extractorID, recs, len(recs), nil) + } + + var h1Title string + for _, sel := range []string{`#jobTitle`, `.job-title`, `h1`} { + if el := doc.First(sel); el != nil { + if cand := wave3JobsCleanJobTitle(el.Text()); cand != "" { + h1Title = cand + break + } + } + } + if h1Title != "" { + for _, sel := range []string{`#jobDescription`, `.job-description`, `[itemprop="description"]`, `main`} { + if el := doc.First(sel); el != nil { + if desc := wave3JobsRichText(el.OuterHTML(), baseURL, 14000); len(desc) >= 40 { + return wave3JobsBuildPostingResult(wave3JobPostingNorm{ + Title: h1Title, + Description: desc, + URL: wave3JobsSafeURL(baseURL, baseURL), + }, baseURL, extractorID) + } + } + } + } + return nil +} diff --git a/internal/extract/wave3_jobs_public_test.go b/internal/extract/wave3_jobs_public_test.go new file mode 100644 index 0000000..f2539b1 --- /dev/null +++ b/internal/extract/wave3_jobs_public_test.go @@ -0,0 +1,493 @@ +package extract + +import ( + "encoding/json" + "net/url" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func wave3JobsTestResolveManifest(t *testing.T, m *DeclarativeAdapterManifest, rawURL string) (*DeclarativeTwinMatch, bool) { + t.Helper() + u, err := url.Parse(rawURL) + if err != nil { + t.Fatalf("url.Parse(%q): %v", rawURL, err) + } + host := strings.TrimSuffix(strings.ToLower(u.Hostname()), ".") + rawParts := splitNonEmptyEscapedSegments(u.EscapedPath()) + return resolveManifestTwinOnParsedURL(m, u, host, rawParts, DeclarativeResolveOptions{}) +} + +func wave3JobsTestMatchHTMLRoute(t *testing.T, m *DeclarativeAdapterManifest, rawURL string) (string, bool) { + t.Helper() + u, err := url.Parse(rawURL) + if err != nil { + t.Fatalf("url.Parse(%q): %v", rawURL, err) + } + host := strings.TrimSuffix(strings.ToLower(u.Hostname()), ".") + rawParts := splitNonEmptyEscapedSegments(u.EscapedPath()) + for _, hr := range m.HTMLRoutes { + if _, ok := matchDeclarativeRoute(hr.Match, u, host, rawParts); ok { + return hr.Mode, true + } + } + return "", false +} + +func wave3JobsDecodeFormattedDoc(t *testing.T, raw string) *DeclarativeFormattedDoc { + t.Helper() + var doc DeclarativeFormattedDoc + if err := json.Unmarshal([]byte(raw), &doc); err != nil { + t.Fatalf("failed to unmarshal DeclarativeFormattedDoc JSON: %v\nraw=%s", err, raw) + } + return &doc +} + +func wave3JobsDecodeHTMLResult(t *testing.T, raw string) *DeclarativePostFetchResult { + t.Helper() + var res DeclarativePostFetchResult + if err := json.Unmarshal([]byte(raw), &res); err != nil { + t.Fatalf("failed to unmarshal DeclarativePostFetchResult JSON: %v\nraw=%s", err, raw) + } + return &res +} + +func TestWave3JobsPublicDispatchModePredicatesAndLazyRegistration(t *testing.T) { + jsonModes := []string{ + "neogov_json", + "bullhorn_joborder_json", + "staffing_ats_json", + "manatal_jobs_json", + "smb_ats_json", + } + for _, m := range jsonModes { + if !IsWave3JobsPublicJSONMode(m) { + t.Fatalf("IsWave3JobsPublicJSONMode(%q) = false, want true", m) + } + } + if IsWave3JobsPublicJSONMode("unknown_cat_c_json") { + t.Fatalf("IsWave3JobsPublicJSONMode(unknown_cat_c_json) = true, want false") + } + + htmlModes := []string{ + "neogov_html", + "bullhorn_portal_html", + "taleo_full_html", + "paradox_olivia_html", + "staffing_ats_pack_html", + "smb_ats_full_html", + "edu_job_boards_html", + "healthcare_careers_html", + } + for _, m := range htmlModes { + if !IsWave3JobsPublicHTMLMode(m) { + t.Fatalf("IsWave3JobsPublicHTMLMode(%q) = false, want true", m) + } + if getExternalHTMLModeLazy(m) == nil { + t.Fatalf("RegisterExternalHTMLModeLazy missing mode %q", m) + } + } + if IsWave3JobsPublicHTMLMode("unknown_cat_c_html") { + t.Fatalf("IsWave3JobsPublicHTMLMode(unknown_cat_c_html) = true, want false") + } +} + +func TestWave3JobsPublicManifestsParseAndSapExclusions(t *testing.T) { + slugs := []string{ + "neogov", + "bullhorn-career-portal", + "taleo-full", + "paradox-olivia", + "staffing-ats-pack", + "smb-ats-full", + "edu-job-boards", + "healthcare-careers", + } + + parsed := make(map[string]*DeclarativeAdapterManifest, len(slugs)) + for _, slug := range slugs { + raw, err := os.ReadFile(filepath.Join("manifests", slug+".yaml")) + if err != nil { + t.Fatalf("failed reading %s.yaml: %v", slug, err) + } + m, err := ParseDeclarativeYAMLManifest(raw) + if err != nil { + t.Fatalf("ParseDeclarativeYAMLManifest(%s.yaml) failed: %v", slug, err) + } + if m.ID != slug { + t.Fatalf("%s.yaml ID=%q, want %q", slug, m.ID, slug) + } + if m.Category != "jobs" { + t.Fatalf("%s.yaml category=%q, want jobs", slug, m.Category) + } + for _, d := range m.Domains { + dl := strings.ToLower(strings.TrimSpace(d)) + if strings.HasPrefix(dl, "careers.") && strings.HasSuffix(dl, ".com") { + t.Fatalf("%s.yaml must NEVER claim careers..com domain %q (sap-rmk-jibe collision)", slug, d) + } + } + parsed[slug] = m + } + + // Verify sap-rmk-jibe.yaml excludes the exact jobs.*.com hosts claimed by Cat C manifests on all routes & htmlRoutes + sapRaw, err := os.ReadFile(filepath.Join("manifests", "sap-rmk-jibe.yaml")) + if err != nil { + t.Fatalf("failed reading sap-rmk-jibe.yaml: %v", err) + } + sap, err := ParseDeclarativeYAMLManifest(sapRaw) + if err != nil { + t.Fatalf("ParseDeclarativeYAMLManifest(sap-rmk-jibe.yaml) failed: %v", err) + } + requiredExcluded := []string{"jobs.mchire.com", "jobs.crelate.com", "jobs.manatal.com", "jobs.chronicle.com"} + for idx, r := range sap.Routes { + exSet := make(map[string]bool) + for _, eh := range r.Match.ExcludeHosts { + exSet[eh] = true + } + for _, req := range requiredExcluded { + if !exSet[req] { + t.Fatalf("sap-rmk-jibe.yaml routes[%d].match.excludeHosts missing %q", idx, req) + } + } + } + for idx, hr := range sap.HTMLRoutes { + exSet := make(map[string]bool) + for _, eh := range hr.Match.ExcludeHosts { + exSet[eh] = true + } + for _, req := range requiredExcluded { + if !exSet[req] { + t.Fatalf("sap-rmk-jibe.yaml htmlRoutes[%d].match.excludeHosts missing %q", idx, req) + } + } + } + + // #226 neogov: strict_robots: true + RSS twin + HTML route + neo := parsed["neogov"] + if !neo.StrictRobots { + t.Fatalf("neogov must set strict_robots: true") + } + if tm, ok := wave3JobsTestResolveManifest(t, neo, "https://www.governmentjobs.com/careers/lacounty/rss"); !ok || tm.Kind != "text" || tm.route.Extract.XML == nil { + t.Fatalf("neogov RSS twin mismatch: ok=%v tm=%+v", ok, tm) + } + if mode, ok := wave3JobsTestMatchHTMLRoute(t, neo, "https://www.schooljobs.com/careers/lausd"); !ok || mode != "neogov_html" { + t.Fatalf("neogov HTML route mismatch: ok=%v mode=%q", ok, mode) + } + + // #227 bullhorn-career-portal + bh := parsed["bullhorn-career-portal"] + if !bh.UniversalEngine { + t.Fatalf("bullhorn-career-portal must set universalEngine: true") + } + if tm, ok := wave3JobsTestResolveManifest(t, bh, "https://public-rest33.bullhornstaffing.com/rest-services/sample/search/JobOrder?query=(isOpen:1)"); !ok || tm.route.Extract.JSONMode != "bullhorn_joborder_json" { + t.Fatalf("bullhorn twin mismatch: ok=%v tm=%+v", ok, tm) + } + + // #228 taleo-full: searchjobs POST twin (requiring portal) + FTL HTML + tal := parsed["taleo-full"] + if !tal.UniversalEngine { + t.Fatalf("taleo-full must set universalEngine: true") + } + if tm, ok := wave3JobsTestResolveManifest(t, tal, "https://chicago.taleo.net/careersection/rest/jobboard/searchjobs?lang=en&portal=101430233"); !ok || tm.Method != "POST" || tm.route.Extract.JSONMode != "taleo_searchjobs_json" { + t.Fatalf("taleo POST searchjobs twin mismatch: ok=%v tm=%+v", ok, tm) + } + if mode, ok := wave3JobsTestMatchHTMLRoute(t, tal, "https://chicago.taleo.net/careersection/100/jobsearch.ftl"); !ok || mode != "taleo_full_html" { + t.Fatalf("taleo FTL HTML route mismatch: ok=%v mode=%q", ok, mode) + } + + // #229 paradox-olivia: universalEngine: true + po := parsed["paradox-olivia"] + if !po.UniversalEngine { + t.Fatalf("paradox-olivia must set universalEngine: true") + } + + // #230 staffing-ats-pack: Crelate RSS + JSON + HTML + stf := parsed["staffing-ats-pack"] + if tm, ok := wave3JobsTestResolveManifest(t, stf, "https://jobs.crelate.com/portal/promotive/rss"); !ok || tm.Kind != "text" { + t.Fatalf("crelate RSS twin mismatch: ok=%v", ok) + } + + // #231 smb-ats-full: Manatal API + jobs.manatal.com upgrade + smb := parsed["smb-ats-full"] + if tm, ok := wave3JobsTestResolveManifest(t, smb, "https://api.manatal.com/open/v3/career-page/manatal/jobs/"); !ok || tm.route.Extract.JSONMode != "manatal_jobs_json" { + t.Fatalf("manatal API twin mismatch: ok=%v", ok) + } + if tm, ok := wave3JobsTestResolveManifest(t, smb, "https://jobs.manatal.com/manatal"); !ok || tm.FetchURL != "https://api.manatal.com/open/v3/career-page/manatal/jobs/" { + t.Fatalf("jobs.manatal.com twin upgrade mismatch: ok=%v tm=%+v", ok, tm) + } + + // #232 edu-job-boards: Chronicle RSS + edu := parsed["edu-job-boards"] + if tm, ok := wave3JobsTestResolveManifest(t, edu, "https://jobs.chronicle.com/jobsrss/?countrycode=US"); !ok || tm.Kind != "text" { + t.Fatalf("chronicle RSS twin mismatch: ok=%v", ok) + } + + // #233 healthcare-careers: excludes careers.symplr.com + universalEngine: true + hc := parsed["healthcare-careers"] + if !hc.UniversalEngine { + t.Fatalf("healthcare-careers must set universalEngine: true") + } + if _, ok := wave3JobsTestMatchHTMLRoute(t, hc, "https://careers.symplr.com/jobs"); ok { + t.Fatalf("healthcare-careers must exclude careers.symplr.com") + } + if mode, ok := wave3JobsTestMatchHTMLRoute(t, hc, "https://pm.healthcaresource.com/CS/midwesthealth"); !ok || mode != "healthcare_careers_html" { + t.Fatalf("healthcare-careers HTML route mismatch: ok=%v mode=%q", ok, mode) + } +} + +func TestWave3JobsPublicJSONAndHTMLPositiveAndNegatives(t *testing.T) { + // #227 Bullhorn: valid + errors.badCorpToken + empty data + bhPayload := `{"total":1,"start":0,"count":1,"data":[{"id":10421,"title":"Registered Nurse - ICU","employmentType":"Contract","publishedCategory":{"name":"Healthcare"},"address":{"city":"Denver","state":"CO","countryName":"United States"},"dateLastPublished":1795132800000}]}` + if raw, ok := FormatWave3JobsPublicJSONMode("bullhorn_joborder_json", []byte(bhPayload), map[string]string{"cluster": "public-rest33"}, "https://public-rest33.bullhornstaffing.com/rest-services/sample/search/JobOrder"); !ok { + t.Fatalf("bullhorn_joborder_json positive failed") + } else { + doc := wave3JobsDecodeFormattedDoc(t, raw) + if !strings.Contains(doc.Markdown, "Registered Nurse - ICU") || !strings.Contains(doc.Markdown, "Denver, CO, United States") { + t.Fatalf("bullhorn_joborder_json unexpected markdown: %s", doc.Markdown) + } + } + if _, ok := FormatWave3JobsPublicJSONMode("bullhorn_joborder_json", []byte(`{"errorMessageKey":"errors.badCorpToken","errorMessage":"Invalid corpToken","errorCode":400}`), nil, "https://public-rest33.bullhornstaffing.com/rest-services/bad/search/JobOrder"); ok { + t.Fatalf("bullhorn_joborder_json must reject errors.badCorpToken") + } + if _, ok := FormatWave3JobsPublicJSONMode("bullhorn_joborder_json", []byte(`{"total":0,"data":[]}`), nil, "https://public-rest33.bullhornstaffing.com/rest-services/sample/search/JobOrder"); ok { + t.Fatalf("bullhorn_joborder_json must reject empty data array") + } + + // #228 Taleo searchjobs JSON (via FormatRound2JSONDoc) + jobdetail.ftl HTML + talSearch := `{"requisitionList":[{"jobId":"40128","contestNo":"2026-0041","column":["Municipal Budget Analyst","[\"Chicago, IL\"]","2026-11-18"]}],"pagingData":{"totalCount":1}}` + if doc, ok := FormatRound2JSONDoc("taleo_searchjobs_json", []byte(talSearch), map[string]string{"section": "100"}, "https://chicago.taleo.net/careersection/rest/jobboard/searchjobs?lang=en&portal=101430233"); !ok || doc == nil || !strings.Contains(doc.Markdown, "Municipal Budget Analyst") { + t.Fatalf("taleo_searchjobs_json failed: ok=%v doc=%+v", ok, doc) + } + if _, ok := FormatRound2JSONDoc("taleo_searchjobs_json", []byte(`{"requisitionList":[]}`), nil, "https://chicago.taleo.net/careersection/rest/jobboard/searchjobs?lang=en&portal=101430233"); ok { + t.Fatalf("taleo_searchjobs_json must reject empty requisitionList") + } + talDetailHTML := `Job Description - Municipal Budget Analyst

Municipal Budget Analyst

Prepare and monitor multi-year municipal capital budgets across city departments.

` + if raw, ok := RunWave3JobsPublicHTMLMode("taleo_full_html", talDetailHTML, "https://chicago.taleo.net/careersection/100/jobdetail.ftl?job=40128"); !ok || !strings.Contains(raw, "Municipal Budget Analyst") { + t.Fatalf("taleo_full_html jobdetail.ftl failed: ok=%v raw=%s", ok, raw) + } + talFillListHTML := `All Jobs
` + if raw, ok := RunWave3JobsPublicHTMLMode("taleo_full_html", talFillListHTML, "https://chicago.taleo.net/careersection/100/joblist.ftl"); !ok || !strings.Contains(raw, "ATTORNEY - EXCLUDED") || !strings.Contains(raw, "jobdetail.ftl?job=209551") { + t.Fatalf("taleo_full_html joblist.ftl fillList failed: ok=%v raw=%s", ok, raw) + } + talFillDetailHTML := `` + if raw, ok := RunWave3JobsPublicHTMLMode("taleo_full_html", talFillDetailHTML, "https://chicago.taleo.net/careersection/100/jobdetail.ftl?job=209551"); !ok || !strings.Contains(raw, "ATTORNEY - EXCLUDED") || !strings.Contains(raw, "procurement matters") || !strings.Contains(raw, "2026-11-27") { + t.Fatalf("taleo_full_html descRequisition fillList failed: ok=%v raw=%s", ok, raw) + } + talBlankSearchHTML := `Job Search - Basic Search
` + if raw, ok := RunWave3JobsPublicHTMLMode("taleo_full_html", talBlankSearchHTML, "https://chicago.taleo.net/careersection/100/jobsearch.ftl"); ok { + t.Fatalf("taleo_full_html must reject blank jobsearch.ftl form, got %s", raw) + } + + // #229 Paradox Olivia: __NEXT_DATA__ board + non-Paradox universal isolation + paradoxNext := `McDonald's Careers
` + if raw, ok := RunWave3JobsPublicHTMLMode("paradox_olivia_html", paradoxNext, "https://jobs.mchire.com/jobs"); !ok || !strings.Contains(raw, "Crew Member") { + t.Fatalf("paradox_olivia_html __NEXT_DATA__ failed: ok=%v raw=%s", ok, raw) + } + unrelatedHTML := `Simpson's Paradox in Statistics

Simpson's Paradox

A statistical phenomenon in probability and data science.

` + if _, ok := RunWave3JobsPublicHTMLMode("paradox_olivia_html", unrelatedHTML, "https://en.wikipedia.org/wiki/Simpson%27s_paradox"); ok { + t.Fatalf("paradox_olivia_html must not match unrelated pages mentioning paradox") + } + + // #230 Staffing ATS: Organization Portal Disabled rejected + disabledHTML := `Organization Portal Disabled

Organization Portal Disabled

This portal is currently disabled.

` + if _, ok := RunWave3JobsPublicHTMLMode("staffing_ats_pack_html", disabledHTML, "https://jobs.crelate.com/portal/corapt"); ok { + t.Fatalf("staffing_ats_pack_html must reject Organization Portal Disabled") + } + + // #231 SMB ATS: 404.homerun.co rejected + Manatal single & paginated nextCursor + if _, ok := RunWave3JobsPublicHTMLMode("smb_ats_full_html", `Vacancy Not Found

Not Found

`, "https://404.homerun.co/vacancies/jobs/homerun"); ok { + t.Fatalf("smb_ats_full_html must reject 404.homerun.co") + } + manatalPage := `{"count":33,"next":"https://core.api.manatal.com/open/v3/career-page/manatal/jobs/?page=2","previous":null,"results":[{"id":2883259,"hash":"L9Y69V66","organization_name":"Manatal","position_name":"Backend Engineer","city":"Bangkok","country":"Thailand","is_remote":true,"contract_details":"Full-time","created_at":"2026-11-15T08:00:00Z"}]}` + if raw, ok := FormatWave3JobsPublicJSONMode("manatal_jobs_json", []byte(manatalPage), map[string]string{"slug": "manatal"}, "https://api.manatal.com/open/v3/career-page/manatal/jobs/"); !ok { + t.Fatalf("manatal_jobs_json failed") + } else { + doc := wave3JobsDecodeFormattedDoc(t, raw) + if doc.NextCursor != "https://core.api.manatal.com/open/v3/career-page/manatal/jobs/?page=2" || doc.Truncated == nil || !*doc.Truncated { + t.Fatalf("manatal_jobs_json pagination mismatch: %+v", doc) + } + } + + // #232 Edu Job Boards: _Incapsula_Resource WAF & unhydrated <%- item. CSR rejected + incapsulaHTML := `` + if _, ok := RunWave3JobsPublicHTMLMode("edu_job_boards_html", incapsulaHTML, "https://www.higheredjobs.com/"); ok { + t.Fatalf("edu_job_boards_html must reject _Incapsula_Resource") + } + edjoinCSR := `EdJoin` + if _, ok := RunWave3JobsPublicHTMLMode("edu_job_boards_html", edjoinCSR, "https://www.edjoin.org/Home/Jobs?keywords=teacher"); ok { + t.Fatalf("edu_job_boards_html must reject unhydrated Underscore CSR template") + } + + // #233 Healthcare Careers: Application Error rejected + careers.symplr.com excluded + appErrHTML := `Application Error

You have encountered a system error. Please verify that you have entered the correct URL .

` + if _, ok := RunWave3JobsPublicHTMLMode("healthcare_careers_html", appErrHTML, "https://pm.healthcaresource.com/CS/henryford"); ok { + t.Fatalf("healthcare_careers_html must reject Application Error") + } + symplrJibeHTML := `symplr Careers

Senior DevOps Engineer

` + if _, ok := RunWave3JobsPublicHTMLMode("healthcare_careers_html", symplrJibeHTML, "https://careers.symplr.com/jobs/2662"); ok { + t.Fatalf("healthcare_careers_html must never extract on careers.symplr.com") + } +} + +func TestWave3JobsPublicFixtures(t *testing.T) { + slugs := []string{ + "neogov", + "bullhorn-career-portal", + "taleo-full", + "paradox-olivia", + "staffing-ats-pack", + "smb-ats-full", + "edu-job-boards", + "healthcare-careers", + } + + type fixtureNeg struct { + Name string `json:"name"` + Status int `json:"status"` + FinalURL string `json:"finalUrl"` + Payload string `json:"payload"` + } + type fixtureDoc struct { + AdapterID string `json:"adapterId"` + Mode string `json:"mode"` + InputURL string `json:"inputUrl"` + ExpectedFetchURL string `json:"expectedFetchUrl"` + MockPayload string `json:"mockPayload"` + ExpectTitleIncludes string `json:"expectTitleIncludes"` + ExpectMarkdownIncludes []string `json:"expectMarkdownIncludes"` + NegativeCases []fixtureNeg `json:"negativeCases"` + } + + for _, slug := range slugs { + rawFX, err := os.ReadFile(filepath.Join("..", "..", "hub", "test", "fixtures", "adapters", slug+".json")) + if err != nil { + t.Fatalf("failed reading fixture %s.json: %v", slug, err) + } + var fx fixtureDoc + if err := json.Unmarshal(rawFX, &fx); err != nil { + t.Fatalf("invalid JSON in %s.json: %v", slug, err) + } + if fx.AdapterID != slug { + t.Fatalf("%s.json adapterId=%q, want %q", slug, fx.AdapterID, slug) + } + if len(fx.NegativeCases) < 4 { + t.Fatalf("%s.json has %d negativeCases, want >= 4", slug, len(fx.NegativeCases)) + } + + rawManifest, err := os.ReadFile(filepath.Join("manifests", slug+".yaml")) + if err != nil { + t.Fatalf("failed reading manifest %s.yaml: %v", slug, err) + } + manifest, err := ParseDeclarativeYAMLManifest(rawManifest) + if err != nil { + t.Fatalf("ParseDeclarativeYAMLManifest(%s.yaml): %v", slug, err) + } + + if fx.Mode == "twin" { + m, ok := wave3JobsTestResolveManifest(t, manifest, fx.InputURL) + if !ok { + t.Fatalf("%s twin resolve failed for %s", slug, fx.InputURL) + } + if fx.ExpectedFetchURL != "" && m.FetchURL != fx.ExpectedFetchURL { + t.Fatalf("%s fetchUrl=%q, want %q", slug, m.FetchURL, fx.ExpectedFetchURL) + } + doc, okDoc := m.Format(fx.MockPayload) + if !okDoc || doc == nil { + t.Fatalf("%s m.Format failed", slug) + } + if fx.ExpectTitleIncludes != "" && !strings.Contains(doc.Title, fx.ExpectTitleIncludes) { + t.Fatalf("%s title=%q missing %q", slug, doc.Title, fx.ExpectTitleIncludes) + } + for _, needle := range fx.ExpectMarkdownIncludes { + if !strings.Contains(doc.Markdown, needle) { + t.Fatalf("%s markdown missing %q", slug, needle) + } + } + for _, nc := range fx.NegativeCases { + if nc.FinalURL != "" && nc.FinalURL != fx.InputURL { + continue + } + if negDoc, okNeg := m.Format(nc.Payload); okNeg && negDoc != nil && strings.TrimSpace(negDoc.Markdown) != "" { + t.Fatalf("%s negativeCase %q unexpectedly succeeded", slug, nc.Name) + } + } + } else { + htmlMode, ok := wave3JobsTestMatchHTMLRoute(t, manifest, fx.InputURL) + if !ok { + t.Fatalf("%s HTML route match failed for %s", slug, fx.InputURL) + } + outRaw, okHTML := RunWave3JobsPublicHTMLMode(htmlMode, fx.MockPayload, fx.InputURL) + if !okHTML { + t.Fatalf("%s RunWave3JobsPublicHTMLMode failed", slug) + } + res := wave3JobsDecodeHTMLResult(t, outRaw) + if fx.ExpectTitleIncludes != "" && !strings.Contains(res.Title, fx.ExpectTitleIncludes) { + t.Fatalf("%s HTML title=%q missing %q", slug, res.Title, fx.ExpectTitleIncludes) + } + for _, needle := range fx.ExpectMarkdownIncludes { + if !strings.Contains(res.Markdown, needle) { + t.Fatalf("%s HTML markdown missing %q", slug, needle) + } + } + for _, nc := range fx.NegativeCases { + targetURL := fx.InputURL + if nc.FinalURL != "" { + targetURL = nc.FinalURL + } + if _, okNeg := RunWave3JobsPublicHTMLMode(htmlMode, nc.Payload, targetURL); okNeg { + t.Fatalf("%s HTML negativeCase %q unexpectedly succeeded", slug, nc.Name) + } + } + } + } +} + +func TestWave3JobsHealthcareCareersDoesNotHijackParadoxOlivia(t *testing.T) { + // #233 healthcare-careers vs #229 paradox-olivia: stray "symplr" mention on Paradox page must NOT hijack paradox-olivia + paradoxHTML := `Registered Nurse | Memorial Health

Registered Nurse

Powered by symplr legacy link
` + u := "https://careers.memorialhealth.org/jobs/123" + + if raw, ok := RunWave3JobsPublicHTMLMode("healthcare_careers_html", paradoxHTML, u); ok { + t.Fatalf("healthcare_careers_html must NOT hijack Paradox Olivia page with stray symplr mention: %s", raw) + } + if _, ok := RunWave3JobsPublicHTMLMode("paradox_olivia_html", paradoxHTML, u); !ok { + t.Fatalf("paradox_olivia_html should extract Paradox Olivia page") + } + declRes, ok := ApplyDeclarativeHTMLExtractor(paradoxHTML, u, "", nil) + if !ok || declRes == nil || declRes.ExtractorID != "paradox-olivia" { + t.Fatalf("ApplyDeclarativeHTMLExtractor expected paradox-olivia, got ok=%v res=%+v", ok, declRes) + } + + // Stray symplr mention on an arbitrary non-HealthcareSource host without HealthcareSource/symplr portal DOM markers must not match + strayHTML := `Software Engineer | Example Corp

Software Engineer

Integrates with symplr scheduling
` + if raw, ok := RunWave3JobsPublicHTMLMode("healthcare_careers_html", strayHTML, "https://jobs.examplecorp.org/role/42"); ok { + t.Fatalf("healthcare_careers_html must NOT match arbitrary host with stray symplr text: %s", raw) + } +} + +func TestWave3JobsM7ParadoxOliviaLatency(t *testing.T) { + descHTML := strings.Repeat(`

Package Handler loads and unloads packages safely in a fast-paced warehouse environment.

  • Lift up to 50 lbs
  • Weekly pay
`, 60) + ldJSON, _ := json.Marshal(map[string]any{ + "@context": "https://schema.org", + "@type": "JobPosting", + "title": "Warehouse Package Handler", + "hiringOrganization": map[string]any{"@type": "Organization", "name": "FedEx"}, + "jobLocation": map[string]any{"@type": "Place", "address": map[string]any{"addressLocality": "Memphis", "addressRegion": "TN", "addressCountry": "US"}}, + "employmentType": "PART_TIME", + "datePosted": "2026-11-20", + "description": descHTML, + }) + paradoxHTML := `Warehouse Package Handler - FedEx

Warehouse Package Handler

` + strings.Repeat("
nav
", 5000) + `` + start := time.Now() + raw, ok := RunWave3JobsPublicHTMLMode("paradox_olivia_html", paradoxHTML, "https://careers.fedex.com/jobs/12345") + elapsed := time.Since(start) + if !ok || !strings.Contains(raw, "Warehouse Package Handler") || !strings.Contains(raw, "Weekly pay") { + t.Fatalf("paradox_olivia_html latency test failed: ok=%v", ok) + } + if elapsed > 25*time.Millisecond*time.Duration(extractRaceSlowdown) { + t.Fatalf("paradox_olivia_html exceeded 25ms latency budget: %v", elapsed) + } +} diff --git a/internal/extract/wave3_media_lyrics.go b/internal/extract/wave3_media_lyrics.go new file mode 100644 index 0000000..9553a60 --- /dev/null +++ b/internal/extract/wave3_media_lyrics.go @@ -0,0 +1,4060 @@ +package extract + +import ( + "bytes" + "encoding/json" + "fmt" + stdhtml "html" + "math" + "strconv" + "strings" +) + +const ( + wave3MediaMaxHTMLBytes = 2 * 1024 * 1024 + wave3MediaMaxJSONBytes = 4 * 1024 * 1024 + wave3MediaMaxTextBytes = 4 * 1024 * 1024 + wave3MediaMaxRecords = 25 +) + +var ( + wave3MediaRxNotFoundTitle = newLazyRegexp(`(?i)(?:^|\b)(?:404|410|403\s+forbidden|forbidden|page\s+not\s+found|not\s+found|error\s*404|we\s+couldn'?t\s+find\s+that|access\s+denied|request\s+(?:rejected|blocked)|could\s+not\s+be\s+satisfied|unauthorized|attention\s+required|just\s+a\s+moment|verifying\s+your\s+browser|security\s+check|blocked|release\s+not\s+found|item\s+currently\s+unavailable)(?:\b|$)`) + wave3MediaRxMaintTitle = newLazyRegexp(`(?i)(?:scheduled\s+maintenance|temporarily\s+unavailable|service\s+unavailable|site\s+maintenance|under\s+maintenance|502\s+bad\s+gateway|503\s+service|down\s+for\s+maintenance)`) + wave3MediaRxErrorTitle = newLazyRegexp(`(?i)^(?:(?:(?:400|401|403|404|406|410|429|500|502|503)\s+)?(?:internal\s+)?server\s+error|application\s+error|system\s+error|unexpected\s+error|whitelabel\s+error\s+page|error\s+page|(?:400|401|403|404|406|410|429|500|502|503|http\s+\d{3})\s+error|error\s+(?:400|401|403|404|406|410|429|500|502|503)|error)(?:\s*[|\-\x{2013}\x{2014}:]\s*.*)?$|^.*(?:\s*[|\-\x{2013}\x{2014}:]\s*error)$`) + wave3MediaRxGenericTitle = newLazyRegexp(`(?i)^(?:loading\.{0,3}|home|welcome|welcome\s+to\s+steam|search|log\s*in|sign\s*in|the\s+movie\s+database\s*\(tmdb\)|imdb\s+datasets|tvmaze|musicbrainz|discogs|podcast\s+index|spotify|setlist\.fm|last\.fm|igdb|bandcamp|genius|azlyrics|musixmatch|songmeanings)$`) + wave3MediaRxHTMLTag = newLazyRegexp(`<[^>]+>`) + wave3MediaRxBRTag = newLazyRegexp(`(?i)`) + wave3MediaRxBlockEndTag = newLazyRegexp(`(?i)`) + wave3MediaRxSpace = newLazyRegexp(`[ \t\r\n]+`) + wave3MediaRxHorizSpace = newLazyRegexp(`[ \t]+`) + wave3MediaRxMultiNewline = newLazyRegexp(`\n{3,}`) + wave3MediaRxTitleTag = newLazyRegexp(`(?is)]*>(.*?)`) + wave3MediaRxMetaTag = newLazyRegexp(`(?is)]*>`) + wave3MediaRxNextData = newLazyRegexp(`(?is)]*\bid\s*=\s*["']__NEXT_DATA__["'][^>]*>(.*?)`) + wave3MediaRxDataTralbumDbl = newLazyRegexp(`(?is)\bdata-tralbum\s*=\s*"([^"]*)"`) + wave3MediaRxDataTralbumSgl = newLazyRegexp(`(?is)\bdata-tralbum\s*=\s*'([^']*)'`) + wave3MediaRxAZLyricsComment = newLazyRegexp(`(?is)(?:]*>\s*(.*?)
|\s*]*>(.*?)
)`) + wave3MediaRxPreloadedDirect = newLazyRegexp(`(?is)window\.__PRELOADED_STATE__\s*=\s*(\{.*?\})\s*;?\s*`) + wave3MediaRxPreloadedParse = newLazyRegexp(`(?is)window\.__PRELOADED_STATE__\s*=\s*JSON\.parse\(\s*('(?:\\.|[^'\\])*'|"(?:\\.|[^"\\])*")\s*\)`) + wave3MediaRxGeniusTitleDash = newLazyRegexp(`(?i)\s+lyrics\s*(?:\|\s*genius(?:\s+lyrics)?.*)?$`) + wave3MediaRxAZTitleClean = newLazyRegexp(`(?i)\s+lyrics\s*(?:\|\s*azlyrics\.com.*)?$`) + wave3MediaRxImdbGZLink = newLazyRegexp(`https?://datasets\.imdbws\.com/[A-Za-z0-9._-]+\.tsv\.gz`) +) + +func init() { + registerWave3MediaLyricsHTMLModes() +} + +// RegisterWave3MediaLyricsHTMLModes registers all Category R Media & Entertainment / Lyrics HTML modes lazily. +func RegisterWave3MediaLyricsHTMLModes() { + registerWave3MediaLyricsHTMLModes() +} + +func registerWave3MediaLyricsHTMLModes() { + for _, mode := range []string{ + "tmdb_html", + "imdb_datasets_html", + "tvmaze_html", + "musicbrainz_html", + "discogs_html", + "podcast_index_html", + "spotify_html", + "setlist_lastfm_html", + "steam_store_html", + "igdb_html", + "bandcamp_html", + "genius_lyrics_html", + } { + m := mode + RegisterExternalHTMLModeLazy(m, func(rawHTML, baseURL string, _ func() string, extractorID string) *DeclarativePostFetchResult { + return Wave3MediaLyricsRunHTML(m, rawHTML, baseURL, extractorID) + }) + } +} + +// IsWave3MediaLyricsHTMLMode reports whether mode is one of the 12 Category R HTML modes (#375-#386). +func IsWave3MediaLyricsHTMLMode(mode string) bool { + switch mode { + case "tmdb_html", + "imdb_datasets_html", + "tvmaze_html", + "musicbrainz_html", + "discogs_html", + "podcast_index_html", + "spotify_html", + "setlist_lastfm_html", + "steam_store_html", + "igdb_html", + "bandcamp_html", + "genius_lyrics_html": + return true + default: + return false + } +} + +// IsWave3MediaLyricsJSONMode reports whether mode is one of the Category R JSON formatters. +func IsWave3MediaLyricsJSONMode(mode string) bool { + switch mode { + case "tmdb_json", + "tvmaze_json", + "musicbrainz_json", + "coverart_archive_json", + "discogs_json", + "podcast_index_json", + "spotify_api_json", + "spotify_oembed_json", + "setlist_fm_json", + "lastfm_json", + "steam_store_json", + "igdb_json": + return true + default: + return false + } +} + +// IsWave3MediaLyricsTextMode reports whether mode is handled by Category R text formatters (`imdb_datasets_tsv`). +func IsWave3MediaLyricsTextMode(mode string) bool { + return mode == "imdb_datasets_tsv" +} + +func wave3MediaDefaultExtractorID(mode string) string { + switch mode { + case "tmdb_html", "tmdb_json": + return "tmdb" + case "imdb_datasets_html", "imdb_datasets_tsv": + return "imdb-datasets" + case "tvmaze_html", "tvmaze_json": + return "tvmaze" + case "musicbrainz_html", "musicbrainz_json", "coverart_archive_json": + return "musicbrainz-coverart" + case "discogs_html", "discogs_json": + return "discogs" + case "podcast_index_html", "podcast_index_json": + return "podcast-index" + case "spotify_html", "spotify_api_json", "spotify_oembed_json": + return "spotify-web-api" + case "setlist_lastfm_html", "setlist_fm_json", "lastfm_json": + return "setlist-lastfm" + case "steam_store_html", "steam_store_json": + return "steam-store" + case "igdb_html", "igdb_json": + return "igdb" + case "bandcamp_html": + return "bandcamp" + case "genius_lyrics_html": + return "genius-lyrics" + default: + return "" + } +} + +// Wave3MediaLyricsRunHTML executes a Category R HTML extractor and returns DeclarativePostFetchResult. +func Wave3MediaLyricsRunHTML(mode, rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + if !IsWave3MediaLyricsHTMLMode(mode) || len(rawHTML) == 0 || strings.IndexByte(rawHTML, '<') < 0 || strings.IndexByte(rawHTML, '>') < 0 { + return nil + } + if len(rawHTML) > wave3MediaMaxHTMLBytes { + rawHTML = truncateUTF8SafeFullDocGo(rawHTML, wave3MediaMaxHTMLBytes) + } + trimmedStart := strings.TrimLeft(rawHTML, " \t\r\n") + if trimmedStart == "" || trimmedStart[0] == '{' || trimmedStart[0] == '[' { + return nil + } + probe := rawHTML + if len(probe) > 65536 { + probe = probe[:65536] + } + probeLower := asciiLowerExtractString(probe) + urlLower := asciiLowerExtractString(baseURL) + + if !wave3MediaMatchesModePrefilter(mode, probeLower, urlLower) { + return nil + } + if wave3MediaHasCommonNegativeShell(mode, rawHTML, probeLower, urlLower) { + return nil + } + if extractorID == "" { + extractorID = wave3MediaDefaultExtractorID(mode) + } + + var res *DeclarativePostFetchResult + switch mode { + case "tmdb_html": + res = wave3MediaExtractTMDBHTML(rawHTML, baseURL, extractorID) + case "imdb_datasets_html": + res = wave3MediaExtractIMDbDatasetsHTML(rawHTML, baseURL, extractorID) + case "tvmaze_html": + res = wave3MediaExtractTVmazeHTML(rawHTML, baseURL, extractorID) + case "musicbrainz_html": + res = wave3MediaExtractMusicBrainzHTML(rawHTML, baseURL, extractorID) + case "discogs_html": + res = wave3MediaExtractDiscogsHTML(rawHTML, baseURL, extractorID) + case "podcast_index_html": + res = wave3MediaExtractPodcastIndexHTML(rawHTML, baseURL, extractorID) + case "spotify_html": + res = wave3MediaExtractSpotifyHTML(rawHTML, baseURL, extractorID) + case "setlist_lastfm_html": + res = wave3MediaExtractSetlistLastfmHTML(rawHTML, baseURL, urlLower, extractorID) + case "steam_store_html": + res = wave3MediaExtractSteamStoreHTML(rawHTML, baseURL, extractorID) + case "igdb_html": + res = wave3MediaExtractIGDBHTML(rawHTML, baseURL, extractorID) + case "bandcamp_html": + res = wave3MediaExtractBandcampHTML(rawHTML, baseURL, extractorID) + case "genius_lyrics_html": + res = wave3MediaExtractGeniusLyricsHTML(rawHTML, probeLower, baseURL, urlLower, extractorID) + } + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return nil + } + return wave3MediaFinalizePostFetch(res) +} + +// RunWave3MediaLyricsHTMLMode executes a Category R HTML extractor and returns JSON-marshaled DeclarativePostFetchResult. +func RunWave3MediaLyricsHTMLMode(mode, rawHTML, baseURL string) (string, bool) { + res := Wave3MediaLyricsRunHTML(mode, rawHTML, baseURL, wave3MediaDefaultExtractorID(mode)) + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return "", false + } + res = sanitizePostFetchResultDeclHTML(res) + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return "", false + } + encoded, err := json.Marshal(res) + if err != nil { + return "", false + } + return string(encoded), true +} + +// FormatWave3MediaLyricsJSONDoc formats a Category R JSON twin payload into DeclarativeFormattedDoc. +func FormatWave3MediaLyricsJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool) { + if !IsWave3MediaLyricsJSONMode(mode) || len(raw) == 0 || len(raw) > wave3MediaMaxJSONBytes { + return nil, false + } + trimmed := bytes.TrimSpace(bytes.TrimPrefix(raw, []byte("\xEF\xBB\xBF"))) + if len(trimmed) == 0 || (trimmed[0] != '{' && trimmed[0] != '[') { + return nil, false + } + parsed, ok := decodeJSONWithNumbers(trimmed) + if !ok || parsed == nil { + return nil, false + } + if obj, isObj := parsed.(map[string]any); isObj && wave3MediaIsGenericJSONError(obj) { + return nil, false + } + + var doc *DeclarativeFormattedDoc + var handled bool + switch mode { + case "tmdb_json": + doc, handled = wave3MediaFormatTMDBJSON(parsed, origURL) + case "tvmaze_json": + doc, handled = wave3MediaFormatTVmazeJSON(parsed, origURL) + case "musicbrainz_json": + doc, handled = wave3MediaFormatMusicBrainzJSON(parsed, origURL) + case "coverart_archive_json": + doc, handled = wave3MediaFormatCoverArtJSON(parsed, origURL) + case "discogs_json": + doc, handled = wave3MediaFormatDiscogsJSON(parsed, origURL) + case "podcast_index_json": + doc, handled = wave3MediaFormatPodcastIndexJSON(parsed, origURL) + case "spotify_api_json": + doc, handled = wave3MediaFormatSpotifyAPIJSON(parsed, origURL) + case "spotify_oembed_json": + doc, handled = wave3MediaFormatSpotifyOEmbedJSON(parsed, origURL) + case "setlist_fm_json": + doc, handled = wave3MediaFormatSetlistFmJSON(parsed, origURL) + case "lastfm_json": + doc, handled = wave3MediaFormatLastfmJSON(parsed, origURL) + case "steam_store_json": + doc, handled = wave3MediaFormatSteamStoreJSON(parsed, origURL) + case "igdb_json": + doc, handled = wave3MediaFormatIGDBJSON(parsed, origURL) + } + if !handled || doc == nil || strings.TrimSpace(doc.Markdown) == "" { + return nil, false + } + return wave3MediaFinalizeDoc(doc), true +} + +// FormatWave3MediaLyricsJSONMode formats a Category R JSON payload and returns JSON-marshaled DeclarativeFormattedDoc. +func FormatWave3MediaLyricsJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool) { + doc, ok := FormatWave3MediaLyricsJSONDoc(mode, raw, params, origURL) + if !ok || doc == nil { + return "", false + } + encoded, err := json.Marshal(doc) + if err != nil { + return "", false + } + return string(encoded), true +} + +// FormatWave3MediaLyricsTextDoc formats a Category R text twin payload (`imdb_datasets_tsv`). +func FormatWave3MediaLyricsTextDoc(mode, rawBody string, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool) { + if !IsWave3MediaLyricsTextMode(mode) || len(rawBody) == 0 { + return nil, false + } + if len(rawBody) > wave3MediaMaxTextBytes { + rawBody = truncateUTF8SafeFullDocGo(rawBody, wave3MediaMaxTextBytes) + } + doc, ok := wave3MediaFormatIMDbDatasetsTSV(rawBody, origURL) + if !ok || doc == nil || strings.TrimSpace(doc.Markdown) == "" { + return nil, false + } + return wave3MediaFinalizeDoc(doc), true +} + +// FormatWave3MediaLyricsTextMode formats a Category R text payload and returns JSON-marshaled DeclarativeFormattedDoc. +func FormatWave3MediaLyricsTextMode(mode, rawBody string, params map[string]string, origURL string) (string, bool) { + doc, ok := FormatWave3MediaLyricsTextDoc(mode, rawBody, params, origURL) + if !ok || doc == nil { + return "", false + } + encoded, err := json.Marshal(doc) + if err != nil { + return "", false + } + return string(encoded), true +} + +// ── Prefilters & Shared Hygiene Helpers ────────────────────────────────────────────────────────── + +func wave3MediaMatchesModePrefilter(mode, probeLower, urlLower string) bool { + switch mode { + case "tmdb_html": + return strings.Contains(urlLower, "themoviedb.org") || + strings.Contains(probeLower, "themoviedb") || + strings.Contains(probeLower, "original_header") || + strings.Contains(probeLower, "application/ld+json") + case "imdb_datasets_html": + return strings.Contains(urlLower, "imdb.com") || + strings.Contains(probeLower, "imdb") || + strings.Contains(probeLower, "datasets.imdbws.com") || + strings.Contains(probeLower, "__next_data__") + case "tvmaze_html": + return strings.Contains(urlLower, "tvmaze.com") || + strings.Contains(probeLower, "tvmaze") || + strings.Contains(probeLower, "general-info-panel") || + strings.Contains(probeLower, "application/ld+json") + case "musicbrainz_html": + return strings.Contains(urlLower, "musicbrainz.org") || + strings.Contains(probeLower, "musicbrainz") || + strings.Contains(probeLower, "__meb_verify") || + strings.Contains(probeLower, "releaseheader") + case "discogs_html": + return strings.Contains(urlLower, "discogs.com") || + strings.Contains(probeLower, "discogs") || + strings.Contains(probeLower, "__next_data__") || + strings.Contains(probeLower, "application/ld+json") + case "podcast_index_html": + return strings.Contains(urlLower, "podcastindex.org") || + strings.Contains(probeLower, "podcastindex") || + strings.Contains(probeLower, "podcast") || + strings.Contains(probeLower, "application/ld+json") + case "spotify_html": + return strings.Contains(urlLower, "open.spotify.com") || + strings.Contains(probeLower, "open.spotify.com") || + strings.Contains(probeLower, "spotify") || + strings.Contains(probeLower, "podcastseries") || + strings.Contains(probeLower, "musicrecording") || + strings.Contains(probeLower, "og:title") + case "setlist_lastfm_html": + return strings.Contains(urlLower, "setlist.fm") || + strings.Contains(urlLower, "last.fm") || + strings.Contains(probeLower, "setlistheadline") || + strings.Contains(probeLower, "songlabel") || + strings.Contains(probeLower, "songpart") || + strings.Contains(probeLower, "last.fm") || + strings.Contains(probeLower, "music:") + case "steam_store_html": + return strings.Contains(urlLower, "store.steampowered.com") || + strings.Contains(probeLower, "apphubappname") || + strings.Contains(probeLower, "game_description_snippet") || + strings.Contains(probeLower, "steampowered") + case "igdb_html": + return strings.Contains(urlLower, "igdb.com") || + strings.Contains(probeLower, "igdb") || + strings.Contains(probeLower, "game_details") || + strings.Contains(probeLower, "application/ld+json") + case "bandcamp_html": + return strings.Contains(urlLower, "bandcamp.com") || + strings.Contains(probeLower, "data-tralbum") || + strings.Contains(probeLower, "bc-page-properties") || + strings.Contains(probeLower, "musicalbum") || + strings.Contains(probeLower, "musicrecording") + case "genius_lyrics_html": + return strings.Contains(probeLower, "data-lyrics-container") || + strings.Contains(probeLower, "__preloaded_state__") || + strings.Contains(probeLower, "azlyrics.com content") || + strings.Contains(probeLower, "editlyricsbody") || + strings.Contains(probeLower, "mxm-lyrics") || + strings.Contains(probeLower, "lyrics__content") || + strings.Contains(probeLower, "lyric-box") || + strings.Contains(probeLower, "musicrecording") || + strings.Contains(probeLower, "__next_data__") || + strings.Contains(urlLower, "genius.com") || + strings.Contains(urlLower, "azlyrics.com") || + strings.Contains(urlLower, "musixmatch.com") || + strings.Contains(urlLower, "songmeanings.com") + default: + return false + } +} + +func wave3MediaIsNegativeURL(urlLower string) bool { + if urlLower == "" { + return false + } + if strings.Contains(urlLower, "/404") || + strings.Contains(urlLower, "/not-found") || + strings.Contains(urlLower, "/page-not-found") || + strings.Contains(urlLower, "/maintenance") || + strings.Contains(urlLower, "error=true") || + strings.Contains(urlLower, "error=1") { + return true + } + pathOnly := urlLower + if idx := strings.Index(pathOnly, "://"); idx >= 0 { + rest := pathOnly[idx+3:] + if slash := strings.IndexByte(rest, '/'); slash >= 0 { + pathOnly = rest[slash:] + } else { + pathOnly = "/" + } + } + if cut := strings.IndexAny(pathOnly, "?#"); cut >= 0 { + pathOnly = pathOnly[:cut] + } + return strings.HasSuffix(pathOnly, "/error") || + strings.Contains(pathOnly, "/error/") || + strings.HasSuffix(pathOnly, "/error.html") || + strings.HasSuffix(pathOnly, "/error.htm") || + strings.HasSuffix(pathOnly, "/login") || + strings.Contains(pathOnly, "/login/") || + strings.Contains(pathOnly, "/agecheck") +} + +func wave3MediaIsNegativeTitle(title string) bool { + t := strings.TrimSpace(title) + if t == "" { + return false + } + return wave3MediaRxNotFoundTitle.MatchString(t) || + wave3MediaRxMaintTitle.MatchString(t) || + wave3MediaRxErrorTitle.MatchString(t) +} + +func wave3MediaIsGenericTitle(title string) bool { + return wave3MediaRxGenericTitle.MatchString(strings.TrimSpace(title)) +} + +func wave3MediaContainsASCIIFold(haystack, needleLower string) bool { + n := len(needleLower) + if n == 0 { + return true + } + if len(haystack) < n { + return false + } + limit := len(haystack) - n + for i := 0; i <= limit; i++ { + matched := true + for j := 0; j < n; j++ { + hc := haystack[i+j] + if hc >= 'A' && hc <= 'Z' { + hc += 32 + } + if hc != needleLower[j] { + matched = false + break + } + } + if matched { + return true + } + } + return false +} + +func wave3MediaExtractTitleBounded(rawHTML string) string { + head := rawHTML + if len(head) > 65536 { + head = head[:65536] + } + if !wave3MediaContainsASCIIFold(head, "= 2 { + return wave3MediaCleanText(m[1]) + } + return "" +} + +func wave3MediaExtractMetaBounded(rawHTML, targetKey string) string { + head := rawHTML + if len(head) > 65536 { + head = head[:65536] + } + if !wave3MediaContainsASCIIFold(head, " len(probeLower) && len(rawHTML) <= 256*1024 { + rawLower = asciiLowerExtractString(rawHTML) + } + hasRichMarkers := hasJSONLDScriptToken(rawLower) || + strings.Contains(rawLower, " 65536 { + tail := rawHTML[65536:] + hasRichMarkers = indexFoldASCIIExtract(tail, "= 0 || + indexFoldASCIIExtract(tail, "application/ld+json") >= 0 || + indexFoldASCIIExtract(tail, "data-lyrics-container") >= 0 || + indexFoldASCIIExtract(tail, "data-tralbum") >= 0 || + indexFoldASCIIExtract(tail, "azlyrics.com content") >= 0 + } + if (strings.Contains(probeLower, "challenge-platform") || strings.Contains(probeLower, "cf-turnstile")) && + len(rawHTML) < 16384 && !hasRichMarkers { + return true + } + if (wave3HasEmptyRootDivShell(rawHTML, probeLower, true) || + strings.Contains(rawLower, `
`) || + strings.Contains(rawLower, `
`)) && !hasRichMarkers { + return true + } + return false +} + +func wave3MediaIsGenericJSONError(obj map[string]any) bool { + if obj == nil { + return true + } + if succ, ok := obj["success"].(bool); ok && !succ { + return true + } + if succNum, ok := wave3MediaFloatVal(obj["success"]); ok && succNum == 0 { + return true + } + if statusStr, ok := obj["status"].(string); ok && strings.EqualFold(strings.TrimSpace(statusStr), "false") { + return true + } + if statusBool, ok := obj["status"].(bool); ok && !statusBool { + return true + } + if errFlag, ok := obj["error"].(bool); ok && errFlag { + return true + } + for _, k := range []string{"error", "errors", "error_message", "errorMessage", "errorCode", "error_description", "fault"} { + if v, exists := obj[k]; exists && v != nil { + switch tv := v.(type) { + case string: + if strings.TrimSpace(tv) != "" { + return true + } + case float64, int, int64, json.Number: + if f, ok := wave3MediaFloatVal(tv); ok && f != 0 { + return true + } + case []any: + if len(tv) > 0 { + return true + } + case map[string]any: + if len(tv) > 0 { + return true + } + case bool: + if tv { + return true + } + } + } + } + for _, k := range []string{"code", "error_code", "statusCode", "status_code", "status"} { + if f, ok := wave3MediaFloatVal(obj[k]); ok && f >= 400 { + return true + } + } + if sc, ok := wave3MediaFloatVal(obj["status_code"]); ok && (sc == 7 || sc == 34 || sc == 6 || sc >= 400) { + return true + } + for _, mk := range []string{"message", "status_message", "detail", "description"} { + if msg := wave3MediaPlain(obj[mk], 240); msg != "" && len(obj) <= 5 { + lm := strings.ToLower(msg) + if strings.Contains(lm, "not found") || + strings.Contains(lm, "unauthorized") || + strings.Contains(lm, "invalid api key") || + strings.Contains(lm, "authorization header") || + strings.Contains(lm, "must authenticate") || + strings.Contains(lm, "forbidden") || + strings.Contains(lm, "does not exist") { + return true + } + } + } + return false +} + +func wave3MediaIntPtr(n int) *int { return &n } +func wave3MediaBoolPtr(b bool) *bool { return &b } + +func wave3MediaFinalizeDoc(doc *DeclarativeFormattedDoc) *DeclarativeFormattedDoc { + if doc == nil { + return nil + } + if len(doc.Records) > wave3MediaMaxRecords { + if doc.Total == nil { + doc.Total = wave3MediaIntPtr(len(doc.Records)) + } + doc.Records = doc.Records[:wave3MediaMaxRecords] + doc.Returned = wave3MediaIntPtr(len(doc.Records)) + doc.Truncated = wave3MediaBoolPtr(true) + if doc.NextCursor == "" { + doc.NextCursor = strconv.Itoa(len(doc.Records)) + } + } + if sanitized, ok := sanitizeDeclarativeFormattedDocGo(doc); ok && sanitized != nil { + return sanitized + } + return nil +} + +func wave3MediaFinalizePostFetch(res *DeclarativePostFetchResult) *DeclarativePostFetchResult { + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return nil + } + if len(res.Records) > wave3MediaMaxRecords { + if res.Total == nil { + res.Total = wave3MediaIntPtr(len(res.Records)) + } + res.Records = res.Records[:wave3MediaMaxRecords] + res.Returned = wave3MediaIntPtr(len(res.Records)) + res.Truncated = wave3MediaBoolPtr(true) + if res.NextCursor == "" { + res.NextCursor = strconv.Itoa(len(res.Records)) + } + } + return res +} + +func wave3MediaCleanText(s string) string { + if s == "" { + return "" + } + if strings.IndexByte(s, '<') >= 0 { + s = wave3MediaRxHTMLTag.ReplaceAllString(s, " ") + } + if strings.IndexByte(s, '&') >= 0 { + s = stdhtml.UnescapeString(s) + if strings.IndexByte(s, '<') >= 0 { + s = wave3MediaRxHTMLTag.ReplaceAllString(s, " ") + } + } + if !strings.ContainsAny(s, "\t\r\n") && !strings.Contains(s, " ") { + return strings.TrimSpace(s) + } + return strings.TrimSpace(wave3MediaRxSpace.ReplaceAllString(s, " ")) +} + +func wave3MediaHTMLToLines(frag string) string { + if frag == "" { + return "" + } + s := strings.ReplaceAll(frag, "\r\n", "\n") + s = strings.ReplaceAll(s, "\r", "\n") + s = wave3MediaRxBRTag.ReplaceAllString(s, "\n") + s = wave3MediaRxBlockEndTag.ReplaceAllString(s, "\n") + if strings.IndexByte(s, '<') >= 0 { + s = wave3MediaRxHTMLTag.ReplaceAllString(s, "") + } + if strings.IndexByte(s, '&') >= 0 { + s = stdhtml.UnescapeString(s) + } + lines := strings.Split(s, "\n") + cleaned := make([]string, 0, len(lines)) + prevBlank := false + for _, ln := range lines { + ln = strings.TrimSpace(wave3MediaRxHorizSpace.ReplaceAllString(ln, " ")) + if ln == "" { + if len(cleaned) > 0 && !prevBlank { + cleaned = append(cleaned, "") + prevBlank = true + } + continue + } + cleaned = append(cleaned, ln) + prevBlank = false + } + for len(cleaned) > 0 && cleaned[len(cleaned)-1] == "" { + cleaned = cleaned[:len(cleaned)-1] + } + out := strings.Join(cleaned, "\n") + return wave3MediaRxMultiNewline.ReplaceAllString(out, "\n\n") +} + +func wave3MediaStringVal(v any) string { + switch tv := v.(type) { + case string: + return strings.TrimSpace(tv) + case json.Number: + return tv.String() + case float64: + if math.IsNaN(tv) || math.IsInf(tv, 0) { + return "" + } + if tv == math.Trunc(tv) { + return strconv.FormatInt(int64(tv), 10) + } + return strconv.FormatFloat(tv, 'f', -1, 64) + case int: + return strconv.Itoa(tv) + case int64: + return strconv.FormatInt(tv, 10) + case bool: + if tv { + return "true" + } + return "false" + default: + return "" + } +} + +func wave3MediaFloatVal(v any) (float64, bool) { + switch tv := v.(type) { + case float64: + if math.IsNaN(tv) || math.IsInf(tv, 0) { + return 0, false + } + return tv, true + case int: + return float64(tv), true + case int64: + return float64(tv), true + case json.Number: + f, err := tv.Float64() + if err != nil || math.IsNaN(f) || math.IsInf(f, 0) { + return 0, false + } + return f, true + case string: + s := strings.TrimSpace(strings.ReplaceAll(strings.TrimPrefix(strings.TrimSpace(tv), "$"), ",", "")) + if s == "" { + return 0, false + } + f, err := strconv.ParseFloat(s, 64) + if err != nil || math.IsNaN(f) || math.IsInf(f, 0) { + return 0, false + } + return f, true + default: + return 0, false + } +} + +func wave3MediaPlain(v any, maxLen int) string { + return SanitizeSchemaPlainField(wave3MediaCleanText(wave3MediaStringVal(v)), maxLen) +} + +func wave3MediaFirstNonEmpty(vals ...string) string { + for _, v := range vals { + if t := strings.TrimSpace(v); t != "" { + return t + } + } + return "" +} + +func wave3MediaAddLink(links *[]string, seen map[string]bool, raw, base string) { + u := SanitizeSchemaHTTPSURL(raw, base) + if u != "" && !seen[u] { + seen[u] = true + *links = append(*links, u) + } +} + +func wave3MediaNestedMap(obj map[string]any, keys ...string) map[string]any { + cur := obj + for _, k := range keys { + if cur == nil { + return nil + } + next, ok := cur[k].(map[string]any) + if !ok { + return nil + } + cur = next + } + return cur +} + +func wave3MediaExtractTitle(doc *HTMLDoc, rawHTML string) string { + if doc != nil { + if h1 := SanitizeSchemaPlainField(wave3MediaCleanText(doc.Text("h1")), 240); h1 != "" && !wave3MediaIsGenericTitle(h1) && !wave3MediaIsNegativeTitle(h1) { + return h1 + } + } + if og := SanitizeSchemaPlainField(wave3MediaExtractMetaBounded(rawHTML, "og:title"), 240); og != "" && !wave3MediaIsGenericTitle(og) && !wave3MediaIsNegativeTitle(og) { + return og + } + if t := SanitizeSchemaPlainField(wave3MediaExtractTitleBounded(rawHTML), 240); t != "" && !wave3MediaIsGenericTitle(t) && !wave3MediaIsNegativeTitle(t) { + return t + } + return "" +} + +func wave3MediaExtractMetaDesc(rawHTML string) string { + return wave3MediaFirstNonEmpty( + SanitizeSchemaPlainField(wave3MediaExtractMetaBounded(rawHTML, "og:description"), 600), + SanitizeSchemaPlainField(wave3MediaExtractMetaBounded(rawHTML, "description"), 600), + ) +} + +func wave3MediaHasSchemaType(obj map[string]any, wanted ...string) bool { + if obj == nil { + return false + } + check := func(s string) bool { + low := strings.ToLower(strings.TrimSpace(s)) + if idx := strings.LastIndexByte(low, '/'); idx >= 0 { + low = low[idx+1:] + } + for _, w := range wanted { + if low == strings.ToLower(w) { + return true + } + } + return false + } + switch t := obj["@type"].(type) { + case string: + return check(t) + case []any: + for _, it := range t { + if s, ok := it.(string); ok && check(s) { + return true + } + } + } + return false +} + +func wave3MediaNameField(v any, maxLen int) string { + switch tv := v.(type) { + case string: + return SanitizeSchemaPlainField(wave3MediaCleanText(tv), maxLen) + case map[string]any: + return wave3MediaPlain(tv["name"], maxLen) + case []any: + var names []string + for _, el := range tv { + if n := wave3MediaNameField(el, maxLen); n != "" { + names = append(names, n) + } + if len(names) >= 8 { + break + } + } + return strings.Join(names, ", ") + } + return "" +} + +func wave3MediaExtractNextDataObj(rawHTML string) map[string]any { + if !strings.Contains(rawHTML, "__NEXT_DATA__") && !wave3MediaContainsASCIIFold(rawHTML, "__next_data__") { + return nil + } + m := wave3MediaRxNextData.FindStringSubmatch(rawHTML) + if len(m) < 2 { + return nil + } + raw := strings.TrimSpace(m[1]) + if raw == "" || raw[0] != '{' { + return nil + } + parsed, ok := decodeJSONWithNumbers([]byte(raw)) + if !ok { + return nil + } + obj, _ := parsed.(map[string]any) + return obj +} + +func wave3MediaJoinNamesArray(arr []any, key string, limit int) []string { + var out []string + seen := make(map[string]bool) + for _, el := range arr { + if len(out) >= limit { + break + } + switch tv := el.(type) { + case string: + if s := SanitizeSchemaPlainField(wave3MediaCleanText(tv), 100); s != "" && !seen[s] { + seen[s] = true + out = append(out, s) + } + case map[string]any: + if s := wave3MediaPlain(tv[key], 100); s != "" && !seen[s] { + seen[s] = true + out = append(out, s) + } + } + } + return out +} + +// ── #375 TMDB (`tmdb_json`, `tmdb_html`) ───────────────────────────────────────────────────────── + +func wave3MediaFormatTMDBJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + obj, ok := parsed.(map[string]any) + if !ok || obj == nil { + return nil, false + } + + // Search / list results (`results[]`) + if results, hasRes := obj["results"].([]any); hasRes { + if len(results) == 0 { + return nil, false + } + var recs []map[string]any + var rows [][]string + for _, item := range results { + if len(recs) >= wave3MediaMaxRecords { + break + } + m, okM := item.(map[string]any) + if !okM { + continue + } + name := wave3MediaFirstNonEmpty(wave3MediaPlain(m["title"], 200), wave3MediaPlain(m["name"], 200)) + if name == "" { + continue + } + idStr := wave3MediaPlain(m["id"], 24) + mediaType := wave3MediaFirstNonEmpty(wave3MediaPlain(m["media_type"], 32), "item") + relDate := wave3MediaFirstNonEmpty(wave3MediaPlain(m["release_date"], 32), wave3MediaPlain(m["first_air_date"], 32)) + vote := wave3MediaPlain(m["vote_average"], 16) + rows = append(rows, []string{ + escapeDeclMarkdownBrackets(name), + wave3MediaFirstNonEmpty(escapeDeclMarkdownBrackets(idStr), "-"), + escapeDeclMarkdownBrackets(mediaType), + wave3MediaFirstNonEmpty(escapeDeclMarkdownBrackets(relDate), "-"), + wave3MediaFirstNonEmpty(escapeDeclMarkdownBrackets(vote), "-"), + }) + rec := map[string]any{"title": name} + if idStr != "" { + rec["id"] = idStr + } + if relDate != "" { + rec["releaseDate"] = relDate + } + if vote != "" { + rec["voteAverage"] = vote + } + recs = append(recs, rec) + } + if len(recs) == 0 { + return nil, false + } + title := "TMDB Search Results" + md := "# " + title + "\n\n" + formatDeclarativeGFMTable([]string{"Title", "ID", "Type", "Date", "Rating"}, rows) + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: md, + Records: recs, + }, true + } + + title := wave3MediaFirstNonEmpty(wave3MediaPlain(obj["title"], 240), wave3MediaPlain(obj["name"], 240)) + idStr := wave3MediaPlain(obj["id"], 24) + if title == "" || idStr == "" { + return nil, false + } + origTitle := wave3MediaFirstNonEmpty(wave3MediaPlain(obj["original_title"], 240), wave3MediaPlain(obj["original_name"], 240)) + tagline := wave3MediaPlain(obj["tagline"], 240) + relDate := wave3MediaFirstNonEmpty(wave3MediaPlain(obj["release_date"], 32), wave3MediaPlain(obj["first_air_date"], 32), wave3MediaPlain(obj["birthday"], 32)) + status := wave3MediaPlain(obj["status"], 64) + runtime := wave3MediaPlain(obj["runtime"], 24) + if runtime == "" { + if ert, okE := obj["episode_run_time"].([]any); okE && len(ert) > 0 { + runtime = wave3MediaPlain(ert[0], 24) + } + } + seasons := wave3MediaPlain(obj["number_of_seasons"], 16) + episodes := wave3MediaPlain(obj["number_of_episodes"], 16) + voteAvg := wave3MediaPlain(obj["vote_average"], 16) + voteCnt := wave3MediaPlain(obj["vote_count"], 16) + imdbID := wave3MediaPlain(obj["imdb_id"], 32) + knownFor := wave3MediaPlain(obj["known_for_department"], 80) + placeOfBirth := wave3MediaPlain(obj["place_of_birth"], 140) + overview := wave3MediaFirstNonEmpty(wave3MediaPlain(obj["overview"], 2000), wave3MediaPlain(obj["biography"], 2000)) + + var genres []string + if gArr, okG := obj["genres"].([]any); okG { + genres = wave3MediaJoinNamesArray(gArr, "name", 10) + } + var networks []string + if nArr, okN := obj["networks"].([]any); okN { + networks = wave3MediaJoinNamesArray(nArr, "name", 8) + } + + var bullets []string + bullets = append(bullets, "- **TMDB ID**: "+escapeDeclMarkdownBrackets(idStr)) + if origTitle != "" && origTitle != title { + bullets = append(bullets, "- **Original Title**: "+escapeDeclMarkdownBrackets(origTitle)) + } + if tagline != "" { + bullets = append(bullets, "- **Tagline**: "+escapeDeclMarkdownBrackets(tagline)) + } + if relDate != "" { + bullets = append(bullets, "- **Date**: "+escapeDeclMarkdownBrackets(relDate)) + } + if runtime != "" { + bullets = append(bullets, "- **Runtime**: "+escapeDeclMarkdownBrackets(runtime)+" min") + } + if seasons != "" { + bullets = append(bullets, "- **Seasons / Episodes**: "+escapeDeclMarkdownBrackets(seasons)+" / "+wave3MediaFirstNonEmpty(escapeDeclMarkdownBrackets(episodes), "-")) + } + if len(genres) > 0 { + bullets = append(bullets, "- **Genres**: "+escapeDeclMarkdownBrackets(strings.Join(genres, ", "))) + } + if len(networks) > 0 { + bullets = append(bullets, "- **Networks**: "+escapeDeclMarkdownBrackets(strings.Join(networks, ", "))) + } + if voteAvg != "" { + ratingDisp := voteAvg + if voteCnt != "" { + ratingDisp += fmt.Sprintf(" (%s votes)", voteCnt) + } + bullets = append(bullets, "- **Rating**: "+escapeDeclMarkdownBrackets(ratingDisp)) + } + if status != "" { + bullets = append(bullets, "- **Status**: "+escapeDeclMarkdownBrackets(status)) + } + if imdbID != "" { + bullets = append(bullets, "- **IMDb ID**: "+escapeDeclMarkdownBrackets(imdbID)) + } + if knownFor != "" { + bullets = append(bullets, "- **Known For**: "+escapeDeclMarkdownBrackets(knownFor)) + } + if placeOfBirth != "" { + bullets = append(bullets, "- **Place of Birth**: "+escapeDeclMarkdownBrackets(placeOfBirth)) + } + + var links []string + seen := make(map[string]bool) + if hp := SanitizeSchemaHTTPSURL(wave3MediaStringVal(obj["homepage"]), origURL); hp != "" { + wave3MediaAddLink(&links, seen, hp, origURL) + } + + blocks := []string{"# " + escapeDeclMarkdownBrackets(title), strings.Join(bullets, "\n")} + if overview != "" { + blocks = append(blocks, "## Overview\n\n"+escapeDeclPlainTextPreservingNewlines(overview)) + } + if parts, okP := obj["parts"].([]any); okP && len(parts) > 0 { + var rows [][]string + for _, rp := range parts { + if len(rows) >= wave3MediaMaxRecords { + break + } + if pm, okPM := rp.(map[string]any); okPM { + pt := wave3MediaPlain(pm["title"], 180) + if pt != "" { + rows = append(rows, []string{ + escapeDeclMarkdownBrackets(pt), + wave3MediaFirstNonEmpty(escapeDeclMarkdownBrackets(wave3MediaPlain(pm["release_date"], 24)), "-"), + wave3MediaFirstNonEmpty(escapeDeclMarkdownBrackets(wave3MediaPlain(pm["vote_average"], 16)), "-"), + }) + } + } + } + if len(rows) > 0 { + blocks = append(blocks, "## Parts\n\n"+formatDeclarativeGFMTable([]string{"Title", "Release Date", "Rating"}, rows)) + } + } + + rec := map[string]any{ + "id": idStr, + "title": title, + } + if relDate != "" { + rec["releaseDate"] = relDate + } + if len(genres) > 0 { + rec["genres"] = genres + } + if voteAvg != "" { + rec["voteAverage"] = voteAvg + } + if imdbID != "" { + rec["imdbId"] = imdbID + } + if status != "" { + rec["status"] = status + } + + return &DeclarativeFormattedDoc{ + Title: title, + Description: sliceRunesMax(overview, 260), + PublishedTime: relDate, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: []map[string]any{rec}, + }, true +} + +func wave3MediaExtractTMDBHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + ldObjs := extractJSONLDObjectsDeclHTML(rawHTML, 16) + var entity map[string]any + for _, obj := range ldObjs { + if wave3MediaHasSchemaType(obj, "Movie", "TVSeries", "Person", "TVEpisode") { + entity = obj + break + } + } + var doc *HTMLDoc + ensureDoc := func() *HTMLDoc { + if doc == nil { + doc = ParseHTMLDoc(rawHTML, wave3MediaMaxHTMLBytes) + } + return doc + } + title := wave3MediaExtractTitle(nil, rawHTML) + if title == "" && (strings.Contains(rawHTML, " 0 { + bullets = append(bullets, "- **Genres**: "+escapeDeclMarkdownBrackets(strings.Join(genres, ", "))) + rec["genres"] = genres + } + if rating != "" { + bullets = append(bullets, "- **Rating**: "+escapeDeclMarkdownBrackets(rating)) + rec["rating"] = rating + } + if len(bullets) == 0 && desc == "" { + return nil + } + + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + if desc != "" { + blocks = append(blocks, "## Overview\n\n"+escapeDeclPlainTextPreservingNewlines(desc)) + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: sliceRunesMax(desc, 260), + PublishedTime: relDate, + Markdown: strings.Join(blocks, "\n\n"), + Records: []map[string]any{rec}, + } +} + +// ── #376 IMDb Datasets (`imdb_datasets_tsv`, `imdb_datasets_html`) ────────────────────────────── + +func wave3MediaFormatIMDbDatasetsTSV(rawBody, origURL string) (*DeclarativeFormattedDoc, bool) { + trimmed := strings.TrimSpace(strings.TrimPrefix(rawBody, "\ufeff")) + if trimmed == "" { + return nil, false + } + probeLen := len(trimmed) + if probeLen > 2048 { + probeLen = 2048 + } + low := asciiLowerExtractString(trimmed[:probeLen]) + if strings.HasPrefix(low, "= wave3MediaMaxRecords { + break + } + line := strings.TrimRight(rawLine, "\r") + if strings.TrimSpace(line) == "" { + continue + } + cols := strings.Split(line, "\t") + if len(cols) < len(cleanHeaders) { + // Truncated final line from Range fetch — ignore partial trailing row + continue + } + rowCells := make([]string, len(cleanHeaders)) + rec := map[string]any{ + "nonCommercialLicense": true, + "license": "IMDb Non-Commercial Datasets", + } + for i, hdr := range cleanHeaders { + val := strings.TrimSpace(cols[i]) + if val == `\N` || val == "" { + rowCells[i] = "-" + } else { + cleanVal := SanitizeSchemaPlainField(val, 140) + rowCells[i] = escapeDeclMarkdownBrackets(wave3MediaFirstNonEmpty(cleanVal, "-")) + rec[hdr] = cleanVal + } + } + rows = append(rows, rowCells) + recs = append(recs, rec) + } + if len(recs) == 0 { + return nil, false + } + + datasetName := "IMDb Non-Commercial Dataset" + if idx := strings.LastIndexByte(origURL, '/'); idx >= 0 && idx+1 < len(origURL) { + filePart := origURL[idx+1:] + if q := strings.IndexByte(filePart, '?'); q >= 0 { + filePart = filePart[:q] + } + if cleanFile := SanitizeSchemaPlainField(filePart, 80); cleanFile != "" { + datasetName = "IMDb Non-Commercial Datasets: " + cleanFile + } + } + + escapedHeaders := make([]string, len(cleanHeaders)) + for i, h := range cleanHeaders { + escapedHeaders[i] = escapeDeclMarkdownBrackets(h) + } + notice := "- **License**: IMDb Non-Commercial Datasets (`nonCommercialLicense: true`) — Personal and non-commercial use only per IMDb Non-Commercial Datasets terms." + md := "# " + escapeDeclMarkdownBrackets(datasetName) + "\n\n" + notice + "\n\n" + formatDeclarativeGFMTable(escapedHeaders, rows) + return &DeclarativeFormattedDoc{ + Title: datasetName, + Description: "IMDb Non-Commercial Datasets TSV sample (nonCommercialLicense: true).", + Markdown: md, + Records: recs, + }, true +} + +func wave3MediaExtractIMDbDatasetsHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + var links []string + seen := make(map[string]bool) + for _, match := range wave3MediaRxImdbGZLink.FindAllString(rawHTML, 25) { + wave3MediaAddLink(&links, seen, match, baseURL) + } + + var recs []map[string]any + var rows [][]string + for _, l := range links { + if len(recs) >= wave3MediaMaxRecords { + break + } + fname := l + if slash := strings.LastIndexByte(l, '/'); slash >= 0 && slash+1 < len(l) { + fname = l[slash+1:] + } + rows = append(rows, []string{escapeDeclMarkdownBrackets(fname), l}) + recs = append(recs, map[string]any{ + "dataset": fname, + "url": l, + "nonCommercialLicense": true, + "license": "IMDb Non-Commercial Datasets", + }) + } + + nextObj := wave3MediaExtractNextDataObj(rawHTML) + var doc *HTMLDoc + if len(recs) == 0 { + doc = ParseHTMLDoc(rawHTML, wave3MediaMaxHTMLBytes) + if doc != nil { + for _, a := range doc.Select("a[href]", 60) { + href := SanitizeSchemaHTTPSURL(a.AttrOrEmpty("href"), baseURL) + if strings.Contains(href, "datasets.imdbws.com") && strings.HasSuffix(strings.ToLower(href), ".tsv.gz") { + wave3MediaAddLink(&links, seen, href, baseURL) + fname := href[strings.LastIndexByte(href, '/')+1:] + rows = append(rows, []string{escapeDeclMarkdownBrackets(fname), href}) + recs = append(recs, map[string]any{ + "dataset": fname, + "url": href, + "nonCommercialLicense": true, + "license": "IMDb Non-Commercial Datasets", + }) + } + } + } + } + + title := wave3MediaExtractTitle(doc, rawHTML) + if title == "" { + if nextObj != nil { + if pp := wave3MediaNestedMap(nextObj, "props", "pageProps"); pp != nil { + title = wave3MediaPlain(pp["title"], 200) + } + } + } + if len(recs) == 0 && title == "" { + return nil + } + if title == "" { + title = "IMDb Non-Commercial Datasets" + } + + desc := wave3MediaExtractMetaDesc(rawHTML) + if len(recs) == 0 && desc == "" && doc != nil { + desc = SanitizeSchemaPlainField(wave3MediaCleanText(doc.Text("main p, article p")), 600) + } + if len(recs) == 0 && desc == "" { + return nil + } + if len(recs) == 0 { + recs = []map[string]any{{ + "title": title, + "nonCommercialLicense": true, + "license": "IMDb Non-Commercial Datasets", + }} + } + + blocks := []string{ + "# " + escapeDeclMarkdownBrackets(title), + "- **License**: IMDb Non-Commercial Datasets (`nonCommercialLicense: true`) — Personal and non-commercial use only per IMDb Non-Commercial Datasets terms.", + } + if desc != "" { + blocks = append(blocks, escapeDeclPlainTextPreservingNewlines(desc)) + } + if len(rows) > 0 { + blocks = append(blocks, "## Available Dataset Files\n\n"+formatDeclarativeGFMTable([]string{"File", "URL"}, rows)) + } + + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: sliceRunesMax(desc, 260), + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: recs, + } +} + +// ── #377 TVmaze (`tvmaze_json`, `tvmaze_html`) ─────────────────────────────────────────────────── + +func wave3MediaFormatTVmazeJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + if arr, isArr := parsed.([]any); isArr { + if len(arr) == 0 { + return nil, false + } + var recs []map[string]any + var rows [][]string + var links []string + seen := make(map[string]bool) + for _, el := range arr { + if len(recs) >= wave3MediaMaxRecords { + break + } + m, okM := el.(map[string]any) + if !okM { + continue + } + target := m + if showMap := wave3MediaNestedMap(m, "show"); showMap != nil { + target = showMap + } + name := wave3MediaPlain(target["name"], 200) + if name == "" { + continue + } + idStr := wave3MediaPlain(target["id"], 24) + premiered := wave3MediaFirstNonEmpty(wave3MediaPlain(target["premiered"], 32), wave3MediaPlain(target["airdate"], 32)) + status := wave3MediaPlain(target["status"], 48) + itemURL := SanitizeSchemaHTTPSURL(wave3MediaStringVal(target["url"]), origURL) + wave3MediaAddLink(&links, seen, itemURL, origURL) + rows = append(rows, []string{ + escapeDeclMarkdownBrackets(name), + wave3MediaFirstNonEmpty(escapeDeclMarkdownBrackets(idStr), "-"), + wave3MediaFirstNonEmpty(escapeDeclMarkdownBrackets(premiered), "-"), + wave3MediaFirstNonEmpty(escapeDeclMarkdownBrackets(status), "-"), + }) + rec := map[string]any{"title": name} + if idStr != "" { + rec["id"] = idStr + } + if premiered != "" { + rec["premiered"] = premiered + } + if itemURL != "" { + rec["url"] = itemURL + } + recs = append(recs, rec) + } + if len(recs) == 0 { + return nil, false + } + title := "TVmaze Results" + md := "# " + title + "\n\n" + formatDeclarativeGFMTable([]string{"Name", "ID", "Date", "Status"}, rows) + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: md, + Links: links, + Records: recs, + }, true + } + + obj, ok := parsed.(map[string]any) + if !ok || obj == nil { + return nil, false + } + name := wave3MediaPlain(obj["name"], 240) + idStr := wave3MediaPlain(obj["id"], 24) + if name == "" || idStr == "" { + return nil, false + } + + showType := wave3MediaPlain(obj["type"], 64) + lang := wave3MediaPlain(obj["language"], 48) + status := wave3MediaPlain(obj["status"], 64) + runtime := wave3MediaPlain(obj["runtime"], 24) + premiered := wave3MediaFirstNonEmpty(wave3MediaPlain(obj["premiered"], 32), wave3MediaPlain(obj["airdate"], 32)) + ended := wave3MediaPlain(obj["ended"], 32) + summary := wave3MediaPlain(obj["summary"], 1800) + var genres []string + if gArr, okG := obj["genres"].([]any); okG { + genres = wave3MediaJoinNamesArray(gArr, "name", 10) + } + rating := "" + if rm := wave3MediaNestedMap(obj, "rating"); rm != nil { + rating = wave3MediaPlain(rm["average"], 16) + } + network := "" + if nm := wave3MediaNestedMap(obj, "network"); nm != nil { + network = wave3MediaPlain(nm["name"], 100) + } else if wc := wave3MediaNestedMap(obj, "webChannel"); wc != nil { + network = wave3MediaPlain(wc["name"], 100) + } + imdbID := "" + if ext := wave3MediaNestedMap(obj, "externals"); ext != nil { + imdbID = wave3MediaPlain(ext["imdb"], 32) + } + + var links []string + seen := make(map[string]bool) + pageURL := SanitizeSchemaHTTPSURL(wave3MediaStringVal(obj["url"]), origURL) + wave3MediaAddLink(&links, seen, pageURL, origURL) + + var bullets []string + bullets = append(bullets, "- **TVmaze ID**: "+escapeDeclMarkdownBrackets(idStr)) + if showType != "" { + bullets = append(bullets, "- **Type**: "+escapeDeclMarkdownBrackets(showType)) + } + if lang != "" { + bullets = append(bullets, "- **Language**: "+escapeDeclMarkdownBrackets(lang)) + } + if status != "" { + bullets = append(bullets, "- **Status**: "+escapeDeclMarkdownBrackets(status)) + } + if premiered != "" { + bullets = append(bullets, "- **Premiered / Airdate**: "+escapeDeclMarkdownBrackets(premiered)) + } + if ended != "" { + bullets = append(bullets, "- **Ended**: "+escapeDeclMarkdownBrackets(ended)) + } + if runtime != "" { + bullets = append(bullets, "- **Runtime**: "+escapeDeclMarkdownBrackets(runtime)+" min") + } + if len(genres) > 0 { + bullets = append(bullets, "- **Genres**: "+escapeDeclMarkdownBrackets(strings.Join(genres, ", "))) + } + if rating != "" { + bullets = append(bullets, "- **Rating**: "+escapeDeclMarkdownBrackets(rating)) + } + if network != "" { + bullets = append(bullets, "- **Network**: "+escapeDeclMarkdownBrackets(network)) + } + if imdbID != "" { + bullets = append(bullets, "- **IMDb**: "+escapeDeclMarkdownBrackets(imdbID)) + } + + blocks := []string{"# " + escapeDeclMarkdownBrackets(name), strings.Join(bullets, "\n")} + if summary != "" { + blocks = append(blocks, "## Summary\n\n"+escapeDeclPlainTextPreservingNewlines(summary)) + } + + rec := map[string]any{ + "id": idStr, + "title": name, + } + if premiered != "" { + rec["premiered"] = premiered + } + if status != "" { + rec["status"] = status + } + if len(genres) > 0 { + rec["genres"] = genres + } + if network != "" { + rec["network"] = network + } + if imdbID != "" { + rec["imdbId"] = imdbID + } + if pageURL != "" { + rec["url"] = pageURL + } + + if emb := wave3MediaNestedMap(obj, "_embedded"); emb != nil { + if eps, okE := emb["episodes"].([]any); okE && len(eps) > 0 { + var rows [][]string + for _, re := range eps { + if len(rows) >= wave3MediaMaxRecords { + break + } + if em, okEM := re.(map[string]any); okEM { + epName := wave3MediaPlain(em["name"], 160) + if epName == "" { + continue + } + sNum := wave3MediaPlain(em["season"], 8) + eNum := wave3MediaPlain(em["number"], 8) + air := wave3MediaPlain(em["airdate"], 24) + code := fmt.Sprintf("S%sE%s", wave3MediaFirstNonEmpty(sNum, "?"), wave3MediaFirstNonEmpty(eNum, "?")) + rows = append(rows, []string{escapeDeclMarkdownBrackets(code), escapeDeclMarkdownBrackets(epName), wave3MediaFirstNonEmpty(escapeDeclMarkdownBrackets(air), "-")}) + } + } + if len(rows) > 0 { + blocks = append(blocks, "## Episodes\n\n"+formatDeclarativeGFMTable([]string{"Episode", "Title", "Airdate"}, rows)) + } + } + } + + return &DeclarativeFormattedDoc{ + Title: name, + Description: sliceRunesMax(summary, 260), + PublishedTime: premiered, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: []map[string]any{rec}, + }, true +} + +func wave3MediaExtractTVmazeHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + ldObjs := extractJSONLDObjectsDeclHTML(rawHTML, 16) + var tvObj map[string]any + for _, obj := range ldObjs { + if wave3MediaHasSchemaType(obj, "TVSeries", "TVEpisode", "Person") { + tvObj = obj + break + } + } + doc := ParseHTMLDoc(rawHTML, wave3MediaMaxHTMLBytes) + title := wave3MediaExtractTitle(doc, rawHTML) + if tvObj != nil { + if n := wave3MediaPlain(tvObj["name"], 240); n != "" { + title = n + } + } + if title == "" { + return nil + } + desc := wave3MediaExtractMetaDesc(rawHTML) + var bullets []string + if tvObj != nil { + if d := wave3MediaPlain(tvObj["description"], 1600); d != "" { + desc = d + } + if dp := wave3MediaPlain(tvObj["datePublished"], 32); dp != "" { + bullets = append(bullets, "- **Published**: "+escapeDeclMarkdownBrackets(dp)) + } + } + if doc != nil { + if sum := SanitizeSchemaPlainField(wave3MediaCleanText(doc.Text("#general-info-panel p, .show-summary")), 1600); sum != "" && desc == "" { + desc = sum + } + if info := SanitizeSchemaPlainField(wave3MediaCleanText(doc.Text("#general-info-panel")), 600); info != "" && len(bullets) == 0 { + bullets = append(bullets, "- **Info**: "+escapeDeclMarkdownBrackets(info)) + } + } + if len(bullets) == 0 && desc == "" { + return nil + } + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + if desc != "" { + blocks = append(blocks, "## Summary\n\n"+escapeDeclPlainTextPreservingNewlines(desc)) + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: sliceRunesMax(desc, 260), + Markdown: strings.Join(blocks, "\n\n"), + Records: []map[string]any{{"title": title}}, + } +} + +// ── #378 MusicBrainz & Cover Art Archive ───────────────────────────────────────────────────────── + +func wave3MediaFormatMusicBrainzJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + obj, ok := parsed.(map[string]any) + if !ok || obj == nil { + return nil, false + } + + // Search wrapper (`artists`, `releases`, `recordings`, `release-groups`) + for _, listKey := range []string{"artists", "releases", "recordings", "release-groups"} { + if arr, okL := obj[listKey].([]any); okL { + if len(arr) == 0 { + return nil, false + } + var recs []map[string]any + var rows [][]string + for _, it := range arr { + if len(recs) >= wave3MediaMaxRecords { + break + } + m, okM := it.(map[string]any) + if !okM { + continue + } + name := wave3MediaFirstNonEmpty(wave3MediaPlain(m["title"], 200), wave3MediaPlain(m["name"], 200)) + mbid := wave3MediaPlain(m["id"], 64) + if name == "" || mbid == "" { + continue + } + dateStr := wave3MediaPlain(m["date"], 32) + country := wave3MediaPlain(m["country"], 16) + rows = append(rows, []string{ + escapeDeclMarkdownBrackets(name), + escapeDeclMarkdownBrackets(mbid), + wave3MediaFirstNonEmpty(escapeDeclMarkdownBrackets(dateStr), "-"), + wave3MediaFirstNonEmpty(escapeDeclMarkdownBrackets(country), "-"), + }) + recs = append(recs, map[string]any{ + "id": mbid, + "name": name, + }) + } + if len(recs) == 0 { + return nil, false + } + title := "MusicBrainz Search (" + listKey + ")" + md := "# " + escapeDeclMarkdownBrackets(title) + "\n\n" + formatDeclarativeGFMTable([]string{"Name", "MBID", "Date", "Country"}, rows) + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: md, + Records: recs, + }, true + } + } + + mbid := wave3MediaPlain(obj["id"], 64) + title := wave3MediaFirstNonEmpty(wave3MediaPlain(obj["title"], 240), wave3MediaPlain(obj["name"], 240)) + if mbid == "" || title == "" { + return nil, false + } + + entityType := wave3MediaPlain(obj["type"], 64) + country := wave3MediaPlain(obj["country"], 32) + date := wave3MediaFirstNonEmpty(wave3MediaPlain(obj["date"], 32), wave3MediaPlain(obj["first-release-date"], 32)) + status := wave3MediaPlain(obj["status"], 48) + barcode := wave3MediaPlain(obj["barcode"], 48) + disamb := wave3MediaPlain(obj["disambiguation"], 180) + + var artists []string + if ac, okAC := obj["artist-credit"].([]any); okAC { + for _, el := range ac { + if am, okAM := el.(map[string]any); okAM { + if n := wave3MediaFirstNonEmpty(wave3MediaPlain(am["name"], 120), wave3MediaPlain(wave3MediaNestedMap(am, "artist")["name"], 120)); n != "" { + artists = append(artists, n) + } + } + } + } + var tags []string + for _, tk := range []string{"genres", "tags"} { + if tArr, okT := obj[tk].([]any); okT { + tags = append(tags, wave3MediaJoinNamesArray(tArr, "name", 10)...) + } + } + var lifeSpan string + if ls := wave3MediaNestedMap(obj, "life-span"); ls != nil { + beg := wave3MediaPlain(ls["begin"], 32) + end := wave3MediaPlain(ls["end"], 32) + if beg != "" || end != "" { + lifeSpan = wave3MediaFirstNonEmpty(beg, "?") + " - " + wave3MediaFirstNonEmpty(end, "present") + } + } + areaName := "" + if area := wave3MediaNestedMap(obj, "area"); area != nil { + areaName = wave3MediaPlain(area["name"], 100) + } + + var bullets []string + bullets = append(bullets, "- **MBID**: "+escapeDeclMarkdownBrackets(mbid)) + if len(artists) > 0 { + bullets = append(bullets, "- **Artist**: "+escapeDeclMarkdownBrackets(strings.Join(artists, ", "))) + } + if entityType != "" { + bullets = append(bullets, "- **Type**: "+escapeDeclMarkdownBrackets(entityType)) + } + if date != "" { + bullets = append(bullets, "- **Date**: "+escapeDeclMarkdownBrackets(date)) + } + if lifeSpan != "" { + bullets = append(bullets, "- **Active**: "+escapeDeclMarkdownBrackets(lifeSpan)) + } + if country != "" { + bullets = append(bullets, "- **Country**: "+escapeDeclMarkdownBrackets(country)) + } + if areaName != "" { + bullets = append(bullets, "- **Area**: "+escapeDeclMarkdownBrackets(areaName)) + } + if status != "" { + bullets = append(bullets, "- **Status**: "+escapeDeclMarkdownBrackets(status)) + } + if barcode != "" { + bullets = append(bullets, "- **Barcode**: "+escapeDeclMarkdownBrackets(barcode)) + } + if disamb != "" { + bullets = append(bullets, "- **Disambiguation**: "+escapeDeclMarkdownBrackets(disamb)) + } + if len(tags) > 0 { + bullets = append(bullets, "- **Tags / Genres**: "+escapeDeclMarkdownBrackets(strings.Join(tags, ", "))) + } + + blocks := []string{"# " + escapeDeclMarkdownBrackets(title), strings.Join(bullets, "\n")} + + if media, okM := obj["media"].([]any); okM && len(media) > 0 { + var rows [][]string + for _, rm := range media { + mm, okMM := rm.(map[string]any) + if !okMM { + continue + } + tracks, _ := mm["tracks"].([]any) + for _, rt := range tracks { + if len(rows) >= wave3MediaMaxRecords { + break + } + tm, okTM := rt.(map[string]any) + if !okTM { + continue + } + tNum := wave3MediaPlain(tm["number"], 12) + tTitle := wave3MediaPlain(tm["title"], 180) + if tTitle == "" { + continue + } + lenMs := "" + if f, okF := wave3MediaFloatVal(tm["length"]); okF && f > 0 { + sec := int(f / 1000) + lenMs = fmt.Sprintf("%d:%02d", sec/60, sec%60) + } + rows = append(rows, []string{wave3MediaFirstNonEmpty(escapeDeclMarkdownBrackets(tNum), "-"), escapeDeclMarkdownBrackets(tTitle), wave3MediaFirstNonEmpty(escapeDeclMarkdownBrackets(lenMs), "-")}) + } + } + if len(rows) > 0 { + blocks = append(blocks, "## Tracklist\n\n"+formatDeclarativeGFMTable([]string{"#", "Track", "Length"}, rows)) + } + } + + rec := map[string]any{ + "mbid": mbid, + "title": title, + } + if len(artists) > 0 { + rec["artist"] = strings.Join(artists, ", ") + } + if date != "" { + rec["date"] = date + } + if country != "" { + rec["country"] = country + } + if barcode != "" { + rec["barcode"] = barcode + } + + return &DeclarativeFormattedDoc{ + Title: title, + Author: strings.Join(artists, ", "), + PublishedTime: date, + Markdown: strings.Join(blocks, "\n\n"), + Records: []map[string]any{rec}, + }, true +} + +func wave3MediaFormatCoverArtJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + obj, ok := parsed.(map[string]any) + if !ok || obj == nil { + return nil, false + } + images, okI := obj["images"].([]any) + if !okI || len(images) == 0 { + return nil, false + } + + releaseURL := SanitizeSchemaHTTPSURL(wave3MediaStringVal(obj["release"]), origURL) + var links []string + seen := make(map[string]bool) + wave3MediaAddLink(&links, seen, releaseURL, origURL) + + var recs []map[string]any + var rows [][]string + for _, rawImg := range images { + if len(recs) >= wave3MediaMaxRecords { + break + } + im, okIM := rawImg.(map[string]any) + if !okIM { + continue + } + imgID := wave3MediaPlain(im["id"], 48) + imgURL := SanitizeSchemaHTTPSURL(wave3MediaStringVal(im["image"]), origURL) + var types []string + if tArr, okT := im["types"].([]any); okT { + types = wave3MediaJoinNamesArray(tArr, "", 6) + } + front := wave3MediaPlain(im["front"], 12) + approved := wave3MediaPlain(im["approved"], 12) + comment := wave3MediaPlain(im["comment"], 120) + wave3MediaAddLink(&links, seen, imgURL, origURL) + + typesDisp := wave3MediaFirstNonEmpty(strings.Join(types, ", "), "-") + rows = append(rows, []string{ + wave3MediaFirstNonEmpty(escapeDeclMarkdownBrackets(imgID), "-"), + escapeDeclMarkdownBrackets(typesDisp), + wave3MediaFirstNonEmpty(escapeDeclMarkdownBrackets(front), "-"), + wave3MediaFirstNonEmpty(escapeDeclMarkdownBrackets(approved), "-"), + wave3MediaFirstNonEmpty(imgURL, "-"), + }) + rec := map[string]any{ + "id": imgID, + "types": types, + "front": front == "true", + } + if imgURL != "" { + rec["image"] = imgURL + } + if comment != "" { + rec["comment"] = comment + } + if releaseURL != "" { + rec["release"] = releaseURL + } + recs = append(recs, rec) + } + if len(recs) == 0 { + return nil, false + } + + title := "Cover Art Archive Release Images" + var bullets []string + if releaseURL != "" { + bullets = append(bullets, "- **Release**: "+releaseURL) + } + bullets = append(bullets, fmt.Sprintf("- **Images**: %d", len(images))) + + md := "# " + title + "\n\n" + strings.Join(bullets, "\n") + "\n\n" + formatDeclarativeGFMTable([]string{"ID", "Types", "Front", "Approved", "Image URL"}, rows) + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: md, + Links: links, + Records: recs, + }, true +} + +func wave3MediaExtractMusicBrainzHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + doc := ParseHTMLDoc(rawHTML, wave3MediaMaxHTMLBytes) + title := wave3MediaExtractTitle(doc, rawHTML) + if title == "" { + return nil + } + var bullets []string + var rows [][]string + if doc != nil { + if sub := SanitizeSchemaPlainField(wave3MediaCleanText(doc.Text(".releaseheader .subheader, .artistheader .subheader")), 200); sub != "" { + bullets = append(bullets, "- **Details**: "+escapeDeclMarkdownBrackets(sub)) + } + for _, tr := range doc.Select("table.tbl tbody tr", wave3MediaMaxRecords) { + tds := tr.Select("td", 6) + if len(tds) >= 2 { + pos := SanitizeSchemaPlainField(wave3MediaCleanText(tds[0].Text()), 16) + trk := SanitizeSchemaPlainField(wave3MediaCleanText(tds[1].Text()), 180) + if trk != "" { + dur := "-" + if len(tds) >= 3 { + dur = wave3MediaFirstNonEmpty(SanitizeSchemaPlainField(wave3MediaCleanText(tds[len(tds)-1].Text()), 24), "-") + } + rows = append(rows, []string{wave3MediaFirstNonEmpty(escapeDeclMarkdownBrackets(pos), "-"), escapeDeclMarkdownBrackets(trk), escapeDeclMarkdownBrackets(dur)}) + } + } + } + } + desc := wave3MediaExtractMetaDesc(rawHTML) + if len(bullets) == 0 && len(rows) == 0 && desc == "" { + return nil + } + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + if desc != "" { + blocks = append(blocks, escapeDeclPlainTextPreservingNewlines(desc)) + } + if len(rows) > 0 { + blocks = append(blocks, "## Tracklist\n\n"+formatDeclarativeGFMTable([]string{"#", "Title", "Length"}, rows)) + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: sliceRunesMax(desc, 260), + Markdown: strings.Join(blocks, "\n\n"), + Records: []map[string]any{{"title": title}}, + } +} + +// ── #379 Discogs (`discogs_json`, `discogs_html`) ──────────────────────────────────────────────── + +func wave3MediaFormatDiscogsJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + obj, ok := parsed.(map[string]any) + if !ok || obj == nil { + return nil, false + } + + if results, hasRes := obj["results"].([]any); hasRes { + if len(results) == 0 { + return nil, false + } + var recs []map[string]any + var rows [][]string + for _, it := range results { + if len(recs) >= wave3MediaMaxRecords { + break + } + m, okM := it.(map[string]any) + if !okM { + continue + } + title := wave3MediaPlain(m["title"], 200) + if title == "" { + continue + } + idStr := wave3MediaPlain(m["id"], 32) + rType := wave3MediaPlain(m["type"], 32) + yr := wave3MediaPlain(m["year"], 16) + country := wave3MediaPlain(m["country"], 32) + rows = append(rows, []string{ + escapeDeclMarkdownBrackets(title), + wave3MediaFirstNonEmpty(escapeDeclMarkdownBrackets(idStr), "-"), + wave3MediaFirstNonEmpty(escapeDeclMarkdownBrackets(rType), "-"), + wave3MediaFirstNonEmpty(escapeDeclMarkdownBrackets(yr), "-"), + wave3MediaFirstNonEmpty(escapeDeclMarkdownBrackets(country), "-"), + }) + recs = append(recs, map[string]any{ + "id": idStr, + "title": title, + "type": rType, + "year": yr, + }) + } + if len(recs) == 0 { + return nil, false + } + md := "# Discogs Search Results\n\n" + formatDeclarativeGFMTable([]string{"Title", "ID", "Type", "Year", "Country"}, rows) + return &DeclarativeFormattedDoc{ + Title: "Discogs Search Results", + Markdown: md, + Records: recs, + }, true + } + + title := wave3MediaFirstNonEmpty(wave3MediaPlain(obj["title"], 240), wave3MediaPlain(obj["name"], 240)) + idStr := wave3MediaPlain(obj["id"], 32) + if title == "" || idStr == "" { + return nil, false + } + + artist := wave3MediaPlain(obj["artists_sort"], 160) + if artist == "" { + if aArr, okA := obj["artists"].([]any); okA { + artist = strings.Join(wave3MediaJoinNamesArray(aArr, "name", 6), ", ") + } + } + year := wave3MediaPlain(obj["year"], 16) + country := wave3MediaPlain(obj["country"], 48) + released := wave3MediaPlain(obj["released"], 32) + notes := wave3MediaFirstNonEmpty(wave3MediaPlain(obj["notes"], 1800), wave3MediaPlain(obj["profile"], 1800)) + lowestPrice := wave3MediaPlain(obj["lowest_price"], 24) + numForSale := wave3MediaPlain(obj["num_for_sale"], 24) + + var genres, styles, labels []string + if gArr, okG := obj["genres"].([]any); okG { + genres = wave3MediaJoinNamesArray(gArr, "", 8) + } + if sArr, okS := obj["styles"].([]any); okS { + styles = wave3MediaJoinNamesArray(sArr, "", 8) + } + if lArr, okL := obj["labels"].([]any); okL { + for _, rl := range lArr { + if lm, okLM := rl.(map[string]any); okLM { + ln := wave3MediaPlain(lm["name"], 80) + cat := wave3MediaPlain(lm["catno"], 40) + if ln != "" { + if cat != "" { + labels = append(labels, ln+" ("+cat+")") + } else { + labels = append(labels, ln) + } + } + } + } + } + + var links []string + seen := make(map[string]bool) + uri := SanitizeSchemaHTTPSURL(wave3MediaStringVal(obj["uri"]), origURL) + wave3MediaAddLink(&links, seen, uri, origURL) + + var bullets []string + bullets = append(bullets, "- **Discogs ID**: "+escapeDeclMarkdownBrackets(idStr)) + if artist != "" { + bullets = append(bullets, "- **Artist**: "+escapeDeclMarkdownBrackets(artist)) + } + if year != "" && year != "0" { + bullets = append(bullets, "- **Year**: "+escapeDeclMarkdownBrackets(year)) + } + if released != "" { + bullets = append(bullets, "- **Released**: "+escapeDeclMarkdownBrackets(released)) + } + if country != "" { + bullets = append(bullets, "- **Country**: "+escapeDeclMarkdownBrackets(country)) + } + if len(genres) > 0 { + bullets = append(bullets, "- **Genres**: "+escapeDeclMarkdownBrackets(strings.Join(genres, ", "))) + } + if len(styles) > 0 { + bullets = append(bullets, "- **Styles**: "+escapeDeclMarkdownBrackets(strings.Join(styles, ", "))) + } + if len(labels) > 0 { + bullets = append(bullets, "- **Labels**: "+escapeDeclMarkdownBrackets(strings.Join(labels, ", "))) + } + if lowestPrice != "" { + bullets = append(bullets, "- **Lowest Price**: $"+escapeDeclMarkdownBrackets(lowestPrice)) + } + if numForSale != "" { + bullets = append(bullets, "- **For Sale**: "+escapeDeclMarkdownBrackets(numForSale)) + } + + blocks := []string{"# " + escapeDeclMarkdownBrackets(title), strings.Join(bullets, "\n")} + if notes != "" { + blocks = append(blocks, "## Notes\n\n"+escapeDeclPlainTextPreservingNewlines(notes)) + } + + if tl, okTL := obj["tracklist"].([]any); okTL && len(tl) > 0 { + var rows [][]string + for _, rt := range tl { + if len(rows) >= wave3MediaMaxRecords { + break + } + tm, okTM := rt.(map[string]any) + if !okTM { + continue + } + tTitle := wave3MediaPlain(tm["title"], 180) + if tTitle == "" { + continue + } + rows = append(rows, []string{ + wave3MediaFirstNonEmpty(escapeDeclMarkdownBrackets(wave3MediaPlain(tm["position"], 16)), "-"), + escapeDeclMarkdownBrackets(tTitle), + wave3MediaFirstNonEmpty(escapeDeclMarkdownBrackets(wave3MediaPlain(tm["duration"], 24)), "-"), + }) + } + if len(rows) > 0 { + blocks = append(blocks, "## Tracklist\n\n"+formatDeclarativeGFMTable([]string{"Pos", "Title", "Duration"}, rows)) + } + } + + rec := map[string]any{ + "id": idStr, + "title": title, + } + if artist != "" { + rec["artist"] = artist + } + if year != "" && year != "0" { + rec["year"] = year + } + if len(genres) > 0 { + rec["genres"] = genres + } + if uri != "" { + rec["url"] = uri + } + + return &DeclarativeFormattedDoc{ + Title: title, + Author: artist, + PublishedTime: released, + Description: sliceRunesMax(notes, 260), + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: []map[string]any{rec}, + }, true +} + +func wave3MediaExtractDiscogsHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + ldObjs := extractJSONLDObjectsDeclHTML(rawHTML, 16) + var musicObj map[string]any + for _, obj := range ldObjs { + if wave3MediaHasSchemaType(obj, "MusicAlbum", "MusicRelease", "MusicGroup", "MusicRecording") { + musicObj = obj + break + } + } + doc := ParseHTMLDoc(rawHTML, wave3MediaMaxHTMLBytes) + title := wave3MediaExtractTitle(doc, rawHTML) + if musicObj != nil { + if n := wave3MediaPlain(musicObj["name"], 240); n != "" { + title = n + } + } + if title == "" { + return nil + } + desc := wave3MediaExtractMetaDesc(rawHTML) + artist := "" + if musicObj != nil { + artist = wave3MediaNameField(musicObj["byArtist"], 140) + } + if artist == "" && desc == "" && doc == nil { + return nil + } + var bullets []string + if artist != "" { + bullets = append(bullets, "- **Artist**: "+escapeDeclMarkdownBrackets(artist)) + } + if len(bullets) == 0 && desc == "" { + return nil + } + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + if desc != "" { + blocks = append(blocks, escapeDeclPlainTextPreservingNewlines(desc)) + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Author: artist, + Description: sliceRunesMax(desc, 260), + Markdown: strings.Join(blocks, "\n\n"), + Records: []map[string]any{{"title": title}}, + } +} + +// ── #380 Podcast Index (`podcast_index_json`, `podcast_index_html`) ────────────────────────────── + +func wave3MediaFormatPodcastIndexJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + obj, ok := parsed.(map[string]any) + if !ok || obj == nil { + return nil, false + } + + var links []string + seen := make(map[string]bool) + + if feed := wave3MediaNestedMap(obj, "feed"); feed != nil { + title := wave3MediaPlain(feed["title"], 240) + idStr := wave3MediaPlain(feed["id"], 32) + if title == "" { + return nil, false + } + author := wave3MediaFirstNonEmpty(wave3MediaPlain(feed["author"], 160), wave3MediaPlain(feed["ownerName"], 160)) + feedURL := SanitizeSchemaHTTPSURL(wave3MediaStringVal(feed["url"]), origURL) + siteURL := SanitizeSchemaHTTPSURL(wave3MediaStringVal(feed["link"]), origURL) + wave3MediaAddLink(&links, seen, feedURL, origURL) + wave3MediaAddLink(&links, seen, siteURL, origURL) + lang := wave3MediaPlain(feed["language"], 32) + epCount := wave3MediaPlain(feed["episodeCount"], 24) + itunesID := wave3MediaPlain(feed["itunesId"], 32) + desc := wave3MediaPlain(feed["description"], 1800) + + var cats []string + if cm, okC := feed["categories"].(map[string]any); okC { + for _, v := range cm { + if c := wave3MediaPlain(v, 64); c != "" { + cats = append(cats, c) + } + } + } + + var bullets []string + if idStr != "" { + bullets = append(bullets, "- **Podcast Index ID**: "+escapeDeclMarkdownBrackets(idStr)) + } + if author != "" { + bullets = append(bullets, "- **Author**: "+escapeDeclMarkdownBrackets(author)) + } + if lang != "" { + bullets = append(bullets, "- **Language**: "+escapeDeclMarkdownBrackets(lang)) + } + if epCount != "" { + bullets = append(bullets, "- **Episodes**: "+escapeDeclMarkdownBrackets(epCount)) + } + if itunesID != "" { + bullets = append(bullets, "- **iTunes ID**: "+escapeDeclMarkdownBrackets(itunesID)) + } + if len(cats) > 0 { + bullets = append(bullets, "- **Categories**: "+escapeDeclMarkdownBrackets(strings.Join(cats, ", "))) + } + if feedURL != "" { + bullets = append(bullets, "- **RSS Feed**: "+feedURL) + } + blocks := []string{"# " + escapeDeclMarkdownBrackets(title), strings.Join(bullets, "\n")} + if desc != "" { + blocks = append(blocks, "## Description\n\n"+escapeDeclPlainTextPreservingNewlines(desc)) + } + rec := map[string]any{"title": title} + if idStr != "" { + rec["id"] = idStr + } + if author != "" { + rec["author"] = author + } + if feedURL != "" { + rec["feedUrl"] = feedURL + } + return &DeclarativeFormattedDoc{ + Title: title, + Author: author, + Description: sliceRunesMax(desc, 260), + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: []map[string]any{rec}, + }, true + } + + // Feeds / Items list + for _, listKey := range []string{"feeds", "items"} { + if arr, okL := obj[listKey].([]any); okL { + if len(arr) == 0 { + return nil, false + } + var recs []map[string]any + var rows [][]string + for _, it := range arr { + if len(recs) >= wave3MediaMaxRecords { + break + } + m, okM := it.(map[string]any) + if !okM { + continue + } + t := wave3MediaPlain(m["title"], 200) + if t == "" { + continue + } + idStr := wave3MediaPlain(m["id"], 32) + auth := wave3MediaFirstNonEmpty(wave3MediaPlain(m["author"], 120), wave3MediaPlain(m["datePublishedPretty"], 48)) + u := SanitizeSchemaHTTPSURL(wave3MediaFirstNonEmpty(wave3MediaStringVal(m["link"]), wave3MediaStringVal(m["enclosureUrl"]), wave3MediaStringVal(m["url"])), origURL) + wave3MediaAddLink(&links, seen, u, origURL) + rows = append(rows, []string{ + escapeDeclMarkdownBrackets(t), + wave3MediaFirstNonEmpty(escapeDeclMarkdownBrackets(idStr), "-"), + wave3MediaFirstNonEmpty(escapeDeclMarkdownBrackets(auth), "-"), + }) + rec := map[string]any{"title": t} + if idStr != "" { + rec["id"] = idStr + } + if u != "" { + rec["url"] = u + } + recs = append(recs, rec) + } + if len(recs) == 0 { + return nil, false + } + title := "Podcast Index " + strings.ToUpper(listKey[:1]) + listKey[1:] + md := "# " + escapeDeclMarkdownBrackets(title) + "\n\n" + formatDeclarativeGFMTable([]string{"Title", "ID", "Author / Date"}, rows) + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: md, + Links: links, + Records: recs, + }, true + } + } + + return nil, false +} + +func wave3MediaExtractPodcastIndexHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + ldObjs := extractJSONLDObjectsDeclHTML(rawHTML, 12) + var podObj map[string]any + for _, obj := range ldObjs { + if wave3MediaHasSchemaType(obj, "PodcastSeries", "PodcastEpisode") { + podObj = obj + break + } + } + doc := ParseHTMLDoc(rawHTML, wave3MediaMaxHTMLBytes) + title := wave3MediaExtractTitle(doc, rawHTML) + if podObj != nil { + if n := wave3MediaPlain(podObj["name"], 240); n != "" { + title = n + } + } + if title == "" { + return nil + } + desc := wave3MediaExtractMetaDesc(rawHTML) + if podObj != nil { + if d := wave3MediaPlain(podObj["description"], 1600); d != "" { + desc = d + } + } + if desc == "" { + return nil + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: sliceRunesMax(desc, 260), + Markdown: "# " + escapeDeclMarkdownBrackets(title) + "\n\n" + escapeDeclPlainTextPreservingNewlines(desc), + Records: []map[string]any{{"title": title}}, + } +} + +// ── #381 Spotify (`spotify_api_json`, `spotify_oembed_json`, `spotify_html`) ───────────────────── + +func wave3MediaFormatSpotifyAPIJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + obj, ok := parsed.(map[string]any) + if !ok || obj == nil { + return nil, false + } + name := wave3MediaPlain(obj["name"], 240) + idStr := wave3MediaPlain(obj["id"], 64) + if name == "" || idStr == "" { + return nil, false + } + + spType := wave3MediaPlain(obj["type"], 32) + publisher := wave3MediaPlain(obj["publisher"], 160) + relDate := wave3MediaPlain(obj["release_date"], 32) + durMs := "" + if f, okF := wave3MediaFloatVal(obj["duration_ms"]); okF && f > 0 { + sec := int(f / 1000) + durMs = fmt.Sprintf("%d:%02d", sec/60, sec%60) + } + totEps := wave3MediaPlain(obj["total_episodes"], 16) + totTracks := wave3MediaPlain(obj["total_tracks"], 16) + desc := wave3MediaPlain(obj["description"], 1800) + + var artists []string + if aArr, okA := obj["artists"].([]any); okA { + artists = wave3MediaJoinNamesArray(aArr, "name", 8) + } + albumName := "" + if alb := wave3MediaNestedMap(obj, "album"); alb != nil { + albumName = wave3MediaPlain(alb["name"], 200) + } + showName := "" + if sh := wave3MediaNestedMap(obj, "show"); sh != nil { + showName = wave3MediaPlain(sh["name"], 200) + } + var links []string + seen := make(map[string]bool) + extURL := "" + if eu := wave3MediaNestedMap(obj, "external_urls"); eu != nil { + extURL = SanitizeSchemaHTTPSURL(wave3MediaStringVal(eu["spotify"]), origURL) + wave3MediaAddLink(&links, seen, extURL, origURL) + } + + var bullets []string + bullets = append(bullets, "- **Spotify ID**: "+escapeDeclMarkdownBrackets(idStr)) + if spType != "" { + bullets = append(bullets, "- **Type**: "+escapeDeclMarkdownBrackets(spType)) + } + if len(artists) > 0 { + bullets = append(bullets, "- **Artists**: "+escapeDeclMarkdownBrackets(strings.Join(artists, ", "))) + } + if publisher != "" { + bullets = append(bullets, "- **Publisher**: "+escapeDeclMarkdownBrackets(publisher)) + } + if albumName != "" { + bullets = append(bullets, "- **Album**: "+escapeDeclMarkdownBrackets(albumName)) + } + if showName != "" { + bullets = append(bullets, "- **Show**: "+escapeDeclMarkdownBrackets(showName)) + } + if relDate != "" { + bullets = append(bullets, "- **Release Date**: "+escapeDeclMarkdownBrackets(relDate)) + } + if durMs != "" { + bullets = append(bullets, "- **Duration**: "+escapeDeclMarkdownBrackets(durMs)) + } + if totEps != "" { + bullets = append(bullets, "- **Total Episodes**: "+escapeDeclMarkdownBrackets(totEps)) + } + if totTracks != "" { + bullets = append(bullets, "- **Total Tracks**: "+escapeDeclMarkdownBrackets(totTracks)) + } + if extURL != "" { + bullets = append(bullets, "- **Spotify URL**: "+extURL) + } + + blocks := []string{"# " + escapeDeclMarkdownBrackets(name), strings.Join(bullets, "\n")} + if desc != "" { + blocks = append(blocks, "## Description\n\n"+escapeDeclPlainTextPreservingNewlines(desc)) + } + rec := map[string]any{ + "id": idStr, + "title": name, + } + if spType != "" { + rec["type"] = spType + } + if len(artists) > 0 { + rec["artists"] = artists + } + if publisher != "" { + rec["publisher"] = publisher + } + if extURL != "" { + rec["url"] = extURL + } + return &DeclarativeFormattedDoc{ + Title: name, + Author: wave3MediaFirstNonEmpty(strings.Join(artists, ", "), publisher), + PublishedTime: relDate, + Description: sliceRunesMax(desc, 260), + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: []map[string]any{rec}, + }, true +} + +func wave3MediaFormatSpotifyOEmbedJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + obj, ok := parsed.(map[string]any) + if !ok || obj == nil { + return nil, false + } + title := wave3MediaPlain(obj["title"], 240) + if title == "" { + return nil, false + } + provider := wave3MediaFirstNonEmpty(wave3MediaPlain(obj["provider_name"], 64), "Spotify") + oType := wave3MediaPlain(obj["type"], 32) + iframeURL := SanitizeSchemaHTTPSURL(wave3MediaStringVal(obj["iframe_url"]), origURL) + thumbURL := SanitizeSchemaHTTPSURL(wave3MediaStringVal(obj["thumbnail_url"]), origURL) + + var links []string + seen := make(map[string]bool) + wave3MediaAddLink(&links, seen, iframeURL, origURL) + wave3MediaAddLink(&links, seen, thumbURL, origURL) + + var bullets []string + bullets = append(bullets, "- **Provider**: "+escapeDeclMarkdownBrackets(provider)) + if oType != "" { + bullets = append(bullets, "- **Type**: "+escapeDeclMarkdownBrackets(oType)) + } + if iframeURL != "" { + bullets = append(bullets, "- **Embed URL**: "+iframeURL) + } + if thumbURL != "" { + bullets = append(bullets, "- **Thumbnail**: "+thumbURL) + } + rec := map[string]any{ + "title": title, + "provider": provider, + } + if iframeURL != "" { + rec["embedUrl"] = iframeURL + } + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: "# " + escapeDeclMarkdownBrackets(title) + "\n\n" + strings.Join(bullets, "\n"), + Links: links, + Records: []map[string]any{rec}, + }, true +} + +func wave3MediaExtractSpotifyHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + ldObjs := extractJSONLDObjectsDeclHTML(rawHTML, 16) + var spObj map[string]any + for _, obj := range ldObjs { + if wave3MediaHasSchemaType(obj, "PodcastSeries", "PodcastEpisode", "MusicRecording", "MusicAlbum", "MusicGroup", "MusicPlaylist") { + spObj = obj + break + } + } + ogTitle := SanitizeSchemaPlainField(wave3MediaExtractMetaBounded(rawHTML, "og:title"), 240) + ogType := SanitizeSchemaPlainField(wave3MediaExtractMetaBounded(rawHTML, "og:type"), 64) + ogDesc := wave3MediaExtractMetaDesc(rawHTML) + musician := SanitizeSchemaPlainField(wave3MediaExtractMetaBounded(rawHTML, "music:musician"), 160) + musicRelDate := SanitizeSchemaPlainField(wave3MediaExtractMetaBounded(rawHTML, "music:release_date"), 32) + musicDur := SanitizeSchemaPlainField(wave3MediaExtractMetaBounded(rawHTML, "music:duration"), 24) + + if spObj == nil && ogTitle == "" { + return nil + } + title := ogTitle + if spObj != nil { + if n := wave3MediaPlain(spObj["name"], 240); n != "" { + title = n + } + } + if title == "" || wave3MediaIsGenericTitle(title) || wave3MediaIsNegativeTitle(title) { + return nil + } + + desc := ogDesc + author := musician + if spObj != nil { + if d := wave3MediaPlain(spObj["description"], 1600); d != "" { + desc = d + } + if a := wave3MediaFirstNonEmpty(wave3MediaNameField(spObj["byArtist"], 140), wave3MediaNameField(spObj["author"], 140)); a != "" { + author = a + } + if dp := wave3MediaPlain(spObj["datePublished"], 32); dp != "" && musicRelDate == "" { + musicRelDate = dp + } + } + + var bullets []string + if ogType != "" { + bullets = append(bullets, "- **Type**: "+escapeDeclMarkdownBrackets(ogType)) + } + if author != "" { + bullets = append(bullets, "- **Artist / Creator**: "+escapeDeclMarkdownBrackets(author)) + } + if musicRelDate != "" { + bullets = append(bullets, "- **Release Date**: "+escapeDeclMarkdownBrackets(musicRelDate)) + } + if musicDur != "" { + bullets = append(bullets, "- **Duration (s)**: "+escapeDeclMarkdownBrackets(musicDur)) + } + if len(bullets) == 0 && desc == "" { + return nil + } + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + if desc != "" { + blocks = append(blocks, "## Description\n\n"+escapeDeclPlainTextPreservingNewlines(desc)) + } + rec := map[string]any{"title": title} + if author != "" { + rec["artist"] = author + } + if ogType != "" { + rec["type"] = ogType + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Author: author, + PublishedTime: musicRelDate, + Description: sliceRunesMax(desc, 260), + Markdown: strings.Join(blocks, "\n\n"), + Records: []map[string]any{rec}, + } +} + +// ── #382 Setlist.fm & Last.fm (`setlist_fm_json`, `lastfm_json`, `setlist_lastfm_html`) ────────── + +func wave3MediaFormatSetlistFmJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + obj, ok := parsed.(map[string]any) + if !ok || obj == nil { + return nil, false + } + + if slArr, hasSL := obj["setlist"].([]any); hasSL { + if len(slArr) == 0 { + return nil, false + } + var recs []map[string]any + var rows [][]string + for _, it := range slArr { + if len(recs) >= wave3MediaMaxRecords { + break + } + m, okM := it.(map[string]any) + if !okM { + continue + } + art := wave3MediaPlain(wave3MediaNestedMap(m, "artist")["name"], 140) + ven := wave3MediaPlain(wave3MediaNestedMap(m, "venue")["name"], 140) + evDate := wave3MediaPlain(m["eventDate"], 32) + idStr := wave3MediaPlain(m["id"], 32) + if art == "" && ven == "" { + continue + } + rows = append(rows, []string{ + escapeDeclMarkdownBrackets(wave3MediaFirstNonEmpty(art, "-")), + escapeDeclMarkdownBrackets(wave3MediaFirstNonEmpty(ven, "-")), + wave3MediaFirstNonEmpty(escapeDeclMarkdownBrackets(evDate), "-"), + wave3MediaFirstNonEmpty(escapeDeclMarkdownBrackets(idStr), "-"), + }) + recs = append(recs, map[string]any{"id": idStr, "artist": art, "venue": ven, "eventDate": evDate}) + } + if len(recs) == 0 { + return nil, false + } + md := "# Setlist.fm Search Results\n\n" + formatDeclarativeGFMTable([]string{"Artist", "Venue", "Date", "ID"}, rows) + return &DeclarativeFormattedDoc{ + Title: "Setlist.fm Search Results", + Markdown: md, + Records: recs, + }, true + } + + idStr := wave3MediaPlain(obj["id"], 32) + artist := wave3MediaPlain(wave3MediaNestedMap(obj, "artist")["name"], 160) + if artist == "" { + artist = wave3MediaPlain(obj["name"], 160) + } + if idStr == "" && artist == "" { + return nil, false + } + evDate := wave3MediaPlain(obj["eventDate"], 32) + venueMap := wave3MediaNestedMap(obj, "venue") + venueName := wave3MediaPlain(venueMap["name"], 160) + cityName := wave3MediaPlain(wave3MediaNestedMap(venueMap, "city")["name"], 100) + tourName := wave3MediaPlain(wave3MediaNestedMap(obj, "tour")["name"], 160) + pageURL := SanitizeSchemaHTTPSURL(wave3MediaStringVal(obj["url"]), origURL) + var links []string + seen := make(map[string]bool) + wave3MediaAddLink(&links, seen, pageURL, origURL) + + var songs []string + var rows [][]string + if setsMap := wave3MediaNestedMap(obj, "sets"); setsMap != nil { + if setArr, okS := setsMap["set"].([]any); okS { + for _, rs := range setArr { + sm, okSM := rs.(map[string]any) + if !okSM { + continue + } + setName := wave3MediaFirstNonEmpty(wave3MediaPlain(sm["name"], 64), "Main Set") + if sArr, okSongs := sm["song"].([]any); okSongs { + for _, rSong := range sArr { + if len(songs) >= wave3MediaMaxRecords { + break + } + sg, okSG := rSong.(map[string]any) + if !okSG { + continue + } + sName := wave3MediaPlain(sg["name"], 160) + if sName == "" { + continue + } + songs = append(songs, sName) + rows = append(rows, []string{strconv.Itoa(len(songs)), escapeDeclMarkdownBrackets(setName), escapeDeclMarkdownBrackets(sName)}) + } + } + } + } + } + + title := artist + if venueName != "" { + title = fmt.Sprintf("%s at %s", artist, venueName) + if evDate != "" { + title += " (" + evDate + ")" + } + } + var bullets []string + if idStr != "" { + bullets = append(bullets, "- **Setlist ID**: "+escapeDeclMarkdownBrackets(idStr)) + } + if artist != "" { + bullets = append(bullets, "- **Artist**: "+escapeDeclMarkdownBrackets(artist)) + } + if venueName != "" { + loc := venueName + if cityName != "" { + loc += ", " + cityName + } + bullets = append(bullets, "- **Venue**: "+escapeDeclMarkdownBrackets(loc)) + } + if evDate != "" { + bullets = append(bullets, "- **Event Date**: "+escapeDeclMarkdownBrackets(evDate)) + } + if tourName != "" { + bullets = append(bullets, "- **Tour**: "+escapeDeclMarkdownBrackets(tourName)) + } + + blocks := []string{"# " + escapeDeclMarkdownBrackets(title), strings.Join(bullets, "\n")} + if len(rows) > 0 { + blocks = append(blocks, "## Setlist\n\n"+formatDeclarativeGFMTable([]string{"#", "Set", "Song"}, rows)) + } + rec := map[string]any{ + "id": idStr, + "artist": artist, + } + if venueName != "" { + rec["venue"] = venueName + } + if evDate != "" { + rec["eventDate"] = evDate + } + if len(songs) > 0 { + rec["songs"] = songs + } + return &DeclarativeFormattedDoc{ + Title: title, + Author: artist, + PublishedTime: evDate, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: []map[string]any{rec}, + }, true +} + +func wave3MediaFormatLastfmJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + obj, ok := parsed.(map[string]any) + if !ok || obj == nil { + return nil, false + } + + if art := wave3MediaNestedMap(obj, "artist"); art != nil { + name := wave3MediaPlain(art["name"], 200) + if name == "" { + return nil, false + } + mbid := wave3MediaPlain(art["mbid"], 64) + stats := wave3MediaNestedMap(art, "stats") + listeners := wave3MediaPlain(stats["listeners"], 32) + playcount := wave3MediaPlain(stats["playcount"], 32) + bio := wave3MediaPlain(wave3MediaNestedMap(art, "bio")["summary"], 1600) + var tags []string + if tArr, okT := wave3MediaNestedMap(art, "tags")["tag"].([]any); okT { + tags = wave3MediaJoinNamesArray(tArr, "name", 8) + } + var bullets []string + if mbid != "" { + bullets = append(bullets, "- **MBID**: "+escapeDeclMarkdownBrackets(mbid)) + } + if listeners != "" { + bullets = append(bullets, "- **Listeners**: "+escapeDeclMarkdownBrackets(listeners)) + } + if playcount != "" { + bullets = append(bullets, "- **Playcount**: "+escapeDeclMarkdownBrackets(playcount)) + } + if len(tags) > 0 { + bullets = append(bullets, "- **Tags**: "+escapeDeclMarkdownBrackets(strings.Join(tags, ", "))) + } + blocks := []string{"# " + escapeDeclMarkdownBrackets(name), strings.Join(bullets, "\n")} + if bio != "" { + blocks = append(blocks, "## Biography\n\n"+escapeDeclPlainTextPreservingNewlines(bio)) + } + rec := map[string]any{"name": name} + if listeners != "" { + rec["listeners"] = listeners + } + if playcount != "" { + rec["playcount"] = playcount + } + return &DeclarativeFormattedDoc{ + Title: name, + Description: sliceRunesMax(bio, 260), + Markdown: strings.Join(blocks, "\n\n"), + Records: []map[string]any{rec}, + }, true + } + + for _, k := range []string{"track", "album"} { + if sub := wave3MediaNestedMap(obj, k); sub != nil { + name := wave3MediaPlain(sub["name"], 200) + if name == "" { + continue + } + artist := wave3MediaFirstNonEmpty(wave3MediaPlain(sub["artist"], 160), wave3MediaPlain(wave3MediaNestedMap(sub, "artist")["name"], 160)) + listeners := wave3MediaPlain(sub["listeners"], 32) + playcount := wave3MediaPlain(sub["playcount"], 32) + var bullets []string + if artist != "" { + bullets = append(bullets, "- **Artist**: "+escapeDeclMarkdownBrackets(artist)) + } + if listeners != "" { + bullets = append(bullets, "- **Listeners**: "+escapeDeclMarkdownBrackets(listeners)) + } + if playcount != "" { + bullets = append(bullets, "- **Playcount**: "+escapeDeclMarkdownBrackets(playcount)) + } + return &DeclarativeFormattedDoc{ + Title: name, + Author: artist, + Markdown: "# " + escapeDeclMarkdownBrackets(name) + "\n\n" + strings.Join(bullets, "\n"), + Records: []map[string]any{{"title": name, "artist": artist}}, + }, true + } + } + + return nil, false +} + +func wave3MediaExtractSetlistLastfmHTML(rawHTML, baseURL, urlLower, extractorID string) *DeclarativePostFetchResult { + doc := ParseHTMLDoc(rawHTML, wave3MediaMaxHTMLBytes) + if doc == nil { + return nil + } + title := wave3MediaExtractTitle(doc, rawHTML) + if title == "" { + if hl := SanitizeSchemaPlainField(wave3MediaCleanText(doc.Text(".setlistHeadline")), 240); hl != "" { + title = hl + } + } + if title == "" { + return nil + } + + // Setlist.fm DOM extraction + songNodes := doc.Select(".songLabel, .songPart", 40) + if len(songNodes) > 0 || strings.Contains(urlLower, "setlist.fm") || strings.Contains(rawHTML, "setlistHeadline") { + var rows [][]string + var songs []string + for _, sn := range songNodes { + if len(songs) >= wave3MediaMaxRecords { + break + } + s := SanitizeSchemaPlainField(wave3MediaCleanText(sn.Text()), 160) + if s == "" { + continue + } + songs = append(songs, s) + rows = append(rows, []string{strconv.Itoa(len(songs)), escapeDeclMarkdownBrackets(s)}) + } + if len(songs) > 0 { + headline := SanitizeSchemaPlainField(wave3MediaCleanText(doc.Text(".setlistHeadline")), 240) + if headline != "" { + title = headline + } + dateText := SanitizeSchemaPlainField(wave3MediaCleanText(doc.Text(".dateBlock")), 48) + var bullets []string + if dateText != "" { + bullets = append(bullets, "- **Date**: "+escapeDeclMarkdownBrackets(dateText)) + } + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + blocks = append(blocks, "## Setlist\n\n"+formatDeclarativeGFMTable([]string{"#", "Song"}, rows)) + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Markdown: strings.Join(blocks, "\n\n"), + Records: []map[string]any{{"title": title, "songs": songs}}, + } + } + } + + // Last.fm SSR HTML fallback + desc := wave3MediaExtractMetaDesc(rawHTML) + var bullets []string + if lfmTitle := SanitizeSchemaPlainField(wave3MediaCleanText(doc.Text(".header-new-title")), 200); lfmTitle != "" { + title = lfmTitle + } + for _, row := range doc.Select(".chartlist-name", 15) { + if tn := SanitizeSchemaPlainField(wave3MediaCleanText(row.Text()), 140); tn != "" { + bullets = append(bullets, "- "+escapeDeclMarkdownBrackets(tn)) + } + } + if len(bullets) == 0 && desc == "" { + return nil + } + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if desc != "" { + blocks = append(blocks, escapeDeclPlainTextPreservingNewlines(desc)) + } + if len(bullets) > 0 { + blocks = append(blocks, "## Tracks\n\n"+strings.Join(bullets, "\n")) + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: sliceRunesMax(desc, 260), + Markdown: strings.Join(blocks, "\n\n"), + Records: []map[string]any{{"title": title}}, + } +} + +// ── #383 Steam Store (`steam_store_json`, `steam_store_html`) ──────────────────────────────────── + +func wave3MediaFormatSteamStoreJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + obj, ok := parsed.(map[string]any) + if !ok || obj == nil { + return nil, false + } + + // 1. ISteamNews GetNewsForApp/v2 (`appnews.newsitems[]`) + if appNews := wave3MediaNestedMap(obj, "appnews"); appNews != nil { + appid := wave3MediaPlain(appNews["appid"], 24) + items, _ := appNews["newsitems"].([]any) + if len(items) == 0 { + return nil, false + } + var recs []map[string]any + var rows [][]string + var links []string + seen := make(map[string]bool) + for _, it := range items { + if len(recs) >= wave3MediaMaxRecords { + break + } + m, okM := it.(map[string]any) + if !okM { + continue + } + t := wave3MediaPlain(m["title"], 200) + if t == "" { + continue + } + author := wave3MediaPlain(m["author"], 100) + feedLabel := wave3MediaPlain(m["feedlabel"], 64) + itemURL := SanitizeSchemaHTTPSURL(wave3MediaStringVal(m["url"]), origURL) + wave3MediaAddLink(&links, seen, itemURL, origURL) + rows = append(rows, []string{ + escapeDeclMarkdownBrackets(t), + wave3MediaFirstNonEmpty(escapeDeclMarkdownBrackets(author), "-"), + wave3MediaFirstNonEmpty(escapeDeclMarkdownBrackets(feedLabel), "-"), + }) + rec := map[string]any{"title": t, "appid": appid} + if itemURL != "" { + rec["url"] = itemURL + } + recs = append(recs, rec) + } + if len(recs) == 0 { + return nil, false + } + title := fmt.Sprintf("Steam App %s News", appid) + md := "# " + escapeDeclMarkdownBrackets(title) + "\n\n" + formatDeclarativeGFMTable([]string{"Headline", "Author", "Feed"}, rows) + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: md, + Links: links, + Records: recs, + }, true + } + + // 2. Steam appreviews (`query_summary` + `reviews[]`) + if qs := wave3MediaNestedMap(obj, "query_summary"); qs != nil { + scoreDesc := wave3MediaPlain(qs["review_score_desc"], 80) + totPos := wave3MediaPlain(qs["total_positive"], 24) + totNeg := wave3MediaPlain(qs["total_negative"], 24) + totRev := wave3MediaPlain(qs["total_reviews"], 24) + var recs []map[string]any + var rows [][]string + if revs, okR := obj["reviews"].([]any); okR { + for _, rr := range revs { + if len(recs) >= wave3MediaMaxRecords { + break + } + rm, okRM := rr.(map[string]any) + if !okRM { + continue + } + rid := wave3MediaPlain(rm["recommendationid"], 32) + votedUp := wave3MediaPlain(rm["voted_up"], 12) + text := wave3MediaPlain(rm["review"], 220) + rows = append(rows, []string{ + wave3MediaFirstNonEmpty(escapeDeclMarkdownBrackets(rid), "-"), + wave3MediaFirstNonEmpty(escapeDeclMarkdownBrackets(votedUp), "-"), + escapeDeclMarkdownBrackets(wave3MediaFirstNonEmpty(text, "-")), + }) + recs = append(recs, map[string]any{ + "recommendationId": rid, + "votedUp": votedUp == "true", + "review": text, + }) + } + } + if len(recs) == 0 && scoreDesc == "" { + return nil, false + } + if len(recs) == 0 { + recs = []map[string]any{{"reviewScoreDesc": scoreDesc, "totalReviews": totRev}} + } + title := "Steam App Reviews" + var bullets []string + if scoreDesc != "" { + bullets = append(bullets, "- **Summary**: "+escapeDeclMarkdownBrackets(scoreDesc)) + } + if totPos != "" || totNeg != "" { + bullets = append(bullets, fmt.Sprintf("- **Positive / Negative**: %s / %s (Total: %s)", escapeDeclMarkdownBrackets(wave3MediaFirstNonEmpty(totPos, "0")), escapeDeclMarkdownBrackets(wave3MediaFirstNonEmpty(totNeg, "0")), escapeDeclMarkdownBrackets(wave3MediaFirstNonEmpty(totRev, "0")))) + } + blocks := []string{"# " + title, strings.Join(bullets, "\n")} + if len(rows) > 0 { + blocks = append(blocks, formatDeclarativeGFMTable([]string{"Review ID", "Recommended", "Excerpt"}, rows)) + } + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: strings.Join(blocks, "\n\n"), + Records: recs, + }, true + } + + // 3. Steam appdetails (`{"620":{"success":true,"data":{...}}}`) + for appKey, rawVal := range obj { + entry, okE := rawVal.(map[string]any) + if !okE { + continue + } + if succ, okS := entry["success"].(bool); !okS || !succ { + return nil, false + } + data := wave3MediaNestedMap(entry, "data") + if data == nil { + return nil, false + } + name := wave3MediaPlain(data["name"], 240) + if name == "" { + return nil, false + } + appid := wave3MediaFirstNonEmpty(wave3MediaPlain(data["steam_appid"], 24), SanitizeSchemaPlainField(appKey, 24)) + appType := wave3MediaPlain(data["type"], 32) + isFree, _ := data["is_free"].(bool) + shortDesc := wave3MediaPlain(data["short_description"], 1200) + var devs, pubs, genres []string + if dArr, okD := data["developers"].([]any); okD { + devs = wave3MediaJoinNamesArray(dArr, "", 6) + } + if pArr, okP := data["publishers"].([]any); okP { + pubs = wave3MediaJoinNamesArray(pArr, "", 6) + } + if gArr, okG := data["genres"].([]any); okG { + genres = wave3MediaJoinNamesArray(gArr, "description", 8) + } + relDate := "" + if rd := wave3MediaNestedMap(data, "release_date"); rd != nil { + relDate = wave3MediaPlain(rd["date"], 48) + } + priceDisp := "" + if isFree { + priceDisp = "Free" + } else if po := wave3MediaNestedMap(data, "price_overview"); po != nil { + priceDisp = wave3MediaPlain(po["final_formatted"], 40) + if priceDisp == "" { + if fin, okF := wave3MediaFloatVal(po["final"]); okF { + cur := wave3MediaPlain(po["currency"], 8) + priceDisp = fmt.Sprintf("%.2f %s", fin/100.0, cur) + } + } + } + metacritic := "" + if mc := wave3MediaNestedMap(data, "metacritic"); mc != nil { + metacritic = wave3MediaPlain(mc["score"], 16) + } + + var bullets []string + bullets = append(bullets, "- **Steam App ID**: "+escapeDeclMarkdownBrackets(appid)) + if appType != "" { + bullets = append(bullets, "- **Type**: "+escapeDeclMarkdownBrackets(appType)) + } + if len(devs) > 0 { + bullets = append(bullets, "- **Developers**: "+escapeDeclMarkdownBrackets(strings.Join(devs, ", "))) + } + if len(pubs) > 0 { + bullets = append(bullets, "- **Publishers**: "+escapeDeclMarkdownBrackets(strings.Join(pubs, ", "))) + } + if relDate != "" { + bullets = append(bullets, "- **Release Date**: "+escapeDeclMarkdownBrackets(relDate)) + } + if priceDisp != "" { + bullets = append(bullets, "- **Price**: "+escapeDeclMarkdownBrackets(priceDisp)) + } + if len(genres) > 0 { + bullets = append(bullets, "- **Genres**: "+escapeDeclMarkdownBrackets(strings.Join(genres, ", "))) + } + if metacritic != "" { + bullets = append(bullets, "- **Metacritic**: "+escapeDeclMarkdownBrackets(metacritic)) + } + + blocks := []string{"# " + escapeDeclMarkdownBrackets(name), strings.Join(bullets, "\n")} + if shortDesc != "" { + blocks = append(blocks, "## Description\n\n"+escapeDeclPlainTextPreservingNewlines(shortDesc)) + } + rec := map[string]any{ + "appid": appid, + "title": name, + } + if priceDisp != "" { + rec["price"] = priceDisp + } + if len(devs) > 0 { + rec["developers"] = devs + } + if len(genres) > 0 { + rec["genres"] = genres + } + return &DeclarativeFormattedDoc{ + Title: name, + Author: strings.Join(devs, ", "), + PublishedTime: relDate, + Description: sliceRunesMax(shortDesc, 260), + Markdown: strings.Join(blocks, "\n\n"), + Records: []map[string]any{rec}, + }, true + } + + return nil, false +} + +func wave3MediaExtractSteamStoreHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + doc := ParseHTMLDoc(rawHTML, wave3MediaMaxHTMLBytes) + if doc == nil { + return nil + } + title := SanitizeSchemaPlainField(wave3MediaCleanText(doc.Text("#appHubAppName, .apphub_AppName")), 240) + if title == "" { + title = wave3MediaExtractTitle(doc, rawHTML) + } + if title == "" { + return nil + } + desc := SanitizeSchemaPlainField(wave3MediaCleanText(doc.Text(".game_description_snippet")), 1200) + if desc == "" { + desc = wave3MediaExtractMetaDesc(rawHTML) + } + price := SanitizeSchemaPlainField(wave3MediaCleanText(doc.Text(".game_purchase_price, .discount_final_price")), 48) + relDate := SanitizeSchemaPlainField(wave3MediaCleanText(doc.Text(".release_date .date")), 48) + + var bullets []string + if price != "" { + bullets = append(bullets, "- **Price**: "+escapeDeclMarkdownBrackets(price)) + } + if relDate != "" { + bullets = append(bullets, "- **Release Date**: "+escapeDeclMarkdownBrackets(relDate)) + } + if len(bullets) == 0 && desc == "" { + return nil + } + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + if desc != "" { + blocks = append(blocks, "## Description\n\n"+escapeDeclPlainTextPreservingNewlines(desc)) + } + rec := map[string]any{"title": title} + if price != "" { + rec["price"] = price + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + PublishedTime: relDate, + Description: sliceRunesMax(desc, 260), + Markdown: strings.Join(blocks, "\n\n"), + Records: []map[string]any{rec}, + } +} + +// ── #384 IGDB (`igdb_json`, `igdb_html`) ───────────────────────────────────────────────────────── + +func wave3MediaFormatIGDBJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + var items []any + switch tv := parsed.(type) { + case []any: + items = tv + case map[string]any: + items = []any{tv} + default: + return nil, false + } + if len(items) == 0 { + return nil, false + } + + var recs []map[string]any + var links []string + seen := make(map[string]bool) + var firstTitle, firstDesc string + + var rows [][]string + for _, rawIt := range items { + if len(recs) >= wave3MediaMaxRecords { + break + } + m, okM := rawIt.(map[string]any) + if !okM || wave3MediaIsGenericJSONError(m) { + continue + } + name := wave3MediaPlain(m["name"], 240) + if name == "" { + continue + } + idStr := wave3MediaPlain(m["id"], 32) + slug := wave3MediaPlain(m["slug"], 160) + summary := wave3MediaPlain(m["summary"], 1800) + rating := "" + if f, okF := wave3MediaFloatVal(m["rating"]); okF && f > 0 { + rating = fmt.Sprintf("%.1f", f) + } + var genres, platforms []string + if gArr, okG := m["genres"].([]any); okG { + genres = wave3MediaJoinNamesArray(gArr, "name", 8) + } + if pArr, okP := m["platforms"].([]any); okP { + platforms = wave3MediaJoinNamesArray(pArr, "name", 10) + } + itemURL := SanitizeSchemaHTTPSURL(wave3MediaStringVal(m["url"]), origURL) + wave3MediaAddLink(&links, seen, itemURL, origURL) + + if firstTitle == "" { + firstTitle = name + firstDesc = summary + } + rows = append(rows, []string{ + escapeDeclMarkdownBrackets(name), + wave3MediaFirstNonEmpty(escapeDeclMarkdownBrackets(idStr), "-"), + wave3MediaFirstNonEmpty(escapeDeclMarkdownBrackets(rating), "-"), + wave3MediaFirstNonEmpty(escapeDeclMarkdownBrackets(strings.Join(genres, ", ")), "-"), + wave3MediaFirstNonEmpty(escapeDeclMarkdownBrackets(strings.Join(platforms, ", ")), "-"), + }) + rec := map[string]any{"title": name} + if idStr != "" { + rec["id"] = idStr + } + if slug != "" { + rec["slug"] = slug + } + if rating != "" { + rec["rating"] = rating + } + if len(genres) > 0 { + rec["genres"] = genres + } + if len(platforms) > 0 { + rec["platforms"] = platforms + } + if itemURL != "" { + rec["url"] = itemURL + } + recs = append(recs, rec) + } + if len(recs) == 0 { + return nil, false + } + + if len(recs) == 1 { + rec := recs[0] + var bullets []string + if idStr, _ := rec["id"].(string); idStr != "" { + bullets = append(bullets, "- **IGDB ID**: "+escapeDeclMarkdownBrackets(idStr)) + } + if slug, _ := rec["slug"].(string); slug != "" { + bullets = append(bullets, "- **Slug**: "+escapeDeclMarkdownBrackets(slug)) + } + if rat, _ := rec["rating"].(string); rat != "" { + bullets = append(bullets, "- **Rating**: "+escapeDeclMarkdownBrackets(rat)) + } + if gs, _ := rec["genres"].([]string); len(gs) > 0 { + bullets = append(bullets, "- **Genres**: "+escapeDeclMarkdownBrackets(strings.Join(gs, ", "))) + } + if ps, _ := rec["platforms"].([]string); len(ps) > 0 { + bullets = append(bullets, "- **Platforms**: "+escapeDeclMarkdownBrackets(strings.Join(ps, ", "))) + } + blocks := []string{"# " + escapeDeclMarkdownBrackets(firstTitle), strings.Join(bullets, "\n")} + if firstDesc != "" { + blocks = append(blocks, "## Summary\n\n"+escapeDeclPlainTextPreservingNewlines(firstDesc)) + } + return &DeclarativeFormattedDoc{ + Title: firstTitle, + Description: sliceRunesMax(firstDesc, 260), + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: recs, + }, true + } + + title := "IGDB Games" + md := "# " + title + "\n\n" + formatDeclarativeGFMTable([]string{"Game", "ID", "Rating", "Genres", "Platforms"}, rows) + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: md, + Links: links, + Records: recs, + }, true +} + +func wave3MediaExtractIGDBHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + ldObjs := extractJSONLDObjectsDeclHTML(rawHTML, 12) + var gameObj map[string]any + for _, obj := range ldObjs { + if wave3MediaHasSchemaType(obj, "VideoGame") { + gameObj = obj + break + } + } + doc := ParseHTMLDoc(rawHTML, wave3MediaMaxHTMLBytes) + title := wave3MediaExtractTitle(doc, rawHTML) + if gameObj != nil { + if n := wave3MediaPlain(gameObj["name"], 240); n != "" { + title = n + } + } + if title == "" { + return nil + } + desc := wave3MediaExtractMetaDesc(rawHTML) + if gameObj != nil { + if d := wave3MediaPlain(gameObj["description"], 1600); d != "" { + desc = d + } + } + if desc == "" { + return nil + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: sliceRunesMax(desc, 260), + Markdown: "# " + escapeDeclMarkdownBrackets(title) + "\n\n" + escapeDeclPlainTextPreservingNewlines(desc), + Records: []map[string]any{{"title": title}}, + } +} + +// ── #385 Bandcamp (`bandcamp_html`) ────────────────────────────────────────────────────────────── + +func wave3MediaExtractBandcampHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + ldObjs := extractJSONLDObjectsDeclHTML(rawHTML, 16) + var ldMusic map[string]any + for _, obj := range ldObjs { + if wave3MediaHasSchemaType(obj, "MusicAlbum", "MusicRecording") { + ldMusic = obj + break + } + } + + var tralbum map[string]any + rawAttr := "" + if m := wave3MediaRxDataTralbumDbl.FindStringSubmatch(rawHTML); len(m) >= 2 { + rawAttr = m[1] + } else if m := wave3MediaRxDataTralbumSgl.FindStringSubmatch(rawHTML); len(m) >= 2 { + rawAttr = m[1] + } + if rawAttr != "" { + unescaped := strings.TrimSpace(stdhtml.UnescapeString(rawAttr)) + if strings.HasPrefix(unescaped, "{") { + if parsed, ok := decodeJSONWithNumbers([]byte(unescaped)); ok { + tralbum, _ = parsed.(map[string]any) + } + } + } + + if ldMusic == nil && tralbum == nil { + return nil + } + + var doc *HTMLDoc + ensureDoc := func() *HTMLDoc { + if doc == nil { + doc = ParseHTMLDoc(rawHTML, wave3MediaMaxHTMLBytes) + } + return doc + } + + var title, artist, relDate, priceDisp, about string + var tracks [][]string + var trackNames []string + var tags []string + + if tralbum != nil { + artist = wave3MediaPlain(tralbum["artist"], 160) + relDate = wave3MediaPlain(tralbum["album_release_date"], 48) + if cur := wave3MediaNestedMap(tralbum, "current"); cur != nil { + title = wave3MediaPlain(cur["title"], 240) + if relDate == "" { + relDate = wave3MediaPlain(cur["release_date"], 48) + } + about = wave3MediaPlain(cur["about"], 1600) + if mp, okM := wave3MediaFloatVal(cur["minimum_price"]); okM { + curCode := wave3MediaPlain(cur["currency"], 8) + if mp == 0 { + priceDisp = "Name Your Price / Free" + } else if curCode != "" { + priceDisp = fmt.Sprintf("%.2f %s", mp, curCode) + } else { + priceDisp = fmt.Sprintf("%.2f", mp) + } + } + } + if tArr, okT := tralbum["trackinfo"].([]any); okT { + for idx, rt := range tArr { + if len(tracks) >= wave3MediaMaxRecords { + break + } + tm, okTM := rt.(map[string]any) + if !okTM { + continue + } + tn := wave3MediaPlain(tm["title"], 180) + if tn == "" { + continue + } + num := wave3MediaPlain(tm["track_num"], 12) + if num == "" { + num = strconv.Itoa(idx + 1) + } + dur := "-" + if dSec, okD := wave3MediaFloatVal(tm["duration"]); okD && dSec > 0 { + sec := int(dSec) + dur = fmt.Sprintf("%d:%02d", sec/60, sec%60) + } + trackNames = append(trackNames, tn) + tracks = append(tracks, []string{escapeDeclMarkdownBrackets(num), escapeDeclMarkdownBrackets(tn), escapeDeclMarkdownBrackets(dur)}) + } + } + } + + if ldMusic != nil { + if title == "" { + title = wave3MediaPlain(ldMusic["name"], 240) + } + if artist == "" { + artist = wave3MediaNameField(ldMusic["byArtist"], 160) + } + if relDate == "" { + relDate = wave3MediaPlain(ldMusic["datePublished"], 48) + } + if about == "" { + about = wave3MediaPlain(ldMusic["description"], 1600) + } + if len(tags) == 0 { + if kw := wave3MediaNameField(ldMusic["keywords"], 200); kw != "" { + for _, k := range strings.Split(kw, ",") { + if ck := strings.TrimSpace(k); ck != "" { + tags = append(tags, ck) + } + } + } + } + if len(tracks) == 0 { + if trkObj := wave3MediaNestedMap(ldMusic, "track"); trkObj != nil { + if els, okE := trkObj["itemListElement"].([]any); okE { + for idx, el := range els { + if len(tracks) >= wave3MediaMaxRecords { + break + } + em, okEM := el.(map[string]any) + if !okEM { + continue + } + item := em + if sub := wave3MediaNestedMap(em, "item"); sub != nil { + item = sub + } + tn := wave3MediaPlain(item["name"], 180) + if tn == "" { + continue + } + pos := wave3MediaFirstNonEmpty(wave3MediaPlain(em["position"], 12), strconv.Itoa(idx+1)) + trackNames = append(trackNames, tn) + tracks = append(tracks, []string{escapeDeclMarkdownBrackets(pos), escapeDeclMarkdownBrackets(tn), "-"}) + } + } + } + } + } + + if len(tags) == 0 && strings.Contains(rawHTML, "tag") { + if d := ensureDoc(); d != nil { + for _, tn := range d.Select(".tralbum-tags .tag, a.tag", 12) { + if ts := SanitizeSchemaPlainField(wave3MediaCleanText(tn.Text()), 48); ts != "" { + tags = append(tags, ts) + } + } + } + } + + if title == "" { + title = wave3MediaExtractTitle(ensureDoc(), rawHTML) + } + if title == "" { + return nil + } + + var bullets []string + if artist != "" { + bullets = append(bullets, "- **Artist**: "+escapeDeclMarkdownBrackets(artist)) + } + if relDate != "" { + bullets = append(bullets, "- **Release Date**: "+escapeDeclMarkdownBrackets(relDate)) + } + if priceDisp != "" { + bullets = append(bullets, "- **Price**: "+escapeDeclMarkdownBrackets(priceDisp)) + } + if len(tags) > 0 { + bullets = append(bullets, "- **Tags**: "+escapeDeclMarkdownBrackets(strings.Join(tags, ", "))) + } + + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + if about != "" { + blocks = append(blocks, "## About\n\n"+escapeDeclPlainTextPreservingNewlines(about)) + } + if len(tracks) > 0 { + blocks = append(blocks, "## Tracklist\n\n"+formatDeclarativeGFMTable([]string{"#", "Track", "Duration"}, tracks)) + } + + rec := map[string]any{"title": title} + if artist != "" { + rec["artist"] = artist + } + if relDate != "" { + rec["releaseDate"] = relDate + } + if priceDisp != "" { + rec["price"] = priceDisp + } + if len(trackNames) > 0 { + rec["tracks"] = trackNames + } + + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Author: artist, + PublishedTime: relDate, + Description: sliceRunesMax(about, 260), + Markdown: strings.Join(blocks, "\n\n"), + Records: []map[string]any{rec}, + } +} + +// ── #386 Genius, AZLyrics, Musixmatch & SongMeanings (`genius_lyrics_html`) ────────────────────── + +func wave3MediaExtractGeniusPreloaded(rawHTML string) map[string]any { + if !wave3MediaContainsASCIIFold(rawHTML, "__preloaded_state__") { + return nil + } + if m := wave3MediaRxPreloadedParse.FindStringSubmatch(rawHTML); len(m) >= 2 { + quoted := m[1] + var unescaped string + if strings.HasPrefix(quoted, `'`) && len(quoted) >= 2 { + inner := quoted[1 : len(quoted)-1] + inner = strings.ReplaceAll(inner, `\'`, `'`) + inner = strings.ReplaceAll(inner, `\"`, `"`) + inner = strings.ReplaceAll(inner, `\\`, `\`) + unescaped = inner + } else if err := json.Unmarshal([]byte(quoted), &unescaped); err != nil { + unescaped = "" + } + unescaped = strings.TrimSpace(unescaped) + if strings.HasPrefix(unescaped, "{") { + if parsed, ok := decodeJSONWithNumbers([]byte(unescaped)); ok { + if obj, okObj := parsed.(map[string]any); okObj { + return obj + } + } + } + } + if m := wave3MediaRxPreloadedDirect.FindStringSubmatch(rawHTML); len(m) >= 2 { + raw := strings.TrimSpace(m[1]) + if strings.HasPrefix(raw, "{") { + if parsed, ok := decodeJSONWithNumbers([]byte(raw)); ok { + if obj, okObj := parsed.(map[string]any); okObj { + return obj + } + } + } + } + return nil +} + +func wave3MediaExtractGeniusLyricsHTML(rawHTML, probeLower, baseURL, urlLower, extractorID string) *DeclarativePostFetchResult { + var title, artist, album, releaseDate, lyrics string + var annotations []string + + ldObjs := extractJSONLDObjectsDeclHTML(rawHTML, 16) + for _, obj := range ldObjs { + if wave3MediaHasSchemaType(obj, "MusicRecording", "CreativeWork") { + if t := wave3MediaPlain(obj["name"], 220); t != "" && title == "" { + title = t + } + if a := wave3MediaNameField(obj["byArtist"], 160); a != "" && artist == "" { + artist = a + } + if al := wave3MediaNameField(obj["inAlbum"], 180); al != "" && album == "" { + album = al + } + if dp := wave3MediaPlain(obj["datePublished"], 32); dp != "" && releaseDate == "" { + releaseDate = dp + } + if txt := wave3MediaHTMLToLines(wave3MediaStringVal(obj["text"])); txt != "" && lyrics == "" { + lyrics = txt + } + } + } + + var doc *HTMLDoc + ensureDoc := func() *HTMLDoc { + if doc == nil { + doc = ParseHTMLDoc(rawHTML, wave3MediaMaxHTMLBytes) + } + return doc + } + + // 1. AZLyrics comment-anchored unclassed
+ if strings.Contains(urlLower, "azlyrics.com") || wave3MediaContainsASCIIFold(rawHTML, "azlyrics.com content") { + searchSlice := rawHTML + if idx := indexFoldASCIIExtract(rawHTML, "azlyrics.com content"); idx >= 0 { + start := idx - 256 + if start < 0 { + start = 0 + } + end := idx + 32*1024 + if end > len(rawHTML) { + end = len(rawHTML) + } + searchSlice = rawHTML[start:end] + } + if m := wave3MediaRxAZLyricsComment.FindStringSubmatch(searchSlice); len(m) >= 2 { + rawLyrics := m[1] + if rawLyrics == "" && len(m) >= 3 { + rawLyrics = m[2] + } + if l := wave3MediaHTMLToLines(rawLyrics); l != "" { + lyrics = l + } + } + if d := ensureDoc(); d != nil { + if h := SanitizeSchemaPlainField(wave3MediaCleanText(d.Text(".lyricsh h2, .lyricsh b")), 140); h != "" && artist == "" { + artist = strings.TrimSuffix(h, " Lyrics") + } + if al := SanitizeSchemaPlainField(wave3MediaCleanText(d.Text(".songinalbum_title b, .album-panel .album-title")), 160); al != "" && album == "" { + album = strings.Trim(al, `"`) + } + if bTitle := SanitizeSchemaPlainField(wave3MediaCleanText(d.Text(".ringtone + b, div.col-xs-12 > b")), 200); bTitle != "" && title == "" { + title = strings.Trim(bTitle, `"`) + } + } + if title == "" { + if rawT := wave3MediaExtractTitleBounded(rawHTML); rawT != "" { + cleanT := wave3MediaRxAZTitleClean.ReplaceAllString(rawT, "") + if parts := strings.SplitN(cleanT, " - ", 2); len(parts) == 2 { + if artist == "" { + artist = SanitizeSchemaPlainField(parts[0], 140) + } + title = SanitizeSchemaPlainField(parts[1], 200) + } else { + title = SanitizeSchemaPlainField(cleanT, 200) + } + } + } + } + + // 2. Genius (`[data-lyrics-container="true"]` + `__PRELOADED_STATE__`) + if strings.Contains(urlLower, "genius.com") || wave3MediaContainsASCIIFold(rawHTML, "data-lyrics-container") || wave3MediaContainsASCIIFold(rawHTML, "__preloaded_state__") { + if d := ensureDoc(); d != nil { + containers := d.Select(`[data-lyrics-container="true"]`, 16) + if len(containers) > 0 { + var parts []string + for _, c := range containers { + inner := c.HTML() + if inner == "" { + inner = c.Text() + } + if ln := wave3MediaHTMLToLines(inner); ln != "" { + parts = append(parts, ln) + } + } + if len(parts) > 0 { + lyrics = strings.Join(parts, "\n\n") + } + } + if title == "" { + title = SanitizeSchemaPlainField(wave3MediaCleanText(d.Text(`[class*="SongHeader"][class*="Title"], h1[class*="SongHeader"], h1`)), 220) + } + if artist == "" { + artist = SanitizeSchemaPlainField(wave3MediaCleanText(d.Text(`[class*="HeaderArtistAndTracklist"] a, [class*="SongHeader"] a[href*="/artists/"]`)), 160) + } + } + if pre := wave3MediaExtractGeniusPreloaded(rawHTML); pre != nil { + if songPage := wave3MediaNestedMap(pre, "songPage"); songPage != nil { + songID := wave3MediaStringVal(songPage["song"]) + if entities := wave3MediaNestedMap(pre, "entities"); entities != nil { + if songsMap := wave3MediaNestedMap(entities, "songs"); songsMap != nil { + if songObj := wave3MediaNestedMap(songsMap, songID); songObj != nil { + if t := wave3MediaPlain(songObj["title"], 220); t != "" && title == "" { + title = t + } + if a := wave3MediaPlain(songObj["artistNames"], 160); a != "" && artist == "" { + artist = a + } + if a2 := wave3MediaPlain(songObj["artist_names"], 160); a2 != "" && artist == "" { + artist = a2 + } + if rd := wave3MediaPlain(songObj["releaseDateForDisplay"], 40); rd != "" && releaseDate == "" { + releaseDate = rd + } + if alb := wave3MediaPlain(wave3MediaNestedMap(songObj, "album")["name"], 180); alb != "" && album == "" { + album = alb + } + } + } + if refsMap := wave3MediaNestedMap(entities, "referents"); refsMap != nil { + for _, rawRef := range refsMap { + if len(annotations) >= 10 { + break + } + if rm, okRM := rawRef.(map[string]any); okRM { + frag := wave3MediaPlain(rm["fragment"], 120) + var annText string + if annArr, okA := rm["annotations"].([]any); okA && len(annArr) > 0 { + if am, okAM := annArr[0].(map[string]any); okAM { + if bm := wave3MediaNestedMap(am, "body"); bm != nil { + annText = wave3MediaFirstNonEmpty(wave3MediaPlain(bm["plain"], 320), wave3MediaPlain(bm["html"], 320)) + } else { + annText = wave3MediaPlain(am["body"], 320) + } + } + } + if annText == "" { + annText = wave3MediaPlain(rm["annotationText"], 320) + } + if annText != "" { + annotations = append(annotations, fmt.Sprintf("%s: %s", wave3MediaFirstNonEmpty(frag, "Note"), annText)) + } + } + } + } + } + } + // Direct flat song object fallback inside __PRELOADED_STATE__ + if songObj := wave3MediaNestedMap(pre, "song"); songObj != nil { + if t := wave3MediaPlain(songObj["title"], 220); t != "" && title == "" { + title = t + } + if a := wave3MediaFirstNonEmpty(wave3MediaPlain(songObj["artist_names"], 160), wave3MediaPlain(wave3MediaNestedMap(songObj, "primary_artist")["name"], 160)); a != "" && artist == "" { + artist = a + } + if alb := wave3MediaPlain(wave3MediaNestedMap(songObj, "album")["name"], 180); alb != "" && album == "" { + album = alb + } + if lyr := wave3MediaHTMLToLines(wave3MediaStringVal(songObj["lyrics"])); lyr != "" && lyrics == "" { + lyrics = lyr + } + } + } + if d := ensureDoc(); d != nil && len(annotations) == 0 { + for _, an := range d.Select(`[class*="Annotation__Container"], [class*="SongDescription__Container"]`, 6) { + if txt := SanitizeSchemaPlainField(wave3MediaCleanText(an.Text()), 360); txt != "" { + annotations = append(annotations, txt) + } + } + } + } + + // 3. Musixmatch (`__NEXT_DATA__` / `.mxm-lyrics__content` / `span.lyrics__content__ok`) + if strings.Contains(urlLower, "musixmatch.com") || wave3MediaContainsASCIIFold(rawHTML, "mxm-lyrics") || wave3MediaContainsASCIIFold(rawHTML, "lyrics__content__ok") { + if nextObj := wave3MediaExtractNextDataObj(rawHTML); nextObj != nil { + if dataObj := wave3MediaNestedMap(nextObj, "props", "pageProps", "data", "trackInfo", "data"); dataObj != nil { + if trk := wave3MediaNestedMap(dataObj, "track"); trk != nil { + if t := wave3MediaPlain(trk["name"], 220); t != "" && title == "" { + title = t + } + if a := wave3MediaPlain(trk["artistName"], 160); a != "" && artist == "" { + artist = a + } + if al := wave3MediaPlain(trk["albumName"], 180); al != "" && album == "" { + album = al + } + } + if lyr := wave3MediaNestedMap(dataObj, "lyrics"); lyr != nil { + if body := wave3MediaHTMLToLines(wave3MediaStringVal(lyr["body"])); body != "" && lyrics == "" { + lyrics = body + } + } + } + } + if lyrics == "" { + if d := ensureDoc(); d != nil { + var parts []string + for _, node := range d.Select(".mxm-lyrics__content, span.lyrics__content__ok", 20) { + inner := node.HTML() + if inner == "" { + inner = node.Text() + } + if ln := wave3MediaHTMLToLines(inner); ln != "" { + parts = append(parts, ln) + } + } + if len(parts) > 0 { + lyrics = strings.Join(parts, "\n") + } + if title == "" { + title = SanitizeSchemaPlainField(wave3MediaCleanText(d.Text(".mxm-track-title__track, h1")), 220) + } + if artist == "" { + artist = SanitizeSchemaPlainField(wave3MediaCleanText(d.Text(".mxm-track-title__artist")), 160) + } + } + } + } + + // 4. SongMeanings (`textarea[name="editLyricsBody"]`, `.lyric-box`, `#lyrics-body`, meanings/comments) + if strings.Contains(urlLower, "songmeanings.com") || wave3MediaContainsASCIIFold(rawHTML, "editlyricsbody") || wave3MediaContainsASCIIFold(rawHTML, "lyric-box") { + if d := ensureDoc(); d != nil { + if lyrics == "" { + if ta := d.First(`textarea[name="editLyricsBody"], #editLyricsBody`); ta != nil { + if ln := wave3MediaHTMLToLines(ta.HTML()); ln != "" { + lyrics = ln + } else if ln := wave3MediaHTMLToLines(ta.Text()); ln != "" { + lyrics = ln + } + } + } + if lyrics == "" { + if box := d.First(`.lyric-box, #lyrics-body`); box != nil { + inner := box.HTML() + if inner == "" { + inner = box.Text() + } + if ln := wave3MediaHTMLToLines(inner); ln != "" { + lyrics = ln + } + } + } + for _, cm := range d.Select(`.comment-body, .meaning-body, #comments .text`, 8) { + if txt := SanitizeSchemaPlainField(wave3MediaCleanText(cm.Text()), 360); txt != "" { + annotations = append(annotations, txt) + } + } + } + } + + if title == "" { + rawT := wave3MediaExtractTitle(ensureDoc(), rawHTML) + rawT = wave3MediaRxGeniusTitleDash.ReplaceAllString(rawT, "") + title = SanitizeSchemaPlainField(rawT, 220) + } + if title == "" || strings.TrimSpace(lyrics) == "" { + return nil + } + + docTitle := title + if artist != "" && !strings.Contains(strings.ToLower(title), strings.ToLower(artist)) { + docTitle = artist + " - " + title + } + + var bullets []string + bullets = append(bullets, "- **Title**: "+escapeDeclMarkdownBrackets(title)) + if artist != "" { + bullets = append(bullets, "- **Artist**: "+escapeDeclMarkdownBrackets(artist)) + } + if album != "" { + bullets = append(bullets, "- **Album**: "+escapeDeclMarkdownBrackets(album)) + } + if releaseDate != "" { + bullets = append(bullets, "- **Release Date**: "+escapeDeclMarkdownBrackets(releaseDate)) + } + + blocks := []string{ + "# " + escapeDeclMarkdownBrackets(docTitle), + strings.Join(bullets, "\n"), + "## Lyrics\n\n" + escapeDeclPlainTextPreservingNewlines(lyrics), + } + if len(annotations) > 0 { + var annBullets []string + for _, a := range annotations { + annBullets = append(annBullets, "- "+escapeDeclMarkdownBrackets(a)) + } + blocks = append(blocks, "## Annotations & Meanings\n\n"+strings.Join(annBullets, "\n")) + } + + rec := map[string]any{ + "title": title, + "lyrics": sliceRunesMax(lyrics, 4000), + } + if artist != "" { + rec["artist"] = artist + } + if album != "" { + rec["album"] = album + } + if releaseDate != "" { + rec["releaseDate"] = releaseDate + } + if len(annotations) > 0 { + rec["annotations"] = annotations + } + + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: docTitle, + Author: artist, + PublishedTime: releaseDate, + Description: sliceRunesMax(strings.ReplaceAll(lyrics, "\n", " "), 240), + Markdown: strings.Join(blocks, "\n\n"), + Records: []map[string]any{rec}, + } +} diff --git a/internal/extract/wave3_media_lyrics_test.go b/internal/extract/wave3_media_lyrics_test.go new file mode 100644 index 0000000..a4f308b --- /dev/null +++ b/internal/extract/wave3_media_lyrics_test.go @@ -0,0 +1,584 @@ +package extract + +import ( + "encoding/json" + "net/url" + "os" + "path/filepath" + "regexp" + "strings" + "testing" + "time" + + "github.com/bartrumb/edgefetch/v2/internal/classify" +) + +func wave3MediaResolveManifest(t *testing.T, m *DeclarativeAdapterManifest, rawURL string) (*DeclarativeTwinMatch, bool) { + t.Helper() + u, err := url.Parse(rawURL) + if err != nil { + t.Fatalf("url.Parse(%q): %v", rawURL, err) + } + host := strings.TrimSuffix(strings.ToLower(u.Hostname()), ".") + rawParts := splitNonEmptyEscapedSegments(u.EscapedPath()) + return resolveManifestTwinOnParsedURL(m, u, host, rawParts, DeclarativeResolveOptions{}) +} + +func TestWave3MediaManifestsAndRouting(t *testing.T) { + catRIDs := []string{ + "tmdb", + "imdb-datasets", + "tvmaze", + "musicbrainz-coverart", + "discogs", + "podcast-index", + "spotify-web-api", + "setlist-lastfm", + "steam-store", + "igdb", + "bandcamp", + "genius-lyrics", + } + + byID := make(map[string]*DeclarativeAdapterManifest) + claimedDomains := make(map[string]string) + + for _, id := range catRIDs { + raw, err := os.ReadFile(filepath.Join("manifests", id+".yaml")) + if err != nil { + t.Fatalf("read %s.yaml: %v", id, err) + } + m, err := ParseDeclarativeYAMLManifest(raw) + if err != nil { + t.Fatalf("ParseDeclarativeYAMLManifest(%s.yaml): %v", id, err) + } + if m.ID != id { + t.Fatalf("%s.yaml has mismatched id=%q", id, m.ID) + } + if m.Category != "commerce-social" { + t.Fatalf("%s.yaml must use category commerce-social, got %q", id, m.Category) + } + if m.AuthMode == "detect-only" || m.DetectOnly != nil { + t.Fatalf("%s.yaml uses retired detect-only", id) + } + for _, d := range m.Domains { + ld := strings.ToLower(strings.TrimSpace(d)) + if prev, exists := claimedDomains[ld]; exists { + t.Fatalf("duplicate domain %q across %s and %s", ld, prev, id) + } + claimedDomains[ld] = id + } + for _, hr := range m.HTMLRoutes { + for _, b := range hr.Bullets { + if strings.ContainsAny(b.Label, "{}") { + t.Fatalf("%s.yaml bullet label contains {}: %q", id, b.Label) + } + } + } + byID[id] = m + } + + // Disjointness from existing media manifests + for _, existingID := range []string{"vimeo", "twitch-kick", "podcasts-apple-lookup", "youtube-oembed"} { + fpath := filepath.Join("manifests", existingID+".yaml") + raw, err := os.ReadFile(fpath) + if err != nil { + continue + } + em, err := ParseDeclarativeYAMLManifest(raw) + if err != nil { + t.Fatalf("ParseDeclarativeYAMLManifest(%s.yaml): %v", existingID, err) + } + for _, d := range em.Domains { + ld := strings.ToLower(strings.TrimSpace(d)) + if catOwner, overlap := claimedDomains[ld]; overlap { + t.Fatalf("Cat R %s overlaps %s domain %q", catOwner, existingID, ld) + } + } + } + + // #375 tmdb: keyed API + movie/tv slug twin + tmTmdb, okTmdb := wave3MediaResolveManifest(t, byID["tmdb"], "https://www.themoviedb.org/movie/550-fight-club") + if !okTmdb || tmTmdb.FetchURL != "https://api.themoviedb.org/3/movie/550" || + tmTmdb.AuthMode != "key" || tmTmdb.route.Extract.JSONMode != "tmdb_json" { + t.Fatalf("tmdb route failed: ok=%v tm=%+v", okTmdb, tmTmdb) + } + + // #376 imdb-datasets: Range header + maxBytes 524288 + textMode imdb_datasets_tsv + tmImdb, okImdb := wave3MediaResolveManifest(t, byID["imdb-datasets"], "https://datasets.imdbws.com/title.ratings.tsv.gz") + if !okImdb || tmImdb.route.Twin.Headers["Range"] != "bytes=0-262143" || + tmImdb.EffectiveMaxBytes() != 524288 || tmImdb.route.Extract.TextMode != "imdb_datasets_tsv" { + t.Fatalf("imdb-datasets route failed: ok=%v tm=%+v", okImdb, tmImdb) + } + + // #377 tvmaze: show slug resolves to api.tvmaze.com; reserved subpaths like /episodes do not rewrite + tmTV, okTV := wave3MediaResolveManifest(t, byID["tvmaze"], "https://www.tvmaze.com/shows/1/under-the-dome") + if !okTV || tmTV.FetchURL != "https://api.tvmaze.com/shows/1?embed=episodes" || tmTV.route.Extract.JSONMode != "tvmaze_json" { + t.Fatalf("tvmaze show route failed: ok=%v tm=%+v", okTV, tmTV) + } + if tmTVEp, okTVEp := wave3MediaResolveManifest(t, byID["tvmaze"], "https://www.tvmaze.com/shows/1/episodes"); okTVEp || tmTVEp != nil { + t.Fatalf("tvmaze /shows/1/episodes must not rewrite to show twin: %+v", tmTVEp) + } + + // #378 musicbrainz-coverart: politeness flags + zero cross-domain twin + mb := byID["musicbrainz-coverart"] + if mb.MinIntervalMs < 1000 || mb.MaxConcurrent != 1 || mb.UserAgentProfile != "musicbrainz" || mb.StrictRobots { + t.Fatalf("musicbrainz-coverart flags mismatch: %+v", mb) + } + tmCAA, okCAA := wave3MediaResolveManifest(t, mb, "https://coverartarchive.org/release/76df3287-6cda-33eb-8e9a-044b5e15ffdd") + if !okCAA || tmCAA.route.Extract.JSONMode != "coverart_archive_json" || tmCAA.UserAgentProfile != "musicbrainz" { + t.Fatalf("coverartarchive route failed: ok=%v tm=%+v", okCAA, tmCAA) + } + tmMBWS, okMBWS := wave3MediaResolveManifest(t, mb, "https://musicbrainz.org/ws/2/artist/5b11f4ce-a62d-471e-81fc-a69a8278c7da") + if !okMBWS || !strings.Contains(tmMBWS.FetchURL, "fmt=json") || tmMBWS.route.Extract.JSONMode != "musicbrainz_json" { + t.Fatalf("musicbrainz ws/2 route failed: ok=%v tm=%+v", okMBWS, tmMBWS) + } + // musicbrainz.org/release/ must NOT cross-domain twin to coverartarchive.org + if tmMBRel, okMBRel := wave3MediaResolveManifest(t, mb, "https://musicbrainz.org/release/76df3287-6cda-33eb-8e9a-044b5e15ffdd"); okMBRel || tmMBRel != nil { + t.Fatalf("musicbrainz.org/release/ must stay on HTML fallback, not twin: %+v", tmMBRel) + } + + // #379 discogs: /release/{id}-slug -> api.discogs.com/releases/{id} + tmDisc, okDisc := wave3MediaResolveManifest(t, byID["discogs"], "https://www.discogs.com/release/249504-Rick-Astley-Never-Gonna-Give-You-Up") + if !okDisc || tmDisc.FetchURL != "https://api.discogs.com/releases/249504" || tmDisc.route.Extract.JSONMode != "discogs_json" { + t.Fatalf("discogs release route failed: ok=%v tm=%+v", okDisc, tmDisc) + } + + // #381 spotify-web-api: /oembed is pub, /v1/ is key, open.spotify.com/track/ uses htmlRoutes + sp := byID["spotify-web-api"] + tmSpOembed, okSpOembed := wave3MediaResolveManifest(t, sp, "https://open.spotify.com/oembed?url=https://open.spotify.com/show/4rOoJ6Egrf8K2IrywzwOMk") + if !okSpOembed || tmSpOembed.AuthMode != "pub" || tmSpOembed.route.Extract.JSONMode != "spotify_oembed_json" { + t.Fatalf("spotify oembed route failed: ok=%v tm=%+v", okSpOembed, tmSpOembed) + } + tmSpAPI, okSpAPI := wave3MediaResolveManifest(t, sp, "https://api.spotify.com/v1/shows/4rOoJ6Egrf8K2IrywzwOMk") + if !okSpAPI || tmSpAPI.AuthMode != "key" || tmSpAPI.route.Extract.JSONMode != "spotify_api_json" { + t.Fatalf("spotify api route failed: ok=%v tm=%+v", okSpAPI, tmSpAPI) + } + if tmSpHTML, okSpHTML := wave3MediaResolveManifest(t, sp, "https://open.spotify.com/track/4cOdK2wGLETKBW3PvgPWqT"); okSpHTML || tmSpHTML != nil { + t.Fatalf("open.spotify.com/track must stay on HTML fallback (api.spotify.com robots disallow), got %+v", tmSpHTML) + } + + // #383 steam-store: /app/620/Portal_2/ -> appdetails?appids=620 + tmSteam, okSteam := wave3MediaResolveManifest(t, byID["steam-store"], "https://store.steampowered.com/app/620/Portal_2/") + if !okSteam || tmSteam.FetchURL != "https://store.steampowered.com/api/appdetails?appids=620" { + t.Fatalf("steam /app/ route failed: ok=%v tm=%+v", okSteam, tmSteam) + } + + // #384 igdb: POST + text/plain + requestBody + tmIGDB, okIGDB := wave3MediaResolveManifest(t, byID["igdb"], "https://www.igdb.com/games/portal-2") + if !okIGDB || tmIGDB.FetchURL != "https://api.igdb.com/v4/games" || tmIGDB.Method != "POST" || + tmIGDB.ContentType != "text/plain" || !strings.Contains(tmIGDB.RequestBody, `where slug = "portal-2"`) { + t.Fatalf("igdb route failed: ok=%v tm=%+v", okIGDB, tmIGDB) + } + + // #386 genius-lyrics: real html adapter (never detect-only) + if byID["genius-lyrics"].AuthMode != "html" { + t.Fatalf("genius-lyrics must be auth_mode: html, got %q", byID["genius-lyrics"].AuthMode) + } +} + +func TestWave3MediaJSONTextAndHTMLModes(t *testing.T) { + registerWave3MediaLyricsHTMLModes() + RegisterWave3MediaLyricsHTMLModes() + + expectedHTMLModes := []string{ + "tmdb_html", + "imdb_datasets_html", + "tvmaze_html", + "musicbrainz_html", + "discogs_html", + "podcast_index_html", + "spotify_html", + "setlist_lastfm_html", + "steam_store_html", + "igdb_html", + "bandcamp_html", + "genius_lyrics_html", + } + for _, hm := range expectedHTMLModes { + if getExternalHTMLModeLazy(hm) == nil { + t.Fatalf("RegisterExternalHTMLModeLazy missing %q", hm) + } + if !IsWave3MediaLyricsHTMLMode(hm) { + t.Fatalf("IsWave3MediaLyricsHTMLMode(%q) = false", hm) + } + } + + // #376 IMDb Datasets TSV + HTML MUST emit nonCommercialLicense: true and IMDb Non-Commercial Datasets notice + tsvPayload := "tconst\taverageRating\tnumVotes\ntt0000001\t5.7\t2244\ntt0000002\t5.5\t308\ntt0000003\t6" + imdbDoc, okImdb := FormatWave3MediaLyricsTextDoc("imdb_datasets_tsv", tsvPayload, nil, "https://datasets.imdbws.com/title.ratings.tsv.gz") + if !okImdb || imdbDoc == nil || len(imdbDoc.Records) != 2 { + t.Fatalf("imdb_datasets_tsv failed (should ignore truncated trailing line): ok=%v doc=%+v", okImdb, imdbDoc) + } + if !strings.Contains(imdbDoc.Markdown, "IMDb Non-Commercial Datasets") || !strings.Contains(imdbDoc.Markdown, "nonCommercialLicense: true") { + t.Fatalf("imdb_datasets_tsv missing license notice in markdown:\n%s", imdbDoc.Markdown) + } + if nc, okNC := imdbDoc.Records[0]["nonCommercialLicense"].(bool); !okNC || !nc { + t.Fatalf("imdb_datasets_tsv missing nonCommercialLicense:true in record: %+v", imdbDoc.Records[0]) + } + + imdbHTML := `IMDb Non-Commercial Datasets

IMDb Non-Commercial Datasets

Subsets of IMDb data are available for access to customers for personal and non-commercial use.

title.basics.tsv.gz
` + imdbHRes := Wave3MediaLyricsRunHTML("imdb_datasets_html", imdbHTML, "https://data.imdb.com/non-commercial-datasets/", "imdb-datasets") + if imdbHRes == nil || !strings.Contains(imdbHRes.Markdown, "IMDb Non-Commercial Datasets") || !strings.Contains(imdbHRes.Markdown, "nonCommercialLicense: true") { + t.Fatalf("imdb_datasets_html missing license notice: %+v", imdbHRes) + } + if nc, okNC := imdbHRes.Records[0]["nonCommercialLicense"].(bool); !okNC || !nc { + t.Fatalf("imdb_datasets_html missing nonCommercialLicense:true in record: %+v", imdbHRes.Records[0]) + } + + // #378 MusicBrainz WS2 JSON + PoW /__meb_verify rejection + mbJSON := `{"id":"5b11f4ce-a62d-471e-81fc-a69a8278c7da","name":"Nirvana","type":"Group","country":"US","life-span":{"begin":"1987","end":"1994"},"genres":[{"name":"grunge"},{"name":"rock"}]}` + mbOut, okMB := FormatWave3MediaLyricsJSONMode("musicbrainz_json", []byte(mbJSON), nil, "https://musicbrainz.org/ws/2/artist/5b11f4ce-a62d-471e-81fc-a69a8278c7da?fmt=json") + if !okMB || !strings.Contains(mbOut, "Nirvana") || !strings.Contains(mbOut, "grunge") { + t.Fatalf("musicbrainz_json failed: ok=%v out=%s", okMB, mbOut) + } + powHTML := `Verifying your browser
` + if r := Wave3MediaLyricsRunHTML("musicbrainz_html", powHTML, "https://musicbrainz.org/release/76df3287-6cda-33eb-8e9a-044b5e15ffdd", "musicbrainz-coverart"); r != nil { + t.Fatalf("musicbrainz_html must reject /__meb_verify PoW challenge, got %+v", r) + } + + // #381 Spotify HTML JSON-LD + og/music metas + spHTML := `The Joe Rogan Experience | Podcast on Spotify
` + spRes := Wave3MediaLyricsRunHTML("spotify_html", spHTML, "https://open.spotify.com/show/4rOoJ6Egrf8K2IrywzwOMk", "spotify-web-api") + if spRes == nil || !strings.Contains(spRes.Markdown, "Joe Rogan") { + t.Fatalf("spotify_html failed: %+v", spRes) + } + + // #382 Setlist.fm + Last.fm Fastly challenge rejection + Setlist.fm JSON + slJSON := `{"id":"3ba45068","eventDate":"23-09-2023","artist":{"name":"Motionless in White"},"venue":{"name":"Mobile Civic Center","city":{"name":"Mobile"}},"sets":{"set":[{"name":"Main","song":[{"name":"Meltdown"},{"name":"Sign of Life"}]}]}}` + if slOut, okSL := FormatWave3MediaLyricsJSONMode("setlist_fm_json", []byte(slJSON), nil, "https://api.setlist.fm/rest/1.0/setlist/3ba45068"); !okSL || !strings.Contains(slOut, "Meltdown") { + t.Fatalf("setlist_fm_json failed: ok=%v out=%s", okSL, slOut) + } + fastlyHTML := `Last.fm` + if r := Wave3MediaLyricsRunHTML("setlist_lastfm_html", fastlyHTML, "https://www.last.fm/music/Nirvana", "setlist-lastfm"); r != nil { + t.Fatalf("setlist_lastfm_html must reject Fastly /_fs-ch- challenge") + } + + // #383 Steam Store appreviews HTML redirect rejection + appdetails success:false rejection + ISteamNews JSON + if _, okBadApp := FormatWave3MediaLyricsJSONMode("steam_store_json", []byte(`{"99999999":{"success":false}}`), nil, "https://store.steampowered.com/api/appdetails?appids=99999999"); okBadApp { + t.Fatalf("steam_store_json must reject appdetails success:false") + } + if _, okBadRev := FormatWave3MediaLyricsJSONMode("steam_store_json", []byte(`Welcome to Steam`), nil, "https://store.steampowered.com/appreviews/620?json=1"); okBadRev { + t.Fatalf("steam_store_json must reject HTML homepage redirect on /appreviews/") + } + steamNews := `{"appnews":{"appid":620,"newsitems":[{"gid":"1","title":"Portal 2 Update Released","author":"Valve","feedlabel":"Product Update","url":"https://store.steampowered.com/news/app/620"}]}}` + if snOut, okSN := FormatWave3MediaLyricsJSONMode("steam_store_json", []byte(steamNews), nil, "https://api.steampowered.com/ISteamNews/GetNewsForApp/v2/?appid=620"); !okSN || !strings.Contains(snOut, "Portal 2 Update Released") { + t.Fatalf("steam_store_json ISteamNews failed: ok=%v out=%s", okSN, snOut) + } + + // #386 Genius Lyrics REAL extractor across Genius, AZLyrics, Musixmatch & SongMeanings + // 1. Genius with JSON.parse('...') __PRELOADED_STATE__ + [data-lyrics-container="true"] + geniusHTML := `Rick Astley - Never Gonna Give You Up Lyrics | Genius Lyrics
[Verse 1]
We're no strangers to love
You know the rules and so do I
` + gRes := Wave3MediaLyricsRunHTML("genius_lyrics_html", geniusHTML, "https://genius.com/Rick-astley-never-gonna-give-you-up-lyrics", "genius-lyrics") + if gRes == nil || !strings.Contains(gRes.Markdown, "We're no strangers to love\nYou know the rules and so do I") || !strings.Contains(gRes.Markdown, "Classic 1987 pop hook.") { + t.Fatalf("genius_lyrics_html Genius extraction failed: %+v", gRes) + } + + // 2. AZLyrics comment-anchored unclassed
+ azHTML := `Rick Astley - Never Gonna Give You Up Lyrics | AZLyrics.com

Rick Astley Lyrics

"Never Gonna Give You Up"
We're no strangers to love
You know the rules and so do I
A full commitment's what I'm thinking of
album: "Whenever You Need Somebody" (1987)
` + azRes := Wave3MediaLyricsRunHTML("genius_lyrics_html", azHTML, "https://www.azlyrics.com/lyrics/rickastley/nevergonnagiveyouup.html", "genius-lyrics") + if azRes == nil || !strings.Contains(azRes.Markdown, "Rick Astley") || !strings.Contains(azRes.Markdown, "You know the rules and so do I\nA full commitment's what I'm thinking of") { + t.Fatalf("genius_lyrics_html AZLyrics extraction failed: %+v", azRes) + } + + // 3. Musixmatch __NEXT_DATA__ and DOM .mxm-lyrics__content + mxmHTML := `Never Gonna Give You Up Lyrics - Rick Astley | Musixmatch
` + mxmRes := Wave3MediaLyricsRunHTML("genius_lyrics_html", mxmHTML, "https://www.musixmatch.com/lyrics/Rick-Astley/Never-Gonna-Give-You-Up", "genius-lyrics") + if mxmRes == nil || !strings.Contains(mxmRes.Markdown, "Never Gonna Give You Up") || !strings.Contains(mxmRes.Markdown, "You know the rules and so do I") { + t.Fatalf("genius_lyrics_html Musixmatch __NEXT_DATA__ extraction failed: %+v", mxmRes) + } + + // 4. SongMeanings MusicRecording JSON-LD + textarea[name="editLyricsBody"] + meaning comment + smHTML := `Rick Astley - Never Gonna Give You Up Lyrics | SongMeanings
An upbeat 80s anthem about unwavering loyalty.
` + smRes := Wave3MediaLyricsRunHTML("genius_lyrics_html", smHTML, "https://songmeanings.com/songs/view/3530822107858506064/", "genius-lyrics") + if smRes == nil || !strings.Contains(smRes.Markdown, "Never Gonna Give You Up") || !strings.Contains(smRes.Markdown, "unwavering loyalty") { + t.Fatalf("genius_lyrics_html SongMeanings extraction failed: %+v", smRes) + } + + // 5. Genius CF shell without lyrics container / __PRELOADED_STATE__ must be rejected + if badG := Wave3MediaLyricsRunHTML("genius_lyrics_html", `Genius
`, "https://genius.com/Rick-astley-never-gonna-give-you-up-lyrics", "genius-lyrics"); badG != nil { + t.Fatalf("genius_lyrics_html must reject Genius shell without lyrics container") + } + + // 6. Additional JSON formatters: spotify_api_json, lastfm_json, igdb_json empty array rejection + spAPI := `{"id":"4rOoJ6Egrf8K2IrywzwOMk","name":"The Joe Rogan Experience","type":"show","publisher":"Joe Rogan","total_episodes":2100,"external_urls":{"spotify":"https://open.spotify.com/show/4rOoJ6Egrf8K2IrywzwOMk"}}` + if spOut, okSP := FormatWave3MediaLyricsJSONMode("spotify_api_json", []byte(spAPI), nil, "https://api.spotify.com/v1/shows/4rOoJ6Egrf8K2IrywzwOMk"); !okSP || !strings.Contains(spOut, "Joe Rogan") { + t.Fatalf("spotify_api_json failed: ok=%v out=%s", okSP, spOut) + } + lfmJSON := `{"artist":{"name":"Cher","mbid":"bfcc6d75-a6a5-4bc6-8282-47aec8531818","stats":{"listeners":"1800000","playcount":"35000000"},"tags":{"tag":[{"name":"pop"},{"name":"dance"}]},"bio":{"summary":"American singer and actress."}}}` + if lfmOut, okLFM := FormatWave3MediaLyricsJSONMode("lastfm_json", []byte(lfmJSON), nil, "https://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=Cher&format=json"); !okLFM || !strings.Contains(lfmOut, "Cher") || !strings.Contains(lfmOut, "1800000") { + t.Fatalf("lastfm_json failed: ok=%v out=%s", okLFM, lfmOut) + } + if _, okEmptyIGDB := FormatWave3MediaLyricsJSONMode("igdb_json", []byte(`[]`), nil, "https://api.igdb.com/v4/games"); okEmptyIGDB { + t.Fatalf("igdb_json must reject empty array []") + } +} + +func TestWave3MediaLyricsFixturesGoldenAndNegativeShells(t *testing.T) { + registerWave3MediaLyricsHTMLModes() + + type fixtureNeg struct { + Name string `json:"name"` + Status int `json:"status"` + InputURL string `json:"inputUrl"` + FinalURL string `json:"finalUrl"` + Payload string `json:"payload"` + } + type fixtureDoc struct { + AdapterID string `json:"adapterId"` + Mode string `json:"mode"` + InputURL string `json:"inputUrl"` + ExpectedFetchURL string `json:"expectedFetchUrl"` + MockPayload string `json:"mockPayload"` + ExpectTitleIncludes string `json:"expectTitleIncludes"` + ExpectMarkdownIncludes []string `json:"expectMarkdownIncludes"` + NegativeCases []fixtureNeg `json:"negativeCases"` + } + + ids := []string{ + "tmdb", + "imdb-datasets", + "tvmaze", + "musicbrainz-coverart", + "discogs", + "podcast-index", + "spotify-web-api", + "setlist-lastfm", + "steam-store", + "igdb", + "bandcamp", + "genius-lyrics", + } + + for _, id := range ids { + fpath := filepath.Join("..", "..", "hub", "test", "fixtures", "adapters", id+".json") + raw, err := os.ReadFile(fpath) + if err != nil { + t.Fatalf("read fixture %s: %v", fpath, err) + } + var fx fixtureDoc + if err := json.Unmarshal(raw, &fx); err != nil { + t.Fatalf("unmarshal fixture %s: %v", fpath, err) + } + if fx.AdapterID != id { + t.Fatalf("%s: adapterId=%q != %q", id, fx.AdapterID, id) + } + if len(fx.NegativeCases) < 4 { + t.Fatalf("%s: expected >= 4 negativeCases, got %d", id, len(fx.NegativeCases)) + } + + mRaw, err := os.ReadFile(filepath.Join("manifests", id+".yaml")) + if err != nil { + t.Fatalf("read %s.yaml: %v", id, err) + } + m, err := ParseDeclarativeYAMLManifest(mRaw) + if err != nil { + t.Fatalf("parse %s.yaml: %v", id, err) + } + + start := time.Now() + var gotTitle, gotMD string + if fx.Mode == "twin" { + tm, ok := wave3MediaResolveManifest(t, m, fx.InputURL) + if !ok || tm == nil { + t.Fatalf("%s: failed to resolve twin for %s", id, fx.InputURL) + } + if fx.ExpectedFetchURL != "" && tm.FetchURL != fx.ExpectedFetchURL { + t.Fatalf("%s: FetchURL=%q, want %q", id, tm.FetchURL, fx.ExpectedFetchURL) + } + if tm.route.Extract.JSONMode != "" && IsWave3MediaLyricsJSONMode(tm.route.Extract.JSONMode) { + doc, okDoc := FormatWave3MediaLyricsJSONDoc(tm.route.Extract.JSONMode, []byte(fx.MockPayload), tm.params, fx.InputURL) + if !okDoc || doc == nil { + t.Fatalf("%s: FormatWave3MediaLyricsJSONDoc(%s) failed", id, tm.route.Extract.JSONMode) + } + gotTitle, gotMD = doc.Title, doc.Markdown + } else if tm.route.Extract.TextMode != "" && IsWave3MediaLyricsTextMode(tm.route.Extract.TextMode) { + doc, okDoc := FormatWave3MediaLyricsTextDoc(tm.route.Extract.TextMode, fx.MockPayload, tm.params, fx.InputURL) + if !okDoc || doc == nil { + t.Fatalf("%s: FormatWave3MediaLyricsTextDoc(%s) failed", id, tm.route.Extract.TextMode) + } + gotTitle, gotMD = doc.Title, doc.Markdown + } else { + doc, okDoc := tm.Format(fx.MockPayload) + if !okDoc || doc == nil { + t.Fatalf("%s: tm.Format failed", id) + } + gotTitle, gotMD = doc.Title, doc.Markdown + } + } else { + if len(m.HTMLRoutes) == 0 { + t.Fatalf("%s: expected htmlRoutes", id) + } + htmlMode := m.HTMLRoutes[0].Mode + res := Wave3MediaLyricsRunHTML(htmlMode, fx.MockPayload, fx.InputURL, id) + if res == nil { + t.Fatalf("%s: Wave3MediaLyricsRunHTML(%s) returned nil on golden payload", id, htmlMode) + } + gotTitle, gotMD = res.Title, res.Markdown + } + if elapsed := time.Since(start); elapsed > 25*time.Millisecond*time.Duration(extractRaceSlowdown) { + t.Fatalf("%s: golden extraction took %v (> 25ms)", id, elapsed) + } + if fx.ExpectTitleIncludes != "" && !strings.Contains(gotTitle, fx.ExpectTitleIncludes) { + t.Fatalf("%s: title %q missing %q", id, gotTitle, fx.ExpectTitleIncludes) + } + for _, sub := range fx.ExpectMarkdownIncludes { + if !strings.Contains(gotMD, sub) { + t.Fatalf("%s: markdown missing %q\nmarkdown:\n%s", id, sub, gotMD) + } + } + + // Verify all negativeCases + for _, nc := range fx.NegativeCases { + negURL := fx.InputURL + if nc.FinalURL != "" { + negURL = nc.FinalURL + } else if nc.InputURL != "" { + negURL = nc.InputURL + } + if len(m.HTMLRoutes) > 0 { + if res := Wave3MediaLyricsRunHTML(m.HTMLRoutes[0].Mode, nc.Payload, negURL, id); res != nil { + t.Fatalf("%s:%s: HTML mode unexpectedly extracted content on negative case", id, nc.Name) + } + } + if fx.Mode == "twin" { + if tm, ok := wave3MediaResolveManifest(t, m, negURL); ok && tm != nil { + if tm.route.Extract.JSONMode != "" && IsWave3MediaLyricsJSONMode(tm.route.Extract.JSONMode) { + if doc, okDoc := FormatWave3MediaLyricsJSONDoc(tm.route.Extract.JSONMode, []byte(nc.Payload), tm.params, negURL); okDoc && doc != nil { + t.Fatalf("%s:%s: JSON mode unexpectedly formatted negative payload", id, nc.Name) + } + } + if tm.route.Extract.TextMode != "" && IsWave3MediaLyricsTextMode(tm.route.Extract.TextMode) { + if doc, okDoc := FormatWave3MediaLyricsTextDoc(tm.route.Extract.TextMode, nc.Payload, tm.params, negURL); okDoc && doc != nil { + t.Fatalf("%s:%s: Text mode unexpectedly formatted negative payload", id, nc.Name) + } + } + } + } + st := nc.Status + if st == 0 { + st = 200 + } + if st >= 200 && st < 300 { + ext := ExtractHTMLDocumentFull(nc.Payload, FullExtractOptions{ + BaseURL: negURL, + OnlyMainContent: true, + }) + cs := classify.ClassifyContentStateFull(classify.ContentStateInput{ + Status: st, + RawHTML: nc.Payload, + Markdown: ext.Markdown, + URL: fx.InputURL, + FinalURL: negURL, + Title: wave3MediaExtractTitleBounded(nc.Payload), + }) + if cs.State == "active" { + t.Fatalf("%s:%s (status=%d): ClassifyContentStateFull unexpectedly returned active (%s)", id, nc.Name, st, cs.Reason) + } + } + } + } +} + +func TestWave3MediaLyricsR7MarkdownHardening(t *testing.T) { + registerWave3MediaLyricsHTMLModes() + reInjectedHeading := regexp.MustCompile(`(?m)^#{1,6}[ \t]+.*InjectedHeading`) + + // 1. #386 genius_lyrics_html: title, artist, lyrics with [Verse 1], [Phish] link, and # InjectedHeading, plus annotation + preloadedInner, err := json.Marshal(map[string]any{ + "songPage": map[string]any{"song": 42}, + "entities": map[string]any{ + "songs": map[string]any{ + "42": map[string]any{ + "title": "Song [Phish](https://evil.example/gt)", + "artistNames": "Artist [Phish](https://evil.example/ga)", + }, + }, + "referents": map[string]any{ + "7": map[string]any{ + "fragment": "Line one", + "annotations": []map[string]any{ + {"body": map[string]any{"plain": "Note [Phish](https://evil.example/gann)"}}, + }, + }, + }, + }, + }) + if err != nil { + t.Fatalf("json.Marshal(preloadedInner): %v", err) + } + preloadedQuoted, err := json.Marshal(string(preloadedInner)) + if err != nil { + t.Fatalf("json.Marshal(preloadedQuoted): %v", err) + } + geniusHTML := `Song [Phish](https://evil.example/gt) Lyrics | Genius Lyrics

Song [Phish](https://evil.example/gt)

[Verse 1]
Line one [Phish](https://evil.example/gly)
# InjectedHeading
Line two
` + + gRes := Wave3MediaLyricsRunHTML("genius_lyrics_html", geniusHTML, "https://genius.com/Artist-song-lyrics", "genius-lyrics") + if gRes == nil { + t.Fatalf("genius_lyrics_html R7 returned nil") + } + if hasUnescapedClickableEvilLinkR10(gRes.Markdown) || strings.Contains(gRes.Markdown, "[Phish](") || !strings.Contains(gRes.Markdown, `\[Phish\]`) { + t.Fatalf("genius_lyrics_html leaked unescaped Markdown link:\n%s", gRes.Markdown) + } + wantLyricsBlock := "Line one \\[Phish\\]\\(https://evil.example/gly)\n\\# InjectedHeading\nLine two" + if !strings.Contains(gRes.Markdown, wantLyricsBlock) { + t.Fatalf("genius_lyrics_html did not preserve linebreaks and escape lyrics block:\nwant: %q\ngot:\n%s", wantLyricsBlock, gRes.Markdown) + } + for _, wantSub := range []string{ + `\[Verse 1\]`, + `https://evil.example/gt`, + `https://evil.example/ga`, + `https://evil.example/gann`, + } { + if !strings.Contains(gRes.Markdown, wantSub) { + t.Fatalf("genius_lyrics_html missing %q in Markdown:\n%s", wantSub, gRes.Markdown) + } + } + if reInjectedHeading.MatchString(gRes.Markdown) { + t.Fatalf("genius_lyrics_html allowed injected heading in Markdown:\n%s", gRes.Markdown) + } + if !strings.Contains(gRes.Title, "[Phish]") { + t.Fatalf("genius_lyrics_html Title should remain unescaped, got %q", gRes.Title) + } + if recLyrics, _ := gRes.Records[0]["lyrics"].(string); !strings.Contains(recLyrics, "Line one [Phish](https://evil.example/gly)") { + t.Fatalf("genius_lyrics_html Records[0][lyrics] should remain unescaped, got %q", recLyrics) + } + + // 2. #376 imdb_datasets_tsv: [Phish](https://evil.example/imdb) in TSV header and cell + tsvPayload := "tconst\tprimaryTitle [Phish](https://evil.example/imdb)\tgenres\ntt0000001\tMovie [Phish](https://evil.example/imdb)\tDrama\n" + imdbDoc, okImdb := FormatWave3MediaLyricsTextDoc("imdb_datasets_tsv", tsvPayload, nil, "https://datasets.imdbws.com/title.basics.tsv.gz") + if !okImdb || imdbDoc == nil { + t.Fatalf("imdb_datasets_tsv R7 failed: ok=%v doc=%+v", okImdb, imdbDoc) + } + if hasUnescapedClickableEvilLinkR10(imdbDoc.Markdown) || strings.Contains(imdbDoc.Markdown, "[Phish](") || !strings.Contains(imdbDoc.Markdown, `\[Phish\]`) { + t.Fatalf("imdb_datasets_tsv leaked unescaped Markdown link:\n%s", imdbDoc.Markdown) + } + if !strings.Contains(imdbDoc.Markdown, `primaryTitle \[Phish\]\(https://evil.example/imdb)`) || !strings.Contains(imdbDoc.Markdown, `Movie \[Phish\]\(https://evil.example/imdb)`) { + t.Fatalf("imdb_datasets_tsv missing escaped header or cell:\n%s", imdbDoc.Markdown) + } + if recVal, okRec := imdbDoc.Records[0]["primaryTitle [Phish](https://evil.example/imdb)"].(string); !okRec || recVal != "Movie [Phish](https://evil.example/imdb)" { + t.Fatalf("imdb_datasets_tsv Records[0] must keep unescaped header key and cell value, got %+v", imdbDoc.Records[0]) + } +} + +func TestWave3MediaLyricsM7AZLyricsCommentFormats(t *testing.T) { + registerWave3MediaLyricsHTMLModes() + + // 1. Live azlyrics.com format: comment INSIDE unclassed
+ azLiveHTML := `Rick Astley - Never Gonna Give You Up Lyrics | AZLyrics.com

Rick Astley Lyrics

"Never Gonna Give You Up"

+ +We're no strangers to love
+You know the rules and so do I +
` + resLive := Wave3MediaLyricsRunHTML("genius_lyrics_html", azLiveHTML, "https://www.azlyrics.com/lyrics/rickastley/nevergonnagiveyouup.html", "genius-lyrics") + if resLive == nil || !strings.Contains(resLive.Markdown, "We're no strangers to love") || !strings.Contains(resLive.Markdown, "You know the rules and so do I") || resLive.Author != "Rick Astley" { + t.Fatalf("azlyrics comment-inside-div failed: %+v", resLive) + } + + // 2. Legacy format: comment BEFORE
+ azLegacyHTML := `Rick Astley - Never Gonna Give You Up Lyrics | AZLyrics.com

Rick Astley Lyrics

A full commitment's what I'm thinking of
You wouldn't get this from any other guy
` + resLegacy := Wave3MediaLyricsRunHTML("genius_lyrics_html", azLegacyHTML, "https://www.azlyrics.com/lyrics/rickastley/nevergonnagiveyouup.html", "genius-lyrics") + if resLegacy == nil || !strings.Contains(resLegacy.Markdown, "A full commitment's what I'm thinking of") { + t.Fatalf("azlyrics comment-before-div compatibility failed: %+v", resLegacy) + } +} diff --git a/internal/extract/wave3_prop_rest_ir.go b/internal/extract/wave3_prop_rest_ir.go new file mode 100644 index 0000000..fdc1c13 --- /dev/null +++ b/internal/extract/wave3_prop_rest_ir.go @@ -0,0 +1,2527 @@ +package extract + +import ( + "bytes" + "encoding/json" + "fmt" + stdhtml "html" + "net/url" + "strconv" + "strings" +) + +const ( + wave3PRIRMaxHTMLBytes = 2 * 1024 * 1024 + wave3PRIRMaxJSONBytes = 4 * 1024 * 1024 + wave3PRIRMaxTextBytes = 2 * 1024 * 1024 + wave3PRIRMaxRecords = 30 +) + +var ( + wave3PRIRRxNotFoundTitle = newLazyRegexp(`(?i)(?:^|\b)(?:404|410|page\s+not\s+found|page\s+cannot\s+be\s+found|not\s+found|error\s*404|we\s+couldn'?t\s+find\s+that\s+page|access\s+denied|request\s+(?:rejected|blocked)|could\s+not\s+be\s+satisfied|unauthorized|attention\s+required|just\s+a\s+moment|403\s+forbidden|forbidden|listing\s+not\s+found|property\s+not\s+found|menu\s+not\s+found|press\s+release\s+not\s+found)(?:\b|$)`) + wave3PRIRRxMaintTitle = newLazyRegexp(`(?i)(?:scheduled\s+maintenance|temporarily\s+unavailable|service\s+unavailable|site\s+maintenance|under\s+maintenance|502\s+bad\s+gateway|503\s+service|down\s+for\s+maintenance)`) + wave3PRIRRxErrorTitle = newLazyRegexp(`(?i)^(?:(?:(?:401|403|404|410|429|500|502|503)\s+)?(?:internal\s+)?server\s+error|application\s+error|system\s+error|unexpected\s+error|error\s+page|(?:401|403|404|410|429|500|502|503|http\s+\d{3})\s+error|error\s+(?:401|403|404|410|429|500|502|503)|error)(?:\s*[|\-\x{2013}\x{2014}:]\s*.*)?$|^.*(?:\s*[|\-\x{2013}\x{2014}:]\s*error)$`) + wave3PRIRRxLoginTitle = newLazyRegexp(`(?i)^(?:log\s*in|sign\s+in|login|authentication\s+required|sso\s+login|single\s+sign[- ]on|web\s+login|resident\s+portal\s+login)(?:\s*[|\-\x{2013}\x{2014}:]\s*.*)?$`) + wave3PRIRRxSpace = newLazyRegexp(`[ \t\r\n]+`) + wave3PRIRRxRent = newLazyRegexp(`\$\s*([0-9][0-9,]*(?:\.[0-9]{2})?)(?:\s*(?:-|to|\x{2013})\s*\$?\s*([0-9][0-9,]*(?:\.[0-9]{2})?))?(?:\s*/\s*(?:mo|month))?`) + wave3PRIRRxBeds = newLazyRegexp(`(?i)\b(studio|\d+(?:\.\d+)?)\s*(?:bd|bed|beds|br|bedroom|bedrooms)\b`) + wave3PRIRRxBaths = newLazyRegexp(`(?i)\b(\d+(?:\.\d+)?)\s*(?:ba|bath|baths|bathroom|bathrooms)\b`) + wave3PRIRRxSqft = newLazyRegexp(`(?i)\b([0-9][0-9,]*(?:\s*-\s*[0-9][0-9,]*)?)\s*(?:sq\.?\s*ft\.?|sqft|sf)\b`) + wave3PRIRRxBootstrap = newLazyRegexp(`__BOOTSTRAP_STATE__\s*=`) + wave3PRIRRxNextData = newLazyRegexp(`(?is)]*\bid\s*=\s*["']__NEXT_DATA__["'][^>]*>(.*?)`) + wave3PRIRRxApolloState = newLazyRegexp(`__APOLLO_STATE__\s*=`) + wave3PRIRRxQ4Date = newLazyRegexp(`(\d{1,2}/\d{1,2}/\d{4}|\d{4}-\d{2}-\d{2}|(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*\s+\d{1,2},\s+\d{4})`) +) + +func init() { + for _, mode := range []string{ + "appfolio_listings_html", + "pm_listing_widgets_html", + "multifamily_portals_html", + "idx_broker_showcase_html", + "popmenu_html", + "bentobox_html", + "square_toast_menu_html", + "schema_menu_html", + "q4_ir_html", + "ir_portal_pack_html", + "company_newsrooms_html", + } { + m := mode + RegisterExternalHTMLModeLazy(m, func(rawHTML, baseURL string, _ func() string, extractorID string) *DeclarativePostFetchResult { + return Wave3PropRestIRRunHTML(m, rawHTML, baseURL, extractorID) + }) + } +} + +// IsWave3PropRestIRHTMLMode reports whether mode is handled by Categories F/G/H HTML extractors (#251-#261). +func IsWave3PropRestIRHTMLMode(mode string) bool { + switch mode { + case "appfolio_listings_html", + "pm_listing_widgets_html", + "multifamily_portals_html", + "idx_broker_showcase_html", + "popmenu_html", + "bentobox_html", + "square_toast_menu_html", + "schema_menu_html", + "q4_ir_html", + "ir_portal_pack_html", + "company_newsrooms_html": + return true + default: + return false + } +} + +// IsWave3PropRestIRJSONMode reports whether mode is handled by Categories F/G/H JSON formatters (#259). +func IsWave3PropRestIRJSONMode(mode string) bool { + return mode == "q4_ir_json" +} + +// IsWave3PropRestIRTextMode reports whether mode is handled by Categories F/G/H text/RSS XML formatters (#260-#261). +func IsWave3PropRestIRTextMode(mode string) bool { + return mode == "ir_portal_rss_xml" || mode == "company_newsroom_rss_xml" +} + +func wave3PRIRDefaultExtractorID(mode string) string { + switch mode { + case "appfolio_listings_html": + return "appfolio-listings" + case "pm_listing_widgets_html": + return "pm-listing-widgets" + case "multifamily_portals_html": + return "multifamily-portals" + case "idx_broker_showcase_html": + return "idx-broker-showcase" + case "popmenu_html": + return "popmenu" + case "bentobox_html": + return "bentobox" + case "square_toast_menu_html": + return "square-toast-menu" + case "schema_menu_html": + return "schema-menu" + case "q4_ir_html", "q4_ir_json": + return "q4-ir" + case "ir_portal_pack_html", "ir_portal_rss_xml": + return "ir-portal-pack" + case "company_newsrooms_html", "company_newsroom_rss_xml": + return "company-newsrooms" + default: + return "" + } +} + +func wave3PRIRMatchesModePrefilter(mode, rawHTML, baseURL string) bool { + probe256K := rawHTML + if len(probe256K) > 256*1024 { + probe256K = probe256K[:256*1024] + } + switch mode { + case "appfolio_listings_html": + return containsAnyFoldASCIIExtract(probe256K, "js-listing-item", "listing-item__", "appfolio", "detail-box__value") + case "pm_listing_widgets_html": + return containsAnyFoldASCIIExtract(probe256K, "managebuilding.com", "rentals-filter", "resident/public/rentals", "propertyware", "rentmanager", "featured-listing", "pw-listing", "rm-unit") + case "multifamily_portals_html": + return containsAnyFoldASCIIExtract(probe256K, "floorplan", "lease-term-wrap", "rentcafe", "entrata", "realpage", "activebuilding", "jonah systems", "apartmentcomplex") + case "idx_broker_showcase_html": + return containsAnyFoldASCIIExtract(baseURL, "idxbroker", "showcaseidx") || + containsAnyFoldASCIIExtract(probe256K, "showcaseidx", "idxbroker", "idx-results", "idx-details", "idx-listing", "idx-main", `id="idx-`, `id='idx-`, "sidx-", "data-mls", ".idx-") + case "popmenu_html": + return containsAnyFoldASCIIExtract(probe256K, "popmenu", "pop-menu", "pm-menu", "__apollo_state__") + case "bentobox_html": + return containsAnyFoldASCIIExtract(probe256K, "getbento.com", "bentobox", "bento-analytics", "bento-menu", "menu-section__header") + case "square_toast_menu_html": + return containsAnyFoldASCIIExtract(baseURL, ".square.site", "order.toasttab.com") || + containsAnyFoldASCIIExtract(probe256K, "__bootstrap_state__", "square-online-featureflags", "toasttab", "toast-menu") + case "schema_menu_html": + if !hasJSONLDScriptToken(rawHTML) { + return false + } + probe512K := rawHTML + if len(probe512K) > 512*1024 { + probe512K = probe512K[:512*1024] + } + return containsAnyFoldASCIIExtract(probe512K, `"menu"`, `"menusection"`, `"menuitem"`, `"hasmenu"`, `"hasmenusection"`, `"hasmenuitem"`) + case "q4_ir_html": + return containsAnyFoldASCIIExtract(probe256K, "q4cdn.com", "q4web.com", "pressrelease.svc", "event.svc", "q4-ir", "module-news", "module-event", "irw-") + case "ir_portal_pack_html": + return containsAnyFoldASCIIExtract(probe256K, "wd_newsfeed", "wd_item_", "wd_script_id", "equisolve", "irwebsites", "nir-widget", "ir-news") + case "company_newsrooms_html": + return containsAnyFoldASCIIExtract(baseURL, "cision.com", "prowly.com", "prezly.com") || + containsAnyFoldASCIIExtract(probe256K, "prowly", "pr-story", "prezly", "cision", "prnewswire") + default: + return true + } +} + +// Wave3PropRestIRRunHTML executes a Category F/G/H HTML extractor and returns DeclarativePostFetchResult. +func Wave3PropRestIRRunHTML(mode, rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + if !IsWave3PropRestIRHTMLMode(mode) || len(rawHTML) == 0 || strings.IndexByte(rawHTML, '<') < 0 || strings.IndexByte(rawHTML, '>') < 0 { + return nil + } + if len(rawHTML) > wave3PRIRMaxHTMLBytes { + rawHTML = truncateUTF8SafeFullDocGo(rawHTML, wave3PRIRMaxHTMLBytes) + } + trimmed := strings.TrimLeft(rawHTML, " \t\r\n") + if trimmed == "" || trimmed[0] == '{' || trimmed[0] == '[' { + return nil + } + if extractorID == "" { + extractorID = wave3PRIRDefaultExtractorID(mode) + } + if !wave3PRIRMatchesModePrefilter(mode, rawHTML, baseURL) { + return nil + } + if wave3PRIRHasNegativeShell(rawHTML, baseURL) { + return nil + } + + var res *DeclarativePostFetchResult + switch mode { + case "appfolio_listings_html": + res = wave3PRIRExtractAppFolioHTML(rawHTML, baseURL, extractorID) + case "pm_listing_widgets_html": + res = wave3PRIRExtractPMWidgetsHTML(rawHTML, baseURL, extractorID) + case "multifamily_portals_html": + res = wave3PRIRExtractMultifamilyHTML(rawHTML, baseURL, extractorID) + case "idx_broker_showcase_html": + res = wave3PRIRExtractIDXShowcaseHTML(rawHTML, baseURL, extractorID) + case "popmenu_html": + res = wave3PRIRExtractPopmenuHTML(rawHTML, baseURL, extractorID) + case "bentobox_html": + res = wave3PRIRExtractBentoBoxHTML(rawHTML, baseURL, extractorID) + case "square_toast_menu_html": + res = wave3PRIRExtractSquareToastMenuHTML(rawHTML, baseURL, extractorID) + case "schema_menu_html": + res = wave3PRIRExtractSchemaMenuHTML(rawHTML, baseURL, extractorID) + case "q4_ir_html": + res = wave3PRIRExtractQ4IRHTML(rawHTML, baseURL, extractorID) + case "ir_portal_pack_html": + res = wave3PRIRExtractIRPortalPackHTML(rawHTML, baseURL, extractorID) + case "company_newsrooms_html": + res = wave3PRIRExtractCompanyNewsroomsHTML(rawHTML, baseURL, extractorID) + } + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return nil + } + return res +} + +// RunWave3PropRestIRHTMLMode executes a Category F/G/H HTML extractor and returns JSON-marshaled DeclarativePostFetchResult. +func RunWave3PropRestIRHTMLMode(mode, rawHTML, baseURL string) (string, bool) { + res := Wave3PropRestIRRunHTML(mode, rawHTML, baseURL, wave3PRIRDefaultExtractorID(mode)) + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return "", false + } + res = sanitizePostFetchResultDeclHTML(res) + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return "", false + } + encoded, err := json.Marshal(res) + if err != nil { + return "", false + } + return string(encoded), true +} + +// FormatWave3PropRestIRJSONDoc formats a Category H JSON twin payload (`q4_ir_json`) into DeclarativeFormattedDoc. +func FormatWave3PropRestIRJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool) { + if !IsWave3PropRestIRJSONMode(mode) || len(raw) == 0 || len(raw) > wave3PRIRMaxJSONBytes { + return nil, false + } + payload := bytes.TrimSpace(bytes.TrimPrefix(raw, []byte("\xEF\xBB\xBF"))) + if len(payload) == 0 || (payload[0] != '{' && payload[0] != '[') { + return nil, false + } + parsed, ok := decodeJSONWithNumbers(payload) + if !ok || parsed == nil { + return nil, false + } + doc, handled := wave3PRIRFormatQ4IRJSON(parsed, origURL) + if !handled || doc == nil || strings.TrimSpace(doc.Markdown) == "" { + return nil, false + } + return wave3PRIRFinalizeDoc(doc), true +} + +// FormatWave3PropRestIRJSONMode formats a Category H JSON payload and returns JSON-marshaled DeclarativeFormattedDoc. +func FormatWave3PropRestIRJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool) { + doc, ok := FormatWave3PropRestIRJSONDoc(mode, raw, params, origURL) + if !ok || doc == nil { + return "", false + } + encoded, err := json.Marshal(doc) + if err != nil { + return "", false + } + return string(encoded), true +} + +// FormatWave3PropRestIRTextDoc formats Category H RSS/Atom XML feeds (`ir_portal_rss_xml`, `company_newsroom_rss_xml`) into DeclarativeFormattedDoc. +func FormatWave3PropRestIRTextDoc(mode, rawBody string, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool) { + if !IsWave3PropRestIRTextMode(mode) || len(rawBody) == 0 || len(rawBody) > wave3PRIRMaxTextBytes { + return nil, false + } + source := wave3PRIRDefaultExtractorID(mode) + doc, handled := wave3PRIRFormatRSSXML(rawBody, origURL, source) + if !handled || doc == nil || strings.TrimSpace(doc.Markdown) == "" { + return nil, false + } + return wave3PRIRFinalizeDoc(doc), true +} + +// FormatWave3PropRestIRTextMode formats Category H RSS/Atom XML feeds and returns JSON-marshaled DeclarativeFormattedDoc. +func FormatWave3PropRestIRTextMode(mode, rawBody string, params map[string]string, origURL string) (string, bool) { + doc, ok := FormatWave3PropRestIRTextDoc(mode, rawBody, params, origURL) + if !ok || doc == nil { + return "", false + } + encoded, err := json.Marshal(doc) + if err != nil { + return "", false + } + return string(encoded), true +} + +// ── Shared Hygiene & Parsing Helpers ────────────────────────────────────────────────────────────── + +func wave3PRIRIntPtr(v int) *int { return &v } +func wave3PRIRBoolPtr(v bool) *bool { return &v } + +func wave3PRIRFinalizeDoc(doc *DeclarativeFormattedDoc) *DeclarativeFormattedDoc { + if doc == nil { + return nil + } + if len(doc.Records) > wave3PRIRMaxRecords { + if doc.Total == nil { + doc.Total = wave3PRIRIntPtr(len(doc.Records)) + } + doc.Records = doc.Records[:wave3PRIRMaxRecords] + doc.Returned = wave3PRIRIntPtr(len(doc.Records)) + doc.Truncated = wave3PRIRBoolPtr(true) + if doc.NextCursor == "" { + doc.NextCursor = strconv.Itoa(len(doc.Records)) + } + } + if sanitized, ok := sanitizeDeclarativeFormattedDocGo(doc); ok && sanitized != nil { + return sanitized + } + return nil +} + +func wave3PRIRFinalizeResult(res *DeclarativePostFetchResult) *DeclarativePostFetchResult { + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return nil + } + if len(res.Records) > wave3PRIRMaxRecords { + if res.Total == nil { + res.Total = wave3PRIRIntPtr(len(res.Records)) + } + res.Records = res.Records[:wave3PRIRMaxRecords] + res.Returned = wave3PRIRIntPtr(len(res.Records)) + res.Truncated = wave3PRIRBoolPtr(true) + if res.NextCursor == "" { + res.NextCursor = strconv.Itoa(len(res.Records)) + } + } + return res +} + +func wave3PRIRIsNegativeURL(baseURL string) bool { + uLower := strings.ToLower(strings.TrimSpace(baseURL)) + if uLower == "" { + return false + } + if strings.Contains(uLower, "/404") || + strings.Contains(uLower, "/not-found") || + strings.Contains(uLower, "/page-not-found") || + strings.Contains(uLower, "/maintenance") || + strings.Contains(uLower, "error=true") || + strings.Contains(uLower, "error=1") || + strings.Contains(uLower, "404.") { + return true + } + pathOnly := uLower + if idx := strings.Index(pathOnly, "://"); idx >= 0 { + rest := pathOnly[idx+3:] + if slash := strings.IndexByte(rest, '/'); slash >= 0 { + pathOnly = rest[slash:] + } else { + pathOnly = "/" + } + } + if cut := strings.IndexAny(pathOnly, "?#"); cut >= 0 { + pathOnly = pathOnly[:cut] + } + return strings.HasSuffix(pathOnly, "/error") || + strings.Contains(pathOnly, "/error/") || + strings.HasSuffix(pathOnly, "/error.html") || + strings.HasSuffix(pathOnly, "/error.htm") || + strings.HasSuffix(pathOnly, "/error.aspx") +} + +func wave3PRIRContainsAny(lower string, needles ...string) bool { + for _, n := range needles { + if strings.Contains(lower, n) { + return true + } + } + return false +} + +func wave3PRIRHasNegativeShell(rawHTML, baseURL string) bool { + if wave3PRIRIsNegativeURL(baseURL) { + return true + } + probe := rawHTML + if len(probe) > 65536 { + probe = probe[:65536] + } + lower := asciiLowerExtractString(probe) + hasRealBodyMarkers := hasJSONLDScriptToken(probe) || + strings.Contains(lower, " 65536 { + tail := rawHTML[65536:] + hasRealBodyMarkers = indexFoldASCIIExtract(tail, "= 0 || + indexFoldASCIIExtract(tail, "= 0 || + indexFoldASCIIExtract(tail, "= 0 || + indexFoldASCIIExtract(tail, "application/ld+json") >= 0 + } + if strings.Contains(lower, "challenge-platform") && len(rawHTML) < 16384 && !hasRealBodyMarkers { + return true + } + if wave3PRIRContainsAny(lower, + "cf-browser-verification", + "_cf_chl_opt", + "cf_chl_opt", + "cf-turnstile", + "challenges.cloudflare.com/turnstile", + "attention required! | cloudflare", + "errors.edgesuite.net", + "you don't have permission to access", + "access denied", + "403 forbidden", + "just a moment", + "page not found | appfolio", + "window.kpsdk", + "kp_uidz", + "_incapsula_resource", + "incapsula incident", + ) { + return true + } + if !hasJSONLDScriptToken(probe) && + wave3PRIRContainsAny(lower, "scheduled maintenance", "down for maintenance", "under maintenance", "temporarily unavailable", "503 service unavailable") && + len(rawHTML) < 48*1024 { + return true + } + title := extractTitleLinearQuick(probe) + if title != "" && (wave3PRIRRxNotFoundTitle.MatchString(title) || wave3PRIRRxMaintTitle.MatchString(title) || wave3PRIRRxErrorTitle.MatchString(title)) { + return true + } + if title != "" && wave3PRIRRxLoginTitle.MatchString(title) && !hasJSONLDScriptToken(probe) && len(rawHTML) < 48*1024 { + return true + } + if len(rawHTML) < 32*1024 && !hasJSONLDScriptToken(probe) && + wave3PRIRContainsAny(lower, `name="samlrequest"`, `name="samlresponse"`, `<input type="password"`, `type='password'`) { + return true + } + if len(rawHTML) < 16384 && + wave3PRIRContainsAny(lower, + `<div id="root"></div>`, + `<div id="app"></div>`, + `<div id="__next"></div>`, + `<div id="__nuxt"></div>`, + `<app-root></app-root>`, + `<ui-view></ui-view>`, + ) && + !hasJSONLDScriptToken(probe) && + !strings.Contains(lower, "__bootstrap_state__") && + !strings.Contains(lower, "__next_data__") && + !strings.Contains(lower, "__nuxt_data__") && + !strings.Contains(lower, "__apollo_state__") && + !strings.Contains(lower, "<h1") && + !strings.Contains(lower, "<article") && + !strings.Contains(lower, "<table") { + return true + } + return false +} + +func wave3PRIRCleanText(s string) string { + if s == "" { + return "" + } + if strings.IndexByte(s, '<') >= 0 { + s = stripTagsInlineLinear(s) + } + if strings.IndexByte(s, '&') >= 0 { + s = stdhtml.UnescapeString(s) + } + return strings.TrimSpace(wave3PRIRRxSpace.ReplaceAllString(s, " ")) +} + +func wave3PRIRFirstNonEmpty(vals ...string) string { + for _, v := range vals { + if t := strings.TrimSpace(v); t != "" { + return t + } + } + return "" +} + +func wave3PRIRPlain(v any, maxLen int) string { + return SanitizeSchemaPlainField(jsonScalarToString(v), maxLen) +} + +func wave3PRIRProbeLower(rawHTML string, maxBytes int) string { + if len(rawHTML) > maxBytes { + rawHTML = rawHTML[:maxBytes] + } + return asciiLowerExtractString(rawHTML) +} + +func wave3PRIRAddLink(links *[]string, seen map[string]bool, raw, baseURL string) string { + safe := SanitizeSchemaHTTPSURL(raw, baseURL) + if safe == "" { + return "" + } + if !seen[safe] { + seen[safe] = true + *links = append(*links, safe) + } + return safe +} + +func wave3PRIRPageMeta(doc *HTMLDoc) (title, siteName, desc string) { + if doc == nil { + return "", "", "" + } + title = SanitizeSchemaPlainField(wave3PRIRFirstNonEmpty( + doc.AttrOf(`meta[property="og:title"]`, "content"), + doc.Text("h1"), + doc.Text("title"), + ), 260) + siteName = SanitizeSchemaPlainField(doc.AttrOf(`meta[property="og:site_name"]`, "content"), 180) + desc = SanitizeSchemaPlainField(wave3PRIRFirstNonEmpty( + doc.AttrOf(`meta[property="og:description"]`, "content"), + doc.AttrOf(`meta[name="description"]`, "content"), + ), 500) + return title, siteName, desc +} + +func wave3PRIRSchemaTypes(obj map[string]any) []string { + return normalizeSchemaTypesSchemaGo(obj["@type"]) +} + +func wave3PRIRHasSchemaType(obj map[string]any, targets ...string) bool { + allowed := make(map[string]bool, len(targets)) + for _, t := range targets { + allowed[strings.ToLower(t)] = true + } + return findMatchingSchemaTypeSchemaGo(wave3PRIRSchemaTypes(obj), allowed) != "" +} + +func wave3PRIRNodeAttr(n *HTMLNode, name string) string { + if n == nil { + return "" + } + return strings.TrimSpace(n.AttrOrEmpty(name)) +} + +func wave3PRIRExtractBalancedAfterRegex(rawHTML string, rx *lazyRegexp, maxBytes int) (map[string]any, bool) { + loc := rx.FindStringIndex(rawHTML) + if loc == nil { + return nil, false + } + tail := rawHTML[loc[1]:] + brace := strings.IndexByte(tail, '{') + if brace < 0 || brace > 64 { + return nil, false + } + rawJSON, _, okBal := ExtractBalancedJSONAt(tail, brace, maxBytes) + if !okBal { + return nil, false + } + parsed, ok := decodeJSONWithNumbers([]byte(rawJSON)) + if !ok { + return nil, false + } + m, okM := parsed.(map[string]any) + return m, okM +} + +func wave3PRIRExtractNextData(rawHTML string) (map[string]any, bool) { + m := wave3PRIRRxNextData.FindStringSubmatch(rawHTML) + if len(m) < 2 { + return nil, false + } + body := strings.TrimSpace(m[1]) + if body == "" || body[0] != '{' { + return nil, false + } + parsed, ok := decodeJSONWithNumbers([]byte(body)) + if !ok { + return nil, false + } + obj, okObj := parsed.(map[string]any) + return obj, okObj +} + +func wave3PRIRParsePriceSpec(text string) string { + if m := wave3PRIRRxRent.FindStringSubmatch(text); len(m) >= 2 { + if m[2] != "" { + return "$" + m[1] + " - $" + m[2] + } + return "$" + m[1] + } + return "" +} + +func wave3PRIRParsePropertySpecs(text string) (rent, beds, baths, sqft string) { + rent = wave3PRIRParsePriceSpec(text) + if m := wave3PRIRRxBeds.FindStringSubmatch(text); len(m) >= 2 { + beds = m[1] + } + if m := wave3PRIRRxBaths.FindStringSubmatch(text); len(m) >= 2 { + baths = m[1] + } + if m := wave3PRIRRxSqft.FindStringSubmatch(text); len(m) >= 2 { + sqft = m[1] + } + return +} + +// ── #251 appfolio-listings ──────────────────────────────────────────────────────────────────────── + +func wave3PRIRExtractAppFolioHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + lower := wave3PRIRProbeLower(rawHTML, 256*1024) + hasMarker := wave3PRIRContainsAny(lower, + "js-listing-item", + "listing-item__", + "images.cdn.appfolio.com", + "appfolio.com/listings", + "detail-box__value", + ) || (strings.Contains(lower, "appfolio") && wave3PRIRContainsAny(lower, "/listings/detail/", "rental listings", "listing-item")) + if !hasMarker { + return nil + } + + doc := ParseHTMLDoc(rawHTML, 512*1024) + pageTitle, siteName, pageDesc := wave3PRIRPageMeta(doc) + if pageTitle == "" { + pageTitle = "AppFolio Rental Listings" + } + + var records []map[string]any + var links []string + seenLinks := map[string]bool{} + var itemLines []string + + cards := doc.Select(`.listing-item, .js-listing-item`, 60) + for _, card := range cards { + if len(records) >= wave3PRIRMaxRecords { + break + } + cardText := wave3PRIRCleanText(card.Text()) + if cardText == "" { + continue + } + title := SanitizeSchemaPlainField(wave3PRIRFirstNonEmpty( + card.Text(`.listing-item__title`), + card.Text(`.js-listing-address`), + card.Text(`h2, h3`), + ), 200) + detailHref := "" + if a := card.First(`a[href*="/listings/detail/"], a.js-link-to-detail, .listing-item__title a`); a != nil { + detailHref = wave3PRIRAddLink(&links, seenLinks, wave3PRIRNodeAttr(a, "href"), baseURL) + if title == "" { + title = SanitizeSchemaPlainField(a.Text(), 200) + } + } + rent, beds, baths, sqft := wave3PRIRParsePropertySpecs(cardText) + if title == "" { + title = SanitizeSchemaPlainField(cardText, 120) + } + if title == "" { + continue + } + rec := map[string]any{ + "title": title, + "source": "appfolio", + } + if rent != "" { + rec["rent"] = rent + } + if beds != "" { + rec["beds"] = beds + } + if baths != "" { + rec["baths"] = baths + } + if sqft != "" { + rec["sqft"] = sqft + } + if detailHref != "" { + rec["url"] = detailHref + } + records = append(records, rec) + + var parts []string + if detailHref != "" { + parts = append(parts, fmt.Sprintf("### [%s](%s)", escapeDeclMarkdownBrackets(title), detailHref)) + } else { + parts = append(parts, "### "+escapeDeclMarkdownBrackets(title)) + } + var meta []string + if rent != "" { + meta = append(meta, "Rent: "+rent) + } + if beds != "" { + meta = append(meta, "Beds: "+beds) + } + if baths != "" { + meta = append(meta, "Baths: "+baths) + } + if sqft != "" { + meta = append(meta, "Sq Ft: "+sqft) + } + if len(meta) > 0 { + parts = append(parts, "- "+strings.Join(meta, " | ")) + } + itemLines = append(itemLines, strings.Join(parts, "\n")) + } + + // Single-listing detail page fallback (`/listings/detail/<uuid>`) + if len(records) == 0 && wave3PRIRContainsAny(lower, "listing-detail", "detail-box__value", "/listings/detail/") { + bodyText := wave3PRIRCleanText(doc.Text(`main, .listing-detail, body`)) + rent, beds, baths, sqft := wave3PRIRParsePropertySpecs(bodyText) + addr := SanitizeSchemaPlainField(wave3PRIRFirstNonEmpty( + doc.Text(`.listing-detail__title, h1`), + pageTitle, + ), 200) + if addr != "" && (rent != "" || beds != "" || baths != "" || sqft != "") { + rec := map[string]any{"title": addr, "source": "appfolio"} + if rent != "" { + rec["rent"] = rent + } + if beds != "" { + rec["beds"] = beds + } + if baths != "" { + rec["baths"] = baths + } + if sqft != "" { + rec["sqft"] = sqft + } + if safeURL := wave3PRIRAddLink(&links, seenLinks, baseURL, baseURL); safeURL != "" { + rec["url"] = safeURL + } + records = append(records, rec) + itemLines = append(itemLines, fmt.Sprintf("- **Address**: %s\n- **Rent**: %s | **Beds**: %s | **Baths**: %s | **Sq Ft**: %s", + escapeDeclMarkdownBlock(addr), wave3PRIRFirstNonEmpty(rent, "-"), wave3PRIRFirstNonEmpty(beds, "-"), wave3PRIRFirstNonEmpty(baths, "-"), wave3PRIRFirstNonEmpty(sqft, "-"))) + } + } + + if len(records) == 0 { + return nil + } + var md []string + md = append(md, "# "+escapeDeclMarkdownBlock(pageTitle)) + if siteName != "" { + md = append(md, "- **Property Manager**: "+escapeDeclMarkdownBlock(siteName)) + } + if pageDesc != "" { + md = append(md, escapeDeclMarkdownBlock(pageDesc)) + } + md = append(md, "## Rental Listings\n\n"+strings.Join(itemLines, "\n\n")) + + return wave3PRIRFinalizeResult(&DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: pageTitle, + Description: pageDesc, + Markdown: strings.Join(md, "\n\n"), + Links: links, + Records: records, + }) +} + +// ── #252 pm-listing-widgets ─────────────────────────────────────────────────────────────────────── + +func wave3PRIRExtractPMWidgetsHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + lower := wave3PRIRProbeLower(rawHTML, 256*1024) + hasMarker := wave3PRIRContainsAny(lower, + "managebuilding.com", + "rentals-filter", + "resident/public/rentals", + "propertyware", + "rentmanager", + "featured-listing", + "pw-listing", + "rm-unit", + ) + if !hasMarker { + return nil + } + + baseLower := strings.ToLower(baseURL) + platform := "Property Management Portal" + switch { + case strings.Contains(lower, "managebuilding") || strings.Contains(baseLower, "managebuilding") || strings.Contains(lower, "rentals-filter") || strings.Contains(lower, "resident/public/rentals"): + platform = "Buildium" + case strings.Contains(lower, "propertyware") || strings.Contains(baseLower, "propertyware") || strings.Contains(lower, "pw-listing"): + platform = "Propertyware" + case strings.Contains(lower, "rentmanager") || strings.Contains(baseLower, "rentmanager") || strings.Contains(lower, "rm-unit"): + platform = "RentManager" + } + + doc := ParseHTMLDoc(rawHTML, 512*1024) + pageTitle, siteName, pageDesc := wave3PRIRPageMeta(doc) + if pageTitle == "" { + pageTitle = platform + " Rental Listings" + } + + var records []map[string]any + var links []string + seenLinks := map[string]bool{} + var blocks []string + + cards := doc.Select(`.featured-listing, .rentals-list-item, .rental-card, .pw-listing, .property-card, .rm-unit, .unit-listing, tr.rental-row, a[href*="/Resident/public/rentals/"]`, 60) + seenTitle := map[string]bool{} + for _, card := range cards { + if len(records) >= wave3PRIRMaxRecords { + break + } + cardText := wave3PRIRCleanText(card.Text()) + if cardText == "" { + continue + } + href := "" + if strings.EqualFold(card.Tag(), "a") { + href = wave3PRIRNodeAttr(card, "href") + } else if a := card.First(`a[href*="/Resident/public/rentals/"], a[href]`); a != nil { + href = wave3PRIRNodeAttr(a, "href") + } + safeURL := wave3PRIRAddLink(&links, seenLinks, href, baseURL) + + title := SanitizeSchemaPlainField(wave3PRIRFirstNonEmpty( + card.Text(`.featured-listing__title, .listing-title, h2, h3, .property-address`), + card.AttrOrEmpty("title"), + ), 200) + rent, beds, baths, sqft := wave3PRIRParsePropertySpecs(cardText) + if title == "" { + title = SanitizeSchemaPlainField(cardText, 120) + } + if title == "" || (rent == "" && beds == "" && baths == "" && safeURL == "") { + continue + } + key := title + "|" + safeURL + if seenTitle[key] { + continue + } + seenTitle[key] = true + + rec := map[string]any{ + "title": title, + "platform": platform, + } + if rent != "" { + rec["rent"] = rent + } + if beds != "" { + rec["beds"] = beds + } + if baths != "" { + rec["baths"] = baths + } + if sqft != "" { + rec["sqft"] = sqft + } + if safeURL != "" { + rec["url"] = safeURL + } + records = append(records, rec) + + header := "### " + escapeDeclMarkdownBrackets(title) + if safeURL != "" { + header = fmt.Sprintf("### [%s](%s)", escapeDeclMarkdownBrackets(title), safeURL) + } + var meta []string + if rent != "" { + meta = append(meta, "Rent: "+rent) + } + if beds != "" { + meta = append(meta, "Beds: "+beds) + } + if baths != "" { + meta = append(meta, "Baths: "+baths) + } + if sqft != "" { + meta = append(meta, "Sq Ft: "+sqft) + } + if len(meta) > 0 { + blocks = append(blocks, header+"\n- "+strings.Join(meta, " | ")) + } else { + blocks = append(blocks, header) + } + } + + if len(records) == 0 { + return nil + } + var md []string + md = append(md, "# "+escapeDeclMarkdownBlock(pageTitle)) + metaLine := "- **Platform**: " + platform + if siteName != "" { + metaLine += " | **Manager**: " + escapeDeclMarkdownBlock(siteName) + } + md = append(md, metaLine) + if pageDesc != "" { + md = append(md, escapeDeclMarkdownBlock(pageDesc)) + } + md = append(md, "## Available Rentals\n\n"+strings.Join(blocks, "\n\n")) + + return wave3PRIRFinalizeResult(&DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: pageTitle, + Description: pageDesc, + Markdown: strings.Join(md, "\n\n"), + Links: links, + Records: records, + }) +} + +// ── #253 multifamily-portals ────────────────────────────────────────────────────────────────────── + +func wave3PRIRExtractMultifamilyHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + if strings.Contains(strings.ToLower(baseURL), ".ashx") { + return nil + } + lower := wave3PRIRProbeLower(rawHTML, 256*1024) + hasMarker := wave3PRIRContainsAny(lower, + "floorplan-details", + "lease-term-wrap", + "rentcafe", + "entrata", + "realpage", + "activebuilding", + "jonah systems", + "apartmentcomplex", + ) || (strings.Contains(lower, "floorplan") && wave3PRIRContainsAny(lower, "bed", "bath", "sq ft", "sqft", "$")) + if !hasMarker { + return nil + } + + doc := ParseHTMLDoc(rawHTML, 512*1024) + pageTitle, siteName, pageDesc := wave3PRIRPageMeta(doc) + if pageTitle == "" { + pageTitle = "Multifamily Floor Plans & Availability" + } + + var records []map[string]any + var links []string + seenLinks := map[string]bool{} + var blocks []string + + // Parse JSON-LD ApartmentComplex / Apartment / FloorPlan if present + if hasJSONLDScriptToken(rawHTML) { + for _, obj := range ExtractJSONLDObjects(rawHTML, 40) { + if len(records) >= wave3PRIRMaxRecords { + break + } + if !wave3PRIRHasSchemaType(obj, "ApartmentComplex", "Apartment", "FloorPlan", "Residence") { + continue + } + name := wave3PRIRPlain(obj["name"], 200) + if name == "" { + continue + } + rec := map[string]any{"name": name, "source": "schema-multifamily"} + if beds := wave3PRIRPlain(obj["numberOfBedrooms"], 32); beds != "" { + rec["beds"] = beds + } + if baths := wave3PRIRPlain(obj["numberOfBathroomsTotal"], 32); baths != "" { + rec["baths"] = baths + } + if u := wave3PRIRAddLink(&links, seenLinks, jsonScalarToString(obj["url"]), baseURL); u != "" { + rec["url"] = u + } + records = append(records, rec) + blocks = append(blocks, "### "+escapeDeclMarkdownBrackets(name)) + } + } + + fpNodes := doc.Select(`.floorplan-details__toggle, .floorplan-card, .fp-card, .fp-row, [class*="floorplan-item"], .unit-card, .lease-term-wrap__item`, 60) + seenFP := map[string]bool{} + for _, node := range fpNodes { + if len(records) >= wave3PRIRMaxRecords { + break + } + txt := wave3PRIRCleanText(node.Text()) + if txt == "" { + continue + } + name := SanitizeSchemaPlainField(wave3PRIRFirstNonEmpty( + node.Text(`.floorplan-name, .fp-name, h2, h3, h4, .title`), + node.AttrOrEmpty("data-floorplan-name"), + ), 180) + rent, beds, baths, sqft := wave3PRIRParsePropertySpecs(txt) + if name == "" { + name = SanitizeSchemaPlainField(txt, 100) + } + if name == "" || seenFP[name] || (rent == "" && beds == "" && baths == "" && sqft == "") { + continue + } + seenFP[name] = true + var href string + if a := node.First(`a[href]`); a != nil { + href = wave3PRIRAddLink(&links, seenLinks, wave3PRIRNodeAttr(a, "href"), baseURL) + } + rec := map[string]any{"name": name, "source": "multifamily-dom"} + if rent != "" { + rec["rent"] = rent + } + if beds != "" { + rec["beds"] = beds + } + if baths != "" { + rec["baths"] = baths + } + if sqft != "" { + rec["sqft"] = sqft + } + if href != "" { + rec["url"] = href + } + records = append(records, rec) + + var meta []string + if rent != "" { + meta = append(meta, "Rent: "+rent) + } + if beds != "" { + meta = append(meta, "Beds: "+beds) + } + if baths != "" { + meta = append(meta, "Baths: "+baths) + } + if sqft != "" { + meta = append(meta, "Sq Ft: "+sqft) + } + blocks = append(blocks, "### "+escapeDeclMarkdownBrackets(name)+"\n- "+strings.Join(meta, " | ")) + } + + if len(records) == 0 { + return nil + } + var md []string + md = append(md, "# "+escapeDeclMarkdownBlock(pageTitle)) + if siteName != "" { + md = append(md, "- **Community**: "+escapeDeclMarkdownBlock(siteName)) + } + if pageDesc != "" { + md = append(md, escapeDeclMarkdownBlock(pageDesc)) + } + md = append(md, "## Floor Plans & Pricing\n\n"+strings.Join(blocks, "\n\n")) + + return wave3PRIRFinalizeResult(&DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: pageTitle, + Description: pageDesc, + Markdown: strings.Join(md, "\n\n"), + Links: links, + Records: records, + }) +} + +// ── #254 idx-broker-showcase ────────────────────────────────────────────────────────────────────── + +func wave3PRIRExtractIDXShowcaseHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + lower := wave3PRIRProbeLower(rawHTML, 256*1024) + hostLower := "" + if u, err := url.Parse(strings.TrimSpace(baseURL)); err == nil { + hostLower = strings.ToLower(u.Hostname()) + } + hasIDXHost := strings.Contains(hostLower, "idxbroker") || strings.Contains(hostLower, "showcaseidx") + hasMarker := hasIDXHost || wave3PRIRContainsAny(lower, + "showcaseidx", + "idxbroker", + "idx-results", + "idx-details", + "idx-listing", + "idx-main", + `id="idx-`, + `id='idx-`, + "sidx-", + "data-mls", + ".idx-", + ) + if !hasMarker { + return nil + } + + doc := ParseHTMLDoc(rawHTML, 512*1024) + pageTitle, siteName, pageDesc := wave3PRIRPageMeta(doc) + if pageTitle == "" { + pageTitle = "IDX Real Estate Listings" + } + + var records []map[string]any + var links []string + seenLinks := map[string]bool{} + var blocks []string + var agentBullets []string + + if hasJSONLDScriptToken(rawHTML) { + for _, obj := range ExtractJSONLDObjects(rawHTML, 40) { + if wave3PRIRHasSchemaType(obj, "RealEstateAgent", "Organization") { + name := wave3PRIRPlain(obj["name"], 180) + tel := wave3PRIRPlain(obj["telephone"], 60) + if name != "" { + agentBullets = append(agentBullets, "- **Brokerage / Agent**: "+escapeDeclMarkdownBlock(name)) + } + if tel != "" { + agentBullets = append(agentBullets, "- **Phone**: "+escapeDeclMarkdownBlock(tel)) + } + if u := wave3PRIRAddLink(&links, seenLinks, jsonScalarToString(obj["url"]), baseURL); u != "" && len(records) == 0 { + records = append(records, map[string]any{"name": wave3PRIRFirstNonEmpty(name, pageTitle), "telephone": tel, "url": u, "kind": "brokerage"}) + } + } + if wave3PRIRHasSchemaType(obj, "RealEstateListing", "SingleFamilyResidence", "Product") && len(records) < wave3PRIRMaxRecords { + name := wave3PRIRPlain(obj["name"], 200) + price := "" + if offers, ok := obj["offers"].(map[string]any); ok { + price = wave3PRIRPlain(offers["price"], 40) + } + u := wave3PRIRAddLink(&links, seenLinks, jsonScalarToString(obj["url"]), baseURL) + if name != "" { + rec := map[string]any{"title": name, "kind": "listing"} + if price != "" { + rec["price"] = price + } + if u != "" { + rec["url"] = u + } + records = append(records, rec) + line := "### " + escapeDeclMarkdownBrackets(name) + if u != "" { + line = fmt.Sprintf("### [%s](%s)", escapeDeclMarkdownBrackets(name), u) + } + if price != "" { + line += "\n- Price: $" + price + } + blocks = append(blocks, line) + } + } + } + } + + cards := doc.Select(`.IDX-resultsCell, .idx-listing, .sidx-listing, .sidx-card, .property-listing, [data-mls]`, 60) + for _, card := range cards { + if len(records) >= wave3PRIRMaxRecords { + break + } + txt := wave3PRIRCleanText(card.Text()) + if txt == "" { + continue + } + addr := SanitizeSchemaPlainField(wave3PRIRFirstNonEmpty( + card.Text(`.IDX-resultsAddress, .idx-address, .sidx-address, h2, h3`), + card.AttrOrEmpty("data-address"), + ), 200) + price, beds, baths, sqft := wave3PRIRParsePropertySpecs(txt) + mls := SanitizeSchemaPlainField(wave3PRIRFirstNonEmpty(card.AttrOrEmpty("data-mls"), card.Text(`.IDX-resultsMLS, .mls-number`)), 64) + var href string + if a := card.First(`a[href]`); a != nil { + href = wave3PRIRAddLink(&links, seenLinks, wave3PRIRNodeAttr(a, "href"), baseURL) + } + if addr == "" { + addr = SanitizeSchemaPlainField(txt, 120) + } + if addr == "" || (price == "" && beds == "" && mls == "" && href == "") { + continue + } + rec := map[string]any{"title": addr, "kind": "listing"} + if price != "" { + rec["price"] = price + } + if beds != "" { + rec["beds"] = beds + } + if baths != "" { + rec["baths"] = baths + } + if sqft != "" { + rec["sqft"] = sqft + } + if mls != "" { + rec["mls"] = mls + } + if href != "" { + rec["url"] = href + } + records = append(records, rec) + + hdr := "### " + escapeDeclMarkdownBrackets(addr) + if href != "" { + hdr = fmt.Sprintf("### [%s](%s)", escapeDeclMarkdownBrackets(addr), href) + } + var meta []string + if price != "" { + meta = append(meta, "Price: "+price) + } + if beds != "" { + meta = append(meta, "Beds: "+beds) + } + if baths != "" { + meta = append(meta, "Baths: "+baths) + } + if sqft != "" { + meta = append(meta, "Sq Ft: "+sqft) + } + if mls != "" { + meta = append(meta, "MLS: "+mls) + } + if len(meta) > 0 { + blocks = append(blocks, hdr+"\n- "+strings.Join(meta, " | ")) + } else { + blocks = append(blocks, hdr) + } + } + + if len(records) == 0 && len(agentBullets) == 0 { + return nil + } + var md []string + md = append(md, "# "+escapeDeclMarkdownBlock(pageTitle)) + if siteName != "" { + md = append(md, "- **Site**: "+escapeDeclMarkdownBlock(siteName)) + } + if len(agentBullets) > 0 { + md = append(md, strings.Join(agentBullets, "\n")) + } + if pageDesc != "" { + md = append(md, escapeDeclMarkdownBlock(pageDesc)) + } + if len(blocks) > 0 { + md = append(md, "## Property Listings\n\n"+strings.Join(blocks, "\n\n")) + } + + return wave3PRIRFinalizeResult(&DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: pageTitle, + Description: pageDesc, + Markdown: strings.Join(md, "\n\n"), + Links: links, + Records: records, + }) +} + +// ── #255 popmenu ────────────────────────────────────────────────────────────────────────────────── + +func wave3PRIRExtractPopmenuHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + lower := wave3PRIRProbeLower(rawHTML, 256*1024) + hasMarker := wave3PRIRContainsAny(lower, "popmenu", "pop-menu", "pm-menu") || + (strings.Contains(lower, "__apollo_state__") && wave3PRIRContainsAny(lower, "menuitem", "menusection")) + if !hasMarker { + return nil + } + + doc := ParseHTMLDoc(rawHTML, 512*1024) + pageTitle, siteName, pageDesc := wave3PRIRPageMeta(doc) + if pageTitle == "" { + pageTitle = "Popmenu Restaurant Menu" + } + + var records []map[string]any + var links []string + seenLinks := map[string]bool{} + var blocks []string + + // Apollo State extraction if present + if apollo, ok := wave3PRIRExtractBalancedAfterRegex(rawHTML, wave3PRIRRxApolloState, 512_000); ok { + for k, v := range apollo { + if len(records) >= wave3PRIRMaxRecords { + break + } + m, okM := v.(map[string]any) + if !okM { + continue + } + if !strings.Contains(strings.ToLower(k), "menuitem") && !strings.EqualFold(jsonScalarToString(m["__typename"]), "MenuItem") { + continue + } + name := wave3PRIRPlain(m["name"], 180) + if name == "" { + continue + } + price := wave3PRIRPlain(m["price"], 40) + desc := wave3PRIRPlain(m["description"], 300) + rec := map[string]any{"name": name, "source": "popmenu-apollo"} + if price != "" { + rec["price"] = price + } + if desc != "" { + rec["description"] = desc + } + records = append(records, rec) + line := "- **" + escapeDeclMarkdownBlock(name) + "**" + if price != "" { + line += " (" + price + ")" + } + if desc != "" { + line += " — " + escapeDeclMarkdownBlock(desc) + } + blocks = append(blocks, line) + } + } + + // Popmenu DOM items + if len(records) == 0 { + items := doc.Select(`.pm-menu-item, .menu-item, [data-menu-item], [class*="MenuItem"]`, 60) + for _, item := range items { + if len(records) >= wave3PRIRMaxRecords { + break + } + name := SanitizeSchemaPlainField(wave3PRIRFirstNonEmpty( + item.Text(`.item-title, .menu-item-title, h3, h4, .name`), + item.AttrOrEmpty("data-item-name"), + ), 180) + if name == "" { + continue + } + price := SanitizeSchemaPlainField(wave3PRIRFirstNonEmpty( + item.Text(`.item-price, .menu-item-price, .price`), + wave3PRIRParsePriceSpec(item.Text()), + ), 40) + desc := SanitizeSchemaPlainField(item.Text(`.item-description, .menu-item-description, p`), 300) + rec := map[string]any{"name": name, "source": "popmenu-dom"} + if price != "" { + rec["price"] = price + } + if desc != "" { + rec["description"] = desc + } + records = append(records, rec) + line := "- **" + escapeDeclMarkdownBlock(name) + "**" + if price != "" { + line += " (" + price + ")" + } + if desc != "" { + line += " — " + escapeDeclMarkdownBlock(desc) + } + blocks = append(blocks, line) + } + } + + // JSON-LD Menu / Restaurant fallback on Popmenu pages + if len(records) == 0 && hasJSONLDScriptToken(rawHTML) { + wave3PRIRCollectMenuJSONLD(rawHTML, baseURL, &records, &links, seenLinks, &blocks) + } + + if len(records) == 0 { + return nil + } + var md []string + md = append(md, "# "+escapeDeclMarkdownBlock(pageTitle)) + if siteName != "" { + md = append(md, "- **Restaurant**: "+escapeDeclMarkdownBlock(siteName)) + } + if pageDesc != "" { + md = append(md, escapeDeclMarkdownBlock(pageDesc)) + } + md = append(md, "## Menu\n\n"+strings.Join(blocks, "\n")) + + return wave3PRIRFinalizeResult(&DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: pageTitle, + Description: pageDesc, + Markdown: strings.Join(md, "\n\n"), + Links: links, + Records: records, + }) +} + +// ── #256 bentobox ───────────────────────────────────────────────────────────────────────────────── + +func wave3PRIRExtractBentoBoxHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + lower := wave3PRIRProbeLower(rawHTML, 256*1024) + hasMarker := wave3PRIRContainsAny(lower, + "getbento.com", + "bentobox", + "bento-analytics", + "bento-menu", + ) || (strings.Contains(lower, "menu-section__header") && strings.Contains(lower, "menu-item__heading")) + if !hasMarker { + return nil + } + + doc := ParseHTMLDoc(rawHTML, 512*1024) + pageTitle, siteName, pageDesc := wave3PRIRPageMeta(doc) + if pageTitle == "" { + pageTitle = "BentoBox Restaurant Menu" + } + + var records []map[string]any + var links []string + seenLinks := map[string]bool{} + var sectionBlocks []string + + sections := doc.Select(`.menu-section`, 30) + for _, sec := range sections { + if len(records) >= wave3PRIRMaxRecords { + break + } + secName := SanitizeSchemaPlainField(sec.Text(`.menu-section__header, h2, h3`), 160) + var itemLines []string + for _, item := range sec.Select(`.menu-item`, 40) { + if len(records) >= wave3PRIRMaxRecords { + break + } + name := SanitizeSchemaPlainField(item.Text(`.menu-item__heading--name, .menu-item__heading, h3, h4`), 180) + if name == "" { + continue + } + desc := SanitizeSchemaPlainField(item.Text(`.menu-item__details--description, .menu-description`), 300) + price := SanitizeSchemaPlainField(wave3PRIRFirstNonEmpty( + item.Text(`.menu-item__details--price`), + wave3PRIRParsePriceSpec(item.Text()), + ), 40) + rec := map[string]any{"name": name, "source": "bentobox"} + if secName != "" { + rec["section"] = secName + } + if price != "" { + rec["price"] = price + } + if desc != "" { + rec["description"] = desc + } + records = append(records, rec) + line := "- **" + escapeDeclMarkdownBlock(name) + "**" + if price != "" { + line += " (" + price + ")" + } + if desc != "" { + line += " — " + escapeDeclMarkdownBlock(desc) + } + itemLines = append(itemLines, line) + } + if len(itemLines) > 0 { + if secName != "" { + sectionBlocks = append(sectionBlocks, "### "+escapeDeclMarkdownBlock(secName)+"\n"+strings.Join(itemLines, "\n")) + } else { + sectionBlocks = append(sectionBlocks, strings.Join(itemLines, "\n")) + } + } + } + + // Orphan .menu-item fallback (without .menu-section wrapper) + if len(records) == 0 { + var itemLines []string + for _, item := range doc.Select(`.menu-item`, 60) { + if len(records) >= wave3PRIRMaxRecords { + break + } + name := SanitizeSchemaPlainField(item.Text(`.menu-item__heading--name, .menu-item__heading`), 180) + if name == "" { + continue + } + desc := SanitizeSchemaPlainField(item.Text(`.menu-item__details--description`), 300) + price := SanitizeSchemaPlainField(item.Text(`.menu-item__details--price`), 40) + rec := map[string]any{"name": name, "source": "bentobox"} + if price != "" { + rec["price"] = price + } + if desc != "" { + rec["description"] = desc + } + records = append(records, rec) + line := "- **" + escapeDeclMarkdownBlock(name) + "**" + if price != "" { + line += " (" + price + ")" + } + if desc != "" { + line += " — " + escapeDeclMarkdownBlock(desc) + } + itemLines = append(itemLines, line) + } + if len(itemLines) > 0 { + sectionBlocks = append(sectionBlocks, strings.Join(itemLines, "\n")) + } + } + + // JSON-LD FoodEstablishment / Restaurant fallback when on getbento.com marketing or restaurant homepage + var venueBullets []string + if len(records) == 0 && hasJSONLDScriptToken(rawHTML) { + for _, obj := range ExtractJSONLDObjects(rawHTML, 32) { + if wave3PRIRHasSchemaType(obj, "FoodEstablishment", "Restaurant", "Organization") { + vName := wave3PRIRPlain(obj["name"], 180) + vType := wave3PRIRFirstNonEmpty(wave3PRIRSchemaTypes(obj)...) + if vName != "" { + venueBullets = append(venueBullets, "- **Venue**: "+escapeDeclMarkdownBlock(vName)) + if u := wave3PRIRAddLink(&links, seenLinks, jsonScalarToString(obj["url"]), baseURL); u != "" { + records = append(records, map[string]any{"name": vName, "type": vType, "url": u, "source": "bentobox"}) + } else { + records = append(records, map[string]any{"name": vName, "type": vType, "source": "bentobox"}) + } + } + } + } + } + + // BentoBox platform homepage / content fallback (e.g. getbento.com) + if len(records) == 0 && strings.Contains(lower, "getbento.com") { + mainText := wave3PRIRCleanText(doc.Text(`main, h1, h2`)) + if len(mainText) >= 40 { + records = append(records, map[string]any{"name": pageTitle, "source": "bentobox"}) + sectionBlocks = append(sectionBlocks, SanitizeSchemaPlainField(mainText, 800)) + } + } + + if len(records) == 0 { + return nil + } + var md []string + md = append(md, "# "+escapeDeclMarkdownBlock(pageTitle)) + if siteName != "" { + md = append(md, "- **Restaurant / Site**: "+escapeDeclMarkdownBlock(siteName)) + } + if len(venueBullets) > 0 { + md = append(md, strings.Join(venueBullets, "\n")) + } + if pageDesc != "" { + md = append(md, escapeDeclMarkdownBlock(pageDesc)) + } + if len(sectionBlocks) > 0 { + md = append(md, "## Menu & Details\n\n"+strings.Join(sectionBlocks, "\n\n")) + } + + return wave3PRIRFinalizeResult(&DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: pageTitle, + Description: pageDesc, + Markdown: strings.Join(md, "\n\n"), + Links: links, + Records: records, + }) +} + +// ── #257 square-toast-menu ──────────────────────────────────────────────────────────────────────── + +func wave3PRIRExtractSquareToastMenuHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + lower := wave3PRIRProbeLower(rawHTML, 256*1024) + baseLower := strings.ToLower(baseURL) + + isSquareRestaurant := (strings.Contains(rawHTML, "__BOOTSTRAP_STATE__") || strings.Contains(lower, "square-online-featureflags") || strings.Contains(baseLower, ".square.site")) && + (strings.Contains(rawHTML, `"selectedVertical":"restaurant"`) || + strings.Contains(rawHTML, `"selectedVertical": "restaurant"`) || + strings.Contains(rawHTML, `"quick-serve-restaurant"`) || + strings.Contains(rawHTML, "/shop/online-menu/") || + strings.Contains(baseLower, "/shop/online-menu/") || + strings.Contains(rawHTML, `"Online Menu"`)) + + isToastMenu := (strings.Contains(baseLower, "order.toasttab.com") || strings.Contains(lower, "toasttab") || strings.Contains(lower, "toast-menu")) && + wave3PRIRContainsAny(lower, "menuitem", "menu-item", "menugroup", "menu-group", "ld+json", "__next_data__", `data-testid="menu`) + + if !isSquareRestaurant && !isToastMenu { + return nil + } + + doc := ParseHTMLDoc(rawHTML, 512*1024) + pageTitle, siteName, pageDesc := wave3PRIRPageMeta(doc) + + var records []map[string]any + var links []string + seenLinks := map[string]bool{} + var bullets []string + var sections []string + + if isSquareRestaurant { + if boot, ok := wave3PRIRExtractBalancedAfterRegex(rawHTML, wave3PRIRRxBootstrap, 512_000); ok { + if merchantID := wave3PRIRPlain(boot["squareMerchantId"], 120); merchantID != "" { + bullets = append(bullets, "- **Square Merchant ID**: `"+merchantID+"`") + } + if vert := wave3PRIRPlain(wave3PRIRFirstNonEmpty(jsonScalarToString(boot["verticalV4"]), jsonScalarToString(boot["selectedVertical"])), 80); vert != "" { + bullets = append(bullets, "- **Vertical**: `"+vert+"`") + } + if storeInfo, okSI := boot["storeInfo"].(map[string]any); okSI { + if sn := wave3PRIRPlain(storeInfo["name"], 180); sn != "" && siteName == "" { + siteName = sn + } + if cur := wave3PRIRPlain(storeInfo["currency"], 16); cur != "" { + bullets = append(bullets, "- **Currency**: `"+cur+"`") + } + if sm := wave3PRIRPlain(storeInfo["store_mode"], 64); sm != "" { + bullets = append(bullets, "- **Order Mode**: "+escapeDeclMarkdownBlock(sm)) + } + } + if cl, okCL := boot["commerceLinks"].(map[string]any); okCL { + if cats, okCats := cl["categories"].(map[string]any); okCats { + var catLines []string + for _, rawCat := range cats { + if len(records) >= wave3PRIRMaxRecords { + break + } + cm, okCM := rawCat.(map[string]any) + if !okCM { + continue + } + cn := wave3PRIRPlain(cm["name"], 160) + cu := wave3PRIRAddLink(&links, seenLinks, jsonScalarToString(cm["site_link"]), baseURL) + if cn == "" { + continue + } + rec := map[string]any{"name": cn, "platform": "square-online-restaurant", "kind": "menu-category"} + if cu != "" { + rec["url"] = cu + catLines = append(catLines, fmt.Sprintf("- [%s](%s)", escapeDeclMarkdownBrackets(cn), cu)) + } else { + catLines = append(catLines, "- "+escapeDeclMarkdownBlock(cn)) + } + records = append(records, rec) + } + if len(catLines) > 0 { + sections = append(sections, "## Menu Categories\n\n"+strings.Join(catLines, "\n")) + } + } + } + } + } + + // Toast / Square DOM menu items & JSON-LD Menu/Product fallback + if hasJSONLDScriptToken(rawHTML) { + var ldBlocks []string + wave3PRIRCollectMenuJSONLD(rawHTML, baseURL, &records, &links, seenLinks, &ldBlocks) + if len(ldBlocks) > 0 { + sections = append(sections, "## Menu Items\n\n"+strings.Join(ldBlocks, "\n")) + } + } + + if isToastMenu { + var toastLines []string + for _, item := range doc.Select(`[data-testid*="menu-item"], .menu-item, .item-card, [class*="menuItem"]`, 60) { + if len(records) >= wave3PRIRMaxRecords { + break + } + name := SanitizeSchemaPlainField(item.Text(`h3, h4, .item-name, [data-testid*="item-name"]`), 180) + if name == "" { + continue + } + price := SanitizeSchemaPlainField(wave3PRIRFirstNonEmpty( + item.Text(`.price, [data-testid*="price"]`), + wave3PRIRParsePriceSpec(item.Text()), + ), 40) + desc := SanitizeSchemaPlainField(item.Text(`.description, p`), 300) + rec := map[string]any{"name": name, "platform": "toast", "kind": "menu-item"} + if price != "" { + rec["price"] = price + } + if desc != "" { + rec["description"] = desc + } + records = append(records, rec) + line := "- **" + escapeDeclMarkdownBlock(name) + "**" + if price != "" { + line += " (" + price + ")" + } + if desc != "" { + line += " — " + escapeDeclMarkdownBlock(desc) + } + toastLines = append(toastLines, line) + } + if len(toastLines) > 0 { + sections = append(sections, "## Toast Online Menu\n\n"+strings.Join(toastLines, "\n")) + } + } + + if len(records) == 0 { + return nil + } + if pageTitle == "" { + pageTitle = wave3PRIRFirstNonEmpty(siteName, "Restaurant Online Menu") + } + var md []string + md = append(md, "# "+escapeDeclMarkdownBlock(pageTitle)) + if siteName != "" { + md = append(md, "- **Restaurant**: "+escapeDeclMarkdownBlock(siteName)) + } + if len(bullets) > 0 { + md = append(md, strings.Join(bullets, "\n")) + } + if pageDesc != "" { + md = append(md, escapeDeclMarkdownBlock(pageDesc)) + } + md = append(md, sections...) + + return wave3PRIRFinalizeResult(&DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: pageTitle, + Description: pageDesc, + Markdown: strings.Join(md, "\n\n"), + Links: links, + Records: records, + }) +} + +// ── #258 schema-menu ────────────────────────────────────────────────────────────────────────────── + +func wave3PRIRCollectMenuJSONLD(rawHTML, baseURL string, records *[]map[string]any, links *[]string, seenLinks map[string]bool, lines *[]string) bool { + foundMenu := false + objs := ExtractJSONLDObjects(rawHTML, 80) + + var visitMenuSection func(sec map[string]any, menuName string) + var visitMenu func(menu map[string]any) + + addMenuItem := func(item map[string]any, sectionName string) { + if len(*records) >= wave3PRIRMaxRecords { + return + } + name := wave3PRIRPlain(item["name"], 180) + if name == "" { + return + } + desc := wave3PRIRPlain(item["description"], 300) + price := "" + currency := "" + if offers, ok := item["offers"].(map[string]any); ok { + price = wave3PRIRPlain(offers["price"], 40) + currency = wave3PRIRPlain(offers["priceCurrency"], 16) + } + diet := wave3PRIRPlain(item["suitableForDiet"], 80) + u := wave3PRIRAddLink(links, seenLinks, jsonScalarToString(item["url"]), baseURL) + + rec := map[string]any{"name": name, "kind": "MenuItem"} + if sectionName != "" { + rec["section"] = sectionName + } + if price != "" { + rec["price"] = price + } + if currency != "" { + rec["priceCurrency"] = currency + } + if desc != "" { + rec["description"] = desc + } + if diet != "" { + rec["diet"] = diet + } + if u != "" { + rec["url"] = u + } + *records = append(*records, rec) + + line := "- **" + escapeDeclMarkdownBlock(name) + "**" + if price != "" { + if currency != "" { + line += " (" + currency + " " + price + ")" + } else { + line += " ($" + price + ")" + } + } + if desc != "" { + line += " — " + escapeDeclMarkdownBlock(desc) + } + *lines = append(*lines, line) + } + + visitMenuSection = func(sec map[string]any, menuName string) { + foundMenu = true + secName := wave3PRIRPlain(sec["name"], 160) + secURL := wave3PRIRAddLink(links, seenLinks, jsonScalarToString(sec["url"]), baseURL) + itemCount := 0 + if rawItems, ok := sec["hasMenuItem"]; ok { + for _, it := range wave3PRIRAsSlice(rawItems) { + if im, okIM := it.(map[string]any); okIM { + addMenuItem(im, secName) + itemCount++ + } + } + } + if itemCount == 0 && secName != "" && len(*records) < wave3PRIRMaxRecords { + rec := map[string]any{"name": secName, "kind": "MenuSection"} + if menuName != "" { + rec["menu"] = menuName + } + if secURL != "" { + rec["url"] = secURL + } + *records = append(*records, rec) + if secURL != "" { + *lines = append(*lines, fmt.Sprintf("- [%s](%s)", escapeDeclMarkdownBrackets(secName), secURL)) + } else { + *lines = append(*lines, "- "+escapeDeclMarkdownBlock(secName)) + } + } + if rawSubSecs, ok := sec["hasMenuSection"]; ok { + for _, sub := range wave3PRIRAsSlice(rawSubSecs) { + if sm, okSM := sub.(map[string]any); okSM { + visitMenuSection(sm, menuName) + } + } + } + } + + visitMenu = func(menu map[string]any) { + foundMenu = true + menuName := wave3PRIRPlain(menu["name"], 160) + if rawSecs, ok := menu["hasMenuSection"]; ok { + for _, s := range wave3PRIRAsSlice(rawSecs) { + if sm, okSM := s.(map[string]any); okSM { + visitMenuSection(sm, menuName) + } + } + } + if rawItems, ok := menu["hasMenuItem"]; ok { + for _, it := range wave3PRIRAsSlice(rawItems) { + if im, okIM := it.(map[string]any); okIM { + addMenuItem(im, menuName) + } + } + } + if len(*records) == 0 && menuName != "" { + rec := map[string]any{"name": menuName, "kind": "Menu"} + if u := wave3PRIRAddLink(links, seenLinks, jsonScalarToString(menu["url"]), baseURL); u != "" { + rec["url"] = u + } + *records = append(*records, rec) + *lines = append(*lines, "- "+escapeDeclMarkdownBlock(menuName)) + } + } + + for _, obj := range objs { + if wave3PRIRHasSchemaType(obj, "Menu") { + visitMenu(obj) + } else if wave3PRIRHasSchemaType(obj, "MenuSection") { + visitMenuSection(obj, "") + } else if wave3PRIRHasSchemaType(obj, "MenuItem") { + foundMenu = true + addMenuItem(obj, "") + } else if hm, ok := obj["hasMenu"]; ok && hm != nil { + for _, entry := range wave3PRIRAsSlice(hm) { + if mm, okMM := entry.(map[string]any); okMM { + visitMenu(mm) + } + } + } + } + return foundMenu && len(*records) > 0 +} + +func wave3PRIRAsSlice(v any) []any { + if v == nil { + return nil + } + if s, ok := v.([]any); ok { + return s + } + return []any{v} +} + +func wave3PRIRExtractSchemaMenuHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + if !hasJSONLDScriptToken(rawHTML) { + return nil + } + lower := wave3PRIRProbeLower(rawHTML, 512*1024) + if !wave3PRIRContainsAny(lower, `"menu"`, `"menusection"`, `"menuitem"`, `"hasmenu"`, `"hasmenusection"`, `"hasmenuitem"`) { + return nil + } + + var records []map[string]any + var links []string + seenLinks := map[string]bool{} + var lines []string + if !wave3PRIRCollectMenuJSONLD(rawHTML, baseURL, &records, &links, seenLinks, &lines) { + return nil + } + + doc := ParseHTMLDoc(rawHTML, 256*1024) + pageTitle, siteName, pageDesc := wave3PRIRPageMeta(doc) + if pageTitle == "" { + pageTitle = "Restaurant Menu" + } + + var md []string + md = append(md, "# "+escapeDeclMarkdownBlock(pageTitle)) + if siteName != "" { + md = append(md, "- **Restaurant**: "+escapeDeclMarkdownBlock(siteName)) + } + if pageDesc != "" { + md = append(md, escapeDeclMarkdownBlock(pageDesc)) + } + md = append(md, "## Menu\n\n"+strings.Join(lines, "\n")) + + return wave3PRIRFinalizeResult(&DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: pageTitle, + Description: pageDesc, + Markdown: strings.Join(md, "\n\n"), + Links: links, + Records: records, + }) +} + +// ── #259 q4-ir ──────────────────────────────────────────────────────────────────────────────────── + +func wave3PRIRFormatQ4IRJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + root, ok := parsed.(map[string]any) + if !ok || root == nil { + return nil, false + } + + var items []any + modeKind := "" + if arr, okA := root["GetPressReleaseListResult"].([]any); okA { + items = arr + modeKind = "press-releases" + } else if arr, okA := root["GetNewsReleaseListResult"].([]any); okA { + items = arr + modeKind = "press-releases" + } else if arr, okA := root["GetEventListResult"].([]any); okA { + items = arr + modeKind = "events" + } else if det, okD := root["GetPressReleaseDetailResult"].(map[string]any); okD { + items = []any{det} + modeKind = "press-release-detail" + } else if det, okD := root["GetEventDetailResult"].(map[string]any); okD { + items = []any{det} + modeKind = "event-detail" + } + + if len(items) == 0 { + return nil, false + } + + var records []map[string]any + var links []string + seenLinks := map[string]bool{} + var blocks []string + + for _, rawItem := range items { + if len(records) >= wave3PRIRMaxRecords { + break + } + m, okM := rawItem.(map[string]any) + if !okM { + continue + } + title := wave3PRIRPlain(wave3PRIRFirstNonEmpty(jsonScalarToString(m["Headline"]), jsonScalarToString(m["Title"])), 240) + if title == "" { + continue + } + dateStr := wave3PRIRPlain(wave3PRIRFirstNonEmpty( + jsonScalarToString(m["PressReleaseDate"]), + jsonScalarToString(m["StartDate"]), + jsonScalarToString(m["Date"]), + ), 64) + detailURL := wave3PRIRAddLink(&links, seenLinks, jsonScalarToString(m["LinkToDetailPage"]), origURL) + webcastURL := wave3PRIRAddLink(&links, seenLinks, jsonScalarToString(m["WebcastLink"]), origURL) + summary := wave3PRIRPlain(wave3PRIRFirstNonEmpty( + wave3PRIRCleanText(jsonScalarToString(m["ShortBody"])), + wave3PRIRCleanText(jsonScalarToString(m["Body"])), + ), 360) + + rec := map[string]any{ + "title": title, + "kind": modeKind, + "source": "q4-ir", + } + if dateStr != "" { + rec["date"] = dateStr + } + if detailURL != "" { + rec["url"] = detailURL + } + if webcastURL != "" { + rec["webcastUrl"] = webcastURL + } + if summary != "" { + rec["summary"] = summary + } + records = append(records, rec) + + hdr := "### " + escapeDeclMarkdownBrackets(title) + if detailURL != "" { + hdr = fmt.Sprintf("### [%s](%s)", escapeDeclMarkdownBrackets(title), detailURL) + } + var meta []string + if dateStr != "" { + meta = append(meta, "Date: "+dateStr) + } + if webcastURL != "" { + meta = append(meta, "[Webcast]("+webcastURL+")") + } + var part []string + part = append(part, hdr) + if len(meta) > 0 { + part = append(part, "- "+strings.Join(meta, " | ")) + } + if summary != "" { + part = append(part, escapeDeclMarkdownBlock(summary)) + } + blocks = append(blocks, strings.Join(part, "\n")) + } + + if len(records) == 0 { + return nil, false + } + + docTitle := "Investor Relations Press Releases" + if modeKind == "events" || modeKind == "event-detail" { + docTitle = "Investor Relations Events" + } + if u, err := url.Parse(origURL); err == nil && u.Hostname() != "" { + docTitle = u.Hostname() + " — " + docTitle + } + md := "# " + escapeDeclMarkdownBlock(docTitle) + "\n\n" + strings.Join(blocks, "\n\n") + return &DeclarativeFormattedDoc{ + Title: docTitle, + Markdown: md, + Links: links, + Records: records, + }, true +} + +func wave3PRIRExtractQ4IRHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + lower := wave3PRIRProbeLower(rawHTML, 256*1024) + hasMarker := wave3PRIRContainsAny(lower, + "q4cdn.com", + "q4web.com", + "pressrelease.svc", + "event.svc", + "q4-ir", + "module-news", + "module-event", + "irw-", + ) + if !hasMarker { + return nil + } + + doc := ParseHTMLDoc(rawHTML, 512*1024) + pageTitle, siteName, pageDesc := wave3PRIRPageMeta(doc) + if pageTitle == "" { + pageTitle = "Investor Relations" + } + + var records []map[string]any + var links []string + seenLinks := map[string]bool{} + var blocks []string + + if hasJSONLDScriptToken(rawHTML) { + for _, obj := range ExtractJSONLDObjects(rawHTML, 40) { + if len(records) >= wave3PRIRMaxRecords { + break + } + if !wave3PRIRHasSchemaType(obj, "NewsArticle", "Article", "Event", "Report") { + continue + } + title := wave3PRIRPlain(wave3PRIRFirstNonEmpty(jsonScalarToString(obj["headline"]), jsonScalarToString(obj["name"])), 240) + if title == "" { + continue + } + dateStr := wave3PRIRPlain(wave3PRIRFirstNonEmpty(jsonScalarToString(obj["datePublished"]), jsonScalarToString(obj["startDate"])), 64) + u := wave3PRIRAddLink(&links, seenLinks, jsonScalarToString(obj["url"]), baseURL) + rec := map[string]any{"title": title, "source": "q4-ir"} + if dateStr != "" { + rec["date"] = dateStr + } + if u != "" { + rec["url"] = u + } + records = append(records, rec) + hdr := "### " + escapeDeclMarkdownBrackets(title) + if u != "" { + hdr = fmt.Sprintf("### [%s](%s)", escapeDeclMarkdownBrackets(title), u) + } + if dateStr != "" { + hdr += "\n- Date: " + dateStr + } + blocks = append(blocks, hdr) + } + } + + if len(records) == 0 { + for _, item := range doc.Select(`.module_item, .module-news_item, .module-event_item, .irw-news-item, article`, 60) { + if len(records) >= wave3PRIRMaxRecords { + break + } + title := SanitizeSchemaPlainField(item.Text(`.module_headline, .module-news_title, .module-event_title, h2, h3, a`), 240) + if title == "" { + continue + } + dateStr := SanitizeSchemaPlainField(wave3PRIRFirstNonEmpty( + item.Text(`.module_date-text, .module-news_date, time`), + wave3PRIRRxQ4Date.FindString(item.Text()), + ), 64) + href := "" + if a := item.First(`a[href]`); a != nil { + href = wave3PRIRAddLink(&links, seenLinks, wave3PRIRNodeAttr(a, "href"), baseURL) + } + rec := map[string]any{"title": title, "source": "q4-ir"} + if dateStr != "" { + rec["date"] = dateStr + } + if href != "" { + rec["url"] = href + } + records = append(records, rec) + hdr := "### " + escapeDeclMarkdownBrackets(title) + if href != "" { + hdr = fmt.Sprintf("### [%s](%s)", escapeDeclMarkdownBrackets(title), href) + } + if dateStr != "" { + hdr += "\n- Date: " + dateStr + } + blocks = append(blocks, hdr) + } + } + + if len(records) == 0 { + return nil + } + var md []string + md = append(md, "# "+escapeDeclMarkdownBlock(pageTitle)) + if siteName != "" { + md = append(md, "- **Company**: "+escapeDeclMarkdownBlock(siteName)) + } + if pageDesc != "" { + md = append(md, escapeDeclMarkdownBlock(pageDesc)) + } + md = append(md, "## Investor Releases & Events\n\n"+strings.Join(blocks, "\n\n")) + + return wave3PRIRFinalizeResult(&DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: pageTitle, + Description: pageDesc, + Markdown: strings.Join(md, "\n\n"), + Links: links, + Records: records, + }) +} + +// ── #260 ir-portal-pack & #261 company-newsrooms Shared RSS Formatter ───────────────────────────── + +func wave3PRIRFormatRSSXML(rawBody, origURL, source string) (*DeclarativeFormattedDoc, bool) { + lowerHead := asciiLowerExtractString(rawBody[:minInt(len(rawBody), 1200)]) + if !strings.Contains(lowerHead, "<rss") && !strings.Contains(lowerHead, "<feed") && !strings.Contains(lowerHead, "<rdf:rdf") { + return nil, false + } + feedDoc, feedLinks := FormatFeedXMLToMarkdown(rawBody, origURL) + if feedDoc == nil || strings.TrimSpace(feedDoc.Markdown) == "" { + return nil, false + } + + var records []map[string]any + lowerXML := asciiLowerExtractString(rawBody) + openTag, closeTag := "<item", "</item>" + if !strings.Contains(lowerXML, "<item") && strings.Contains(lowerXML, "<entry") { + openTag, closeTag = "<entry", "</entry>" + } + pos := 0 + for len(records) < wave3PRIRMaxRecords { + rel := strings.Index(lowerXML[pos:], openTag) + if rel < 0 { + break + } + start := pos + rel + gt := strings.IndexByte(lowerXML[start:], '>') + if gt < 0 { + break + } + bodyStart := start + gt + 1 + endRel := strings.Index(lowerXML[bodyStart:], closeTag) + if endRel < 0 { + break + } + block := rawBody[bodyStart : bodyStart+endRel] + pos = bodyStart + endRel + len(closeTag) + + itTitle := SanitizeSchemaPlainField(wave3PRIRCleanText(matchFirstXMLTagFmtGo(block, []string{"title"})), 240) + itLink := SanitizeSchemaHTTPSURL(matchFirstXMLTagFmtGo(block, []string{"link", "guid"}), origURL) + itDate := SanitizeSchemaPlainField(matchFirstXMLTagFmtGo(block, []string{"pubDate", "published", "updated", "dc:date"}), 64) + itDesc := SanitizeSchemaPlainField(wave3PRIRCleanText(matchFirstXMLTagFmtGo(block, []string{"description", "summary"})), 300) + if itTitle == "" { + continue + } + rec := map[string]any{"title": itTitle, "source": source} + if itLink != "" { + rec["url"] = itLink + } + if itDate != "" { + rec["publishedAt"] = itDate + } + if itDesc != "" { + rec["description"] = itDesc + } + records = append(records, rec) + } + if len(records) == 0 { + return nil, false + } + + title := feedDoc.Title + if title == "" { + title = "Press Releases Feed" + } + return &DeclarativeFormattedDoc{ + Title: title, + Description: feedDoc.Description, + Markdown: feedDoc.Markdown, + Links: feedLinks, + Records: records, + }, true +} + +// ── #260 ir-portal-pack ─────────────────────────────────────────────────────────────────────────── + +func wave3PRIRExtractIRPortalPackHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + lower := wave3PRIRProbeLower(rawHTML, 256*1024) + hasMarker := wave3PRIRContainsAny(lower, + "wd_newsfeed", + "wd_item_", + "wd_script_id", + "equisolve", + "irwebsites", + "nir-widget", + "ir-news", + ) + if !hasMarker { + return nil + } + + doc := ParseHTMLDoc(rawHTML, 512*1024) + pageTitle, siteName, pageDesc := wave3PRIRPageMeta(doc) + if pageTitle == "" { + pageTitle = "Investor Relations Portal" + } + + var records []map[string]any + var links []string + seenLinks := map[string]bool{} + var blocks []string + + // Discover RSS feed links + for _, linkEl := range doc.Select(`link[type="application/rss+xml"], link[type="application/atom+xml"]`, 10) { + wave3PRIRAddLink(&links, seenLinks, wave3PRIRNodeAttr(linkEl, "href"), baseURL) + } + + // Notified / Intrado (`wd_item`), Nasdaq IR (`nir-news`), Equisolve release rows + for _, item := range doc.Select(`.wd_item, .wd_newsfeed_releases .wd_item, .nir-widget--news .nir-widget--list .nir-widget--item, .press-release-item, article`, 60) { + if len(records) >= wave3PRIRMaxRecords { + break + } + title := SanitizeSchemaPlainField(wave3PRIRFirstNonEmpty( + item.Text(`.wd_title, .nir-widget--news--headline, h2, h3`), + item.Text(`a`), + ), 240) + if title == "" { + continue + } + dateStr := SanitizeSchemaPlainField(wave3PRIRFirstNonEmpty( + item.Text(`.wd_date, .nir-widget--news--date-time, time`), + wave3PRIRRxQ4Date.FindString(item.Text()), + ), 64) + summary := SanitizeSchemaPlainField(item.Text(`.wd_subtitle, .wd_summary, p`), 300) + href := "" + if a := item.First(`.wd_title a, a[href]`); a != nil { + href = wave3PRIRAddLink(&links, seenLinks, wave3PRIRNodeAttr(a, "href"), baseURL) + } + rec := map[string]any{"title": title, "source": "ir-portal-pack"} + if dateStr != "" { + rec["date"] = dateStr + } + if href != "" { + rec["url"] = href + } + if summary != "" { + rec["summary"] = summary + } + records = append(records, rec) + + hdr := "### " + escapeDeclMarkdownBrackets(title) + if href != "" { + hdr = fmt.Sprintf("### [%s](%s)", escapeDeclMarkdownBrackets(title), href) + } + if dateStr != "" { + hdr += "\n- Date: " + dateStr + } + if summary != "" { + hdr += "\n" + escapeDeclMarkdownBlock(summary) + } + blocks = append(blocks, hdr) + } + + // JSON-LD Corporation / NewsArticle fallback (e.g. Equisolve IR homepages) + if len(records) == 0 && hasJSONLDScriptToken(rawHTML) { + for _, obj := range ExtractJSONLDObjects(rawHTML, 32) { + if len(records) >= wave3PRIRMaxRecords { + break + } + if !wave3PRIRHasSchemaType(obj, "Corporation", "Organization", "NewsArticle", "WebSite") { + continue + } + name := wave3PRIRPlain(wave3PRIRFirstNonEmpty(jsonScalarToString(obj["headline"]), jsonScalarToString(obj["name"])), 240) + if name == "" { + continue + } + u := wave3PRIRAddLink(&links, seenLinks, jsonScalarToString(obj["url"]), baseURL) + ticker := wave3PRIRPlain(obj["tickerSymbol"], 32) + rec := map[string]any{"name": name, "source": "ir-portal-pack"} + if ticker != "" { + rec["ticker"] = ticker + } + if u != "" { + rec["url"] = u + } + records = append(records, rec) + line := "- **" + escapeDeclMarkdownBlock(name) + "**" + if ticker != "" { + line += " (`" + ticker + "`)" + } + if u != "" { + line += " — " + u + } + blocks = append(blocks, line) + } + } + + if len(records) == 0 { + return nil + } + var md []string + md = append(md, "# "+escapeDeclMarkdownBlock(pageTitle)) + if siteName != "" { + md = append(md, "- **Company**: "+escapeDeclMarkdownBlock(siteName)) + } + if pageDesc != "" { + md = append(md, escapeDeclMarkdownBlock(pageDesc)) + } + md = append(md, "## Investor News & Releases\n\n"+strings.Join(blocks, "\n\n")) + + return wave3PRIRFinalizeResult(&DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: pageTitle, + Description: pageDesc, + Markdown: strings.Join(md, "\n\n"), + Links: links, + Records: records, + }) +} + +// ── #261 company-newsrooms ──────────────────────────────────────────────────────────────────────── + +func wave3PRIRExtractCompanyNewsroomsHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + lower := wave3PRIRProbeLower(rawHTML, 256*1024) + hostLower := "" + if u, err := url.Parse(strings.TrimSpace(baseURL)); err == nil { + hostLower = strings.ToLower(u.Hostname()) + } + hasMarker := strings.Contains(hostLower, "cision.com") || + strings.Contains(hostLower, "prowly.com") || + strings.Contains(hostLower, "prezly.com") || + wave3PRIRContainsAny(lower, + "prowly", + "pr-story", + "prezly", + "theme-assets.prezly.com", + "news.cision.com", + "multimedia.cision.com", + "cision.com", + "cision-", + "cision_", + "cisionweb", + "prnewswire", + "powered by cision", + ) + if !hasMarker { + return nil + } + + doc := ParseHTMLDoc(rawHTML, 512*1024) + pageTitle, siteName, pageDesc := wave3PRIRPageMeta(doc) + if pageTitle == "" { + pageTitle = "Company Newsroom" + } + + var records []map[string]any + var links []string + seenLinks := map[string]bool{} + var blocks []string + + // Discover RSS/Atom feed links + for _, linkEl := range doc.Select(`link[type="application/rss+xml"], link[type="application/atom+xml"]`, 10) { + wave3PRIRAddLink(&links, seenLinks, wave3PRIRNodeAttr(linkEl, "href"), baseURL) + } + + // JSON-LD NewsArticle / Article + if hasJSONLDScriptToken(rawHTML) { + for _, obj := range ExtractJSONLDObjects(rawHTML, 40) { + if len(records) >= wave3PRIRMaxRecords { + break + } + if !wave3PRIRHasSchemaType(obj, "NewsArticle", "Article", "BlogPosting") { + continue + } + title := wave3PRIRPlain(wave3PRIRFirstNonEmpty(jsonScalarToString(obj["headline"]), jsonScalarToString(obj["name"])), 240) + if title == "" { + continue + } + dateStr := wave3PRIRPlain(obj["datePublished"], 64) + desc := wave3PRIRPlain(obj["description"], 300) + u := wave3PRIRAddLink(&links, seenLinks, jsonScalarToString(obj["url"]), baseURL) + rec := map[string]any{"title": title, "source": "company-newsrooms"} + if dateStr != "" { + rec["publishedAt"] = dateStr + } + if u != "" { + rec["url"] = u + } + if desc != "" { + rec["description"] = desc + } + records = append(records, rec) + hdr := "### " + escapeDeclMarkdownBrackets(title) + if u != "" { + hdr = fmt.Sprintf("### [%s](%s)", escapeDeclMarkdownBrackets(title), u) + } + if dateStr != "" { + hdr += "\n- Published: " + dateStr + } + if desc != "" { + hdr += "\n" + escapeDeclMarkdownBlock(desc) + } + blocks = append(blocks, hdr) + } + } + + // Prowly (.pr-story), Prezly (story-card), Cision (.release-item / .container-card / .card-information / article) + if len(records) == 0 { + extractCardItems := func(selector string) { + for _, item := range doc.Select(selector, 60) { + if len(records) >= wave3PRIRMaxRecords { + break + } + title := SanitizeSchemaPlainField(wave3PRIRFirstNonEmpty( + item.Text(`.pr-story-title, .pr-story__header, .card-information h2, .card-information h3, .card-information h4, .card-information h5, .card-information .title, .card-information .headline, h2, h3, h4, h5`), + item.Text(`.card-information a, a`), + ), 240) + if title == "" { + continue + } + dateStr := SanitizeSchemaPlainField(wave3PRIRFirstNonEmpty( + item.Text(`time, .date, .published-at, .card-information time, .card-information .date`), + wave3PRIRRxQ4Date.FindString(item.Text()), + ), 64) + summary := SanitizeSchemaPlainField(item.Text(`p, .summary, .pr-story-lead, .pr-story__lead, .card-information p`), 300) + href := "" + if a := item.First(`a[href]`); a != nil { + href = wave3PRIRAddLink(&links, seenLinks, wave3PRIRNodeAttr(a, "href"), baseURL) + } else if item.Tag() == "a" { + href = wave3PRIRAddLink(&links, seenLinks, wave3PRIRNodeAttr(item, "href"), baseURL) + } + rec := map[string]any{"title": title, "source": "company-newsrooms"} + if dateStr != "" { + rec["publishedAt"] = dateStr + } + if href != "" { + rec["url"] = href + } + if summary != "" { + rec["description"] = summary + } + records = append(records, rec) + hdr := "### " + escapeDeclMarkdownBrackets(title) + if href != "" { + hdr = fmt.Sprintf("### [%s](%s)", escapeDeclMarkdownBrackets(title), href) + } + if dateStr != "" { + hdr += "\n- Published: " + dateStr + } + if summary != "" { + hdr += "\n" + escapeDeclMarkdownBlock(summary) + } + blocks = append(blocks, hdr) + } + } + extractCardItems(`.pr-story, .story-card, [class*="StoryCard"], .release-item, .cision-article, .container-card, article`) + if len(records) == 0 { + extractCardItems(`.card-information`) + } + } + + // Prezly Next.js __NEXT_DATA__ stories fallback + if len(records) == 0 && strings.Contains(rawHTML, "__NEXT_DATA__") { + if nd, ok := wave3PRIRExtractNextData(rawHTML); ok { + if props, okP := nd["props"].(map[string]any); okP { + if pageProps, okPP := props["pageProps"].(map[string]any); okPP { + if stories, okS := pageProps["stories"].([]any); okS { + for _, st := range stories { + if len(records) >= wave3PRIRMaxRecords { + break + } + sm, okSM := st.(map[string]any) + if !okSM { + continue + } + title := wave3PRIRPlain(sm["title"], 240) + if title == "" { + continue + } + dateStr := wave3PRIRPlain(sm["published_at"], 64) + sub := wave3PRIRPlain(sm["subtitle"], 300) + u := wave3PRIRAddLink(&links, seenLinks, jsonScalarToString(sm["url"]), baseURL) + rec := map[string]any{"title": title, "source": "company-newsrooms"} + if dateStr != "" { + rec["publishedAt"] = dateStr + } + if u != "" { + rec["url"] = u + } + if sub != "" { + rec["description"] = sub + } + records = append(records, rec) + hdr := "### " + escapeDeclMarkdownBrackets(title) + if u != "" { + hdr = fmt.Sprintf("### [%s](%s)", escapeDeclMarkdownBrackets(title), u) + } + blocks = append(blocks, hdr) + } + } + } + } + } + } + + if len(records) == 0 { + return nil + } + var md []string + md = append(md, "# "+escapeDeclMarkdownBlock(pageTitle)) + if siteName != "" { + md = append(md, "- **Newsroom**: "+escapeDeclMarkdownBlock(siteName)) + } + if pageDesc != "" { + md = append(md, escapeDeclMarkdownBlock(pageDesc)) + } + md = append(md, "## Stories & Press Releases\n\n"+strings.Join(blocks, "\n\n")) + + return wave3PRIRFinalizeResult(&DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: pageTitle, + Description: pageDesc, + Markdown: strings.Join(md, "\n\n"), + Links: links, + Records: records, + }) +} diff --git a/internal/extract/wave3_prop_rest_ir_test.go b/internal/extract/wave3_prop_rest_ir_test.go new file mode 100644 index 0000000..acbc749 --- /dev/null +++ b/internal/extract/wave3_prop_rest_ir_test.go @@ -0,0 +1,321 @@ +package extract + +import ( + "encoding/json" + "strings" + "testing" + + "github.com/bartrumb/edgefetch/v2/internal/classify" +) + +func TestWave3PropRestIRModesRegistered(t *testing.T) { + modes := []string{ + "appfolio_listings_html", + "pm_listing_widgets_html", + "multifamily_portals_html", + "idx_broker_showcase_html", + "popmenu_html", + "bentobox_html", + "square_toast_menu_html", + "schema_menu_html", + "q4_ir_html", + "ir_portal_pack_html", + "company_newsrooms_html", + } + externalHTMLModesMu.RLock() + defer externalHTMLModesMu.RUnlock() + for _, m := range modes { + if _, ok := externalHTMLModesLazy[m]; !ok { + t.Fatalf("RegisterExternalHTMLModeLazy missing mode %q", m) + } + } +} + +func TestWave3PropRestIRHTMLPositiveAndGuards(t *testing.T) { + // #251 appfolio-listings (list + detail + /page-not-found-sub rejection) + afHTML := `<!doctype html><html><head><title>Rental Listings

Available Listings

1234 Sunset Blvd #204

$2,450/mo | 2 bd | 1 ba | 920 sq ft
` + afRes := Wave3PropRestIRRunHTML("appfolio_listings_html", afHTML, "https://lapmg.appfolio.com/listings", "") + if afRes == nil || afRes.ExtractorID != "appfolio-listings" || !strings.Contains(afRes.Markdown, "1234 Sunset Blvd #204") || !strings.Contains(afRes.Markdown, "$2,450") { + t.Fatalf("appfolio-listings positive failed: %+v", afRes) + } + afSoft404 := `Page not found | AppFolio

Page not found

` + if bad := Wave3PropRestIRRunHTML("appfolio_listings_html", afSoft404, "https://www.appfolio.com/page-not-found-sub", ""); bad != nil { + t.Fatalf("appfolio-listings must reject /page-not-found-sub, got %+v", bad) + } + + // #252 pm-listing-widgets (Buildium + Propertyware) + pmHTML := `Rentals | Portland PM
` + pmRes := Wave3PropRestIRRunHTML("pm_listing_widgets_html", pmHTML, "https://portland.managebuilding.com/Resident/public/rentals", "") + if pmRes == nil || pmRes.ExtractorID != "pm-listing-widgets" || !strings.Contains(pmRes.Markdown, "Buildium") || !strings.Contains(pmRes.Markdown, "742 NW Flanders St") { + t.Fatalf("pm-listing-widgets Buildium failed: %+v", pmRes) + } + pwHTML := `Rentals

910 Oak Ave

$1,650/mo | 2 bd | 2 ba

Details
` + pwRes := Wave3PropRestIRRunHTML("pm_listing_widgets_html", pwHTML, "https://acme.propertyware.com/rentals", "") + if pwRes == nil || !strings.Contains(pwRes.Markdown, "Propertyware") { + t.Fatalf("pm-listing-widgets Propertyware failed: %+v", pwRes) + } + + // #253 multifamily-portals (Jonah/RentCafe + .ashx guard) + mfHTML := `Floor Plans | Canvas at Midlothian

The Oakwood

$1,725/mo | 2 Bed | 2 Bath | 1,080 sq ft
` + mfRes := Wave3PropRestIRRunHTML("multifamily_portals_html", mfHTML, "https://www.canvasatmidlothian.com/", "") + if mfRes == nil || mfRes.ExtractorID != "multifamily-portals" || !strings.Contains(mfRes.Markdown, "The Oakwood") { + t.Fatalf("multifamily-portals failed: %+v", mfRes) + } + if ashx := Wave3PropRestIRRunHTML("multifamily_portals_html", mfHTML, "https://www.rentcafe.com/availableunits.ashx", ""); ashx != nil { + t.Fatalf("multifamily-portals must reject .ashx URLs disallowed by robots.txt") + } + + // #254 idx-broker-showcase (Showcase IDX + IDX Broker) + sidxHTML := `Featured Homes | Entity Realty

410 Barton Springs Rd

$685,000 | 3 Bed | 2.5 Bath | 2,140 sq ft

` + idxRes := Wave3PropRestIRRunHTML("idx_broker_showcase_html", sidxHTML, "https://entityrealty.com/", "") + if idxRes == nil || idxRes.ExtractorID != "idx-broker-showcase" || !strings.Contains(idxRes.Markdown, "ATX99812") || !strings.Contains(idxRes.Markdown, "Entity Realty") { + t.Fatalf("idx-broker-showcase Showcase failed: %+v", idxRes) + } + idxBrokerHTML := `Home Search
88 Pine StMLS100

$540,000 | 3 Bed | 2 Bath

View
` + idxBRes := Wave3PropRestIRRunHTML("idx_broker_showcase_html", idxBrokerHTML, "https://demo.idxbroker.com/idx/results/listings", "") + if idxBRes == nil || !strings.Contains(idxBRes.Markdown, "88 Pine St") { + t.Fatalf("idx-broker-showcase IDX Broker failed: %+v", idxBRes) + } + + // #255 popmenu + popHTML := `Menu | Sample Bistro

Wood-Fired Margherita

$18.50

San Marzano tomatoes and basil.

` + popRes := Wave3PropRestIRRunHTML("popmenu_html", popHTML, "https://samplebistro.popmenu.com/menu", "") + if popRes == nil || popRes.ExtractorID != "popmenu" || !strings.Contains(popRes.Markdown, "Wood-Fired Margherita") { + t.Fatalf("popmenu failed: %+v", popRes) + } + + // #256 bentobox + bentoHTML := `Menu | Gramercy Tavern` + bentoRes := Wave3PropRestIRRunHTML("bentobox_html", bentoHTML, "https://www.gramercytavern.com/dining-room-menu/", "") + if bentoRes == nil || bentoRes.ExtractorID != "bentobox" || !strings.Contains(bentoRes.Markdown, "Roasted Maitake Mushrooms") { + t.Fatalf("bentobox failed: %+v", bentoRes) + } + + // #257 square-toast-menu (Square restaurant + Toast order.toasttab.com) + sqRestHTML := `Online Menu
` + sqRes := Wave3PropRestIRRunHTML("square_toast_menu_html", sqRestHTML, "https://rinconmx-restaurant.square.site/shop/online-menu/LL5C6YEQHRVCYJVZRVRVY4WR", "") + if sqRes == nil || sqRes.ExtractorID != "square-toast-menu" || !strings.Contains(sqRes.Markdown, "Rincon MX Restaurant") || !strings.Contains(sqRes.Markdown, "Tacos & Bowls") { + t.Fatalf("square-toast-menu Square failed: %+v", sqRes) + } + toastHTML := `Order Online | Over the Counter

Classic Smash Burger

$14.50

Double patty, cheddar, house sauce

` + toastRes := Wave3PropRestIRRunHTML("square_toast_menu_html", toastHTML, "https://order.toasttab.com/online/over-the-counter-3", "") + if toastRes == nil || toastRes.ExtractorID != "square-toast-menu" || !strings.Contains(toastRes.Markdown, "Classic Smash Burger") { + t.Fatalf("square-toast-menu Toast failed: %+v", toastRes) + } + + // #258 schema-menu (Menu JSON-LD positive + plain Restaurant non-hijack guard) + menuLD := `Menu | Chili's

Chili's Menu

` + smRes := Wave3PropRestIRRunHTML("schema_menu_html", menuLD, "https://www.chilis.com/menu", "") + if smRes == nil || smRes.ExtractorID != "schema-menu" || !strings.Contains(smRes.Markdown, "Skillet Queso") || !strings.Contains(smRes.Markdown, "USD 11.29") { + t.Fatalf("schema-menu positive failed: %+v", smRes) + } + plainRestaurantLD := `Tartine Bakery

Tartine

` + if hijacked := Wave3PropRestIRRunHTML("schema_menu_html", plainRestaurantLD, "https://tartinebakery.com/", ""); hijacked != nil { + t.Fatalf("schema-menu MUST NOT hijack plain Restaurant without Menu/MenuSection/MenuItem/hasMenu, got %+v", hijacked) + } + + // #259 q4-ir HTML + q4HTML := `News | Braze IR` + q4Res := Wave3PropRestIRRunHTML("q4_ir_html", q4HTML, "https://investors.braze.com/news", "") + if q4Res == nil || q4Res.ExtractorID != "q4-ir" || !strings.Contains(q4Res.Markdown, "Braze Reports Q3 Fiscal Results") { + t.Fatalf("q4-ir HTML failed: %+v", q4Res) + } + + // #260 ir-portal-pack HTML (Notified/Intrado + Equisolve) + irNotified := `Press Releases | Iridium
Nov 10, 2026
New satellite constellation milestones achieved.
` + irRes := Wave3PropRestIRRunHTML("ir_portal_pack_html", irNotified, "https://investor.iridium.com/press-releases", "") + if irRes == nil || irRes.ExtractorID != "ir-portal-pack" || !strings.Contains(irRes.Markdown, "Iridium Expands Direct-to-Device Network") { + t.Fatalf("ir-portal-pack HTML failed: %+v", irRes) + } + + // #261 company-newsrooms HTML (Prowly) + prowlyHTML := `Residence Newsroom

Residence Launches New Anthology

Annual Nordic design book.

` + cnRes := Wave3PropRestIRRunHTML("company_newsrooms_html", prowlyHTML, "https://residence.prowly.com/", "") + if cnRes == nil || cnRes.ExtractorID != "company-newsrooms" || !strings.Contains(cnRes.Markdown, "Residence Launches New Anthology") { + t.Fatalf("company-newsrooms HTML failed: %+v", cnRes) + } + + // RunWave3PropRestIRHTMLMode smoke test + if encoded, okEnc := RunWave3PropRestIRHTMLMode("schema_menu_html", menuLD, "https://www.chilis.com/menu"); !okEnc || !json.Valid([]byte(encoded)) { + t.Fatalf("RunWave3PropRestIRHTMLMode failed: ok=%v", okEnc) + } +} + +func TestWave3PropRestIRJSONAndRSSModes(t *testing.T) { + // #259 q4_ir_json PressRelease + Event + empty rejection + q4PR := `{"GetPressReleaseListResult":[{"Headline":"Q4 Systems Reports Record Q3","PressReleaseDate":"11/12/2026 08:00:00","LinkToDetailPage":"https://mtr.q4web.com/news/q3","ShortBody":"Revenue up 24% YoY."}]}` + prDoc, ok := FormatWave3PropRestIRJSONDoc("q4_ir_json", []byte(q4PR), nil, "https://mtr.q4web.com/feed/PressRelease.svc/GetPressReleaseList") + if !ok || prDoc == nil || !strings.Contains(prDoc.Markdown, "Q4 Systems Reports Record Q3") { + t.Fatalf("q4_ir_json press release failed: ok=%v doc=%+v", ok, prDoc) + } + q4Ev := `{"GetEventListResult":[{"Title":"Q3 Earnings Call","StartDate":"12/04/2026 17:00:00","LinkToDetailPage":"https://investors.braze.com/events/q3","WebcastLink":"https://events.q4inc.com/attendee/123"}]}` + evDoc, okEv := FormatWave3PropRestIRJSONDoc("q4_ir_json", []byte(q4Ev), nil, "https://investors.braze.com/feed/Event.svc/GetEventList") + if !okEv || evDoc == nil || !strings.Contains(evDoc.Markdown, "Q3 Earnings Call") { + t.Fatalf("q4_ir_json event failed: ok=%v doc=%+v", okEv, evDoc) + } + if _, okEmpty := FormatWave3PropRestIRJSONDoc("q4_ir_json", []byte(`{"GetPressReleaseListResult":[]}`), nil, "https://mtr.q4web.com/feed/PressRelease.svc/GetPressReleaseList"); okEmpty { + t.Fatalf("q4_ir_json empty result must return false") + } + if encoded, okMode := FormatWave3PropRestIRJSONMode("q4_ir_json", []byte(q4PR), nil, "https://mtr.q4web.com/feed/PressRelease.svc/GetPressReleaseList"); !okMode || !json.Valid([]byte(encoded)) { + t.Fatalf("FormatWave3PropRestIRJSONMode failed") + } + + // #260 ir_portal_rss_xml + #261 company_newsroom_rss_xml + rssXML := `Bowhead Press ReleasesBowhead Reports Q3https://ir.bowheadspecialty.com/news/q3Wed, 04 Nov 2026 21:00:00 GMTStrong underwriting growth.` + irRSSDoc, okIR := FormatWave3PropRestIRTextDoc("ir_portal_rss_xml", rssXML, nil, "https://ir.bowheadspecialty.com/news-events/press-releases/rss") + if !okIR || irRSSDoc == nil || !strings.Contains(irRSSDoc.Markdown, "Bowhead Reports Q3") { + t.Fatalf("ir_portal_rss_xml failed: ok=%v doc=%+v", okIR, irRSSDoc) + } + cnRSSDoc, okCN := FormatWave3PropRestIRTextDoc("company_newsroom_rss_xml", rssXML, nil, "https://residence.prowly.com/rss") + if !okCN || cnRSSDoc == nil || !strings.Contains(cnRSSDoc.Markdown, "Bowhead Reports Q3") { + t.Fatalf("company_newsroom_rss_xml failed: ok=%v doc=%+v", okCN, cnRSSDoc) + } + if _, okEmptyRSS := FormatWave3PropRestIRTextDoc("company_newsroom_rss_xml", `Empty`, nil, "https://residence.prowly.com/rss"); okEmptyRSS { + t.Fatalf("empty RSS feed must fail") + } + if encoded, okMode := FormatWave3PropRestIRTextMode("ir_portal_rss_xml", rssXML, nil, "https://ir.bowheadspecialty.com/news-events/press-releases/rss"); !okMode || !json.Valid([]byte(encoded)) { + t.Fatalf("FormatWave3PropRestIRTextMode failed") + } +} + +func TestWave3PropRestIRNegativeShellsAcrossAllModes(t *testing.T) { + modes := []string{ + "appfolio_listings_html", + "pm_listing_widgets_html", + "multifamily_portals_html", + "idx_broker_showcase_html", + "popmenu_html", + "bentobox_html", + "square_toast_menu_html", + "schema_menu_html", + "q4_ir_html", + "ir_portal_pack_html", + "company_newsrooms_html", + } + negShells := []struct { + name string + url string + html string + }{ + { + name: "404-not-found", + url: "https://example.com/404", + html: `404 Page Not Found

Not Found

`, + }, + { + name: "redirect-to-error", + url: "https://example.com/error", + html: `Error

Error

`, + }, + { + name: "appfolio-page-not-found-sub", + url: "https://www.appfolio.com/page-not-found-sub", + html: `Page not found | AppFolio
Fake
`, + }, + { + name: "cloudflare-challenge", + url: "https://order.toasttab.com/online/demo", + html: `Just a moment...
Checking your browser
`, + }, + { + name: "waf-403-forbidden", + url: "https://demo.idxbroker.com/idx/results", + html: `403 Forbidden

403 Forbidden

You don't have permission to access this resource.

`, + }, + { + name: "maintenance-503", + url: "https://example.com/listings", + html: `503 Service Unavailable

Scheduled Maintenance

This site is down for maintenance.

`, + }, + { + name: "empty-spa-shell", + url: "https://example.com/menu", + html: `Loading...
`, + }, + } + + for _, m := range modes { + for _, tc := range negShells { + if got := Wave3PropRestIRRunHTML(m, tc.html, tc.url, ""); got != nil { + t.Fatalf("mode %q leaked on negative shell %q: %+v", m, tc.name, got) + } + } + } + + // Verify content_state classifies AppFolio soft-404 & Cloudflare challenge as non-active + csAF := classify.ClassifyContentStateFull(classify.ContentStateInput{ + Status: 200, + URL: "https://rpmexpress.appfolio.com/listings", + FinalURL: "https://www.appfolio.com/page-not-found-sub", + RawHTML: `Page not found | AppFolio

Page not found

The page you requested could not be found.

`, + Markdown: "Page not found", + }) + if csAF.State == "active" { + t.Fatalf("AppFolio /page-not-found-sub must never classify as active, got %q", csAF.State) + } +} + +func TestWave3PropRestIRNonHijackAndCisionRegressions(t *testing.T) { + // Finding 1: company-newsrooms MUST NOT hijack articles containing "decision", "precision", etc. + for _, word := range []string{"decision", "precision", "incision"} { + articleHTML := `Editorial on ` + word + `

Making a ` + word + `

Thoughtful analysis on ` + word + ` making in engineering.

` + if got := Wave3PropRestIRRunHTML("company_newsrooms_html", articleHTML, "https://blog.example.org/post", ""); got != nil { + t.Fatalf("company-newsrooms hijacked unrelated article containing %q: %+v", word, got) + } + } + // Positive Cision newsroom MUST still match via Cision-specific markers or host + cisionHTML := `Newsroom | Tietoevry

Tietoevry Reports Q3

Strong cloud revenue growth.

` + if got := Wave3PropRestIRRunHTML("company_newsrooms_html", cisionHTML, "https://news.cision.com/tietoevry", ""); got == nil || got.ExtractorID != "company-newsrooms" { + t.Fatalf("company-newsrooms Cision positive failed: %+v", got) + } + + // Finding 2: ir-portal-pack MUST NOT hijack corporate pages mentioning "corporation" and "press-releases" + corpHTML := `About Acme Corporation

About Acme Corporation

Founded in 1980.

` + if got := Wave3PropRestIRRunHTML("ir_portal_pack_html", corpHTML, "https://www.acme.example.com/about", ""); got != nil { + t.Fatalf("ir-portal-pack hijacked generic corporation + press-releases page: %+v", got) + } + + // Finding 3: idx-broker-showcase MUST NOT hijack standalone RealEstateAgent or Product JSON-LD without IDX/MLS markers + standaloneAgentHTML := `Jane Doe Realty

Jane Doe Realty

` + if got := Wave3PropRestIRRunHTML("idx_broker_showcase_html", standaloneAgentHTML, "https://janedoerealty.example.com/", ""); got != nil { + t.Fatalf("idx-broker-showcase hijacked standalone RealEstateAgent without IDX markers: %+v", got) + } + // Standalone RealEstateAgent MUST resolve cleanly to schema-localbusiness + if lb := Round2RunHTML("schema_localbusiness_html", standaloneAgentHTML, "https://janedoerealty.example.com/", ""); lb == nil || lb.ExtractorID != "schema-localbusiness" { + t.Fatalf("standalone RealEstateAgent should resolve to schema-localbusiness, got %+v", lb) + } +} + +func TestWave3PropRestIRM7ProwlyAndCisionCards(t *testing.T) { + // 1. Prowly newsroom with
inside .pr-story (residence.prowly.com) + prowlyHTML := `Residence Newsroom
Residence Launches Spring Collection

Architectural lighting debuts in Stockholm.

` + pRes := Wave3PropRestIRRunHTML("company_newsrooms_html", prowlyHTML, "https://residence.prowly.com/", "company-newsrooms") + if pRes == nil || pRes.ExtractorID != "company-newsrooms" || len(pRes.Records) != 1 || !strings.Contains(pRes.Markdown, "Residence Launches Spring Collection") || !strings.Contains(pRes.Markdown, "https://residence.prowly.com/301-spring-collection") { + t.Fatalf("company-newsrooms Prowly .pr-story__header/h5 failed: %+v", pRes) + } + + // 2. Cision newsroom with .container-card / .card-information (news.cision.com/tietoevry) + cisionCardHTML := `Tietoevry Newsroom

Tietoevry Publishes Q4 Interim Report

Cloud engineering revenue grew 12 percent.

` + cRes := Wave3PropRestIRRunHTML("company_newsrooms_html", cisionCardHTML, "https://news.cision.com/tietoevry", "company-newsrooms") + if cRes == nil || cRes.ExtractorID != "company-newsrooms" || len(cRes.Records) != 1 || !strings.Contains(cRes.Markdown, "Tietoevry Publishes Q4 Interim Report") || !strings.Contains(cRes.Markdown, "2025-02-14") { + t.Fatalf("company-newsrooms Cision .container-card/.card-information failed: %+v", cRes) + } + + // 3. Cision standalone .card-information fallback + cisionInfoOnlyHTML := `Tietoevry Newsroom

Tietoevry Launches AI Platform

Enterprise AI governance update.

` + ciRes := Wave3PropRestIRRunHTML("company_newsrooms_html", cisionInfoOnlyHTML, "https://news.cision.com/tietoevry", "company-newsrooms") + if ciRes == nil || len(ciRes.Records) != 1 || !strings.Contains(ciRes.Markdown, "Tietoevry Launches AI Platform") { + t.Fatalf("company-newsrooms standalone .card-information failed: %+v", ciRes) + } + + // 4. Cision SSR newsroom with passive Cloudflare challenge-platform JS detection script + real cards MUST succeed; + // small <16KB challenge-platform shell without body markers MUST still be rejected. + cisionWithCF := `Tietoevry Newsroom

Tietoevry Newsroom

Tietoevry Announces Q1 Results

Strong digital engineering performance.

` + if cfRes := Wave3PropRestIRRunHTML("company_newsrooms_html", cisionWithCF, "https://news.cision.com/tietoevry", "company-newsrooms"); cfRes == nil || len(cfRes.Records) != 1 { + t.Fatalf("company-newsrooms must allow valid Cision SSR page with passive challenge-platform script, got: %+v", cfRes) + } + cfNeg := `Security Check
` + if cfNegRes := Wave3PropRestIRRunHTML("company_newsrooms_html", cfNeg, "https://news.cision.com/tietoevry", "company-newsrooms"); cfNegRes != nil { + t.Fatalf("company-newsrooms must reject small challenge-platform shell without body markers, got: %+v", cfNegRes) + } +} diff --git a/internal/extract/wave3_regulators.go b/internal/extract/wave3_regulators.go new file mode 100644 index 0000000..4ab1646 --- /dev/null +++ b/internal/extract/wave3_regulators.go @@ -0,0 +1,2363 @@ +package extract + +import ( + "bytes" + "encoding/json" + stdhtml "html" + "math" + "net/url" + "strconv" + "strings" +) + +const ( + wave3K1MaxHTMLBytes = 4 * 1024 * 1024 + wave3K1MaxJSONBytes = 4 * 1024 * 1024 + wave3K1MaxRecords = 25 +) + +var ( + wave3K1RxNotFoundTitle = newLazyRegexp(`(?i)(?:^|\b)(?:404|410|406|page\s+not\s+found|case\s+not\s+found|not\s+found|not\s+acceptable|bad\s+request|error\s*404|we\s+couldn'?t\s+find\s+that\s+page|access\s+denied|request\s+(?:rejected|blocked)|could\s+not\s+be\s+satisfied|unauthorized|attention\s+required|just\s+a\s+moment|403\s+forbidden|forbidden|403\s+error)(?:\b|$)`) + wave3K1RxMaintTitle = newLazyRegexp(`(?i)(?:scheduled\s+maintenance|temporarily\s+unavailable|service\s+unavailable|site\s+maintenance|under\s+maintenance|502\s+bad\s+gateway|503\s+service|down\s+for\s+maintenance)`) + wave3K1RxErrorTitle = newLazyRegexp(`(?i)^(?:(?:(?:400|401|403|404|406|410|429|500|502|503)\s+)?(?:internal\s+)?server\s+error|application\s+error|system\s+error|unexpected\s+error|error\s+page|(?:400|401|403|404|406|410|429|500|502|503|http\s+\d{3})\s+error|error\s+(?:400|401|403|404|406|410|429|500|502|503)|error)(?:\s*[|\-\x{2013}\x{2014}:]\s*.*)?$|^.*(?:\s*[|\-\x{2013}\x{2014}:]\s*error)$`) + wave3K1RxGenericTitle = newLazyRegexp(`(?i)^(?:loading\.{0,3}|home|welcome|search|cases|legal\s+library|ecfs|uls|adams)$`) + wave3K1RxHTMLTag = newLazyRegexp(`<[^>]+>`) + wave3K1RxSpaceCollapse = newLazyRegexp(`[ \t\r\n]+`) + wave3K1RxHref = newLazyRegexp(`(?i)]*\bhref\s*=\s*["']([^"'#][^"']*)["'][^>]*>(.*?)`) + wave3K1RxTRow = newLazyRegexp(`(?is)]*>(.*?)`) + wave3K1RxTCell = newLazyRegexp(`(?is)]*>(.*?)`) + wave3K1RxDateLike = newLazyRegexp(`\b(?:\d{4}-\d{2}-\d{2}|\d{1,2}[-/]\d{1,2}[-/]\d{2,4}|(?:January|February|March|April|May|June|July|August|September|October|November|December|Jan|Feb|Mar|Apr|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\.?\s+\d{1,2},\s+\d{4})\b`) + wave3K1RxISODate = newLazyRegexp(`^\d{4}-\d{2}-\d{2}`) + wave3K1RxMoney = newLazyRegexp(`\$[0-9]{1,3}(?:,[0-9]{3})*(?:\.[0-9]{2})?(?:\s*(?:million|billion))?`) + wave3K1RxNLRBCaseNo = newLazyRegexp(`(?i)\b\d{2}-[A-Z]{2}-\d{5,7}\b`) + wave3K1RxNLRBField = newLazyRegexp(`(?is)]*>\s*(Case Number|Date Filed|Status|Location|Region Assigned)\s*:?\s*\s*([^<\r\n]+)`) + wave3K1RxFTCMatter = newLazyRegexp(`(?is)(?:Matter(?:/File)?\s*Number|File\s*Number|Civil\s*Action\s*Number|Docket\s*Number)\s*:?\s*\s*(?:<[^>]+>\s*)*([A-Z0-9][A-Z0-9\-\.\s/:]{2,48})`) + wave3K1RxCallSign = newLazyRegexp(`\b[KW][A-Z0-9]{2,6}\b`) + wave3K1RxAccession = newLazyRegexp(`\bML\d{8,11}\b`) + wave3K1RxReleaseNum = newLazyRegexp(`(?i)\b(?:Release\s+(?:Number|No\.?)\s*[:#]?\s*|OCC\s+(?:Bulletin|News\s+Release)\s+)([A-Z0-9\-]{4,24})`) + wave3K1RxTitleTag = newLazyRegexp(`(?is)]*>(.*?)`) + wave3RxEmptyRootDiv = newLazyRegexp(`(?i)]*\bid=["'](?:root|app|__next|react-root)["'][^>]*>\s*
`) + wave3RxEmptyRootDivMain = newLazyRegexp(`(?i)]*\bid=["'](?:root|app|__next|react-root|main-content)["'][^>]*>\s*
`) +) + +func wave3HasEmptyRootDivShell(rawHTML, probeLower string, includeMainContent bool) bool { + rx := wave3RxEmptyRootDiv + if includeMainContent { + rx = wave3RxEmptyRootDivMain + } + if strings.Contains(probeLower, " 65536 && len(rawHTML) <= 262144 { + tail := rawHTML[65400:] + if indexFoldASCIIExtract(tail, "= 0 && rx.MatchString(tail) { + return true + } + } + return false +} + +func init() { + for _, mode := range []string{ + "dol_enforcement_html", + "osha_establishment_html", + "nlrb_cases_html", + "eeoc_litigation_html", + "ftc_cases_html", + "fcc_ecfs_html", + "fcc_uls_html", + "ferc_nrc_dockets_html", + "financial_regulators_html", + "oversight_gov_html", + } { + m := mode + RegisterExternalHTMLModeLazy(m, func(rawHTML, baseURL string, _ func() string, extractorID string) *DeclarativePostFetchResult { + return wave3K1RunHTMLModeCore(m, rawHTML, baseURL, extractorID) + }) + } +} + +// IsWave3RegulatorsHTMLMode reports whether mode is one of the 10 Category K Part 1 HTML extractors (#279-#288). +func IsWave3RegulatorsHTMLMode(mode string) bool { + switch mode { + case "dol_enforcement_html", + "osha_establishment_html", + "nlrb_cases_html", + "eeoc_litigation_html", + "ftc_cases_html", + "fcc_ecfs_html", + "fcc_uls_html", + "ferc_nrc_dockets_html", + "financial_regulators_html", + "oversight_gov_html": + return true + default: + return false + } +} + +// RunWave3RegulatorsHTMLMode executes a Category K Part 1 HTML extractor and returns JSON-marshaled DeclarativePostFetchResult. +func RunWave3RegulatorsHTMLMode(mode, rawHTML, baseURL string) (string, bool) { + if !IsWave3RegulatorsHTMLMode(mode) || strings.TrimSpace(rawHTML) == "" { + return "", false + } + res := wave3K1RunHTMLModeCore(mode, rawHTML, baseURL, wave3K1DefaultExtractorID(mode)) + res = sanitizePostFetchResultDeclHTML(res) + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return "", false + } + encoded, err := json.Marshal(res) + if err != nil { + return "", false + } + return string(encoded), true +} + +// IsWave3RegulatorsJSONMode reports whether mode is one of the Category K Part 1 JSON formatters. +func IsWave3RegulatorsJSONMode(mode string) bool { + switch mode { + case "dol_enforcement_json", + "fcc_ecfs_json", + "fcc_uls_json": + return true + default: + return false + } +} + +// FormatWave3RegulatorsJSONDoc formats a Category K Part 1 JSON payload into DeclarativeFormattedDoc. +func FormatWave3RegulatorsJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool) { + if !IsWave3RegulatorsJSONMode(mode) || len(raw) == 0 || len(raw) > wave3K1MaxJSONBytes { + return nil, false + } + trimmed := bytes.TrimSpace(bytes.TrimPrefix(raw, []byte("\xEF\xBB\xBF"))) + if len(trimmed) == 0 || (trimmed[0] != '{' && trimmed[0] != '[') { + return nil, false + } + parsed, ok := decodeJSONWithNumbers(trimmed) + if !ok || parsed == nil { + return nil, false + } + + var doc *DeclarativeFormattedDoc + var handled bool + switch mode { + case "dol_enforcement_json": + doc, handled = wave3K1FormatDOLJSON(parsed, origURL) + case "fcc_ecfs_json": + doc, handled = wave3K1FormatFCCECFSJSON(parsed, origURL) + case "fcc_uls_json": + doc, handled = wave3K1FormatFCCULSJSON(parsed, origURL) + } + if !handled || doc == nil || strings.TrimSpace(doc.Markdown) == "" { + return nil, false + } + return wave3K1FinalizeDoc(doc), true +} + +// FormatWave3RegulatorsJSONMode formats a Category K Part 1 JSON payload and returns JSON-marshaled DeclarativeFormattedDoc. +func FormatWave3RegulatorsJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool) { + doc, ok := FormatWave3RegulatorsJSONDoc(mode, raw, params, origURL) + if !ok || doc == nil { + return "", false + } + encoded, err := json.Marshal(doc) + if err != nil { + return "", false + } + return string(encoded), true +} + +func wave3K1DefaultExtractorID(mode string) string { + switch mode { + case "dol_enforcement_html": + return "dol-enforcement" + case "osha_establishment_html": + return "osha-establishment" + case "nlrb_cases_html": + return "nlrb-cases" + case "eeoc_litigation_html": + return "eeoc-litigation" + case "ftc_cases_html": + return "ftc-cases" + case "fcc_ecfs_html": + return "fcc-ecfs" + case "fcc_uls_html": + return "fcc-uls" + case "ferc_nrc_dockets_html": + return "ferc-nrc-dockets" + case "financial_regulators_html": + return "financial-regulators-enforcement" + case "oversight_gov_html": + return "oversight-gov" + default: + return "" + } +} + +func wave3K1RunHTMLModeCore(mode, rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + if len(rawHTML) == 0 || strings.IndexByte(rawHTML, '<') < 0 || strings.IndexByte(rawHTML, '>') < 0 { + return nil + } + if len(rawHTML) > wave3K1MaxHTMLBytes { + rawHTML = truncateUTF8SafeFullDocGo(rawHTML, wave3K1MaxHTMLBytes) + } + trimmedStart := strings.TrimLeft(rawHTML, " \t\r\n") + if trimmedStart == "" || trimmedStart[0] == '{' || trimmedStart[0] == '[' { + return nil + } + probe := rawHTML + if len(probe) > 65536 { + probe = probe[:65536] + } + probeLower := asciiLowerExtractString(probe) + urlLower := asciiLowerExtractString(baseURL) + + // Cheap byte prefilter BEFORE negative-shell checks or DOM extraction. + if !wave3K1MatchesModePrefilter(mode, probeLower, urlLower) { + return nil + } + if wave3K1HasCommonNegativeShell(rawHTML, probeLower, urlLower) { + return nil + } + if extractorID == "" { + extractorID = wave3K1DefaultExtractorID(mode) + } + + switch mode { + case "dol_enforcement_html": + return wave3K1ExtractDOLHTML(rawHTML, probeLower, baseURL, extractorID) + case "osha_establishment_html": + return wave3K1ExtractOSHAHTML(rawHTML, baseURL, extractorID) + case "nlrb_cases_html": + return wave3K1ExtractNLRBHTML(rawHTML, baseURL, urlLower, extractorID) + case "eeoc_litigation_html": + return wave3K1ExtractEEOCHTML(rawHTML, baseURL, extractorID) + case "ftc_cases_html": + return wave3K1ExtractFTCHTML(rawHTML, baseURL, extractorID) + case "fcc_ecfs_html": + return wave3K1ExtractFCCECFSHTML(rawHTML, baseURL, extractorID) + case "fcc_uls_html": + return wave3K1ExtractFCCULSHTML(rawHTML, baseURL, extractorID) + case "ferc_nrc_dockets_html": + return wave3K1ExtractFERCNRCHTML(rawHTML, baseURL, urlLower, extractorID) + case "financial_regulators_html": + return wave3K1ExtractFinRegHTML(rawHTML, baseURL, urlLower, extractorID) + case "oversight_gov_html": + return wave3K1ExtractOversightHTML(rawHTML, baseURL, extractorID) + default: + return nil + } +} + +func wave3K1MatchesModePrefilter(mode, probeLower, urlLower string) bool { + switch mode { + case "dol_enforcement_html": + return strings.Contains(urlLower, "dol.gov") || + strings.Contains(probeLower, "dol.gov") || + strings.Contains(probeLower, "department of labor") || + strings.Contains(probeLower, "wage and hour division") || + strings.Contains(probeLower, "whd_enforcement") + case "osha_establishment_html": + return strings.Contains(urlLower, "osha.gov") || + strings.Contains(probeLower, "osha.gov") || + strings.Contains(probeLower, "occupational safety and health") || + strings.Contains(probeLower, "/pls/imis/") || + strings.Contains(probeLower, "establishment") + case "nlrb_cases_html": + return strings.Contains(urlLower, "nlrb.gov") || + strings.Contains(probeLower, "nlrb.gov") || + strings.Contains(probeLower, "national labor relations board") || + strings.Contains(probeLower, "case_docket_activity") + case "eeoc_litigation_html": + return strings.Contains(urlLower, "eeoc.gov") || + strings.Contains(probeLower, "eeoc.gov") || + strings.Contains(probeLower, "equal employment opportunity commission") + case "ftc_cases_html": + return strings.Contains(urlLower, "ftc.gov") || + strings.Contains(probeLower, "ftc.gov") || + strings.Contains(probeLower, "federal trade commission") + case "fcc_ecfs_html": + return strings.Contains(urlLower, "fcc.gov/ecfs") || + strings.Contains(probeLower, "electronic comment filing") || + strings.Contains(probeLower, "ecfs") + case "fcc_uls_html": + return strings.Contains(urlLower, "wireless2.fcc.gov") || + strings.Contains(urlLower, "opendata.fcc.gov") || + strings.Contains(urlLower, "data.fcc.gov") || + strings.Contains(probeLower, "universal licensing system") || + strings.Contains(probeLower, "ulsapp") + case "ferc_nrc_dockets_html": + return strings.Contains(urlLower, "ferc.gov") || + strings.Contains(urlLower, "nrc.gov") || + strings.Contains(probeLower, "ferc") || + strings.Contains(probeLower, "nrc.gov") || + strings.Contains(probeLower, "elibrary") || + strings.Contains(probeLower, "adams") + case "financial_regulators_html": + return strings.Contains(urlLower, "cftc.gov") || + strings.Contains(urlLower, "occ.gov") || + strings.Contains(urlLower, "fincen.gov") || + strings.Contains(probeLower, "cftc.gov") || + strings.Contains(probeLower, "occ.gov") || + strings.Contains(probeLower, "fincen.gov") || + strings.Contains(probeLower, "commodity futures trading commission") || + strings.Contains(probeLower, "office of the comptroller of the currency") || + strings.Contains(probeLower, "financial crimes enforcement network") + case "oversight_gov_html": + return strings.Contains(urlLower, "oversight.gov") || + strings.Contains(probeLower, "oversight.gov") || + strings.Contains(probeLower, "inspector general") + default: + return false + } +} + +// ── Shared Negative-Shell, Sanitizing & DOM Helpers ────────────────────────────────────────────── + +func wave3K1IsNegativeURL(urlLower string) bool { + if urlLower == "" { + return false + } + if strings.Contains(urlLower, "/404") || + strings.Contains(urlLower, "/not-found") || + strings.Contains(urlLower, "/maintenance") || + strings.Contains(urlLower, "missing_key.html") || + strings.Contains(urlLower, "error=true") { + return true + } + pathOnly := urlLower + if idx := strings.Index(pathOnly, "://"); idx >= 0 { + rest := pathOnly[idx+3:] + if slash := strings.IndexByte(rest, '/'); slash >= 0 { + pathOnly = rest[slash:] + } else { + pathOnly = "/" + } + } + if cut := strings.IndexAny(pathOnly, "?#"); cut >= 0 { + pathOnly = pathOnly[:cut] + } + return strings.HasSuffix(pathOnly, "/error") || + strings.Contains(pathOnly, "/error/") || + strings.HasSuffix(pathOnly, "/error.html") || + strings.HasSuffix(pathOnly, "/error.htm") || + strings.HasSuffix(pathOnly, "/error.aspx") || + strings.HasSuffix(pathOnly, "/login") || + strings.Contains(pathOnly, "/login/") +} + +func wave3K1IsNegativeTitle(title string) bool { + t := strings.TrimSpace(title) + if t == "" { + return false + } + return wave3K1RxNotFoundTitle.MatchString(t) || + wave3K1RxMaintTitle.MatchString(t) || + wave3K1RxErrorTitle.MatchString(t) +} + +func wave3K1IsGenericTitle(title string) bool { + return wave3K1RxGenericTitle.MatchString(strings.TrimSpace(title)) +} + +func wave3K1HasEmptyTitleTag(probeLower string) bool { + m := wave3K1RxTitleTag.FindStringSubmatch(probeLower) + if len(m) < 2 { + return false + } + return strings.TrimSpace(wave3K1RxHTMLTag.ReplaceAllString(m[1], "")) == "" +} + +func wave3K1HasCommonNegativeShell(rawHTML, probeLower, urlLower string) bool { + if wave3K1IsNegativeURL(urlLower) { + return true + } + hasRealBodyMarkers := hasJSONLDScriptToken(probeLower) || + strings.Contains(probeLower, " 65536 { + tail := rawHTML[65536:] + hasRealBodyMarkers = indexFoldASCIIExtract(tail, "= 0 || + indexFoldASCIIExtract(tail, "= 0 || + indexFoldASCIIExtract(tail, "= 0 || + indexFoldASCIIExtract(tail, "application/ld+json") >= 0 + } + if (strings.Contains(probeLower, "challenge-platform") || strings.Contains(probeLower, "/cdn-cgi/challenge-platform")) && + len(rawHTML) < 16384 && !hasRealBodyMarkers { + return true + } + for _, marker := range []string{ + "cf-browser-verification", + "cf-turnstile", + "_cf_chl_opt", + "cf_chl_opt", + "attention required! | cloudflare", + "just a moment...", + "errors.edgesuite.net", + "error from cloudfront", + "generated by cloudfront", + "the request could not be satisfied", + "you don't have permission to access", + "access denied", + "403 forbidden", + "403 error", + "not acceptable", + "406 not acceptable", + "bad request. reference:", + "missing authentication token", + "api key is either incorrect or missing", + "api_key_missing", + "no api_key was supplied", + `rx-contentitemname" content="404"`, + "page not found | fincen.gov", + "404 page not found", + "window.kpsdk", + "kp_uidz", + "_incapsula_resource", + "incapsula incident", + "x-amzn-waf-action", + "the requested url was rejected", + "your support id is", + "var dd=", + "var dd =", + "dd={'rt'", + "geo.captcha-delivery.com", + "captcha-delivery.com", + "please enable js and disable any ad blocker", + } { + if strings.Contains(probeLower, marker) { + return true + } + } + title := extractTitleLinearQuick(rawHTML) + if wave3K1IsNegativeTitle(title) { + return true + } + if wave3K1HasEmptyTitleTag(probeLower) && + !strings.Contains(probeLower, "") + if !hasAppRoot && len(rawHTML) > 65536 && len(rawHTML) <= 262144 { + hasAppRoot = indexFoldASCIIExtract(rawHTML[65536:], "") >= 0 + } + hasTailRealMarkers := len(rawHTML) > 65536 && + (indexFoldASCIIExtract(rawHTML[65536:], "= 0 || + indexFoldASCIIExtract(rawHTML[65536:], "= 0 || + indexFoldASCIIExtract(rawHTML[65536:], "= 0) + if hasAppRoot && + !hasJSONLDScriptToken(rawHTML) && + !strings.Contains(probeLower, " 0 { + return true + } + case map[string]any: + if len(tv) > 0 { + if k == "Errors" { + if errVal, okE := tv["Err"]; okE && errVal != nil { + if s, okS := errVal.(string); !okS || strings.TrimSpace(s) != "" { + return true + } + } + continue + } + return true + } + case bool: + if tv { + return true + } + } + } + } + for _, k := range []string{"error_code", "statusCode", "status_code", "status"} { + if f, ok := wave3K1FloatVal(obj[k]); ok && f >= 400 { + return true + } + } + if st := strings.ToUpper(wave3K1Plain(obj["status"], 48)); st == "ERROR" || st == "ERR" || st == "NOT_FOUND" || st == "PERMISSION_DENIED" || st == "UNAUTHENTICATED" || st == "NOTAUTHENTICATED" { + return true + } + if msg := wave3K1Plain(obj["message"], 200); msg != "" && len(obj) <= 3 { + lm := strings.ToLower(msg) + if strings.Contains(lm, "unauthorized") || strings.Contains(lm, "not found") || + strings.Contains(lm, "invalid") || strings.Contains(lm, "forbidden") || + strings.Contains(lm, "missing authentication") || strings.Contains(lm, "api key") || + strings.Contains(lm, "no http resource") { + return true + } + } + return false +} + +func wave3K1CleanText(s string) string { + if s == "" { + return "" + } + if strings.IndexByte(s, '<') >= 0 { + s = wave3K1RxHTMLTag.ReplaceAllString(s, " ") + } + if strings.IndexByte(s, '&') >= 0 { + s = stdhtml.UnescapeString(s) + } + return strings.TrimSpace(wave3K1RxSpaceCollapse.ReplaceAllString(s, " ")) +} + +func wave3K1Plain(v any, maxLen int) string { + return SanitizeSchemaPlainField(wave3K1StringVal(v), maxLen) +} + +func wave3K1FirstNonEmpty(vals ...string) string { + for _, v := range vals { + if t := strings.TrimSpace(v); t != "" { + return t + } + } + return "" +} + +func wave3K1StringVal(v any) string { + switch tv := v.(type) { + case string: + return strings.TrimSpace(tv) + case json.Number: + return tv.String() + case float64: + if math.IsNaN(tv) || math.IsInf(tv, 0) { + return "" + } + if tv == math.Trunc(tv) { + return strconv.FormatInt(int64(tv), 10) + } + return strconv.FormatFloat(tv, 'f', -1, 64) + case int: + return strconv.Itoa(tv) + case int64: + return strconv.FormatInt(tv, 10) + case bool: + if tv { + return "true" + } + return "false" + default: + return "" + } +} + +func wave3K1FloatVal(v any) (float64, bool) { + switch tv := v.(type) { + case float64: + if math.IsNaN(tv) || math.IsInf(tv, 0) { + return 0, false + } + return tv, true + case int: + return float64(tv), true + case int64: + return float64(tv), true + case json.Number: + f, err := tv.Float64() + if err != nil || math.IsNaN(f) || math.IsInf(f, 0) { + return 0, false + } + return f, true + case string: + s := strings.TrimSpace(strings.ReplaceAll(tv, ",", "")) + if s == "" { + return 0, false + } + f, err := strconv.ParseFloat(s, 64) + if err != nil || math.IsNaN(f) || math.IsInf(f, 0) { + return 0, false + } + return f, true + default: + return 0, false + } +} + +func wave3K1Map(v any) map[string]any { + if m, ok := v.(map[string]any); ok { + return m + } + return nil +} + +func wave3K1Slice(v any) []any { + if s, ok := v.([]any); ok { + return s + } + return nil +} + +func wave3K1IntPtr(n int) *int { + v := n + return &v +} + +func wave3K1BoolPtr(b bool) *bool { + v := b + return &v +} + +func wave3K1AddLink(links *[]string, seen map[string]bool, raw, base string) { + u := SanitizeSchemaHTTPSURL(raw, base) + if u != "" && !seen[u] { + seen[u] = true + *links = append(*links, u) + } +} + +func wave3K1ExtractH1(rawHTML string) string { + inner, ok := findElementInnerLinearDeclHTML(rawHTML, "h1", nil, 0) + if !ok { + return "" + } + return wave3K1CleanText(inner) +} + +func wave3K1ExtractMeta(rawHTML, key string) string { + target := strings.ToLower(strings.TrimSpace(key)) + pos := 0 + for i := 0; i < 64 && pos < len(rawHTML); i++ { + open, ok := findOpenTagLinearDeclHTML(rawHTML, "meta", nil, pos) + if !ok { + break + } + pos = open.openEnd + nameVal, _ := getAttrValueLinearDeclHTML(open.attrStr, "name") + propVal, _ := getAttrValueLinearDeclHTML(open.attrStr, "property") + if strings.EqualFold(strings.TrimSpace(nameVal), target) || strings.EqualFold(strings.TrimSpace(propVal), target) { + if content, okC := getAttrValueLinearDeclHTML(open.attrStr, "content"); okC { + return wave3K1CleanText(content) + } + } + } + return "" +} + +func wave3K1ExtractByID(rawHTML, tagName, id string) string { + if strings.EqualFold(tagName, "div") { + open, ok := findOpenTagLinearDeclHTML(rawHTML, "div", func(attrStr string) bool { + v, okID := getAttrValueLinearDeclHTML(attrStr, "id") + return okID && strings.EqualFold(strings.TrimSpace(v), id) + }, 0) + if !ok { + return "" + } + if inner, okB := extractBalancedDivAtDeclHTML(rawHTML, open.index); okB { + return inner + } + return "" + } + inner, ok := findElementInnerLinearDeclHTML(rawHTML, tagName, func(attrStr string) bool { + v, okID := getAttrValueLinearDeclHTML(attrStr, "id") + return okID && strings.EqualFold(strings.TrimSpace(v), id) + }, 0) + if !ok { + return "" + } + return inner +} + +func wave3K1ExtractByClassSub(rawHTML, tagName, classNeedle string) string { + needle := strings.ToLower(classNeedle) + if strings.EqualFold(tagName, "div") { + open, ok := findOpenTagLinearDeclHTML(rawHTML, "div", func(attrStr string) bool { + v, okC := getAttrValueLinearDeclHTML(attrStr, "class") + return okC && strings.Contains(strings.ToLower(v), needle) + }, 0) + if !ok { + return "" + } + if inner, okB := extractBalancedDivAtDeclHTML(rawHTML, open.index); okB { + return inner + } + return "" + } + inner, ok := findElementInnerLinearDeclHTML(rawHTML, tagName, func(attrStr string) bool { + v, okC := getAttrValueLinearDeclHTML(attrStr, "class") + return okC && strings.Contains(strings.ToLower(v), needle) + }, 0) + if !ok { + return "" + } + return inner +} + +// wave3K1MainRegion slices the primary
or content container so large Drupal/Gov +// headers and megamenus (e.g., nlrb.gov, ftc.gov, fincen.gov) are bypassed quickly. +func wave3K1MainRegion(rawHTML string) string { + if open, ok := findOpenTagLinearDeclHTML(rawHTML, "main", nil, 0); ok { + if _, closeEnd, okC := findCloseTagLinearDeclHTML(rawHTML, "main", open.openEnd); okC && closeEnd > open.openEnd { + return rawHTML[open.openEnd:closeEnd] + } + if open.openEnd < len(rawHTML) { + return rawHTML[open.openEnd:] + } + } + for _, id := range []string{"main-content", "main_content", "block-mainpagecontent", "content"} { + if frag := wave3K1ExtractByID(rawHTML, "div", id); frag != "" { + return frag + } + } + if art, okA := findElementInnerLinearDeclHTML(rawHTML, "article", nil, 0); okA && art != "" { + return art + } + return rawHTML +} + +func wave3K1FragToMD(frag, baseURL string) string { + if strings.TrimSpace(frag) == "" { + return "" + } + doc := ExtractHTMLDocumentFull(""+frag+"", FullExtractOptions{ + BaseURL: baseURL, + OnlyMainContent: false, + IncludeImages: false, + IsFragment: true, + SkipUniversalExtractors: true, + SkipPlainText: true, + }) + return strings.TrimSpace(doc.Markdown) +} + +func wave3K1ExtractLinks(frag, baseURL string, maxLinks int) []struct{ Text, URL string } { + matches := wave3K1RxHref.FindAllStringSubmatch(frag, maxLinks*3) + out := make([]struct{ Text, URL string }, 0, maxLinks) + seen := make(map[string]bool) + for _, m := range matches { + if len(out) >= maxLinks { + break + } + if len(m) < 3 { + continue + } + u := SanitizeSchemaHTTPSURL(stdhtml.UnescapeString(strings.TrimSpace(m[1])), baseURL) + if u == "" || seen[u] { + continue + } + txt := wave3K1CleanText(m[2]) + if txt == "" { + continue + } + seen[u] = true + out = append(out, struct{ Text, URL string }{Text: txt, URL: u}) + } + return out +} + +func wave3K1FinalizeDoc(doc *DeclarativeFormattedDoc) *DeclarativeFormattedDoc { + if doc == nil { + return nil + } + doc.Title = SanitizeScrapedMeta(doc.Title) + doc.Description = SanitizeScrapedMeta(doc.Description) + doc.Author = SanitizeScrapedMeta(doc.Author) + doc.PublishedTime = SanitizeSchemaPlainField(doc.PublishedTime, 64) + doc.Markdown = SanitizeScrapedMarkdown(escapeDangerousRawHTMLOutsideFencesDeclGo(doc.Markdown)) + if len(doc.Links) > 0 { + clean := make([]string, 0, len(doc.Links)) + seen := make(map[string]bool, len(doc.Links)) + for _, l := range doc.Links { + if u := SanitizeSchemaHTTPSURL(l, ""); u != "" && !seen[u] { + seen[u] = true + clean = append(clean, u) + } + } + doc.Links = clean + } + if len(doc.Records) > wave3K1MaxRecords { + total := len(doc.Records) + if doc.Total != nil && *doc.Total > total { + total = *doc.Total + } + doc.Records = doc.Records[:wave3K1MaxRecords] + doc.Total = wave3K1IntPtr(total) + doc.Returned = wave3K1IntPtr(len(doc.Records)) + doc.Truncated = wave3K1BoolPtr(true) + if doc.NextCursor == "" { + doc.NextCursor = strconv.Itoa(len(doc.Records)) + } + } else if len(doc.Records) > 0 { + if doc.Returned == nil { + doc.Returned = wave3K1IntPtr(len(doc.Records)) + } + if doc.Total == nil { + doc.Total = wave3K1IntPtr(len(doc.Records)) + } + } + return doc +} + +func wave3K1CapRecords(recs []map[string]any, total int) ([]map[string]any, *int, *int, *bool) { + if len(recs) == 0 { + return nil, nil, nil, nil + } + if total < len(recs) { + total = len(recs) + } + if len(recs) > wave3K1MaxRecords { + recs = recs[:wave3K1MaxRecords] + return recs, wave3K1IntPtr(total), wave3K1IntPtr(len(recs)), wave3K1BoolPtr(true) + } + if total > len(recs) { + return recs, wave3K1IntPtr(total), wave3K1IntPtr(len(recs)), wave3K1BoolPtr(true) + } + return recs, wave3K1IntPtr(total), wave3K1IntPtr(len(recs)), nil +} + +func wave3K1HostFromURL(rawURL string) string { + u, err := url.Parse(strings.TrimSpace(rawURL)) + if err != nil { + return "" + } + return strings.TrimSuffix(strings.ToLower(u.Hostname()), ".") +} + +func wave3K1MDCell(s string) string { + s = strings.ReplaceAll(s, "|", "\\|") + s = strings.ReplaceAll(s, "\n", " ") + return strings.TrimSpace(s) +} + +func wave3K1PickISODate(raw string) string { + raw = strings.TrimSpace(raw) + if len(raw) >= 10 && wave3K1RxISODate.MatchString(raw[:10]) { + return raw[:10] + } + return "" +} + +func wave3K1ExtractTables(frag, baseURL, source string, maxRows int) ([]map[string]any, [][]string, []string, []string) { + var headers []string + var rowsMD [][]string + var recs []map[string]any + var links []string + seen := make(map[string]bool) + + for _, tr := range wave3K1RxTRow.FindAllStringSubmatch(frag, maxRows+10) { + cells := wave3K1RxTCell.FindAllStringSubmatch(tr[1], 12) + if len(cells) < 2 { + continue + } + if len(headers) == 0 && strings.Contains(strings.ToLower(tr[1]), " 0 { + rawItems = []any{obj} + } + if t, ok := wave3K1FloatVal(obj["count"]); ok && t > 0 { + totalCount = int(t) + } else if t, ok := wave3K1FloatVal(obj["total"]); ok && t > 0 { + totalCount = int(t) + } + } else if arr := wave3K1Slice(parsed); arr != nil { + rawItems = arr + } + if len(rawItems) == 0 { + return nil, false + } + + var recs []map[string]any + var latestDate string + isOSHA := strings.Contains(strings.ToLower(origURL), "/osha/") + + for _, el := range rawItems { + m := wave3K1Map(el) + if m == nil { + continue + } + caseID := wave3K1Plain(wave3K1FirstNonEmpty( + wave3K1StringVal(m["case_id"]), + wave3K1StringVal(m["activity_nr"]), + wave3K1StringVal(m["inspection_nr"]), + wave3K1StringVal(m["id"]), + ), 48) + entity := wave3K1Plain(wave3K1FirstNonEmpty( + wave3K1StringVal(m["trade_nm"]), + wave3K1StringVal(m["legal_name"]), + wave3K1StringVal(m["estab_name"]), + wave3K1StringVal(m["establishment_name"]), + wave3K1StringVal(m["name"]), + ), 140) + city := wave3K1Plain(wave3K1FirstNonEmpty(wave3K1StringVal(m["city_nm"]), wave3K1StringVal(m["site_city"]), wave3K1StringVal(m["city"])), 64) + state := wave3K1Plain(wave3K1FirstNonEmpty(wave3K1StringVal(m["st_cd"]), wave3K1StringVal(m["site_state"]), wave3K1StringVal(m["state"])), 16) + naics := wave3K1Plain(wave3K1FirstNonEmpty(wave3K1StringVal(m["naics_code_description"]), wave3K1StringVal(m["naics_cd"]), wave3K1StringVal(m["naics_code"])), 120) + dateStr := wave3K1PickISODate(wave3K1FirstNonEmpty( + wave3K1StringVal(m["findings_end_date"]), + wave3K1StringVal(m["findings_start_date"]), + wave3K1StringVal(m["close_case_date"]), + wave3K1StringVal(m["open_date"]), + wave3K1StringVal(m["load_dt"]), + )) + if dateStr != "" && dateStr > latestDate { + latestDate = dateStr + } + if caseID == "" && entity == "" { + continue + } + rec := map[string]any{ + "source": "dol-enforcement", + } + if caseID != "" { + rec["caseId"] = caseID + } + if entity != "" { + rec["entity"] = entity + } + if city != "" || state != "" { + rec["location"] = strings.Trim(city+", "+state, ", ") + } + if naics != "" { + rec["industry"] = naics + } + if dateStr != "" { + rec["date"] = dateStr + } + if amt, ok := wave3K1FloatVal(m["bw_atp_amt"]); ok { + rec["backWagesUsd"] = amt + } + if cmp, ok := wave3K1FloatVal(m["cmp_assd_cnt"]); ok { + rec["civilPenaltyUsd"] = cmp + } + if pen, ok := wave3K1FloatVal(m["total_current_penalty"]); ok { + rec["currentPenaltyUsd"] = pen + } + if vcnt, ok := wave3K1FloatVal(m["flsa_violtn_cnt"]); ok { + rec["flsaViolations"] = int(vcnt) + } + if inst, ok := wave3K1FloatVal(m["nr_instances"]); ok { + rec["instances"] = int(inst) + } + recs = append(recs, rec) + } + if len(recs) == 0 { + return nil, false + } + if totalCount < len(recs) { + totalCount = len(recs) + } + capped, totalPtr, retPtr, truncPtr := wave3K1CapRecords(recs, totalCount) + + title := "DOL WHD Enforcement Records" + if isOSHA { + title = "DOL OSHA Inspection Records" + } + if len(capped) == 1 { + if ent := wave3K1StringVal(capped[0]["entity"]); ent != "" { + title += ": " + ent + } + } + + var md strings.Builder + md.WriteString("# ") + md.WriteString(title) + md.WriteString("\n\n- **Source**: U.S. Department of Labor Open Data API (`apiprod.dol.gov`)\n") + if latestDate != "" { + md.WriteString("- **Latest Record Date**: ") + md.WriteString(latestDate) + md.WriteByte('\n') + } + md.WriteString("\n| Case / Activity | Entity | Location | Date | Penalty / Back Wages |\n|---|---|---|---|---|\n") + for _, r := range capped { + amt := "-" + if bw, ok := wave3K1FloatVal(r["backWagesUsd"]); ok { + amt = "$" + strconv.FormatFloat(bw, 'f', 2, 64) + " back wages" + } else if pen, ok := wave3K1FloatVal(r["currentPenaltyUsd"]); ok { + amt = "$" + strconv.FormatFloat(pen, 'f', 2, 64) + " penalty" + } else if cmp, ok := wave3K1FloatVal(r["civilPenaltyUsd"]); ok { + amt = "$" + strconv.FormatFloat(cmp, 'f', 2, 64) + " CMP" + } + md.WriteString("| `") + md.WriteString(wave3K1MDCell(wave3K1FirstNonEmpty(wave3K1StringVal(r["caseId"]), "-"))) + md.WriteString("` | ") + md.WriteString(wave3K1MDCell(wave3K1FirstNonEmpty(wave3K1StringVal(r["entity"]), "-"))) + md.WriteString(" | ") + md.WriteString(wave3K1MDCell(wave3K1FirstNonEmpty(wave3K1StringVal(r["location"]), "-"))) + md.WriteString(" | ") + md.WriteString(wave3K1MDCell(wave3K1FirstNonEmpty(wave3K1StringVal(r["date"]), "-"))) + md.WriteString(" | ") + md.WriteString(wave3K1MDCell(amt)) + md.WriteString(" |\n") + } + + return &DeclarativeFormattedDoc{ + Title: title, + Description: "U.S. Department of Labor enforcement records (" + strconv.Itoa(len(capped)) + " shown).", + PublishedTime: latestDate, + Markdown: md.String(), + Records: capped, + Total: totalPtr, + Returned: retPtr, + Truncated: truncPtr, + }, true +} + +func wave3K1ExtractDOLHTML(rawHTML, probeLower, baseURL, extractorID string) *DeclarativePostFetchResult { + // Reject empty React shell on data.dol.gov + if strings.Contains(probeLower, "data.dol.gov") && + (wave3K1HasEmptyTitleTag(probeLower) || strings.Contains(probeLower, `
`)) && + !strings.Contains(probeLower, " 0 && len(headers) >= 2 { + md.WriteString("\n## Inspection & Establishment Records\n\n| ") + for _, h := range headers { + md.WriteString(wave3K1MDCell(h)) + md.WriteString(" | ") + } + md.WriteString("\n|") + for range headers { + md.WriteString("---|") + } + md.WriteByte('\n') + for _, row := range rowsMD { + md.WriteString("| ") + for i := range headers { + val := "-" + if i < len(row) && row[i] != "" { + val = row[i] + } + md.WriteString(wave3K1MDCell(val)) + md.WriteString(" | ") + } + md.WriteByte('\n') + } + } + if bodyMD != "" { + md.WriteString("\n") + md.WriteString(bodyMD) + md.WriteByte('\n') + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: wave3K1ExtractMeta(rawHTML, "description"), + Markdown: md.String(), + Links: links, + Records: capped, + Total: totalPtr, + Returned: retPtr, + Truncated: truncPtr, + } +} + +// ── #281 NLRB Cases HTML ───────────────────────────────────────────────────────────────────────── + +func wave3K1ExtractNLRBHTML(rawHTML, baseURL, urlLower, extractorID string) *DeclarativePostFetchResult { + mainFrag := wave3K1MainRegion(rawHTML) + if block := wave3K1ExtractByID(mainFrag, "div", "block-mainpagecontent"); block != "" { + mainFrag = block + } + h1 := wave3K1FirstNonEmpty(wave3K1ExtractH1(mainFrag), wave3K1ExtractH1(rawHTML)) + title := wave3K1FirstNonEmpty(h1, wave3K1ExtractMeta(rawHTML, "og:title"), wave3K1CleanText(extractTitleLinearQuick(rawHTML))) + if title == "" || wave3K1IsNegativeTitle(title) || wave3K1IsGenericTitle(title) { + return nil + } + + fields := make(map[string]string) + for _, m := range wave3K1RxNLRBField.FindAllStringSubmatch(mainFrag, 10) { + if len(m) >= 3 { + k := strings.TrimSpace(m[1]) + v := wave3K1CleanText(m[2]) + if k != "" && v != "" { + fields[k] = v + } + } + } + if fields["Case Number"] == "" { + if cm := wave3K1RxNLRBCaseNo.FindString(baseURL + " " + mainFrag); cm != "" { + fields["Case Number"] = cm + } + } + + recs, rowsMD, headers, links := wave3K1ExtractTables(mainFrag, baseURL, "nlrb-cases", wave3K1MaxRecords) + seen := make(map[string]bool, len(links)) + for _, l := range links { + seen[l] = true + } + for _, lk := range wave3K1ExtractLinks(mainFrag, baseURL, 25) { + low := strings.ToLower(lk.URL) + if strings.Contains(low, "/case/") || strings.Contains(low, ".pdf") || strings.Contains(low, "/sites/default/files/") { + wave3K1AddLink(&links, seen, lk.URL, baseURL) + if len(rowsMD) == 0 && strings.Contains(low, "/case/") { + recs = append(recs, map[string]any{"source": "nlrb-cases", "title": lk.Text, "url": lk.URL}) + } + } + } + + bodyMD := wave3K1FragToMD(mainFrag, baseURL) + if fields["Case Number"] == "" && len(recs) == 0 && len(strings.Fields(bodyMD)) < 15 { + return nil + } + // Reject generic "Cases" landing page without docket/case rows or case number + if strings.Contains(urlLower, "/cases-decisions/") && fields["Case Number"] == "" && len(recs) == 0 { + return nil + } + + if len(recs) == 0 { + rec := map[string]any{ + "source": "nlrb-cases", + "title": title, + "url": baseURL, + } + if cn := fields["Case Number"]; cn != "" { + rec["caseNumber"] = cn + } + if df := fields["Date Filed"]; df != "" { + rec["dateFiled"] = df + } + if st := fields["Status"]; st != "" { + rec["status"] = st + } + if loc := fields["Location"]; loc != "" { + rec["location"] = loc + } + if reg := fields["Region Assigned"]; reg != "" { + rec["region"] = reg + } + recs = append(recs, rec) + } + capped, totalPtr, retPtr, truncPtr := wave3K1CapRecords(recs, len(recs)) + + var md strings.Builder + md.WriteString("# ") + md.WriteString(title) + md.WriteString("\n\n- **Agency**: National Labor Relations Board (NLRB)\n") + for _, k := range []string{"Case Number", "Date Filed", "Status", "Location", "Region Assigned"} { + if v := fields[k]; v != "" { + md.WriteString("- **") + md.WriteString(k) + md.WriteString("**: ") + if k == "Case Number" { + md.WriteByte('`') + md.WriteString(v) + md.WriteByte('`') + } else { + md.WriteString(v) + } + md.WriteByte('\n') + } + } + if len(rowsMD) > 0 && len(headers) >= 2 { + md.WriteString("\n## Docket & Case Table\n\n| ") + for _, h := range headers { + md.WriteString(wave3K1MDCell(h)) + md.WriteString(" | ") + } + md.WriteString("\n|") + for range headers { + md.WriteString("---|") + } + md.WriteByte('\n') + for _, row := range rowsMD { + md.WriteString("| ") + for i := range headers { + val := "-" + if i < len(row) && row[i] != "" { + val = row[i] + } + md.WriteString(wave3K1MDCell(val)) + md.WriteString(" | ") + } + md.WriteByte('\n') + } + } + if bodyMD != "" { + md.WriteString("\n") + md.WriteString(bodyMD) + md.WriteByte('\n') + } + + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: wave3K1ExtractMeta(rawHTML, "description"), + PublishedTime: fields["Date Filed"], + Markdown: md.String(), + Links: links, + Records: capped, + Total: totalPtr, + Returned: retPtr, + Truncated: truncPtr, + } +} + +// ── #282 EEOC Litigation HTML ──────────────────────────────────────────────────────────────────── + +func wave3K1ExtractEEOCHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + mainFrag := wave3K1MainRegion(rawHTML) + if art, okA := findElementInnerLinearDeclHTML(mainFrag, "article", nil, 0); okA && art != "" { + mainFrag = art + } + h1 := wave3K1FirstNonEmpty(wave3K1ExtractH1(mainFrag), wave3K1ExtractH1(rawHTML)) + title := wave3K1FirstNonEmpty(h1, wave3K1ExtractMeta(rawHTML, "og:title"), wave3K1CleanText(extractTitleLinearQuick(rawHTML))) + if title == "" || wave3K1IsNegativeTitle(title) || wave3K1IsGenericTitle(title) { + return nil + } + + subHead := wave3K1CleanText(wave3K1ExtractByClassSub(mainFrag, "div", "press-release__site-subheading")) + pubDate := wave3K1RxDateLike.FindString(subHead) + if pubDate == "" { + pubDate = wave3K1RxDateLike.FindString(wave3K1CleanText(mainFrag)) + } + bodyMD := wave3K1FragToMD(mainFrag, baseURL) + if len(strings.Fields(bodyMD)) < 12 { + return nil + } + settlement := wave3K1RxMoney.FindString(title + " " + bodyMD) + + var links []string + seen := make(map[string]bool) + var recs []map[string]any + for _, lk := range wave3K1ExtractLinks(mainFrag, baseURL, 25) { + wave3K1AddLink(&links, seen, lk.URL, baseURL) + low := strings.ToLower(lk.URL) + if strings.Contains(low, "/newsroom/") && len(lk.Text) >= 12 { + recs = append(recs, map[string]any{"source": "eeoc-litigation", "title": lk.Text, "url": lk.URL}) + } + } + if len(recs) == 0 { + rec := map[string]any{ + "source": "eeoc-litigation", + "title": title, + "url": baseURL, + } + if pubDate != "" { + rec["date"] = pubDate + } + if settlement != "" { + rec["monetaryRelief"] = settlement + } + recs = append(recs, rec) + } + capped, totalPtr, retPtr, truncPtr := wave3K1CapRecords(recs, len(recs)) + + var md strings.Builder + md.WriteString("# ") + md.WriteString(title) + md.WriteString("\n\n- **Agency**: U.S. Equal Employment Opportunity Commission (EEOC)\n") + if pubDate != "" { + md.WriteString("- **Date**: ") + md.WriteString(pubDate) + md.WriteByte('\n') + } + if settlement != "" { + md.WriteString("- **Monetary Relief / Amount**: ") + md.WriteString(settlement) + md.WriteByte('\n') + } + md.WriteString("\n") + md.WriteString(bodyMD) + md.WriteByte('\n') + + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: wave3K1ExtractMeta(rawHTML, "description"), + PublishedTime: pubDate, + Markdown: md.String(), + Links: links, + Records: capped, + Total: totalPtr, + Returned: retPtr, + Truncated: truncPtr, + } +} + +// ── #283 FTC Cases & Proceedings HTML ──────────────────────────────────────────────────────────── + +func wave3K1ExtractFTCHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + mainFrag := wave3K1MainRegion(rawHTML) + h1 := wave3K1FirstNonEmpty(wave3K1ExtractH1(mainFrag), wave3K1ExtractH1(rawHTML)) + title := wave3K1FirstNonEmpty(h1, wave3K1ExtractMeta(rawHTML, "og:title"), wave3K1CleanText(extractTitleLinearQuick(rawHTML))) + if title == "" || wave3K1IsNegativeTitle(title) || wave3K1IsGenericTitle(title) { + return nil + } + + matterNum := "" + if mm := wave3K1RxFTCMatter.FindStringSubmatch(mainFrag); len(mm) >= 2 { + matterNum = wave3K1CleanText(mm[1]) + } + pubDate := wave3K1RxDateLike.FindString(wave3K1CleanText(wave3K1FirstNonEmpty( + wave3K1ExtractByClassSub(mainFrag, "div", "field--name-field-date"), + wave3K1ExtractByClassSub(mainFrag, "div", "field--name-field-last-updated"), + mainFrag, + ))) + + var links []string + seen := make(map[string]bool) + var recs []map[string]any + for _, lk := range wave3K1ExtractLinks(mainFrag, baseURL, 30) { + wave3K1AddLink(&links, seen, lk.URL, baseURL) + low := strings.ToLower(lk.URL) + if (strings.Contains(low, "/legal-library/browse/") || strings.Contains(low, ".pdf")) && len(lk.Text) >= 8 { + recs = append(recs, map[string]any{ + "source": "ftc-cases", + "title": lk.Text, + "url": lk.URL, + }) + } + } + + bodyMD := wave3K1FragToMD(mainFrag, baseURL) + if len(recs) == 0 && len(strings.Fields(bodyMD)) < 12 { + return nil + } + if len(recs) == 0 { + rec := map[string]any{"source": "ftc-cases", "title": title, "url": baseURL} + if matterNum != "" { + rec["matterNumber"] = matterNum + } + if pubDate != "" { + rec["date"] = pubDate + } + recs = append(recs, rec) + } + capped, totalPtr, retPtr, truncPtr := wave3K1CapRecords(recs, len(recs)) + + var md strings.Builder + md.WriteString("# ") + md.WriteString(title) + md.WriteString("\n\n- **Agency**: Federal Trade Commission (FTC)\n") + if matterNum != "" { + md.WriteString("- **Matter / Docket Number**: `") + md.WriteString(matterNum) + md.WriteString("`\n") + } + if pubDate != "" { + md.WriteString("- **Date**: ") + md.WriteString(pubDate) + md.WriteByte('\n') + } + md.WriteString("\n") + md.WriteString(bodyMD) + md.WriteByte('\n') + + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: wave3K1ExtractMeta(rawHTML, "description"), + PublishedTime: pubDate, + Markdown: md.String(), + Links: links, + Records: capped, + Total: totalPtr, + Returned: retPtr, + Truncated: truncPtr, + } +} + +// ── #284 FCC ECFS JSON & HTML ──────────────────────────────────────────────────────────────────── + +func wave3K1FormatFCCECFSJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + var rawFilings []any + totalCount := 0 + if obj := wave3K1Map(parsed); obj != nil { + if wave3K1IsGenericJSONError(obj) { + return nil, false + } + if f := wave3K1Slice(obj["filing"]); f != nil { + rawFilings = f + } else if f := wave3K1Slice(obj["filings"]); f != nil { + rawFilings = f + } else if obj["id_submission"] != nil { + rawFilings = []any{obj} + } + if agg := wave3K1Map(obj["aggregations"]); agg != nil { + if t, ok := wave3K1FloatVal(agg["total"]); ok && t > 0 { + totalCount = int(t) + } + } + if totalCount == 0 { + if t, ok := wave3K1FloatVal(obj["total"]); ok && t > 0 { + totalCount = int(t) + } + } + } else if arr := wave3K1Slice(parsed); arr != nil { + rawFilings = arr + } + if len(rawFilings) == 0 { + return nil, false + } + + var recs []map[string]any + var links []string + seen := make(map[string]bool) + var latestDate string + + for _, el := range rawFilings { + m := wave3K1Map(el) + if m == nil { + continue + } + subID := wave3K1Plain(m["id_submission"], 48) + if subID == "" { + continue + } + subType := "" + if st := wave3K1Map(m["submissiontype"]); st != nil { + subType = wave3K1Plain(wave3K1FirstNonEmpty(wave3K1StringVal(st["description"]), wave3K1StringVal(st["short"])), 64) + } + status := "" + if fs := wave3K1Map(m["filingstatus"]); fs != nil { + status = wave3K1Plain(fs["description"], 48) + } + var filerNames []string + for _, fl := range wave3K1Slice(m["filers"]) { + if fm := wave3K1Map(fl); fm != nil { + if n := wave3K1Plain(fm["name"], 100); n != "" { + filerNames = append(filerNames, n) + } + } + } + var procNames []string + var procDesc string + var bureau string + for _, pr := range wave3K1Slice(m["proceedings"]) { + if pm := wave3K1Map(pr); pm != nil { + if pn := wave3K1Plain(pm["name"], 32); pn != "" { + procNames = append(procNames, pn) + } + if procDesc == "" { + procDesc = wave3K1Plain(wave3K1FirstNonEmpty(wave3K1StringVal(pm["description_display"]), wave3K1StringVal(pm["description"])), 200) + } + if bureau == "" { + bureau = wave3K1Plain(pm["bureau_name"], 80) + } + } + } + dateStr := wave3K1PickISODate(wave3K1FirstNonEmpty( + wave3K1StringVal(m["date_disseminated"]), + wave3K1StringVal(m["date_submission"]), + wave3K1StringVal(m["date_received"]), + )) + if dateStr != "" && dateStr > latestDate { + latestDate = dateStr + } + textExcerpt := wave3K1Plain(m["text_data"], 220) + for _, dm := range wave3K1Slice(m["documents"]) { + if docObj := wave3K1Map(dm); docObj != nil { + wave3K1AddLink(&links, seen, wave3K1StringVal(docObj["src"]), "https://www.fcc.gov") + } + } + filingURL := "https://www.fcc.gov/ecfs/filing/" + url.PathEscape(subID) + wave3K1AddLink(&links, seen, filingURL, "") + + rec := map[string]any{ + "source": "fcc-ecfs", + "submissionId": subID, + "url": filingURL, + } + if subType != "" { + rec["submissionType"] = subType + } + if status != "" { + rec["status"] = status + } + if len(filerNames) > 0 { + rec["filers"] = strings.Join(filerNames, "; ") + } + if len(procNames) > 0 { + rec["proceedings"] = strings.Join(procNames, ", ") + } + if bureau != "" { + rec["bureau"] = bureau + } + if dateStr != "" { + rec["date"] = dateStr + } + if textExcerpt != "" { + rec["excerpt"] = textExcerpt + } + recs = append(recs, rec) + } + if len(recs) == 0 { + return nil, false + } + if totalCount < len(recs) { + totalCount = len(recs) + } + capped, totalPtr, retPtr, truncPtr := wave3K1CapRecords(recs, totalCount) + + title := "FCC ECFS Filings" + if p := wave3K1StringVal(capped[0]["proceedings"]); p != "" { + title += " — Docket " + p + } + var md strings.Builder + md.WriteString("# ") + md.WriteString(title) + md.WriteString("\n\n- **Source**: FCC Electronic Comment Filing System (`publicapi.fcc.gov`)\n") + if latestDate != "" { + md.WriteString("- **Latest Disseminated Date**: ") + md.WriteString(latestDate) + md.WriteByte('\n') + } + md.WriteString("\n| Submission ID | Type | Proceeding(s) | Filer(s) | Date | Excerpt |\n|---|---|---|---|---|---|\n") + for _, r := range capped { + md.WriteString("| `") + md.WriteString(wave3K1MDCell(wave3K1StringVal(r["submissionId"]))) + md.WriteString("` | ") + md.WriteString(wave3K1MDCell(wave3K1FirstNonEmpty(wave3K1StringVal(r["submissionType"]), "-"))) + md.WriteString(" | ") + md.WriteString(wave3K1MDCell(wave3K1FirstNonEmpty(wave3K1StringVal(r["proceedings"]), "-"))) + md.WriteString(" | ") + md.WriteString(wave3K1MDCell(wave3K1FirstNonEmpty(wave3K1StringVal(r["filers"]), "-"))) + md.WriteString(" | ") + md.WriteString(wave3K1MDCell(wave3K1FirstNonEmpty(wave3K1StringVal(r["date"]), "-"))) + md.WriteString(" | ") + md.WriteString(wave3K1MDCell(wave3K1FirstNonEmpty(wave3K1StringVal(r["excerpt"]), "-"))) + md.WriteString(" |\n") + } + + return &DeclarativeFormattedDoc{ + Title: title, + Description: "FCC ECFS public filings (" + strconv.Itoa(len(capped)) + " shown).", + PublishedTime: latestDate, + Markdown: md.String(), + Links: links, + Records: capped, + Total: totalPtr, + Returned: retPtr, + Truncated: truncPtr, + }, true +} + +func wave3K1ExtractFCCECFSHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + h1 := wave3K1ExtractH1(rawHTML) + title := wave3K1FirstNonEmpty(h1, wave3K1ExtractMeta(rawHTML, "og:title"), wave3K1CleanText(extractTitleLinearQuick(rawHTML))) + if title == "" || wave3K1IsNegativeTitle(title) || wave3K1IsGenericTitle(title) { + return nil + } + mainFrag := wave3K1MainRegion(rawHTML) + recs, rowsMD, headers, links := wave3K1ExtractTables(mainFrag, baseURL, "fcc-ecfs", wave3K1MaxRecords) + bodyMD := wave3K1FragToMD(mainFrag, baseURL) + if len(recs) == 0 && len(strings.Fields(bodyMD)) < 15 { + return nil + } + if len(recs) == 0 { + recs = append(recs, map[string]any{"source": "fcc-ecfs", "title": title, "url": baseURL}) + } + capped, totalPtr, retPtr, truncPtr := wave3K1CapRecords(recs, len(recs)) + var md strings.Builder + md.WriteString("# ") + md.WriteString(title) + md.WriteString("\n\n- **System**: FCC Electronic Comment Filing System (ECFS)\n") + if len(rowsMD) > 0 && len(headers) >= 2 { + md.WriteString("\n| ") + for _, h := range headers { + md.WriteString(wave3K1MDCell(h)) + md.WriteString(" | ") + } + md.WriteString("\n|") + for range headers { + md.WriteString("---|") + } + md.WriteByte('\n') + for _, row := range rowsMD { + md.WriteString("| ") + for i := range headers { + val := "-" + if i < len(row) && row[i] != "" { + val = row[i] + } + md.WriteString(wave3K1MDCell(val)) + md.WriteString(" | ") + } + md.WriteByte('\n') + } + } + if bodyMD != "" { + md.WriteString("\n") + md.WriteString(bodyMD) + md.WriteByte('\n') + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: wave3K1ExtractMeta(rawHTML, "description"), + Markdown: md.String(), + Links: links, + Records: capped, + Total: totalPtr, + Returned: retPtr, + Truncated: truncPtr, + } +} + +// ── #285 FCC ULS JSON & HTML ───────────────────────────────────────────────────────────────────── + +func wave3K1FormatFCCULSJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + var recs []map[string]any + var links []string + seen := make(map[string]bool) + totalCount := 0 + var latestDate string + title := "FCC ULS Licensing Records" + + // Format 1: Socrata ULS row array (`opendata.fcc.gov/resource/*.json`) + if arr := wave3K1Slice(parsed); arr != nil { + if len(arr) == 0 { + return nil, false + } + for _, el := range arr { + m := wave3K1Map(el) + if m == nil { + continue + } + callSign := wave3K1Plain(wave3K1FirstNonEmpty(wave3K1StringVal(m["u_call_sign"]), wave3K1StringVal(m["call_sign"]), wave3K1StringVal(m["callsign"])), 32) + licName := wave3K1Plain(wave3K1FirstNonEmpty(wave3K1StringVal(m["u_license_name"]), wave3K1StringVal(m["license_name"]), wave3K1StringVal(m["lic_name"]), wave3K1StringVal(m["entity_name"])), 140) + frn := wave3K1Plain(wave3K1FirstNonEmpty(wave3K1StringVal(m["u_frns"]), wave3K1StringVal(m["frn"])), 32) + status := wave3K1Plain(wave3K1FirstNonEmpty(wave3K1StringVal(m["u_application_status"]), wave3K1StringVal(m["status_desc"]), wave3K1StringVal(m["license_status"])), 48) + city := wave3K1Plain(wave3K1FirstNonEmpty(wave3K1StringVal(m["u_location_city"]), wave3K1StringVal(m["city"])), 64) + state := wave3K1Plain(wave3K1FirstNonEmpty(wave3K1StringVal(m["u_location_state"]), wave3K1StringVal(m["state"])), 16) + dateStr := wave3K1PickISODate(wave3K1FirstNonEmpty(wave3K1StringVal(m["u_status_date"]), wave3K1StringVal(m["grant_date"]), wave3K1StringVal(m["expired_date"]))) + if dateStr != "" && dateStr > latestDate { + latestDate = dateStr + } + if callSign == "" && licName == "" && frn == "" { + continue + } + rec := map[string]any{"source": "fcc-uls"} + if callSign != "" { + rec["callSign"] = callSign + } + if licName != "" { + rec["licensee"] = licName + } + if frn != "" { + rec["frn"] = frn + } + if status != "" { + rec["status"] = status + } + if city != "" || state != "" { + rec["location"] = strings.Trim(city+", "+state, ", ") + } + if dateStr != "" { + rec["date"] = dateStr + } + recs = append(recs, rec) + } + } else if obj := wave3K1Map(parsed); obj != nil { + if wave3K1IsGenericJSONError(obj) { + return nil, false + } + // Format 2a: Legacy data.fcc.gov License View (`Licenses.License[]`) + if licsObj := wave3K1Map(obj["Licenses"]); licsObj != nil { + if t, ok := wave3K1FloatVal(licsObj["totalRows"]); ok && t > 0 { + totalCount = int(t) + } + licArr := wave3K1Slice(licsObj["License"]) + if len(licArr) == 0 { + if single := wave3K1Map(licsObj["License"]); single != nil { + licArr = []any{single} + } + } + for _, el := range licArr { + m := wave3K1Map(el) + if m == nil { + continue + } + callSign := wave3K1Plain(m["callsign"], 32) + licName := wave3K1Plain(m["licName"], 140) + frn := wave3K1Plain(m["frn"], 32) + service := wave3K1Plain(m["serviceDesc"], 80) + status := wave3K1Plain(m["statusDesc"], 48) + expDate := wave3K1Plain(m["expiredDate"], 32) + detailURL := SanitizeSchemaHTTPSURL(wave3K1StringVal(m["licDetailURL"]), "https://wireless2.fcc.gov") + if detailURL != "" { + wave3K1AddLink(&links, seen, detailURL, "") + } + if callSign == "" && licName == "" { + continue + } + rec := map[string]any{ + "source": "fcc-uls", + "callSign": callSign, + "licensee": licName, + } + if frn != "" { + rec["frn"] = frn + } + if service != "" { + rec["service"] = service + } + if status != "" { + rec["status"] = status + } + if expDate != "" { + rec["expiredDate"] = expDate + } + if detailURL != "" { + rec["url"] = detailURL + } + recs = append(recs, rec) + } + } else if results := wave3K1Slice(obj["results"]); results != nil { + // Format 2b: Socrata Catalog API (`/api/catalog/v1`) + title = "FCC Open Data Catalog (ULS)" + if rs, ok := wave3K1FloatVal(obj["resultSetSize"]); ok && rs > 0 { + totalCount = int(rs) + } + for _, el := range results { + m := wave3K1Map(el) + if m == nil { + continue + } + resObj := wave3K1Map(m["resource"]) + if resObj == nil { + continue + } + id := wave3K1Plain(resObj["id"], 24) + name := wave3K1Plain(resObj["name"], 160) + desc := wave3K1Plain(resObj["description"], 200) + upd := wave3K1PickISODate(wave3K1StringVal(resObj["updatedAt"])) + if upd != "" && upd > latestDate { + latestDate = upd + } + dsURL := SanitizeSchemaHTTPSURL(wave3K1StringVal(m["link"]), "https://opendata.fcc.gov") + if dsURL == "" && id != "" { + dsURL = "https://opendata.fcc.gov/resource/" + id + ".json" + } + if dsURL != "" { + wave3K1AddLink(&links, seen, dsURL, "") + } + if id == "" && name == "" { + continue + } + recs = append(recs, map[string]any{ + "source": "fcc-uls", + "datasetId": id, + "name": name, + "description": desc, + "updatedAt": upd, + "url": dsURL, + }) + } + } else if viewID := wave3K1Plain(obj["id"], 24); viewID != "" && wave3K1Plain(obj["name"], 160) != "" { + // Format 2c: Socrata View Metadata (`/api/views/.json`) + name := wave3K1Plain(obj["name"], 160) + title = name + " (FCC Open Data)" + desc := wave3K1Plain(obj["description"], 300) + for _, col := range wave3K1Slice(obj["columns"]) { + if cm := wave3K1Map(col); cm != nil { + fn := wave3K1Plain(cm["fieldName"], 64) + if fn == "" || strings.HasPrefix(fn, ":@") { + continue + } + recs = append(recs, map[string]any{ + "source": "fcc-uls", + "datasetId": viewID, + "fieldName": fn, + "dataType": wave3K1Plain(cm["dataTypeName"], 32), + }) + } + } + if len(recs) == 0 { + recs = append(recs, map[string]any{"source": "fcc-uls", "datasetId": viewID, "name": name, "description": desc}) + } + } + } + + if len(recs) == 0 { + return nil, false + } + if totalCount < len(recs) { + totalCount = len(recs) + } + capped, totalPtr, retPtr, truncPtr := wave3K1CapRecords(recs, totalCount) + + var md strings.Builder + md.WriteString("# ") + md.WriteString(title) + md.WriteString("\n\n- **Source**: FCC Universal Licensing System / Open Data (`") + md.WriteString(wave3K1FirstNonEmpty(wave3K1HostFromURL(origURL), "opendata.fcc.gov")) + md.WriteString("`)\n") + if latestDate != "" { + md.WriteString("- **Latest Date**: ") + md.WriteString(latestDate) + md.WriteByte('\n') + } + md.WriteByte('\n') + if _, isCatalog := capped[0]["datasetId"]; isCatalog { + md.WriteString("| ID | Name / Field | Detail | URL |\n|---|---|---|---|\n") + for _, r := range capped { + md.WriteString("| `") + md.WriteString(wave3K1MDCell(wave3K1StringVal(r["datasetId"]))) + md.WriteString("` | ") + md.WriteString(wave3K1MDCell(wave3K1FirstNonEmpty(wave3K1StringVal(r["name"]), wave3K1StringVal(r["fieldName"]), "-"))) + md.WriteString(" | ") + md.WriteString(wave3K1MDCell(wave3K1FirstNonEmpty(wave3K1StringVal(r["dataType"]), wave3K1StringVal(r["description"]), "-"))) + md.WriteString(" | ") + md.WriteString(wave3K1MDCell(wave3K1FirstNonEmpty(wave3K1StringVal(r["url"]), "-"))) + md.WriteString(" |\n") + } + } else { + md.WriteString("| Call Sign | Licensee | FRN | Status | Service / Location |\n|---|---|---|---|---|\n") + for _, r := range capped { + md.WriteString("| `") + md.WriteString(wave3K1MDCell(wave3K1FirstNonEmpty(wave3K1StringVal(r["callSign"]), "-"))) + md.WriteString("` | ") + md.WriteString(wave3K1MDCell(wave3K1FirstNonEmpty(wave3K1StringVal(r["licensee"]), "-"))) + md.WriteString(" | ") + md.WriteString(wave3K1MDCell(wave3K1FirstNonEmpty(wave3K1StringVal(r["frn"]), "-"))) + md.WriteString(" | ") + md.WriteString(wave3K1MDCell(wave3K1FirstNonEmpty(wave3K1StringVal(r["status"]), "-"))) + md.WriteString(" | ") + md.WriteString(wave3K1MDCell(wave3K1FirstNonEmpty(wave3K1StringVal(r["service"]), wave3K1StringVal(r["location"]), "-"))) + md.WriteString(" |\n") + } + } + + return &DeclarativeFormattedDoc{ + Title: title, + Description: "FCC ULS licensing & dataset records (" + strconv.Itoa(len(capped)) + " shown).", + PublishedTime: latestDate, + Markdown: md.String(), + Links: links, + Records: capped, + Total: totalPtr, + Returned: retPtr, + Truncated: truncPtr, + }, true +} + +func wave3K1ExtractFCCULSHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + h1 := wave3K1ExtractH1(rawHTML) + title := wave3K1FirstNonEmpty(h1, wave3K1ExtractMeta(rawHTML, "og:title"), wave3K1CleanText(extractTitleLinearQuick(rawHTML))) + if title == "" || wave3K1IsNegativeTitle(title) || wave3K1IsGenericTitle(title) { + return nil + } + mainFrag := wave3K1MainRegion(rawHTML) + recs, rowsMD, headers, links := wave3K1ExtractTables(mainFrag, baseURL, "fcc-uls", wave3K1MaxRecords) + bodyMD := wave3K1FragToMD(mainFrag, baseURL) + callSign := wave3K1RxCallSign.FindString(title + " " + bodyMD) + if len(recs) == 0 && len(strings.Fields(bodyMD)) < 12 { + return nil + } + if len(recs) == 0 { + rec := map[string]any{"source": "fcc-uls", "title": title, "url": baseURL} + if callSign != "" { + rec["callSign"] = callSign + } + recs = append(recs, rec) + } + capped, totalPtr, retPtr, truncPtr := wave3K1CapRecords(recs, len(recs)) + var md strings.Builder + md.WriteString("# ") + md.WriteString(title) + md.WriteString("\n\n- **System**: FCC Universal Licensing System (ULS)\n") + if callSign != "" { + md.WriteString("- **Call Sign**: `") + md.WriteString(callSign) + md.WriteString("`\n") + } + if len(rowsMD) > 0 && len(headers) >= 2 { + md.WriteString("\n| ") + for _, h := range headers { + md.WriteString(wave3K1MDCell(h)) + md.WriteString(" | ") + } + md.WriteString("\n|") + for range headers { + md.WriteString("---|") + } + md.WriteByte('\n') + for _, row := range rowsMD { + md.WriteString("| ") + for i := range headers { + val := "-" + if i < len(row) && row[i] != "" { + val = row[i] + } + md.WriteString(wave3K1MDCell(val)) + md.WriteString(" | ") + } + md.WriteByte('\n') + } + } + if bodyMD != "" { + md.WriteString("\n") + md.WriteString(bodyMD) + md.WriteByte('\n') + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: wave3K1ExtractMeta(rawHTML, "description"), + Markdown: md.String(), + Links: links, + Records: capped, + Total: totalPtr, + Returned: retPtr, + Truncated: truncPtr, + } +} + +// ── #286 FERC eLibrary & NRC ADAMS Dockets HTML ────────────────────────────────────────────────── + +func wave3K1ExtractFERCNRCHTML(rawHTML, baseURL, urlLower, extractorID string) *DeclarativePostFetchResult { + h1 := wave3K1ExtractH1(rawHTML) + title := wave3K1FirstNonEmpty(h1, wave3K1ExtractMeta(rawHTML, "og:title"), wave3K1CleanText(extractTitleLinearQuick(rawHTML))) + if title == "" || wave3K1IsNegativeTitle(title) || wave3K1IsGenericTitle(title) { + return nil + } + agency := "NRC ADAMS" + if strings.Contains(urlLower, "ferc.gov") || strings.Contains(strings.ToLower(title), "ferc") || strings.Contains(strings.ToLower(title), "elibrary") { + agency = "FERC eLibrary" + } + mainFrag := wave3K1MainRegion(rawHTML) + recs, rowsMD, headers, links := wave3K1ExtractTables(mainFrag, baseURL, "ferc-nrc-dockets", wave3K1MaxRecords) + seen := make(map[string]bool, len(links)) + for _, l := range links { + seen[l] = true + } + for _, lk := range wave3K1ExtractLinks(mainFrag, baseURL, 25) { + wave3K1AddLink(&links, seen, lk.URL, baseURL) + } + bodyMD := wave3K1FragToMD(mainFrag, baseURL) + if len(recs) == 0 && len(strings.Fields(bodyMD)) < 12 { + return nil + } + accNo := wave3K1RxAccession.FindString(title + " " + bodyMD) + if len(recs) == 0 { + rec := map[string]any{ + "source": "ferc-nrc-dockets", + "agency": agency, + "title": title, + "url": baseURL, + } + if accNo != "" { + rec["accessionNumber"] = accNo + } + recs = append(recs, rec) + } + capped, totalPtr, retPtr, truncPtr := wave3K1CapRecords(recs, len(recs)) + var md strings.Builder + md.WriteString("# ") + md.WriteString(title) + md.WriteString("\n\n- **Agency / System**: ") + md.WriteString(agency) + md.WriteByte('\n') + if accNo != "" { + md.WriteString("- **Accession Number**: `") + md.WriteString(accNo) + md.WriteString("`\n") + } + if len(rowsMD) > 0 && len(headers) >= 2 { + md.WriteString("\n## Docket & Document Table\n\n| ") + for _, h := range headers { + md.WriteString(wave3K1MDCell(h)) + md.WriteString(" | ") + } + md.WriteString("\n|") + for range headers { + md.WriteString("---|") + } + md.WriteByte('\n') + for _, row := range rowsMD { + md.WriteString("| ") + for i := range headers { + val := "-" + if i < len(row) && row[i] != "" { + val = row[i] + } + md.WriteString(wave3K1MDCell(val)) + md.WriteString(" | ") + } + md.WriteByte('\n') + } + } + if bodyMD != "" { + md.WriteString("\n") + md.WriteString(bodyMD) + md.WriteByte('\n') + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: wave3K1ExtractMeta(rawHTML, "description"), + Markdown: md.String(), + Links: links, + Records: capped, + Total: totalPtr, + Returned: retPtr, + Truncated: truncPtr, + } +} + +// ── #287 CFTC, OCC & FinCEN Enforcement HTML ───────────────────────────────────────────────────── + +func wave3K1ExtractFinRegHTML(rawHTML, baseURL, urlLower, extractorID string) *DeclarativePostFetchResult { + mainFrag := wave3K1MainRegion(rawHTML) + agency := "Financial Regulator" + switch { + case strings.Contains(urlLower, "cftc.gov"): + agency = "Commodity Futures Trading Commission (CFTC)" + case strings.Contains(urlLower, "occ.gov"): + agency = "Office of the Comptroller of the Currency (OCC)" + case strings.Contains(urlLower, "fincen.gov"): + agency = "Financial Crimes Enforcement Network (FinCEN)" + } + + h1 := wave3K1FirstNonEmpty(wave3K1ExtractH1(mainFrag), wave3K1ExtractH1(rawHTML)) + ogTitle := wave3K1ExtractMeta(rawHTML, "og:title") + rawTitle := wave3K1CleanText(extractTitleLinearQuick(rawHTML)) + // On CFTC, the first

is "Release Number 9331-26" and the headline is in

...

or . + releaseNum := "" + if rm := wave3K1RxReleaseNum.FindStringSubmatch(h1 + " " + wave3K1CleanText(mainFrag[:minIntReg(len(mainFrag), 2048)])); len(rm) >= 2 { + releaseNum = strings.TrimSpace(rm[1]) + } + title := wave3K1FirstNonEmpty(ogTitle, rawTitle, h1) + if strings.HasPrefix(strings.ToLower(h1), "release number") && rawTitle != "" { + title = rawTitle + } else if h1 != "" && !strings.HasPrefix(strings.ToLower(h1), "release number") { + title = h1 + } + if title == "" || wave3K1IsNegativeTitle(title) || wave3K1IsGenericTitle(title) { + return nil + } + + pubDate := wave3K1RxDateLike.FindString(wave3K1CleanText(mainFrag[:minIntReg(len(mainFrag), 4096)])) + bodyMD := wave3K1FragToMD(mainFrag, baseURL) + if len(strings.Fields(bodyMD)) < 10 { + return nil + } + + var links []string + seen := make(map[string]bool) + var recs []map[string]any + for _, lk := range wave3K1ExtractLinks(mainFrag, baseURL, 25) { + wave3K1AddLink(&links, seen, lk.URL, baseURL) + low := strings.ToLower(lk.URL) + if (strings.Contains(low, "/pressroom/") || strings.Contains(low, "/news-issuances/") || strings.Contains(low, "/news/") || strings.Contains(low, ".pdf")) && len(lk.Text) >= 10 { + recs = append(recs, map[string]any{ + "source": "financial-regulators-enforcement", + "agency": agency, + "title": lk.Text, + "url": lk.URL, + }) + } + } + if len(recs) == 0 { + rec := map[string]any{ + "source": "financial-regulators-enforcement", + "agency": agency, + "title": title, + "url": baseURL, + } + if releaseNum != "" { + rec["releaseNumber"] = releaseNum + } + if pubDate != "" { + rec["date"] = pubDate + } + recs = append(recs, rec) + } + capped, totalPtr, retPtr, truncPtr := wave3K1CapRecords(recs, len(recs)) + + var md strings.Builder + md.WriteString("# ") + md.WriteString(title) + md.WriteString("\n\n- **Agency**: ") + md.WriteString(agency) + md.WriteByte('\n') + if releaseNum != "" { + md.WriteString("- **Release / Bulletin**: `") + md.WriteString(releaseNum) + md.WriteString("`\n") + } + if pubDate != "" { + md.WriteString("- **Date**: ") + md.WriteString(pubDate) + md.WriteByte('\n') + } + md.WriteString("\n") + md.WriteString(bodyMD) + md.WriteByte('\n') + + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: wave3K1ExtractMeta(rawHTML, "description"), + PublishedTime: pubDate, + Markdown: md.String(), + Links: links, + Records: capped, + Total: totalPtr, + Returned: retPtr, + Truncated: truncPtr, + } +} + +func minIntReg(a, b int) int { + if a < b { + return a + } + return b +} + +// ── #288 Oversight.gov IG Reports HTML ─────────────────────────────────────────────────────────── + +func wave3K1ExtractOversightHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + h1 := wave3K1ExtractH1(rawHTML) + title := wave3K1FirstNonEmpty(h1, wave3K1ExtractMeta(rawHTML, "og:title"), wave3K1CleanText(extractTitleLinearQuick(rawHTML))) + if title == "" || wave3K1IsNegativeTitle(title) || wave3K1IsGenericTitle(title) { + return nil + } + mainFrag := wave3K1MainRegion(rawHTML) + recs, rowsMD, headers, links := wave3K1ExtractTables(mainFrag, baseURL, "oversight-gov", wave3K1MaxRecords) + seen := make(map[string]bool, len(links)) + for _, l := range links { + seen[l] = true + } + for _, lk := range wave3K1ExtractLinks(mainFrag, baseURL, 25) { + wave3K1AddLink(&links, seen, lk.URL, baseURL) + low := strings.ToLower(lk.URL) + if len(rowsMD) == 0 && (strings.Contains(low, "/report") || strings.Contains(low, ".pdf")) && len(lk.Text) >= 10 { + recs = append(recs, map[string]any{ + "source": "oversight-gov", + "title": lk.Text, + "url": lk.URL, + }) + } + } + bodyMD := wave3K1FragToMD(mainFrag, baseURL) + if len(recs) == 0 && len(strings.Fields(bodyMD)) < 12 { + return nil + } + pubDate := wave3K1RxDateLike.FindString(wave3K1CleanText(mainFrag[:minIntReg(len(mainFrag), 4096)])) + if len(recs) == 0 { + rec := map[string]any{"source": "oversight-gov", "title": title, "url": baseURL} + if pubDate != "" { + rec["date"] = pubDate + } + recs = append(recs, rec) + } + capped, totalPtr, retPtr, truncPtr := wave3K1CapRecords(recs, len(recs)) + + var md strings.Builder + md.WriteString("# ") + md.WriteString(title) + md.WriteString("\n\n- **Source**: Oversight.gov (CIGIE Inspector General Reports)\n") + if pubDate != "" { + md.WriteString("- **Date**: ") + md.WriteString(pubDate) + md.WriteByte('\n') + } + if len(rowsMD) > 0 && len(headers) >= 2 { + md.WriteString("\n## Reports\n\n| ") + for _, h := range headers { + md.WriteString(wave3K1MDCell(h)) + md.WriteString(" | ") + } + md.WriteString("\n|") + for range headers { + md.WriteString("---|") + } + md.WriteByte('\n') + for _, row := range rowsMD { + md.WriteString("| ") + for i := range headers { + val := "-" + if i < len(row) && row[i] != "" { + val = row[i] + } + md.WriteString(wave3K1MDCell(val)) + md.WriteString(" | ") + } + md.WriteByte('\n') + } + } + if bodyMD != "" { + md.WriteString("\n") + md.WriteString(bodyMD) + md.WriteByte('\n') + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: wave3K1ExtractMeta(rawHTML, "description"), + PublishedTime: pubDate, + Markdown: md.String(), + Links: links, + Records: capped, + Total: totalPtr, + Returned: retPtr, + Truncated: truncPtr, + } +} diff --git a/internal/extract/wave3_regulators_health.go b/internal/extract/wave3_regulators_health.go new file mode 100644 index 0000000..eb00730 --- /dev/null +++ b/internal/extract/wave3_regulators_health.go @@ -0,0 +1,3237 @@ +package extract + +import ( + "bytes" + "encoding/csv" + "encoding/json" + "fmt" + stdhtml "html" + "io" + "math" + "net/url" + "sort" + "strconv" + "strings" +) + +const ( + wave3K2MaxHTMLBytes = 2 * 1024 * 1024 + wave3K2MaxJSONBytes = 4 * 1024 * 1024 + wave3K2MaxTextBytes = 4 * 1024 * 1024 + wave3K2MaxRecords = 25 + wave3K2MaxHPTLocations = 50 +) + +var ( + wave3K2RxNotFoundTitle = newLazyRegexp(`(?i)(?:^|\b)(?:404|410|406|page\s+not\s+found|not\s+found|not\s+acceptable|error\s*404|we\s+couldn'?t\s+find\s+that\s+page|access\s+denied|request\s+(?:rejected|blocked)|could\s+not\s+be\s+satisfied|unauthorized|attention\s+required|just\s+a\s+moment|403\s+forbidden|forbidden|403\s+error|error\s+403)(?:\b|$)`) + wave3K2RxMaintTitle = newLazyRegexp(`(?i)(?:scheduled\s+maintenance|temporarily\s+unavailable|service\s+unavailable|site\s+maintenance|under\s+maintenance|system\s+maintenance|502\s+bad\s+gateway|503\s+service|down\s+for\s+maintenance)`) + wave3K2RxErrorTitle = newLazyRegexp(`(?i)^(?:(?:(?:401|403|404|406|410|429|500|502|503)\s+)?(?:internal\s+)?server\s+error|application\s+error|system\s+error|unexpected\s+error|error\s+page|(?:401|403|404|406|410|429|500|502|503|http\s+\d{3})\s+error|error\s+(?:401|403|404|406|410|429|500|502|503)|error)(?:\s*[|\-\x{2013}\x{2014}:]\s*.*)?$|^.*(?:\s*[|\-\x{2013}\x{2014}:]\s*error)$`) + wave3K2RxGenericTitle = newLazyRegexp(`(?i)^(?:loading\.{0,3}|home|welcome|search|cms\s+medicaid\s+data|medicaid\.gov|sba\s+small\s+business\s+search|usps\s+developer\s+portal|va\.gov|healthcare\.gov)$`) + wave3K2RxHTMLTag = newLazyRegexp(`<[^>]+>`) + wave3K2RxSpaceCollapse = newLazyRegexp(`[ \t\r\n]+`) + wave3K2RxHref = newLazyRegexp(`(?i)<a\b[^>]*\bhref\s*=\s*["']([^"'#][^"']*)["'][^>]*>(.*?)</a>`) + wave3K2RxGAOID = newLazyRegexp(`(?i)\bGAO-\d{2}-\d{4,7}[A-Z]?\b`) + wave3K2RxPubID = newLazyRegexp(`(?i)/publication/(\d+)`) + wave3K2RxCRSID = newLazyRegexp(`(?i)\b([A-Z]{1,3}\d{4,6})\b`) + wave3K2RxISODate = newLazyRegexp(`\b(\d{4}-\d{2}-\d{2})\b`) +) + +func init() { + for _, mode := range []string{ + "gao_reports_html", + "cbo_html", + "everycrs_html", + "gov_wp_newsroom_html", + "gsa_site_scanning_html", + "va_facilities_html", + "healthcare_gov_html", + "cms_price_transparency_html", + "medicaid_nadac_html", + "usps_docs_html", + "sba_dsbs_loans_html", + } { + m := mode + RegisterExternalHTMLModeLazy(m, func(rawHTML, baseURL string, _ func() string, extractorID string) *DeclarativePostFetchResult { + return Wave3RegulatorsHealthRunHTML(m, rawHTML, baseURL, extractorID) + }) + } +} + +// IsWave3RegulatorsHealthHTMLMode reports whether mode is one of the Category K Part 2 HTML extractors (#289-#300). +func IsWave3RegulatorsHealthHTMLMode(mode string) bool { + switch mode { + case "gao_reports_html", + "cbo_html", + "everycrs_html", + "gov_wp_newsroom_html", + "gsa_site_scanning_html", + "va_facilities_html", + "healthcare_gov_html", + "cms_price_transparency_html", + "medicaid_nadac_html", + "usps_docs_html", + "sba_dsbs_loans_html": + return true + default: + return false + } +} + +// IsWave3RegulatorsHealthJSONMode reports whether mode is one of the Category K Part 2 JSON formatters (#291-#300). +func IsWave3RegulatorsHealthJSONMode(mode string) bool { + switch mode { + case "everycrs_json", + "gov_wp_posts_json", + "gsa_site_scanning_json", + "va_facilities_json", + "healthcare_marketplace_json", + "cms_mrf_json", + "medicaid_nadac_json", + "usps_addresses_json", + "carrier_tracking_json", + "sba_dkan_json": + return true + default: + return false + } +} + +// IsWave3RegulatorsHealthTextMode reports whether mode is one of the Category K Part 2 text/RSS/CSV formatters (#289-#291, #296). +func IsWave3RegulatorsHealthTextMode(mode string) bool { + switch mode { + case "gao_rss_xml", + "cbo_rss_xml", + "everycrs_csv", + "cms_hpt_txt", + "cms_mrf_csv": + return true + default: + return false + } +} + +func wave3K2DefaultExtractorID(mode string) string { + switch mode { + case "gao_reports_html", "gao_rss_xml": + return "gao-reports" + case "cbo_html", "cbo_rss_xml": + return "cbo" + case "everycrs_html", "everycrs_json", "everycrs_csv": + return "everycrsreport" + case "gov_wp_newsroom_html", "gov_wp_posts_json": + return "gov-wordpress-newsrooms" + case "gsa_site_scanning_html", "gsa_site_scanning_json": + return "gsa-site-scanning" + case "va_facilities_html", "va_facilities_json": + return "va-lighthouse-facilities" + case "healthcare_gov_html", "healthcare_marketplace_json": + return "healthcare-gov-marketplace" + case "cms_price_transparency_html", "cms_hpt_txt", "cms_mrf_json", "cms_mrf_csv": + return "cms-price-transparency" + case "medicaid_nadac_html", "medicaid_nadac_json": + return "medicaid-nadac" + case "usps_docs_html", "usps_addresses_json": + return "usps-addresses" + case "carrier_tracking_json": + return "carrier-tracking-official" + case "sba_dsbs_loans_html", "sba_dkan_json": + return "sba-dsbs-loans" + default: + return "" + } +} + +// Wave3RegulatorsHealthRunHTML executes a Category K Part 2 HTML extractor (#289-#300). +func Wave3RegulatorsHealthRunHTML(mode, rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + if !IsWave3RegulatorsHealthHTMLMode(mode) || len(rawHTML) == 0 || strings.IndexByte(rawHTML, '<') < 0 || strings.IndexByte(rawHTML, '>') < 0 { + return nil + } + if len(rawHTML) > wave3K2MaxHTMLBytes { + rawHTML = truncateUTF8SafeFullDocGo(rawHTML, wave3K2MaxHTMLBytes) + } + trimmedStart := strings.TrimLeft(rawHTML, " \t\r\n") + if trimmedStart == "" || trimmedStart[0] == '{' || trimmedStart[0] == '[' { + return nil + } + + probe := rawHTML + if len(probe) > 65536 { + probe = probe[:65536] + } + probeLower := asciiLowerExtractString(probe) + urlLower := asciiLowerExtractString(baseURL) + + // Cheap byte prefilter BEFORE common negative-shell checks or DOM extraction. + if !wave3K2MatchesModePrefilter(mode, probeLower, urlLower) { + return nil + } + if wave3K2HasCommonNegativeShell(rawHTML, probeLower, urlLower) { + return nil + } + if extractorID == "" { + extractorID = wave3K2DefaultExtractorID(mode) + } + + var res *DeclarativePostFetchResult + switch mode { + case "gao_reports_html": + res = wave3K2ExtractGAOHTML(rawHTML, probeLower, baseURL, extractorID) + case "cbo_html": + res = wave3K2ExtractCBOHTML(rawHTML, probeLower, baseURL, extractorID) + case "everycrs_html": + res = wave3K2ExtractEveryCRSHTML(rawHTML, probeLower, baseURL, extractorID) + case "gov_wp_newsroom_html": + res = wave3K2ExtractGovWPHTML(rawHTML, probeLower, baseURL, extractorID) + case "gsa_site_scanning_html": + res = wave3K2ExtractGSAHTML(rawHTML, probeLower, baseURL, extractorID) + case "va_facilities_html": + res = wave3K2ExtractVAFacilitiesHTML(rawHTML, probeLower, baseURL, extractorID) + case "healthcare_gov_html": + res = wave3K2ExtractHealthcareGovHTML(rawHTML, probeLower, baseURL, extractorID) + case "cms_price_transparency_html": + res = wave3K2ExtractCMSPriceHTML(rawHTML, probeLower, baseURL, extractorID) + case "medicaid_nadac_html": + res = wave3K2ExtractMedicaidHTML(rawHTML, probeLower, baseURL, extractorID) + case "usps_docs_html": + res = wave3K2ExtractUSPSDocsHTML(rawHTML, probeLower, baseURL, extractorID) + case "sba_dsbs_loans_html": + res = wave3K2ExtractSBADSBSHTML(rawHTML, probeLower, baseURL, urlLower, extractorID) + } + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return nil + } + return res +} + +// RunWave3RegulatorsHealthHTMLMode executes a Category K Part 2 HTML extractor and returns JSON-marshaled DeclarativePostFetchResult. +func RunWave3RegulatorsHealthHTMLMode(mode, rawHTML, baseURL string) (string, bool) { + res := Wave3RegulatorsHealthRunHTML(mode, rawHTML, baseURL, wave3K2DefaultExtractorID(mode)) + res = sanitizePostFetchResultDeclHTML(res) + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return "", false + } + encoded, err := json.Marshal(res) + if err != nil { + return "", false + } + return string(encoded), true +} + +// FormatWave3RegulatorsHealthJSONDoc formats a Category K Part 2 JSON twin payload into DeclarativeFormattedDoc. +func FormatWave3RegulatorsHealthJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool) { + if !IsWave3RegulatorsHealthJSONMode(mode) || len(raw) == 0 || len(raw) > wave3K2MaxJSONBytes { + return nil, false + } + + // #296 cms_mrf_json must detect ZIP (PK\x03\x04) and gzip (\x1f\x8b) magic bytes before JSON parsing. + if mode == "cms_mrf_json" { + if archFmt := wave3K2DetectArchiveFormat(raw); archFmt != "" { + doc := wave3K2FormatCMSArchiveDoc(archFmt, len(raw), origURL) + return wave3K2FinalizeDoc(doc), true + } + doc, handled := wave3K2FormatCMSMRFJSON(raw, origURL) + if !handled || doc == nil || strings.TrimSpace(doc.Markdown) == "" { + return nil, false + } + return wave3K2FinalizeDoc(doc), true + } + + trimmed := bytes.TrimSpace(bytes.TrimPrefix(raw, []byte("\xEF\xBB\xBF"))) + if len(trimmed) == 0 || (trimmed[0] != '{' && trimmed[0] != '[') { + return nil, false + } + parsed, ok := decodeJSONWithNumbers(trimmed) + if !ok || parsed == nil { + return nil, false + } + + var doc *DeclarativeFormattedDoc + var handled bool + switch mode { + case "everycrs_json": + doc, handled = wave3K2FormatEveryCRSJSON(parsed, origURL) + case "gov_wp_posts_json": + doc, handled = wave3K2FormatGovWPPostsJSON(parsed, origURL) + case "gsa_site_scanning_json": + doc, handled = wave3K2FormatGSASiteScanningJSON(parsed, origURL) + case "va_facilities_json": + doc, handled = wave3K2FormatVAFacilitiesJSON(parsed, origURL) + case "healthcare_marketplace_json": + doc, handled = wave3K2FormatHealthcareMarketplaceJSON(parsed, origURL) + case "medicaid_nadac_json": + doc, handled = wave3K2FormatMedicaidDKANJSON(parsed, origURL, "Medicaid NADAC Data") + case "usps_addresses_json": + doc, handled = wave3K2FormatUSPSAddressesJSON(parsed, origURL) + case "carrier_tracking_json": + doc, handled = wave3K2FormatCarrierTrackingJSON(parsed, origURL) + case "sba_dkan_json": + doc, handled = wave3K2FormatMedicaidDKANJSON(parsed, origURL, "SBA Open Data (DKAN)") + } + if !handled || doc == nil || strings.TrimSpace(doc.Markdown) == "" { + return nil, false + } + return wave3K2FinalizeDoc(doc), true +} + +// FormatWave3RegulatorsHealthJSONMode formats a Category K Part 2 JSON payload and returns JSON-marshaled DeclarativeFormattedDoc. +func FormatWave3RegulatorsHealthJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool) { + doc, ok := FormatWave3RegulatorsHealthJSONDoc(mode, raw, params, origURL) + if !ok || doc == nil { + return "", false + } + encoded, err := json.Marshal(doc) + if err != nil { + return "", false + } + return string(encoded), true +} + +// FormatWave3RegulatorsHealthTextDoc formats a Category K Part 2 text/RSS/CSV payload into DeclarativeFormattedDoc. +func FormatWave3RegulatorsHealthTextDoc(mode, rawBody string, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool) { + if !IsWave3RegulatorsHealthTextMode(mode) || len(rawBody) == 0 || len(rawBody) > wave3K2MaxTextBytes { + return nil, false + } + + if mode == "cms_mrf_csv" { + if archFmt := wave3K2DetectArchiveFormat([]byte(rawBody)); archFmt != "" { + doc := wave3K2FormatCMSArchiveDoc(archFmt, len(rawBody), origURL) + return wave3K2FinalizeDoc(doc), true + } + } + + var doc *DeclarativeFormattedDoc + var handled bool + switch mode { + case "gao_rss_xml": + doc, handled = wave3K2FormatRSSXML(rawBody, origURL, "GAO Reports & Testimonies") + case "cbo_rss_xml": + doc, handled = wave3K2FormatRSSXML(rawBody, origURL, "Congressional Budget Office (CBO)") + case "everycrs_csv": + doc, handled = wave3K2FormatEveryCRSCSV(rawBody, origURL) + case "cms_hpt_txt": + doc, handled = wave3K2FormatCMSHPTTxt(rawBody, origURL) + case "cms_mrf_csv": + doc, handled = wave3K2FormatCMSMRFCSV(rawBody, origURL) + } + if !handled || doc == nil || strings.TrimSpace(doc.Markdown) == "" { + return nil, false + } + return wave3K2FinalizeDoc(doc), true +} + +// FormatWave3RegulatorsHealthTextMode formats a Category K Part 2 text payload and returns JSON-marshaled DeclarativeFormattedDoc. +func FormatWave3RegulatorsHealthTextMode(mode, rawBody string, params map[string]string, origURL string) (string, bool) { + doc, ok := FormatWave3RegulatorsHealthTextDoc(mode, rawBody, params, origURL) + if !ok || doc == nil { + return "", false + } + encoded, err := json.Marshal(doc) + if err != nil { + return "", false + } + return string(encoded), true +} + +// ── Prefilters & Common Negative Shell Guards ─────────────────────────────────────────────────── + +func wave3K2MatchesModePrefilter(mode, probeLower, urlLower string) bool { + switch mode { + case "gao_reports_html": + return strings.Contains(urlLower, "gao.gov") || + strings.Contains(probeLower, "page-node-type-product") || + strings.Contains(probeLower, "gao-uswds") || + strings.Contains(probeLower, "what gao found") || + strings.Contains(probeLower, "u.s. government accountability office") + case "cbo_html": + return strings.Contains(urlLower, "cbo.gov") || + strings.Contains(probeLower, "congressional budget office") || + strings.Contains(probeLower, "cbo-") + case "everycrs_html": + return strings.Contains(urlLower, "everycrsreport.com") || + strings.Contains(probeLower, "everycrsreport") || + strings.Contains(probeLower, "every crs report") || + strings.Contains(probeLower, "crsreports.congress.gov") + case "gov_wp_newsroom_html": + if strings.Contains(probeLower, "woocommerce") || strings.Contains(probeLower, "wc-block") || strings.Contains(probeLower, "wc-ajax") { + return false + } + return strings.Contains(probeLower, "wp-content") || + strings.Contains(probeLower, "wp-block-") || + strings.Contains(probeLower, "wp-json") || + strings.Contains(probeLower, "yoast") || + strings.Contains(urlLower, "whitehouse.gov") || + strings.Contains(urlLower, "news.va.gov") || + strings.Contains(urlLower, "nasa.gov") + case "gsa_site_scanning_html": + return strings.Contains(probeLower, "site-scanning") || + strings.Contains(probeLower, "site scanning") || + strings.Contains(probeLower, "api.gsa.gov") || + strings.Contains(urlLower, "open.gsa.gov") + case "va_facilities_html": + return strings.Contains(urlLower, "va.gov") || + strings.Contains(probeLower, "va facilities") || + strings.Contains(probeLower, "veterans affairs") || + strings.Contains(probeLower, "lighthouse") + case "healthcare_gov_html": + return strings.Contains(urlLower, "healthcare.gov") || + strings.Contains(probeLower, "healthcare.gov") || + strings.Contains(probeLower, "health insurance marketplace") + case "cms_price_transparency_html": + return strings.Contains(probeLower, "cms-hpt.txt") || + strings.Contains(probeLower, "standardcharges") || + strings.Contains(probeLower, "45 cfr 180") || + strings.Contains(probeLower, "transparency in coverage") || + (strings.Contains(probeLower, "price transparency") && + (strings.Contains(probeLower, "machine-readable") || strings.Contains(probeLower, "machine readable") || strings.Contains(probeLower, "mrf"))) + case "medicaid_nadac_html": + return strings.Contains(urlLower, "data.medicaid.gov") || + strings.Contains(probeLower, "nadac") || + strings.Contains(probeLower, "medicaid") + case "usps_docs_html": + return strings.Contains(urlLower, "developers.usps.com") || + strings.Contains(probeLower, "usps") || + strings.Contains(probeLower, "addresses/v3") + case "sba_dsbs_loans_html": + return strings.Contains(urlLower, "sba.gov") || + strings.Contains(probeLower, "sba open data") || + strings.Contains(probeLower, "small business administration") || + strings.Contains(probeLower, "dkan") + default: + return false + } +} + +func wave3K2IsNegativeURL(urlLower string) bool { + if urlLower == "" { + return false + } + if strings.Contains(urlLower, "/404") || + strings.Contains(urlLower, "/not-found") || + strings.Contains(urlLower, "/maintenance") || + strings.Contains(urlLower, "error=true") { + return true + } + pathOnly := urlLower + if idx := strings.Index(pathOnly, "://"); idx >= 0 { + rest := pathOnly[idx+3:] + if slash := strings.IndexByte(rest, '/'); slash >= 0 { + pathOnly = rest[slash:] + } else { + pathOnly = "/" + } + } + if cut := strings.IndexAny(pathOnly, "?#"); cut >= 0 { + pathOnly = pathOnly[:cut] + } + return strings.HasSuffix(pathOnly, "/error") || + strings.Contains(pathOnly, "/error/") || + strings.HasSuffix(pathOnly, "/error.html") || + strings.HasSuffix(pathOnly, "/error.htm") || + strings.HasSuffix(pathOnly, "/error.aspx") || + strings.HasSuffix(pathOnly, "/login") || + strings.Contains(pathOnly, "/login/") +} + +func wave3K2IsNegativeTitle(title string) bool { + t := strings.TrimSpace(title) + if t == "" { + return false + } + return wave3K2RxNotFoundTitle.MatchString(t) || + wave3K2RxMaintTitle.MatchString(t) || + wave3K2RxErrorTitle.MatchString(t) +} + +func wave3K2IsGenericTitle(title string) bool { + return wave3K2RxGenericTitle.MatchString(strings.TrimSpace(title)) +} + +func wave3K2HasWAFOrChallengeMarkers(lower string) bool { + for _, marker := range []string{ + "var dd=", + "var dd =", + "dd={'rt'", + "geo.captcha-delivery.com", + "captcha-delivery.com", + "please enable js and disable any ad blocker", + "cf-browser-verification", + "cf-turnstile", + "cf-mitigated", + "challenge-platform", + "_cf_chl_opt", + "cf_chl_opt", + "attention required! | cloudflare", + "just a moment...", + "errors.edgesuite.net", + "error from cloudfront", + "the request could not be satisfied", + "you don't have permission to access", + "<title>access denied", + "403 forbidden", + "error 403", + "not acceptable", + "window.kpsdk", + "kp_uidz", + "_incapsula_resource", + "incapsula incident", + "x-amzn-waf-action", + "the requested url was rejected", + "your support id is", + } { + if strings.Contains(lower, marker) { + return true + } + } + return false +} + +func wave3K2HasCommonNegativeShell(rawHTML, probeLower, urlLower string) bool { + if wave3K2IsNegativeURL(urlLower) { + return true + } + if wave3K2HasWAFOrChallengeMarkers(probeLower) { + return true + } + title := extractTitleLinearQuick(rawHTML) + if wave3K2IsNegativeTitle(title) { + return true + } + hasSPAShell := wave3HasEmptyRootDivShell(rawHTML, probeLower, false) || + strings.Contains(probeLower, ``) + if !hasSPAShell && len(rawHTML) > 65536 && len(rawHTML) <= 262144 { + tail := rawHTML[65400:] + hasSPAShell = indexFoldASCIIExtract(tail, ``) >= 0 + } + hasTailRealMarkers := len(rawHTML) > 65536 && + (indexFoldASCIIExtract(rawHTML[65536:], "= 0 || + indexFoldASCIIExtract(rawHTML[65536:], "= 0 || + indexFoldASCIIExtract(rawHTML[65536:], "= 0) + if hasSPAShell && + !hasJSONLDScriptToken(rawHTML) && + !strings.Contains(probeLower, " 0 { + return true + } + case map[string]any: + if len(tv) > 0 { + return true + } + case bool: + if tv { + return true + } + } + } + } + for _, k := range []string{"error_code", "statusCode", "status_code", "status"} { + if f, ok := wave3K2FloatVal(obj[k]); ok && f >= 400 { + return true + } + } + if code := wave3K2Plain(obj["code"], 80); strings.HasPrefix(code, "rest_") { + return true + } + if msg := wave3K2Plain(obj["message"], 200); msg != "" && len(obj) <= 3 { + lm := strings.ToLower(msg) + if strings.Contains(lm, "unauthorized") || strings.Contains(lm, "not found") || + strings.Contains(lm, "no api key") || strings.Contains(lm, "invalid api key") || + strings.Contains(lm, "invalid_token") || strings.Contains(lm, "access token") || + strings.Contains(lm, "forbidden") || strings.Contains(lm, "api_key_missing") { + return true + } + } + return false +} + +// ── Shared Formatting & DOM Helpers ───────────────────────────────────────────────────────────── + +func wave3K2IntPtr(n int) *int { return &n } +func wave3K2BoolPtr(b bool) *bool { return &b } + +func wave3K2FinalizeDoc(doc *DeclarativeFormattedDoc) *DeclarativeFormattedDoc { + if doc == nil { + return nil + } + if len(doc.Records) > wave3K2MaxRecords { + if doc.Total == nil { + doc.Total = wave3K2IntPtr(len(doc.Records)) + } + doc.Records = doc.Records[:wave3K2MaxRecords] + doc.Returned = wave3K2IntPtr(len(doc.Records)) + doc.Truncated = wave3K2BoolPtr(true) + if doc.NextCursor == "" { + doc.NextCursor = strconv.Itoa(len(doc.Records)) + } + } + if sanitized, ok := sanitizeDeclarativeFormattedDocGo(doc); ok && sanitized != nil { + return sanitized + } + return nil +} + +func wave3K2CleanText(s string) string { + if s == "" { + return "" + } + if strings.IndexByte(s, '<') >= 0 { + s = wave3K2RxHTMLTag.ReplaceAllString(s, " ") + } + if strings.IndexByte(s, '&') >= 0 { + s = stdhtml.UnescapeString(s) + } + return strings.TrimSpace(wave3K2RxSpaceCollapse.ReplaceAllString(s, " ")) +} + +func wave3K2Plain(v any, maxLen int) string { + return SanitizeSchemaPlainField(wave3K2StringVal(v), maxLen) +} + +func wave3K2FirstNonEmpty(vals ...string) string { + for _, v := range vals { + if t := strings.TrimSpace(v); t != "" { + return t + } + } + return "" +} + +func wave3K2StringVal(v any) string { + switch tv := v.(type) { + case string: + return strings.TrimSpace(tv) + case json.Number: + return tv.String() + case float64: + if math.IsNaN(tv) || math.IsInf(tv, 0) { + return "" + } + if tv == math.Trunc(tv) { + return strconv.FormatInt(int64(tv), 10) + } + return strconv.FormatFloat(tv, 'f', -1, 64) + case int: + return strconv.Itoa(tv) + case int64: + return strconv.FormatInt(tv, 10) + case bool: + if tv { + return "true" + } + return "false" + default: + return "" + } +} + +func wave3K2FloatVal(v any) (float64, bool) { + switch tv := v.(type) { + case float64: + if math.IsNaN(tv) || math.IsInf(tv, 0) { + return 0, false + } + return tv, true + case int: + return float64(tv), true + case int64: + return float64(tv), true + case json.Number: + f, err := tv.Float64() + if err != nil || math.IsNaN(f) || math.IsInf(f, 0) { + return 0, false + } + return f, true + case string: + s := strings.TrimSpace(strings.ReplaceAll(tv, ",", "")) + if s == "" { + return 0, false + } + f, err := strconv.ParseFloat(s, 64) + if err != nil || math.IsNaN(f) || math.IsInf(f, 0) { + return 0, false + } + return f, true + default: + return 0, false + } +} + +func wave3K2Map(v any) map[string]any { + if m, ok := v.(map[string]any); ok { + return m + } + return nil +} + +func wave3K2Slice(v any) []any { + if s, ok := v.([]any); ok { + return s + } + return nil +} + +func wave3K2AddLink(links *[]string, seen map[string]bool, raw, base string) { + u := SanitizeSchemaHTTPSURL(raw, base) + if u != "" && !seen[u] { + seen[u] = true + *links = append(*links, u) + } +} + +func wave3K2ExtractH1(rawHTML string) string { + inner, ok := findElementInnerLinearDeclHTML(rawHTML, "h1", nil, 0) + if !ok { + return "" + } + return wave3K2CleanText(inner) +} + +func wave3K2ExtractMeta(rawHTML, key string) string { + target := strings.ToLower(strings.TrimSpace(key)) + pos := 0 + for i := 0; i < 64 && pos < len(rawHTML); i++ { + open, ok := findOpenTagLinearDeclHTML(rawHTML, "meta", nil, pos) + if !ok { + break + } + pos = open.openEnd + nameVal, _ := getAttrValueLinearDeclHTML(open.attrStr, "name") + propVal, _ := getAttrValueLinearDeclHTML(open.attrStr, "property") + if strings.EqualFold(strings.TrimSpace(nameVal), target) || strings.EqualFold(strings.TrimSpace(propVal), target) { + if content, okC := getAttrValueLinearDeclHTML(open.attrStr, "content"); okC { + return wave3K2CleanText(content) + } + } + } + return "" +} + +func wave3K2ExtractMainHTML(rawHTML, baseURL string) string { + frag := "" + for _, tag := range []string{"main", "article"} { + if inner, ok := findElementInnerLinearDeclHTML(rawHTML, tag, nil, 0); ok && len(strings.TrimSpace(inner)) > 40 { + frag = inner + break + } + } + if frag == "" { + if body, ok := findElementInnerLinearDeclHTML(rawHTML, "body", nil, 0); ok { + frag = body + } else { + frag = rawHTML + } + } + doc := ExtractHTMLDocumentFull(""+frag+"", FullExtractOptions{ + BaseURL: baseURL, + OnlyMainContent: true, + IncludeImages: false, + IsFragment: true, + SkipUniversalExtractors: true, + SkipPlainText: true, + }) + return strings.TrimSpace(doc.Markdown) +} + +func wave3K2FragToMD(frag, baseURL string) string { + if strings.TrimSpace(frag) == "" { + return "" + } + doc := ExtractHTMLDocumentFull(""+frag+"", FullExtractOptions{ + BaseURL: baseURL, + OnlyMainContent: false, + IncludeImages: false, + IsFragment: true, + SkipUniversalExtractors: true, + SkipPlainText: true, + }) + return strings.TrimSpace(doc.Markdown) +} + +func wave3K2ExtractLinks(frag, baseURL string, maxLinks int) []struct{ Text, URL string } { + matches := wave3K2RxHref.FindAllStringSubmatch(frag, maxLinks*3) + out := make([]struct{ Text, URL string }, 0, maxLinks) + seen := make(map[string]bool) + for _, m := range matches { + if len(out) >= maxLinks { + break + } + if len(m) < 3 { + continue + } + u := SanitizeSchemaHTTPSURL(stdhtml.UnescapeString(strings.TrimSpace(m[1])), baseURL) + if u == "" || seen[u] { + continue + } + txt := wave3K2CleanText(m[2]) + if txt == "" { + continue + } + seen[u] = true + out = append(out, struct{ Text, URL string }{Text: txt, URL: u}) + } + return out +} + +func wave3K2JoinBullets(bullets []string) string { + if len(bullets) == 0 { + return "" + } + return strings.Join(bullets, "\n") +} + +// ── #289 GAO Reports & #290 CBO RSS/HTML ──────────────────────────────────────────────────────── + +func wave3K2FormatRSSXML(rawBody, origURL, fallbackTitle string) (*DeclarativeFormattedDoc, bool) { + lowerProbe := asciiLowerExtractString(rawBody) + if len(lowerProbe) > 65536 { + lowerProbe = lowerProbe[:65536] + } + if isLikelyHTMLSoft404(rawBody) || wave3K2HasWAFOrChallengeMarkers(lowerProbe) { + return nil, false + } + if !strings.Contains(lowerProbe, " 0 { + head = head[:idx] + } + feedTitle := SanitizeScrapedMeta(extractXMLTagTextGo(head, "title")) + if feedTitle == "" { + feedTitle = fallbackTitle + } + + var rows [][]string + var records []map[string]any + var links []string + seenLink := make(map[string]bool) + + for _, blk := range blocks { + itemTitle := wave3K2CleanText(extractXMLTagTextGo(blk, "title")) + itemLink := strings.TrimSpace(extractXMLTagTextGo(blk, "link")) + if itemLink == "" { + if open, ok := findOpenTagLinearDeclHTML(blk, "link", nil, 0); ok { + if href, okH := getAttrValueLinearDeclHTML(open.attrStr, "href"); okH { + itemLink = strings.TrimSpace(href) + } + } + } + if itemLink == "" { + itemLink = strings.TrimSpace(extractXMLTagTextGo(blk, "guid")) + } + pubDate := wave3K2CleanText(wave3K2FirstNonEmpty( + extractXMLTagTextGo(blk, "pubDate"), + extractXMLTagTextGo(blk, "published"), + extractXMLTagTextGo(blk, "updated"), + extractXMLTagTextGo(blk, "dc:date"), + )) + desc := wave3K2CleanText(wave3K2FirstNonEmpty( + extractXMLTagTextGo(blk, "description"), + extractXMLTagTextGo(blk, "summary"), + )) + if itemTitle == "" && itemLink == "" { + continue + } + safeLink := SanitizeSchemaHTTPSURL(itemLink, origURL) + if safeLink != "" { + wave3K2AddLink(&links, seenLink, safeLink, origURL) + } + + if len(records) < wave3K2MaxRecords { + rec := map[string]any{ + "title": itemTitle, + } + if pubDate != "" { + rec["published"] = pubDate + } + if safeLink != "" { + rec["url"] = safeLink + } + if desc != "" { + rec["summary"] = sliceRunesMax(desc, 240) + } + if gaoID := wave3K2RxGAOID.FindString(itemTitle + " " + safeLink); gaoID != "" { + rec["reportId"] = strings.ToUpper(gaoID) + } else if pm := wave3K2RxPubID.FindStringSubmatch(safeLink); len(pm) > 1 { + rec["publicationId"] = pm[1] + } + records = append(records, rec) + + titleCell := escapeDeclMarkdownBrackets(itemTitle) + if safeLink != "" { + titleCell = "[" + escapeDeclMarkdownBrackets(itemTitle) + "](" + safeLink + ")" + } + rows = append(rows, []string{titleCell, pubDate, sliceRunesMax(desc, 140)}) + } + } + + if len(rows) == 0 { + return nil, false + } + + var md []string + md = append(md, "# "+escapeDeclMarkdownBrackets(feedTitle)) + md = append(md, fmt.Sprintf("- **Feed Items**: %d", len(blocks))) + md = append(md, formatDeclarativeGFMTable([]string{"Title", "Published", "Summary"}, rows)) + + total := len(blocks) + ret := len(records) + trunc := total > ret + return &DeclarativeFormattedDoc{ + Title: feedTitle, + Markdown: strings.Join(md, "\n\n"), + Links: links, + Records: records, + Total: wave3K2IntPtr(total), + Returned: wave3K2IntPtr(ret), + Truncated: wave3K2BoolPtr(trunc), + }, true +} + +func wave3K2ExtractGAOHTML(rawHTML, probeLower, baseURL, extractorID string) *DeclarativePostFetchResult { + h1 := wave3K2ExtractH1(rawHTML) + ogTitle := wave3K2ExtractMeta(rawHTML, "og:title") + rawTitle := extractTitleLinearQuick(rawHTML) + title := wave3K2FirstNonEmpty(h1, ogTitle, rawTitle) + title = strings.TrimSpace(strings.TrimSuffix(title, "| U.S. GAO")) + title = strings.TrimSpace(strings.TrimSuffix(title, "- U.S. GAO")) + if title == "" || wave3K2IsNegativeTitle(title) || wave3K2IsGenericTitle(title) { + return nil + } + + reportID := wave3K2RxGAOID.FindString(baseURL + " " + title + " " + probeLower) + reportID = strings.ToUpper(reportID) + pubDate := wave3K2FirstNonEmpty( + wave3K2ExtractMeta(rawHTML, "article:published_time"), + wave3K2ExtractMeta(rawHTML, "dc.date"), + wave3K2RxISODate.FindString(probeLower), + ) + desc := wave3K2ExtractMeta(rawHTML, "description") + bodyMD := wave3K2ExtractMainHTML(rawHTML, baseURL) + if bodyMD == "" && desc == "" { + return nil + } + + var links []string + seen := make(map[string]bool) + for _, lnk := range wave3K2ExtractLinks(rawHTML, baseURL, 20) { + if strings.Contains(strings.ToLower(lnk.URL), ".pdf") || strings.Contains(strings.ToLower(lnk.URL), "/products/") { + wave3K2AddLink(&links, seen, lnk.URL, baseURL) + } + } + + var bullets []string + bullets = append(bullets, "- **Source**: U.S. Government Accountability Office (GAO)") + if reportID != "" { + bullets = append(bullets, "- **Report Number**: `"+sanitizeDeclInlineCodeVal(reportID)+"`") + } + if pubDate != "" { + bullets = append(bullets, "- **Published**: "+escapeDeclMarkdownBrackets(pubDate)) + } + + var blocks []string + blocks = append(blocks, "# "+escapeDeclMarkdownBrackets(title)) + blocks = append(blocks, wave3K2JoinBullets(bullets)) + if bodyMD != "" { + blocks = append(blocks, bodyMD) + } else if desc != "" { + blocks = append(blocks, escapeDeclMarkdownBlock(desc)) + } + + rec := map[string]any{"title": title} + if reportID != "" { + rec["reportId"] = reportID + } + if pubDate != "" { + rec["published"] = pubDate + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + PublishedTime: pubDate, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: []map[string]any{rec}, + } +} + +func wave3K2ExtractCBOHTML(rawHTML, probeLower, baseURL, extractorID string) *DeclarativePostFetchResult { + h1 := wave3K2ExtractH1(rawHTML) + ogTitle := wave3K2ExtractMeta(rawHTML, "og:title") + rawTitle := extractTitleLinearQuick(rawHTML) + title := wave3K2FirstNonEmpty(h1, ogTitle, rawTitle) + title = strings.TrimSpace(strings.TrimSuffix(title, "| Congressional Budget Office")) + if title == "" || wave3K2IsNegativeTitle(title) || wave3K2IsGenericTitle(title) { + return nil + } + + pubID := "" + if pm := wave3K2RxPubID.FindStringSubmatch(baseURL); len(pm) > 1 { + pubID = pm[1] + } + pubDate := wave3K2FirstNonEmpty( + wave3K2ExtractMeta(rawHTML, "article:published_time"), + wave3K2ExtractMeta(rawHTML, "dc.date"), + wave3K2RxISODate.FindString(probeLower), + ) + desc := wave3K2ExtractMeta(rawHTML, "description") + bodyMD := wave3K2ExtractMainHTML(rawHTML, baseURL) + if bodyMD == "" && desc == "" { + return nil + } + + var links []string + seen := make(map[string]bool) + for _, lnk := range wave3K2ExtractLinks(rawHTML, baseURL, 20) { + if strings.Contains(strings.ToLower(lnk.URL), ".pdf") || strings.Contains(strings.ToLower(lnk.URL), "/publication/") { + wave3K2AddLink(&links, seen, lnk.URL, baseURL) + } + } + + var bullets []string + bullets = append(bullets, "- **Source**: Congressional Budget Office (CBO)") + if pubID != "" { + bullets = append(bullets, "- **Publication ID**: `"+sanitizeDeclInlineCodeVal(pubID)+"`") + } + if pubDate != "" { + bullets = append(bullets, "- **Published**: "+escapeDeclMarkdownBrackets(pubDate)) + } + + var blocks []string + blocks = append(blocks, "# "+escapeDeclMarkdownBrackets(title)) + blocks = append(blocks, wave3K2JoinBullets(bullets)) + if bodyMD != "" { + blocks = append(blocks, bodyMD) + } else if desc != "" { + blocks = append(blocks, escapeDeclMarkdownBlock(desc)) + } + + rec := map[string]any{"title": title} + if pubID != "" { + rec["publicationId"] = pubID + } + if pubDate != "" { + rec["published"] = pubDate + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + PublishedTime: pubDate, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: []map[string]any{rec}, + } +} + +// ── #291 EveryCRSReport (JSON, CSV, HTML) ─────────────────────────────────────────────────────── + +func wave3K2FormatEveryCRSJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + obj := wave3K2Map(parsed) + if obj == nil || wave3K2IsGenericJSONError(obj) { + return nil, false + } + number := wave3K2Plain(obj["number"], 64) + versions := wave3K2Slice(obj["versions"]) + if number == "" && len(versions) == 0 { + return nil, false + } + + reportType := wave3K2Plain(obj["type"], 120) + source := wave3K2Plain(obj["source"], 180) + activeStr := wave3K2Plain(obj["active"], 16) + + var latestTitle, latestDate, latestSummary, latestSourceLink string + var rows [][]string + var records []map[string]any + var links []string + seen := make(map[string]bool) + + for idx, v := range versions { + vm := wave3K2Map(v) + if vm == nil { + continue + } + vTitle := wave3K2Plain(vm["title"], 280) + vDate := wave3K2Plain(vm["date"], 48) + vSummary := wave3K2Plain(vm["summary"], 1600) + vSource := SanitizeSchemaHTTPSURL(vm["sourceLink"], origURL) + if idx == 0 { + latestTitle = vTitle + latestDate = vDate + latestSummary = vSummary + latestSourceLink = vSource + } + var fmtNames []string + for _, f := range wave3K2Slice(vm["formats"]) { + fm := wave3K2Map(f) + if fm == nil { + continue + } + fn := wave3K2Plain(fm["format"], 32) + fu := SanitizeSchemaHTTPSURL(fm["url"], origURL) + if fn != "" { + fmtNames = append(fmtNames, fn) + } + if fu != "" { + wave3K2AddLink(&links, seen, fu, origURL) + } + } + if vSource != "" { + wave3K2AddLink(&links, seen, vSource, origURL) + } + if len(records) < wave3K2MaxRecords { + records = append(records, map[string]any{ + "number": number, + "date": vDate, + "title": vTitle, + "formats": strings.Join(fmtNames, ", "), + }) + rows = append(rows, []string{vDate, escapeDeclMarkdownBrackets(vTitle), strings.Join(fmtNames, ", ")}) + } + } + + title := wave3K2FirstNonEmpty(latestTitle, "CRS Report "+number) + var bullets []string + if number != "" { + bullets = append(bullets, "- **Report Number**: `"+sanitizeDeclInlineCodeVal(number)+"`") + } + if reportType != "" { + bullets = append(bullets, "- **Type**: "+escapeDeclMarkdownBrackets(reportType)) + } + if latestDate != "" { + bullets = append(bullets, "- **Latest Version**: "+escapeDeclMarkdownBrackets(latestDate)) + } + if activeStr != "" { + bullets = append(bullets, "- **Active**: "+escapeDeclMarkdownBrackets(activeStr)) + } + if source != "" { + bullets = append(bullets, "- **Source**: "+escapeDeclMarkdownBrackets(source)) + } + if latestSourceLink != "" { + bullets = append(bullets, "- **Official Link**: ["+latestSourceLink+"]("+latestSourceLink+")") + } + + var md []string + md = append(md, "# "+escapeDeclMarkdownBrackets(title)) + if len(bullets) > 0 { + md = append(md, wave3K2JoinBullets(bullets)) + } + if latestSummary != "" { + md = append(md, "## Summary\n\n"+escapeDeclMarkdownBlock(latestSummary)) + } + if len(rows) > 0 { + md = append(md, "## Versions\n\n"+formatDeclarativeGFMTable([]string{"Date", "Title", "Formats"}, rows)) + } + + total := len(versions) + ret := len(records) + trunc := total > ret + return &DeclarativeFormattedDoc{ + Title: title, + Description: sliceRunesMax(latestSummary, 500), + PublishedTime: latestDate, + Markdown: strings.Join(md, "\n\n"), + Links: links, + Records: records, + Total: wave3K2IntPtr(total), + Returned: wave3K2IntPtr(ret), + Truncated: wave3K2BoolPtr(trunc), + }, true +} + +func wave3K2FormatEveryCRSCSV(rawBody, origURL string) (*DeclarativeFormattedDoc, bool) { + if isLikelyHTMLSoft404(rawBody) { + return nil, false + } + clean := strings.TrimPrefix(rawBody, "\ufeff") + r := csv.NewReader(strings.NewReader(clean)) + r.FieldsPerRecord = -1 + + header, err := r.Read() + if err != nil || len(header) < 2 { + return nil, false + } + colIdx := make(map[string]int, len(header)) + for i, h := range header { + colIdx[strings.ToLower(strings.TrimSpace(h))] = i + } + if _, hasNum := colIdx["number"]; !hasNum { + if _, hasTitle := colIdx["title"]; !hasTitle { + return nil, false + } + } + + getCol := func(row []string, name string) string { + if idx, ok := colIdx[name]; ok && idx < len(row) { + return strings.TrimSpace(row[idx]) + } + return "" + } + + var rows [][]string + var records []map[string]any + var links []string + seen := make(map[string]bool) + + for len(records) < wave3K2MaxRecords { + recRow, rErr := r.Read() + if rErr == io.EOF { + break + } + if rErr != nil { + // Tolerate truncated final row at maxBytes boundary. + break + } + num := getCol(recRow, "number") + title := getCol(recRow, "title") + pubDate := getCol(recRow, "latestpubdate") + relURL := getCol(recRow, "url") + pdfURL := getCol(recRow, "latestpdf") + htmlURL := getCol(recRow, "latesthtml") + if num == "" && title == "" { + continue + } + fullHTML := SanitizeSchemaHTTPSURL(wave3K2FirstNonEmpty(htmlURL, relURL), origURL) + fullPDF := SanitizeSchemaHTTPSURL(pdfURL, origURL) + if fullHTML != "" { + wave3K2AddLink(&links, seen, fullHTML, origURL) + } + if fullPDF != "" { + wave3K2AddLink(&links, seen, fullPDF, origURL) + } + records = append(records, map[string]any{ + "number": num, + "title": title, + "latestPubDate": pubDate, + "url": fullHTML, + }) + titleCell := escapeDeclMarkdownBrackets(title) + if fullHTML != "" { + titleCell = "[" + titleCell + "](" + fullHTML + ")" + } + rows = append(rows, []string{"`" + sanitizeDeclInlineCodeVal(num) + "`", titleCell, pubDate}) + } + + if len(records) == 0 { + return nil, false + } + title := "EveryCRSReport Index" + md := "# " + title + "\n\n" + formatDeclarativeGFMTable([]string{"Report", "Title", "Latest Date"}, rows) + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: md, + Links: links, + Records: records, + Returned: wave3K2IntPtr(len(records)), + Truncated: wave3K2BoolPtr(true), + }, true +} + +func wave3K2ExtractEveryCRSHTML(rawHTML, probeLower, baseURL, extractorID string) *DeclarativePostFetchResult { + h1 := wave3K2ExtractH1(rawHTML) + rawTitle := extractTitleLinearQuick(rawHTML) + title := wave3K2FirstNonEmpty(h1, wave3K2ExtractMeta(rawHTML, "og:title"), rawTitle) + title = strings.TrimSpace(strings.TrimSuffix(title, "- EveryCRSReport.com")) + if title == "" || wave3K2IsNegativeTitle(title) || wave3K2IsGenericTitle(title) { + return nil + } + reportID := wave3K2RxCRSID.FindString(baseURL + " " + title) + bodyMD := wave3K2ExtractMainHTML(rawHTML, baseURL) + if bodyMD == "" { + return nil + } + var bullets []string + bullets = append(bullets, "- **Source**: EveryCRSReport") + if reportID != "" { + bullets = append(bullets, "- **Report Number**: `"+sanitizeDeclInlineCodeVal(strings.ToUpper(reportID))+"`") + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Markdown: "# " + escapeDeclMarkdownBrackets(title) + "\n\n" + wave3K2JoinBullets(bullets) + "\n\n" + bodyMD, + } +} + +// ── #292 Federal .gov WordPress Newsrooms ─────────────────────────────────────────────────────── + +func wave3K2GovAgencyName(origURL string) string { + u, err := url.Parse(origURL) + if err != nil { + return "Federal .gov Newsroom" + } + h := strings.ToLower(u.Hostname()) + switch { + case strings.HasSuffix(h, "whitehouse.gov"): + return "The White House" + case h == "news.va.gov" || strings.HasSuffix(h, ".va.gov"): + return "U.S. Department of Veterans Affairs (VA News)" + case strings.HasSuffix(h, "nasa.gov"): + return "NASA" + default: + return "Federal .gov Newsroom" + } +} + +func wave3K2FormatGovWPPostsJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + agency := wave3K2GovAgencyName(origURL) + var posts []map[string]any + switch tv := parsed.(type) { + case map[string]any: + if wave3K2IsGenericJSONError(tv) { + return nil, false + } + if _, hasTitle := tv["title"]; !hasTitle { + if _, hasSlug := tv["slug"]; !hasSlug { + return nil, false + } + } + posts = []map[string]any{tv} + case []any: + if len(tv) == 0 { + return nil, false + } + for _, el := range tv { + if m := wave3K2Map(el); m != nil { + posts = append(posts, m) + } + } + default: + return nil, false + } + if len(posts) == 0 { + return nil, false + } + + if len(posts) == 1 { + p := posts[0] + titleObj := wave3K2Map(p["title"]) + titleRaw := "" + if titleObj != nil { + titleRaw = wave3K2CleanText(wave3K2StringVal(titleObj["rendered"])) + } else { + titleRaw = wave3K2CleanText(wave3K2StringVal(p["title"])) + } + if titleRaw == "" { + return nil, false + } + link := SanitizeSchemaHTTPSURL(p["link"], origURL) + date := wave3K2Plain(wave3K2FirstNonEmpty(wave3K2StringVal(p["date_gmt"]), wave3K2StringVal(p["date"])), 48) + contentObj := wave3K2Map(p["content"]) + excerptObj := wave3K2Map(p["excerpt"]) + contentHTML := "" + if contentObj != nil { + contentHTML = wave3K2StringVal(contentObj["rendered"]) + } + excerptHTML := "" + if excerptObj != nil { + excerptHTML = wave3K2StringVal(excerptObj["rendered"]) + } + bodyMD := wave3K2FragToMD(contentHTML, origURL) + if bodyMD == "" { + bodyMD = wave3K2FragToMD(excerptHTML, origURL) + } + if bodyMD == "" { + return nil, false + } + var bullets []string + bullets = append(bullets, "- **Agency**: "+escapeDeclMarkdownBrackets(agency)) + if date != "" { + bullets = append(bullets, "- **Published**: "+escapeDeclMarkdownBrackets(date)) + } + if idStr := wave3K2Plain(p["id"], 32); idStr != "" { + bullets = append(bullets, "- **Post ID**: `"+sanitizeDeclInlineCodeVal(idStr)+"`") + } + if link != "" { + bullets = append(bullets, "- **Canonical URL**: ["+link+"]("+link+")") + } + var links []string + if link != "" { + links = append(links, link) + } + return &DeclarativeFormattedDoc{ + Title: titleRaw, + Author: agency, + PublishedTime: date, + Markdown: "# " + escapeDeclMarkdownBrackets(titleRaw) + "\n\n" + wave3K2JoinBullets(bullets) + "\n\n" + bodyMD, + Links: links, + Records: []map[string]any{{ + "id": wave3K2Plain(p["id"], 32), + "title": titleRaw, + "date": date, + "url": link, + "publisher": agency, + }}, + }, true + } + + var rows [][]string + var records []map[string]any + var links []string + seen := make(map[string]bool) + for _, p := range posts { + if len(records) >= wave3K2MaxRecords { + break + } + titleObj := wave3K2Map(p["title"]) + titleRaw := "" + if titleObj != nil { + titleRaw = wave3K2CleanText(wave3K2StringVal(titleObj["rendered"])) + } else { + titleRaw = wave3K2CleanText(wave3K2StringVal(p["title"])) + } + if titleRaw == "" { + continue + } + link := SanitizeSchemaHTTPSURL(p["link"], origURL) + date := wave3K2Plain(wave3K2FirstNonEmpty(wave3K2StringVal(p["date_gmt"]), wave3K2StringVal(p["date"])), 48) + if link != "" { + wave3K2AddLink(&links, seen, link, origURL) + } + records = append(records, map[string]any{ + "id": wave3K2Plain(p["id"], 32), + "title": titleRaw, + "date": date, + "url": link, + "publisher": agency, + }) + cell := escapeDeclMarkdownBrackets(titleRaw) + if link != "" { + cell = "[" + cell + "](" + link + ")" + } + rows = append(rows, []string{cell, date}) + } + if len(records) == 0 { + return nil, false + } + title := agency + " — Newsroom Posts" + return &DeclarativeFormattedDoc{ + Title: title, + Author: agency, + Markdown: "# " + escapeDeclMarkdownBrackets(title) + "\n\n" + formatDeclarativeGFMTable([]string{"Title", "Published"}, rows), + Links: links, + Records: records, + Total: wave3K2IntPtr(len(posts)), + Returned: wave3K2IntPtr(len(records)), + Truncated: wave3K2BoolPtr(len(posts) > len(records)), + }, true +} + +func wave3K2ExtractGovWPHTML(rawHTML, probeLower, baseURL, extractorID string) *DeclarativePostFetchResult { + h1 := wave3K2ExtractH1(rawHTML) + ogTitle := wave3K2ExtractMeta(rawHTML, "og:title") + rawTitle := extractTitleLinearQuick(rawHTML) + title := wave3K2FirstNonEmpty(h1, ogTitle, rawTitle) + if title == "" || wave3K2IsNegativeTitle(title) || wave3K2IsGenericTitle(title) { + return nil + } + if strings.Contains(probeLower, "nothing found") && len(rawHTML) < 16384 { + return nil + } + agency := wave3K2GovAgencyName(baseURL) + pubDate := wave3K2FirstNonEmpty( + wave3K2ExtractMeta(rawHTML, "article:published_time"), + wave3K2ExtractMeta(rawHTML, "article:modified_time"), + ) + desc := wave3K2ExtractMeta(rawHTML, "description") + bodyMD := wave3K2ExtractMainHTML(rawHTML, baseURL) + if bodyMD == "" && desc == "" { + return nil + } + + var bullets []string + bullets = append(bullets, "- **Agency**: "+escapeDeclMarkdownBrackets(agency)) + if pubDate != "" { + bullets = append(bullets, "- **Published**: "+escapeDeclMarkdownBrackets(pubDate)) + } + var blocks []string + blocks = append(blocks, "# "+escapeDeclMarkdownBrackets(title)) + blocks = append(blocks, wave3K2JoinBullets(bullets)) + if bodyMD != "" { + blocks = append(blocks, bodyMD) + } else { + blocks = append(blocks, escapeDeclMarkdownBlock(desc)) + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Author: agency, + PublishedTime: pubDate, + Markdown: strings.Join(blocks, "\n\n"), + } +} + +// ── #293 GSA Site Scanning ────────────────────────────────────────────────────────────────────── + +func wave3K2FormatGSASiteScanningJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + obj := wave3K2Map(parsed) + if obj == nil || wave3K2IsGenericJSONError(obj) { + return nil, false + } + + var items []map[string]any + if rawItems := wave3K2Slice(obj["items"]); rawItems != nil { + for _, el := range rawItems { + if m := wave3K2Map(el); m != nil { + items = append(items, m) + } + } + } else if _, hasDom := obj["initial_base_domain"]; hasDom { + items = []map[string]any{obj} + } else if _, hasDom2 := obj["target_url_domain"]; hasDom2 { + items = []map[string]any{obj} + } + if len(items) == 0 { + return nil, false + } + + var rows [][]string + var records []map[string]any + var links []string + seen := make(map[string]bool) + + for _, it := range items { + if len(records) >= wave3K2MaxRecords { + break + } + dom := wave3K2Plain(firstNonNilSchemaGo(it["initial_base_domain"], it["target_url_domain"], it["final_url_domain"]), 120) + finalU := SanitizeSchemaHTTPSURL(it["final_url"], origURL) + agency := wave3K2Plain(it["agency"], 120) + bureau := wave3K2Plain(it["bureau"], 120) + scanDate := wave3K2Plain(it["scan_date"], 48) + status := wave3K2Plain(firstNonNilSchemaGo(it["final_url_status_code"], it["primary_scan_status"]), 32) + uswds := wave3K2Plain(it["uswds_semantic_version"], 32) + dap := wave3K2Plain(it["dap_detected"], 16) + if dom == "" && finalU == "" { + continue + } + if finalU != "" { + wave3K2AddLink(&links, seen, finalU, origURL) + } + rec := map[string]any{ + "domain": dom, + "finalUrl": finalU, + "agency": agency, + "bureau": bureau, + "scanDate": scanDate, + "status": status, + "uswds": uswds, + "dap": dap, + } + records = append(records, rec) + rows = append(rows, []string{ + "`" + sanitizeDeclInlineCodeVal(dom) + "`", + escapeDeclMarkdownBrackets(wave3K2FirstNonEmpty(agency, bureau, "-")), + status, + uswds, + dap, + }) + } + if len(records) == 0 { + return nil, false + } + + title := "GSA Site Scanning Websites" + if len(records) == 1 { + if dom, ok := records[0]["domain"].(string); ok && dom != "" { + title = "GSA Site Scan: " + dom + } + } + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: "# " + escapeDeclMarkdownBrackets(title) + "\n\n" + formatDeclarativeGFMTable([]string{"Domain", "Agency", "Status", "USWDS", "DAP"}, rows), + Links: links, + Records: records, + Total: wave3K2IntPtr(len(items)), + Returned: wave3K2IntPtr(len(records)), + Truncated: wave3K2BoolPtr(len(items) > len(records)), + }, true +} + +func wave3K2ExtractGSAHTML(rawHTML, probeLower, baseURL, extractorID string) *DeclarativePostFetchResult { + h1 := wave3K2ExtractH1(rawHTML) + title := wave3K2FirstNonEmpty(h1, wave3K2ExtractMeta(rawHTML, "og:title"), extractTitleLinearQuick(rawHTML)) + if title == "" || wave3K2IsNegativeTitle(title) || wave3K2IsGenericTitle(title) { + return nil + } + bodyMD := wave3K2ExtractMainHTML(rawHTML, baseURL) + if bodyMD == "" { + return nil + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Markdown: "# " + escapeDeclMarkdownBrackets(title) + "\n\n- **Source**: GSA Site Scanning\n\n" + bodyMD, + } +} + +// ── #294 VA Lighthouse Facilities ─────────────────────────────────────────────────────────────── + +func wave3K2FormatVAFacilitiesJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + obj := wave3K2Map(parsed) + if obj == nil || wave3K2IsGenericJSONError(obj) { + return nil, false + } + + var rawFacilities []map[string]any + switch d := obj["data"].(type) { + case []any: + for _, el := range d { + if m := wave3K2Map(el); m != nil { + rawFacilities = append(rawFacilities, m) + } + } + case map[string]any: + rawFacilities = []map[string]any{d} + } + if len(rawFacilities) == 0 { + return nil, false + } + + var rows [][]string + var records []map[string]any + var links []string + seen := make(map[string]bool) + + for _, fac := range rawFacilities { + if len(records) >= wave3K2MaxRecords { + break + } + facID := wave3K2Plain(fac["id"], 64) + attrs := wave3K2Map(fac["attributes"]) + if attrs == nil { + attrs = fac + } + name := wave3K2Plain(attrs["name"], 200) + if name == "" && facID == "" { + continue + } + facType := wave3K2Plain(attrs["facilityType"], 80) + classification := wave3K2Plain(attrs["classification"], 120) + website := SanitizeSchemaHTTPSURL(attrs["website"], origURL) + if website != "" { + wave3K2AddLink(&links, seen, website, origURL) + } + phone := "" + if ph := wave3K2Map(attrs["phone"]); ph != nil { + phone = wave3K2Plain(ph["main"], 48) + } + addrStr := "" + if addr := wave3K2Map(attrs["address"]); addr != nil { + if phys := wave3K2Map(addr["physical"]); phys != nil { + addrStr = strings.TrimSpace(strings.Join([]string{ + wave3K2Plain(phys["address1"], 120), + wave3K2Plain(phys["city"], 64), + wave3K2Plain(phys["state"], 16), + wave3K2Plain(phys["zip"], 20), + }, ", ")) + addrStr = strings.Trim(addrStr, ", ") + } + } + opStatus := "" + if osMap := wave3K2Map(attrs["operatingStatus"]); osMap != nil { + opStatus = wave3K2Plain(osMap["code"], 40) + } + + records = append(records, map[string]any{ + "id": facID, + "name": name, + "facilityType": facType, + "classification": classification, + "address": addrStr, + "phone": phone, + "status": opStatus, + "website": website, + }) + nameCell := escapeDeclMarkdownBrackets(name) + if website != "" { + nameCell = "[" + nameCell + "](" + website + ")" + } + rows = append(rows, []string{"`" + sanitizeDeclInlineCodeVal(facID) + "`", nameCell, wave3K2FirstNonEmpty(classification, facType), addrStr, phone, opStatus}) + } + + if len(records) == 0 { + return nil, false + } + + title := "VA Facilities Directory" + if len(records) == 1 { + if n, ok := records[0]["name"].(string); ok && n != "" { + title = n + } + } + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: "# " + escapeDeclMarkdownBrackets(title) + "\n\n" + formatDeclarativeGFMTable([]string{"ID", "Facility", "Type", "Address", "Phone", "Status"}, rows), + Links: links, + Records: records, + Total: wave3K2IntPtr(len(rawFacilities)), + Returned: wave3K2IntPtr(len(records)), + Truncated: wave3K2BoolPtr(len(rawFacilities) > len(records)), + }, true +} + +func wave3K2ExtractVAFacilitiesHTML(rawHTML, probeLower, baseURL, extractorID string) *DeclarativePostFetchResult { + // Reject unhydrated VA React locator shells when there is no rendered heading/content. + if strings.Contains(probeLower, `id="react-root"`) && !strings.Contains(probeLower, " 0 { + var rows [][]string + var records []map[string]any + var links []string + seen := make(map[string]bool) + for _, el := range rawPlans { + if len(records) >= wave3K2MaxRecords { + break + } + pm := wave3K2Map(el) + if pm == nil { + continue + } + id := wave3K2Plain(pm["id"], 64) + name := wave3K2Plain(pm["name"], 200) + metal := wave3K2Plain(pm["metal_level"], 32) + ptype := wave3K2Plain(pm["type"], 32) + issuerName := "" + if iss := wave3K2Map(pm["issuer"]); iss != nil { + issuerName = wave3K2Plain(iss["name"], 120) + } + prem := wave3K2Plain(pm["premium"], 24) + premCredit := wave3K2Plain(pm["premium_w_credit"], 24) + if urlVal := SanitizeSchemaHTTPSURL(firstNonNilSchemaGo(pm["benefits_url"], pm["brochure_url"]), origURL); urlVal != "" { + wave3K2AddLink(&links, seen, urlVal, origURL) + } + if id == "" && name == "" { + continue + } + records = append(records, map[string]any{ + "id": id, + "name": name, + "issuer": issuerName, + "metalLevel": metal, + "planType": ptype, + "premium": prem, + "premiumWithCredit": premCredit, + }) + rows = append(rows, []string{ + "`" + sanitizeDeclInlineCodeVal(id) + "`", + escapeDeclMarkdownBrackets(name), + escapeDeclMarkdownBrackets(issuerName), + metal, + ptype, + wave3K2FirstNonEmpty(premCredit, prem), + }) + } + if len(records) == 0 { + return nil, false + } + title := "HealthCare.gov Marketplace Plans" + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: "# " + title + "\n\n" + formatDeclarativeGFMTable([]string{"Plan ID", "Plan Name", "Issuer", "Metal", "Type", "Premium"}, rows), + Links: links, + Records: records, + Total: wave3K2IntPtr(len(rawPlans)), + Returned: wave3K2IntPtr(len(records)), + Truncated: wave3K2BoolPtr(len(rawPlans) > len(records)), + }, true + } + + if singlePlan := wave3K2Map(obj["plan"]); singlePlan != nil { + id := wave3K2Plain(singlePlan["id"], 64) + name := wave3K2Plain(singlePlan["name"], 200) + if id == "" && name == "" { + return nil, false + } + metal := wave3K2Plain(singlePlan["metal_level"], 32) + ptype := wave3K2Plain(singlePlan["type"], 32) + prem := wave3K2Plain(singlePlan["premium"], 24) + title := wave3K2FirstNonEmpty(name, id) + var bullets []string + if id != "" { + bullets = append(bullets, "- **Plan ID**: `"+sanitizeDeclInlineCodeVal(id)+"`") + } + if metal != "" { + bullets = append(bullets, "- **Metal Level**: "+metal) + } + if ptype != "" { + bullets = append(bullets, "- **Plan Type**: "+ptype) + } + if prem != "" { + bullets = append(bullets, "- **Premium**: $"+prem) + } + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: "# " + escapeDeclMarkdownBrackets(title) + "\n\n" + wave3K2JoinBullets(bullets), + Records: []map[string]any{{ + "id": id, + "name": name, + "metalLevel": metal, + "planType": ptype, + "premium": prem, + }}, + }, true + } + + if rawStates := wave3K2Slice(obj["states"]); len(rawStates) > 0 { + var rows [][]string + var records []map[string]any + for _, el := range rawStates { + if len(records) >= wave3K2MaxRecords { + break + } + sm := wave3K2Map(el) + if sm == nil { + continue + } + abbr := wave3K2Plain(sm["abbrev"], 16) + name := wave3K2Plain(sm["name"], 120) + model := wave3K2Plain(sm["marketplace_model"], 64) + if abbr == "" && name == "" { + continue + } + records = append(records, map[string]any{"abbrev": abbr, "name": name, "marketplaceModel": model}) + rows = append(rows, []string{abbr, escapeDeclMarkdownBrackets(name), model}) + } + if len(records) == 0 { + return nil, false + } + title := "HealthCare.gov Marketplace States" + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: "# " + title + "\n\n" + formatDeclarativeGFMTable([]string{"State", "Name", "Model"}, rows), + Records: records, + Total: wave3K2IntPtr(len(rawStates)), + Returned: wave3K2IntPtr(len(records)), + Truncated: wave3K2BoolPtr(len(rawStates) > len(records)), + }, true + } + + if rawCounties := wave3K2Slice(obj["counties"]); len(rawCounties) > 0 { + var rows [][]string + var records []map[string]any + for _, el := range rawCounties { + if len(records) >= wave3K2MaxRecords { + break + } + cm := wave3K2Map(el) + if cm == nil { + continue + } + fips := wave3K2Plain(cm["fips"], 16) + name := wave3K2Plain(cm["name"], 120) + state := wave3K2Plain(cm["state"], 16) + zip := wave3K2Plain(cm["zipcode"], 16) + if fips == "" && name == "" { + continue + } + records = append(records, map[string]any{"fips": fips, "name": name, "state": state, "zipcode": zip}) + rows = append(rows, []string{"`" + sanitizeDeclInlineCodeVal(fips) + "`", escapeDeclMarkdownBrackets(name), state, zip}) + } + if len(records) == 0 { + return nil, false + } + title := "HealthCare.gov Marketplace Counties" + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: "# " + title + "\n\n" + formatDeclarativeGFMTable([]string{"FIPS", "County", "State", "ZIP"}, rows), + Records: records, + Total: wave3K2IntPtr(len(rawCounties)), + Returned: wave3K2IntPtr(len(records)), + Truncated: wave3K2BoolPtr(len(rawCounties) > len(records)), + }, true + } + + return nil, false +} + +func wave3K2ExtractHealthcareGovHTML(rawHTML, probeLower, baseURL, extractorID string) *DeclarativePostFetchResult { + h1 := wave3K2ExtractH1(rawHTML) + title := wave3K2FirstNonEmpty(h1, wave3K2ExtractMeta(rawHTML, "og:title"), extractTitleLinearQuick(rawHTML)) + title = strings.TrimSpace(strings.TrimSuffix(title, "| HealthCare.gov")) + if title == "" || wave3K2IsNegativeTitle(title) || wave3K2IsGenericTitle(title) { + return nil + } + bodyMD := wave3K2ExtractMainHTML(rawHTML, baseURL) + if bodyMD == "" { + return nil + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: wave3K2ExtractMeta(rawHTML, "description"), + Markdown: "# " + escapeDeclMarkdownBrackets(title) + "\n\n- **Source**: HealthCare.gov\n\n" + bodyMD, + } +} + +// ── #296 CMS Price Transparency (HPT, MRF JSON, MRF CSV, Archive Magic, HTML) ─────────────────── + +func wave3K2DetectArchiveFormat(raw []byte) string { + if len(raw) >= 4 && raw[0] == 'P' && raw[1] == 'K' && raw[2] == 0x03 && raw[3] == 0x04 { + return "zip" + } + if len(raw) >= 2 && raw[0] == 0x1f && raw[1] == 0x8b { + return "gzip" + } + // Handle UTF-8 encoded 0x1f 0x8b when passed as a JS string across the WASM boundary. + if len(raw) >= 3 && raw[0] == 0x1f && raw[1] == 0xc2 && raw[2] == 0x8b { + return "gzip" + } + return "" +} + +func wave3K2FormatCMSArchiveDoc(formatName string, sampleBytes int, origURL string) *DeclarativeFormattedDoc { + upper := strings.ToUpper(formatName) + title := "CMS Machine-Readable Archive (" + upper + ")" + bullets := []string{ + "- **Format**: `" + upper + "`", + fmt.Sprintf("- **Sample Bytes Read**: %d", sampleBytes), + "- **Status**: Compressed archive detected via magic bytes; download and decompress offline for full charge tables.", + } + if safeU := SanitizeSchemaHTTPSURL(origURL, origURL); safeU != "" { + bullets = append(bullets, "- **Source URL**: ["+safeU+"]("+safeU+")") + } + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: "# " + title + "\n\n" + wave3K2JoinBullets(bullets), + Records: []map[string]any{{ + "format": formatName, + "archive": true, + "sampleBytes": sampleBytes, + "url": SanitizeSchemaHTTPSURL(origURL, origURL), + }}, + } +} + +func wave3K2FormatCMSHPTTxt(rawBody, origURL string) (*DeclarativeFormattedDoc, bool) { + lowerHead := asciiLowerExtractString(rawBody) + if len(lowerHead) > 4096 { + lowerHead = lowerHead[:4096] + } + if isLikelyHTMLSoft404(rawBody) || wave3K2HasWAFOrChallengeMarkers(lowerHead) { + return nil, false + } + + type hptStanza struct { + locationName string + sourcePageURL string + mrfURL string + contactName string + contactEmail string + lastUpdated string + hospitalName string + } + + var stanzas []hptStanza + var cur hptStanza + hasFields := false + flush := func() { + if !hasFields { + return + } + if cur.locationName != "" || cur.mrfURL != "" || cur.sourcePageURL != "" || cur.hospitalName != "" { + stanzas = append(stanzas, cur) + } + cur = hptStanza{} + hasFields = false + } + + norm := strings.ReplaceAll(strings.TrimPrefix(rawBody, "\ufeff"), "\r\n", "\n") + for _, rawLine := range strings.Split(norm, "\n") { + line := strings.TrimSpace(rawLine) + if line == "" { + flush() + continue + } + if strings.HasPrefix(line, "#") { + continue + } + colon := strings.IndexByte(line, ':') + if colon <= 0 { + continue + } + key := strings.ToLower(strings.TrimSpace(line[:colon])) + val := strings.TrimSpace(line[colon+1:]) + if val == "" { + continue + } + // Start a new stanza automatically if location-name repeats without blank line + if key == "location-name" && hasFields && cur.locationName != "" { + flush() + } + switch key { + case "location-name": + cur.locationName = val + hasFields = true + case "hospital-name": + cur.hospitalName = val + hasFields = true + case "source-page-url": + cur.sourcePageURL = val + hasFields = true + case "mrf-url": + cur.mrfURL = val + hasFields = true + case "contact-name": + cur.contactName = val + hasFields = true + case "contact-email": + cur.contactEmail = val + hasFields = true + case "last-updated": + cur.lastUpdated = val + hasFields = true + } + } + flush() + + if len(stanzas) == 0 { + return nil, false + } + + var rows [][]string + var records []map[string]any + var links []string + seen := make(map[string]bool) + + for i, st := range stanzas { + if i >= wave3K2MaxHPTLocations { + break + } + mrfSafe := SanitizeSchemaHTTPSURL(st.mrfURL, origURL) + srcSafe := SanitizeSchemaHTTPSURL(st.sourcePageURL, origURL) + if mrfSafe != "" { + wave3K2AddLink(&links, seen, mrfSafe, origURL) + } + if srcSafe != "" { + wave3K2AddLink(&links, seen, srcSafe, origURL) + } + loc := wave3K2FirstNonEmpty(st.locationName, st.hospitalName, "-") + mrfCell := "-" + if mrfSafe != "" { + mrfCell = "[MRF](" + mrfSafe + ")" + } + srcCell := "-" + if srcSafe != "" { + srcCell = "[Source](" + srcSafe + ")" + } + rows = append(rows, []string{escapeDeclMarkdownBrackets(loc), mrfCell, srcCell, escapeDeclMarkdownBrackets(st.contactEmail)}) + if len(records) < wave3K2MaxRecords { + records = append(records, map[string]any{ + "locationName": loc, + "mrfUrl": mrfSafe, + "sourcePageUrl": srcSafe, + "contactName": st.contactName, + "contactEmail": st.contactEmail, + "lastUpdated": st.lastUpdated, + }) + } + } + + title := "CMS Hospital Price Transparency (cms-hpt.txt)" + if len(stanzas) > 0 { + if firstLoc := wave3K2FirstNonEmpty(stanzas[0].hospitalName, stanzas[0].locationName); firstLoc != "" { + title = firstLoc + " — CMS HPT Index" + } + } + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: "# " + escapeDeclMarkdownBrackets(title) + "\n\n" + fmt.Sprintf("- **Locations Listed**: %d\n\n", len(stanzas)) + formatDeclarativeGFMTable([]string{"Location", "MRF URL", "Source Page", "Contact"}, rows), + Links: links, + Records: records, + Total: wave3K2IntPtr(len(stanzas)), + Returned: wave3K2IntPtr(len(records)), + Truncated: wave3K2BoolPtr(len(stanzas) > len(records)), + }, true +} + +func wave3K2FormatCMSMRFJSON(raw []byte, origURL string) (*DeclarativeFormattedDoc, bool) { + trimmed := bytes.TrimSpace(bytes.TrimPrefix(raw, []byte("\xEF\xBB\xBF"))) + if len(trimmed) == 0 || trimmed[0] != '{' { + return nil, false + } + + dec := json.NewDecoder(bytes.NewReader(trimmed)) + dec.UseNumber() + + tok, err := dec.Token() + if err != nil { + return nil, false + } + delim, ok := tok.(json.Delim) + if !ok || delim != '{' { + return nil, false + } + + var hospitalName, lastUpdated, version, entityName, entityType string + var locationNames, addresses, npis []string + var chargeRows [][]string + var chargeRecords []map[string]any + var ticRows [][]string + var ticRecords []map[string]any + var blobRows [][]string + var blobRecords []map[string]any + var links []string + seenLinks := make(map[string]bool) + hasMRFSignal := false + + for dec.More() { + kt, kErr := dec.Token() + if kErr != nil { + break + } + key, isKey := kt.(string) + if !isKey { + break + } + switch key { + case "hospital_name": + var v any + if dec.Decode(&v) != nil { + goto doneStream + } + hospitalName = wave3K2Plain(v, 200) + if hospitalName != "" { + hasMRFSignal = true + } + case "reporting_entity_name": + var v any + if dec.Decode(&v) != nil { + goto doneStream + } + entityName = wave3K2Plain(v, 200) + if entityName != "" { + hasMRFSignal = true + } + case "reporting_entity_type": + var v any + if dec.Decode(&v) != nil { + goto doneStream + } + entityType = wave3K2Plain(v, 120) + case "last_updated_on": + var v any + if dec.Decode(&v) != nil { + goto doneStream + } + lastUpdated = wave3K2Plain(v, 64) + case "version": + var v any + if dec.Decode(&v) != nil { + goto doneStream + } + version = wave3K2Plain(v, 32) + case "location_name": + var v any + if dec.Decode(&v) != nil { + goto doneStream + } + switch tv := v.(type) { + case string: + if s := wave3K2Plain(tv, 160); s != "" { + locationNames = append(locationNames, s) + } + case []any: + for _, el := range tv { + if len(locationNames) >= 10 { + break + } + if s := wave3K2Plain(el, 160); s != "" { + locationNames = append(locationNames, s) + } + } + } + case "hospital_address": + var v any + if dec.Decode(&v) != nil { + goto doneStream + } + switch tv := v.(type) { + case string: + if s := wave3K2Plain(tv, 200); s != "" { + addresses = append(addresses, s) + } + case []any: + for _, el := range tv { + if len(addresses) >= 10 { + break + } + if s := wave3K2Plain(el, 200); s != "" { + addresses = append(addresses, s) + } + } + } + case "type_2_npi": + var v any + if dec.Decode(&v) != nil { + goto doneStream + } + switch tv := v.(type) { + case string, json.Number: + if s := wave3K2Plain(tv, 32); s != "" { + npis = append(npis, s) + } + case []any: + for _, el := range tv { + if len(npis) >= 10 { + break + } + if s := wave3K2Plain(el, 32); s != "" { + npis = append(npis, s) + } + } + } + case "standard_charge_information": + hasMRFSignal = true + arrTok, aErr := dec.Token() + if aErr != nil { + goto doneStream + } + if arrDelim, isArr := arrTok.(json.Delim); isArr && arrDelim == '[' { + for dec.More() && len(chargeRecords) < wave3K2MaxRecords { + var item map[string]any + if iErr := dec.Decode(&item); iErr != nil { + goto doneStream + } + desc := wave3K2Plain(item["description"], 200) + codeStr, codeType := "", "" + for _, ci := range wave3K2Slice(item["code_information"]) { + cm := wave3K2Map(ci) + if cm == nil { + continue + } + codeStr = wave3K2Plain(cm["code"], 40) + codeType = wave3K2Plain(cm["type"], 32) + if codeStr != "" { + break + } + } + gross, cash, minChg, maxChg := "", "", "", "" + for _, sc := range wave3K2Slice(item["standard_charges"]) { + sm := wave3K2Map(sc) + if sm == nil { + continue + } + gross = wave3K2FirstNonEmpty(gross, wave3K2Plain(sm["gross_charge"], 24)) + cash = wave3K2FirstNonEmpty(cash, wave3K2Plain(sm["discounted_cash"], 24)) + minChg = wave3K2FirstNonEmpty(minChg, wave3K2Plain(sm["minimum"], 24)) + maxChg = wave3K2FirstNonEmpty(maxChg, wave3K2Plain(sm["maximum"], 24)) + } + chargeRecords = append(chargeRecords, map[string]any{ + "description": desc, + "code": codeStr, + "codeType": codeType, + "grossCharge": gross, + "discountedCash": cash, + "minimumCharge": minChg, + "maximumCharge": maxChg, + }) + chargeRows = append(chargeRows, []string{ + escapeDeclMarkdownBrackets(desc), + wave3K2FirstNonEmpty(codeType+" "+codeStr, "-"), + gross, + cash, + }) + } + // Stop scanning once bounded sample is collected to keep bounded 2 MiB parsing fast. + if len(chargeRecords) >= wave3K2MaxRecords { + goto doneStream + } + } + case "reporting_structure": + hasMRFSignal = true + arrTok, aErr := dec.Token() + if aErr != nil { + goto doneStream + } + if arrDelim, isArr := arrTok.(json.Delim); isArr && arrDelim == '[' { + for dec.More() && len(ticRecords) < wave3K2MaxRecords { + var entry map[string]any + if iErr := dec.Decode(&entry); iErr != nil { + goto doneStream + } + var planNames []string + for _, rp := range wave3K2Slice(entry["reporting_plans"]) { + pm := wave3K2Map(rp) + if pm == nil { + continue + } + if pn := wave3K2Plain(pm["plan_name"], 120); pn != "" && len(planNames) < 3 { + planNames = append(planNames, pn) + } + } + var fileURLs []string + for _, inf := range wave3K2Slice(entry["in_network_files"]) { + fm := wave3K2Map(inf) + if fm == nil { + continue + } + if loc := SanitizeSchemaHTTPSURL(fm["location"], origURL); loc != "" { + wave3K2AddLink(&links, seenLinks, loc, origURL) + if len(fileURLs) < 2 { + fileURLs = append(fileURLs, loc) + } + } + } + if aa := wave3K2Map(entry["allowed_amount_file"]); aa != nil { + if loc := SanitizeSchemaHTTPSURL(aa["location"], origURL); loc != "" { + wave3K2AddLink(&links, seenLinks, loc, origURL) + } + } + plansJoined := strings.Join(planNames, "; ") + fileCell := "-" + if len(fileURLs) > 0 { + fileCell = "[MRF](" + fileURLs[0] + ")" + } + ticRecords = append(ticRecords, map[string]any{ + "plans": plansJoined, + "inNetworkFiles": len(wave3K2Slice(entry["in_network_files"])), + "sampleFileUrl": wave3K2FirstNonEmpty(append(fileURLs, "")[0]), + }) + ticRows = append(ticRows, []string{ + escapeDeclMarkdownBrackets(wave3K2FirstNonEmpty(plansJoined, "Plan Group")), + strconv.Itoa(len(wave3K2Slice(entry["in_network_files"]))), + fileCell, + }) + } + if len(ticRecords) >= wave3K2MaxRecords { + goto doneStream + } + } + case "blobs": + hasMRFSignal = true + arrTok, aErr := dec.Token() + if aErr != nil { + goto doneStream + } + if arrDelim, isArr := arrTok.(json.Delim); isArr && arrDelim == '[' { + for dec.More() && len(blobRecords) < wave3K2MaxRecords { + var b map[string]any + if iErr := dec.Decode(&b); iErr != nil { + goto doneStream + } + bName := wave3K2Plain(b["name"], 180) + dl := SanitizeSchemaHTTPSURL(b["downloadUrl"], origURL) + sz := wave3K2Plain(b["size"], 32) + if dl != "" { + wave3K2AddLink(&links, seenLinks, dl, origURL) + } + if bName == "" && dl == "" { + continue + } + blobRecords = append(blobRecords, map[string]any{ + "name": bName, + "downloadUrl": dl, + "size": sz, + }) + nameCell := escapeDeclMarkdownBrackets(bName) + if dl != "" { + nameCell = "[" + nameCell + "](" + dl + ")" + } + blobRows = append(blobRows, []string{nameCell, sz}) + } + if len(blobRecords) >= wave3K2MaxRecords { + goto doneStream + } + } + default: + if skipJSONValue(dec) != nil { + goto doneStream + } + } + } + +doneStream: + if !hasMRFSignal { + return nil, false + } + + if len(blobRecords) > 0 { + title := "UHC Transparency in Coverage Index" + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: "# " + title + "\n\n" + formatDeclarativeGFMTable([]string{"File", "Size (Bytes)"}, blobRows), + Links: links, + Records: blobRecords, + Returned: wave3K2IntPtr(len(blobRecords)), + Truncated: wave3K2BoolPtr(len(blobRecords) >= wave3K2MaxRecords), + }, true + } + + if entityName != "" || len(ticRecords) > 0 { + title := wave3K2FirstNonEmpty(entityName, "CMS Transparency in Coverage Table of Contents") + var bullets []string + if entityType != "" { + bullets = append(bullets, "- **Reporting Entity Type**: "+escapeDeclMarkdownBrackets(entityType)) + } + if lastUpdated != "" { + bullets = append(bullets, "- **Last Updated**: "+escapeDeclMarkdownBrackets(lastUpdated)) + } + if version != "" { + bullets = append(bullets, "- **Schema Version**: `"+sanitizeDeclInlineCodeVal(version)+"`") + } + var md []string + md = append(md, "# "+escapeDeclMarkdownBrackets(title)) + if len(bullets) > 0 { + md = append(md, wave3K2JoinBullets(bullets)) + } + if len(ticRows) > 0 { + md = append(md, formatDeclarativeGFMTable([]string{"Reporting Plans", "In-Network Files", "Sample File"}, ticRows)) + } + return &DeclarativeFormattedDoc{ + Title: title, + PublishedTime: lastUpdated, + Markdown: strings.Join(md, "\n\n"), + Links: links, + Records: ticRecords, + Returned: wave3K2IntPtr(len(ticRecords)), + Truncated: wave3K2BoolPtr(len(ticRecords) >= wave3K2MaxRecords), + }, true + } + + title := wave3K2FirstNonEmpty(hospitalName, "Hospital Standard Charges MRF") + var bullets []string + if lastUpdated != "" { + bullets = append(bullets, "- **Last Updated**: "+escapeDeclMarkdownBrackets(lastUpdated)) + } + if version != "" { + bullets = append(bullets, "- **CMS Version**: `"+sanitizeDeclInlineCodeVal(version)+"`") + } + if len(locationNames) > 0 { + bullets = append(bullets, "- **Locations**: "+escapeDeclMarkdownBrackets(strings.Join(locationNames, ", "))) + } + if len(addresses) > 0 { + bullets = append(bullets, "- **Address**: "+escapeDeclMarkdownBrackets(strings.Join(addresses, "; "))) + } + if len(npis) > 0 { + bullets = append(bullets, "- **Type 2 NPI**: `"+sanitizeDeclInlineCodeVal(strings.Join(npis, ", "))+"`") + } + + var md []string + md = append(md, "# "+escapeDeclMarkdownBrackets(title)) + if len(bullets) > 0 { + md = append(md, wave3K2JoinBullets(bullets)) + } + if len(chargeRows) > 0 { + md = append(md, "## Sample Standard Charges\n\n"+formatDeclarativeGFMTable([]string{"Description", "Code", "Gross Charge", "Discounted Cash"}, chargeRows)) + } + return &DeclarativeFormattedDoc{ + Title: title, + PublishedTime: lastUpdated, + Markdown: strings.Join(md, "\n\n"), + Records: chargeRecords, + Returned: wave3K2IntPtr(len(chargeRecords)), + Truncated: wave3K2BoolPtr(len(chargeRecords) >= wave3K2MaxRecords), + }, true +} + +func wave3K2FormatCMSMRFCSV(rawBody, origURL string) (*DeclarativeFormattedDoc, bool) { + if isLikelyHTMLSoft404(rawBody) { + return nil, false + } + clean := strings.TrimPrefix(rawBody, "\ufeff") + r := csv.NewReader(strings.NewReader(clean)) + r.FieldsPerRecord = -1 + + row0, err0 := r.Read() + if err0 != nil || len(row0) < 2 { + return nil, false + } + + // CMS MRF v2/v3 CSV puts metadata headers in Row 0, metadata values in Row 1, charge headers in Row 2, and charge rows in Row 3+. + metaHeaders := make(map[string]int, len(row0)) + for i, h := range row0 { + metaHeaders[strings.ToLower(strings.TrimSpace(h))] = i + } + _, hasHospName := metaHeaders["hospital_name"] + _, hasVersion := metaHeaders["version"] + _, hasLastUpd := metaHeaders["last_updated_on"] + + if hasHospName || hasVersion || hasLastUpd { + row1, err1 := r.Read() + if err1 != nil { + return nil, false + } + getMeta := func(keys ...string) string { + for _, k := range keys { + for hName, idx := range metaHeaders { + if (hName == k || strings.HasPrefix(hName, k+"|")) && idx < len(row1) { + if v := strings.TrimSpace(row1[idx]); v != "" { + return v + } + } + } + } + return "" + } + + hospName := getMeta("hospital_name") + lastUpd := getMeta("last_updated_on") + version := getMeta("version") + locName := getMeta("location_name") + hospAddr := getMeta("hospital_address") + npi := getMeta("type_2_npi") + licenseNum := getMeta("license_number") + + var chargeHeaders []string + if row2, err2 := r.Read(); err2 == nil { + chargeHeaders = row2 + } + + var chargeRows [][]string + var records []map[string]any + if len(chargeHeaders) > 0 { + chIdx := make(map[string]int, len(chargeHeaders)) + for i, h := range chargeHeaders { + chIdx[strings.ToLower(strings.TrimSpace(h))] = i + } + getCell := func(row []string, candidates ...string) string { + for _, c := range candidates { + if idx, ok := chIdx[c]; ok && idx < len(row) { + if v := strings.TrimSpace(row[idx]); v != "" { + return v + } + } + } + return "" + } + for len(records) < wave3K2MaxRecords { + crow, cErr := r.Read() + if cErr != nil { + // Tolerate io.EOF or truncated quote at the 2 MiB boundary. + break + } + desc := getCell(crow, "description") + code := getCell(crow, "code|1", "code") + codeType := getCell(crow, "code|1|type", "code_type") + gross := getCell(crow, "standard_charge|gross", "gross_charge") + cash := getCell(crow, "standard_charge|discounted_cash", "discounted_cash") + if desc == "" && code == "" { + continue + } + records = append(records, map[string]any{ + "description": desc, + "code": code, + "codeType": codeType, + "grossCharge": gross, + "discountedCash": cash, + }) + chargeRows = append(chargeRows, []string{ + escapeDeclMarkdownBrackets(desc), + wave3K2FirstNonEmpty(codeType+" "+code, "-"), + gross, + cash, + }) + } + } + + title := wave3K2FirstNonEmpty(hospName, "Hospital Standard Charges CSV") + var bullets []string + if lastUpd != "" { + bullets = append(bullets, "- **Last Updated**: "+escapeDeclMarkdownBrackets(lastUpd)) + } + if version != "" { + bullets = append(bullets, "- **CMS Version**: `"+sanitizeDeclInlineCodeVal(version)+"`") + } + if locName != "" { + bullets = append(bullets, "- **Location**: "+escapeDeclMarkdownBrackets(locName)) + } + if hospAddr != "" { + bullets = append(bullets, "- **Address**: "+escapeDeclMarkdownBrackets(hospAddr)) + } + if licenseNum != "" { + bullets = append(bullets, "- **License**: `"+sanitizeDeclInlineCodeVal(licenseNum)+"`") + } + if npi != "" { + bullets = append(bullets, "- **Type 2 NPI**: `"+sanitizeDeclInlineCodeVal(npi)+"`") + } + + var md []string + md = append(md, "# "+escapeDeclMarkdownBrackets(title)) + if len(bullets) > 0 { + md = append(md, wave3K2JoinBullets(bullets)) + } + if len(chargeRows) > 0 { + md = append(md, "## Sample Standard Charges\n\n"+formatDeclarativeGFMTable([]string{"Description", "Code", "Gross Charge", "Discounted Cash"}, chargeRows)) + } + return &DeclarativeFormattedDoc{ + Title: title, + PublishedTime: lastUpd, + Markdown: strings.Join(md, "\n\n"), + Records: records, + Returned: wave3K2IntPtr(len(records)), + Truncated: wave3K2BoolPtr(len(records) >= wave3K2MaxRecords), + }, true + } + + return nil, false +} + +func wave3K2ExtractCMSPriceHTML(rawHTML, probeLower, baseURL, extractorID string) *DeclarativePostFetchResult { + h1 := wave3K2ExtractH1(rawHTML) + title := wave3K2FirstNonEmpty(h1, wave3K2ExtractMeta(rawHTML, "og:title"), extractTitleLinearQuick(rawHTML)) + if title == "" || wave3K2IsNegativeTitle(title) || wave3K2IsGenericTitle(title) { + return nil + } + var links []string + seen := make(map[string]bool) + for _, lnk := range wave3K2ExtractLinks(rawHTML, baseURL, 25) { + lowU := strings.ToLower(lnk.URL) + if strings.Contains(lowU, "cms-hpt.txt") || strings.Contains(lowU, "standardcharges") || strings.Contains(lowU, "transparency") { + wave3K2AddLink(&links, seen, lnk.URL, baseURL) + } + } + bodyMD := wave3K2ExtractMainHTML(rawHTML, baseURL) + if bodyMD == "" && len(links) == 0 { + return nil + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: wave3K2ExtractMeta(rawHTML, "description"), + Markdown: "# " + escapeDeclMarkdownBrackets(title) + "\n\n- **Category**: CMS Price Transparency\n\n" + bodyMD, + Links: links, + } +} + +// ── #297 Medicaid NADAC & #300 SBA DKAN ───────────────────────────────────────────────────────── + +func wave3K2FormatMedicaidDKANJSON(parsed any, origURL, fallbackTitle string) (*DeclarativeFormattedDoc, bool) { + switch tv := parsed.(type) { + case map[string]any: + if wave3K2IsGenericJSONError(tv) { + return nil, false + } + // DKAN Datastore query response (`{"results":[...], "count":..., "schema":...}`) + if rawResults := wave3K2Slice(tv["results"]); rawResults != nil { + if len(rawResults) == 0 { + return nil, false + } + firstRow := wave3K2Map(rawResults[0]) + if firstRow == nil { + return nil, false + } + isNADAC := firstRow["ndc_description"] != nil || firstRow["nadac_per_unit"] != nil + var headers []string + var keys []string + if isNADAC { + headers = []string{"NDC Description", "NDC", "NADAC / Unit", "Unit", "Effective Date"} + keys = []string{"ndc_description", "ndc", "nadac_per_unit", "pricing_unit", "effective_date"} + } else { + for k := range firstRow { + keys = append(keys, k) + } + sort.Strings(keys) + if len(keys) > 5 { + keys = keys[:5] + } + headers = append(headers, keys...) + } + var rows [][]string + var records []map[string]any + for _, el := range rawResults { + if len(records) >= wave3K2MaxRecords { + break + } + rm := wave3K2Map(el) + if rm == nil { + continue + } + records = append(records, rm) + rowCells := make([]string, len(keys)) + for i, k := range keys { + rowCells[i] = escapeDeclMarkdownBrackets(wave3K2Plain(rm[k], 120)) + } + rows = append(rows, rowCells) + } + if len(records) == 0 { + return nil, false + } + title := fallbackTitle + " — Datastore Query" + if isNADAC { + title = "Medicaid NADAC Drug Pricing Query" + } + total := len(rawResults) + if cnt, okC := wave3K2FloatVal(tv["count"]); okC && int(cnt) > total { + total = int(cnt) + } + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: "# " + escapeDeclMarkdownBrackets(title) + "\n\n" + fmt.Sprintf("- **Total Matching Rows**: %d\n\n", total) + formatDeclarativeGFMTable(headers, rows), + Records: records, + Total: wave3K2IntPtr(total), + Returned: wave3K2IntPtr(len(records)), + Truncated: wave3K2BoolPtr(total > len(records)), + }, true + } + + // DKAN Metastore single dataset + title := wave3K2Plain(tv["title"], 280) + ident := wave3K2Plain(tv["identifier"], 80) + if title == "" && ident == "" { + return nil, false + } + desc := wave3K2Plain(tv["description"], 1600) + modified := wave3K2Plain(tv["modified"], 64) + pubName := "" + if pub := wave3K2Map(tv["publisher"]); pub != nil { + if pd := wave3K2Map(pub["data"]); pd != nil { + pubName = wave3K2Plain(pd["name"], 120) + } else { + pubName = wave3K2Plain(pub["name"], 120) + } + } + var links []string + seen := make(map[string]bool) + var distRows [][]string + for _, d := range wave3K2Slice(tv["distribution"]) { + dm := wave3K2Map(d) + if dm == nil { + continue + } + inner := dm + if dd := wave3K2Map(dm["data"]); dd != nil { + inner = dd + } + dl := SanitizeSchemaHTTPSURL(firstNonNilSchemaGo(inner["downloadURL"], inner["accessURL"]), origURL) + fm := wave3K2Plain(firstNonNilSchemaGo(inner["format"], inner["mediaType"]), 40) + if dl != "" { + wave3K2AddLink(&links, seen, dl, origURL) + distRows = append(distRows, []string{wave3K2FirstNonEmpty(fm, "Data"), "[Download](" + dl + ")"}) + } + } + var bullets []string + if ident != "" { + bullets = append(bullets, "- **Identifier**: `"+sanitizeDeclInlineCodeVal(ident)+"`") + } + if pubName != "" { + bullets = append(bullets, "- **Publisher**: "+escapeDeclMarkdownBrackets(pubName)) + } + if modified != "" { + bullets = append(bullets, "- **Modified**: "+escapeDeclMarkdownBrackets(modified)) + } + var md []string + md = append(md, "# "+escapeDeclMarkdownBrackets(wave3K2FirstNonEmpty(title, ident))) + if len(bullets) > 0 { + md = append(md, wave3K2JoinBullets(bullets)) + } + if desc != "" { + md = append(md, escapeDeclMarkdownBlock(desc)) + } + if len(distRows) > 0 { + md = append(md, "## Distributions\n\n"+formatDeclarativeGFMTable([]string{"Format", "URL"}, distRows)) + } + return &DeclarativeFormattedDoc{ + Title: wave3K2FirstNonEmpty(title, ident), + Description: sliceRunesMax(desc, 500), + PublishedTime: modified, + Markdown: strings.Join(md, "\n\n"), + Links: links, + Records: []map[string]any{{"identifier": ident, "title": title, "modified": modified, "publisher": pubName}}, + }, true + + case []any: + if len(tv) == 0 { + return nil, false + } + var rows [][]string + var records []map[string]any + for _, el := range tv { + if len(records) >= wave3K2MaxRecords { + break + } + dm := wave3K2Map(el) + if dm == nil { + continue + } + title := wave3K2Plain(dm["title"], 240) + ident := wave3K2Plain(dm["identifier"], 80) + mod := wave3K2Plain(dm["modified"], 48) + if title == "" && ident == "" { + continue + } + records = append(records, map[string]any{"identifier": ident, "title": title, "modified": mod}) + rows = append(rows, []string{"`" + sanitizeDeclInlineCodeVal(ident) + "`", escapeDeclMarkdownBrackets(title), mod}) + } + if len(records) == 0 { + return nil, false + } + return &DeclarativeFormattedDoc{ + Title: fallbackTitle + " Catalog", + Markdown: "# " + escapeDeclMarkdownBrackets(fallbackTitle+" Catalog") + "\n\n" + formatDeclarativeGFMTable([]string{"Identifier", "Title", "Modified"}, rows), + Records: records, + Total: wave3K2IntPtr(len(tv)), + Returned: wave3K2IntPtr(len(records)), + Truncated: wave3K2BoolPtr(len(tv) > len(records)), + }, true + } + return nil, false +} + +func wave3K2ExtractMedicaidHTML(rawHTML, probeLower, baseURL, extractorID string) *DeclarativePostFetchResult { + h1 := wave3K2ExtractH1(rawHTML) + ogTitle := wave3K2ExtractMeta(rawHTML, "og:title") + rawTitle := extractTitleLinearQuick(rawHTML) + title := wave3K2FirstNonEmpty(h1, ogTitle, rawTitle) + if title == "" || wave3K2IsNegativeTitle(title) || wave3K2IsGenericTitle(title) { + return nil + } + // Reject unhydrated DKAN React shell when title is generic "CMS Medicaid Data" and there is no real dataset content. + if strings.EqualFold(strings.TrimSpace(ogTitle), "cms medicaid data") && h1 == "" && !hasJSONLDScriptToken(rawHTML) { + return nil + } + bodyMD := wave3K2ExtractMainHTML(rawHTML, baseURL) + if bodyMD == "" { + return nil + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: wave3K2ExtractMeta(rawHTML, "description"), + Markdown: "# " + escapeDeclMarkdownBrackets(title) + "\n\n- **Source**: data.medicaid.gov\n\n" + bodyMD, + } +} + +func wave3K2ExtractSBADSBSHTML(rawHTML, probeLower, baseURL, urlLower, extractorID string) *DeclarativePostFetchResult { + // Reject empty React SPA shell on search.certifications.sba.gov / dsbs.sba.gov. + if (strings.Contains(urlLower, "search.certifications.sba.gov") || strings.Contains(urlLower, "dsbs.sba.gov") || strings.Contains(probeLower, `sba small business search`)) && + strings.Contains(probeLower, `
`) && !strings.Contains(probeLower, "= wave3K2MaxRecords { + break + } + em := wave3K2Map(ev) + if em == nil { + continue + } + ts := wave3K2Plain(em["eventTimestamp"], 64) + evType := wave3K2Plain(em["eventType"], 160) + loc := strings.Trim(strings.Join([]string{ + wave3K2Plain(em["eventCity"], 64), + wave3K2Plain(em["eventState"], 16), + wave3K2Plain(em["eventZIP"], 16), + }, ", "), ", ") + records = append(records, map[string]any{ + "carrier": "USPS", + "trackingNumber": tn, + "timestamp": ts, + "event": evType, + "location": loc, + }) + rows = append(rows, []string{ts, escapeDeclMarkdownBrackets(evType), escapeDeclMarkdownBrackets(loc)}) + } + if tn == "" && len(records) == 0 { + return nil, false + } + if len(records) == 0 { + records = []map[string]any{{"carrier": "USPS", "trackingNumber": tn, "status": status}} + } + title := "USPS Tracking: " + wave3K2FirstNonEmpty(tn, status) + var bullets []string + bullets = append(bullets, "- **Carrier**: USPS") + if tn != "" { + bullets = append(bullets, "- **Tracking Number**: `"+sanitizeDeclInlineCodeVal(tn)+"`") + } + if status != "" { + bullets = append(bullets, "- **Status**: "+escapeDeclMarkdownBrackets(status)) + } + if mailClass != "" { + bullets = append(bullets, "- **Service**: "+escapeDeclMarkdownBrackets(mailClass)) + } + if expected != "" { + bullets = append(bullets, "- **Expected Delivery**: "+escapeDeclMarkdownBrackets(expected)) + } + var md []string + md = append(md, "# "+escapeDeclMarkdownBrackets(title), wave3K2JoinBullets(bullets)) + if summary != "" { + md = append(md, escapeDeclMarkdownBlock(summary)) + } + if len(rows) > 0 { + md = append(md, "## Checkpoints\n\n"+formatDeclarativeGFMTable([]string{"Timestamp", "Event", "Location"}, rows)) + } + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: strings.Join(md, "\n\n"), + Records: records, + }, true + } + + // 2. UPS Track v1 (`trackResponse.shipment[0].package[0]`) + if tr := wave3K2Map(obj["trackResponse"]); tr != nil { + ships := wave3K2Slice(tr["shipment"]) + if len(ships) == 0 { + return nil, false + } + ship := wave3K2Map(ships[0]) + if ship == nil { + return nil, false + } + pkgs := wave3K2Slice(ship["package"]) + if len(pkgs) == 0 { + return nil, false + } + pkg := wave3K2Map(pkgs[0]) + if pkg == nil { + return nil, false + } + tn := wave3K2Plain(pkg["trackingNumber"], 64) + curStatus := "" + if cs := wave3K2Map(pkg["currentStatus"]); cs != nil { + curStatus = wave3K2Plain(cs["description"], 120) + } + delivDate := "" + if dd := wave3K2Slice(pkg["deliveryDate"]); len(dd) > 0 { + if dm := wave3K2Map(dd[0]); dm != nil { + delivDate = wave3K2Plain(dm["date"], 32) + } + } + + var rows [][]string + var records []map[string]any + for _, act := range wave3K2Slice(pkg["activity"]) { + if len(records) >= wave3K2MaxRecords { + break + } + am := wave3K2Map(act) + if am == nil { + continue + } + dt := strings.TrimSpace(wave3K2Plain(am["date"], 16) + " " + wave3K2Plain(am["time"], 16)) + stDesc := "" + if sm := wave3K2Map(am["status"]); sm != nil { + stDesc = wave3K2Plain(sm["description"], 160) + } + if curStatus == "" { + curStatus = stDesc + } + locStr := "" + if lm := wave3K2Map(am["location"]); lm != nil { + if addr := wave3K2Map(lm["address"]); addr != nil { + locStr = strings.Trim(strings.Join([]string{ + wave3K2Plain(addr["city"], 64), + wave3K2Plain(addr["stateProvince"], 16), + wave3K2Plain(addr["countryCode"], 16), + }, ", "), ", ") + } + } + records = append(records, map[string]any{ + "carrier": "UPS", + "trackingNumber": tn, + "timestamp": dt, + "event": stDesc, + "location": locStr, + }) + rows = append(rows, []string{dt, escapeDeclMarkdownBrackets(stDesc), escapeDeclMarkdownBrackets(locStr)}) + } + if tn == "" && len(records) == 0 { + return nil, false + } + if len(records) == 0 { + records = []map[string]any{{"carrier": "UPS", "trackingNumber": tn, "status": curStatus}} + } + title := "UPS Tracking: " + wave3K2FirstNonEmpty(tn, curStatus) + var bullets []string + bullets = append(bullets, "- **Carrier**: UPS") + if tn != "" { + bullets = append(bullets, "- **Tracking Number**: `"+sanitizeDeclInlineCodeVal(tn)+"`") + } + if curStatus != "" { + bullets = append(bullets, "- **Status**: "+escapeDeclMarkdownBrackets(curStatus)) + } + if delivDate != "" { + bullets = append(bullets, "- **Delivery Date**: "+escapeDeclMarkdownBrackets(delivDate)) + } + var md []string + md = append(md, "# "+escapeDeclMarkdownBrackets(title), wave3K2JoinBullets(bullets)) + if len(rows) > 0 { + md = append(md, "## Checkpoints\n\n"+formatDeclarativeGFMTable([]string{"Timestamp", "Event", "Location"}, rows)) + } + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: strings.Join(md, "\n\n"), + Records: records, + }, true + } + + // 3. FedEx Track v1 (`output.completeTrackResults[0].trackResults[0]`) + if outMap := wave3K2Map(obj["output"]); outMap != nil { + complete := wave3K2Slice(outMap["completeTrackResults"]) + if len(complete) == 0 { + return nil, false + } + c0 := wave3K2Map(complete[0]) + if c0 == nil { + return nil, false + } + trs := wave3K2Slice(c0["trackResults"]) + if len(trs) == 0 { + return nil, false + } + tr0 := wave3K2Map(trs[0]) + if tr0 == nil || wave3K2Map(tr0["error"]) != nil { + return nil, false + } + tn := "" + if tni := wave3K2Map(tr0["trackingNumberInfo"]); tni != nil { + tn = wave3K2Plain(tni["trackingNumber"], 64) + } + status := "" + if lsd := wave3K2Map(tr0["latestStatusDetail"]); lsd != nil { + status = wave3K2Plain(firstNonNilSchemaGo(lsd["statusByLocale"], lsd["description"]), 120) + } + var rows [][]string + var records []map[string]any + for _, se := range wave3K2Slice(tr0["scanEvents"]) { + if len(records) >= wave3K2MaxRecords { + break + } + sem := wave3K2Map(se) + if sem == nil { + continue + } + dt := wave3K2Plain(sem["date"], 48) + desc := wave3K2Plain(sem["eventDescription"], 160) + locStr := "" + if sl := wave3K2Map(sem["scanLocation"]); sl != nil { + locStr = strings.Trim(strings.Join([]string{ + wave3K2Plain(sl["city"], 64), + wave3K2Plain(sl["stateOrProvinceCode"], 16), + wave3K2Plain(sl["countryCode"], 16), + }, ", "), ", ") + } + records = append(records, map[string]any{ + "carrier": "FedEx", + "trackingNumber": tn, + "timestamp": dt, + "event": desc, + "location": locStr, + }) + rows = append(rows, []string{dt, escapeDeclMarkdownBrackets(desc), escapeDeclMarkdownBrackets(locStr)}) + } + if tn == "" && len(records) == 0 { + return nil, false + } + if len(records) == 0 { + records = []map[string]any{{"carrier": "FedEx", "trackingNumber": tn, "status": status}} + } + title := "FedEx Tracking: " + wave3K2FirstNonEmpty(tn, status) + var bullets []string + bullets = append(bullets, "- **Carrier**: FedEx") + if tn != "" { + bullets = append(bullets, "- **Tracking Number**: `"+sanitizeDeclInlineCodeVal(tn)+"`") + } + if status != "" { + bullets = append(bullets, "- **Status**: "+escapeDeclMarkdownBrackets(status)) + } + var md []string + md = append(md, "# "+escapeDeclMarkdownBrackets(title), wave3K2JoinBullets(bullets)) + if len(rows) > 0 { + md = append(md, "## Checkpoints\n\n"+formatDeclarativeGFMTable([]string{"Timestamp", "Event", "Location"}, rows)) + } + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: strings.Join(md, "\n\n"), + Records: records, + }, true + } + + return nil, false +} diff --git a/internal/extract/wave3_regulators_health_test.go b/internal/extract/wave3_regulators_health_test.go new file mode 100644 index 0000000..4630949 --- /dev/null +++ b/internal/extract/wave3_regulators_health_test.go @@ -0,0 +1,501 @@ +package extract + +import ( + "encoding/json" + "fmt" + "net/url" + "os" + "path/filepath" + "strings" + "testing" +) + +func wave3K2DecodeDoc(t *testing.T, raw string) *DeclarativeFormattedDoc { + t.Helper() + var doc DeclarativeFormattedDoc + if err := json.Unmarshal([]byte(raw), &doc); err != nil { + t.Fatalf("unmarshal DeclarativeFormattedDoc: %v\nraw=%s", err, raw) + } + return &doc +} + +func wave3K2ResolveManifest(t *testing.T, m *DeclarativeAdapterManifest, rawURL string) (*DeclarativeTwinMatch, bool) { + t.Helper() + u, err := url.Parse(rawURL) + if err != nil { + t.Fatalf("url.Parse(%q): %v", rawURL, err) + } + host := strings.TrimSuffix(strings.ToLower(u.Hostname()), ".") + rawParts := splitNonEmptyEscapedSegments(u.EscapedPath()) + return resolveManifestTwinOnParsedURL(m, u, host, rawParts, DeclarativeResolveOptions{}) +} + +func TestWave3RegulatorsHealthManifestsAndRoutingPrecedence(t *testing.T) { + catK2IDs := []string{ + "gao-reports", + "cbo", + "everycrsreport", + "gov-wordpress-newsrooms", + "gsa-site-scanning", + "va-lighthouse-facilities", + "healthcare-gov-marketplace", + "cms-price-transparency", + "medicaid-nadac", + "usps-addresses", + "carrier-tracking-official", + "sba-dsbs-loans", + } + + byID := make(map[string]*DeclarativeAdapterManifest, len(catK2IDs)) + for _, id := range catK2IDs { + raw, err := os.ReadFile(filepath.Join("manifests", id+".yaml")) + if err != nil { + t.Fatalf("read %s.yaml: %v", id, err) + } + m, err := ParseDeclarativeYAMLManifest(raw) + if err != nil { + t.Fatalf("ParseDeclarativeYAMLManifest(%s.yaml): %v", id, err) + } + if m.ID != id { + t.Fatalf("%s.yaml has mismatched id=%q", id, m.ID) + } + if m.AuthMode == "detect-only" || m.DetectOnly != nil { + t.Fatalf("%s.yaml uses retired detect-only", id) + } + for _, hr := range m.HTMLRoutes { + for _, b := range hr.Bullets { + if strings.ContainsAny(b.Label, "{}") { + t.Fatalf("%s.yaml bullet label contains {}: %q", id, b.Label) + } + } + } + byID[id] = m + } + + // #289 gao-reports must set strict_robots: true + if !byID["gao-reports"].StrictRobots { + t.Fatalf("gao-reports must enforce strict_robots: true") + } + + // #291 everycrsreport must map .html -> .json and /reports.csv (not reports.json) + ecrs := byID["everycrsreport"] + if tm, ok := wave3K2ResolveManifest(t, ecrs, "https://www.everycrsreport.com/reports/IN11532.html"); !ok || tm.FetchURL != "https://www.everycrsreport.com/reports/IN11532.json" { + t.Fatalf("everycrsreport .html twin mismatch: ok=%v tm=%+v", ok, tm) + } + if tm, ok := wave3K2ResolveManifest(t, ecrs, "https://www.everycrsreport.com/reports.csv"); !ok || tm.route.Extract.TextMode != "everycrs_csv" { + t.Fatalf("everycrsreport /reports.csv route mismatch: ok=%v tm=%+v", ok, tm) + } + + // #292 gov-wordpress-newsrooms must exclude whitehouse.gov from /wp-json/wp/v2/posts + gwp := byID["gov-wordpress-newsrooms"] + if tm, ok := wave3K2ResolveManifest(t, gwp, "https://www.whitehouse.gov/wp-json/wp/v2/posts"); ok || tm != nil { + t.Fatalf("gov-wordpress-newsrooms must exclude whitehouse.gov from /wp-json/: %+v", tm) + } + if tm, ok := wave3K2ResolveManifest(t, gwp, "https://news.va.gov/wp-json/wp/v2/posts?per_page=1"); !ok || tm.route.Extract.JSONMode != "gov_wp_posts_json" { + t.Fatalf("gov-wordpress-newsrooms news.va.gov wp-json failed: ok=%v tm=%+v", ok, tm) + } + + // #295 healthcare-gov-marketplace POST /api/v1/plans/search + hc := byID["healthcare-gov-marketplace"] + if tm, ok := wave3K2ResolveManifest(t, hc, "https://marketplace.api.healthcare.gov/api/v1/plans/search"); !ok || tm.Method != "POST" || tm.ContentType != "application/json" || tm.RequestBody == "" { + t.Fatalf("healthcare-gov-marketplace POST route mismatch: ok=%v tm=%+v", ok, tm) + } + + // #296 cms-price-transparency universalEngine, Range header, maxBytes, and no collision with my.clevelandclinic.org + cms := byID["cms-price-transparency"] + if !cms.UniversalEngine { + t.Fatalf("cms-price-transparency must set universalEngine: true") + } + for _, d := range cms.Domains { + if d == "my.clevelandclinic.org" { + t.Fatalf("cms-price-transparency must NOT duplicate my.clevelandclinic.org (owned by schema-medical.yaml)") + } + } + if tm, ok := wave3K2ResolveManifest(t, cms, "https://stanfordhealthcare.org/content/dam/SHC/946174066_stanford_standardcharges.json"); !ok || tm.EffectiveMaxBytes() != 2097152 || tm.Headers["Range"] != "bytes=0-2097151" { + t.Fatalf("cms-price-transparency MRF JSON Range/maxBytes mismatch: ok=%v tm=%+v", ok, tm) + } + + // #299 carrier-tracking-official headers & POST + ct := byID["carrier-tracking-official"] + if tm, ok := wave3K2ResolveManifest(t, ct, "https://onlinetools.ups.com/api/track/v1/details/1Z999AA10123456784"); !ok || tm.Headers["transactionSrc"] != "edgefetch" { + t.Fatalf("carrier-tracking-official UPS transactionSrc mismatch: ok=%v tm=%+v", ok, tm) + } + if tm, ok := wave3K2ResolveManifest(t, ct, "https://apis.fedex.com/track/v1/trackingnumbers?trackingNumber=794812345678"); !ok || tm.Method != "POST" || !strings.Contains(tm.RequestBody, "794812345678") { + t.Fatalf("carrier-tracking-official FedEx POST mismatch: ok=%v tm=%+v", ok, tm) + } + + // Full manifest set validation on disk + live registry precedence check for #298 vs #299 and #296 universalEngine! + entries, err := os.ReadDir("manifests") + if err != nil { + t.Fatalf("ReadDir(manifests): %v", err) + } + var allManifests []DeclarativeAdapterManifest + reg := &declarativeRegistry{byHost: make(map[string][]*DeclarativeAdapterManifest)} + seenIDs := make(map[string]bool) + twinOwners := make(map[string]string) + for _, ent := range entries { + if ent.IsDir() || !strings.HasSuffix(ent.Name(), ".yaml") { + continue + } + raw, rErr := os.ReadFile(filepath.Join("manifests", ent.Name())) + if rErr != nil { + t.Fatalf("read %s: %v", ent.Name(), rErr) + } + m, pErr := ParseDeclarativeYAMLManifest(raw) + if pErr != nil { + t.Fatalf("ParseDeclarativeYAMLManifest(%s): %v", ent.Name(), pErr) + } + allManifests = append(allManifests, *m) + mCopy := *m + if regErr := registerManifestInRegistry(reg, &mCopy, seenIDs, twinOwners); regErr != nil { + t.Fatalf("registerManifestInRegistry(%s): %v", ent.Name(), regErr) + } + } + if err := ValidateDeclarativeManifests(allManifests); err != nil { + t.Fatalf("ValidateDeclarativeManifests across all disk YAML files failed: %v", err) + } + + // Verify #298 usps-addresses vs #299 carrier-tracking-official routing precedence on apis.usps.com! + if m, ok := resolveDeclarativeTwinWithRegistry(reg, "https://apis.usps.com/addresses/v3/address?streetAddress=475&city=DC&state=DC", DeclarativeResolveOptions{}); !ok || m.AdapterID != "usps-addresses" { + t.Fatalf("apis.usps.com/addresses/v3/... must resolve to usps-addresses: ok=%v m=%+v", ok, m) + } + if m, ok := resolveDeclarativeTwinWithRegistry(reg, "https://apis.usps.com/tracking/v3/tracking/9400111899223344556677", DeclarativeResolveOptions{}); !ok || m.AdapterID != "carrier-tracking-official" { + t.Fatalf("apis.usps.com/tracking/... must resolve to carrier-tracking-official via universalEngine: ok=%v m=%+v", ok, m) + } + if m, ok := resolveDeclarativeTwinWithRegistry(reg, "https://apis-tem.usps.com/tracking/v3/tracking/9400111899223344556677", DeclarativeResolveOptions{}); !ok || m.AdapterID != "carrier-tracking-official" { + t.Fatalf("apis-tem.usps.com/tracking/... must resolve to carrier-tracking-official: ok=%v m=%+v", ok, m) + } + + // Verify #296 universalEngine resolves my.clevelandclinic.org/cms-hpt.txt cleanly even though schema-medical owns my.clevelandclinic.org! + if m, ok := resolveDeclarativeTwinWithRegistry(reg, "https://my.clevelandclinic.org/cms-hpt.txt", DeclarativeResolveOptions{}); !ok || m.AdapterID != "cms-price-transparency" { + t.Fatalf("my.clevelandclinic.org/cms-hpt.txt must resolve to cms-price-transparency: ok=%v m=%+v", ok, m) + } + + // Verify #297 medicaid-nadac owns data.medicaid.gov and #300 sba-dsbs-loans owns data.sba.gov over universal dkan! + if m, ok := resolveDeclarativeTwinWithRegistry(reg, "https://data.medicaid.gov/dataset/fbb83258-11c7-47f5-8b18-5f8e79f7e704", DeclarativeResolveOptions{}); !ok || m.AdapterID != "medicaid-nadac" { + t.Fatalf("data.medicaid.gov/dataset/... must resolve to medicaid-nadac: ok=%v m=%+v", ok, m) + } + if m, ok := resolveDeclarativeTwinWithRegistry(reg, "https://data.sba.gov/api/1/metastore/schemas/dataset/items/SBA-OCA-CKAN-002", DeclarativeResolveOptions{}); !ok || m.AdapterID != "sba-dsbs-loans" { + t.Fatalf("data.sba.gov/api/1/metastore/... must resolve to sba-dsbs-loans: ok=%v m=%+v", ok, m) + } +} + +func TestWave3RegulatorsHealthHTMLExtractorsAndNegatives(t *testing.T) { + modes := []string{ + "gao_reports_html", + "cbo_html", + "everycrs_html", + "gov_wp_newsroom_html", + "gsa_site_scanning_html", + "va_facilities_html", + "healthcare_gov_html", + "cms_price_transparency_html", + "medicaid_nadac_html", + "usps_docs_html", + "sba_dsbs_loans_html", + } + for _, m := range modes { + if !IsWave3RegulatorsHealthHTMLMode(m) { + t.Fatalf("IsWave3RegulatorsHealthHTMLMode(%q) = false", m) + } + if getExternalHTMLModeLazy(m) == nil { + t.Fatalf("RegisterExternalHTMLModeLazy missing %q", m) + } + } + + // #289 GAO positive + Akamai Access Denied negative + gaoGood := `GAO-27-108423 | U.S. GAO

Federal Cybersecurity Governance

What GAO Found: agencies need stronger risk monitoring.

PDF
` + if raw, ok := RunWave3RegulatorsHealthHTMLMode("gao_reports_html", gaoGood, "https://www.gao.gov/products/gao-27-108423"); !ok || !strings.Contains(raw, "GAO-27-108423") { + t.Fatalf("gao_reports_html positive failed: ok=%v raw=%s", ok, raw) + } + if _, ok := RunWave3RegulatorsHealthHTMLMode("gao_reports_html", `Access Denied

Access Denied

Reference #18.errors.edgesuite.net

`, "https://www.gao.gov/reports-testimonies"); ok { + t.Fatalf("gao_reports_html must reject Akamai Access Denied") + } + + // #290 CBO DataDome challenge must return false + ddHTML := `cbo.gov

Please enable JS and disable any ad blocker

` + if _, ok := RunWave3RegulatorsHealthHTMLMode("cbo_html", ddHTML, "https://www.cbo.gov/publication/62899"); ok { + t.Fatalf("cbo_html must reject DataDome challenge") + } + cboGood := `Cost Estimate H.R. 4120 | Congressional Budget Office

Cost Estimate for H.R. 4120

CBO estimates enacting this bill would increase spending by $1.4 billion.

` + if raw, ok := RunWave3RegulatorsHealthHTMLMode("cbo_html", cboGood, "https://www.cbo.gov/publication/62899"); !ok || !strings.Contains(raw, "62899") { + t.Fatalf("cbo_html positive failed: ok=%v raw=%s", ok, raw) + } + + // #292 gov_wp_newsroom_html rejects WooCommerce & 403, extracts White House HTML + whGood := `Presidential Actions - The White House

Presidential Actions Briefing

Executive actions published by the White House press office.

` + if raw, ok := RunWave3RegulatorsHealthHTMLMode("gov_wp_newsroom_html", whGood, "https://www.whitehouse.gov/presidential-actions/"); !ok || !strings.Contains(raw, "The White House") { + t.Fatalf("gov_wp_newsroom_html positive failed: ok=%v raw=%s", ok, raw) + } + if _, ok := RunWave3RegulatorsHealthHTMLMode("gov_wp_newsroom_html", `Store

Shop

Cart

`, "https://example.gov/shop"); ok { + t.Fatalf("gov_wp_newsroom_html must reject WooCommerce") + } + + // #294 VA Facilities rejects unhydrated page-react.html shell + vaReactShell := `Find VA Locations | Veterans Affairs
` + if _, ok := RunWave3RegulatorsHealthHTMLMode("va_facilities_html", vaReactShell, "https://www.va.gov/find-locations"); ok { + t.Fatalf("va_facilities_html must reject unhydrated React locator shell") + } + + // #296 cms_price_transparency_html prefilter & positive + cmsHTML := `Hospital Price Transparency

Hospital Price Transparency (45 CFR 180)

Download our machine-readable standard charges file.

cms-hpt.txt
` + if raw, ok := RunWave3RegulatorsHealthHTMLMode("cms_price_transparency_html", cmsHTML, "https://stanfordhealthcare.org/pricing-transparency"); !ok || !strings.Contains(raw, "cms-hpt.txt") { + t.Fatalf("cms_price_transparency_html positive failed: ok=%v raw=%s", ok, raw) + } + if _, ok := RunWave3RegulatorsHealthHTMLMode("cms_price_transparency_html", `Regular Blog

Hello World

Unrelated post.

`, "https://example.com/blog"); ok { + t.Fatalf("cms_price_transparency_html prefilter must reject unrelated pages") + } + + // #297 medicaid_nadac_html rejects empty DKAN React shell ("CMS Medicaid Data" generic title) + medicaidShell := `CMS Medicaid Data
` + if _, ok := RunWave3RegulatorsHealthHTMLMode("medicaid_nadac_html", medicaidShell, "https://data.medicaid.gov/dataset/fbb83258-11c7-47f5-8b18-5f8e79f7e704"); ok { + t.Fatalf("medicaid_nadac_html must reject generic CMS Medicaid Data React shell") + } + + // #300 sba_dsbs_loans_html rejects empty React SPA shell on search.certifications.sba.gov + sbaShell := `SBA Small Business Search
` + if _, ok := RunWave3RegulatorsHealthHTMLMode("sba_dsbs_loans_html", sbaShell, "https://search.certifications.sba.gov/"); ok { + t.Fatalf("sba_dsbs_loans_html must reject empty React SPA shell") + } + sbaDataHTML := `SBA FOIA Quarterly Reports | SBA open data

SBA FOIA Quarterly Reports

DKAN dataset containing quarterly FOIA metrics.

` + if raw, ok := RunWave3RegulatorsHealthHTMLMode("sba_dsbs_loans_html", sbaDataHTML, "https://data.sba.gov/dataset/sba-foia-quarterly-reports"); !ok || !strings.Contains(raw, "SBA FOIA Quarterly Reports") { + t.Fatalf("sba_dsbs_loans_html positive failed: ok=%v raw=%s", ok, raw) + } +} + +func TestWave3RegulatorsHealthCMSPriceTransparencyStreamingAndArchives(t *testing.T) { + // 1. ZIP (PK\x03\x04) & gzip (\x1f\x8b) magic bytes in BOTH cms_mrf_json and cms_mrf_csv + zipBytes := append([]byte{'P', 'K', 0x03, 0x04}, []byte("mock-zip-central-dir-bytes")...) + gzipBytes := append([]byte{0x1f, 0x8b, 0x08, 0x00}, []byte("mock-gzip-stream")...) + + for _, tc := range []struct { + name string + raw []byte + want string + }{ + {"zip", zipBytes, "ZIP"}, + {"gzip", gzipBytes, "GZIP"}, + } { + rawJ, okJ := FormatWave3RegulatorsHealthJSONMode("cms_mrf_json", tc.raw, nil, "https://my.clevelandclinic.org/panacea_standardcharges.json") + if !okJ || !strings.Contains(rawJ, tc.want) { + t.Fatalf("cms_mrf_json %s magic detection failed: ok=%v raw=%s", tc.name, okJ, rawJ) + } + rawC, okC := FormatWave3RegulatorsHealthTextMode("cms_mrf_csv", string(tc.raw), nil, "https://my.clevelandclinic.org/panacea_standardcharges.csv") + if !okC || !strings.Contains(rawC, tc.want) { + t.Fatalf("cms_mrf_csv %s magic detection failed: ok=%v raw=%s", tc.name, okC, rawC) + } + } + + // 2. Truncated Hospital MRF JSON (> 25 items + incomplete tail at 2 MiB boundary) + var mrfItems []string + for i := 1; i <= 28; i++ { + mrfItems = append(mrfItems, fmt.Sprintf(`{"description":"MRI Brain Scan %d","code_information":[{"code":"7055%d","type":"CPT"}],"standard_charges":[{"gross_charge":2500.00,"discounted_cash":1250.00}]}`, i, i)) + } + truncatedMRFJSON := `{"hospital_name":"Stanford Health Care","last_updated_on":"2026-04-01","version":"3.0.0","location_name":["Stanford Hospital"],"hospital_address":["300 Pasteur Dr"],"type_2_npi":["1234567890"],"standard_charge_information":[` + + strings.Join(mrfItems, ",") + `,{"description":"Truncated tail` // intentionally truncated without closing brace/bracket! + rawMRFJ, okMRFJ := FormatWave3RegulatorsHealthJSONMode("cms_mrf_json", []byte(truncatedMRFJSON), nil, "https://stanfordhealthcare.org/946174066_standardcharges.json") + if !okMRFJ { + t.Fatalf("cms_mrf_json truncated stream failed") + } + docMRFJ := wave3K2DecodeDoc(t, rawMRFJ) + if len(docMRFJ.Records) != 25 || !strings.Contains(docMRFJ.Markdown, "Stanford Health Care") { + t.Fatalf("cms_mrf_json cap/title mismatch: len=%d md=%s", len(docMRFJ.Records), docMRFJ.Markdown) + } + + // Also verify early truncation (< 25 items, EOF mid-object) + earlyTrunc := `{"hospital_name":"Mount Sinai Hospital","last_updated_on":"2026-03-01","version":"3.0.0","standard_charge_information":[{"description":"Chest X-Ray","code_information":[{"code":"71046","type":"CPT"}],"standard_charges":[{"gross_charge":450,"discounted_cash":220}]},{"description":"Broken` + rawEarly, okEarly := FormatWave3RegulatorsHealthJSONMode("cms_mrf_json", []byte(earlyTrunc), nil, "https://www.mountsinai.org/mrf_standardcharges.json") + if !okEarly || !strings.Contains(rawEarly, "Mount Sinai Hospital") || !strings.Contains(rawEarly, "Chest X-Ray") { + t.Fatalf("cms_mrf_json early truncation failed: ok=%v raw=%s", okEarly, rawEarly) + } + + // 3. CMS TiC Table of Contents & UHC TiC Blobs + ticTOC := `{"reporting_entity_name":"Example Health Plan","reporting_entity_type":"health insurance issuer","last_updated_on":"2026-11-01","version":"1.0.0","reporting_structure":[{"reporting_plans":[{"plan_name":"Gold PPO 1000"}],"in_network_files":[{"location":"https://example.org/in_network_1.json.gz"}]}]}` + if rawTOC, okTOC := FormatWave3RegulatorsHealthJSONMode("cms_mrf_json", []byte(ticTOC), nil, "https://example.org/table-of-contents.json"); !okTOC || !strings.Contains(rawTOC, "Example Health Plan") || !strings.Contains(rawTOC, "Gold PPO 1000") { + t.Fatalf("cms_mrf_json TiC TOC failed: ok=%v raw=%s", okTOC, rawTOC) + } + uhcBlobs := `{"blobs":[{"name":"2026-11-01_uhc_index.json.gz","downloadUrl":"https://transparency-in-coverage.uhc.com/api/v1/uhc/blobs/download/123","size":9876543}]}` + if rawUHC, okUHC := FormatWave3RegulatorsHealthJSONMode("cms_mrf_json", []byte(uhcBlobs), nil, "https://transparency-in-coverage.uhc.com/api/v1/uhc/blobs/"); !okUHC || !strings.Contains(rawUHC, "2026-11-01_uhc_index.json.gz") { + t.Fatalf("cms_mrf_json UHC blobs failed: ok=%v raw=%s", okUHC, rawUHC) + } + + // 4. Hospital MRF CSV with quoted multiline Row-0 attestation + > 25 rows + truncated final quote + var csvLines []string + csvLines = append(csvLines, `hospital_name,last_updated_on,version,location_name,hospital_address,license_number|NY,type_2_npi,"To the best of its knowledge and belief, the hospital has included all applicable standard charge information in accordance with`+"\n"+`45 CFR 180.50 requirements.",attester_name`) + csvLines = append(csvLines, `NYU Langone Health,2026-02-01,3.0.0,Tisch Hospital,"550 First Ave, New York, NY 10016",7002053H,1234567890,Attested,Jane Doe`) + csvLines = append(csvLines, `description,code|1,code|1|type,standard_charge|gross,standard_charge|discounted_cash`) + for i := 1; i <= 27; i++ { + csvLines = append(csvLines, fmt.Sprintf(`"Procedure Item %d",9921%d,CPT,500.00,250.00`, i, i%9)) + } + csvLines = append(csvLines, `"Truncated final row without closing quote`) + rawCSV, okCSV := FormatWave3RegulatorsHealthTextMode("cms_mrf_csv", strings.Join(csvLines, "\n"), nil, "https://nyulangone.org/nyu_standardcharges.csv") + if !okCSV { + t.Fatalf("cms_mrf_csv failed on multiline attestation + truncated tail") + } + docCSV := wave3K2DecodeDoc(t, rawCSV) + if len(docCSV.Records) != 25 || !strings.Contains(docCSV.Markdown, "NYU Langone Health") || !strings.Contains(docCSV.Markdown, "7002053H") { + t.Fatalf("cms_mrf_csv mismatch: len=%d md=%s", len(docCSV.Records), docCSV.Markdown) + } + + // 5. cms_hpt_txt stanza parser + hpt := "location-name: Stanford Health Care\nsource-page-url: https://stanfordhealthcare.org/pricing.html\nmrf-url: https://stanfordhealthcare.org/mrf.json\ncontact-email: pricing@stanfordhealthcare.org\n\nlocation-name: ValleyCare\nmrf-url: https://stanfordhealthcare.org/valleycare_mrf.json\n" + if rawHPT, okHPT := FormatWave3RegulatorsHealthTextMode("cms_hpt_txt", hpt, nil, "https://stanfordhealthcare.org/cms-hpt.txt"); !okHPT || !strings.Contains(rawHPT, "ValleyCare") { + t.Fatalf("cms_hpt_txt failed: ok=%v raw=%s", okHPT, rawHPT) + } +} + +func TestWave3RegulatorsHealthOtherJSONAndTextModes(t *testing.T) { + // #291 everycrs_csv + truncated tail + csvCRS := "number,url,sha1,latestPubDate,title,latestPDF,latestHTML\nIN11532,/reports/IN11532.html,abc,2026-10-14,\"Federal Grants, Overview\",/files/IN11532.pdf,/reports/IN11532.html\nR47000,/reports/R47000.html,def,2026-10-01,\"Truncated" + if raw, ok := FormatWave3RegulatorsHealthTextMode("everycrs_csv", csvCRS, nil, "https://www.everycrsreport.com/reports.csv"); !ok || !strings.Contains(raw, "IN11532") { + t.Fatalf("everycrs_csv failed: ok=%v raw=%s", ok, raw) + } + + // #299 carrier_tracking_json: USPS, UPS, FedEx + error rejections + upsPayload := `{"trackResponse":{"shipment":[{"package":[{"trackingNumber":"1Z999AA10123456784","currentStatus":{"description":"Delivered"},"deliveryDate":[{"date":"20261126"}],"activity":[{"date":"20261126","time":"103000","status":{"description":"Delivered"},"location":{"address":{"city":"ATLANTA","stateProvince":"GA","countryCode":"US"}}}]}]}]}}` + if raw, ok := FormatWave3RegulatorsHealthJSONMode("carrier_tracking_json", []byte(upsPayload), nil, "https://onlinetools.ups.com/api/track/v1/details/1Z999AA10123456784"); !ok || !strings.Contains(raw, "UPS Tracking") || !strings.Contains(raw, "ATLANTA") { + t.Fatalf("carrier_tracking_json UPS failed: ok=%v raw=%s", ok, raw) + } + fedexPayload := `{"output":{"completeTrackResults":[{"trackResults":[{"trackingNumberInfo":{"trackingNumber":"784592018372"},"latestStatusDetail":{"statusByLocale":"Delivered"},"scanEvents":[{"date":"2026-11-26T09:15:00-06:00","eventDescription":"Delivered","scanLocation":{"city":"MEMPHIS","stateOrProvinceCode":"TN","countryCode":"US"}}]}]}]}}` + if raw, ok := FormatWave3RegulatorsHealthJSONMode("carrier_tracking_json", []byte(fedexPayload), nil, "https://apis.fedex.com/track/v1/trackingnumbers"); !ok || !strings.Contains(raw, "FedEx Tracking") || !strings.Contains(raw, "MEMPHIS") { + t.Fatalf("carrier_tracking_json FedEx failed: ok=%v raw=%s", ok, raw) + } + + // #297 medicaid_nadac_json datastore query + nadacQuery := `{"results":[{"ndc_description":"ATORVASTATIN 20 MG TABLET","ndc":"00093505798","nadac_per_unit":"0.04123","pricing_unit":"EA","effective_date":"2026-11-18"}],"count":1}` + if raw, ok := FormatWave3RegulatorsHealthJSONMode("medicaid_nadac_json", []byte(nadacQuery), nil, "https://data.medicaid.gov/api/1/datastore/query/e3af839d/0"); !ok || !strings.Contains(raw, "ATORVASTATIN 20 MG TABLET") { + t.Fatalf("medicaid_nadac_json datastore query failed: ok=%v raw=%s", ok, raw) + } +} + +func TestWave3RegulatorsHealthFixturesJSONValidAndSelfConsistent(t *testing.T) { + catK2IDs := []string{ + "gao-reports", + "cbo", + "everycrsreport", + "gov-wordpress-newsrooms", + "gsa-site-scanning", + "va-lighthouse-facilities", + "healthcare-gov-marketplace", + "cms-price-transparency", + "medicaid-nadac", + "usps-addresses", + "carrier-tracking-official", + "sba-dsbs-loans", + } + + for _, id := range catK2IDs { + raw, err := os.ReadFile(filepath.Join("..", "..", "hub", "test", "fixtures", "adapters", id+".json")) + if err != nil { + t.Fatalf("read fixture %s.json: %v", id, err) + } + var fx struct { + AdapterID string `json:"adapterId"` + Mode string `json:"mode"` + InputURL string `json:"inputUrl"` + ExpectedFetchURL string `json:"expectedFetchUrl"` + MockPayload string `json:"mockPayload"` + ExpectTitle string `json:"expectTitleIncludes"` + ExpectIncludes []string `json:"expectMarkdownIncludes"` + NegativeCases []struct { + Name string `json:"name"` + Status int `json:"status"` + FinalURL string `json:"finalUrl"` + Payload string `json:"payload"` + } `json:"negativeCases"` + } + if err := json.Unmarshal(raw, &fx); err != nil { + t.Fatalf("invalid JSON in %s.json: %v", id, err) + } + if fx.AdapterID != id || (fx.Mode != "twin" && fx.Mode != "html") || fx.InputURL == "" || fx.MockPayload == "" || len(fx.NegativeCases) < 4 { + t.Fatalf("fixture %s.json contract failed: id=%q mode=%q neg=%d", id, fx.AdapterID, fx.Mode, len(fx.NegativeCases)) + } + + // Verify golden + negative payloads against Go extractor/formatter + mRaw, err := os.ReadFile(filepath.Join("manifests", id+".yaml")) + if err != nil { + t.Fatalf("read manifest %s.yaml: %v", id, err) + } + m, err := ParseDeclarativeYAMLManifest(mRaw) + if err != nil { + t.Fatalf("parse %s.yaml: %v", id, err) + } + + if fx.Mode == "html" { + mode := m.HTMLRoutes[0].Mode + out, ok := RunWave3RegulatorsHealthHTMLMode(mode, fx.MockPayload, fx.InputURL) + if !ok { + t.Fatalf("fixture %s golden HTML failed", id) + } + for _, needle := range fx.ExpectIncludes { + if !strings.Contains(out, needle) { + t.Fatalf("fixture %s HTML missing %q in %s", id, needle, out) + } + } + for _, nc := range fx.NegativeCases { + targetURL := nc.FinalURL + if targetURL == "" { + targetURL = fx.InputURL + } + if negOut, okNeg := RunWave3RegulatorsHealthHTMLMode(mode, nc.Payload, targetURL); okNeg { + t.Fatalf("fixture %s negative case %q unexpectedly matched: %s", id, nc.Name, negOut) + } + } + } else { + tm, ok := wave3K2ResolveManifest(t, m, fx.InputURL) + if !ok || tm == nil { + t.Fatalf("fixture %s inputUrl %s failed to match manifest twin", id, fx.InputURL) + } + if fx.ExpectedFetchURL != "" && tm.FetchURL != fx.ExpectedFetchURL { + t.Fatalf("fixture %s expectedFetchUrl %q != %q", id, fx.ExpectedFetchURL, tm.FetchURL) + } + var out string + var okFmt bool + if tm.route.Extract.TextMode != "" { + out, okFmt = FormatWave3RegulatorsHealthTextMode(tm.route.Extract.TextMode, fx.MockPayload, tm.params, fx.InputURL) + } else { + out, okFmt = FormatWave3RegulatorsHealthJSONMode(tm.route.Extract.JSONMode, []byte(fx.MockPayload), tm.params, fx.InputURL) + } + if !okFmt { + t.Fatalf("fixture %s golden twin format failed", id) + } + for _, needle := range fx.ExpectIncludes { + if !strings.Contains(out, needle) { + t.Fatalf("fixture %s twin missing %q in %s", id, needle, out) + } + } + for _, nc := range fx.NegativeCases { + if nc.FinalURL != "" { + continue + } + var okNeg bool + if tm.route.Extract.TextMode != "" { + _, okNeg = FormatWave3RegulatorsHealthTextMode(tm.route.Extract.TextMode, nc.Payload, tm.params, fx.InputURL) + } else { + _, okNeg = FormatWave3RegulatorsHealthJSONMode(tm.route.Extract.JSONMode, []byte(nc.Payload), tm.params, fx.InputURL) + } + if okNeg { + t.Fatalf("fixture %s negative case %q unexpectedly formatted", id, nc.Name) + } + } + } + } + + // Regression tests for P2: F5 BIG-IP ASM (neutral ) and 78 KB <div id="root"></div> shells + f5Shell := `<!doctype html><html><head><title>Notice

The requested URL was rejected. Please consult with your administrator.
Your support ID is: 12345678901234567890

` + largeReactRoot := `SBA Search
` + for _, tc := range []struct { + mode string + url string + html string + name string + }{ + {"gao_reports_html", "https://www.gao.gov/products/gao-26-100001", f5Shell, "gao-f5-asm"}, + {"cbo_html", "https://www.cbo.gov/publication/60001", f5Shell, "cbo-f5-asm"}, + {"sba_dsbs_loans_html", "https://search.certifications.sba.gov/profile/123", largeReactRoot, "sba-78kb-div-root"}, + } { + if _, ok := RunWave3RegulatorsHealthHTMLMode(tc.mode, tc.html, tc.url); ok { + t.Fatalf("%s must reject negative shell", tc.name) + } + } +} diff --git a/internal/extract/wave3_regulators_test.go b/internal/extract/wave3_regulators_test.go new file mode 100644 index 0000000..15282bd --- /dev/null +++ b/internal/extract/wave3_regulators_test.go @@ -0,0 +1,417 @@ +package extract + +import ( + "encoding/json" + "net/url" + "os" + "path/filepath" + "strings" + "testing" +) + +func wave3K1DecodeDoc(t *testing.T, raw string) *DeclarativeFormattedDoc { + t.Helper() + var doc DeclarativeFormattedDoc + if err := json.Unmarshal([]byte(raw), &doc); err != nil { + t.Fatalf("unmarshal DeclarativeFormattedDoc: %v\nraw=%s", err, raw) + } + return &doc +} + +func wave3K1ResolveManifest(t *testing.T, m *DeclarativeAdapterManifest, rawURL string) (*DeclarativeTwinMatch, bool) { + t.Helper() + u, err := url.Parse(rawURL) + if err != nil { + t.Fatalf("url.Parse(%q): %v", rawURL, err) + } + host := strings.TrimSuffix(strings.ToLower(u.Hostname()), ".") + rawParts := splitNonEmptyEscapedSegments(u.EscapedPath()) + return resolveManifestTwinOnParsedURL(m, u, host, rawParts, DeclarativeResolveOptions{}) +} + +func TestWave3RegulatorsManifestsOnDisk(t *testing.T) { + catK1IDs := []string{ + "dol-enforcement", + "osha-establishment", + "nlrb-cases", + "eeoc-litigation", + "ftc-cases", + "fcc-ecfs", + "fcc-uls", + "ferc-nrc-dockets", + "financial-regulators-enforcement", + "oversight-gov", + } + + byID := make(map[string]*DeclarativeAdapterManifest, len(catK1IDs)) + for _, id := range catK1IDs { + raw, err := os.ReadFile(filepath.Join("manifests", id+".yaml")) + if err != nil { + t.Fatalf("read %s.yaml: %v", id, err) + } + m, err := ParseDeclarativeYAMLManifest(raw) + if err != nil { + t.Fatalf("ParseDeclarativeYAMLManifest(%s.yaml): %v", id, err) + } + if m.ID != id { + t.Fatalf("%s.yaml has mismatched id=%q", id, m.ID) + } + if m.AuthMode == "detect-only" || m.DetectOnly != nil { + t.Fatalf("%s.yaml uses retired detect-only", id) + } + for _, hr := range m.HTMLRoutes { + for _, b := range hr.Bullets { + if strings.ContainsAny(b.Label, "{}") { + t.Fatalf("%s.yaml bullet label contains {}: %q", id, b.Label) + } + } + } + byID[id] = m + } + + // #283 ftc-cases: Crawl-delay: 5 enforcement + ftc := byID["ftc-cases"] + if !ftc.StrictRobots || ftc.MinIntervalMs != 5000 || ftc.MaxConcurrent != 1 { + t.Fatalf("ftc-cases.yaml politeness mismatch: strict_robots=%v min_interval_ms=%d max_concurrent=%d", ftc.StrictRobots, ftc.MinIntervalMs, ftc.MaxConcurrent) + } + + // #280 osha-establishment: strict_robots + min_interval_ms: 1500 + osha := byID["osha-establishment"] + if !osha.StrictRobots || osha.MinIntervalMs != 1500 { + t.Fatalf("osha-establishment.yaml politeness mismatch: strict_robots=%v min_interval_ms=%d", osha.StrictRobots, osha.MinIntervalMs) + } + + // #286 ferc-nrc-dockets: strict_robots: true + if !byID["ferc-nrc-dockets"].StrictRobots { + t.Fatalf("ferc-nrc-dockets.yaml must set strict_robots: true") + } + + // #284 fcc-ecfs: must NOT claim apps.fcc.gov; keyed route on publicapi.fcc.gov/ecfs/ + ecfs := byID["fcc-ecfs"] + if ecfs.AuthMode != "key" { + t.Fatalf("fcc-ecfs.yaml auth_mode=%q want key", ecfs.AuthMode) + } + for _, d := range ecfs.Domains { + if d == "apps.fcc.gov" { + t.Fatalf("fcc-ecfs.yaml must NOT claim apps.fcc.gov") + } + } + if tm, ok := wave3K1ResolveManifest(t, ecfs, "https://publicapi.fcc.gov/ecfs/filings?limit=2"); !ok || tm.AuthMode != "key" || tm.route.Extract.JSONMode != "fcc_ecfs_json" { + t.Fatalf("fcc-ecfs API route mismatch: ok=%v tm=%+v", ok, tm) + } + + // #285 fcc-uls: must NOT claim apps.fcc.gov or www.fcc.gov; min_interval_ms: 1000 + uls := byID["fcc-uls"] + if uls.MinIntervalMs != 1000 { + t.Fatalf("fcc-uls.yaml min_interval_ms=%d want 1000", uls.MinIntervalMs) + } + for _, d := range uls.Domains { + if d == "apps.fcc.gov" || d == "www.fcc.gov" { + t.Fatalf("fcc-uls.yaml must NOT claim %q", d) + } + } + for _, u := range []string{ + "https://opendata.fcc.gov/resource/dpvg-tvcx.json?$limit=2", + "https://opendata.fcc.gov/api/catalog/v1?q=ULS&limit=3", + "https://opendata.fcc.gov/api/views/dpvg-tvcx.json", + "https://data.fcc.gov/api/license-view/basicSearch/getLicenses?searchValue=Verizon&format=json", + } { + if tm, ok := wave3K1ResolveManifest(t, uls, u); !ok || tm.route.Extract.JSONMode != "fcc_uls_json" { + t.Fatalf("fcc-uls route mismatch for %s: ok=%v tm=%+v", u, ok, tm) + } + } + + // #279 dol-enforcement: keyed route on apiprod.dol.gov/v4/ + dol := byID["dol-enforcement"] + if dol.AuthMode != "key" { + t.Fatalf("dol-enforcement.yaml auth_mode=%q want key", dol.AuthMode) + } + if tm, ok := wave3K1ResolveManifest(t, dol, "https://apiprod.dol.gov/v4/get/WHD/whd_enforcement/json?limit=2"); !ok || tm.AuthMode != "key" || tm.route.Extract.JSONMode != "dol_enforcement_json" { + t.Fatalf("dol-enforcement API route mismatch: ok=%v tm=%+v", ok, tm) + } + + // #287 financial-regulators-enforcement: OCC RSS XML route + fin := byID["financial-regulators-enforcement"] + tmRSS, okRSS := wave3K1ResolveManifest(t, fin, "https://www.occ.gov/rss/occ_news.xml") + if !okRSS || tmRSS.route.Extract.XML == nil || tmRSS.route.Extract.XML.Mode != "items_table" { + t.Fatalf("financial-regulators-enforcement OCC RSS route mismatch: ok=%v tm=%+v", okRSS, tmRSS) + } + occRSS := `OCC NewsAgencies Announce ThresholdAnnual appraisal exemption threshold update.25 Nov 2026 15:00:00 -0500https://www.occ.gov/news-issuances/news-releases/2026/nr-ia-2026-105.html` + rssDoc, okDoc := formatXMLTwinGo(occRSS, tmRSS.route.Extract.XML, map[string]string{"host": "www.occ.gov"}) + if !okDoc || !strings.Contains(rssDoc.Title, "OCC News") || !strings.Contains(rssDoc.Markdown, "Agencies Announce Threshold") { + t.Fatalf("OCC RSS XML format failed: ok=%v doc=%+v", okDoc, rssDoc) + } +} + +func TestWave3RegulatorsHTMLExtractorsAndGuardrails(t *testing.T) { + modes := []string{ + "dol_enforcement_html", + "osha_establishment_html", + "nlrb_cases_html", + "eeoc_litigation_html", + "ftc_cases_html", + "fcc_ecfs_html", + "fcc_uls_html", + "ferc_nrc_dockets_html", + "financial_regulators_html", + "oversight_gov_html", + } + for _, m := range modes { + if !IsWave3RegulatorsHTMLMode(m) { + t.Fatalf("IsWave3RegulatorsHTMLMode(%q) = false", m) + } + if getExternalHTMLModeLazy(m) == nil { + t.Fatalf("RegisterExternalHTMLModeLazy missing %q", m) + } + } + + // #279 DOL HTML positive & empty data.dol.gov React shell rejection + dolHTML := `Wage and Hour Division Data | U.S. Department of Labor

Wage and Hour Division Enforcement Data

Explore FLSA back wages, civil money penalties, and enforcement case records published by the U.S. Department of Labor.

WHD Enforcement API
` + rawDOL, okDOL := RunWave3RegulatorsHTMLMode("dol_enforcement_html", dolHTML, "https://www.dol.gov/agencies/whd/data") + if !okDOL || !strings.Contains(rawDOL, "Wage and Hour Division") { + t.Fatalf("dol_enforcement_html failed: ok=%v raw=%s", okDOL, rawDOL) + } + if _, okEmpty := RunWave3RegulatorsHTMLMode("dol_enforcement_html", `
`, "https://data.dol.gov/"); okEmpty { + t.Fatalf("dol_enforcement_html must reject empty data.dol.gov React shell") + } + + // #280 OSHA HTML positive & CloudFront 403 rejection + oshaHTML := `Establishment Search Results | OSHA

Establishment Search Results

Inspection history for industrial manufacturing establishments in Region 5.

ActivityOpenedEstablishment
17452102026-04-12Midwest Metalworks Inc.
` + rawOSHA, okOSHA := RunWave3RegulatorsHTMLMode("osha_establishment_html", oshaHTML, "https://www.osha.gov/pls/imis/establishment.html") + if !okOSHA || !strings.Contains(rawOSHA, "Midwest Metalworks Inc.") { + t.Fatalf("osha_establishment_html failed: ok=%v raw=%s", okOSHA, rawOSHA) + } + if _, okCF := RunWave3RegulatorsHTMLMode("osha_establishment_html", `ERROR: The request could not be satisfied

403 ERROR

Generated by cloudfront (CloudFront).

`, "https://www.osha.gov/pls/imis/establishment.html"); okCF { + t.Fatalf("osha_establishment_html must reject CloudFront 403 block") + } + + // #281 NLRB HTML (including >200KB header padding before
) & generic/not-found rejection + pad := strings.Repeat("", 20000) + nlrbHTML := `Trader Joe's East Inc. | National Labor Relations Board` + pad + `

Trader Joe's East Inc.

Case Number: 13-CA-394913

Date Filed: 09/15/2026

Status: Open

Region Assigned: Region 13, Chicago, Illinois

DateDocument
2026-09-15Charge Filed
` + rawNLRB, okNLRB := RunWave3RegulatorsHTMLMode("nlrb_cases_html", nlrbHTML, "https://www.nlrb.gov/case/13-CA-394913") + if !okNLRB || !strings.Contains(rawNLRB, "13-CA-394913") || !strings.Contains(rawNLRB, "Region 13, Chicago, Illinois") { + t.Fatalf("nlrb_cases_html failed on padded Drupal page: ok=%v raw=%s", okNLRB, rawNLRB) + } + if _, okGen := RunWave3RegulatorsHTMLMode("nlrb_cases_html", `Cases | National Labor Relations Board

Cases

Search NLRB case filings.

`, "https://www.nlrb.gov/cases-decisions/cases"); okGen { + t.Fatalf("nlrb_cases_html must reject generic /cases-decisions/cases shell without docket rows or case number") + } + + // #282 EEOC HTML positive & negative + eeocHTML := `Boss Man Tacos to Pay $42,000 | EEOC
Press Release 11-25-2026

Boss Man Tacos to Pay $42,000 in EEOC Sexual Harassment Suit

The U.S. Equal Employment Opportunity Commission announced a $42,000 federal consent decree resolving Title VII retaliation claims.

` + rawEEOC, okEEOC := RunWave3RegulatorsHTMLMode("eeoc_litigation_html", eeocHTML, "https://www.eeoc.gov/newsroom/boss-man-tacos-pay-42000-eeoc-sexual-harassment-suit") + if !okEEOC || !strings.Contains(rawEEOC, "$42,000") || !strings.Contains(rawEEOC, "11-25-2026") { + t.Fatalf("eeoc_litigation_html failed: ok=%v raw=%s", okEEOC, rawEEOC) + } + + // #283 FTC HTML positive & negative + ftcHTML := `Banned Debt Collectors | Federal Trade Commission

Legal Library: Banned Debt Collectors

Matter Number: 192 3088

The Federal Trade Commission maintains a list of individuals and businesses banned from debt collection.

Phantom Recovery LLC
` + rawFTC, okFTC := RunWave3RegulatorsHTMLMode("ftc_cases_html", ftcHTML, "https://www.ftc.gov/legal-library/browse/cases-proceedings/banned-debt-collectors") + if !okFTC || !strings.Contains(rawFTC, "192 3088") { + t.Fatalf("ftc_cases_html failed: ok=%v raw=%s", okFTC, rawFTC) + } + + // #284 & #285 FCC HTML positive & Akamai 403 rejection + if _, okAkamai := RunWave3RegulatorsHTMLMode("fcc_ecfs_html", `Access Denied

Access Denied

errors.edgesuite.net

`, "https://www.fcc.gov/ecfs/search/search-filings"); okAkamai { + t.Fatalf("fcc_ecfs_html must reject Akamai 403") + } + ulsHTML := `ULS License - WQVF475

ULS License WQVF475 - Electronic Innovations Inc.

Universal Licensing System active license details.

Call SignFRNStatus
WQVF4750024248098Active
` + rawULS, okULS := RunWave3RegulatorsHTMLMode("fcc_uls_html", ulsHTML, "https://wireless2.fcc.gov/UlsApp/UlsSearch/license.jsp?licKey=12345") + if !okULS || !strings.Contains(rawULS, "WQVF475") { + t.Fatalf("fcc_uls_html failed: ok=%v raw=%s", okULS, rawULS) + } + + // #286 FERC/NRC HTML positive & Cloudflare / Angular shell rejection + nrcHTML := `ADAMS Public Documents | U.S. NRC

ADAMS Public Documents

Publicly available NRC regulatory records including ML26101A014.

AccessionTitle
ML26101A014Inspection Report
` + rawNRC, okNRC := RunWave3RegulatorsHTMLMode("ferc_nrc_dockets_html", nrcHTML, "https://www.nrc.gov/documents-reports/adams-public-documents") + if !okNRC || !strings.Contains(rawNRC, "ML26101A014") { + t.Fatalf("ferc_nrc_dockets_html failed: ok=%v raw=%s", okNRC, rawNRC) + } + if _, okCFChl := RunWave3RegulatorsHTMLMode("ferc_nrc_dockets_html", `Just a moment...`, "https://elibrary.ferc.gov/eLibrary/search"); okCFChl { + t.Fatalf("ferc_nrc_dockets_html must reject Cloudflare challenge") + } + if _, okAng := RunWave3RegulatorsHTMLMode("ferc_nrc_dockets_html", `NRC ADAMS`, "https://adams-search.nrc.gov/"); okAng { + t.Fatalf("ferc_nrc_dockets_html must reject unhydrated ") + } + + // #287 CFTC / OCC / FinCEN HTML + OCC 404 marker rejection + occHTML := `Third-Party Relationships | OCC

OCC Bulletin 2023-17 | June 6, 2023

Third-Party Relationships: Interagency Guidance on Risk Management

Summary

The Office of the Comptroller of the Currency issued interagency third-party risk management guidance for national banks and federal savings associations.

` + rawOCC, okOCC := RunWave3RegulatorsHTMLMode("financial_regulators_html", occHTML, "https://www.occ.gov/news-issuances/bulletins/2023/bulletin-2023-17.html") + if !okOCC || !strings.Contains(rawOCC, "2023-17") || !strings.Contains(rawOCC, "Office of the Comptroller of the Currency") { + t.Fatalf("financial_regulators_html OCC failed: ok=%v raw=%s", okOCC, rawOCC) + } + if _, okOCC404 := RunWave3RegulatorsHTMLMode("financial_regulators_html", `OCC

Missing

Not available.

`, "https://www.occ.gov/news-issuances/missing.html"); okOCC404 { + t.Fatalf("financial_regulators_html must reject OCC rx-contentitemname=404") + } + + // #288 Oversight.gov positive & Azure App GW 406 rejection + ovHTML := `Reports | Oversight.gov

Inspector General Reports

Federal Offices of Inspector General audit and evaluation reports.

TitleOIG
Cybersecurity AuditDOJ OIG
` + rawOV, okOV := RunWave3RegulatorsHTMLMode("oversight_gov_html", ovHTML, "https://www.oversight.gov/reports") + if !okOV || !strings.Contains(rawOV, "DOJ OIG") { + t.Fatalf("oversight_gov_html failed: ok=%v raw=%s", okOV, rawOV) + } + if _, ok406 := RunWave3RegulatorsHTMLMode("oversight_gov_html", `406 Not Acceptable

Bad request. Reference: abc123

`, "https://www.oversight.gov/reports"); ok406 { + t.Fatalf("oversight_gov_html must reject Azure App GW 406") + } +} + +func TestWave3RegulatorsJSONFormattersAndFixtures(t *testing.T) { + for _, m := range []string{"dol_enforcement_json", "fcc_ecfs_json", "fcc_uls_json"} { + if !IsWave3RegulatorsJSONMode(m) { + t.Fatalf("IsWave3RegulatorsJSONMode(%q) = false", m) + } + } + + // 1. DOL OSHA inspection JSON + missing token rejection + oshaJSON := `{"data":[{"activity_nr":"1745210","estab_name":"Midwest Metalworks","site_city":"Cleveland","site_state":"OH","open_date":"2026-04-12","total_current_penalty":16131,"nr_instances":2}]}` + rawDOL, okDOL := FormatWave3RegulatorsJSONMode("dol_enforcement_json", []byte(oshaJSON), nil, "https://apiprod.dol.gov/v4/get/OSHA/inspection/json?limit=2") + if !okDOL || !strings.Contains(rawDOL, "1745210") || !strings.Contains(rawDOL, "16131.00") { + t.Fatalf("dol_enforcement_json OSHA failed: ok=%v raw=%s", okDOL, rawDOL) + } + if _, okErr := FormatWave3RegulatorsJSONMode("dol_enforcement_json", []byte(`{"message":"Missing Authentication Token"}`), nil, "https://apiprod.dol.gov/v4/get/OSHA/inspection/json"); okErr { + t.Fatalf("dol_enforcement_json must reject Missing Authentication Token") + } + + // 2. FCC ULS legacy data.fcc.gov + Socrata catalog v1 + Errors.Err rejection + legacyULS := `{"status":"OK","Licenses":{"totalRows":"1","License":[{"callsign":"WPTJ776","licName":"VERIZON WIRELESS","frn":"0003290673","serviceDesc":"AW - AWS","statusDesc":"Active","expiredDate":"04/15/2031","licDetailURL":"https://wireless2.fcc.gov/UlsApp/UlsSearch/license.jsp?licKey=123"}]}}` + rawLeg, okLeg := FormatWave3RegulatorsJSONMode("fcc_uls_json", []byte(legacyULS), nil, "https://data.fcc.gov/api/license-view/basicSearch/getLicenses?searchValue=Verizon&format=json") + if !okLeg || !strings.Contains(rawLeg, "WPTJ776") || !strings.Contains(rawLeg, "VERIZON WIRELESS") { + t.Fatalf("fcc_uls_json legacy format failed: ok=%v raw=%s", okLeg, rawLeg) + } + catULS := `{"resultSetSize":1,"results":[{"resource":{"id":"dpvg-tvcx","name":"ULS Microwave Locations","description":"FCC ULS microwave dataset","updatedAt":"2026-01-15T00:00:00.000Z"},"link":"https://opendata.fcc.gov/d/dpvg-tvcx"}]}` + rawCat, okCat := FormatWave3RegulatorsJSONMode("fcc_uls_json", []byte(catULS), nil, "https://opendata.fcc.gov/api/catalog/v1?q=ULS") + if !okCat || !strings.Contains(rawCat, "dpvg-tvcx") || !strings.Contains(rawCat, "ULS Microwave Locations") { + t.Fatalf("fcc_uls_json catalog format failed: ok=%v raw=%s", okCat, rawCat) + } + if _, okErrULS := FormatWave3RegulatorsJSONMode("fcc_uls_json", []byte(`{"status":"Err","Errors":{"Err":{"code":"100","msg":"No records"}}}`), nil, "https://data.fcc.gov/api/license-view/basicSearch/getLicenses"); okErrULS { + t.Fatalf("fcc_uls_json must reject Errors.Err") + } + + // 3. Validate all 10 JSON fixtures on disk + type fixtureNeg struct { + Name string `json:"name"` + Status int `json:"status"` + FinalURL string `json:"finalUrl"` + Payload string `json:"payload"` + } + type fixtureFile struct { + AdapterID string `json:"adapterId"` + Mode string `json:"mode"` + InputURL string `json:"inputUrl"` + ExpectedFetchURL string `json:"expectedFetchUrl"` + MockPayload string `json:"mockPayload"` + ExpectTitleIncludes string `json:"expectTitleIncludes"` + ExpectMarkdownIncludes []string `json:"expectMarkdownIncludes"` + NegativeCases []fixtureNeg `json:"negativeCases"` + } + + fixtures := []struct { + slug string + goMode string + isJSON bool + }{ + {"dol-enforcement", "dol_enforcement_json", true}, + {"osha-establishment", "osha_establishment_html", false}, + {"nlrb-cases", "nlrb_cases_html", false}, + {"eeoc-litigation", "eeoc_litigation_html", false}, + {"ftc-cases", "ftc_cases_html", false}, + {"fcc-ecfs", "fcc_ecfs_json", true}, + {"fcc-uls", "fcc_uls_json", true}, + {"ferc-nrc-dockets", "ferc_nrc_dockets_html", false}, + {"financial-regulators-enforcement", "financial_regulators_html", false}, + {"oversight-gov", "oversight_gov_html", false}, + } + + for _, tc := range fixtures { + raw, err := os.ReadFile(filepath.Join("..", "..", "hub", "test", "fixtures", "adapters", tc.slug+".json")) + if err != nil { + t.Fatalf("read fixture %s.json: %v", tc.slug, err) + } + var fx fixtureFile + if err := json.Unmarshal(raw, &fx); err != nil { + t.Fatalf("parse fixture %s.json: %v", tc.slug, err) + } + if fx.AdapterID != tc.slug { + t.Fatalf("%s.json adapterId=%q want %q", tc.slug, fx.AdapterID, tc.slug) + } + if len(fx.NegativeCases) < 4 { + t.Fatalf("%s.json has %d negativeCases; want >= 4", tc.slug, len(fx.NegativeCases)) + } + if tc.isJSON { + out, ok := FormatWave3RegulatorsJSONMode(tc.goMode, []byte(fx.MockPayload), nil, fx.InputURL) + if !ok { + t.Fatalf("%s.json golden JSON formatting failed", tc.slug) + } + doc := wave3K1DecodeDoc(t, out) + if fx.ExpectTitleIncludes != "" && !strings.Contains(doc.Title, fx.ExpectTitleIncludes) { + t.Fatalf("%s.json title %q missing %q", tc.slug, doc.Title, fx.ExpectTitleIncludes) + } + for _, needle := range fx.ExpectMarkdownIncludes { + if !strings.Contains(doc.Markdown, needle) { + t.Fatalf("%s.json markdown missing %q", tc.slug, needle) + } + } + for _, nc := range fx.NegativeCases { + if _, okNeg := FormatWave3RegulatorsJSONMode(tc.goMode, []byte(nc.Payload), nil, fx.InputURL); okNeg { + t.Fatalf("%s.json negativeCase %q unexpectedly succeeded", tc.slug, nc.Name) + } + } + } else { + out, ok := RunWave3RegulatorsHTMLMode(tc.goMode, fx.MockPayload, fx.InputURL) + if !ok { + t.Fatalf("%s.json golden HTML extraction failed", tc.slug) + } + var res DeclarativePostFetchResult + if err := json.Unmarshal([]byte(out), &res); err != nil { + t.Fatalf("%s.json decode PostFetchResult: %v", tc.slug, err) + } + if fx.ExpectTitleIncludes != "" && !strings.Contains(res.Title, fx.ExpectTitleIncludes) { + t.Fatalf("%s.json title %q missing %q", tc.slug, res.Title, fx.ExpectTitleIncludes) + } + for _, needle := range fx.ExpectMarkdownIncludes { + if !strings.Contains(res.Markdown, needle) { + t.Fatalf("%s.json markdown missing %q", tc.slug, needle) + } + } + for _, nc := range fx.NegativeCases { + targetURL := fx.InputURL + if nc.FinalURL != "" { + targetURL = nc.FinalURL + } + if _, okNeg := RunWave3RegulatorsHTMLMode(tc.goMode, nc.Payload, targetURL); okNeg { + t.Fatalf("%s.json negativeCase %q unexpectedly succeeded", tc.slug, nc.Name) + } + } + } + } + + // Regression tests for P2: F5 BIG-IP ASM (neutral ), DataDome var dd=, and 78 KB <div id="root"></div> shells + f5Shell := `<!doctype html><html><head><title>Notice

The requested URL was rejected. Please consult with your administrator.
Your support ID is: 12345678901234567890

` + ddShell := `Notice` + ddMinimalShell := `Notice

Please enable JS and disable any ad blocker.

` + largeReactRoot := `NLRB Case Search
` + attrFirstReactRoot := `NLRB Case Search
` + for _, tc := range []struct { + mode string + url string + html string + name string + }{ + {"ftc_cases_html", "https://www.ftc.gov/legal-library/browse/cases-proceedings/example-case", f5Shell, "ftc-f5-asm"}, + {"nlrb_cases_html", "https://www.nlrb.gov/case/01-CA-123456", f5Shell, "nlrb-f5-asm"}, + {"nlrb_cases_html", "https://www.nlrb.gov/case/01-CA-123456", ddShell, "nlrb-datadome"}, + {"nlrb_cases_html", "https://www.nlrb.gov/case/01-CA-123456", largeReactRoot, "nlrb-78kb-div-root"}, + {"nlrb_cases_html", "https://www.nlrb.gov/case/01-CA-123456", attrFirstReactRoot, "nlrb-78kb-attr-div-root"}, + {"bis_entity_list_html", "https://www.bis.gov/entity-list", ddMinimalShell, "bis-datadome-minimal"}, + {"bis_entity_list_html", "https://www.bis.gov/entity-list", attrFirstReactRoot, "bis-78kb-attr-div-root"}, + } { + if _, ok := RunWave3RegulatorsHTMLMode(tc.mode, tc.html, tc.url); ok { + t.Fatalf("%s must reject negative shell", tc.name) + } + } + + // M7: CFTC >= 16 KB real Drupal release embedding passive challenge-platform script must succeed + cftcHTML := `CFTC Charges Entity | CFTC

CFTC Orders Company to Pay Penalty

` + strings.Repeat("The Commodity Futures Trading Commission today issued an order filing and settling charges. ", 180) + `

` + if rawCFTC, okCFTC := RunWave3RegulatorsHTMLMode("financial_regulators_html", cftcHTML, "https://www.cftc.gov/PressRoom/PressReleases/9331-26"); !okCFTC || !strings.Contains(rawCFTC, "CFTC Orders Company") { + t.Fatalf("financial_regulators_html must not false-positive on passive challenge-platform in >=16KB cftc.gov page: ok=%v", okCFTC) + } +} diff --git a/internal/extract/wave3_resale.go b/internal/extract/wave3_resale.go new file mode 100644 index 0000000..6ccc0b1 --- /dev/null +++ b/internal/extract/wave3_resale.go @@ -0,0 +1,2927 @@ +package extract + +import ( + "bytes" + "encoding/json" + "fmt" + stdhtml "html" + "math" + "net/url" + "strconv" + "strings" +) + +const ( + wave3ResaleMaxHTMLBytes = 2 * 1024 * 1024 + wave3ResaleStdHTMLMaxBytes = 1 * 1024 * 1024 + wave3ResaleMaxJSONBytes = 4 * 1024 * 1024 + wave3ResaleMaxRecords = 25 +) + +var ( + wave3ResaleRxNotFoundTitle = newLazyRegexp(`(?i)(?:^|\b)(?:404|410|403\s+forbidden|forbidden|page\s+not\s+found|not\s+found|error\s*404|we\s+couldn'?t\s+find\s+that\s+page|access\s+denied|request\s+(?:rejected|blocked)|could\s+not\s+be\s+satisfied|unauthorized|attention\s+required|just\s+a\s+moment|blocked|listing\s+not\s+found|item\s+not\s+found|item\s+not\s+available|product\s+not\s+found|posting\s+(?:has\s+been\s+)?deleted)(?:\b|$)`) + wave3ResaleRxMaintTitle = newLazyRegexp(`(?i)(?:scheduled\s+maintenance|temporarily\s+unavailable|service\s+unavailable|site\s+maintenance|under\s+maintenance|502\s+bad\s+gateway|503\s+service|down\s+for\s+maintenance)`) + wave3ResaleRxErrorTitle = newLazyRegexp(`(?i)^(?:(?:(?:400|401|403|404|406|410|429|500|502|503)\s+)?(?:internal\s+)?server\s+error|application\s+error|system\s+error|unexpected\s+error|error\s+page|(?:400|401|403|404|406|410|429|500|502|503|http\s+\d{3})\s+error|error\s+(?:400|401|403|404|406|410|429|500|502|503)|error)(?:\s*[|\-\x{2013}\x{2014}:]\s*.*)?$|^.*(?:\s*[|\-\x{2013}\x{2014}:]\s*error)$`) + wave3ResaleRxGenericTitle = newLazyRegexp(`(?i)^(?:loading\.{0,3}|home|welcome|search|log\s*in|sign\s*in|facebook|marketplace|gumroad|lemon\s*squeezy|payhip|sellfy|back\s*market|swappa|mercari|poshmark|depop|grailed|pinkbike|upway|the\s+pro'?s\s+closet|bicycle\s+blue\s+book|chairish|1stdibs)$`) + wave3ResaleRxHTMLTag = newLazyRegexp(`<[^>]+>`) + wave3ResaleRxSpace = newLazyRegexp(`[ \t\r\n]+`) + wave3ResaleRxGTIN = newLazyRegexp(`^(?:\d{8}|\d{12}|\d{13}|\d{14})$`) + wave3ResaleRxCurrency3 = newLazyRegexp(`^[A-Z]{3}$`) + wave3ResaleRxTitleTag = newLazyRegexp(`(?is)]*>(.*?)`) + wave3ResaleRxMetaTag = newLazyRegexp(`(?is)]*>`) + wave3ResaleRxNextData = newLazyRegexp(`(?is)]*\bid\s*=\s*["']__NEXT_DATA__["'][^>]*>(.*?)`) + wave3ResaleRxBBBPriceRange = newLazyRegexp(`\$([0-9][0-9,]*(?:\.[0-9]{1,2})?)\s*[-\x{2013}\x{2014}]\s*\$([0-9][0-9,]*(?:\.[0-9]{1,2})?)`) + wave3ResaleRxBBBMSRP = newLazyRegexp(`(?i)(?:original\s+msrp|msrp)\s*:?\s*\$([0-9][0-9,]*(?:\.[0-9]{1,2})?)`) + wave3ResaleRxBBBTradeIn = newLazyRegexp(`(?i)trade[- ]?in(?:\s+value)?\s*:?\s*\$([0-9][0-9,]*(?:\.[0-9]{1,2})?)`) + wave3ResaleRxBBBTrend = newLazyRegexp(`(?i)12[- ]?month\s+projected\s+trend\s*:?\s*([+-]?\s*\d+(?:\.\d+)?)\s*%`) + wave3ResaleRxDimText = newLazyRegexp(`(?i)\b(?:dimensions?|measurements?)\s*:?\s*([^\n<]{3,140})`) + wave3ResaleRxCondText = newLazyRegexp(`(?i)\bcondition\s*:?\s*([A-Za-z0-9 ,/&\-]{2,80})`) +) + +func init() { + registerWave3ResaleHTMLModes() +} + +// RegisterWave3ResaleHTMLModes registers all Category P Resale & Marketplaces HTML modes lazily. +func RegisterWave3ResaleHTMLModes() { + registerWave3ResaleHTMLModes() +} + +func registerWave3ResaleHTMLModes() { + for _, mode := range []string{ + "pinkbike_buysell_html", + "used_bikes_shopify_html", + "bicycle_blue_book_html", + "back_market_swappa_html", + "peer_resale_fashion_html", + "local_classifieds_html", + "creator_digital_stores_html", + "chairish_1stdibs_html", + } { + m := mode + RegisterExternalHTMLModeLazy(m, func(rawHTML, baseURL string, _ func() string, extractorID string) *DeclarativePostFetchResult { + return Wave3ResaleRunHTML(m, rawHTML, baseURL, extractorID) + }) + } +} + +// IsWave3ResaleHTMLMode reports whether mode is one of the 8 Category P HTML modes (#360-#367). +func IsWave3ResaleHTMLMode(mode string) bool { + switch mode { + case "pinkbike_buysell_html", + "used_bikes_shopify_html", + "bicycle_blue_book_html", + "back_market_swappa_html", + "peer_resale_fashion_html", + "local_classifieds_html", + "creator_digital_stores_html", + "chairish_1stdibs_html": + return true + default: + return false + } +} + +// IsWave3ResaleJSONMode reports whether mode is one of the Category P JSON formatters (`reverb_listing_json`, `reverb_search_json`). +func IsWave3ResaleJSONMode(mode string) bool { + switch mode { + case "reverb_listing_json", "reverb_search_json": + return true + default: + return false + } +} + +func wave3ResaleDefaultExtractorID(mode string) string { + switch mode { + case "reverb_listing_json", "reverb_search_json": + return "reverb" + case "pinkbike_buysell_html": + return "pinkbike-buysell" + case "used_bikes_shopify_html": + return "used-bikes-shopify" + case "bicycle_blue_book_html": + return "bicycle-blue-book" + case "back_market_swappa_html": + return "back-market-swappa" + case "peer_resale_fashion_html": + return "peer-resale-fashion" + case "local_classifieds_html": + return "local-classifieds-marketplaces" + case "creator_digital_stores_html": + return "creator-digital-stores" + case "chairish_1stdibs_html": + return "chairish-1stdibs" + default: + return "" + } +} + +// Wave3ResaleRunHTML executes a Category P HTML extractor and returns DeclarativePostFetchResult. +func Wave3ResaleRunHTML(mode, rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + if !IsWave3ResaleHTMLMode(mode) || len(rawHTML) == 0 || strings.IndexByte(rawHTML, '<') < 0 || strings.IndexByte(rawHTML, '>') < 0 { + return nil + } + maxHTML := wave3ResaleStdHTMLMaxBytes + if mode == "peer_resale_fashion_html" || mode == "used_bikes_shopify_html" || mode == "local_classifieds_html" || mode == "chairish_1stdibs_html" { + maxHTML = wave3ResaleMaxHTMLBytes + } + if len(rawHTML) > maxHTML { + rawHTML = truncateUTF8SafeFullDocGo(rawHTML, maxHTML) + } + trimmedStart := strings.TrimLeft(rawHTML, " \t\r\n") + if trimmedStart == "" || trimmedStart[0] == '{' || trimmedStart[0] == '[' { + return nil + } + probe := rawHTML + if len(probe) > 65536 { + probe = probe[:65536] + } + probeLower := asciiLowerExtractString(probe) + urlLower := asciiLowerExtractString(baseURL) + + if !wave3ResaleMatchesModePrefilter(mode, probeLower, urlLower) { + return nil + } + if wave3ResaleHasCommonNegativeShell(mode, rawHTML, probeLower, urlLower) { + return nil + } + if extractorID == "" { + extractorID = wave3ResaleDefaultExtractorID(mode) + } + + var res *DeclarativePostFetchResult + switch mode { + case "pinkbike_buysell_html": + res = wave3ResaleExtractPinkbikeHTML(rawHTML, baseURL, extractorID) + case "used_bikes_shopify_html": + res = wave3ResaleExtractUsedBikesHTML(rawHTML, baseURL, urlLower, extractorID) + case "bicycle_blue_book_html": + res = wave3ResaleExtractBicycleBlueBookHTML(rawHTML, baseURL, extractorID) + case "back_market_swappa_html": + res = wave3ResaleExtractBackMarketSwappaHTML(rawHTML, baseURL, extractorID) + case "peer_resale_fashion_html": + res = wave3ResaleExtractPeerResaleHTML(rawHTML, baseURL, extractorID) + case "local_classifieds_html": + res = wave3ResaleExtractLocalClassifiedsHTML(rawHTML, baseURL, urlLower, extractorID) + case "creator_digital_stores_html": + res = wave3ResaleExtractCreatorStoresHTML(rawHTML, baseURL, extractorID) + case "chairish_1stdibs_html": + res = wave3ResaleExtractChairish1stDibsHTML(rawHTML, baseURL, extractorID) + } + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return nil + } + return wave3ResaleFinalizePostFetch(res) +} + +// RunWave3ResaleHTMLMode executes a Category P HTML extractor and returns JSON-marshaled DeclarativePostFetchResult. +func RunWave3ResaleHTMLMode(mode, rawHTML, baseURL string) (string, bool) { + res := Wave3ResaleRunHTML(mode, rawHTML, baseURL, wave3ResaleDefaultExtractorID(mode)) + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return "", false + } + res = sanitizePostFetchResultDeclHTML(res) + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return "", false + } + encoded, err := json.Marshal(res) + if err != nil { + return "", false + } + return string(encoded), true +} + +// FormatWave3ResaleJSONDoc formats a Category P JSON twin payload into DeclarativeFormattedDoc. +func FormatWave3ResaleJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool) { + if !IsWave3ResaleJSONMode(mode) || len(raw) == 0 || len(raw) > wave3ResaleMaxJSONBytes { + return nil, false + } + trimmed := bytes.TrimSpace(bytes.TrimPrefix(raw, []byte("\xEF\xBB\xBF"))) + if len(trimmed) == 0 || trimmed[0] != '{' { + return nil, false + } + parsed, ok := decodeJSONWithNumbers(trimmed) + if !ok || parsed == nil { + return nil, false + } + obj, isObj := parsed.(map[string]any) + if !isObj || wave3ResaleIsGenericJSONError(obj) { + return nil, false + } + var doc *DeclarativeFormattedDoc + var handled bool + switch mode { + case "reverb_listing_json": + doc, handled = wave3ResaleFormatReverbListingJSON(obj, origURL) + case "reverb_search_json": + doc, handled = wave3ResaleFormatReverbSearchJSON(obj, origURL) + } + if !handled || doc == nil || strings.TrimSpace(doc.Markdown) == "" { + return nil, false + } + return wave3ResaleFinalizeDoc(doc), true +} + +// FormatWave3ResaleJSONMode formats a Category P JSON payload and returns JSON-marshaled DeclarativeFormattedDoc. +func FormatWave3ResaleJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool) { + doc, ok := FormatWave3ResaleJSONDoc(mode, raw, params, origURL) + if !ok || doc == nil { + return "", false + } + encoded, err := json.Marshal(doc) + if err != nil { + return "", false + } + return string(encoded), true +} + +// ── Prefilters & Shared Hygiene Helpers ────────────────────────────────────────────────────────── + +func wave3ResaleMatchesModePrefilter(mode, probeLower, urlLower string) bool { + switch mode { + case "pinkbike_buysell_html": + return strings.Contains(urlLower, "pinkbike.com") || + strings.Contains(probeLower, "pinkbike") || + strings.Contains(probeLower, "buysell") + case "used_bikes_shopify_html": + return strings.Contains(urlLower, "upway.co") || + strings.Contains(urlLower, "theproscloset.com") || + strings.Contains(probeLower, "data-upway-hydrogen") || + strings.Contains(probeLower, "upway") || + strings.Contains(probeLower, "theproscloset") || + strings.Contains(probeLower, "application/ld+json") + case "bicycle_blue_book_html": + return strings.Contains(urlLower, "bicyclebluebook.com") || + strings.Contains(probeLower, "bicyclebluebook") || + strings.Contains(probeLower, "bicycle blue book") || + strings.Contains(probeLower, "original msrp") + case "back_market_swappa_html": + return strings.Contains(urlLower, "backmarket.com") || + strings.Contains(urlLower, "swappa.com") || + strings.Contains(probeLower, "backmarket") || + strings.Contains(probeLower, "back market") || + strings.Contains(probeLower, "swappa") + case "peer_resale_fashion_html": + return strings.Contains(urlLower, "poshmark.com") || + strings.Contains(urlLower, "mercari.com") || + strings.Contains(urlLower, "depop.com") || + strings.Contains(urlLower, "grailed.com") || + strings.Contains(probeLower, "poshmark") || + strings.Contains(probeLower, "mercari") || + strings.Contains(probeLower, "depop") || + strings.Contains(probeLower, "grailed") + case "local_classifieds_html": + return strings.Contains(urlLower, "craigslist.org") || + strings.Contains(urlLower, "offerup.com") || + strings.Contains(urlLower, "facebook.com") || + strings.Contains(probeLower, "craigslist") || + strings.Contains(probeLower, "offerup") || + strings.Contains(probeLower, "postingbody") || + strings.Contains(probeLower, "marketplace") + case "creator_digital_stores_html": + return strings.Contains(urlLower, "gumroad.com") || + strings.Contains(urlLower, "lemonsqueezy.com") || + strings.Contains(urlLower, "payhip.com") || + strings.Contains(urlLower, "sellfy.") || + strings.Contains(probeLower, "gumroad") || + strings.Contains(probeLower, "lemonsqueezy") || + strings.Contains(probeLower, "lemon squeezy") || + strings.Contains(probeLower, "payhip") || + strings.Contains(probeLower, "sellfy") + case "chairish_1stdibs_html": + return strings.Contains(urlLower, "chairish.com") || + strings.Contains(urlLower, "1stdibs.com") || + strings.Contains(probeLower, "chairish") || + strings.Contains(probeLower, "1stdibs") + default: + return false + } +} + +func wave3ResaleIsNegativeURL(urlLower string) bool { + if urlLower == "" { + return false + } + if strings.Contains(urlLower, "/404") || + strings.Contains(urlLower, "/not-found") || + strings.Contains(urlLower, "/page-not-found") || + strings.Contains(urlLower, "/maintenance") || + strings.Contains(urlLower, "error=true") || + strings.Contains(urlLower, "error=1") { + return true + } + pathOnly := urlLower + if idx := strings.Index(pathOnly, "://"); idx >= 0 { + rest := pathOnly[idx+3:] + if slash := strings.IndexByte(rest, '/'); slash >= 0 { + pathOnly = rest[slash:] + } else { + pathOnly = "/" + } + } + if cut := strings.IndexAny(pathOnly, "?#"); cut >= 0 { + pathOnly = pathOnly[:cut] + } + return strings.HasSuffix(pathOnly, "/error") || + strings.Contains(pathOnly, "/error/") || + strings.HasSuffix(pathOnly, "/error.html") || + strings.HasSuffix(pathOnly, "/error.htm") || + strings.HasSuffix(pathOnly, "/error.aspx") || + strings.HasSuffix(pathOnly, "/login") || + strings.Contains(pathOnly, "/login/") || + strings.Contains(pathOnly, "/testchallengepage") +} + +func wave3ResaleIsNegativeTitle(title string) bool { + t := strings.TrimSpace(title) + if t == "" { + return false + } + return wave3ResaleRxNotFoundTitle.MatchString(t) || + wave3ResaleRxMaintTitle.MatchString(t) || + wave3ResaleRxErrorTitle.MatchString(t) +} + +func wave3ResaleIsGenericTitle(title string) bool { + return wave3ResaleRxGenericTitle.MatchString(strings.TrimSpace(title)) +} + +func wave3ResaleContainsASCIIFold(haystack, needleLower string) bool { + return indexFoldASCIIExtract(haystack, needleLower) >= 0 +} + +func wave3ResaleSlimHTMLForDOM(rawHTML string, maxBytes int) string { + slim := stripScriptsAndStylesDeclHTML(rawHTML) + if maxBytes > 0 && len(slim) > maxBytes { + slim = truncateUTF8SafeFullDocGo(slim, maxBytes) + } + return slim +} + +func wave3ResaleExtractTitleBounded(rawHTML string) string { + head := rawHTML + if len(head) > 65536 { + head = head[:65536] + } + if !wave3ResaleContainsASCIIFold(head, "= 2 { + return wave3ResaleCleanText(m[1]) + } + return "" +} + +func wave3ResaleExtractMetaBounded(rawHTML, targetKey string) string { + head := rawHTML + if len(head) > 65536 { + head = head[:65536] + } + if !wave3ResaleContainsASCIIFold(head, " len(probeLower) && len(rawHTML) <= 256*1024 { + rawLower = asciiLowerExtractString(rawHTML) + } + // Password input without Product/ItemList JSON-LD indicates a login wall. + if (strings.Contains(rawLower, `type="password"`) || strings.Contains(rawLower, `type='password'`)) && + !strings.Contains(rawLower, `"product"`) && !strings.Contains(rawLower, `"itemlist"`) { + return true + } + + hasRichMarkers := hasJSONLDScriptToken(rawLower) || + strings.Contains(rawLower, " 65536 { + tail := rawHTML[65536:] + hasRichMarkers = indexFoldASCIIExtract(tail, "= 0 || + indexFoldASCIIExtract(tail, "= 0 || + indexFoldASCIIExtract(tail, "application/ld+json") >= 0 || + (indexFoldASCIIExtract(tail, "data-page=") >= 0 && (indexFoldASCIIExtract(tail, `"props"`) >= 0 || indexFoldASCIIExtract(tail, ""props"") >= 0)) + } + if (strings.Contains(probeLower, "challenge-platform") || strings.Contains(probeLower, "cf-turnstile")) && + len(rawHTML) < 16384 && !hasRichMarkers { + return true + } + if (wave3HasEmptyRootDivShell(rawHTML, probeLower, true) || strings.Contains(rawLower, `id="mount_0_0"`)) && !hasRichMarkers { + return true + } + return false +} + +func wave3ResaleIsGenericJSONError(obj map[string]any) bool { + if obj == nil { + return true + } + if succ, ok := obj["success"].(bool); ok && !succ { + return true + } + if errFlag, ok := obj["error"].(bool); ok && errFlag { + return true + } + for _, k := range []string{"error", "errors", "errorMessages", "error_message", "errorMessage", "errorCode", "error_description", "fault"} { + if v, exists := obj[k]; exists && v != nil { + switch tv := v.(type) { + case string: + if strings.TrimSpace(tv) != "" { + return true + } + case []any: + if len(tv) > 0 { + return true + } + case map[string]any: + if len(tv) > 0 { + return true + } + case bool: + if tv { + return true + } + } + } + } + for _, k := range []string{"error_code", "statusCode", "status_code", "status"} { + if f, ok := wave3ResaleFloatVal(obj[k]); ok && f >= 400 { + return true + } + } + for _, mk := range []string{"message", "detail"} { + if msg := wave3ResalePlain(obj[mk], 240); msg != "" && len(obj) <= 4 { + lm := strings.ToLower(msg) + if strings.Contains(lm, "not found") || + strings.Contains(lm, "unauthorized") || + strings.Contains(lm, "invalid") || + strings.Contains(lm, "forbidden") || + strings.Contains(lm, "does not exist") || + strings.Contains(lm, "accept-version") { + return true + } + } + } + return false +} + +func wave3ResaleIntPtr(n int) *int { return &n } +func wave3ResaleBoolPtr(b bool) *bool { return &b } + +func wave3ResaleFinalizeDoc(doc *DeclarativeFormattedDoc) *DeclarativeFormattedDoc { + if doc == nil { + return nil + } + if len(doc.Records) > wave3ResaleMaxRecords { + if doc.Total == nil { + doc.Total = wave3ResaleIntPtr(len(doc.Records)) + } + doc.Records = doc.Records[:wave3ResaleMaxRecords] + doc.Returned = wave3ResaleIntPtr(len(doc.Records)) + doc.Truncated = wave3ResaleBoolPtr(true) + if doc.NextCursor == "" { + doc.NextCursor = strconv.Itoa(len(doc.Records)) + } + } + if sanitized, ok := sanitizeDeclarativeFormattedDocGo(doc); ok && sanitized != nil { + return sanitized + } + return nil +} + +func wave3ResaleFinalizePostFetch(res *DeclarativePostFetchResult) *DeclarativePostFetchResult { + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return nil + } + if len(res.Records) > wave3ResaleMaxRecords { + if res.Total == nil { + res.Total = wave3ResaleIntPtr(len(res.Records)) + } + res.Records = res.Records[:wave3ResaleMaxRecords] + res.Returned = wave3ResaleIntPtr(len(res.Records)) + res.Truncated = wave3ResaleBoolPtr(true) + if res.NextCursor == "" { + res.NextCursor = strconv.Itoa(len(res.Records)) + } + } + return res +} + +func wave3ResaleCleanText(s string) string { + if s == "" { + return "" + } + if strings.IndexByte(s, '<') >= 0 { + s = wave3ResaleRxHTMLTag.ReplaceAllString(s, " ") + } + if strings.IndexByte(s, '&') >= 0 { + s = stdhtml.UnescapeString(s) + if strings.IndexByte(s, '<') >= 0 { + s = wave3ResaleRxHTMLTag.ReplaceAllString(s, " ") + } + } + if !strings.ContainsAny(s, "\t\r\n") && !strings.Contains(s, " ") { + return strings.TrimSpace(s) + } + return strings.TrimSpace(wave3ResaleRxSpace.ReplaceAllString(s, " ")) +} + +func wave3ResaleStringVal(v any) string { + switch tv := v.(type) { + case string: + return strings.TrimSpace(tv) + case json.Number: + return tv.String() + case float64: + if math.IsNaN(tv) || math.IsInf(tv, 0) { + return "" + } + if tv == math.Trunc(tv) { + return strconv.FormatInt(int64(tv), 10) + } + return strconv.FormatFloat(tv, 'f', -1, 64) + case int: + return strconv.Itoa(tv) + case int64: + return strconv.FormatInt(tv, 10) + case bool: + if tv { + return "true" + } + return "false" + default: + return "" + } +} + +func wave3ResaleFloatVal(v any) (float64, bool) { + switch tv := v.(type) { + case float64: + if math.IsNaN(tv) || math.IsInf(tv, 0) { + return 0, false + } + return tv, true + case int: + return float64(tv), true + case int64: + return float64(tv), true + case json.Number: + f, err := tv.Float64() + if err != nil || math.IsNaN(f) || math.IsInf(f, 0) { + return 0, false + } + return f, true + case string: + s := strings.TrimSpace(strings.ReplaceAll(strings.TrimPrefix(strings.TrimSpace(tv), "$"), ",", "")) + if s == "" { + return 0, false + } + f, err := strconv.ParseFloat(s, 64) + if err != nil || math.IsNaN(f) || math.IsInf(f, 0) { + return 0, false + } + return f, true + default: + return 0, false + } +} + +func wave3ResalePlain(v any, maxLen int) string { + return SanitizeSchemaPlainField(wave3ResaleCleanText(wave3ResaleStringVal(v)), maxLen) +} + +func wave3ResaleFirstNonEmpty(vals ...string) string { + for _, v := range vals { + if t := strings.TrimSpace(v); t != "" { + return t + } + } + return "" +} + +func wave3ResaleValidGTIN(raw string) string { + s := strings.TrimSpace(raw) + if wave3ResaleRxGTIN.MatchString(s) { + return s + } + return "" +} + +func wave3ResaleValidCurrency(raw string) string { + s := strings.ToUpper(strings.TrimSpace(raw)) + if wave3ResaleRxCurrency3.MatchString(s) { + return s + } + return "" +} + +func wave3ResaleFormatPrice(amount any, currency string) (string, string, string) { + cur := wave3ResaleValidCurrency(currency) + f, ok := wave3ResaleFloatVal(amount) + if !ok || f < 0 { + return "", "", cur + } + numStr := strconv.FormatFloat(f, 'f', 2, 64) + if cur != "" { + return fmt.Sprintf("%s %s", numStr, cur), numStr, cur + } + return numStr, numStr, "" +} + +func wave3ResaleCapitalizeWords(s string) string { + parts := strings.Fields(s) + for i, p := range parts { + if len(p) > 0 && p[0] >= 'a' && p[0] <= 'z' { + parts[i] = string(p[0]-'a'+'A') + p[1:] + } + } + return strings.Join(parts, " ") +} + +func wave3ResaleAddLink(links *[]string, seen map[string]bool, raw, base string) { + u := SanitizeSchemaHTTPSURL(raw, base) + if u != "" && !seen[u] { + seen[u] = true + *links = append(*links, u) + } +} + +func wave3ResaleNestedMap(obj map[string]any, keys ...string) map[string]any { + cur := obj + for _, k := range keys { + if cur == nil { + return nil + } + next, ok := cur[k].(map[string]any) + if !ok { + return nil + } + cur = next + } + return cur +} + +func wave3ResaleExtractTitle(doc *HTMLDoc, rawHTML string) string { + if doc != nil { + if h1 := SanitizeSchemaPlainField(wave3ResaleCleanText(doc.Text("h1")), 240); h1 != "" && !wave3ResaleIsGenericTitle(h1) && !wave3ResaleIsNegativeTitle(h1) { + return h1 + } + } + if og := SanitizeSchemaPlainField(wave3ResaleExtractMetaBounded(rawHTML, "og:title"), 240); og != "" && !wave3ResaleIsGenericTitle(og) && !wave3ResaleIsNegativeTitle(og) { + return og + } + if t := SanitizeSchemaPlainField(wave3ResaleExtractTitleBounded(rawHTML), 240); t != "" && !wave3ResaleIsGenericTitle(t) && !wave3ResaleIsNegativeTitle(t) { + return t + } + return "" +} + +func wave3ResaleExtractMetaDesc(rawHTML string) string { + return wave3ResaleFirstNonEmpty( + SanitizeSchemaPlainField(wave3ResaleExtractMetaBounded(rawHTML, "og:description"), 600), + SanitizeSchemaPlainField(wave3ResaleExtractMetaBounded(rawHTML, "description"), 600), + ) +} + +func wave3ResaleHasSchemaType(obj map[string]any, wanted ...string) bool { + if obj == nil { + return false + } + check := func(s string) bool { + low := strings.ToLower(strings.TrimSpace(s)) + if idx := strings.LastIndexByte(low, '/'); idx >= 0 { + low = low[idx+1:] + } + for _, w := range wanted { + if low == strings.ToLower(w) { + return true + } + } + return false + } + switch t := obj["@type"].(type) { + case string: + return check(t) + case []any: + for _, it := range t { + if s, ok := it.(string); ok && check(s) { + return true + } + } + } + return false +} + +func wave3ResaleCleanSchemaEnum(raw string) string { + s := strings.TrimSpace(raw) + if idx := strings.LastIndexByte(s, '/'); idx >= 0 && idx+1 < len(s) { + s = s[idx+1:] + } + return SanitizeSchemaPlainField(s, 80) +} + +func wave3ResaleExtractBrandName(v any) string { + switch tv := v.(type) { + case string: + return SanitizeSchemaPlainField(tv, 120) + case map[string]any: + return SanitizeSchemaPlainField(wave3ResaleStringVal(tv["name"]), 120) + case []any: + for _, el := range tv { + if n := wave3ResaleExtractBrandName(el); n != "" { + return n + } + } + } + return "" +} + +func wave3ResaleExtractJSONLDProduct(ldObjs []map[string]any) map[string]any { + for _, obj := range ldObjs { + if wave3ResaleHasSchemaType(obj, "Product", "IndividualProduct", "ProductModel") { + return obj + } + } + for _, obj := range ldObjs { + if wave3ResaleHasSchemaType(obj, "ProductGroup") { + return obj + } + } + return nil +} + +type wave3ResaleOfferInfo struct { + Price string + Currency string + LowPrice string + HighPrice string + OfferCount string + Availability string + Condition string + Seller string + URL string +} + +func wave3ResaleParseOffers(v any, baseURL string) []wave3ResaleOfferInfo { + var out []wave3ResaleOfferInfo + parseOne := func(m map[string]any) { + if m == nil { + return + } + cur := wave3ResaleValidCurrency(wave3ResaleStringVal(m["priceCurrency"])) + var info wave3ResaleOfferInfo + info.Currency = cur + if _, pStr, _ := wave3ResaleFormatPrice(m["price"], cur); pStr != "" { + info.Price = pStr + } else if ps, okP := wave3ResaleNestedMap(m, "priceSpecification"), true; okP && ps != nil { + if pCur := wave3ResaleFirstNonEmpty(cur, wave3ResaleValidCurrency(wave3ResaleStringVal(ps["priceCurrency"]))); pCur != "" { + info.Currency = pCur + } + if _, pStr2, _ := wave3ResaleFormatPrice(ps["price"], info.Currency); pStr2 != "" { + info.Price = pStr2 + } + } + if _, lp, _ := wave3ResaleFormatPrice(m["lowPrice"], cur); lp != "" { + info.LowPrice = lp + } + if _, hp, _ := wave3ResaleFormatPrice(m["highPrice"], cur); hp != "" { + info.HighPrice = hp + } + if f, ok := wave3ResaleFloatVal(m["offerCount"]); ok && f >= 0 { + info.OfferCount = strconv.Itoa(int(f)) + } + info.Availability = wave3ResaleCleanSchemaEnum(wave3ResaleStringVal(m["availability"])) + info.Condition = wave3ResaleCleanSchemaEnum(wave3ResaleStringVal(m["itemCondition"])) + info.Seller = wave3ResaleExtractBrandName(m["seller"]) + info.URL = SanitizeSchemaHTTPSURL(wave3ResaleStringVal(m["url"]), baseURL) + if info.Price != "" || info.LowPrice != "" || info.Availability != "" || info.Condition != "" { + out = append(out, info) + } + } + switch tv := v.(type) { + case map[string]any: + if nested, hasNested := tv["offers"]; hasNested { + out = append(out, wave3ResaleParseOffers(nested, baseURL)...) + } + if len(out) == 0 { + parseOne(tv) + } + case []any: + for _, el := range tv { + if len(out) >= 12 { + break + } + if em, ok := el.(map[string]any); ok { + parseOne(em) + } + } + } + return out +} + +func wave3ResaleExtractNextDataObj(rawHTML string) map[string]any { + if !strings.Contains(rawHTML, "__NEXT_DATA__") && !wave3ResaleContainsASCIIFold(rawHTML, "__next_data__") { + return nil + } + m := wave3ResaleRxNextData.FindStringSubmatch(rawHTML) + if len(m) < 2 { + return nil + } + raw := strings.TrimSpace(m[1]) + if raw == "" || raw[0] != '{' { + return nil + } + parsed, ok := decodeJSONWithNumbers([]byte(raw)) + if !ok { + return nil + } + obj, _ := parsed.(map[string]any) + return obj +} + +func wave3ResaleExtractBalancedJSONField(src, key string) (string, bool) { + needle := `"` + key + `"` + pos := 0 + for pos < len(src) { + rel := strings.Index(src[pos:], needle) + if rel < 0 { + return "", false + } + after := pos + rel + len(needle) + for after < len(src) && (src[after] == ' ' || src[after] == '\t' || src[after] == '\r' || src[after] == '\n') { + after++ + } + if after < len(src) && src[after] == ':' { + if raw, _, ok := ExtractBalancedJSONAt(src, after+1, 512*1024); ok { + return raw, true + } + } + pos += rel + len(needle) + } + return "", false +} + +func wave3ResaleExtractInitStateObj(rawHTML string) map[string]any { + idx := indexFoldASCIIExtract(rawHTML, "window.__initial_state__") + if idx < 0 { + return nil + } + rawJSON, _, ok := ExtractBalancedJSONAt(rawHTML, idx+len("window.__INITIAL_STATE__"), 1_200_000) + if !ok || rawJSON == "" || rawJSON[0] != '{' { + return nil + } + + // Fast bounded path for Poshmark's $_listing.listing without full-tree 500KB JSON decode. + if subRaw, okSub := wave3ResaleExtractBalancedJSONField(rawJSON, "$_listing"); okSub { + if lstRaw, okLst := wave3ResaleExtractBalancedJSONField(subRaw, "listing"); okLst { + if parsedLst, okParse := decodeJSONWithNumbers([]byte(lstRaw)); okParse { + if lstMap, okMap := parsedLst.(map[string]any); okMap { + return map[string]any{"$_listing": map[string]any{"listing": lstMap}} + } + } + } + } + + // Streaming top-level key decoder fallback (skips unrelated Vuex/Redux state). + dec := json.NewDecoder(strings.NewReader(rawJSON)) + dec.UseNumber() + tok, err := dec.Token() + if err != nil { + return nil + } + if d, okD := tok.(json.Delim); !okD || d != '{' { + return nil + } + out := make(map[string]any) + for dec.More() { + kTok, errK := dec.Token() + if errK != nil { + break + } + key, _ := kTok.(string) + var valRaw json.RawMessage + if errV := dec.Decode(&valRaw); errV != nil { + break + } + if key == "$_listing" || key == "listing" { + if parsed, okP := decodeJSONWithNumbers(valRaw); okP { + out[key] = parsed + } + } + } + if len(out) == 0 { + return nil + } + return out +} + +func wave3ResaleTitleFromURLSlug(itemURL string) string { + u, err := url.Parse(strings.TrimSpace(itemURL)) + if err != nil { + return "" + } + p := strings.Trim(u.Path, "/") + if p == "" { + return "" + } + if idx := strings.LastIndexByte(p, '/'); idx >= 0 { + p = p[idx+1:] + } + for _, ext := range []string{".html", ".htm", ".php"} { + if strings.HasSuffix(strings.ToLower(p), ext) { + p = p[:len(p)-len(ext)] + break + } + } + if strings.Contains(p, "%") { + if unesc, uErr := url.PathUnescape(p); uErr == nil { + p = unesc + } + } + p = strings.NewReplacer("-", " ", "_", " ").Replace(p) + tokens := strings.Fields(p) + if len(tokens) == 0 { + return "" + } + // Drop trailing Poshmark-style hex ID (e.g. 6a67deaeb6af921bbc5288a4) or numeric ID when descriptive words precede it. + if len(tokens) >= 2 { + last := tokens[len(tokens)-1] + isHex := len(last) >= 12 + isDigits := len(last) >= 4 + for i := 0; i < len(last); i++ { + c := last[i] + if !((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')) { + isHex = false + } + if c < '0' || c > '9' { + isDigits = false + } + } + if isHex || isDigits { + tokens = tokens[:len(tokens)-1] + } + } + joined := strings.Join(tokens, " ") + hasAlpha := false + hasUpper := false + for i := 0; i < len(joined); i++ { + c := joined[i] + if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') { + hasAlpha = true + } + if c >= 'A' && c <= 'Z' { + hasUpper = true + } + } + if !hasAlpha { + return "" + } + low := strings.ToLower(joined) + switch low { + case "listing", "item", "product", "women", "men", "category", "discover": + return "" + } + if !hasUpper { + joined = wave3ResaleCapitalizeWords(joined) + } + return SanitizeSchemaPlainField(joined, 200) +} + +func wave3ResaleExtractItemList(ldObjs []map[string]any, baseURL string) ([]map[string]any, [][]string, []string) { + var recs []map[string]any + var rows [][]string + var links []string + seen := make(map[string]bool) + + pushItem := func(title, price, cur, cond, itemURL string) { + if title == "" || len(recs) >= wave3ResaleMaxRecords { + return + } + priceCell := "-" + if price != "" { + if cur != "" { + priceCell = price + " " + cur + } else { + priceCell = price + } + } + condCell := wave3ResaleFirstNonEmpty(cond, "-") + rows = append(rows, []string{escapeDeclMarkdownBrackets(title), priceCell, condCell}) + rec := map[string]any{"title": title} + if price != "" { + rec["price"] = price + } + if cur != "" { + rec["currency"] = cur + } + if cond != "" { + rec["condition"] = cond + } + if itemURL != "" { + rec["url"] = itemURL + wave3ResaleAddLink(&links, seen, itemURL, baseURL) + } + recs = append(recs, rec) + } + + for _, obj := range ldObjs { + if !wave3ResaleHasSchemaType(obj, "ItemList", "SearchResultsPage", "CollectionPage") { + continue + } + var elems []any + if arr, ok := obj["itemListElement"].([]any); ok { + elems = arr + } else if mainEnt := wave3ResaleNestedMap(obj, "mainEntity"); mainEnt != nil { + if arr, ok := mainEnt["itemListElement"].([]any); ok { + elems = arr + } + } + for _, rawEl := range elems { + if len(recs) >= wave3ResaleMaxRecords { + break + } + el, ok := rawEl.(map[string]any) + if !ok { + continue + } + target := el + if sub, okSub := el["item"].(map[string]any); okSub && sub != nil { + target = sub + } + itemURL := wave3ResaleFirstNonEmpty( + SanitizeSchemaHTTPSURL(wave3ResaleStringVal(target["url"]), baseURL), + SanitizeSchemaHTTPSURL(wave3ResaleStringVal(el["url"]), baseURL), + ) + title := wave3ResaleFirstNonEmpty( + wave3ResalePlain(target["name"], 200), + wave3ResalePlain(el["name"], 200), + wave3ResalePlain(target["alternateName"], 200), + wave3ResalePlain(el["alternateName"], 200), + ) + if title == "" && itemURL != "" { + title = wave3ResaleTitleFromURLSlug(itemURL) + } + var price, cur, cond string + if offers := wave3ResaleParseOffers(target["offers"], baseURL); len(offers) > 0 { + price = wave3ResaleFirstNonEmpty(offers[0].Price, offers[0].LowPrice) + cur = offers[0].Currency + cond = offers[0].Condition + } + pushItem(title, price, cur, cond, itemURL) + } + } + return recs, rows, links +} + +// ── #359 Reverb (`reverb_listing_json`, `reverb_search_json`) ──────────────────────────────────── + +func wave3ResaleFormatReverbListingJSON(obj map[string]any, origURL string) (*DeclarativeFormattedDoc, bool) { + title := wave3ResalePlain(obj["title"], 240) + idStr := wave3ResalePlain(obj["id"], 48) + if title == "" || idStr == "" { + return nil, false + } + makeName := wave3ResalePlain(obj["make"], 120) + modelName := wave3ResalePlain(obj["model"], 120) + finish := wave3ResalePlain(obj["finish"], 120) + year := wave3ResalePlain(obj["year"], 32) + shopName := wave3ResalePlain(obj["shop_name"], 120) + if shopName == "" { + if shop := wave3ResaleNestedMap(obj, "shop"); shop != nil { + shopName = wave3ResalePlain(shop["name"], 120) + } + } + condition := "" + if cm := wave3ResaleNestedMap(obj, "condition"); cm != nil { + condition = wave3ResaleFirstNonEmpty(wave3ResalePlain(cm["display_name"], 80), wave3ResalePlain(cm["name"], 80)) + } else { + condition = wave3ResalePlain(obj["condition"], 80) + } + var priceDisp, priceNum, priceCur string + if pm := wave3ResaleNestedMap(obj, "price"); pm != nil { + priceDisp, priceNum, priceCur = wave3ResaleFormatPrice(pm["amount"], wave3ResaleStringVal(pm["currency"])) + } + var shipDisp string + if sm := wave3ResaleNestedMap(obj, "shipping"); sm != nil { + if rm := wave3ResaleNestedMap(sm, "rate"); rm != nil { + shipDisp, _, _ = wave3ResaleFormatPrice(rm["amount"], wave3ResaleStringVal(rm["currency"])) + } else if freeExp, ok := sm["free_expedited_shipping"].(bool); ok && freeExp { + shipDisp = "Free Expedited Shipping" + } + } + var location string + if lm := wave3ResaleNestedMap(obj, "location"); lm != nil { + location = wave3ResalePlain(lm["display_location"], 140) + if location == "" { + var parts []string + for _, k := range []string{"locality", "region", "country_code"} { + if p := wave3ResalePlain(lm[k], 60); p != "" { + parts = append(parts, p) + } + } + location = strings.Join(parts, ", ") + } + } + var cats []string + if catArr, ok := obj["categories"].([]any); ok { + for _, rc := range catArr { + if cm, okC := rc.(map[string]any); okC { + if cn := wave3ResaleFirstNonEmpty(wave3ResalePlain(cm["full_name"], 120), wave3ResalePlain(cm["name"], 80)); cn != "" { + cats = append(cats, cn) + } + } + } + } + inventory := wave3ResalePlain(obj["inventory"], 32) + stateStr := "" + if stm := wave3ResaleNestedMap(obj, "state"); stm != nil { + stateStr = wave3ResaleFirstNonEmpty(wave3ResalePlain(stm["description"], 64), wave3ResalePlain(stm["slug"], 64)) + } else { + stateStr = wave3ResalePlain(obj["state"], 64) + } + upc := wave3ResaleValidGTIN(wave3ResaleStringVal(obj["upc"])) + desc := wave3ResalePlain(obj["description"], 1800) + + var links []string + seen := make(map[string]bool) + var webURL string + if wm := wave3ResaleNestedMap(obj, "_links", "web"); wm != nil { + webURL = SanitizeSchemaHTTPSURL(wave3ResaleStringVal(wm["href"]), origURL) + wave3ResaleAddLink(&links, seen, webURL, origURL) + } + + var bullets []string + bullets = append(bullets, "- **Listing ID**: "+idStr) + if makeName != "" || modelName != "" { + bullets = append(bullets, "- **Make / Model**: "+strings.TrimSpace(makeName+" "+modelName)) + } + if finish != "" { + bullets = append(bullets, "- **Finish**: "+finish) + } + if year != "" { + bullets = append(bullets, "- **Year**: "+year) + } + if condition != "" { + bullets = append(bullets, "- **Condition**: "+condition) + } + if priceDisp != "" { + bullets = append(bullets, "- **Price**: "+priceDisp) + } + if shipDisp != "" { + bullets = append(bullets, "- **Shipping**: "+shipDisp) + } + if shopName != "" { + bullets = append(bullets, "- **Seller / Shop**: "+shopName) + } + if location != "" { + bullets = append(bullets, "- **Location**: "+location) + } + if len(cats) > 0 { + bullets = append(bullets, "- **Categories**: "+strings.Join(cats, " | ")) + } + if inventory != "" { + bullets = append(bullets, "- **Inventory**: "+inventory) + } + if stateStr != "" { + bullets = append(bullets, "- **State**: "+stateStr) + } + if upc != "" { + bullets = append(bullets, "- **GTIN / UPC**: "+upc) + } + if webURL != "" { + bullets = append(bullets, "- **Listing URL**: "+webURL) + } + + blocks := []string{"# " + title, strings.Join(bullets, "\n")} + if desc != "" { + blocks = append(blocks, "## Description\n\n"+desc) + } + rec := map[string]any{ + "id": idStr, + "title": title, + } + if makeName != "" { + rec["make"] = makeName + } + if modelName != "" { + rec["model"] = modelName + } + if priceNum != "" { + rec["price"] = priceNum + } + if priceCur != "" { + rec["currency"] = priceCur + } + if condition != "" { + rec["condition"] = condition + } + if upc != "" { + rec["gtin"] = upc + } + if webURL != "" { + rec["url"] = webURL + } + + return &DeclarativeFormattedDoc{ + Title: title, + Description: sliceRunesMax(desc, 260), + Author: shopName, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: []map[string]any{rec}, + }, true +} + +func wave3ResaleFormatReverbSearchJSON(obj map[string]any, origURL string) (*DeclarativeFormattedDoc, bool) { + listings, ok := obj["listings"].([]any) + if !ok || len(listings) == 0 { + return nil, false + } + var recs []map[string]any + var rows [][]string + var links []string + seen := make(map[string]bool) + + for _, rawItem := range listings { + if len(recs) >= wave3ResaleMaxRecords { + break + } + it, okIt := rawItem.(map[string]any) + if !okIt { + continue + } + title := wave3ResalePlain(it["title"], 200) + idStr := wave3ResalePlain(it["id"], 48) + if title == "" { + continue + } + cond := "" + if cm := wave3ResaleNestedMap(it, "condition"); cm != nil { + cond = wave3ResaleFirstNonEmpty(wave3ResalePlain(cm["display_name"], 64), wave3ResalePlain(cm["name"], 64)) + } + var priceDisp, priceNum, priceCur string + if pm := wave3ResaleNestedMap(it, "price"); pm != nil { + priceDisp, priceNum, priceCur = wave3ResaleFormatPrice(pm["amount"], wave3ResaleStringVal(pm["currency"])) + } + shopName := wave3ResalePlain(it["shop_name"], 100) + stateStr := "" + if stm := wave3ResaleNestedMap(it, "state"); stm != nil { + stateStr = wave3ResaleFirstNonEmpty(wave3ResalePlain(stm["description"], 48), wave3ResalePlain(stm["slug"], 48)) + } + var itemURL string + if wm := wave3ResaleNestedMap(it, "_links", "web"); wm != nil { + itemURL = SanitizeSchemaHTTPSURL(wave3ResaleStringVal(wm["href"]), origURL) + wave3ResaleAddLink(&links, seen, itemURL, origURL) + } + rows = append(rows, []string{ + escapeDeclMarkdownBrackets(title), + wave3ResaleFirstNonEmpty(cond, "-"), + wave3ResaleFirstNonEmpty(priceDisp, "-"), + wave3ResaleFirstNonEmpty(shopName, "-"), + wave3ResaleFirstNonEmpty(stateStr, "-"), + }) + rec := map[string]any{"title": title} + if idStr != "" { + rec["id"] = idStr + } + if priceNum != "" { + rec["price"] = priceNum + } + if priceCur != "" { + rec["currency"] = priceCur + } + if cond != "" { + rec["condition"] = cond + } + if shopName != "" { + rec["shop"] = shopName + } + if itemURL != "" { + rec["url"] = itemURL + } + recs = append(recs, rec) + } + if len(recs) == 0 { + return nil, false + } + + title := "Reverb Listings Search" + if q := wave3ResalePlain(wave3ResaleNestedMap(obj, "humanized_params")["query"], 100); q != "" { + title = "Reverb Search: " + q + } + var bullets []string + if totalF, okT := wave3ResaleFloatVal(obj["total"]); okT && totalF >= 0 { + bullets = append(bullets, fmt.Sprintf("- **Total Matches**: %d", int(totalF))) + } + if curP, okCP := wave3ResaleFloatVal(obj["current_page"]); okCP && curP > 0 { + if totP, okTP := wave3ResaleFloatVal(obj["total_pages"]); okTP && totP > 0 { + bullets = append(bullets, fmt.Sprintf("- **Page**: %d of %d", int(curP), int(totP))) + } + } + + blocks := []string{"# " + title} + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + blocks = append(blocks, formatDeclarativeGFMTable([]string{"Listing", "Condition", "Price", "Shop", "State"}, rows)) + doc := &DeclarativeFormattedDoc{ + Title: title, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: recs, + } + if totalF, okT := wave3ResaleFloatVal(obj["total"]); okT && totalF >= 0 { + doc.Total = wave3ResaleIntPtr(int(totalF)) + if int(totalF) > len(recs) { + doc.Truncated = wave3ResaleBoolPtr(true) + doc.Returned = wave3ResaleIntPtr(len(recs)) + } + } + return doc, true +} + +// ── #360 Pinkbike BuySell (`pinkbike_buysell_html`) ────────────────────────────────────────────── + +func wave3ResaleExtractPinkbikeHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + ldObjs := extractJSONLDObjectsDeclHTML(rawHTML, 20) + prod := wave3ResaleExtractJSONLDProduct(ldObjs) + hasGridMarker := strings.Contains(rawHTML, "bsitem") || strings.Contains(rawHTML, "buysell-item") || strings.Contains(rawHTML, "data-buysell-id") + hasDetailMarker := strings.Contains(rawHTML, "buysell-container") || strings.Contains(rawHTML, "buysell-details") || strings.Contains(rawHTML, "buysell-item-details") || strings.Contains(rawHTML, "buysell-price") + if prod == nil && !hasGridMarker && !hasDetailMarker { + return nil + } + var doc *HTMLDoc + ensureDoc := func() *HTMLDoc { + if doc == nil { + doc = ParseHTMLDoc(rawHTML, wave3ResaleStdHTMLMaxBytes) + } + return doc + } + title := wave3ResaleExtractTitle(nil, rawHTML) + if title == "" && (strings.Contains(rawHTML, " 0 && offers[0].Price != "" { + disp := offers[0].Price + if offers[0].Currency != "" { + disp += " " + offers[0].Currency + rec["currency"] = offers[0].Currency + } + bullets = append(bullets, "- **Price**: "+disp) + rec["price"] = offers[0].Price + } + if len(offers) > 0 && offers[0].Condition != "" { + bullets = append(bullets, "- **Condition**: "+offers[0].Condition) + rec["condition"] = offers[0].Condition + } + if len(offers) > 0 && offers[0].Seller != "" { + bullets = append(bullets, "- **Seller**: "+offers[0].Seller) + } + if strings.Contains(rawHTML, " 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + if desc != "" { + blocks = append(blocks, "## Description\n\n"+desc) + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: name, + Description: sliceRunesMax(desc, 260), + Markdown: strings.Join(blocks, "\n\n"), + Records: []map[string]any{rec}, + } + } + } + + if hasGridMarker { + d := ensureDoc() + if d == nil { + return nil + } + // Category / search listing grid (.bsitem) + items := d.Select(".bsitem, .buysell-item, [data-buysell-id]", wave3ResaleMaxRecords) + if len(items) > 0 { + var rows [][]string + var recs []map[string]any + var links []string + seen := make(map[string]bool) + for _, it := range items { + itTitle := SanitizeSchemaPlainField(wave3ResaleCleanText(it.Text("a.bsitem-title, .bsitem-title, h2, h3, a")), 180) + if itTitle == "" { + continue + } + itPrice := SanitizeSchemaPlainField(wave3ResaleCleanText(it.Text(".bsitem-price, .price")), 64) + itLoc := SanitizeSchemaPlainField(wave3ResaleCleanText(it.Text(".bsitem-location, .location")), 100) + href := SanitizeSchemaHTTPSURL(it.AttrOf("a", "href"), baseURL) + rows = append(rows, []string{ + escapeDeclMarkdownBrackets(itTitle), + wave3ResaleFirstNonEmpty(itPrice, "-"), + wave3ResaleFirstNonEmpty(itLoc, "-"), + }) + rec := map[string]any{"title": itTitle} + if itPrice != "" { + rec["price"] = itPrice + } + if itLoc != "" { + rec["location"] = itLoc + } + if href != "" { + rec["url"] = href + wave3ResaleAddLink(&links, seen, href, baseURL) + } + recs = append(recs, rec) + } + if len(recs) > 0 { + if title == "" { + title = "Pinkbike BuySell Listings" + } + md := "# " + title + "\n\n" + formatDeclarativeGFMTable([]string{"Listing", "Price", "Location"}, rows) + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Markdown: md, + Links: links, + Records: recs, + } + } + } + } + + // Single detail DOM fallback (#buysell-container / .buysell-details) + if hasDetailMarker && title != "" { + if d := ensureDoc(); d != nil && d.First("#buysell-container, .buysell-details, .buysell-item-details, .buysell-price") != nil { + price := SanitizeSchemaPlainField(wave3ResaleCleanText(d.Text(".buysell-price, .price")), 64) + desc := SanitizeSchemaPlainField(wave3ResaleCleanText(d.Text(".buysell-description, #buysell-description, .description")), 1600) + dlMap := d.DLMap("dl") + var bullets []string + if price != "" { + bullets = append(bullets, "- **Price**: "+price) + } + for k, v := range dlMap { + if cv := SanitizeSchemaPlainField(v, 120); cv != "" { + bullets = append(bullets, fmt.Sprintf("- **%s**: %s", SanitizeSchemaPlainField(k, 48), cv)) + } + } + if len(bullets) > 0 || desc != "" { + blocks := []string{"# " + title} + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + if desc != "" { + blocks = append(blocks, "## Description\n\n"+desc) + } + rec := map[string]any{"title": title} + if price != "" { + rec["price"] = price + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: sliceRunesMax(desc, 260), + Markdown: strings.Join(blocks, "\n\n"), + Records: []map[string]any{rec}, + } + } + } + } + return nil +} + +// ── #361 Used Bikes Shopify + Upway Hydrogen (`used_bikes_shopify_html`) ─────────────────────── + +func wave3ResaleExtractUsedBikesHTML(rawHTML, baseURL, urlLower, extractorID string) *DeclarativePostFetchResult { + // Reject .js / .json paths that fall through to an HTML homepage/404 shell. + if strings.HasSuffix(urlLower, ".js") || strings.HasSuffix(urlLower, ".json") || + strings.Contains(urlLower, ".js?") || strings.Contains(urlLower, ".json?") { + return nil + } + ldObjs := extractJSONLDObjectsDeclHTML(rawHTML, 24) + prod := wave3ResaleExtractJSONLDProduct(ldObjs) + recsList, listRows, listLinks := wave3ResaleExtractItemList(ldObjs, baseURL) + if prod == nil && len(recsList) == 0 { + return nil + } + + var doc *HTMLDoc + ensureDoc := func() *HTMLDoc { + if doc == nil { + slim := wave3ResaleSlimHTMLForDOM(rawHTML, 512*1024) + doc = ParseHTMLDoc(slim, 512*1024) + } + return doc + } + title := wave3ResaleExtractTitle(nil, rawHTML) + if title == "" && (strings.Contains(rawHTML, " 0 { + o := offers[0] + if o.Price != "" { + disp := o.Price + if o.Currency != "" { + disp += " " + o.Currency + rec["currency"] = o.Currency + } + bullets = append(bullets, "- **Price**: "+disp) + rec["price"] = o.Price + } + if o.Condition != "" { + bullets = append(bullets, "- **Condition**: "+o.Condition) + rec["condition"] = o.Condition + } + if o.Availability != "" { + bullets = append(bullets, "- **Availability**: "+o.Availability) + } + } + if sku != "" { + bullets = append(bullets, "- **SKU**: "+sku) + rec["sku"] = sku + } + if gtin != "" { + bullets = append(bullets, "- **GTIN**: "+gtin) + rec["gtin"] = gtin + } + + // Collect bike/e-bike spec pairs from DOM (
or ) + var specRows [][]string + if strings.Contains(rawHTML, "= 20 { + break + } + } + } + } + } + + blocks := []string{"# " + name} + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + if len(specRows) > 0 { + blocks = append(blocks, "## Specifications\n\n"+formatDeclarativeGFMTable([]string{"Spec", "Value"}, specRows)) + } + if desc != "" { + blocks = append(blocks, "## Description\n\n"+desc) + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: name, + Description: sliceRunesMax(desc, 260), + Author: brand, + Markdown: strings.Join(blocks, "\n\n"), + Records: []map[string]any{rec}, + } + } + + if len(recsList) > 0 { + if title == "" { + title = "Certified Pre-Owned Bikes" + } + md := "# " + title + "\n\n" + formatDeclarativeGFMTable([]string{"Bike", "Price", "Condition"}, listRows) + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Markdown: md, + Links: listLinks, + Records: recsList, + } + } + return nil +} + +// ── #362 Bicycle Blue Book (`bicycle_blue_book_html`) ──────────────────────────────────────────── + +func wave3ResaleExtractBicycleBlueBookHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + ldObjs := extractJSONLDObjectsDeclHTML(rawHTML, 24) + doc := ParseHTMLDoc(rawHTML, wave3ResaleStdHTMLMaxBytes) + title := wave3ResaleExtractTitle(doc, rawHTML) + if title == "" { + return nil + } + desc := wave3ResaleExtractMetaDesc(rawHTML) + + plainBody := "" + if doc != nil { + plainBody = wave3ResaleCleanText(doc.Text("main, body")) + } + msrp := "" + if m := wave3ResaleRxBBBMSRP.FindStringSubmatch(plainBody); len(m) >= 2 { + msrp = "$" + strings.ReplaceAll(m[1], ",", "") + } + usedRange := "" + if m := wave3ResaleRxBBBPriceRange.FindStringSubmatch(plainBody); len(m) >= 3 { + usedRange = "$" + strings.ReplaceAll(m[1], ",", "") + " - $" + strings.ReplaceAll(m[2], ",", "") + } + tradeIn := "" + if m := wave3ResaleRxBBBTradeIn.FindStringSubmatch(plainBody); len(m) >= 2 { + tradeIn = "$" + strings.ReplaceAll(m[1], ",", "") + } + trendPct := "" + if m := wave3ResaleRxBBBTrend.FindStringSubmatch(plainBody); len(m) >= 2 { + trendPct = strings.ReplaceAll(strings.TrimSpace(m[1]), " ", "") + "%" + } + + recsList, listRows, listLinks := wave3ResaleExtractItemList(ldObjs, baseURL) + + // Extract DOM model links if ItemList JSON-LD was absent + if len(recsList) == 0 && doc != nil { + seen := make(map[string]bool) + for _, a := range doc.Select("a[href*='/value-guide/']", wave3ResaleMaxRecords) { + href := SanitizeSchemaHTTPSURL(a.AttrOrEmpty("href"), baseURL) + txt := SanitizeSchemaPlainField(wave3ResaleCleanText(a.Text()), 140) + if href == "" || txt == "" || len(txt) < 3 { + continue + } + if seen[href] { + continue + } + seen[href] = true + listLinks = append(listLinks, href) + listRows = append(listRows, []string{escapeDeclMarkdownBrackets(txt), "-", "-"}) + recsList = append(recsList, map[string]any{"title": txt, "url": href}) + } + } + + if msrp == "" && usedRange == "" && tradeIn == "" && trendPct == "" && len(recsList) == 0 { + return nil + } + + var bullets []string + rec := map[string]any{"title": title} + if msrp != "" { + bullets = append(bullets, "- **Original MSRP**: "+msrp) + rec["msrp"] = msrp + } + if usedRange != "" { + bullets = append(bullets, "- **Used Estimate Range**: "+usedRange) + rec["usedEstimateRange"] = usedRange + } + if tradeIn != "" { + bullets = append(bullets, "- **Trade-In Value**: "+tradeIn) + rec["tradeInValue"] = tradeIn + } + if trendPct != "" { + bullets = append(bullets, "- **12-Month Projected Trend**: "+trendPct) + rec["projectedTrend12Mo"] = trendPct + } + + blocks := []string{"# " + title} + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + var outRecs []map[string]any + if len(recsList) > 0 { + blocks = append(blocks, "## Models\n\n"+formatDeclarativeGFMTable([]string{"Model", "Price", "Condition"}, listRows)) + outRecs = recsList + } else { + outRecs = []map[string]any{rec} + } + if desc != "" { + blocks = append(blocks, "## Overview\n\n"+desc) + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: sliceRunesMax(desc, 260), + Markdown: strings.Join(blocks, "\n\n"), + Links: listLinks, + Records: outRecs, + } +} + +// ── #363 Back Market & Swappa (`back_market_swappa_html`) ──────────────────────────────────────── + +func wave3ResaleExtractBackMarketSwappaHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + ldObjs := extractJSONLDObjectsDeclHTML(rawHTML, 24) + prod := wave3ResaleExtractJSONLDProduct(ldObjs) + recsList, listRows, listLinks := wave3ResaleExtractItemList(ldObjs, baseURL) + if prod == nil && len(recsList) == 0 { + return nil + } + doc := ParseHTMLDoc(rawHTML, wave3ResaleStdHTMLMaxBytes) + title := wave3ResaleExtractTitle(doc, rawHTML) + + if prod != nil { + name := wave3ResaleFirstNonEmpty(wave3ResalePlain(prod["name"], 240), title) + if name == "" { + return nil + } + brand := wave3ResaleExtractBrandName(prod["brand"]) + sku := wave3ResalePlain(prod["sku"], 80) + gtin := wave3ResaleValidGTIN(wave3ResaleFirstNonEmpty( + wave3ResaleStringVal(prod["gtin13"]), + wave3ResaleStringVal(prod["gtin12"]), + wave3ResaleStringVal(prod["gtin"]), + )) + desc := wave3ResaleFirstNonEmpty(wave3ResalePlain(prod["description"], 1600), wave3ResaleExtractMetaDesc(rawHTML)) + offers := wave3ResaleParseOffers(prod["offers"], baseURL) + + var bullets []string + rec := map[string]any{"title": name} + if brand != "" { + bullets = append(bullets, "- **Brand**: "+brand) + rec["brand"] = brand + } + if len(offers) > 0 { + o := offers[0] + if o.LowPrice != "" && o.HighPrice != "" { + disp := o.LowPrice + " - " + o.HighPrice + if o.Currency != "" { + disp += " " + o.Currency + rec["currency"] = o.Currency + } + bullets = append(bullets, "- **Price Range**: "+disp) + rec["lowPrice"] = o.LowPrice + rec["highPrice"] = o.HighPrice + } else if o.Price != "" { + disp := o.Price + if o.Currency != "" { + disp += " " + o.Currency + rec["currency"] = o.Currency + } + bullets = append(bullets, "- **Price**: "+disp) + rec["price"] = o.Price + } + if o.OfferCount != "" { + bullets = append(bullets, "- **Offer Count**: "+o.OfferCount) + rec["offerCount"] = o.OfferCount + } + if o.Condition != "" { + bullets = append(bullets, "- **Condition**: "+o.Condition) + rec["condition"] = o.Condition + } + if o.Availability != "" { + bullets = append(bullets, "- **Availability**: "+o.Availability) + } + } + if ar := wave3ResaleNestedMap(prod, "aggregateRating"); ar != nil { + rv := wave3ResalePlain(ar["ratingValue"], 16) + rc := wave3ResaleFirstNonEmpty(wave3ResalePlain(ar["reviewCount"], 16), wave3ResalePlain(ar["ratingCount"], 16)) + if rv != "" { + if rc != "" { + bullets = append(bullets, fmt.Sprintf("- **Rating**: %s (%s reviews)", rv, rc)) + } else { + bullets = append(bullets, "- **Rating**: "+rv) + } + } + } + if sku != "" { + bullets = append(bullets, "- **SKU**: "+sku) + } + if gtin != "" { + bullets = append(bullets, "- **GTIN**: "+gtin) + rec["gtin"] = gtin + } + + var specRows [][]string + if doc != nil { + for _, r := range doc.TableRows("table") { + if len(r) == 2 { + k := SanitizeSchemaPlainField(r[0], 64) + v := SanitizeSchemaPlainField(r[1], 140) + if k != "" && v != "" { + specRows = append(specRows, []string{k, v}) + } + } + if len(specRows) >= 16 { + break + } + } + if len(specRows) == 0 { + for k, v := range doc.DLMap("dl") { + if cv := SanitizeSchemaPlainField(v, 140); cv != "" { + specRows = append(specRows, []string{SanitizeSchemaPlainField(k, 64), cv}) + } + if len(specRows) >= 16 { + break + } + } + } + } + + blocks := []string{"# " + name} + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + if len(specRows) > 0 { + blocks = append(blocks, "## Specifications\n\n"+formatDeclarativeGFMTable([]string{"Spec", "Value"}, specRows)) + } + if desc != "" { + blocks = append(blocks, "## Description\n\n"+desc) + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: name, + Description: sliceRunesMax(desc, 260), + Author: brand, + Markdown: strings.Join(blocks, "\n\n"), + Records: []map[string]any{rec}, + } + } + + if title == "" { + title = "Refurbished Electronics Listings" + } + md := "# " + title + "\n\n" + formatDeclarativeGFMTable([]string{"Product", "Price", "Condition"}, listRows) + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Markdown: md, + Links: listLinks, + Records: recsList, + } +} + +// ── #364 Peer Resale Fashion (`peer_resale_fashion_html`) ───────────────────────────────────────── + +func wave3ResaleExtractPeerResaleHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + ldObjs := extractJSONLDObjectsDeclHTML(rawHTML, 24) + prod := wave3ResaleExtractJSONLDProduct(ldObjs) + recsList, listRows, listLinks := wave3ResaleExtractItemList(ldObjs, baseURL) + + // Extract hydration state (Poshmark __INITIAL_STATE__ or Next.js __NEXT_DATA__) + var hydTitle, hydBrand, hydSize, hydPrice, hydCur, hydCond, hydSeller, hydDesc string + if initState := wave3ResaleExtractInitStateObj(rawHTML); initState != nil { + // Poshmark listing structure: $_listing.listing or listing + var lst map[string]any + if dl := wave3ResaleNestedMap(initState, "$_listing", "listing"); dl != nil { + lst = dl + } else if dl2 := wave3ResaleNestedMap(initState, "listing"); dl2 != nil { + lst = dl2 + } + if lst != nil { + hydTitle = wave3ResalePlain(lst["title"], 220) + hydBrand = wave3ResalePlain(lst["brand"], 100) + hydSize = wave3ResalePlain(lst["size"], 64) + hydCond = wave3ResalePlain(lst["condition"], 64) + hydDesc = wave3ResalePlain(lst["description"], 1600) + hydSeller = wave3ResalePlain(lst["creator_username"], 80) + if pm := wave3ResaleNestedMap(lst, "price_amount"); pm != nil { + _, hydPrice, hydCur = wave3ResaleFormatPrice(pm["val"], wave3ResaleStringVal(pm["currency_code"])) + } + } + } + if hydTitle == "" { + if nd := wave3ResaleExtractNextDataObj(rawHTML); nd != nil { + if pp := wave3ResaleNestedMap(nd, "props", "pageProps"); pp != nil { + for _, k := range []string{"listing", "product", "item"} { + if m := wave3ResaleNestedMap(pp, k); m != nil { + hydTitle = wave3ResaleFirstNonEmpty(wave3ResalePlain(m["title"], 220), wave3ResalePlain(m["name"], 220)) + hydBrand = wave3ResaleExtractBrandName(m["brand"]) + hydSize = wave3ResalePlain(m["size"], 64) + hydCond = wave3ResalePlain(m["condition"], 64) + hydDesc = wave3ResalePlain(m["description"], 1600) + _, hydPrice, hydCur = wave3ResaleFormatPrice(m["price"], wave3ResaleFirstNonEmpty(wave3ResaleStringVal(m["currency"]), "USD")) + if hydTitle != "" { + break + } + } + } + } + } + } + + var doc *HTMLDoc + ensureDoc := func() *HTMLDoc { + if doc == nil { + slim := wave3ResaleSlimHTMLForDOM(rawHTML, 512*1024) + doc = ParseHTMLDoc(slim, 512*1024) + } + return doc + } + title := wave3ResaleExtractTitle(nil, rawHTML) + if title == "" && (strings.Contains(rawHTML, " 0 { + price = wave3ResaleFirstNonEmpty(offers[0].Price, offers[0].LowPrice) + cur = offers[0].Currency + cond = offers[0].Condition + seller = offers[0].Seller + } + } + name = wave3ResaleFirstNonEmpty(name, hydTitle, title) + if name == "" { + return nil + } + brand = wave3ResaleFirstNonEmpty(brand, hydBrand) + price = wave3ResaleFirstNonEmpty(price, hydPrice) + cur = wave3ResaleFirstNonEmpty(cur, hydCur) + cond = wave3ResaleFirstNonEmpty(cond, hydCond) + seller = wave3ResaleFirstNonEmpty(seller, hydSeller) + desc = wave3ResaleFirstNonEmpty(desc, hydDesc, wave3ResaleExtractMetaDesc(rawHTML)) + + var bullets []string + rec := map[string]any{"title": name} + if brand != "" { + bullets = append(bullets, "- **Brand**: "+brand) + rec["brand"] = brand + } + if hydSize != "" { + bullets = append(bullets, "- **Size**: "+hydSize) + rec["size"] = hydSize + } + if price != "" { + disp := price + if cur != "" { + disp += " " + cur + rec["currency"] = cur + } + bullets = append(bullets, "- **Price**: "+disp) + rec["price"] = price + } + if cond != "" { + bullets = append(bullets, "- **Condition**: "+cond) + rec["condition"] = cond + } + if seller != "" { + bullets = append(bullets, "- **Seller**: "+seller) + } + if sku != "" { + bullets = append(bullets, "- **SKU**: "+sku) + } + blocks := []string{"# " + name} + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + if desc != "" { + blocks = append(blocks, "## Description\n\n"+desc) + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: name, + Description: sliceRunesMax(desc, 260), + Author: seller, + Markdown: strings.Join(blocks, "\n\n"), + Records: []map[string]any{rec}, + } + } + + if len(recsList) == 0 && strings.Contains(strings.ToLower(baseURL), "poshmark.com") { + if d := ensureDoc(); d != nil { + var rows [][]string + var recs []map[string]any + var links []string + seen := make(map[string]bool) + for _, card := range d.Select(".tile, [data-et-name='listing'], .card--small", wave3ResaleMaxRecords) { + href := SanitizeSchemaHTTPSURL(card.AttrOf("a[href*='/listing/'], a[href]", "href"), baseURL) + ct := SanitizeSchemaPlainField(wave3ResaleCleanText(card.Text(".tile__title, .title__condition__container a, a[href*='/listing/']")), 200) + if ct == "" && href != "" { + ct = wave3ResaleTitleFromURLSlug(href) + } + if ct == "" { + continue + } + cp := SanitizeSchemaPlainField(wave3ResaleCleanText(card.Text(".p--t--1, .fw--bold, .price")), 48) + rows = append(rows, []string{escapeDeclMarkdownBrackets(ct), wave3ResaleFirstNonEmpty(cp, "-"), "-"}) + rec := map[string]any{"title": ct} + if cp != "" { + rec["price"] = cp + } + if href != "" { + rec["url"] = href + wave3ResaleAddLink(&links, seen, href, baseURL) + } + recs = append(recs, rec) + } + if len(recs) > 0 { + recsList, listRows, listLinks = recs, rows, links + } + } + } + + if len(recsList) > 0 { + if title == "" { + title = "Peer Resale Fashion Listings" + } + md := "# " + title + "\n\n" + formatDeclarativeGFMTable([]string{"Item", "Price", "Condition"}, listRows) + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Markdown: md, + Links: listLinks, + Records: recsList, + } + } + + // DOM fallback for listing detail when neither JSON-LD nor hydration was embedded + if title != "" && (strings.Contains(rawHTML, "listing-price") || strings.Contains(rawHTML, "listing__price") || strings.Contains(rawHTML, "itemprop") || strings.Contains(rawHTML, "price")) { + d := ensureDoc() + if d != nil { + domPrice := SanitizeSchemaPlainField(wave3ResaleCleanText(d.Text("[data-testid='listing-price'], .listing__price, [itemprop='price'], .price")), 64) + domDesc := SanitizeSchemaPlainField(wave3ResaleCleanText(d.Text("[data-testid='listing-description'], .listing__description, [itemprop='description']")), 1600) + if domPrice != "" && domDesc != "" { + md := fmt.Sprintf("# %s\n\n- **Price**: %s\n\n## Description\n\n%s", title, domPrice, domDesc) + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: sliceRunesMax(domDesc, 260), + Markdown: md, + Records: []map[string]any{{"title": title, "price": domPrice}}, + } + } + } + } + return nil +} + +// ── #365 Local Classifieds Marketplaces (`local_classifieds_html`) ─────────────────────────────── + +func wave3ResaleExtractLocalClassifiedsHTML(rawHTML, baseURL, urlLower, extractorID string) *DeclarativePostFetchResult { + ldObjs := extractJSONLDObjectsDeclHTML(rawHTML, 30) + prod := wave3ResaleExtractJSONLDProduct(ldObjs) + recsList, listRows, listLinks := wave3ResaleExtractItemList(ldObjs, baseURL) + + var doc *HTMLDoc + ensureDoc := func() *HTMLDoc { + if doc == nil { + slim := wave3ResaleSlimHTMLForDOM(rawHTML, 512*1024) + doc = ParseHTMLDoc(slim, 512*1024) + } + return doc + } + title := wave3ResaleExtractTitle(nil, rawHTML) + if title == "" && (strings.Contains(rawHTML, " 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + if lDesc != "" { + blocks = append(blocks, "## Description\n\n"+lDesc) + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: lTitle, + Description: sliceRunesMax(lDesc, 260), + Markdown: strings.Join(blocks, "\n\n"), + Records: []map[string]any{rec}, + } + } + } + } + } + } + + hasCLDetail := strings.Contains(rawHTML, "postingbody") || strings.Contains(rawHTML, "titletextonly") + hasCLGrid := strings.Contains(rawHTML, "cl-search-result") || strings.Contains(rawHTML, "result-row") + if prod == nil && len(recsList) == 0 && !hasCLDetail && !hasCLGrid { + return nil + } + + // Craigslist single posting DOM + JSON-LD (#titletextonly, .price, #postingbody, .attrgroup) + var clTitle, clPrice, clBody, clLoc string + var clAttrs []string + if hasCLDetail { + if d := ensureDoc(); d != nil { + clTitle = SanitizeSchemaPlainField(wave3ResaleCleanText(d.Text("#titletextonly")), 220) + clPrice = SanitizeSchemaPlainField(wave3ResaleCleanText(d.Text(".price")), 64) + clBody = SanitizeSchemaPlainField(wave3ResaleCleanText(d.Text("#postingbody")), 1800) + clBody = strings.TrimSpace(strings.TrimPrefix(clBody, "QR Code Link to This Post")) + for _, ag := range d.Select(".attrgroup span", 24) { + if txt := SanitizeSchemaPlainField(wave3ResaleCleanText(ag.Text()), 120); txt != "" { + clAttrs = append(clAttrs, txt) + } + } + } + } + + // Extract location from Place / PostalAddress JSON-LD + for _, obj := range ldObjs { + if wave3ResaleHasSchemaType(obj, "Place", "PostalAddress") { + clLoc = wave3ResaleFirstNonEmpty( + wave3ResalePlain(obj["name"], 120), + wave3ResalePlain(obj["addressLocality"], 80), + ) + if clLoc != "" { + break + } + } + if place := wave3ResaleNestedMap(obj, "availableAtOrFrom"); place != nil && clLoc == "" { + clLoc = wave3ResalePlain(place["name"], 120) + if clLoc == "" { + if addr := wave3ResaleNestedMap(place, "address"); addr != nil { + clLoc = wave3ResaleFirstNonEmpty(wave3ResalePlain(addr["addressLocality"], 80), wave3ResalePlain(addr["addressRegion"], 40)) + } + } + } + } + + if prod != nil || clBody != "" { + var name, desc, price, cur, cond string + if prod != nil { + name = wave3ResalePlain(prod["name"], 240) + desc = wave3ResalePlain(prod["description"], 1800) + if offers := wave3ResaleParseOffers(prod["offers"], baseURL); len(offers) > 0 { + price = wave3ResaleFirstNonEmpty(offers[0].Price, offers[0].LowPrice) + cur = offers[0].Currency + cond = offers[0].Condition + if clLoc == "" { + if place := wave3ResaleNestedMap(prod, "offers", "availableAtOrFrom"); place != nil { + clLoc = wave3ResalePlain(place["name"], 120) + } + } + } + } + name = wave3ResaleFirstNonEmpty(clTitle, name, title) + if name == "" { + return nil + } + desc = wave3ResaleFirstNonEmpty(clBody, desc, wave3ResaleExtractMetaDesc(rawHTML)) + if price == "" && clPrice != "" { + _, pNum, pCur := wave3ResaleFormatPrice(clPrice, "USD") + if pNum != "" { + price = pNum + cur = pCur + } + } + var bullets []string + rec := map[string]any{"title": name} + if price != "" { + disp := price + if cur != "" { + disp += " " + cur + rec["currency"] = cur + } + bullets = append(bullets, "- **Price**: "+disp) + rec["price"] = price + } else if clPrice != "" { + bullets = append(bullets, "- **Price**: "+clPrice) + rec["price"] = clPrice + } + if cond != "" { + bullets = append(bullets, "- **Condition**: "+cond) + rec["condition"] = cond + } + if clLoc != "" { + bullets = append(bullets, "- **Location**: "+clLoc) + rec["location"] = clLoc + } + if len(clAttrs) > 0 { + bullets = append(bullets, "- **Attributes**: "+strings.Join(clAttrs, "; ")) + } + blocks := []string{"# " + name} + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + if desc != "" { + blocks = append(blocks, "## Description\n\n"+desc) + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: name, + Description: sliceRunesMax(desc, 260), + Markdown: strings.Join(blocks, "\n\n"), + Records: []map[string]any{rec}, + } + } + + if len(recsList) > 0 { + if title == "" { + title = "Local Classifieds Listings" + } + md := "# " + title + "\n\n" + formatDeclarativeGFMTable([]string{"Listing", "Price", "Condition"}, listRows) + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Markdown: md, + Links: listLinks, + Records: recsList, + } + } + + // Craigslist DOM search results fallback + if hasCLGrid { + if d := ensureDoc(); d != nil { + clCards := d.Select(".cl-search-result, .result-row", wave3ResaleMaxRecords) + if len(clCards) > 0 { + var rows [][]string + var recs []map[string]any + var links []string + seen := make(map[string]bool) + for _, card := range clCards { + ct := SanitizeSchemaPlainField(wave3ResaleCleanText(card.Text(".titlestring, .result-title, a.posting-title, a")), 180) + if ct == "" { + continue + } + cp := SanitizeSchemaPlainField(wave3ResaleCleanText(card.Text(".priceinfo, .result-price")), 48) + cl := SanitizeSchemaPlainField(wave3ResaleCleanText(card.Text(".meta, .result-hood")), 80) + href := SanitizeSchemaHTTPSURL(card.AttrOf("a", "href"), baseURL) + rows = append(rows, []string{ + escapeDeclMarkdownBrackets(ct), + wave3ResaleFirstNonEmpty(cp, "-"), + wave3ResaleFirstNonEmpty(cl, "-"), + }) + rec := map[string]any{"title": ct} + if cp != "" { + rec["price"] = cp + } + if cl != "" { + rec["location"] = cl + } + if href != "" { + rec["url"] = href + wave3ResaleAddLink(&links, seen, href, baseURL) + } + recs = append(recs, rec) + } + if len(recs) > 0 { + if title == "" { + title = "Craigslist Search Results" + } + md := "# " + title + "\n\n" + formatDeclarativeGFMTable([]string{"Listing", "Price", "Location"}, rows) + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Markdown: md, + Links: links, + Records: recs, + } + } + } + } + } + return nil +} + +// ── #366 Creator Digital Stores (`creator_digital_stores_html`) ────────────────────────────────── + +func wave3ResaleExtractInertiaPageProps(rawHTML string) map[string]any { + pos := 0 + for pos < len(rawHTML) { + rel := indexFoldASCIIExtract(rawHTML[pos:], "data-page=") + if rel < 0 { + return nil + } + idx := pos + rel + len("data-page=") + for idx < len(rawHTML) && (rawHTML[idx] == ' ' || rawHTML[idx] == '\t') { + idx++ + } + if idx >= len(rawHTML) { + return nil + } + quote := rawHTML[idx] + if quote != '"' && quote != '\'' { + pos = idx + 1 + continue + } + valStart := idx + 1 + maxEnd := valStart + 512*1024 + if maxEnd > len(rawHTML) { + maxEnd = len(rawHTML) + } + valEnd := -1 + for i := valStart; i < maxEnd; i++ { + if rawHTML[i] == quote { + valEnd = i + break + } + } + if valEnd < 0 { + return nil + } + rawVal := strings.TrimSpace(rawHTML[valStart:valEnd]) + var jsonStr string + if strings.HasPrefix(rawVal, "{") || strings.HasPrefix(rawVal, """) || strings.HasPrefix(rawVal, "&#") { + jsonStr = strings.TrimSpace(stdhtml.UnescapeString(rawVal)) + } else { + // Inertia v2 + gt := strings.IndexByte(rawHTML[valEnd:], '>') + if gt >= 0 { + bodyStart := valEnd + gt + 1 + if rawJSON, _, ok := ExtractBalancedJSONAt(rawHTML, bodyStart, 512*1024); ok { + jsonStr = rawJSON + } + } + } + if strings.HasPrefix(jsonStr, "{") { + if parsed, ok := decodeJSONWithNumbers([]byte(jsonStr)); ok { + if obj, okObj := parsed.(map[string]any); okObj { + if props, okP := obj["props"].(map[string]any); okP { + return props + } + return obj + } + } + } + pos = valEnd + 1 + } + return nil +} + +func wave3ResaleInertiaProductFields(pm map[string]any, baseURL string) (name, creator, price, cur, itemURL, desc string, ok bool) { + if pm == nil { + return + } + name = wave3ResaleFirstNonEmpty(wave3ResalePlain(pm["name"], 200), wave3ResalePlain(pm["title"], 200)) + if name == "" { + return + } + creator = wave3ResaleFirstNonEmpty( + wave3ResalePlain(wave3ResaleNestedMap(pm, "seller")["name"], 100), + wave3ResalePlain(wave3ResaleNestedMap(pm, "creator")["name"], 100), + wave3ResalePlain(pm["seller_name"], 100), + wave3ResalePlain(pm["creator_name"], 100), + ) + if s := wave3ResaleNestedMap(pm, "seller"); s != nil && creator == "" { + creator = wave3ResalePlain(s["username"], 100) + } + curHint := wave3ResaleFirstNonEmpty(wave3ResaleStringVal(pm["currency_code"]), wave3ResaleStringVal(pm["currency"]), "USD") + if cents, okC := wave3ResaleFloatVal(pm["price_cents"]); okC && cents >= 0 { + _, price, cur = wave3ResaleFormatPrice(cents/100.0, curHint) + } + if price == "" { + for _, pk := range []string{"price_formatted", "formatted_price", "price"} { + if pv := pm[pk]; pv != nil { + _, price, cur = wave3ResaleFormatPrice(pv, curHint) + if price != "" { + break + } + } + } + } + itemURL = wave3ResaleFirstNonEmpty( + SanitizeSchemaHTTPSURL(wave3ResaleStringVal(pm["url"]), baseURL), + SanitizeSchemaHTTPSURL(wave3ResaleStringVal(pm["short_url"]), baseURL), + ) + if itemURL == "" { + if perm := wave3ResalePlain(pm["permalink"], 120); perm != "" && strings.Contains(strings.ToLower(baseURL), "gumroad.com") { + itemURL = SanitizeSchemaHTTPSURL("https://gumroad.com/l/"+strings.TrimPrefix(perm, "/"), baseURL) + } + } + desc = wave3ResaleFirstNonEmpty(wave3ResalePlain(pm["description"], 600), wave3ResalePlain(pm["summary"], 600)) + ok = price != "" || itemURL != "" || creator != "" + return +} + +func wave3ResaleExtractInertiaCreatorProducts(rawHTML, baseURL string) ([]map[string]any, [][]string, []string) { + if indexFoldASCIIExtract(rawHTML, "data-page=") < 0 { + return nil, nil, nil + } + props := wave3ResaleExtractInertiaPageProps(rawHTML) + if props == nil { + return nil, nil, nil + } + var recs []map[string]any + var rows [][]string + var links []string + seenURL := make(map[string]bool) + seenTitle := make(map[string]bool) + + pushProd := func(pm map[string]any) { + if len(recs) >= wave3ResaleMaxRecords { + return + } + name, creator, price, cur, itemURL, desc, ok := wave3ResaleInertiaProductFields(pm, baseURL) + if !ok { + return + } + dedupKey := itemURL + if dedupKey == "" { + dedupKey = strings.ToLower(name) + } + if seenTitle[dedupKey] { + return + } + seenTitle[dedupKey] = true + priceCell := "-" + if price != "" { + priceCell = price + if cur != "" { + priceCell += " " + cur + } + } + creatorCell := wave3ResaleFirstNonEmpty(creator, "-") + rows = append(rows, []string{escapeDeclMarkdownBrackets(name), priceCell, escapeDeclMarkdownBrackets(creatorCell)}) + rec := map[string]any{"title": name} + if creator != "" { + rec["creator"] = creator + } + if price != "" { + rec["price"] = price + } + if cur != "" { + rec["currency"] = cur + } + if desc != "" { + rec["description"] = desc + } + if itemURL != "" { + rec["url"] = itemURL + wave3ResaleAddLink(&links, seenURL, itemURL, baseURL) + } + recs = append(recs, rec) + } + + var walk func(v any, depth int) + walk = func(v any, depth int) { + if depth > 4 || len(recs) >= wave3ResaleMaxRecords { + return + } + switch tv := v.(type) { + case map[string]any: + for _, k := range []string{"products", "curated_products", "recommended_products", "featured_products", "search_results", "sections", "items", "results", "product"} { + if sub, exists := tv[k]; exists { + walk(sub, depth+1) + } + } + if _, hasName := tv["name"]; hasName { + pushProd(tv) + } else if _, hasTitle := tv["title"]; hasTitle { + pushProd(tv) + } + case []any: + for _, el := range tv { + if len(recs) >= wave3ResaleMaxRecords { + break + } + if em, ok := el.(map[string]any); ok { + pushProd(em) + if len(recs) < wave3ResaleMaxRecords { + if subProds, okSP := em["products"].([]any); okSP { + walk(subProds, depth+1) + } + } + } + } + } + } + walk(props, 0) + return recs, rows, links +} + +func wave3ResaleExtractCreatorStoresHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + ldObjs := extractJSONLDObjectsDeclHTML(rawHTML, 24) + prod := wave3ResaleExtractJSONLDProduct(ldObjs) + recsList, listRows, listLinks := wave3ResaleExtractItemList(ldObjs, baseURL) + var inertiaRecs []map[string]any + var inertiaRows [][]string + var inertiaLinks []string + if prod == nil && len(recsList) == 0 { + inertiaRecs, inertiaRows, inertiaLinks = wave3ResaleExtractInertiaCreatorProducts(rawHTML, baseURL) + } + slim := wave3ResaleSlimHTMLForDOM(rawHTML, 512*1024) + doc := ParseHTMLDoc(slim, 512*1024) + title := wave3ResaleExtractTitle(doc, rawHTML) + + ogPrice := wave3ResaleFirstNonEmpty( + wave3ResaleExtractMetaBounded(rawHTML, "product:price:amount"), + wave3ResaleExtractMetaBounded(rawHTML, "og:price:amount"), + ) + ogCur := wave3ResaleFirstNonEmpty( + wave3ResaleExtractMetaBounded(rawHTML, "product:price:currency"), + wave3ResaleExtractMetaBounded(rawHTML, "og:price:currency"), + ) + + if prod != nil { + name := wave3ResaleFirstNonEmpty(wave3ResalePlain(prod["name"], 240), title) + if name == "" { + return nil + } + brand := wave3ResaleExtractBrandName(prod["brand"]) + sku := wave3ResalePlain(prod["sku"], 80) + desc := wave3ResaleFirstNonEmpty(wave3ResalePlain(prod["description"], 1600), wave3ResaleExtractMetaDesc(rawHTML)) + offers := wave3ResaleParseOffers(prod["offers"], baseURL) + + var bullets []string + rec := map[string]any{"title": name} + if brand != "" { + bullets = append(bullets, "- **Creator / Brand**: "+brand) + rec["creator"] = brand + } + var price, cur string + if len(offers) > 0 { + price = wave3ResaleFirstNonEmpty(offers[0].Price, offers[0].LowPrice) + cur = offers[0].Currency + } + if price == "" && ogPrice != "" { + _, price, cur = wave3ResaleFormatPrice(ogPrice, wave3ResaleFirstNonEmpty(ogCur, "USD")) + } + if price != "" { + disp := price + if cur != "" { + disp += " " + cur + rec["currency"] = cur + } + bullets = append(bullets, "- **Price**: "+disp) + rec["price"] = price + } + if ar := wave3ResaleNestedMap(prod, "aggregateRating"); ar != nil { + rv := wave3ResalePlain(ar["ratingValue"], 16) + rc := wave3ResaleFirstNonEmpty(wave3ResalePlain(ar["ratingCount"], 16), wave3ResalePlain(ar["reviewCount"], 16)) + if rv != "" { + if rc != "" { + bullets = append(bullets, fmt.Sprintf("- **Rating**: %s (%s ratings)", rv, rc)) + rec["ratingCount"] = rc + } else { + bullets = append(bullets, "- **Rating**: "+rv) + } + rec["ratingValue"] = rv + } + } + if sku != "" { + bullets = append(bullets, "- **SKU**: "+sku) + rec["sku"] = sku + } + blocks := []string{"# " + name} + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + if desc != "" { + blocks = append(blocks, "## Description\n\n"+desc) + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: name, + Description: sliceRunesMax(desc, 260), + Author: brand, + Markdown: strings.Join(blocks, "\n\n"), + Records: []map[string]any{rec}, + } + } + + if len(recsList) > 0 { + if title == "" { + title = "Creator Digital Products" + } + md := "# " + title + "\n\n" + formatDeclarativeGFMTable([]string{"Product", "Price", "Condition"}, listRows) + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Markdown: md, + Links: listLinks, + Records: recsList, + } + } + + if len(inertiaRecs) > 0 { + if title == "" { + title = "Creator Digital Products" + } + md := "# " + title + "\n\n" + formatDeclarativeGFMTable([]string{"Product", "Price", "Creator"}, inertiaRows) + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Markdown: md, + Links: inertiaLinks, + Records: inertiaRecs, + } + } + + // OpenGraph + DOM fallback + if title != "" && (ogPrice != "" || (doc != nil && doc.First("[data-testid='product-price'], .price, [itemprop='price']") != nil)) { + domPrice := ogPrice + domCur := wave3ResaleValidCurrency(ogCur) + if domPrice == "" && doc != nil { + rawP := wave3ResaleCleanText(doc.Text("[data-testid='product-price'], .price, [itemprop='price']")) + _, domPrice, domCur = wave3ResaleFormatPrice(rawP, "USD") + } + desc := wave3ResaleExtractMetaDesc(rawHTML) + if desc == "" && doc != nil { + desc = SanitizeSchemaPlainField(wave3ResaleCleanText(doc.Text("main p, .description, [itemprop='description']")), 1600) + } + if domPrice != "" { + disp := domPrice + if domCur != "" { + disp += " " + domCur + } + blocks := []string{"# " + title, "- **Price**: " + disp} + if desc != "" { + blocks = append(blocks, "## Description\n\n"+desc) + } + rec := map[string]any{"title": title, "price": domPrice} + if domCur != "" { + rec["currency"] = domCur + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: sliceRunesMax(desc, 260), + Markdown: strings.Join(blocks, "\n\n"), + Records: []map[string]any{rec}, + } + } + } + return nil +} + +// ── #367 Chairish & 1stDibs (`chairish_1stdibs_html`) ──────────────────────────────────────────── + +func wave3ResaleExtractChairish1stDibsHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + ldObjs := extractJSONLDObjectsDeclHTML(rawHTML, 24) + prod := wave3ResaleExtractJSONLDProduct(ldObjs) + recsList, listRows, listLinks := wave3ResaleExtractItemList(ldObjs, baseURL) + if prod == nil && len(recsList) == 0 { + return nil + } + doc := ParseHTMLDoc(rawHTML, wave3ResaleMaxHTMLBytes) + title := wave3ResaleExtractTitle(doc, rawHTML) + + if prod != nil { + name := wave3ResaleFirstNonEmpty(wave3ResalePlain(prod["name"], 240), title) + if name == "" { + return nil + } + brand := wave3ResaleFirstNonEmpty(wave3ResaleExtractBrandName(prod["brand"]), wave3ResaleExtractBrandName(prod["creator"])) + sku := wave3ResalePlain(prod["sku"], 80) + material := wave3ResalePlain(prod["material"], 120) + desc := wave3ResaleFirstNonEmpty(wave3ResalePlain(prod["description"], 1800), wave3ResaleExtractMetaDesc(rawHTML)) + offers := wave3ResaleParseOffers(prod["offers"], baseURL) + + // Extract dimensions & condition from JSON-LD or DOM + var dimParts []string + for _, dk := range []string{"width", "height", "depth", "weight"} { + if v := prod[dk]; v != nil { + var dv string + if vm, ok := v.(map[string]any); ok { + val := wave3ResalePlain(vm["value"], 32) + unit := wave3ResaleFirstNonEmpty(wave3ResalePlain(vm["unitText"], 24), wave3ResalePlain(vm["unitCode"], 16)) + dv = strings.TrimSpace(val + " " + unit) + } else { + dv = wave3ResalePlain(v, 48) + } + if dv != "" { + dimParts = append(dimParts, wave3ResaleCapitalizeWords(dk)+": "+dv) + } + } + } + dimensions := strings.Join(dimParts, " | ") + condition := "" + if len(offers) > 0 { + condition = offers[0].Condition + } + + if doc != nil { + dlMap := doc.DLMap("dl") + if dimensions == "" { + dimensions = SanitizeSchemaPlainField(wave3ResaleFirstNonEmpty( + dlMap["dimensions"], + dlMap["size"], + dlMap["measurements"], + wave3ResaleCleanText(doc.Text(".dimensions, [data-testid='dimensions'], [data-tn='pdp-dimensions']")), + ), 180) + } + if condition == "" { + condition = SanitizeSchemaPlainField(wave3ResaleFirstNonEmpty( + dlMap["condition"], + wave3ResaleCleanText(doc.Text(".condition, [data-testid='condition'], [data-tn='pdp-condition']")), + ), 120) + } + if dimensions == "" || condition == "" { + bodyTxt := wave3ResaleCleanText(doc.Text("main, body")) + if dimensions == "" { + if m := wave3ResaleRxDimText.FindStringSubmatch(bodyTxt); len(m) >= 2 { + dimensions = SanitizeSchemaPlainField(m[1], 140) + } + } + if condition == "" { + if m := wave3ResaleRxCondText.FindStringSubmatch(bodyTxt); len(m) >= 2 { + condition = SanitizeSchemaPlainField(m[1], 80) + } + } + } + } + + var bullets []string + rec := map[string]any{"title": name} + if brand != "" { + bullets = append(bullets, "- **Creator / Brand**: "+brand) + rec["brand"] = brand + } + if len(offers) > 0 && offers[0].Price != "" { + disp := offers[0].Price + if offers[0].Currency != "" { + disp += " " + offers[0].Currency + rec["currency"] = offers[0].Currency + } + bullets = append(bullets, "- **Primary Price**: "+disp) + rec["price"] = offers[0].Price + } + if condition != "" { + bullets = append(bullets, "- **Condition**: "+condition) + rec["condition"] = condition + } + if dimensions != "" { + bullets = append(bullets, "- **Dimensions**: "+dimensions) + rec["dimensions"] = dimensions + } + if material != "" { + bullets = append(bullets, "- **Material**: "+material) + } + if sku != "" { + bullets = append(bullets, "- **SKU**: "+sku) + rec["sku"] = sku + } + + blocks := []string{"# " + name} + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + if len(offers) > 1 { + var offerRows [][]string + for _, o := range offers { + if o.Price == "" { + continue + } + offerRows = append(offerRows, []string{ + wave3ResaleFirstNonEmpty(o.Currency, "-"), + o.Price, + wave3ResaleFirstNonEmpty(o.Availability, "-"), + wave3ResaleFirstNonEmpty(o.Condition, "-"), + }) + } + if len(offerRows) > 0 { + blocks = append(blocks, "## Multi-Currency Offers\n\n"+formatDeclarativeGFMTable([]string{"Currency", "Price", "Availability", "Condition"}, offerRows)) + } + } + if desc != "" { + blocks = append(blocks, "## Description\n\n"+desc) + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: name, + Description: sliceRunesMax(desc, 260), + Author: brand, + Markdown: strings.Join(blocks, "\n\n"), + Records: []map[string]any{rec}, + } + } + + if title == "" { + title = "Chairish & 1stDibs Listings" + } + md := "# " + title + "\n\n" + formatDeclarativeGFMTable([]string{"Item", "Price", "Condition"}, listRows) + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Markdown: md, + Links: listLinks, + Records: recsList, + } +} diff --git a/internal/extract/wave3_resale_test.go b/internal/extract/wave3_resale_test.go new file mode 100644 index 0000000..f47c09d --- /dev/null +++ b/internal/extract/wave3_resale_test.go @@ -0,0 +1,563 @@ +package extract + +import ( + "encoding/json" + "fmt" + "net/url" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/bartrumb/edgefetch/v2/internal/classify" +) + +func wave3ResaleResolveManifest(t *testing.T, m *DeclarativeAdapterManifest, rawURL string) (*DeclarativeTwinMatch, bool) { + t.Helper() + u, err := url.Parse(rawURL) + if err != nil { + t.Fatalf("url.Parse(%q): %v", rawURL, err) + } + host := strings.TrimSuffix(strings.ToLower(u.Hostname()), ".") + rawParts := splitNonEmptyEscapedSegments(u.EscapedPath()) + return resolveManifestTwinOnParsedURL(m, u, host, rawParts, DeclarativeResolveOptions{}) +} + +func TestWave3ResaleManifestsAndRouting(t *testing.T) { + catPIDs := []string{ + "reverb", + "pinkbike-buysell", + "used-bikes-shopify", + "bicycle-blue-book", + "back-market-swappa", + "peer-resale-fashion", + "local-classifieds-marketplaces", + "creator-digital-stores", + "chairish-1stdibs", + } + + byID := make(map[string]*DeclarativeAdapterManifest) + claimedDomains := make(map[string]string) + + for _, id := range catPIDs { + raw, err := os.ReadFile(filepath.Join("manifests", id+".yaml")) + if err != nil { + t.Fatalf("read %s.yaml: %v", id, err) + } + m, err := ParseDeclarativeYAMLManifest(raw) + if err != nil { + t.Fatalf("ParseDeclarativeYAMLManifest(%s.yaml): %v", id, err) + } + if m.ID != id { + t.Fatalf("%s.yaml has mismatched id=%q", id, m.ID) + } + if m.Category != "commerce-social" { + t.Fatalf("%s.yaml must use category commerce-social, got %q", id, m.Category) + } + if m.AuthMode == "detect-only" || m.DetectOnly != nil { + t.Fatalf("%s.yaml uses retired detect-only", id) + } + for _, d := range m.Domains { + ld := strings.ToLower(strings.TrimSpace(d)) + if prev, exists := claimedDomains[ld]; exists { + t.Fatalf("duplicate domain %q across %s and %s", ld, prev, id) + } + claimedDomains[ld] = id + } + for _, hr := range m.HTMLRoutes { + for _, b := range hr.Bullets { + if strings.ContainsAny(b.Label, "{}") { + t.Fatalf("%s.yaml bullet label contains {}: %q", id, b.Label) + } + } + } + byID[id] = m + } + + // Disjointness from existing commerce/cycling manifests + for _, existingID := range []string{"ebay", "etsy", "shopify", "bike-index", "specialized", "giant-liv-bikes", "smartetailing", "ebike-state-laws"} { + raw, err := os.ReadFile(filepath.Join("manifests", existingID+".yaml")) + if err != nil { + t.Fatalf("read %s.yaml: %v", existingID, err) + } + em, err := ParseDeclarativeYAMLManifest(raw) + if err != nil { + t.Fatalf("ParseDeclarativeYAMLManifest(%s.yaml): %v", existingID, err) + } + for _, d := range em.Domains { + ld := strings.ToLower(strings.TrimSpace(d)) + if catOwner, overlap := claimedDomains[ld]; overlap { + t.Fatalf("Cat P %s overlaps %s domain %q", catOwner, existingID, ld) + } + } + } + + // #359 reverb: pub, min_interval_ms=1000, no strict_robots, Accept-Version: 3.0, application/hal+json + rev := byID["reverb"] + if rev.AuthMode != "pub" || rev.MinIntervalMs != 1000 || rev.StrictRobots { + t.Fatalf("reverb manifest flags mismatch: %+v", rev) + } + tmRev, okRev := wave3ResaleResolveManifest(t, rev, "https://reverb.com/item/36356670-fender-stratocaster-knob-set-black") + if !okRev || tmRev.FetchURL != "https://api.reverb.com/api/listings/36356670" || + tmRev.route.Twin.Headers["Accept-Version"] != "3.0" || + tmRev.route.Twin.Accept != "application/hal+json" || + tmRev.route.Extract.JSONMode != "reverb_listing_json" { + t.Fatalf("reverb /item/ route failed: ok=%v tm=%+v", okRev, tmRev) + } + if tmDir, okDir := wave3ResaleResolveManifest(t, rev, "https://api.reverb.com/api/listings/36356670"); !okDir || tmDir.route.Extract.JSONMode != "reverb_listing_json" { + t.Fatalf("reverb /api/listings/{id} failed: ok=%v", okDir) + } + if tmSearch, okSearch := wave3ResaleResolveManifest(t, rev, "https://api.reverb.com/api/listings?query=fender&per_page=2"); !okSearch || tmSearch.route.Extract.JSONMode != "reverb_search_json" { + t.Fatalf("reverb /api/listings search failed: ok=%v", okSearch) + } + + // #360 pinkbike-buysell: min_interval_ms=2000, max_concurrent=1, strict_robots=true + pb := byID["pinkbike-buysell"] + if pb.MinIntervalMs != 2000 || pb.MaxConcurrent != 1 || !pb.StrictRobots { + t.Fatalf("pinkbike-buysell flags mismatch: %+v", pb) + } + + // #361 used-bikes-shopify: routes ONLY on theproscloset.com, NEVER on upway.co + ubs := byID["used-bikes-shopify"] + if ubs.AuthMode != "pub" || ubs.MinIntervalMs != 2000 || !ubs.StrictRobots { + t.Fatalf("used-bikes-shopify flags mismatch: %+v", ubs) + } + if tmTPC, okTPC := wave3ResaleResolveManifest(t, ubs, "https://www.theproscloset.com/products/10226226168000-cervelo-p-series-red-axs-time-trial-bike-2022-58cm"); !okTPC || + tmTPC.FetchURL != "https://www.theproscloset.com/products/10226226168000-cervelo-p-series-red-axs-time-trial-bike-2022-58cm.js" || + tmTPC.route.Extract.CommerceMode != "shopify_product_js" { + t.Fatalf("TPC product route failed: ok=%v tm=%+v", okTPC, tmTPC) + } + if tmTPCJson, okTPCJson := wave3ResaleResolveManifest(t, ubs, "https://www.theproscloset.com/products/10226226168000-cervelo.json"); !okTPCJson || tmTPCJson.route.Extract.CommerceMode != "shopify_product" { + t.Fatalf("TPC .json route failed: ok=%v tm=%+v", okTPCJson, tmTPCJson) + } + if tmTPCCat, okTPCCat := wave3ResaleResolveManifest(t, ubs, "https://www.theproscloset.com/products.json?limit=5&page=1"); !okTPCCat || tmTPCCat.route.Extract.CommerceMode != "shopify_catalog_page" { + t.Fatalf("TPC catalog route failed: ok=%v", okTPCCat) + } + for _, upwayURL := range []string{ + "https://upway.co/products/lane-lane-express-uaa01", + "https://upway.co/products/lane-lane-express-uaa01.js", + "https://upway.co/products.json?limit=2", + } { + if tmUp, okUp := wave3ResaleResolveManifest(t, ubs, upwayURL); okUp || tmUp != nil { + t.Fatalf("upway.co URL %q must NOT match routes twin: %+v", upwayURL, tmUp) + } + } + + // #364 & #365 must be real adapters, and #365 must have NO ?format=rss route + if byID["peer-resale-fashion"].AuthMode != "html" || byID["local-classifieds-marketplaces"].AuthMode != "html" { + t.Fatalf("#364 and #365 must be real html adapters") + } + if len(byID["local-classifieds-marketplaces"].Routes) != 0 { + t.Fatalf("#365 must not define any ?format=rss twin routes") + } + + // #366 creator-digital-stores: matches *.sellfy.store/p/* via hostSubdomain + universalEngine + cds := byID["creator-digital-stores"] + sellfyHTML := `LUT Pack | Demo Sellfy

Cinema LUT Pack

` + resSellfy, okSellfy := ExtractHTMLOnManifest(cds, sellfyHTML, "https://demo.sellfy.store/p/cinema-lut-pack/", "", nil) + if !okSellfy || resSellfy == nil || !strings.Contains(resSellfy.Markdown, "19.00 USD") { + t.Fatalf("creator-digital-stores failed on *.sellfy.store: ok=%v res=%+v", okSellfy, resSellfy) + } + if resOther, okOther := ExtractHTMLOnManifest(cds, sellfyHTML, "https://other.example.com/p/cinema-lut-pack/", "", nil); okOther || resOther != nil { + t.Fatalf("creator-digital-stores must NOT match unrelated universal domain") + } +} + +func TestWave3ResaleJSONAndHTMLModes(t *testing.T) { + registerWave3ResaleHTMLModes() + RegisterWave3ResaleHTMLModes() + + expectedHTMLModes := []string{ + "pinkbike_buysell_html", + "used_bikes_shopify_html", + "bicycle_blue_book_html", + "back_market_swappa_html", + "peer_resale_fashion_html", + "local_classifieds_html", + "creator_digital_stores_html", + "chairish_1stdibs_html", + } + for _, hm := range expectedHTMLModes { + if getExternalHTMLModeLazy(hm) == nil { + t.Fatalf("RegisterExternalHTMLModeLazy missing %q", hm) + } + if !IsWave3ResaleHTMLMode(hm) { + t.Fatalf("IsWave3ResaleHTMLMode(%q) = false", hm) + } + } + + // #359 Reverb listing + search JSON + revListing := []byte(`{"id":36356670,"make":"Fender","model":"Stratocaster Knob Set","finish":"Black","year":"2023","title":"Fender Stratocaster Knob Set - Black","shop_name":"Tone Vault Music","description":"

Genuine Fender control knobs.

","condition":{"display_name":"Brand New"},"price":{"amount":"14.99","currency":"USD"},"shipping":{"rate":{"amount":"5.00","currency":"USD"}},"categories":[{"full_name":"Parts / Knobs"}],"inventory":8,"state":{"slug":"live","description":"Live"},"upc":"885978102037","location":{"display_location":"Nashville, TN, United States"},"_links":{"web":{"href":"https://reverb.com/item/36356670-fender-stratocaster-knob-set-black"}}}`) + revDoc, okRev := FormatWave3ResaleJSONDoc("reverb_listing_json", revListing, nil, "https://api.reverb.com/api/listings/36356670") + if !okRev || revDoc == nil || !strings.Contains(revDoc.Markdown, "14.99 USD") || !strings.Contains(revDoc.Markdown, "885978102037") { + t.Fatalf("reverb_listing_json failed: ok=%v doc=%+v", okRev, revDoc) + } + // Invalid UPC (non-8/12/13/14 digit) must be stripped by Rule 4 validation + revBadUPC := []byte(`{"id":36356670,"title":"Fender Knob","upc":"ABC-123","price":{"amount":"14.99","currency":"USD"}}`) + revBadDoc, okBadUPC := FormatWave3ResaleJSONDoc("reverb_listing_json", revBadUPC, nil, "https://api.reverb.com/api/listings/36356670") + if !okBadUPC || strings.Contains(revBadDoc.Markdown, "ABC-123") { + t.Fatalf("reverb_listing_json must omit invalid UPC ABC-123: %+v", revBadDoc) + } + + revSearch := []byte(`{"total":42,"current_page":1,"per_page":2,"total_pages":21,"humanized_params":{"query":"fender stratocaster"},"listings":[{"id":101,"title":"Fender American Pro Strat","shop_name":"Guitar Shop","condition":{"display_name":"Mint"},"price":{"amount":"1299.00","currency":"USD"},"state":{"description":"Live"},"_links":{"web":{"href":"https://reverb.com/item/101-strat"}}}]}`) + revSearchRaw, okRS := FormatWave3ResaleJSONMode("reverb_search_json", revSearch, nil, "https://api.reverb.com/api/listings?query=fender+stratocaster") + if !okRS || !strings.Contains(revSearchRaw, "Fender American Pro Strat") || !strings.Contains(revSearchRaw, "1299.00 USD") { + t.Fatalf("reverb_search_json failed: ok=%v raw=%s", okRS, revSearchRaw) + } + if _, negOK := FormatWave3ResaleJSONMode("reverb_listing_json", []byte(`{"message":"Accept-Version header is required"}`), nil, "https://api.reverb.com/api/listings/36356670"); negOK { + t.Fatalf("reverb_listing_json must reject missing Accept-Version error JSON") + } + + // #361 Upway Hydrogen + TPC HTML fallback + Upway .js 404 homepage rejection + upwayHTML := `2023 Specialized Turbo Vado 4.0 | Upway

2023 Specialized Turbo Vado 4.0

Motor
Specialized 2.0 70Nm
Battery
710Wh
` + resUp := Wave3ResaleRunHTML("used_bikes_shopify_html", upwayHTML, "https://upway.co/products/specialized-turbo-vado-4", "used-bikes-shopify") + if resUp == nil || !strings.Contains(resUp.Markdown, "2499.00 USD") || !strings.Contains(resUp.Markdown, "710Wh") { + t.Fatalf("used_bikes_shopify_html Upway failed: %+v", resUp) + } + if negUpJS := Wave3ResaleRunHTML("used_bikes_shopify_html", upwayHTML, "https://upway.co/products/specialized-turbo-vado-4.js", "used-bikes-shopify"); negUpJS != nil { + t.Fatalf("used_bikes_shopify_html must reject .js paths") + } + if negUpHome := Wave3ResaleRunHTML("used_bikes_shopify_html", `Electric Bikes for Sale | Up to 60% Off

Electric Bikes for Sale

`, "https://upway.co/products/missing", "used-bikes-shopify"); negUpHome != nil { + t.Fatalf("used_bikes_shopify_html must reject Upway homepage fallback") + } + + // #362 Bicycle Blue Book model list + detail + bbbListHTML := `All-City Cyclocross Bikes - Bicycle Blue Book

All-City Cyclocross

` + resBBBList := Wave3ResaleRunHTML("bicycle_blue_book_html", bbbListHTML, "https://www.bicyclebluebook.com/value-guide/cyclocross/all-city", "bicycle-blue-book") + if resBBBList == nil || len(resBBBList.Records) != 1 || !strings.Contains(resBBBList.Markdown, "Macho King LTD") { + t.Fatalf("bicycle_blue_book_html model list failed: %+v", resBBBList) + } + + // #364 Poshmark category ItemList + Next.js __NEXT_DATA__ + poshCatHTML := `Women's Fashion | Poshmark

Women

` + resPoshCat := Wave3ResaleRunHTML("peer_resale_fashion_html", poshCatHTML, "https://poshmark.com/category/Women", "peer-resale-fashion") + if resPoshCat == nil || len(resPoshCat.Records) != 1 || !strings.Contains(resPoshCat.Markdown, "Patagonia Better Sweater") { + t.Fatalf("peer_resale_fashion_html category failed: %+v", resPoshCat) + } + + // #365 OfferUp ItemList + Craigslist search + Facebook login_wall/CSR checks + offerUpHTML := `Bikes & Cycling on OfferUp

Bikes & Cycling

` + resOfferUp := Wave3ResaleRunHTML("local_classifieds_html", offerUpHTML, "https://offerup.com/c/bikes-and-cycling", "local-classifieds-marketplaces") + if resOfferUp == nil || len(resOfferUp.Records) != 1 || !strings.Contains(resOfferUp.Markdown, "Trek Domane AL 3") { + t.Fatalf("local_classifieds_html OfferUp failed: %+v", resOfferUp) + } + + fbLoginHTML := `Log in to Facebook

Log in to Facebook

` + if resFBLogin := Wave3ResaleRunHTML("local_classifieds_html", fbLoginHTML, "https://www.facebook.com/marketplace/sanfrancisco/bicycles", "local-classifieds-marketplaces"); resFBLogin != nil { + t.Fatalf("Facebook login wall must return nil from HTML extractor") + } + csFBLogin := classify.ClassifyContentStateFull(classify.ContentStateInput{ + Status: 200, + RawHTML: fbLoginHTML, + Markdown: "Log in to Facebook", + URL: "https://www.facebook.com/marketplace/sanfrancisco/bicycles", + FinalURL: "https://www.facebook.com/login/", + Title: "Log in to Facebook", + }) + if csFBLogin.State != "login_wall" { + t.Fatalf("expected Facebook login page state=login_wall, got %q (%s)", csFBLogin.State, csFBLogin.Reason) + } +} + +func TestWave3ResaleFixturesGoldenAndNegativeShells(t *testing.T) { + registerWave3ResaleHTMLModes() + + type fixtureNeg struct { + Name string `json:"name"` + Status int `json:"status"` + InputURL string `json:"inputUrl"` + FinalURL string `json:"finalUrl"` + Payload string `json:"payload"` + } + type fixtureDoc struct { + AdapterID string `json:"adapterId"` + Mode string `json:"mode"` + InputURL string `json:"inputUrl"` + ExpectedFetchURL string `json:"expectedFetchUrl"` + MockPayload string `json:"mockPayload"` + ExpectTitleIncludes string `json:"expectTitleIncludes"` + ExpectMarkdownIncludes []string `json:"expectMarkdownIncludes"` + NegativeCases []fixtureNeg `json:"negativeCases"` + } + + ids := []string{ + "reverb", + "pinkbike-buysell", + "used-bikes-shopify", + "bicycle-blue-book", + "back-market-swappa", + "peer-resale-fashion", + "local-classifieds-marketplaces", + "creator-digital-stores", + "chairish-1stdibs", + } + + for _, id := range ids { + fpath := filepath.Join("..", "..", "hub", "test", "fixtures", "adapters", id+".json") + raw, err := os.ReadFile(fpath) + if err != nil { + t.Fatalf("read fixture %s: %v", fpath, err) + } + var fx fixtureDoc + if err := json.Unmarshal(raw, &fx); err != nil { + t.Fatalf("unmarshal fixture %s: %v", fpath, err) + } + if fx.AdapterID != id { + t.Fatalf("%s: adapterId=%q != %q", id, fx.AdapterID, id) + } + if len(fx.NegativeCases) < 4 { + t.Fatalf("%s: expected >= 4 negativeCases, got %d", id, len(fx.NegativeCases)) + } + + // Load manifest to match htmlRoute or twin route + mRaw, err := os.ReadFile(filepath.Join("manifests", id+".yaml")) + if err != nil { + t.Fatalf("read %s.yaml: %v", id, err) + } + m, err := ParseDeclarativeYAMLManifest(mRaw) + if err != nil { + t.Fatalf("parse %s.yaml: %v", id, err) + } + + start := time.Now() + var gotTitle, gotMD string + if fx.Mode == "twin" { + tm, ok := wave3ResaleResolveManifest(t, m, fx.InputURL) + if !ok || tm == nil { + t.Fatalf("%s: failed to resolve twin for %s", id, fx.InputURL) + } + if fx.ExpectedFetchURL != "" && tm.FetchURL != fx.ExpectedFetchURL { + t.Fatalf("%s: FetchURL=%q, want %q", id, tm.FetchURL, fx.ExpectedFetchURL) + } + if tm.route.Extract.JSONMode != "" && IsWave3ResaleJSONMode(tm.route.Extract.JSONMode) { + doc, okDoc := FormatWave3ResaleJSONDoc(tm.route.Extract.JSONMode, []byte(fx.MockPayload), tm.params, fx.InputURL) + if !okDoc || doc == nil { + t.Fatalf("%s: FormatWave3ResaleJSONDoc(%s) failed", id, tm.route.Extract.JSONMode) + } + gotTitle, gotMD = doc.Title, doc.Markdown + } else { + doc, okDoc := tm.Format(fx.MockPayload) + if !okDoc || doc == nil { + t.Fatalf("%s: tm.Format failed", id) + } + gotTitle, gotMD = doc.Title, doc.Markdown + } + } else { + if len(m.HTMLRoutes) == 0 { + t.Fatalf("%s: expected htmlRoutes", id) + } + htmlMode := m.HTMLRoutes[0].Mode + res := Wave3ResaleRunHTML(htmlMode, fx.MockPayload, fx.InputURL, id) + if res == nil { + t.Fatalf("%s: Wave3ResaleRunHTML(%s) returned nil on golden payload", id, htmlMode) + } + gotTitle, gotMD = res.Title, res.Markdown + } + if elapsed := time.Since(start); elapsed > 25*time.Millisecond*time.Duration(extractRaceSlowdown) { + t.Fatalf("%s: golden extraction took %v (> 25ms)", id, elapsed) + } + if fx.ExpectTitleIncludes != "" && !strings.Contains(gotTitle, fx.ExpectTitleIncludes) { + t.Fatalf("%s: title %q missing %q", id, gotTitle, fx.ExpectTitleIncludes) + } + for _, sub := range fx.ExpectMarkdownIncludes { + if !strings.Contains(gotMD, sub) { + t.Fatalf("%s: markdown missing %q\nmarkdown:\n%s", id, sub, gotMD) + } + } + + // Verify all negativeCases + for _, nc := range fx.NegativeCases { + negURL := fx.InputURL + if nc.FinalURL != "" { + negURL = nc.FinalURL + } else if nc.InputURL != "" { + negURL = nc.InputURL + } + if len(m.HTMLRoutes) > 0 { + if res := Wave3ResaleRunHTML(m.HTMLRoutes[0].Mode, nc.Payload, negURL, id); res != nil { + t.Fatalf("%s:%s: HTML mode unexpectedly extracted content on negative case", id, nc.Name) + } + } + if fx.Mode == "twin" { + if tm, ok := wave3ResaleResolveManifest(t, m, negURL); ok && tm != nil && tm.route.Extract.JSONMode != "" && IsWave3ResaleJSONMode(tm.route.Extract.JSONMode) { + if doc, okDoc := FormatWave3ResaleJSONDoc(tm.route.Extract.JSONMode, []byte(nc.Payload), tm.params, negURL); okDoc && doc != nil { + t.Fatalf("%s:%s: JSON mode unexpectedly formatted negative payload", id, nc.Name) + } + } + } + st := nc.Status + if st == 0 { + st = 200 + } + if st >= 200 && st < 300 { + ext := ExtractHTMLDocumentFull(nc.Payload, FullExtractOptions{ + BaseURL: negURL, + OnlyMainContent: true, + }) + cs := classify.ClassifyContentStateFull(classify.ContentStateInput{ + Status: st, + RawHTML: nc.Payload, + Markdown: ext.Markdown, + URL: fx.InputURL, + FinalURL: negURL, + Title: wave3ResaleExtractTitleBounded(nc.Payload), + }) + if cs.State == "active" { + t.Fatalf("%s:%s (status=%d): ClassifyContentStateFull unexpectedly returned active (%s)", id, nc.Name, st, cs.Reason) + } + } + } + } +} + +func TestWave3ResalePassiveCloudflareAndLemmyOfferUp(t *testing.T) { + registerWave3ResaleHTMLModes() + + // 1. 200 OK full resale product pages with passive /cdn-cgi/challenge-platform/ script + Product JSON-LD extract cleanly as active + cfScript := `` + for _, tc := range []struct { + id string + mode string + url string + html string + }{ + { + id: "used-bikes-shopify", + mode: "used_bikes_shopify_html", + url: "https://upway.co/products/specialized-turbo-vado-4", + html: `2023 Specialized Turbo Vado 4.0 | Upway` + cfScript + `

2023 Specialized Turbo Vado 4.0

Certified pre-owned e-bike.

`, + }, + { + id: "back-market-swappa", + mode: "back_market_swappa_html", + url: "https://swappa.com/buy/apple-iphone-14", + html: `Apple iPhone 14 | Swappa` + cfScript + `

Apple iPhone 14

`, + }, + { + id: "pinkbike-buysell", + mode: "pinkbike_buysell_html", + url: "https://www.pinkbike.com/buysell/3910001/", + html: `2023 Santa Cruz Bronson | Pinkbike` + cfScript + `

2023 Santa Cruz Bronson

`, + }, + { + id: "chairish-1stdibs", + mode: "chairish_1stdibs_html", + url: "https://www.chairish.com/product/99887766/mid-century-chair", + html: `Mid-Century Lounge Chair | Chairish` + cfScript + `

Mid-Century Lounge Chair

`, + }, + } { + res := Wave3ResaleRunHTML(tc.mode, tc.html, tc.url, tc.id) + if res == nil || res.ExtractorID != tc.id { + t.Fatalf("%s with passive challenge-platform script must extract cleanly, got %+v", tc.id, res) + } + cs := classify.ClassifyContentStateFull(classify.ContentStateInput{ + Status: 200, + RawHTML: tc.html, + Markdown: res.Markdown, + URL: tc.url, + FinalURL: tc.url, + Title: res.Title, + }) + if cs.State != "active" { + t.Fatalf("%s with passive challenge-platform script got contentState=%q (%s), want active", tc.id, cs.State, cs.Reason) + } + } + + // Small challenge shells without real body markers or with challenge titles/cf-mitigated must still be rejected + for _, neg := range []struct { + name string + html string + }{ + {"small-challenge-platform", `Verify
`}, + {"small-cf-turnstile", `Security
`}, + {"just-a-moment-with-h1", `Just a moment...

upway.co

`}, + {"attention-required-with-ld", `Attention Required! | Cloudflare

Sorry, you have been blocked

`}, + {"cf-mitigated", `Swappa

Blocked

cf-mitigated challenge

`}, + } { + if r := Wave3ResaleRunHTML("used_bikes_shopify_html", neg.html, "https://upway.co/products/test", "used-bikes-shopify"); r != nil { + t.Fatalf("%s must still be rejected, got %+v", neg.name, r) + } + } + + // 2. lemmy.yaml Route 4 (post/{postId}) must exclude offerup.com / www.offerup.com + lemmyRaw, err := os.ReadFile(filepath.Join("manifests", "lemmy.yaml")) + if err != nil { + t.Fatalf("read lemmy.yaml: %v", err) + } + lemmyM, err := ParseDeclarativeYAMLManifest(lemmyRaw) + if err != nil { + t.Fatalf("ParseDeclarativeYAMLManifest(lemmy.yaml): %v", err) + } + for _, ouURL := range []string{ + "https://offerup.com/post/123456", + "https://www.offerup.com/post/123456", + } { + if tm, ok := wave3ResaleResolveManifest(t, lemmyM, ouURL); ok || tm != nil { + t.Fatalf("lemmy Route 4 must NOT match %q, got %+v", ouURL, tm) + } + } + if tm, ok := wave3ResaleResolveManifest(t, lemmyM, "https://lemmy.world/post/54926010"); !ok || tm == nil || tm.FetchURL != "https://lemmy.world/api/v3/post?id=54926010" { + t.Fatalf("lemmy Route 4 must still match lemmy.world/post/54926010: ok=%v tm=%+v", ok, tm) + } +} + +func TestWave3ResaleM7RegressionsAndPerfBudget(t *testing.T) { + registerWave3ResaleHTMLModes() + + // 1. peer-resale-fashion (poshmark.com/category/Women): ItemList ListItems omitting `name` must derive titles from listing URL slugs (not drop all 48 items) + var listElems []string + for i := 1; i <= 48; i++ { + listElems = append(listElems, fmt.Sprintf(`{"@type":"ListItem","position":%d,"url":"https://poshmark.com/listing/Patagonia-Better-Sweater-Jacket-%d-65a1b2c3d4e5f60123456789"}`, i, i)) + } + poshNoNameCat := `Women's Fashion | Poshmark

Women

` + resNoName := Wave3ResaleRunHTML("peer_resale_fashion_html", poshNoNameCat, "https://poshmark.com/category/Women", "peer-resale-fashion") + if resNoName == nil || len(resNoName.Records) != 25 || !strings.Contains(resNoName.Markdown, "Patagonia Better Sweater Jacket 1") { + t.Fatalf("poshmark category ItemList without name must derive slug titles (25 capped), got: %+v", resNoName) + } + + // 1b. Poshmark DOM tile fallback when ItemList has numeric-only URLs without names + poshDOMCat := `Women | Poshmark

Women

` + resDOMCat := Wave3ResaleRunHTML("peer_resale_fashion_html", poshDOMCat, "https://poshmark.com/category/Women", "peer-resale-fashion") + if resDOMCat == nil || len(resDOMCat.Records) != 1 || !strings.Contains(resDOMCat.Markdown, "Lululemon Align Leggings Size 6") { + t.Fatalf("poshmark DOM tile fallback failed: %+v", resDOMCat) + } + + // 2. peer-resale-fashion (poshmark.com/listing/...): ~500KB __INITIAL_STATE__ +

Arc'teryx Beta LT Jacket

` + t0 := time.Now() + resPosh := Wave3ResaleRunHTML("peer_resale_fashion_html", poshBloated, "https://poshmark.com/listing/Arcteryx-Beta-LT-Jacket-65a1b2c3d4e5f60123456789", "peer-resale-fashion") + poshElapsed := time.Since(t0) + if resPosh == nil || !strings.Contains(resPosh.Markdown, "Arc'teryx") || !strings.Contains(resPosh.Markdown, "395.00 USD") { + t.Fatalf("poshmark bloated __INITIAL_STATE__ extraction failed: %+v", resPosh) + } + if poshElapsed > 25*time.Millisecond*time.Duration(extractRaceSlowdown) { + t.Fatalf("poshmark 900KB+ __INITIAL_STATE__ took %v (>25ms budget)", poshElapsed) + } + + // 3. used-bikes-shopify (upway.co): bloated ` + strings.Repeat(``, 15000) + `

Gazelle Ultimate C8+

Motor
Bosch Active Line Plus
` + t1 := time.Now() + resUp := Wave3ResaleRunHTML("used_bikes_shopify_html", upwayBloated, "https://upway.co/products/gazelle-ultimate-c8", "used-bikes-shopify") + upElapsed := time.Since(t1) + if resUp == nil || !strings.Contains(resUp.Markdown, "2199.00 USD") || !strings.Contains(resUp.Markdown, "Bosch Active Line Plus") { + t.Fatalf("upway bloated HTML extraction failed: %+v", resUp) + } + if upElapsed > 25*time.Millisecond*time.Duration(extractRaceSlowdown) { + t.Fatalf("upway bloated HTML took %v (>25ms budget)", upElapsed) + } + + // 4. creator-digital-stores (gumroad.com/discover): Inertia data-page products + inertiaPayload := `{"component":"Discover/Index","props":{"products":[{"name":"Pro Notion Finance OS","permalink":"notion-finance-os","price_cents":2900,"currency_code":"USD","seller":{"name":"TemplateCraft"}},{"name":"Blender Shader Pack","url":"https://creator.gumroad.com/l/blender-shaders","price_formatted":"$15.00","seller":{"name":"3DStudio"}}]}}` + escapedInertia := strings.ReplaceAll(inertiaPayload, `"`, `"`) + gumDiscoverHTML := `Discover | Gumroad
` + resGum := Wave3ResaleRunHTML("creator_digital_stores_html", gumDiscoverHTML, "https://gumroad.com/discover", "creator-digital-stores") + if resGum == nil || len(resGum.Records) != 2 || !strings.Contains(resGum.Markdown, "Pro Notion Finance OS") || !strings.Contains(resGum.Markdown, "29.00 USD") || !strings.Contains(resGum.Markdown, "TemplateCraft") { + t.Fatalf("gumroad.com/discover Inertia data-page extraction failed: %+v", resGum) + } + // Empty
without data-page props must still be rejected as SPA shell + if negGum := Wave3ResaleRunHTML("creator_digital_stores_html", `Gumroad
`, "https://gumroad.com/discover", "creator-digital-stores"); negGum != nil { + t.Fatalf("empty Gumroad
shell must return nil, got %+v", negGum) + } +} diff --git a/internal/extract/wave3_schema.go b/internal/extract/wave3_schema.go new file mode 100644 index 0000000..e391629 --- /dev/null +++ b/internal/extract/wave3_schema.go @@ -0,0 +1,1604 @@ +package extract + +import ( + "encoding/json" + "fmt" + "net/url" + "strconv" + "strings" +) + +const ( + wave3SchemaMaxHTMLBytes = 2 * 1024 * 1024 + wave3SchemaMaxEvents = 25 + wave3SchemaMaxListItems = 50 + wave3SchemaMaxRecordsCap = 25 +) + +var ( + wave3SchemaRxNotFoundTitle = newLazyRegexp(`(?i)(?:^|\b)(?:404|410|406|page\s+not\s+found|page\s+cannot\s+be\s+found|not\s+found|error\s*404|we\s+couldn'?t\s+find\s+that\s+page|access\s+denied|request\s+(?:rejected|blocked)|could\s+not\s+be\s+satisfied|unauthorized|attention\s+required|just\s+a\s+moment|403\s+forbidden|forbidden)(?:\b|$)`) + wave3SchemaRxMaintTitle = newLazyRegexp(`(?i)(?:scheduled\s+maintenance|temporarily\s+unavailable|service\s+unavailable|site\s+maintenance|under\s+maintenance|502\s+bad\s+gateway|503\s+service|down\s+for\s+maintenance)`) + wave3SchemaRxErrorTitle = newLazyRegexp(`(?i)^(?:(?:(?:401|403|404|406|410|429|500|502|503)\s+)?(?:internal\s+)?server\s+error|application\s+error|system\s+error|unexpected\s+error|error\s+page|(?:401|403|404|406|410|429|500|502|503|http\s+\d{3})\s+error|error\s+(?:401|403|404|406|410|429|500|502|503)|error)(?:\s*[|\-\x{2013}\x{2014}:]\s*.*)?$|^.*(?:\s*[|\-\x{2013}\x{2014}:]\s*error)$`) + wave3SchemaRxLoginTitle = newLazyRegexp(`(?i)^(?:log\s*in|sign\s+in|login|authentication\s+required|sso\s+login)(?:\s*[|\-\x{2013}\x{2014}:]\s*.*)?$`) + wave3SchemaRxCurrency3 = newLazyRegexp(`^[A-Z]{3}$`) +) + +func init() { + for _, mode := range []string{ + "schema_vehicle_html", + "schema_faq_howto_html", + "schema_dataset_html", + "schema_software_app_html", + "schema_medical_html", + } { + m := mode + RegisterExternalHTMLModeLazy(m, func(rawHTML, baseURL string, _ func() string, extractorID string) *DeclarativePostFetchResult { + return Wave3SchemaRunHTML(m, rawHTML, baseURL, extractorID) + }) + } +} + +// IsWave3SchemaHTMLMode reports whether mode is handled by Category D Universal Schema.org extractors (#237-#241). +func IsWave3SchemaHTMLMode(mode string) bool { + switch mode { + case "schema_vehicle_html", + "schema_faq_howto_html", + "schema_dataset_html", + "schema_software_app_html", + "schema_medical_html": + return true + default: + return false + } +} + +func wave3SchemaDefaultExtractorID(mode string) string { + switch mode { + case "schema_vehicle_html": + return "schema-vehicle" + case "schema_faq_howto_html": + return "schema-faq-howto" + case "schema_dataset_html": + return "schema-dataset" + case "schema_software_app_html": + return "schema-software-app" + case "schema_medical_html": + return "schema-medical" + default: + return "" + } +} + +// Wave3SchemaRunHTML executes a Category D Universal Schema.org HTML extractor. +func Wave3SchemaRunHTML(mode, rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + if !IsWave3SchemaHTMLMode(mode) || len(rawHTML) == 0 || strings.IndexByte(rawHTML, '<') < 0 || strings.IndexByte(rawHTML, '>') < 0 { + return nil + } + if len(rawHTML) > wave3SchemaMaxHTMLBytes { + rawHTML = truncateUTF8SafeFullDocGo(rawHTML, wave3SchemaMaxHTMLBytes) + } + trimmed := strings.TrimLeft(rawHTML, " \t\r\n") + if trimmed == "" || trimmed[0] == '{' || trimmed[0] == '[' { + return nil + } + if !hasJSONLDScriptToken(rawHTML) { + return nil + } + if wave3SchemaHasNegativeShell(rawHTML, baseURL) { + return nil + } + if !wave3SchemaPassesModePrefilter(mode, rawHTML, baseURL) { + return nil + } + if extractorID == "" { + extractorID = wave3SchemaDefaultExtractorID(mode) + } + + entities := ExtractJSONLDObjects(rawHTML, 250) + if len(entities) == 0 { + return nil + } + graph := wave3SchemaBuildGraph(entities) + + var res *DeclarativePostFetchResult + switch mode { + case "schema_vehicle_html": + res = wave3SchemaExtractVehicle(graph, rawHTML, baseURL, extractorID) + case "schema_faq_howto_html": + res = wave3SchemaExtractFAQHowTo(graph, rawHTML, baseURL, extractorID) + case "schema_dataset_html": + res = wave3SchemaExtractDataset(graph, rawHTML, baseURL, extractorID) + case "schema_software_app_html": + res = wave3SchemaExtractSoftwareApp(graph, rawHTML, baseURL, extractorID) + case "schema_medical_html": + res = wave3SchemaExtractMedical(graph, rawHTML, baseURL, extractorID) + } + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return nil + } + return res +} + +func wave3SchemaPassesModePrefilter(mode, rawHTML, _ string) bool { + switch mode { + case "schema_vehicle_html": + return wave3SchemaContainsAnyFold(rawHTML, + "vehicle", + "car", + "motorcycle", + "motorizedbicycle", + "vehicleidentificationnumber", + ) + case "schema_faq_howto_html": + return wave3SchemaContainsAnyFold(rawHTML, "faqpage", "howto") + case "schema_dataset_html": + return wave3SchemaContainsAnyFold(rawHTML, "dataset", "datacatalog") + case "schema_software_app_html": + return wave3SchemaContainsAnyFold(rawHTML, "softwareapplication", "webapplication", "mobileapplication") + case "schema_medical_html": + return wave3SchemaContainsAnyFold(rawHTML, + "medicalcondition", + "medicalwebpage", + "medicalclinic", + "physician", + "drug", + ) + default: + return false + } +} + +func wave3SchemaContainsAnyFold(haystack string, needles ...string) bool { + for _, n := range needles { + if indexFoldASCIIExtract(haystack, n) >= 0 { + return true + } + } + return false +} + +func wave3SchemaIsExcludedEventHost(baseURL string) bool { + u, err := url.Parse(strings.TrimSpace(baseURL)) + if err != nil { + return false + } + host := strings.TrimSuffix(strings.ToLower(u.Hostname()), ".") + switch host { + case "eventbrite.com", "www.eventbrite.com", + "meetup.com", "www.meetup.com", + "lu.ma", "www.lu.ma", + "luma.com", "www.luma.com", + "ticketmaster.com", "www.ticketmaster.com", + "runsignup.com", "www.runsignup.com": + return true + default: + return false + } +} + +func wave3SchemaHasCommercePlatformMarkers(rawHTML string) bool { + return wave3SchemaContainsAnyFold(rawHTML, + "shopify.shop", + "myshopify.com", + "cdn.shopify.com", + "woocommerce-", + "squarespace", + "wixstatic", + ) +} + +func wave3SchemaIsNegativeURL(baseURL string) bool { + uLower := strings.ToLower(strings.TrimSpace(baseURL)) + if uLower == "" { + return false + } + if strings.Contains(uLower, "/404") || + strings.Contains(uLower, "/not-found") || + strings.Contains(uLower, "/maintenance") || + strings.Contains(uLower, "error=true") || + strings.Contains(uLower, "error=1") || + strings.Contains(uLower, "404.") { + return true + } + pathOnly := uLower + if idx := strings.Index(pathOnly, "://"); idx >= 0 { + rest := pathOnly[idx+3:] + if slash := strings.IndexByte(rest, '/'); slash >= 0 { + pathOnly = rest[slash:] + } else { + pathOnly = "/" + } + } + if cut := strings.IndexAny(pathOnly, "?#"); cut >= 0 { + pathOnly = pathOnly[:cut] + } + return strings.HasSuffix(pathOnly, "/error") || + strings.Contains(pathOnly, "/error/") || + strings.HasSuffix(pathOnly, "/error.html") || + strings.HasSuffix(pathOnly, "/error.htm") || + strings.HasSuffix(pathOnly, "/error.aspx") +} + +func wave3SchemaHasNegativeShell(rawHTML, baseURL string) bool { + if wave3SchemaIsNegativeURL(baseURL) { + return true + } + probe := rawHTML + if len(probe) > 65536 { + probe = probe[:65536] + } + lower := asciiLowerExtractString(probe) + for _, marker := range []string{ + "cf-browser-verification", + "challenge-platform", + "_cf_chl_opt", + "cf_chl_opt", + "attention required! | cloudflare", + "errors.edgesuite.net", + "you don't have permission to access", + "access denied", + "403 forbidden", + "window.kpsdk", + "kp_uidz", + "_incapsula_resource", + "incapsula incident", + "making sure you're not a bot!", + } { + if strings.Contains(lower, marker) { + return true + } + } + title := extractTitleLinearQuick(probe) + if title != "" && (wave3SchemaRxNotFoundTitle.MatchString(title) || + wave3SchemaRxMaintTitle.MatchString(title) || + wave3SchemaRxErrorTitle.MatchString(title)) { + return true + } + if len(rawHTML) < 48*1024 { + for _, maint := range []string{ + "scheduled maintenance", + "down for maintenance", + "under maintenance", + "temporarily unavailable", + "503 service unavailable", + } { + if strings.Contains(lower, maint) { + return true + } + } + if title != "" && wave3SchemaRxLoginTitle.MatchString(title) { + return true + } + } + if len(rawHTML) < 16384 && + !strings.Contains(lower, "
`, + `
`, + `
`, + `
`, + ``, + ``, + } { + if strings.Contains(lower, spa) { + return true + } + } + } + return false +} + +// ── Shared JSON-LD Graph & Field Helpers ──────────────────────────────────────────────────────── + +type wave3SchemaGraph struct { + entities []map[string]any + nestedEntities []map[string]any + byID map[string]map[string]any + allTypes map[string]bool +} + +func wave3SchemaBuildGraph(entities []map[string]any) *wave3SchemaGraph { + g := &wave3SchemaGraph{ + entities: entities, + byID: make(map[string]map[string]any, len(entities)*2), + allTypes: make(map[string]bool, len(entities)*2), + } + visited := 0 + var walk func(node any, depth int, isTop bool) + walk = func(node any, depth int, isTop bool) { + if node == nil || depth > 6 || visited > 500 { + return + } + switch v := node.(type) { + case []any: + for _, el := range v { + if visited > 500 { + break + } + walk(el, depth+1, false) + } + case map[string]any: + visited++ + if !isTop { + g.nestedEntities = append(g.nestedEntities, v) + } + if id, ok := v["@id"].(string); ok { + if tid := strings.TrimSpace(id); tid != "" { + existing, exists := g.byID[tid] + isRich := len(v) > 1 && (v["@type"] != nil || v["name"] != nil || v["text"] != nil || v["streetAddress"] != nil || v["latitude"] != nil) + existingRich := len(existing) > 1 && (existing["@type"] != nil || existing["name"] != nil || existing["text"] != nil || existing["streetAddress"] != nil || existing["latitude"] != nil) + if !exists || (!existingRich && isRich) { + g.byID[tid] = v + } + } + } + for _, t := range normalizeSchemaTypesSchemaGo(v["@type"]) { + g.allTypes[strings.ToLower(t)] = true + } + for k, child := range v { + if k == "@id" || k == "@type" || k == "@context" { + continue + } + switch child.(type) { + case map[string]any, []any: + walk(child, depth+1, false) + } + } + } + } + for _, ent := range entities { + walk(ent, 0, true) + } + return g +} + +func (g *wave3SchemaGraph) hasAnyType(types ...string) bool { + for _, t := range types { + if g.allTypes[strings.ToLower(t)] { + return true + } + } + return false +} + +func (g *wave3SchemaGraph) resolve(v any) map[string]any { + m, ok := v.(map[string]any) + if !ok || m == nil { + return nil + } + if id, hasID := m["@id"].(string); hasID { + if target, found := g.byID[strings.TrimSpace(id)]; found && target != nil { + // Prefer the resolved graph node when the reference object only carries `@id` (or minimal wrapper keys). + if len(m) <= 2 && m["@type"] == nil && m["name"] == nil && m["text"] == nil && m["streetAddress"] == nil && m["latitude"] == nil { + return target + } + } + } + return m +} + +func (g *wave3SchemaGraph) resolveList(v any) []map[string]any { + switch x := v.(type) { + case map[string]any: + if r := g.resolve(x); r != nil { + return []map[string]any{r} + } + case []any: + out := make([]map[string]any, 0, len(x)) + for _, el := range x { + if r := g.resolve(el); r != nil { + out = append(out, r) + } + } + return out + } + return nil +} + +func wave3SchemaHasEntityType(ent map[string]any, targetLower string) bool { + for _, t := range normalizeSchemaTypesSchemaGo(ent["@type"]) { + if strings.ToLower(t) == targetLower { + return true + } + } + return false +} + +func wave3SchemaFindMatchingType(ent map[string]any, allowed map[string]bool) string { + for _, t := range normalizeSchemaTypesSchemaGo(ent["@type"]) { + if allowed[strings.ToLower(t)] { + return t + } + } + return "" +} + +func wave3SchemaPlain(v any, maxLen int) string { + return SanitizeSchemaPlainField(v, maxLen) +} + +func wave3SchemaFirstNonEmpty(vals ...string) string { + for _, v := range vals { + if t := strings.TrimSpace(v); t != "" { + return t + } + } + return "" +} + +func wave3SchemaJoinStrings(v any, maxItems, maxItemLen int) string { + switch x := v.(type) { + case string, json.Number, float64, int, int64: + return wave3SchemaPlain(x, maxItemLen) + case []any: + var parts []string + seen := make(map[string]bool) + for _, el := range x { + if len(parts) >= maxItems { + break + } + var s string + switch em := el.(type) { + case map[string]any: + s = wave3SchemaPlain(firstNonNilSchemaGo(em["name"], em["text"], em["value"]), maxItemLen) + default: + s = wave3SchemaPlain(el, maxItemLen) + } + if s != "" && !seen[s] { + seen[s] = true + parts = append(parts, s) + } + } + return strings.Join(parts, ", ") + case map[string]any: + return wave3SchemaPlain(firstNonNilSchemaGo(x["name"], x["text"], x["value"]), maxItemLen) + } + return "" +} + +func (g *wave3SchemaGraph) extractActorName(v any) string { + if v == nil { + return "" + } + switch x := v.(type) { + case string: + return wave3SchemaPlain(x, 180) + case map[string]any: + r := g.resolve(x) + return wave3SchemaPlain(firstNonNilSchemaGo(r["name"], r["alternateName"]), 180) + case []any: + var parts []string + for i := 0; i < len(x) && len(parts) < 5; i++ { + if n := g.extractActorName(x[i]); n != "" { + parts = append(parts, n) + } + } + return strings.Join(parts, ", ") + } + return "" +} + +func wave3SchemaValidatePrice(raw any) (string, bool) { + switch v := raw.(type) { + case json.Number: + if f, err := v.Float64(); err == nil && f >= 0 { + if f == 0 { + return "0", true + } + return strings.TrimRight(strings.TrimRight(fmt.Sprintf("%.2f", f), "0"), "."), true + } + case float64: + if v >= 0 { + if v == 0 { + return "0", true + } + return strings.TrimRight(strings.TrimRight(fmt.Sprintf("%.2f", v), "0"), "."), true + } + case int: + if v >= 0 { + return strconv.Itoa(v), true + } + case string: + s := strings.TrimSpace(strings.TrimPrefix(v, "$")) + s = strings.ReplaceAll(s, ",", "") + if s == "" { + return "", false + } + if f, err := strconv.ParseFloat(s, 64); err == nil && f >= 0 { + if f == 0 { + return "0", true + } + return strings.TrimRight(strings.TrimRight(fmt.Sprintf("%.2f", f), "0"), "."), true + } + } + return "", false +} + +func wave3SchemaValidateCurrency(raw string) string { + c := strings.ToUpper(strings.TrimSpace(raw)) + if wave3SchemaRxCurrency3.MatchString(c) { + return c + } + return "" +} + +type wave3SchemaOfferInfo struct { + PriceText string + Price string + Currency string + URL string + Seller string +} + +func (g *wave3SchemaGraph) extractOffer(raw any, baseURL string) wave3SchemaOfferInfo { + var offerMap map[string]any + switch x := raw.(type) { + case map[string]any: + offerMap = g.resolve(x) + case []any: + for _, el := range x { + if m := g.resolve(el); m != nil { + offerMap = m + break + } + } + } + if offerMap == nil { + return wave3SchemaOfferInfo{} + } + var info wave3SchemaOfferInfo + priceRaw := firstNonNilSchemaGo(offerMap["price"], offerMap["lowPrice"]) + if p, ok := wave3SchemaValidatePrice(priceRaw); ok { + info.Price = p + info.Currency = wave3SchemaValidateCurrency(wave3SchemaPlain(offerMap["priceCurrency"], 10)) + if info.Currency != "" { + info.PriceText = info.Price + " " + info.Currency + } else { + info.PriceText = info.Price + } + } + info.URL = SanitizeSchemaHTTPSURL(offerMap["url"], baseURL) + info.Seller = g.extractActorName(offerMap["seller"]) + return info +} + +func wave3SchemaExtractRating(raw any) string { + m, ok := raw.(map[string]any) + if !ok || m == nil { + return "" + } + val := wave3SchemaPlain(m["ratingValue"], 24) + if val == "" { + return "" + } + best := wave3SchemaPlain(m["bestRating"], 16) + cnt := wave3SchemaPlain(firstNonNilSchemaGo(m["ratingCount"], m["reviewCount"]), 24) + out := val + if best != "" { + out += " / " + best + } else { + out += " / 5" + } + if cnt != "" { + out += " (" + cnt + " reviews)" + } + return out +} + +func (g *wave3SchemaGraph) formatAddress(raw any) string { + switch x := raw.(type) { + case string: + return wave3SchemaPlain(x, 260) + case map[string]any: + addr := g.resolve(x) + if addr == nil { + return "" + } + street := wave3SchemaPlain(addr["streetAddress"], 140) + city := wave3SchemaPlain(addr["addressLocality"], 80) + region := wave3SchemaPlain(addr["addressRegion"], 80) + postal := wave3SchemaPlain(addr["postalCode"], 32) + country := "" + switch c := addr["addressCountry"].(type) { + case string: + country = wave3SchemaPlain(c, 64) + case map[string]any: + country = wave3SchemaPlain(firstNonNilSchemaGo(c["name"], c["alternateName"]), 64) + } + var parts []string + if street != "" { + parts = append(parts, street) + } + cityReg := strings.TrimSpace(strings.Trim(city+", "+region, ", ")) + if postal != "" { + if cityReg != "" { + cityReg += " " + postal + } else { + cityReg = postal + } + } + if cityReg != "" { + parts = append(parts, cityReg) + } + if country != "" { + parts = append(parts, country) + } + if len(parts) > 0 { + return strings.Join(parts, ", ") + } + return wave3SchemaPlain(addr["name"], 200) + } + return "" +} + +func wave3SchemaRenderMarkdown(title string, bullets, sections []string) string { + var blocks []string + if title != "" { + blocks = append(blocks, "# "+escapeDeclMarkdownBrackets(title)) + } + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + for _, sec := range sections { + if t := strings.TrimSpace(sec); t != "" { + blocks = append(blocks, t) + } + } + return strings.TrimSpace(strings.Join(blocks, "\n\n")) +} + +// ── #234 schema-recipe ────────────────────────────────────────────────────────────────────────── + +// ── #237 schema-vehicle ───────────────────────────────────────────────────────────────────────── + +var wave3SchemaVehicleTypes = map[string]bool{ + "vehicle": true, + "car": true, + "motorcycle": true, + "motorizedbicycle": true, +} + +func (g *wave3SchemaGraph) extractMileage(raw any) string { + switch x := raw.(type) { + case string, json.Number, float64, int: + return wave3SchemaPlain(x, 40) + case map[string]any: + m := g.resolve(x) + if m == nil { + return "" + } + val := wave3SchemaPlain(m["value"], 32) + if val == "" { + return "" + } + unit := wave3SchemaPlain(firstNonNilSchemaGo(m["unitText"], m["unitCode"]), 16) + if strings.EqualFold(unit, "SMI") { + unit = "mi" + } else if strings.EqualFold(unit, "KMT") { + unit = "km" + } + if unit != "" { + return val + " " + unit + } + return val + } + return "" +} + +func wave3SchemaExtractVehicle(g *wave3SchemaGraph, rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + if wave3SchemaHasCommercePlatformMarkers(rawHTML) { + return nil + } + for _, ent := range g.entities { + if (wave3SchemaHasEntityType(ent, "product") || wave3SchemaHasEntityType(ent, "productgroup")) && + wave3SchemaFindMatchingType(ent, wave3SchemaVehicleTypes) == "" { + return nil + } + } + for _, ent := range g.nestedEntities { + if (wave3SchemaHasEntityType(ent, "product") || wave3SchemaHasEntityType(ent, "productgroup")) && + wave3SchemaFindMatchingType(ent, wave3SchemaVehicleTypes) == "" { + return nil + } + } + + type vehItem struct { + schemaType string + name string + vin string + make string + model string + year string + mileage string + priceText string + color string + trans string + seller string + url string + desc string + } + + var items []vehItem + seen := make(map[string]bool) + + scanList := func(list []map[string]any) { + for _, ent := range list { + matchedType := wave3SchemaFindMatchingType(ent, wave3SchemaVehicleTypes) + rawVIN := jsonScalarToString(firstNonNilSchemaGo(ent["vehicleIdentificationNumber"], ent["vin"])) + makeVal := g.extractActorName(firstNonNilSchemaGo(ent["brand"], ent["make"])) + modelVal := wave3SchemaPlain(ent["model"], 100) + if modelVal == "" { + if mm, ok := ent["model"].(map[string]any); ok { + modelVal = wave3SchemaPlain(mm["name"], 100) + } + } + if matchedType == "" { + if rawVIN != "" && (makeVal != "" || modelVal != "") { + matchedType = "Vehicle" + } else { + continue + } + } + + // Rule 4: strict 17-char VIN validation excluding I/O/Q; invalid VINs MUST be omitted. + validVIN := wave2cHTValidateVIN(rawVIN) + + yearStr := "" + if yr, okY := wave2cHTValidateYear(firstNonNilSchemaGo(ent["vehicleModelDate"], ent["modelDate"], ent["year"])); okY { + yearStr = strconv.Itoa(yr) + } + name := wave3SchemaPlain(firstNonNilSchemaGo(ent["name"], ent["headline"]), 220) + if name == "" { + parts := []string{} + if yearStr != "" { + parts = append(parts, yearStr) + } + if makeVal != "" { + parts = append(parts, makeVal) + } + if modelVal != "" { + parts = append(parts, modelVal) + } + name = strings.Join(parts, " ") + } + if name == "" { + continue + } + vURL := SanitizeSchemaHTTPSURL(ent["url"], baseURL) + dedupe := wave3SchemaFirstNonEmpty(validVIN, vURL, name) + if seen[dedupe] { + continue + } + seen[dedupe] = true + if len(items) >= wave3SchemaMaxRecordsCap { + break + } + offer := g.extractOffer(ent["offers"], baseURL) + items = append(items, vehItem{ + schemaType: matchedType, + name: name, + vin: validVIN, + make: makeVal, + model: modelVal, + year: yearStr, + mileage: g.extractMileage(ent["mileageFromOdometer"]), + priceText: offer.PriceText, + color: wave3SchemaPlain(ent["color"], 64), + trans: wave3SchemaPlain(ent["vehicleTransmission"], 64), + seller: wave3SchemaFirstNonEmpty(g.extractActorName(ent["seller"]), offer.Seller), + url: vURL, + desc: wave3SchemaPlain(ent["description"], 800), + }) + } + } + scanList(g.entities) + if len(items) == 0 && len(g.nestedEntities) > 0 { + scanList(g.nestedEntities) + } + if len(items) == 0 { + return nil + } + + records := make([]map[string]any, 0, len(items)) + var links []string + seenLink := make(map[string]bool) + for _, it := range items { + rec := map[string]any{ + "kind": "Vehicle", + "schemaType": it.schemaType, + "name": it.name, + } + if it.vin != "" { + rec["vin"] = it.vin + } + if it.make != "" { + rec["make"] = it.make + } + if it.model != "" { + rec["model"] = it.model + } + if it.year != "" { + rec["year"] = it.year + } + if it.mileage != "" { + rec["mileage"] = it.mileage + } + if it.priceText != "" { + rec["price"] = it.priceText + } + if it.seller != "" { + rec["seller"] = it.seller + } + if it.url != "" { + rec["url"] = it.url + if !seenLink[it.url] { + seenLink[it.url] = true + links = append(links, it.url) + } + } + records = append(records, rec) + } + + var title, desc, md string + if len(items) == 1 { + v := items[0] + title = v.name + desc = v.desc + bullets := []string{"- **Schema Type**: " + v.schemaType} + if v.vin != "" { + bullets = append(bullets, "- **VIN**: `"+v.vin+"`") + } + if v.make != "" { + bullets = append(bullets, "- **Make**: "+escapeDeclMarkdownBrackets(v.make)) + } + if v.model != "" { + bullets = append(bullets, "- **Model**: "+escapeDeclMarkdownBrackets(v.model)) + } + if v.year != "" { + bullets = append(bullets, "- **Year**: "+v.year) + } + if v.mileage != "" { + bullets = append(bullets, "- **Mileage**: "+escapeDeclMarkdownBrackets(v.mileage)) + } + if v.priceText != "" { + bullets = append(bullets, "- **Price**: "+v.priceText) + } + if v.color != "" { + bullets = append(bullets, "- **Color**: "+escapeDeclMarkdownBrackets(v.color)) + } + if v.trans != "" { + bullets = append(bullets, "- **Transmission**: "+escapeDeclMarkdownBrackets(v.trans)) + } + if v.seller != "" { + bullets = append(bullets, "- **Seller**: "+escapeDeclMarkdownBrackets(v.seller)) + } + if v.url != "" { + bullets = append(bullets, "- **URL**: "+v.url) + } + var sections []string + if v.desc != "" { + sections = append(sections, escapeDeclMarkdownBlock(v.desc)) + } + md = wave3SchemaRenderMarkdown(title, bullets, sections) + } else { + pageTitle := wave3SchemaPlain(extractTitleLinearQuick(rawHTML), 200) + title = wave3SchemaFirstNonEmpty(pageTitle, fmt.Sprintf("Vehicles (%d)", len(items))) + bullets := []string{ + "- **Schema Type**: Vehicle", + fmt.Sprintf("- **Vehicles Extracted**: %d", len(items)), + } + var rows []string + for _, v := range items { + vinCell := "-" + if v.vin != "" { + vinCell = "`" + v.vin + "`" + } + rows = append(rows, fmt.Sprintf("| %s | %s | %s | %s |", + escapeDeclMarkdownBrackets(v.name), + vinCell, + wave3SchemaFirstNonEmpty(v.mileage, "-"), + wave3SchemaFirstNonEmpty(v.priceText, "-"), + )) + } + sec := "## Vehicles\n\n| Vehicle | VIN | Mileage | Price |\n|---|---|---|---|\n" + strings.Join(rows, "\n") + md = wave3SchemaRenderMarkdown(title, bullets, []string{sec}) + } + + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: md, + Links: links, + Records: records, + } +} + +// ── #238 schema-faq-howto ─────────────────────────────────────────────────────────────────────── + +func wave3SchemaExtractFAQHowTo(g *wave3SchemaGraph, rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + // CRITICAL YIELD (`f` < `r`): must yield when domain-specific vertical Schema.org types are present. + if g.hasAnyType( + "recipe", + "product", "productgroup", + "jobposting", + "course", "courseinstance", "educationaloccupationalprogram", + "softwareapplication", "webapplication", "mobileapplication", + "medicalwebpage", "medicalcondition", "drug", "physician", "medicalclinic", + "dataset", "datacatalog", + "vehicle", "car", "motorcycle", "motorizedbicycle", + "event", "sportsevent", "musicevent", "educationevent", "businessevent", "socialevent", "theaterevent", "festival", + ) { + return nil + } + + var faqEnt map[string]any + var howToEnt map[string]any + for _, ent := range g.entities { + if faqEnt == nil && wave3SchemaHasEntityType(ent, "faqpage") { + faqEnt = ent + } + if howToEnt == nil && wave3SchemaHasEntityType(ent, "howto") { + howToEnt = ent + } + } + + if faqEnt != nil { + if res := wave3SchemaBuildFAQResult(g, faqEnt, rawHTML, baseURL, extractorID); res != nil { + return res + } + } + if howToEnt != nil { + if res := wave3SchemaBuildHowToResult(g, howToEnt, baseURL, extractorID); res != nil { + return res + } + } + return nil +} + +func wave3SchemaBuildFAQResult(g *wave3SchemaGraph, faq map[string]any, rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + qNodes := g.resolveList(firstNonNilSchemaGo(faq["mainEntity"], faq["hasPart"])) + if len(qNodes) == 0 { + for _, ent := range g.entities { + if wave3SchemaHasEntityType(ent, "question") && (ent["acceptedAnswer"] != nil || ent["suggestedAnswer"] != nil) { + qNodes = append(qNodes, ent) + } + } + } + if len(qNodes) == 0 { + return nil + } + + var records []map[string]any + var qaBlocks []string + for i := 0; i < len(qNodes) && len(records) < wave3SchemaMaxListItems; i++ { + q := g.resolve(qNodes[i]) + if q == nil { + continue + } + qText := wave3SchemaPlain(firstNonNilSchemaGo(q["name"], q["headline"], q["text"]), 400) + if qText == "" { + continue + } + ansRaw := q["acceptedAnswer"] + if ansRaw == nil { + if arr, ok := q["suggestedAnswer"].([]any); ok && len(arr) > 0 { + ansRaw = arr[0] + } else { + ansRaw = q["suggestedAnswer"] + } + } + var ansSrc any + if ansObj := g.resolve(ansRaw); ansObj != nil { + ansSrc = firstNonNilSchemaGo(ansObj["text"], ansObj["articleBody"], ansObj["name"]) + } else { + ansSrc = firstNonNilSchemaGo(ansRaw, q["answer"]) + } + ansPlain := wave3SchemaPlain(ansSrc, 2000) + if ansPlain == "" { + continue + } + rec := map[string]any{ + "kind": "Question", + "position": len(records) + 1, + "question": qText, + "answer": ansPlain, + } + if qURL := SanitizeSchemaHTTPSURL(q["url"], baseURL); qURL != "" { + rec["url"] = qURL + } + records = append(records, rec) + qaBlocks = append(qaBlocks, fmt.Sprintf("### %s\n\n%s", escapeDeclMarkdownBrackets(qText), escapeDeclMarkdownBlock(ansPlain))) + } + if len(records) == 0 { + return nil + } + + title := wave3SchemaFirstNonEmpty( + wave3SchemaPlain(firstNonNilSchemaGo(faq["name"], faq["headline"]), 220), + wave3SchemaPlain(extractTitleLinearQuick(rawHTML), 220), + "FAQ", + ) + desc := wave3SchemaPlain(faq["description"], 800) + bullets := []string{ + "- **Schema Type**: FAQPage", + fmt.Sprintf("- **Questions**: %d", len(records)), + } + var sections []string + if desc != "" { + sections = append(sections, escapeDeclMarkdownBlock(desc)) + } + sections = append(sections, "## Questions & Answers\n\n"+strings.Join(qaBlocks, "\n\n")) + var links []string + if u := SanitizeSchemaHTTPSURL(faq["url"], baseURL); u != "" { + links = append(links, u) + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: wave3SchemaRenderMarkdown(title, bullets, sections), + Links: links, + Records: records, + } +} + +func wave3SchemaBuildHowToResult(g *wave3SchemaGraph, howto map[string]any, baseURL, extractorID string) *DeclarativePostFetchResult { + title := wave3SchemaPlain(firstNonNilSchemaGo(howto["name"], howto["headline"]), 240) + if title == "" { + return nil + } + desc := wave3SchemaPlain(howto["description"], 1000) + totalTime := wave3SchemaPlain(firstNonNilSchemaGo(howto["totalTime"], howto["performTime"]), 60) + + collectNamed := func(raw any) []string { + var out []string + switch x := raw.(type) { + case string: + if s := wave3SchemaPlain(x, 180); s != "" { + out = append(out, s) + } + case map[string]any: + if s := wave3SchemaPlain(firstNonNilSchemaGo(x["name"], x["text"]), 180); s != "" { + out = append(out, s) + } + case []any: + for _, el := range x { + if len(out) >= 40 { + break + } + switch em := el.(type) { + case string: + if s := wave3SchemaPlain(em, 180); s != "" { + out = append(out, s) + } + case map[string]any: + if s := wave3SchemaPlain(firstNonNilSchemaGo(em["name"], em["text"]), 180); s != "" { + out = append(out, s) + } + } + } + } + return out + } + + supplies := collectNamed(howto["supply"]) + tools := collectNamed(howto["tool"]) + + var stepRecords []map[string]any + var stepLines []string + var pushStep func(raw any, sectionName string) + pushStep = func(raw any, sectionName string) { + if raw == nil || len(stepRecords) >= wave3SchemaMaxListItems { + return + } + switch st := raw.(type) { + case string: + txt := wave3SchemaPlain(st, 1500) + if txt == "" { + return + } + pos := len(stepRecords) + 1 + rec := map[string]any{"kind": "HowToStep", "position": pos, "text": txt} + if sectionName != "" { + rec["section"] = sectionName + } + stepRecords = append(stepRecords, rec) + stepLines = append(stepLines, fmt.Sprintf("%d. %s", pos, escapeDeclMarkdownBrackets(txt))) + case []any: + for _, sub := range st { + pushStep(sub, sectionName) + } + case map[string]any: + m := g.resolve(st) + if m == nil { + return + } + if subItems, ok := m["itemListElement"].([]any); ok && len(subItems) > 0 && m["text"] == nil { + secTitle := wave3SchemaPlain(m["name"], 180) + if secTitle != "" { + stepLines = append(stepLines, "### "+escapeDeclMarkdownBrackets(secTitle)) + } + pushStep(subItems, wave3SchemaFirstNonEmpty(secTitle, sectionName)) + return + } + stepTitle := wave3SchemaPlain(m["name"], 200) + stepText := wave3SchemaPlain(firstNonNilSchemaGo(m["text"], m["description"]), 1500) + if stepText == "" && stepTitle == "" { + return + } + pos := len(stepRecords) + 1 + rec := map[string]any{"kind": "HowToStep", "position": pos} + if sectionName != "" { + rec["section"] = sectionName + } + if stepTitle != "" { + rec["title"] = stepTitle + } + if stepText != "" { + rec["text"] = stepText + } + if su := SanitizeSchemaHTTPSURL(m["url"], baseURL); su != "" { + rec["url"] = su + } + stepRecords = append(stepRecords, rec) + if stepTitle != "" && stepTitle != stepText && stepText != "" { + stepLines = append(stepLines, fmt.Sprintf("%d. **%s** — %s", pos, escapeDeclMarkdownBrackets(stepTitle), escapeDeclMarkdownBrackets(stepText))) + } else { + stepLines = append(stepLines, fmt.Sprintf("%d. %s", pos, escapeDeclMarkdownBrackets(wave3SchemaFirstNonEmpty(stepText, stepTitle)))) + } + } + } + pushStep(firstNonNilSchemaGo(howto["step"], howto["steps"]), "") + + if len(stepRecords) == 0 && desc == "" { + return nil + } + + bullets := []string{"- **Schema Type**: HowTo"} + if totalTime != "" { + bullets = append(bullets, "- **Total Time**: "+totalTime) + } + if len(supplies) > 0 { + bullets = append(bullets, "- **Supplies**: "+escapeDeclMarkdownBrackets(strings.Join(supplies, ", "))) + } + if len(tools) > 0 { + bullets = append(bullets, "- **Tools**: "+escapeDeclMarkdownBrackets(strings.Join(tools, ", "))) + } + if len(stepRecords) > 0 { + bullets = append(bullets, fmt.Sprintf("- **Steps**: %d", len(stepRecords))) + } + + var sections []string + if desc != "" { + sections = append(sections, escapeDeclMarkdownBlock(desc)) + } + if len(stepLines) > 0 { + sections = append(sections, "## Steps\n\n"+strings.Join(stepLines, "\n")) + } + var links []string + if u := SanitizeSchemaHTTPSURL(howto["url"], baseURL); u != "" { + links = append(links, u) + } + out := &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: wave3SchemaRenderMarkdown(title, bullets, sections), + Links: links, + } + if len(stepRecords) > 0 { + out.Records = stepRecords + } + return out +} + +// ── #239 schema-dataset ───────────────────────────────────────────────────────────────────────── + +func wave3SchemaExtractDataset(g *wave3SchemaGraph, rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + if wave3SchemaHasCommercePlatformMarkers(rawHTML) || g.hasAnyType("product", "productgroup") { + return nil + } + var ds map[string]any + var dsType string + for _, ent := range g.entities { + if wave3SchemaHasEntityType(ent, "dataset") { + ds = ent + dsType = "Dataset" + break + } + } + if ds == nil { + for _, ent := range g.entities { + if wave3SchemaHasEntityType(ent, "datacatalog") { + ds = ent + dsType = "DataCatalog" + break + } + } + } + if ds == nil { + return nil + } + + name := wave3SchemaPlain(firstNonNilSchemaGo(ds["name"], ds["headline"]), 260) + if name == "" { + return nil + } + desc := SanitizeSchemaRichMarkdown(ds["description"], baseURL, nil, 8000) + descPlain := wave3SchemaPlain(ds["description"], 512) + creator := g.extractActorName(firstNonNilSchemaGo(ds["creator"], ds["publisher"], ds["sourceOrganization"])) + license := "" + switch lv := ds["license"].(type) { + case string: + license = wave3SchemaPlain(lv, 400) + case map[string]any: + lm := g.resolve(lv) + license = wave3SchemaPlain(firstNonNilSchemaGo(lm["name"], lm["url"]), 400) + } + temporal := wave3SchemaJoinStrings(ds["temporalCoverage"], 3, 120) + spatial := wave3SchemaJoinStrings(ds["spatialCoverage"], 4, 120) + identifier := "" + switch iv := ds["identifier"].(type) { + case string, json.Number, float64, int: + identifier = wave3SchemaPlain(iv, 160) + case map[string]any: + identifier = wave3SchemaPlain(firstNonNilSchemaGo(iv["value"], iv["name"], iv["url"]), 160) + case []any: + identifier = wave3SchemaJoinStrings(iv, 3, 120) + } + + bullets := []string{"- **Schema Type**: " + dsType} + if creator != "" { + bullets = append(bullets, "- **Creator**: "+escapeDeclMarkdownBrackets(creator)) + } + if identifier != "" { + bullets = append(bullets, "- **Identifier**: `"+identifier+"`") + } + if temporal != "" { + bullets = append(bullets, "- **Temporal Coverage**: "+escapeDeclMarkdownBrackets(temporal)) + } + if spatial != "" { + bullets = append(bullets, "- **Spatial Coverage**: "+escapeDeclMarkdownBrackets(spatial)) + } + if license != "" { + bullets = append(bullets, "- **License**: "+escapeDeclMarkdownBrackets(license)) + } + + var distRecords []map[string]any + var distRows []string + var links []string + seenLink := make(map[string]bool) + addLink := func(u string) { + if u != "" && !seenLink[u] { + seenLink[u] = true + links = append(links, u) + } + } + if u := SanitizeSchemaHTTPSURL(ds["url"], baseURL); u != "" { + addLink(u) + } + + for _, dist := range g.resolveList(ds["distribution"]) { + if len(distRecords) >= wave3SchemaMaxRecordsCap { + break + } + dURL := SanitizeSchemaHTTPSURL(firstNonNilSchemaGo(dist["contentUrl"], dist["url"]), baseURL) + fmtStr := wave3SchemaPlain(firstNonNilSchemaGo(dist["encodingFormat"], dist["fileFormat"]), 64) + sizeStr := wave3SchemaPlain(dist["contentSize"], 48) + dName := wave3SchemaPlain(dist["name"], 140) + if dURL == "" && fmtStr == "" && dName == "" { + continue + } + rec := map[string]any{"kind": "DataDownload"} + if dName != "" { + rec["name"] = dName + } + if dURL != "" { + rec["contentUrl"] = dURL + addLink(dURL) + } + if fmtStr != "" { + rec["encodingFormat"] = fmtStr + } + if sizeStr != "" { + rec["contentSize"] = sizeStr + } + distRecords = append(distRecords, rec) + label := wave3SchemaFirstNonEmpty(dName, fmtStr, "Download") + urlCell := "-" + if dURL != "" { + urlCell = fmt.Sprintf("[%s](%s)", escapeMarkdownLinkLabelGo(label), PercentEncodeUnsafeRecordURLChars(dURL)) + } else { + urlCell = escapeDeclMarkdownBrackets(label) + } + distRows = append(distRows, fmt.Sprintf("| %s | %s | %s |", + urlCell, + escapeDeclMarkdownBrackets(wave3SchemaFirstNonEmpty(fmtStr, "-")), + escapeDeclMarkdownBrackets(wave3SchemaFirstNonEmpty(sizeStr, "-")), + )) + } + + var sections []string + if desc != "" { + sections = append(sections, desc) + } + if len(distRows) > 0 { + sections = append(sections, "## Distributions\n\n| Distribution | Format | Size |\n|---|---|---|\n"+strings.Join(distRows, "\n")) + } + + md := wave3SchemaRenderMarkdown(name, bullets, sections) + if md == "" { + return nil + } + out := &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: name, + Description: descPlain, + Author: creator, + Markdown: md, + Links: links, + } + if len(distRecords) > 0 { + out.Records = distRecords + } + return out +} + +// ── #240 schema-software-app ──────────────────────────────────────────────────────────────────── + +var wave3SchemaSoftwareTypes = map[string]bool{ + "softwareapplication": true, + "webapplication": true, + "mobileapplication": true, +} + +func wave3SchemaExtractSoftwareApp(g *wave3SchemaGraph, rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + if wave3SchemaHasCommercePlatformMarkers(rawHTML) || g.hasAnyType("product", "productgroup") { + return nil + } + var app map[string]any + var appType string + for _, ent := range g.entities { + if mt := wave3SchemaFindMatchingType(ent, wave3SchemaSoftwareTypes); mt != "" { + app = ent + appType = mt + break + } + } + if app == nil { + return nil + } + + name := wave3SchemaPlain(firstNonNilSchemaGo(app["name"], app["headline"]), 220) + if name == "" { + return nil + } + version := wave3SchemaPlain(firstNonNilSchemaGo(app["softwareVersion"], app["version"]), 64) + osList := wave3SchemaJoinStrings(app["operatingSystem"], 8, 64) + category := wave3SchemaJoinStrings(app["applicationCategory"], 4, 80) + subCategory := wave3SchemaPlain(app["applicationSubCategory"], 80) + author := g.extractActorName(firstNonNilSchemaGo(app["author"], app["publisher"], app["creator"])) + offer := g.extractOffer(app["offers"], baseURL) + rating := wave3SchemaExtractRating(app["aggregateRating"]) + downloadURL := SanitizeSchemaHTTPSURL(firstNonNilSchemaGo(app["downloadUrl"], app["installUrl"]), baseURL) + appURL := SanitizeSchemaHTTPSURL(app["url"], baseURL) + desc := wave3SchemaPlain(app["description"], 1200) + + bullets := []string{"- **Schema Type**: " + appType} + if version != "" { + bullets = append(bullets, "- **Version**: `"+version+"`") + } + if osList != "" { + bullets = append(bullets, "- **Operating System**: "+escapeDeclMarkdownBrackets(osList)) + } + if category != "" { + catText := category + if subCategory != "" && subCategory != category { + catText += " (" + subCategory + ")" + } + bullets = append(bullets, "- **Category**: "+escapeDeclMarkdownBrackets(catText)) + } + if offer.PriceText != "" { + bullets = append(bullets, "- **Price**: "+offer.PriceText) + } + if rating != "" { + bullets = append(bullets, "- **Rating**: "+rating) + } + if author != "" { + bullets = append(bullets, "- **Publisher**: "+escapeDeclMarkdownBrackets(author)) + } + if downloadURL != "" { + bullets = append(bullets, "- **Download URL**: "+downloadURL) + } + + var sections []string + if desc != "" { + sections = append(sections, escapeDeclMarkdownBlock(desc)) + } + var links []string + seenLink := make(map[string]bool) + for _, cand := range []string{downloadURL, appURL, offer.URL} { + if cand != "" && !seenLink[cand] { + seenLink[cand] = true + links = append(links, cand) + } + } + + rec := map[string]any{ + "kind": "SoftwareApplication", + "schemaType": appType, + "name": name, + } + if version != "" { + rec["version"] = version + } + if osList != "" { + rec["operatingSystem"] = osList + } + if category != "" { + rec["applicationCategory"] = category + } + if offer.PriceText != "" { + rec["price"] = offer.PriceText + } + if author != "" { + rec["author"] = author + } + if downloadURL != "" { + rec["downloadUrl"] = downloadURL + } + + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: name, + Description: desc, + Author: author, + Markdown: wave3SchemaRenderMarkdown(name, bullets, sections), + Links: links, + Records: []map[string]any{rec}, + } +} + +// ── #241 schema-medical ───────────────────────────────────────────────────────────────────────── + +var wave3SchemaMedicalPriority = []string{ + "medicalcondition", + "drug", + "physician", + "medicalclinic", + "medicalwebpage", +} + +func wave3SchemaExtractMedical(g *wave3SchemaGraph, rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + if g.hasAnyType("product", "productgroup") { + return nil + } + + var med map[string]any + var medType string + for _, target := range wave3SchemaMedicalPriority { + for _, ent := range g.entities { + for _, t := range normalizeSchemaTypesSchemaGo(ent["@type"]) { + if strings.ToLower(t) == target { + med = ent + medType = t + break + } + } + if med != nil { + break + } + } + if med != nil { + break + } + } + if med == nil { + return nil + } + + name := wave3SchemaPlain(firstNonNilSchemaGo(med["name"], med["headline"]), 240) + if name == "" { + if about := g.resolve(med["about"]); about != nil { + name = wave3SchemaPlain(firstNonNilSchemaGo(about["name"], about["headline"]), 240) + } + } + if name == "" { + return nil + } + + headline := wave3SchemaPlain(med["headline"], 260) + desc := wave3SchemaPlain(med["description"], 1200) + specialty := wave3SchemaJoinStrings(med["medicalSpecialty"], 6, 80) + symptoms := wave3SchemaJoinStrings(med["signOrSymptom"], 12, 100) + treatments := wave3SchemaJoinStrings(med["possibleTreatment"], 12, 100) + activeIng := wave3SchemaJoinStrings(med["activeIngredient"], 6, 100) + dosageForm := wave3SchemaPlain(med["dosageForm"], 80) + nonProp := wave3SchemaPlain(med["nonProprietaryName"], 120) + addr := g.formatAddress(med["address"]) + tel := wave3SchemaPlain(med["telephone"], 60) + reviewed := wave3SchemaPlain(firstNonNilSchemaGo(med["lastReviewed"], med["dateModified"], med["datePublished"]), 64) + author := g.extractActorName(firstNonNilSchemaGo(med["author"], med["publisher"])) + u := SanitizeSchemaHTTPSURL(med["url"], baseURL) + + bullets := []string{"- **Schema Type**: " + medType} + if headline != "" && headline != name { + bullets = append(bullets, "- **Headline**: "+escapeDeclMarkdownBrackets(headline)) + } + if specialty != "" { + bullets = append(bullets, "- **Medical Specialty**: "+escapeDeclMarkdownBrackets(specialty)) + } + if activeIng != "" { + bullets = append(bullets, "- **Active Ingredient**: "+escapeDeclMarkdownBrackets(activeIng)) + } + if nonProp != "" { + bullets = append(bullets, "- **Non-Proprietary Name**: "+escapeDeclMarkdownBrackets(nonProp)) + } + if dosageForm != "" { + bullets = append(bullets, "- **Dosage Form**: "+escapeDeclMarkdownBrackets(dosageForm)) + } + if symptoms != "" { + bullets = append(bullets, "- **Signs or Symptoms**: "+escapeDeclMarkdownBrackets(symptoms)) + } + if treatments != "" { + bullets = append(bullets, "- **Possible Treatments**: "+escapeDeclMarkdownBrackets(treatments)) + } + if addr != "" { + bullets = append(bullets, "- **Address**: "+escapeDeclMarkdownBrackets(addr)) + } + if tel != "" { + bullets = append(bullets, "- **Telephone**: "+escapeDeclMarkdownBrackets(tel)) + } + if reviewed != "" { + bullets = append(bullets, "- **Last Reviewed / Modified**: "+reviewed) + } + if author != "" { + bullets = append(bullets, "- **Publisher**: "+escapeDeclMarkdownBrackets(author)) + } + + var sections []string + if desc != "" { + sections = append(sections, escapeDeclMarkdownBlock(desc)) + } + var links []string + if u != "" { + links = append(links, u) + } + rec := map[string]any{ + "kind": "MedicalEntity", + "schemaType": medType, + "name": name, + } + if specialty != "" { + rec["medicalSpecialty"] = specialty + } + if activeIng != "" { + rec["activeIngredient"] = activeIng + } + if dosageForm != "" { + rec["dosageForm"] = dosageForm + } + if addr != "" { + rec["address"] = addr + } + if tel != "" { + rec["telephone"] = tel + } + if reviewed != "" { + rec["lastReviewed"] = reviewed + } + + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: name, + Description: desc, + Author: author, + PublishedTime: reviewed, + Markdown: wave3SchemaRenderMarkdown(name, bullets, sections), + Links: links, + Records: []map[string]any{rec}, + } +} diff --git a/internal/extract/wave3_schema_test.go b/internal/extract/wave3_schema_test.go new file mode 100644 index 0000000..e892060 --- /dev/null +++ b/internal/extract/wave3_schema_test.go @@ -0,0 +1,492 @@ +package extract + +import ( + "fmt" + "strings" + "testing" + + "github.com/bartrumb/edgefetch/v2/internal/classify" +) + +func TestWave3SchemaAllEightAdaptersPositive(t *testing.T) { + // 1. #234 schema-recipe (including HowToSection + HowToStep, nutrition, aggregateRating) + recipeHTML := `Chewy Cookies

Chewy Chocolate Chip Cookies

` + + recRes := Round2RunHTML("schema_recipe_html", recipeHTML, "https://sallysbakingaddiction.com/chewy-chocolate-chip-cookies/", "") + if recRes == nil || recRes.ExtractorID != "schema-recipe" { + t.Fatalf("schema-recipe positive failed: %+v", recRes) + } + for _, want := range []string{"Sally McKenney", "15 min", "13 min", "2 hr 45 min", "2 1/4 cups flour", "Dough", "Whisk dry ingredients together.", "210 kcal", "4.7"} { + if !strings.Contains(recRes.Markdown, want) { + t.Fatalf("schema-recipe markdown missing %q:\n%s", want, recRes.Markdown) + } + } + + // 2. #235 schema-event (single event + multi-event cap at 50) + singleEventHTML := `Jazz Night

Blue Note Jazz Night

` + evRes := Round2RunHTML("schema_event_html", singleEventHTML, "https://events.example.edu/jazz-night", "") + if evRes == nil || evRes.ExtractorID != "schema-event" { + t.Fatalf("schema-event single failed: %+v", evRes) + } + for _, want := range []string{"Blue Note Jazz Night", "2026-12-10T20:00:00-05:00", "Main Hall", "Campus Arts", "25 USD", "EventScheduled"} { + if !strings.Contains(evRes.Markdown, want) { + t.Fatalf("schema-event markdown missing %q:\n%s", want, evRes.Markdown) + } + } + + // Multi-event cap at round2MaxRecords (55 input events -> Returned=50, Total=55, Truncated=true) + var evObjs []string + for i := 1; i <= 55; i++ { + evObjs = append(evObjs, fmt.Sprintf(`{"@type":"Event","name":"Campus Talk %d","startDate":"2026-12-%02dT12:00:00Z","location":{"@type":"VirtualLocation","name":"Zoom","url":"https://events.example.edu/talk/%d"}}`, i, (i%28)+1, i)) + } + multiEventHTML := `Stanford Calendar

Calendar

` + mEvRes := Round2RunHTML("schema_event_html", multiEventHTML, "https://events.stanford.edu/", "") + if mEvRes == nil || len(mEvRes.Records) != 50 || mEvRes.Total == nil || *mEvRes.Total != 55 || mEvRes.Truncated == nil || !*mEvRes.Truncated { + t.Fatalf("schema-event multi-event cap failed: records=%d total=%v trunc=%v", len(mEvRes.Records), mEvRes.Total, mEvRes.Truncated) + } + + // 3. #236 schema-localbusiness + lbHTML := `Apple Fifth Avenue

Apple Fifth Avenue

` + lbRes := Round2RunHTML("schema_localbusiness_html", lbHTML, "https://www.apple.com/retail/fifthavenue/", "") + if lbRes == nil || lbRes.ExtractorID != "schema-localbusiness" { + t.Fatalf("schema-localbusiness positive failed: %+v", lbRes) + } + for _, want := range []string{"767 Fifth Avenue", "(212) 336-1440", "40.76383, -73.97296", "09:00"} { + if !strings.Contains(lbRes.Markdown, want) { + t.Fatalf("schema-localbusiness missing %q:\n%s", want, lbRes.Markdown) + } + } + + // 4. #237 schema-vehicle (["Product","Car"], @id seller ref, and strict VIN validation) + vehHTML := `2022 Dodge Charger

2022 Dodge Charger

` + vehRes := Wave3SchemaRunHTML("schema_vehicle_html", vehHTML, "https://dealer.example.com/listings/charger-2022", "") + if vehRes == nil || vehRes.ExtractorID != "schema-vehicle" { + t.Fatalf("schema-vehicle positive failed: %+v", vehRes) + } + for _, want := range []string{"2C3CDXBG0NH250138", "Dodge", "Charger", "2022", "31500 mi", "18220 USD", "Metro Auto"} { + if !strings.Contains(vehRes.Markdown, want) { + t.Fatalf("schema-vehicle missing %q:\n%s", want, vehRes.Markdown) + } + } + + // 5. #238 schema-faq-howto (FAQPage @id graph resolution + HowTo HowToSection) + faqHTML := `Yoast FAQ

Yoast FAQ

` + faqRes := Wave3SchemaRunHTML("schema_faq_howto_html", faqHTML, "https://yoast.com/features/structured-data/faq-block/", "") + if faqRes == nil || faqRes.ExtractorID != "schema-faq-howto" || !strings.Contains(faqRes.Markdown, "Is JSON-LD supported?") || !strings.Contains(faqRes.Markdown, "Yes, natively.") { + t.Fatalf("schema-faq-howto FAQPage failed: %+v", faqRes) + } + + howToHTML := `How to Tie a Tie

How to Tie a Tie

` + htRes := Wave3SchemaRunHTML("schema_faq_howto_html", howToHTML, "https://www.wikihow.com/Tie-a-Tie", "") + if htRes == nil || htRes.ExtractorID != "schema-faq-howto" { + t.Fatalf("schema-faq-howto HowTo failed: %+v", htRes) + } + for _, want := range []string{"PT5M", "Necktie", "Mirror", "Four-in-Hand", "Drape the tie around your neck."} { + if !strings.Contains(htRes.Markdown, want) { + t.Fatalf("schema-faq-howto HowTo missing %q:\n%s", want, htRes.Markdown) + } + } + if len(htRes.Records) != 2 || htRes.Records[0]["section"] != "Four-in-Hand" { + t.Fatalf("schema-faq-howto HowTo records unexpected: %+v", htRes.Records) + } + + // 6. #239 schema-dataset + dsHTML := `NOAA GOES

NOAA GOES

` + dsRes := Wave3SchemaRunHTML("schema_dataset_html", dsHTML, "https://registry.opendata.aws/noaa-goes/", "") + if dsRes == nil || dsRes.ExtractorID != "schema-dataset" { + t.Fatalf("schema-dataset positive failed: %+v", dsRes) + } + for _, want := range []string{"NOAA", "noaa-goes", "2017-05-24/..", "North America", "application/x-netcdf", "1.2 TB"} { + if !strings.Contains(dsRes.Markdown, want) { + t.Fatalf("schema-dataset missing %q:\n%s", want, dsRes.Markdown) + } + } + + // 7. #240 schema-software-app + swHTML := `VS Code

Visual Studio Code

` + swRes := Wave3SchemaRunHTML("schema_software_app_html", swHTML, "https://code.visualstudio.com/", "") + if swRes == nil || swRes.ExtractorID != "schema-software-app" { + t.Fatalf("schema-software-app positive failed: %+v", swRes) + } + for _, want := range []string{"1.148", "Mac, Linux, Windows", "DeveloperApplication", "0 USD", "4.8 / 5 (4200 reviews)", "Microsoft", "https://code.visualstudio.com/download"} { + if !strings.Contains(swRes.Markdown, want) { + t.Fatalf("schema-software-app missing %q:\n%s", want, swRes.Markdown) + } + } + + // 8. #241 schema-medical (MedicalWebPage + Drug) + medHTML := `Asthma

Asthma

` + medRes := Wave3SchemaRunHTML("schema_medical_html", medHTML, "https://my.clevelandclinic.org/health/diseases/6424-asthma", "") + if medRes == nil || medRes.ExtractorID != "schema-medical" { + t.Fatalf("schema-medical positive failed: %+v", medRes) + } + for _, want := range []string{"Pulmonology", "Wheezing", "Inhaled corticosteroids", "2026-03-30"} { + if !strings.Contains(medRes.Markdown, want) { + t.Fatalf("schema-medical missing %q:\n%s", want, medRes.Markdown) + } + } + + drugHTML := `Albuterol

Albuterol

` + drugRes := Wave3SchemaRunHTML("schema_medical_html", drugHTML, "https://med.example.org/drugs/albuterol", "") + if drugRes == nil || !strings.Contains(drugRes.Markdown, "Albuterol sulfate") || !strings.Contains(drugRes.Markdown, "Aerosol, metered") { + t.Fatalf("schema-medical Drug failed: %+v", drugRes) + } +} + +func TestWave3SchemaAlphabeticalPrecedenceAndYields(t *testing.T) { + // 1. schema-faq-howto (`f` < `r`) MUST yield when @graph contains Recipe, Product, JobPosting, Course, SoftwareApplication, MedicalWebPage, MedicalCondition + sallyShape := `Cookies

Cookies

` + if got := Wave3SchemaRunHTML("schema_faq_howto_html", sallyShape, "https://sallysbakingaddiction.com/cookies/", ""); got != nil { + t.Fatalf("schema-faq-howto MUST yield on Recipe @graph, got %+v", got) + } + if got := Round2RunHTML("schema_recipe_html", sallyShape, "https://sallysbakingaddiction.com/cookies/", ""); got == nil || got.ExtractorID != "schema-recipe" { + t.Fatalf("schema-recipe must claim Recipe after schema-faq-howto yields, got %+v", got) + } + + for _, blockingType := range []string{"Product", "JobPosting", "Course", "SoftwareApplication", "MedicalWebPage", "MedicalCondition"} { + html := fmt.Sprintf(`Page

Page

`, blockingType) + if got := Wave3SchemaRunHTML("schema_faq_howto_html", html, "https://example.com/page", ""); got != nil { + t.Fatalf("schema-faq-howto MUST yield when %s is in @graph, got %+v", blockingType, got) + } + } + + // 2. schema-localbusiness MUST yield on Product, ProductGroup, Recipe, Event, Car, Vehicle, and commerce markers + for _, blockingType := range []string{"Product", "ProductGroup", "Recipe", "Event", "Car", "Vehicle", "MedicalClinic"} { + html := fmt.Sprintf(`Store

Shop

`, blockingType) + if got := Round2RunHTML("schema_localbusiness_html", html, "https://shop.example.com/item", ""); got != nil { + t.Fatalf("schema-localbusiness MUST yield when %s is present, got %+v", blockingType, got) + } + } + for _, marker := range []string{"Shopify.shop = 'demo.myshopify.com';", ``, ``, `https://static.wixstatic.com/media/1.png`} { + html := fmt.Sprintf(`Store

Shop

`, marker) + if got := Round2RunHTML("schema_localbusiness_html", html, "https://shop.example.com/", ""); got != nil { + t.Fatalf("schema-localbusiness MUST yield on commerce marker %q, got %+v", marker, got) + } + } + // Missing all of address/telephone/openingHours/geo -> yield + minimalLB := `Name Only

Name Only

` + if got := Round2RunHTML("schema_localbusiness_html", minimalLB, "https://example.com/", ""); got != nil { + t.Fatalf("schema-localbusiness MUST yield without address/telephone/hours/geo, got %+v", got) + } + + // 3. schema-recipe yields on Product without Recipe + productOnly := `Mug

Mug

` + if got := Round2RunHTML("schema_recipe_html", productOnly, "https://shop.example.com/products/mug", ""); got != nil { + t.Fatalf("schema-recipe MUST yield on Product without Recipe, got %+v", got) + } + + // 4. schema-medical yields when Product is present + medProduct := `Supplement

Vitamin D3

` + if got := Wave3SchemaRunHTML("schema_medical_html", medProduct, "https://shop.example.com/products/vitd", ""); got != nil { + t.Fatalf("schema-medical MUST yield when Product is present, got %+v", got) + } + + // 5. schema-event excludes eventbrite/meetup/lu.ma/luma/ticketmaster/runsignup + evHTML := `Concert

Concert

` + for _, host := range []string{"eventbrite.com", "www.meetup.com", "lu.ma", "luma.com", "www.ticketmaster.com", "runsignup.com"} { + if got := Round2RunHTML("schema_event_html", evHTML, "https://"+host+"/e/123", ""); got != nil { + t.Fatalf("schema-event MUST exclude host %s, got %+v", host, got) + } + } + + // 6. schema-vehicle strict 17-char VIN validation excluding I, O, Q + for _, badVIN := range []string{ + "1HGCM82633A00435", // 16 chars + "1HGCM82633A0043521", // 18 chars + "1HGCM826I3A004352", // contains I + "1HGCM826O3A004352", // contains O + "1HGCM826Q3A004352", // contains Q + } { + html := fmt.Sprintf(`2023 Honda Civic

2023 Honda Civic

`, badVIN) + res := Wave3SchemaRunHTML("schema_vehicle_html", html, "https://cars.example.com/civic", "") + if res == nil { + t.Fatalf("expected vehicle extraction without invalid VIN %q, got nil", badVIN) + } + if strings.Contains(res.Markdown, badVIN) { + t.Fatalf("invalid VIN %q MUST NEVER be emitted in Markdown:\n%s", badVIN, res.Markdown) + } + if _, hasVIN := res.Records[0]["vin"]; hasVIN { + t.Fatalf("invalid VIN %q MUST NEVER be emitted in Records: %+v", badVIN, res.Records[0]) + } + } +} + +func TestWave3SchemaManifestRouteExecution(t *testing.T) { + // Verify explicit manifest dispatch through ExtractHTMLOnManifest (including excludeHosts on schema-event) + eventManifest := &DeclarativeAdapterManifest{ + ID: "schema-event", + Name: "Schema.org Event & Festival", + Category: "commerce-social", + Description: "Universal Schema.org Event extractor.", + Domains: []string{"events.stanford.edu"}, + UniversalEngine: true, + AuthMode: "html", + ExampleURLs: []string{"https://events.stanford.edu/"}, + HTMLRoutes: []DeclarativeHTMLRouteSpec{ + { + ID: "schema-event", + Mode: "schema_event_html", + Match: DeclarativeMatchSpec{ + ExcludeHosts: []string{"eventbrite.com", "www.eventbrite.com", "meetup.com", "lu.ma", "luma.com", "ticketmaster.com", "runsignup.com"}, + }, + }, + }, + } + evHTML := `Stanford Talk

AI Symposium

` + out, ok := ExtractHTMLOnManifest(eventManifest, evHTML, "https://events.stanford.edu/", "", nil) + if !ok || out == nil || out.ExtractorID != "schema-event" { + t.Fatalf("ExtractHTMLOnManifest failed for schema-event: ok=%v out=%+v", ok, out) + } + if _, excludedOK := ExtractHTMLOnManifest(eventManifest, evHTML, "https://www.eventbrite.com/e/123", "", nil); excludedOK { + t.Fatalf("ExtractHTMLOnManifest must exclude eventbrite.com") + } +} + +func TestWave3SchemaNegativeShellsAndSafety(t *testing.T) { + modes := []string{ + "schema_vehicle_html", + "schema_faq_howto_html", + "schema_dataset_html", + "schema_software_app_html", + "schema_medical_html", + } + negShells := []struct { + name string + status int + url string + html string + checkStateFull bool + }{ + {"http-404", 404, "https://example.com/item", `404 Page Not Found

Not Found

`, true}, + {"error-redirect", 200, "https://example.com/error", `Site

Error

`, true}, + {"maintenance", 503, "https://example.com/item", `503 Service Unavailable

Scheduled Maintenance

Site is down for maintenance. Please check back soon.

`, true}, + {"empty-spa", 200, "https://example.com/item", `Loading...
`, true}, + {"cf-challenge", 403, "https://example.com/item", `Just a moment...
`, true}, + {"anubis-pow", 200, "https://example.com/item", `Making sure you're not a bot!

Making sure you're not a bot!

`, false}, + } + + for _, m := range modes { + for _, ns := range negShells { + if res := Wave3SchemaRunHTML(m, ns.html, ns.url, ""); res != nil { + t.Fatalf("mode %s negative %s returned non-nil: %+v", m, ns.name, res) + } + if ns.checkStateFull { + cs := classify.ClassifyContentStateFull(classify.ContentStateInput{ + Status: ns.status, + URL: "https://example.com/item", + FinalURL: ns.url, + RawHTML: ns.html, + Markdown: "", + }) + if cs.State == "active" { + t.Fatalf("negative shell %s must never classify as active", ns.name) + } + } + } + } + + // XSS / unsafe URL sanitization check (JSON-escaped

Dataset

` + xssRes := Wave3SchemaRunHTML("schema_dataset_html", xssHTML, "https://data.example.org/ds", "") + if xssRes == nil { + t.Fatalf("expected sanitized dataset result") + } + if strings.Contains(xssRes.Markdown, "

Bistro Foo

` + if got := Round2RunHTML("schema_localbusiness_html", restHasMenu, "https://bistrofoo.example.com/menu", ""); got != nil { + t.Fatalf("schema-localbusiness MUST yield on Restaurant+hasMenu, got %+v", got) + } + if menuOut := Wave3PropRestIRRunHTML("schema_menu_html", restHasMenu, "https://bistrofoo.example.com/menu", ""); menuOut == nil || menuOut.ExtractorID != "schema-menu" { + t.Fatalf("schema-menu must extract Restaurant+hasMenu, got %+v", menuOut) + } + + restGraphMenu := `Bistro Bar

Bistro Bar

` + if got := Round2RunHTML("schema_localbusiness_html", restGraphMenu, "https://bistrobar.example.com/menu", ""); got != nil { + t.Fatalf("schema-localbusiness MUST yield on @graph Restaurant+Menu, got %+v", got) + } + + // Plain Restaurant with string hasMenu URL (no Menu items) should still resolve to schema-localbusiness + restLinkMenu := `Cafe

Corner Cafe

` + if got := Round2RunHTML("schema_localbusiness_html", restLinkMenu, "https://cafe.example.com/", ""); got == nil || got.ExtractorID != "schema-localbusiness" { + t.Fatalf("Restaurant with string hasMenu URL should still resolve to schema-localbusiness, got %+v", got) + } + + // Finding 7: schema-dataset, schema-software-app, schema-vehicle MUST yield on Product/ProductGroup or commerce platform markers + shopifyGraph := func(extraNode string) string { + return fmt.Sprintf(`Store

Item

`, extraNode) + } + if got := Wave3SchemaRunHTML("schema_dataset_html", shopifyGraph(`{"@type":"Dataset","name":"Size Chart Dataset"}`), "https://demo.example.com/products/shirt", ""); got != nil { + t.Fatalf("schema-dataset MUST yield on Product + Shopify.shop, got %+v", got) + } + if got := Wave3SchemaRunHTML("schema_software_app_html", shopifyGraph(`{"@type":"SoftwareApplication","name":"Store App"}`), "https://demo.example.com/products/app", ""); got != nil { + t.Fatalf("schema-software-app MUST yield on Product + Shopify.shop, got %+v", got) + } + if got := Wave3SchemaRunHTML("schema_vehicle_html", shopifyGraph(`{"@type":"Vehicle","name":"Roof Rack Fitment","vehicleIdentificationNumber":"1HGCM82633A004352"}`), "https://demo.example.com/products/rack", ""); got != nil { + t.Fatalf("schema-vehicle MUST yield on Product + Shopify.shop, got %+v", got) + } + // Separate Product + Vehicle without Shopify markers MUST also yield + separateProdVeh := `Roof Rack

Roof Rack

` + if got := Wave3SchemaRunHTML("schema_vehicle_html", separateProdVeh, "https://accessories.example.com/rack", ""); got != nil { + t.Fatalf("schema-vehicle MUST yield when separate Product node lacks Car/Vehicle type, got %+v", got) + } + // Dealership VDP with @type: ["Product","Car"] and NO Shopify/Woo markers MUST STILL WORK + dealerVDP := `2024 Honda Accord

2024 Honda Accord

` + if got := Wave3SchemaRunHTML("schema_vehicle_html", dealerVDP, "https://www.hondaofseattle.com/inventory/new-2024-honda-accord", ""); got == nil || got.ExtractorID != "schema-vehicle" { + t.Fatalf("dealership VDP with @type: ['Product','Car'] must resolve to schema-vehicle, got %+v", got) + } +} diff --git a/internal/extract/wave3_scholarly.go b/internal/extract/wave3_scholarly.go new file mode 100644 index 0000000..7f3aa6b --- /dev/null +++ b/internal/extract/wave3_scholarly.go @@ -0,0 +1,4218 @@ +package extract + +import ( + "bytes" + "encoding/json" + "encoding/xml" + "fmt" + stdhtml "html" + "io" + "math" + "net/url" + "strconv" + "strings" +) + +const ( + wave3ScholarlyMaxHTMLBytes = 2 * 1024 * 1024 + wave3ScholarlyMaxJSONBytes = 4 * 1024 * 1024 + wave3ScholarlyMaxTextBytes = 2 * 1024 * 1024 + wave3ScholarlyMaxRecords = 25 +) + +func wave3ScholarlyTruncateDesc(s string) string { + s = strings.TrimSpace(s) + if len(s) <= 260 { + return s + } + cut := sliceRunesMax(s, 260) + if len(cut) < len(s) { + return strings.TrimSpace(cut) + "..." + } + return s +} + +var ( + wave3ScholarlyRxNotFoundTitle = newLazyRegexp(`(?i)(?:^|\b)(?:404|410|406|401|403|429|page\s+not\s+found|page\s+cannot\s+be\s+found|not\s+found|error\s*404|we\s+couldn'?t\s+find\s+that\s+page|access\s+denied|request\s+(?:rejected|blocked)|could\s+not\s+be\s+satisfied|unauthorized|attention\s+required|just\s+a\s+moment|making\s+sure\s+you'?re\s+not\s+a\s+bot|vercel\s+security\s+checkpoint|forbidden|under\s+heavy\s+load)(?:\b|$)`) + wave3ScholarlyRxMaintTitle = newLazyRegexp(`(?i)(?:scheduled\s+maintenance|temporarily\s+unavailable|service\s+unavailable|site\s+maintenance|under\s+maintenance|502\s+bad\s+gateway|503\s+service|down\s+for\s+maintenance)`) + wave3ScholarlyRxErrorTitle = newLazyRegexp(`(?i)^(?:(?:(?:401|403|404|406|410|429|500|502|503)\s+)?(?:internal\s+)?server\s+error|application\s+error|system\s+error|unexpected\s+error|error\s+page|(?:401|403|404|406|410|429|500|502|503|http\s+\d{3})\s+error|error\s+(?:401|403|404|406|410|429|500|502|503)|error)(?:\s*[|\-\x{2013}\x{2014}:]\s*.*)?$|^.*(?:\s*[|\-\x{2013}\x{2014}:]\s*error)$`) + wave3ScholarlyRxGenericTitle = newLazyRegexp(`(?i)^(?:loading\.{0,3}|home|welcome|search|orcid|report\s*[\x{203a}>]\s*reporter|award\s+details\s*-\s*nsf\s+award\s+search|nsf\s+award\s+search|semantic\s+scholar|datacite\s+commons|core|ror|ssrn)$`) + wave3ScholarlyRxHTMLTag = newLazyRegexp(`<[^>]+>`) + wave3ScholarlyRxSpaceCollapse = newLazyRegexp(`[ \t\r\n]+`) + wave3ScholarlyRxSlashDate = newLazyRegexp(`^(\d{1,2})/(\d{1,2})/(\d{4})$`) + wave3ScholarlyRxYYYYSlashDate = newLazyRegexp(`^(\d{4})/(\d{1,2})/(\d{1,2})$`) + wave3ScholarlyRxISODate = newLazyRegexp(`^(\d{4})(?:-(\d{2})(?:-(\d{2}))?)?`) + wave3ScholarlyRxDOI = newLazyRegexp(`^10\.\d{4,9}/\S+$`) + wave3ScholarlyRxORCID = newLazyRegexp(`^0000-\d{4}-\d{4}-\d{3}[\dX]$`) + wave3ScholarlyRxROR = newLazyRegexp(`^0[a-z0-9]{6}\d{2}$`) + wave3ScholarlyRxNextData = newLazyRegexp(`(?is)]*\bid\s*=\s*["']__NEXT_DATA__["'][^>]*>(.*?)`) +) + +func init() { + RegisterWave3ScholarlyHTMLModes() +} + +// RegisterWave3ScholarlyHTMLModes registers all 14 Category L Research & Scholarly HTML modes (#301-#314). +func RegisterWave3ScholarlyHTMLModes() { + for _, mode := range []string{ + "semantic_scholar_html", + "unpaywall_html", + "core_ac_html", + "orcid_html", + "ror_html", + "dblp_html", + "biorxiv_medrxiv_html", + "nasa_ads_html", + "nih_reporter_html", + "nsf_awards_html", + "doe_osti_html", + "research_repo_pack_html", + "datacite_html", + "ssrn_nber_html", + } { + m := mode + RegisterExternalHTMLModeLazy(m, func(rawHTML, baseURL string, _ func() string, extractorID string) *DeclarativePostFetchResult { + return Wave3ScholarlyRunHTML(m, rawHTML, baseURL, extractorID) + }) + } +} + +// IsWave3ScholarlyHTMLMode reports whether mode is one of the 14 Category L HTML extractors (#301-#314). +func IsWave3ScholarlyHTMLMode(mode string) bool { + switch mode { + case "semantic_scholar_html", + "unpaywall_html", + "core_ac_html", + "orcid_html", + "ror_html", + "dblp_html", + "biorxiv_medrxiv_html", + "nasa_ads_html", + "nih_reporter_html", + "nsf_awards_html", + "doe_osti_html", + "research_repo_pack_html", + "datacite_html", + "ssrn_nber_html": + return true + default: + return false + } +} + +// IsWave3ScholarlyJSONMode reports whether mode is one of the Category L JSON formatters (#301-#313). +func IsWave3ScholarlyJSONMode(mode string) bool { + switch mode { + case "semantic_scholar_json", + "unpaywall_json", + "core_ac_json", + "orcid_json", + "ror_json", + "dblp_json", + "biorxiv_medrxiv_json", + "nasa_ads_json", + "nih_reporter_json", + "nsf_awards_json", + "doe_osti_json", + "research_repo_pack_json", + "datacite_json": + return true + default: + return false + } +} + +// IsWave3ScholarlyTextMode reports whether mode is a Category L text/XML formatter (`dblp_xml`). +func IsWave3ScholarlyTextMode(mode string) bool { + return mode == "dblp_xml" +} + +func wave3ScholarlyDefaultExtractorID(mode string) string { + switch mode { + case "semantic_scholar_html", "semantic_scholar_json": + return "semantic-scholar" + case "unpaywall_html", "unpaywall_json": + return "unpaywall" + case "core_ac_html", "core_ac_json": + return "core-ac" + case "orcid_html", "orcid_json": + return "orcid" + case "ror_html", "ror_json": + return "ror" + case "dblp_html", "dblp_json", "dblp_xml": + return "dblp" + case "biorxiv_medrxiv_html", "biorxiv_medrxiv_json": + return "biorxiv-medrxiv" + case "nasa_ads_html", "nasa_ads_json": + return "nasa-ads" + case "nih_reporter_html", "nih_reporter_json": + return "nih-reporter" + case "nsf_awards_html", "nsf_awards_json": + return "nsf-awards" + case "doe_osti_html", "doe_osti_json": + return "doe-osti" + case "research_repo_pack_html", "research_repo_pack_json": + return "research-repo-pack" + case "datacite_html", "datacite_json": + return "datacite" + case "ssrn_nber_html": + return "ssrn-nber" + default: + return "" + } +} + +// Wave3ScholarlyRunHTML executes a Category L HTML extractor and returns DeclarativePostFetchResult. +func Wave3ScholarlyRunHTML(mode, rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + if !IsWave3ScholarlyHTMLMode(mode) || len(rawHTML) == 0 || strings.IndexByte(rawHTML, '<') < 0 || strings.IndexByte(rawHTML, '>') < 0 { + return nil + } + if len(rawHTML) > wave3ScholarlyMaxHTMLBytes { + rawHTML = truncateUTF8SafeFullDocGo(rawHTML, wave3ScholarlyMaxHTMLBytes) + } + trimmedStart := strings.TrimLeft(rawHTML, " \t\r\n") + if trimmedStart == "" || trimmedStart[0] == '{' || trimmedStart[0] == '[' { + return nil + } + + probe := rawHTML + if len(probe) > 65536 { + probe = probe[:65536] + } + probeLower := asciiLowerExtractString(probe) + urlLower := asciiLowerExtractString(baseURL) + + if !wave3ScholarlyMatchesModePrefilter(mode, probeLower, urlLower) { + return nil + } + if wave3ScholarlyHasCommonNegativeShell(rawHTML, probeLower, urlLower) { + return nil + } + if extractorID == "" { + extractorID = wave3ScholarlyDefaultExtractorID(mode) + } + + var res *DeclarativePostFetchResult + switch mode { + case "semantic_scholar_html": + res = wave3ScholarlyExtractAcademicMetaHTML(rawHTML, baseURL, extractorID, "semantic-scholar") + case "unpaywall_html": + res = wave3ScholarlyExtractInfoPageHTML(rawHTML, baseURL, extractorID, "unpaywall") + case "core_ac_html": + res = wave3ScholarlyExtractAcademicMetaHTML(rawHTML, baseURL, extractorID, "core-ac") + case "orcid_html": + res = wave3ScholarlyExtractORCIDHTML(rawHTML, probeLower, baseURL, extractorID) + case "ror_html": + res = wave3ScholarlyExtractRORHTML(rawHTML, baseURL, extractorID) + case "dblp_html": + res = wave3ScholarlyExtractDBLPHTML(rawHTML, probeLower, baseURL, extractorID) + case "biorxiv_medrxiv_html": + res = wave3ScholarlyExtractAcademicMetaHTML(rawHTML, baseURL, extractorID, "biorxiv-medrxiv") + case "nasa_ads_html": + res = wave3ScholarlyExtractAcademicMetaHTML(rawHTML, baseURL, extractorID, "nasa-ads") + case "nih_reporter_html": + res = wave3ScholarlyExtractNIHReporterHTML(rawHTML, probeLower, baseURL, extractorID) + case "nsf_awards_html": + res = wave3ScholarlyExtractNSFAwardsHTML(rawHTML, probeLower, baseURL, extractorID) + case "doe_osti_html": + res = wave3ScholarlyExtractAcademicMetaHTML(rawHTML, baseURL, extractorID, "doe-osti") + case "research_repo_pack_html": + res = wave3ScholarlyExtractRepoPackHTML(rawHTML, probeLower, baseURL, urlLower, extractorID) + case "datacite_html": + res = wave3ScholarlyExtractDataCiteHTML(rawHTML, baseURL, extractorID) + case "ssrn_nber_html": + res = wave3ScholarlyExtractSSRNNBERHTML(rawHTML, probeLower, baseURL, urlLower, extractorID) + } + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return nil + } + return wave3ScholarlyFinalizePostFetch(res) +} + +// RunWave3ScholarlyHTMLMode executes a Category L HTML extractor and returns JSON-marshaled DeclarativePostFetchResult. +func RunWave3ScholarlyHTMLMode(mode, rawHTML, baseURL string) (string, bool) { + res := Wave3ScholarlyRunHTML(mode, rawHTML, baseURL, wave3ScholarlyDefaultExtractorID(mode)) + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return "", false + } + res = sanitizePostFetchResultDeclHTML(res) + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return "", false + } + encoded, err := json.Marshal(res) + if err != nil { + return "", false + } + return string(encoded), true +} + +// FormatWave3ScholarlyJSONDoc formats a Category L JSON twin payload into DeclarativeFormattedDoc. +func FormatWave3ScholarlyJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool) { + if !IsWave3ScholarlyJSONMode(mode) || len(raw) == 0 || len(raw) > wave3ScholarlyMaxJSONBytes { + return nil, false + } + trimmed := bytes.TrimSpace(bytes.TrimPrefix(raw, []byte("\xEF\xBB\xBF"))) + if len(trimmed) == 0 || (trimmed[0] != '{' && trimmed[0] != '[') { + return nil, false + } + parsed, ok := decodeJSONWithNumbers(trimmed) + if !ok || parsed == nil { + return nil, false + } + + var doc *DeclarativeFormattedDoc + var handled bool + switch mode { + case "semantic_scholar_json": + doc, handled = wave3ScholarlyFormatSemanticScholarJSON(parsed, origURL) + case "unpaywall_json": + doc, handled = wave3ScholarlyFormatUnpaywallJSON(parsed, origURL) + case "core_ac_json": + doc, handled = wave3ScholarlyFormatCoreACJSON(parsed, origURL) + case "orcid_json": + doc, handled = wave3ScholarlyFormatORCIDJSON(parsed, origURL) + case "ror_json": + doc, handled = wave3ScholarlyFormatRORJSON(parsed, origURL) + case "dblp_json": + doc, handled = wave3ScholarlyFormatDBLPJSON(parsed, origURL) + case "biorxiv_medrxiv_json": + doc, handled = wave3ScholarlyFormatBioRxivJSON(parsed, origURL) + case "nasa_ads_json": + doc, handled = wave3ScholarlyFormatNASAADSJSON(parsed, origURL) + case "nih_reporter_json": + doc, handled = wave3ScholarlyFormatNIHReporterJSON(parsed, origURL) + case "nsf_awards_json": + doc, handled = wave3ScholarlyFormatNSFAwardsJSON(parsed, origURL) + case "doe_osti_json": + doc, handled = wave3ScholarlyFormatDOEOSTIJSON(parsed, origURL) + case "research_repo_pack_json": + doc, handled = wave3ScholarlyFormatRepoPackJSON(parsed, origURL) + case "datacite_json": + doc, handled = wave3ScholarlyFormatDataCiteJSON(parsed, origURL) + } + if !handled || doc == nil || strings.TrimSpace(doc.Markdown) == "" { + return nil, false + } + return wave3ScholarlyFinalizeDoc(doc), true +} + +// FormatWave3ScholarlyJSONMode formats a Category L JSON payload and returns JSON-marshaled DeclarativeFormattedDoc. +func FormatWave3ScholarlyJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool) { + doc, ok := FormatWave3ScholarlyJSONDoc(mode, raw, params, origURL) + if !ok || doc == nil { + return "", false + } + encoded, err := json.Marshal(doc) + if err != nil { + return "", false + } + return string(encoded), true +} + +// FormatWave3ScholarlyTextDoc formats a Category L text/XML twin payload (`dblp_xml`). +func FormatWave3ScholarlyTextDoc(mode, rawBody string, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool) { + if !IsWave3ScholarlyTextMode(mode) || len(rawBody) == 0 { + return nil, false + } + if len(rawBody) > wave3ScholarlyMaxTextBytes { + rawBody = truncateUTF8SafeFullDocGo(rawBody, wave3ScholarlyMaxTextBytes) + } + var doc *DeclarativeFormattedDoc + var handled bool + switch mode { + case "dblp_xml": + doc, handled = wave3ScholarlyFormatDBLPXML(rawBody, origURL) + } + if !handled || doc == nil || strings.TrimSpace(doc.Markdown) == "" { + return nil, false + } + return wave3ScholarlyFinalizeDoc(doc), true +} + +// FormatWave3ScholarlyTextMode formats a Category L text/XML payload and returns JSON-marshaled DeclarativeFormattedDoc. +func FormatWave3ScholarlyTextMode(mode, rawBody string, params map[string]string, origURL string) (string, bool) { + doc, ok := FormatWave3ScholarlyTextDoc(mode, rawBody, params, origURL) + if !ok || doc == nil { + return "", false + } + encoded, err := json.Marshal(doc) + if err != nil { + return "", false + } + return string(encoded), true +} + +// ── Prefilters & Shared Hygiene Helpers ────────────────────────────────────────────────────────── + +func wave3ScholarlyMatchesModePrefilter(mode, probeLower, urlLower string) bool { + switch mode { + case "semantic_scholar_html": + return strings.Contains(probeLower, "citation_title") || + strings.Contains(probeLower, "paper-detail-title") || + strings.Contains(probeLower, "scholarlyarticle") || + (strings.Contains(urlLower, "semanticscholar.org") && strings.Contains(probeLower, "= 0 { + rest := pathOnly[idx+3:] + if slash := strings.IndexByte(rest, '/'); slash >= 0 { + pathOnly = rest[slash:] + } else { + pathOnly = "/" + } + } + if cut := strings.IndexAny(pathOnly, "?#"); cut >= 0 { + pathOnly = pathOnly[:cut] + } + return strings.HasSuffix(pathOnly, "/error") || + strings.Contains(pathOnly, "/error/") || + strings.HasSuffix(pathOnly, "/error.html") || + strings.HasSuffix(pathOnly, "/error.htm") || + strings.HasSuffix(pathOnly, "/error.aspx") || + strings.HasSuffix(pathOnly, "/login") || + strings.Contains(pathOnly, "/login/") +} + +func wave3ScholarlyIsNegativeTitle(title string) bool { + t := strings.TrimSpace(title) + if t == "" { + return false + } + return wave3ScholarlyRxNotFoundTitle.MatchString(t) || + wave3ScholarlyRxMaintTitle.MatchString(t) || + wave3ScholarlyRxErrorTitle.MatchString(t) +} + +func wave3ScholarlyIsGenericTitle(title string) bool { + return wave3ScholarlyRxGenericTitle.MatchString(strings.TrimSpace(title)) +} + +func wave3ScholarlyHasCommonNegativeShell(rawHTML, probeLower, urlLower string) bool { + if wave3ScholarlyIsNegativeURL(urlLower) { + return true + } + rawLower := asciiLowerExtractString(rawHTML) + hasRealBodyMarkers := hasJSONLDScriptToken(rawHTML) || + strings.Contains(rawLower, "") || strings.Contains(rawLower, " 0 { + return true + } + case map[string]any: + if len(tv) > 0 { + return true + } + case bool: + if tv { + return true + } + case float64, int, int64, json.Number: + if f, fOK := wave3ScholarlyFloatVal(tv); fOK && f != 0 { + return true + } + } + } + } + for _, k := range []string{"error_code", "statusCode", "status_code", "HTTP_status_code", "status-code"} { + if f, ok := wave3ScholarlyFloatVal(obj[k]); ok && f >= 400 { + return true + } + } + if st := strings.ToUpper(wave3ScholarlyPlain(obj["status"], 48)); st == "ERROR" || st == "NOT_FOUND" || st == "PERMISSION_DENIED" || st == "UNAUTHENTICATED" || st == "UNAUTHORIZED" { + return true + } + if msg := wave3ScholarlyPlain(obj["message"], 240); msg != "" && len(obj) <= 4 { + lm := strings.ToLower(msg) + if strings.Contains(lm, "unauthorized") || + strings.Contains(lm, "not found") || + strings.Contains(lm, "invalid") || + strings.Contains(lm, "forbidden") || + strings.Contains(lm, "missing") || + strings.Contains(lm, "authentication") { + return true + } + } + return false +} + +func wave3ScholarlyIntPtr(n int) *int { return &n } +func wave3ScholarlyBoolPtr(b bool) *bool { return &b } + +func wave3ScholarlyFinalizeDoc(doc *DeclarativeFormattedDoc) *DeclarativeFormattedDoc { + if doc == nil { + return nil + } + if len(doc.Records) > wave3ScholarlyMaxRecords { + if doc.Total == nil { + doc.Total = wave3ScholarlyIntPtr(len(doc.Records)) + } + doc.Records = doc.Records[:wave3ScholarlyMaxRecords] + doc.Returned = wave3ScholarlyIntPtr(len(doc.Records)) + doc.Truncated = wave3ScholarlyBoolPtr(true) + if doc.NextCursor == "" { + doc.NextCursor = strconv.Itoa(len(doc.Records)) + } + } + if sanitized, ok := sanitizeDeclarativeFormattedDocGo(doc); ok && sanitized != nil { + return sanitized + } + return nil +} + +func wave3ScholarlyFinalizePostFetch(res *DeclarativePostFetchResult) *DeclarativePostFetchResult { + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return nil + } + if len(res.Records) > wave3ScholarlyMaxRecords { + if res.Total == nil { + res.Total = wave3ScholarlyIntPtr(len(res.Records)) + } + res.Records = res.Records[:wave3ScholarlyMaxRecords] + res.Returned = wave3ScholarlyIntPtr(len(res.Records)) + res.Truncated = wave3ScholarlyBoolPtr(true) + if res.NextCursor == "" { + res.NextCursor = strconv.Itoa(len(res.Records)) + } + } + return res +} + +func wave3ScholarlyCleanText(s string) string { + if s == "" { + return "" + } + if strings.IndexByte(s, '<') >= 0 { + s = wave3ScholarlyRxHTMLTag.ReplaceAllString(s, " ") + } + if strings.IndexByte(s, '&') >= 0 { + s = stdhtml.UnescapeString(s) + if strings.IndexByte(s, '<') >= 0 { + s = wave3ScholarlyRxHTMLTag.ReplaceAllString(s, " ") + } + } + if !strings.ContainsAny(s, "\t\r\n") && !strings.Contains(s, " ") { + return strings.TrimSpace(s) + } + return strings.TrimSpace(wave3ScholarlyRxSpaceCollapse.ReplaceAllString(s, " ")) +} + +func wave3ScholarlyStringVal(v any) string { + switch tv := v.(type) { + case string: + return strings.TrimSpace(tv) + case json.Number: + return tv.String() + case float64: + if math.IsNaN(tv) || math.IsInf(tv, 0) { + return "" + } + if tv == math.Trunc(tv) { + return strconv.FormatInt(int64(tv), 10) + } + return strconv.FormatFloat(tv, 'f', -1, 64) + case int: + return strconv.Itoa(tv) + case int64: + return strconv.FormatInt(tv, 10) + case bool: + if tv { + return "true" + } + return "false" + default: + return "" + } +} + +func wave3ScholarlyFloatVal(v any) (float64, bool) { + switch tv := v.(type) { + case float64: + if math.IsNaN(tv) || math.IsInf(tv, 0) { + return 0, false + } + return tv, true + case int: + return float64(tv), true + case int64: + return float64(tv), true + case json.Number: + f, err := tv.Float64() + if err != nil || math.IsNaN(f) || math.IsInf(f, 0) { + return 0, false + } + return f, true + case string: + s := strings.TrimSpace(strings.ReplaceAll(tv, ",", "")) + if s == "" { + return 0, false + } + f, err := strconv.ParseFloat(s, 64) + if err != nil || math.IsNaN(f) || math.IsInf(f, 0) { + return 0, false + } + return f, true + default: + return 0, false + } +} + +func wave3ScholarlyPlain(v any, maxLen int) string { + return SanitizeSchemaPlainField(wave3ScholarlyStringVal(v), maxLen) +} + +func wave3ScholarlyFirstNonEmpty(vals ...string) string { + for _, v := range vals { + if t := strings.TrimSpace(v); t != "" { + return t + } + } + return "" +} + +func wave3ScholarlyAddLink(links *[]string, seen map[string]bool, raw, base string) { + u := SanitizeSchemaHTTPSURL(raw, base) + if u != "" && !seen[u] { + seen[u] = true + *links = append(*links, u) + } +} + +func wave3ScholarlyNormalizeDOI(raw string) string { + s := strings.TrimSpace(raw) + if s == "" { + return "" + } + low := strings.ToLower(s) + for _, pref := range []string{ + "https://doi.org/", + "http://doi.org/", + "https://dx.doi.org/", + "http://dx.doi.org/", + "doi:", + } { + if strings.HasPrefix(low, pref) { + s = strings.TrimSpace(s[len(pref):]) + break + } + } + if !wave3ScholarlyRxDOI.MatchString(s) { + return "" + } + return s +} + +func wave3ScholarlyNormalizeORCID(raw string) string { + s := strings.TrimSpace(raw) + low := strings.ToLower(s) + for _, pref := range []string{"https://orcid.org/", "http://orcid.org/"} { + if strings.HasPrefix(low, pref) { + s = strings.TrimSpace(s[len(pref):]) + break + } + } + s = strings.ToUpper(strings.Trim(s, "/")) + if !wave3ScholarlyRxORCID.MatchString(s) { + return "" + } + return s +} + +func wave3ScholarlyNormalizeRORID(raw string) string { + s := strings.TrimSpace(raw) + low := strings.ToLower(s) + for _, pref := range []string{"https://ror.org/", "http://ror.org/"} { + if strings.HasPrefix(low, pref) { + s = strings.TrimSpace(s[len(pref):]) + break + } + } + s = strings.ToLower(strings.Trim(s, "/")) + if !wave3ScholarlyRxROR.MatchString(s) { + return "" + } + return s +} + +func wave3ScholarlyNormalizeDate(raw string) string { + s := SanitizeSchemaPlainField(raw, 48) + if s == "" { + return "" + } + if m := wave3ScholarlyRxYYYYSlashDate.FindStringSubmatch(s); len(m) == 4 { + mo, _ := strconv.Atoi(m[2]) + da, _ := strconv.Atoi(m[3]) + if mo >= 1 && mo <= 12 && da >= 1 && da <= 31 { + return fmt.Sprintf("%s-%02d-%02d", m[1], mo, da) + } + } + if m := wave3ScholarlyRxSlashDate.FindStringSubmatch(s); len(m) == 4 { + mo, _ := strconv.Atoi(m[1]) + da, _ := strconv.Atoi(m[2]) + if mo >= 1 && mo <= 12 && da >= 1 && da <= 31 { + return fmt.Sprintf("%s-%02d-%02d", m[3], mo, da) + } + } + if m := wave3ScholarlyRxISODate.FindStringSubmatch(s); len(m) >= 2 && m[1] != "" { + if m[2] != "" && m[3] != "" { + return m[1] + "-" + m[2] + "-" + m[3] + } + if m[2] != "" { + return m[1] + "-" + m[2] + } + return m[1] + } + return s +} + +func wave3ScholarlyMapAt(m map[string]any, keys ...string) map[string]any { + cur := m + for _, k := range keys { + if cur == nil { + return nil + } + nxt, ok := cur[k].(map[string]any) + if !ok { + return nil + } + cur = nxt + } + return cur +} + +func wave3ScholarlyValAt(m map[string]any, keys ...string) any { + if len(keys) == 0 || m == nil { + return nil + } + cur := m + for i := 0; i < len(keys)-1; i++ { + nxt, ok := cur[keys[i]].(map[string]any) + if !ok { + return nil + } + cur = nxt + } + return cur[keys[len(keys)-1]] +} + +func wave3ScholarlyJoinStrings(arr any, limit int) []string { + list, ok := arr.([]any) + if !ok || len(list) == 0 { + return nil + } + out := make([]string, 0, len(list)) + for _, item := range list { + if limit > 0 && len(out) >= limit { + break + } + if s := wave3ScholarlyPlain(item, 180); s != "" { + out = append(out, s) + } + } + return out +} + +func wave3ScholarlyFormatAmount(v any) string { + f, ok := wave3ScholarlyFloatVal(v) + if !ok { + return "" + } + n := int64(math.Round(f)) + neg := n < 0 + if neg { + n = -n + } + s := strconv.FormatInt(n, 10) + if len(s) <= 3 { + if neg { + return "-" + s + } + return s + } + var out strings.Builder + if neg { + out.WriteByte('-') + } + rem := len(s) % 3 + if rem > 0 { + out.WriteString(s[:rem]) + out.WriteByte(',') + } + for i := rem; i < len(s); i += 3 { + if i > rem { + out.WriteByte(',') + } + out.WriteString(s[i : i+3]) + } + return out.String() +} + +// ── #301 Semantic Scholar JSON ────────────────────────────────────────────────────────────────── + +func wave3ScholarlyFormatSemanticScholarJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + m, ok := parsed.(map[string]any) + if !ok || wave3ScholarlyIsGenericJSONError(m) { + return nil, false + } + + // Search/batch list (`data: [...]`) + if dataArr, okD := m["data"].([]any); okD { + if len(dataArr) == 0 { + return nil, false + } + var recs []map[string]any + var rows [][]string + var links []string + seen := make(map[string]bool) + for _, it := range dataArr { + if len(recs) >= wave3ScholarlyMaxRecords { + break + } + pm, okPM := it.(map[string]any) + if !okPM { + continue + } + title := wave3ScholarlyPlain(pm["title"], 260) + if title == "" { + continue + } + pid := wave3ScholarlyPlain(pm["paperId"], 64) + year := wave3ScholarlyPlain(pm["year"], 8) + venue := wave3ScholarlyPlain(pm["venue"], 120) + citCount := wave3ScholarlyPlain(pm["citationCount"], 16) + paperURL := SanitizeSchemaHTTPSURL(wave3ScholarlyStringVal(pm["url"]), origURL) + if paperURL == "" && pid != "" { + paperURL = "https://www.semanticscholar.org/paper/" + pid + } + wave3ScholarlyAddLink(&links, seen, paperURL, origURL) + doi := wave3ScholarlyNormalizeDOI(wave3ScholarlyStringVal(wave3ScholarlyValAt(pm, "externalIds", "DOI"))) + rec := map[string]any{ + "source": "semantic-scholar", + "title": title, + } + if pid != "" { + rec["paperId"] = pid + } + if year != "" { + rec["year"] = year + } + if venue != "" { + rec["venue"] = venue + } + if doi != "" { + rec["doi"] = doi + wave3ScholarlyAddLink(&links, seen, "https://doi.org/"+doi, origURL) + } + if citCount != "" { + rec["citationCount"] = citCount + } + if paperURL != "" { + rec["url"] = paperURL + } + recs = append(recs, rec) + rows = append(rows, []string{title, year, venue, citCount, doi}) + } + if len(recs) == 0 { + return nil, false + } + total := len(recs) + if t, okT := wave3ScholarlyFloatVal(m["total"]); okT && int(t) > total { + total = int(t) + } + md := "# Semantic Scholar Papers\n\n" + formatDeclarativeGFMTable([]string{"Title", "Year", "Venue", "Citations", "DOI"}, rows) + return &DeclarativeFormattedDoc{ + Title: "Semantic Scholar Papers", + Markdown: md, + Links: links, + Records: recs, + Total: wave3ScholarlyIntPtr(total), + Returned: wave3ScholarlyIntPtr(len(recs)), + Truncated: wave3ScholarlyBoolPtr(total > len(recs)), + }, true + } + + // Author object (`authorId` + `name`) + if authorName := wave3ScholarlyPlain(m["name"], 200); authorName != "" && wave3ScholarlyPlain(m["authorId"], 48) != "" { + aid := wave3ScholarlyPlain(m["authorId"], 48) + affils := wave3ScholarlyJoinStrings(m["affiliations"], 6) + paperCount := wave3ScholarlyPlain(m["paperCount"], 16) + citCount := wave3ScholarlyPlain(m["citationCount"], 16) + hIndex := wave3ScholarlyPlain(m["hIndex"], 16) + homepage := SanitizeSchemaHTTPSURL(wave3ScholarlyStringVal(m["homepage"]), origURL) + authorURL := SanitizeSchemaHTTPSURL(wave3ScholarlyStringVal(m["url"]), origURL) + if authorURL == "" { + authorURL = "https://www.semanticscholar.org/author/" + aid + } + var bullets []string + bullets = append(bullets, "- **Author ID**: `"+aid+"`") + if len(affils) > 0 { + bullets = append(bullets, "- **Affiliations**: "+strings.Join(affils, ", ")) + } + if paperCount != "" { + bullets = append(bullets, "- **Papers**: "+paperCount) + } + if citCount != "" { + bullets = append(bullets, "- **Citations**: "+citCount) + } + if hIndex != "" { + bullets = append(bullets, "- **h-index**: "+hIndex) + } + if homepage != "" { + bullets = append(bullets, "- **Homepage**: "+homepage) + } + var links []string + seen := make(map[string]bool) + wave3ScholarlyAddLink(&links, seen, authorURL, origURL) + wave3ScholarlyAddLink(&links, seen, homepage, origURL) + rec := map[string]any{ + "source": "semantic-scholar", + "authorId": aid, + "name": authorName, + "url": authorURL, + } + if len(affils) > 0 { + rec["affiliations"] = affils + } + if paperCount != "" { + rec["paperCount"] = paperCount + } + if citCount != "" { + rec["citationCount"] = citCount + } + if hIndex != "" { + rec["hIndex"] = hIndex + } + return &DeclarativeFormattedDoc{ + Title: authorName, + Author: authorName, + Markdown: "# " + escapeDeclMarkdownBrackets(authorName) + "\n\n" + strings.Join(bullets, "\n"), + Links: links, + Records: []map[string]any{rec}, + Total: wave3ScholarlyIntPtr(1), + Returned: wave3ScholarlyIntPtr(1), + }, true + } + + // Single paper object + title := wave3ScholarlyPlain(m["title"], 300) + if title == "" { + return nil, false + } + pid := wave3ScholarlyPlain(m["paperId"], 64) + year := wave3ScholarlyPlain(m["year"], 8) + pubDate := wave3ScholarlyNormalizeDate(wave3ScholarlyStringVal(m["publicationDate"])) + if pubDate == "" { + pubDate = year + } + venue := wave3ScholarlyFirstNonEmpty( + wave3ScholarlyPlain(wave3ScholarlyValAt(m, "publicationVenue", "name"), 140), + wave3ScholarlyPlain(m["venue"], 140), + ) + abstract := wave3ScholarlyPlain(m["abstract"], 4000) + citCount := wave3ScholarlyPlain(m["citationCount"], 16) + refCount := wave3ScholarlyPlain(m["referenceCount"], 16) + infCit := wave3ScholarlyPlain(m["influentialCitationCount"], 16) + oaPdf := SanitizeSchemaHTTPSURL(wave3ScholarlyStringVal(wave3ScholarlyValAt(m, "openAccessPdf", "url")), origURL) + paperURL := SanitizeSchemaHTTPSURL(wave3ScholarlyStringVal(m["url"]), origURL) + if paperURL == "" && pid != "" { + paperURL = "https://www.semanticscholar.org/paper/" + pid + } + + var authors []string + if aArr, okA := m["authors"].([]any); okA { + for _, av := range aArr { + if len(authors) >= 16 { + break + } + if am, okAM := av.(map[string]any); okAM { + if name := wave3ScholarlyPlain(am["name"], 100); name != "" { + authors = append(authors, name) + } + } + } + } + authorsStr := strings.Join(authors, ", ") + authorsShort := authorsStr + if len(authors) > 4 { + authorsShort = strings.Join(authors[:4], ", ") + } + + doi := wave3ScholarlyNormalizeDOI(wave3ScholarlyStringVal(wave3ScholarlyValAt(m, "externalIds", "DOI"))) + arxivID := wave3ScholarlyPlain(wave3ScholarlyValAt(m, "externalIds", "ArXiv"), 48) + pmid := wave3ScholarlyPlain(wave3ScholarlyValAt(m, "externalIds", "PubMed"), 32) + + var bullets []string + if pid != "" { + bullets = append(bullets, "- **Paper ID**: `"+pid+"`") + } + if authorsStr != "" { + bullets = append(bullets, "- **Authors**: "+authorsStr) + } + if venue != "" { + bullets = append(bullets, "- **Venue**: "+venue) + } + if pubDate != "" { + bullets = append(bullets, "- **Published**: "+pubDate) + } + if doi != "" { + bullets = append(bullets, "- **DOI**: `"+doi+"`") + } + if arxivID != "" { + bullets = append(bullets, "- **arXiv**: `"+arxivID+"`") + } + if pmid != "" { + bullets = append(bullets, "- **PubMed ID**: `"+pmid+"`") + } + if citCount != "" { + bullets = append(bullets, "- **Citations**: "+citCount) + } + if infCit != "" { + bullets = append(bullets, "- **Influential Citations**: "+infCit) + } + if refCount != "" { + bullets = append(bullets, "- **References**: "+refCount) + } + if oaPdf != "" { + bullets = append(bullets, "- **Open Access PDF**: "+oaPdf) + } + if paperURL != "" { + bullets = append(bullets, "- **Semantic Scholar URL**: "+paperURL) + } + + var blocks []string + blocks = append(blocks, "# "+escapeDeclMarkdownBrackets(title)) + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + if abstract != "" { + blocks = append(blocks, "## Abstract\n\n"+abstract) + } + + var links []string + seen := make(map[string]bool) + wave3ScholarlyAddLink(&links, seen, paperURL, origURL) + wave3ScholarlyAddLink(&links, seen, oaPdf, origURL) + if doi != "" { + wave3ScholarlyAddLink(&links, seen, "https://doi.org/"+doi, origURL) + } + + rec := map[string]any{ + "source": "semantic-scholar", + "title": title, + } + if pid != "" { + rec["paperId"] = pid + } + if len(authors) > 0 { + rec["authors"] = authors + } + if venue != "" { + rec["venue"] = venue + } + if pubDate != "" { + rec["publishedDate"] = pubDate + } + if doi != "" { + rec["doi"] = doi + } + if arxivID != "" { + rec["arxivId"] = arxivID + } + if oaPdf != "" { + rec["openAccessPdf"] = oaPdf + } + if citCount != "" { + rec["citationCount"] = citCount + } + + desc := abstract + desc = wave3ScholarlyTruncateDesc(desc) + return &DeclarativeFormattedDoc{ + Title: title, + Description: desc, + Author: authorsShort, + PublishedTime: pubDate, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: []map[string]any{rec}, + Total: wave3ScholarlyIntPtr(1), + Returned: wave3ScholarlyIntPtr(1), + }, true +} + +// ── #302 Unpaywall JSON ───────────────────────────────────────────────────────────────────────── + +func wave3ScholarlyFormatUnpaywallJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + m, ok := parsed.(map[string]any) + if !ok || wave3ScholarlyIsGenericJSONError(m) { + return nil, false + } + // Search response (`results: [{response: {...}}]`) + if resArr, okR := m["results"].([]any); okR { + if len(resArr) == 0 { + return nil, false + } + var recs []map[string]any + var rows [][]string + var links []string + seen := make(map[string]bool) + for _, item := range resArr { + if len(recs) >= wave3ScholarlyMaxRecords { + break + } + im, okIM := item.(map[string]any) + if !okIM { + continue + } + if inner, okIn := im["response"].(map[string]any); okIn { + im = inner + } + doi := wave3ScholarlyNormalizeDOI(wave3ScholarlyStringVal(im["doi"])) + title := wave3ScholarlyPlain(im["title"], 260) + if doi == "" && title == "" { + continue + } + if title == "" { + title = doi + } + oaStatus := wave3ScholarlyPlain(im["oa_status"], 32) + journal := wave3ScholarlyPlain(im["journal_name"], 120) + bestURL := SanitizeSchemaHTTPSURL(wave3ScholarlyFirstNonEmpty( + wave3ScholarlyStringVal(wave3ScholarlyValAt(im, "best_oa_location", "url_for_pdf")), + wave3ScholarlyStringVal(wave3ScholarlyValAt(im, "best_oa_location", "url")), + ), origURL) + wave3ScholarlyAddLink(&links, seen, bestURL, origURL) + if doi != "" { + wave3ScholarlyAddLink(&links, seen, "https://doi.org/"+doi, origURL) + } + rec := map[string]any{ + "source": "unpaywall", + "title": title, + "doi": doi, + "oaStatus": oaStatus, + } + if journal != "" { + rec["journal"] = journal + } + if bestURL != "" { + rec["bestOaUrl"] = bestURL + } + recs = append(recs, rec) + rows = append(rows, []string{title, doi, oaStatus, journal}) + } + if len(recs) == 0 { + return nil, false + } + md := "# Unpaywall Search Results\n\n" + formatDeclarativeGFMTable([]string{"Title", "DOI", "OA Status", "Journal"}, rows) + return &DeclarativeFormattedDoc{ + Title: "Unpaywall Search Results", + Markdown: md, + Links: links, + Records: recs, + Total: wave3ScholarlyIntPtr(len(recs)), + Returned: wave3ScholarlyIntPtr(len(recs)), + }, true + } + + doi := wave3ScholarlyNormalizeDOI(wave3ScholarlyStringVal(m["doi"])) + title := wave3ScholarlyPlain(m["title"], 300) + if doi == "" || title == "" { + return nil, false + } + isOA := "false" + if b, okB := m["is_oa"].(bool); okB && b { + isOA = "true" + } + oaStatus := wave3ScholarlyPlain(m["oa_status"], 32) + journal := wave3ScholarlyPlain(m["journal_name"], 160) + publisher := wave3ScholarlyPlain(m["publisher"], 140) + pubDate := wave3ScholarlyNormalizeDate(wave3ScholarlyStringVal(m["published_date"])) + if pubDate == "" { + pubDate = wave3ScholarlyPlain(m["year"], 8) + } + genre := wave3ScholarlyPlain(m["genre"], 48) + + var authors []string + if zArr, okZ := m["z_authors"].([]any); okZ { + for _, av := range zArr { + if len(authors) >= 16 { + break + } + am, okAM := av.(map[string]any) + if !okAM { + continue + } + given := wave3ScholarlyPlain(am["given"], 60) + family := wave3ScholarlyPlain(am["family"], 60) + full := strings.TrimSpace(given + " " + family) + if full == "" { + full = wave3ScholarlyPlain(am["raw_author_name"], 100) + } + if full != "" { + authors = append(authors, full) + } + } + } + authorsStr := strings.Join(authors, ", ") + authorsShort := authorsStr + if len(authors) > 4 { + authorsShort = strings.Join(authors[:4], ", ") + } + + bestLoc := wave3ScholarlyMapAt(m, "best_oa_location") + bestURL := SanitizeSchemaHTTPSURL(wave3ScholarlyStringVal(bestLoc["url"]), origURL) + bestPDF := SanitizeSchemaHTTPSURL(wave3ScholarlyStringVal(bestLoc["url_for_pdf"]), origURL) + bestLicense := wave3ScholarlyPlain(bestLoc["license"], 64) + bestHostType := wave3ScholarlyPlain(bestLoc["host_type"], 48) + bestVersion := wave3ScholarlyPlain(bestLoc["version"], 48) + + var bullets []string + bullets = append(bullets, "- **DOI**: `"+doi+"`") + bullets = append(bullets, "- **Open Access**: "+isOA) + if oaStatus != "" { + bullets = append(bullets, "- **OA Status**: "+oaStatus) + } + if authorsStr != "" { + bullets = append(bullets, "- **Authors**: "+authorsStr) + } + if journal != "" { + bullets = append(bullets, "- **Journal**: "+journal) + } + if publisher != "" { + bullets = append(bullets, "- **Publisher**: "+publisher) + } + if pubDate != "" { + bullets = append(bullets, "- **Published**: "+pubDate) + } + if genre != "" { + bullets = append(bullets, "- **Type**: "+genre) + } + if bestPDF != "" { + bullets = append(bullets, "- **Best OA PDF**: "+bestPDF) + } + if bestURL != "" { + bullets = append(bullets, "- **Best OA Landing URL**: "+bestURL) + } + if bestLicense != "" { + bullets = append(bullets, "- **License**: "+bestLicense) + } + if bestHostType != "" { + bullets = append(bullets, "- **Host Type**: "+bestHostType) + } + if bestVersion != "" { + bullets = append(bullets, "- **Version**: "+bestVersion) + } + + var oaRows [][]string + if locs, okL := m["oa_locations"].([]any); okL { + for _, lv := range locs { + if len(oaRows) >= 12 { + break + } + lm, okLM := lv.(map[string]any) + if !okLM { + continue + } + lu := SanitizeSchemaHTTPSURL(wave3ScholarlyFirstNonEmpty(wave3ScholarlyStringVal(lm["url_for_pdf"]), wave3ScholarlyStringVal(lm["url"])), origURL) + if lu == "" { + continue + } + oaRows = append(oaRows, []string{ + wave3ScholarlyPlain(lm["host_type"], 40), + wave3ScholarlyPlain(lm["version"], 40), + wave3ScholarlyPlain(lm["license"], 40), + lu, + }) + } + } + + var blocks []string + blocks = append(blocks, "# "+escapeDeclMarkdownBrackets(title)) + blocks = append(blocks, strings.Join(bullets, "\n")) + if len(oaRows) > 0 { + blocks = append(blocks, "## Open Access Locations\n\n"+formatDeclarativeGFMTable([]string{"Host Type", "Version", "License", "URL"}, oaRows)) + } + + var links []string + seen := make(map[string]bool) + wave3ScholarlyAddLink(&links, seen, "https://doi.org/"+doi, origURL) + wave3ScholarlyAddLink(&links, seen, bestPDF, origURL) + wave3ScholarlyAddLink(&links, seen, bestURL, origURL) + + rec := map[string]any{ + "source": "unpaywall", + "doi": doi, + "title": title, + "isOa": isOA == "true", + "oaStatus": oaStatus, + } + if journal != "" { + rec["journalName"] = journal + } + if pubDate != "" { + rec["publishedDate"] = pubDate + } + if bestPDF != "" { + rec["bestOaPdf"] = bestPDF + } + if bestURL != "" { + rec["bestOaUrl"] = bestURL + } + if bestLicense != "" { + rec["license"] = bestLicense + } + if len(authors) > 0 { + rec["authors"] = authors + } + + return &DeclarativeFormattedDoc{ + Title: title, + Author: authorsShort, + PublishedTime: pubDate, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: []map[string]any{rec}, + Total: wave3ScholarlyIntPtr(1), + Returned: wave3ScholarlyIntPtr(1), + }, true +} + +// ── #303 CORE.ac.uk JSON ──────────────────────────────────────────────────────────────────────── + +func wave3ScholarlyFormatCoreACJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + m, ok := parsed.(map[string]any) + if !ok || wave3ScholarlyIsGenericJSONError(m) { + return nil, false + } + + // Search endpoint (`results: [...]`) + if resArr, okR := m["results"].([]any); okR { + if len(resArr) == 0 { + return nil, false + } + var recs []map[string]any + var rows [][]string + var links []string + seen := make(map[string]bool) + for _, it := range resArr { + if len(recs) >= wave3ScholarlyMaxRecords { + break + } + wm, okWM := it.(map[string]any) + if !okWM { + continue + } + title := wave3ScholarlyPlain(wm["title"], 260) + if title == "" { + continue + } + id := wave3ScholarlyPlain(wm["id"], 32) + year := wave3ScholarlyPlain(wm["yearPublished"], 8) + doi := wave3ScholarlyNormalizeDOI(wave3ScholarlyStringVal(wm["doi"])) + dl := SanitizeSchemaHTTPSURL(wave3ScholarlyStringVal(wm["downloadUrl"]), origURL) + wave3ScholarlyAddLink(&links, seen, dl, origURL) + if id != "" { + wave3ScholarlyAddLink(&links, seen, "https://core.ac.uk/works/"+id, origURL) + } + rec := map[string]any{ + "source": "core-ac", + "title": title, + } + if id != "" { + rec["id"] = id + } + if year != "" { + rec["yearPublished"] = year + } + if doi != "" { + rec["doi"] = doi + } + if dl != "" { + rec["downloadUrl"] = dl + } + recs = append(recs, rec) + rows = append(rows, []string{id, title, year, doi}) + } + if len(recs) == 0 { + return nil, false + } + total := len(recs) + if t, okT := wave3ScholarlyFloatVal(m["totalHits"]); okT && int(t) > total { + total = int(t) + } + return &DeclarativeFormattedDoc{ + Title: "CORE Scholarly Works Search", + Markdown: "# CORE Scholarly Works Search\n\n" + formatDeclarativeGFMTable([]string{"CORE ID", "Title", "Year", "DOI"}, rows), + Links: links, + Records: recs, + Total: wave3ScholarlyIntPtr(total), + Returned: wave3ScholarlyIntPtr(len(recs)), + Truncated: wave3ScholarlyBoolPtr(total > len(recs)), + }, true + } + + // Single work object + title := wave3ScholarlyPlain(m["title"], 300) + if title == "" { + return nil, false + } + id := wave3ScholarlyPlain(m["id"], 32) + doi := wave3ScholarlyNormalizeDOI(wave3ScholarlyStringVal(m["doi"])) + pubDate := wave3ScholarlyNormalizeDate(wave3ScholarlyFirstNonEmpty(wave3ScholarlyStringVal(m["publishedDate"]), wave3ScholarlyStringVal(m["yearPublished"]))) + publisher := wave3ScholarlyPlain(m["publisher"], 140) + abstract := wave3ScholarlyPlain(m["abstract"], 4000) + dl := SanitizeSchemaHTTPSURL(wave3ScholarlyStringVal(m["downloadUrl"]), origURL) + + var authors []string + if aArr, okA := m["authors"].([]any); okA { + for _, av := range aArr { + if len(authors) >= 16 { + break + } + switch tv := av.(type) { + case string: + if name := wave3ScholarlyPlain(tv, 100); name != "" { + authors = append(authors, name) + } + case map[string]any: + if name := wave3ScholarlyPlain(tv["name"], 100); name != "" { + authors = append(authors, name) + } + } + } + } + authorsStr := strings.Join(authors, ", ") + authorsShort := authorsStr + if len(authors) > 4 { + authorsShort = strings.Join(authors[:4], ", ") + } + + var links []string + seen := make(map[string]bool) + if id != "" { + wave3ScholarlyAddLink(&links, seen, "https://core.ac.uk/works/"+id, origURL) + } + wave3ScholarlyAddLink(&links, seen, dl, origURL) + if sft, okS := m["sourceFulltextUrls"].([]any); okS { + for _, su := range sft { + wave3ScholarlyAddLink(&links, seen, wave3ScholarlyStringVal(su), origURL) + } + } + if doi != "" { + wave3ScholarlyAddLink(&links, seen, "https://doi.org/"+doi, origURL) + } + + var bullets []string + if id != "" { + bullets = append(bullets, "- **CORE ID**: `"+id+"`") + } + if authorsStr != "" { + bullets = append(bullets, "- **Authors**: "+authorsStr) + } + if pubDate != "" { + bullets = append(bullets, "- **Published**: "+pubDate) + } + if publisher != "" { + bullets = append(bullets, "- **Publisher**: "+publisher) + } + if doi != "" { + bullets = append(bullets, "- **DOI**: `"+doi+"`") + } + if dl != "" { + bullets = append(bullets, "- **Full Text PDF**: "+dl) + } + + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + if abstract != "" { + blocks = append(blocks, "## Abstract\n\n"+abstract) + } + + rec := map[string]any{ + "source": "core-ac", + "title": title, + } + if id != "" { + rec["id"] = id + } + if doi != "" { + rec["doi"] = doi + } + if pubDate != "" { + rec["publishedDate"] = pubDate + } + if dl != "" { + rec["downloadUrl"] = dl + } + if len(authors) > 0 { + rec["authors"] = authors + } + + desc := abstract + desc = wave3ScholarlyTruncateDesc(desc) + return &DeclarativeFormattedDoc{ + Title: title, + Description: desc, + Author: authorsShort, + PublishedTime: pubDate, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: []map[string]any{rec}, + Total: wave3ScholarlyIntPtr(1), + Returned: wave3ScholarlyIntPtr(1), + }, true +} + +// ── #304 ORCID JSON ───────────────────────────────────────────────────────────────────────────── + +func wave3ScholarlyFormatORCIDJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + m, ok := parsed.(map[string]any) + if !ok || wave3ScholarlyIsGenericJSONError(m) { + return nil, false + } + + orcidID := wave3ScholarlyNormalizeORCID(wave3ScholarlyFirstNonEmpty( + wave3ScholarlyStringVal(wave3ScholarlyValAt(m, "orcid-identifier", "path")), + wave3ScholarlyStringVal(wave3ScholarlyValAt(m, "orcid-identifier", "uri")), + )) + person := wave3ScholarlyMapAt(m, "person") + if person == nil && m["name"] != nil { + person = m + } + if orcidID == "" && person == nil { + return nil, false + } + + creditName := wave3ScholarlyPlain(wave3ScholarlyValAt(person, "name", "credit-name", "value"), 140) + given := wave3ScholarlyPlain(wave3ScholarlyValAt(person, "name", "given-names", "value"), 100) + family := wave3ScholarlyPlain(wave3ScholarlyValAt(person, "name", "family-name", "value"), 100) + fullName := creditName + if fullName == "" { + fullName = strings.TrimSpace(given + " " + family) + } + if fullName == "" && orcidID == "" { + return nil, false + } + if fullName == "" { + fullName = "ORCID " + orcidID + } + + bio := wave3ScholarlyPlain(wave3ScholarlyValAt(person, "biography", "content"), 2000) + + var links []string + seen := make(map[string]bool) + profileURL := "" + if orcidID != "" { + profileURL = "https://orcid.org/" + orcidID + wave3ScholarlyAddLink(&links, seen, profileURL, origURL) + } + if ruArr, okRU := wave3ScholarlyValAt(person, "researcher-urls", "researcher-url").([]any); okRU { + for _, rv := range ruArr { + if rm, okRM := rv.(map[string]any); okRM { + wave3ScholarlyAddLink(&links, seen, wave3ScholarlyStringVal(wave3ScholarlyValAt(rm, "url", "value")), origURL) + } + } + } + + var empRows [][]string + if affGroups, okEG := wave3ScholarlyValAt(m, "activities-summary", "employments", "affiliation-group").([]any); okEG { + for _, ag := range affGroups { + if len(empRows) >= 10 { + break + } + agMap, okAG := ag.(map[string]any) + if !okAG { + continue + } + sums, _ := agMap["summaries"].([]any) + for _, sv := range sums { + sm, okSM := sv.(map[string]any) + if !okSM { + continue + } + es := wave3ScholarlyMapAt(sm, "employment-summary") + if es == nil { + continue + } + org := wave3ScholarlyPlain(wave3ScholarlyValAt(es, "organization", "name"), 140) + role := wave3ScholarlyPlain(es["role-title"], 120) + startY := wave3ScholarlyPlain(wave3ScholarlyValAt(es, "start-date", "year", "value"), 8) + endY := wave3ScholarlyPlain(wave3ScholarlyValAt(es, "end-date", "year", "value"), 8) + if org != "" { + empRows = append(empRows, []string{org, role, startY, endY}) + } + } + } + } + + var workRows [][]string + if wGroups, okWG := wave3ScholarlyValAt(m, "activities-summary", "works", "group").([]any); okWG { + for _, wg := range wGroups { + if len(workRows) >= 15 { + break + } + wgMap, okWGM := wg.(map[string]any) + if !okWGM { + continue + } + wSums, _ := wgMap["work-summary"].([]any) + if len(wSums) == 0 { + continue + } + ws, okWS := wSums[0].(map[string]any) + if !okWS { + continue + } + wt := wave3ScholarlyPlain(wave3ScholarlyValAt(ws, "title", "title", "value"), 200) + if wt == "" { + continue + } + wType := wave3ScholarlyPlain(ws["type"], 40) + wYear := wave3ScholarlyPlain(wave3ScholarlyValAt(ws, "publication-date", "year", "value"), 8) + workRows = append(workRows, []string{wt, wType, wYear}) + } + } + + var bullets []string + if orcidID != "" { + bullets = append(bullets, "- **ORCID**: `"+orcidID+"`") + } + if profileURL != "" { + bullets = append(bullets, "- **Profile**: "+profileURL) + } + if len(empRows) > 0 { + bullets = append(bullets, "- **Employments**: "+strconv.Itoa(len(empRows))) + } + if len(workRows) > 0 { + bullets = append(bullets, "- **Works Listed**: "+strconv.Itoa(len(workRows))) + } + + blocks := []string{"# " + escapeDeclMarkdownBrackets(fullName)} + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + if bio != "" { + blocks = append(blocks, "## Biography\n\n"+bio) + } + if len(empRows) > 0 { + blocks = append(blocks, "## Employments\n\n"+formatDeclarativeGFMTable([]string{"Organization", "Role", "Start", "End"}, empRows)) + } + if len(workRows) > 0 { + blocks = append(blocks, "## Works\n\n"+formatDeclarativeGFMTable([]string{"Title", "Type", "Year"}, workRows)) + } + + rec := map[string]any{ + "source": "orcid", + "name": fullName, + } + if orcidID != "" { + rec["orcid"] = orcidID + } + if profileURL != "" { + rec["url"] = profileURL + } + if bio != "" { + rec["biography"] = bio + } + + desc := bio + desc = wave3ScholarlyTruncateDesc(desc) + return &DeclarativeFormattedDoc{ + Title: fullName, + Description: desc, + Author: fullName, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: []map[string]any{rec}, + Total: wave3ScholarlyIntPtr(1), + Returned: wave3ScholarlyIntPtr(1), + }, true +} + +// ── #305 ROR v2 JSON ──────────────────────────────────────────────────────────────────────────── + +func wave3ScholarlyExtractRORDisplayName(org map[string]any) (string, []string) { + var display string + var aliases []string + if namesArr, okN := org["names"].([]any); okN { + for _, nv := range namesArr { + nm, okNM := nv.(map[string]any) + if !okNM { + continue + } + val := wave3ScholarlyPlain(nm["value"], 180) + if val == "" { + continue + } + isDisplay := false + if typesArr, okT := nm["types"].([]any); okT { + for _, tv := range typesArr { + if wave3ScholarlyStringVal(tv) == "ror_display" { + isDisplay = true + break + } + } + } + if isDisplay && display == "" { + display = val + } else if len(aliases) < 8 { + aliases = append(aliases, val) + } + } + } + if display == "" && len(aliases) > 0 { + display = aliases[0] + aliases = aliases[1:] + } + if display == "" { + display = wave3ScholarlyPlain(org["name"], 180) + } + return display, aliases +} + +func wave3ScholarlyFormatRORJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + m, ok := parsed.(map[string]any) + if !ok || wave3ScholarlyIsGenericJSONError(m) { + return nil, false + } + + // Search list (`items: [...]`) + if items, okI := m["items"].([]any); okI { + if len(items) == 0 { + return nil, false + } + var recs []map[string]any + var rows [][]string + var links []string + seen := make(map[string]bool) + for _, it := range items { + if len(recs) >= wave3ScholarlyMaxRecords { + break + } + om, okOM := it.(map[string]any) + if !okOM { + continue + } + rorID := wave3ScholarlyNormalizeRORID(wave3ScholarlyStringVal(om["id"])) + name, _ := wave3ScholarlyExtractRORDisplayName(om) + if name == "" || rorID == "" { + continue + } + status := wave3ScholarlyPlain(om["status"], 24) + types := strings.Join(wave3ScholarlyJoinStrings(om["types"], 4), ", ") + country := "" + if locs, okL := om["locations"].([]any); okL && len(locs) > 0 { + if lm, okLM := locs[0].(map[string]any); okLM { + country = wave3ScholarlyPlain(wave3ScholarlyValAt(lm, "geonames_details", "country_name"), 64) + } + } + rorURL := "https://ror.org/" + rorID + wave3ScholarlyAddLink(&links, seen, rorURL, origURL) + recs = append(recs, map[string]any{ + "source": "ror", + "rorId": rorID, + "name": name, + "status": status, + "country": country, + "url": rorURL, + }) + rows = append(rows, []string{rorID, name, types, country, status}) + } + if len(recs) == 0 { + return nil, false + } + total := len(recs) + if t, okT := wave3ScholarlyFloatVal(m["number_of_results"]); okT && int(t) > total { + total = int(t) + } + return &DeclarativeFormattedDoc{ + Title: "ROR Organization Search", + Markdown: "# ROR Organization Search\n\n" + formatDeclarativeGFMTable([]string{"ROR ID", "Name", "Types", "Country", "Status"}, rows), + Links: links, + Records: recs, + Total: wave3ScholarlyIntPtr(total), + Returned: wave3ScholarlyIntPtr(len(recs)), + Truncated: wave3ScholarlyBoolPtr(total > len(recs)), + }, true + } + + rorID := wave3ScholarlyNormalizeRORID(wave3ScholarlyStringVal(m["id"])) + name, aliases := wave3ScholarlyExtractRORDisplayName(m) + if rorID == "" || name == "" { + return nil, false + } + rorURL := "https://ror.org/" + rorID + status := wave3ScholarlyPlain(m["status"], 24) + established := wave3ScholarlyPlain(m["established"], 8) + types := wave3ScholarlyJoinStrings(m["types"], 6) + domains := wave3ScholarlyJoinStrings(m["domains"], 8) + + var links []string + seen := make(map[string]bool) + wave3ScholarlyAddLink(&links, seen, rorURL, origURL) + if linksArr, okL := m["links"].([]any); okL { + for _, lv := range linksArr { + if lm, okLM := lv.(map[string]any); okLM { + wave3ScholarlyAddLink(&links, seen, wave3ScholarlyStringVal(lm["value"]), origURL) + } + } + } + + var locNames []string + if locs, okL := m["locations"].([]any); okL { + for _, lv := range locs { + lm, okLM := lv.(map[string]any) + if !okLM { + continue + } + gd := wave3ScholarlyMapAt(lm, "geonames_details") + if gd == nil { + continue + } + city := wave3ScholarlyPlain(gd["name"], 64) + subdiv := wave3ScholarlyPlain(gd["country_subdivision_name"], 64) + country := wave3ScholarlyPlain(gd["country_name"], 64) + parts := make([]string, 0, 3) + for _, p := range []string{city, subdiv, country} { + if p != "" { + parts = append(parts, p) + } + } + if len(parts) > 0 { + locNames = append(locNames, strings.Join(parts, ", ")) + } + } + } + + var extIDs []string + if extArr, okE := m["external_ids"].([]any); okE { + for _, ev := range extArr { + em, okEM := ev.(map[string]any) + if !okEM { + continue + } + et := wave3ScholarlyPlain(em["type"], 32) + pref := wave3ScholarlyPlain(em["preferred"], 64) + if pref == "" { + allVals := wave3ScholarlyJoinStrings(em["all"], 2) + if len(allVals) > 0 { + pref = allVals[0] + } + } + if et != "" && pref != "" { + extIDs = append(extIDs, et+": "+pref) + } + } + } + + var bullets []string + bullets = append(bullets, "- **ROR ID**: `"+rorID+"`") + bullets = append(bullets, "- **ROR URL**: "+rorURL) + if status != "" { + bullets = append(bullets, "- **Status**: "+status) + } + if len(types) > 0 { + bullets = append(bullets, "- **Types**: "+strings.Join(types, ", ")) + } + if established != "" { + bullets = append(bullets, "- **Established**: "+established) + } + if len(locNames) > 0 { + bullets = append(bullets, "- **Location**: "+strings.Join(locNames, "; ")) + } + if len(domains) > 0 { + bullets = append(bullets, "- **Domains**: "+strings.Join(domains, ", ")) + } + if len(aliases) > 0 { + bullets = append(bullets, "- **Other Names**: "+strings.Join(aliases, ", ")) + } + if len(extIDs) > 0 { + bullets = append(bullets, "- **External IDs**: "+strings.Join(extIDs, "; ")) + } + + rec := map[string]any{ + "source": "ror", + "rorId": rorID, + "name": name, + "url": rorURL, + } + if status != "" { + rec["status"] = status + } + if established != "" { + rec["established"] = established + } + if len(types) > 0 { + rec["types"] = types + } + if len(domains) > 0 { + rec["domains"] = domains + } + if len(locNames) > 0 { + rec["locations"] = locNames + } + + return &DeclarativeFormattedDoc{ + Title: name, + Markdown: "# " + escapeDeclMarkdownBrackets(name) + "\n\n" + strings.Join(bullets, "\n"), + Links: links, + Records: []map[string]any{rec}, + Total: wave3ScholarlyIntPtr(1), + Returned: wave3ScholarlyIntPtr(1), + }, true +} + +// ── #306 DBLP JSON & XML ──────────────────────────────────────────────────────────────────────── + +func wave3ScholarlyFormatDBLPJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + m, ok := parsed.(map[string]any) + if !ok || wave3ScholarlyIsGenericJSONError(m) { + return nil, false + } + hitsMap := wave3ScholarlyMapAt(m, "result", "hits") + if hitsMap == nil { + return nil, false + } + hitArr, okH := hitsMap["hit"].([]any) + if !okH || len(hitArr) == 0 { + return nil, false + } + + var recs []map[string]any + var rows [][]string + var links []string + seen := make(map[string]bool) + + for _, hv := range hitArr { + if len(recs) >= wave3ScholarlyMaxRecords { + break + } + hm, okHM := hv.(map[string]any) + if !okHM { + continue + } + info := wave3ScholarlyMapAt(hm, "info") + if info == nil { + continue + } + title := wave3ScholarlyPlain(wave3ScholarlyFirstNonEmpty(wave3ScholarlyStringVal(info["title"]), wave3ScholarlyStringVal(info["author"])), 260) + if title == "" { + continue + } + venue := wave3ScholarlyPlain(info["venue"], 100) + year := wave3ScholarlyPlain(info["year"], 8) + doi := wave3ScholarlyNormalizeDOI(wave3ScholarlyStringVal(info["doi"])) + key := wave3ScholarlyPlain(info["key"], 120) + ee := SanitizeSchemaHTTPSURL(wave3ScholarlyStringVal(info["ee"]), origURL) + dblpURL := SanitizeSchemaHTTPSURL(wave3ScholarlyStringVal(info["url"]), origURL) + wave3ScholarlyAddLink(&links, seen, dblpURL, origURL) + wave3ScholarlyAddLink(&links, seen, ee, origURL) + + var authors []string + if rawAuth := wave3ScholarlyValAt(info, "authors", "author"); rawAuth != nil { + switch ta := rawAuth.(type) { + case []any: + for _, av := range ta { + if len(authors) >= 12 { + break + } + switch tv := av.(type) { + case string: + if s := wave3ScholarlyPlain(tv, 80); s != "" { + authors = append(authors, s) + } + case map[string]any: + if s := wave3ScholarlyPlain(tv["text"], 80); s != "" { + authors = append(authors, s) + } + } + } + case map[string]any: + if s := wave3ScholarlyPlain(ta["text"], 80); s != "" { + authors = append(authors, s) + } + } + } + + rec := map[string]any{ + "source": "dblp", + "title": title, + } + if key != "" { + rec["key"] = key + } + if len(authors) > 0 { + rec["authors"] = authors + } + if venue != "" { + rec["venue"] = venue + } + if year != "" { + rec["year"] = year + } + if doi != "" { + rec["doi"] = doi + } + if dblpURL != "" { + rec["url"] = dblpURL + } + recs = append(recs, rec) + rows = append(rows, []string{title, strings.Join(authors, ", "), venue, year, doi}) + } + if len(recs) == 0 { + return nil, false + } + + total := len(recs) + if f, okF := wave3ScholarlyFloatVal(hitsMap["@total"]); okF && int(f) > total { + total = int(f) + } + return &DeclarativeFormattedDoc{ + Title: "DBLP Search Results", + Markdown: "# DBLP Search Results\n\n" + formatDeclarativeGFMTable([]string{"Title", "Authors", "Venue", "Year", "DOI"}, rows), + Links: links, + Records: recs, + Total: wave3ScholarlyIntPtr(total), + Returned: wave3ScholarlyIntPtr(len(recs)), + Truncated: wave3ScholarlyBoolPtr(total > len(recs)), + }, true +} + +func wave3ScholarlyFormatDBLPXML(rawBody, origURL string) (*DeclarativeFormattedDoc, bool) { + low := asciiLowerExtractString(rawBody) + if strings.Contains(low, "anubis_version") || strings.Contains(low, "anubis_challenge") || strings.Contains(low, "making sure you're not a bot") || strings.Contains(low, " 0 { + rec["authors"] = r.Authors + } + if r.Venue != "" { + rec["venue"] = r.Venue + } + if r.Year != "" { + rec["year"] = r.Year + } + if r.EE != "" { + rec["ee"] = r.EE + } + recs = append(recs, rec) + rows = append(rows, []string{r.Title, strings.Join(r.Authors, ", "), r.Venue, r.Year}) + } + + title := records[0].Title + if len(records) > 1 { + title = "DBLP XML Records" + } + md := "# " + escapeDeclMarkdownBrackets(title) + "\n\n" + formatDeclarativeGFMTable([]string{"Title", "Authors", "Venue", "Year"}, rows) + return &DeclarativeFormattedDoc{ + Title: title, + Author: strings.Join(records[0].Authors, ", "), + PublishedTime: records[0].Year, + Markdown: md, + Links: links, + Records: recs, + Total: wave3ScholarlyIntPtr(len(recs)), + Returned: wave3ScholarlyIntPtr(len(recs)), + }, true +} + +// ── #307 bioRxiv / medRxiv JSON ───────────────────────────────────────────────────────────────── + +func wave3ScholarlyFormatBioRxivJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + m, ok := parsed.(map[string]any) + if !ok || wave3ScholarlyIsGenericJSONError(m) { + return nil, false + } + coll, okC := m["collection"].([]any) + if !okC || len(coll) == 0 { + return nil, false + } + + // Pick latest version in collection + latest, _ := coll[len(coll)-1].(map[string]any) + if latest == nil { + return nil, false + } + title := wave3ScholarlyPlain(latest["title"], 300) + doi := wave3ScholarlyNormalizeDOI(wave3ScholarlyStringVal(latest["doi"])) + if title == "" || doi == "" { + return nil, false + } + authors := wave3ScholarlyPlain(latest["authors"], 600) + date := wave3ScholarlyNormalizeDate(wave3ScholarlyStringVal(latest["date"])) + version := wave3ScholarlyPlain(latest["version"], 16) + category := wave3ScholarlyPlain(latest["category"], 80) + server := wave3ScholarlyPlain(latest["server"], 32) + license := wave3ScholarlyPlain(latest["license"], 64) + published := wave3ScholarlyPlain(latest["published"], 120) + abstract := wave3ScholarlyPlain(latest["abstract"], 4000) + jatsxml := SanitizeSchemaHTTPSURL(wave3ScholarlyStringVal(latest["jatsxml"]), origURL) + + host := "www.biorxiv.org" + if strings.EqualFold(server, "medrxiv") || strings.Contains(strings.ToLower(origURL), "/medrxiv/") { + host = "www.medrxiv.org" + } + pageURL := "https://" + host + "/content/" + doi + if version != "" { + pageURL += "v" + version + } + + var bullets []string + bullets = append(bullets, "- **DOI**: `"+doi+"`") + if server != "" { + bullets = append(bullets, "- **Server**: "+server) + } + if version != "" { + bullets = append(bullets, "- **Version**: v"+version) + } + if authors != "" { + bullets = append(bullets, "- **Authors**: "+authors) + } + if date != "" { + bullets = append(bullets, "- **Posted**: "+date) + } + if category != "" { + bullets = append(bullets, "- **Category**: "+category) + } + if license != "" { + bullets = append(bullets, "- **License**: "+license) + } + if published != "" && published != "NA" { + bullets = append(bullets, "- **Published DOI**: "+published) + } + if jatsxml != "" { + bullets = append(bullets, "- **JATS XML**: "+jatsxml) + } + + blocks := []string{"# " + escapeDeclMarkdownBrackets(title), strings.Join(bullets, "\n")} + if abstract != "" { + blocks = append(blocks, "## Abstract\n\n"+abstract) + } + + var links []string + seen := make(map[string]bool) + wave3ScholarlyAddLink(&links, seen, pageURL, origURL) + wave3ScholarlyAddLink(&links, seen, "https://doi.org/"+doi, origURL) + wave3ScholarlyAddLink(&links, seen, jatsxml, origURL) + + rec := map[string]any{ + "source": "biorxiv-medrxiv", + "doi": doi, + "title": title, + "server": server, + "version": version, + "date": date, + "category": category, + } + if authors != "" { + rec["authors"] = authors + } + if license != "" { + rec["license"] = license + } + + desc := abstract + desc = wave3ScholarlyTruncateDesc(desc) + return &DeclarativeFormattedDoc{ + Title: title, + Description: desc, + Author: authors, + PublishedTime: date, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: []map[string]any{rec}, + Total: wave3ScholarlyIntPtr(len(coll)), + Returned: wave3ScholarlyIntPtr(1), + }, true +} + +// ── #308 NASA ADS JSON ────────────────────────────────────────────────────────────────────────── + +func wave3ScholarlyFormatNASAADSJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + m, ok := parsed.(map[string]any) + if !ok || wave3ScholarlyIsGenericJSONError(m) { + return nil, false + } + resp := wave3ScholarlyMapAt(m, "response") + if resp == nil { + return nil, false + } + docs, okD := resp["docs"].([]any) + if !okD || len(docs) == 0 { + return nil, false + } + + var recs []map[string]any + var rows [][]string + var links []string + seen := make(map[string]bool) + + for _, dv := range docs { + if len(recs) >= wave3ScholarlyMaxRecords { + break + } + dm, okDM := dv.(map[string]any) + if !okDM { + continue + } + bibcode := wave3ScholarlyPlain(dm["bibcode"], 48) + titles := wave3ScholarlyJoinStrings(dm["title"], 2) + title := "" + if len(titles) > 0 { + title = titles[0] + } else { + title = wave3ScholarlyPlain(dm["title"], 260) + } + if title == "" && bibcode == "" { + continue + } + if title == "" { + title = bibcode + } + authors := wave3ScholarlyJoinStrings(dm["author"], 12) + pub := wave3ScholarlyPlain(dm["pub"], 120) + pubDate := wave3ScholarlyNormalizeDate(wave3ScholarlyFirstNonEmpty(wave3ScholarlyStringVal(dm["pubdate"]), wave3ScholarlyStringVal(dm["year"]))) + citCount := wave3ScholarlyPlain(dm["citation_count"], 16) + abstract := wave3ScholarlyPlain(dm["abstract"], 3000) + dois := wave3ScholarlyJoinStrings(dm["doi"], 2) + doi := "" + if len(dois) > 0 { + doi = wave3ScholarlyNormalizeDOI(dois[0]) + } + absURL := "" + if bibcode != "" { + absURL = "https://ui.adsabs.harvard.edu/abs/" + url.PathEscape(bibcode) + "/abstract" + wave3ScholarlyAddLink(&links, seen, absURL, origURL) + } + if doi != "" { + wave3ScholarlyAddLink(&links, seen, "https://doi.org/"+doi, origURL) + } + + rec := map[string]any{ + "source": "nasa-ads", + "bibcode": bibcode, + "title": title, + } + if len(authors) > 0 { + rec["authors"] = authors + } + if pub != "" { + rec["publication"] = pub + } + if pubDate != "" { + rec["publishedDate"] = pubDate + } + if citCount != "" { + rec["citationCount"] = citCount + } + if doi != "" { + rec["doi"] = doi + } + if abstract != "" { + rec["abstract"] = abstract + } + if absURL != "" { + rec["url"] = absURL + } + recs = append(recs, rec) + rows = append(rows, []string{bibcode, title, pubDate, citCount, doi}) + } + if len(recs) == 0 { + return nil, false + } + + total := len(recs) + if f, okF := wave3ScholarlyFloatVal(resp["numFound"]); okF && int(f) > total { + total = int(f) + } + + if len(recs) == 1 { + r := recs[0] + title := wave3ScholarlyStringVal(r["title"]) + var bullets []string + if b := wave3ScholarlyStringVal(r["bibcode"]); b != "" { + bullets = append(bullets, "- **Bibcode**: `"+b+"`") + } + if a, okA := r["authors"].([]string); okA && len(a) > 0 { + bullets = append(bullets, "- **Authors**: "+strings.Join(a, ", ")) + } + if p := wave3ScholarlyStringVal(r["publication"]); p != "" { + bullets = append(bullets, "- **Publication**: "+p) + } + if pd := wave3ScholarlyStringVal(r["publishedDate"]); pd != "" { + bullets = append(bullets, "- **Published**: "+pd) + } + if d := wave3ScholarlyStringVal(r["doi"]); d != "" { + bullets = append(bullets, "- **DOI**: `"+d+"`") + } + if cc := wave3ScholarlyStringVal(r["citationCount"]); cc != "" { + bullets = append(bullets, "- **Citations**: "+cc) + } + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + abs := wave3ScholarlyStringVal(r["abstract"]) + if abs != "" { + blocks = append(blocks, "## Abstract\n\n"+abs) + } + desc := abs + desc = wave3ScholarlyTruncateDesc(desc) + authShort := "" + if a, okA := r["authors"].([]string); okA && len(a) > 0 { + if len(a) > 4 { + authShort = strings.Join(a[:4], ", ") + } else { + authShort = strings.Join(a, ", ") + } + } + return &DeclarativeFormattedDoc{ + Title: title, + Description: desc, + Author: authShort, + PublishedTime: wave3ScholarlyStringVal(r["publishedDate"]), + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: recs, + Total: wave3ScholarlyIntPtr(total), + Returned: wave3ScholarlyIntPtr(1), + }, true + } + + return &DeclarativeFormattedDoc{ + Title: "NASA ADS Search Results", + Markdown: "# NASA ADS Search Results\n\n" + formatDeclarativeGFMTable([]string{"Bibcode", "Title", "Date", "Citations", "DOI"}, rows), + Links: links, + Records: recs, + Total: wave3ScholarlyIntPtr(total), + Returned: wave3ScholarlyIntPtr(len(recs)), + Truncated: wave3ScholarlyBoolPtr(total > len(recs)), + }, true +} + +// ── #309 NIH RePORTER JSON ────────────────────────────────────────────────────────────────────── + +func wave3ScholarlyFormatNIHReporterJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + m, ok := parsed.(map[string]any) + if !ok || wave3ScholarlyIsGenericJSONError(m) { + return nil, false + } + resArr, okR := m["results"].([]any) + if !okR || len(resArr) == 0 { + return nil, false + } + + var recs []map[string]any + var rows [][]string + var links []string + seen := make(map[string]bool) + + for _, rv := range resArr { + if len(recs) >= wave3ScholarlyMaxRecords { + break + } + pm, okPM := rv.(map[string]any) + if !okPM { + continue + } + title := wave3ScholarlyPlain(pm["project_title"], 280) + projNum := wave3ScholarlyPlain(pm["project_num"], 48) + applID := wave3ScholarlyPlain(pm["appl_id"], 24) + if title == "" && projNum == "" { + continue + } + if title == "" { + title = projNum + } + orgName := wave3ScholarlyPlain(wave3ScholarlyValAt(pm, "organization", "org_name"), 140) + orgCity := wave3ScholarlyPlain(wave3ScholarlyValAt(pm, "organization", "org_city"), 64) + orgState := wave3ScholarlyPlain(wave3ScholarlyValAt(pm, "organization", "org_state"), 16) + awardAmt := wave3ScholarlyFormatAmount(pm["award_amount"]) + fy := wave3ScholarlyPlain(pm["fiscal_year"], 8) + startDate := wave3ScholarlyNormalizeDate(wave3ScholarlyStringVal(pm["project_start_date"])) + endDate := wave3ScholarlyNormalizeDate(wave3ScholarlyStringVal(pm["project_end_date"])) + icName := wave3ScholarlyPlain(wave3ScholarlyValAt(pm, "agency_ic_admin", "name"), 120) + abstract := wave3ScholarlyPlain(pm["abstract_text"], 3500) + detailURL := SanitizeSchemaHTTPSURL(wave3ScholarlyStringVal(pm["project_detail_url"]), origURL) + if detailURL == "" && applID != "" { + detailURL = "https://reporter.nih.gov/project-details/" + applID + } + wave3ScholarlyAddLink(&links, seen, detailURL, origURL) + + var pis []string + if piArr, okPI := pm["principal_investigators"].([]any); okPI { + for _, piv := range piArr { + if len(pis) >= 8 { + break + } + if pim, okPIM := piv.(map[string]any); okPIM { + if fn := wave3ScholarlyPlain(pim["full_name"], 100); fn != "" { + pis = append(pis, fn) + } else { + comb := strings.TrimSpace(wave3ScholarlyPlain(pim["first_name"], 50) + " " + wave3ScholarlyPlain(pim["last_name"], 50)) + if comb != "" { + pis = append(pis, comb) + } + } + } + } + } + + rec := map[string]any{ + "source": "nih-reporter", + "title": title, + "projectNum": projNum, + } + if applID != "" { + rec["applId"] = applID + } + if orgName != "" { + rec["organization"] = orgName + } + if orgCity != "" && orgState != "" { + rec["location"] = orgCity + ", " + orgState + } + if len(pis) > 0 { + rec["principalInvestigators"] = pis + } + if awardAmt != "" { + rec["awardAmount"] = "$" + awardAmt + } + if fy != "" { + rec["fiscalYear"] = fy + } + if startDate != "" { + rec["startDate"] = startDate + } + if endDate != "" { + rec["endDate"] = endDate + } + if icName != "" { + rec["agencyIC"] = icName + } + if abstract != "" { + rec["abstract"] = abstract + } + if detailURL != "" { + rec["url"] = detailURL + } + recs = append(recs, rec) + amtDisp := "" + if awardAmt != "" { + amtDisp = "$" + awardAmt + } + rows = append(rows, []string{projNum, title, orgName, fy, amtDisp}) + } + if len(recs) == 0 { + return nil, false + } + + total := len(recs) + if f, okF := wave3ScholarlyFloatVal(wave3ScholarlyValAt(m, "meta", "total")); okF && int(f) > total { + total = int(f) + } + + if len(recs) == 1 { + r := recs[0] + title := wave3ScholarlyStringVal(r["title"]) + var bullets []string + if pn := wave3ScholarlyStringVal(r["projectNum"]); pn != "" { + bullets = append(bullets, "- **Project Number**: `"+pn+"`") + } + if aid := wave3ScholarlyStringVal(r["applId"]); aid != "" { + bullets = append(bullets, "- **Application ID**: `"+aid+"`") + } + if pis, okPI := r["principalInvestigators"].([]string); okPI && len(pis) > 0 { + bullets = append(bullets, "- **Principal Investigators**: "+strings.Join(pis, ", ")) + } + if org := wave3ScholarlyStringVal(r["organization"]); org != "" { + bullets = append(bullets, "- **Organization**: "+org) + } + if ic := wave3ScholarlyStringVal(r["agencyIC"]); ic != "" { + bullets = append(bullets, "- **Administering IC**: "+ic) + } + if fy := wave3ScholarlyStringVal(r["fiscalYear"]); fy != "" { + bullets = append(bullets, "- **Fiscal Year**: "+fy) + } + if amt := wave3ScholarlyStringVal(r["awardAmount"]); amt != "" { + bullets = append(bullets, "- **Award Amount**: "+amt) + } + if sd := wave3ScholarlyStringVal(r["startDate"]); sd != "" { + ed := wave3ScholarlyStringVal(r["endDate"]) + if ed != "" { + bullets = append(bullets, "- **Project Dates**: "+sd+" to "+ed) + } else { + bullets = append(bullets, "- **Start Date**: "+sd) + } + } + blocks := []string{"# " + escapeDeclMarkdownBrackets(title), strings.Join(bullets, "\n")} + abs := wave3ScholarlyStringVal(r["abstract"]) + if abs != "" { + blocks = append(blocks, "## Abstract\n\n"+abs) + } + desc := abs + desc = wave3ScholarlyTruncateDesc(desc) + authStr := "" + if pis, okPI := r["principalInvestigators"].([]string); okPI { + authStr = strings.Join(pis, ", ") + } + return &DeclarativeFormattedDoc{ + Title: title, + Description: desc, + Author: authStr, + PublishedTime: wave3ScholarlyStringVal(r["startDate"]), + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: recs, + Total: wave3ScholarlyIntPtr(total), + Returned: wave3ScholarlyIntPtr(1), + }, true + } + + return &DeclarativeFormattedDoc{ + Title: "NIH RePORTER Projects", + Markdown: "# NIH RePORTER Projects\n\n" + formatDeclarativeGFMTable([]string{"Project #", "Title", "Organization", "FY", "Award"}, rows), + Links: links, + Records: recs, + Total: wave3ScholarlyIntPtr(total), + Returned: wave3ScholarlyIntPtr(len(recs)), + Truncated: wave3ScholarlyBoolPtr(total > len(recs)), + }, true +} + +// ── #310 NSF Awards JSON ──────────────────────────────────────────────────────────────────────── + +func wave3ScholarlyFormatNSFAwardsJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + m, ok := parsed.(map[string]any) + if !ok || wave3ScholarlyIsGenericJSONError(m) { + return nil, false + } + resp := wave3ScholarlyMapAt(m, "response") + if resp == nil { + return nil, false + } + if sn, exists := resp["serviceNotification"]; exists && sn != nil { + if arr, okSN := sn.([]any); okSN && len(arr) > 0 { + return nil, false + } + } + awards, okA := resp["award"].([]any) + if !okA || len(awards) == 0 { + return nil, false + } + + var recs []map[string]any + var rows [][]string + var links []string + seen := make(map[string]bool) + + for _, av := range awards { + if len(recs) >= wave3ScholarlyMaxRecords { + break + } + am, okAM := av.(map[string]any) + if !okAM { + continue + } + id := wave3ScholarlyPlain(am["id"], 24) + title := wave3ScholarlyPlain(am["title"], 280) + if id == "" || title == "" { + continue + } + agency := wave3ScholarlyPlain(am["agency"], 32) + awardee := wave3ScholarlyFirstNonEmpty(wave3ScholarlyPlain(am["awardeeName"], 140), wave3ScholarlyPlain(am["awardee"], 140)) + city := wave3ScholarlyPlain(am["awardeeCity"], 64) + state := wave3ScholarlyPlain(am["awardeeStateCode"], 16) + pi := wave3ScholarlyPlain(am["pdPIName"], 100) + if pi == "" { + pi = strings.TrimSpace(wave3ScholarlyPlain(am["piFirstName"], 50) + " " + wave3ScholarlyPlain(am["piLastName"], 50)) + } + amt := wave3ScholarlyFormatAmount(wave3ScholarlyFirstNonEmpty(wave3ScholarlyStringVal(am["fundsObligatedAmt"]), wave3ScholarlyStringVal(am["estimatedTotalAmt"]))) + date := wave3ScholarlyNormalizeDate(wave3ScholarlyStringVal(am["date"])) + startDate := wave3ScholarlyNormalizeDate(wave3ScholarlyStringVal(am["startDate"])) + expDate := wave3ScholarlyNormalizeDate(wave3ScholarlyStringVal(am["expDate"])) + prog := wave3ScholarlyPlain(am["fundProgramName"], 140) + abstract := wave3ScholarlyPlain(am["abstractText"], 3500) + awardURL := "https://www.nsf.gov/awardsearch/show-award?AWD_ID=" + url.QueryEscape(id) + wave3ScholarlyAddLink(&links, seen, awardURL, origURL) + + rec := map[string]any{ + "source": "nsf-awards", + "awardId": id, + "title": title, + } + if agency != "" { + rec["agency"] = agency + } + if awardee != "" { + rec["awardeeName"] = awardee + } + if pi != "" { + rec["principalInvestigator"] = pi + } + if amt != "" { + rec["fundsObligatedAmt"] = "$" + amt + } + if date != "" { + rec["date"] = date + } + if startDate != "" { + rec["startDate"] = startDate + } + if expDate != "" { + rec["expDate"] = expDate + } + if prog != "" { + rec["program"] = prog + } + if city != "" && state != "" { + rec["location"] = city + ", " + state + } + if abstract != "" { + rec["abstract"] = abstract + } + rec["url"] = awardURL + recs = append(recs, rec) + amtDisp := "" + if amt != "" { + amtDisp = "$" + amt + } + rows = append(rows, []string{id, title, awardee, pi, amtDisp}) + } + if len(recs) == 0 { + return nil, false + } + + if len(recs) == 1 { + r := recs[0] + title := wave3ScholarlyStringVal(r["title"]) + var bullets []string + bullets = append(bullets, "- **NSF Award ID**: `"+wave3ScholarlyStringVal(r["awardId"])+"`") + if pi := wave3ScholarlyStringVal(r["principalInvestigator"]); pi != "" { + bullets = append(bullets, "- **Principal Investigator**: "+pi) + } + if aw := wave3ScholarlyStringVal(r["awardeeName"]); aw != "" { + bullets = append(bullets, "- **Awardee**: "+aw) + } + if loc := wave3ScholarlyStringVal(r["location"]); loc != "" { + bullets = append(bullets, "- **Location**: "+loc) + } + if prog := wave3ScholarlyStringVal(r["program"]); prog != "" { + bullets = append(bullets, "- **Program**: "+prog) + } + if amt := wave3ScholarlyStringVal(r["fundsObligatedAmt"]); amt != "" { + bullets = append(bullets, "- **Obligated Amount**: "+amt) + } + if d := wave3ScholarlyStringVal(r["date"]); d != "" { + bullets = append(bullets, "- **Award Date**: "+d) + } + if sd := wave3ScholarlyStringVal(r["startDate"]); sd != "" { + ed := wave3ScholarlyStringVal(r["expDate"]) + if ed != "" { + bullets = append(bullets, "- **Term**: "+sd+" to "+ed) + } else { + bullets = append(bullets, "- **Start Date**: "+sd) + } + } + blocks := []string{"# " + escapeDeclMarkdownBrackets(title), strings.Join(bullets, "\n")} + abs := wave3ScholarlyStringVal(r["abstract"]) + if abs != "" { + blocks = append(blocks, "## Abstract\n\n"+abs) + } + desc := abs + desc = wave3ScholarlyTruncateDesc(desc) + return &DeclarativeFormattedDoc{ + Title: title, + Description: desc, + Author: wave3ScholarlyStringVal(r["principalInvestigator"]), + PublishedTime: wave3ScholarlyStringVal(r["date"]), + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: recs, + Total: wave3ScholarlyIntPtr(1), + Returned: wave3ScholarlyIntPtr(1), + }, true + } + + return &DeclarativeFormattedDoc{ + Title: "NSF Awards Search", + Markdown: "# NSF Awards Search\n\n" + formatDeclarativeGFMTable([]string{"Award ID", "Title", "Awardee", "PI", "Amount"}, rows), + Links: links, + Records: recs, + Total: wave3ScholarlyIntPtr(len(recs)), + Returned: wave3ScholarlyIntPtr(len(recs)), + }, true +} + +// ── #311 DOE OSTI JSON ────────────────────────────────────────────────────────────────────────── + +func wave3ScholarlyFormatDOEOSTIJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + var items []any + switch pv := parsed.(type) { + case []any: + items = pv + case map[string]any: + if wave3ScholarlyIsGenericJSONError(pv) { + return nil, false + } + if arr, okR := pv["records"].([]any); okR { + items = arr + } else { + items = []any{pv} + } + } + if len(items) == 0 { + return nil, false + } + + var recs []map[string]any + var rows [][]string + var links []string + seen := make(map[string]bool) + + for _, it := range items { + if len(recs) >= wave3ScholarlyMaxRecords { + break + } + rm, okRM := it.(map[string]any) + if !okRM { + continue + } + title := wave3ScholarlyPlain(rm["title"], 280) + ostiID := wave3ScholarlyPlain(rm["osti_id"], 24) + if title == "" { + continue + } + doi := wave3ScholarlyNormalizeDOI(wave3ScholarlyStringVal(rm["doi"])) + pubDate := wave3ScholarlyNormalizeDate(wave3ScholarlyStringVal(rm["publication_date"])) + prodType := wave3ScholarlyPlain(rm["product_type"], 64) + journal := wave3ScholarlyPlain(rm["journal_name"], 140) + publisher := wave3ScholarlyPlain(rm["publisher"], 140) + desc := wave3ScholarlyPlain(rm["description"], 3500) + authors := wave3ScholarlyJoinStrings(rm["authors"], 12) + researchOrgs := wave3ScholarlyJoinStrings(rm["research_orgs"], 6) + sponsorOrgs := wave3ScholarlyJoinStrings(rm["sponsor_orgs"], 6) + subjects := wave3ScholarlyJoinStrings(rm["subjects"], 6) + + biblioURL := "" + if ostiID != "" { + biblioURL = "https://www.osti.gov/biblio/" + ostiID + wave3ScholarlyAddLink(&links, seen, biblioURL, origURL) + } + if linkArr, okL := rm["links"].([]any); okL { + for _, lv := range linkArr { + if lm, okLM := lv.(map[string]any); okLM { + wave3ScholarlyAddLink(&links, seen, wave3ScholarlyStringVal(lm["href"]), origURL) + } + } + } + if doi != "" { + wave3ScholarlyAddLink(&links, seen, "https://doi.org/"+doi, origURL) + } + + rec := map[string]any{ + "source": "doe-osti", + "title": title, + } + if ostiID != "" { + rec["ostiId"] = ostiID + } + if doi != "" { + rec["doi"] = doi + } + if pubDate != "" { + rec["publicationDate"] = pubDate + } + if prodType != "" { + rec["productType"] = prodType + } + if journal != "" { + rec["journalName"] = journal + } + if publisher != "" { + rec["publisher"] = publisher + } + if len(authors) > 0 { + rec["authors"] = authors + } + if len(researchOrgs) > 0 { + rec["researchOrgs"] = researchOrgs + } + if len(sponsorOrgs) > 0 { + rec["sponsorOrgs"] = sponsorOrgs + } + if len(subjects) > 0 { + rec["subjects"] = subjects + } + if desc != "" { + rec["description"] = desc + } + if biblioURL != "" { + rec["url"] = biblioURL + } + recs = append(recs, rec) + rows = append(rows, []string{ostiID, title, prodType, pubDate, doi}) + } + if len(recs) == 0 { + return nil, false + } + + if len(recs) == 1 { + r := recs[0] + title := wave3ScholarlyStringVal(r["title"]) + var bullets []string + if oid := wave3ScholarlyStringVal(r["ostiId"]); oid != "" { + bullets = append(bullets, "- **OSTI ID**: `"+oid+"`") + } + if a, okA := r["authors"].([]string); okA && len(a) > 0 { + bullets = append(bullets, "- **Authors**: "+strings.Join(a, "; ")) + } + if pt := wave3ScholarlyStringVal(r["productType"]); pt != "" { + bullets = append(bullets, "- **Product Type**: "+pt) + } + if j := wave3ScholarlyStringVal(r["journalName"]); j != "" { + bullets = append(bullets, "- **Journal**: "+j) + } + if pub := wave3ScholarlyStringVal(r["publisher"]); pub != "" { + bullets = append(bullets, "- **Publisher**: "+pub) + } + if pd := wave3ScholarlyStringVal(r["publicationDate"]); pd != "" { + bullets = append(bullets, "- **Published**: "+pd) + } + if d := wave3ScholarlyStringVal(r["doi"]); d != "" { + bullets = append(bullets, "- **DOI**: `"+d+"`") + } + if ro, okRO := r["researchOrgs"].([]string); okRO && len(ro) > 0 { + bullets = append(bullets, "- **Research Organizations**: "+strings.Join(ro, "; ")) + } + if so, okSO := r["sponsorOrgs"].([]string); okSO && len(so) > 0 { + bullets = append(bullets, "- **Sponsoring Organizations**: "+strings.Join(so, "; ")) + } + blocks := []string{"# " + escapeDeclMarkdownBrackets(title), strings.Join(bullets, "\n")} + desc := wave3ScholarlyStringVal(r["description"]) + if desc != "" { + blocks = append(blocks, "## Abstract\n\n"+desc) + } + shortDesc := desc + shortDesc = wave3ScholarlyTruncateDesc(shortDesc) + authShort := "" + if a, okA := r["authors"].([]string); okA && len(a) > 0 { + if len(a) > 4 { + authShort = strings.Join(a[:4], "; ") + } else { + authShort = strings.Join(a, "; ") + } + } + return &DeclarativeFormattedDoc{ + Title: title, + Description: shortDesc, + Author: authShort, + PublishedTime: wave3ScholarlyStringVal(r["publicationDate"]), + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: recs, + Total: wave3ScholarlyIntPtr(1), + Returned: wave3ScholarlyIntPtr(1), + }, true + } + + return &DeclarativeFormattedDoc{ + Title: "DOE OSTI Records", + Markdown: "# DOE OSTI Records\n\n" + formatDeclarativeGFMTable([]string{"OSTI ID", "Title", "Type", "Published", "DOI"}, rows), + Links: links, + Records: recs, + Total: wave3ScholarlyIntPtr(len(recs)), + Returned: wave3ScholarlyIntPtr(len(recs)), + }, true +} + +// ── #312 Research Repository Pack JSON (Zenodo, Figshare, Dryad, OSF) ─────────────────────────── + +func wave3ScholarlyFormatRepoPackJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + m, ok := parsed.(map[string]any) + if !ok || wave3ScholarlyIsGenericJSONError(m) { + return nil, false + } + + var repoName, recID, title, desc, doi, pubDate, license, itemURL string + var authors, keywords []string + var fileCount int + + lowURL := strings.ToLower(origURL) + + // 1. OSF JSON:API (`data.type == "nodes"`) + if dataObj := wave3ScholarlyMapAt(m, "data"); dataObj != nil && wave3ScholarlyPlain(dataObj["type"], 24) == "nodes" { + repoName = "OSF" + recID = wave3ScholarlyPlain(dataObj["id"], 32) + attrs := wave3ScholarlyMapAt(dataObj, "attributes") + if attrs == nil { + return nil, false + } + title = wave3ScholarlyPlain(attrs["title"], 280) + desc = wave3ScholarlyPlain(attrs["description"], 3500) + pubDate = wave3ScholarlyNormalizeDate(wave3ScholarlyFirstNonEmpty(wave3ScholarlyStringVal(attrs["date_modified"]), wave3ScholarlyStringVal(attrs["date_created"]))) + keywords = wave3ScholarlyJoinStrings(attrs["tags"], 10) + itemURL = SanitizeSchemaHTTPSURL(wave3ScholarlyStringVal(wave3ScholarlyValAt(dataObj, "links", "html")), origURL) + if itemURL == "" && recID != "" { + itemURL = "https://osf.io/" + recID + "/" + } + } else if m["metadata"] != nil && (strings.Contains(lowURL, "zenodo.org") || m["conceptrecid"] != nil || m["recid"] != nil) { + // 2. Zenodo record JSON + repoName = "Zenodo" + recID = wave3ScholarlyPlain(m["id"], 32) + meta := wave3ScholarlyMapAt(m, "metadata") + if meta == nil { + return nil, false + } + title = wave3ScholarlyPlain(meta["title"], 280) + desc = wave3ScholarlyPlain(wave3ScholarlyCleanText(wave3ScholarlyStringVal(meta["description"])), 3500) + doi = wave3ScholarlyNormalizeDOI(wave3ScholarlyFirstNonEmpty(wave3ScholarlyStringVal(m["doi"]), wave3ScholarlyStringVal(meta["doi"]))) + pubDate = wave3ScholarlyNormalizeDate(wave3ScholarlyStringVal(meta["publication_date"])) + license = wave3ScholarlyPlain(wave3ScholarlyValAt(meta, "license", "id"), 64) + keywords = wave3ScholarlyJoinStrings(meta["keywords"], 10) + if creators, okC := meta["creators"].([]any); okC { + for _, cv := range creators { + if len(authors) >= 16 { + break + } + if cm, okCM := cv.(map[string]any); okCM { + if n := wave3ScholarlyPlain(cm["name"], 100); n != "" { + authors = append(authors, n) + } + } + } + } + if files, okF := m["files"].([]any); okF { + fileCount = len(files) + } + itemURL = SanitizeSchemaHTTPSURL(wave3ScholarlyStringVal(wave3ScholarlyValAt(m, "links", "self_html")), origURL) + if itemURL == "" && recID != "" { + itemURL = "https://zenodo.org/records/" + recID + } + } else if strings.Contains(lowURL, "datadryad.org") || m["identifier"] != nil && (m["storageSize"] != nil || m["versionNumber"] != nil) { + // 3. Dryad API v2 dataset JSON + repoName = "Dryad" + recID = wave3ScholarlyPlain(m["id"], 32) + title = wave3ScholarlyPlain(m["title"], 280) + desc = wave3ScholarlyPlain(wave3ScholarlyCleanText(wave3ScholarlyStringVal(m["abstract"])), 3500) + doi = wave3ScholarlyNormalizeDOI(wave3ScholarlyStringVal(m["identifier"])) + pubDate = wave3ScholarlyNormalizeDate(wave3ScholarlyStringVal(m["publicationDate"])) + license = wave3ScholarlyPlain(m["license"], 120) + keywords = wave3ScholarlyJoinStrings(m["keywords"], 10) + if aArr, okA := m["authors"].([]any); okA { + for _, av := range aArr { + if len(authors) >= 16 { + break + } + if am, okAM := av.(map[string]any); okAM { + full := strings.TrimSpace(wave3ScholarlyPlain(am["firstName"], 50) + " " + wave3ScholarlyPlain(am["lastName"], 50)) + if full != "" { + authors = append(authors, full) + } + } + } + } + if doi != "" { + itemURL = "https://datadryad.org/dataset/doi:" + doi + } + } else { + // 4. Figshare API v2 article JSON + repoName = "Figshare" + recID = wave3ScholarlyPlain(m["id"], 32) + title = wave3ScholarlyPlain(m["title"], 280) + desc = wave3ScholarlyPlain(wave3ScholarlyCleanText(wave3ScholarlyStringVal(m["description"])), 3500) + doi = wave3ScholarlyNormalizeDOI(wave3ScholarlyStringVal(m["doi"])) + pubDate = wave3ScholarlyNormalizeDate(wave3ScholarlyFirstNonEmpty(wave3ScholarlyStringVal(m["published_date"]), wave3ScholarlyStringVal(m["posted_date"]), wave3ScholarlyStringVal(m["created_date"]))) + license = wave3ScholarlyPlain(wave3ScholarlyValAt(m, "license", "name"), 80) + keywords = wave3ScholarlyJoinStrings(m["tags"], 10) + if aArr, okA := m["authors"].([]any); okA { + for _, av := range aArr { + if len(authors) >= 16 { + break + } + if am, okAM := av.(map[string]any); okAM { + if fn := wave3ScholarlyPlain(am["full_name"], 100); fn != "" { + authors = append(authors, fn) + } + } + } + } + if files, okF := m["files"].([]any); okF { + fileCount = len(files) + } + itemURL = SanitizeSchemaHTTPSURL(wave3ScholarlyFirstNonEmpty(wave3ScholarlyStringVal(m["url_public_html"]), wave3ScholarlyStringVal(m["figshare_url"])), origURL) + } + + if title == "" { + return nil, false + } + + var bullets []string + bullets = append(bullets, "- **Repository**: "+repoName) + if recID != "" { + bullets = append(bullets, "- **Record ID**: `"+recID+"`") + } + if doi != "" { + bullets = append(bullets, "- **DOI**: `"+doi+"`") + } + if len(authors) > 0 { + bullets = append(bullets, "- **Authors**: "+strings.Join(authors, ", ")) + } + if pubDate != "" { + bullets = append(bullets, "- **Published**: "+pubDate) + } + if license != "" { + bullets = append(bullets, "- **License**: "+license) + } + if fileCount > 0 { + bullets = append(bullets, "- **Files**: "+strconv.Itoa(fileCount)) + } + if len(keywords) > 0 { + bullets = append(bullets, "- **Keywords**: "+strings.Join(keywords, ", ")) + } + if itemURL != "" { + bullets = append(bullets, "- **URL**: "+itemURL) + } + + blocks := []string{"# " + escapeDeclMarkdownBrackets(title), strings.Join(bullets, "\n")} + if desc != "" { + blocks = append(blocks, "## Description\n\n"+desc) + } + + var links []string + seen := make(map[string]bool) + wave3ScholarlyAddLink(&links, seen, itemURL, origURL) + if doi != "" { + wave3ScholarlyAddLink(&links, seen, "https://doi.org/"+doi, origURL) + } + + rec := map[string]any{ + "source": "research-repo-pack", + "repository": repoName, + "title": title, + } + if recID != "" { + rec["id"] = recID + } + if doi != "" { + rec["doi"] = doi + } + if pubDate != "" { + rec["publishedDate"] = pubDate + } + if license != "" { + rec["license"] = license + } + if len(authors) > 0 { + rec["authors"] = authors + } + if itemURL != "" { + rec["url"] = itemURL + } + + shortDesc := desc + shortDesc = wave3ScholarlyTruncateDesc(shortDesc) + return &DeclarativeFormattedDoc{ + Title: title, + Description: shortDesc, + Author: strings.Join(authors, ", "), + PublishedTime: pubDate, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: []map[string]any{rec}, + Total: wave3ScholarlyIntPtr(1), + Returned: wave3ScholarlyIntPtr(1), + }, true +} + +// ── #313 DataCite JSON:API ────────────────────────────────────────────────────────────────────── + +func wave3ScholarlyFormatDataCiteJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + m, ok := parsed.(map[string]any) + if !ok || wave3ScholarlyIsGenericJSONError(m) { + return nil, false + } + + var items []map[string]any + switch dv := m["data"].(type) { + case map[string]any: + items = []map[string]any{dv} + case []any: + for _, el := range dv { + if len(items) >= wave3ScholarlyMaxRecords { + break + } + if em, okEM := el.(map[string]any); okEM { + items = append(items, em) + } + } + } + if len(items) == 0 { + return nil, false + } + + var recs []map[string]any + var rows [][]string + var links []string + seen := make(map[string]bool) + + for _, item := range items { + attrs := wave3ScholarlyMapAt(item, "attributes") + if attrs == nil { + continue + } + doi := wave3ScholarlyNormalizeDOI(wave3ScholarlyFirstNonEmpty(wave3ScholarlyStringVal(attrs["doi"]), wave3ScholarlyStringVal(item["id"]))) + title := "" + if titles, okT := attrs["titles"].([]any); okT && len(titles) > 0 { + if tm, okTM := titles[0].(map[string]any); okTM { + title = wave3ScholarlyPlain(tm["title"], 280) + } + } + if title == "" && doi == "" { + continue + } + if title == "" { + title = doi + } + publisher := wave3ScholarlyPlain(attrs["publisher"], 140) + pubYear := wave3ScholarlyPlain(attrs["publicationYear"], 8) + resType := wave3ScholarlyPlain(wave3ScholarlyValAt(attrs, "types", "resourceTypeGeneral"), 64) + targetURL := SanitizeSchemaHTTPSURL(wave3ScholarlyStringVal(attrs["url"]), origURL) + wave3ScholarlyAddLink(&links, seen, targetURL, origURL) + if doi != "" { + wave3ScholarlyAddLink(&links, seen, "https://doi.org/"+doi, origURL) + wave3ScholarlyAddLink(&links, seen, "https://commons.datacite.org/doi.org/"+doi, origURL) + } + + var creators []string + if crArr, okCR := attrs["creators"].([]any); okCR { + for _, cv := range crArr { + if len(creators) >= 16 { + break + } + if cm, okCM := cv.(map[string]any); okCM { + n := wave3ScholarlyPlain(cm["name"], 100) + if n == "" { + n = strings.TrimSpace(wave3ScholarlyPlain(cm["givenName"], 50) + " " + wave3ScholarlyPlain(cm["familyName"], 50)) + } + if n != "" { + creators = append(creators, n) + } + } + } + } + + desc := "" + if descArr, okD := attrs["descriptions"].([]any); okD && len(descArr) > 0 { + if dm, okDM := descArr[0].(map[string]any); okDM { + desc = wave3ScholarlyPlain(wave3ScholarlyCleanText(wave3ScholarlyStringVal(dm["description"])), 3500) + } + } + + rec := map[string]any{ + "source": "datacite", + "doi": doi, + "title": title, + } + if len(creators) > 0 { + rec["creators"] = creators + } + if publisher != "" { + rec["publisher"] = publisher + } + if pubYear != "" { + rec["publicationYear"] = pubYear + } + if resType != "" { + rec["resourceType"] = resType + } + if targetURL != "" { + rec["url"] = targetURL + } + if desc != "" { + rec["description"] = desc + } + recs = append(recs, rec) + rows = append(rows, []string{doi, title, publisher, pubYear, resType}) + } + if len(recs) == 0 { + return nil, false + } + + total := len(recs) + if f, okF := wave3ScholarlyFloatVal(wave3ScholarlyValAt(m, "meta", "total")); okF && int(f) > total { + total = int(f) + } + + if len(recs) == 1 { + r := recs[0] + title := wave3ScholarlyStringVal(r["title"]) + var bullets []string + if d := wave3ScholarlyStringVal(r["doi"]); d != "" { + bullets = append(bullets, "- **DOI**: `"+d+"`") + } + if cr, okCR := r["creators"].([]string); okCR && len(cr) > 0 { + bullets = append(bullets, "- **Creators**: "+strings.Join(cr, ", ")) + } + if pub := wave3ScholarlyStringVal(r["publisher"]); pub != "" { + bullets = append(bullets, "- **Publisher**: "+pub) + } + if py := wave3ScholarlyStringVal(r["publicationYear"]); py != "" { + bullets = append(bullets, "- **Publication Year**: "+py) + } + if rt := wave3ScholarlyStringVal(r["resourceType"]); rt != "" { + bullets = append(bullets, "- **Resource Type**: "+rt) + } + if u := wave3ScholarlyStringVal(r["url"]); u != "" { + bullets = append(bullets, "- **Landing URL**: "+u) + } + blocks := []string{"# " + escapeDeclMarkdownBrackets(title), strings.Join(bullets, "\n")} + desc := wave3ScholarlyStringVal(r["description"]) + if desc != "" { + blocks = append(blocks, "## Description\n\n"+desc) + } + shortDesc := desc + shortDesc = wave3ScholarlyTruncateDesc(shortDesc) + authShort := "" + if cr, okCR := r["creators"].([]string); okCR && len(cr) > 0 { + if len(cr) > 4 { + authShort = strings.Join(cr[:4], ", ") + } else { + authShort = strings.Join(cr, ", ") + } + } + return &DeclarativeFormattedDoc{ + Title: title, + Description: shortDesc, + Author: authShort, + PublishedTime: wave3ScholarlyStringVal(r["publicationYear"]), + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: recs, + Total: wave3ScholarlyIntPtr(total), + Returned: wave3ScholarlyIntPtr(1), + }, true + } + + return &DeclarativeFormattedDoc{ + Title: "DataCite DOIs", + Markdown: "# DataCite DOIs\n\n" + formatDeclarativeGFMTable([]string{"DOI", "Title", "Publisher", "Year", "Type"}, rows), + Links: links, + Records: recs, + Total: wave3ScholarlyIntPtr(total), + Returned: wave3ScholarlyIntPtr(len(recs)), + Truncated: wave3ScholarlyBoolPtr(total > len(recs)), + }, true +} + +// ── HTML Extractors (#301-#314) ───────────────────────────────────────────────────────────────── + +func wave3ScholarlyExtractAcademicMetaHTML(rawHTML, baseURL, extractorID, sourceName string) *DeclarativePostFetchResult { + doc := ParseHTMLDoc(rawHTML, wave3ScholarlyMaxHTMLBytes) + title := wave3ScholarlyFirstNonEmpty( + SanitizeSchemaPlainField(extractMetaContentDeclHTML(rawHTML, "citation_title"), 280), + SanitizeSchemaPlainField(extractMetaContentDeclHTML(rawHTML, "og:title"), 280), + ) + if title == "" && doc != nil { + title = SanitizeSchemaPlainField(wave3ScholarlyCleanText(doc.Text("h1")), 280) + } + if title == "" { + title = SanitizeSchemaPlainField(extractTitleLinearQuick(rawHTML), 280) + } + if title == "" || wave3ScholarlyIsNegativeTitle(title) || wave3ScholarlyIsGenericTitle(title) { + return nil + } + + var authors []string + for _, a := range extractAllMetaContentsDeclHTML(rawHTML, "citation_author") { + if len(authors) >= 20 { + break + } + if clean := SanitizeSchemaPlainField(a, 100); clean != "" { + authors = append(authors, clean) + } + } + pubDate := wave3ScholarlyNormalizeDate(wave3ScholarlyFirstNonEmpty( + extractMetaContentDeclHTML(rawHTML, "citation_publication_date"), + extractMetaContentDeclHTML(rawHTML, "citation_date"), + extractMetaContentDeclHTML(rawHTML, "citation_online_date"), + )) + doi := wave3ScholarlyNormalizeDOI(wave3ScholarlyFirstNonEmpty( + extractMetaContentDeclHTML(rawHTML, "citation_doi"), + extractMetaContentDeclHTML(rawHTML, "dc.identifier"), + )) + journal := SanitizeSchemaPlainField(wave3ScholarlyFirstNonEmpty( + extractMetaContentDeclHTML(rawHTML, "citation_journal_title"), + extractMetaContentDeclHTML(rawHTML, "citation_conference_title"), + extractMetaContentDeclHTML(rawHTML, "citation_preprint_server"), + ), 140) + pdfURL := SanitizeSchemaHTTPSURL(extractMetaContentDeclHTML(rawHTML, "citation_pdf_url"), baseURL) + abstract := SanitizeSchemaPlainField(wave3ScholarlyFirstNonEmpty( + extractMetaContentDeclHTML(rawHTML, "citation_abstract"), + extractMetaContentDeclHTML(rawHTML, "description"), + extractMetaContentDeclHTML(rawHTML, "og:description"), + ), 3500) + + // Try JSON-LD ScholarlyArticle / Dataset enrichment if meta tags were sparse + for _, ld := range extractJSONLDObjectsDeclHTML(rawHTML, 8) { + if pubDate == "" { + pubDate = wave3ScholarlyNormalizeDate(wave3ScholarlyStringVal(ld["datePublished"])) + } + if abstract == "" { + abstract = wave3ScholarlyPlain(ld["description"], 3500) + } + if doi == "" { + doi = wave3ScholarlyNormalizeDOI(wave3ScholarlyStringVal(ld["sameAs"])) + } + } + + if abstract == "" && doc != nil { + for _, sel := range []string{"#abstract", ".abstract", ".pane-biorxiv-abstract", ".abstract-content", ".s-abstract-content", "article p", "main p"} { + if txt := SanitizeSchemaPlainField(wave3ScholarlyCleanText(doc.Text(sel)), 3500); len(txt) >= 30 { + abstract = strings.TrimPrefix(txt, "Abstract") + abstract = strings.TrimSpace(strings.TrimPrefix(abstract, ":")) + break + } + } + } + + if len(authors) == 0 && doi == "" && abstract == "" && pdfURL == "" { + return nil + } + + var bullets []string + if len(authors) > 0 { + bullets = append(bullets, "- **Authors**: "+strings.Join(authors, ", ")) + } + if journal != "" { + bullets = append(bullets, "- **Venue / Journal**: "+journal) + } + if pubDate != "" { + bullets = append(bullets, "- **Published**: "+pubDate) + } + if doi != "" { + bullets = append(bullets, "- **DOI**: `"+doi+"`") + } + if pdfURL != "" { + bullets = append(bullets, "- **PDF**: "+pdfURL) + } + + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + if abstract != "" { + blocks = append(blocks, "## Abstract\n\n"+abstract) + } + + var links []string + seen := make(map[string]bool) + wave3ScholarlyAddLink(&links, seen, baseURL, baseURL) + wave3ScholarlyAddLink(&links, seen, pdfURL, baseURL) + if doi != "" { + wave3ScholarlyAddLink(&links, seen, "https://doi.org/"+doi, baseURL) + } + + rec := map[string]any{ + "source": sourceName, + "title": title, + "url": baseURL, + } + if len(authors) > 0 { + rec["authors"] = authors + } + if journal != "" { + rec["venue"] = journal + } + if pubDate != "" { + rec["publishedDate"] = pubDate + } + if doi != "" { + rec["doi"] = doi + } + if pdfURL != "" { + rec["pdfUrl"] = pdfURL + } + + shortDesc := abstract + shortDesc = wave3ScholarlyTruncateDesc(shortDesc) + authShort := strings.Join(authors, ", ") + if len(authors) > 4 { + authShort = strings.Join(authors[:4], ", ") + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: shortDesc, + Author: authShort, + PublishedTime: pubDate, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: []map[string]any{rec}, + Total: wave3ScholarlyIntPtr(1), + Returned: wave3ScholarlyIntPtr(1), + } +} + +func wave3ScholarlyExtractInfoPageHTML(rawHTML, baseURL, extractorID, sourceName string) *DeclarativePostFetchResult { + doc := ParseHTMLDoc(rawHTML, wave3ScholarlyMaxHTMLBytes) + if doc == nil { + return nil + } + title := wave3ScholarlyFirstNonEmpty( + SanitizeSchemaPlainField(wave3ScholarlyCleanText(doc.Text("h1")), 240), + SanitizeSchemaPlainField(extractMetaContentDeclHTML(rawHTML, "og:title"), 240), + SanitizeSchemaPlainField(extractTitleLinearQuick(rawHTML), 240), + ) + if title == "" || wave3ScholarlyIsNegativeTitle(title) { + return nil + } + desc := SanitizeSchemaPlainField(wave3ScholarlyFirstNonEmpty( + extractMetaContentDeclHTML(rawHTML, "og:description"), + extractMetaContentDeclHTML(rawHTML, "description"), + ), 600) + var paras []string + for _, p := range doc.Select("main p, article p, p", 8) { + txt := SanitizeSchemaPlainField(wave3ScholarlyCleanText(p.Text()), 600) + if len(txt) >= 25 { + paras = append(paras, txt) + } + } + if desc == "" && len(paras) == 0 { + return nil + } + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if desc != "" { + blocks = append(blocks, desc) + } + if len(paras) > 0 { + blocks = append(blocks, strings.Join(paras, "\n\n")) + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: strings.Join(blocks, "\n\n"), + Links: []string{baseURL}, + Records: []map[string]any{{"source": sourceName, "title": title, "url": baseURL}}, + Total: wave3ScholarlyIntPtr(1), + Returned: wave3ScholarlyIntPtr(1), + } +} + +func wave3ScholarlyExtractORCIDHTML(rawHTML, probeLower, baseURL, extractorID string) *DeclarativePostFetchResult { + // Strict Angular CSR SPA rejection: ORCID + [ROBOTS_PARAMETERS] / no researcher name + if strings.Contains(probeLower, "[robots_parameters]") { + return nil + } + doc := ParseHTMLDoc(rawHTML, wave3ScholarlyMaxHTMLBytes) + title := "" + if doc != nil { + title = SanitizeSchemaPlainField(wave3ScholarlyCleanText(doc.Text("h1")), 180) + } + if title == "" { + title = SanitizeSchemaPlainField(extractMetaContentDeclHTML(rawHTML, "og:title"), 180) + } + if title == "" || strings.EqualFold(title, "ORCID") || wave3ScholarlyIsNegativeTitle(title) || wave3ScholarlyIsGenericTitle(title) { + return nil + } + orcidID := "" + if u, err := url.Parse(baseURL); err == nil { + orcidID = wave3ScholarlyNormalizeORCID(strings.Trim(u.Path, "/")) + } + var bullets []string + if orcidID != "" { + bullets = append(bullets, "- **ORCID**: `"+orcidID+"`") + } + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + if doc != nil { + if bio := SanitizeSchemaPlainField(wave3ScholarlyCleanText(doc.Text(".biography, #biography")), 1500); bio != "" { + blocks = append(blocks, "## Biography\n\n"+bio) + } + } + if len(blocks) < 2 { + return nil + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Author: title, + Markdown: strings.Join(blocks, "\n\n"), + Links: []string{baseURL}, + Records: []map[string]any{{"source": "orcid", "orcid": orcidID, "name": title, "url": baseURL}}, + Total: wave3ScholarlyIntPtr(1), + Returned: wave3ScholarlyIntPtr(1), + } +} + +func wave3ScholarlyExtractRORHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + doc := ParseHTMLDoc(rawHTML, wave3ScholarlyMaxHTMLBytes) + title := "" + if doc != nil { + title = SanitizeSchemaPlainField(wave3ScholarlyCleanText(doc.Text("h1")), 220) + } + if title == "" { + title = SanitizeSchemaPlainField(extractMetaContentDeclHTML(rawHTML, "og:title"), 220) + } + if title == "" || wave3ScholarlyIsNegativeTitle(title) || wave3ScholarlyIsGenericTitle(title) { + return nil + } + desc := SanitizeSchemaPlainField(extractMetaContentDeclHTML(rawHTML, "description"), 600) + if desc == "" && doc != nil { + desc = SanitizeSchemaPlainField(wave3ScholarlyCleanText(doc.Text("main p, p")), 600) + } + if desc == "" { + return nil + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: "# " + escapeDeclMarkdownBrackets(title) + "\n\n" + desc, + Links: []string{baseURL}, + Records: []map[string]any{{"source": "ror", "name": title, "url": baseURL}}, + Total: wave3ScholarlyIntPtr(1), + Returned: wave3ScholarlyIntPtr(1), + } +} + +func wave3ScholarlyExtractDBLPHTML(rawHTML, probeLower, baseURL, extractorID string) *DeclarativePostFetchResult { + if strings.Contains(probeLower, "anubis_version") || strings.Contains(probeLower, "anubis_challenge") || strings.Contains(probeLower, "making sure you're not a bot") { + return nil + } + doc := ParseHTMLDoc(rawHTML, wave3ScholarlyMaxHTMLBytes) + if doc == nil { + return nil + } + title := wave3ScholarlyFirstNonEmpty( + SanitizeSchemaPlainField(wave3ScholarlyCleanText(doc.Text("#headline h1, h1")), 260), + SanitizeSchemaPlainField(extractMetaContentDeclHTML(rawHTML, "og:title"), 260), + ) + if title == "" || wave3ScholarlyIsNegativeTitle(title) || wave3ScholarlyIsGenericTitle(title) { + return nil + } + + var recs []map[string]any + var itemBullets []string + var links []string + seen := make(map[string]bool) + wave3ScholarlyAddLink(&links, seen, baseURL, baseURL) + + for _, el := range doc.Select("li.entry cite.data, cite.data", 25) { + txt := SanitizeSchemaPlainField(wave3ScholarlyCleanText(el.Text()), 400) + if txt == "" { + continue + } + itemBullets = append(itemBullets, "- "+txt) + recs = append(recs, map[string]any{ + "source": "dblp", + "citation": txt, + }) + } + if len(recs) == 0 { + return nil + } + blocks := []string{"# " + escapeDeclMarkdownBrackets(title), strings.Join(itemBullets, "\n")} + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: recs, + Total: wave3ScholarlyIntPtr(len(recs)), + Returned: wave3ScholarlyIntPtr(len(recs)), + } +} + +func wave3ScholarlyExtractNIHReporterHTML(rawHTML, probeLower, baseURL, extractorID string) *DeclarativePostFetchResult { + doc := ParseHTMLDoc(rawHTML, wave3ScholarlyMaxHTMLBytes) + title := "" + if doc != nil { + title = SanitizeSchemaPlainField(wave3ScholarlyCleanText(doc.Text("h1.project-title, h1")), 260) + } + if title == "" || wave3ScholarlyIsNegativeTitle(title) || wave3ScholarlyIsGenericTitle(title) { + return nil + } + desc := "" + if doc != nil { + desc = SanitizeSchemaPlainField(wave3ScholarlyCleanText(doc.Text(".abstract-text, #abstract, main p")), 2000) + } + if desc == "" { + return nil + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: "# " + escapeDeclMarkdownBrackets(title) + "\n\n" + desc, + Links: []string{baseURL}, + Records: []map[string]any{{"source": "nih-reporter", "title": title, "url": baseURL}}, + Total: wave3ScholarlyIntPtr(1), + Returned: wave3ScholarlyIntPtr(1), + } +} + +func wave3ScholarlyExtractNSFAwardsHTML(rawHTML, probeLower, baseURL, extractorID string) *DeclarativePostFetchResult { + doc := ParseHTMLDoc(rawHTML, wave3ScholarlyMaxHTMLBytes) + title := "" + if doc != nil { + title = SanitizeSchemaPlainField(wave3ScholarlyCleanText(doc.Text("h1.award-title, h1")), 260) + } + if title == "" || wave3ScholarlyIsNegativeTitle(title) || wave3ScholarlyIsGenericTitle(title) { + return nil + } + desc := "" + if doc != nil { + desc = SanitizeSchemaPlainField(wave3ScholarlyCleanText(doc.Text(".award-abstract, #abstract, main p")), 2000) + } + if desc == "" { + return nil + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: "# " + escapeDeclMarkdownBrackets(title) + "\n\n" + desc, + Links: []string{baseURL}, + Records: []map[string]any{{"source": "nsf-awards", "title": title, "url": baseURL}}, + Total: wave3ScholarlyIntPtr(1), + Returned: wave3ScholarlyIntPtr(1), + } +} + +func wave3ScholarlyExtractRepoPackHTML(rawHTML, probeLower, baseURL, urlLower, extractorID string) *DeclarativePostFetchResult { + repoName := "Research Repository" + switch { + case strings.Contains(urlLower, "zenodo.org"): + repoName = "Zenodo" + case strings.Contains(urlLower, "datadryad.org"): + repoName = "Dryad" + case strings.Contains(urlLower, "osf.io"): + repoName = "OSF" + case strings.Contains(urlLower, "figshare.com"): + repoName = "Figshare" + } + + doc := ParseHTMLDoc(rawHTML, wave3ScholarlyMaxHTMLBytes) + title := wave3ScholarlyFirstNonEmpty( + SanitizeSchemaPlainField(extractMetaContentDeclHTML(rawHTML, "citation_title"), 280), + SanitizeSchemaPlainField(extractMetaContentDeclHTML(rawHTML, "og:title"), 280), + ) + if title == "" && doc != nil { + title = SanitizeSchemaPlainField(wave3ScholarlyCleanText(doc.Text("h1")), 280) + } + if title == "" || wave3ScholarlyIsNegativeTitle(title) || wave3ScholarlyIsGenericTitle(title) { + return nil + } + + var authors []string + for _, a := range extractAllMetaContentsDeclHTML(rawHTML, "citation_author") { + if len(authors) >= 16 { + break + } + if clean := SanitizeSchemaPlainField(a, 100); clean != "" { + authors = append(authors, clean) + } + } + pubDate := wave3ScholarlyNormalizeDate(wave3ScholarlyFirstNonEmpty( + extractMetaContentDeclHTML(rawHTML, "citation_publication_date"), + extractMetaContentDeclHTML(rawHTML, "citation_date"), + )) + doi := wave3ScholarlyNormalizeDOI(wave3ScholarlyFirstNonEmpty( + extractMetaContentDeclHTML(rawHTML, "citation_doi"), + extractMetaContentDeclHTML(rawHTML, "dc.identifier"), + )) + desc := SanitizeSchemaPlainField(wave3ScholarlyFirstNonEmpty( + extractMetaContentDeclHTML(rawHTML, "og:description"), + extractMetaContentDeclHTML(rawHTML, "description"), + ), 3500) + + for _, ld := range extractJSONLDObjectsDeclHTML(rawHTML, 8) { + if pubDate == "" { + pubDate = wave3ScholarlyNormalizeDate(wave3ScholarlyStringVal(ld["datePublished"])) + } + if desc == "" { + rawDesc := wave3ScholarlyStringVal(ld["description"]) + if rawDesc == "" { + if dArr, okArr := ld["description"].([]any); okArr { + var parts []string + for _, item := range dArr { + if s := wave3ScholarlyCleanText(wave3ScholarlyStringVal(item)); s != "" { + parts = append(parts, s) + } + } + rawDesc = strings.Join(parts, "\n\n") + } + } + if rawDesc != "" { + desc = wave3ScholarlyPlain(wave3ScholarlyCleanText(rawDesc), 3500) + } + } + if doi == "" { + doi = wave3ScholarlyNormalizeDOI(wave3ScholarlyStringVal(ld["identifier"])) + if doi == "" { + if idObj, okID := ld["identifier"].(map[string]any); okID { + doi = wave3ScholarlyNormalizeDOI(wave3ScholarlyFirstNonEmpty( + wave3ScholarlyStringVal(idObj["value"]), + wave3ScholarlyStringVal(idObj["url"]), + )) + } + } + if doi == "" { + doi = wave3ScholarlyNormalizeDOI(wave3ScholarlyFirstNonEmpty( + wave3ScholarlyStringVal(ld["@id"]), + wave3ScholarlyStringVal(ld["url"]), + )) + } + } + if len(authors) == 0 { + addAuthor := func(rawName string) { + if len(authors) >= 16 { + return + } + if clean := SanitizeSchemaPlainField(rawName, 100); clean != "" { + for _, existing := range authors { + if strings.EqualFold(existing, clean) { + return + } + } + authors = append(authors, clean) + } + } + extractCreatorVal := func(val any) { + switch cv := val.(type) { + case string: + addAuthor(cv) + case map[string]any: + name := wave3ScholarlyStringVal(cv["name"]) + if name == "" { + given := wave3ScholarlyStringVal(cv["givenName"]) + family := wave3ScholarlyStringVal(cv["familyName"]) + name = strings.TrimSpace(given + " " + family) + } + addAuthor(name) + case []any: + for _, item := range cv { + switch iv := item.(type) { + case string: + addAuthor(iv) + case map[string]any: + name := wave3ScholarlyStringVal(iv["name"]) + if name == "" { + given := wave3ScholarlyStringVal(iv["givenName"]) + family := wave3ScholarlyStringVal(iv["familyName"]) + name = strings.TrimSpace(given + " " + family) + } + addAuthor(name) + } + } + } + } + if ld["creator"] != nil { + extractCreatorVal(ld["creator"]) + } else if ld["author"] != nil { + extractCreatorVal(ld["author"]) + } + } + } + + if desc == "" && doc != nil { + for _, sel := range []string{"#description", ".abstract", "section p", "main p"} { + if txt := SanitizeSchemaPlainField(wave3ScholarlyCleanText(doc.Text(sel)), 3500); len(txt) >= 25 { + desc = txt + break + } + } + } + if len(authors) == 0 && doi == "" && desc == "" { + return nil + } + + var bullets []string + bullets = append(bullets, "- **Repository**: "+repoName) + if len(authors) > 0 { + bullets = append(bullets, "- **Authors**: "+strings.Join(authors, ", ")) + } + if pubDate != "" { + bullets = append(bullets, "- **Published**: "+pubDate) + } + if doi != "" { + bullets = append(bullets, "- **DOI**: `"+doi+"`") + } + + blocks := []string{"# " + escapeDeclMarkdownBrackets(title), strings.Join(bullets, "\n")} + if desc != "" { + blocks = append(blocks, "## Description\n\n"+desc) + } + + var links []string + seen := make(map[string]bool) + wave3ScholarlyAddLink(&links, seen, baseURL, baseURL) + if doi != "" { + wave3ScholarlyAddLink(&links, seen, "https://doi.org/"+doi, baseURL) + } + + rec := map[string]any{ + "source": "research-repo-pack", + "repository": repoName, + "title": title, + "url": baseURL, + } + if doi != "" { + rec["doi"] = doi + } + if pubDate != "" { + rec["publishedDate"] = pubDate + } + if len(authors) > 0 { + rec["authors"] = authors + } + + shortDesc := desc + shortDesc = wave3ScholarlyTruncateDesc(shortDesc) + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: shortDesc, + Author: strings.Join(authors, ", "), + PublishedTime: pubDate, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: []map[string]any{rec}, + Total: wave3ScholarlyIntPtr(1), + Returned: wave3ScholarlyIntPtr(1), + } +} + +func wave3ScholarlyExtractDataCiteHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + if m := wave3ScholarlyRxNextData.FindStringSubmatch(rawHTML); len(m) >= 2 { + if parsed, ok := decodeJSONWithNumbers([]byte(m[1])); ok { + if pm, okPM := parsed.(map[string]any); okPM { + if work := wave3ScholarlyMapAt(pm, "props", "pageProps", "work"); work != nil { + if title := wave3ScholarlyPlain(wave3ScholarlyFirstNonEmpty(wave3ScholarlyStringVal(work["title"]), wave3ScholarlyStringVal(wave3ScholarlyValAt(work, "titles", "0", "title"))), 280); title != "" { + doi := wave3ScholarlyNormalizeDOI(wave3ScholarlyStringVal(work["doi"])) + desc := wave3ScholarlyPlain(work["description"], 3000) + var links []string + seen := make(map[string]bool) + wave3ScholarlyAddLink(&links, seen, baseURL, baseURL) + if doi != "" { + wave3ScholarlyAddLink(&links, seen, "https://doi.org/"+doi, baseURL) + } + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if doi != "" { + blocks = append(blocks, "- **DOI**: `"+doi+"`") + } + if desc != "" { + blocks = append(blocks, desc) + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: []map[string]any{{"source": "datacite", "doi": doi, "title": title, "url": baseURL}}, + Total: wave3ScholarlyIntPtr(1), + Returned: wave3ScholarlyIntPtr(1), + } + } + } + } + } + } + return wave3ScholarlyExtractAcademicMetaHTML(rawHTML, baseURL, extractorID, "datacite") +} + +func wave3ScholarlyExtractSSRNNBERHTML(rawHTML, probeLower, baseURL, urlLower, extractorID string) *DeclarativePostFetchResult { + doc := ParseHTMLDoc(rawHTML, wave3ScholarlyMaxHTMLBytes) + title := wave3ScholarlyFirstNonEmpty( + SanitizeSchemaPlainField(extractMetaContentDeclHTML(rawHTML, "citation_title"), 280), + SanitizeSchemaPlainField(extractMetaContentDeclHTML(rawHTML, "og:title"), 280), + ) + if title == "" && doc != nil { + title = SanitizeSchemaPlainField(wave3ScholarlyCleanText(doc.Text("h1")), 280) + } + if title == "" || wave3ScholarlyIsNegativeTitle(title) || wave3ScholarlyIsGenericTitle(title) { + return nil + } + + var authors []string + for _, a := range extractAllMetaContentsDeclHTML(rawHTML, "citation_author") { + if len(authors) >= 20 { + break + } + if clean := SanitizeSchemaPlainField(a, 100); clean != "" { + authors = append(authors, clean) + } + } + pubDate := wave3ScholarlyNormalizeDate(wave3ScholarlyFirstNonEmpty( + extractMetaContentDeclHTML(rawHTML, "citation_publication_date"), + extractMetaContentDeclHTML(rawHTML, "citation_date"), + extractMetaContentDeclHTML(rawHTML, "dcterms.issued"), + )) + doi := wave3ScholarlyNormalizeDOI(wave3ScholarlyFirstNonEmpty( + extractMetaContentDeclHTML(rawHTML, "citation_doi"), + extractMetaContentDeclHTML(rawHTML, "dcterms.identifier"), + )) + reportNum := SanitizeSchemaPlainField(extractMetaContentDeclHTML(rawHTML, "citation_technical_report_number"), 48) + pdfURL := SanitizeSchemaHTTPSURL(extractMetaContentDeclHTML(rawHTML, "citation_pdf_url"), baseURL) + abstract := SanitizeSchemaPlainField(wave3ScholarlyFirstNonEmpty( + extractMetaContentDeclHTML(rawHTML, "citation_abstract"), + extractMetaContentDeclHTML(rawHTML, "dcterms.abstract"), + extractMetaContentDeclHTML(rawHTML, "description"), + extractMetaContentDeclHTML(rawHTML, "og:description"), + ), 3500) + + if doc != nil && (abstract == "" || len(abstract) < 60) { + for _, sel := range []string{".page-header__intro", ".abstract-text", "#abstract", ".field--name-body", "article p", "main p"} { + if txt := SanitizeSchemaPlainField(wave3ScholarlyCleanText(doc.Text(sel)), 3500); len(txt) >= 40 { + txt = strings.TrimSpace(strings.TrimPrefix(strings.TrimPrefix(txt, "Abstract"), ":")) + if len(txt) > len(abstract) { + abstract = txt + } + break + } + } + } + if len(authors) == 0 && doi == "" && abstract == "" && reportNum == "" { + return nil + } + + venue := "NBER Working Paper" + if strings.Contains(urlLower, "ssrn.com") { + venue = "SSRN" + } + + var bullets []string + bullets = append(bullets, "- **Source**: "+venue) + if reportNum != "" { + bullets = append(bullets, "- **Working Paper #**: `"+reportNum+"`") + } + if len(authors) > 0 { + bullets = append(bullets, "- **Authors**: "+strings.Join(authors, ", ")) + } + if pubDate != "" { + bullets = append(bullets, "- **Published**: "+pubDate) + } + if doi != "" { + bullets = append(bullets, "- **DOI**: `"+doi+"`") + } + if pdfURL != "" { + bullets = append(bullets, "- **PDF**: "+pdfURL) + } + + blocks := []string{"# " + escapeDeclMarkdownBrackets(title), strings.Join(bullets, "\n")} + if abstract != "" { + blocks = append(blocks, "## Abstract\n\n"+abstract) + } + + var links []string + seen := make(map[string]bool) + wave3ScholarlyAddLink(&links, seen, baseURL, baseURL) + wave3ScholarlyAddLink(&links, seen, pdfURL, baseURL) + if doi != "" { + wave3ScholarlyAddLink(&links, seen, "https://doi.org/"+doi, baseURL) + } + + rec := map[string]any{ + "source": "ssrn-nber", + "venue": venue, + "title": title, + "url": baseURL, + } + if reportNum != "" { + rec["workingPaperNumber"] = reportNum + } + if len(authors) > 0 { + rec["authors"] = authors + } + if pubDate != "" { + rec["publishedDate"] = pubDate + } + if doi != "" { + rec["doi"] = doi + } + if pdfURL != "" { + rec["pdfUrl"] = pdfURL + } + + shortDesc := abstract + shortDesc = wave3ScholarlyTruncateDesc(shortDesc) + authShort := strings.Join(authors, ", ") + if len(authors) > 4 { + authShort = strings.Join(authors[:4], ", ") + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: shortDesc, + Author: authShort, + PublishedTime: pubDate, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: []map[string]any{rec}, + Total: wave3ScholarlyIntPtr(1), + Returned: wave3ScholarlyIntPtr(1), + } +} diff --git a/internal/extract/wave3_scholarly_test.go b/internal/extract/wave3_scholarly_test.go new file mode 100644 index 0000000..7b3c76a --- /dev/null +++ b/internal/extract/wave3_scholarly_test.go @@ -0,0 +1,585 @@ +package extract + +import ( + "encoding/json" + "net/url" + "os" + "path/filepath" + "strings" + "testing" + "time" + "unicode/utf8" +) + +func wave3ScholarlyDecodeDoc(t *testing.T, raw string) *DeclarativeFormattedDoc { + t.Helper() + var doc DeclarativeFormattedDoc + if err := json.Unmarshal([]byte(raw), &doc); err != nil { + t.Fatalf("unmarshal DeclarativeFormattedDoc: %v\nraw=%s", err, raw) + } + return &doc +} + +func wave3ScholarlyResolveManifest(t *testing.T, m *DeclarativeAdapterManifest, rawURL string) (*DeclarativeTwinMatch, bool) { + t.Helper() + u, err := url.Parse(rawURL) + if err != nil { + t.Fatalf("url.Parse(%q): %v", rawURL, err) + } + host := strings.TrimSuffix(strings.ToLower(u.Hostname()), ".") + rawParts := splitNonEmptyEscapedSegments(u.EscapedPath()) + return resolveManifestTwinOnParsedURL(m, u, host, rawParts, DeclarativeResolveOptions{}) +} + +func TestWave3ScholarlyManifestsRoutesAndCompliance(t *testing.T) { + catLIDs := []string{ + "semantic-scholar", + "unpaywall", + "core-ac", + "orcid", + "ror", + "dblp", + "biorxiv-medrxiv", + "nasa-ads", + "nih-reporter", + "nsf-awards", + "doe-osti", + "research-repo-pack", + "datacite", + "ssrn-nber", + } + + byID := make(map[string]*DeclarativeAdapterManifest) + claimedDomains := make(map[string]string) + + for _, id := range catLIDs { + raw, err := os.ReadFile(filepath.Join("manifests", id+".yaml")) + if err != nil { + t.Fatalf("read %s.yaml: %v", id, err) + } + m, err := ParseDeclarativeYAMLManifest(raw) + if err != nil { + t.Fatalf("ParseDeclarativeYAMLManifest(%s.yaml): %v", id, err) + } + if m.ID != id { + t.Fatalf("%s.yaml has mismatched id=%q", id, m.ID) + } + if m.Category != "research-health" { + t.Fatalf("%s.yaml must use category research-health, got %q", id, m.Category) + } + if m.AuthMode == "detect-only" || m.DetectOnly != nil { + t.Fatalf("%s.yaml uses retired detect-only", id) + } + for _, d := range m.Domains { + ld := strings.ToLower(strings.TrimSpace(d)) + if prev, exists := claimedDomains[ld]; exists { + t.Fatalf("duplicate domain %q across %s and %s", ld, prev, id) + } + claimedDomains[ld] = id + } + for _, hr := range m.HTMLRoutes { + for _, b := range hr.Bullets { + if strings.ContainsAny(b.Label, "{}") { + t.Fatalf("%s.yaml bullet label contains {}: %q", id, b.Label) + } + } + } + byID[id] = m + } + + // Verify strict disjointness from existing scholarly/baseline manifests + for _, existingID := range []string{ + "arxiv", "doi-crossref", "openalex", "pubmed-pmc", "nasa-apis", + "clinicaltrials", "dailymed", "medlineplus", "pubchem", "rxnorm-rxnav", "schema-course", + } { + raw, err := os.ReadFile(filepath.Join("manifests", existingID+".yaml")) + if err != nil { + t.Fatalf("read %s.yaml: %v", existingID, err) + } + em, err := ParseDeclarativeYAMLManifest(raw) + if err != nil { + t.Fatalf("ParseDeclarativeYAMLManifest(%s.yaml): %v", existingID, err) + } + for _, d := range em.Domains { + ld := strings.ToLower(strings.TrimSpace(d)) + if owner, overlap := claimedDomains[ld]; overlap { + t.Fatalf("Cat L %s overlaps %s domain %q", owner, existingID, ld) + } + } + } + + // #301 semantic-scholar + s2 := byID["semantic-scholar"] + if tm, ok := wave3ScholarlyResolveManifest(t, s2, "https://www.semanticscholar.org/paper/Attention-is-All-you-Need-Vaswani-Shazeer/204e3073870fae3d05bcbc2f6a8e263d9b72e776"); !ok || + tm.route.Extract.JSONMode != "semantic_scholar_json" || + !strings.HasPrefix(tm.FetchURL, "https://api.semanticscholar.org/graph/v1/paper/204e3073870fae3d05bcbc2f6a8e263d9b72e776") { + t.Fatalf("semantic-scholar paper twin failed: ok=%v tm=%+v", ok, tm) + } + + // #302 unpaywall: ALWAYS enforce email=bot@edgefetch.dev (never caller email!) + upw := byID["unpaywall"] + for _, u := range []string{ + "https://api.unpaywall.org/v2/10.1038/s41586-021-03819-2", + "https://api.unpaywall.org/v2/10.1038/s41586-021-03819-2?email=personal.user@gmail.com", + } { + tm, ok := wave3ScholarlyResolveManifest(t, upw, u) + if !ok || tm.route.Extract.JSONMode != "unpaywall_json" { + t.Fatalf("unpaywall resolve failed for %s: ok=%v tm=%+v", u, ok, tm) + } + if !strings.Contains(tm.FetchURL, "email=bot%40edgefetch.dev") || strings.Contains(tm.FetchURL, "gmail.com") { + t.Fatalf("unpaywall must enforce bot@edgefetch.dev only, got FetchURL=%q", tm.FetchURL) + } + } + + // #303 core-ac: auth_mode=key + core := byID["core-ac"] + if tm, ok := wave3ScholarlyResolveManifest(t, core, "https://core.ac.uk/works/11689643"); !ok || + tm.route.Twin.AuthMode != "key" || + tm.FetchURL != "https://api.core.ac.uk/v3/works/11689643" { + t.Fatalf("core-ac work twin failed: ok=%v tm=%+v", ok, tm) + } + + // #304 orcid + orc := byID["orcid"] + if tm, ok := wave3ScholarlyResolveManifest(t, orc, "https://orcid.org/0000-0002-1825-0097"); !ok || + tm.FetchURL != "https://pub.orcid.org/v3.0/0000-0002-1825-0097/record" { + t.Fatalf("orcid twin failed: ok=%v tm=%+v", ok, tm) + } + + // #305 ror + ror := byID["ror"] + if tm, ok := wave3ScholarlyResolveManifest(t, ror, "https://ror.org/03yrm5c26"); !ok || + tm.FetchURL != "https://api.ror.org/v2/organizations/03yrm5c26" { + t.Fatalf("ror twin failed: ok=%v tm=%+v", ok, tm) + } + + // #306 dblp: /search/publ/api -> JSON, /rec/*.xml -> XML, /rec/*.html -> falls through to htmlRoutes (robots.txt Disallow: /rec/xml) + dblp := byID["dblp"] + if tm, ok := wave3ScholarlyResolveManifest(t, dblp, "https://dblp.org/search/publ/api?q=attention&format=json"); !ok || tm.route.Extract.JSONMode != "dblp_json" { + t.Fatalf("dblp search API failed: ok=%v tm=%+v", ok, tm) + } + if tm, ok := wave3ScholarlyResolveManifest(t, dblp, "https://dblp.org/rec/conf/nips/VaswaniSPUJGKP17.xml"); !ok || tm.route.Extract.TextMode != "dblp_xml" { + t.Fatalf("dblp xml route failed: ok=%v tm=%+v", ok, tm) + } + if tm, ok := wave3ScholarlyResolveManifest(t, dblp, "https://dblp.org/rec/conf/nips/VaswaniSPUJGKP17.html"); ok || tm != nil { + t.Fatalf("dblp .html must NOT upgrade to /rec/*.xml (robots.txt disallowed): %+v", tm) + } + + // #307 biorxiv-medrxiv: Rule 7 — www.medrxiv.org MUST NOT twin-fetch api.biorxiv.org + bio := byID["biorxiv-medrxiv"] + if tm, ok := wave3ScholarlyResolveManifest(t, bio, "https://api.biorxiv.org/details/medrxiv/10.1101/2020.05.28.20116129/na/json"); !ok || tm.route.Extract.JSONMode != "biorxiv_medrxiv_json" { + t.Fatalf("biorxiv-medrxiv direct API failed: ok=%v tm=%+v", ok, tm) + } + if tm, ok := wave3ScholarlyResolveManifest(t, bio, "https://www.medrxiv.org/content/10.1101/2020.05.28.20116129v1"); ok || tm != nil { + t.Fatalf("Rule 7 violation: www.medrxiv.org must route via htmlRoutes, not twin-fetch api.biorxiv.org: %+v", tm) + } + + // #308 nasa-ads: auth_mode=key + ads := byID["nasa-ads"] + if tm, ok := wave3ScholarlyResolveManifest(t, ads, "https://ui.adsabs.harvard.edu/abs/2017arXiv170603762V/abstract"); !ok || + tm.route.Twin.AuthMode != "key" || + !strings.HasPrefix(tm.FetchURL, "https://api.adsabs.harvard.edu/v1/search/query") { + t.Fatalf("nasa-ads twin failed: ok=%v tm=%+v", ok, tm) + } + + // #309 nih-reporter: POST twin + nih := byID["nih-reporter"] + if tm, ok := wave3ScholarlyResolveManifest(t, nih, "https://reporter.nih.gov/project-details/10476325"); !ok || + tm.Method != "POST" || + tm.ContentType != "application/json" || + !strings.Contains(tm.RequestBody, "10476325") { + t.Fatalf("nih-reporter POST twin failed: ok=%v tm=%+v", ok, tm) + } + + // #310 nsf-awards + nsf := byID["nsf-awards"] + if tm, ok := wave3ScholarlyResolveManifest(t, nsf, "https://www.nsf.gov/awardsearch/show-award?AWD_ID=2535346"); !ok || + tm.FetchURL != "https://api.nsf.gov/services/v1/awards/2535346.json" { + t.Fatalf("nsf-awards twin failed: ok=%v tm=%+v", ok, tm) + } + + // #311 doe-osti + osti := byID["doe-osti"] + if tm, ok := wave3ScholarlyResolveManifest(t, osti, "https://www.osti.gov/biblio/1800000"); !ok || + tm.FetchURL != "https://www.osti.gov/api/v1/records/1800000" { + t.Fatalf("doe-osti twin failed: ok=%v tm=%+v", ok, tm) + } + + // #312 research-repo-pack: Zenodo /records & OSF HTML must NOT upgrade to API; Figshare upgrades to api.figshare.com + repo := byID["research-repo-pack"] + if tm, ok := wave3ScholarlyResolveManifest(t, repo, "https://zenodo.org/records/24485086"); ok || tm != nil { + t.Fatalf("zenodo.org/records must NOT upgrade to /api/records (robots.txt Disallow: /api): %+v", tm) + } + if tm, ok := wave3ScholarlyResolveManifest(t, repo, "https://osf.io/k7thf/"); ok || tm != nil { + t.Fatalf("osf.io must NOT upgrade to api.osf.io (robots.txt Disallow: /): %+v", tm) + } + if tm, ok := wave3ScholarlyResolveManifest(t, repo, "https://figshare.com/articles/dataset/Global_Climate/35148283"); !ok || + tm.FetchURL != "https://api.figshare.com/v2/articles/35148283" { + t.Fatalf("figshare article twin failed: ok=%v tm=%+v", ok, tm) + } + + // #313 datacite + dc := byID["datacite"] + if _, claimedDOI := claimedDomains["doi.org"]; claimedDOI { + t.Fatalf("datacite must NOT claim doi.org") + } + if tm, ok := wave3ScholarlyResolveManifest(t, dc, "https://commons.datacite.org/doi.org/10.5281/zenodo.24485086"); !ok || + tm.FetchURL != "https://api.datacite.org/dois/10.5281/zenodo.24485086" { + t.Fatalf("datacite commons twin failed: ok=%v tm=%+v", ok, tm) + } +} + +func TestWave3ScholarlyJSONAndXMLFormatters(t *testing.T) { + // #301 semantic_scholar_json + s2Raw, ok := FormatWave3ScholarlyJSONMode("semantic_scholar_json", []byte(`{"paperId":"204e3073870fae3d05bcbc2f6a8e263d9b72e776","title":"Attention Is All You Need","year":2017,"venue":"NeurIPS","citationCount":95000,"externalIds":{"DOI":"10.48550/arXiv.1706.03762"},"openAccessPdf":{"url":"https://arxiv.org/pdf/1706.03762.pdf"},"authors":[{"name":"Ashish Vaswani"}],"abstract":"Transformer sequence transduction."}`), nil, "https://api.semanticscholar.org/graph/v1/paper/204e3073870fae3d05bcbc2f6a8e263d9b72e776") + if !ok { + t.Fatalf("semantic_scholar_json failed") + } + s2Doc := wave3ScholarlyDecodeDoc(t, s2Raw) + if !strings.Contains(s2Doc.Markdown, "Ashish Vaswani") || !strings.Contains(s2Doc.Markdown, "10.48550/arXiv.1706.03762") { + t.Fatalf("unexpected semantic_scholar_json output: %+v", s2Doc) + } + if _, neg := FormatWave3ScholarlyJSONMode("semantic_scholar_json", []byte(`{"error":"Paper not found"}`), nil, "https://api.semanticscholar.org/graph/v1/paper/bad"); neg { + t.Fatalf("semantic_scholar_json must reject error") + } + + // #302 unpaywall_json + upwRaw, ok := FormatWave3ScholarlyJSONMode("unpaywall_json", []byte(`{"doi":"10.1038/s41586-021-03819-2","title":"AlphaFold","is_oa":true,"oa_status":"hybrid","journal_name":"Nature","published_date":"2021-07-15","best_oa_location":{"url_for_pdf":"https://www.nature.com/articles/s41586-021-03819-2.pdf","license":"cc-by"},"z_authors":[{"given":"John","family":"Jumper"}]}`), nil, "https://api.unpaywall.org/v2/10.1038/s41586-021-03819-2?email=bot@edgefetch.dev") + if !ok { + t.Fatalf("unpaywall_json failed") + } + upwDoc := wave3ScholarlyDecodeDoc(t, upwRaw) + if !strings.Contains(upwDoc.Markdown, "hybrid") || !strings.Contains(upwDoc.Markdown, "John Jumper") { + t.Fatalf("unexpected unpaywall_json output: %+v", upwDoc) + } + if _, neg := FormatWave3ScholarlyJSONMode("unpaywall_json", []byte(`{"error":true,"HTTP_status_code":404}`), nil, "https://api.unpaywall.org/v2/10.9999/bad?email=bot@edgefetch.dev"); neg { + t.Fatalf("unpaywall_json must reject 404") + } + + // #303 core_ac_json + if _, ok := FormatWave3ScholarlyJSONMode("core_ac_json", []byte(`{"id":11689643,"title":"Solar Grid Study","doi":"10.1016/j.solener.2020.01.001","yearPublished":2020,"authors":[{"name":"Elena Vance"}]}`), nil, "https://api.core.ac.uk/v3/works/11689643"); !ok { + t.Fatalf("core_ac_json failed") + } + if _, neg := FormatWave3ScholarlyJSONMode("core_ac_json", []byte(`{"results":[]}`), nil, "https://api.core.ac.uk/v3/search/works?q=none"); neg { + t.Fatalf("core_ac_json must reject empty results") + } + + // #304 orcid_json + if _, ok := FormatWave3ScholarlyJSONMode("orcid_json", []byte(`{"orcid-identifier":{"path":"0000-0002-1825-0097"},"person":{"name":{"credit-name":{"value":"Josiah Carberry"}}}}`), nil, "https://pub.orcid.org/v3.0/0000-0002-1825-0097/record"); !ok { + t.Fatalf("orcid_json failed") + } + if _, neg := FormatWave3ScholarlyJSONMode("orcid_json", []byte(`{"error-code":9016,"developer-message":"not found"}`), nil, "https://pub.orcid.org/v3.0/bad/record"); neg { + t.Fatalf("orcid_json must reject error-code") + } + + // #305 ror_json + if _, ok := FormatWave3ScholarlyJSONMode("ror_json", []byte(`{"id":"https://ror.org/03yrm5c26","status":"active","names":[{"types":["ror_display"],"value":"California Digital Library"}],"domains":["cdlib.org"]}`), nil, "https://api.ror.org/v2/organizations/03yrm5c26"); !ok { + t.Fatalf("ror_json failed") + } + if _, neg := FormatWave3ScholarlyJSONMode("ror_json", []byte(`{"errors":["not found"]}`), nil, "https://api.ror.org/v2/organizations/000000000"); neg { + t.Fatalf("ror_json must reject errors") + } + + // #306 dblp_json & dblp_xml + if _, ok := FormatWave3ScholarlyJSONMode("dblp_json", []byte(`{"result":{"hits":{"@total":"1","hit":[{"info":{"title":"Attention Is All You Need","authors":{"author":[{"text":"Ashish Vaswani"}]},"venue":"NIPS","year":"2017"}}]}}}`), nil, "https://dblp.org/search/publ/api?q=attention&format=json"); !ok { + t.Fatalf("dblp_json failed") + } + if _, ok := FormatWave3ScholarlyTextMode("dblp_xml", `Ashish VaswaniAttention Is All You Need.NIPS2017`, nil, "https://dblp.org/rec/conf/nips/VaswaniSPUJGKP17.xml"); !ok { + t.Fatalf("dblp_xml failed") + } + if _, neg := FormatWave3ScholarlyTextMode("dblp_xml", `Making sure you're not a bot!`, nil, "https://dblp.org/rec/conf/nips/VaswaniSPUJGKP17.xml"); neg { + t.Fatalf("dblp_xml must reject Anubis PoW HTML") + } + + // #307 biorxiv_medrxiv_json + if _, ok := FormatWave3ScholarlyJSONMode("biorxiv_medrxiv_json", []byte(`{"collection":[{"doi":"10.1101/2020.09.02.278911","title":"Viral Genomics","authors":"Smith, A.","date":"2020-09-03","version":"1","server":"bioRxiv"}]}`), nil, "https://api.biorxiv.org/details/biorxiv/10.1101/2020.09.02.278911/na/json"); !ok { + t.Fatalf("biorxiv_medrxiv_json failed") + } + if _, neg := FormatWave3ScholarlyJSONMode("biorxiv_medrxiv_json", []byte(`{"messages":[{"status":"DOI not recognizable"}],"collection":[]}`), nil, "https://api.biorxiv.org/details/biorxiv/bad/na/json"); neg { + t.Fatalf("biorxiv_medrxiv_json must reject empty collection") + } + + // #308 nasa_ads_json + if _, ok := FormatWave3ScholarlyJSONMode("nasa_ads_json", []byte(`{"response":{"numFound":1,"docs":[{"bibcode":"2017arXiv170603762V","title":["Attention Is All You Need"],"author":["Vaswani, Ashish"],"year":"2017","citation_count":95000}]}}`), nil, "https://api.adsabs.harvard.edu/v1/search/query"); !ok { + t.Fatalf("nasa_ads_json failed") + } + if _, neg := FormatWave3ScholarlyJSONMode("nasa_ads_json", []byte(`{"message":"Missing \"Authorization\" in headers."}`), nil, "https://api.adsabs.harvard.edu/v1/search/query"); neg { + t.Fatalf("nasa_ads_json must reject 401 unauthorized") + } + + // #309 nih_reporter_json + if _, ok := FormatWave3ScholarlyJSONMode("nih_reporter_json", []byte(`{"meta":{"total":1},"results":[{"appl_id":10476325,"project_num":"5R01CA242003-04","project_title":"Cancer Biomarkers","award_amount":485000,"organization":{"org_name":"STANFORD UNIVERSITY"}}]}`), nil, "https://api.reporter.nih.gov/v2/projects/search"); !ok { + t.Fatalf("nih_reporter_json failed") + } + if _, neg := FormatWave3ScholarlyJSONMode("nih_reporter_json", []byte(`{"meta":{"total":0},"results":[]}`), nil, "https://api.reporter.nih.gov/v2/projects/search"); neg { + t.Fatalf("nih_reporter_json must reject empty results") + } + + // #310 nsf_awards_json + if _, ok := FormatWave3ScholarlyJSONMode("nsf_awards_json", []byte(`{"response":{"award":[{"id":"2535346","title":"EPSCoR Fellowship","awardeeName":"University of Nebraska-Lincoln","pdPIName":"Brigitte Tenhumberg","fundsObligatedAmt":"1749000","date":"08/25/2026"}]}}`), nil, "https://api.nsf.gov/services/v1/awards/2535346.json"); !ok { + t.Fatalf("nsf_awards_json failed") + } + if _, neg := FormatWave3ScholarlyJSONMode("nsf_awards_json", []byte(`{"response":{"award":[]}}`), nil, "https://api.nsf.gov/services/v1/awards/2100001.json"); neg { + t.Fatalf("nsf_awards_json must reject empty award array") + } + + // #311 doe_osti_json (both array and single object!) + if _, ok := FormatWave3ScholarlyJSONMode("doe_osti_json", []byte(`[{"osti_id":"1800000","title":"Wigner Solid Melting","doi":"10.1103/physrevlett.125.036601","publication_date":"2020-07-14T00:00:00Z"}]`), nil, "https://www.osti.gov/api/v1/records/1800000"); !ok { + t.Fatalf("doe_osti_json root array failed") + } + if _, ok := FormatWave3ScholarlyJSONMode("doe_osti_json", []byte(`{"osti_id":"1800000","title":"Wigner Solid Melting","doi":"10.1103/physrevlett.125.036601"}`), nil, "https://www.osti.gov/api/v1/records/1800000"); !ok { + t.Fatalf("doe_osti_json single object failed") + } + if _, neg := FormatWave3ScholarlyJSONMode("doe_osti_json", []byte(`[]`), nil, "https://www.osti.gov/api/v1/records/0"); neg { + t.Fatalf("doe_osti_json must reject empty array") + } + + // #312 research_repo_pack_json (Zenodo, Figshare, Dryad, OSF) + if _, ok := FormatWave3ScholarlyJSONMode("research_repo_pack_json", []byte(`{"id":24485086,"doi":"10.5281/zenodo.24485086","metadata":{"title":"Zenodo Corpus","publication_date":"2025-01-10","creators":[{"name":"Doe, Jane"}]}}`), nil, "https://zenodo.org/api/records/24485086"); !ok { + t.Fatalf("research_repo_pack_json zenodo failed") + } + if _, ok := FormatWave3ScholarlyJSONMode("research_repo_pack_json", []byte(`{"id":35148283,"title":"Figshare Dataset","doi":"10.6084/m9.figshare.35148283","authors":[{"full_name":"Alice"}]}`), nil, "https://api.figshare.com/v2/articles/35148283"); !ok { + t.Fatalf("research_repo_pack_json figshare failed") + } + if _, ok := FormatWave3ScholarlyJSONMode("research_repo_pack_json", []byte(`{"id":99,"identifier":"doi:10.5061/dryad.7rh4625","title":"Dryad Ecological Data","publicationDate":"2024-03-01","storageSize":1024}`), nil, "https://datadryad.org/api/v2/datasets/doi%3A10.5061%2Fdryad.7rh4625"); !ok { + t.Fatalf("research_repo_pack_json dryad failed") + } + if _, ok := FormatWave3ScholarlyJSONMode("research_repo_pack_json", []byte(`{"data":{"id":"k7thf","type":"nodes","attributes":{"title":"OSF Preprint Project","description":"Open Science Framework study"}}}`), nil, "https://api.osf.io/v2/nodes/k7thf/"); !ok { + t.Fatalf("research_repo_pack_json osf failed") + } + + // #313 datacite_json + if _, ok := FormatWave3ScholarlyJSONMode("datacite_json", []byte(`{"data":{"id":"10.5281/zenodo.24485086","type":"dois","attributes":{"doi":"10.5281/zenodo.24485086","titles":[{"title":"Multilingual Benchmark"}],"publisher":"Zenodo","publicationYear":2025}}}`), nil, "https://api.datacite.org/dois/10.5281/zenodo.24485086"); !ok { + t.Fatalf("datacite_json failed") + } + if _, neg := FormatWave3ScholarlyJSONMode("datacite_json", []byte(`{"errors":[{"status":"404","title":"Not found"}]}`), nil, "https://api.datacite.org/dois/10.9999/bad"); neg { + t.Fatalf("datacite_json must reject errors") + } +} + +func TestWave3ScholarlyHTMLExtractorsAndNegativeGuards(t *testing.T) { + // Positive HTML checks + start := time.Now() + nberHTML := `Macroeconomic Effects | NBER

Macroeconomic Effects

We analyze supply chain bottlenecks and inflation dynamics across sectors.

` + rawOut, ok := RunWave3ScholarlyHTMLMode("ssrn_nber_html", nberHTML, "https://www.nber.org/papers/w30000") + if !ok || !strings.Contains(rawOut, "10.3386/w30000") || !strings.Contains(rawOut, "Alice Economist") { + t.Fatalf("ssrn_nber_html positive NBER failed: ok=%v out=%s", ok, rawOut) + } + if elapsed := time.Since(start); elapsed > 50*time.Millisecond*time.Duration(extractRaceSlowdown) { + t.Fatalf("ssrn_nber_html exceeded latency target: %v", elapsed) + } + + zenodoHTML := `Open Corpus | Zenodo

Open Corpus

Curated open dataset for benchmark evaluation.

` + if out, zOK := RunWave3ScholarlyHTMLMode("research_repo_pack_html", zenodoHTML, "https://zenodo.org/records/24485086"); !zOK || !strings.Contains(out, "Zenodo") { + t.Fatalf("research_repo_pack_html Zenodo failed: ok=%v out=%s", zOK, out) + } + + bioHTML := `

Viral Genomics

Genomic surveillance reveals transmission clusters across regions.

` + if out, bOK := RunWave3ScholarlyHTMLMode("biorxiv_medrxiv_html", bioHTML, "https://www.biorxiv.org/content/10.1101/2020.09.02.278911v1"); !bOK || !strings.Contains(out, "10.1101/2020.09.02.278911") { + t.Fatalf("biorxiv_medrxiv_html failed: ok=%v out=%s", bOK, out) + } + + // Negative CSR / WAF / PoW / CF / Overload shell rejections + negCases := []struct { + mode string + url string + html string + }{ + {"orcid_html", "https://orcid.org/0000-0002-1825-0097", `ORCID`}, + {"dblp_html", "https://dblp.org/rec/conf/nips/VaswaniSPUJGKP17.html", `Making sure you're not a bot!

Making sure you're not a bot!

`}, + {"core_ac_html", "https://core.ac.uk/works/11689643", `Just a moment...
cf-turnstile
`}, + {"ror_html", "https://ror.org/03yrm5c26", `Vercel Security Checkpoint

We're verifying your browser

`}, + {"biorxiv_medrxiv_html", "https://www.medrxiv.org/content/10.1101/2020.05.28.20116129v1", `Attention Required! | Cloudflare

Sorry, you have been blocked

`}, + {"nih_reporter_html", "https://reporter.nih.gov/project-details/10476325", `RePORT › RePORTER
`}, + {"nsf_awards_html", "https://www.nsf.gov/awardsearch/show-award?AWD_ID=2535346", `Award Details - NSF Award Search`}, + {"datacite_html", "https://commons.datacite.org/doi.org/10.5281/zenodo.24485086", `

This website is under heavy load (queue full)

`}, + {"ssrn_nber_html", "https://papers.ssrn.com/sol3/papers.cfm?abstract_id=4131630", `Just a moment...
`}, + {"semantic_scholar_html", "https://www.semanticscholar.org/paper/foo/204e3073870fae3d05bcbc2f6a8e263d9b72e776", `Semantic Scholar
`}, + } + + for _, nc := range negCases { + if out, negOK := RunWave3ScholarlyHTMLMode(nc.mode, nc.html, nc.url); negOK { + t.Fatalf("%s must reject negative shell for %s, got: %s", nc.mode, nc.url, out) + } + } +} + +func TestWave3ScholarlyFixturesGoldenAndNegative(t *testing.T) { + catLIDs := []string{ + "semantic-scholar", + "unpaywall", + "core-ac", + "orcid", + "ror", + "dblp", + "biorxiv-medrxiv", + "nasa-ads", + "nih-reporter", + "nsf-awards", + "doe-osti", + "research-repo-pack", + "datacite", + "ssrn-nber", + } + + type fixtureNeg struct { + Name string `json:"name"` + Status int `json:"status"` + InputURL string `json:"inputUrl"` + FinalURL string `json:"finalUrl"` + Payload string `json:"payload"` + } + type fixture struct { + AdapterID string `json:"adapterId"` + Mode string `json:"mode"` + InputURL string `json:"inputUrl"` + ExpectedFetchURL string `json:"expectedFetchUrl"` + MockPayload string `json:"mockPayload"` + ExpectTitleIncludes string `json:"expectTitleIncludes"` + ExpectMarkdownIncludes []string `json:"expectMarkdownIncludes"` + NegativeCases []fixtureNeg `json:"negativeCases"` + } + + for _, id := range catLIDs { + rawManifest, err := os.ReadFile(filepath.Join("manifests", id+".yaml")) + if err != nil { + t.Fatalf("read %s.yaml: %v", id, err) + } + m, err := ParseDeclarativeYAMLManifest(rawManifest) + if err != nil { + t.Fatalf("parse %s.yaml: %v", id, err) + } + + rawFx, err := os.ReadFile(filepath.Join("..", "..", "hub", "test", "fixtures", "adapters", id+".json")) + if err != nil { + t.Fatalf("read fixture %s.json: %v", id, err) + } + var fx fixture + if err := json.Unmarshal(rawFx, &fx); err != nil { + t.Fatalf("unmarshal fixture %s.json: %v", id, err) + } + if fx.AdapterID != id || len(fx.NegativeCases) < 4 { + t.Fatalf("fixture %s.json invalid header/negative count: %+v", id, len(fx.NegativeCases)) + } + + if fx.Mode == "twin" { + tm, ok := wave3ScholarlyResolveManifest(t, m, fx.InputURL) + if !ok { + t.Fatalf("%s: expected twin resolution for %s", id, fx.InputURL) + } + if fx.ExpectedFetchURL != "" && tm.FetchURL != fx.ExpectedFetchURL { + t.Fatalf("%s: FetchURL=%q want=%q", id, tm.FetchURL, fx.ExpectedFetchURL) + } + var rawDoc string + var fmtOK bool + if tm.route.Extract.JSONMode != "" { + rawDoc, fmtOK = FormatWave3ScholarlyJSONMode(tm.route.Extract.JSONMode, []byte(fx.MockPayload), tm.params, fx.InputURL) + } else if tm.route.Extract.TextMode != "" { + rawDoc, fmtOK = FormatWave3ScholarlyTextMode(tm.route.Extract.TextMode, fx.MockPayload, tm.params, fx.InputURL) + } + if !fmtOK { + t.Fatalf("%s: golden formatter failed", id) + } + doc := wave3ScholarlyDecodeDoc(t, rawDoc) + if fx.ExpectTitleIncludes != "" && !strings.Contains(doc.Title, fx.ExpectTitleIncludes) { + t.Fatalf("%s: title %q missing %q", id, doc.Title, fx.ExpectTitleIncludes) + } + for _, needle := range fx.ExpectMarkdownIncludes { + if !strings.Contains(doc.Markdown, needle) { + t.Fatalf("%s: markdown missing %q", id, needle) + } + } + } else { + if len(m.HTMLRoutes) == 0 { + t.Fatalf("%s: expected htmlRoutes for mode=html", id) + } + rawOut, ok := RunWave3ScholarlyHTMLMode(m.HTMLRoutes[0].Mode, fx.MockPayload, fx.InputURL) + if !ok { + t.Fatalf("%s: golden HTML extractor failed", id) + } + var res DeclarativePostFetchResult + if err := json.Unmarshal([]byte(rawOut), &res); err != nil { + t.Fatalf("%s: unmarshal HTML result: %v", id, err) + } + if fx.ExpectTitleIncludes != "" && !strings.Contains(res.Title, fx.ExpectTitleIncludes) { + t.Fatalf("%s: title %q missing %q", id, res.Title, fx.ExpectTitleIncludes) + } + for _, needle := range fx.ExpectMarkdownIncludes { + if !strings.Contains(res.Markdown, needle) { + t.Fatalf("%s: markdown missing %q", id, needle) + } + } + } + + for _, nc := range fx.NegativeCases { + ncURL := nc.InputURL + if ncURL == "" { + ncURL = fx.InputURL + } + if nc.FinalURL != "" { + if len(m.HTMLRoutes) > 0 { + if _, negOK := RunWave3ScholarlyHTMLMode(m.HTMLRoutes[0].Mode, nc.Payload, nc.FinalURL); negOK { + t.Fatalf("%s:%s redirect HTML unexpectedly succeeded", id, nc.Name) + } + } + continue + } + trim := strings.TrimSpace(nc.Payload) + if strings.HasPrefix(trim, "{") || strings.HasPrefix(trim, "[") { + if tm, ok := wave3ScholarlyResolveManifest(t, m, ncURL); ok && tm.route.Extract.JSONMode != "" { + if _, negOK := FormatWave3ScholarlyJSONMode(tm.route.Extract.JSONMode, []byte(nc.Payload), tm.params, ncURL); negOK { + t.Fatalf("%s:%s negative JSON unexpectedly succeeded", id, nc.Name) + } + } + } else if len(m.HTMLRoutes) > 0 { + if _, negOK := RunWave3ScholarlyHTMLMode(m.HTMLRoutes[0].Mode, nc.Payload, ncURL); negOK { + t.Fatalf("%s:%s negative HTML unexpectedly succeeded", id, nc.Name) + } + } + } + } +} + +func TestWave3ScholarlyUTF8SafeDescriptionTruncation(t *testing.T) { + // Place a 3-byte UTF-8 rune ("—") straddling byte offset 260 (bytes 259..261). + abstract := strings.Repeat("a", 259) + "—" + strings.Repeat("b", 50) + payload := `{"paperId":"p1","title":"UTF-8 Abstract Paper","abstract":"` + abstract + `","year":2026,"authors":[{"name":"Ada Lovelace"}]}` + raw, ok := FormatWave3ScholarlyJSONMode("semantic_scholar_json", []byte(payload), nil, "https://api.semanticscholar.org/graph/v1/paper/p1") + if !ok { + t.Fatalf("expected semantic_scholar_json to format UTF-8 abstract") + } + doc := wave3ScholarlyDecodeDoc(t, raw) + if !utf8.ValidString(doc.Description) || strings.ContainsRune(doc.Description, '\uFFFD') { + t.Fatalf("description contains invalid UTF-8 or replacement rune: %q", doc.Description) + } + if !strings.HasSuffix(doc.Description, "...") { + t.Fatalf("expected truncated description suffix '...', got %q", doc.Description) + } +} + +func TestWave3ScholarlyDryadJSONLDRepoPack(t *testing.T) { + // #312 research-repo-pack Dryad page with @id DOI, []any description, and creator (no citation_* meta tags) + dryadHTML := `Cenozoic marine diversification

Cenozoic marine diversification

` + declRes, okDecl := ApplyDeclarativeHTMLExtractor(dryadHTML, "https://datadryad.org/dataset/doi:10.5061/dryad.7rh4625", "", nil) + if !okDecl || declRes == nil || declRes.ExtractorID != "research-repo-pack" { + t.Fatalf("expected research-repo-pack on Dryad without schema-dataset preemption, got ok=%v res=%+v", okDecl, declRes) + } + if !strings.Contains(declRes.Markdown, "10.5061/dryad.7rh4625") || + !strings.Contains(declRes.Markdown, "Jane Paleontologist") || + !strings.Contains(declRes.Markdown, "Alan Grant") || + !strings.Contains(declRes.Markdown, "Over the Cenozoic") { + t.Fatalf("Dryad extracted markdown missing expected DOI/authors/description:\n%s", declRes.Markdown) + } + + // #312 research-repo-pack Dryad page with passive AWS WAF jsapi.js script + real body markers MUST still extract cleanly + dryadWithPassiveWAF := `Distinct predatory behaviors in sabertooth cats

Distinct predatory behaviors in scimitar- and dirk-toothed sabertooth cats

` + wafRes, okWaf := ApplyDeclarativeHTMLExtractor(dryadWithPassiveWAF, "https://datadryad.org/dataset/doi:10.5061/dryad.7rh4625", "", nil) + if !okWaf || wafRes == nil || wafRes.ExtractorID != "research-repo-pack" { + t.Fatalf("expected research-repo-pack on Dryad with passive awswaf jsapi.js + body markers, got ok=%v res=%+v", okWaf, wafRes) + } + // Thin <16KB AWS WAF challenge shell without real body markers MUST still be rejected + thinWAF := `Verification
` + if negRes := Wave3ScholarlyRunHTML("research_repo_pack_html", thinWAF, "https://datadryad.org/dataset/doi:10.5061/dryad.7rh4625", "research-repo-pack"); negRes != nil { + t.Fatalf("expected thin awswaf shell without body markers to be rejected, got %+v", negRes) + } +} diff --git a/internal/extract/wave3_security_intel.go b/internal/extract/wave3_security_intel.go new file mode 100644 index 0000000..c8255c1 --- /dev/null +++ b/internal/extract/wave3_security_intel.go @@ -0,0 +1,3582 @@ +package extract + +import ( + "bytes" + "encoding/csv" + "encoding/json" + "fmt" + stdhtml "html" + "io" + "math" + "net/url" + "strconv" + "strings" +) + +const ( + wave3SecMaxHTMLBytes = 2 * 1024 * 1024 + wave3SecBGPHEMaxBytes = 1 * 1024 * 1024 + wave3SecMaxJSONBytes = 4 * 1024 * 1024 + wave3SecMaxTextBytes = 4 * 1024 * 1024 + wave3SecMaxRecords = 25 + wave3SecMaxSnippetByte = 2400 +) + +var ( + wave3SecRxNotFoundTitle = newLazyRegexp(`(?i)(?:^|\b)(?:404|410|406|page\s+not\s+found|not\s+found|error\s*404|we\s+couldn'?t\s+find\s+that\s+page|access\s+denied|request\s+(?:rejected|blocked)|could\s+not\s+be\s+satisfied|unauthorized|attention\s+required|just\s+a\s+moment|403\s+forbidden|forbidden|403\s+error|bad\s+gateway|502\s+bad\s+gateway)(?:\b|$)`) + wave3SecRxMaintTitle = newLazyRegexp(`(?i)(?:scheduled\s+maintenance|temporarily\s+unavailable|service\s+unavailable|site\s+maintenance|under\s+maintenance|502\s+bad\s+gateway|503\s+service|down\s+for\s+maintenance)`) + wave3SecRxErrorTitle = newLazyRegexp(`(?i)^(?:(?:(?:400|401|403|404|406|410|429|500|502|503)\s+)?(?:internal\s+)?server\s+error|application\s+error|system\s+error|unexpected\s+error|error\s+page|(?:400|401|403|404|406|410|429|500|502|503|http\s+\d{3})\s+error|error\s+(?:400|401|403|404|406|410|429|500|502|503)|error)(?:\s*[|\-\x{2013}\x{2014}:]\s*.*)?$|^.*(?:\s*[|\-\x{2013}\x{2014}:]\s*error)$`) + wave3SecRxGenericTitle = newLazyRegexp(`(?i)^(?:loading\.{0,3}|home|welcome|search|crt\.sh|bgp\.he\.net|cve\s+record)$`) + wave3SecRxHTMLTag = newLazyRegexp(`<[^>]+>`) + wave3SecRxSpaceCollapse = newLazyRegexp(`[ \t\r\n]+`) + wave3SecRxCVE = newLazyRegexp(`(?i)\bCVE-\d{4}-\d{4,7}\b`) + wave3SecRxEDBID = newLazyRegexp(`(?i)(?:/exploits/|EDB-ID\s*:?\s*)(\d{1,8})`) + wave3SecRxASN = newLazyRegexp(`(?i)\bAS\d{1,10}\b`) + wave3SecRxISODate = newLazyRegexp(`\b(\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2}))?)\b`) + wave3SecRxCSAFURL = newLazyRegexp(`https://(?:github\.com|raw\.githubusercontent\.com)/cisagov/CSAF/[^\s"'<>]+?\.json`) + wave3SecRxPreCode = newLazyRegexp(`(?is)]*>(.*?)|]*>(.*?)`) +) + +func init() { + registerWave3SecurityIntelHTMLModes() +} + +// RegisterWave3SecurityIntelHTMLModes registers all Category M HTML modes via RegisterExternalHTMLModeLazy. +func RegisterWave3SecurityIntelHTMLModes() { + registerWave3SecurityIntelHTMLModes() +} + +func registerWave3SecurityIntelHTMLModes() { + for _, mode := range []string{ + "cisa_kev_html", + "mitre_attack_html", + "mitre_cwe_capec_html", + "cve_org_html", + "cisa_advisories_html", + "exploit_db_html", + "cert_transparency_html", + "bgp_he_html", + } { + m := mode + RegisterExternalHTMLModeLazy(m, func(rawHTML, baseURL string, _ func() string, extractorID string) *DeclarativePostFetchResult { + return Wave3SecurityIntelRunHTML(m, rawHTML, baseURL, extractorID) + }) + } +} + +// IsWave3SecurityIntelHTMLMode reports whether mode is one of the Category M HTML extractors. +func IsWave3SecurityIntelHTMLMode(mode string) bool { + switch mode { + case "cisa_kev_html", + "mitre_attack_html", + "mitre_cwe_capec_html", + "cve_org_html", + "cisa_advisories_html", + "exploit_db_html", + "cert_transparency_html", + "bgp_he_html": + return true + default: + return false + } +} + +func isWave3SecurityIntelJSONMode(mode string) bool { + return IsWave3SecurityIntelJSONMode(mode) +} + +// IsWave3SecurityIntelJSONMode reports whether mode is one of the Category M JSON formatters (#315-#326). +func IsWave3SecurityIntelJSONMode(mode string) bool { + switch mode { + case "cisa_kev_json", + "first_epss_json", + "mitre_attack_index_json", + "mitre_cwe_json", + "cve_org_json", + "vendor_csaf_json", + "cert_transparency_json", + "rdap_bootstrap_json", + "rdap_json", + "bgp_asn_ripe_json": + return true + default: + return false + } +} + +func isWave3SecurityIntelTextMode(mode string) bool { + return IsWave3SecurityIntelTextMode(mode) +} + +// IsWave3SecurityIntelTextMode reports whether mode is one of the Category M text/CSV/STIX/RSS formatters. +func IsWave3SecurityIntelTextMode(mode string) bool { + switch mode { + case "cisa_kev_csv", + "mitre_attack_stix_bundle", + "cisa_advisories_rss", + "security_txt_text", + "exploit_db_csv", + "exploit_db_rss": + return true + default: + return false + } +} + +func wave3SecDefaultExtractorID(mode string) string { + switch mode { + case "cisa_kev_html", "cisa_kev_json", "cisa_kev_csv": + return "cisa-kev" + case "first_epss_json": + return "first-epss" + case "mitre_attack_html", "mitre_attack_index_json", "mitre_attack_stix_bundle": + return "mitre-attack" + case "mitre_cwe_capec_html", "mitre_cwe_json": + return "mitre-cwe-capec" + case "cve_org_html", "cve_org_json": + return "cve-org" + case "cisa_advisories_html", "cisa_advisories_rss": + return "cisa-advisories-ics" + case "vendor_csaf_json": + return "vendor-csaf" + case "security_txt_text": + return "security-txt" + case "exploit_db_html", "exploit_db_csv", "exploit_db_rss": + return "exploit-db" + case "cert_transparency_html", "cert_transparency_json": + return "certificate-transparency" + case "rdap_bootstrap_json", "rdap_json": + return "rdap" + case "bgp_he_html", "bgp_asn_ripe_json": + return "bgp-asn" + default: + return "" + } +} + +// Wave3SecurityIntelRunHTML executes a Category M HTML extractor and returns DeclarativePostFetchResult. +func Wave3SecurityIntelRunHTML(mode, rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + if !IsWave3SecurityIntelHTMLMode(mode) || len(rawHTML) == 0 || strings.IndexByte(rawHTML, '<') < 0 || strings.IndexByte(rawHTML, '>') < 0 { + return nil + } + if mode == "bgp_he_html" { + if len(rawHTML) > wave3SecBGPHEMaxBytes { + rawHTML = truncateUTF8SafeFullDocGo(rawHTML, wave3SecBGPHEMaxBytes) + } + } else if len(rawHTML) > wave3SecMaxHTMLBytes { + rawHTML = truncateUTF8SafeFullDocGo(rawHTML, wave3SecMaxHTMLBytes) + } + trimmedStart := strings.TrimLeft(rawHTML, " \t\r\n") + if trimmedStart == "" || trimmedStart[0] == '{' || trimmedStart[0] == '[' { + return nil + } + + probe := rawHTML + if len(probe) > 65536 { + probe = probe[:65536] + } + probeLower := asciiLowerExtractString(probe) + urlLower := asciiLowerExtractString(baseURL) + + // Cheap byte prefilter BEFORE common negative-shell checks or DOM parsing. + if !wave3SecMatchesModePrefilter(mode, probeLower, urlLower) { + return nil + } + if wave3SecHasCommonNegativeShell(rawHTML, probeLower, urlLower) { + return nil + } + if extractorID == "" { + extractorID = wave3SecDefaultExtractorID(mode) + } + + var res *DeclarativePostFetchResult + switch mode { + case "cisa_kev_html": + res = wave3SecExtractCISAKEVHTML(rawHTML, baseURL, extractorID) + case "mitre_attack_html": + res = wave3SecExtractMitreAttackHTML(rawHTML, baseURL, extractorID) + case "mitre_cwe_capec_html": + res = wave3SecExtractMitreCWECAPECHTML(rawHTML, probeLower, baseURL, urlLower, extractorID) + case "cve_org_html": + res = wave3SecExtractCVEOrgHTML(rawHTML, probeLower, baseURL, extractorID) + case "cisa_advisories_html": + res = wave3SecExtractCISAAdvisoriesHTML(rawHTML, baseURL, extractorID) + case "exploit_db_html": + res = wave3SecExtractExploitDBHTML(rawHTML, probeLower, baseURL, extractorID) + case "cert_transparency_html": + res = wave3SecExtractCertTransparencyHTML(rawHTML, baseURL, extractorID) + case "bgp_he_html": + res = wave3SecExtractBGPHEHTML(rawHTML, probeLower, baseURL, extractorID) + } + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return nil + } + return wave3SecFinalizePostFetch(res) +} + +// RunWave3SecurityIntelHTMLMode executes a Category M HTML extractor and returns JSON-marshaled DeclarativePostFetchResult. +func RunWave3SecurityIntelHTMLMode(mode, rawHTML, baseURL string) (string, bool) { + res := Wave3SecurityIntelRunHTML(mode, rawHTML, baseURL, wave3SecDefaultExtractorID(mode)) + res = sanitizePostFetchResultDeclHTML(res) + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return "", false + } + encoded, err := json.Marshal(res) + if err != nil { + return "", false + } + return string(encoded), true +} + +func formatWave3SecurityIntelJSON(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool) { + return FormatWave3SecurityIntelJSONDoc(mode, raw, params, origURL) +} + +// FormatWave3SecurityIntelJSONDoc formats a Category M JSON payload into DeclarativeFormattedDoc. +func FormatWave3SecurityIntelJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool) { + if !IsWave3SecurityIntelJSONMode(mode) || len(raw) == 0 || len(raw) > wave3SecMaxJSONBytes { + return nil, false + } + trimmed := bytes.TrimSpace(bytes.TrimPrefix(raw, []byte("\xEF\xBB\xBF"))) + if len(trimmed) == 0 || (trimmed[0] != '{' && trimmed[0] != '[') { + return nil, false + } + parsed, ok := decodeJSONWithNumbers(trimmed) + if !ok || parsed == nil { + return nil, false + } + + var doc *DeclarativeFormattedDoc + var handled bool + switch mode { + case "cisa_kev_json": + doc, handled = wave3SecFormatCISAKEVJSON(parsed, origURL) + case "first_epss_json": + doc, handled = wave3SecFormatFirstEPSSJSON(parsed, origURL) + case "mitre_attack_index_json": + doc, handled = wave3SecFormatMitreAttackIndexJSON(parsed, origURL) + case "mitre_cwe_json": + doc, handled = wave3SecFormatMitreCWEJSON(parsed, origURL) + case "cve_org_json": + doc, handled = wave3SecFormatCVEOrgJSON(parsed, origURL) + case "vendor_csaf_json": + doc, handled = wave3SecFormatVendorCSAFJSON(parsed, origURL) + case "cert_transparency_json": + doc, handled = wave3SecFormatCertTransparencyJSON(parsed, origURL) + case "rdap_bootstrap_json": + doc, handled = wave3SecFormatRDAPBootstrapJSON(parsed, origURL) + case "rdap_json": + doc, handled = wave3SecFormatRDAPJSON(parsed, origURL) + case "bgp_asn_ripe_json": + doc, handled = wave3SecFormatBGPASNRipeJSON(parsed, origURL) + } + if !handled || doc == nil || strings.TrimSpace(doc.Markdown) == "" { + return nil, false + } + return wave3SecFinalizeDoc(doc), true +} + +// FormatWave3SecurityIntelJSONMode formats a Category M JSON payload and returns JSON-marshaled DeclarativeFormattedDoc. +func FormatWave3SecurityIntelJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool) { + doc, ok := FormatWave3SecurityIntelJSONDoc(mode, raw, params, origURL) + if !ok || doc == nil { + return "", false + } + encoded, err := json.Marshal(doc) + if err != nil { + return "", false + } + return string(encoded), true +} + +func formatWave3SecurityIntelText(mode, rawBody string, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool) { + return FormatWave3SecurityIntelTextDoc(mode, rawBody, params, origURL) +} + +// FormatWave3SecurityIntelTextDoc formats a Category M text/CSV/STIX/RSS payload into DeclarativeFormattedDoc. +func FormatWave3SecurityIntelTextDoc(mode, rawBody string, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool) { + if !IsWave3SecurityIntelTextMode(mode) || len(rawBody) == 0 { + return nil, false + } + if len(rawBody) > wave3SecMaxTextBytes { + rawBody = truncateUTF8SafeFullDocGo(rawBody, wave3SecMaxTextBytes) + } + rawBody = strings.TrimPrefix(rawBody, "\xEF\xBB\xBF") + + var doc *DeclarativeFormattedDoc + var handled bool + switch mode { + case "cisa_kev_csv": + doc, handled = wave3SecFormatCISAKEVCSV(rawBody, origURL) + case "mitre_attack_stix_bundle": + doc, handled = wave3SecFormatMitreAttackSTIXBundle(rawBody, origURL) + case "cisa_advisories_rss": + doc, handled = wave3SecFormatRSS(rawBody, origURL, "CISA Cybersecurity Advisories", true) + case "security_txt_text": + doc, handled = wave3SecFormatSecurityTxt(rawBody, origURL) + case "exploit_db_csv": + doc, handled = wave3SecFormatExploitDBCSV(rawBody, origURL) + case "exploit_db_rss": + doc, handled = wave3SecFormatRSS(rawBody, origURL, "Exploit-DB Recent Exploits", false) + } + if !handled || doc == nil || strings.TrimSpace(doc.Markdown) == "" { + return nil, false + } + return wave3SecFinalizeDoc(doc), true +} + +// FormatWave3SecurityIntelTextMode formats a Category M text payload and returns JSON-marshaled DeclarativeFormattedDoc. +func FormatWave3SecurityIntelTextMode(mode, rawBody string, params map[string]string, origURL string) (string, bool) { + doc, ok := FormatWave3SecurityIntelTextDoc(mode, rawBody, params, origURL) + if !ok || doc == nil { + return "", false + } + encoded, err := json.Marshal(doc) + if err != nil { + return "", false + } + return string(encoded), true +} + +// ── Prefilters & Shared Hygiene Helpers ────────────────────────────────────────────────────────── + +func wave3SecMatchesModePrefilter(mode, probeLower, urlLower string) bool { + switch mode { + case "cisa_kev_html": + return strings.Contains(urlLower, "known-exploited-vulnerabilities-catalog") || + strings.Contains(probeLower, "known exploited vulnerabilities") || + strings.Contains(probeLower, "known_exploited_vulnerabilities") + case "mitre_attack_html": + return strings.Contains(urlLower, "attack.mitre.org") || + strings.Contains(probeLower, "attack.mitre.org") || + strings.Contains(probeLower, "card-data") || + strings.Contains(probeLower, "description-body") || + strings.Contains(probeLower, "mitre att&ck") + case "mitre_cwe_capec_html": + return strings.Contains(urlLower, "cwe.mitre.org") || + strings.Contains(urlLower, "capec.mitre.org") || + strings.Contains(probeLower, "cwe-") || + strings.Contains(probeLower, "capec-") + case "cve_org_html": + return strings.Contains(urlLower, "cve.org") || + strings.Contains(probeLower, "cve-") || + strings.Contains(probeLower, "common vulnerabilities and exposures") + case "cisa_advisories_html": + return strings.Contains(urlLower, "cisa.gov") || + strings.Contains(probeLower, "cisa.gov") || + strings.Contains(probeLower, "l-page__main") || + strings.Contains(probeLower, "icsa-") || + strings.Contains(probeLower, "icsma-") + case "exploit_db_html": + return strings.Contains(urlLower, "exploit-db.com") || + strings.Contains(probeLower, "exploit-db") || + strings.Contains(probeLower, "exploit database") || + strings.Contains(probeLower, "edb-id") + case "cert_transparency_html": + return strings.Contains(urlLower, "crt.sh") || + strings.Contains(probeLower, "crt.sh") || + strings.Contains(probeLower, "certificate search") || + strings.Contains(probeLower, "logged at") + case "bgp_he_html": + return strings.Contains(urlLower, "bgp.he.net") || + strings.Contains(probeLower, "bgp.he.net") || + strings.Contains(probeLower, "asinfo") || + strings.Contains(probeLower, "hurricane electric") + default: + return false + } +} + +func wave3SecIsNegativeURL(urlLower string) bool { + if urlLower == "" { + return false + } + if strings.Contains(urlLower, "/404") || + strings.Contains(urlLower, "/not-found") || + strings.Contains(urlLower, "/page-not-found") || + strings.Contains(urlLower, "/maintenance") || + strings.Contains(urlLower, "error=true") || + strings.Contains(urlLower, "error=1") { + return true + } + pathOnly := urlLower + if idx := strings.Index(pathOnly, "://"); idx >= 0 { + rest := pathOnly[idx+3:] + if slash := strings.IndexByte(rest, '/'); slash >= 0 { + pathOnly = rest[slash:] + } else { + pathOnly = "/" + } + } + if cut := strings.IndexAny(pathOnly, "?#"); cut >= 0 { + pathOnly = pathOnly[:cut] + } + return strings.HasSuffix(pathOnly, "/error") || + strings.Contains(pathOnly, "/error/") || + strings.HasSuffix(pathOnly, "/error.html") || + strings.HasSuffix(pathOnly, "/error.htm") || + strings.HasSuffix(pathOnly, "/error.aspx") || + strings.HasSuffix(pathOnly, "/login") || + strings.Contains(pathOnly, "/login/") +} + +func wave3SecIsNegativeTitle(title string) bool { + t := strings.TrimSpace(title) + if t == "" { + return false + } + return wave3SecRxNotFoundTitle.MatchString(t) || + wave3SecRxMaintTitle.MatchString(t) || + wave3SecRxErrorTitle.MatchString(t) +} + +func wave3SecIsGenericTitle(title string) bool { + return wave3SecRxGenericTitle.MatchString(strings.TrimSpace(title)) +} + +func wave3SecHasCommonNegativeShell(rawHTML, probeLower, urlLower string) bool { + if wave3SecIsNegativeURL(urlLower) { + return true + } + for _, marker := range []string{ + "cf-browser-verification", + "cf-turnstile", + "challenge-platform", + "_cf_chl_opt", + "cf_chl_opt", + "attention required! | cloudflare", + "just a moment...", + "errors.edgesuite.net", + "error from cloudfront", + "the request could not be satisfied", + "you don't have permission to access", + "the requested url was rejected", + "your support id is", + "var dd=", + "var dd =", + "dd={'rt'", + "geo.captcha-delivery.com", + "captcha-delivery.com", + "vercel security checkpoint", + "anubis_version", + "anubis_challenge", + "cae-xauth-err", + "scheduled maintenance", + "down for maintenance", + "temporarily unavailable", + "502 bad gateway", + } { + if strings.Contains(probeLower, marker) { + return true + } + } + title := extractTitleLinearQuick(rawHTML) + if wave3SecIsNegativeTitle(title) { + return true + } + if canon := strings.ToLower(extractMetaContentDeclHTML(rawHTML, "og:url")); strings.HasSuffix(canon, "/404") || strings.Contains(canon, "/404?") { + return true + } + rawLower := asciiLowerExtractString(rawHTML) + hasRealBodyMarkers := hasJSONLDScriptToken(rawHTML) || + strings.Contains(rawLower, "
") || strings.Contains(rawLower, "")) && + !hasRealBodyMarkers { + return true + } + if wave3HasEmptyRootDivShell(rawHTML, probeLower, true) && !hasRealBodyMarkers { + return true + } + return false +} + +func wave3SecIsGenericJSONError(obj map[string]any) bool { + if obj == nil { + return true + } + if succ, ok := obj["success"].(bool); ok && !succ { + return true + } + for _, k := range []string{"error", "errors", "error_message", "errorMessage", "error_description", "fault"} { + if v, exists := obj[k]; exists && v != nil { + switch tv := v.(type) { + case string: + if strings.TrimSpace(tv) != "" { + return true + } + case []any: + if len(tv) > 0 { + return true + } + case map[string]any: + if len(tv) > 0 { + return true + } + case bool: + if tv { + return true + } + } + } + } + for _, k := range []string{"errorCode", "error_code", "statusCode", "status_code", "status-code"} { + if f, ok := wave3SecFloatVal(obj[k]); ok && f >= 400 { + return true + } + } + if st := strings.ToUpper(wave3SecPlain(obj["status"], 48)); st == "ERROR" || st == "NOT_FOUND" || st == "PERMISSION_DENIED" || st == "UNAUTHENTICATED" || st == "UNAUTHORIZED" { + return true + } + if typ := strings.ToLower(wave3SecPlain(obj["type"], 32)); typ == "error" { + return true + } + if msg := wave3SecPlain(obj["message"], 240); msg != "" && len(obj) <= 4 { + lm := strings.ToLower(msg) + if strings.Contains(lm, "not found") || + strings.Contains(lm, "invalid") || + strings.Contains(lm, "unauthorized") || + strings.Contains(lm, "forbidden") || + strings.Contains(lm, "rate limit") { + return true + } + } + return false +} + +func wave3SecIntPtr(n int) *int { return &n } +func wave3SecBoolPtr(b bool) *bool { return &b } + +func wave3SecFinalizeDoc(doc *DeclarativeFormattedDoc) *DeclarativeFormattedDoc { + if doc == nil { + return nil + } + if len(doc.Records) > wave3SecMaxRecords { + if doc.Total == nil { + doc.Total = wave3SecIntPtr(len(doc.Records)) + } + doc.Records = doc.Records[:wave3SecMaxRecords] + doc.Returned = wave3SecIntPtr(len(doc.Records)) + doc.Truncated = wave3SecBoolPtr(true) + if doc.NextCursor == "" { + doc.NextCursor = strconv.Itoa(len(doc.Records)) + } + } + if sanitized, ok := sanitizeDeclarativeFormattedDocGo(doc); ok && sanitized != nil { + return sanitized + } + return nil +} + +func wave3SecFinalizePostFetch(res *DeclarativePostFetchResult) *DeclarativePostFetchResult { + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return nil + } + if len(res.Records) > wave3SecMaxRecords { + if res.Total == nil { + res.Total = wave3SecIntPtr(len(res.Records)) + } + res.Records = res.Records[:wave3SecMaxRecords] + res.Returned = wave3SecIntPtr(len(res.Records)) + res.Truncated = wave3SecBoolPtr(true) + if res.NextCursor == "" { + res.NextCursor = strconv.Itoa(len(res.Records)) + } + } + return res +} + +func wave3SecCleanText(s string) string { + if s == "" { + return "" + } + if strings.IndexByte(s, '<') >= 0 { + s = wave3SecRxHTMLTag.ReplaceAllString(s, " ") + } + if strings.IndexByte(s, '&') >= 0 { + s = stdhtml.UnescapeString(s) + if strings.IndexByte(s, '<') >= 0 { + s = wave3SecRxHTMLTag.ReplaceAllString(s, " ") + } + } + if !strings.ContainsAny(s, "\t\r\n") && !strings.Contains(s, " ") { + return strings.TrimSpace(s) + } + return strings.TrimSpace(wave3SecRxSpaceCollapse.ReplaceAllString(s, " ")) +} + +func wave3SecStringVal(v any) string { + switch tv := v.(type) { + case string: + return strings.TrimSpace(tv) + case json.Number: + return tv.String() + case float64: + if math.IsNaN(tv) || math.IsInf(tv, 0) { + return "" + } + if tv == math.Trunc(tv) { + return strconv.FormatInt(int64(tv), 10) + } + return strconv.FormatFloat(tv, 'f', -1, 64) + case int: + return strconv.Itoa(tv) + case int64: + return strconv.FormatInt(tv, 10) + case bool: + if tv { + return "true" + } + return "false" + default: + return "" + } +} + +func wave3SecFloatVal(v any) (float64, bool) { + switch tv := v.(type) { + case float64: + if math.IsNaN(tv) || math.IsInf(tv, 0) { + return 0, false + } + return tv, true + case int: + return float64(tv), true + case int64: + return float64(tv), true + case json.Number: + f, err := tv.Float64() + if err != nil || math.IsNaN(f) || math.IsInf(f, 0) { + return 0, false + } + return f, true + case string: + s := strings.TrimSpace(strings.ReplaceAll(tv, ",", "")) + if s == "" { + return 0, false + } + f, err := strconv.ParseFloat(s, 64) + if err != nil || math.IsNaN(f) || math.IsInf(f, 0) { + return 0, false + } + return f, true + default: + return 0, false + } +} + +func wave3SecPlain(v any, maxLen int) string { + return SanitizeSchemaPlainField(wave3SecStringVal(v), maxLen) +} + +func wave3SecFirstNonEmpty(vals ...string) string { + for _, v := range vals { + if t := strings.TrimSpace(v); t != "" { + return t + } + } + return "" +} + +func wave3SecNormalizeDate(raw string) string { + s := SanitizeSchemaPlainField(raw, 48) + if s == "" { + return "" + } + if len(s) >= 10 && s[4] == '-' && s[7] == '-' { + return s[:10] + } + if m := wave3SecRxISODate.FindStringSubmatch(s); len(m) >= 2 { + return m[1][:10] + } + return s +} + +func wave3SecAddLink(links *[]string, seen map[string]bool, raw, base string) { + u := SanitizeSchemaHTTPSURL(raw, base) + if u != "" && !seen[u] { + seen[u] = true + *links = append(*links, u) + } +} + +func wave3SecExtractTitle(doc *HTMLDoc, rawHTML string) string { + if doc != nil { + if h1 := SanitizeSchemaPlainField(wave3SecCleanText(doc.Text("h1")), 240); h1 != "" && !wave3SecIsGenericTitle(h1) { + return h1 + } + } + if og := SanitizeSchemaPlainField(extractMetaContentDeclHTML(rawHTML, "og:title"), 240); og != "" && !wave3SecIsGenericTitle(og) { + return og + } + if t := SanitizeSchemaPlainField(extractTitleLinearQuick(rawHTML), 240); t != "" && !wave3SecIsGenericTitle(t) { + return t + } + return "" +} + +func wave3SecExtractMetaDesc(rawHTML string) string { + return wave3SecFirstNonEmpty( + SanitizeSchemaPlainField(extractMetaContentDeclHTML(rawHTML, "og:description"), 600), + SanitizeSchemaPlainField(extractMetaContentDeclHTML(rawHTML, "description"), 600), + ) +} + +func wave3SecFragToMD(frag, baseURL string) string { + if strings.TrimSpace(frag) == "" { + return "" + } + doc := ExtractHTMLDocumentFull(""+frag+"", FullExtractOptions{ + BaseURL: baseURL, + OnlyMainContent: false, + IncludeImages: false, + IsFragment: true, + SkipUniversalExtractors: true, + SkipPlainText: true, + }) + return strings.TrimSpace(doc.Markdown) +} + +func wave3SecExtractCVEs(text string, max int) []string { + if text == "" { + return nil + } + matches := wave3SecRxCVE.FindAllString(text, max*3) + if len(matches) == 0 { + return nil + } + seen := make(map[string]bool, len(matches)) + out := make([]string, 0, len(matches)) + for _, m := range matches { + up := strings.ToUpper(m) + if !seen[up] { + seen[up] = true + out = append(out, up) + if len(out) >= max { + break + } + } + } + return out +} + +func wave3SecExtractTableBlock(doc *HTMLDoc, selector string, maxRows int) (string, [][]string) { + if doc == nil { + return "", nil + } + rows := doc.TableRows(selector) + if len(rows) < 2 || len(rows[0]) == 0 { + return "", nil + } + cols := len(rows[0]) + if cols > 6 { + cols = 6 + } + hdr := make([]string, cols) + for i := 0; i < cols; i++ { + hdr[i] = SanitizeSchemaPlainField(rows[0][i], 80) + if hdr[i] == "" { + hdr[i] = fmt.Sprintf("Col %d", i+1) + } + } + var dataRows [][]string + for _, r := range rows[1:] { + if len(dataRows) >= maxRows { + break + } + out := make([]string, cols) + nonEmpty := false + for c := 0; c < cols; c++ { + if c < len(r) { + out[c] = SanitizeSchemaPlainField(r[c], 140) + } + if out[c] == "" { + out[c] = "-" + } else { + nonEmpty = true + } + } + if nonEmpty { + dataRows = append(dataRows, out) + } + } + if len(dataRows) == 0 { + return "", nil + } + return formatDeclarativeGFMTable(hdr, dataRows), dataRows +} + +// ── #315 CISA KEV (JSON / CSV / HTML) ──────────────────────────────────────────────────────────── + +func wave3SecCVEFilterParam(origURL string) string { + u, err := url.Parse(origURL) + if err != nil { + return "" + } + for k, vals := range u.Query() { + if strings.EqualFold(k, "cve") && len(vals) > 0 { + cand := strings.ToUpper(strings.TrimSpace(vals[0])) + if isValidCVEIDGo(cand) { + return cand + } + } + } + return "" +} + +func wave3SecFormatCISAKEVJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + obj, ok := parsed.(map[string]any) + if !ok || wave3SecIsGenericJSONError(obj) { + return nil, false + } + vulns, okV := obj["vulnerabilities"].([]any) + if !okV || len(vulns) == 0 { + return nil, false + } + title := wave3SecFirstNonEmpty(wave3SecPlain(obj["title"], 180), "CISA Known Exploited Vulnerabilities (KEV) Catalog") + ver := wave3SecPlain(obj["catalogVersion"], 48) + released := wave3SecNormalizeDate(wave3SecStringVal(obj["dateReleased"])) + filterCVE := wave3SecCVEFilterParam(origURL) + + totalCount := len(vulns) + if c, okC := wave3SecFloatVal(obj["count"]); okC && int(c) > totalCount { + totalCount = int(c) + } + + var records []map[string]any + var rows [][]string + matchedTotal := 0 + for _, rawV := range vulns { + vm, okM := rawV.(map[string]any) + if !okM { + continue + } + cveID := strings.ToUpper(wave3SecPlain(vm["cveID"], 32)) + if cveID == "" { + continue + } + if filterCVE != "" && !strings.EqualFold(cveID, filterCVE) { + continue + } + matchedTotal++ + if len(records) >= wave3SecMaxRecords { + continue + } + vendor := wave3SecPlain(vm["vendorProject"], 80) + product := wave3SecPlain(vm["product"], 80) + vulnName := wave3SecPlain(vm["vulnerabilityName"], 160) + dateAdded := wave3SecNormalizeDate(wave3SecStringVal(vm["dateAdded"])) + dueDate := wave3SecNormalizeDate(wave3SecStringVal(vm["dueDate"])) + ransomware := wave3SecPlain(vm["knownRansomwareCampaignUse"], 24) + shortDesc := wave3SecPlain(vm["shortDescription"], 400) + reqAction := wave3SecPlain(vm["requiredAction"], 300) + + rec := map[string]any{ + "cveID": cveID, + "vendorProject": vendor, + "product": product, + "name": vulnName, + "dateAdded": dateAdded, + "dueDate": dueDate, + } + if ransomware != "" { + rec["knownRansomwareCampaignUse"] = ransomware + } + if shortDesc != "" { + rec["shortDescription"] = shortDesc + } + if reqAction != "" { + rec["requiredAction"] = reqAction + } + records = append(records, rec) + rows = append(rows, []string{ + "`" + cveID + "`", + wave3SecFirstNonEmpty(vendor, "-"), + wave3SecFirstNonEmpty(product, "-"), + wave3SecFirstNonEmpty(dateAdded, "-"), + wave3SecFirstNonEmpty(dueDate, "-"), + wave3SecFirstNonEmpty(ransomware, "-"), + }) + } + if len(records) == 0 { + if filterCVE != "" { + missTitle := fmt.Sprintf("CISA KEV — %s", filterCVE) + var missMD strings.Builder + missMD.WriteString("# " + escapeDeclMarkdownBrackets(missTitle) + "\n\n") + if ver != "" { + missMD.WriteString("- **Catalog Version**: `" + ver + "`\n") + } + if released != "" { + missMD.WriteString("- **Date Released**: " + released + "\n") + } + missMD.WriteString(fmt.Sprintf("- **Total Catalog Entries**: %d\n", totalCount)) + missMD.WriteString("- **Returned**: 0\n\n") + missMD.WriteString("No matching KEV entry found for " + filterCVE + ".") + return &DeclarativeFormattedDoc{ + Title: missTitle, + PublishedTime: released, + Markdown: missMD.String(), + Records: []map[string]any{}, + Total: wave3SecIntPtr(0), + Returned: wave3SecIntPtr(0), + Truncated: wave3SecBoolPtr(false), + }, true + } + return nil, false + } + + effectiveTotal := totalCount + if filterCVE != "" { + effectiveTotal = matchedTotal + title = fmt.Sprintf("CISA KEV — %s", filterCVE) + } + + var md strings.Builder + md.WriteString("# " + escapeDeclMarkdownBrackets(title) + "\n\n") + if ver != "" { + md.WriteString("- **Catalog Version**: `" + ver + "`\n") + } + if released != "" { + md.WriteString("- **Date Released**: " + released + "\n") + } + md.WriteString(fmt.Sprintf("- **Total Catalog Entries**: %d\n", effectiveTotal)) + md.WriteString(fmt.Sprintf("- **Returned**: %d\n\n", len(records))) + md.WriteString("## Known Exploited Vulnerabilities\n\n") + md.WriteString(formatDeclarativeGFMTable([]string{"CVE", "Vendor", "Product", "Date Added", "Due Date", "Ransomware"}, rows)) + + trunc := effectiveTotal > len(records) + nextCur := "" + if trunc { + nextCur = strconv.Itoa(len(records)) + } + return &DeclarativeFormattedDoc{ + Title: title, + PublishedTime: released, + Markdown: md.String(), + Records: records, + Total: wave3SecIntPtr(effectiveTotal), + Returned: wave3SecIntPtr(len(records)), + Truncated: wave3SecBoolPtr(trunc), + NextCursor: nextCur, + }, true +} + +func wave3SecFormatCISAKEVCSV(rawBody, origURL string) (*DeclarativeFormattedDoc, bool) { + lines := strings.Split(rawBody, "\n") + if len(lines) < 2 { + return nil, false + } + hdrLine := strings.TrimSpace(lines[0]) + if !strings.Contains(strings.ToLower(hdrLine), "cveid") || !strings.Contains(strings.ToLower(hdrLine), "vendorproject") { + return nil, false + } + r := csv.NewReader(strings.NewReader(rawBody)) + r.ReuseRecord = true + headers, err := r.Read() + if err != nil || len(headers) < 4 { + return nil, false + } + colIdx := make(map[string]int, len(headers)) + for i, h := range headers { + colIdx[strings.ToLower(strings.TrimSpace(h))] = i + } + getCol := func(rec []string, name string) string { + idx, ok := colIdx[name] + if !ok || idx >= len(rec) { + return "" + } + return SanitizeSchemaPlainField(rec[idx], 240) + } + + filterCVE := wave3SecCVEFilterParam(origURL) + var records []map[string]any + var rows [][]string + totalMatched := 0 + catalogTotal := 0 + for { + rec, err := r.Read() + if err == io.EOF { + break + } + if err != nil { + break + } + cveID := strings.ToUpper(getCol(rec, "cveid")) + if !isValidCVEIDGo(cveID) { + continue + } + catalogTotal++ + if filterCVE != "" && !strings.EqualFold(cveID, filterCVE) { + continue + } + totalMatched++ + if len(records) >= wave3SecMaxRecords { + continue + } + vendor := getCol(rec, "vendorproject") + product := getCol(rec, "product") + dateAdded := wave3SecNormalizeDate(getCol(rec, "dateadded")) + dueDate := wave3SecNormalizeDate(getCol(rec, "duedate")) + ransomware := getCol(rec, "knownransomwarecampaignuse") + records = append(records, map[string]any{ + "cveID": cveID, + "vendorProject": vendor, + "product": product, + "name": getCol(rec, "vulnerabilityname"), + "dateAdded": dateAdded, + "dueDate": dueDate, + }) + rows = append(rows, []string{ + "`" + cveID + "`", + wave3SecFirstNonEmpty(vendor, "-"), + wave3SecFirstNonEmpty(product, "-"), + wave3SecFirstNonEmpty(dateAdded, "-"), + wave3SecFirstNonEmpty(dueDate, "-"), + wave3SecFirstNonEmpty(ransomware, "-"), + }) + } + if len(records) == 0 { + if filterCVE != "" && catalogTotal > 0 { + missTitle := fmt.Sprintf("CISA KEV — %s", filterCVE) + missMD := fmt.Sprintf("# %s\n\n- **Total Catalog Entries**: %d\n- **Returned**: 0\n\nNo matching KEV entry found for %s.", + escapeDeclMarkdownBrackets(missTitle), catalogTotal, filterCVE) + return &DeclarativeFormattedDoc{ + Title: missTitle, + Markdown: missMD, + Records: []map[string]any{}, + Total: wave3SecIntPtr(0), + Returned: wave3SecIntPtr(0), + Truncated: wave3SecBoolPtr(false), + }, true + } + return nil, false + } + title := "CISA Known Exploited Vulnerabilities (KEV) Catalog (CSV)" + if filterCVE != "" { + title = fmt.Sprintf("CISA KEV — %s", filterCVE) + } + var md strings.Builder + md.WriteString("# " + escapeDeclMarkdownBrackets(title) + "\n\n") + md.WriteString(fmt.Sprintf("- **Total Matching Entries**: %d\n- **Returned**: %d\n\n", totalMatched, len(records))) + md.WriteString(formatDeclarativeGFMTable([]string{"CVE", "Vendor", "Product", "Date Added", "Due Date", "Ransomware"}, rows)) + trunc := totalMatched > len(records) + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: md.String(), + Records: records, + Total: wave3SecIntPtr(totalMatched), + Returned: wave3SecIntPtr(len(records)), + Truncated: wave3SecBoolPtr(trunc), + }, true +} + +func wave3SecExtractCISAKEVHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + headProbe := rawHTML + if len(headProbe) > 131_072 { + headProbe = truncateUTF8SafeFullDocGo(headProbe, 131_072) + } + slimHTML := stripScriptsAndStylesDeclHTML(rawHTML) + if len(slimHTML) > wave3SecMaxHTMLBytes { + slimHTML = truncateUTF8SafeFullDocGo(slimHTML, wave3SecMaxHTMLBytes) + } + + h1 := "" + if h1Inner, okH1 := findElementInnerLinearDeclHTML(slimHTML, "h1", nil, 0); okH1 { + h1 = SanitizeSchemaPlainField(wave3SecCleanText(h1Inner), 240) + if wave3SecIsGenericTitle(h1) { + h1 = "" + } + } + ogTitle := SanitizeSchemaPlainField(extractMetaContentDeclHTML(headProbe, "og:title"), 240) + if wave3SecIsGenericTitle(ogTitle) { + ogTitle = "" + } + desc := wave3SecExtractMetaDesc(headProbe) + mainDoc := ExtractHTMLDocumentFull(slimHTML, FullExtractOptions{ + BaseURL: baseURL, + OnlyMainContent: true, + IncludeImages: false, + SkipUniversalExtractors: true, + SkipPlainText: true, + }) + mainTitle := SanitizeSchemaPlainField(mainDoc.Title, 240) + if wave3SecIsGenericTitle(mainTitle) { + mainTitle = "" + } + rawTitle := SanitizeSchemaPlainField(extractTitleLinearQuick(headProbe), 240) + if wave3SecIsGenericTitle(rawTitle) { + rawTitle = "" + } + title := wave3SecFirstNonEmpty(h1, ogTitle, mainTitle, rawTitle, "Known Exploited Vulnerabilities Catalog") + + bodyMD := strings.TrimSpace(mainDoc.Markdown) + if bodyMD == "" && desc == "" { + return nil + } + var links []string + seen := make(map[string]bool) + for _, l := range mainDoc.Links { + if strings.Contains(l, "known_exploited_vulnerabilities") || strings.Contains(l, "cisa.gov") { + wave3SecAddLink(&links, seen, l, baseURL) + } + } + for _, l := range mainDoc.Links { + wave3SecAddLink(&links, seen, l, baseURL) + if len(links) >= 20 { + break + } + } + var md strings.Builder + md.WriteString("# " + escapeDeclMarkdownBrackets(title) + "\n\n") + if desc != "" { + md.WriteString("> " + desc + "\n\n") + } + if bodyMD != "" { + md.WriteString(bodyMD) + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: md.String(), + Links: links, + } +} + +// ── #316 FIRST EPSS (JSON) ─────────────────────────────────────────────────────────────────────── + +func wave3SecFormatFirstEPSSJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + obj, ok := parsed.(map[string]any) + if !ok || wave3SecIsGenericJSONError(obj) { + return nil, false + } + if st := wave3SecPlain(obj["status"], 32); st != "" && !strings.EqualFold(st, "OK") { + return nil, false + } + dataArr, okD := obj["data"].([]any) + if !okD || len(dataArr) == 0 { + return nil, false + } + + total := len(dataArr) + if t, okT := wave3SecFloatVal(obj["total"]); okT && int(t) > total { + total = int(t) + } + + var records []map[string]any + var rows [][]string + firstDate := "" + firstCVE := "" + for _, rawItem := range dataArr { + if len(records) >= wave3SecMaxRecords { + break + } + im, okM := rawItem.(map[string]any) + if !okM { + continue + } + cve := strings.ToUpper(wave3SecPlain(im["cve"], 32)) + if cve == "" { + continue + } + epssVal, okE := wave3SecFloatVal(im["epss"]) + pctVal, okP := wave3SecFloatVal(im["percentile"]) + dateStr := wave3SecNormalizeDate(wave3SecStringVal(im["date"])) + if firstDate == "" { + firstDate = dateStr + } + if firstCVE == "" { + firstCVE = cve + } + epssDisp := "-" + if okE { + epssDisp = fmt.Sprintf("%.5f (%.2f%%)", epssVal, epssVal*100) + } + pctDisp := "-" + if okP { + pctDisp = fmt.Sprintf("%.2f%%", pctVal*100) + } + rec := map[string]any{ + "cve": cve, + "date": dateStr, + } + if okE { + rec["epss"] = epssVal + } + if okP { + rec["percentile"] = pctVal + } + records = append(records, rec) + rows = append(rows, []string{ + "`" + cve + "`", + epssDisp, + pctDisp, + wave3SecFirstNonEmpty(dateStr, "-"), + }) + } + if len(records) == 0 { + return nil, false + } + + title := "FIRST EPSS Exploit Prediction Scores" + if len(records) == 1 && firstCVE != "" { + title = fmt.Sprintf("FIRST EPSS — %s", firstCVE) + } + var md strings.Builder + md.WriteString("# " + escapeDeclMarkdownBrackets(title) + "\n\n") + if modelVer := wave3SecPlain(obj["model_version"], 48); modelVer != "" { + md.WriteString("- **Model Version**: `" + modelVer + "`\n") + } + if firstDate != "" { + md.WriteString("- **Score Date**: " + firstDate + "\n") + } + md.WriteString("\n") + md.WriteString(formatDeclarativeGFMTable([]string{"CVE", "EPSS Score", "Percentile", "Date"}, rows)) + + trunc := total > len(records) + return &DeclarativeFormattedDoc{ + Title: title, + PublishedTime: firstDate, + Markdown: md.String(), + Records: records, + Total: wave3SecIntPtr(total), + Returned: wave3SecIntPtr(len(records)), + Truncated: wave3SecBoolPtr(trunc), + }, true +} + +// ── #317 MITRE ATT&CK (STIX Index JSON / Linear Prefix STIX Scanner / HTML) ────────────────────── + +func wave3SecFormatMitreAttackIndexJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + obj, ok := parsed.(map[string]any) + if !ok || wave3SecIsGenericJSONError(obj) { + return nil, false + } + cols, okC := obj["collections"].([]any) + if !okC || len(cols) == 0 { + return nil, false + } + title := wave3SecFirstNonEmpty(wave3SecPlain(obj["name"], 180), "MITRE ATT&CK STIX Collections Index") + var records []map[string]any + var rows [][]string + var links []string + seen := make(map[string]bool) + + for _, rawCol := range cols { + if len(records) >= wave3SecMaxRecords { + break + } + cm, okM := rawCol.(map[string]any) + if !okM { + continue + } + name := wave3SecPlain(cm["name"], 120) + id := wave3SecPlain(cm["id"], 80) + if name == "" && id == "" { + continue + } + latestVer := "" + latestURL := "" + latestMod := "" + if vers, okV := cm["versions"].([]any); okV && len(vers) > 0 { + if vm, okVM := vers[0].(map[string]any); okVM { + latestVer = wave3SecPlain(vm["version"], 32) + latestURL = SanitizeSchemaHTTPSURL(wave3SecStringVal(vm["url"]), origURL) + latestMod = wave3SecNormalizeDate(wave3SecStringVal(vm["modified"])) + wave3SecAddLink(&links, seen, latestURL, origURL) + } + } + records = append(records, map[string]any{ + "id": id, + "name": name, + "latestVersion": latestVer, + "modified": latestMod, + "url": latestURL, + }) + rows = append(rows, []string{ + wave3SecFirstNonEmpty(name, id), + wave3SecFirstNonEmpty(latestVer, "-"), + wave3SecFirstNonEmpty(latestMod, "-"), + wave3SecFirstNonEmpty(latestURL, "-"), + }) + } + if len(records) == 0 { + return nil, false + } + var md strings.Builder + md.WriteString("# " + escapeDeclMarkdownBrackets(title) + "\n\n") + md.WriteString(formatDeclarativeGFMTable([]string{"Collection", "Latest Version", "Modified", "STIX URL"}, rows)) + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: md.String(), + Links: links, + Records: records, + Total: wave3SecIntPtr(len(cols)), + Returned: wave3SecIntPtr(len(records)), + }, true +} + +// wave3SecFormatMitreAttackSTIXBundle linearly scans a bounded (possibly Range-truncated) STIX 2.1 +// bundle prefix without failing on truncated EOF, extracting collection metadata + up to 25 complete objects. +func wave3SecSkipJSONValue(dec *json.Decoder) error { + tok, err := dec.Token() + if err != nil { + return err + } + delim, ok := tok.(json.Delim) + if !ok { + return nil + } + depth := 1 + for depth > 0 { + t, errT := dec.Token() + if errT != nil { + return errT + } + if d, isDelim := t.(json.Delim); isDelim { + switch d { + case '{', '[': + depth++ + case '}', ']': + depth-- + } + } + } + _ = delim + return nil +} + +func wave3SecStreamTruncatedMitreCollection(rawObjPrefix string) (colName, colVersion, colModified, colDesc string, records []map[string]any, rows [][]string, ok bool) { + dec := json.NewDecoder(strings.NewReader(rawObjPrefix)) + dec.UseNumber() + tok, err := dec.Token() + if err != nil { + return "", "", "", "", nil, nil, false + } + if delim, isDelim := tok.(json.Delim); !isDelim || delim != '{' { + return "", "", "", "", nil, nil, false + } + stixType := "" + for dec.More() { + kt, kErr := dec.Token() + if kErr != nil { + break + } + key, isKey := kt.(string) + if !isKey { + break + } + switch key { + case "type": + var s string + if dec.Decode(&s) != nil { + goto done + } + stixType = strings.TrimSpace(s) + case "name": + var s string + if dec.Decode(&s) != nil { + goto done + } + colName = wave3SecFirstNonEmpty(colName, wave3SecPlain(s, 160)) + case "x_mitre_version": + var v any + if dec.Decode(&v) != nil { + goto done + } + colVersion = wave3SecFirstNonEmpty(colVersion, wave3SecPlain(v, 32)) + case "modified": + var s string + if dec.Decode(&s) != nil { + goto done + } + colModified = wave3SecFirstNonEmpty(colModified, wave3SecNormalizeDate(s)) + case "description": + var s string + if dec.Decode(&s) != nil { + goto done + } + colDesc = wave3SecFirstNonEmpty(colDesc, wave3SecPlain(s, 500)) + case "x_mitre_contents": + arrTok, arrErr := dec.Token() + if arrErr != nil { + goto done + } + if ad, isAD := arrTok.(json.Delim); !isAD || ad != '[' { + goto done + } + for dec.More() && len(records) < wave3SecMaxRecords { + var entry map[string]any + if errE := dec.Decode(&entry); errE != nil { + break + } + objRef := wave3SecPlain(entry["object_ref"], 96) + objMod := wave3SecNormalizeDate(wave3SecStringVal(entry["object_modified"])) + if objRef == "" { + continue + } + refType := objRef + if dash := strings.Index(objRef, "--"); dash > 0 { + refType = objRef[:dash] + } + rec := map[string]any{ + "id": objRef, + "type": "x-mitre-content-ref", + "refType": refType, + "modified": objMod, + } + records = append(records, rec) + rows = append(rows, []string{ + wave3SecFirstNonEmpty(refType, "-"), + "x-mitre-content-ref", + objRef, + wave3SecFirstNonEmpty(objMod, "-"), + }) + } + goto done + default: + if wave3SecSkipJSONValue(dec) != nil { + goto done + } + } + } +done: + if stixType != "x-mitre-collection" && len(records) == 0 { + return "", "", "", "", nil, nil, false + } + return colName, colVersion, colModified, colDesc, records, rows, len(records) > 0 || colName != "" +} + +func wave3SecFormatMitreAttackSTIXBundle(rawBody, origURL string) (*DeclarativeFormattedDoc, bool) { + trimmed := strings.TrimSpace(rawBody) + if len(trimmed) < 20 || trimmed[0] != '{' { + return nil, false + } + if !strings.Contains(trimmed, `"objects"`) { + return nil, false + } + hasSTIXSignal := strings.Contains(trimmed, `"bundle"`) || + strings.Contains(trimmed, `"attack-pattern"`) || + strings.Contains(trimmed, `"x-mitre-"`) || + strings.Contains(trimmed, `"intrusion-set"`) || + strings.Contains(trimmed, `"malware"`) || + strings.Contains(trimmed, `"tool"`) || + strings.Contains(trimmed, `"course-of-action"`) + if !hasSTIXSignal { + return nil, false + } + + objKeyIdx := strings.Index(trimmed, `"objects"`) + if objKeyIdx < 0 { + return nil, false + } + arrStart := -1 + for i := objKeyIdx + len(`"objects"`); i < len(trimmed); i++ { + b := trimmed[i] + if b == '[' { + arrStart = i + break + } + if b != ':' && b != ' ' && b != '\t' && b != '\r' && b != '\n' { + return nil, false + } + } + if arrStart < 0 { + return nil, false + } + + colName := "" + colVersion := "" + colModified := "" + colDesc := "" + var records []map[string]any + var rows [][]string + var links []string + seenLinks := make(map[string]bool) + completeObjects := 0 + sawTruncated := false + reachedArrayEnd := false + + i := arrStart + 1 + n := len(trimmed) + firstObjStart := -1 + for i < n { + // Skip whitespace and commas between STIX objects + for i < n && (trimmed[i] == ' ' || trimmed[i] == '\t' || trimmed[i] == '\r' || trimmed[i] == '\n' || trimmed[i] == ',') { + i++ + } + if i >= n { + sawTruncated = true + break + } + if trimmed[i] == ']' { + reachedArrayEnd = true + break + } + if trimmed[i] != '{' { + sawTruncated = true + break + } + if len(records) >= wave3SecMaxRecords { + sawTruncated = true + break + } + + objStart := i + if firstObjStart < 0 { + firstObjStart = objStart + } + depth := 0 + inStr := false + escaped := false + objEnd := -1 + for i < n { + c := trimmed[i] + if inStr { + if escaped { + escaped = false + } else if c == '\\' { + escaped = true + } else if c == '"' { + inStr = false + } + } else { + switch c { + case '"': + inStr = true + case '{': + depth++ + case '}': + depth-- + if depth == 0 { + objEnd = i + 1 + } + } + } + i++ + if objEnd > 0 { + break + } + } + if objEnd < 0 { + sawTruncated = true + break + } + + var stixObj map[string]any + if err := json.Unmarshal([]byte(trimmed[objStart:objEnd]), &stixObj); err != nil || stixObj == nil { + continue + } + completeObjects++ + stixType := wave3SecPlain(stixObj["type"], 64) + if stixType == "x-mitre-collection" { + colName = wave3SecFirstNonEmpty(colName, wave3SecPlain(stixObj["name"], 160)) + colVersion = wave3SecFirstNonEmpty(colVersion, wave3SecPlain(stixObj["x_mitre_version"], 32)) + colModified = wave3SecFirstNonEmpty(colModified, wave3SecNormalizeDate(wave3SecStringVal(stixObj["modified"]))) + colDesc = wave3SecFirstNonEmpty(colDesc, wave3SecPlain(stixObj["description"], 500)) + continue + } + switch stixType { + case "attack-pattern", "intrusion-set", "malware", "tool", "course-of-action", "x-mitre-tactic", "campaign", "x-mitre-data-source": + default: + continue + } + + attackID := "" + if refs, okR := stixObj["external_references"].([]any); okR { + for _, rr := range refs { + rm, okRM := rr.(map[string]any) + if !okRM { + continue + } + src := wave3SecPlain(rm["source_name"], 48) + extID := wave3SecPlain(rm["external_id"], 48) + extURL := SanitizeSchemaHTTPSURL(wave3SecStringVal(rm["url"]), origURL) + if extURL != "" && len(links) < 20 { + wave3SecAddLink(&links, seenLinks, extURL, origURL) + } + if attackID == "" && extID != "" && (strings.Contains(strings.ToLower(src), "mitre") || src == "") { + attackID = extID + } + } + } + + name := wave3SecPlain(stixObj["name"], 160) + stixID := wave3SecPlain(stixObj["id"], 80) + desc := wave3SecPlain(stixObj["description"], 260) + var platforms []string + if pArr, okP := stixObj["x_mitre_platforms"].([]any); okP { + for _, p := range pArr { + if ps := wave3SecPlain(p, 48); ps != "" { + platforms = append(platforms, ps) + } + } + } + rec := map[string]any{ + "id": stixID, + "type": stixType, + "name": name, + "mitreId": attackID, + } + if len(platforms) > 0 { + rec["platforms"] = platforms + } + if desc != "" { + rec["description"] = desc + } + records = append(records, rec) + rows = append(rows, []string{ + wave3SecFirstNonEmpty(attackID, "-"), + stixType, + wave3SecFirstNonEmpty(name, stixID), + wave3SecFirstNonEmpty(strings.Join(platforms, ", "), "-"), + }) + } + + if completeObjects == 0 && firstObjStart >= 0 && firstObjStart < len(trimmed) { + if sName, sVer, sMod, sDesc, sRecs, sRows, sOK := wave3SecStreamTruncatedMitreCollection(trimmed[firstObjStart:]); sOK { + colName = wave3SecFirstNonEmpty(colName, sName) + colVersion = wave3SecFirstNonEmpty(colVersion, sVer) + colModified = wave3SecFirstNonEmpty(colModified, sMod) + colDesc = wave3SecFirstNonEmpty(colDesc, sDesc) + records = append(records, sRecs...) + rows = append(rows, sRows...) + completeObjects = 1 + sawTruncated = true + } + } + + if completeObjects == 0 { + return nil, false + } + if len(records) == 0 && colName != "" { + records = append(records, map[string]any{ + "type": "x-mitre-collection", + "name": colName, + "version": colVersion, + }) + } + if len(records) == 0 { + return nil, false + } + + title := wave3SecFirstNonEmpty(colName, "MITRE ATT&CK STIX 2.1 Bundle") + if colVersion != "" { + title = fmt.Sprintf("%s (v%s)", title, colVersion) + } + var md strings.Builder + md.WriteString("# " + escapeDeclMarkdownBrackets(title) + "\n\n") + if colDesc != "" { + md.WriteString("> " + colDesc + "\n\n") + } + if colVersion != "" { + md.WriteString("- **ATT&CK Version**: `" + colVersion + "`\n") + } + if colModified != "" { + md.WriteString("- **Modified**: " + colModified + "\n") + } + md.WriteString(fmt.Sprintf("- **Returned Objects**: %d", len(records))) + if sawTruncated || !reachedArrayEnd { + md.WriteString(" (bounded STIX prefix scan)") + } + md.WriteString("\n\n") + if len(rows) > 0 { + md.WriteString(formatDeclarativeGFMTable([]string{"ATT&CK ID", "Type", "Name", "Platforms"}, rows)) + } + + trunc := sawTruncated || !reachedArrayEnd + return &DeclarativeFormattedDoc{ + Title: title, + Description: colDesc, + PublishedTime: colModified, + Markdown: md.String(), + Links: links, + Records: records, + Total: wave3SecIntPtr(len(records)), + Returned: wave3SecIntPtr(len(records)), + Truncated: wave3SecBoolPtr(trunc), + }, true +} + +func wave3SecExtractMitreAttackHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + doc := ParseHTMLDoc(rawHTML, wave3SecMaxHTMLBytes) + title := wave3SecExtractTitle(doc, rawHTML) + if title == "" { + return nil + } + desc := wave3SecExtractMetaDesc(rawHTML) + var bullets []string + if doc != nil { + for _, cardNode := range doc.Select(".card-data", 12) { + if c := SanitizeSchemaPlainField(wave3SecCleanText(cardNode.Text()), 180); c != "" { + bullets = append(bullets, "- "+c) + } + } + } + mainDoc := ExtractHTMLDocumentFull(rawHTML, FullExtractOptions{ + BaseURL: baseURL, + OnlyMainContent: true, + IncludeImages: false, + SkipUniversalExtractors: true, + SkipPlainText: true, + }) + bodyMD := strings.TrimSpace(mainDoc.Markdown) + if bodyMD == "" && len(bullets) == 0 { + return nil + } + var links []string + seen := make(map[string]bool) + for _, l := range mainDoc.Links { + wave3SecAddLink(&links, seen, l, baseURL) + if len(links) >= 20 { + break + } + } + var md strings.Builder + md.WriteString("# " + escapeDeclMarkdownBrackets(title) + "\n\n") + if desc != "" { + md.WriteString("> " + desc + "\n\n") + } + if len(bullets) > 0 { + md.WriteString(strings.Join(bullets, "\n") + "\n\n") + } + if bodyMD != "" { + md.WriteString(bodyMD) + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: md.String(), + Links: links, + } +} + +// ── #318 MITRE CWE & CAPEC (JSON + XHTML) ──────────────────────────────────────────────────────── + +func wave3SecFormatMitreCWEJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + if arr, isArr := parsed.([]any); isArr { + if len(arr) == 0 { + return nil, false + } + var records []map[string]any + var rows [][]string + for _, it := range arr { + if len(records) >= wave3SecMaxRecords { + break + } + m, ok := it.(map[string]any) + if !ok { + continue + } + id := wave3SecPlain(m["ID"], 32) + typ := wave3SecPlain(m["Type"], 64) + name := wave3SecPlain(m["Name"], 160) + if id == "" { + continue + } + records = append(records, map[string]any{ + "id": "CWE-" + id, + "type": typ, + "name": name, + }) + rows = append(rows, []string{"`CWE-" + id + "`", wave3SecFirstNonEmpty(typ, "-"), wave3SecFirstNonEmpty(name, "-")}) + } + if len(records) == 0 { + return nil, false + } + title := fmt.Sprintf("MITRE %s", wave3SecStringVal(records[0]["id"])) + var md strings.Builder + md.WriteString("# " + title + "\n\n") + md.WriteString(formatDeclarativeGFMTable([]string{"ID", "Type", "Name"}, rows)) + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: md.String(), + Records: records, + Total: wave3SecIntPtr(len(arr)), + Returned: wave3SecIntPtr(len(records)), + }, true + } + + obj, ok := parsed.(map[string]any) + if !ok || wave3SecIsGenericJSONError(obj) { + return nil, false + } + var items []any + kindLabel := "CWE Weakness" + for _, key := range []string{"Weaknesses", "Categories", "Views"} { + if arr, okA := obj[key].([]any); okA && len(arr) > 0 { + items = arr + if key == "Categories" { + kindLabel = "CWE Category" + } else if key == "Views" { + kindLabel = "CWE View" + } + break + } + } + if len(items) == 0 { + return nil, false + } + first, okF := items[0].(map[string]any) + if !okF { + return nil, false + } + cweID := wave3SecPlain(first["ID"], 32) + name := wave3SecFirstNonEmpty(wave3SecPlain(first["Name"], 200), "Unknown Weakness") + if cweID == "" { + return nil, false + } + cweCode := "CWE-" + cweID + title := fmt.Sprintf("%s: %s", cweCode, name) + desc := wave3SecPlain(first["Description"], 1600) + extDesc := wave3SecPlain(first["ExtendedDescription"], 1600) + abstraction := wave3SecPlain(first["Abstraction"], 48) + status := wave3SecPlain(first["Status"], 48) + likelihood := wave3SecPlain(first["LikelihoodOfExploit"], 48) + + var md strings.Builder + md.WriteString("# " + escapeDeclMarkdownBrackets(title) + "\n\n") + md.WriteString("- **Type**: " + kindLabel + "\n") + if abstraction != "" { + md.WriteString("- **Abstraction**: " + abstraction + "\n") + } + if status != "" { + md.WriteString("- **Status**: " + status + "\n") + } + if likelihood != "" { + md.WriteString("- **Likelihood of Exploit**: " + likelihood + "\n") + } + if desc != "" { + md.WriteString("\n## Description\n\n" + desc + "\n") + } + if extDesc != "" { + md.WriteString("\n## Extended Description\n\n" + extDesc + "\n") + } + if mitArr, okM := first["PotentialMitigations"].([]any); okM && len(mitArr) > 0 { + var mRows [][]string + for _, rm := range mitArr { + if len(mRows) >= 12 { + break + } + mm, okMM := rm.(map[string]any) + if !okMM { + continue + } + phase := "-" + if ps, okPS := mm["Phase"].([]any); okPS && len(ps) > 0 { + var pList []string + for _, p := range ps { + if s := wave3SecPlain(p, 48); s != "" { + pList = append(pList, s) + } + } + if len(pList) > 0 { + phase = strings.Join(pList, ", ") + } + } + mDesc := wave3SecPlain(mm["Description"], 240) + if mDesc != "" { + mRows = append(mRows, []string{phase, mDesc}) + } + } + if len(mRows) > 0 { + md.WriteString("\n## Potential Mitigations\n\n" + formatDeclarativeGFMTable([]string{"Phase", "Mitigation"}, mRows)) + } + } + + rec := map[string]any{ + "id": cweCode, + "name": name, + "abstraction": abstraction, + "status": status, + } + if likelihood != "" { + rec["likelihoodOfExploit"] = likelihood + } + cweURL := fmt.Sprintf("https://cwe.mitre.org/data/definitions/%s.html", cweID) + return &DeclarativeFormattedDoc{ + Title: title, + Description: SanitizeSchemaPlainField(desc, 300), + Markdown: md.String(), + Links: []string{cweURL}, + Records: []map[string]any{rec}, + Total: wave3SecIntPtr(1), + Returned: wave3SecIntPtr(1), + }, true +} + +func wave3SecExtractMitreCWECAPECHTML(rawHTML, probeLower, baseURL, urlLower, extractorID string) *DeclarativePostFetchResult { + doc := ParseHTMLDoc(rawHTML, wave3SecMaxHTMLBytes) + title := wave3SecExtractTitle(doc, rawHTML) + if title == "" { + return nil + } + desc := "" + var sectionBlocks []string + if doc != nil { + for _, sid := range []string{"Description", "Extended_Description", "Execution_Flow", "Common_Consequences", "Potential_Mitigations", "Mitigations", "Related_Weaknesses", "Observed_Examples"} { + node := doc.First("#" + sid) + if node == nil { + continue + } + frag := node.HTML() + secMD := wave3SecFragToMD(frag, baseURL) + if secMD != "" { + heading := strings.ReplaceAll(sid, "_", " ") + sectionBlocks = append(sectionBlocks, "## "+heading+"\n\n"+secMD) + if sid == "Description" && desc == "" { + desc = SanitizeSchemaPlainField(wave3SecCleanText(node.Text()), 320) + } + } + } + } + if len(sectionBlocks) == 0 { + mainDoc := ExtractHTMLDocumentFull(rawHTML, FullExtractOptions{ + BaseURL: baseURL, + OnlyMainContent: true, + IncludeImages: false, + SkipUniversalExtractors: true, + SkipPlainText: true, + }) + if strings.TrimSpace(mainDoc.Markdown) == "" { + return nil + } + sectionBlocks = append(sectionBlocks, strings.TrimSpace(mainDoc.Markdown)) + } + var md strings.Builder + md.WriteString("# " + escapeDeclMarkdownBrackets(title) + "\n\n") + md.WriteString(strings.Join(sectionBlocks, "\n\n")) + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: md.String(), + } +} + +// ── #319 CVE.org (CVE JSON 5.x + Vue CSR Shell Guard) ──────────────────────────────────────────── + +func wave3SecFormatCVEOrgJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + obj, ok := parsed.(map[string]any) + if !ok || wave3SecIsGenericJSONError(obj) { + return nil, false + } + meta, okM := obj["cveMetadata"].(map[string]any) + if !okM { + return nil, false + } + cveID := strings.ToUpper(wave3SecPlain(meta["cveId"], 32)) + if !isValidCVEIDGo(cveID) { + return nil, false + } + state := wave3SecPlain(meta["state"], 32) + assigner := wave3SecPlain(meta["assignerShortName"], 64) + datePub := wave3SecNormalizeDate(wave3SecStringVal(meta["datePublished"])) + dateUpd := wave3SecNormalizeDate(wave3SecStringVal(meta["dateUpdated"])) + + containers, _ := obj["containers"].(map[string]any) + cna, _ := containers["cna"].(map[string]any) + cnaTitle := wave3SecPlain(cna["title"], 220) + + desc := "" + if descs, okD := cna["descriptions"].([]any); okD { + for _, rd := range descs { + dm, okDM := rd.(map[string]any) + if !okDM { + continue + } + val := wave3SecPlain(dm["value"], 2000) + if val == "" { + continue + } + lang := strings.ToLower(wave3SecPlain(dm["lang"], 16)) + if desc == "" || strings.HasPrefix(lang, "en") { + desc = val + if strings.HasPrefix(lang, "en") { + break + } + } + } + } + + var cvssScore, cvssSev, cvssVec string + extractMetrics := func(metricsAny any) { + mArr, okMA := metricsAny.([]any) + if !okMA { + return + } + for _, rm := range mArr { + mm, okMM := rm.(map[string]any) + if !okMM { + continue + } + for _, key := range []string{"cvssV4_0", "cvssV3_1", "cvssV3_0"} { + if cm, okCM := mm[key].(map[string]any); okCM && cvssScore == "" { + cvssScore = wave3SecPlain(cm["baseScore"], 16) + cvssSev = wave3SecPlain(cm["baseSeverity"], 24) + cvssVec = wave3SecPlain(cm["vectorString"], 128) + } + } + } + } + extractMetrics(cna["metrics"]) + if adpArr, okADP := containers["adp"].([]any); okADP && cvssScore == "" { + for _, ra := range adpArr { + if am, okAM := ra.(map[string]any); okAM { + extractMetrics(am["metrics"]) + } + } + } + + var cwes []string + if ptArr, okPT := cna["problemTypes"].([]any); okPT { + for _, rpt := range ptArr { + pm, okPM := rpt.(map[string]any) + if !okPM { + continue + } + if descs, okPD := pm["descriptions"].([]any); okPD { + for _, rd := range descs { + if dm, okDM := rd.(map[string]any); okDM { + cwe := wave3SecFirstNonEmpty(wave3SecPlain(dm["cweId"], 32), wave3SecPlain(dm["description"], 120)) + if cwe != "" && len(cwes) < 8 { + cwes = append(cwes, cwe) + } + } + } + } + } + } + + var affRows [][]string + if affArr, okAF := cna["affected"].([]any); okAF { + for _, raf := range affArr { + if len(affRows) >= 20 { + break + } + am, okAM := raf.(map[string]any) + if !okAM { + continue + } + vendor := wave3SecFirstNonEmpty(wave3SecPlain(am["vendor"], 80), "-") + product := wave3SecFirstNonEmpty(wave3SecPlain(am["product"], 80), "-") + var vers []string + if vArr, okVA := am["versions"].([]any); okVA { + for _, rv := range vArr { + if vm, okVM := rv.(map[string]any); okVM && len(vers) < 5 { + v := wave3SecPlain(vm["version"], 48) + st := wave3SecPlain(vm["status"], 24) + if v != "" { + if st != "" { + vers = append(vers, v+" ("+st+")") + } else { + vers = append(vers, v) + } + } + } + } + } + affRows = append(affRows, []string{vendor, product, wave3SecFirstNonEmpty(strings.Join(vers, ", "), "-")}) + } + } + + var links []string + seen := make(map[string]bool) + if refArr, okRF := cna["references"].([]any); okRF { + for _, rrf := range refArr { + if rm, okRM := rrf.(map[string]any); okRM && len(links) < 20 { + wave3SecAddLink(&links, seen, wave3SecStringVal(rm["url"]), origURL) + } + } + } + + title := cveID + if cnaTitle != "" { + title = fmt.Sprintf("%s — %s", cveID, cnaTitle) + } + var md strings.Builder + md.WriteString("# " + escapeDeclMarkdownBrackets(title) + "\n\n") + if state != "" { + md.WriteString("- **State**: `" + state + "`\n") + } + if assigner != "" { + md.WriteString("- **CNA**: " + assigner + "\n") + } + if datePub != "" { + md.WriteString("- **Published**: " + datePub + "\n") + } + if dateUpd != "" { + md.WriteString("- **Updated**: " + dateUpd + "\n") + } + if cvssScore != "" { + md.WriteString("- **CVSS**: **" + cvssScore + "**") + if cvssSev != "" { + md.WriteString(" (" + cvssSev + ")") + } + if cvssVec != "" { + md.WriteString(" — `" + cvssVec + "`") + } + md.WriteString("\n") + } + if len(cwes) > 0 { + md.WriteString("- **CWEs**: " + strings.Join(cwes, ", ") + "\n") + } + if desc != "" { + md.WriteString("\n## Description\n\n" + desc + "\n") + } + if len(affRows) > 0 { + md.WriteString("\n## Affected Products\n\n" + formatDeclarativeGFMTable([]string{"Vendor", "Product", "Versions"}, affRows)) + } + + rec := map[string]any{ + "cveId": cveID, + "state": state, + "assigner": assigner, + } + if cvssScore != "" { + rec["cvssScore"] = cvssScore + rec["cvssSeverity"] = cvssSev + } + return &DeclarativeFormattedDoc{ + Title: title, + Description: SanitizeSchemaPlainField(desc, 300), + PublishedTime: datePub, + Markdown: md.String(), + Links: links, + Records: []map[string]any{rec}, + Total: wave3SecIntPtr(1), + Returned: wave3SecIntPtr(1), + }, true +} + +func wave3SecExtractCVEOrgHTML(rawHTML, probeLower, baseURL, extractorID string) *DeclarativePostFetchResult { + // Strictly reject Vue CSR SPA shell (
+

) + if strings.Contains(probeLower, "
") || strings.Contains(probeLower, "
") { + return nil + } + if strings.Contains(probeLower, "

= n { + return "" + } + c := chunk[afterIdx] + if c != '>' && c != ' ' && c != '\t' && c != '\r' && c != '\n' && c != '/' { + pos = afterIdx + continue + } + gtRel := strings.IndexByte(chunk[afterIdx:], '>') + if gtRel < 0 { + return "" + } + openTagEnd := afterIdx + gtRel + 1 + if chunk[openTagEnd-2] == '/' { + pos = openTagEnd + continue + } + closeIdx := indexFoldASCIIExtract(chunk[openTagEnd:], closeNeedle) + if closeIdx < 0 { + return "" + } + inner := chunk[openTagEnd : openTagEnd+closeIdx] + trimmed := strings.TrimSpace(inner) + if strings.HasPrefix(trimmed, ""); endCD >= len("= n { + break + } + c := rawBody[afterIdx] + if c != '>' && c != ' ' && c != '\t' && c != '\r' && c != '\n' { + pos = afterIdx + continue + } + gtRel := strings.IndexByte(rawBody[afterIdx:], '>') + if gtRel < 0 { + break + } + itemStart := afterIdx + gtRel + 1 + closeRel := indexFoldASCIIExtract(rawBody[itemStart:], "') + if cgt < 0 { + pos = itemStart + closeRel + 7 + } else { + pos = itemStart + closeRel + cgt + 1 + } + + title := SanitizeSchemaPlainField(wave3SecCleanText(wave3SecExtractXMLTagLinear(body, "title")), 200) + link := "" + if rawLink := wave3SecExtractXMLTagLinear(body, "link"); rawLink != "" { + link = SanitizeSchemaHTTPSURL(strings.TrimSpace(rawLink), origURL) + wave3SecAddLink(&links, seen, link, origURL) + } + pubDate := SanitizeSchemaPlainField(wave3SecCleanText(wave3SecExtractXMLTagLinear(body, "pubdate")), 48) + descRaw := wave3SecExtractXMLTagLinear(body, "description") + if title == "" && link == "" { + continue + } + cveSrc := title + if len(descRaw) > 0 { + dProbe := descRaw + if len(dProbe) > 16384 { + dProbe = dProbe[:16384] + } + cveSrc = title + " " + dProbe + } + cves := wave3SecExtractCVEs(cveSrc, 10) + csafURL := "" + if extractCSAF && strings.Contains(descRaw, "cisagov/CSAF") { + csafProbe := descRaw + if len(csafProbe) > 32768 { + csafProbe = csafProbe[:32768] + } + if strings.IndexByte(csafProbe, '&') >= 0 { + csafProbe = stdhtml.UnescapeString(csafProbe) + } + if cm := wave3SecRxCSAFURL.FindString(csafProbe); cm != "" { + csafURL = SanitizeSchemaHTTPSURL(cm, origURL) + wave3SecAddLink(&links, seen, csafURL, origURL) + } + } + rec := map[string]any{ + "title": title, + "url": link, + "pubDate": pubDate, + } + if len(cves) > 0 { + rec["cves"] = cves + } + if csafURL != "" { + rec["csafUrl"] = csafURL + } + records = append(records, rec) + cvesCell := "-" + if len(cves) > 0 { + cvesCell = strings.Join(cves, ", ") + } + rows = append(rows, []string{ + wave3SecFirstNonEmpty(title, "-"), + wave3SecFirstNonEmpty(pubDate, "-"), + cvesCell, + wave3SecFirstNonEmpty(link, "-"), + }) + } + if len(records) == 0 { + return nil, false + } + hasMoreItems := pos < n && indexFoldASCIIExtract(rawBody[pos:], "= 0 + var md strings.Builder + md.WriteString("# " + escapeDeclMarkdownBrackets(chanTitle) + "\n\n") + md.WriteString(formatDeclarativeGFMTable([]string{"Title", "Published", "CVEs", "URL"}, rows)) + doc := &DeclarativeFormattedDoc{ + Title: chanTitle, + Markdown: md.String(), + Links: links, + Records: records, + Returned: wave3SecIntPtr(len(records)), + Truncated: wave3SecBoolPtr(hasMoreItems), + } + if !hasMoreItems { + doc.Total = wave3SecIntPtr(len(records)) + } else { + doc.NextCursor = strconv.Itoa(len(records)) + } + return doc, true +} + +func wave3SecExtractCISAAdvisoriesHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + doc := ParseHTMLDoc(rawHTML, wave3SecMaxHTMLBytes) + title := wave3SecExtractTitle(doc, rawHTML) + if title == "" { + return nil + } + desc := wave3SecExtractMetaDesc(rawHTML) + mainDoc := ExtractHTMLDocumentFull(rawHTML, FullExtractOptions{ + BaseURL: baseURL, + OnlyMainContent: true, + IncludeImages: false, + SkipUniversalExtractors: true, + SkipPlainText: true, + }) + bodyMD := strings.TrimSpace(mainDoc.Markdown) + if bodyMD == "" { + return nil + } + cves := wave3SecExtractCVEs(rawHTML, 15) + var links []string + seen := make(map[string]bool) + for _, l := range mainDoc.Links { + wave3SecAddLink(&links, seen, l, baseURL) + if len(links) >= 20 { + break + } + } + var md strings.Builder + md.WriteString("# " + escapeDeclMarkdownBrackets(title) + "\n\n") + if desc != "" { + md.WriteString("> " + desc + "\n\n") + } + if len(cves) > 0 { + md.WriteString("- **CVEs Referenced**: `" + strings.Join(cves, "`, `") + "`\n\n") + } + md.WriteString(bodyMD) + + var records []map[string]any + if len(cves) > 0 { + records = []map[string]any{{"title": title, "url": baseURL, "cves": cves}} + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: md.String(), + Links: links, + Records: records, + } +} + +// ── #321 Vendor CSAF 2.0 & Provider Metadata (JSON) ────────────────────────────────────────────── + +func wave3SecFormatVendorCSAFJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + obj, ok := parsed.(map[string]any) + if !ok || wave3SecIsGenericJSONError(obj) { + return nil, false + } + + // Case A: CSAF 2.0 provider-metadata.json + if _, hasCanon := obj["canonical_url"]; hasCanon || obj["distributions"] != nil || obj["metadata_version"] != nil { + canon := SanitizeSchemaHTTPSURL(wave3SecStringVal(obj["canonical_url"]), origURL) + metaVer := wave3SecPlain(obj["metadata_version"], 24) + role := wave3SecPlain(obj["role"], 48) + lastUpd := wave3SecNormalizeDate(wave3SecStringVal(obj["last_updated"])) + pubMap, _ := obj["publisher"].(map[string]any) + pubName := wave3SecPlain(pubMap["name"], 120) + pubNS := SanitizeSchemaHTTPSURL(wave3SecStringVal(pubMap["namespace"]), origURL) + contact := wave3SecPlain(pubMap["contact_details"], 200) + + var links []string + seen := make(map[string]bool) + wave3SecAddLink(&links, seen, canon, origURL) + wave3SecAddLink(&links, seen, pubNS, origURL) + + var records []map[string]any + var distRows [][]string + if distArr, okD := obj["distributions"].([]any); okD { + for _, rd := range distArr { + if len(records) >= wave3SecMaxRecords { + break + } + dm, okDM := rd.(map[string]any) + if !okDM { + continue + } + dirURL := SanitizeSchemaHTTPSURL(wave3SecStringVal(dm["directory_url"]), origURL) + wave3SecAddLink(&links, seen, dirURL, origURL) + rolieFeeds := 0 + if rolie, okR := dm["rolie"].(map[string]any); okR { + if feeds, okF := rolie["feeds"].([]any); okF { + rolieFeeds = len(feeds) + for _, rf := range feeds { + if fm, okFM := rf.(map[string]any); okFM { + wave3SecAddLink(&links, seen, wave3SecStringVal(fm["url"]), origURL) + } + } + } + } + records = append(records, map[string]any{ + "directoryUrl": dirURL, + "rolieFeeds": rolieFeeds, + }) + distRows = append(distRows, []string{ + wave3SecFirstNonEmpty(dirURL, "-"), + strconv.Itoa(rolieFeeds), + }) + } + } + if canon == "" && pubName == "" && len(records) == 0 { + return nil, false + } + title := "CSAF Provider Metadata" + if pubName != "" { + title = fmt.Sprintf("CSAF Provider Metadata — %s", pubName) + } + var md strings.Builder + md.WriteString("# " + escapeDeclMarkdownBrackets(title) + "\n\n") + if metaVer != "" { + md.WriteString("- **Metadata Version**: `" + metaVer + "`\n") + } + if role != "" { + md.WriteString("- **Role**: " + role + "\n") + } + if lastUpd != "" { + md.WriteString("- **Last Updated**: " + lastUpd + "\n") + } + if contact != "" { + md.WriteString("- **Contact**: " + contact + "\n") + } + if canon != "" { + md.WriteString("- **Canonical URL**: " + canon + "\n") + } + if len(distRows) > 0 { + md.WriteString("\n## Distributions\n\n" + formatDeclarativeGFMTable([]string{"Directory URL", "ROLIE Feeds"}, distRows)) + } + return &DeclarativeFormattedDoc{ + Title: title, + PublishedTime: lastUpd, + Markdown: md.String(), + Links: links, + Records: records, + Total: wave3SecIntPtr(len(records)), + Returned: wave3SecIntPtr(len(records)), + }, true + } + + // Case B: CSAF 2.0 Advisory Document + docMap, okDoc := obj["document"].(map[string]any) + if !okDoc { + return nil, false + } + csafVer := wave3SecPlain(docMap["csaf_version"], 24) + tracking, _ := docMap["tracking"].(map[string]any) + trackID := wave3SecPlain(tracking["id"], 80) + docTitle := wave3SecPlain(docMap["title"], 220) + if csafVer == "" && trackID == "" && docTitle == "" { + return nil, false + } + category := wave3SecPlain(docMap["category"], 64) + status := wave3SecPlain(tracking["status"], 32) + relDate := wave3SecNormalizeDate(wave3SecStringVal(tracking["current_release_date"])) + pubMap, _ := docMap["publisher"].(map[string]any) + pubName := wave3SecPlain(pubMap["name"], 120) + aggSevMap, _ := docMap["aggregate_severity"].(map[string]any) + aggSev := wave3SecPlain(aggSevMap["text"], 48) + + summaryText := "" + if notes, okN := docMap["notes"].([]any); okN { + for _, rn := range notes { + nm, okNM := rn.(map[string]any) + if !okNM { + continue + } + txt := wave3SecPlain(nm["text"], 1400) + if txt != "" { + summaryText = txt + break + } + } + } + + var links []string + seen := make(map[string]bool) + if refs, okR := docMap["references"].([]any); okR { + for _, rr := range refs { + if rm, okRM := rr.(map[string]any); okRM && len(links) < 20 { + wave3SecAddLink(&links, seen, wave3SecStringVal(rm["url"]), origURL) + } + } + } + + vulns, _ := obj["vulnerabilities"].([]any) + var records []map[string]any + var rows [][]string + for _, rv := range vulns { + if len(records) >= wave3SecMaxRecords { + break + } + vm, okVM := rv.(map[string]any) + if !okVM { + continue + } + cve := strings.ToUpper(wave3SecPlain(vm["cve"], 32)) + vTitle := wave3SecPlain(vm["title"], 160) + cweID := "" + if cm, okC := vm["cwe"].(map[string]any); okC { + cweID = wave3SecPlain(cm["id"], 32) + } + cvssScore := "" + if scores, okS := vm["scores"].([]any); okS { + for _, rs := range scores { + sm, okSM := rs.(map[string]any) + if !okSM { + continue + } + if v3, okV3 := sm["cvss_v3"].(map[string]any); okV3 && cvssScore == "" { + cvssScore = wave3SecPlain(v3["baseScore"], 16) + } + if v2, okV2 := sm["cvss_v2"].(map[string]any); okV2 && cvssScore == "" { + cvssScore = wave3SecPlain(v2["baseScore"], 16) + } + } + } + records = append(records, map[string]any{ + "cve": cve, + "title": vTitle, + "cwe": cweID, + "cvssScore": cvssScore, + }) + rows = append(rows, []string{ + wave3SecFirstNonEmpty(cve, "-"), + wave3SecFirstNonEmpty(cvssScore, "-"), + wave3SecFirstNonEmpty(cweID, "-"), + wave3SecFirstNonEmpty(vTitle, "-"), + }) + } + if len(records) == 0 && trackID != "" { + records = append(records, map[string]any{ + "trackingId": trackID, + "title": docTitle, + "publisher": pubName, + }) + } + + title := wave3SecFirstNonEmpty(docTitle, trackID, "CSAF 2.0 Security Advisory") + if trackID != "" && docTitle != "" && !strings.Contains(docTitle, trackID) { + title = fmt.Sprintf("%s — %s", trackID, docTitle) + } + var md strings.Builder + md.WriteString("# " + escapeDeclMarkdownBrackets(title) + "\n\n") + if pubName != "" { + md.WriteString("- **Publisher**: " + pubName + "\n") + } + if trackID != "" { + md.WriteString("- **Tracking ID**: `" + trackID + "`\n") + } + if csafVer != "" { + md.WriteString("- **CSAF Version**: `" + csafVer + "`\n") + } + if category != "" { + md.WriteString("- **Category**: `" + category + "`\n") + } + if status != "" { + md.WriteString("- **Status**: `" + status + "`\n") + } + if aggSev != "" { + md.WriteString("- **Aggregate Severity**: " + aggSev + "\n") + } + if relDate != "" { + md.WriteString("- **Release Date**: " + relDate + "\n") + } + if summaryText != "" { + md.WriteString("\n## Summary\n\n" + summaryText + "\n") + } + if len(rows) > 0 { + md.WriteString("\n## Vulnerabilities\n\n" + formatDeclarativeGFMTable([]string{"CVE", "CVSS", "CWE", "Title"}, rows)) + } + + totalVulns := len(vulns) + if totalVulns == 0 { + totalVulns = len(records) + } + return &DeclarativeFormattedDoc{ + Title: title, + Description: SanitizeSchemaPlainField(summaryText, 300), + PublishedTime: relDate, + Markdown: md.String(), + Links: links, + Records: records, + Total: wave3SecIntPtr(totalVulns), + Returned: wave3SecIntPtr(len(records)), + Truncated: wave3SecBoolPtr(totalVulns > len(records)), + }, true +} + +// ── #322 RFC 9116 security.txt (Text) ──────────────────────────────────────────────────────────── + +func wave3SecFormatSecurityTxt(rawBody, origURL string) (*DeclarativeFormattedDoc, bool) { + probe := rawBody + if len(probe) > 8192 { + probe = probe[:8192] + } + probeLower := asciiLowerExtractString(probe) + if strings.Contains(probeLower, " 0 { + expires = wave3SecNormalizeDate(fields["expires"][0]) + } + + var md strings.Builder + md.WriteString("# " + escapeDeclMarkdownBrackets(title) + "\n\n") + for _, k := range orderedKeys { + label := strings.ToUpper(k[:1]) + k[1:] + for _, v := range fields[k] { + md.WriteString("- **" + label + "**: " + v + "\n") + } + } + + rec := map[string]any{ + "host": host, + "contacts": contacts, + } + if expires != "" { + rec["expires"] = expires + } + if len(fields["canonical"]) > 0 { + rec["canonical"] = fields["canonical"] + } + if len(fields["policy"]) > 0 { + rec["policy"] = fields["policy"] + } + if len(fields["encryption"]) > 0 { + rec["encryption"] = fields["encryption"] + } + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: md.String(), + Links: links, + Records: []map[string]any{rec}, + Total: wave3SecIntPtr(1), + Returned: wave3SecIntPtr(1), + }, true +} + +// ── #323 Exploit-DB (Bounded CSV / RSS / HTML) ─────────────────────────────────────────────────── + +func wave3SecFormatExploitDBCSV(rawBody, origURL string) (*DeclarativeFormattedDoc, bool) { + firstNL := strings.IndexByte(rawBody, '\n') + if firstNL < 0 { + return nil, false + } + hdrLower := strings.ToLower(strings.TrimSpace(rawBody[:firstNL])) + if !strings.HasPrefix(hdrLower, "id,file,description,date_published") { + return nil, false + } + + // Drop trailing partial line from Range cut (or any unterminated last line) + safeBody := rawBody + if !strings.HasSuffix(safeBody, "\n") || len(safeBody) >= 2000000 { + if lastNL := strings.LastIndexByte(safeBody, '\n'); lastNL > firstNL { + safeBody = safeBody[:lastNL+1] + } + } + + r := csv.NewReader(strings.NewReader(safeBody)) + r.ReuseRecord = true + headers, err := r.Read() + if err != nil || len(headers) < 8 { + return nil, false + } + colIdx := make(map[string]int, len(headers)) + for i, h := range headers { + colIdx[strings.ToLower(strings.TrimSpace(h))] = i + } + getCol := func(rec []string, name string) string { + idx, ok := colIdx[name] + if !ok || idx >= len(rec) { + return "" + } + return SanitizeSchemaPlainField(rec[idx], 200) + } + + var records []map[string]any + var rows [][]string + totalParsed := 0 + for { + rec, err := r.Read() + if err == io.EOF { + break + } + if err != nil { + break + } + if len(rec) < 8 { + continue + } + edbID := getCol(rec, "id") + desc := getCol(rec, "description") + if edbID == "" || desc == "" { + continue + } + totalParsed++ + if len(records) >= wave3SecMaxRecords { + continue + } + pubDate := wave3SecNormalizeDate(getCol(rec, "date_published")) + author := getCol(rec, "author") + exType := getCol(rec, "type") + platform := getCol(rec, "platform") + codes := getCol(rec, "codes") + records = append(records, map[string]any{ + "id": edbID, + "description": desc, + "datePublished": pubDate, + "author": author, + "type": exType, + "platform": platform, + "codes": codes, + }) + rows = append(rows, []string{ + "`EDB-" + edbID + "`", + wave3SecFirstNonEmpty(pubDate, "-"), + wave3SecFirstNonEmpty(platform, "-"), + wave3SecFirstNonEmpty(exType, "-"), + wave3SecFirstNonEmpty(codes, "-"), + desc, + }) + } + if len(records) == 0 { + return nil, false + } + title := "Exploit-DB Exploits CSV Index" + trunc := totalParsed > len(records) || len(rawBody) >= 2000000 || !strings.HasSuffix(rawBody, "\n") + var md strings.Builder + md.WriteString("# " + title + "\n\n") + md.WriteString(fmt.Sprintf("- **Returned Exploits**: %d\n\n", len(records))) + md.WriteString(formatDeclarativeGFMTable([]string{"EDB-ID", "Published", "Platform", "Type", "Codes/CVEs", "Title"}, rows)) + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: md.String(), + Records: records, + Total: wave3SecIntPtr(totalParsed), + Returned: wave3SecIntPtr(len(records)), + Truncated: wave3SecBoolPtr(trunc), + }, true +} + +func wave3SecExtractExploitDBHTML(rawHTML, probeLower, baseURL, extractorID string) *DeclarativePostFetchResult { + rawTitle := extractTitleLinearQuick(rawHTML) + if strings.HasPrefix(strings.ToLower(strings.TrimSpace(rawTitle)), "exploit database - exploits") && + !strings.Contains(probeLower, "edb-id") && !strings.Contains(probeLower, "= 2 { + edbID = m[1] + } + cves := wave3SecExtractCVEs(rawHTML, 10) + mainDoc := ExtractHTMLDocumentFull(rawHTML, FullExtractOptions{ + BaseURL: baseURL, + OnlyMainContent: true, + IncludeImages: false, + SkipUniversalExtractors: true, + SkipPlainText: true, + }) + snippet := "" + if pm := wave3SecRxPreCode.FindStringSubmatch(rawHTML); len(pm) >= 2 { + rawCode := wave3SecFirstNonEmpty(pm[1], pm[2]) + cleanCode := strings.TrimSpace(stdhtml.UnescapeString(wave3SecRxHTMLTag.ReplaceAllString(rawCode, ""))) + if len(cleanCode) > wave3SecMaxSnippetByte { + cleanCode = truncateUTF8SafeFullDocGo(cleanCode, wave3SecMaxSnippetByte) + "\n..." + } + snippet = cleanCode + } + bodyMD := strings.TrimSpace(mainDoc.Markdown) + if bodyMD == "" && snippet == "" { + return nil + } + var md strings.Builder + md.WriteString("# " + escapeDeclMarkdownBrackets(title) + "\n\n") + if edbID != "" { + md.WriteString("- **EDB-ID**: `" + edbID + "`\n") + } + if len(cves) > 0 { + md.WriteString("- **CVEs**: `" + strings.Join(cves, "`, `") + "`\n") + } + md.WriteString("\n") + if bodyMD != "" { + md.WriteString(bodyMD + "\n\n") + } + if snippet != "" && !strings.Contains(bodyMD, snippet[:wave3SecMinInt(len(snippet), 64)]) { + md.WriteString("## Exploit Snippet\n\n```\n" + snippet + "\n```\n") + } + rec := map[string]any{"title": title, "url": baseURL} + if edbID != "" { + rec["edbId"] = edbID + } + if len(cves) > 0 { + rec["cves"] = cves + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: wave3SecExtractMetaDesc(rawHTML), + Markdown: md.String(), + Records: []map[string]any{rec}, + } +} + +func wave3SecMinInt(a, b int) int { + if a < b { + return a + } + return b +} + +// ── #324 Certificate Transparency (Cert Spotter + crt.sh JSON/HTML) ────────────────────────────── + +func wave3SecFormatCertTransparencyJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + if obj, isObj := parsed.(map[string]any); isObj { + if wave3SecIsGenericJSONError(obj) { + return nil, false + } + return nil, false + } + arr, ok := parsed.([]any) + if !ok || len(arr) == 0 { + return nil, false + } + + var records []map[string]any + var rows [][]string + for _, rawIt := range arr { + if len(records) >= wave3SecMaxRecords { + break + } + im, okM := rawIt.(map[string]any) + if !okM { + continue + } + id := wave3SecPlain(im["id"], 48) + notBefore := wave3SecNormalizeDate(wave3SecStringVal(im["not_before"])) + notAfter := wave3SecNormalizeDate(wave3SecStringVal(im["not_after"])) + + // Cert Spotter format vs crt.sh format + var dnsNames []string + if dArr, okD := im["dns_names"].([]any); okD { + for _, rd := range dArr { + if ds := wave3SecPlain(rd, 120); ds != "" && len(dnsNames) < 8 { + dnsNames = append(dnsNames, ds) + } + } + } + commonName := wave3SecPlain(im["common_name"], 120) + nameVal := wave3SecPlain(im["name_value"], 200) + if len(dnsNames) == 0 && nameVal != "" { + for _, part := range strings.Split(nameVal, "\n") { + if p := strings.TrimSpace(part); p != "" && len(dnsNames) < 8 { + dnsNames = append(dnsNames, p) + } + } + } + if len(dnsNames) == 0 && commonName != "" { + dnsNames = append(dnsNames, commonName) + } + if id == "" && len(dnsNames) == 0 { + continue + } + issuer := wave3SecPlain(im["issuer_name"], 140) + if issuer == "" { + if issMap, okIM := im["issuer"].(map[string]any); okIM { + issuer = wave3SecPlain(issMap["name"], 140) + } + } + certSHA := wave3SecPlain(im["cert_sha256"], 80) + serial := wave3SecPlain(im["serial_number"], 80) + revoked := "" + if rBool, okRB := im["revoked"].(bool); okRB { + if rBool { + revoked = "true" + } else { + revoked = "false" + } + } + rec := map[string]any{ + "id": id, + "dnsNames": dnsNames, + "notBefore": notBefore, + "notAfter": notAfter, + } + if issuer != "" { + rec["issuer"] = issuer + } + if certSHA != "" { + rec["certSha256"] = certSHA + } + if serial != "" { + rec["serialNumber"] = serial + } + if revoked != "" { + rec["revoked"] = revoked == "true" + } + records = append(records, rec) + rows = append(rows, []string{ + wave3SecFirstNonEmpty(id, "-"), + wave3SecFirstNonEmpty(strings.Join(dnsNames, ", "), "-"), + wave3SecFirstNonEmpty(notBefore, "-"), + wave3SecFirstNonEmpty(notAfter, "-"), + wave3SecFirstNonEmpty(issuer, "-"), + }) + } + if len(records) == 0 { + return nil, false + } + + title := "Certificate Transparency Log Issuances" + if u, err := url.Parse(origURL); err == nil { + if dom := wave3SecFirstNonEmpty(u.Query().Get("domain"), u.Query().Get("q")); dom != "" { + title = fmt.Sprintf("Certificate Transparency — %s", SanitizeSchemaPlainField(dom, 120)) + } + } + var md strings.Builder + md.WriteString("# " + escapeDeclMarkdownBrackets(title) + "\n\n") + md.WriteString(fmt.Sprintf("- **Total Issuances**: %d\n- **Returned**: %d\n\n", len(arr), len(records))) + md.WriteString(formatDeclarativeGFMTable([]string{"ID", "DNS Names", "Not Before", "Not After", "Issuer"}, rows)) + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: md.String(), + Records: records, + Total: wave3SecIntPtr(len(arr)), + Returned: wave3SecIntPtr(len(records)), + Truncated: wave3SecBoolPtr(len(arr) > len(records)), + }, true +} + +func wave3SecExtractCertTransparencyHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + lower := asciiLowerExtractString(rawHTML) + if strings.Contains(lower, "none found") || strings.Contains(lower, "no certificates found") { + return nil + } + doc := ParseHTMLDoc(rawHTML, wave3SecMaxHTMLBytes) + tblMD, rows := wave3SecExtractTableBlock(doc, "table", wave3SecMaxRecords) + if tblMD == "" || len(rows) == 0 { + return nil + } + title := wave3SecFirstNonEmpty(wave3SecExtractTitle(doc, rawHTML), "crt.sh Certificate Search") + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Markdown: "# " + escapeDeclMarkdownBrackets(title) + "\n\n" + tblMD, + Total: wave3SecIntPtr(len(rows)), + Returned: wave3SecIntPtr(len(rows)), + } +} + +// ── #325 RDAP (RFC 9083 + IANA Bootstrap JSON) ─────────────────────────────────────────────────── + +func wave3SecFormatRDAPBootstrapJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + obj, ok := parsed.(map[string]any) + if !ok || wave3SecIsGenericJSONError(obj) { + return nil, false + } + services, okS := obj["services"].([]any) + if !okS || len(services) == 0 { + return nil, false + } + title := wave3SecFirstNonEmpty(wave3SecPlain(obj["description"], 180), "IANA RDAP Bootstrap Registry") + pub := wave3SecNormalizeDate(wave3SecStringVal(obj["publication"])) + ver := wave3SecPlain(obj["version"], 24) + + var records []map[string]any + var rows [][]string + var links []string + seen := make(map[string]bool) + + for _, rs := range services { + if len(records) >= wave3SecMaxRecords { + break + } + pair, okP := rs.([]any) + if !okP || len(pair) < 2 { + continue + } + keysAny, _ := pair[0].([]any) + urlsAny, _ := pair[1].([]any) + var keys, urls []string + for _, k := range keysAny { + if ks := wave3SecPlain(k, 64); ks != "" && len(keys) < 10 { + keys = append(keys, ks) + } + } + for _, u := range urlsAny { + if us := SanitizeSchemaHTTPSURL(wave3SecStringVal(u), origURL); us != "" { + urls = append(urls, us) + if len(links) < 25 { + wave3SecAddLink(&links, seen, us, origURL) + } + } + } + if len(keys) == 0 || len(urls) == 0 { + continue + } + records = append(records, map[string]any{ + "prefixes": keys, + "rdapUrls": urls, + }) + rows = append(rows, []string{ + strings.Join(keys, ", "), + strings.Join(urls, ", "), + }) + } + if len(records) == 0 { + return nil, false + } + var md strings.Builder + md.WriteString("# " + escapeDeclMarkdownBrackets(title) + "\n\n") + if ver != "" { + md.WriteString("- **Bootstrap Version**: `" + ver + "`\n") + } + if pub != "" { + md.WriteString("- **Publication**: " + pub + "\n") + } + md.WriteString(fmt.Sprintf("- **Total Service Entries**: %d\n\n", len(services))) + md.WriteString(formatDeclarativeGFMTable([]string{"Keys / Prefixes", "RDAP Base URLs"}, rows)) + return &DeclarativeFormattedDoc{ + Title: title, + PublishedTime: pub, + Markdown: md.String(), + Links: links, + Records: records, + Total: wave3SecIntPtr(len(services)), + Returned: wave3SecIntPtr(len(records)), + Truncated: wave3SecBoolPtr(len(services) > len(records)), + }, true +} + +func wave3SecExtractVCardField(vcardAny any) (org, email string) { + outer, ok := vcardAny.([]any) + if !ok || len(outer) < 2 { + return "", "" + } + props, okP := outer[1].([]any) + if !okP { + return "", "" + } + for _, rp := range props { + prop, okPr := rp.([]any) + if !okPr || len(prop) < 4 { + continue + } + pname := strings.ToLower(wave3SecPlain(prop[0], 24)) + pval := wave3SecPlain(prop[3], 120) + if (pname == "fn" || pname == "org") && org == "" && pval != "" { + org = pval + } + if pname == "email" && email == "" && pval != "" { + email = pval + } + } + return org, email +} + +func wave3SecFormatRDAPJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + obj, ok := parsed.(map[string]any) + if !ok || wave3SecIsGenericJSONError(obj) { + return nil, false + } + if errCode, okEC := wave3SecFloatVal(obj["errorCode"]); okEC && errCode >= 400 { + return nil, false + } + objClass := strings.ToLower(wave3SecPlain(obj["objectClassName"], 48)) + switch objClass { + case "domain", "ip network", "autnum", "entity", "nameserver": + default: + if obj["rdapConformance"] == nil { + return nil, false + } + } + + handle := wave3SecPlain(obj["handle"], 80) + ldhName := wave3SecPlain(obj["ldhName"], 160) + name := wave3SecPlain(obj["name"], 160) + country := wave3SecPlain(obj["country"], 16) + startAddr := wave3SecPlain(obj["startAddress"], 64) + endAddr := wave3SecPlain(obj["endAddress"], 64) + startAut := wave3SecPlain(obj["startAutnum"], 24) + endAut := wave3SecPlain(obj["endAutnum"], 24) + port43 := wave3SecPlain(obj["port43"], 120) + + var statuses []string + if stArr, okS := obj["status"].([]any); okS { + for _, rs := range stArr { + if ss := wave3SecPlain(rs, 48); ss != "" { + statuses = append(statuses, ss) + } + } + } + + var events [][]string + if evArr, okE := obj["events"].([]any); okE { + for _, re := range evArr { + em, okEM := re.(map[string]any) + if !okEM { + continue + } + act := wave3SecPlain(em["eventAction"], 48) + dt := wave3SecNormalizeDate(wave3SecStringVal(em["eventDate"])) + if act != "" && dt != "" { + events = append(events, []string{act, dt}) + } + } + } + + var nameservers []string + if nsArr, okNS := obj["nameservers"].([]any); okNS { + for _, rns := range nsArr { + if nsm, okNSM := rns.(map[string]any); okNSM { + if n := wave3SecPlain(nsm["ldhName"], 120); n != "" { + nameservers = append(nameservers, n) + } + } + } + } + + var entityRows [][]string + if entArr, okEN := obj["entities"].([]any); okEN { + for _, ren := range entArr { + if len(entityRows) >= 15 { + break + } + enm, okENM := ren.(map[string]any) + if !okENM { + continue + } + eh := wave3SecPlain(enm["handle"], 64) + var roles []string + if rArr, okR := enm["roles"].([]any); okR { + for _, rr := range rArr { + if rs := wave3SecPlain(rr, 32); rs != "" { + roles = append(roles, rs) + } + } + } + org, email := wave3SecExtractVCardField(enm["vcardArray"]) + entityRows = append(entityRows, []string{ + wave3SecFirstNonEmpty(eh, "-"), + wave3SecFirstNonEmpty(strings.Join(roles, ", "), "-"), + wave3SecFirstNonEmpty(org, "-"), + wave3SecFirstNonEmpty(email, "-"), + }) + } + } + + subject := wave3SecFirstNonEmpty(ldhName, name, handle) + if startAut != "" { + subject = "AS" + startAut + if endAut != "" && endAut != startAut { + subject = fmt.Sprintf("AS%s–AS%s", startAut, endAut) + } + } + if subject == "" && startAddr != "" { + subject = startAddr + } + if subject == "" { + return nil, false + } + + title := fmt.Sprintf("RDAP (%s) — %s", wave3SecFirstNonEmpty(objClass, "object"), subject) + var md strings.Builder + md.WriteString("# " + escapeDeclMarkdownBrackets(title) + "\n\n") + if handle != "" { + md.WriteString("- **Handle**: `" + handle + "`\n") + } + if objClass != "" { + md.WriteString("- **Object Class**: `" + objClass + "`\n") + } + if startAddr != "" && endAddr != "" { + md.WriteString("- **IP Range**: `" + startAddr + " - " + endAddr + "`\n") + } + if name != "" && name != subject { + md.WriteString("- **Network / Name**: " + name + "\n") + } + if country != "" { + md.WriteString("- **Country**: `" + country + "`\n") + } + if len(statuses) > 0 { + md.WriteString("- **Status**: `" + strings.Join(statuses, "`, `") + "`\n") + } + if len(nameservers) > 0 { + md.WriteString("- **Nameservers**: `" + strings.Join(nameservers, "`, `") + "`\n") + } + if port43 != "" { + md.WriteString("- **WHOIS Server**: `" + port43 + "`\n") + } + if len(events) > 0 { + md.WriteString("\n## Events\n\n" + formatDeclarativeGFMTable([]string{"Event", "Date"}, events)) + } + if len(entityRows) > 0 { + md.WriteString("\n## Entities\n\n" + formatDeclarativeGFMTable([]string{"Handle", "Roles", "Organization", "Email"}, entityRows)) + } + + rec := map[string]any{ + "objectClassName": objClass, + "handle": handle, + "subject": subject, + "status": statuses, + } + if len(nameservers) > 0 { + rec["nameservers"] = nameservers + } + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: md.String(), + Records: []map[string]any{rec}, + Total: wave3SecIntPtr(1), + Returned: wave3SecIntPtr(1), + }, true +} + +// ── #326 BGP & ASN (RIPEstat JSON + bgp.he.net <= 1 MiB HTML) ──────────────────────────────────── + +func wave3SecFormatBGPASNRipeJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + obj, ok := parsed.(map[string]any) + if !ok || wave3SecIsGenericJSONError(obj) { + return nil, false + } + if st := strings.ToLower(wave3SecPlain(obj["status"], 24)); st != "" && st != "ok" { + return nil, false + } + data, okD := obj["data"].(map[string]any) + if !okD || len(data) == 0 { + return nil, false + } + + resource := wave3SecPlain(data["resource"], 64) + holder := wave3SecPlain(data["holder"], 180) + asType := wave3SecPlain(data["type"], 32) + announced := wave3SecPlain(data["announced"], 16) + blockMap, _ := data["block"].(map[string]any) + blockRes := wave3SecPlain(blockMap["resource"], 64) + blockName := wave3SecPlain(blockMap["name"], 120) + blockDesc := wave3SecPlain(blockMap["desc"], 160) + + var records []map[string]any + var prefixRows [][]string + if prefixes, okP := data["prefixes"].([]any); okP && len(prefixes) > 0 { + for _, rp := range prefixes { + if len(records) >= wave3SecMaxRecords { + break + } + pm, okPM := rp.(map[string]any) + if !okPM { + continue + } + pfx := wave3SecPlain(pm["prefix"], 64) + if pfx == "" { + continue + } + records = append(records, map[string]any{ + "resource": resource, + "prefix": pfx, + }) + prefixRows = append(prefixRows, []string{"`" + pfx + "`"}) + } + } + + if len(records) == 0 && (resource != "" || holder != "") { + rec := map[string]any{ + "resource": resource, + "holder": holder, + } + if announced != "" { + rec["announced"] = announced == "true" + } + if blockName != "" { + rec["rir"] = blockName + } + records = append(records, rec) + } + if len(records) == 0 { + return nil, false + } + + asnLabel := resource + if asnLabel != "" && !strings.HasPrefix(strings.ToUpper(asnLabel), "AS") && asType == "as" { + asnLabel = "AS" + asnLabel + } + title := wave3SecFirstNonEmpty(asnLabel, "RIPEstat BGP ASN") + if holder != "" { + title = fmt.Sprintf("%s — %s", title, holder) + } + + var md strings.Builder + md.WriteString("# " + escapeDeclMarkdownBrackets(title) + "\n\n") + if resource != "" { + md.WriteString("- **Resource**: `" + asnLabel + "`\n") + } + if holder != "" { + md.WriteString("- **Holder**: " + holder + "\n") + } + if announced != "" { + md.WriteString("- **Announced**: `" + announced + "`\n") + } + if blockName != "" || blockRes != "" { + md.WriteString("- **Allocation Block**: " + wave3SecFirstNonEmpty(blockName, blockRes)) + if blockDesc != "" { + md.WriteString(" (" + blockDesc + ")") + } + md.WriteString("\n") + } + if len(prefixRows) > 0 { + md.WriteString("\n## Announced Prefixes\n\n" + formatDeclarativeGFMTable([]string{"Prefix"}, prefixRows)) + } + + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: md.String(), + Records: records, + Total: wave3SecIntPtr(len(records)), + Returned: wave3SecIntPtr(len(records)), + }, true +} + +func wave3SecIsASCIIAlphaNum(b byte) bool { + return (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') || (b >= '0' && b <= '9') +} + +func wave3SecContainsWordPhraseASCII(s, lowerNeedle string) bool { + nLen := len(lowerNeedle) + if nLen == 0 || len(s) < nLen { + return false + } + pos := 0 + for pos <= len(s)-nLen { + rel := indexFoldASCIIExtract(s[pos:], lowerNeedle) + if rel < 0 { + return false + } + idx := pos + rel + end := idx + nLen + leftOK := idx == 0 || !wave3SecIsASCIIAlphaNum(s[idx-1]) + rightOK := end == len(s) || !wave3SecIsASCIIAlphaNum(s[end]) + if leftOK && rightOK { + return true + } + pos = idx + 1 + } + return false +} + +func wave3SecExtractBGPHEHTML(rawHTML, _ /* probeLower */, baseURL, extractorID string) *DeclarativePostFetchResult { + if wave3SecContainsWordPhraseASCII(rawHTML, "invalid as") || + wave3SecContainsWordPhraseASCII(rawHTML, "not a valid asn") || + indexFoldASCIIExtract(rawHTML, "could not find") >= 0 { + return nil + } + doc := ParseHTMLDoc(rawHTML, wave3SecBGPHEMaxBytes) + title := wave3SecExtractTitle(doc, rawHTML) + if title == "" { + return nil + } + asn := "" + if m := wave3SecRxASN.FindString(title + " " + baseURL); m != "" { + asn = strings.ToUpper(m) + } + asInfoMD := "" + if doc != nil { + if asInfoNode := doc.First("#asinfo"); asInfoNode != nil { + asInfoMD = wave3SecFragToMD(asInfoNode.HTML(), baseURL) + } + } + tblMD, rows := wave3SecExtractTableBlock(doc, "table", wave3SecMaxRecords) + if asInfoMD == "" && tblMD == "" { + mainDoc := ExtractHTMLDocumentFull(rawHTML, FullExtractOptions{ + BaseURL: baseURL, + OnlyMainContent: true, + IncludeImages: false, + SkipUniversalExtractors: true, + SkipPlainText: true, + }) + if strings.TrimSpace(mainDoc.Markdown) == "" { + return nil + } + asInfoMD = strings.TrimSpace(mainDoc.Markdown) + } + + var md strings.Builder + md.WriteString("# " + escapeDeclMarkdownBrackets(title) + "\n\n") + if asn != "" { + md.WriteString("- **ASN**: `" + asn + "`\n\n") + } + if asInfoMD != "" { + md.WriteString("## AS Information\n\n" + asInfoMD + "\n\n") + } + if tblMD != "" { + md.WriteString("## Prefixes & Peers\n\n" + tblMD) + } + rec := map[string]any{"title": title, "url": baseURL} + if asn != "" { + rec["asn"] = asn + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: wave3SecExtractMetaDesc(rawHTML), + Markdown: md.String(), + Records: []map[string]any{rec}, + Total: wave3SecIntPtr(wave3SecMaxInt(1, len(rows))), + Returned: wave3SecIntPtr(wave3SecMaxInt(1, len(rows))), + } +} + +func wave3SecMaxInt(a, b int) int { + if a > b { + return a + } + return b +} diff --git a/internal/extract/wave3_security_intel_test.go b/internal/extract/wave3_security_intel_test.go new file mode 100644 index 0000000..63dd14d --- /dev/null +++ b/internal/extract/wave3_security_intel_test.go @@ -0,0 +1,570 @@ +package extract + +import ( + "encoding/json" + "fmt" + "net/url" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func wave3SecDecodeDoc(t *testing.T, raw string) *DeclarativeFormattedDoc { + t.Helper() + var doc DeclarativeFormattedDoc + if err := json.Unmarshal([]byte(raw), &doc); err != nil { + t.Fatalf("unmarshal DeclarativeFormattedDoc: %v\nraw=%s", err, raw) + } + return &doc +} + +func wave3SecResolveManifest(t *testing.T, m *DeclarativeAdapterManifest, rawURL string) (*DeclarativeTwinMatch, bool) { + t.Helper() + u, err := url.Parse(rawURL) + if err != nil { + t.Fatalf("url.Parse(%q): %v", rawURL, err) + } + host := strings.TrimSuffix(strings.ToLower(u.Hostname()), ".") + rawParts := splitNonEmptyEscapedSegments(u.EscapedPath()) + return resolveManifestTwinOnParsedURL(m, u, host, rawParts, DeclarativeResolveOptions{}) +} + +func TestWave3SecurityIntelManifestsAndConflictBoundaries(t *testing.T) { + catMIDs := []string{ + "cisa-kev", + "first-epss", + "mitre-attack", + "mitre-cwe-capec", + "cve-org", + "cisa-advisories-ics", + "vendor-csaf", + "security-txt", + "exploit-db", + "certificate-transparency", + "rdap", + "bgp-asn", + } + + byID := make(map[string]*DeclarativeAdapterManifest, len(catMIDs)) + claimedDomains := make(map[string]string) + var allCatM []DeclarativeAdapterManifest + + for _, id := range catMIDs { + raw, err := os.ReadFile(filepath.Join("manifests", id+".yaml")) + if err != nil { + t.Fatalf("read %s.yaml: %v", id, err) + } + m, err := ParseDeclarativeYAMLManifest(raw) + if err != nil { + t.Fatalf("ParseDeclarativeYAMLManifest(%s.yaml): %v", id, err) + } + if m.ID != id { + t.Fatalf("%s.yaml has mismatched id=%q", id, m.ID) + } + if m.AuthMode == "detect-only" || m.DetectOnly != nil { + t.Fatalf("%s.yaml uses retired detect-only", id) + } + for _, d := range m.Domains { + ld := strings.ToLower(strings.TrimSpace(d)) + if prev, exists := claimedDomains[ld]; exists { + t.Fatalf("duplicate domain %q across %s and %s", ld, prev, id) + } + claimedDomains[ld] = id + } + for _, hr := range m.HTMLRoutes { + for _, b := range hr.Bullets { + if strings.ContainsAny(b.Label, "{}") { + t.Fatalf("%s.yaml bullet label contains {}: %q", id, b.Label) + } + } + } + byID[id] = m + allCatM = append(allCatM, *m) + } + + // Verify full cross-manifest rules (Rule 7, PSL, duplicate domains) across Cat M + colliding baseline manifests + for _, existingID := range []string{"osv-ghsa", "nist-nvd", "gitlab-forgejo", "edge-cloud-changelogs", "google-shopping-feed"} { + raw, err := os.ReadFile(filepath.Join("manifests", existingID+".yaml")) + if err != nil { + t.Fatalf("read %s.yaml: %v", existingID, err) + } + em, err := ParseDeclarativeYAMLManifest(raw) + if err != nil { + t.Fatalf("ParseDeclarativeYAMLManifest(%s.yaml): %v", existingID, err) + } + for _, d := range em.Domains { + ld := strings.ToLower(strings.TrimSpace(d)) + if catOwner, overlap := claimedDomains[ld]; overlap { + t.Fatalf("Cat M %s overlaps %s domain %q", catOwner, existingID, ld) + } + } + allCatM = append(allCatM, *em) + } + if err := ValidateDeclarativeManifests(allCatM); err != nil { + t.Fatalf("ValidateDeclarativeManifests failed: %v", err) + } + + // #315 cisa-kev vs #320 cisa-advisories-ics zero collision + kev := byID["cisa-kev"] + if !kev.UniversalEngine { + t.Fatalf("cisa-kev must set universalEngine: true") + } + if tm, ok := wave3SecResolveManifest(t, kev, "https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json"); !ok || tm.EffectiveMaxBytes() != 4194304 || tm.route.Extract.JSONMode != "cisa_kev_json" { + t.Fatalf("cisa-kev JSON route failed: ok=%v tm=%+v", ok, tm) + } + if tm, ok := wave3SecResolveManifest(t, kev, "https://www.cisa.gov/sites/default/files/csv/known_exploited_vulnerabilities.csv"); !ok || tm.route.Extract.TextMode != "cisa_kev_csv" { + t.Fatalf("cisa-kev CSV route failed: ok=%v tm=%+v", ok, tm) + } + if tm, ok := wave3SecResolveManifest(t, kev, "https://cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json"); !ok || tm.route.Extract.JSONMode != "cisa_kev_json" { + t.Fatalf("cisa-kev bare cisa.gov JSON route failed: ok=%v tm=%+v", ok, tm) + } + cisaAdv := byID["cisa-advisories-ics"] + if !cisaAdv.UniversalEngine { + t.Fatalf("cisa-advisories-ics must set universalEngine: true for bare cisa.gov routing") + } + for _, kevURL := range []string{ + "https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json", + "https://cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json", + "https://cisa.gov/sites/default/files/csv/known_exploited_vulnerabilities.csv", + } { + if tm, ok := wave3SecResolveManifest(t, cisaAdv, kevURL); ok || tm != nil { + t.Fatalf("cisa-advisories-ics must NOT match KEV path %s", kevURL) + } + } + for _, advXML := range []string{ + "https://www.cisa.gov/cybersecurity-advisories/ics-advisories.xml", + "https://cisa.gov/cybersecurity-advisories/ics-advisories.xml", + } { + if tm, ok := wave3SecResolveManifest(t, cisaAdv, advXML); !ok || tm.route.Extract.TextMode != "cisa_advisories_rss" { + t.Fatalf("cisa-advisories-ics RSS route failed for %s: ok=%v tm=%+v", advXML, ok, tm) + } + } + // Verify full ResolveDeclarativeTwin & ApplyDeclarativeHTMLExtractor routing on bare cisa.gov + if resolvedBareXML, okBareXML := ResolveDeclarativeTwin("https://cisa.gov/cybersecurity-advisories/ics-advisories.xml"); !okBareXML || resolvedBareXML == nil || resolvedBareXML.AdapterID != "cisa-advisories-ics" { + t.Fatalf("ResolveDeclarativeTwin bare cisa.gov ICS XML failed: ok=%v res=%+v", okBareXML, resolvedBareXML) + } + if resolvedBareKEV, okBareKEV := ResolveDeclarativeTwin("https://cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json"); !okBareKEV || resolvedBareKEV == nil || resolvedBareKEV.AdapterID != "cisa-kev" { + t.Fatalf("ResolveDeclarativeTwin bare cisa.gov KEV JSON failed: ok=%v res=%+v", okBareKEV, resolvedBareKEV) + } + bareICSHTML := `ICSA-26-328-01 | CISA

ICSA-26-328-01 Example PLC

CVE-2026-41001 affects industrial controllers.

` + if bareHTMLRes, okBareHTML := ApplyDeclarativeHTMLExtractor(bareICSHTML, "https://cisa.gov/news-events/ics-advisories/icsa-26-328-01", "", nil); !okBareHTML || bareHTMLRes == nil || bareHTMLRes.ExtractorID != "cisa-advisories-ics" { + t.Fatalf("ApplyDeclarativeHTMLExtractor bare cisa.gov ICS HTML failed: ok=%v res=%+v", okBareHTML, bareHTMLRes) + } + + // #317 mitre-attack STIX Range route & index.json route + att := byID["mitre-attack"] + if tm, ok := wave3SecResolveManifest(t, att, "https://raw.githubusercontent.com/mitre-attack/attack-stix-data/master/index.json"); !ok || tm.route.Extract.JSONMode != "mitre_attack_index_json" { + t.Fatalf("mitre-attack index.json route failed: ok=%v tm=%+v", ok, tm) + } + if tm, ok := wave3SecResolveManifest(t, att, "https://raw.githubusercontent.com/mitre-attack/attack-stix-data/master/enterprise-attack/enterprise-attack.json"); !ok || tm.route.Extract.TextMode != "mitre_attack_stix_bundle" || tm.EffectiveMaxBytes() != 1048576 || tm.route.Twin.Headers["Range"] != "bytes=0-524287" { + t.Fatalf("mitre-attack STIX bundle route failed: ok=%v tm=%+v", ok, tm) + } + + // #319 cve-org zero cross-domain twin + cve := byID["cve-org"] + if tm, ok := wave3SecResolveManifest(t, cve, "https://cveawg.mitre.org/api/cve/CVE-2024-3094"); !ok || tm.route.Extract.JSONMode != "cve_org_json" { + t.Fatalf("cve-org API route failed: ok=%v tm=%+v", ok, tm) + } + if tm, ok := wave3SecResolveManifest(t, cve, "https://www.cve.org/CVERecord?id=CVE-2024-3094"); ok || tm != nil { + t.Fatalf("www.cve.org must NOT twin-route to cveawg.mitre.org (Rule 7)") + } + + // #323 exploit-db GitLab CSV Range route must not match gitlab-forgejo + edb := byID["exploit-db"] + if tm, ok := wave3SecResolveManifest(t, edb, "https://gitlab.com/exploit-database/exploitdb/-/raw/main/files_exploits.csv"); !ok || tm.route.Extract.TextMode != "exploit_db_csv" || tm.route.Twin.Headers["Range"] != "bytes=0-2097151" { + t.Fatalf("exploit-db GitLab CSV route failed: ok=%v tm=%+v", ok, tm) + } + gitlabRaw, _ := os.ReadFile(filepath.Join("manifests", "gitlab-forgejo.yaml")) + gitlabM, _ := ParseDeclarativeYAMLManifest(gitlabRaw) + if tm, ok := wave3SecResolveManifest(t, gitlabM, "https://gitlab.com/exploit-database/exploitdb/-/raw/main/files_exploits.csv"); ok || tm != nil { + t.Fatalf("gitlab-forgejo must NOT match exploit-db /-/raw/ CSV path") + } +} + +func TestWave3SecurityIntelJSONAndTextFormatters(t *testing.T) { + // 1. #315 cisa_kev_json (bounding >25 records + ?cve= filter) + var kevVulns []string + for i := 1; i <= 30; i++ { + cve := "CVE-2026-" + strings.ReplaceAll(strings.TrimSpace(string([]byte{'1' + byte(i/10), '0' + byte(i%10), '0', '0'})), " ", "") + kevVulns = append(kevVulns, `{"cveID":"`+cve+`","vendorProject":"Acme","product":"Widget","vulnerabilityName":"Test Bug","dateAdded":"2026-11-01","dueDate":"2026-11-22","knownRansomwareCampaignUse":"Known"}`) + } + kevPayload := `{"title":"CISA KEV","catalogVersion":"2026.11.28","dateReleased":"2026-11-28T00:00:00Z","count":1808,"vulnerabilities":[` + strings.Join(kevVulns, ",") + `]}` + kevRaw, ok := FormatWave3SecurityIntelJSONMode("cisa_kev_json", []byte(kevPayload), nil, "https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json") + if !ok { + t.Fatalf("cisa_kev_json failed") + } + kevDoc := wave3SecDecodeDoc(t, kevRaw) + if len(kevDoc.Records) != wave3SecMaxRecords || kevDoc.Total == nil || *kevDoc.Total != 1808 || kevDoc.Truncated == nil || !*kevDoc.Truncated { + t.Fatalf("unexpected cisa_kev_json bounding: len=%d total=%v trunc=%v", len(kevDoc.Records), kevDoc.Total, kevDoc.Truncated) + } + kevFiltRaw, ok := FormatWave3SecurityIntelJSONMode("cisa_kev_json", []byte(kevPayload), nil, "https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json?cve=CVE-2026-1500") + if !ok { + t.Fatalf("cisa_kev_json ?cve= filter failed") + } + kevFiltDoc := wave3SecDecodeDoc(t, kevFiltRaw) + if len(kevFiltDoc.Records) != 1 || kevFiltDoc.Records[0]["cveID"] != "CVE-2026-1500" { + t.Fatalf("unexpected cisa_kev_json filtered result: %+v", kevFiltDoc.Records) + } + kevMissRaw, missOK := FormatWave3SecurityIntelJSONMode("cisa_kev_json", []byte(kevPayload), nil, "https://www.cisa.gov/sites/default/files/feeds/known_exploited_vulnerabilities.json?cve=CVE-1999-9999") + if !missOK { + t.Fatalf("cisa_kev_json must handle unmatched ?cve= query with concise bounded output") + } + kevMissDoc := wave3SecDecodeDoc(t, kevMissRaw) + if len(kevMissDoc.Records) != 0 || kevMissDoc.Returned == nil || *kevMissDoc.Returned != 0 || !strings.Contains(kevMissDoc.Markdown, "No matching KEV entry found for CVE-1999-9999") { + t.Fatalf("unexpected cisa_kev_json unmatched ?cve= result: %+v", kevMissDoc) + } + + // #315 cisa_kev_csv + kevCSV := "cveID,vendorProject,product,vulnerabilityName,dateAdded,shortDescription,requiredAction,dueDate,knownRansomwareCampaignUse,notes\nCVE-2024-3094,Tukaani,XZ Utils,XZ Backdoor,2024-04-01,Malicious code,Apply updates,2024-04-22,Unknown,https://nvd.nist.gov\n" + if csvRaw, ok := FormatWave3SecurityIntelTextMode("cisa_kev_csv", kevCSV, nil, "https://www.cisa.gov/sites/default/files/csv/known_exploited_vulnerabilities.csv"); !ok || !strings.Contains(csvRaw, "CVE-2024-3094") { + t.Fatalf("cisa_kev_csv failed: ok=%v raw=%s", ok, csvRaw) + } + + // 2. #316 first_epss_json + epssPayload := `{"status":"OK","status-code":200,"total":1,"data":[{"cve":"CVE-2024-3094","epss":"0.94210","percentile":"0.99950","date":"2026-11-28"}]}` + if epssRaw, ok := FormatWave3SecurityIntelJSONMode("first_epss_json", []byte(epssPayload), nil, "https://api.first.org/data/v1/epss?cve=CVE-2024-3094"); !ok || !strings.Contains(epssRaw, "94.21%") || !strings.Contains(epssRaw, "99.95%") { + t.Fatalf("first_epss_json failed: ok=%v raw=%s", ok, epssRaw) + } + if _, negOK := FormatWave3SecurityIntelJSONMode("first_epss_json", []byte(`{"status":"OK","status-code":200,"total":0,"data":[]}`), nil, "https://api.first.org/data/v1/epss?cve=CVE-1999-0001"); negOK { + t.Fatalf("first_epss_json must reject empty data") + } + + // 3. #317 mitre_attack_index_json + mitre_attack_stix_bundle (2 MiB Range-truncated prefix scan < 25ms) + idxPayload := `{"name":"ATT&CK STIX Collections","collections":[{"id":"x-mitre-collection--1","name":"Enterprise ATT&CK","versions":[{"version":"16.1","modified":"2026-10-31T00:00:00Z","url":"https://raw.githubusercontent.com/mitre-attack/attack-stix-data/master/enterprise-attack/enterprise-attack.json"}]}]}` + idxRaw, idxOK := FormatWave3SecurityIntelJSONMode("mitre_attack_index_json", []byte(idxPayload), nil, "https://raw.githubusercontent.com/mitre-attack/attack-stix-data/master/index.json") + if !idxOK { + t.Fatalf("mitre_attack_index_json failed") + } + idxDoc := wave3SecDecodeDoc(t, idxRaw) + if !strings.Contains(idxDoc.Markdown, "Enterprise ATT&CK") || len(idxDoc.Records) != 1 { + t.Fatalf("unexpected mitre_attack_index_json doc: %+v", idxDoc) + } + + var stixBuf strings.Builder + stixBuf.Grow(2*1024*1024 + 1024) + stixBuf.WriteString(`{"type":"bundle","id":"bundle--test","objects":[{"type":"x-mitre-collection","id":"x-mitre-collection--1","name":"Enterprise ATT&CK","x_mitre_version":"16.1","modified":"2026-10-31T00:00:00Z","description":"Enterprise Matrix"}`) + techTemplate := `,{"type":"attack-pattern","id":"attack-pattern--1","name":"Command and Scripting Interpreter","description":"` + strings.Repeat("A", 300) + `","x_mitre_platforms":["Linux","Windows"],"external_references":[{"source_name":"mitre-attack","external_id":"T1059","url":"https://attack.mitre.org/techniques/T1059"}]}` + for stixBuf.Len() < 2*1024*1024 { + stixBuf.WriteString(techTemplate) + } + // Truncate mid-object at exactly 2 MiB + stix2MiB := stixBuf.String()[:2*1024*1024] + tStart := time.Now() + stixRaw, stixOK := FormatWave3SecurityIntelTextMode("mitre_attack_stix_bundle", stix2MiB, nil, "https://raw.githubusercontent.com/mitre-attack/attack-stix-data/master/enterprise-attack/enterprise-attack.json") + tElapsed := time.Since(tStart) + if !stixOK { + t.Fatalf("mitre_attack_stix_bundle failed on 2 MiB truncated prefix") + } + if tElapsed > 25*time.Millisecond*time.Duration(extractRaceSlowdown) { + t.Fatalf("mitre_attack_stix_bundle 2 MiB scan exceeded 25ms budget: %v", tElapsed) + } + stixDoc := wave3SecDecodeDoc(t, stixRaw) + if len(stixDoc.Records) != wave3SecMaxRecords || stixDoc.Truncated == nil || !*stixDoc.Truncated { + t.Fatalf("unexpected STIX bundle result: len=%d trunc=%v", len(stixDoc.Records), stixDoc.Truncated) + } + // #317 STIX key order: "objects" BEFORE "type":"bundle" (> 4 KB offset) + var objectsFirstBuf strings.Builder + objectsFirstBuf.WriteString(`{"objects":[{"type":"x-mitre-collection","id":"x-mitre-collection--1","name":"Enterprise ATT&CK","x_mitre_version":"16.1","modified":"2026-10-31T00:00:00Z"},{"type":"attack-pattern","id":"attack-pattern--1","name":"PowerShell","description":"` + strings.Repeat("B", 5000) + `","external_references":[{"source_name":"mitre-attack","external_id":"T1059.001"}]}],"id":"bundle--late","type":"bundle"}`) + if ofRaw, ofOK := FormatWave3SecurityIntelTextMode("mitre_attack_stix_bundle", objectsFirstBuf.String(), nil, "https://raw.githubusercontent.com/mitre-attack/attack-stix-data/master/enterprise-attack/enterprise-attack.json"); !ofOK || !strings.Contains(ofRaw, "T1059.001") { + t.Fatalf("mitre_attack_stix_bundle with objects before type:bundle (>4KB) failed: ok=%v", ofOK) + } + + // 4. #318 mitre_cwe_json + cwePayload := `{"Weaknesses":[{"ID":"79","Name":"Cross-site Scripting","Abstraction":"Base","Status":"Stable","Description":"Improper neutralization of input.","LikelihoodOfExploit":"High"}]}` + if cweRaw, ok := FormatWave3SecurityIntelJSONMode("mitre_cwe_json", []byte(cwePayload), nil, "https://cwe-api.mitre.org/api/v1/cwe/weakness/79"); !ok || !strings.Contains(cweRaw, "CWE-79") { + t.Fatalf("mitre_cwe_json failed") + } + + // 5. #319 cve_org_json + cvePayload := `{"dataType":"CVE_RECORD","cveMetadata":{"cveId":"CVE-2024-3094","state":"PUBLISHED","assignerShortName":"redhat","datePublished":"2024-03-29T18:00:00Z"},"containers":{"cna":{"title":"XZ Utils backdoor","descriptions":[{"lang":"en","value":"Backdoor in liblzma."}],"metrics":[{"cvssV3_1":{"baseScore":10.0,"baseSeverity":"CRITICAL","vectorString":"CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:C/C:H/I:H/A:H"}}]}}}` + if cveRaw, ok := FormatWave3SecurityIntelJSONMode("cve_org_json", []byte(cvePayload), nil, "https://cveawg.mitre.org/api/cve/CVE-2024-3094"); !ok || !strings.Contains(cveRaw, "CVE-2024-3094") || !strings.Contains(cveRaw, "CRITICAL") { + t.Fatalf("cve_org_json failed") + } + + // 6. #320 cisa_advisories_rss + rssPayload := `CISA ICS AdvisoriesICSA-26-328-01 PLChttps://www.cisa.gov/news-events/ics-advisories/icsa-26-328-01Tue, 24 Nov 2026 12:00:00 +0000CVE-2026-41001 https://github.com/cisagov/CSAF/blob/develop/csaf_files/OT/white/2026/icsa-26-328-01.json` + if rssRaw, ok := FormatWave3SecurityIntelTextMode("cisa_advisories_rss", rssPayload, nil, "https://www.cisa.gov/cybersecurity-advisories/ics-advisories.xml"); !ok || !strings.Contains(rssRaw, "CVE-2026-41001") || !strings.Contains(rssRaw, "icsa-26-328-01.json") { + t.Fatalf("cisa_advisories_rss failed") + } + + // 7. #321 vendor_csaf_json (provider-metadata.json + advisory JSON) + pmPayload := `{"canonical_url":"https://security.access.redhat.com/data/csaf/v2/provider-metadata.json","metadata_version":"2.0","role":"csaf_publisher","last_updated":"2026-11-28T00:00:00Z","publisher":{"name":"Red Hat Product Security","namespace":"https://access.redhat.com"},"distributions":[{"directory_url":"https://security.access.redhat.com/data/csaf/v2/advisories/"}]}` + if pmRaw, ok := FormatWave3SecurityIntelJSONMode("vendor_csaf_json", []byte(pmPayload), nil, "https://security.access.redhat.com/data/csaf/v2/provider-metadata.json"); !ok || !strings.Contains(pmRaw, "Red Hat Product Security") { + t.Fatalf("vendor_csaf_json provider-metadata failed") + } + csafAdvPayload := `{"document":{"csaf_version":"2.0","category":"csaf_security_advisory","title":"openssl update","tracking":{"id":"RHSA-2026:88339","status":"final","current_release_date":"2026-11-20T00:00:00Z"},"publisher":{"name":"Red Hat"}},"vulnerabilities":[{"cve":"CVE-2026-10001","title":"TLS bug","cwe":{"id":"CWE-125"},"scores":[{"cvss_v3":{"baseScore":7.5}}]}]}` + if advRaw, ok := FormatWave3SecurityIntelJSONMode("vendor_csaf_json", []byte(csafAdvPayload), nil, "https://security.access.redhat.com/data/csaf/v2/advisories/2026/rhsa-2026_88339.json"); !ok || !strings.Contains(advRaw, "RHSA-2026:88339") { + t.Fatalf("vendor_csaf_json advisory failed") + } + + // 8. #322 security_txt_text (with PGP cleartext wrapper + negative checks) + pgpSecTxt := "-----BEGIN PGP SIGNED MESSAGE-----\nHash: SHA256\n\n# Security policy\nContact: mailto:security@example.com\nExpires: 2027-06-30T23:59:59Z\nPolicy: https://example.com/security-policy\n-----BEGIN PGP SIGNATURE-----\niQIzBAEBCAAdFiEE\n-----END PGP SIGNATURE-----\n" + if secRaw, ok := FormatWave3SecurityIntelTextMode("security_txt_text", pgpSecTxt, nil, "https://example.com/.well-known/security.txt"); !ok || !strings.Contains(secRaw, "mailto:security@example.com") || !strings.Contains(secRaw, "2027-06-30") { + t.Fatalf("security_txt_text failed") + } + if _, negOK := FormatWave3SecurityIntelTextMode("security_txt_text", "Contact: mailto:a@b.com", nil, "https://example.com/.well-known/security.txt"); negOK { + t.Fatalf("security_txt_text must reject HTML responses") + } + if _, negOK := FormatWave3SecurityIntelTextMode("security_txt_text", "# comment\nExpires: 2027-06-30T23:59:59Z\n", nil, "https://example.com/.well-known/security.txt"); negOK { + t.Fatalf("security_txt_text must reject missing Contact:") + } + + // 9. #323 exploit_db_csv (Range-cut partial last line dropped + 2 MiB budget) + var edbBuf strings.Builder + edbBuf.WriteString("id,file,description,date_published,author,type,platform,port,date_added,date_updated,verified,codes,tags,aliases,screenshot_url,application_url,source_url\n") + for i := 1; i <= 30; i++ { + edbBuf.WriteString("51000,exploits/hardware/webapps/51000.py,\"Router RCE\",2022-08-01,Researcher,webapps,hardware,,2022-08-01,2022-08-01,1,CVE-2020-20277,,,,,\n") + } + // Simulate partial trailing line from Range boundary + edbBuf.WriteString("99999,exploits/partial/TRUNCATED_LINE") + edbRaw, edbOK := FormatWave3SecurityIntelTextMode("exploit_db_csv", edbBuf.String(), nil, "https://gitlab.com/exploit-database/exploitdb/-/raw/main/files_exploits.csv") + if !edbOK || strings.Contains(edbRaw, "TRUNCATED_LINE") { + t.Fatalf("exploit_db_csv failed or emitted partial last line: ok=%v", edbOK) + } + edbDoc := wave3SecDecodeDoc(t, edbRaw) + if len(edbDoc.Records) != wave3SecMaxRecords || edbDoc.Truncated == nil || !*edbDoc.Truncated { + t.Fatalf("unexpected exploit_db_csv result: len=%d trunc=%v", len(edbDoc.Records), edbDoc.Truncated) + } + + // 10. #324 cert_transparency_json (Cert Spotter + crt.sh) + crtShPayload := `[{"issuer_ca_id":1,"issuer_name":"C=US, O=Let's Encrypt","common_name":"example.org","name_value":"example.org\nwww.example.org","id":987654,"not_before":"2026-10-01T00:00:00","not_after":"2026-12-30T00:00:00","serial_number":"0123abcd"}]` + if ctRaw, ok := FormatWave3SecurityIntelJSONMode("cert_transparency_json", []byte(crtShPayload), nil, "https://crt.sh/?q=example.org&output=json"); !ok || !strings.Contains(ctRaw, "example.org") || !strings.Contains(ctRaw, "Let's Encrypt") { + t.Fatalf("cert_transparency_json crt.sh failed") + } + + // 11. #325 rdap_bootstrap_json + rdap_json + bootPayload := `{"version":"1.0","publication":"2026-11-28T00:00:00Z","description":"IANA RDAP Bootstrap for DNS","services":[[["com","net"],["https://rdap.verisign.com/com/v1/"]]]}` + if bootRaw, ok := FormatWave3SecurityIntelJSONMode("rdap_bootstrap_json", []byte(bootPayload), nil, "https://data.iana.org/rdap/dns.json"); !ok || !strings.Contains(bootRaw, "rdap.verisign.com") { + t.Fatalf("rdap_bootstrap_json failed") + } + ipRdap := `{"objectClassName":"ip network","handle":"NET-1-1-1-0-1","startAddress":"1.1.1.0","endAddress":"1.1.1.255","name":"APNIC-LABS","country":"AU","status":["active"]}` + if ipRaw, ok := FormatWave3SecurityIntelJSONMode("rdap_json", []byte(ipRdap), nil, "https://rdap.apnic.net/ip/1.1.1.1"); !ok || !strings.Contains(ipRaw, "1.1.1.0 - 1.1.1.255") { + t.Fatalf("rdap_json IP failed") + } + + // 12. #326 bgp_asn_ripe_json + ripePayload := `{"status":"ok","data":{"type":"as","resource":"13335","holder":"CLOUDFLARENET","announced":true,"block":{"resource":"13172-14195","name":"Administered by ARIN"}}}` + if ripeRaw, ok := FormatWave3SecurityIntelJSONMode("bgp_asn_ripe_json", []byte(ripePayload), nil, "https://stat.ripe.net/data/as-overview/data.json?resource=AS13335"); !ok || !strings.Contains(ripeRaw, "AS13335") || !strings.Contains(ripeRaw, "CLOUDFLARENET") { + t.Fatalf("bgp_asn_ripe_json failed") + } +} + +func TestWave3SecurityIntelHTMLExtractorsAndFixtures(t *testing.T) { + htmlModes := []string{ + "cisa_kev_html", + "mitre_attack_html", + "mitre_cwe_capec_html", + "cve_org_html", + "cisa_advisories_html", + "exploit_db_html", + "cert_transparency_html", + "bgp_he_html", + } + for _, m := range htmlModes { + if getExternalHTMLModeLazy(m) == nil { + t.Fatalf("RegisterExternalHTMLModeLazy missing %q", m) + } + } + + // Verify all 12 fixture files exist, have >=4 negativeCases, and pass positive + negative checks + catMIDs := []string{ + "cisa-kev", + "first-epss", + "mitre-attack", + "mitre-cwe-capec", + "cve-org", + "cisa-advisories-ics", + "vendor-csaf", + "security-txt", + "exploit-db", + "certificate-transparency", + "rdap", + "bgp-asn", + } + type adapterFixture struct { + AdapterID string `json:"adapterId"` + Mode string `json:"mode"` + InputURL string `json:"inputUrl"` + ExpectedFetchURL string `json:"expectedFetchUrl"` + MockPayload string `json:"mockPayload"` + ExpectTitleIncludes string `json:"expectTitleIncludes"` + ExpectMarkdownIncludes []string `json:"expectMarkdownIncludes"` + NegativeCases []struct { + Name string `json:"name"` + Status int `json:"status"` + InputURL string `json:"inputUrl"` + FinalURL string `json:"finalUrl"` + Payload string `json:"payload"` + } `json:"negativeCases"` + } + + for _, slug := range catMIDs { + rawFX, err := os.ReadFile(filepath.Join("..", "..", "hub", "test", "fixtures", "adapters", slug+".json")) + if err != nil { + t.Fatalf("read fixture %s.json: %v", slug, err) + } + var fx adapterFixture + if err := json.Unmarshal(rawFX, &fx); err != nil { + t.Fatalf("unmarshal %s.json: %v", slug, err) + } + if fx.AdapterID != slug { + t.Fatalf("%s.json adapterId=%q != %q", slug, fx.AdapterID, slug) + } + if len(fx.NegativeCases) < 4 { + t.Fatalf("%s.json must have >= 4 negativeCases, got %d", slug, len(fx.NegativeCases)) + } + if fx.Mode == "html" { + modeName := "exploit_db_html" + start := time.Now() + out, ok := RunWave3SecurityIntelHTMLMode(modeName, fx.MockPayload, fx.InputURL) + elapsed := time.Since(start) + if !ok { + t.Fatalf("%s HTML golden failed", slug) + } + if elapsed > 75*time.Millisecond*time.Duration(extractRaceSlowdown) { + t.Fatalf("%s HTML extraction exceeded 75ms budget: %v", slug, elapsed) + } + for _, needle := range fx.ExpectMarkdownIncludes { + if !strings.Contains(out, needle) { + t.Fatalf("%s HTML output missing %q", slug, needle) + } + } + for _, nc := range fx.NegativeCases { + u := nc.FinalURL + if u == "" { + u = nc.InputURL + } + if u == "" { + u = fx.InputURL + } + if _, negOK := RunWave3SecurityIntelHTMLMode(modeName, nc.Payload, u); negOK { + t.Fatalf("%s HTML negative case %q must be rejected", slug, nc.Name) + } + } + } + } + + // #317 mitre_attack_html + attackHTML := `Command and Scripting Interpreter, Technique T1059 | MITRE ATT&CK

Command and Scripting Interpreter

ID: T1059
Tactics: Execution

Adversaries may abuse command and script interpreters to execute commands.

` + if out, ok := RunWave3SecurityIntelHTMLMode("mitre_attack_html", attackHTML, "https://attack.mitre.org/techniques/T1059/"); !ok || !strings.Contains(out, "T1059") { + t.Fatalf("mitre_attack_html failed") + } + + // #318 mitre_cwe_capec_html (CAPEC XHTML) + capecHTML := `CAPEC-1: Accessing Functionality Not Properly Constrained by ACLs

CAPEC-1: Accessing Functionality Not Properly Constrained by ACLs

An adversary exploits missing access control checks.

Enforce role-based authorization on every endpoint.

` + if out, ok := RunWave3SecurityIntelHTMLMode("mitre_cwe_capec_html", capecHTML, "https://capec.mitre.org/data/definitions/1.html"); !ok || !strings.Contains(out, "CAPEC-1") || !strings.Contains(out, "role-based authorization") { + t.Fatalf("mitre_cwe_capec_html failed: ok=%v out=%s", ok, out) + } + + // #319 cve_org_html Vue CSR SPA shell strict rejection + vueShell := `CVE Record

Common vulnerabilities and Exposures (CVE)

` + if _, ok := RunWave3SecurityIntelHTMLMode("cve_org_html", vueShell, "https://www.cve.org/CVERecord?id=CVE-2024-3094"); ok { + t.Fatalf("cve_org_html must reject Vue CSR SPA shell") + } + + // #326 bgp_he_html > 4 MiB HTML sliced to <= 1 MiB in Go before parsing (< 25ms) + bgpPrefix := `AS13335 Cloudflare, Inc. - bgp.he.net

AS13335 Cloudflare, Inc.

Origin AS13335 registered to Cloudflare, Inc. (ARIN).

PrefixDescription
1.1.1.0/24Cloudflare DNS
` + bgpHuge := bgpPrefix + strings.Repeat("198.51.100.0/24Padding", 90000) + `
` + if len(bgpHuge) <= 4*1024*1024 { + t.Fatalf("expected bgpHuge > 4 MiB, got %d", len(bgpHuge)) + } + tStart := time.Now() + bgpOut, bgpOK := RunWave3SecurityIntelHTMLMode("bgp_he_html", bgpHuge, "https://bgp.he.net/AS13335") + tElapsed := time.Since(tStart) + if !bgpOK || !strings.Contains(bgpOut, "AS13335") || !strings.Contains(bgpOut, "1.1.1.0/24") { + t.Fatalf("bgp_he_html >4MiB slice failed: ok=%v", bgpOK) + } + if tElapsed > 50*time.Millisecond*time.Duration(extractRaceSlowdown) { + t.Fatalf("bgp_he_html >4MiB slice exceeded 50ms budget: %v", tElapsed) + } + if _, negOK := RunWave3SecurityIntelHTMLMode("bgp_he_html", `AS999999 - bgp.he.net
Invalid AS
`, "https://bgp.he.net/AS999999"); negOK { + t.Fatalf("bgp_he_html must reject Invalid AS") + } + if _, neg180OK := RunWave3SecurityIntelHTMLMode("bgp_he_html", `

Invalid AS

Invalid AS specified. Please enter a valid ASN.

`, "https://bgp.he.net/AS9999999"); neg180OK { + t.Fatalf("bgp_he_html must reject 180B Invalid AS specified") + } + bgpPast64KInvalid := `AS9999999 - bgp.he.net` + strings.Repeat("", 4000) + `

Invalid AS

Invalid AS specified. Please enter a valid ASN.

` + if _, negPast64OK := RunWave3SecurityIntelHTMLMode("bgp_he_html", bgpPast64KInvalid, "https://bgp.he.net/AS9999999"); negPast64OK { + t.Fatalf("bgp_he_html must reject past-64KB Invalid AS") + } + bgpPast64KNotValidASN := `AS9999999 - bgp.he.net` + strings.Repeat("", 4000) + `

Not a valid ASN

` + if _, negASNOK := RunWave3SecurityIntelHTMLMode("bgp_he_html", bgpPast64KNotValidASN, "https://bgp.he.net/AS9999999"); negASNOK { + t.Fatalf("bgp_he_html must reject past-64KB Not a valid ASN") + } + bgpValidWordBoundary := `AS13335 Cloudflare, Inc. - bgp.he.net

AS13335 Cloudflare, Inc.

Ignore invalid ascii comment in description.

` + if outWB, okWB := RunWave3SecurityIntelHTMLMode("bgp_he_html", bgpValidWordBoundary, "https://bgp.he.net/AS13335"); !okWB || !strings.Contains(outWB, "AS13335") { + t.Fatalf("bgp_he_html word boundary check false-positived on invalid ascii: ok=%v", okWB) + } + + // Unrelated HTML fast rejection across all 8 HTML modes + unrelated := `Example Blog

Hello World

Just a post.

` + for _, m := range htmlModes { + if _, ok := RunWave3SecurityIntelHTMLMode(m, unrelated, "https://blog.example.org/post"); ok { + t.Fatalf("%s must not match unrelated HTML", m) + } + } +} + +func TestWave3SecM7StreamingAndLatencyFixes(t *testing.T) { + // 1. #317 mitre-attack: object #0 (x-mitre-collection) > prefix boundary -> extracts collection + first 25 x_mitre_contents < 25ms + var contents strings.Builder + for i := 0; i < 6000; i++ { + if i > 0 { + contents.WriteByte(',') + } + contents.WriteString(fmt.Sprintf(`{"object_ref":"attack-pattern--%08d-0000-0000-0000-000000000000","object_modified":"2026-10-01T00:00:00.000Z"}`, i)) + } + mitreTruncPrefix := `{"type":"bundle","id":"bundle--ent","objects":[{"type":"x-mitre-collection","id":"x-mitre-collection--1","name":"Enterprise ATT&CK","x_mitre_version":"16.1","modified":"2026-10-31T00:00:00Z","description":"Enterprise Matrix","x_mitre_contents":[` + contents.String() + if len(mitreTruncPrefix) > 524288 { + mitreTruncPrefix = mitreTruncPrefix[:524288] + } + startM := time.Now() + mitreRaw, okM := FormatWave3SecurityIntelTextMode("mitre_attack_stix_bundle", mitreTruncPrefix, nil, "https://raw.githubusercontent.com/mitre-attack/attack-stix-data/master/enterprise-attack/enterprise-attack.json") + elapsedM := time.Since(startM) + if !okM { + t.Fatalf("mitre_attack_stix_bundle truncated x-mitre-collection fallback failed") + } + mitreDoc := wave3SecDecodeDoc(t, mitreRaw) + if len(mitreDoc.Records) != 25 || mitreDoc.Truncated == nil || !*mitreDoc.Truncated || !strings.Contains(mitreDoc.Title, "Enterprise ATT&CK") { + t.Fatalf("unexpected mitre truncated collection doc: %+v", mitreDoc) + } + if budget := 25 * time.Millisecond * time.Duration(extractRaceSlowdown); elapsedM > budget { + t.Fatalf("mitre_attack_stix_bundle exceeded %v budget: %v", budget, elapsedM) + } + + // 2. #320 cisa-advisories-ics: 963 KiB RSS XML < 25ms + var rssBuf strings.Builder + rssBuf.WriteString(`CISA ICS Advisories`) + itemBody := strings.Repeat("

Industrial control systems advisory details and mitigation guidance for operators.

", 80) + for i := 0; i < 150; i++ { + rssBuf.WriteString(fmt.Sprintf(`ICSA-26-%03d-01 Devicehttps://www.cisa.gov/news-events/ics-advisories/icsa-26-%03d-01Tue, 24 Nov 2026 12:00:00 +0000`, i, i, i, itemBody, i)) + } + rssBuf.WriteString(`
`) + startR := time.Now() + rssRaw, okR := FormatWave3SecurityIntelTextMode("cisa_advisories_rss", rssBuf.String(), nil, "https://www.cisa.gov/cybersecurity-advisories/ics-advisories.xml") + elapsedR := time.Since(startR) + if !okR { + t.Fatalf("cisa_advisories_rss 1MB failed") + } + rssDoc := wave3SecDecodeDoc(t, rssRaw) + if len(rssDoc.Records) != 25 || rssDoc.Truncated == nil || !*rssDoc.Truncated { + t.Fatalf("unexpected cisa_advisories_rss 1MB doc: recs=%d trunc=%v", len(rssDoc.Records), rssDoc.Truncated) + } + if budget := 25 * time.Millisecond * time.Duration(extractRaceSlowdown); elapsedR > budget { + t.Fatalf("cisa_advisories_rss 1MB exceeded %v budget: %v", budget, elapsedR) + } + + // 3. #315 cisa-kev HTML: 300 KB HTML with inline scripts/styles < 25ms + kevHTML := `Known Exploited Vulnerabilities Catalog | CISA

Known Exploited Vulnerabilities Catalog

This catalog lists authoritative vulnerabilities exploited in the wild.

JSON Feed
` + startK := time.Now() + kevOut, okK := RunWave3SecurityIntelHTMLMode("cisa_kev_html", kevHTML, "https://www.cisa.gov/known-exploited-vulnerabilities-catalog") + elapsedK := time.Since(startK) + if !okK || !strings.Contains(kevOut, "Known Exploited Vulnerabilities Catalog") { + t.Fatalf("cisa_kev_html failed: ok=%v", okK) + } + if budget := 25 * time.Millisecond * time.Duration(extractRaceSlowdown); elapsedK > budget { + t.Fatalf("cisa_kev_html exceeded %v budget: %v", budget, elapsedK) + } +} diff --git a/internal/extract/wave3_social_creator.go b/internal/extract/wave3_social_creator.go new file mode 100644 index 0000000..bb40411 --- /dev/null +++ b/internal/extract/wave3_social_creator.go @@ -0,0 +1,3252 @@ +package extract + +import ( + "bytes" + "encoding/json" + "fmt" + stdhtml "html" + "net/url" + "strconv" + "strings" + "time" +) + +const ( + wave3SocialMaxHTMLBytes = 2 * 1024 * 1024 + wave3SocialStdHTMLMaxBytes = 1 * 1024 * 1024 + wave3SocialMaxJSONBytes = 4 * 1024 * 1024 + wave3SocialMaxRecords = 25 + wave3SocialMaxNostrEvents = 20 +) + +var ( + wave3SocialRxNotFoundTitle = newLazyRegexp(`(?i)(?:^|\b)(?:404|410|403\s+forbidden|forbidden|page\s+not\s+found|not\s+found|error\s*404|we\s+couldn'?t\s+find\s+that\s+page|access\s+denied|request\s+(?:rejected|blocked)|could\s+not\s+be\s+satisfied|unauthorized|attention\s+required|just\s+a\s+moment|checking\s+your\s+browser|blocked|event\s+not\s+found|note\s+not\s+found|post\s+not\s+found|profile\s+not\s+found|user\s+not\s+found|content\s+isn'?t\s+available)(?:\b|$)`) + wave3SocialRxMaintTitle = newLazyRegexp(`(?i)(?:scheduled\s+maintenance|temporarily\s+unavailable|service\s+unavailable|site\s+maintenance|under\s+maintenance|502\s+bad\s+gateway|503\s+service|down\s+for\s+maintenance)`) + wave3SocialRxErrorTitle = newLazyRegexp(`(?i)^(?:(?:(?:400|401|403|404|406|410|429|500|502|503)\s+)?(?:internal\s+)?server\s+error|application\s+error|system\s+error|unexpected\s+error|error\s+page|(?:400|401|403|404|406|410|429|500|502|503|http\s+\d{3})\s+error|error\s+(?:400|401|403|404|406|410|429|500|502|503)|error)(?:\s*[|\-\x{2013}\x{2014}:]\s*.*)?$|^.*(?:\s*[|\-\x{2013}\x{2014}:]\s*error)$`) + wave3SocialRxGenericTitle = newLazyRegexp(`(?i)^(?:loading\.{0,3}|home|welcome|search|log\s*in|sign\s*in|sign\s*up|threads|threads\s*[•|\-]\s*log\s*in|tumblr|farcaster|product\s*hunt|substack|patreon|njump)$`) + wave3SocialRxSpace = newLazyRegexp(`[ \t\r\n]+`) + wave3SocialRxTitleTag = newLazyRegexp(`(?is)]*>(.*?)`) + wave3SocialRxMetaTag = newLazyRegexp(`(?is)]*>`) + wave3SocialRxNextData = newLazyRegexp(`(?is)]*\bid\s*=\s*["']__NEXT_DATA__["'][^>]*>(.*?)`) + wave3SocialRxISODuration = newLazyRegexp(`^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?)?$`) + wave3SocialRxTumblrSuffix = newLazyRegexp(`(?i)\s*\|\s*Tumblr\s*$`) + wave3SocialRxPHSuffix = newLazyRegexp(`(?i)\s*[-|]\s*Product Hunt\s*$`) + wave3SocialRxPatreonSuffix = newLazyRegexp(`(?i)\s*\|\s*Patreon\s*$`) + wave3SocialRxJSLink = newLazyRegexp(`(?i)(?:javascript|vbscript|data|file|blob):`) +) + +func init() { + registerWave3SocialCreatorHTMLModes() +} + +// RegisterWave3SocialCreatorHTMLModes registers all Category T Open Social & Creator HTML modes lazily. +func RegisterWave3SocialCreatorHTMLModes() { + registerWave3SocialCreatorHTMLModes() +} + +func registerWave3SocialCreatorHTMLModes() { + for _, mode := range []string{ + "threads_html", + "tumblr_html", + "farcaster_html", + "nostr_njump_html", + "product_hunt_html", + "substack_notes_html", + "patreon_public_html", + } { + m := mode + RegisterExternalHTMLModeLazy(m, func(rawHTML, baseURL string, _ func() string, extractorID string) *DeclarativePostFetchResult { + return Wave3SocialCreatorRunHTML(m, rawHTML, baseURL, extractorID) + }) + } +} + +// IsWave3SocialCreatorHTMLMode reports whether mode is one of the 7 Category T HTML modes (#394-#400). +func IsWave3SocialCreatorHTMLMode(mode string) bool { + switch mode { + case "threads_html", + "tumblr_html", + "farcaster_html", + "nostr_njump_html", + "product_hunt_html", + "substack_notes_html", + "patreon_public_html": + return true + default: + return false + } +} + +// IsWave3SocialCreatorJSONMode reports whether mode is one of the 7 Category T JSON modes (#393-#399). +func IsWave3SocialCreatorJSONMode(mode string) bool { + switch mode { + case "youtube_data_api_json", + "threads_api_json", + "tumblr_api_json", + "farcaster_hub_json", + "nostr_relay_json", + "product_hunt_json", + "beehiiv_api_json": + return true + default: + return false + } +} + +func wave3SocialDefaultExtractorID(mode string) string { + switch mode { + case "youtube_data_api_json": + return "youtube-data-api" + case "threads_api_json", "threads_html": + return "threads-api" + case "tumblr_api_json", "tumblr_html": + return "tumblr" + case "farcaster_hub_json", "farcaster_html": + return "farcaster-hub" + case "nostr_relay_json", "nostr_njump_html": + return "nostr-relays" + case "product_hunt_json", "product_hunt_html": + return "product-hunt" + case "beehiiv_api_json", "substack_notes_html": + return "substack-notes-beehiiv" + case "patreon_public_html": + return "patreon-public" + default: + return "" + } +} + +// Wave3SocialCreatorRunHTML executes a Category T HTML extractor and returns DeclarativePostFetchResult. +func Wave3SocialCreatorRunHTML(mode, rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + if !IsWave3SocialCreatorHTMLMode(mode) || len(rawHTML) == 0 || strings.IndexByte(rawHTML, '<') < 0 || strings.IndexByte(rawHTML, '>') < 0 { + return nil + } + maxHTML := wave3SocialStdHTMLMaxBytes + if mode == "tumblr_html" || mode == "substack_notes_html" || mode == "patreon_public_html" { + maxHTML = wave3SocialMaxHTMLBytes + } + if len(rawHTML) > maxHTML { + rawHTML = truncateUTF8SafeFullDocGo(rawHTML, maxHTML) + } + trimmedStart := strings.TrimLeft(rawHTML, " \t\r\n") + if trimmedStart == "" || trimmedStart[0] == '{' || trimmedStart[0] == '[' { + return nil + } + probe := rawHTML + if len(probe) > 65536 { + probe = probe[:65536] + } + probeLower := asciiLowerExtractString(probe) + urlLower := asciiLowerExtractString(baseURL) + + if !wave3SocialMatchesModePrefilter(mode, probeLower, urlLower) { + return nil + } + if wave3SocialHasCommonNegativeShell(mode, rawHTML, probeLower, urlLower) { + return nil + } + if extractorID == "" { + extractorID = wave3SocialDefaultExtractorID(mode) + } + + var res *DeclarativePostFetchResult + switch mode { + case "threads_html": + res = wave3SocialExtractThreadsHTML(rawHTML, baseURL, extractorID) + case "tumblr_html": + res = wave3SocialExtractTumblrHTML(rawHTML, baseURL, extractorID) + case "farcaster_html": + res = wave3SocialExtractFarcasterHTML(rawHTML, baseURL, extractorID) + case "nostr_njump_html": + res = wave3SocialExtractNjumpHTML(rawHTML, baseURL, extractorID) + case "product_hunt_html": + res = wave3SocialExtractProductHuntHTML(rawHTML, baseURL, extractorID) + case "substack_notes_html": + res = wave3SocialExtractSubstackNotesHTML(rawHTML, baseURL, extractorID) + case "patreon_public_html": + res = wave3SocialExtractPatreonHTML(rawHTML, baseURL, extractorID) + } + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return nil + } + return wave3SocialFinalizePostFetch(res) +} + +// RunWave3SocialCreatorHTMLMode executes a Category T HTML extractor and returns JSON-marshaled DeclarativePostFetchResult. +func RunWave3SocialCreatorHTMLMode(mode, rawHTML, baseURL string) (string, bool) { + res := Wave3SocialCreatorRunHTML(mode, rawHTML, baseURL, wave3SocialDefaultExtractorID(mode)) + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return "", false + } + res = sanitizePostFetchResultDeclHTML(res) + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return "", false + } + encoded, err := json.Marshal(res) + if err != nil { + return "", false + } + return string(encoded), true +} + +// FormatWave3SocialCreatorJSONDoc formats a Category T JSON twin payload into DeclarativeFormattedDoc. +func FormatWave3SocialCreatorJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool) { + if !IsWave3SocialCreatorJSONMode(mode) || len(raw) == 0 || len(raw) > wave3SocialMaxJSONBytes { + return nil, false + } + trimmed := bytes.TrimSpace(bytes.TrimPrefix(raw, []byte("\xEF\xBB\xBF"))) + if len(trimmed) == 0 || trimmed[0] != '{' { + return nil, false + } + parsed, ok := decodeJSONWithNumbers(trimmed) + if !ok || parsed == nil { + return nil, false + } + obj, isObj := parsed.(map[string]any) + if !isObj || wave3SocialIsGenericJSONError(obj) { + return nil, false + } + + var doc *DeclarativeFormattedDoc + var handled bool + switch mode { + case "youtube_data_api_json": + doc, handled = wave3SocialFormatYouTubeJSON(obj, origURL) + case "threads_api_json": + doc, handled = wave3SocialFormatThreadsJSON(obj, origURL) + case "tumblr_api_json": + doc, handled = wave3SocialFormatTumblrJSON(obj, origURL) + case "farcaster_hub_json": + doc, handled = wave3SocialFormatFarcasterJSON(obj, origURL) + case "nostr_relay_json": + doc, handled = wave3SocialFormatNostrJSON(obj, origURL) + case "product_hunt_json": + doc, handled = wave3SocialFormatProductHuntJSON(obj, origURL) + case "beehiiv_api_json": + doc, handled = wave3SocialFormatBeehiivJSON(obj, origURL) + } + if !handled || doc == nil || strings.TrimSpace(doc.Markdown) == "" { + return nil, false + } + return wave3SocialFinalizeDoc(doc), true +} + +// FormatWave3SocialCreatorJSONMode formats a Category T JSON payload and returns JSON-marshaled DeclarativeFormattedDoc. +func FormatWave3SocialCreatorJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool) { + doc, ok := FormatWave3SocialCreatorJSONDoc(mode, raw, params, origURL) + if !ok || doc == nil { + return "", false + } + encoded, err := json.Marshal(doc) + if err != nil { + return "", false + } + return string(encoded), true +} + +// ── Prefilters & Shared Hygiene Helpers ────────────────────────────────────────────────────────── + +func wave3SocialMatchesModePrefilter(mode, probeLower, urlLower string) bool { + switch mode { + case "threads_html": + return strings.Contains(urlLower, "threads.net") || + strings.Contains(urlLower, "threads.com") || + strings.Contains(probeLower, "threads") || + strings.Contains(probeLower, "og:title") + case "tumblr_html": + return strings.Contains(urlLower, "tumblr.com") || + strings.Contains(probeLower, "___initial_state___") || + strings.Contains(probeLower, "tumblr") + case "farcaster_html": + return strings.Contains(urlLower, "farcaster.xyz") || + strings.Contains(probeLower, "farcaster") || + strings.Contains(probeLower, "og:title") + case "nostr_njump_html": + return strings.Contains(urlLower, "njump.me") || + strings.Contains(probeLower, "njump") || + strings.Contains(probeLower, `itemprop="articlebody"`) || + strings.Contains(probeLower, `itemprop='articlebody'`) || + strings.Contains(probeLower, "nostr") + case "product_hunt_html": + return strings.Contains(urlLower, "producthunt.com") || + strings.Contains(probeLower, "producthunt") || + strings.Contains(probeLower, "product hunt") || + strings.Contains(probeLower, "__next_data__") || + strings.Contains(probeLower, "application/ld+json") + case "substack_notes_html": + return strings.Contains(urlLower, "substack.com") || + strings.Contains(probeLower, "preloads-json") || + strings.Contains(probeLower, "window._preloads") || + strings.Contains(probeLower, "substackcdn.com") || + strings.Contains(probeLower, "substack") + case "patreon_public_html": + return strings.Contains(urlLower, "patreon.com") || + strings.Contains(probeLower, "structured-data") || + strings.Contains(probeLower, "patreonusercontent.com") || + strings.Contains(probeLower, "patreon") || + strings.Contains(probeLower, "__next_f") + default: + return false + } +} + +func wave3SocialIsNegativeURL(urlLower string) bool { + if urlLower == "" { + return false + } + if strings.Contains(urlLower, "/404") || + strings.Contains(urlLower, "/not-found") || + strings.Contains(urlLower, "/page-not-found") || + strings.Contains(urlLower, "/maintenance") || + strings.Contains(urlLower, "error=true") || + strings.Contains(urlLower, "error=1") { + return true + } + pathOnly := urlLower + if idx := strings.Index(pathOnly, "://"); idx >= 0 { + rest := pathOnly[idx+3:] + if slash := strings.IndexByte(rest, '/'); slash >= 0 { + pathOnly = rest[slash:] + } else { + pathOnly = "/" + } + } + if cut := strings.IndexAny(pathOnly, "?#"); cut >= 0 { + pathOnly = pathOnly[:cut] + } + return strings.HasSuffix(pathOnly, "/error") || + strings.Contains(pathOnly, "/error/") || + strings.HasSuffix(pathOnly, "/error.html") || + strings.HasSuffix(pathOnly, "/error.htm") || + strings.HasSuffix(pathOnly, "/error.aspx") || + strings.HasSuffix(pathOnly, "/login") || + strings.Contains(pathOnly, "/login/") || + strings.HasSuffix(pathOnly, "/signin") || + strings.HasSuffix(pathOnly, "/signup") || + strings.Contains(pathOnly, "/__challenge/") +} + +func wave3SocialIsNegativeTitle(title string) bool { + t := strings.TrimSpace(title) + if t == "" { + return false + } + return wave3SocialRxNotFoundTitle.MatchString(t) || + wave3SocialRxMaintTitle.MatchString(t) || + wave3SocialRxErrorTitle.MatchString(t) +} + +func wave3SocialIsGenericTitle(title string) bool { + return wave3SocialRxGenericTitle.MatchString(strings.TrimSpace(title)) +} + +func wave3SocialContainsASCIIFold(haystack, needleLower string) bool { + n := len(needleLower) + if n == 0 { + return true + } + if len(haystack) < n { + return false + } + limit := len(haystack) - n + for i := 0; i <= limit; i++ { + matched := true + for j := 0; j < n; j++ { + hc := haystack[i+j] + if hc >= 'A' && hc <= 'Z' { + hc += 32 + } + if hc != needleLower[j] { + matched = false + break + } + } + if matched { + return true + } + } + return false +} + +func wave3SocialExtractTitleBounded(rawHTML string) string { + head := rawHTML + if len(head) > 65536 { + head = head[:65536] + } + if !wave3SocialContainsASCIIFold(head, "= 2 { + return wave3SocialCleanText(m[1]) + } + return "" +} + +func wave3SocialExtractMetaBounded(rawHTML, targetKey string) string { + head := rawHTML + if len(head) > 65536 { + head = head[:65536] + } + if !wave3SocialContainsASCIIFold(head, "
`) || + strings.Contains(probeLower, `
`) || + strings.Contains(probeLower, `
`) || + strings.Contains(probeLower, `
`) || + strings.Contains(probeLower, `
`) || + strings.Contains(probeLower, `
`) || + strings.Contains(probeLower, `
`) || + strings.Contains(probeLower, `
`) || + strings.Contains(probeLower, `
`) || + strings.Contains(probeLower, ``) + if isSpaShell && ogDesc == "" && (ogTitle == "" || wave3SocialIsGenericTitle(ogTitle)) { + return true + } + if (wave3SocialIsGenericTitle(title) || title == "") && ogDesc == "" && ogTitle == "" && + !strings.Contains(probeLower, " 0 { + if dataVal, hasData := obj["data"]; !hasData || dataVal == nil { + return true + } + } + // Tumblr meta.status >= 400 + if meta, ok := obj["meta"].(map[string]any); ok { + if st, okNum := wave3SocialToInt(meta["status"]); okNum && st >= 400 { + return true + } + } + // Neynar / Beehiiv / generic status >= 400 or errCode + if ec := strings.TrimSpace(jsonScalarToString(obj["errCode"])); ec != "" { + return true + } + if st, okNum := wave3SocialToInt(obj["status"]); okNum && st >= 400 { + return true + } + if code, okNum := wave3SocialToInt(obj["code"]); okNum && code >= 400 { + if _, hasData := obj["data"]; !hasData { + return true + } + } + if msg := strings.TrimSpace(jsonScalarToString(obj["message"])); msg != "" { + if len(obj) <= 3 { + if _, hasName := obj["name"]; !hasName { + if _, hasData := obj["data"]; !hasData { + return true + } + } + } + } + return false +} + +func wave3SocialCleanText(s string) string { + if s == "" { + return "" + } + if strings.IndexByte(s, '<') >= 0 { + s = stripTagsInlineLinear(s) + } + if strings.IndexByte(s, '&') >= 0 { + s = stdhtml.UnescapeString(s) + } + s = stripInvisibleAndNUL(s) + return strings.TrimSpace(wave3SocialRxSpace.ReplaceAllString(s, " ")) +} + +func wave3SocialPlain(v any, maxLen int) string { + s := jsonScalarToString(v) + if s == "" { + return "" + } + if strings.IndexByte(s, '<') >= 0 { + s = stripTagsInlineLinear(s) + } + if strings.IndexByte(s, '&') >= 0 { + s = stdhtml.UnescapeString(s) + } + return SanitizeSchemaPlainField(s, maxLen) +} + +func wave3SocialSanitizeUntrustedContent(raw string, maxRunes int) string { + if raw == "" { + return "" + } + s := stripInvisibleAndNUL(raw) + if strings.IndexByte(s, '<') >= 0 { + s = stripTagsInlineLinear(s) + } + if strings.IndexByte(s, '&') >= 0 { + s = stdhtml.UnescapeString(s) + } + s = wave3SocialRxJSLink.ReplaceAllString(s, "blocked:") + s = SanitizeScrapedMarkdown(s) + s = strings.TrimSpace(s) + if maxRunes > 0 { + s = sliceRunesMax(s, maxRunes) + } + return s +} + +func wave3SocialFirstNonEmpty(vals ...string) string { + for _, v := range vals { + if t := strings.TrimSpace(v); t != "" { + return t + } + } + return "" +} + +func wave3SocialToInt(v any) (int64, bool) { + switch x := v.(type) { + case json.Number: + if i, err := x.Int64(); err == nil { + return i, true + } + if f, err := x.Float64(); err == nil { + return int64(f), true + } + case float64: + return int64(x), true + case int64: + return x, true + case int: + return int64(x), true + case string: + t := strings.TrimSpace(x) + if t != "" { + if i, err := strconv.ParseInt(t, 10, 64); err == nil { + return i, true + } + } + } + return 0, false +} + +func wave3SocialFormatEpochUTC(sec int64) string { + if sec <= 0 || sec > 4102444800 { + return "" + } + return time.Unix(sec, 0).UTC().Format(time.RFC3339) +} + +func wave3SocialFormatISODuration(raw string) string { + s := strings.TrimSpace(raw) + m := wave3SocialRxISODuration.FindStringSubmatch(s) + if len(m) == 0 { + return s + } + days, _ := strconv.Atoi(m[1]) + hrs, _ := strconv.Atoi(m[2]) + mins, _ := strconv.Atoi(m[3]) + secs, _ := strconv.Atoi(m[4]) + hrs += days * 24 + if hrs > 0 { + return fmt.Sprintf("%d:%02d:%02d (%s)", hrs, mins, secs, s) + } + return fmt.Sprintf("%d:%02d (%s)", mins, secs, s) +} + +func wave3SocialAddLink(links *[]string, seen map[string]bool, raw, baseURL string) { + u := SanitizeSchemaHTTPSURL(raw, baseURL) + if u == "" || seen[u] { + return + } + seen[u] = true + *links = append(*links, u) +} + +func wave3SocialTableCell(s string, maxRunes int) string { + c := wave3SocialSanitizeUntrustedContent(s, maxRunes) + c = escapeDeclMarkdownBrackets(c) + c = strings.ReplaceAll(c, "\r", " ") + c = strings.ReplaceAll(c, "\n", " ") + c = strings.ReplaceAll(c, "|", "\\|") + return strings.TrimSpace(wave3SocialRxSpace.ReplaceAllString(c, " ")) +} + +func wave3SocialFinalizeDoc(doc *DeclarativeFormattedDoc) *DeclarativeFormattedDoc { + if doc == nil { + return nil + } + if len(doc.Records) > wave3SocialMaxRecords { + doc.Records = doc.Records[:wave3SocialMaxRecords] + tr := true + doc.Truncated = &tr + } + if len(doc.Records) > 0 && doc.Returned == nil { + ret := len(doc.Records) + doc.Returned = &ret + } + san, ok := sanitizeDeclarativeFormattedDocGo(doc) + if !ok { + return nil + } + return san +} + +func wave3SocialFinalizePostFetch(res *DeclarativePostFetchResult) *DeclarativePostFetchResult { + if res == nil { + return nil + } + if len(res.Records) > wave3SocialMaxRecords { + res.Records = res.Records[:wave3SocialMaxRecords] + tr := true + res.Truncated = &tr + } + if len(res.Records) > 0 && res.Returned == nil { + ret := len(res.Records) + res.Returned = &ret + } + return sanitizePostFetchResultDeclHTML(res) +} + +func wave3SocialExtractBalancedJSON(src string, startIdx int) (string, int, bool) { + if startIdx < 0 || startIdx >= len(src) { + return "", -1, false + } + open := src[startIdx] + var closeCh byte + if open == '{' { + closeCh = '}' + } else if open == '[' { + closeCh = ']' + } else { + return "", -1, false + } + depth := 0 + inStr := false + escaped := false + for i := startIdx; i < len(src); i++ { + c := src[i] + if inStr { + if escaped { + escaped = false + continue + } + if c == '\\' { + escaped = true + continue + } + if c == '"' { + inStr = false + } + continue + } + if c == '"' { + inStr = true + continue + } + if c == open { + depth++ + } else if c == closeCh { + depth-- + if depth == 0 { + return src[startIdx : i+1], i + 1, true + } + } + } + return "", -1, false +} + +func wave3SocialExtractScriptByID(rawHTML, targetID string) string { + if !wave3SocialContainsASCIIFold(rawHTML, targetID) { + return "" + } + found := "" + replaceHTMLTagBlocksLinearFullDocGo(rawHTML, "script", func(_, attrStr, inner string) string { + if found == "" && strings.EqualFold(parseTagAttrsFullDocGo(attrStr)["id"], targetID) { + found = inner + } + return "" + }, maxHTMLScanCharsFullDocGo) + return strings.TrimSpace(found) +} + +// ── #393 YouTube Data API v3 (`youtube_data_api_json`) ─────────────────────────────────────────── + +func wave3SocialFormatYouTubeJSON(obj map[string]any, origURL string) (*DeclarativeFormattedDoc, bool) { + items, _ := obj["items"].([]any) + if len(items) == 0 { + return nil, false + } + kind := wave3SocialPlain(obj["kind"], 80) + nextToken := wave3SocialPlain(obj["nextPageToken"], 120) + + var recs []map[string]any + var rows [][]string + var links []string + seenLinks := make(map[string]bool) + + type ytParsed struct { + id string + itemType string + title string + channelTitle string + channelID string + publishedAt string + description string + duration string + views string + likes string + comments string + subs string + videos string + itemCount string + customURL string + canonicalURL string + tags []string + } + var parsedItems []ytParsed + + for _, rawIt := range items { + if len(parsedItems) >= wave3SocialMaxRecords { + break + } + it, ok := rawIt.(map[string]any) + if !ok { + continue + } + snippet, _ := it["snippet"].(map[string]any) + stats, _ := it["statistics"].(map[string]any) + cd, _ := it["contentDetails"].(map[string]any) + + itemKind := wave3SocialPlain(it["kind"], 64) + var itemID, itemType, canonURL string + switch idVal := it["id"].(type) { + case string: + itemID = SanitizeSchemaPlainField(idVal, 80) + case map[string]any: + srKind := wave3SocialPlain(idVal["kind"], 64) + if vid := wave3SocialPlain(idVal["videoId"], 40); vid != "" { + itemID = vid + itemType = "video" + canonURL = "https://www.youtube.com/watch?v=" + url.QueryEscape(vid) + } else if cid := wave3SocialPlain(idVal["channelId"], 40); cid != "" { + itemID = cid + itemType = "channel" + canonURL = "https://www.youtube.com/channel/" + url.PathEscape(cid) + } else if pid := wave3SocialPlain(idVal["playlistId"], 64); pid != "" { + itemID = pid + itemType = "playlist" + canonURL = "https://www.youtube.com/playlist?list=" + url.QueryEscape(pid) + } else { + itemType = srKind + } + } + if itemType == "" { + switch { + case strings.Contains(itemKind, "channel") || strings.Contains(kind, "channel"): + itemType = "channel" + if itemID != "" { + canonURL = "https://www.youtube.com/channel/" + url.PathEscape(itemID) + } + case strings.Contains(itemKind, "playlist") || strings.Contains(kind, "playlist"): + itemType = "playlist" + if itemID != "" { + canonURL = "https://www.youtube.com/playlist?list=" + url.QueryEscape(itemID) + } + default: + itemType = "video" + if itemID != "" { + canonURL = "https://www.youtube.com/watch?v=" + url.QueryEscape(itemID) + } + } + } + + title := wave3SocialPlain(snippet["title"], 240) + if title == "" && itemID == "" { + continue + } + chTitle := wave3SocialPlain(snippet["channelTitle"], 120) + chID := wave3SocialPlain(snippet["channelId"], 64) + pub := wave3SocialPlain(snippet["publishedAt"], 48) + desc := wave3SocialPlain(snippet["description"], 2000) + dur := "" + if cd != nil { + if rawDur := wave3SocialPlain(cd["duration"], 32); rawDur != "" { + dur = rawDur + } + } + views := wave3SocialPlain(stats["viewCount"], 32) + likes := wave3SocialPlain(stats["likeCount"], 32) + comments := wave3SocialPlain(stats["commentCount"], 32) + subs := wave3SocialPlain(stats["subscriberCount"], 32) + vidCount := wave3SocialPlain(stats["videoCount"], 32) + itemCount := wave3SocialPlain(cd["itemCount"], 32) + customURL := wave3SocialPlain(snippet["customUrl"], 80) + + var tags []string + if rawTags, ok := snippet["tags"].([]any); ok { + for _, t := range rawTags { + if len(tags) >= 12 { + break + } + if ts := wave3SocialPlain(t, 48); ts != "" { + tags = append(tags, ts) + } + } + } + + p := ytParsed{ + id: itemID, + itemType: itemType, + title: wave3SocialFirstNonEmpty(title, itemID), + channelTitle: chTitle, + channelID: chID, + publishedAt: pub, + description: desc, + duration: dur, + views: views, + likes: likes, + comments: comments, + subs: subs, + videos: vidCount, + itemCount: itemCount, + customURL: customURL, + canonicalURL: canonURL, + tags: tags, + } + parsedItems = append(parsedItems, p) + + rec := map[string]any{"type": itemType, "title": p.title} + if itemID != "" { + rec["id"] = itemID + } + if chTitle != "" { + rec["channelTitle"] = chTitle + } + if chID != "" { + rec["channelId"] = chID + } + if pub != "" { + rec["publishedAt"] = pub + } + if dur != "" { + rec["duration"] = dur + } + if views != "" { + rec["viewCount"] = views + } + if likes != "" { + rec["likeCount"] = likes + } + if subs != "" { + rec["subscriberCount"] = subs + } + if canonURL != "" { + rec["url"] = canonURL + wave3SocialAddLink(&links, seenLinks, canonURL, origURL) + } + recs = append(recs, rec) + + metric := "-" + if views != "" { + metric = views + " views" + } else if subs != "" { + metric = subs + " subscribers" + } else if itemCount != "" { + metric = itemCount + " items" + } + rows = append(rows, []string{ + wave3SocialTableCell(p.title, 100), + escapeDeclMarkdownBrackets(itemType), + wave3SocialFirstNonEmpty(wave3SocialTableCell(chTitle, 60), "-"), + wave3SocialFirstNonEmpty(escapeDeclMarkdownBrackets(pub), "-"), + escapeDeclMarkdownBrackets(metric), + }) + } + + if len(parsedItems) == 0 { + return nil, false + } + + var totalPtr *int + if pageInfo, ok := obj["pageInfo"].(map[string]any); ok { + if tr, okNum := wave3SocialToInt(pageInfo["totalResults"]); okNum && tr >= 0 { + tv := int(tr) + totalPtr = &tv + } + } + + if len(parsedItems) == 1 { + p := parsedItems[0] + var bullets []string + if p.id != "" { + bullets = append(bullets, "- **ID**: "+escapeDeclMarkdownBrackets(p.id)) + } + bullets = append(bullets, "- **Type**: "+escapeDeclMarkdownBrackets(p.itemType)) + if p.channelTitle != "" { + bullets = append(bullets, "- **Channel**: "+escapeDeclMarkdownBrackets(p.channelTitle)) + } + if p.customURL != "" { + bullets = append(bullets, "- **Handle**: "+escapeDeclMarkdownBrackets(p.customURL)) + } + if p.publishedAt != "" { + bullets = append(bullets, "- **Published**: "+escapeDeclMarkdownBrackets(p.publishedAt)) + } + if p.duration != "" { + bullets = append(bullets, "- **Duration**: "+escapeDeclMarkdownBrackets(wave3SocialFormatISODuration(p.duration))) + } + if p.views != "" { + bullets = append(bullets, "- **Views**: "+escapeDeclMarkdownBrackets(p.views)) + } + if p.likes != "" { + bullets = append(bullets, "- **Likes**: "+escapeDeclMarkdownBrackets(p.likes)) + } + if p.comments != "" { + bullets = append(bullets, "- **Comments**: "+escapeDeclMarkdownBrackets(p.comments)) + } + if p.subs != "" { + bullets = append(bullets, "- **Subscribers**: "+escapeDeclMarkdownBrackets(p.subs)) + } + if p.videos != "" { + bullets = append(bullets, "- **Videos**: "+escapeDeclMarkdownBrackets(p.videos)) + } + if p.itemCount != "" { + bullets = append(bullets, "- **Items**: "+escapeDeclMarkdownBrackets(p.itemCount)) + } + if len(p.tags) > 0 { + bullets = append(bullets, "- **Tags**: "+escapeDeclMarkdownBrackets(strings.Join(p.tags, ", "))) + } + if p.canonicalURL != "" { + bullets = append(bullets, "- **URL**: "+escapeDeclMarkdownBrackets(p.canonicalURL)) + } + blocks := []string{"# " + escapeDeclMarkdownBrackets(p.title), strings.Join(bullets, "\n")} + if p.description != "" { + blocks = append(blocks, "## Description\n\n"+escapeDeclPlainTextPreservingNewlines(p.description)) + } + return &DeclarativeFormattedDoc{ + Title: p.title, + Description: sliceRunesMax(p.description, 260), + Author: p.channelTitle, + PublishedTime: p.publishedAt, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: recs, + Total: totalPtr, + NextCursor: nextToken, + }, true + } + + title := "YouTube Data API Results" + if strings.Contains(kind, "search") { + title = "YouTube Search Results" + } else if strings.Contains(kind, "channel") { + title = "YouTube Channels" + } else if strings.Contains(kind, "playlist") { + title = "YouTube Playlists" + } + md := "# " + escapeDeclMarkdownBrackets(title) + "\n\n" + formatDeclarativeGFMTable([]string{"Title", "Type", "Channel", "Published", "Stats"}, rows) + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: md, + Links: links, + Records: recs, + Total: totalPtr, + NextCursor: nextToken, + }, true +} + +// ── #394 Threads API & HTML (`threads_api_json` / `threads_html`) ──────────────────────────────── + +func wave3SocialFormatThreadsJSON(obj map[string]any, origURL string) (*DeclarativeFormattedDoc, bool) { + // List endpoint (/v1.0/me/threads, /replies, /conversation, /keyword_search) + if dataArr, ok := obj["data"].([]any); ok { + if len(dataArr) == 0 { + return nil, false + } + var recs []map[string]any + var rows [][]string + var links []string + seenLinks := make(map[string]bool) + + for _, rawItem := range dataArr { + if len(recs) >= wave3SocialMaxRecords { + break + } + it, ok := rawItem.(map[string]any) + if !ok { + continue + } + id := wave3SocialPlain(it["id"], 64) + user := wave3SocialPlain(it["username"], 80) + text := wave3SocialSanitizeUntrustedContent(jsonScalarToString(it["text"]), 600) + mType := wave3SocialPlain(it["media_type"], 40) + ts := wave3SocialPlain(it["timestamp"], 48) + perm := SanitizeSchemaHTTPSURL(jsonScalarToString(it["permalink"]), origURL) + if id == "" && text == "" && user == "" { + continue + } + rec := map[string]any{} + if id != "" { + rec["id"] = id + } + if user != "" { + rec["username"] = user + } + if text != "" { + rec["text"] = text + } + if mType != "" { + rec["mediaType"] = mType + } + if ts != "" { + rec["timestamp"] = ts + } + if perm != "" { + rec["url"] = perm + wave3SocialAddLink(&links, seenLinks, perm, origURL) + } + recs = append(recs, rec) + rows = append(rows, []string{ + wave3SocialFirstNonEmpty(escapeDeclMarkdownBrackets(user), escapeDeclMarkdownBrackets(id), "-"), + wave3SocialFirstNonEmpty(wave3SocialTableCell(text, 160), "-"), + wave3SocialFirstNonEmpty(escapeDeclMarkdownBrackets(mType), "-"), + wave3SocialFirstNonEmpty(escapeDeclMarkdownBrackets(ts), "-"), + }) + } + if len(recs) == 0 { + return nil, false + } + nextCur := "" + if paging, ok := obj["paging"].(map[string]any); ok { + if cursors, ok := paging["cursors"].(map[string]any); ok { + nextCur = wave3SocialPlain(cursors["after"], 160) + } + } + title := "Threads Posts" + md := "# " + title + "\n\n" + formatDeclarativeGFMTable([]string{"Author", "Text", "Media Type", "Timestamp"}, rows) + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: md, + Links: links, + Records: recs, + NextCursor: nextCur, + }, true + } + + // Single profile or thread object + id := wave3SocialPlain(obj["id"], 64) + username := wave3SocialPlain(obj["username"], 80) + name := wave3SocialPlain(obj["name"], 120) + bio := wave3SocialSanitizeUntrustedContent(jsonScalarToString(obj["threads_biography"]), 1000) + text := wave3SocialSanitizeUntrustedContent(jsonScalarToString(obj["text"]), 2000) + mType := wave3SocialPlain(obj["media_type"], 40) + ts := wave3SocialPlain(obj["timestamp"], 48) + perm := SanitizeSchemaHTTPSURL(jsonScalarToString(obj["permalink"]), origURL) + shortcode := wave3SocialPlain(obj["shortcode"], 48) + + if id == "" && username == "" && text == "" && bio == "" { + return nil, false + } + + var links []string + seenLinks := make(map[string]bool) + if perm != "" { + wave3SocialAddLink(&links, seenLinks, perm, origURL) + } + if mediaURL := SanitizeSchemaHTTPSURL(jsonScalarToString(obj["media_url"]), origURL); mediaURL != "" { + wave3SocialAddLink(&links, seenLinks, mediaURL, origURL) + } + + var title string + if text != "" { + if username != "" { + title = "@" + username + " on Threads" + } else { + title = sliceRunesMax(text, 90) + } + } else { + title = wave3SocialFirstNonEmpty(name, "@"+username, "Threads Profile "+id) + } + + var bullets []string + rec := map[string]any{} + if id != "" { + bullets = append(bullets, "- **ID**: "+escapeDeclMarkdownBrackets(id)) + rec["id"] = id + } + if username != "" { + bullets = append(bullets, "- **Username**: @"+escapeDeclMarkdownBrackets(username)) + rec["username"] = username + } + if name != "" { + bullets = append(bullets, "- **Name**: "+escapeDeclMarkdownBrackets(name)) + rec["name"] = name + } + if mType != "" { + bullets = append(bullets, "- **Media Type**: "+escapeDeclMarkdownBrackets(mType)) + rec["mediaType"] = mType + } + if shortcode != "" { + bullets = append(bullets, "- **Shortcode**: "+escapeDeclMarkdownBrackets(shortcode)) + rec["shortcode"] = shortcode + } + if ts != "" { + bullets = append(bullets, "- **Timestamp**: "+escapeDeclMarkdownBrackets(ts)) + rec["timestamp"] = ts + } + if perm != "" { + bullets = append(bullets, "- **Permalink**: "+escapeDeclMarkdownBrackets(perm)) + rec["url"] = perm + } + if bio != "" { + rec["biography"] = bio + } + if text != "" { + rec["text"] = text + } + + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + if text != "" { + blocks = append(blocks, "## Post\n\n"+escapeDeclPlainTextPreservingNewlines(text)) + } + if bio != "" { + blocks = append(blocks, "## Biography\n\n"+escapeDeclPlainTextPreservingNewlines(bio)) + } + + return &DeclarativeFormattedDoc{ + Title: title, + Description: sliceRunesMax(wave3SocialFirstNonEmpty(text, bio), 260), + Author: wave3SocialFirstNonEmpty(name, username), + PublishedTime: ts, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: []map[string]any{rec}, + }, true +} + +func wave3SocialExtractThreadsHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + ldObjs := extractJSONLDObjectsDeclHTML(rawHTML, 16) + ogTitle := SanitizeSchemaPlainField(wave3SocialExtractMetaBounded(rawHTML, "og:title"), 240) + ogDesc := SanitizeSchemaPlainField(wave3SocialExtractMetaBounded(rawHTML, "og:description"), 1600) + metaDesc := SanitizeSchemaPlainField(wave3SocialExtractMetaBounded(rawHTML, "description"), 1000) + titleTag := wave3SocialExtractTitleBounded(rawHTML) + + title := wave3SocialFirstNonEmpty(ogTitle, titleTag) + if title != "" && (wave3SocialIsNegativeTitle(title) || wave3SocialIsGenericTitle(title)) { + title = "" + } + + var ldAuthor, ldBody, ldDate string + for _, ld := range ldObjs { + if tp := wave3SocialPlain(ld["@type"], 40); tp == "SocialMediaPosting" || tp == "DiscussionForumPosting" || tp == "ProfilePage" || tp == "Person" { + ldBody = wave3SocialFirstNonEmpty(ldBody, wave3SocialPlain(ld["articleBody"], 2000), wave3SocialPlain(ld["text"], 2000), wave3SocialPlain(ld["description"], 1600)) + ldDate = wave3SocialFirstNonEmpty(ldDate, wave3SocialPlain(ld["datePublished"], 48)) + if aMap, ok := ld["author"].(map[string]any); ok { + ldAuthor = wave3SocialFirstNonEmpty(ldAuthor, wave3SocialPlain(aMap["name"], 120), wave3SocialPlain(aMap["alternateName"], 80)) + } + if me, ok := ld["mainEntity"].(map[string]any); ok { + ldAuthor = wave3SocialFirstNonEmpty(ldAuthor, wave3SocialPlain(me["name"], 120), wave3SocialPlain(me["alternateName"], 80)) + ldBody = wave3SocialFirstNonEmpty(ldBody, wave3SocialPlain(me["description"], 1600)) + } + if title == "" { + title = wave3SocialPlain(ld["headline"], 240) + } + } + } + + body := wave3SocialFirstNonEmpty(ldBody, ogDesc, metaDesc) + if title == "" || body == "" { + return nil + } + + var links []string + seenLinks := make(map[string]bool) + if ogURL := wave3SocialExtractMetaBounded(rawHTML, "og:url"); ogURL != "" { + wave3SocialAddLink(&links, seenLinks, ogURL, baseURL) + } + + rec := map[string]any{"title": title, "content": body} + if ldAuthor != "" { + rec["author"] = ldAuthor + } + if ldDate != "" { + rec["publishedTime"] = ldDate + } + + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if ldAuthor != "" || ldDate != "" { + var bullets []string + if ldAuthor != "" { + bullets = append(bullets, "- **Author**: "+escapeDeclMarkdownBrackets(ldAuthor)) + } + if ldDate != "" { + bullets = append(bullets, "- **Published**: "+escapeDeclMarkdownBrackets(ldDate)) + } + blocks = append(blocks, strings.Join(bullets, "\n")) + } + blocks = append(blocks, escapeDeclPlainTextPreservingNewlines(body)) + + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: sliceRunesMax(body, 260), + Author: ldAuthor, + PublishedTime: ldDate, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: []map[string]any{rec}, + } +} + +// ── #395 Tumblr API & HTML (`tumblr_api_json` / `tumblr_html`) ─────────────────────────────────── + +func wave3SocialFormatTumblrJSON(obj map[string]any, origURL string) (*DeclarativeFormattedDoc, bool) { + resp, ok := obj["response"].(map[string]any) + if !ok || len(resp) == 0 { + return nil, false + } + + blog, _ := resp["blog"].(map[string]any) + blogTitle := wave3SocialPlain(blog["title"], 200) + blogName := wave3SocialPlain(blog["name"], 80) + blogDesc := wave3SocialPlain(blog["description"], 1000) + blogURL := SanitizeSchemaHTTPSURL(jsonScalarToString(blog["url"]), origURL) + totalPosts, hasTotal := wave3SocialToInt(wave3SocialFirstNonEmpty(jsonScalarToString(resp["total_posts"]), jsonScalarToString(blog["posts"]))) + + posts, _ := resp["posts"].([]any) + if len(posts) == 0 && blogTitle == "" && blogName == "" { + return nil, false + } + + var links []string + seenLinks := make(map[string]bool) + if blogURL != "" { + wave3SocialAddLink(&links, seenLinks, blogURL, origURL) + } + + var recs []map[string]any + var rows [][]string + var singlePostMD, singleTitle, singleDate string + + for idx, rawPost := range posts { + if len(recs) >= wave3SocialMaxRecords { + break + } + p, ok := rawPost.(map[string]any) + if !ok { + continue + } + pid := wave3SocialFirstNonEmpty(wave3SocialPlain(p["id_string"], 48), wave3SocialPlain(p["id"], 48)) + pType := wave3SocialPlain(p["type"], 32) + pBlog := wave3SocialFirstNonEmpty(wave3SocialPlain(p["blog_name"], 80), blogName) + pDate := wave3SocialPlain(p["date"], 48) + if pDate == "" { + if ts, okTs := wave3SocialToInt(p["timestamp"]); okTs { + pDate = wave3SocialFormatEpochUTC(ts) + } + } + pURL := SanitizeSchemaHTTPSURL(jsonScalarToString(p["post_url"]), origURL) + if pURL != "" { + wave3SocialAddLink(&links, seenLinks, pURL, origURL) + } + pTitle := wave3SocialFirstNonEmpty( + wave3SocialPlain(p["title"], 200), + wave3SocialPlain(p["summary"], 200), + ) + pBody := wave3SocialSanitizeUntrustedContent(wave3SocialFirstNonEmpty( + jsonScalarToString(p["body"]), + jsonScalarToString(p["caption"]), + jsonScalarToString(p["text"]), + wave3SocialExtractTumblrNPFText(p), + jsonScalarToString(p["summary"]), + ), 2000) + noteCount := wave3SocialPlain(p["note_count"], 24) + + var tags []string + if rawTags, ok := p["tags"].([]any); ok { + for _, t := range rawTags { + if len(tags) >= 8 { + break + } + if ts := wave3SocialPlain(t, 48); ts != "" { + tags = append(tags, ts) + } + } + } + + if pTitle == "" && pBody != "" { + pTitle = sliceRunesMax(pBody, 90) + } + if pTitle == "" && pid == "" { + continue + } + + rec := map[string]any{"title": wave3SocialFirstNonEmpty(pTitle, "Tumblr Post "+pid)} + if pid != "" { + rec["id"] = pid + } + if pBlog != "" { + rec["blog"] = pBlog + } + if pType != "" { + rec["type"] = pType + } + if pDate != "" { + rec["date"] = pDate + } + if noteCount != "" { + rec["noteCount"] = noteCount + } + if pURL != "" { + rec["url"] = pURL + } + if len(tags) > 0 { + rec["tags"] = tags + } + recs = append(recs, rec) + + rows = append(rows, []string{ + wave3SocialTableCell(wave3SocialFirstNonEmpty(pTitle, pid), 90), + wave3SocialFirstNonEmpty(escapeDeclMarkdownBrackets(pType), "-"), + wave3SocialFirstNonEmpty(escapeDeclMarkdownBrackets(pDate), "-"), + wave3SocialFirstNonEmpty(escapeDeclMarkdownBrackets(noteCount), "-"), + }) + if idx == 0 { + singleTitle = wave3SocialFirstNonEmpty(pTitle, blogTitle, pBlog) + singleDate = pDate + singlePostMD = pBody + } + } + + if len(recs) == 0 && blogTitle == "" { + return nil, false + } + + var totalPtr *int + if hasTotal && totalPosts >= 0 { + tv := int(totalPosts) + totalPtr = &tv + } + + if len(recs) == 1 && singlePostMD != "" { + var bullets []string + if blogTitle != "" || blogName != "" { + bullets = append(bullets, "- **Blog**: "+escapeDeclMarkdownBrackets(wave3SocialFirstNonEmpty(blogTitle, blogName))) + } + if singleDate != "" { + bullets = append(bullets, "- **Published**: "+escapeDeclMarkdownBrackets(singleDate)) + } + if nc, _ := recs[0]["noteCount"].(string); nc != "" { + bullets = append(bullets, "- **Notes**: "+escapeDeclMarkdownBrackets(nc)) + } + blocks := []string{"# " + escapeDeclMarkdownBrackets(singleTitle)} + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + blocks = append(blocks, escapeDeclPlainTextPreservingNewlines(singlePostMD)) + return &DeclarativeFormattedDoc{ + Title: singleTitle, + Description: sliceRunesMax(singlePostMD, 260), + Author: wave3SocialFirstNonEmpty(blogTitle, blogName), + PublishedTime: singleDate, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: recs, + Total: totalPtr, + }, true + } + + title := wave3SocialFirstNonEmpty(blogTitle, blogName, "Tumblr Blog") + var blocks []string + blocks = append(blocks, "# "+escapeDeclMarkdownBrackets(title)) + var metaBullets []string + if blogName != "" { + metaBullets = append(metaBullets, "- **Blog Name**: "+escapeDeclMarkdownBrackets(blogName)) + } + if blogURL != "" { + metaBullets = append(metaBullets, "- **URL**: "+escapeDeclMarkdownBrackets(blogURL)) + } + if blogDesc != "" { + metaBullets = append(metaBullets, "- **Description**: "+escapeDeclMarkdownBrackets(blogDesc)) + } + if len(metaBullets) > 0 { + blocks = append(blocks, strings.Join(metaBullets, "\n")) + } + if len(rows) > 0 { + blocks = append(blocks, "## Posts\n\n"+formatDeclarativeGFMTable([]string{"Post", "Type", "Date", "Notes"}, rows)) + } + + return &DeclarativeFormattedDoc{ + Title: title, + Description: sliceRunesMax(blogDesc, 260), + Author: wave3SocialFirstNonEmpty(blogTitle, blogName), + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: recs, + Total: totalPtr, + }, true +} + +func wave3SocialExtractTumblrNPFText(post map[string]any) string { + var parts []string + if content, ok := post["content"].([]any); ok { + for _, rawBlock := range content { + if b, ok := rawBlock.(map[string]any); ok { + if txt := wave3SocialPlain(b["text"], 800); txt != "" { + parts = append(parts, txt) + } + } + } + } + if trail, ok := post["trail"].([]any); ok && len(parts) == 0 { + for _, rawTr := range trail { + if tr, ok := rawTr.(map[string]any); ok { + if txt := wave3SocialPlain(tr["content_raw"], 800); txt != "" { + parts = append(parts, txt) + } else if txt := wave3SocialPlain(tr["content"], 800); txt != "" { + parts = append(parts, txt) + } + } + } + } + return strings.Join(parts, "\n\n") +} + +func wave3SocialExtractTumblrHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + var stateObj map[string]any + if idx := strings.Index(rawHTML, "___INITIAL_STATE___"); idx >= 0 { + if eqIdx := strings.IndexByte(rawHTML[idx:], '='); eqIdx >= 0 { + braceRel := strings.IndexByte(rawHTML[idx+eqIdx:], '{') + if braceRel >= 0 { + if jsonStr, _, ok := wave3SocialExtractBalancedJSON(rawHTML, idx+eqIdx+braceRel); ok { + if parsed, okDec := decodeJSONWithNumbers([]byte(jsonStr)); okDec { + stateObj, _ = parsed.(map[string]any) + } + } + } + } + } + + ogTitle := wave3SocialRxTumblrSuffix.ReplaceAllString(SanitizeSchemaPlainField(wave3SocialExtractMetaBounded(rawHTML, "og:title"), 240), "") + ogDesc := SanitizeSchemaPlainField(wave3SocialExtractMetaBounded(rawHTML, "og:description"), 1600) + rawTitleTag := wave3SocialRxTumblrSuffix.ReplaceAllString(wave3SocialExtractTitleBounded(rawHTML), "") + + var blogTitle, blogName, blogDesc string + var recs []map[string]any + var rows [][]string + var links []string + seenLinks := make(map[string]bool) + + if ogURL := wave3SocialExtractMetaBounded(rawHTML, "og:url"); ogURL != "" { + wave3SocialAddLink(&links, seenLinks, ogURL, baseURL) + } + + if stateObj != nil { + // Look into PeeprRoute or Blog or queries + if peepr, ok := stateObj["PeeprRoute"].(map[string]any); ok { + if b, ok := peepr["blog"].(map[string]any); ok { + blogTitle = wave3SocialFirstNonEmpty(blogTitle, wave3SocialPlain(b["title"], 200)) + blogName = wave3SocialFirstNonEmpty(blogName, wave3SocialPlain(b["name"], 80)) + blogDesc = wave3SocialFirstNonEmpty(blogDesc, wave3SocialPlain(b["description"], 1000)) + } + if post, ok := peepr["post"].(map[string]any); ok { + pid := wave3SocialFirstNonEmpty(wave3SocialPlain(post["idString"], 48), wave3SocialPlain(post["id"], 48)) + pTitle := wave3SocialFirstNonEmpty(wave3SocialPlain(post["title"], 200), wave3SocialPlain(post["summary"], 200), ogTitle) + pBody := wave3SocialSanitizeUntrustedContent(wave3SocialFirstNonEmpty( + wave3SocialExtractTumblrNPFText(post), + jsonScalarToString(post["body"]), + ogDesc, + ), 2000) + pDate := wave3SocialPlain(post["date"], 48) + if pDate == "" { + if ts, okTs := wave3SocialToInt(post["timestamp"]); okTs { + pDate = wave3SocialFormatEpochUTC(ts) + } + } + if pTitle != "" || pBody != "" { + rec := map[string]any{"title": wave3SocialFirstNonEmpty(pTitle, "Tumblr Post")} + if pid != "" { + rec["id"] = pid + } + if pDate != "" { + rec["date"] = pDate + } + if pBody != "" { + rec["summary"] = sliceRunesMax(pBody, 300) + } + recs = append(recs, rec) + rows = append(rows, []string{wave3SocialTableCell(wave3SocialFirstNonEmpty(pTitle, pid), 100), wave3SocialFirstNonEmpty(escapeDeclMarkdownBrackets(pDate), "-")}) + } + } + if tl, ok := peepr["timeline"].(map[string]any); ok { + if elems, ok := tl["elements"].([]any); ok { + for _, rawEl := range elems { + if len(recs) >= wave3SocialMaxRecords { + break + } + el, ok := rawEl.(map[string]any) + if !ok { + continue + } + pid := wave3SocialFirstNonEmpty(wave3SocialPlain(el["idString"], 48), wave3SocialPlain(el["id"], 48)) + pSummary := wave3SocialFirstNonEmpty(wave3SocialPlain(el["summary"], 180), wave3SocialPlain(wave3SocialExtractTumblrNPFText(el), 180)) + pDate := wave3SocialPlain(el["date"], 48) + pURL := SanitizeSchemaHTTPSURL(jsonScalarToString(el["postUrl"]), baseURL) + if pSummary == "" && pid == "" { + continue + } + rec := map[string]any{"title": wave3SocialFirstNonEmpty(pSummary, "Post "+pid)} + if pid != "" { + rec["id"] = pid + } + if pDate != "" { + rec["date"] = pDate + } + if pURL != "" { + rec["url"] = pURL + wave3SocialAddLink(&links, seenLinks, pURL, baseURL) + } + recs = append(recs, rec) + rows = append(rows, []string{wave3SocialTableCell(wave3SocialFirstNonEmpty(pSummary, pid), 110), wave3SocialFirstNonEmpty(escapeDeclMarkdownBrackets(pDate), "-")}) + } + } + } + } + if blogMap, ok := stateObj["Blog"].(map[string]any); ok && blogTitle == "" { + if blogs, ok := blogMap["blogs"].(map[string]any); ok { + for _, bv := range blogs { + if bm, ok := bv.(map[string]any); ok { + blogTitle = wave3SocialFirstNonEmpty(blogTitle, wave3SocialPlain(bm["title"], 200)) + blogName = wave3SocialFirstNonEmpty(blogName, wave3SocialPlain(bm["name"], 80)) + blogDesc = wave3SocialFirstNonEmpty(blogDesc, wave3SocialPlain(bm["description"], 1000)) + break + } + } + } + } + } + + title := wave3SocialFirstNonEmpty(blogTitle, ogTitle, rawTitleTag) + if title != "" && (wave3SocialIsNegativeTitle(title) || wave3SocialIsGenericTitle(title)) { + title = "" + } + desc := wave3SocialFirstNonEmpty(blogDesc, ogDesc) + if title == "" && len(recs) == 0 { + return nil + } + if title == "" { + title = "Tumblr" + } + if desc == "" && len(recs) == 0 { + return nil + } + + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if blogName != "" { + blocks = append(blocks, "- **Blog**: "+escapeDeclMarkdownBrackets(blogName)) + } + if desc != "" { + blocks = append(blocks, escapeDeclPlainTextPreservingNewlines(desc)) + } + if len(rows) > 0 { + blocks = append(blocks, "## Posts\n\n"+formatDeclarativeGFMTable([]string{"Post", "Date"}, rows)) + } + if len(recs) == 0 && desc != "" { + recs = append(recs, map[string]any{"title": title, "description": desc}) + } + + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: sliceRunesMax(desc, 260), + Author: wave3SocialFirstNonEmpty(blogName, blogTitle), + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: recs, + } +} + +// ── #396 Farcaster Hub & HTML (`farcaster_hub_json` / `farcaster_html`) ────────────────────────── + +func wave3SocialFormatFarcasterTS(raw any) string { + v, ok := wave3SocialToInt(raw) + if !ok || v <= 0 { + return "" + } + // Hubble timestamps use Farcaster epoch (seconds since 2021-01-01T00:00:00Z = 1609459200). + // Fnames / Unix timestamps are already >= 1500000000. + if v < 1_000_000_000 { + v += 1609459200 + } + return wave3SocialFormatEpochUTC(v) +} + +func wave3SocialFormatFarcasterJSON(obj map[string]any, origURL string) (*DeclarativeFormattedDoc, bool) { + // 1. fnames.farcaster.xyz/transfers + if transfers, ok := obj["transfers"].([]any); ok { + if len(transfers) == 0 { + return nil, false + } + var recs []map[string]any + var rows [][]string + for _, rawTr := range transfers { + if len(recs) >= wave3SocialMaxRecords { + break + } + tr, ok := rawTr.(map[string]any) + if !ok { + continue + } + uname := wave3SocialPlain(tr["username"], 80) + owner := wave3SocialPlain(tr["owner"], 64) + toFid := wave3SocialPlain(tr["to"], 32) + ts := wave3SocialFormatFarcasterTS(tr["timestamp"]) + id := wave3SocialPlain(tr["id"], 32) + if uname == "" && toFid == "" { + continue + } + rec := map[string]any{"username": uname} + if id != "" { + rec["id"] = id + } + if toFid != "" { + rec["fid"] = toFid + } + if owner != "" { + rec["owner"] = owner + } + if ts != "" { + rec["timestamp"] = ts + } + recs = append(recs, rec) + rows = append(rows, []string{ + wave3SocialFirstNonEmpty(escapeDeclMarkdownBrackets(uname), "-"), + wave3SocialFirstNonEmpty(escapeDeclMarkdownBrackets(toFid), "-"), + wave3SocialFirstNonEmpty(escapeDeclMarkdownBrackets(owner), "-"), + wave3SocialFirstNonEmpty(escapeDeclMarkdownBrackets(ts), "-"), + }) + } + if len(recs) == 0 { + return nil, false + } + title := "Farcaster Name Transfers" + md := "# " + title + "\n\n" + formatDeclarativeGFMTable([]string{"Username", "FID", "Owner", "Timestamp"}, rows) + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: md, + Records: recs, + }, true + } + + // 2. Hubble messages[] or single Message object (data + hash) + var messages []any + if arr, ok := obj["messages"].([]any); ok { + messages = arr + } else if _, hasData := obj["data"].(map[string]any); hasData { + messages = []any{obj} + } + if len(messages) == 0 { + return nil, false + } + + var recs []map[string]any + var rows [][]string + var links []string + seenLinks := make(map[string]bool) + + for _, rawMsg := range messages { + if len(recs) >= wave3SocialMaxRecords { + break + } + msg, ok := rawMsg.(map[string]any) + if !ok { + continue + } + data, _ := msg["data"].(map[string]any) + if data == nil { + continue + } + hash := wave3SocialPlain(msg["hash"], 80) + fid := wave3SocialPlain(data["fid"], 32) + msgType := wave3SocialPlain(data["type"], 64) + ts := wave3SocialFormatFarcasterTS(data["timestamp"]) + + var text, fieldType string + if castBody, ok := data["castAddBody"].(map[string]any); ok { + text = wave3SocialSanitizeUntrustedContent(jsonScalarToString(castBody["text"]), 600) + fieldType = "cast" + if embeds, ok := castBody["embeds"].([]any); ok { + for _, e := range embeds { + if em, ok := e.(map[string]any); ok { + if eu := SanitizeSchemaHTTPSURL(jsonScalarToString(em["url"]), origURL); eu != "" { + wave3SocialAddLink(&links, seenLinks, eu, origURL) + } + } + } + } + } else if udBody, ok := data["userDataBody"].(map[string]any); ok { + fieldType = wave3SocialPlain(udBody["type"], 64) + text = wave3SocialSanitizeUntrustedContent(jsonScalarToString(udBody["value"]), 600) + } + if text == "" && hash == "" { + continue + } + rec := map[string]any{"fid": fid} + if hash != "" { + rec["hash"] = hash + } + if msgType != "" { + rec["type"] = msgType + } + if fieldType != "" { + rec["kind"] = fieldType + } + if text != "" { + rec["value"] = text + } + if ts != "" { + rec["timestamp"] = ts + } + recs = append(recs, rec) + rows = append(rows, []string{ + wave3SocialFirstNonEmpty(escapeDeclMarkdownBrackets(fid), "-"), + wave3SocialFirstNonEmpty(escapeDeclMarkdownBrackets(fieldType), escapeDeclMarkdownBrackets(msgType), "-"), + wave3SocialFirstNonEmpty(wave3SocialTableCell(text, 160), "-"), + wave3SocialFirstNonEmpty(escapeDeclMarkdownBrackets(ts), "-"), + }) + } + if len(recs) == 0 { + return nil, false + } + nextCur := wave3SocialPlain(obj["nextPageToken"], 160) + title := "Farcaster Hub Messages" + if len(recs) == 1 { + if fid, _ := recs[0]["fid"].(string); fid != "" { + title = "Farcaster FID " + fid + } + } + md := "# " + escapeDeclMarkdownBrackets(title) + "\n\n" + formatDeclarativeGFMTable([]string{"FID", "Kind", "Content", "Timestamp"}, rows) + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: md, + Links: links, + Records: recs, + NextCursor: nextCur, + }, true +} + +func wave3SocialExtractFarcasterHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + ogTitle := SanitizeSchemaPlainField(wave3SocialExtractMetaBounded(rawHTML, "og:title"), 240) + ogDesc := SanitizeSchemaPlainField(wave3SocialExtractMetaBounded(rawHTML, "og:description"), 1600) + twTitle := SanitizeSchemaPlainField(wave3SocialExtractMetaBounded(rawHTML, "twitter:title"), 240) + twDesc := SanitizeSchemaPlainField(wave3SocialExtractMetaBounded(rawHTML, "twitter:description"), 1600) + titleTag := wave3SocialExtractTitleBounded(rawHTML) + + title := wave3SocialFirstNonEmpty(ogTitle, twTitle, titleTag) + if title != "" && (wave3SocialIsNegativeTitle(title) || wave3SocialIsGenericTitle(title)) { + title = "" + } + body := wave3SocialFirstNonEmpty(ogDesc, twDesc) + if body == "" { + doc := ParseHTMLDoc(rawHTML, wave3SocialStdHTMLMaxBytes) + if doc != nil { + body = SanitizeSchemaPlainField(wave3SocialCleanText(doc.Text("main, article")), 1200) + } + } + if title == "" || body == "" { + return nil + } + var links []string + seenLinks := make(map[string]bool) + if ogURL := wave3SocialExtractMetaBounded(rawHTML, "og:url"); ogURL != "" { + wave3SocialAddLink(&links, seenLinks, ogURL, baseURL) + } + rec := map[string]any{"title": title, "content": body} + md := "# " + escapeDeclMarkdownBrackets(title) + "\n\n" + escapeDeclPlainTextPreservingNewlines(body) + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: sliceRunesMax(body, 260), + Markdown: md, + Links: links, + Records: []map[string]any{rec}, + } +} + +// ── #397 Nostr Relays (NIP-11 + NIP-01 Envelope) & njump.me (`nostr_relay_json` / `nostr_njump_html`) ── + +// NostrNIP01Plan holds the Go-validated read-only NIP-01 REQ/CLOSE frames and relay endpoints for a Nostr URL. +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"` +} + +func isHex64LowerGo(s string) bool { + if len(s) != 64 { + return false + } + for i := 0; i < 64; i++ { + c := s[i] + if !((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f')) { + return false + } + } + return true +} + +func isDigitsOnlyGo(s string, maxLen int) bool { + if len(s) == 0 || len(s) > maxLen { + return false + } + for i := 0; i < len(s); i++ { + if s[i] < '0' || s[i] > '9' { + return false + } + } + return true +} + +// PrepareNostrNIP01 parses and validates a Nostr relay URL for bounded read-only NIP-01 WebSocket REQ querying. +func PrepareNostrNIP01(rawURL, selfHost, subID string, maxEvents int) NostrNIP01Plan { + u, err := url.Parse(strings.TrimSpace(rawURL)) + if err != nil || u.Hostname() == "" { + return NostrNIP01Plan{OK: false, Reason: "invalid_url"} + } + q := u.Query() + nip01Val := strings.ToLower(strings.TrimSpace(q.Get("nip01"))) + _, hasKinds := q["kinds"] + _, hasAuthors := q["authors"] + _, hasIDs := q["ids"] + enabled := nip01Val == "1" || nip01Val == "true" || hasKinds || hasAuthors || hasIDs + + if strings.ToLower(u.Scheme) != "https" { + return NostrNIP01Plan{Enabled: enabled, OK: false, Reason: "nostr_requires_https"} + } + if port := u.Port(); port != "" && port != "443" { + return NostrNIP01Plan{Enabled: enabled, OK: false, Reason: "nostr_port_443_only"} + } + if u.User != nil { + return NostrNIP01Plan{Enabled: enabled, OK: false, Reason: "nostr_credentials_forbidden"} + } + host := strings.TrimSuffix(strings.ToLower(u.Hostname()), ".") + if !isSafePublicHostnameWithSelfSchemaGo(host, selfHost) { + return NostrNIP01Plan{Enabled: enabled, OK: false, Reason: "ssrf_blocked"} + } + clampMax := maxEvents + if clampMax < 1 { + clampMax = 20 + } else if clampMax > 20 { + clampMax = 20 + } + var kinds []int + if rawKinds := q.Get("kinds"); rawKinds != "" { + seenK := make(map[int]bool) + for _, part := range strings.Split(rawKinds, ",") { + trimmed := strings.TrimSpace(part) + if !isDigitsOnlyGo(trimmed, 5) { + continue + } + n, pErr := strconv.Atoi(trimmed) + if pErr == nil && n >= 0 && n <= 65535 && !seenK[n] { + seenK[n] = true + kinds = append(kinds, n) + if len(kinds) >= 10 { + break + } + } + } + } + var authors []string + if rawAuthors := q.Get("authors"); rawAuthors != "" { + seenA := make(map[string]bool) + for _, part := range strings.Split(rawAuthors, ",") { + trimmed := strings.ToLower(strings.TrimSpace(part)) + if isHex64LowerGo(trimmed) && !seenA[trimmed] { + seenA[trimmed] = true + authors = append(authors, trimmed) + if len(authors) >= 10 { + break + } + } + } + } + var ids []string + if rawIDs := q.Get("ids"); rawIDs != "" { + seenI := make(map[string]bool) + for _, part := range strings.Split(rawIDs, ",") { + trimmed := strings.ToLower(strings.TrimSpace(part)) + if isHex64LowerGo(trimmed) && !seenI[trimmed] { + seenI[trimmed] = true + ids = append(ids, trimmed) + if len(ids) >= 20 { + break + } + } + } + } + limit := 20 + if rawLimit := strings.TrimSpace(q.Get("limit")); isDigitsOnlyGo(rawLimit, 4) { + if parsed, lErr := strconv.Atoi(rawLimit); lErr == nil && parsed >= 1 && parsed < limit { + limit = parsed + } + } + if clampMax < limit { + limit = clampMax + } + if len(kinds) == 0 && len(authors) == 0 && len(ids) == 0 { + kinds = []int{1} + } + filter := map[string]any{"limit": limit} + if len(kinds) > 0 { + filter["kinds"] = kinds + } + if len(authors) > 0 { + filter["authors"] = authors + } + if len(ids) > 0 { + filter["ids"] = ids + } + cleanSub := strings.TrimSpace(subID) + if cleanSub == "" { + cleanSub = "ef-nostr" + } + reqBytes, _ := json.Marshal([]any{"REQ", cleanSub, filter}) + closeBytes, _ := json.Marshal([]any{"CLOSE", cleanSub}) + return NostrNIP01Plan{ + Enabled: enabled, + OK: true, + NIP11URL: "https://" + host + "/", + WSSURL: "wss://" + host + "/", + SubID: cleanSub, + ReqFrame: string(reqBytes), + CloseFrame: string(closeBytes), + MaxEvents: clampMax, + } +} + +// ParseNostrNIP01Frames extracts validated NIP-01 EVENT objects matching subID from raw WebSocket frames. +func ParseNostrNIP01Frames(subID string, frames []string, maxEvents int) []any { + capEv := maxEvents + if capEv <= 0 || capEv > wave3SocialMaxNostrEvents { + capEv = wave3SocialMaxNostrEvents + } + events := make([]any, 0, len(frames)) + for _, raw := range frames { + if len(events) >= capEv { + break + } + trimmed := strings.TrimSpace(raw) + if trimmed == "" || trimmed[0] != '[' { + continue + } + var arr []any + if err := json.Unmarshal([]byte(trimmed), &arr); err != nil || len(arr) < 3 { + continue + } + kind, _ := arr[0].(string) + frameSub, _ := arr[1].(string) + if kind != "EVENT" || (subID != "" && frameSub != subID) { + continue + } + if evObj, ok := arr[2].(map[string]any); ok && evObj != nil { + events = append(events, evObj) + } + } + return events +} + +// FormatNostrNIP01Frames parses optional NIP-11 relay metadata + raw NIP-01 WebSocket frames into a sanitized DeclarativeFormattedDoc. +func FormatNostrNIP01Frames(origURL, relayURL, subID, nip11Raw string, frames []string, maxEvents int) (*DeclarativeFormattedDoc, bool) { + var nip11Obj map[string]any + if trimmed := strings.TrimSpace(nip11Raw); trimmed != "" && trimmed[0] == '{' { + var parsed map[string]any + if err := json.Unmarshal([]byte(trimmed), &parsed); err == nil && parsed != nil { + nip11Obj = parsed + } + } + events := ParseNostrNIP01Frames(subID, frames, maxEvents) + env := map[string]any{ + "relay": relayURL, + "events": events, + } + if nip11Obj != nil { + env["nip11"] = nip11Obj + } + doc, ok := wave3SocialFormatNostrJSON(env, origURL) + if !ok || doc == nil { + return nil, false + } + return sanitizeDeclarativeFormattedDocGo(doc) +} + +func wave3SocialIsNIP11Object(m map[string]any) bool { + if m == nil { + return false + } + for _, k := range []string{"name", "description", "pubkey", "supported_nips", "software", "version", "limitation"} { + if v, ok := m[k]; ok && v != nil { + return true + } + } + return false +} + +func wave3SocialFormatNostrJSON(obj map[string]any, origURL string) (*DeclarativeFormattedDoc, bool) { + // Support BOTH plain NIP-11 relay metadata JSON AND Hub TS NIP-01 envelopes {relay, nip11, events[]} + var nip11 map[string]any + if sub, ok := obj["nip11"].(map[string]any); ok { + nip11 = sub + } else if wave3SocialIsNIP11Object(obj) { + nip11 = obj + } + rawEvents, _ := obj["events"].([]any) + relayRaw := wave3SocialPlain(obj["relay"], 200) + + if nip11 == nil && len(rawEvents) == 0 { + return nil, false + } + + var links []string + seenLinks := make(map[string]bool) + + relayName := wave3SocialPlain(nip11["name"], 160) + relayDesc := wave3SocialSanitizeUntrustedContent(jsonScalarToString(nip11["description"]), 800) + relayPubkey := wave3SocialPlain(nip11["pubkey"], 80) + relayContact := wave3SocialPlain(nip11["contact"], 160) + relaySoftware := wave3SocialPlain(nip11["software"], 160) + relayVersion := wave3SocialPlain(nip11["version"], 48) + if relaySoftware != "" && strings.HasPrefix(relaySoftware, "https://") { + wave3SocialAddLink(&links, seenLinks, relaySoftware, origURL) + } + + var nipsList []string + if rawNips, ok := nip11["supported_nips"].([]any); ok { + for _, n := range rawNips { + if len(nipsList) >= 40 { + break + } + if s := wave3SocialPlain(n, 16); s != "" { + nipsList = append(nipsList, s) + } + } + } + + var limSummary []string + if lim, ok := nip11["limitation"].(map[string]any); ok { + if mml := wave3SocialPlain(lim["max_message_length"], 24); mml != "" { + limSummary = append(limSummary, "max_message_length="+mml) + } + if ms := wave3SocialPlain(lim["max_subscriptions"], 24); ms != "" { + limSummary = append(limSummary, "max_subscriptions="+ms) + } + if ar, ok := lim["auth_required"].(bool); ok { + limSummary = append(limSummary, fmt.Sprintf("auth_required=%t", ar)) + } + if pr, ok := lim["payment_required"].(bool); ok { + limSummary = append(limSummary, fmt.Sprintf("payment_required=%t", pr)) + } + } + + var hostLabel string + if u, err := url.Parse(origURL); err == nil && u.Hostname() != "" { + hostLabel = u.Hostname() + } + title := wave3SocialFirstNonEmpty(relayName, relayRaw, hostLabel, "Nostr Relay") + + var bullets []string + if relayRaw != "" { + bullets = append(bullets, "- **Relay**: "+escapeDeclMarkdownBrackets(relayRaw)) + } + if relaySoftware != "" { + sw := relaySoftware + if relayVersion != "" { + sw += " (" + relayVersion + ")" + } + bullets = append(bullets, "- **Software**: "+escapeDeclMarkdownBrackets(sw)) + } + if len(nipsList) > 0 { + bullets = append(bullets, "- **Supported NIPs**: "+escapeDeclMarkdownBrackets(strings.Join(nipsList, ", "))) + } + if relayPubkey != "" { + bullets = append(bullets, "- **Pubkey**: "+escapeDeclMarkdownBrackets(relayPubkey)) + } + if relayContact != "" { + bullets = append(bullets, "- **Contact**: "+escapeDeclMarkdownBrackets(relayContact)) + } + if len(limSummary) > 0 { + bullets = append(bullets, "- **Limitations**: "+escapeDeclMarkdownBrackets(strings.Join(limSummary, ", "))) + } + + var recs []map[string]any + var eventRows [][]string + + if len(rawEvents) > 0 { + for _, rawEv := range rawEvents { + if len(recs) >= wave3SocialMaxNostrEvents { + break + } + ev, ok := rawEv.(map[string]any) + if !ok { + continue + } + evID := wave3SocialPlain(ev["id"], 64) + pubkey := wave3SocialPlain(ev["pubkey"], 64) + kindStr := wave3SocialPlain(ev["kind"], 16) + createdAt := "" + if ca, okCa := wave3SocialToInt(ev["created_at"]); okCa { + createdAt = wave3SocialFormatEpochUTC(ca) + } + content := wave3SocialSanitizeUntrustedContent(jsonScalarToString(ev["content"]), 600) + if evID == "" && pubkey == "" && content == "" { + continue + } + // Extract safe HTTPS URLs from NIP-01 tags (e.g. ["r", "https://..."]) + if tags, ok := ev["tags"].([]any); ok { + for _, rawTag := range tags { + if arr, ok := rawTag.([]any); ok && len(arr) >= 2 { + tagKey := wave3SocialPlain(arr[0], 16) + if tagKey == "r" || tagKey == "url" { + if u := SanitizeSchemaHTTPSURL(jsonScalarToString(arr[1]), origURL); u != "" { + wave3SocialAddLink(&links, seenLinks, u, origURL) + } + } + } + } + } + rec := map[string]any{} + if evID != "" { + rec["id"] = evID + } + if pubkey != "" { + rec["pubkey"] = pubkey + } + if kindStr != "" { + rec["kind"] = kindStr + } + if createdAt != "" { + rec["createdAt"] = createdAt + } + if content != "" { + rec["content"] = content + } + recs = append(recs, rec) + + shortPub := pubkey + if len(shortPub) > 12 { + shortPub = shortPub[:12] + "..." + } + eventRows = append(eventRows, []string{ + wave3SocialFirstNonEmpty(escapeDeclMarkdownBrackets(kindStr), "-"), + wave3SocialFirstNonEmpty(escapeDeclMarkdownBrackets(shortPub), "-"), + wave3SocialFirstNonEmpty(escapeDeclMarkdownBrackets(createdAt), "-"), + wave3SocialFirstNonEmpty(wave3SocialTableCell(content, 160), "-"), + }) + } + } + + if len(recs) == 0 && nip11 != nil { + rec := map[string]any{"name": title} + if relaySoftware != "" { + rec["software"] = relaySoftware + } + if relayVersion != "" { + rec["version"] = relayVersion + } + if relayPubkey != "" { + rec["pubkey"] = relayPubkey + } + if len(nipsList) > 0 { + rec["supportedNips"] = nipsList + } + recs = append(recs, rec) + } + + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + if relayDesc != "" { + blocks = append(blocks, escapeDeclPlainTextPreservingNewlines(relayDesc)) + } + if len(eventRows) > 0 { + blocks = append(blocks, "## Recent Nostr Events\n\n"+formatDeclarativeGFMTable([]string{"Kind", "Pubkey", "Created At", "Content"}, eventRows)) + } + + return &DeclarativeFormattedDoc{ + Title: title, + Description: sliceRunesMax(relayDesc, 260), + Author: relayPubkey, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: recs, + }, true +} + +func wave3SocialExtractNjumpHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + doc := ParseHTMLDoc(rawHTML, wave3SocialStdHTMLMaxBytes) + ogTitle := SanitizeSchemaPlainField(wave3SocialExtractMetaBounded(rawHTML, "og:title"), 240) + ogDesc := SanitizeSchemaPlainField(wave3SocialExtractMetaBounded(rawHTML, "og:description"), 1600) + titleTag := wave3SocialExtractTitleBounded(rawHTML) + + var articleBody, author, pubTime string + if doc != nil { + articleBody = wave3SocialSanitizeUntrustedContent(doc.Text("article[itemprop='articleBody'], [itemprop='articleBody'], article, main"), 2400) + author = SanitizeSchemaPlainField(wave3SocialCleanText(doc.Text("[rel='author'], [itemprop='author'], .author")), 120) + if tNode := doc.First("time[datetime]"); tNode != nil { + if dt, okDT := tNode.Attr("datetime"); okDT { + pubTime = SanitizeSchemaPlainField(dt, 48) + } + } + } + + title := wave3SocialFirstNonEmpty(ogTitle, titleTag) + if title != "" && (wave3SocialIsNegativeTitle(title) || wave3SocialIsGenericTitle(title)) { + title = "" + } + body := wave3SocialFirstNonEmpty(articleBody, ogDesc) + if title == "" || body == "" { + return nil + } + + var links []string + seenLinks := make(map[string]bool) + if ogURL := wave3SocialExtractMetaBounded(rawHTML, "og:url"); ogURL != "" { + wave3SocialAddLink(&links, seenLinks, ogURL, baseURL) + } + rec := map[string]any{"title": title, "content": sliceRunesMax(body, 600)} + if author != "" { + rec["author"] = author + } + if pubTime != "" { + rec["publishedTime"] = pubTime + } + + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + var bullets []string + if author != "" { + bullets = append(bullets, "- **Author**: "+escapeDeclMarkdownBrackets(author)) + } + if pubTime != "" { + bullets = append(bullets, "- **Published**: "+escapeDeclMarkdownBrackets(pubTime)) + } + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + blocks = append(blocks, escapeDeclPlainTextPreservingNewlines(body)) + + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: sliceRunesMax(body, 260), + Author: author, + PublishedTime: pubTime, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: []map[string]any{rec}, + } +} + +// ── #398 Product Hunt GraphQL & HTML (`product_hunt_json` / `product_hunt_html`) ───────────────── + +func wave3SocialFormatProductHuntJSON(obj map[string]any, origURL string) (*DeclarativeFormattedDoc, bool) { + data, ok := obj["data"].(map[string]any) + if !ok || len(data) == 0 { + return nil, false + } + + var nodes []map[string]any + if post, ok := data["post"].(map[string]any); ok { + nodes = append(nodes, post) + } else if posts, ok := data["posts"].(map[string]any); ok { + if edges, ok := posts["edges"].([]any); ok { + for _, re := range edges { + if em, ok := re.(map[string]any); ok { + if node, ok := em["node"].(map[string]any); ok { + nodes = append(nodes, node) + } + } + } + } else if nl, ok := posts["nodes"].([]any); ok { + for _, rn := range nl { + if nm, ok := rn.(map[string]any); ok { + nodes = append(nodes, nm) + } + } + } + } + if len(nodes) == 0 { + return nil, false + } + + var recs []map[string]any + var rows [][]string + var links []string + seenLinks := make(map[string]bool) + + for _, n := range nodes { + if len(recs) >= wave3SocialMaxRecords { + break + } + id := wave3SocialPlain(n["id"], 48) + name := wave3SocialPlain(n["name"], 200) + tagline := wave3SocialPlain(n["tagline"], 280) + desc := wave3SocialPlain(n["description"], 1800) + votes := wave3SocialPlain(n["votesCount"], 24) + comments := wave3SocialPlain(n["commentsCount"], 24) + createdAt := wave3SocialPlain(n["createdAt"], 48) + phURL := SanitizeSchemaHTTPSURL(jsonScalarToString(n["url"]), origURL) + siteURL := SanitizeSchemaHTTPSURL(jsonScalarToString(n["website"]), origURL) + if name == "" { + continue + } + if phURL != "" { + wave3SocialAddLink(&links, seenLinks, phURL, origURL) + } + if siteURL != "" { + wave3SocialAddLink(&links, seenLinks, siteURL, origURL) + } + + var topics []string + if topMap, ok := n["topics"].(map[string]any); ok { + if edges, ok := topMap["edges"].([]any); ok { + for _, te := range edges { + if tem, ok := te.(map[string]any); ok { + if tn, ok := tem["node"].(map[string]any); ok { + if nm := wave3SocialPlain(tn["name"], 60); nm != "" { + topics = append(topics, nm) + } + } + } + } + } + } + var makers []string + if rawMakers, ok := n["makers"].([]any); ok { + for _, rm := range rawMakers { + if mm, ok := rm.(map[string]any); ok { + if mn := wave3SocialFirstNonEmpty(wave3SocialPlain(mm["name"], 80), wave3SocialPlain(mm["username"], 80)); mn != "" { + makers = append(makers, mn) + } + } + } + } + + rec := map[string]any{"name": name} + if id != "" { + rec["id"] = id + } + if tagline != "" { + rec["tagline"] = tagline + } + if desc != "" { + rec["description"] = sliceRunesMax(desc, 400) + } + if votes != "" { + rec["votesCount"] = votes + } + if comments != "" { + rec["commentsCount"] = comments + } + if createdAt != "" { + rec["createdAt"] = createdAt + } + if phURL != "" { + rec["url"] = phURL + } + if siteURL != "" { + rec["website"] = siteURL + } + if len(topics) > 0 { + rec["topics"] = topics + } + if len(makers) > 0 { + rec["makers"] = makers + } + recs = append(recs, rec) + rows = append(rows, []string{ + wave3SocialTableCell(name, 80), + wave3SocialFirstNonEmpty(wave3SocialTableCell(tagline, 120), "-"), + wave3SocialFirstNonEmpty(escapeDeclMarkdownBrackets(votes), "-"), + wave3SocialFirstNonEmpty(escapeDeclMarkdownBrackets(strings.Join(topics, ", ")), "-"), + }) + } + if len(recs) == 0 { + return nil, false + } + + if len(recs) == 1 { + n := nodes[0] + name := wave3SocialPlain(n["name"], 200) + tagline := wave3SocialPlain(n["tagline"], 280) + desc := wave3SocialPlain(n["description"], 1800) + votes := wave3SocialPlain(n["votesCount"], 24) + comments := wave3SocialPlain(n["commentsCount"], 24) + createdAt := wave3SocialPlain(n["createdAt"], 48) + + var bullets []string + if tagline != "" { + bullets = append(bullets, "- **Tagline**: "+escapeDeclMarkdownBrackets(tagline)) + } + if votes != "" { + bullets = append(bullets, "- **Votes**: "+escapeDeclMarkdownBrackets(votes)) + } + if comments != "" { + bullets = append(bullets, "- **Comments**: "+escapeDeclMarkdownBrackets(comments)) + } + if createdAt != "" { + bullets = append(bullets, "- **Launched**: "+escapeDeclMarkdownBrackets(createdAt)) + } + if makers, ok := recs[0]["makers"].([]string); ok && len(makers) > 0 { + bullets = append(bullets, "- **Makers**: "+escapeDeclMarkdownBrackets(strings.Join(makers, ", "))) + } + if topics, ok := recs[0]["topics"].([]string); ok && len(topics) > 0 { + bullets = append(bullets, "- **Topics**: "+escapeDeclMarkdownBrackets(strings.Join(topics, ", "))) + } + blocks := []string{"# " + escapeDeclMarkdownBrackets(name)} + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + if desc != "" { + blocks = append(blocks, "## Description\n\n"+escapeDeclPlainTextPreservingNewlines(desc)) + } + return &DeclarativeFormattedDoc{ + Title: name, + Description: sliceRunesMax(wave3SocialFirstNonEmpty(tagline, desc), 260), + PublishedTime: createdAt, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: recs, + }, true + } + + title := "Product Hunt Launches" + md := "# " + title + "\n\n" + formatDeclarativeGFMTable([]string{"Product", "Tagline", "Votes", "Topics"}, rows) + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: md, + Links: links, + Records: recs, + }, true +} + +func wave3SocialExtractProductHuntHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + ldObjs := extractJSONLDObjectsDeclHTML(rawHTML, 16) + ogTitle := wave3SocialRxPHSuffix.ReplaceAllString(SanitizeSchemaPlainField(wave3SocialExtractMetaBounded(rawHTML, "og:title"), 240), "") + ogDesc := SanitizeSchemaPlainField(wave3SocialExtractMetaBounded(rawHTML, "og:description"), 1600) + titleTag := wave3SocialRxPHSuffix.ReplaceAllString(wave3SocialExtractTitleBounded(rawHTML), "") + + var name, desc, maker, datePub, votes string + for _, ld := range ldObjs { + tp := wave3SocialPlain(ld["@type"], 48) + if tp == "SoftwareApplication" || tp == "Product" || tp == "WebApplication" || tp == "MobileApplication" { + name = wave3SocialFirstNonEmpty(name, wave3SocialPlain(ld["name"], 200)) + desc = wave3SocialFirstNonEmpty(desc, wave3SocialPlain(ld["description"], 1600)) + datePub = wave3SocialFirstNonEmpty(datePub, wave3SocialPlain(ld["datePublished"], 48)) + if aMap, ok := ld["author"].(map[string]any); ok { + maker = wave3SocialFirstNonEmpty(maker, wave3SocialPlain(aMap["name"], 120)) + } + if ar, ok := ld["aggregateRating"].(map[string]any); ok { + votes = wave3SocialFirstNonEmpty(votes, wave3SocialPlain(ar["ratingCount"], 24), wave3SocialPlain(ar["reviewCount"], 24)) + } + } + } + + if (name == "" || desc == "") && wave3SocialContainsASCIIFold(rawHTML, "__NEXT_DATA__") { + if m := wave3SocialRxNextData.FindStringSubmatch(rawHTML); len(m) >= 2 { + if parsed, ok := decodeJSONWithNumbers([]byte(m[1])); ok { + if root, ok := parsed.(map[string]any); ok { + if props, ok := root["props"].(map[string]any); ok { + if pp, ok := props["pageProps"].(map[string]any); ok { + if post, ok := pp["post"].(map[string]any); ok { + name = wave3SocialFirstNonEmpty(name, wave3SocialPlain(post["name"], 200)) + desc = wave3SocialFirstNonEmpty(desc, wave3SocialPlain(post["tagline"], 280), wave3SocialPlain(post["description"], 1600)) + votes = wave3SocialFirstNonEmpty(votes, wave3SocialPlain(post["votesCount"], 24)) + } + } + } + } + } + } + } + + title := wave3SocialFirstNonEmpty(name, ogTitle, titleTag) + if title != "" && (wave3SocialIsNegativeTitle(title) || wave3SocialIsGenericTitle(title)) { + title = "" + } + desc = wave3SocialFirstNonEmpty(desc, ogDesc) + if title == "" || desc == "" { + return nil + } + + rec := map[string]any{"name": title, "description": desc} + var bullets []string + if maker != "" { + bullets = append(bullets, "- **Maker**: "+escapeDeclMarkdownBrackets(maker)) + rec["maker"] = maker + } + if votes != "" { + bullets = append(bullets, "- **Votes**: "+escapeDeclMarkdownBrackets(votes)) + rec["votesCount"] = votes + } + if datePub != "" { + bullets = append(bullets, "- **Published**: "+escapeDeclMarkdownBrackets(datePub)) + rec["publishedTime"] = datePub + } + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + blocks = append(blocks, escapeDeclPlainTextPreservingNewlines(desc)) + + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: sliceRunesMax(desc, 260), + Author: maker, + PublishedTime: datePub, + Markdown: strings.Join(blocks, "\n\n"), + Records: []map[string]any{rec}, + } +} + +// ── #399 Substack Notes & Beehiiv API (`beehiiv_api_json` / `substack_notes_html`) ─────────────── + +func wave3SocialFormatBeehiivJSON(obj map[string]any, origURL string) (*DeclarativeFormattedDoc, bool) { + dataVal, exists := obj["data"] + if !exists || dataVal == nil { + return nil, false + } + + var items []map[string]any + switch dv := dataVal.(type) { + case []any: + for _, r := range dv { + if m, ok := r.(map[string]any); ok { + items = append(items, m) + } + } + case map[string]any: + items = append(items, dv) + } + if len(items) == 0 { + return nil, false + } + + var recs []map[string]any + var rows [][]string + var links []string + seenLinks := make(map[string]bool) + + for _, it := range items { + if len(recs) >= wave3SocialMaxRecords { + break + } + id := wave3SocialPlain(it["id"], 80) + title := wave3SocialFirstNonEmpty(wave3SocialPlain(it["title"], 220), wave3SocialPlain(it["name"], 220)) + subtitle := wave3SocialPlain(it["subtitle"], 400) + status := wave3SocialPlain(it["status"], 40) + webURL := SanitizeSchemaHTTPSURL(jsonScalarToString(it["web_url"]), origURL) + if webURL != "" { + wave3SocialAddLink(&links, seenLinks, webURL, origURL) + } + pubDate := "" + if pd, okPd := wave3SocialToInt(it["publish_date"]); okPd { + pubDate = wave3SocialFormatEpochUTC(pd) + } else if cd, okCd := wave3SocialToInt(it["created"]); okCd { + pubDate = wave3SocialFormatEpochUTC(cd) + } + var authors []string + if rawAuth, ok := it["authors"].([]any); ok { + for _, a := range rawAuth { + if as := wave3SocialPlain(a, 80); as != "" { + authors = append(authors, as) + } + } + } + if title == "" && id == "" { + continue + } + rec := map[string]any{"title": wave3SocialFirstNonEmpty(title, id)} + if id != "" { + rec["id"] = id + } + if subtitle != "" { + rec["subtitle"] = subtitle + } + if status != "" { + rec["status"] = status + } + if pubDate != "" { + rec["publishDate"] = pubDate + } + if len(authors) > 0 { + rec["authors"] = authors + } + if webURL != "" { + rec["url"] = webURL + } + recs = append(recs, rec) + rows = append(rows, []string{ + wave3SocialTableCell(wave3SocialFirstNonEmpty(title, id), 100), + wave3SocialFirstNonEmpty(escapeDeclMarkdownBrackets(strings.Join(authors, ", ")), "-"), + wave3SocialFirstNonEmpty(escapeDeclMarkdownBrackets(status), "-"), + wave3SocialFirstNonEmpty(escapeDeclMarkdownBrackets(pubDate), "-"), + }) + } + if len(recs) == 0 { + return nil, false + } + + var totalPtr *int + if tr, okTr := wave3SocialToInt(obj["total_results"]); okTr && tr >= 0 { + tv := int(tr) + totalPtr = &tv + } + + if len(recs) == 1 { + it := items[0] + title := wave3SocialFirstNonEmpty(wave3SocialPlain(it["title"], 220), wave3SocialPlain(it["name"], 220), wave3SocialPlain(it["id"], 80)) + subtitle := wave3SocialPlain(it["subtitle"], 400) + var contentBody string + if cMap, ok := it["content"].(map[string]any); ok { + if freeMap, ok := cMap["free"].(map[string]any); ok { + contentBody = wave3SocialSanitizeUntrustedContent(wave3SocialFirstNonEmpty(jsonScalarToString(freeMap["web"]), jsonScalarToString(freeMap["email"])), 3000) + } + } + if contentBody == "" { + contentBody = subtitle + } + var bullets []string + if id, _ := recs[0]["id"].(string); id != "" { + bullets = append(bullets, "- **ID**: "+escapeDeclMarkdownBrackets(id)) + } + if authors, ok := recs[0]["authors"].([]string); ok && len(authors) > 0 { + bullets = append(bullets, "- **Authors**: "+escapeDeclMarkdownBrackets(strings.Join(authors, ", "))) + } + if pd, _ := recs[0]["publishDate"].(string); pd != "" { + bullets = append(bullets, "- **Published**: "+escapeDeclMarkdownBrackets(pd)) + } + if st, _ := recs[0]["status"].(string); st != "" { + bullets = append(bullets, "- **Status**: "+escapeDeclMarkdownBrackets(st)) + } + if u, _ := recs[0]["url"].(string); u != "" { + bullets = append(bullets, "- **URL**: "+escapeDeclMarkdownBrackets(u)) + } + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + if contentBody != "" { + blocks = append(blocks, escapeDeclPlainTextPreservingNewlines(contentBody)) + } + authorStr := "" + if authors, ok := recs[0]["authors"].([]string); ok && len(authors) > 0 { + authorStr = strings.Join(authors, ", ") + } + pubStr, _ := recs[0]["publishDate"].(string) + return &DeclarativeFormattedDoc{ + Title: title, + Description: sliceRunesMax(wave3SocialFirstNonEmpty(subtitle, contentBody), 260), + Author: authorStr, + PublishedTime: pubStr, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: recs, + Total: totalPtr, + }, true + } + + title := "Beehiiv Publication Posts" + md := "# " + title + "\n\n" + formatDeclarativeGFMTable([]string{"Title", "Authors", "Status", "Published"}, rows) + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: md, + Links: links, + Records: recs, + Total: totalPtr, + }, true +} + +func wave3SocialExtractSubstackPreloads(rawHTML string) map[string]any { + if rawJSON := wave3SocialExtractScriptByID(rawHTML, "preloads-json"); rawJSON != "" { + if parsed, ok := decodeJSONWithNumbers([]byte(rawJSON)); ok { + if m, okMap := parsed.(map[string]any); okMap { + return m + } + } + } + if idx := strings.Index(rawHTML, "window._preloads"); idx >= 0 { + const prefix = `JSON.parse("` + if pRel := strings.Index(rawHTML[idx:], prefix); pRel >= 0 { + startQuote := idx + pRel + len(prefix) - 1 + // Scan JSON-escaped string literal + escaped := false + for i := startQuote + 1; i < len(rawHTML) && i-startQuote < 1024*1024; i++ { + c := rawHTML[i] + if escaped { + escaped = false + continue + } + if c == '\\' { + escaped = true + continue + } + if c == '"' { + var inner string + if err := json.Unmarshal([]byte(rawHTML[startQuote:i+1]), &inner); err == nil { + if parsed, ok := decodeJSONWithNumbers([]byte(inner)); ok { + if m, okMap := parsed.(map[string]any); okMap { + return m + } + } + } + break + } + } + } + } + return nil +} + +func wave3SocialExtractSubstackNotesHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + preloads := wave3SocialExtractSubstackPreloads(rawHTML) + ogTitle := SanitizeSchemaPlainField(wave3SocialExtractMetaBounded(rawHTML, "og:title"), 240) + ogDesc := SanitizeSchemaPlainField(wave3SocialExtractMetaBounded(rawHTML, "og:description"), 1600) + titleTag := wave3SocialExtractTitleBounded(rawHTML) + + var profileName, profileHandle, profileBio, subCount string + var recs []map[string]any + var rows [][]string + var links []string + seenLinks := make(map[string]bool) + var singleBody, singleDate string + + if ogURL := wave3SocialExtractMetaBounded(rawHTML, "og:url"); ogURL != "" { + wave3SocialAddLink(&links, seenLinks, ogURL, baseURL) + } + + if preloads != nil { + for _, pk := range []string{"publicProfile", "profile", "user"} { + if pm, ok := preloads[pk].(map[string]any); ok { + profileName = wave3SocialFirstNonEmpty(profileName, wave3SocialPlain(pm["name"], 140)) + profileHandle = wave3SocialFirstNonEmpty(profileHandle, wave3SocialPlain(pm["handle"], 80)) + profileBio = wave3SocialFirstNonEmpty(profileBio, wave3SocialPlain(pm["bio"], 1000)) + subCount = wave3SocialFirstNonEmpty(subCount, wave3SocialPlain(pm["subscriberCountString"], 64)) + } + } + + // Single note comment (`initialComment`, `comment`, `note`) + var singleComment map[string]any + for _, ck := range []string{"initialComment", "comment", "note"} { + if cm, ok := preloads[ck].(map[string]any); ok { + singleComment = cm + break + } + } + if singleComment != nil { + cid := wave3SocialPlain(singleComment["id"], 48) + cAuthor := wave3SocialFirstNonEmpty(wave3SocialPlain(singleComment["name"], 120), profileName) + cHandle := wave3SocialFirstNonEmpty(wave3SocialPlain(singleComment["handle"], 80), profileHandle) + cDate := wave3SocialPlain(singleComment["date"], 48) + cBody := wave3SocialSanitizeUntrustedContent(wave3SocialFirstNonEmpty( + jsonScalarToString(singleComment["body"]), + jsonScalarToString(singleComment["body_html"]), + ), 2400) + likes := wave3SocialPlain(singleComment["reaction_count"], 24) + if likes == "" { + if rMap, ok := singleComment["reactions"].(map[string]any); ok { + for _, rv := range rMap { + likes = wave3SocialPlain(rv, 24) + break + } + } + } + restacks := wave3SocialPlain(singleComment["restacks"], 24) + if cBody != "" { + singleBody = cBody + singleDate = cDate + profileName = wave3SocialFirstNonEmpty(profileName, cAuthor) + profileHandle = wave3SocialFirstNonEmpty(profileHandle, cHandle) + rec := map[string]any{"body": sliceRunesMax(cBody, 600)} + if cid != "" { + rec["id"] = cid + } + if cAuthor != "" { + rec["author"] = cAuthor + } + if cHandle != "" { + rec["handle"] = cHandle + } + if cDate != "" { + rec["date"] = cDate + } + if likes != "" { + rec["reactions"] = likes + } + if restacks != "" { + rec["restacks"] = restacks + } + recs = append(recs, rec) + } + } + + // Notes feed array (`notes`, `feedItems`, `items`) + if len(recs) == 0 { + var feedList []any + for _, fk := range []string{"notes", "feedItems", "items"} { + if arr, ok := preloads[fk].([]any); ok && len(arr) > 0 { + feedList = arr + break + } + } + for _, rawItem := range feedList { + if len(recs) >= wave3SocialMaxRecords { + break + } + im, ok := rawItem.(map[string]any) + if !ok { + continue + } + cm := im + if inner, ok := im["comment"].(map[string]any); ok { + cm = inner + } + cid := wave3SocialPlain(cm["id"], 48) + cAuthor := wave3SocialFirstNonEmpty(wave3SocialPlain(cm["name"], 120), profileName) + cHandle := wave3SocialFirstNonEmpty(wave3SocialPlain(cm["handle"], 80), profileHandle) + cDate := wave3SocialPlain(cm["date"], 48) + cBody := wave3SocialSanitizeUntrustedContent(wave3SocialFirstNonEmpty( + jsonScalarToString(cm["body"]), + jsonScalarToString(cm["body_html"]), + ), 600) + if cBody == "" { + continue + } + cURL := SanitizeSchemaHTTPSURL(jsonScalarToString(im["url"]), baseURL) + if cURL != "" { + wave3SocialAddLink(&links, seenLinks, cURL, baseURL) + } + rec := map[string]any{"body": cBody} + if cid != "" { + rec["id"] = cid + } + if cAuthor != "" { + rec["author"] = cAuthor + } + if cHandle != "" { + rec["handle"] = cHandle + } + if cDate != "" { + rec["date"] = cDate + } + if cURL != "" { + rec["url"] = cURL + } + recs = append(recs, rec) + rows = append(rows, []string{ + wave3SocialFirstNonEmpty(escapeDeclMarkdownBrackets(cAuthor), escapeDeclMarkdownBrackets(cHandle), "-"), + wave3SocialTableCell(cBody, 160), + wave3SocialFirstNonEmpty(escapeDeclMarkdownBrackets(cDate), "-"), + }) + } + } + } + + title := wave3SocialFirstNonEmpty(profileName, ogTitle, titleTag) + if title != "" && (wave3SocialIsNegativeTitle(title) || wave3SocialIsGenericTitle(title)) { + title = "" + } + if title == "" && profileHandle != "" { + title = "@" + profileHandle + " on Substack" + } + if title == "" && len(recs) == 0 { + return nil + } + if title == "" { + title = "Substack Notes" + } + if singleBody == "" && len(rows) == 0 && profileBio == "" && ogDesc == "" { + return nil + } + + var blocks []string + blocks = append(blocks, "# "+escapeDeclMarkdownBrackets(title)) + var bullets []string + if profileHandle != "" { + bullets = append(bullets, "- **Handle**: @"+escapeDeclMarkdownBrackets(profileHandle)) + } + if subCount != "" { + bullets = append(bullets, "- **Subscribers**: "+escapeDeclMarkdownBrackets(subCount)) + } + if singleDate != "" { + bullets = append(bullets, "- **Date**: "+escapeDeclMarkdownBrackets(singleDate)) + } + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + if profileBio != "" { + blocks = append(blocks, "## Bio\n\n"+escapeDeclPlainTextPreservingNewlines(profileBio)) + } + if singleBody != "" { + blocks = append(blocks, "## Note\n\n"+escapeDeclPlainTextPreservingNewlines(singleBody)) + } else if len(rows) > 0 { + blocks = append(blocks, "## Notes\n\n"+formatDeclarativeGFMTable([]string{"Author", "Note", "Date"}, rows)) + } else if ogDesc != "" { + blocks = append(blocks, escapeDeclPlainTextPreservingNewlines(ogDesc)) + if len(recs) == 0 { + recs = append(recs, map[string]any{"title": title, "description": ogDesc}) + } + } + + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: sliceRunesMax(wave3SocialFirstNonEmpty(singleBody, profileBio, ogDesc), 260), + Author: wave3SocialFirstNonEmpty(profileName, profileHandle), + PublishedTime: singleDate, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: recs, + } +} + +// ── #400 Patreon Public Creator & Post Pages (`patreon_public_html`) ───────────────────────────── + +func wave3SocialExtractPatreonRSC(rawHTML string) (creatorName, creationName, patronCount, summary string, posts []map[string]string) { + if !strings.Contains(rawHTML, "__next_f") { + return + } + const needle = `__next_f.push(` + pos := 0 + scannedChunks := 0 + var combined strings.Builder + for pos < len(rawHTML) && scannedChunks < 64 { + rel := strings.Index(rawHTML[pos:], needle) + if rel < 0 { + break + } + arrStart := pos + rel + len(needle) + if arrStart >= len(rawHTML) || rawHTML[arrStart] != '[' { + pos = arrStart + 1 + continue + } + arrJSON, nextPos, ok := wave3SocialExtractBalancedJSON(rawHTML, arrStart) + if !ok { + pos = arrStart + 1 + continue + } + pos = nextPos + scannedChunks++ + var pair []any + if err := json.Unmarshal([]byte(arrJSON), &pair); err == nil && len(pair) >= 2 { + if chunk, okStr := pair[1].(string); okStr && chunk != "" { + combined.WriteString(chunk) + combined.WriteByte('\n') + if combined.Len() > 512*1024 { + break + } + } + } + } + payload := combined.String() + if payload == "" { + return + } + + extractJSONStrField := func(src, key string) string { + pat := `"` + key + `":"` + idx := strings.Index(src, pat) + if idx < 0 { + return "" + } + valStart := idx + len(pat) - 1 + escaped := false + for i := valStart + 1; i < len(src) && i-valStart < 2048; i++ { + c := src[i] + if escaped { + escaped = false + continue + } + if c == '\\' { + escaped = true + continue + } + if c == '"' { + var out string + if err := json.Unmarshal([]byte(src[valStart:i+1]), &out); err == nil { + return wave3SocialCleanText(out) + } + return "" + } + } + return "" + } + extractJSONIntField := func(src, key string) string { + pat := `"` + key + `":` + idx := strings.Index(src, pat) + if idx < 0 { + return "" + } + vStart := idx + len(pat) + end := vStart + for end < len(src) && end-vStart < 20 && src[end] >= '0' && src[end] <= '9' { + end++ + } + if end > vStart { + return src[vStart:end] + } + return "" + } + + creatorName = wave3SocialFirstNonEmpty(extractJSONStrField(payload, "vanity"), extractJSONStrField(payload, "name")) + creationName = extractJSONStrField(payload, "creation_name") + patronCount = wave3SocialFirstNonEmpty(extractJSONIntField(payload, "patron_count"), extractJSONIntField(payload, "paid_member_count")) + summary = extractJSONStrField(payload, "summary") + + // Extract up to 10 public posts from RSC `"post_type"` / `"title"` blocks if present + scan := 0 + for len(posts) < 10 && scan < len(payload) { + rel := strings.Index(payload[scan:], `"published_at":"`) + if rel < 0 { + break + } + winStart := scan + rel - 400 + if winStart < scan { + winStart = scan + } + winEnd := scan + rel + 500 + if winEnd > len(payload) { + winEnd = len(payload) + } + window := payload[winStart:winEnd] + pTitle := extractJSONStrField(window, "title") + pDate := extractJSONStrField(window, "published_at") + pURL := extractJSONStrField(window, "url") + if pTitle != "" { + posts = append(posts, map[string]string{ + "title": pTitle, + "date": pDate, + "url": pURL, + }) + } + scan = scan + rel + 16 + } + return +} + +func wave3SocialExtractPatreonHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + ldObjs := extractJSONLDObjectsDeclHTML(rawHTML, 16) + ogTitle := wave3SocialRxPatreonSuffix.ReplaceAllString(SanitizeSchemaPlainField(wave3SocialExtractMetaBounded(rawHTML, "og:title"), 240), "") + ogDesc := SanitizeSchemaPlainField(wave3SocialExtractMetaBounded(rawHTML, "og:description"), 1600) + titleTag := wave3SocialRxPatreonSuffix.ReplaceAllString(wave3SocialExtractTitleBounded(rawHTML), "") + + var creatorName, creatorDesc, creatorURL, memberCount string + var links []string + seenLinks := make(map[string]bool) + + for _, ld := range ldObjs { + tp := wave3SocialPlain(ld["@type"], 48) + if tp == "ProfilePage" || tp == "Person" || tp == "Organization" || tp == "Article" || tp == "CreativeWork" { + target := ld + if me, ok := ld["mainEntity"].(map[string]any); ok { + target = me + } + creatorName = wave3SocialFirstNonEmpty(creatorName, wave3SocialPlain(target["name"], 200), wave3SocialPlain(ld["headline"], 200)) + creatorDesc = wave3SocialFirstNonEmpty(creatorDesc, wave3SocialPlain(target["description"], 1600), wave3SocialPlain(ld["description"], 1600)) + if u := SanitizeSchemaHTTPSURL(jsonScalarToString(target["url"]), baseURL); u != "" { + creatorURL = u + wave3SocialAddLink(&links, seenLinks, u, baseURL) + } + if stats, ok := target["interactionStatistic"].([]any); ok { + for _, rs := range stats { + if sm, ok := rs.(map[string]any); ok { + if uc := wave3SocialPlain(sm["userInteractionCount"], 32); uc != "" { + memberCount = uc + break + } + } + } + } + } + } + + rscName, rscCreation, rscPatrons, rscSummary, rscPosts := wave3SocialExtractPatreonRSC(rawHTML) + creatorName = wave3SocialFirstNonEmpty(creatorName, rscName, ogTitle, titleTag) + if creatorName != "" && (wave3SocialIsNegativeTitle(creatorName) || wave3SocialIsGenericTitle(creatorName)) { + creatorName = "" + } + creatorDesc = wave3SocialFirstNonEmpty(creatorDesc, rscSummary, ogDesc) + memberCount = wave3SocialFirstNonEmpty(memberCount, rscPatrons) + + if creatorName == "" || (creatorDesc == "" && rscCreation == "" && len(rscPosts) == 0) { + return nil + } + + var recs []map[string]any + var postRows [][]string + for _, p := range rscPosts { + rec := map[string]any{"title": p["title"]} + if p["date"] != "" { + rec["publishedAt"] = p["date"] + } + if pu := SanitizeSchemaHTTPSURL(p["url"], baseURL); pu != "" { + rec["url"] = pu + wave3SocialAddLink(&links, seenLinks, pu, baseURL) + } + recs = append(recs, rec) + postRows = append(postRows, []string{ + wave3SocialTableCell(p["title"], 120), + wave3SocialFirstNonEmpty(escapeDeclMarkdownBrackets(p["date"]), "-"), + }) + } + if len(recs) == 0 { + rec := map[string]any{"creator": creatorName} + if rscCreation != "" { + rec["creating"] = rscCreation + } + if memberCount != "" { + rec["members"] = memberCount + } + if creatorDesc != "" { + rec["description"] = sliceRunesMax(creatorDesc, 400) + } + if creatorURL != "" { + rec["url"] = creatorURL + } + recs = append(recs, rec) + } + + var bullets []string + if rscCreation != "" { + bullets = append(bullets, "- **Creating**: "+escapeDeclMarkdownBrackets(rscCreation)) + } + if memberCount != "" { + bullets = append(bullets, "- **Members / Patrons**: "+escapeDeclMarkdownBrackets(memberCount)) + } + if creatorURL != "" { + bullets = append(bullets, "- **URL**: "+escapeDeclMarkdownBrackets(creatorURL)) + } + + blocks := []string{"# " + escapeDeclMarkdownBrackets(creatorName)} + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + if creatorDesc != "" { + blocks = append(blocks, "## About\n\n"+escapeDeclPlainTextPreservingNewlines(creatorDesc)) + } + if len(postRows) > 0 { + blocks = append(blocks, "## Public Posts\n\n"+formatDeclarativeGFMTable([]string{"Post", "Published"}, postRows)) + } + + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: creatorName, + Description: sliceRunesMax(wave3SocialFirstNonEmpty(creatorDesc, rscCreation), 260), + Author: creatorName, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: recs, + } +} diff --git a/internal/extract/wave3_social_creator_test.go b/internal/extract/wave3_social_creator_test.go new file mode 100644 index 0000000..0694c2d --- /dev/null +++ b/internal/extract/wave3_social_creator_test.go @@ -0,0 +1,664 @@ +package extract + +import ( + "encoding/json" + "net/url" + "os" + "path/filepath" + "regexp" + "strings" + "testing" + "time" + + "github.com/bartrumb/edgefetch/v2/internal/classify" +) + +func wave3SocialResolveManifest(t *testing.T, m *DeclarativeAdapterManifest, rawURL string) (*DeclarativeTwinMatch, bool) { + t.Helper() + u, err := url.Parse(rawURL) + if err != nil { + t.Fatalf("url.Parse(%q): %v", rawURL, err) + } + host := strings.TrimSuffix(strings.ToLower(u.Hostname()), ".") + rawParts := splitNonEmptyEscapedSegments(u.EscapedPath()) + return resolveManifestTwinOnParsedURL(m, u, host, rawParts, DeclarativeResolveOptions{}) +} + +func TestWave3SocialCreatorManifestsAndRouting(t *testing.T) { + catTIDs := []string{ + "youtube-data-api", + "threads-api", + "tumblr", + "farcaster-hub", + "nostr-relays", + "product-hunt", + "substack-notes-beehiiv", + "patreon-public", + } + + byID := make(map[string]*DeclarativeAdapterManifest) + claimedDomains := make(map[string]string) + + for _, id := range catTIDs { + raw, err := os.ReadFile(filepath.Join("manifests", id+".yaml")) + if err != nil { + t.Fatalf("read %s.yaml: %v", id, err) + } + m, err := ParseDeclarativeYAMLManifest(raw) + if err != nil { + t.Fatalf("ParseDeclarativeYAMLManifest(%s.yaml): %v", id, err) + } + if m.ID != id { + t.Fatalf("%s.yaml has mismatched id=%q", id, m.ID) + } + if m.Category != "commerce-social" { + t.Fatalf("%s.yaml must use category commerce-social, got %q", id, m.Category) + } + if m.AuthMode == "detect-only" || m.DetectOnly != nil { + t.Fatalf("%s.yaml uses retired detect-only", id) + } + for _, d := range m.Domains { + ld := strings.ToLower(strings.TrimSpace(d)) + if strings.Contains(ld, "*") { + t.Fatalf("%s.yaml unexpectedly claims wildcard domain %q", id, ld) + } + if prev, exists := claimedDomains[ld]; exists { + t.Fatalf("duplicate domain %q across %s and %s", ld, prev, id) + } + claimedDomains[ld] = id + } + for _, hr := range m.HTMLRoutes { + for _, b := range hr.Bullets { + if strings.ContainsAny(b.Label, "{}") { + t.Fatalf("%s.yaml bullet label contains {}: %q", id, b.Label) + } + } + } + byID[id] = m + } + + // Disjointness from ALL existing manifests in internal/extract/manifests/ + entries, err := os.ReadDir("manifests") + if err != nil { + t.Fatalf("ReadDir(manifests): %v", err) + } + catTSet := make(map[string]bool, len(catTIDs)) + for _, id := range catTIDs { + catTSet[id] = true + } + for _, ent := range entries { + if ent.IsDir() || !strings.HasSuffix(ent.Name(), ".yaml") { + continue + } + otherID := strings.TrimSuffix(ent.Name(), ".yaml") + if catTSet[otherID] { + continue + } + raw, err := os.ReadFile(filepath.Join("manifests", ent.Name())) + if err != nil { + t.Fatalf("read %s: %v", ent.Name(), err) + } + om, err := ParseDeclarativeYAMLManifest(raw) + if err != nil { + t.Fatalf("ParseDeclarativeYAMLManifest(%s): %v", ent.Name(), err) + } + for _, d := range om.Domains { + ld := strings.ToLower(strings.TrimSpace(d)) + if catOwner, overlap := claimedDomains[ld]; overlap { + t.Fatalf("Cat T %s overlaps %s domain %q", catOwner, om.ID, ld) + } + if strings.HasPrefix(ld, "*.") { + suf := ld[1:] + for cd, catOwner := range claimedDomains { + if strings.HasSuffix(cd, suf) && len(cd) > len(suf) { + t.Fatalf("Cat T %s domain %q overlaps wildcard %q in %s", catOwner, cd, ld, om.ID) + } + } + } + } + } + + // #393 youtube-data-api: www.googleapis.com ONLY (via universalEngine since googleapis.com is in PSL), /youtube/v3/{videos,channels,playlists,search}, NEVER youtube.com + yt := byID["youtube-data-api"] + if yt.AuthMode != "key" || !yt.UniversalEngine { + t.Fatalf("youtube-data-api must be auth_mode=key and universalEngine=true, got auth=%q univ=%v", yt.AuthMode, yt.UniversalEngine) + } + for _, goodYT := range []string{ + "https://www.googleapis.com/youtube/v3/videos?part=snippet&id=dQw4w9WgXcQ", + "https://www.googleapis.com/youtube/v3/channels?part=snippet&id=UC123", + "https://www.googleapis.com/youtube/v3/playlists?part=snippet&id=PL123", + "https://www.googleapis.com/youtube/v3/search?part=snippet&q=go", + } { + tm, ok := wave3SocialResolveManifest(t, yt, goodYT) + if !ok || tm == nil || tm.AuthMode != "key" || tm.route.Extract.JSONMode != "youtube_data_api_json" { + t.Fatalf("youtube-data-api failed to match %s: ok=%v tm=%+v", goodYT, ok, tm) + } + tmVal, okVal := ResolveTwinOnManifest(yt, goodYT) + if !okVal || tmVal == nil || tmVal.ID != "youtube-data-api" { + t.Fatalf("ResolveTwinOnManifest failed for %s: ok=%v", goodYT, okVal) + } + } + for _, badYT := range []string{ + "https://www.youtube.com/watch?v=dQw4w9WgXcQ", + "https://www.googleapis.com/youtube/v3/comments?id=123", + "https://www.googleapis.com/drive/v3/files", + "https://console.cloud.google.com/", + } { + if tm, ok := wave3SocialResolveManifest(t, yt, badYT); ok || tm != nil { + t.Fatalf("youtube-data-api must NOT match %s: %+v", badYT, tm) + } + } + + // #394 threads-api: graph.threads.net /v1.0/ (key) + threads.net/threads.com HTML + th := byID["threads-api"] + if tm, ok := wave3SocialResolveManifest(t, th, "https://graph.threads.net/v1.0/me?fields=id,username"); !ok || tm.AuthMode != "key" || tm.route.Extract.JSONMode != "threads_api_json" { + t.Fatalf("threads-api graph route failed: ok=%v tm=%+v", ok, tm) + } + if tm, ok := wave3SocialResolveManifest(t, th, "https://www.threads.net/@threads"); ok || tm != nil { + t.Fatalf("threads.net HTML must not match twin routes") + } + + // #395 tumblr: api.tumblr.com + www.tumblr.com ONLY (NO *.tumblr.com), /dashboard excluded + tb := byID["tumblr"] + if tm, ok := wave3SocialResolveManifest(t, tb, "https://api.tumblr.com/v2/blog/staff.tumblr.com/posts"); !ok || tm.AuthMode != "key" || tm.route.Extract.JSONMode != "tumblr_api_json" { + t.Fatalf("tumblr API route failed: ok=%v tm=%+v", ok, tm) + } + if tm, ok := wave3SocialResolveManifest(t, tb, "https://staff.tumblr.com/"); ok || tm != nil { + t.Fatalf("tumblr must NOT match PoW *.tumblr.com subdomain") + } + + // #396 farcaster-hub: Neynar key + fnames pub + universal /v1/{castsByFid,castById,userDataByFid} + fc := byID["farcaster-hub"] + if !fc.UniversalEngine { + t.Fatalf("farcaster-hub must set universalEngine: true") + } + if tm, ok := wave3SocialResolveManifest(t, fc, "https://hub-api.neynar.com/v1/castsByFid?fid=3"); !ok || tm.AuthMode != "key" || tm.route.Extract.JSONMode != "farcaster_hub_json" { + t.Fatalf("farcaster-hub Neynar route failed: ok=%v tm=%+v", ok, tm) + } + if tm, ok := wave3SocialResolveManifest(t, fc, "https://fnames.farcaster.xyz/transfers?fid=3"); !ok || tm.AuthMode != "pub" || tm.route.Extract.JSONMode != "farcaster_hub_json" { + t.Fatalf("farcaster-hub fnames route failed: ok=%v tm=%+v", ok, tm) + } + for _, univURL := range []string{ + "https://hub.example-hubble.org/v1/castsByFid?fid=3", + "https://hub.example-hubble.org/v1/castById?fid=3&hash=0x123", + "https://hub.example-hubble.org/v1/userDataByFid?fid=3", + } { + if tm, ok := wave3SocialResolveManifest(t, fc, univURL); !ok || tm.AuthMode != "pub" || tm.route.Extract.JSONMode != "farcaster_hub_json" { + t.Fatalf("farcaster-hub universal route failed for %s: ok=%v tm=%+v", univURL, ok, tm) + } + } + for _, badFC := range []string{ + "https://api.farcaster.xyz/v1/castsByFid?fid=3", + "https://client.farcaster.xyz/v1/castsByFid?fid=3", + "https://snapchain.farcaster.xyz/v1/castsByFid?fid=3", + } { + if tm, ok := wave3SocialResolveManifest(t, fc, badFC); ok || tm != nil { + t.Fatalf("farcaster-hub must exclude %s", badFC) + } + } + + // #397 nostr-relays: relay roots (including with and without trailing slash) -> nostr_relay_json + nr := byID["nostr-relays"] + for _, relayURL := range []string{"https://nos.lol/", "https://nos.lol", "https://purplepag.es/", "https://relay.primal.net/", "https://relay.damus.io/"} { + tm, ok := wave3SocialResolveManifest(t, nr, relayURL) + if !ok || tm == nil || tm.Accept != "application/nostr+json" || tm.route.Extract.JSONMode != "nostr_relay_json" { + t.Fatalf("nostr-relays root route failed for %s: ok=%v tm=%+v", relayURL, ok, tm) + } + } + if tm, ok := wave3SocialResolveManifest(t, nr, "https://nos.lol/about"); ok || tm != nil { + t.Fatalf("nostr-relays twin route must only match root /, not /about") + } + + // #398 product-hunt: POST /v2/api/graphql + ph := byID["product-hunt"] + if tm, ok := wave3SocialResolveManifest(t, ph, "https://api.producthunt.com/v2/api/graphql"); !ok || tm.Method != "POST" || tm.AuthMode != "key" || tm.route.Extract.JSONMode != "product_hunt_json" { + t.Fatalf("product-hunt GraphQL route failed: ok=%v tm=%+v", ok, tm) + } + + // #399 substack-notes-beehiiv: api.beehiiv.com (key) + substack.com htmlRoutes (no /notes/post/*, no *.beehiiv.com) + sb := byID["substack-notes-beehiiv"] + if tm, ok := wave3SocialResolveManifest(t, sb, "https://api.beehiiv.com/v2/publications/pub_123/posts"); !ok || tm.AuthMode != "key" || tm.route.Extract.JSONMode != "beehiiv_api_json" { + t.Fatalf("substack-notes-beehiiv Beehiiv route failed: ok=%v tm=%+v", ok, tm) + } + if tm, ok := wave3SocialResolveManifest(t, sb, "https://rss.beehiiv.com/feeds/abc.xml"); ok || tm != nil { + t.Fatalf("substack-notes-beehiiv must NOT match rss.beehiiv.com") + } + if len(sb.HTMLRoutes) != 1 { + t.Fatalf("substack-notes-beehiiv must have 1 htmlRoute") + } + // Verify /notes/post/123 is excluded while /@hamish and /@hamish/note/c-123 match + registerWave3SocialCreatorHTMLModes() + ssHTML := `Hamish | Substack

Hamish

` + if _, ok := ExtractHTMLOnManifest(sb, ssHTML, "https://substack.com/@hamish", "", nil); !ok { + t.Fatalf("substack-notes-beehiiv failed to match /@hamish") + } + if _, ok := ExtractHTMLOnManifest(sb, ssHTML, "https://substack.com/@hamish/note/c-696062135", "", nil); !ok { + t.Fatalf("substack-notes-beehiiv failed to match /@hamish/note/c-696062135") + } + if _, ok := ExtractHTMLOnManifest(sb, ssHTML, "https://substack.com/notes/post/12345", "", nil); ok { + t.Fatalf("substack-notes-beehiiv must NOT match robots-disallowed /notes/post/12345") + } + + // #400 patreon-public: auth_mode=html, NO routes, /api/ and /rss/ excluded + pt := byID["patreon-public"] + if pt.AuthMode != "html" || len(pt.Routes) != 0 || !pt.StrictRobots { + t.Fatalf("patreon-public must be auth_mode=html with 0 twin routes and strict_robots=true: %+v", pt) + } + ptHTML := `Kurzgesagt | Patreon

Kurzgesagt

` + if _, ok := ExtractHTMLOnManifest(pt, ptHTML, "https://www.patreon.com/cw/Kurzgesagt", "", nil); !ok { + t.Fatalf("patreon-public failed to match /cw/Kurzgesagt") + } + for _, disallowed := range []string{ + "https://www.patreon.com/api/posts?filter[campaign_id]=1", + "https://www.patreon.com/rss/Kurzgesagt", + "https://www.patreon.com/login", + } { + if _, ok := ExtractHTMLOnManifest(pt, ptHTML, disallowed, "", nil); ok { + t.Fatalf("patreon-public must NOT match disallowed path %s", disallowed) + } + } +} + +func TestWave3SocialCreatorJSONAndHTMLModes(t *testing.T) { + registerWave3SocialCreatorHTMLModes() + RegisterWave3SocialCreatorHTMLModes() + + expectedHTMLModes := []string{ + "threads_html", + "tumblr_html", + "farcaster_html", + "nostr_njump_html", + "product_hunt_html", + "substack_notes_html", + "patreon_public_html", + } + for _, hm := range expectedHTMLModes { + if getExternalHTMLModeLazy(hm) == nil { + t.Fatalf("RegisterExternalHTMLModeLazy missing %q", hm) + } + if !IsWave3SocialCreatorHTMLMode(hm) { + t.Fatalf("IsWave3SocialCreatorHTMLMode(%q) = false", hm) + } + } + + expectedJSONModes := []string{ + "youtube_data_api_json", + "threads_api_json", + "tumblr_api_json", + "farcaster_hub_json", + "nostr_relay_json", + "product_hunt_json", + "beehiiv_api_json", + } + for _, jm := range expectedJSONModes { + if !IsWave3SocialCreatorJSONMode(jm) { + t.Fatalf("IsWave3SocialCreatorJSONMode(%q) = false", jm) + } + } + + // #393 YouTube channel + search JSON + ytSearch := []byte(`{"kind":"youtube#searchListResponse","nextPageToken":"CAUQAA","pageInfo":{"totalResults":100},"items":[{"kind":"youtube#searchResult","id":{"kind":"youtube#video","videoId":"abc123"},"snippet":{"title":"Go WASI Tutorial","channelTitle":"Systems Lab","publishedAt":"2026-10-01T12:00:00Z","description":"Building fast WASI modules."}}]}`) + ytRaw, okYT := FormatWave3SocialCreatorJSONMode("youtube_data_api_json", ytSearch, nil, "https://www.googleapis.com/youtube/v3/search?part=snippet&q=wasi") + if !okYT || !strings.Contains(ytRaw, "Go WASI Tutorial") || !strings.Contains(ytRaw, "https://www.youtube.com/watch?v=abc123") { + t.Fatalf("youtube_data_api_json failed: ok=%v raw=%s", okYT, ytRaw) + } + + // #394 Threads list JSON + HTML fallback + thList := []byte(`{"data":[{"id":"101","username":"builder","text":"Hello from Threads API","media_type":"TEXT_POST","timestamp":"2026-11-28T10:00:00+0000","permalink":"https://www.threads.net/@builder/post/101"}],"paging":{"cursors":{"after":"CUR2"}}}`) + thDoc, okTH := FormatWave3SocialCreatorJSONDoc("threads_api_json", thList, nil, "https://graph.threads.net/v1.0/me/threads") + if !okTH || thDoc.NextCursor != "CUR2" || !strings.Contains(thDoc.Markdown, "Hello from Threads API") { + t.Fatalf("threads_api_json list failed: ok=%v doc=%+v", okTH, thDoc) + } + thHTML := `Builder on Threads

@builder

` + if resTH := Wave3SocialCreatorRunHTML("threads_html", thHTML, "https://www.threads.net/@builder", "threads-api"); resTH == nil || !strings.Contains(resTH.Markdown, "Sharing notes about open social protocols.") { + t.Fatalf("threads_html failed: %+v", resTH) + } + + // #395 Tumblr API v2 JSON + PoW HTML rejection + tbAPI := []byte(`{"meta":{"status":200,"msg":"OK"},"response":{"blog":{"name":"engineering","title":"Tumblr Engineering","description":"Systems notes"},"total_posts":1,"posts":[{"id_string":"9001","blog_name":"engineering","post_url":"https://www.tumblr.com/engineering/9001/scaling-feeds","type":"text","date":"2026-11-15 10:00:00 GMT","title":"Scaling Feeds","body":"

How we partition timeline writes.

","note_count":42}]}}`) + tbDoc, okTB := FormatWave3SocialCreatorJSONDoc("tumblr_api_json", tbAPI, nil, "https://api.tumblr.com/v2/blog/engineering.tumblr.com/posts") + if !okTB || !strings.Contains(tbDoc.Markdown, "Scaling Feeds") || !strings.Contains(tbDoc.Markdown, "partition timeline writes") { + t.Fatalf("tumblr_api_json failed: ok=%v doc=%+v", okTB, tbDoc) + } + if powRes := Wave3SocialCreatorRunHTML("tumblr_html", `Tumblr`, "https://www.tumblr.com/staff", "tumblr"); powRes != nil { + t.Fatalf("tumblr_html must reject PoW hashcash challenge") + } + + // #396 Farcaster Hubble castsByFid (Farcaster epoch timestamp) + farcaster_html + fcHubble := []byte(`{"messages":[{"data":{"type":"MESSAGE_TYPE_CAST_ADD","fid":3,"timestamp":120000000,"castAddBody":{"text":"Hello Farcaster Hub!","embeds":[{"url":"https://farcaster.xyz"}]}},"hash":"0xabc123"}],"nextPageToken":"page2"}`) + fcDoc, okFC := FormatWave3SocialCreatorJSONDoc("farcaster_hub_json", fcHubble, nil, "https://hub.example-hubble.org/v1/castsByFid?fid=3") + if !okFC || fcDoc.NextCursor != "page2" || !strings.Contains(fcDoc.Markdown, "Hello Farcaster Hub!") || !strings.Contains(fcDoc.Markdown, "2024-") { + t.Fatalf("farcaster_hub_json Hubble castsByFid failed: ok=%v doc=%+v", okFC, fcDoc) + } + fcHTML := `dwr on Farcaster

dwr

` + if resFC := Wave3SocialCreatorRunHTML("farcaster_html", fcHTML, "https://farcaster.xyz/dwr", "farcaster-hub"); resFC == nil || !strings.Contains(resFC.Markdown, "Working on Farcaster.") { + t.Fatalf("farcaster_html failed: %+v", resFC) + } + + // #397 Nostr plain NIP-11 + NIP-01 envelope sanitization + 20-event cap + njump HTML + plainNIP11 := []byte(`{"name":"relay.primal.net","description":"Primal public Nostr relay","pubkey":"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef","supported_nips":[1,11,42],"software":"https://github.com/PrimalHQ/primal-server","version":"2.1"}`) + nip11Doc, okN11 := FormatWave3SocialCreatorJSONDoc("nostr_relay_json", plainNIP11, nil, "https://relay.primal.net/") + if !okN11 || nip11Doc.Title != "relay.primal.net" || !strings.Contains(nip11Doc.Markdown, "Primal public Nostr relay") { + t.Fatalf("nostr_relay_json plain NIP-11 failed: ok=%v doc=%+v", okN11, nip11Doc) + } + // Verify >20 events capped to 20 and dangerous script/javascript links neutralized + var evObjs []map[string]any + for i := 0; i < 25; i++ { + evObjs = append(evObjs, map[string]any{ + "id": strings.Repeat("a", 64), + "pubkey": strings.Repeat("b", 64), + "created_at": 1732838400 + i, + "kind": 1, + "content": "Note [bad](javascript:alert(1)) ", + }) + } + envBytes, _ := json.Marshal(map[string]any{"relay": "https://nos.lol/", "nip11": map[string]any{"name": "nos.lol"}, "events": evObjs}) + envDoc, okEnv := FormatWave3SocialCreatorJSONDoc("nostr_relay_json", envBytes, nil, "https://nos.lol/") + if !okEnv || len(envDoc.Records) != 20 || strings.Contains(envDoc.Markdown, "

Claude 3.5 Sonnet

` + if resPH := Wave3SocialCreatorRunHTML("product_hunt_html", phHTML, "https://www.producthunt.com/posts/claude-3-5-sonnet", "product-hunt"); resPH == nil || !strings.Contains(resPH.Markdown, "Fast frontier intelligence model.") { + t.Fatalf("product_hunt_html failed: %+v", resPH) + } + + // #399 Beehiiv API v2 JSON + Substack Note permalink preloads-json + bhAPI := []byte(`{"data":[{"id":"post_1","title":"Weekly Systems Digest","subtitle":"Deep dive into edge workers","authors":["Ada Lovelace"],"status":"confirmed","publish_date":1732838400,"web_url":"https://digest.example.com/p/weekly-systems"}],"total_results":1}`) + if bhDoc, okBH := FormatWave3SocialCreatorJSONDoc("beehiiv_api_json", bhAPI, nil, "https://api.beehiiv.com/v2/publications/pub_1/posts"); !okBH || !strings.Contains(bhDoc.Markdown, "Weekly Systems Digest") { + t.Fatalf("beehiiv_api_json failed: ok=%v doc=%+v", okBH, bhDoc) + } + ssNoteHTML := `Note by Hamish | Substack` + if resSSN := Wave3SocialCreatorRunHTML("substack_notes_html", ssNoteHTML, "https://substack.com/@hamish/note/c-696062135", "substack-notes-beehiiv"); resSSN == nil || !strings.Contains(resSSN.Markdown, "Readers deserve direct control") { + t.Fatalf("substack_notes_html single note failed: %+v", resSSN) + } +} + +func TestWave3SocialCreatorFixturesGoldenAndNegativeShells(t *testing.T) { + registerWave3SocialCreatorHTMLModes() + + type fixtureNeg struct { + Name string `json:"name"` + Status int `json:"status"` + InputURL string `json:"inputUrl"` + FinalURL string `json:"finalUrl"` + Payload string `json:"payload"` + } + type fixtureDoc struct { + AdapterID string `json:"adapterId"` + Mode string `json:"mode"` + InputURL string `json:"inputUrl"` + ExpectedFetchURL string `json:"expectedFetchUrl"` + MockPayload string `json:"mockPayload"` + ExpectTitleIncludes string `json:"expectTitleIncludes"` + ExpectMarkdownIncludes []string `json:"expectMarkdownIncludes"` + NegativeCases []fixtureNeg `json:"negativeCases"` + } + + ids := []string{ + "youtube-data-api", + "threads-api", + "tumblr", + "farcaster-hub", + "nostr-relays", + "product-hunt", + "substack-notes-beehiiv", + "patreon-public", + } + + hostileHTML := `Social

Social

` + strings.Repeat(`
` + + for _, id := range ids { + fpath := filepath.Join("..", "..", "hub", "test", "fixtures", "adapters", id+".json") + raw, err := os.ReadFile(fpath) + if err != nil { + t.Fatalf("read fixture %s: %v", fpath, err) + } + var fx fixtureDoc + if err := json.Unmarshal(raw, &fx); err != nil { + t.Fatalf("unmarshal fixture %s: %v", fpath, err) + } + if fx.AdapterID != id { + t.Fatalf("%s: adapterId=%q != %q", id, fx.AdapterID, id) + } + if len(fx.NegativeCases) < 4 { + t.Fatalf("%s: expected >= 4 negativeCases, got %d", id, len(fx.NegativeCases)) + } + + mRaw, err := os.ReadFile(filepath.Join("manifests", id+".yaml")) + if err != nil { + t.Fatalf("read %s.yaml: %v", id, err) + } + m, err := ParseDeclarativeYAMLManifest(mRaw) + if err != nil { + t.Fatalf("parse %s.yaml: %v", id, err) + } + + start := time.Now() + var gotTitle, gotMD string + if fx.Mode == "twin" { + tm, ok := wave3SocialResolveManifest(t, m, fx.InputURL) + if !ok || tm == nil { + t.Fatalf("%s: failed to resolve twin for %s", id, fx.InputURL) + } + if fx.ExpectedFetchURL != "" && tm.FetchURL != fx.ExpectedFetchURL { + t.Fatalf("%s: FetchURL=%q, want %q", id, tm.FetchURL, fx.ExpectedFetchURL) + } + doc, okDoc := FormatWave3SocialCreatorJSONDoc(tm.route.Extract.JSONMode, []byte(fx.MockPayload), tm.params, fx.InputURL) + if !okDoc || doc == nil { + t.Fatalf("%s: FormatWave3SocialCreatorJSONDoc(%s) failed", id, tm.route.Extract.JSONMode) + } + gotTitle, gotMD = doc.Title, doc.Markdown + } else { + if len(m.HTMLRoutes) == 0 { + t.Fatalf("%s: expected htmlRoutes", id) + } + res := Wave3SocialCreatorRunHTML(m.HTMLRoutes[0].Mode, fx.MockPayload, fx.InputURL, id) + if res == nil { + t.Fatalf("%s: Wave3SocialCreatorRunHTML(%s) returned nil on golden payload", id, m.HTMLRoutes[0].Mode) + } + gotTitle, gotMD = res.Title, res.Markdown + } + if elapsed := time.Since(start); elapsed > 25*time.Millisecond*time.Duration(extractRaceSlowdown) { + t.Fatalf("%s: golden extraction took %v (> 25ms)", id, elapsed) + } + if fx.ExpectTitleIncludes != "" && !strings.Contains(gotTitle, fx.ExpectTitleIncludes) { + t.Fatalf("%s: title %q missing %q", id, gotTitle, fx.ExpectTitleIncludes) + } + for _, sub := range fx.ExpectMarkdownIncludes { + if !strings.Contains(gotMD, sub) { + t.Fatalf("%s: markdown missing %q\nmarkdown:\n%s", id, sub, gotMD) + } + } + + // Hostile unclosed div 100KB perf budget (< 75ms) on HTML modes + if len(m.HTMLRoutes) > 0 { + hStart := time.Now() + _ = Wave3SocialCreatorRunHTML(m.HTMLRoutes[0].Mode, hostileHTML, fx.InputURL, id) + if hElapsed := time.Since(hStart); hElapsed > 75*time.Millisecond*time.Duration(extractRaceSlowdown) { + t.Fatalf("%s: hostile unclosed-div HTML took %v (> 75ms)", id, hElapsed) + } + } + + for _, nc := range fx.NegativeCases { + negURL := fx.InputURL + if nc.FinalURL != "" { + negURL = nc.FinalURL + } else if nc.InputURL != "" { + negURL = nc.InputURL + } + if len(m.HTMLRoutes) > 0 { + if res := Wave3SocialCreatorRunHTML(m.HTMLRoutes[0].Mode, nc.Payload, negURL, id); res != nil { + t.Fatalf("%s:%s: HTML mode unexpectedly extracted content on negative case", id, nc.Name) + } + } + if tm, ok := wave3SocialResolveManifest(t, m, negURL); ok && tm != nil && tm.route.Extract.JSONMode != "" { + if doc, okDoc := FormatWave3SocialCreatorJSONDoc(tm.route.Extract.JSONMode, []byte(nc.Payload), tm.params, negURL); okDoc && doc != nil { + t.Fatalf("%s:%s: JSON mode unexpectedly formatted negative payload", id, nc.Name) + } + } + st := nc.Status + if st == 0 { + st = 200 + } + if st >= 200 && st < 300 && strings.HasPrefix(strings.TrimSpace(nc.Payload), "<") { + ext := ExtractHTMLDocumentFull(nc.Payload, FullExtractOptions{ + BaseURL: negURL, + OnlyMainContent: true, + }) + cs := classify.ClassifyContentStateFull(classify.ContentStateInput{ + Status: st, + RawHTML: nc.Payload, + Markdown: ext.Markdown, + URL: fx.InputURL, + FinalURL: negURL, + Title: wave3SocialExtractTitleBounded(nc.Payload), + }) + if cs.State == "active" { + t.Fatalf("%s:%s (status=%d): ClassifyContentStateFull unexpectedly returned active (%s)", id, nc.Name, st, cs.Reason) + } + } + } + } +} + +func TestWave3SocialCreatorR7MarkdownHardening(t *testing.T) { + registerWave3SocialCreatorHTMLModes() + reInjectedHeading := regexp.MustCompile(`(?m)^#{1,6}[ \t]+InjectedHeading`) + + // 1. #397 nostr_relay_json: NIP-11 name/description + NIP-01 event content + nostrPayload, err := json.Marshal(map[string]any{ + "relay": "https://nos.lol/", + "nip11": map[string]any{ + "name": "Relay [Phish](https://evil.example/nname)", + "description": "Desc [Phish](https://evil.example/ndesc)\n# InjectedHeading", + "software": "https://github.com/nostr-protocol/nips", + }, + "events": []map[string]any{ + { + "id": strings.Repeat("a", 64), + "pubkey": strings.Repeat("b", 64), + "created_at": 1732838400, + "kind": 1, + "content": "Hello [Phish](https://evil.example/nev) ", + }, + }, + }) + if err != nil { + t.Fatalf("json.Marshal(nostr): %v", err) + } + nostrDoc, okNostr := FormatWave3SocialCreatorJSONDoc("nostr_relay_json", nostrPayload, nil, "https://nos.lol/") + if !okNostr || nostrDoc == nil { + t.Fatalf("nostr_relay_json R7 payload failed: ok=%v doc=%+v", okNostr, nostrDoc) + } + if hasUnescapedClickableEvilLinkR10(nostrDoc.Markdown) || strings.Contains(nostrDoc.Markdown, "[Phish](") || !strings.Contains(nostrDoc.Markdown, `\[Phish\]`) { + t.Fatalf("nostr_relay_json leaked unescaped Markdown link:\n%s", nostrDoc.Markdown) + } + for _, wantEsc := range []string{ + `Relay \[Phish\]\(https://evil.example/nname)`, + `Desc \[Phish\]\(https://evil.example/ndesc)`, + `Hello \[Phish\]\(https://evil.example/nev)`, + `\# InjectedHeading`, + } { + if !strings.Contains(nostrDoc.Markdown, wantEsc) { + t.Fatalf("nostr_relay_json missing escaped substring %q in Markdown:\n%s", wantEsc, nostrDoc.Markdown) + } + } + if reInjectedHeading.MatchString(nostrDoc.Markdown) { + t.Fatalf("nostr_relay_json allowed injected heading in Markdown:\n%s", nostrDoc.Markdown) + } + if !strings.Contains(nostrDoc.Title, "[Phish]") { + t.Fatalf("nostr_relay_json Title should remain unescaped plain text, got %q", nostrDoc.Title) + } + if len(nostrDoc.Records) == 0 { + t.Fatalf("nostr_relay_json expected >= 1 record") + } + recContent, _ := nostrDoc.Records[0]["content"].(string) + if !strings.Contains(recContent, "Hello [Phish](https://evil.example/nev)") || strings.Contains(recContent, "` + ssRes := Wave3SocialCreatorRunHTML("substack_notes_html", ssHTML, "https://substack.com/@author_soc/note/c-r7", "substack-notes-beehiiv") + if ssRes == nil { + t.Fatalf("substack_notes_html R7 returned nil") + } + if hasUnescapedClickableEvilLinkR10(ssRes.Markdown) || strings.Contains(ssRes.Markdown, "[Phish](") || !strings.Contains(ssRes.Markdown, `\[Phish\]`) || reInjectedHeading.MatchString(ssRes.Markdown) { + t.Fatalf("substack_notes_html leaked unescaped Markdown or injected heading:\n%s", ssRes.Markdown) + } + if !strings.Contains(ssRes.Title, "[Phish]") { + t.Fatalf("substack_notes_html Title should remain unescaped, got %q", ssRes.Title) + } + if recBody, _ := ssRes.Records[0]["body"].(string); !strings.Contains(recBody, "Note body [Phish](https://evil.example/soc)") { + t.Fatalf("substack_notes_html Records[0][body] should remain unescaped, got %q", recBody) + } +} diff --git a/internal/extract/wave3_store_addons.go b/internal/extract/wave3_store_addons.go new file mode 100644 index 0000000..cedbd52 --- /dev/null +++ b/internal/extract/wave3_store_addons.go @@ -0,0 +1,2123 @@ +package extract + +import ( + "bytes" + "encoding/json" + "fmt" + stdhtml "html" + "math" + "net/url" + "strconv" + "strings" +) + +const ( + wave3StoreMaxHTMLBytes = 2 * 1024 * 1024 + wave3StoreMaxJSONBytes = 4 * 1024 * 1024 + wave3StoreMaxRecords = 30 +) + +var ( + wave3StoreRxNotFoundTitle = newLazyRegexp(`(?i)(?:^|\b)(?:404|410|page\s+not\s+found|page\s+cannot\s+be\s+found|not\s+found|error\s*404|we\s+couldn'?t\s+find\s+that\s+page|access\s+denied|request\s+(?:rejected|blocked)|could\s+not\s+be\s+satisfied|unauthorized|attention\s+required|just\s+a\s+moment|403\s+forbidden|forbidden|tracking\s+not\s+found|shipment\s+not\s+found|article\s+not\s+found|product\s+not\s+found)(?:\b|$)`) + wave3StoreRxMaintTitle = newLazyRegexp(`(?i)(?:scheduled\s+maintenance|temporarily\s+unavailable|service\s+unavailable|site\s+maintenance|under\s+maintenance|502\s+bad\s+gateway|503\s+service|down\s+for\s+maintenance)`) + wave3StoreRxErrorTitle = newLazyRegexp(`(?i)^(?:(?:(?:401|403|404|410|429|500|502|503)\s+)?(?:internal\s+)?server\s+error|application\s+error|system\s+error|unexpected\s+error|error\s+page|(?:401|403|404|410|429|500|502|503|http\s+\d{3})\s+error|error\s+(?:401|403|404|410|429|500|502|503)|error)(?:\s*[|\-\x{2013}\x{2014}:]\s*.*)?$|^.*(?:\s*[|\-\x{2013}\x{2014}:]\s*error)$`) + wave3StoreRxGenericHead = newLazyRegexp(`(?i)^(?:loading\.{0,3}|home|welcome|search|menu|navigation|route\s+tracking)$`) + wave3StoreRxCurrency3 = newLazyRegexp(`^[A-Z]{3}$`) + wave3StoreRxISODate = newLazyRegexp(`^(\d{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\d|3[01]))(?:$|T\d{2}:\d{2}| \d{2}:\d{2})`) + wave3StoreRxSpace = newLazyRegexp(`[ \t\r\n]+`) + wave3StoreRxKlaviyoCID = newLazyRegexp(`(?i)(?:static\.klaviyo\.com/onsite/js/(?:([A-Za-z0-9]{4,16})/klaviyo\.js|klaviyo\.js\?company_id=([A-Za-z0-9]{4,16}))|[?&]company_id=([A-Za-z0-9]{4,16})|_learnq\.push\(\s*\[\s*['"]account['"]\s*,\s*['"]([A-Za-z0-9]{4,16})['"])`) + wave3StoreRxKlaviyoFormID = newLazyRegexp(`(?i)(?:data-klaviyo-form-id\s*=\s*["']([A-Za-z0-9]{4,16})["']|klaviyo-form-([A-Za-z0-9]{4,16}))`) + wave3StoreRxAttentiveTag = newLazyRegexp(`(?i)https?://cdn\.attn\.tv/([a-z0-9_-]{2,64})/dtag\.js`) + wave3StoreRxSellingSize = newLazyRegexp(`(?i)selling_plans_size\s*[:=]\s*["']?(\d+)["']?`) + wave3StoreRxRechargeShop = newLazyRegexp(`(?i)rechargecdn\.com/[^\s"'<>]*[?&]shop=([a-z0-9.-]+)`) + wave3StoreRxProductJSONLD = newLazyRegexp(`(?i)"@type"\s*:\s*(?:"(?:https?://schema\.org/)?(?:Product|ProductGroup|Article|NewsArticle|BlogPosting|Recipe|Event|Course|JobPosting)"|\[[^\]]{0,240}"(?:https?://schema\.org/)?(?:Product|ProductGroup|Article|NewsArticle|BlogPosting|Recipe|Event|Course|JobPosting)")`) + wave3StoreRxOGTypeProduct = newLazyRegexp(`(?is)]*(?:property\s*=\s*["']og:type["'][^>]*content\s*=\s*["']product["']|content\s*=\s*["']product["'][^>]*property\s*=\s*["']og:type["'])`) + wave3StoreRxHydratedTrack = newLazyRegexp(`(?i)(?:"trackingNumber"|"tracking_number"|"checkpoints"|"trackingStatus"|"deliveryStatus"|"orderNumber"|"order_number"|"courierSlug"|"slug"\s*:\s*"(?:ups|usps|fedex|dhl|ontrac|lasership|dpd|royal-mail))`) +) + +func init() { + for _, mode := range []string{ + "shopify_hydrogen_html", + "recharge_bold_subscriptions_html", + "shopify_filter_apps_html", + "rebuy_searchanise_html", + "aftership_tracking_html", + "branded_tracking_pack_html", + "gorgias_reamaze_html", + "klaviyo_attentive_forms_html", + } { + m := mode + RegisterExternalHTMLModeLazy(m, func(rawHTML, baseURL string, _ func() string, extractorID string) *DeclarativePostFetchResult { + return Wave3StoreAddonsRunHTML(m, rawHTML, baseURL, extractorID) + }) + } +} + +// IsWave3StoreAddonsHTMLMode reports whether mode is handled by Category I Store Add-Ons HTML extractors (#263-#270). +func IsWave3StoreAddonsHTMLMode(mode string) bool { + switch mode { + case "shopify_hydrogen_html", + "recharge_bold_subscriptions_html", + "shopify_filter_apps_html", + "rebuy_searchanise_html", + "aftership_tracking_html", + "branded_tracking_pack_html", + "gorgias_reamaze_html", + "klaviyo_attentive_forms_html": + return true + default: + return false + } +} + +// IsWave3StoreAddonsJSONMode reports whether mode is handled by Category I Store Add-Ons JSON formatters (#265, #266). +func IsWave3StoreAddonsJSONMode(mode string) bool { + switch mode { + case "shopify_filter_apps_json", + "rebuy_searchanise_json": + return true + default: + return false + } +} + +func wave3StoreDefaultExtractorID(mode string) string { + switch mode { + case "shopify_hydrogen_html": + return "shopify-hydrogen" + case "recharge_bold_subscriptions_html": + return "recharge-bold-subscriptions" + case "shopify_filter_apps_html", "shopify_filter_apps_json": + return "shopify-filter-apps" + case "rebuy_searchanise_html", "rebuy_searchanise_json": + return "rebuy-searchanise" + case "aftership_tracking_html": + return "aftership-tracking-page" + case "branded_tracking_pack_html": + return "branded-tracking-pack" + case "gorgias_reamaze_html": + return "gorgias-reamaze" + case "klaviyo_attentive_forms_html": + return "klaviyo-attentive-forms" + default: + return "" + } +} + +func wave3StoreMatchesModePrefilter(mode, rawHTML string) bool { + probe256K := rawHTML + if len(probe256K) > 256*1024 { + probe256K = probe256K[:256*1024] + } + switch mode { + case "shopify_hydrogen_html": + return containsAnyFoldASCIIExtract(probe256K, "__remixcontext") + case "recharge_bold_subscriptions_html": + return containsAnyFoldASCIIExtract(rawHTML, + "rechargecdn.com", "rechargepayments.com", "rc-widget", "rc-selling-plans", + "variant-purchase-selector", "selling_plans_size", "selling_plan_groups", + "boldapps.net", "bold-subscriptions", "bold_subscriptions", "bold-ro__", "bsub-widget", + ) + case "aftership_tracking_html": + if containsAnyFoldASCIIExtract(probe256K, "aftership") { + return true + } + return containsAnyFoldASCIIExtract(rawHTML, "__next_data__") && containsAnyFoldASCIIExtract(probe256K, "tracking", "checkpoint") + case "branded_tracking_pack_html": + return containsAnyFoldASCIIExtract(probe256K, "narvar", "parcelpanel", "routeapp.io", "tracking.route.com", "route tracking", "malomo", "wonderment") + case "gorgias_reamaze_html": + return containsAnyFoldASCIIExtract(rawHTML, "gorgias.help", "gorgias-help", "reamaze.com") || containsAnyFoldASCIIExtract(probe256K, "reamaze") + case "klaviyo_attentive_forms_html": + return containsAnyFoldASCIIExtract(rawHTML, "static.klaviyo.com", "klaviyo.js", "klaviyo-form", "_learnq", "cdn.attn.tv", "attn.tv") + default: + return true + } +} + +// 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 Wave3StoreAddonsRunHTML(mode, rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + switch mode { + case "shopify_filter_apps_html", "rebuy_searchanise_html": + // Companion-only page-key modes return nil in HTML extraction so they never preempt + // shopify_html in alphabetical reg.universal order or block Tier 1A/1B auto-twins. + return nil + } + if !IsWave3StoreAddonsHTMLMode(mode) || len(rawHTML) == 0 || strings.IndexByte(rawHTML, '<') < 0 || strings.IndexByte(rawHTML, '>') < 0 { + return nil + } + if len(rawHTML) > wave3StoreMaxHTMLBytes { + rawHTML = truncateUTF8SafeFullDocGo(rawHTML, wave3StoreMaxHTMLBytes) + } + trimmed := strings.TrimLeft(rawHTML, " \t\r\n") + if trimmed == "" || trimmed[0] == '{' || trimmed[0] == '[' { + return nil + } + if !wave3StoreMatchesModePrefilter(mode, rawHTML) { + return nil + } + if wave3StoreHasNegativeShell(rawHTML, baseURL) { + return nil + } + if extractorID == "" { + extractorID = wave3StoreDefaultExtractorID(mode) + } + + var res *DeclarativePostFetchResult + switch mode { + case "shopify_hydrogen_html": + res = wave3StoreExtractHydrogenHTML(rawHTML, baseURL, extractorID) + case "recharge_bold_subscriptions_html": + res = wave3StoreExtractRechargeBoldHTML(rawHTML, baseURL, extractorID) + case "aftership_tracking_html": + res = wave3StoreExtractAfterShipHTML(rawHTML, baseURL, extractorID) + case "branded_tracking_pack_html": + res = wave3StoreExtractBrandedTrackingHTML(rawHTML, baseURL, extractorID) + case "gorgias_reamaze_html": + res = wave3StoreExtractGorgiasReamazeHTML(rawHTML, baseURL, extractorID) + case "klaviyo_attentive_forms_html": + res = wave3StoreExtractKlaviyoAttentiveHTML(rawHTML, baseURL, extractorID) + } + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return nil + } + return res +} + +// RunWave3StoreAddonsHTMLMode executes a Category I HTML extractor and returns JSON-marshaled DeclarativePostFetchResult. +func RunWave3StoreAddonsHTMLMode(mode, rawHTML, baseURL string) (string, bool) { + res := Wave3StoreAddonsRunHTML(mode, rawHTML, baseURL, wave3StoreDefaultExtractorID(mode)) + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return "", false + } + res = sanitizePostFetchResultDeclHTML(res) + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return "", false + } + encoded, err := json.Marshal(res) + if err != nil { + return "", false + } + return string(encoded), true +} + +// FormatWave3StoreAddonsJSONDoc formats a Category I Store Add-Ons JSON payload into DeclarativeFormattedDoc. +func FormatWave3StoreAddonsJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool) { + if !IsWave3StoreAddonsJSONMode(mode) || len(raw) == 0 || len(raw) > wave3StoreMaxJSONBytes { + return nil, false + } + payload := bytes.TrimSpace(bytes.TrimPrefix(raw, []byte("\xEF\xBB\xBF"))) + if len(payload) == 0 || (payload[0] != '{' && payload[0] != '[') { + return nil, false + } + parsed, ok := decodeJSONWithNumbers(payload) + if !ok || parsed == nil { + return nil, false + } + var doc *DeclarativeFormattedDoc + var handled bool + switch mode { + case "shopify_filter_apps_json": + doc, handled = wave3StoreFormatFilterAppsJSON(parsed, origURL) + case "rebuy_searchanise_json": + doc, handled = wave3StoreFormatRebuySearchaniseJSON(parsed, origURL) + } + if !handled || doc == nil || strings.TrimSpace(doc.Markdown) == "" { + return nil, false + } + return wave3StoreFinalizeDoc(doc), true +} + +// FormatWave3StoreAddonsJSONMode formats a Category I JSON payload and returns JSON-marshaled DeclarativeFormattedDoc. +func FormatWave3StoreAddonsJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool) { + doc, ok := FormatWave3StoreAddonsJSONDoc(mode, raw, params, origURL) + if !ok || doc == nil { + return "", false + } + encoded, err := json.Marshal(doc) + if err != nil { + return "", false + } + return string(encoded), true +} + +// ── Shared Hygiene & Validation Helpers ───────────────────────────────────────────────────────── + +func wave3StoreIntPtr(v int) *int { return &v } +func wave3StoreBoolPtr(v bool) *bool { return &v } + +func wave3StoreFinalizeDoc(doc *DeclarativeFormattedDoc) *DeclarativeFormattedDoc { + if doc == nil { + return nil + } + if len(doc.Records) > wave3StoreMaxRecords { + if doc.Total == nil { + doc.Total = wave3StoreIntPtr(len(doc.Records)) + } + doc.Records = doc.Records[:wave3StoreMaxRecords] + doc.Returned = wave3StoreIntPtr(len(doc.Records)) + doc.Truncated = wave3StoreBoolPtr(true) + if doc.NextCursor == "" { + doc.NextCursor = strconv.Itoa(len(doc.Records)) + } + } + if sanitized, ok := sanitizeDeclarativeFormattedDocGo(doc); ok && sanitized != nil { + return sanitized + } + return nil +} + +func wave3StoreCleanText(s string) string { + if s == "" { + return "" + } + s = stdhtml.UnescapeString(s) + s = stripTagsInlineLinear(s) + s = wave3StoreRxSpace.ReplaceAllString(s, " ") + return strings.TrimSpace(s) +} + +func wave3StorePlain(v any, maxLen int) string { + return SanitizeSchemaPlainField(v, maxLen) +} + +func wave3StoreFirstNonEmpty(vals ...string) string { + for _, v := range vals { + if strings.TrimSpace(v) != "" { + return strings.TrimSpace(v) + } + } + return "" +} + +func wave3StoreLowerProbe(rawHTML string, maxBytes int) string { + return strings.ToLower(truncateUTF8SafeFullDocGo(rawHTML, maxBytes)) +} + +func wave3StoreCollectWindows(rawHTML string, anchors []string, back, fwd, maxHits int) string { + if rawHTML == "" || len(anchors) == 0 || maxHits <= 0 { + return "" + } + var sb strings.Builder + hits := 0 + for _, anchor := range anchors { + pos := 0 + for pos < len(rawHTML) && hits < maxHits { + rel := indexFoldASCIIExtract(rawHTML[pos:], anchor) + if rel < 0 { + break + } + hit := pos + rel + start := hit - back + if start < 0 { + start = 0 + } + end := hit + fwd + if end > len(rawHTML) { + end = len(rawHTML) + } + sb.WriteString(rawHTML[start:end]) + sb.WriteByte('\n') + hits++ + pos = hit + len(anchor) + } + if hits >= maxHits { + break + } + } + return sb.String() +} + +func wave3StoreValidateCurrency(raw string) string { + c := strings.ToUpper(strings.TrimSpace(raw)) + if wave3StoreRxCurrency3.MatchString(c) { + return c + } + return "" +} + +func wave3StoreValidatePrice(v any) (string, bool) { + switch t := v.(type) { + case json.Number: + f, err := t.Float64() + if err != nil || math.IsNaN(f) || math.IsInf(f, 0) || f < 0 { + return "", false + } + return strconv.FormatFloat(f, 'f', 2, 64), true + case float64: + if math.IsNaN(t) || math.IsInf(t, 0) || t < 0 { + return "", false + } + return strconv.FormatFloat(t, 'f', 2, 64), true + case int: + if t < 0 { + return "", false + } + return strconv.Itoa(t) + ".00", true + case string: + s := strings.TrimSpace(t) + if s == "" { + return "", false + } + clean := strings.TrimSpace(strings.TrimLeft(s, "$€£¥")) + clean = strings.ReplaceAll(clean, ",", "") + f, err := strconv.ParseFloat(clean, 64) + if err != nil || math.IsNaN(f) || math.IsInf(f, 0) || f < 0 { + return "", false + } + return strconv.FormatFloat(f, 'f', 2, 64), true + default: + return "", false + } +} + +func wave3StoreValidateISODate(raw string) string { + s := strings.TrimSpace(raw) + if m := wave3StoreRxISODate.FindStringSubmatch(s); len(m) == 2 { + return m[1] + } + return "" +} + +func wave3StoreResolveURL(rawRef, baseURL string) string { + ref := strings.TrimSpace(stdhtml.UnescapeString(rawRef)) + if ref == "" || strings.HasPrefix(ref, "#") || strings.HasPrefix(strings.ToLower(ref), "javascript:") || strings.HasPrefix(strings.ToLower(ref), "mailto:") { + return "" + } + if strings.HasPrefix(ref, "//") { + ref = "https:" + ref + } + u, err := url.Parse(ref) + if err != nil { + return "" + } + if !u.IsAbs() && baseURL != "" { + if bu, bErr := url.Parse(baseURL); bErr == nil { + u = bu.ResolveReference(u) + } + } + if u.Scheme != "https" && u.Scheme != "http" { + return "" + } + return u.String() +} + +func wave3StoreHTMLToMD(frag, baseURL string) (string, []string) { + trimmed := strings.TrimSpace(frag) + if trimmed == "" { + return "", nil + } + if !strings.Contains(trimmed, "<") { + return SanitizeSchemaPlainField(trimmed, 8000), nil + } + ext := ExtractHTMLDocumentFull(""+trimmed+"", FullExtractOptions{ + BaseURL: baseURL, + OnlyMainContent: false, + IncludeImages: true, + IsFragment: true, + SkipUniversalExtractors: true, + SkipPlainText: true, + }) + return ext.Markdown, ext.Links +} + +func wave3StoreIsNegativeURL(baseURL string) bool { + u, err := url.Parse(strings.TrimSpace(baseURL)) + if err != nil { + return false + } + p := strings.ToLower(u.Path) + for _, seg := range strings.Split(p, "/") { + switch seg { + case "error", "404", "403", "500", "502", "503", "not-found", "page-not-found", "maintenance", "unavailable", "cdn-cgi": + return true + } + } + return strings.Contains(p, "/cdn-cgi/challenge") +} + +func wave3StoreHasNegativeShell(rawHTML, baseURL string) bool { + if wave3StoreIsNegativeURL(baseURL) { + return true + } + probe := rawHTML + if len(probe) > 64*1024 { + probe = probe[:64*1024] + } + low := strings.ToLower(probe) + + // Cloudflare / WAF / anti-bot challenges (must reject honestly without bypass) + if strings.Contains(low, "cf-mitigated") || + strings.Contains(low, "cf-turnstile") || + strings.Contains(low, "cdn-cgi/challenge-platform") || + strings.Contains(low, "checking your browser before accessing") || + strings.Contains(low, "enable javascript and cookies to continue") || + strings.Contains(low, "attention required! | cloudflare") || + strings.Contains(low, "ddos-guard") || + strings.Contains(low, "px-captcha") { + return true + } + + doc := ParseHTMLDoc(probe, 64*1024) + title := strings.TrimSpace(doc.Text("title")) + h1 := strings.TrimSpace(doc.Text("h1")) + if wave3StoreRxNotFoundTitle.MatchString(title) || wave3StoreRxMaintTitle.MatchString(title) || wave3StoreRxErrorTitle.MatchString(title) { + return true + } + if wave3StoreRxNotFoundTitle.MatchString(h1) || wave3StoreRxMaintTitle.MatchString(h1) || wave3StoreRxErrorTitle.MatchString(h1) { + return true + } + if strings.Contains(low, "scheduled maintenance") || strings.Contains(low, "down for maintenance") || strings.Contains(low, "temporarily unavailable") { + if len(wave3StoreCleanText(doc.Text("body"))) < 800 { + return true + } + } + + // Empty SPA/CSR shell check (when no hydration payloads with data exist) + bodyText := wave3StoreCleanText(doc.Text("body")) + if len(bodyText) < 120 && + !strings.Contains(low, "__next_data__") && + !strings.Contains(low, "__remixcontext") && + !strings.Contains(low, "selling_plan") && + !strings.Contains(low, "ld+json") && + !strings.Contains(low, "klaviyo") && + !strings.Contains(low, "attn.tv") { + if strings.Contains(low, `id="root"`) || strings.Contains(low, `id='root'`) || + strings.Contains(low, `id="app"`) || strings.Contains(low, `id='app'`) || + strings.Contains(low, `id="__next"`) || strings.Contains(low, `id="__nuxt"`) || + wave3StoreRxGenericHead.MatchString(title) { + return true + } + } + return false +} + +func wave3StoreExtractScriptJSONByID(rawHTML, scriptID string) (any, bool) { + marker := fmt.Sprintf(`id="%s"`, scriptID) + idx := indexFoldASCIIExtract(rawHTML, strings.ToLower(marker)) + if idx < 0 { + markerSQ := fmt.Sprintf(`id='%s'`, scriptID) + idx = indexFoldASCIIExtract(rawHTML, strings.ToLower(markerSQ)) + } + if idx < 0 { + return nil, false + } + gt := strings.IndexByte(rawHTML[idx:], '>') + if gt < 0 { + return nil, false + } + start := idx + gt + 1 + endRel := indexFoldASCIIExtract(rawHTML[start:], "") + if endRel < 0 || endRel > 1024*1024 { + return nil, false + } + rawJSON := strings.TrimSpace(rawHTML[start : start+endRel]) + if rawJSON == "" || (rawJSON[0] != '{' && rawJSON[0] != '[') { + return nil, false + } + return decodeJSONWithNumbers([]byte(rawJSON)) +} + +func wave3StoreAppendLink(links *[]string, seen map[string]bool, rawURL string) { + if rawURL == "" || seen[rawURL] || len(*links) >= 40 { + return + } + seen[rawURL] = true + *links = append(*links, rawURL) +} + +func wave3StoreAsMap(v any) map[string]any { + m, _ := v.(map[string]any) + return m +} + +func wave3StoreAsSlice(v any) []any { + s, _ := v.([]any) + return s +} + +func wave3StoreIsJSONError(obj map[string]any) bool { + if obj == nil { + return true + } + if errVal, ok := obj["error"]; ok && errVal != nil && errVal != false && errVal != "" { + return true + } + if st := strings.ToLower(wave3StorePlain(obj["status"], 40)); st == "error" || st == "fail" || st == "failed" || st == "forbidden" || st == "unauthorized" { + return true + } + if code, ok := obj["statusCode"]; ok { + if f, okF := jsonValueToFloat(code); okF && f >= 400 { + return true + } + } + if code, ok := obj["status_code"]; ok { + if f, okF := jsonValueToFloat(code); okF && f >= 400 { + return true + } + } + return false +} + +// ── #262: Shopify Storefront GraphQL JSON Formatter ───────────────────────────────────────────── + +func wave3StoreExtractGraphQLNodes(conn map[string]any) []map[string]any { + if conn == nil { + return nil + } + var out []map[string]any + if edges := wave3StoreAsSlice(conn["edges"]); len(edges) > 0 { + for _, e := range edges { + if em := wave3StoreAsMap(e); em != nil { + if node := wave3StoreAsMap(em["node"]); node != nil { + out = append(out, node) + } + } + } + return out + } + if nodes := wave3StoreAsSlice(conn["nodes"]); len(nodes) > 0 { + for _, n := range nodes { + if nm := wave3StoreAsMap(n); nm != nil { + out = append(out, nm) + } + } + } + return out +} + +func wave3StoreFormatMoneyV2(m map[string]any) string { + if m == nil { + return "" + } + priceStr, okP := wave3StoreValidatePrice(m["amount"]) + if !okP { + return "" + } + cur := wave3StoreValidateCurrency(wave3StorePlain(m["currencyCode"], 10)) + if cur != "" { + return cur + " " + priceStr + } + return priceStr +} + +// ── #263: Shopify Hydrogen (__remixContext) HTML Extractor ────────────────────────────────────── + +func wave3StoreContainsShopifyHydrogenToken(s string) bool { + return strings.Contains(s, "gid://shopify/") || + strings.Contains(s, "checkout.hydrogen.shop") || + strings.Contains(s, "cdn.shopify.com") || + strings.Contains(s, "myshopify.com") || + strings.Contains(s, "shopify.com") +} + +func wave3StoreWalkHydrogenData(val any, shopInfo *map[string]any, products *[]map[string]any, collections *[]map[string]any, depth int) { + if depth > 6 || val == nil { + return + } + switch t := val.(type) { + case map[string]any: + if s := wave3StoreAsMap(t["shop"]); s != nil && wave3StorePlain(s["name"], 120) != "" && *shopInfo == nil { + *shopInfo = s + } + if p := wave3StoreAsMap(t["product"]); p != nil && wave3StorePlain(p["title"], 200) != "" { + *products = append(*products, p) + } + for _, arrKey := range []string{"products", "recommendedProducts", "featuredProducts", "items"} { + if conn := wave3StoreAsMap(t[arrKey]); conn != nil { + *products = append(*products, wave3StoreExtractGraphQLNodes(conn)...) + } else if arr := wave3StoreAsSlice(t[arrKey]); len(arr) > 0 { + for _, it := range arr { + if m := wave3StoreAsMap(it); m != nil && wave3StorePlain(m["title"], 200) != "" { + *products = append(*products, m) + } + } + } + } + for _, colKey := range []string{"collections", "featuredCollections"} { + if colConn := wave3StoreAsMap(t[colKey]); colConn != nil { + *collections = append(*collections, wave3StoreExtractGraphQLNodes(colConn)...) + } else if colArr := wave3StoreAsSlice(t[colKey]); len(colArr) > 0 { + for _, it := range colArr { + if m := wave3StoreAsMap(it); m != nil && wave3StorePlain(m["title"], 160) != "" { + *collections = append(*collections, m) + } + } + } + } + for k, v := range t { + if k == "shop" || k == "product" || k == "products" || k == "recommendedProducts" || k == "featuredProducts" || k == "items" || k == "collections" || k == "featuredCollections" { + continue + } + wave3StoreWalkHydrogenData(v, shopInfo, products, collections, depth+1) + } + case []any: + for i, it := range t { + if i >= 20 { + break + } + wave3StoreWalkHydrogenData(it, shopInfo, products, collections, depth+1) + } + } +} + +func wave3StoreExtractHydrogenHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + slice := truncateUTF8SafeFullDocGo(rawHTML, 256*1024) + if !strings.Contains(slice, "__remixContext") { + return nil + } + idx := strings.Index(slice, "__remixContext") + if idx < 0 { + return nil + } + tail := rawHTML[idx:] + if !wave3StoreContainsShopifyHydrogenToken(truncateUTF8SafeFullDocGo(tail, 1024*1024)) { + return nil + } + braceRel := strings.IndexByte(tail, '{') + if braceRel < 0 || braceRel > 48 { + return nil + } + rawJSON, _, ok := ExtractBalancedJSONAt(tail, braceRel, 1024*1024) + if !ok || rawJSON == "" || !wave3StoreContainsShopifyHydrogenToken(rawJSON) { + return nil + } + parsed, okP := decodeJSONWithNumbers([]byte(rawJSON)) + if !okP || parsed == nil { + return nil + } + root := wave3StoreAsMap(parsed) + state := wave3StoreAsMap(root["state"]) + loaderData := wave3StoreAsMap(state["loaderData"]) + if len(loaderData) == 0 { + return nil + } + if errs := wave3StoreAsMap(state["errors"]); len(errs) > 0 && len(loaderData) <= 1 { + // Remix error boundary without active route data + if _, hasRootOnly := loaderData["root"]; hasRootOnly && len(loaderData) == 1 { + return nil + } + } + + var shopInfo map[string]any + var products []map[string]any + var collections []map[string]any + wave3StoreWalkHydrogenData(loaderData, &shopInfo, &products, &collections, 0) + + doc := ParseHTMLDoc(rawHTML, 256*1024) + shopName := wave3StorePlain(shopInfo["name"], 160) + shopDesc := wave3StorePlain(shopInfo["description"], 400) + pageTitle := wave3StoreFirstNonEmpty( + wave3StorePlain(doc.Text("h1"), 220), + wave3StorePlain(doc.Text("title"), 220), + shopName, + ) + + if len(products) == 0 && len(collections) == 0 && shopName == "" { + return nil + } + + var md []string + var recs []map[string]any + var links []string + seenLinks := map[string]bool{} + + md = append(md, "# "+escapeDeclMarkdownBrackets(wave3StoreFirstNonEmpty(pageTitle, "Shopify Hydrogen Storefront"))) + var metaBullets []string + if shopName != "" { + metaBullets = append(metaBullets, "- **Store**: "+escapeDeclMarkdownBrackets(shopName)) + } + metaBullets = append(metaBullets, "- **Framework**: Shopify Hydrogen (Remix SSR)") + if prim := wave3StoreAsMap(shopInfo["primaryDomain"]); prim != nil { + if pu := wave3StoreResolveURL(wave3StorePlain(prim["url"], 300), baseURL); pu != "" { + metaBullets = append(metaBullets, "- **Domain**: "+pu) + wave3StoreAppendLink(&links, seenLinks, pu) + } + } + md = append(md, strings.Join(metaBullets, "\n")) + if shopDesc != "" { + md = append(md, shopDesc) + } + + seenProd := map[string]bool{} + var prodRows []string + for _, p := range products { + if len(recs) >= wave3StoreMaxRecords { + break + } + pt := wave3StorePlain(p["title"], 200) + if pt == "" { + continue + } + ph := wave3StorePlain(p["handle"], 140) + key := strings.ToLower(pt + "|" + ph) + if seenProd[key] { + continue + } + seenProd[key] = true + vendor := wave3StorePlain(p["vendor"], 120) + pr := wave3StoreAsMap(p["priceRange"]) + price := wave3StoreFormatMoneyV2(wave3StoreAsMap(pr["minVariantPrice"])) + if price == "" { + if sv := wave3StoreAsMap(p["selectedVariant"]); sv != nil { + price = wave3StoreFormatMoneyV2(wave3StoreAsMap(sv["price"])) + } + } + pURL := "" + if ph != "" { + pURL = wave3StoreResolveURL("/products/"+ph, baseURL) + wave3StoreAppendLink(&links, seenLinks, pURL) + } + titleCell := escapeDeclMarkdownBrackets(pt) + if pURL != "" { + titleCell = fmt.Sprintf("[%s](%s)", titleCell, pURL) + } + prodRows = append(prodRows, fmt.Sprintf("| %s | %s | %s |", + titleCell, escapeDeclMarkdownBrackets(wave3StoreFirstNonEmpty(vendor, "-")), wave3StoreFirstNonEmpty(price, "-"))) + rec := map[string]any{"type": "product", "title": pt} + if ph != "" { + rec["handle"] = ph + } + if vendor != "" { + rec["vendor"] = vendor + } + if price != "" { + rec["price"] = price + } + if pURL != "" { + rec["url"] = pURL + } + recs = append(recs, rec) + } + if len(prodRows) > 0 { + md = append(md, "## Products\n\n| Product | Vendor | Price |\n|---|---|---|\n"+strings.Join(prodRows, "\n")) + } + + var colLines []string + for i, c := range collections { + if i >= 15 { + break + } + ct := wave3StorePlain(c["title"], 160) + if ct == "" { + continue + } + ch := wave3StorePlain(c["handle"], 120) + cURL := "" + if ch != "" { + cURL = wave3StoreResolveURL("/collections/"+ch, baseURL) + wave3StoreAppendLink(&links, seenLinks, cURL) + } + if cURL != "" { + colLines = append(colLines, fmt.Sprintf("- [%s](%s)", escapeDeclMarkdownBrackets(ct), cURL)) + } else { + colLines = append(colLines, "- "+escapeDeclMarkdownBrackets(ct)) + } + if len(recs) < wave3StoreMaxRecords { + recs = append(recs, map[string]any{"type": "collection", "title": ct, "handle": ch}) + } + } + if len(colLines) > 0 { + md = append(md, "## Collections\n\n"+strings.Join(colLines, "\n")) + } + + if len(recs) == 0 && shopName != "" { + // Shop metadata present — ensure meaningful DOM content exists so empty shell is rejected + bodyText := wave3StoreCleanText(doc.Text("main")) + if bodyText == "" { + bodyText = wave3StoreCleanText(doc.Text("body")) + } + if len(bodyText) < 40 && shopDesc == "" { + return nil + } + recs = append(recs, map[string]any{"type": "shop", "name": shopName, "framework": "shopify-hydrogen"}) + } + + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: pageTitle, + Description: shopDesc, + Markdown: strings.Join(md, "\n\n"), + Links: links, + Records: recs, + } +} + +// ── #264: Recharge & Bold Subscriptions HTML Extractor ────────────────────────────────────────── + +func wave3StoreExtractRechargeBoldHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + // Cheap byte prefilter: must contain Recharge or Bold Subscriptions markers + hasRechargeMarker := strings.Contains(rawHTML, "rechargecdn.com") || + strings.Contains(rawHTML, "rechargepayments.com") || + strings.Contains(rawHTML, "rc-widget") || + strings.Contains(rawHTML, "rc-selling-plans") || + strings.Contains(rawHTML, "variant-purchase-selector") || + strings.Contains(rawHTML, "selling_plans_size") || + strings.Contains(rawHTML, "selling_plan_groups") + hasBoldMarker := strings.Contains(rawHTML, "boldapps.net") || + strings.Contains(rawHTML, "bold-subscriptions") || + strings.Contains(rawHTML, "bold_subscriptions") || + strings.Contains(rawHTML, "bold-ro__") || + strings.Contains(rawHTML, "bsub-widget") + if !hasRechargeMarker && !hasBoldMarker { + return nil + } + + // Non-preemption guard: verify genuine subscription / selling-plan data is present + // so normal Shopify PDPs without active subscriptions fall through cleanly to shopify_html. + hasSellingPlans := false + explicitZeroPlans := false + if idx := indexFoldASCIIExtract(rawHTML, "selling_plans_size"); idx >= 0 { + winEnd := idx + 64 + if winEnd > len(rawHTML) { + winEnd = len(rawHTML) + } + if m := wave3StoreRxSellingSize.FindStringSubmatch(rawHTML[idx:winEnd]); len(m) == 2 { + if n, err := strconv.Atoi(m[1]); err == nil { + if n > 0 { + hasSellingPlans = true + } else { + explicitZeroPlans = true + } + } + } + } + if !hasSellingPlans { + hasSellingPlans = indexFoldASCIIExtract(rawHTML, "selling_plan_groups") >= 0 || + indexFoldASCIIExtract(rawHTML, "rc-option--subsave") >= 0 || + indexFoldASCIIExtract(rawHTML, "bold-ro__recurring") >= 0 || + indexFoldASCIIExtract(rawHTML, "bsub-widget__plan") >= 0 + if !hasSellingPlans && !explicitZeroPlans { + probe := truncateUTF8SafeFullDocGo(rawHTML, 128*1024) + hasSellingPlans = indexFoldASCIIExtract(probe, `data-one-time-only="false"`) >= 0 || + indexFoldASCIIExtract(probe, `data-one-time-only='false'`) >= 0 || + indexFoldASCIIExtract(probe, "subscribe & save") >= 0 || + indexFoldASCIIExtract(probe, "subscribe & save") >= 0 || + indexFoldASCIIExtract(probe, "subscribe and save") >= 0 || + indexFoldASCIIExtract(probe, "delivery every") >= 0 + } + } + if !hasSellingPlans { + return nil + } + + doc := ParseHTMLDoc(rawHTML, 512*1024) + title := wave3StoreFirstNonEmpty( + wave3StorePlain(doc.Text("h1"), 220), + wave3StorePlain(doc.AttrOf(`meta[property="og:title"]`, "content"), 220), + wave3StorePlain(doc.Text("title"), 220), + ) + if title == "" { + return nil + } + + var provider []string + if hasRechargeMarker { + provider = append(provider, "Recharge") + } + if hasBoldMarker { + provider = append(provider, "Bold Subscriptions") + } + + // Extract Product context from JSON-LD + meta tags + DOM + brand := wave3StorePlain(doc.AttrOf(`meta[property="og:site_name"]`, "content"), 140) + price := "" + currency := wave3StoreValidateCurrency(doc.AttrOf(`meta[property="product:price:currency"]`, "content")) + if pMeta := doc.AttrOf(`meta[property="product:price:amount"]`, "content"); pMeta != "" { + if pv, okP := wave3StoreValidatePrice(pMeta); okP { + price = pv + } + } + sku := "" + desc := wave3StorePlain(doc.AttrOf(`meta[name="description"]`, "content"), 500) + availability := "" + + for _, m := range ExtractJSONLDObjects(rawHTML, 25) { + isProduct := false + if tp, okT := m["@type"].(string); okT && strings.EqualFold(tp, "Product") { + isProduct = true + } else if tps, okArr := m["@type"].([]any); okArr { + for _, t := range tps { + if ts, okS := t.(string); okS && strings.EqualFold(ts, "Product") { + isProduct = true + break + } + } + } + if !isProduct { + continue + } + if pt := wave3StorePlain(m["name"], 220); pt != "" { + title = pt + } + if b := wave3StoreAsMap(m["brand"]); b != nil { + brand = wave3StoreFirstNonEmpty(wave3StorePlain(b["name"], 140), brand) + } else if bs := wave3StorePlain(m["brand"], 140); bs != "" { + brand = bs + } + sku = wave3StoreFirstNonEmpty(wave3StorePlain(m["sku"], 80), sku) + desc = wave3StoreFirstNonEmpty(wave3StorePlain(m["description"], 1200), desc) + offers := wave3StoreAsMap(m["offers"]) + if offers == nil { + if arr := wave3StoreAsSlice(m["offers"]); len(arr) > 0 { + offers = wave3StoreAsMap(arr[0]) + } + } + if offers != nil { + if pv, okP := wave3StoreValidatePrice(offers["price"]); okP { + price = pv + } else if pv, okP := wave3StoreValidatePrice(offers["lowPrice"]); okP { + price = pv + } + if c := wave3StoreValidateCurrency(wave3StorePlain(offers["priceCurrency"], 10)); c != "" { + currency = c + } + if av := wave3StorePlain(offers["availability"], 80); av != "" { + availability = av + } + } + break + } + + // Extract selling_plan_groups JSON if embedded + type planItem struct { + Group string + Name string + Info string + } + var plans []planItem + seenPlan := map[string]bool{} + if idx := strings.Index(rawHTML, `"selling_plan_groups"`); idx >= 0 { + tail := rawHTML[idx+len(`"selling_plan_groups"`):] + if arrStart := strings.IndexByte(tail, '['); arrStart >= 0 && arrStart < 16 { + if rawArr, _, okArr := ExtractBalancedJSONAt(tail, arrStart, 128*1024); okArr { + if parsedArr, okJ := decodeJSONWithNumbers([]byte(rawArr)); okJ { + for _, g := range wave3StoreAsSlice(parsedArr) { + gm := wave3StoreAsMap(g) + if gm == nil { + continue + } + gName := wave3StorePlain(gm["name"], 120) + for _, sp := range wave3StoreAsSlice(gm["selling_plans"]) { + spm := wave3StoreAsMap(sp) + if spm == nil { + continue + } + spName := wave3StorePlain(spm["name"], 160) + spDesc := wave3StorePlain(spm["description"], 200) + if spName != "" && !seenPlan[spName] { + seenPlan[spName] = true + plans = append(plans, planItem{Group: gName, Name: spName, Info: spDesc}) + } + } + } + } + } + } + } + + // Also extract DOM subscription options (Recharge/Bold selectors) + for _, opt := range doc.Select(`variant-purchase-selector option, .rc-selling-plans option, .rc-option__label, .bold-ro__recurring-lbl, .bsub-widget__plan-header, [data-selling-plan-id]`, 25) { + txt := wave3StoreCleanText(opt.Text()) + if len(txt) < 3 || len(txt) > 160 || seenPlan[txt] { + continue + } + seenPlan[txt] = true + plans = append(plans, planItem{Group: "Subscription Option", Name: txt}) + } + + shopDomain := "" + if idx := indexFoldASCIIExtract(rawHTML, "rechargecdn.com"); idx >= 0 { + winEnd := idx + 256 + if winEnd > len(rawHTML) { + winEnd = len(rawHTML) + } + if sm := wave3StoreRxRechargeShop.FindStringSubmatch(rawHTML[idx:winEnd]); len(sm) == 2 { + shopDomain = sm[1] + } + } + + var md []string + md = append(md, "# "+escapeDeclMarkdownBrackets(title)) + var bullets []string + bullets = append(bullets, "- **Subscription Provider**: "+strings.Join(provider, ", ")) + if brand != "" { + bullets = append(bullets, "- **Brand**: "+escapeDeclMarkdownBrackets(brand)) + } + if price != "" { + priceOut := price + if currency != "" { + priceOut = currency + " " + price + } + bullets = append(bullets, "- **Price**: "+priceOut) + } + if sku != "" { + bullets = append(bullets, "- **SKU**: `"+sku+"`") + } + if availability != "" { + bullets = append(bullets, "- **Availability**: "+escapeDeclMarkdownBrackets(availability)) + } + if shopDomain != "" { + bullets = append(bullets, "- **Shop**: `"+shopDomain+"`") + } + if m := wave3StoreRxSellingSize.FindStringSubmatch(rawHTML); len(m) == 2 { + bullets = append(bullets, "- **Selling Plans Count**: "+m[1]) + } + md = append(md, strings.Join(bullets, "\n")) + + if desc != "" { + md = append(md, "## Product Details\n\n"+desc) + } + + var planRecs []map[string]any + if len(plans) > 0 { + var rows []string + for i, p := range plans { + if i >= 20 { + break + } + rows = append(rows, fmt.Sprintf("| %s | %s | %s |", + escapeDeclMarkdownBrackets(wave3StoreFirstNonEmpty(p.Group, "-")), + escapeDeclMarkdownBrackets(p.Name), + escapeDeclMarkdownBrackets(wave3StoreFirstNonEmpty(p.Info, "-")))) + planRecs = append(planRecs, map[string]any{ + "group": p.Group, + "name": p.Name, + "info": p.Info, + }) + } + md = append(md, "## Subscription Plans\n\n| Group | Plan | Details |\n|---|---|---|\n"+strings.Join(rows, "\n")) + } + + rec := map[string]any{ + "title": title, + "providers": provider, + } + if price != "" { + rec["price"] = price + } + if currency != "" { + rec["currency"] = currency + } + if len(planRecs) > 0 { + rec["selling_plans"] = planRecs + } + + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: wave3StorePlain(desc, 260), + Markdown: strings.Join(md, "\n\n"), + Records: []map[string]any{rec}, + } +} + +// ── #265: Shopify Filter Apps (Boost Commerce / Globo) JSON Formatter ─────────────────────────── + +func wave3StoreFormatFilterAppsJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + root := wave3StoreAsMap(parsed) + if root == nil || wave3StoreIsJSONError(root) { + return nil, false + } + // Boost Commerce 403 shape: {"message":"403 Forbidden: "} + if msg := strings.ToLower(wave3StorePlain(root["message"], 120)); strings.Contains(msg, "403") || strings.Contains(msg, "forbidden") || strings.Contains(msg, "unauthorized") { + return nil, false + } + + products := wave3StoreAsSlice(root["products"]) + if len(products) == 0 { + return nil, false + } + + totalCount := len(products) + for _, tk := range []string{"total_product", "total", "totalProducts"} { + if f, okF := jsonValueToFloat(root[tk]); okF && f >= float64(len(products)) { + totalCount = int(f) + break + } + } + + var rows []string + var recs []map[string]any + var links []string + seenLinks := map[string]bool{} + + for i, rawP := range products { + if i >= wave3StoreMaxRecords { + break + } + pm := wave3StoreAsMap(rawP) + if pm == nil { + continue + } + title := wave3StorePlain(pm["title"], 200) + if title == "" { + continue + } + handle := wave3StorePlain(pm["handle"], 140) + vendor := wave3StorePlain(pm["vendor"], 120) + ptype := wave3StorePlain(pm["product_type"], 100) + priceStr := "" + for _, pk := range []string{"price_min", "price", "price_max"} { + if pv, okP := wave3StoreValidatePrice(pm[pk]); okP { + priceStr = pv + break + } + } + availStr := "-" + if av, okA := pm["available"].(bool); okA { + if av { + availStr = "In Stock" + } else { + availStr = "Out of Stock" + } + } + pURL := wave3StoreResolveURL(wave3StorePlain(pm["url"], 500), origURL) + titleCell := escapeDeclMarkdownBrackets(title) + if pURL != "" { + titleCell = fmt.Sprintf("[%s](%s)", titleCell, pURL) + wave3StoreAppendLink(&links, seenLinks, pURL) + } + rows = append(rows, fmt.Sprintf("| %s | %s | %s | %s | %s |", + titleCell, + escapeDeclMarkdownBrackets(wave3StoreFirstNonEmpty(vendor, "-")), + escapeDeclMarkdownBrackets(wave3StoreFirstNonEmpty(ptype, "-")), + wave3StoreFirstNonEmpty(priceStr, "-"), + availStr)) + rec := map[string]any{ + "id": wave3StorePlain(pm["id"], 64), + "title": title, + "handle": handle, + } + if vendor != "" { + rec["vendor"] = vendor + } + if priceStr != "" { + rec["price"] = priceStr + } + if availStr != "-" { + rec["availability"] = availStr + } + if pURL != "" { + rec["url"] = pURL + } + recs = append(recs, rec) + } + if len(recs) == 0 { + return nil, false + } + + var md []string + md = append(md, fmt.Sprintf("# Shopify Filter Catalog (%d products)\n\n| Product | Vendor | Type | Price | Availability |\n|---|---|---|---|---|\n%s", + totalCount, strings.Join(rows, "\n"))) + + // Extract filter facets (Boost `filter.options` or Globo `filters`) + var facetLines []string + var optionsArr []any + if filt := wave3StoreAsMap(root["filter"]); filt != nil { + optionsArr = wave3StoreAsSlice(filt["options"]) + } + if len(optionsArr) == 0 { + optionsArr = wave3StoreAsSlice(root["filters"]) + } + for i, rawF := range optionsArr { + if i >= 12 { + break + } + fm := wave3StoreAsMap(rawF) + if fm == nil { + continue + } + label := wave3StoreFirstNonEmpty(wave3StorePlain(fm["label"], 80), wave3StorePlain(fm["title"], 80), wave3StorePlain(fm["filterOptionId"], 80)) + if label == "" { + continue + } + var vals []string + for j, rawV := range wave3StoreAsSlice(fm["values"]) { + if j >= 8 { + break + } + if vm := wave3StoreAsMap(rawV); vm != nil { + if vn := wave3StoreFirstNonEmpty(wave3StorePlain(vm["key"], 60), wave3StorePlain(vm["label"], 60)); vn != "" { + vals = append(vals, vn) + } + } + } + if len(vals) > 0 { + facetLines = append(facetLines, fmt.Sprintf("- **%s**: %s", escapeDeclMarkdownBrackets(label), escapeDeclMarkdownBrackets(strings.Join(vals, ", ")))) + } else { + facetLines = append(facetLines, "- **"+escapeDeclMarkdownBrackets(label)+"**") + } + } + if len(facetLines) > 0 { + md = append(md, "## Filter Facets\n\n"+strings.Join(facetLines, "\n")) + } + + return &DeclarativeFormattedDoc{ + Title: "Shopify Filter Catalog", + Markdown: strings.Join(md, "\n\n"), + Links: links, + Records: recs, + Total: wave3StoreIntPtr(totalCount), + Returned: wave3StoreIntPtr(len(recs)), + }, true +} + +// ── #266: Rebuy & Searchanise JSON Formatter ──────────────────────────────────────────────────── + +func wave3StoreFormatRebuySearchaniseJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + root := wave3StoreAsMap(parsed) + if root == nil || wave3StoreIsJSONError(root) { + return nil, false + } + if msg := strings.ToLower(wave3StorePlain(root["message"], 120)); strings.Contains(msg, "invalid") || strings.Contains(msg, "forbidden") || strings.Contains(msg, "unauthorized") { + return nil, false + } + + var items []any + sourceName := "Rebuy & Searchanise" + totalCount := 0 + if saItems := wave3StoreAsSlice(root["items"]); len(saItems) > 0 { + items = saItems + sourceName = "Searchanise Product Search" + if f, okF := jsonValueToFloat(root["totalItems"]); okF { + totalCount = int(f) + } + } else if rbData := wave3StoreAsSlice(root["data"]); len(rbData) > 0 { + items = rbData + sourceName = "Rebuy Product Recommendations" + } else if rbProds := wave3StoreAsSlice(root["products"]); len(rbProds) > 0 { + items = rbProds + sourceName = "Rebuy Product Recommendations" + } + if len(items) == 0 { + return nil, false + } + if totalCount < len(items) { + totalCount = len(items) + } + + var rows []string + var recs []map[string]any + var links []string + seenLinks := map[string]bool{} + + for i, rawItem := range items { + if i >= wave3StoreMaxRecords { + break + } + im := wave3StoreAsMap(rawItem) + if im == nil { + continue + } + title := wave3StorePlain(im["title"], 200) + if title == "" { + continue + } + pid := wave3StoreFirstNonEmpty(wave3StorePlain(im["product_id"], 64), wave3StorePlain(im["id"], 64)) + sku := wave3StoreFirstNonEmpty(wave3StorePlain(im["product_code"], 80), wave3StorePlain(im["sku"], 80)) + vendor := wave3StorePlain(im["vendor"], 100) + priceStr, _ := wave3StoreValidatePrice(im["price"]) + if priceStr == "" { + if vars := wave3StoreAsSlice(im["variants"]); len(vars) > 0 { + if vm := wave3StoreAsMap(vars[0]); vm != nil { + priceStr, _ = wave3StoreValidatePrice(vm["price"]) + if sku == "" { + sku = wave3StorePlain(vm["sku"], 80) + } + } + } + } + itemURL := wave3StoreResolveURL(wave3StoreFirstNonEmpty(wave3StorePlain(im["link"], 500), wave3StorePlain(im["url"], 500)), origURL) + titleCell := escapeDeclMarkdownBrackets(title) + if itemURL != "" { + titleCell = fmt.Sprintf("[%s](%s)", titleCell, itemURL) + wave3StoreAppendLink(&links, seenLinks, itemURL) + } + rows = append(rows, fmt.Sprintf("| %s | %s | %s | %s |", + titleCell, + escapeDeclMarkdownBrackets(wave3StoreFirstNonEmpty(sku, "-")), + wave3StoreFirstNonEmpty(priceStr, "-"), + escapeDeclMarkdownBrackets(wave3StoreFirstNonEmpty(vendor, "-")))) + rec := map[string]any{ + "id": pid, + "title": title, + } + if sku != "" { + rec["sku"] = sku + } + if priceStr != "" { + rec["price"] = priceStr + } + if vendor != "" { + rec["vendor"] = vendor + } + if itemURL != "" { + rec["url"] = itemURL + } + recs = append(recs, rec) + } + if len(recs) == 0 { + return nil, false + } + + md := fmt.Sprintf("# %s (%d items)\n\n| Product | SKU | Price | Vendor |\n|---|---|---|---|\n%s", + sourceName, totalCount, strings.Join(rows, "\n")) + return &DeclarativeFormattedDoc{ + Title: sourceName, + Markdown: md, + Links: links, + Records: recs, + Total: wave3StoreIntPtr(totalCount), + Returned: wave3StoreIntPtr(len(recs)), + }, true +} + +// ── #267: AfterShip Tracking Page HTML Extractor ──────────────────────────────────────────────── + +func wave3StoreExtractAfterShipHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + low := wave3StoreLowerProbe(rawHTML, 256*1024) + if !strings.Contains(low, "aftership") && + !(strings.Contains(rawHTML, "__NEXT_DATA__") && (strings.Contains(low, "tracking") || strings.Contains(low, "checkpoint"))) { + return nil + } + + doc := ParseHTMLDoc(rawHTML, 256*1024) + title := wave3StoreFirstNonEmpty( + wave3StorePlain(doc.Text("h1"), 220), + wave3StorePlain(doc.Text("title"), 220), + ) + + var md []string + var recs []map[string]any + var links []string + seenLinks := map[string]bool{} + + // 1. Parse __NEXT_DATA__ for tracking payload or portal brand config + trackingNum := "" + courier := "" + status := "" + estDelivery := "" + brandName := "" + + type checkpointRow struct { + Time string + Location string + Status string + Message string + } + var checkpoints []checkpointRow + + if nextObj, okNext := wave3StoreExtractScriptJSONByID(rawHTML, "__NEXT_DATA__"); okNext { + if nm := wave3StoreAsMap(nextObj); nm != nil { + if props := wave3StoreAsMap(nm["props"]); props != nil { + if pageProps := wave3StoreAsMap(props["pageProps"]); pageProps != nil { + if org := wave3StoreAsMap(pageProps["organization"]); org != nil { + brandName = wave3StorePlain(org["name"], 140) + } + if brandName == "" { + if portal := wave3StoreAsMap(pageProps["portal"]); portal != nil { + brandName = wave3StorePlain(portal["brandName"], 140) + } + } + tr := wave3StoreAsMap(pageProps["tracking"]) + if tr == nil { + tr = wave3StoreAsMap(pageProps["shipment"]) + } + if tr != nil { + trackingNum = wave3StoreFirstNonEmpty(wave3StorePlain(tr["tracking_number"], 80), wave3StorePlain(tr["trackingNumber"], 80)) + courier = wave3StoreFirstNonEmpty(wave3StorePlain(tr["courier_name"], 100), wave3StorePlain(tr["slug"], 80), wave3StorePlain(tr["courier"], 100)) + status = wave3StoreFirstNonEmpty(wave3StorePlain(tr["subtag_message"], 120), wave3StorePlain(tr["tag"], 80), wave3StorePlain(tr["status"], 80)) + estDelivery = wave3StoreFirstNonEmpty( + wave3StoreValidateISODate(wave3StorePlain(tr["expected_delivery"], 40)), + wave3StorePlain(tr["expected_delivery"], 60), + ) + for i, rawCP := range wave3StoreAsSlice(tr["checkpoints"]) { + if i >= 25 { + break + } + if cpm := wave3StoreAsMap(rawCP); cpm != nil { + checkpoints = append(checkpoints, checkpointRow{ + Time: wave3StoreFirstNonEmpty(wave3StorePlain(cpm["checkpoint_time"], 40), wave3StorePlain(cpm["time"], 40)), + Location: wave3StoreFirstNonEmpty(wave3StorePlain(cpm["location"], 100), wave3StorePlain(cpm["city"], 80)), + Status: wave3StoreFirstNonEmpty(wave3StorePlain(cpm["tag"], 60), wave3StorePlain(cpm["subtag_message"], 80)), + Message: wave3StorePlain(cpm["message"], 200), + }) + } + } + } + } + } + } + } + + // 2. Fallback to hydrated AfterShip DOM + if trackingNum == "" { + trackingNum = wave3StorePlain(doc.Text(".tracking-number, [data-testid='tracking-number']"), 80) + } + if status == "" { + status = wave3StorePlain(doc.Text(".tracking-status, [data-testid='tracking-status'], .tag-label"), 120) + } + if courier == "" { + courier = wave3StorePlain(doc.Text(".courier-name, [data-testid='courier-name']"), 100) + } + if len(checkpoints) == 0 { + for _, cp := range doc.Select(".checkpoint, .checkpoints-list li", 20) { + msg := wave3StoreCleanText(cp.Text()) + if len(msg) > 6 { + checkpoints = append(checkpoints, checkpointRow{Message: wave3StorePlain(msg, 200)}) + } + } + } + + bodyText := wave3StoreCleanText(doc.Text("main, .tracking-container, body")) + hasTrackingData := trackingNum != "" || status != "" || len(checkpoints) > 0 + hasHydratedPortal := brandName != "" && len(bodyText) >= 80 + if !hasTrackingData && !hasHydratedPortal { + return nil + } + + heading := wave3StoreFirstNonEmpty(title, brandName, "AfterShip Order Tracking") + md = append(md, "# "+escapeDeclMarkdownBrackets(heading)) + var bullets []string + if brandName != "" { + bullets = append(bullets, "- **Merchant**: "+escapeDeclMarkdownBrackets(brandName)) + } + if trackingNum != "" { + bullets = append(bullets, "- **Tracking Number**: `"+trackingNum+"`") + } + if courier != "" { + bullets = append(bullets, "- **Carrier**: "+escapeDeclMarkdownBrackets(courier)) + } + if status != "" { + bullets = append(bullets, "- **Status**: "+escapeDeclMarkdownBrackets(status)) + } + if estDelivery != "" { + bullets = append(bullets, "- **Estimated Delivery**: "+escapeDeclMarkdownBrackets(estDelivery)) + } + if len(bullets) > 0 { + md = append(md, strings.Join(bullets, "\n")) + } + + if len(checkpoints) > 0 { + var rows []string + for _, cp := range checkpoints { + rows = append(rows, fmt.Sprintf("| %s | %s | %s | %s |", + escapeDeclMarkdownBrackets(wave3StoreFirstNonEmpty(cp.Time, "-")), + escapeDeclMarkdownBrackets(wave3StoreFirstNonEmpty(cp.Location, "-")), + escapeDeclMarkdownBrackets(wave3StoreFirstNonEmpty(cp.Status, "-")), + escapeDeclMarkdownBrackets(wave3StoreFirstNonEmpty(cp.Message, "-")))) + recs = append(recs, map[string]any{ + "type": "checkpoint", + "time": cp.Time, + "location": cp.Location, + "status": cp.Status, + "message": cp.Message, + }) + } + md = append(md, "## Tracking Checkpoints\n\n| Time | Location | Status | Event |\n|---|---|---|---|\n"+strings.Join(rows, "\n")) + } else if bodyText != "" { + md = append(md, "## Tracking Portal\n\n"+wave3StorePlain(bodyText, 1200)) + recs = append(recs, map[string]any{"type": "portal", "brand": brandName, "tracking_number": trackingNum}) + } + + for _, a := range doc.Select("a[href]", 20) { + if href, ok := a.Attr("href"); ok { + wave3StoreAppendLink(&links, seenLinks, wave3StoreResolveURL(href, baseURL)) + } + } + + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: heading, + Markdown: strings.Join(md, "\n\n"), + Links: links, + Records: recs, + } +} + +// ── #268: Branded Tracking Pack (Narvar / Route / ParcelPanel / Malomo / Wonderment) ──────────── + +func wave3StoreExtractBrandedTrackingHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + probe := truncateUTF8SafeFullDocGo(rawHTML, 256*1024) + low := strings.ToLower(probe) + if !strings.Contains(low, "narvar") && + !strings.Contains(low, "parcelpanel") && + !strings.Contains(low, "routeapp.io") && + !strings.Contains(low, "tracking.route.com") && + !strings.Contains(low, "route tracking") && + !strings.Contains(low, "malomo") && + !strings.Contains(low, "wonderment") { + return nil + } + + doc := ParseHTMLDoc(rawHTML, 256*1024) + bodyText := wave3StoreCleanText(doc.Text("body")) + + // Strictly reject empty 1 KB CSR shells like tracking.route.com/ lacking hydrated tracking/order/checkpoint payload + hasHydratedTrack := wave3StoreRxHydratedTrack.MatchString(probe) + if !hasHydratedTrack && len(bodyText) < 200 { + return nil + } + if strings.Contains(low, "route tracking") && !hasHydratedTrack { + return nil + } + + platform := "Branded Tracking" + switch { + case strings.Contains(low, "narvar"): + platform = "Narvar" + case strings.Contains(low, "parcelpanel"): + platform = "ParcelPanel" + case strings.Contains(low, "route"): + platform = "Route" + case strings.Contains(low, "malomo"): + platform = "Malomo" + case strings.Contains(low, "wonderment"): + platform = "Wonderment" + } + + trackingNum := "" + orderNum := "" + carrier := "" + status := "" + retailer := "" + var checkpointLines []string + var recs []map[string]any + + if nextObj, okNext := wave3StoreExtractScriptJSONByID(rawHTML, "__NEXT_DATA__"); okNext { + if nm := wave3StoreAsMap(nextObj); nm != nil { + if props := wave3StoreAsMap(nm["props"]); props != nil { + if pp := wave3StoreAsMap(props["pageProps"]); pp != nil { + retailer = wave3StoreFirstNonEmpty(wave3StorePlain(pp["retailer"], 100), wave3StorePlain(pp["retailerName"], 100), wave3StorePlain(pp["brand"], 100)) + trackingNum = wave3StoreFirstNonEmpty(wave3StorePlain(pp["trackingNumber"], 80), wave3StorePlain(pp["tracking_number"], 80)) + orderNum = wave3StoreFirstNonEmpty(wave3StorePlain(pp["orderNumber"], 80), wave3StorePlain(pp["order_number"], 80)) + carrier = wave3StoreFirstNonEmpty(wave3StorePlain(pp["carrier"], 80), wave3StorePlain(pp["carrierName"], 80)) + status = wave3StoreFirstNonEmpty(wave3StorePlain(pp["status"], 100), wave3StorePlain(pp["deliveryStatus"], 100)) + if tr := wave3StoreAsMap(pp["tracking"]); tr != nil { + trackingNum = wave3StoreFirstNonEmpty(trackingNum, wave3StorePlain(tr["trackingNumber"], 80), wave3StorePlain(tr["tracking_number"], 80)) + carrier = wave3StoreFirstNonEmpty(carrier, wave3StorePlain(tr["carrier"], 80)) + status = wave3StoreFirstNonEmpty(status, wave3StorePlain(tr["status"], 100)) + for i, rawCP := range wave3StoreAsSlice(tr["checkpoints"]) { + if i >= 20 { + break + } + if cpm := wave3StoreAsMap(rawCP); cpm != nil { + msg := wave3StoreFirstNonEmpty(wave3StorePlain(cpm["message"], 200), wave3StorePlain(cpm["description"], 200), wave3StorePlain(cpm["status"], 120)) + dt := wave3StoreFirstNonEmpty(wave3StorePlain(cpm["time"], 40), wave3StorePlain(cpm["date"], 40)) + loc := wave3StorePlain(cpm["location"], 100) + if msg != "" { + checkpointLines = append(checkpointLines, fmt.Sprintf("- %s %s %s", dt, loc, msg)) + recs = append(recs, map[string]any{"type": "checkpoint", "time": dt, "location": loc, "message": msg}) + } + } + } + } + } + } + } + } + + if trackingNum == "" { + trackingNum = wave3StorePlain(doc.Text(".tracking-number, .pp_tracking_number, [data-testid='tracking-number']"), 80) + } + if status == "" { + status = wave3StorePlain(doc.Text(".tracking-status, .pp_tracking_status, .shipment-status"), 120) + } + if carrier == "" { + carrier = wave3StorePlain(doc.Text(".carrier-name, .pp_carrier_name"), 100) + } + if len(checkpointLines) == 0 { + for _, el := range doc.Select(".pp_checkpoint, .tracking-event, .checkpoint-item", 20) { + txt := wave3StoreCleanText(el.Text()) + if len(txt) > 6 { + checkpointLines = append(checkpointLines, "- "+wave3StorePlain(txt, 220)) + recs = append(recs, map[string]any{"type": "checkpoint", "message": wave3StorePlain(txt, 220)}) + } + } + } + + title := wave3StoreFirstNonEmpty( + wave3StorePlain(doc.Text("h1"), 200), + wave3StorePlain(doc.Text("title"), 200), + platform+" Tracking", + ) + hasHydratedPayload := trackingNum != "" || orderNum != "" || status != "" || len(checkpointLines) > 0 || (retailer != "" && len(bodyText) >= 120) + if !hasHydratedPayload { + return nil + } + + var md []string + md = append(md, "# "+escapeDeclMarkdownBrackets(title)) + var bullets []string + bullets = append(bullets, "- **Tracking Platform**: "+platform) + if retailer != "" { + bullets = append(bullets, "- **Retailer**: "+escapeDeclMarkdownBrackets(retailer)) + } + if orderNum != "" { + bullets = append(bullets, "- **Order**: `"+orderNum+"`") + } + if trackingNum != "" { + bullets = append(bullets, "- **Tracking Number**: `"+trackingNum+"`") + } + if carrier != "" { + bullets = append(bullets, "- **Carrier**: "+escapeDeclMarkdownBrackets(carrier)) + } + if status != "" { + bullets = append(bullets, "- **Status**: "+escapeDeclMarkdownBrackets(status)) + } + md = append(md, strings.Join(bullets, "\n")) + if len(checkpointLines) > 0 { + md = append(md, "## Checkpoints\n\n"+strings.Join(checkpointLines, "\n")) + } else if bodyText != "" { + md = append(md, "## Tracking Details\n\n"+wave3StorePlain(bodyText, 1200)) + recs = append(recs, map[string]any{"type": "tracking", "platform": platform, "retailer": retailer, "status": status}) + } + + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Markdown: strings.Join(md, "\n\n"), + Records: recs, + } +} + +// ── #269: Gorgias & Re:amaze Help Center HTML Extractor ───────────────────────────────────────── + +func wave3StoreExtractGorgiasReamazeHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + low := wave3StoreLowerProbe(rawHTML, 256*1024) + isGorgias := strings.Contains(low, "assets.gorgias.help") || strings.Contains(low, "gorgias.help") || strings.Contains(low, "gorgias-help") + if !isGorgias && len(rawHTML) > 256*1024 { + isGorgias = indexFoldASCIIExtract(rawHTML, "gorgias.help") >= 0 || indexFoldASCIIExtract(rawHTML, "gorgias-help") >= 0 + } + isReamaze := strings.Contains(low, "cdn.reamaze.com") || strings.Contains(low, "reamaze.com") || (strings.Contains(low, "topic-index") && strings.Contains(low, "reamaze")) + if !isGorgias && !isReamaze { + return nil + } + + var doc *HTMLDoc + ensureDoc := func() *HTMLDoc { + if doc == nil { + slim := stripScriptsAndStylesDeclHTML(rawHTML) + if len(slim) > 512*1024 { + slim = truncateUTF8SafeFullDocGo(slim, 512*1024) + } + doc = ParseHTMLDoc(slim, 512*1024) + } + return doc + } + var md []string + var recs []map[string]any + var links []string + seenLinks := map[string]bool{} + title := "" + desc := "" + + resolveGorgiasSlugURL := func(m map[string]any) string { + if m == nil { + return "" + } + if direct := wave3StoreFirstNonEmpty(wave3StorePlain(m["url"], 400), wave3StorePlain(m["path"], 400)); direct != "" { + return wave3StoreResolveURL(direct, baseURL) + } + slug := strings.Trim(wave3StorePlain(m["slug"], 200), "/") + if slug == "" { + return "" + } + if u, err := url.Parse(baseURL); err == nil && u.Scheme != "" && u.Host != "" { + if idxArt := strings.Index(u.Path, "/articles/"); idxArt >= 0 { + return wave3StoreResolveURL(u.Path[:idxArt+len("/articles/")]+slug, baseURL) + } + return wave3StoreResolveURL("/articles/"+slug, baseURL) + } + return "" + } + + if isGorgias { + // Parse Gorgias __NEXT_DATA__ + if nextObj, okNext := wave3StoreExtractScriptJSONByID(rawHTML, "__NEXT_DATA__"); okNext { + if nm := wave3StoreAsMap(nextObj); nm != nil { + if props := wave3StoreAsMap(nm["props"]); props != nil { + if pp := wave3StoreAsMap(props["pageProps"]); pp != nil { + if art := wave3StoreAsMap(pp["article"]); art != nil { + title = wave3StorePlain(art["title"], 250) + desc = wave3StorePlain(art["excerpt"], 300) + bodyHTML := wave3StoreFirstNonEmpty(wave3StorePlain(art["body"], 64*1024), wave3StorePlain(art["bodyHtml"], 64*1024)) + if bodyHTML != "" { + bodyMD, bodyLinks := wave3StoreHTMLToMD(bodyHTML, baseURL) + if title != "" { + md = append(md, "# "+escapeDeclMarkdownBrackets(title)) + } + md = append(md, "- **Help Center**: Gorgias") + if upd := wave3StoreValidateISODate(wave3StorePlain(art["updatedAt"], 40)); upd != "" { + md[len(md)-1] += "\n- **Updated**: " + upd + } + if bodyMD != "" { + md = append(md, bodyMD) + } + for _, l := range bodyLinks { + wave3StoreAppendLink(&links, seenLinks, l) + } + recs = append(recs, map[string]any{"type": "article", "platform": "gorgias", "title": title}) + } + } + if len(recs) == 0 { + var articleItems []string + var navItems []string + seenCats := map[string]bool{} + + if selCat := wave3StoreAsMap(pp["selectedCategory"]); selCat != nil { + if ct := wave3StoreFirstNonEmpty(wave3StorePlain(selCat["name"], 220), wave3StorePlain(selCat["title"], 220)); ct != "" { + title = ct + } + if cd := wave3StoreFirstNonEmpty(wave3StorePlain(selCat["description"], 300), wave3StorePlain(selCat["subtitle"], 300)); cd != "" { + desc = cd + } + } + + childArticles := wave3StoreAsSlice(pp["childrenArticles"]) + if len(childArticles) == 0 { + if selCat := wave3StoreAsMap(pp["selectedCategory"]); selCat != nil { + childArticles = wave3StoreAsSlice(selCat["childrenArticles"]) + if len(childArticles) == 0 { + childArticles = wave3StoreAsSlice(selCat["articles"]) + } + } + } + for _, rawArt := range childArticles { + if len(recs) >= wave3StoreMaxRecords { + break + } + am := wave3StoreAsMap(rawArt) + if am == nil { + continue + } + at := wave3StoreFirstNonEmpty(wave3StorePlain(am["title"], 200), wave3StorePlain(am["name"], 200)) + if at == "" { + continue + } + au := resolveGorgiasSlugURL(am) + ax := wave3StoreFirstNonEmpty(wave3StorePlain(am["excerpt"], 240), wave3StorePlain(am["description"], 240), wave3StorePlain(am["summary"], 240)) + line := "- " + escapeDeclMarkdownBrackets(at) + if au != "" { + line = fmt.Sprintf("- [%s](%s)", escapeDeclMarkdownBrackets(at), au) + wave3StoreAppendLink(&links, seenLinks, au) + } + if ax != "" { + line += " — " + escapeDeclMarkdownBrackets(ax) + } + articleItems = append(articleItems, line) + rec := map[string]any{"type": "article", "platform": "gorgias", "title": at} + if title != "" { + rec["category"] = title + } + if au != "" { + rec["url"] = au + } + if ax != "" { + rec["excerpt"] = ax + } + recs = append(recs, rec) + } + + appendCategories := func(rawCats []any) { + for _, rawCat := range rawCats { + cm := wave3StoreAsMap(rawCat) + if cm == nil { + continue + } + cn := wave3StoreFirstNonEmpty(wave3StorePlain(cm["name"], 140), wave3StorePlain(cm["title"], 140)) + if cn == "" { + continue + } + ck := strings.ToLower(cn) + if seenCats[ck] { + continue + } + seenCats[ck] = true + cu := resolveGorgiasSlugURL(cm) + if cu != "" { + navItems = append(navItems, fmt.Sprintf("- [%s](%s)", escapeDeclMarkdownBrackets(cn), cu)) + wave3StoreAppendLink(&links, seenLinks, cu) + } else { + navItems = append(navItems, "- "+escapeDeclMarkdownBrackets(cn)) + } + if len(recs) < wave3StoreMaxRecords { + catRec := map[string]any{"type": "category", "platform": "gorgias", "name": cn} + if cu != "" { + catRec["url"] = cu + } + recs = append(recs, catRec) + } + } + } + appendCategories(wave3StoreAsSlice(pp["categories"])) + appendCategories(wave3StoreAsSlice(pp["sidebarCategories"])) + + for _, rawNav := range wave3StoreAsSlice(pp["headerNavigationItems"]) { + if nm2 := wave3StoreAsMap(rawNav); nm2 != nil { + nt := wave3StorePlain(nm2["label"], 120) + nu := wave3StoreResolveURL(wave3StorePlain(nm2["url"], 400), baseURL) + if nt != "" { + if nu != "" { + navItems = append(navItems, fmt.Sprintf("- [%s](%s)", escapeDeclMarkdownBrackets(nt), nu)) + wave3StoreAppendLink(&links, seenLinks, nu) + } else { + navItems = append(navItems, "- "+escapeDeclMarkdownBrackets(nt)) + } + } + } + } + if len(articleItems) > 0 || len(navItems) > 0 { + if title == "" { + d := ensureDoc() + title = wave3StoreFirstNonEmpty(wave3StorePlain(d.Text("h1"), 220), wave3StorePlain(d.Text("title"), 220), "Gorgias Help Center") + } + md = append(md, "# "+escapeDeclMarkdownBrackets(title)) + md = append(md, "- **Help Center**: Gorgias") + if desc != "" { + md = append(md, escapeDeclMarkdownBrackets(desc)) + } + if len(articleItems) > 0 { + md = append(md, "## Articles\n\n"+strings.Join(articleItems, "\n")) + } + if len(navItems) > 0 { + md = append(md, "## Topics\n\n"+strings.Join(navItems, "\n")) + } + } + } + } + } + } + } + } + + // Re:amaze branch (or Gorgias DOM fallback) + if len(md) == 0 { + d := ensureDoc() + platform := "Re:amaze" + if isGorgias { + platform = "Gorgias" + } + title = wave3StoreFirstNonEmpty( + wave3StorePlain(d.Text(`h1[itemprop="name"]`), 250), + wave3StorePlain(d.Text("h1"), 250), + wave3StorePlain(d.Text("title"), 250), + ) + if title == "" { + return nil + } + bodyHTML := wave3StoreFirstNonEmpty( + d.HTML(`[itemprop="text"]`), + d.HTML(".kb-article-body"), + d.HTML(".article-content"), + d.HTML("article"), + ) + bodyMD, bodyLinks := wave3StoreHTMLToMD(bodyHTML, baseURL) + for _, l := range bodyLinks { + wave3StoreAppendLink(&links, seenLinks, l) + } + + var topicLines []string + for _, a := range d.Select(".topic-index a, .content-list a, .kb-topic-list a", 30) { + txt := wave3StoreCleanText(a.Text()) + href, _ := a.Attr("href") + resolved := wave3StoreResolveURL(href, baseURL) + if txt != "" && resolved != "" { + topicLines = append(topicLines, fmt.Sprintf("- [%s](%s)", escapeDeclMarkdownBrackets(txt), resolved)) + wave3StoreAppendLink(&links, seenLinks, resolved) + if len(recs) < wave3StoreMaxRecords { + recs = append(recs, map[string]any{"type": "article_link", "platform": strings.ToLower(platform), "title": txt, "url": resolved}) + } + } + } + + if bodyMD == "" && len(topicLines) == 0 { + return nil + } + md = append(md, "# "+escapeDeclMarkdownBrackets(title)) + md = append(md, "- **Help Center**: "+platform) + if bodyMD != "" { + md = append(md, bodyMD) + if len(recs) == 0 { + recs = append(recs, map[string]any{"type": "article", "platform": strings.ToLower(platform), "title": title}) + } + } + if len(topicLines) > 0 { + md = append(md, "## Articles & Topics\n\n"+strings.Join(topicLines, "\n")) + } + } + + if len(md) == 0 { + return nil + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: strings.Join(md, "\n\n"), + Links: links, + Records: recs, + } +} + +// ── #270: Klaviyo & Attentive Read-Only Onsite Form / Tag Metadata Extractor ──────────────────── + +func wave3StoreExtractKlaviyoAttentiveHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + // Cheap byte prefilter + hasKlaviyo := strings.Contains(rawHTML, "static.klaviyo.com") || + strings.Contains(rawHTML, "klaviyo.js") || + strings.Contains(rawHTML, "klaviyo-form") || + strings.Contains(rawHTML, "_learnq") + hasAttentive := strings.Contains(rawHTML, "cdn.attn.tv") || + strings.Contains(rawHTML, "attn.tv") + if !hasKlaviyo && !hasAttentive { + return nil + } + + // CRITICAL Alphabetical Preemption Yield: + // "klaviyo-attentive-forms" precedes "shopify" ("s") and "woocommerce" ("w") in reg.universal! + // MUST yield (return nil) on product/collection PDPs, commerce platforms, and Product/Article/Recipe/Event/Course/JobPosting JSON-LD pages. + if u, err := url.Parse(strings.TrimSpace(baseURL)); err == nil { + lowPath := strings.ToLower(u.Path) + if strings.Contains(lowPath, "/products/") || strings.Contains(lowPath, "/product/") || strings.Contains(lowPath, "/collections/") { + return nil + } + } + probe := truncateUTF8SafeFullDocGo(rawHTML, 256*1024) + if indexFoldASCIIExtract(rawHTML, "shopify.shop") >= 0 || + indexFoldASCIIExtract(rawHTML, "cdn.shopify.com") >= 0 || + indexFoldASCIIExtract(rawHTML, "woocommerce-") >= 0 || + indexFoldASCIIExtract(probe, `og:type="product"`) >= 0 || + indexFoldASCIIExtract(probe, `og:type='product'`) >= 0 || + (indexFoldASCIIExtract(probe, "og:type") >= 0 && wave3StoreRxOGTypeProduct.MatchString(probe)) { + return nil + } + if hasJSONLDScriptToken(rawHTML) { + for _, obj := range ExtractJSONLDObjects(rawHTML, 40) { + for _, t := range normalizeSchemaTypesSchemaGo(obj["@type"]) { + switch strings.ToLower(t) { + case "product", "productgroup", "article", "newsarticle", "blogposting", "recipe", "event", "course", "jobposting": + return nil + } + } + } + } + if typeProbe := wave3StoreCollectWindows(rawHTML, []string{`"@type"`}, 16, 256, 20); typeProbe != "" && wave3StoreRxProductJSONLD.MatchString(typeProbe) { + return nil + } + + // Extract read-only Klaviyo & Attentive metadata (NEVER submit forms) using bounded anchor windows + var companyIDs []string + seenCID := map[string]bool{} + if cidProbe := wave3StoreCollectWindows(rawHTML, []string{"klaviyo.js", "company_id=", "_learnq"}, 96, 160, 12); cidProbe != "" { + for _, m := range wave3StoreRxKlaviyoCID.FindAllStringSubmatch(cidProbe, 10) { + cid := wave3StoreFirstNonEmpty(m[1], m[2], m[3], m[4]) + if cid != "" && !seenCID[cid] { + seenCID[cid] = true + companyIDs = append(companyIDs, cid) + } + } + } + + var formIDs []string + seenFID := map[string]bool{} + if fidProbe := wave3StoreCollectWindows(rawHTML, []string{"klaviyo-form"}, 32, 96, 15); fidProbe != "" { + for _, m := range wave3StoreRxKlaviyoFormID.FindAllStringSubmatch(fidProbe, 15) { + fid := wave3StoreFirstNonEmpty(m[1], m[2]) + if fid != "" && !seenFID[fid] { + seenFID[fid] = true + formIDs = append(formIDs, fid) + } + } + } + + var attentiveSlugs []string + seenAtt := map[string]bool{} + if attProbe := wave3StoreCollectWindows(rawHTML, []string{"cdn.attn.tv"}, 16, 120, 10); attProbe != "" { + for _, m := range wave3StoreRxAttentiveTag.FindAllStringSubmatch(attProbe, 10) { + slug := strings.TrimSpace(m[1]) + if slug != "" && !seenAtt[slug] { + seenAtt[slug] = true + attentiveSlugs = append(attentiveSlugs, slug) + } + } + } + + if len(companyIDs) == 0 && len(formIDs) == 0 && len(attentiveSlugs) == 0 { + return nil + } + + doc := ParseHTMLDoc(rawHTML, 256*1024) + siteTitle := wave3StoreFirstNonEmpty( + wave3StorePlain(doc.AttrOf(`meta[property="og:site_name"]`, "content"), 180), + wave3StorePlain(doc.Text("h1"), 180), + wave3StorePlain(doc.Text("title"), 180), + ExtractSlugTitleFromURL(baseURL), + ) + desc := wave3StorePlain(doc.AttrOf(`meta[name="description"]`, "content"), 400) + + // Collect read-only offer / signup prompt snippets if embedded in Klaviyo/Attentive form containers + var offerSnippets []string + seenOffer := map[string]bool{} + for _, sel := range []string{`[class*="klaviyo-form"]`, `[data-testid*="klaviyo"]`, `[id*="attentive"]`} { + for _, el := range doc.Select(sel, 8) { + txt := wave3StoreCleanText(el.Text()) + if len(txt) >= 6 && len(txt) <= 240 && !seenOffer[txt] { + seenOffer[txt] = true + offerSnippets = append(offerSnippets, txt) + } + } + } + + var md []string + md = append(md, "# "+escapeDeclMarkdownBrackets(wave3StoreFirstNonEmpty(siteTitle, "Klaviyo & Attentive Onsite Metadata"))) + var bullets []string + bullets = append(bullets, "- **Extraction Mode**: Read-only onsite marketing & signup metadata (no form submission)") + if len(companyIDs) > 0 { + bullets = append(bullets, "- **Klaviyo Company IDs**: `"+strings.Join(companyIDs, "`, `")+"`") + } + if len(formIDs) > 0 { + bullets = append(bullets, "- **Klaviyo Form IDs**: `"+strings.Join(formIDs, "`, `")+"`") + } + if len(attentiveSlugs) > 0 { + bullets = append(bullets, "- **Attentive Tag Slugs**: `"+strings.Join(attentiveSlugs, "`, `")+"`") + } + md = append(md, strings.Join(bullets, "\n")) + if desc != "" { + md = append(md, desc) + } + if len(offerSnippets) > 0 { + var lines []string + for _, o := range offerSnippets { + lines = append(lines, "- "+escapeDeclMarkdownBrackets(o)) + } + md = append(md, "## Onsite Signup Offers (Read-Only)\n\n"+strings.Join(lines, "\n")) + } + + var recs []map[string]any + if len(companyIDs) > 0 || len(formIDs) > 0 { + recs = append(recs, map[string]any{ + "platform": "klaviyo", + "company_ids": companyIDs, + "form_ids": formIDs, + "read_only": true, + }) + } + if len(attentiveSlugs) > 0 { + recs = append(recs, map[string]any{ + "platform": "attentive", + "brand_slug": attentiveSlugs[0], + "slugs": attentiveSlugs, + "read_only": true, + }) + } + + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: siteTitle, + Description: desc, + Markdown: strings.Join(md, "\n\n"), + Records: recs, + } +} diff --git a/internal/extract/wave3_store_addons_test.go b/internal/extract/wave3_store_addons_test.go new file mode 100644 index 0000000..a4f2517 --- /dev/null +++ b/internal/extract/wave3_store_addons_test.go @@ -0,0 +1,291 @@ +package extract + +import ( + "strings" + "testing" + "time" +) + +func TestWave3StoreAddonsRegistryAndCompanionNoOp(t *testing.T) { + htmlModes := []string{ + "shopify_hydrogen_html", + "recharge_bold_subscriptions_html", + "shopify_filter_apps_html", + "rebuy_searchanise_html", + "aftership_tracking_html", + "branded_tracking_pack_html", + "gorgias_reamaze_html", + "klaviyo_attentive_forms_html", + } + for _, m := range htmlModes { + if !IsWave3StoreAddonsHTMLMode(m) { + t.Fatalf("IsWave3StoreAddonsHTMLMode(%q) = false", m) + } + if getExternalHTMLModeLazy(m) == nil { + t.Fatalf("RegisterExternalHTMLModeLazy missing %q", m) + } + } + for _, jm := range []string{"shopify_filter_apps_json", "rebuy_searchanise_json"} { + if !IsWave3StoreAddonsJSONMode(jm) { + t.Fatalf("IsWave3StoreAddonsJSONMode(%q) = false", jm) + } + } + + // Companion-only page-key HTML modes MUST return nil so they never preempt shopify_html + shopifyPDP := `Layering Collection | Henry Rose

The Layering Collection

` + for _, noopMode := range []string{"shopify_filter_apps_html", "rebuy_searchanise_html"} { + if res := Wave3StoreAddonsRunHTML(noopMode, shopifyPDP, "https://www.henryrose.com/products/the-layering-collection", ""); res != nil { + t.Fatalf("companion-only mode %q must return nil, got %+v", noopMode, res) + } + } +} + +func TestWave3StoreAddonsPlatformTwinStorefrontGraphQL(t *testing.T) { + html := `The Layering Collection

The Layering Collection

` + + // Opt-out via AllowPageKeyTwins = false + off := DiscoverPlatformCompanionTwin(html, PlatformTwinDiscoveryInput{ + PageURL: "https://www.henryrose.com/products/the-layering-collection", + AllowPageKeyTwins: BoolPtr(false), + }) + if off.Matched { + t.Fatalf("expected Matched=false when AllowPageKeyTwins=false, got %+v", off) + } + + // Default ON (nil) and explicit true + for _, ptr := range []*bool{nil, BoolPtr(true)} { + cand := DiscoverPlatformCompanionTwin(html, PlatformTwinDiscoveryInput{ + PageURL: "https://www.henryrose.com/products/the-layering-collection", + AllowPageKeyTwins: ptr, + }) + if !cand.Matched || cand.AdapterID != "shopify-storefront-graphql" { + t.Fatalf("expected shopify-storefront-graphql twin, got %+v", cand) + } + if cand.FetchURL != "https://www.henryrose.com/api/2024-10/graphql.json" { + t.Fatalf("unexpected same-origin FetchURL: %q", cand.FetchURL) + } + if cand.Method != "POST" || !cand.RequiresPageKeyOptIn || cand.FormatMode != "json:shopify_storefront_graphql_json" { + t.Fatalf("unexpected candidate metadata: %+v", cand) + } + if cand.Headers["X-Shopify-Storefront-Access-Token"] != "c6f547549c3f539b991db94e4c0fb111" { + t.Fatalf("missing storefront access token header: %+v", cand.Headers) + } + if !strings.Contains(cand.RequestBody, "the-layering-collection") { + t.Fatalf("expected product handle in GraphQL body: %s", cand.RequestBody) + } + } + + // Rule 7: Cross-origin page-key-config MUST be rejected + evilHTML := `` + if evil := DiscoverPlatformCompanionTwin(evilHTML, PlatformTwinDiscoveryInput{ + PageURL: "https://www.henryrose.com/", + AllowPageKeyTwins: BoolPtr(true), + }); evil.Matched { + t.Fatalf("Rule 7 violation: cross-origin storefront GraphQL endpoint must be rejected, got %+v", evil) + } +} + +func TestWave3StoreAddonsJSONModesPositiveAndNegative(t *testing.T) { + // 1. #262 shopify_storefront_graphql_json (single product via FormatRound2JSONDoc + catalog + error rejection) + gqlProduct := `{"data":{"product":{"id":"gid://shopify/Product/15400794882138","handle":"the-layering-collection","title":"The Layering Collection","vendor":"Henry Rose","productType":"Fragrance Set","onlineStoreUrl":"https://www.henryrose.com/products/the-layering-collection","description":"Explore clean fine fragrances.","priceRange":{"minVariantPrice":{"amount":"45.0","currencyCode":"USD"},"maxVariantPrice":{"amount":"45.0","currencyCode":"USD"}},"variants":{"edges":[{"node":{"id":"gid://shopify/ProductVariant/1","title":"Discovery Set","sku":"HR-LAY-01","availableForSale":true,"price":{"amount":"45.0","currencyCode":"USD"}}}]}}}}` + doc, ok := FormatRound2JSONDoc("shopify_storefront_graphql_json", []byte(gqlProduct), nil, "https://www.henryrose.com/api/2024-10/graphql.json") + if !ok || doc == nil || !strings.Contains(doc.Markdown, "The Layering Collection") || !strings.Contains(doc.Markdown, "45.00 USD") || !strings.Contains(doc.Markdown, "HR-LAY-01") { + t.Fatalf("shopify_storefront_graphql_json single product failed: ok=%v doc=%+v", ok, doc) + } + if _, errOK := FormatRound2JSONDoc("shopify_storefront_graphql_json", []byte(`{"errors":[{"message":"Unauthorized"}],"data":{}}`), nil, "https://www.henryrose.com/api/2024-10/graphql.json"); errOK { + t.Fatalf("shopify_storefront_graphql_json must reject GraphQL errors with empty data") + } + + // 2. #265 shopify_filter_apps_json (Boost Commerce + Globo + 403 rejection) + boostJSON := `{"total_product":2,"products":[{"id":101,"title":"MagSafe Leather Case","handle":"magsafe-leather-case","vendor":"Casely","product_type":"Phone Case","price_min":35,"available":true,"url":"/products/magsafe-leather-case"}],"filter":{"options":[{"label":"Device","values":[{"key":"iPhone 16 Pro"}]}]}}` + fDoc, okF := FormatWave3StoreAddonsJSONDoc("shopify_filter_apps_json", []byte(boostJSON), nil, "https://services.mybcapps.com/bc-sf-filter/filter?shop=get-casely.myshopify.com") + if !okF || fDoc == nil || !strings.Contains(fDoc.Markdown, "MagSafe Leather Case") || !strings.Contains(fDoc.Markdown, "iPhone 16 Pro") { + t.Fatalf("shopify_filter_apps_json failed: ok=%v doc=%+v", okF, fDoc) + } + if _, errF := FormatWave3StoreAddonsJSONDoc("shopify_filter_apps_json", []byte(`{"message":"403 Forbidden: "}`), nil, "https://services.mybcapps.com/bc-sf-filter/filter"); errF { + t.Fatalf("shopify_filter_apps_json must reject 403 Forbidden payload") + } + + // 3. #266 rebuy_searchanise_json (Searchanise + Rebuy + error rejection) + saJSON := `{"totalItems":318,"items":[{"product_id":"901","title":"Liquid Chlorophyll Drops","product_code":"MR-CHL-01","price":"24.95","vendor":"MaryRuth Organics","link":"https://www.maryruthorganics.com/products/chlorophyll"}]}` + rDoc, okR := FormatWave3StoreAddonsJSONDoc("rebuy_searchanise_json", []byte(saJSON), nil, "https://www.searchserverapi.com/getresults?apiKey=1Q7P8A7s4h&q=&output=json") + if !okR || rDoc == nil || !strings.Contains(rDoc.Markdown, "Liquid Chlorophyll Drops") || !strings.Contains(rDoc.Markdown, "MR-CHL-01") { + t.Fatalf("rebuy_searchanise_json failed: ok=%v doc=%+v", okR, rDoc) + } + rebuyJSON := `{"data":[{"id":77,"title":"Electrolyte Powder","handle":"electrolyte-powder","vendor":"Hydrate","variants":[{"sku":"HYD-1","price":"29.00"}]}]}` + rbDoc, okRB := FormatWave3StoreAddonsJSONDoc("rebuy_searchanise_json", []byte(rebuyJSON), nil, "https://rebuyengine.com/api/v1/products/recommended?key=pub123") + if !okRB || rbDoc == nil || !strings.Contains(rbDoc.Markdown, "Electrolyte Powder") { + t.Fatalf("rebuy_searchanise_json Rebuy failed: ok=%v doc=%+v", okRB, rbDoc) + } + if _, errR := FormatWave3StoreAddonsJSONDoc("rebuy_searchanise_json", []byte(`{"error":"Invalid API key"}`), nil, "https://www.searchserverapi.com/getresults"); errR { + t.Fatalf("rebuy_searchanise_json must reject error JSON") + } +} + +func TestWave3StoreAddonsHTMLModesPositiveAndPreemption(t *testing.T) { + // 1. #263 shopify-hydrogen + hydroHTML := `Hydrogen Demo Store

Hydrogen Demo Store

` + hRes := Wave3StoreAddonsRunHTML("shopify_hydrogen_html", hydroHTML, "https://hydrogen.shop/", "") + if hRes == nil || hRes.ExtractorID != "shopify-hydrogen" || !strings.Contains(hRes.Markdown, "The Hydrogen Snowboard") || !strings.Contains(hRes.Markdown, "Snowboards") { + t.Fatalf("shopify_hydrogen_html positive failed: %+v", hRes) + } + nonShopifyRemix := `My Remix Blog

My Remix Blog

` + if got := Wave3StoreAddonsRunHTML("shopify_hydrogen_html", nonShopifyRemix, "https://blog.example.com/", ""); got != nil { + t.Fatalf("shopify_hydrogen_html must reject non-Shopify Remix apps, got %+v", got) + } + + // 2. #264 recharge-bold-subscriptions (positive + non-preemption on normal Shopify PDP) + rcHTML := `100% Recycled Toilet Paper | Who Gives A Crap

100% Recycled Toilet Paper Jumbo Rolls

` + rcRes := Wave3StoreAddonsRunHTML("recharge_bold_subscriptions_html", rcHTML, "https://us.whogivesacrap.org/products/100-recycled-toilet-paper-jumbo-rolls", "") + if rcRes == nil || rcRes.ExtractorID != "recharge-bold-subscriptions" || !strings.Contains(rcRes.Markdown, "Recharge") || !strings.Contains(rcRes.Markdown, "Every 4 Weeks") || !strings.Contains(rcRes.Markdown, "USD 52.00") { + t.Fatalf("recharge_bold_subscriptions_html positive failed: %+v", rcRes) + } + plainShopifyPDP := `The Layering Collection | Henry Rose

The Layering Collection

Fine fragrance discovery set.

` + if got := Wave3StoreAddonsRunHTML("recharge_bold_subscriptions_html", plainShopifyPDP, "https://www.henryrose.com/products/the-layering-collection", ""); got != nil { + t.Fatalf("recharge_bold_subscriptions_html must yield on plain Shopify PDP, got %+v", got) + } + + // 3. #267 aftership-tracking-page (positive + CF rejection) + asHTML := `Track Your Order | Neal's Yard Remedies

Track Your Order

` + asRes := Wave3StoreAddonsRunHTML("aftership_tracking_html", asHTML, "https://track.example.com/1Z999AA10123456784", "") + if asRes == nil || asRes.ExtractorID != "aftership-tracking-page" || !strings.Contains(asRes.Markdown, "1Z999AA10123456784") || !strings.Contains(asRes.Markdown, "Boston, MA") { + t.Fatalf("aftership_tracking_html positive failed: %+v", asRes) + } + cfHTML := `Just a moment...
Enable JavaScript and cookies to continue
` + if got := Wave3StoreAddonsRunHTML("aftership_tracking_html", cfHTML, "https://www.aftership.com/track", ""); got != nil { + t.Fatalf("aftership_tracking_html must reject CF challenge, got %+v", got) + } + + // 4. #268 branded-tracking-pack (positive Narvar + Route 1KB empty shell rejection) + narvarHTML := `ASICS Order Tracking | Narvar

ASICS Order Tracking

` + nvRes := Wave3StoreAddonsRunHTML("branded_tracking_pack_html", narvarHTML, "https://tracking.narvar.com/asics/tracking", "") + if nvRes == nil || nvRes.ExtractorID != "branded-tracking-pack" || !strings.Contains(nvRes.Markdown, "Narvar") || !strings.Contains(nvRes.Markdown, "9400111899223344556677") { + t.Fatalf("branded_tracking_pack_html Narvar positive failed: %+v", nvRes) + } + routeEmptyShell := `Route Tracking
` + if got := Wave3StoreAddonsRunHTML("branded_tracking_pack_html", routeEmptyShell, "https://tracking.route.com/", ""); got != nil { + t.Fatalf("branded_tracking_pack_html must reject 1KB Route empty CSR shell, got %+v", got) + } + + // 5. #269 gorgias-reamaze (Gorgias __NEXT_DATA__ + Re:amaze DOM) + gorgiasHTML := `Contact Us | BURGA Help Center

How to Contact Support

` + gRes := Wave3StoreAddonsRunHTML("gorgias_reamaze_html", gorgiasHTML, "https://support.burga.com/en-US/articles/contact-us-24868", "") + if gRes == nil || gRes.ExtractorID != "gorgias-reamaze" || !strings.Contains(gRes.Markdown, "How to Contact Support") || !strings.Contains(gRes.Markdown, "Gorgias") { + t.Fatalf("gorgias_reamaze_html Gorgias failed: %+v", gRes) + } + reamazeHTML := `Firmware Update | Storypod

Firmware Update Instructions

Connect your Storypod to Wi-Fi and press the top button to install updates.

` + rmRes := Wave3StoreAddonsRunHTML("gorgias_reamaze_html", reamazeHTML, "https://storypod.reamaze.com/kb/all-about-storypod/firmware-update", "") + if rmRes == nil || rmRes.ExtractorID != "gorgias-reamaze" || !strings.Contains(rmRes.Markdown, "Re:amaze") || !strings.Contains(rmRes.Markdown, "Initial Setup") { + t.Fatalf("gorgias_reamaze_html Re:amaze failed: %+v", rmRes) + } + + // 6. #270 klaviyo-attentive-forms (Read-only positive + non-preemption yield on Shopify PDP) + klaviyoHomeHTML := `Casely | Bold Phone Cases

Shop Bold Phone Cases

Sign up for 15% off your first case order.

` + kRes := Wave3StoreAddonsRunHTML("klaviyo_attentive_forms_html", klaviyoHomeHTML, "https://www.getcasely.com/", "") + if kRes == nil || kRes.ExtractorID != "klaviyo-attentive-forms" || !strings.Contains(kRes.Markdown, "L74p8W") || !strings.Contains(kRes.Markdown, "casely") || !strings.Contains(kRes.Markdown, "XyZ123") || !strings.Contains(kRes.Markdown, "Read-only") { + t.Fatalf("klaviyo_attentive_forms_html positive failed: %+v", kRes) + } + shopifyWithKlaviyoPDP := `The Layering Collection | Henry Rose

The Layering Collection

` + if got := Wave3StoreAddonsRunHTML("klaviyo_attentive_forms_html", shopifyWithKlaviyoPDP, "https://www.henryrose.com/products/the-layering-collection", ""); got != nil { + t.Fatalf("klaviyo_attentive_forms_html MUST yield on /products/ + Product JSON-LD so shopify_html is never preempted, got %+v", got) + } +} + +func TestWave3StoreAddonsNegativeShellsAndLatencyBudget(t *testing.T) { + negCases := []struct { + name string + baseURL string + html string + }{ + {"404", "https://example.com/missing", `404 Not Found

Page Not Found

`}, + {"error-redirect", "https://example.com/error", `Error

Application Error

`}, + {"maintenance", "https://example.com/", `503 Service Unavailable

Down for Maintenance

`}, + {"empty-spa", "https://example.com/", `Loading...
`}, + {"cf-challenge", "https://example.com/", `Just a moment...
Checking your browser before accessing
`}, + } + + activeModes := []string{ + "shopify_hydrogen_html", + "recharge_bold_subscriptions_html", + "aftership_tracking_html", + "branded_tracking_pack_html", + "gorgias_reamaze_html", + "klaviyo_attentive_forms_html", + } + start := time.Now() + for _, m := range activeModes { + for _, nc := range negCases { + if res := Wave3StoreAddonsRunHTML(m, nc.html, nc.baseURL, ""); res != nil { + t.Fatalf("mode %q negative case %q must return nil, got %+v", m, nc.name, res) + } + } + } + elapsed := time.Since(start) + if elapsed > 200*time.Millisecond*time.Duration(extractRaceSlowdown) { + t.Fatalf("negative shell sweep exceeded latency budget: %v", elapsed) + } +} + +func TestWave3StoreAddonsPreemptionAnd2MBPerfBudget(t *testing.T) { + // Finding 9a: klaviyo-attentive-forms yields on @type: ["Thing", "Product"], ProductGroup, schema.org/Product, and commerce markers + wooArrayProd := `Trail Boots

Trail Boots

` + if got := Wave3StoreAddonsRunHTML("klaviyo_attentive_forms_html", wooArrayProd, "https://woo.example.com/shop/trail-boots/", ""); got != nil { + t.Fatalf("klaviyo must yield on WooCommerce + @type:[Thing,Product], got %+v", got) + } + shopifyOGProd := `Trail Boots

Trail Boots

` + if got := Wave3StoreAddonsRunHTML("klaviyo_attentive_forms_html", shopifyOGProd, "https://shop.example.com/gear/trail-boots", ""); got != nil { + t.Fatalf("klaviyo must yield on Shopify.shop / cdn.shopify.com / og:type=product, got %+v", got) + } + + // Finding 9b: recharge-bold-subscriptions MUST NOT match generic prose when selling_plans_size = 0 and no widget DOM exists + zeroPlansProse := `Single Origin Coffee

Single Origin Coffee

Subscribe and save 10% on our newsletter! Free delivery every Friday.

` + if got := Wave3StoreAddonsRunHTML("recharge_bold_subscriptions_html", zeroPlansProse, "https://coffee.example.com/products/single-origin", ""); got != nil { + t.Fatalf("recharge must yield when selling_plans_size=0 and no widget DOM exists, got %+v", got) + } + + // Finding 8: 2.37 MB HTML latency budget (< 75ms per extractor) + pad := strings.Repeat("

Product catalog item description and styling details for storefront layout.

\n", 26000) + bigKlaviyo := `Casely
Sign up for 15% off
` + pad + `` + bigRecharge := `Coffee

Coffee

` + pad + `` + bigBranded := `Track

` + strings.Repeat("Order status details. ", 15) + `

` + pad + `` + + for _, tc := range []struct { + mode string + html string + }{ + {"klaviyo_attentive_forms_html", bigKlaviyo}, + {"recharge_bold_subscriptions_html", bigRecharge}, + {"branded_tracking_pack_html", bigBranded}, + } { + tStart := time.Now() + _ = Wave3StoreAddonsRunHTML(tc.mode, tc.html, "https://example.com/", "") + budget := 50 * time.Millisecond * time.Duration(extractRaceSlowdown) + if d := time.Since(tStart); d > budget { + t.Fatalf("2.3MB HTML run for %s exceeded %v native Go budget (must be << 75ms in WASM): %v", tc.mode, budget, d) + } + } +} + +func TestWave3StoreAddonsM7GorgiasSelectedCategory(t *testing.T) { + burgaHTML := `Contact Us | BURGA Help Center

Contact Us

` + res := Wave3StoreAddonsRunHTML("gorgias_reamaze_html", burgaHTML, "https://support.burga.com/en-US/articles/contact-us-24868", "gorgias-reamaze") + if res == nil || res.ExtractorID != "gorgias-reamaze" { + t.Fatalf("gorgias_reamaze_html selectedCategory returned nil: %+v", res) + } + for _, want := range []string{ + "Contact Us", + "Ways to reach BURGA customer support.", + "How can I contact customer support?", + "https://support.burga.com/en-US/articles/how-can-i-contact-customer-support-24869", + "Order modification window", + "Shipping & Delivery", + "Returns & Warranty", + } { + if !strings.Contains(res.Markdown, want) { + t.Fatalf("gorgias_reamaze_html selectedCategory missing %q in Markdown:\n%s", want, res.Markdown) + } + } + if len(res.Records) != 4 { + t.Fatalf("expected 4 records (2 childrenArticles + 2 sidebarCategories), got %d: %+v", len(res.Records), res.Records) + } +} diff --git a/internal/extract/wave3_trade.go b/internal/extract/wave3_trade.go new file mode 100644 index 0000000..9562bf8 --- /dev/null +++ b/internal/extract/wave3_trade.go @@ -0,0 +1,2222 @@ +package extract + +import ( + "bytes" + "encoding/json" + "fmt" + stdhtml "html" + "math" + "net/url" + "strconv" + "strings" +) + +const ( + wave3TradeMaxHTMLBytes = 2 * 1024 * 1024 + wave3TradeMaxJSONBytes = 4 * 1024 * 1024 + wave3TradeMaxTextBytes = 4 * 1024 * 1024 + wave3TradeMaxRecords = 25 + wave3TradeMaxOFACRecords = 25 +) + +var ( + wave3TradeRxNotFoundTitle = newLazyRegexp(`(?i)(?:^|\b)(?:404|410|406|page\s+not\s+found|page\s+cannot\s+be\s+found|not\s+found|error\s*404|we\s+couldn'?t\s+find\s+that\s+page|access\s+denied|request\s+(?:rejected|blocked)|could\s+not\s+be\s+satisfied|unauthorized|attention\s+required|just\s+a\s+moment|403\s+forbidden|forbidden|403\s+error|ruling\s+not\s+found)(?:\b|$)`) + wave3TradeRxMaintTitle = newLazyRegexp(`(?i)(?:scheduled\s+maintenance|temporarily\s+unavailable|service\s+unavailable|site\s+maintenance|under\s+maintenance|502\s+bad\s+gateway|503\s+service|down\s+for\s+maintenance)`) + wave3TradeRxErrorTitle = newLazyRegexp(`(?i)^(?:(?:(?:401|403|404|406|410|429|500|502|503)\s+)?(?:internal\s+)?server\s+error|application\s+error|system\s+error|unexpected\s+error|error\s+page|(?:401|403|404|406|410|429|500|502|503|http\s+\d{3})\s+error|error\s+(?:401|403|404|406|410|429|500|502|503)|error|invalid\s+key)(?:\s*[|\-\x{2013}\x{2014}:]\s*.*)?$|^.*(?:\s*[|\-\x{2013}\x{2014}:]\s*error)$`) + wave3TradeRxGenericTitle = newLazyRegexp(`(?i)^(?:loading\.{0,3}|home|welcome|search|menu|navigation|harmonized\s+tariff\s+schedule|customs\s+rulings\s+online\s+search\s+system\s*\(cross\)|usa\s+trade\s+online)$`) + wave3TradeRxHTMLTag = newLazyRegexp(`<[^>]+>`) + wave3TradeRxSpaceCollapse = newLazyRegexp(`[ \t\r\n]+`) + wave3TradeRxHref = newLazyRegexp(`(?is)]*\bhref\s*=\s*["']([^"'#][^"']*)["'][^>]*>(.*?)`) + wave3TradeRxSlashDate = newLazyRegexp(`^(\d{1,2})/(\d{1,2})/(\d{4})$`) + wave3TradeRxNextData = newLazyRegexp(`(?is)]*\bid\s*=\s*["']__NEXT_DATA__["'][^>]*>(.*?)`) + wave3TradeRxFDAField = newLazyRegexp(`(?i)(Import\s+Alert\s*#\s*:?|(?:Published\s+Date|Type|Import\s+Alert\s+Name|Reason\s+for\s+Alert)\s*:)\s*`) +) + +func init() { + for _, mode := range []string{ + "usitc_hts_html", + "cbp_cross_html", + "census_foreign_trade_html", + "ustr_301_html", + "trade_gov_csl_html", + "ofac_html", + "bis_entity_list_html", + "import_alerts_fda_aphis_html", + } { + m := mode + RegisterExternalHTMLModeLazy(m, func(rawHTML, baseURL string, _ func() string, extractorID string) *DeclarativePostFetchResult { + return Wave3TradeRunHTML(m, rawHTML, baseURL, extractorID) + }) + } +} + +// IsWave3TradeHTMLMode reports whether mode is one of the 8 Category J Trade, Tariffs & Sanctions HTML extractors (#271-#278). +func IsWave3TradeHTMLMode(mode string) bool { + switch mode { + case "usitc_hts_html", + "cbp_cross_html", + "census_foreign_trade_html", + "ustr_301_html", + "trade_gov_csl_html", + "ofac_html", + "bis_entity_list_html", + "import_alerts_fda_aphis_html": + return true + default: + return false + } +} + +// IsWave3TradeJSONMode reports whether mode is handled by Category J JSON formatters (#271, #272, #275). +func IsWave3TradeJSONMode(mode string) bool { + switch mode { + case "usitc_hts_json", + "cbp_cross_json", + "trade_gov_csl_json": + return true + default: + return false + } +} + +// IsWave3TradeTextMode reports whether mode is handled by Category J XML/text formatters (#274, #276). +func IsWave3TradeTextMode(mode string) bool { + switch mode { + case "ofac_sdn_xml", + "ustr_301_rss_xml": + return true + default: + return false + } +} + +func wave3TradeDefaultExtractorID(mode string) string { + switch mode { + case "usitc_hts_html", "usitc_hts_json": + return "usitc-hts" + case "cbp_cross_html", "cbp_cross_json": + return "cbp-cross-rulings" + case "census_foreign_trade_html": + return "census-foreign-trade" + case "ustr_301_html", "ustr_301_rss_xml": + return "ustr-301" + case "trade_gov_csl_html", "trade_gov_csl_json": + return "trade-gov-csl" + case "ofac_html", "ofac_sdn_xml": + return "ofac-sdn" + case "bis_entity_list_html": + return "bis-entity-list" + case "import_alerts_fda_aphis_html": + return "import-alerts-aphis-fda" + default: + return "" + } +} + +// Wave3TradeRunHTML executes a Category J HTML extractor and returns DeclarativePostFetchResult. +func Wave3TradeRunHTML(mode, rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + if !IsWave3TradeHTMLMode(mode) || len(rawHTML) == 0 || strings.IndexByte(rawHTML, '<') < 0 || strings.IndexByte(rawHTML, '>') < 0 { + return nil + } + if len(rawHTML) > wave3TradeMaxHTMLBytes { + rawHTML = truncateUTF8SafeFullDocGo(rawHTML, wave3TradeMaxHTMLBytes) + } + trimmedStart := strings.TrimLeft(rawHTML, " \t\r\n") + if trimmedStart == "" || trimmedStart[0] == '{' || trimmedStart[0] == '[' { + return nil + } + probe := rawHTML + if len(probe) > 65536 { + probe = probe[:65536] + } + probeLower := asciiLowerExtractString(probe) + urlLower := asciiLowerExtractString(baseURL) + + // Cheap byte prefilter BEFORE common negative-shell checks or DOM parsing. + if !wave3TradeMatchesModePrefilter(mode, probeLower, urlLower) { + return nil + } + if wave3TradeHasCommonNegativeShell(rawHTML, probeLower, baseURL, urlLower) { + return nil + } + if extractorID == "" { + extractorID = wave3TradeDefaultExtractorID(mode) + } + + var res *DeclarativePostFetchResult + switch mode { + case "usitc_hts_html": + res = wave3TradeExtractUSITCHTSHTML(rawHTML, probeLower, baseURL, extractorID) + case "cbp_cross_html": + res = wave3TradeExtractCBPCrossHTML(rawHTML, probeLower, baseURL, extractorID) + case "census_foreign_trade_html": + res = wave3TradeExtractCensusForeignTradeHTML(rawHTML, baseURL, extractorID) + case "ustr_301_html": + res = wave3TradeExtractUSTR301HTML(rawHTML, baseURL, extractorID) + case "trade_gov_csl_html": + res = wave3TradeExtractTradeGovCSLHTML(rawHTML, baseURL, extractorID) + case "ofac_html": + res = wave3TradeExtractOFACHTML(rawHTML, baseURL, extractorID) + case "bis_entity_list_html": + res = wave3TradeExtractBISEntityListHTML(rawHTML, probeLower, baseURL, extractorID) + case "import_alerts_fda_aphis_html": + res = wave3TradeExtractImportAlertsHTML(rawHTML, probeLower, baseURL, urlLower, extractorID) + } + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return nil + } + return wave3TradeFinalizePostFetch(res) +} + +// RunWave3TradeHTMLMode executes a Category J HTML extractor and returns JSON-marshaled DeclarativePostFetchResult. +func RunWave3TradeHTMLMode(mode, rawHTML, baseURL string) (string, bool) { + res := Wave3TradeRunHTML(mode, rawHTML, baseURL, wave3TradeDefaultExtractorID(mode)) + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return "", false + } + res = sanitizePostFetchResultDeclHTML(res) + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return "", false + } + encoded, err := json.Marshal(res) + if err != nil { + return "", false + } + return string(encoded), true +} + +// FormatWave3TradeJSONDoc formats a Category J JSON twin payload into DeclarativeFormattedDoc. +func FormatWave3TradeJSONDoc(mode string, raw []byte, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool) { + if !IsWave3TradeJSONMode(mode) || len(raw) == 0 || len(raw) > wave3TradeMaxJSONBytes { + return nil, false + } + trimmed := bytes.TrimSpace(bytes.TrimPrefix(raw, []byte("\xEF\xBB\xBF"))) + if len(trimmed) == 0 || (trimmed[0] != '{' && trimmed[0] != '[') { + return nil, false + } + parsed, ok := decodeJSONWithNumbers(trimmed) + if !ok || parsed == nil { + return nil, false + } + + var doc *DeclarativeFormattedDoc + var handled bool + switch mode { + case "usitc_hts_json": + doc, handled = wave3TradeFormatUSITCHTSJSON(parsed, origURL) + case "cbp_cross_json": + doc, handled = wave3TradeFormatCBPCrossJSON(parsed, origURL) + case "trade_gov_csl_json": + doc, handled = wave3TradeFormatTradeGovCSLJSON(parsed, origURL) + } + if !handled || doc == nil || strings.TrimSpace(doc.Markdown) == "" { + return nil, false + } + return wave3TradeFinalizeDoc(doc), true +} + +// FormatWave3TradeJSONMode formats a Category J JSON payload and returns JSON-marshaled DeclarativeFormattedDoc. +func FormatWave3TradeJSONMode(mode string, raw []byte, params map[string]string, origURL string) (string, bool) { + doc, ok := FormatWave3TradeJSONDoc(mode, raw, params, origURL) + if !ok || doc == nil { + return "", false + } + encoded, err := json.Marshal(doc) + if err != nil { + return "", false + } + return string(encoded), true +} + +// FormatWave3TradeTextDoc formats a Category J XML/text twin payload (`ofac_sdn_xml`, `ustr_301_rss_xml`). +func FormatWave3TradeTextDoc(mode, rawBody string, params map[string]string, origURL string) (*DeclarativeFormattedDoc, bool) { + if !IsWave3TradeTextMode(mode) || len(rawBody) == 0 { + return nil, false + } + if len(rawBody) > wave3TradeMaxTextBytes { + rawBody = truncateUTF8SafeFullDocGo(rawBody, wave3TradeMaxTextBytes) + } + + var doc *DeclarativeFormattedDoc + var handled bool + switch mode { + case "ofac_sdn_xml": + doc, handled = wave3TradeFormatOFACSDNXML(rawBody, origURL) + case "ustr_301_rss_xml": + doc, handled = wave3TradeFormatUSTR301RSS(rawBody, origURL) + } + if !handled || doc == nil || strings.TrimSpace(doc.Markdown) == "" { + return nil, false + } + return wave3TradeFinalizeDoc(doc), true +} + +// FormatWave3TradeTextMode formats a Category J XML/text payload and returns JSON-marshaled DeclarativeFormattedDoc. +func FormatWave3TradeTextMode(mode, rawBody string, params map[string]string, origURL string) (string, bool) { + doc, ok := FormatWave3TradeTextDoc(mode, rawBody, params, origURL) + if !ok || doc == nil { + return "", false + } + encoded, err := json.Marshal(doc) + if err != nil { + return "", false + } + return string(encoded), true +} + +// ── Prefilters & Shared Hygiene Helpers ────────────────────────────────────────────────────────── + +func wave3TradeMatchesModePrefilter(mode, probeLower, urlLower string) bool { + switch mode { + case "usitc_hts_html": + return strings.Contains(urlLower, "hts.usitc.gov") || + strings.Contains(probeLower, "hts.usitc.gov") || + strings.Contains(probeLower, "harmonized tariff schedule") || + strings.Contains(probeLower, "hts-root") + case "cbp_cross_html": + return strings.Contains(urlLower, "rulings.cbp.gov") || + strings.Contains(probeLower, "rulings.cbp.gov") || + strings.Contains(probeLower, "customs rulings online search system") || + strings.Contains(probeLower, "rulingnumber") + case "census_foreign_trade_html": + return strings.Contains(urlLower, "usatradeonline.census.gov") || + strings.Contains(urlLower, "usatrade.census.gov") || + strings.Contains(probeLower, "usa trade online") || + strings.Contains(probeLower, "usatradeonline") + case "ustr_301_html": + return strings.Contains(urlLower, "ustr.gov") || + strings.Contains(probeLower, "ustr.gov") || + strings.Contains(probeLower, "united states trade representative") || + strings.Contains(probeLower, "section 301") + case "trade_gov_csl_html": + return strings.Contains(urlLower, "trade.gov") || + strings.Contains(probeLower, "trade.gov") || + strings.Contains(probeLower, "consolidated screening list") || + strings.Contains(probeLower, "international trade administration") + case "ofac_html": + return strings.Contains(urlLower, "ofac.treasury.gov") || + strings.Contains(probeLower, "ofac.treasury.gov") || + strings.Contains(probeLower, "office of foreign assets control") || + strings.Contains(probeLower, "sanctions-programs") + case "bis_entity_list_html": + return strings.Contains(urlLower, "bis.gov") || + strings.Contains(probeLower, "bis.gov") || + strings.Contains(probeLower, "bureau of industry and security") || + strings.Contains(probeLower, "export administration regulations") + case "import_alerts_fda_aphis_html": + return strings.Contains(urlLower, "accessdata.fda.gov") || + strings.Contains(urlLower, "aphis.usda.gov") || + strings.Contains(probeLower, "import alert") || + strings.Contains(probeLower, "cms_ia") || + strings.Contains(probeLower, "aphis.usda.gov") || + strings.Contains(probeLower, "animal and plant health inspection service") + default: + return false + } +} + +func wave3TradeIsNegativeURL(urlLower string) bool { + if urlLower == "" { + return false + } + if strings.Contains(urlLower, "/404") || + strings.Contains(urlLower, "/not-found") || + strings.Contains(urlLower, "/page-not-found") || + strings.Contains(urlLower, "/maintenance") || + strings.Contains(urlLower, "missing_key.html") || + strings.Contains(urlLower, "error=true") || + strings.Contains(urlLower, "error=1") { + return true + } + pathOnly := urlLower + if idx := strings.Index(pathOnly, "://"); idx >= 0 { + rest := pathOnly[idx+3:] + if slash := strings.IndexByte(rest, '/'); slash >= 0 { + pathOnly = rest[slash:] + } else { + pathOnly = "/" + } + } + if cut := strings.IndexAny(pathOnly, "?#"); cut >= 0 { + pathOnly = pathOnly[:cut] + } + return strings.HasSuffix(pathOnly, "/error") || + strings.Contains(pathOnly, "/error/") || + strings.HasSuffix(pathOnly, "/error.html") || + strings.HasSuffix(pathOnly, "/error.htm") || + strings.HasSuffix(pathOnly, "/error.aspx") || + strings.HasSuffix(pathOnly, "/login") || + strings.Contains(pathOnly, "/login/") +} + +func wave3TradeIsNegativeTitle(title string) bool { + t := strings.TrimSpace(title) + if t == "" { + return false + } + return wave3TradeRxNotFoundTitle.MatchString(t) || + wave3TradeRxMaintTitle.MatchString(t) || + wave3TradeRxErrorTitle.MatchString(t) +} + +func wave3TradeIsGenericTitle(title string) bool { + return wave3TradeRxGenericTitle.MatchString(strings.TrimSpace(title)) +} + +func wave3TradeHasCommonNegativeShell(rawHTML, probeLower, baseURL, urlLower string) bool { + if wave3TradeIsNegativeURL(urlLower) { + return true + } + for _, marker := range []string{ + "cf-browser-verification", + "cf-turnstile", + "challenge-platform", + "_cf_chl_opt", + "cf_chl_opt", + "attention required! | cloudflare", + "just a moment...", + "errors.edgesuite.net", + "error from cloudfront", + "the request could not be satisfied", + "you don't have permission to access", + "the requested url was rejected", + "your support id is", + "var dd=", + "var dd =", + "dd={'rt'", + "geo.captcha-delivery.com", + "captcha-delivery.com", + "please enable js and disable any ad blocker", + "missing_key.html", + "security parameters are missing", + "missing subscription key", + "invalid subscription key", + "scheduled maintenance", + "down for maintenance", + "temporarily unavailable", + } { + if strings.Contains(probeLower, marker) { + return true + } + } + title := extractTitleLinearQuick(rawHTML) + if wave3TradeIsNegativeTitle(title) { + return true + } + if canon := strings.ToLower(extractMetaContentDeclHTML(rawHTML, "og:url")); strings.HasSuffix(canon, "/404") || strings.Contains(canon, "/404?") { + return true + } + rawLower := asciiLowerExtractString(rawHTML) + hasRealBodyMarkers := hasJSONLDScriptToken(rawHTML) || + strings.Contains(rawLower, ", ) can ship with >60KB inline CSS; + // reject them regardless of byte length when no SSR heading, article, table, or JSON-LD exists. + if (strings.Contains(rawLower, "") || strings.Contains(rawLower, "")) && + !hasRealBodyMarkers { + return true + } + if wave3HasEmptyRootDivShell(rawHTML, probeLower, true) && + !hasRealBodyMarkers { + return true + } + return false +} + +func wave3TradeIsGenericJSONError(obj map[string]any) bool { + if obj == nil { + return true + } + if succ, ok := obj["success"].(bool); ok && !succ { + return true + } + for _, k := range []string{"error", "errors", "error_message", "errorMessage", "errorCode", "error_description", "fault"} { + if v, exists := obj[k]; exists && v != nil { + switch tv := v.(type) { + case string: + if strings.TrimSpace(tv) != "" { + return true + } + case []any: + if len(tv) > 0 { + return true + } + case map[string]any: + if len(tv) > 0 { + return true + } + case bool: + if tv { + return true + } + } + } + } + for _, k := range []string{"error_code", "statusCode", "status_code", "status"} { + if f, ok := wave3TradeFloatVal(obj[k]); ok && f >= 400 { + return true + } + } + if st := strings.ToUpper(wave3TradePlain(obj["status"], 48)); st == "ERROR" || st == "NOT_FOUND" || st == "PERMISSION_DENIED" || st == "UNAUTHENTICATED" || st == "UNAUTHORIZED" { + return true + } + if msg := wave3TradePlain(obj["message"], 240); msg != "" && len(obj) <= 4 { + lm := strings.ToLower(msg) + if strings.Contains(lm, "unauthorized") || + strings.Contains(lm, "not found") || + strings.Contains(lm, "invalid") || + strings.Contains(lm, "forbidden") || + strings.Contains(lm, "security parameters") || + strings.Contains(lm, "subscription key") || + strings.Contains(lm, "missing") { + return true + } + } + return false +} + +func wave3TradeIntPtr(n int) *int { return &n } +func wave3TradeBoolPtr(b bool) *bool { return &b } + +func wave3TradeFinalizeDoc(doc *DeclarativeFormattedDoc) *DeclarativeFormattedDoc { + if doc == nil { + return nil + } + if len(doc.Records) > wave3TradeMaxRecords { + if doc.Total == nil { + doc.Total = wave3TradeIntPtr(len(doc.Records)) + } + doc.Records = doc.Records[:wave3TradeMaxRecords] + doc.Returned = wave3TradeIntPtr(len(doc.Records)) + doc.Truncated = wave3TradeBoolPtr(true) + if doc.NextCursor == "" { + doc.NextCursor = strconv.Itoa(len(doc.Records)) + } + } + if sanitized, ok := sanitizeDeclarativeFormattedDocGo(doc); ok && sanitized != nil { + return sanitized + } + return nil +} + +func wave3TradeFinalizePostFetch(res *DeclarativePostFetchResult) *DeclarativePostFetchResult { + if res == nil || strings.TrimSpace(res.Markdown) == "" { + return nil + } + if len(res.Records) > wave3TradeMaxRecords { + if res.Total == nil { + res.Total = wave3TradeIntPtr(len(res.Records)) + } + res.Records = res.Records[:wave3TradeMaxRecords] + res.Returned = wave3TradeIntPtr(len(res.Records)) + res.Truncated = wave3TradeBoolPtr(true) + if res.NextCursor == "" { + res.NextCursor = strconv.Itoa(len(res.Records)) + } + } + return res +} + +func wave3TradeCleanText(s string) string { + if s == "" { + return "" + } + if strings.IndexByte(s, '<') >= 0 { + s = wave3TradeRxHTMLTag.ReplaceAllString(s, " ") + } + if strings.IndexByte(s, '&') >= 0 { + s = stdhtml.UnescapeString(s) + if strings.IndexByte(s, '<') >= 0 { + s = wave3TradeRxHTMLTag.ReplaceAllString(s, " ") + } + } + if !strings.ContainsAny(s, "\t\r\n") && !strings.Contains(s, " ") { + return strings.TrimSpace(s) + } + return strings.TrimSpace(wave3TradeRxSpaceCollapse.ReplaceAllString(s, " ")) +} + +func wave3TradeStringVal(v any) string { + switch tv := v.(type) { + case string: + return strings.TrimSpace(tv) + case json.Number: + return tv.String() + case float64: + if math.IsNaN(tv) || math.IsInf(tv, 0) { + return "" + } + if tv == math.Trunc(tv) { + return strconv.FormatInt(int64(tv), 10) + } + return strconv.FormatFloat(tv, 'f', -1, 64) + case int: + return strconv.Itoa(tv) + case int64: + return strconv.FormatInt(tv, 10) + case bool: + if tv { + return "true" + } + return "false" + default: + return "" + } +} + +func wave3TradeFloatVal(v any) (float64, bool) { + switch tv := v.(type) { + case float64: + if math.IsNaN(tv) || math.IsInf(tv, 0) { + return 0, false + } + return tv, true + case int: + return float64(tv), true + case int64: + return float64(tv), true + case json.Number: + f, err := tv.Float64() + if err != nil || math.IsNaN(f) || math.IsInf(f, 0) { + return 0, false + } + return f, true + case string: + s := strings.TrimSpace(strings.ReplaceAll(tv, ",", "")) + if s == "" { + return 0, false + } + f, err := strconv.ParseFloat(s, 64) + if err != nil || math.IsNaN(f) || math.IsInf(f, 0) { + return 0, false + } + return f, true + default: + return 0, false + } +} + +func wave3TradePlain(v any, maxLen int) string { + return SanitizeSchemaPlainField(wave3TradeStringVal(v), maxLen) +} + +func wave3TradeFirstNonEmpty(vals ...string) string { + for _, v := range vals { + if t := strings.TrimSpace(v); t != "" { + return t + } + } + return "" +} + +func wave3TradeNormalizeDate(raw string) string { + s := SanitizeSchemaPlainField(raw, 48) + if s == "" { + return "" + } + if m := wave3TradeRxSlashDate.FindStringSubmatch(s); len(m) == 4 { + mo, _ := strconv.Atoi(m[1]) + da, _ := strconv.Atoi(m[2]) + if mo >= 1 && mo <= 12 && da >= 1 && da <= 31 { + return fmt.Sprintf("%s-%02d-%02d", m[3], mo, da) + } + } + if len(s) >= 10 && s[4] == '-' && s[7] == '-' { + return s[:10] + } + return s +} + +func wave3TradeAddLink(links *[]string, seen map[string]bool, raw, base string) { + u := SanitizeSchemaHTTPSURL(raw, base) + if u != "" && !seen[u] { + seen[u] = true + *links = append(*links, u) + } +} + +func wave3TradeExtractTitle(doc *HTMLDoc, rawHTML string) string { + if doc != nil { + if h1 := SanitizeSchemaPlainField(wave3TradeCleanText(doc.Text("h1")), 240); h1 != "" && !wave3TradeIsGenericTitle(h1) { + return h1 + } + } + if og := SanitizeSchemaPlainField(extractMetaContentDeclHTML(rawHTML, "og:title"), 240); og != "" && !wave3TradeIsGenericTitle(og) { + return og + } + if t := SanitizeSchemaPlainField(extractTitleLinearQuick(rawHTML), 240); t != "" && !wave3TradeIsGenericTitle(t) { + return t + } + return "" +} + +func wave3TradeExtractMetaDesc(rawHTML string) string { + return wave3TradeFirstNonEmpty( + SanitizeSchemaPlainField(extractMetaContentDeclHTML(rawHTML, "og:description"), 600), + SanitizeSchemaPlainField(extractMetaContentDeclHTML(rawHTML, "description"), 600), + SanitizeSchemaPlainField(extractMetaContentDeclHTML(rawHTML, "dc.description"), 600), + ) +} + +func wave3TradeFragToMD(frag, baseURL string) string { + if strings.TrimSpace(frag) == "" { + return "" + } + doc := ExtractHTMLDocumentFull(""+frag+"", FullExtractOptions{ + BaseURL: baseURL, + OnlyMainContent: false, + IncludeImages: false, + IsFragment: true, + SkipUniversalExtractors: true, + SkipPlainText: true, + }) + return strings.TrimSpace(doc.Markdown) +} + +func wave3TradeExtractTableBlock(doc *HTMLDoc) (string, [][]string) { + if doc == nil { + return "", nil + } + rows := doc.TableRows("table") + if len(rows) < 2 { + return "", nil + } + headers := rows[0] + if len(headers) == 0 { + return "", nil + } + cols := len(headers) + if cols > 6 { + cols = 6 + } + cleanHdr := make([]string, cols) + for i := 0; i < cols; i++ { + cleanHdr[i] = SanitizeSchemaPlainField(headers[i], 80) + if cleanHdr[i] == "" { + cleanHdr[i] = fmt.Sprintf("Col %d", i+1) + } + } + var dataRows [][]string + for rIdx := 1; rIdx < len(rows) && len(dataRows) < wave3TradeMaxRecords; rIdx++ { + r := rows[rIdx] + if len(r) == 0 { + continue + } + dr := make([]string, cols) + nonEmpty := false + for c := 0; c < cols; c++ { + if c < len(r) { + dr[c] = SanitizeSchemaPlainField(r[c], 140) + if dr[c] != "" { + nonEmpty = true + } + } + } + if nonEmpty { + dataRows = append(dataRows, dr) + } + } + if len(dataRows) == 0 { + return "", nil + } + return formatDeclarativeGFMTable(cleanHdr, dataRows), dataRows +} + +func wave3TradeExtractParagraphs(doc *HTMLDoc, maxParas int) []string { + if doc == nil { + return nil + } + var paras []string + seen := make(map[string]bool) + for _, sel := range []string{"main p, article p, .field--name-body p", "p"} { + for _, p := range doc.Select(sel, maxParas*2) { + txt := SanitizeSchemaPlainField(wave3TradeCleanText(p.Text()), 800) + if len(txt) < 20 || seen[txt] { + continue + } + seen[txt] = true + paras = append(paras, txt) + if len(paras) >= maxParas { + return paras + } + } + if len(paras) > 0 { + break + } + } + return paras +} + +func wave3TradeExtractLinksFromHTML(rawHTML, baseURL string, maxLinks int) []struct{ Text, URL string } { + matches := wave3TradeRxHref.FindAllStringSubmatch(rawHTML, maxLinks*4) + out := make([]struct{ Text, URL string }, 0, maxLinks) + seen := make(map[string]bool) + for _, m := range matches { + if len(out) >= maxLinks { + break + } + if len(m) < 3 { + continue + } + href := stdhtml.UnescapeString(strings.TrimSpace(m[1])) + if href == "" || strings.HasPrefix(strings.ToLower(href), "javascript:") { + continue + } + u := SanitizeSchemaHTTPSURL(href, baseURL) + if u == "" || seen[u] { + continue + } + txt := SanitizeSchemaPlainField(wave3TradeCleanText(m[2]), 140) + if txt == "" { + continue + } + seen[u] = true + out = append(out, struct{ Text, URL string }{Text: txt, URL: u}) + } + return out +} + +// ── #271 USITC HTS JSON & HTML ────────────────────────────────────────────────────────────────── + +func wave3TradeFormatUSITCHTSJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + var items []any + switch pv := parsed.(type) { + case []any: + items = pv + case map[string]any: + if wave3TradeIsGenericJSONError(pv) { + return nil, false + } + for _, k := range []string{"results", "items", "hts", "data"} { + if arr, ok := pv[k].([]any); ok && len(arr) > 0 { + items = arr + break + } + } + } + if len(items) == 0 { + return nil, false + } + + var recs []map[string]any + var rows [][]string + for _, it := range items { + if len(recs) >= wave3TradeMaxRecords { + break + } + m, ok := it.(map[string]any) + if !ok { + continue + } + htsno := wave3TradePlain(m["htsno"], 32) + desc := wave3TradePlain(m["description"], 240) + if htsno == "" && desc == "" { + continue + } + indent := wave3TradePlain(m["indent"], 8) + general := wave3TradePlain(m["general"], 80) + special := wave3TradePlain(m["special"], 140) + other := wave3TradePlain(m["other"], 80) + addDuties := wave3TradeFirstNonEmpty( + wave3TradePlain(m["additionalDuties"], 120), + wave3TradePlain(m["addiitionalDuties"], 120), + ) + + var units []string + if uArr, okU := m["units"].([]any); okU { + for _, uv := range uArr { + if us := wave3TradePlain(uv, 24); us != "" { + units = append(units, us) + } + } + } + + var footnoteStrs []string + if fnArr, okF := m["footnotes"].([]any); okF { + for _, fv := range fnArr { + fm, okFM := fv.(map[string]any) + if !okFM { + continue + } + val := wave3TradePlain(fm["value"], 160) + if val == "" { + continue + } + var cols []string + if cArr, okC := fm["columns"].([]any); okC { + for _, cv := range cArr { + if cs := wave3TradePlain(cv, 24); cs != "" { + cols = append(cols, cs) + } + } + } + if len(cols) > 0 { + footnoteStrs = append(footnoteStrs, strings.Join(cols, "/")+": "+val) + } else { + footnoteStrs = append(footnoteStrs, val) + } + if len(footnoteStrs) >= 4 { + break + } + } + } + footnotesJoined := strings.Join(footnoteStrs, "; ") + if addDuties != "" { + if footnotesJoined != "" { + footnotesJoined += "; Additional: " + addDuties + } else { + footnotesJoined = "Additional: " + addDuties + } + } + + rec := map[string]any{ + "source": "usitc-hts", + "htsno": htsno, + "description": desc, + } + if indent != "" { + rec["indent"] = indent + } + if len(units) > 0 { + rec["units"] = units + } + if general != "" { + rec["general"] = general + } + if special != "" { + rec["special"] = special + } + if other != "" { + rec["other"] = other + } + if footnotesJoined != "" { + rec["footnotes"] = footnotesJoined + } + if addDuties != "" { + rec["additionalDuties"] = addDuties + } + recs = append(recs, rec) + rows = append(rows, []string{ + wave3TradeFirstNonEmpty(htsno, "-"), + wave3TradeFirstNonEmpty(desc, "-"), + wave3TradeFirstNonEmpty(general, "-"), + wave3TradeFirstNonEmpty(special, "-"), + wave3TradeFirstNonEmpty(other, "-"), + wave3TradeFirstNonEmpty(footnotesJoined, "-"), + }) + } + if len(recs) == 0 { + return nil, false + } + + title := "USITC Harmonized Tariff Schedule" + if u, err := url.Parse(origURL); err == nil { + if kw := SanitizeSchemaPlainField(u.Query().Get("keyword"), 80); kw != "" { + title = fmt.Sprintf("USITC HTS Search: %s", kw) + } else if from := SanitizeSchemaPlainField(u.Query().Get("from"), 32); from != "" { + to := SanitizeSchemaPlainField(u.Query().Get("to"), 32) + if to != "" && to != from { + title = fmt.Sprintf("USITC HTS Range: %s to %s", from, to) + } else { + title = fmt.Sprintf("USITC HTS Heading: %s", from) + } + } + } + + blocks := []string{ + "# " + escapeDeclMarkdownBrackets(title), + fmt.Sprintf("- **Returned**: %d of %d tariff lines", len(recs), len(items)), + "## Tariff Lines\n\n" + formatDeclarativeGFMTable( + []string{"HTS No.", "Description", "General", "Special", "Other", "Footnotes / Sec. 301"}, + rows, + ), + } + truncated := len(items) > len(recs) + doc := &DeclarativeFormattedDoc{ + Title: title, + Markdown: strings.Join(blocks, "\n\n"), + Records: recs, + Total: wave3TradeIntPtr(len(items)), + Returned: wave3TradeIntPtr(len(recs)), + Truncated: wave3TradeBoolPtr(truncated), + } + if truncated { + doc.NextCursor = strconv.Itoa(len(recs)) + } + return doc, true +} + +func wave3TradeExtractUSITCHTSHTML(rawHTML, probeLower, baseURL, extractorID string) *DeclarativePostFetchResult { + doc := ParseHTMLDoc(rawHTML, wave3TradeMaxHTMLBytes) + tableMD, tableRows := wave3TradeExtractTableBlock(doc) + paras := wave3TradeExtractParagraphs(doc, 8) + if tableMD == "" && len(paras) == 0 { + return nil + } + title := wave3TradeFirstNonEmpty(wave3TradeExtractTitle(doc, rawHTML), "USITC Harmonized Tariff Schedule") + if wave3TradeIsNegativeTitle(title) { + return nil + } + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if tableMD != "" { + blocks = append(blocks, "## Tariff Schedule\n\n"+tableMD) + } + if len(paras) > 0 { + blocks = append(blocks, strings.Join(paras, "\n\n")) + } + rec := map[string]any{ + "source": "usitc-hts", + "title": title, + "url": baseURL, + } + if len(tableRows) > 0 { + rec["rowCount"] = len(tableRows) + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: wave3TradeExtractMetaDesc(rawHTML), + Markdown: strings.Join(blocks, "\n\n"), + Links: []string{baseURL}, + Records: []map[string]any{rec}, + Total: wave3TradeIntPtr(1), + Returned: wave3TradeIntPtr(1), + Truncated: wave3TradeBoolPtr(false), + } +} + +// ── #272 CBP CROSS Rulings JSON & HTML ─────────────────────────────────────────────────────────── + +func wave3TradeFormatCBPCrossJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + switch pv := parsed.(type) { + case map[string]any: + if wave3TradeIsGenericJSONError(pv) { + return nil, false + } + // 1. Search response: {"rulings": [...]} or {"results": [...]} or {"items": [...]} + for _, k := range []string{"rulings", "results", "items"} { + if arr, ok := pv[k].([]any); ok && len(arr) > 0 { + totalCount := len(arr) + for _, tk := range []string{"total", "totalCount", "totalHits", "count"} { + if tf, okT := wave3TradeFloatVal(pv[tk]); okT && int(tf) > totalCount { + totalCount = int(tf) + break + } + } + return wave3TradeFormatCBPCrossList(arr, totalCount, origURL) + } + } + // 2. Single ruling detail: {"rulingNumber": "...", "subject": "...", ...} + rulingNo := wave3TradeFirstNonEmpty( + wave3TradePlain(pv["rulingNumber"], 48), + wave3TradePlain(pv["ruling_number"], 48), + wave3TradePlain(pv["number"], 48), + ) + subject := wave3TradeFirstNonEmpty( + wave3TradePlain(pv["subject"], 300), + wave3TradePlain(pv["title"], 300), + ) + if rulingNo == "" && subject == "" { + return nil, false + } + rDate := wave3TradeNormalizeDate(wave3TradeFirstNonEmpty( + wave3TradeStringVal(pv["rulingDate"]), + wave3TradeStringVal(pv["date"]), + wave3TradeStringVal(pv["issuedDate"]), + )) + cat := wave3TradeFirstNonEmpty( + wave3TradePlain(pv["category"], 120), + wave3TradePlain(pv["collection"], 120), + ) + var tariffs []string + if tArr, okT := pv["tariffs"].([]any); okT { + for _, tv := range tArr { + if ts := wave3TradePlain(tv, 32); ts != "" { + tariffs = append(tariffs, ts) + } + } + } + fullText := wave3TradeFirstNonEmpty( + wave3TradePlain(pv["fullText"], 4000), + wave3TradePlain(pv["text"], 4000), + wave3TradePlain(pv["summary"], 2000), + ) + if fullText == "" && subject == "" { + return nil, false + } + title := rulingNo + if subject != "" && rulingNo != "" { + title = rulingNo + " — " + subject + } else if subject != "" { + title = subject + } + var bullets []string + if rulingNo != "" { + bullets = append(bullets, "- **Ruling Number**: `"+rulingNo+"`") + } + if rDate != "" { + bullets = append(bullets, "- **Ruling Date**: "+rDate) + } + if cat != "" { + bullets = append(bullets, "- **Category**: "+cat) + } + if len(tariffs) > 0 { + bullets = append(bullets, "- **Tariff Numbers**: "+strings.Join(tariffs, ", ")) + } + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + if fullText != "" { + blocks = append(blocks, "## Ruling Text\n\n"+escapeDeclMarkdownBlock(fullText)) + } + rec := map[string]any{ + "source": "cbp-cross-rulings", + "title": title, + "url": origURL, + } + if rulingNo != "" { + rec["rulingNumber"] = rulingNo + } + if rDate != "" { + rec["rulingDate"] = rDate + } + if len(tariffs) > 0 { + rec["tariffs"] = tariffs + } + return &DeclarativeFormattedDoc{ + Title: title, + Markdown: strings.Join(blocks, "\n\n"), + Links: []string{origURL}, + Records: []map[string]any{rec}, + Total: wave3TradeIntPtr(1), + Returned: wave3TradeIntPtr(1), + Truncated: wave3TradeBoolPtr(false), + }, true + case []any: + return wave3TradeFormatCBPCrossList(pv, len(pv), origURL) + default: + return nil, false + } +} + +func wave3TradeFormatCBPCrossList(arr []any, totalCount int, origURL string) (*DeclarativeFormattedDoc, bool) { + if len(arr) == 0 { + return nil, false + } + var recs []map[string]any + var rows [][]string + var links []string + seen := make(map[string]bool) + for _, it := range arr { + if len(recs) >= wave3TradeMaxRecords { + break + } + m, ok := it.(map[string]any) + if !ok { + continue + } + rNum := wave3TradeFirstNonEmpty( + wave3TradePlain(m["rulingNumber"], 48), + wave3TradePlain(m["ruling_number"], 48), + wave3TradePlain(m["number"], 48), + ) + subj := wave3TradeFirstNonEmpty( + wave3TradePlain(m["subject"], 240), + wave3TradePlain(m["title"], 240), + ) + if rNum == "" && subj == "" { + continue + } + rDate := wave3TradeNormalizeDate(wave3TradeFirstNonEmpty( + wave3TradeStringVal(m["rulingDate"]), + wave3TradeStringVal(m["date"]), + )) + var tariffs []string + if tArr, okT := m["tariffs"].([]any); okT { + for _, tv := range tArr { + if ts := wave3TradePlain(tv, 32); ts != "" { + tariffs = append(tariffs, ts) + } + if len(tariffs) >= 4 { + break + } + } + } + rURL := "" + if rNum != "" { + rURL = "https://rulings.cbp.gov/ruling/" + url.PathEscape(rNum) + if !seen[rURL] { + seen[rURL] = true + links = append(links, rURL) + } + } + rec := map[string]any{ + "source": "cbp-cross-rulings", + } + if rNum != "" { + rec["rulingNumber"] = rNum + } + if subj != "" { + rec["subject"] = subj + } + if rDate != "" { + rec["rulingDate"] = rDate + } + if len(tariffs) > 0 { + rec["tariffs"] = tariffs + } + if rURL != "" { + rec["url"] = rURL + } + recs = append(recs, rec) + rows = append(rows, []string{ + wave3TradeFirstNonEmpty(rNum, "-"), + wave3TradeFirstNonEmpty(rDate, "-"), + wave3TradeFirstNonEmpty(strings.Join(tariffs, ", "), "-"), + wave3TradeFirstNonEmpty(subj, "-"), + }) + } + if len(recs) == 0 { + return nil, false + } + title := "CBP CROSS Customs Rulings" + if u, err := url.Parse(origURL); err == nil { + if term := SanitizeSchemaPlainField(u.Query().Get("term"), 80); term != "" { + title = fmt.Sprintf("CBP CROSS Rulings: %s", term) + } + } + blocks := []string{ + "# " + escapeDeclMarkdownBrackets(title), + fmt.Sprintf("- **Returned**: %d of %d rulings", len(recs), totalCount), + "## Rulings\n\n" + formatDeclarativeGFMTable([]string{"Ruling", "Date", "Tariff", "Subject"}, rows), + } + truncated := totalCount > len(recs) + doc := &DeclarativeFormattedDoc{ + Title: title, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: recs, + Total: wave3TradeIntPtr(totalCount), + Returned: wave3TradeIntPtr(len(recs)), + Truncated: wave3TradeBoolPtr(truncated), + } + if truncated { + doc.NextCursor = strconv.Itoa(len(recs)) + } + return doc, true +} + +func wave3TradeExtractCBPCrossHTML(rawHTML, probeLower, baseURL, extractorID string) *DeclarativePostFetchResult { + doc := ParseHTMLDoc(rawHTML, wave3TradeMaxHTMLBytes) + tableMD, _ := wave3TradeExtractTableBlock(doc) + paras := wave3TradeExtractParagraphs(doc, 8) + if tableMD == "" && len(paras) == 0 { + return nil + } + title := wave3TradeExtractTitle(doc, rawHTML) + if title == "" || wave3TradeIsNegativeTitle(title) { + return nil + } + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if tableMD != "" { + blocks = append(blocks, tableMD) + } + if len(paras) > 0 { + blocks = append(blocks, strings.Join(paras, "\n\n")) + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: wave3TradeExtractMetaDesc(rawHTML), + Markdown: strings.Join(blocks, "\n\n"), + Links: []string{baseURL}, + Records: []map[string]any{{ + "source": "cbp-cross-rulings", + "title": title, + "url": baseURL, + }}, + Total: wave3TradeIntPtr(1), + Returned: wave3TradeIntPtr(1), + Truncated: wave3TradeBoolPtr(false), + } +} + +// ── #273 Census Foreign Trade (USA Trade Online) HTML ──────────────────────────────────────────── + +func wave3TradeExtractCensusForeignTradeHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + doc := ParseHTMLDoc(rawHTML, wave3TradeMaxHTMLBytes) + title := wave3TradeExtractTitle(doc, rawHTML) + if title == "" || wave3TradeIsNegativeTitle(title) { + return nil + } + desc := wave3TradeExtractMetaDesc(rawHTML) + tableMD, _ := wave3TradeExtractTableBlock(doc) + paras := wave3TradeExtractParagraphs(doc, 8) + if desc == "" && tableMD == "" && len(paras) == 0 { + return nil + } + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if desc != "" { + blocks = append(blocks, desc) + } + if tableMD != "" { + blocks = append(blocks, tableMD) + } + if len(paras) > 0 { + blocks = append(blocks, strings.Join(paras, "\n\n")) + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: strings.Join(blocks, "\n\n"), + Links: []string{baseURL}, + Records: []map[string]any{{ + "source": "census-foreign-trade", + "title": title, + "url": baseURL, + }}, + Total: wave3TradeIntPtr(1), + Returned: wave3TradeIntPtr(1), + Truncated: wave3TradeBoolPtr(false), + } +} + +// ── #274 USTR Section 301 HTML & RSS ───────────────────────────────────────────────────────────── + +func wave3TradeExtractUSTR301HTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + doc := ParseHTMLDoc(rawHTML, wave3TradeMaxHTMLBytes) + title := wave3TradeExtractTitle(doc, rawHTML) + if title == "" { + // USTR Drupal sometimes puts the page title in + if spanInner, ok := findElementInnerLinearDeclHTML(rawHTML, "span", func(attrStr string) bool { + idVal, okID := getAttrValueLinearDeclHTML(attrStr, "id") + return okID && strings.EqualFold(strings.TrimSpace(idVal), "pageTitle") + }, 0); ok { + title = SanitizeSchemaPlainField(wave3TradeCleanText(spanInner), 240) + } + } + if title == "" || wave3TradeIsNegativeTitle(title) { + return nil + } + desc := wave3TradeExtractMetaDesc(rawHTML) + tableMD, _ := wave3TradeExtractTableBlock(doc) + + bodyFrag := "" + if inner, ok := findElementInnerLinearDeclHTML(rawHTML, "div", func(attrStr string) bool { + cls, okC := getAttrValueLinearDeclHTML(attrStr, "class") + return okC && strings.Contains(strings.ToLower(cls), "field--name-body") + }, 0); ok { + bodyFrag = inner + } else if mainInner, okM := findElementInnerLinearDeclHTML(rawHTML, "main", nil, 0); okM { + bodyFrag = mainInner + } + bodyMD := wave3TradeFragToMD(bodyFrag, baseURL) + paras := wave3TradeExtractParagraphs(doc, 10) + if desc == "" && tableMD == "" && bodyMD == "" && len(paras) == 0 { + return nil + } + + var links []string + seenLinks := make(map[string]bool) + wave3TradeAddLink(&links, seenLinks, baseURL, baseURL) + for _, lk := range wave3TradeExtractLinksFromHTML(rawHTML, baseURL, 20) { + if strings.Contains(strings.ToLower(lk.URL), "section-301") || + strings.Contains(strings.ToLower(lk.URL), "tariff") || + strings.Contains(strings.ToLower(lk.URL), ".pdf") { + wave3TradeAddLink(&links, seenLinks, lk.URL, baseURL) + } + } + + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if desc != "" { + blocks = append(blocks, desc) + } + if tableMD != "" { + blocks = append(blocks, "## Section 301 Actions\n\n"+tableMD) + } + if bodyMD != "" { + blocks = append(blocks, bodyMD) + } else if len(paras) > 0 { + blocks = append(blocks, strings.Join(paras, "\n\n")) + } + + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: []map[string]any{{ + "source": "ustr-301", + "title": title, + "url": baseURL, + }}, + Total: wave3TradeIntPtr(1), + Returned: wave3TradeIntPtr(1), + Truncated: wave3TradeBoolPtr(false), + } +} + +func wave3TradeFormatUSTR301RSS(rawBody, origURL string) (*DeclarativeFormattedDoc, bool) { + lower := asciiLowerExtractString(rawBody) + if strings.Contains(lower, " 0 { + head := rawBody[:idx] + if ct := SanitizeSchemaPlainField(wave3TradeCleanText(extractXMLTagTextGo(head, "title")), 200); ct != "" { + channelTitle = ct + } + } + + var recs []map[string]any + var rows [][]string + var links []string + seen := make(map[string]bool) + for _, it := range items { + if len(recs) >= wave3TradeMaxRecords { + break + } + iTitle := SanitizeSchemaPlainField(wave3TradeCleanText(extractXMLTagTextGo(it, "title")), 240) + iLink := SanitizeSchemaHTTPSURL(wave3TradeCleanText(extractXMLTagTextGo(it, "link")), origURL) + iDate := wave3TradeNormalizeDate(wave3TradeCleanText(wave3TradeFirstNonEmpty( + extractXMLTagTextGo(it, "pubDate"), + extractXMLTagTextGo(it, "updated"), + extractXMLTagTextGo(it, "dc:date"), + ))) + iDesc := SanitizeSchemaPlainField(wave3TradeCleanText(wave3TradeFirstNonEmpty( + extractXMLTagTextGo(it, "description"), + extractXMLTagTextGo(it, "summary"), + )), 240) + if iTitle == "" { + continue + } + rec := map[string]any{ + "source": "ustr-301", + "title": iTitle, + } + if iLink != "" { + rec["url"] = iLink + if !seen[iLink] { + seen[iLink] = true + links = append(links, iLink) + } + } + if iDate != "" { + rec["publishedAt"] = iDate + } + if iDesc != "" { + rec["description"] = iDesc + } + recs = append(recs, rec) + rows = append(rows, []string{ + wave3TradeFirstNonEmpty(iDate, "-"), + iTitle, + wave3TradeFirstNonEmpty(iDesc, "-"), + }) + } + if len(recs) == 0 { + return nil, false + } + + title := fmt.Sprintf("%s (%d items)", channelTitle, len(items)) + blocks := []string{ + "# " + escapeDeclMarkdownBrackets(title), + "## Feed Items\n\n" + formatDeclarativeGFMTable([]string{"Date", "Title", "Summary"}, rows), + } + truncated := len(items) > len(recs) + doc := &DeclarativeFormattedDoc{ + Title: title, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: recs, + Total: wave3TradeIntPtr(len(items)), + Returned: wave3TradeIntPtr(len(recs)), + Truncated: wave3TradeBoolPtr(truncated), + } + if truncated { + doc.NextCursor = strconv.Itoa(len(recs)) + } + return doc, true +} + +// ── #275 Trade.gov Consolidated Screening List JSON & HTML ─────────────────────────────────────── + +func wave3TradeFormatTradeGovCSLJSON(parsed any, origURL string) (*DeclarativeFormattedDoc, bool) { + obj, ok := parsed.(map[string]any) + if !ok || wave3TradeIsGenericJSONError(obj) { + return nil, false + } + results, okRes := obj["results"].([]any) + if !okRes || len(results) == 0 { + return nil, false + } + totalCount := len(results) + if tf, okT := wave3TradeFloatVal(obj["total"]); okT && int(tf) > totalCount { + totalCount = int(tf) + } + + var recs []map[string]any + var rows [][]string + var links []string + seen := make(map[string]bool) + + for _, it := range results { + if len(recs) >= wave3TradeMaxRecords { + break + } + m, okM := it.(map[string]any) + if !okM { + continue + } + name := wave3TradePlain(m["name"], 200) + src := wave3TradePlain(m["source"], 160) + entType := wave3TradePlain(m["type"], 64) + entNum := wave3TradeFirstNonEmpty( + wave3TradePlain(m["entity_number"], 64), + wave3TradePlain(m["id"], 64), + ) + if name == "" && entNum == "" { + continue + } + + var programs []string + if pArr, okP := m["programs"].([]any); okP { + for _, pv := range pArr { + if ps := wave3TradePlain(pv, 48); ps != "" { + programs = append(programs, ps) + } + if len(programs) >= 4 { + break + } + } + } + + var altNames []string + if aArr, okA := m["alt_names"].([]any); okA { + for _, av := range aArr { + if as := wave3TradePlain(av, 120); as != "" { + altNames = append(altNames, as) + } + if len(altNames) >= 4 { + break + } + } + } + + var countries []string + seenCountry := make(map[string]bool) + if addrArr, okAddr := m["addresses"].([]any); okAddr { + for _, adv := range addrArr { + am, okAM := adv.(map[string]any) + if !okAM { + continue + } + if c := wave3TradePlain(am["country"], 16); c != "" && !seenCountry[c] { + seenCountry[c] = true + countries = append(countries, c) + } + } + } + + srcURL := SanitizeSchemaHTTPSURL(m["source_information_url"], origURL) + if srcURL == "" { + srcURL = SanitizeSchemaHTTPSURL(m["source_list_url"], origURL) + } + if srcURL != "" && !seen[srcURL] { + seen[srcURL] = true + links = append(links, srcURL) + } + + rec := map[string]any{ + "source": "trade-gov-csl", + "name": name, + } + if src != "" { + rec["listSource"] = src + } + if entType != "" { + rec["type"] = entType + } + if entNum != "" { + rec["id"] = entNum + } + if len(programs) > 0 { + rec["programs"] = programs + } + if len(altNames) > 0 { + rec["altNames"] = altNames + } + if len(countries) > 0 { + rec["countries"] = countries + } + if srcURL != "" { + rec["url"] = srcURL + } + recs = append(recs, rec) + rows = append(rows, []string{ + wave3TradeFirstNonEmpty(name, "-"), + wave3TradeFirstNonEmpty(src, "-"), + wave3TradeFirstNonEmpty(entType, "-"), + wave3TradeFirstNonEmpty(strings.Join(programs, ", "), "-"), + wave3TradeFirstNonEmpty(strings.Join(countries, ", "), "-"), + wave3TradeFirstNonEmpty(entNum, "-"), + }) + } + if len(recs) == 0 { + return nil, false + } + + title := "Trade.gov Consolidated Screening List" + if u, err := url.Parse(origURL); err == nil { + if q := SanitizeSchemaPlainField(u.Query().Get("q"), 80); q != "" { + title = fmt.Sprintf("Trade.gov CSL Search: %s", q) + } else if nm := SanitizeSchemaPlainField(u.Query().Get("name"), 80); nm != "" { + title = fmt.Sprintf("Trade.gov CSL Search: %s", nm) + } + } + + blocks := []string{ + "# " + escapeDeclMarkdownBrackets(title), + fmt.Sprintf("- **Returned**: %d of %d matching entities", len(recs), totalCount), + "## Screening Matches\n\n" + formatDeclarativeGFMTable( + []string{"Name", "List Source", "Type", "Programs", "Country", "ID"}, + rows, + ), + } + truncated := totalCount > len(recs) + doc := &DeclarativeFormattedDoc{ + Title: title, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: recs, + Total: wave3TradeIntPtr(totalCount), + Returned: wave3TradeIntPtr(len(recs)), + Truncated: wave3TradeBoolPtr(truncated), + } + if truncated { + doc.NextCursor = strconv.Itoa(len(recs)) + } + return doc, true +} + +func wave3TradeExtractTradeGovCSLHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + doc := ParseHTMLDoc(rawHTML, wave3TradeMaxHTMLBytes) + title := wave3TradeExtractTitle(doc, rawHTML) + if title == "" || wave3TradeIsNegativeTitle(title) { + return nil + } + desc := wave3TradeExtractMetaDesc(rawHTML) + paras := wave3TradeExtractParagraphs(doc, 10) + tableMD, _ := wave3TradeExtractTableBlock(doc) + + var links []string + seenLinks := make(map[string]bool) + wave3TradeAddLink(&links, seenLinks, baseURL, baseURL) + var downloadBullets []string + for _, lk := range wave3TradeExtractLinksFromHTML(rawHTML, baseURL, 24) { + lu := strings.ToLower(lk.URL) + if strings.Contains(lu, "consolidated") || strings.Contains(lu, "csl") || + strings.HasSuffix(lu, ".csv") || strings.HasSuffix(lu, ".tsv") || strings.HasSuffix(lu, ".json") { + wave3TradeAddLink(&links, seenLinks, lk.URL, baseURL) + if len(downloadBullets) < 8 { + downloadBullets = append(downloadBullets, fmt.Sprintf("- [%s](%s)", escapeDeclMarkdownBrackets(lk.Text), lk.URL)) + } + } + } + + if desc == "" && tableMD == "" && len(paras) == 0 && len(downloadBullets) == 0 { + return nil + } + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if desc != "" { + blocks = append(blocks, desc) + } + if len(downloadBullets) > 0 { + blocks = append(blocks, "## Screening Resources\n\n"+strings.Join(downloadBullets, "\n")) + } + if tableMD != "" { + blocks = append(blocks, tableMD) + } + if len(paras) > 0 { + blocks = append(blocks, strings.Join(paras, "\n\n")) + } + + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: []map[string]any{{ + "source": "trade-gov-csl", + "title": title, + "url": baseURL, + }}, + Total: wave3TradeIntPtr(1), + Returned: wave3TradeIntPtr(1), + Truncated: wave3TradeBoolPtr(false), + } +} + +// ── #276 OFAC SDN Bounded Streaming XML & HTML ─────────────────────────────────────────────────── + +func indexOFACSDNOpenGo(s string) int { + const needle = " limit { + return -1 + } + c2 := s[cand+2] + if c2 == 's' || c2 == 'S' { + if asciiLowerExtractByte(s[cand+3]) == 'd' && + asciiLowerExtractByte(s[cand+4]) == 'n' && + asciiLowerExtractByte(s[cand+5]) == 'e' && + asciiLowerExtractByte(s[cand+6]) == 'n' && + asciiLowerExtractByte(s[cand+7]) == 't' && + asciiLowerExtractByte(s[cand+8]) == 'r' && + asciiLowerExtractByte(s[cand+9]) == 'y' && + s[cand+10] == '>' { + return cand + } + } + pos = cand + 2 + } + return -1 +} + +func wave3TradeFormatOFACSDNXML(rawBody, origURL string) (*DeclarativeFormattedDoc, bool) { + probe := rawBody + if len(probe) > 8192 { + probe = probe[:8192] + } + probeLower := asciiLowerExtractString(probe) + if strings.Contains(probeLower, " 0 { + declaredTotal = rc + } + } + } + + // Bounded linear scan of complete ... elements. + // Stops cleanly before any partial/truncated trailing at the Range boundary. + var recs []map[string]any + var rows [][]string + truncatedTail := false + for len(recs) < wave3TradeMaxOFACRecords && pos < len(rawBody) { + relOpen := indexOFACSDNOpenGo(rawBody[pos:]) + if relOpen < 0 { + break + } + openStart := pos + relOpen + afterName := openStart + len("= len(rawBody) { + truncatedTail = true + break + } + ch := rawBody[afterName] + if ch != '>' && ch != ' ' && ch != '\t' && ch != '\r' && ch != '\n' { + pos = afterName + continue + } + gtRel := strings.IndexByte(rawBody[afterName:], '>') + if gtRel < 0 { + truncatedTail = true + break + } + bodyStart := afterName + gtRel + 1 + closeRel := indexOFACSDNCloseGo(rawBody[bodyStart:]) + if closeRel < 0 { + // Truncated trailing entry at 2 MiB byte boundary — stop cleanly. + truncatedTail = true + break + } + entryXML := rawBody[bodyStart : bodyStart+closeRel] + pos = bodyStart + closeRel + len("") + + uid := SanitizeSchemaPlainField(wave3TradeCleanText(extractXMLTagTextGo(entryXML, "uid")), 32) + firstName := SanitizeSchemaPlainField(wave3TradeCleanText(extractXMLTagTextGo(entryXML, "firstName")), 120) + lastName := SanitizeSchemaPlainField(wave3TradeCleanText(extractXMLTagTextGo(entryXML, "lastName")), 160) + fullName := strings.TrimSpace(strings.TrimSpace(firstName + " " + lastName)) + sdnType := SanitizeSchemaPlainField(wave3TradeCleanText(extractXMLTagTextGo(entryXML, "sdnType")), 48) + if fullName == "" && uid == "" { + continue + } + + var programs []string + seenProg := make(map[string]bool) + if progList, _, okP := findLinearElementInnerGo(entryXML, "programlist", 0); okP { + for _, pInner := range findAllLinearElementInnersGo(progList, "program", 8) { + p := SanitizeSchemaPlainField(wave3TradeCleanText(pInner), 48) + if p != "" && !seenProg[p] { + seenProg[p] = true + programs = append(programs, p) + } + } + } + + var akas []string + if akaList, _, okA := findLinearElementInnerGo(entryXML, "akalist", 0); okA { + for _, aInner := range findAllLinearElementInnersGo(akaList, "aka", 4) { + af := SanitizeSchemaPlainField(wave3TradeCleanText(extractXMLTagTextGo(aInner, "firstName")), 80) + al := SanitizeSchemaPlainField(wave3TradeCleanText(extractXMLTagTextGo(aInner, "lastName")), 100) + aName := strings.TrimSpace(strings.TrimSpace(af + " " + al)) + if aName != "" { + akas = append(akas, aName) + } + } + } + + var countries []string + seenCountry := make(map[string]bool) + if addrList, _, okAddr := findLinearElementInnerGo(entryXML, "addresslist", 0); okAddr { + for _, addrInner := range findAllLinearElementInnersGo(addrList, "address", 4) { + country := SanitizeSchemaPlainField(wave3TradeCleanText(extractXMLTagTextGo(addrInner, "country")), 64) + if country != "" && !seenCountry[country] { + seenCountry[country] = true + countries = append(countries, country) + } + } + } + + rec := map[string]any{ + "source": "ofac-sdn", + "uid": uid, + "name": fullName, + } + if sdnType != "" { + rec["sdnType"] = sdnType + } + if len(programs) > 0 { + rec["programs"] = programs + } + if len(akas) > 0 { + rec["aliases"] = akas + } + if len(countries) > 0 { + rec["countries"] = countries + } + recs = append(recs, rec) + rows = append(rows, []string{ + wave3TradeFirstNonEmpty(uid, "-"), + wave3TradeFirstNonEmpty(fullName, "-"), + wave3TradeFirstNonEmpty(sdnType, "-"), + wave3TradeFirstNonEmpty(strings.Join(programs, ", "), "-"), + wave3TradeFirstNonEmpty(strings.Join(countries, ", "), "-"), + }) + } + + if len(recs) == 0 { + return nil, false + } + + totalCount := len(recs) + if declaredTotal > totalCount { + totalCount = declaredTotal + } else if pos < len(rawBody) && indexOFACSDNOpenGo(rawBody[pos:]) >= 0 { + totalCount = len(recs) + 1 + } + + title := "OFAC Specially Designated Nationals (SDN) List" + var bullets []string + if pubDate != "" { + bullets = append(bullets, "- **Published Date**: "+pubDate) + } + if declaredTotal > 0 { + bullets = append(bullets, fmt.Sprintf("- **Declared Record Count**: %d", declaredTotal)) + } + bullets = append(bullets, fmt.Sprintf("- **Returned Sample**: %d complete entries", len(recs))) + if truncatedTail { + bullets = append(bullets, "- **Bounded Scan**: Stopped cleanly before truncated trailing ``") + } + + blocks := []string{ + "# " + title, + strings.Join(bullets, "\n"), + "## SDN Entries\n\n" + formatDeclarativeGFMTable( + []string{"UID", "Name", "Type", "Programs", "Countries"}, + rows, + ), + } + truncated := totalCount > len(recs) || truncatedTail + doc := &DeclarativeFormattedDoc{ + Title: title, + Markdown: strings.Join(blocks, "\n\n"), + Links: []string{origURL}, + Records: recs, + Total: wave3TradeIntPtr(totalCount), + Returned: wave3TradeIntPtr(len(recs)), + Truncated: wave3TradeBoolPtr(truncated), + } + if truncated { + doc.NextCursor = strconv.Itoa(len(recs)) + } + return doc, true +} + +func wave3TradeExtractOFACHTML(rawHTML, baseURL, extractorID string) *DeclarativePostFetchResult { + doc := ParseHTMLDoc(rawHTML, wave3TradeMaxHTMLBytes) + title := wave3TradeExtractTitle(doc, rawHTML) + if title == "" || wave3TradeIsNegativeTitle(title) { + return nil + } + desc := wave3TradeExtractMetaDesc(rawHTML) + tableMD, _ := wave3TradeExtractTableBlock(doc) + paras := wave3TradeExtractParagraphs(doc, 10) + + var links []string + seen := make(map[string]bool) + wave3TradeAddLink(&links, seen, baseURL, baseURL) + var actionBullets []string + for _, lk := range wave3TradeExtractLinksFromHTML(rawHTML, baseURL, 25) { + lu := strings.ToLower(lk.URL) + if strings.Contains(lu, "/recent-actions/") || strings.Contains(lu, "/sanctions-programs") { + wave3TradeAddLink(&links, seen, lk.URL, baseURL) + if len(actionBullets) < 12 { + actionBullets = append(actionBullets, fmt.Sprintf("- [%s](%s)", escapeDeclMarkdownBrackets(lk.Text), lk.URL)) + } + } + } + + if desc == "" && tableMD == "" && len(paras) == 0 && len(actionBullets) == 0 { + return nil + } + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if desc != "" { + blocks = append(blocks, desc) + } + if len(actionBullets) > 0 { + blocks = append(blocks, "## Sanctions Actions & Programs\n\n"+strings.Join(actionBullets, "\n")) + } + if tableMD != "" { + blocks = append(blocks, tableMD) + } + if len(paras) > 0 { + blocks = append(blocks, strings.Join(paras, "\n\n")) + } + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: []map[string]any{{ + "source": "ofac-sdn", + "title": title, + "url": baseURL, + }}, + Total: wave3TradeIntPtr(1), + Returned: wave3TradeIntPtr(1), + Truncated: wave3TradeBoolPtr(false), + } +} + +// ── #277 BIS Entity List / EAR HTML ────────────────────────────────────────────────────────────── + +func wave3TradeExtractBISEntityListHTML(rawHTML, probeLower, baseURL, extractorID string) *DeclarativePostFetchResult { + doc := ParseHTMLDoc(rawHTML, wave3TradeMaxHTMLBytes) + title := wave3TradeExtractTitle(doc, rawHTML) + if title == "" || wave3TradeIsNegativeTitle(title) { + return nil + } + desc := wave3TradeExtractMetaDesc(rawHTML) + tableMD, _ := wave3TradeExtractTableBlock(doc) + + mainFrag := "" + if inner, ok := findElementInnerLinearDeclHTML(rawHTML, "main", nil, 0); ok { + mainFrag = inner + } else if inner, ok := findElementInnerLinearDeclHTML(rawHTML, "article", nil, 0); ok { + mainFrag = inner + } + mainMD := wave3TradeFragToMD(mainFrag, baseURL) + paras := wave3TradeExtractParagraphs(doc, 10) + + // Next.js __NEXT_DATA__ supplemental metadata if DOM paragraphs are light + nextSummary := "" + if m := wave3TradeRxNextData.FindStringSubmatch(rawHTML); len(m) >= 2 { + if parsed, ok := decodeJSONWithNumbers([]byte(strings.TrimSpace(m[1]))); ok { + if root := mapFieldMap(parsed, "props", "pageProps"); root != nil { + for _, k := range []string{"summary", "description", "body", "subtitle"} { + if v := wave3TradePlain(root[k], 600); v != "" { + nextSummary = v + break + } + } + } + } + } + + if desc == "" && tableMD == "" && mainMD == "" && len(paras) == 0 && nextSummary == "" { + return nil + } + + var links []string + seen := make(map[string]bool) + wave3TradeAddLink(&links, seen, baseURL, baseURL) + for _, lk := range wave3TradeExtractLinksFromHTML(rawHTML, baseURL, 24) { + lu := strings.ToLower(lk.URL) + if strings.Contains(lu, "/regulations/") || strings.Contains(lu, "744") || strings.Contains(lu, "csl-search") { + wave3TradeAddLink(&links, seen, lk.URL, baseURL) + } + } + + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if desc != "" { + blocks = append(blocks, desc) + } + if nextSummary != "" && nextSummary != desc { + blocks = append(blocks, nextSummary) + } + if tableMD != "" { + blocks = append(blocks, tableMD) + } + if mainMD != "" { + blocks = append(blocks, mainMD) + } else if len(paras) > 0 { + blocks = append(blocks, strings.Join(paras, "\n\n")) + } + + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: []map[string]any{{ + "source": "bis-entity-list", + "title": title, + "url": baseURL, + }}, + Total: wave3TradeIntPtr(1), + Returned: wave3TradeIntPtr(1), + Truncated: wave3TradeBoolPtr(false), + } +} + +func mapFieldMap(v any, keys ...string) map[string]any { + cur := v + for _, k := range keys { + m, ok := cur.(map[string]any) + if !ok { + return nil + } + cur = m[k] + } + m, _ := cur.(map[string]any) + return m +} + +// ── #278 FDA Import Alerts & USDA APHIS HTML ───────────────────────────────────────────────────── + +func wave3TradeExtractImportAlertsHTML(rawHTML, probeLower, baseURL, urlLower, extractorID string) *DeclarativePostFetchResult { + doc := ParseHTMLDoc(rawHTML, wave3TradeMaxHTMLBytes) + title := wave3TradeExtractTitle(doc, rawHTML) + if title == "" || wave3TradeIsNegativeTitle(title) { + return nil + } + desc := wave3TradeExtractMetaDesc(rawHTML) + tableMD, tableRows := wave3TradeExtractTableBlock(doc) + paras := wave3TradeExtractParagraphs(doc, 10) + + isFDA := strings.Contains(urlLower, "accessdata.fda.gov") || strings.Contains(probeLower, "cms_ia") || strings.Contains(probeLower, "import alert #") + var bullets []string + var pubDate string + var alertNum, alertType, alertName string + + if isFDA { + // Parse FDA structured labels ("Import Alert #", "Published Date:", "Type:", "Import Alert Name:", "Reason for Alert:") + fullText := wave3TradeCleanText(doc.Text("body")) + if fullText == "" { + fullText = wave3TradeCleanText(rawHTML) + } + locs := wave3TradeRxFDAField.FindAllStringSubmatchIndex(fullText, 10) + for i, loc := range locs { + if len(loc) < 4 { + continue + } + label := strings.TrimSpace(fullText[loc[2]:loc[3]]) + valStart := loc[1] + valEnd := len(fullText) + if i+1 < len(locs) { + valEnd = locs[i+1][0] + } + if valEnd-valStart > 500 { + valEnd = valStart + 500 + } + val := SanitizeSchemaPlainField(fullText[valStart:valEnd], 400) + if val == "" { + continue + } + lowLabel := strings.ToLower(label) + switch { + case strings.Contains(lowLabel, "import alert #"): + alertNum = val + bullets = append(bullets, "- **Import Alert #**: `"+val+"`") + case strings.Contains(lowLabel, "published date"): + pubDate = wave3TradeNormalizeDate(val) + bullets = append(bullets, "- **Published Date**: "+pubDate) + case lowLabel == "type": + alertType = val + bullets = append(bullets, "- **Type**: "+val) + case strings.Contains(lowLabel, "import alert name"): + alertName = val + bullets = append(bullets, "- **Import Alert Name**: "+val) + case strings.Contains(lowLabel, "reason for alert"): + bullets = append(bullets, "- **Reason for Alert**: "+val) + } + } + } else { + // APHIS Article JSON-LD metadata + for _, ld := range extractJSONLDObjectsDeclHTML(rawHTML, 12) { + if pubDate == "" { + pubDate = wave3TradeNormalizeDate(wave3TradePlain(ld["datePublished"], 48)) + } + if desc == "" { + desc = wave3TradePlain(ld["description"], 600) + } + } + if pubDate != "" { + bullets = append(bullets, "- **Published Date**: "+pubDate) + } + } + + var links []string + seen := make(map[string]bool) + wave3TradeAddLink(&links, seen, baseURL, baseURL) + var itemBullets []string + for _, lk := range wave3TradeExtractLinksFromHTML(rawHTML, baseURL, 25) { + lu := strings.ToLower(lk.URL) + if strings.Contains(lu, "importalert_") || strings.Contains(lu, "import") || strings.Contains(lu, "manual") { + wave3TradeAddLink(&links, seen, lk.URL, baseURL) + if len(itemBullets) < 12 && tableMD == "" { + itemBullets = append(itemBullets, fmt.Sprintf("- [%s](%s)", escapeDeclMarkdownBrackets(lk.Text), lk.URL)) + } + } + } + + if desc == "" && tableMD == "" && len(paras) == 0 && len(bullets) == 0 && len(itemBullets) == 0 { + return nil + } + + blocks := []string{"# " + escapeDeclMarkdownBrackets(title)} + if len(bullets) > 0 { + blocks = append(blocks, strings.Join(bullets, "\n")) + } + if desc != "" { + blocks = append(blocks, desc) + } + if tableMD != "" { + blocks = append(blocks, tableMD) + } else if len(itemBullets) > 0 { + blocks = append(blocks, "## Import Resources\n\n"+strings.Join(itemBullets, "\n")) + } + if len(paras) > 0 { + blocks = append(blocks, strings.Join(paras, "\n\n")) + } + + rec := map[string]any{ + "source": "import-alerts-aphis-fda", + "title": title, + "url": baseURL, + } + if alertNum != "" { + rec["alertNumber"] = alertNum + } + if alertType != "" { + rec["alertType"] = alertType + } + if alertName != "" { + rec["alertName"] = alertName + } + if pubDate != "" { + rec["publishedDate"] = pubDate + } + if len(tableRows) > 0 { + rec["rowCount"] = len(tableRows) + } + + return &DeclarativePostFetchResult{ + ExtractorID: extractorID, + Title: title, + Description: desc, + PublishedTime: pubDate, + Markdown: strings.Join(blocks, "\n\n"), + Links: links, + Records: []map[string]any{rec}, + Total: wave3TradeIntPtr(1), + Returned: wave3TradeIntPtr(1), + Truncated: wave3TradeBoolPtr(false), + } +} diff --git a/internal/extract/wave3_trade_test.go b/internal/extract/wave3_trade_test.go new file mode 100644 index 0000000..e3bdefd --- /dev/null +++ b/internal/extract/wave3_trade_test.go @@ -0,0 +1,403 @@ +package extract + +import ( + "encoding/json" + "net/url" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func wave3TradeDecodeDoc(t *testing.T, raw string) *DeclarativeFormattedDoc { + t.Helper() + var doc DeclarativeFormattedDoc + if err := json.Unmarshal([]byte(raw), &doc); err != nil { + t.Fatalf("unmarshal DeclarativeFormattedDoc: %v\nraw=%s", err, raw) + } + return &doc +} + +func wave3TradeResolveManifest(t *testing.T, m *DeclarativeAdapterManifest, rawURL string) (*DeclarativeTwinMatch, bool) { + t.Helper() + u, err := url.Parse(rawURL) + if err != nil { + t.Fatalf("url.Parse(%q): %v", rawURL, err) + } + host := strings.TrimSuffix(strings.ToLower(u.Hostname()), ".") + rawParts := splitNonEmptyEscapedSegments(u.EscapedPath()) + return resolveManifestTwinOnParsedURL(m, u, host, rawParts, DeclarativeResolveOptions{}) +} + +func TestWave3TradeManifestsAndDisjointDomains(t *testing.T) { + catJIDs := []string{ + "usitc-hts", + "cbp-cross-rulings", + "census-foreign-trade", + "ustr-301", + "trade-gov-csl", + "ofac-sdn", + "bis-entity-list", + "import-alerts-aphis-fda", + } + + byID := make(map[string]*DeclarativeAdapterManifest) + claimedDomains := make(map[string]string) + for _, id := range catJIDs { + raw, err := os.ReadFile(filepath.Join("manifests", id+".yaml")) + if err != nil { + t.Fatalf("read %s.yaml: %v", id, err) + } + m, err := ParseDeclarativeYAMLManifest(raw) + if err != nil { + t.Fatalf("ParseDeclarativeYAMLManifest(%s.yaml): %v", id, err) + } + if m.ID != id { + t.Fatalf("%s.yaml has mismatched id=%q", id, m.ID) + } + if m.Category != "public-records" { + t.Fatalf("%s.yaml must use category public-records, got %q", id, m.Category) + } + if m.AuthMode == "detect-only" || m.DetectOnly != nil { + t.Fatalf("%s.yaml uses retired detect-only", id) + } + for _, d := range m.Domains { + ld := strings.ToLower(strings.TrimSpace(d)) + if prev, exists := claimedDomains[ld]; exists { + t.Fatalf("duplicate domain %q across %s and %s", ld, prev, id) + } + claimedDomains[ld] = id + } + for _, hr := range m.HTMLRoutes { + for _, b := range hr.Bullets { + if strings.ContainsAny(b.Label, "{}") { + t.Fatalf("%s.yaml bullet label contains {}: %q", id, b.Label) + } + } + } + byID[id] = m + } + + // Verify strict disjointness from existing baseline manifests + for _, existingID := range []string{"census", "federal-register", "ecfr", "openfda", "usda-nass-fdc", "treasury-fiscal-data"} { + raw, err := os.ReadFile(filepath.Join("manifests", existingID+".yaml")) + if err != nil { + t.Fatalf("read %s.yaml: %v", existingID, err) + } + em, err := ParseDeclarativeYAMLManifest(raw) + if err != nil { + t.Fatalf("ParseDeclarativeYAMLManifest(%s.yaml): %v", existingID, err) + } + for _, d := range em.Domains { + ld := strings.ToLower(strings.TrimSpace(d)) + if catOwner, overlap := claimedDomains[ld]; overlap { + t.Fatalf("Cat J %s overlaps %s domain %q", catOwner, existingID, ld) + } + } + } + + // #271 usitc-hts routes + hts := byID["usitc-hts"] + if tm, ok := wave3TradeResolveManifest(t, hts, "https://hts.usitc.gov/reststop/search?keyword=bicycle"); !ok || tm.route.Extract.JSONMode != "usitc_hts_json" { + t.Fatalf("usitc-hts search route failed: ok=%v tm=%+v", ok, tm) + } + if tm, ok := wave3TradeResolveManifest(t, hts, "https://hts.usitc.gov/reststop/exportList?from=8712.00&to=8712.00&format=JSON&styles=false"); !ok || tm.route.Extract.JSONMode != "usitc_hts_json" { + t.Fatalf("usitc-hts exportList route failed: ok=%v tm=%+v", ok, tm) + } + + // #272 cbp-cross-rulings routes + cbp := byID["cbp-cross-rulings"] + if tm, ok := wave3TradeResolveManifest(t, cbp, "https://rulings.cbp.gov/api/ruling/N328640"); !ok || tm.EffectiveMaxBytes() != 2097152 || tm.route.Extract.JSONMode != "cbp_cross_json" { + t.Fatalf("cbp-cross-rulings API route failed: ok=%v tm=%+v", ok, tm) + } + if tm, ok := wave3TradeResolveManifest(t, cbp, "https://rulings.cbp.gov/search?term=bicycle"); ok || tm != nil { + t.Fatalf("cbp-cross-rulings HTML search URL should fall through to htmlRoutes: %+v", tm) + } + + // #274 ustr-301 RSS route + ustr := byID["ustr-301"] + if tm, ok := wave3TradeResolveManifest(t, ustr, "https://ustr.gov/rss.xml"); !ok || tm.route.Extract.TextMode != "ustr_301_rss_xml" { + t.Fatalf("ustr-301 rss route failed: ok=%v tm=%+v", ok, tm) + } + + // #275 trade-gov-csl keyed API + HTML fallback + csl := byID["trade-gov-csl"] + if tm, ok := wave3TradeResolveManifest(t, csl, "https://data.trade.gov/consolidated_screening_list/v1/search?q=example"); !ok || tm.route.Twin.AuthMode != "key" || tm.route.Extract.JSONMode != "trade_gov_csl_json" { + t.Fatalf("trade-gov-csl API route failed: ok=%v tm=%+v", ok, tm) + } + if tm, ok := wave3TradeResolveManifest(t, csl, "https://www.trade.gov/consolidated-screening-list"); ok || tm != nil { + t.Fatalf("trade-gov-csl www.trade.gov URL must fall through to htmlRoutes: %+v", tm) + } + + // #276 ofac-sdn case-insensitive SDN.XML + Range header + 2 MiB maxBytes + ofac := byID["ofac-sdn"] + for _, sdnURL := range []string{ + "https://sanctionslistservice.ofac.treas.gov/api/PublicationPreview/exports/SDN.XML", + "https://sanctionslistservice.ofac.treas.gov/api/publicationpreview/exports/sdn.xml", + } { + tm, ok := wave3TradeResolveManifest(t, ofac, sdnURL) + if !ok || tm.EffectiveMaxBytes() != 2097152 || tm.route.Extract.TextMode != "ofac_sdn_xml" { + t.Fatalf("ofac-sdn route failed for %s: ok=%v tm=%+v", sdnURL, ok, tm) + } + if tm.route.Twin.Headers["Range"] != "bytes=0-2097151" { + t.Fatalf("ofac-sdn missing Range header: %+v", tm.route.Twin.Headers) + } + } +} + +func TestWave3TradeJSONAndXMLFormatters(t *testing.T) { + // 1. #271 usitc_hts_json + htsPayload := `[{"htsno":"8712.00.15.00","indent":"1","description":"Bicycles having both wheels not exceeding 63.5 cm in diameter","units":["No."],"general":"11%","special":"Free (A+,AU)","other":"30%","footnotes":[{"columns":["general"],"marker":"1","value":"See 9903.88.15."}],"additionalDuties":"See 9903.88.15"}]` + htsRaw, ok := FormatWave3TradeJSONMode("usitc_hts_json", []byte(htsPayload), nil, "https://hts.usitc.gov/reststop/search?keyword=bicycle") + if !ok { + t.Fatalf("usitc_hts_json failed") + } + htsDoc := wave3TradeDecodeDoc(t, htsRaw) + if len(htsDoc.Records) != 1 || !strings.Contains(htsDoc.Markdown, "8712.00.15.00") || !strings.Contains(htsDoc.Markdown, "9903.88.15") { + t.Fatalf("unexpected usitc_hts_json output: %+v", htsDoc) + } + if _, negOK := FormatWave3TradeJSONMode("usitc_hts_json", []byte(`[]`), nil, "https://hts.usitc.gov/reststop/search?keyword=none"); negOK { + t.Fatalf("usitc_hts_json must reject empty array") + } + + // 2. #272 cbp_cross_json (single ruling + search error rejection) + cbpPayload := `{"rulingNumber":"N328640","rulingDate":"2022-10-18","category":"Classification","tariffs":["8712.00.1500"],"subject":"Bicycle frame assemblies","fullText":"Classified under subheading 8712.00.1500."}` + cbpRaw, ok := FormatWave3TradeJSONMode("cbp_cross_json", []byte(cbpPayload), nil, "https://rulings.cbp.gov/api/ruling/N328640") + if !ok { + t.Fatalf("cbp_cross_json failed") + } + cbpDoc := wave3TradeDecodeDoc(t, cbpRaw) + if !strings.Contains(cbpDoc.Title, "N328640") || !strings.Contains(cbpDoc.Markdown, "8712.00.1500") { + t.Fatalf("unexpected cbp_cross_json output: %+v", cbpDoc) + } + if _, negOK := FormatWave3TradeJSONMode("cbp_cross_json", []byte(`{"message":"Security parameters are missing from this request context."}`), nil, "https://rulings.cbp.gov/api/search?term=bicycle"); negOK { + t.Fatalf("cbp_cross_json must reject 403 security parameters error") + } + + // 3. #275 trade_gov_csl_json + cslPayload := `{"total":2,"offset":0,"results":[{"id":"100","entity_number":"100","name":"EXAMPLE TECH LTD","type":"Entity","source":"Entity List (EL) - BIS","programs":["EAR"],"alt_names":["Example Tech"],"addresses":[{"country":"CN"}],"source_information_url":"https://www.bis.gov/regulations/ear/744"}]}` + cslRaw, ok := FormatWave3TradeJSONMode("trade_gov_csl_json", []byte(cslPayload), nil, "https://data.trade.gov/consolidated_screening_list/v1/search?q=example") + if !ok { + t.Fatalf("trade_gov_csl_json failed") + } + cslDoc := wave3TradeDecodeDoc(t, cslRaw) + if len(cslDoc.Records) != 1 || !strings.Contains(cslDoc.Markdown, "EXAMPLE TECH LTD") { + t.Fatalf("unexpected trade_gov_csl_json output: %+v", cslDoc) + } + if _, negOK := FormatWave3TradeJSONMode("trade_gov_csl_json", []byte(`{"statusCode":401,"message":"Access denied due to missing subscription key."}`), nil, "https://data.trade.gov/consolidated_screening_list/v1/search?q=example"); negOK { + t.Fatalf("trade_gov_csl_json must reject 401 missing subscription key") + } + + // 4. #276 ofac_sdn_xml bounded scan + truncated trailing entry handling + var xmlBuf strings.Builder + xmlBuf.WriteString(`11/23/202619629`) + for i := 1; i <= 30; i++ { + xmlBuf.WriteString(``) + xmlBuf.WriteString(strings.Repeat("1", 1)) + xmlBuf.WriteString(`ENTITY `) + xmlBuf.WriteString(strings.Repeat("X", 20)) + xmlBuf.WriteString(`EntityCUBA
Cuba
`) + } + // Plus a truncated entry at the end + xmlBuf.WriteString(`99999TRUNCATED_ENTRY`) + ofacRaw, ok := FormatWave3TradeTextMode("ofac_sdn_xml", xmlBuf.String(), nil, "https://sanctionslistservice.ofac.treas.gov/api/PublicationPreview/exports/SDN.XML") + if !ok { + t.Fatalf("ofac_sdn_xml failed") + } + ofacDoc := wave3TradeDecodeDoc(t, ofacRaw) + if len(ofacDoc.Records) != wave3TradeMaxOFACRecords { + t.Fatalf("expected %d OFAC records, got %d", wave3TradeMaxOFACRecords, len(ofacDoc.Records)) + } + if !strings.Contains(ofacDoc.Markdown, "2026-11-23") || !strings.Contains(ofacDoc.Markdown, "CUBA") || !strings.Contains(ofacDoc.Markdown, "Cuba") { + t.Fatalf("ofac_sdn_xml missing publish date/program/country: %s", ofacDoc.Markdown) + } + if ofacDoc.Total == nil || *ofacDoc.Total != 19629 || ofacDoc.Truncated == nil || !*ofacDoc.Truncated { + t.Fatalf("expected OFAC total=19629 and truncated=true, got total=%v trunc=%v", ofacDoc.Total, ofacDoc.Truncated) + } + if strings.Contains(ofacDoc.Markdown, "TRUNCATED_ENTRY") { + t.Fatalf("ofac_sdn_xml must not emit truncated trailing entry") + } + + // Specifically test 1 complete entry + 1 truncated trailing entry (below cap) + partialXML := `11/23/2026236AEROCARIBBEAN AIRLINESEntityCUBA173INCOMPLETE_TAIL` + partialRaw, ok := FormatWave3TradeTextMode("ofac_sdn_xml", partialXML, nil, "https://sanctionslistservice.ofac.treas.gov/api/PublicationPreview/exports/SDN.XML") + if !ok { + t.Fatalf("ofac_sdn_xml partial tail failed") + } + partialDoc := wave3TradeDecodeDoc(t, partialRaw) + if len(partialDoc.Records) != 1 || strings.Contains(partialDoc.Markdown, "INCOMPLETE_TAIL") { + t.Fatalf("expected exactly 1 complete record without INCOMPLETE_TAIL: %+v", partialDoc) + } + if _, negOK := FormatWave3TradeTextMode("ofac_sdn_xml", `11/23/20260`, nil, "https://sanctionslistservice.ofac.treas.gov/api/PublicationPreview/exports/SDN.XML"); negOK { + t.Fatalf("ofac_sdn_xml must reject empty sdnList") + } + + // 2 MiB OFAC XML with 30+ entries cut mid-entry + latency budget check + var twoMiB strings.Builder + twoMiB.Grow(2*1024*1024 + 512) + twoMiB.WriteString(`11/23/202619629`) + entryTemplate := `42TEST ENTITYEntitySDGT
United States
` + for twoMiB.Len()+len(entryTemplate) < 2*1024*1024 { + twoMiB.WriteString(entryTemplate) + } + twoMiBSrc := (twoMiB.String() + `99CUT` + strings.Repeat("A", 512))[:2*1024*1024] + tStart := time.Now() + twoMiBRaw, twoMiBOK := FormatWave3TradeTextMode("ofac_sdn_xml", twoMiBSrc, nil, "https://sanctionslistservice.ofac.treas.gov/api/PublicationPreview/exports/SDN.XML") + tElapsed := time.Since(tStart) + if !twoMiBOK { + t.Fatalf("ofac_sdn_xml 2 MiB failed") + } + if tElapsed > 25*time.Millisecond*time.Duration(extractRaceSlowdown) { + t.Fatalf("ofac_sdn_xml 2 MiB exceeded 25ms Go budget: %v", tElapsed) + } + twoMiBDoc := wave3TradeDecodeDoc(t, twoMiBRaw) + if len(twoMiBDoc.Records) != wave3TradeMaxOFACRecords { + t.Fatalf("expected %d records from 2 MiB OFAC XML, got %d", wave3TradeMaxOFACRecords, len(twoMiBDoc.Records)) + } + + // 5. #274 ustr_301_rss_xml + rss := `United States Trade RepresentativeSection 301 Exclusion Noticehttps://ustr.gov/about-us/policy-offices/press-office/press-releases/section-3012026-11-20<p>USTR announces Section 301 tariff exclusion updates.</p>` + rssRaw, ok := FormatWave3TradeTextMode("ustr_301_rss_xml", rss, nil, "https://ustr.gov/rss.xml") + if !ok || !strings.Contains(rssRaw, "Section 301 Exclusion Notice") || strings.Contains(rssRaw, "

") { + t.Fatalf("ustr_301_rss_xml failed: ok=%v raw=%s", ok, rssRaw) + } +} + +func TestWave3TradeHTMLExtractorsAndGuardrails(t *testing.T) { + modes := []string{ + "usitc_hts_html", + "cbp_cross_html", + "census_foreign_trade_html", + "ustr_301_html", + "trade_gov_csl_html", + "ofac_html", + "bis_entity_list_html", + "import_alerts_fda_aphis_html", + } + for _, m := range modes { + if getExternalHTMLModeLazy(m) == nil { + t.Fatalf("RegisterExternalHTMLModeLazy missing %q", m) + } + } + + // Test every fixture (positive + all negative cases) and verify latency < 25ms + slugs := []string{ + "usitc-hts", + "cbp-cross-rulings", + "census-foreign-trade", + "ustr-301", + "trade-gov-csl", + "ofac-sdn", + "bis-entity-list", + "import-alerts-aphis-fda", + } + type adapterFixture struct { + AdapterID string `json:"adapterId"` + Mode string `json:"mode"` + InputURL string `json:"inputUrl"` + ExpectedFetchURL string `json:"expectedFetchUrl"` + MockPayload string `json:"mockPayload"` + ExpectTitleIncludes string `json:"expectTitleIncludes"` + ExpectMarkdownIncludes []string `json:"expectMarkdownIncludes"` + NegativeCases []struct { + Name string `json:"name"` + Status int `json:"status"` + InputURL string `json:"inputUrl"` + FinalURL string `json:"finalUrl"` + Payload string `json:"payload"` + } `json:"negativeCases"` + } + + for _, slug := range slugs { + rawFX, err := os.ReadFile(filepath.Join("..", "..", "hub", "test", "fixtures", "adapters", slug+".json")) + if err != nil { + t.Fatalf("read fixture %s.json: %v", slug, err) + } + var fx adapterFixture + if err := json.Unmarshal(rawFX, &fx); err != nil { + t.Fatalf("unmarshal %s.json: %v", slug, err) + } + if len(fx.NegativeCases) < 4 { + t.Fatalf("%s.json must have >= 4 negativeCases, got %d", slug, len(fx.NegativeCases)) + } + if fx.Mode == "html" { + modeName := "" + for _, candidate := range modes { + if wave3TradeDefaultExtractorID(candidate) == slug { + modeName = candidate + break + } + } + start := time.Now() + out, ok := RunWave3TradeHTMLMode(modeName, fx.MockPayload, fx.InputURL) + elapsed := time.Since(start) + if !ok { + t.Fatalf("%s HTML golden failed", slug) + } + if elapsed > 75*time.Millisecond*time.Duration(extractRaceSlowdown) { + t.Fatalf("%s HTML extraction exceeded 75ms budget: %v", slug, elapsed) + } + for _, needle := range fx.ExpectMarkdownIncludes { + if !strings.Contains(out, needle) { + t.Fatalf("%s output missing %q", slug, needle) + } + } + for _, nc := range fx.NegativeCases { + u := nc.FinalURL + if u == "" { + u = nc.InputURL + } + if u == "" { + u = fx.InputURL + } + if _, negOK := RunWave3TradeHTMLMode(modeName, nc.Payload, u); negOK { + t.Fatalf("%s negative case %q must be rejected", slug, nc.Name) + } + } + } + } + + // Large 78KB Angular Material CSR shell for CBP CROSS must be rejected quickly + largeAppRoot := "Customs Rulings Online Search System (CROSS)" + if _, ok := RunWave3TradeHTMLMode("cbp_cross_html", largeAppRoot, "https://rulings.cbp.gov/search?term=bicycle"); ok { + t.Fatalf("cbp_cross_html must reject 78KB unhydrated shell") + } + + // Non-matching unrelated HTML must be rejected by cheap prefilter in < 1ms + unrelated := "Example Blog

Hello World

Just a blog post.

" + for _, m := range modes { + if _, ok := RunWave3TradeHTMLMode(m, unrelated, "https://blog.example.org/post"); ok { + t.Fatalf("%s must not match unrelated host/content", m) + } + } +} + +func TestCensusIntlTradeEnrichment(t *testing.T) { + // 1. 2D intltrade matrix + intlMatrix := `[["CTY_CODE","CTY_NAME","I_COMMODITY","E_COMMODITY","GEN_VAL_MO","CON_VAL_MO","ALL_VAL_MO","time"],["5700","CHINA","871200","","12345678","12000000","12500000","2024-01"]]` + raw, ok := FormatWave2cEconJSONMode("census_json", []byte(intlMatrix), nil, "https://api.census.gov/data/timeseries/intltrade/imports/hs?get=CTY_CODE,CTY_NAME,I_COMMODITY,E_COMMODITY,GEN_VAL_MO,CON_VAL_MO,ALL_VAL_MO&time=2024-01") + if !ok { + t.Fatalf("census_json intltrade matrix failed") + } + doc := wave3TradeDecodeDoc(t, raw) + if !strings.Contains(doc.Title, "International Trade") || len(doc.Records) != 1 || doc.Records[0]["dataset"] != "intltrade" || doc.Records[0]["CTY_NAME"] != "CHINA" { + t.Fatalf("unexpected intltrade doc: %+v", doc) + } + if !strings.Contains(doc.Markdown, "ALL_VAL_MO") { + t.Fatalf("expected 7th intltrade column ALL_VAL_MO in table: %s", doc.Markdown) + } + + // 2. DCAT intltrade catalog JSON + dcat := `{"dataset":[{"title":"Time Series International Trade: Monthly U.S. Imports by HS Code","identifier":"https://api.census.gov/data/timeseries/intltrade/imports/hs","c_dataset":["timeseries","intltrade","imports","hs"],"c_variablesLink":"https://api.census.gov/data/timeseries/intltrade/imports/hs/variables.json","landingPage":"https://www.census.gov/foreign-trade/"}]}` + dRaw, dOK := FormatWave2cEconJSONMode("census_json", []byte(dcat), nil, "https://api.census.gov/data/timeseries/intltrade/imports/hs.json") + if !dOK { + t.Fatalf("census_json intltrade DCAT failed") + } + dDoc := wave3TradeDecodeDoc(t, dRaw) + if len(dDoc.Records) != 1 || dDoc.Records[0]["datasetPath"] != "timeseries/intltrade/imports/hs" { + t.Fatalf("expected datasetPath on intltrade DCAT record: %+v", dDoc) + } +}