Compare commits

...
Author SHA1 Message Date
José AlvesandClaude Sonnet 4.6 66b2373a1d fix(config): andebol.net wp_endpoint must use internal Docker port
Tests / bridge tests (push) Failing after 7s
Tests / writer-pipeline tests (push) Successful in 28s
Tests / frontend lib tests (push) Successful in 30s
Tests / writer-pipeline tests (pull_request) Successful in 26s
Tests / bridge tests (pull_request) Successful in 27s
Tests / frontend lib tests (pull_request) Successful in 31s
The bridge runs on the same CT as WordPress. The external HTTPS URL
(https://andebol.net/wp-json) requires port 443 which is terminated at
the edge proxy — not on the CT. Use the direct Docker port instead,
matching the pattern in newsproject.bitreport.pt.json.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
2026-06-18 10:57:05 +00:00
José AlvesandPaperclip 8fcb9f5803 ci: retrigger tests (BIT-25556)
Tests / writer-pipeline tests (push) Failing after 12s
Tests / bridge tests (push) Successful in 46s
Tests / writer-pipeline tests (pull_request) Successful in 42s
Tests / frontend lib tests (push) Successful in 47s
Tests / bridge tests (pull_request) Successful in 44s
Tests / frontend lib tests (pull_request) Successful in 41s
Co-Authored-By: Paperclip <[email protected]>
2026-06-18 10:46:05 +00:00
José Alves 7fb7ca272a feat(writer-pipeline): smart featured-image backfill for andebol.net (BIT-25556)
Add backfill-featured-smart.ts: extracts source URLs from post content,
queries FPA WP API for matching featured images, scrapes og:image from
IHF/EHF/Handball-Planet sources, falls back to FPA title search for
Portuguese articles, and finally tries WebDAV archive. More robust than
the slug-only backfill-featured-from-fpa.ts.

All 147 published posts now have featured_media (backfill ran in prior
heartbeat). New npm script backfill:featured-smart for future re-runs.

Paperclip-Issue: BIT-25556
Paperclip-Run: f182fddd-6d43-437a-9d2f-644fd0a76330
2026-06-18 10:46:04 +00:00
spark ddd92427f4 Merge pull request 'fix(frontend): force pt-PT locale and handball-only for andebol.net (BIT-25555)' (#24) from task/BIT-25555-andebol-fixes into main
Tests / bridge tests (push) Successful in 37s
Tests / writer-pipeline tests (push) Successful in 49s
Tests / frontend lib tests (push) Successful in 37s
fix(frontend): force pt-PT locale and handball-only for andebol.net (BIT-25555)
2026-06-18 11:45:01 +01:00
spark 152397932e Merge pull request 'feat(writer-pipeline): PT imprensa ingest for andebol.net (BIT-25559)' (#25) from feat/BIT-25559-pt-imprensa-ingest into main
Tests / writer-pipeline tests (push) Successful in 30s
Tests / bridge tests (push) Successful in 38s
Tests / frontend lib tests (push) Successful in 41s
feat(writer-pipeline): PT imprensa ingest for andebol.net (BIT-25559)
2026-06-18 11:44:42 +01:00
José AlvesandPaperclip 80ec057745 ci: retrigger tests (BIT-25555)
Tests / frontend lib tests (push) Failing after 11s
Tests / writer-pipeline tests (push) Successful in 28s
Tests / bridge tests (push) Successful in 30s
Tests / writer-pipeline tests (pull_request) Successful in 33s
Tests / bridge tests (pull_request) Successful in 29s
Tests / frontend lib tests (pull_request) Successful in 30s
Co-Authored-By: Paperclip <[email protected]>
2026-06-18 10:43:05 +00:00
José AlvesandPaperclip 7ecda44d40 ci: retrigger tests (BIT-25559)
Tests / bridge tests (push) Failing after 7s
Tests / writer-pipeline tests (push) Successful in 30s
Tests / frontend lib tests (push) Successful in 32s
Tests / writer-pipeline tests (pull_request) Successful in 35s
Tests / bridge tests (pull_request) Successful in 34s
Tests / frontend lib tests (pull_request) Successful in 32s
Co-Authored-By: Paperclip <[email protected]>
2026-06-18 10:43:00 +00:00
José Alves 919153aaf7 fix(frontend): force pt-PT locale and handball-only for andebol.net (BIT-25555)
Tests / frontend lib tests (push) Failing after 9s
Tests / writer-pipeline tests (push) Successful in 26s
Tests / bridge tests (push) Successful in 28s
Tests / bridge tests (pull_request) Failing after 7s
Tests / writer-pipeline tests (pull_request) Successful in 28s
Tests / frontend lib tests (pull_request) Successful in 29s
Root cause: DOMAINS_CONFIG_PATH was missing from the frontend env so
getDomainConfig('andebol.net') fell through to the English fallback.

Fixes applied:
- deploy/systemd/frontend.env.example: add DOMAINS_CONFIG_PATH and
  BRIDGE_INTERNAL_URL so Astro SSR resolves domain JSON on the CT
- bridge/src/lib/request-host.ts: drop X-Site-Host; resolve site domain
  from the HTTP Host header which nginx already preserves ($host)
- frontend/src/lib/bridge.ts: multi-domain SWR cache keys; nginx-routed
  bridge calls via public hostname with BRIDGE_INTERNAL_URL loopback
  override for CT environments where public DNS does not resolve locally
- config/writers/f0251a61: restrict Nelson Alves topics to Andebol only
  (remove Futebol / Desportos — BIT-22288 intent)
- frontend: overhauled article page (hero image, masthead, sidebar,
  share bar), rich related-articles grid, improved LatestGrid institutional
  theme, FpaAgendaSection rewrite, ui-i18n PT strings completed
2026-06-18 10:09:35 +00:00
José Alves 3f7b4eff71 feat(writer-pipeline): PT imprensa ingest for andebol.net (BIT-25559)
Tests / bridge tests (push) Failing after 7s
Tests / writer-pipeline tests (push) Successful in 31s
Tests / frontend lib tests (push) Successful in 31s
Tests / writer-pipeline tests (pull_request) Successful in 26s
Tests / bridge tests (pull_request) Successful in 27s
Tests / frontend lib tests (pull_request) Successful in 31s
Add html_listing ingest for Record and A Bola andebol sections and
revista_imprensa PDF index parsing from FPA media. Document AGGREGATOR_URL
in bridge.env.example and AGGREGATOR_OPERATIONS.md.

Paperclip-Issue: BIT-25559
Paperclip-Run: 0ab092e1-68ab-4e5a-90bd-4262e9c3d9fc
2026-06-18 10:01:28 +00:00
spark 129c43336b Merge pull request 'fix(writer-pipeline): stop eurohandball sitemap timeout error loop (BIT-25342)' (#22) from fix/BIT-25342-eurohandball-sitemap-timeout into main
Tests / bridge tests (push) Successful in 1m45s
Tests / frontend lib tests (push) Successful in 1m44s
Tests / writer-pipeline tests (push) Successful in 1m49s
2026-06-16 18:09:49 +01:00
José AlvesandCursor 4238ee0aa3 fix(writer-pipeline): stop eurohandball sitemap timeout error loop (BIT-25342)
Tests / writer-pipeline tests (push) Successful in 1m24s
Tests / bridge tests (push) Successful in 1m40s
Tests / frontend lib tests (push) Successful in 1m34s
Tests / writer-pipeline tests (pull_request) Successful in 1m44s
Tests / bridge tests (pull_request) Successful in 1m13s
Tests / frontend lib tests (pull_request) Successful in 1m45s
Narrow eurohandball pathIncludes to news/match pages, add pageTimeoutMs,
and report per-URL sitemap probe failures as warnings so transient
timeouts do not reopen ERRCLUSTER:97ab5f145754.

Co-authored-by: Cursor <[email protected]>
2026-06-16 17:03:00 +00:00
spark 58e1fb85eb Merge pull request 'fix(deploy): ensure writer-pipeline var is writable by www-data (BIT-25140/BIT-25141)' (#21) from task/BIT-25140-writer-var-eacces into main
Tests / writer-pipeline tests (push) Failing after 17s
Tests / bridge tests (push) Successful in 42s
Tests / frontend lib tests (push) Successful in 49s
fix(deploy): ensure writer-pipeline var is writable by www-data
2026-06-14 21:13:11 +01:00
José Alves 31a6431b54 ci: retrigger writer-pipeline tests (BIT-25141)
Tests / writer-pipeline tests (push) Failing after 10s
Tests / bridge tests (push) Failing after 12s
Tests / frontend lib tests (push) Successful in 40s
Tests / writer-pipeline tests (pull_request) Successful in 43s
Tests / bridge tests (pull_request) Successful in 42s
Tests / frontend lib tests (pull_request) Successful in 41s
Paperclip-Issue: BIT-25141
2026-06-14 20:09:16 +00:00
José AlvesandCursor be0b0c9c6f fix(deploy): ensure writer-pipeline var is writable by www-data
Tests / writer-pipeline tests (push) Failing after 11s
Tests / bridge tests (push) Successful in 29s
Tests / frontend lib tests (push) Successful in 31s
Tests / writer-pipeline tests (pull_request) Failing after 11s
Tests / bridge tests (pull_request) Failing after 13s
Tests / frontend lib tests (pull_request) Successful in 29s
Writer systemd oneshots run as www-data but deploy never chowned
writer-pipeline/var, causing EACCES on aggregated-items.json when
the store was created by root. Mirror BIT-743 bridge/config/writers
fix; rebuild writer-pipeline on webhook when that tree changes.

Paperclip-Issue: BIT-25140
Co-authored-by: Cursor <[email protected]>
2026-06-14 20:04:03 +00:00
spark eff2fdc9de Merge pull request 'fix(writer-pipeline): retry featured-image fetches on transient network errors (BIT-25135)' (#20) from task/BIT-25135-writer-fetch-retry into main
Tests / writer-pipeline tests (push) Successful in 1m53s
Tests / bridge tests (push) Successful in 1m51s
Tests / frontend lib tests (push) Successful in 2m2s
2026-06-14 20:28:56 +01:00
José AlvesandCursor dbd8c52359 ci: retrigger writer-pipeline push checks (BIT-25135)
Tests / writer-pipeline tests (push) Successful in 2m37s
Tests / bridge tests (push) Successful in 2m50s
Tests / writer-pipeline tests (pull_request) Successful in 3m1s
Tests / frontend lib tests (push) Successful in 3m7s
Tests / bridge tests (pull_request) Successful in 3m4s
Tests / frontend lib tests (pull_request) Successful in 3m19s
Paperclip-Issue: BIT-25135
Co-authored-by: Cursor <[email protected]>
2026-06-14 19:24:50 +00:00
José AlvesandCursor 6079046c5c fix(writer-pipeline): retry featured-image fetches on transient network errors
Tests / writer-pipeline tests (push) Failing after 55s
Tests / bridge tests (push) Successful in 1m45s
Tests / frontend lib tests (push) Successful in 1m44s
Tests / bridge tests (pull_request) Successful in 1m28s
Tests / frontend lib tests (pull_request) Successful in 1m56s
Tests / writer-pipeline tests (pull_request) Successful in 1m59s
Handball Planet draft publish failed with undici "fetch failed" on a single
cycle; ingest already retries but publish-path HTML/image GETs did not.

Co-authored-by: Cursor <[email protected]>
2026-06-14 19:20:37 +00:00
spark 70cdc516dc Merge pull request 'feat(writer-pipeline): report ingest failures to error hub (BIT-25125)' (#19) from task/BIT-25023-error-hub-reporters into main
Tests / writer-pipeline tests (push) Successful in 1m47s
Tests / bridge tests (push) Successful in 1m45s
Tests / frontend lib tests (push) Successful in 1m49s
feat(writer-pipeline): report ingest failures to error hub (BIT-25125)
2026-06-14 19:01:37 +01:00
José AlvesandCursor bcb95f6a0e feat(writer-pipeline): report ingest failures to error hub (BIT-25125)
Tests / writer-pipeline tests (push) Successful in 1m20s
Tests / bridge tests (push) Successful in 1m18s
Tests / frontend lib tests (push) Successful in 1m23s
Tests / writer-pipeline tests (pull_request) Successful in 1m27s
Tests / bridge tests (pull_request) Successful in 1m26s
Tests / frontend lib tests (pull_request) Successful in 1m25s
Wire run-cycle ingest and publish errors to errors.bitreport.pt using the
same reporter as bridge; document ERROR_REPORTING_* in writer env examples.

Paperclip-Agent: Artur Moreira (id ac1be104-8818-496a-80c5-fbc590a87855)
Paperclip-Issue: BIT-25125
Paperclip-Run: 06e3abea-e97b-481b-a1d5-70b286cf8983
Co-authored-by: Cursor <[email protected]>
2026-06-14 17:45:23 +00:00
spark 7a43a8c67f Merge pull request 'feat(error-hub): wire BitReport error reporter (BIT-25023)' (#18) from task/BIT-25023-error-hub-reporters into main
Tests / writer-pipeline tests (push) Successful in 2m20s
Tests / frontend lib tests (push) Successful in 2m18s
Tests / bridge tests (push) Successful in 2m20s
2026-06-12 18:06:04 +01:00
José Alves dc5e7808e3 docs(env): document ERROR_REPORTING vars for bridge (BIT-25023)
Tests / writer-pipeline tests (push) Successful in 3m30s
Tests / bridge tests (push) Successful in 2m18s
Tests / frontend lib tests (push) Successful in 2m17s
Tests / writer-pipeline tests (pull_request) Successful in 2m49s
Tests / bridge tests (pull_request) Successful in 3m56s
Tests / frontend lib tests (pull_request) Successful in 2m57s
Paperclip-Issue: BIT-25023
Paperclip-Run: f1482381-ca8c-43d6-889f-effd16f8a314
2026-06-12 11:06:53 +00:00
spark 6695e1d2c7 Merge pull request 'docs(deploy): add .env runtime preservation rules (BIT-25005)' (#17) from task/BIT-25008-env-preservation into main
Tests / writer-pipeline tests (push) Successful in 2m5s
Tests / bridge tests (push) Successful in 2m23s
Tests / frontend lib tests (push) Successful in 2m45s
docs(deploy): add .env runtime preservation rules (BIT-25005)
2026-06-11 17:21:00 +01:00
José Alves ea9a7ad5d9 docs(deploy): add .env runtime preservation rules (BIT-25005)
Tests / writer-pipeline tests (push) Successful in 3m9s
Tests / bridge tests (push) Successful in 3m9s
Tests / frontend lib tests (push) Successful in 3m26s
Tests / writer-pipeline tests (pull_request) Successful in 3m16s
Tests / bridge tests (pull_request) Successful in 1m48s
Tests / frontend lib tests (pull_request) Successful in 1m40s
Propagate DEPLOY_STANDARD.md §3.1 to this repo: prohibit cp .env.example .env
over existing production .env, require rsync excludes, and mandate
PRODUCTION_ACCESS_SYNC_LOG entries for credential changes.

Paperclip-Task: BIT-25008
2026-06-11 15:37:19 +00:00
spark 8a330be214 Merge pull request 'feat(writer-pipeline): FPA featured-image backfill + media:content ingestion — BIT-24384' (#16) from feat/BIT-24389-backfill-featured-fpa into main
Tests / writer-pipeline tests (push) Successful in 32s
Tests / bridge tests (push) Successful in 31s
Tests / frontend lib tests (push) Successful in 34s
2026-06-05 03:31:09 +01:00
José Alves e08840af18 feat(writer-pipeline): FPA featured-image backfill + media:content ingestion — BIT-24384
Tests / writer-pipeline tests (push) Successful in 31s
Tests / bridge tests (push) Successful in 32s
Tests / frontend lib tests (push) Successful in 34s
Tests / writer-pipeline tests (pull_request) Successful in 28s
Tests / bridge tests (pull_request) Successful in 32s
Tests / frontend lib tests (pull_request) Successful in 31s
- Add backfill-featured-from-fpa.ts: matches andebol.net post slugs against
  FPA portal WP REST API and uploads featured images for matched posts
- Export attachFeaturedImageToPost from wp-publish.ts for reuse by backfill
- Add npm script backfill:featured for one-shot execution
- Extend RSS ingest to extract media:content and media:thumbnail fields
  (BIT-24388: FPA feed uses <media:content> for images, not <enclosure>)
- Update config/domains/andebol.net.json: wp_endpoint → public HTTPS URL
- Update docs; add pino-pretty dev dep to bridge

Backfill result (2026-06-05): 30 updated, 52 skipped (no FPA match), 0 errors.

Paperclip-Agent: José Alves (urlKey jos-alves; id 11179220-3cec-4f0f-880d-2771ff64fce8)
Paperclip-Issue: BIT-24389
2026-06-05 02:29:47 +00:00
spark fc1c9066b6 Merge pull request 'fix(docs): CT222 IP 10.10.50.140 → 10.10.50.204 static — BIT-24053' (#15) from fix/bit-24053-ct222-static-ip into main
Tests / writer-pipeline tests (push) Successful in 26s
Tests / bridge tests (push) Successful in 28s
Tests / frontend lib tests (push) Successful in 29s
2026-06-01 14:30:46 +01:00
José Alves cba153cfc1 fix(docs): update CT222 IP from 10.10.50.140 to 10.10.50.204 — BIT-24053
Tests / bridge tests (push) Successful in 29s
Tests / writer-pipeline tests (push) Successful in 30s
Tests / frontend lib tests (push) Successful in 31s
Tests / writer-pipeline tests (pull_request) Successful in 28s
Tests / bridge tests (pull_request) Successful in 28s
Tests / frontend lib tests (pull_request) Successful in 26s
CT222 news-project-test changed IP following DHCP re-lease (BIT-24050
emergency fix). IP is now static at 10.10.50.204 via systemd-networkd.
Update all doc references, deploy script post-install notes, and
wordpress/README direct-access URLs.

Paperclip-Agent: Tiago Neves (devops; id 5d084b36-f38f-42a5-a92a-520005afda4f)
Paperclip-Issue: BIT-24053
Paperclip-Run: 9c69919d-4c21-48b0-8eb7-2b9745bed65c
2026-06-01 13:12:36 +00:00
spark 0e7897ba77 Merge pull request 'fix(nginx): add wp_andebol_content volume to nginx-andebol (BIT-23734)' (#14) from fix/BIT-23734-nginx-andebol-wp-content-volume into main
Tests / writer-pipeline tests (push) Successful in 39s
Tests / bridge tests (push) Successful in 38s
Tests / frontend lib tests (push) Successful in 37s
2026-05-26 00:32:35 +01:00
Tiago Neves 86261a1a54 fix(nginx): add wp_andebol_content volume to nginx-andebol (BIT-23734)
Tests / writer-pipeline tests (push) Successful in 50s
Tests / bridge tests (push) Successful in 1m3s
Tests / frontend lib tests (push) Successful in 1m3s
Tests / bridge tests (pull_request) Successful in 1m11s
Tests / writer-pipeline tests (pull_request) Successful in 1m14s
Tests / frontend lib tests (pull_request) Successful in 1m9s
nginx-andebol was missing the wp_andebol_content volume mount, causing
uploaded files to return 404 even though they were written correctly to
the wp_andebol_content Docker volume by the WordPress PHP-FPM container.

Paperclip-Task: BIT-23734
Paperclip-Agent: devops
2026-05-25 23:25:52 +00:00
spark 0c9e5df61c Merge pull request 'feat(writer-pipeline): newsproject.bitreport.pt writer cycle and WP env split' (#12) from feat/BIT-22288-newsproject-writer into main
Tests / writer-pipeline tests (push) Successful in 13s
Tests / bridge tests (push) Successful in 13s
Tests / frontend lib tests (push) Successful in 14s
Reviewed-on: #12
2026-05-14 19:10:00 +01:00
José Alves aaaafd0c8f ci: re-trigger push checks after runner cache fix
Tests / writer-pipeline tests (push) Successful in 11s
Tests / bridge tests (push) Successful in 15s
Tests / frontend lib tests (push) Successful in 16s
Tests / writer-pipeline tests (pull_request) Successful in 15s
Tests / bridge tests (pull_request) Successful in 15s
Tests / frontend lib tests (pull_request) Successful in 15s
Empty commit to re-run push-event CI (previous failure was runner
infrastructure — missing act cache entry for actions/setup-node@v4).

Paperclip-Issue: BIT-22306
Paperclip-Run: 9c297293-f7c3-491c-9f8e-a4488578d556
2026-05-14 18:09:29 +00:00
spark 369e0b27c2 Merge pull request 'fix(writer-pipeline): handle ns0: XML namespace prefix in WebDAV PROPFIND parser (BIT-22306)' (#13) from fix/BIT-22306-webdav-ns-prefix into main
Tests / writer-pipeline tests (push) Successful in 12s
Tests / bridge tests (push) Successful in 12s
Tests / frontend lib tests (push) Successful in 13s
Merge fix(writer-pipeline): handle ns0: XML namespace prefix in WebDAV PROPFIND parser (BIT-22306)
2026-05-14 17:46:59 +01:00
Artur Moreira 738c1a56d0 fix(writer-pipeline): handle ns0: XML namespace prefix in WebDAV PROPFIND parser (BIT-22306)
Tests / writer-pipeline tests (push) Successful in 14s
Tests / bridge tests (push) Successful in 14s
Tests / frontend lib tests (push) Successful in 15s
Tests / writer-pipeline tests (pull_request) Successful in 11s
Tests / bridge tests (pull_request) Successful in 12s
Tests / frontend lib tests (pull_request) Successful in 13s
Python's xml.etree.ElementTree auto-assigns numeric prefixes like ns0: for
the first namespace it encounters. The PROPFIND regex [a-z]+: did not match
ns0: because of the digit, causing parsePropfindImageHrefs to return empty
on any WebDAV server backed by Python (WsgiDAV, some NextCloud configs).

Change [a-z]+: → [a-z][a-z0-9]*: in all three namespace-tagged element
patterns (response, href, getlastmodified). Test added with a real WsgiDAV
multistatus fixture.

Paperclip-Issue: BIT-22306
2026-05-14 16:33:49 +00:00
Artur Moreira 0a220c158f docs(writer-pipeline): clarify WebDAV disabled vs unreachable fallback
Tests / writer-pipeline tests (push) Failing after 5s
Tests / bridge tests (push) Successful in 20s
Tests / writer-pipeline tests (pull_request) Successful in 16s
Tests / bridge tests (pull_request) Successful in 16s
Tests / frontend lib tests (push) Successful in 20s
Tests / frontend lib tests (pull_request) Successful in 17s
Document that when WRITER_WEBDAV_ENABLED is off the archive is not used,
and that enabled-but-failing PROPFIND/GET surfaces an explicit error with
operational fallback (disable or restore connectivity). Aligns BIT-22292
acceptance wording with actual pipeline behaviour.
2026-05-14 16:10:14 +00:00
Artur MoreiraandCursor 7c0a515368 feat(writer-pipeline): newsproject.bitreport.pt writer cycle and WP env split
Tests / writer-pipeline tests (push) Failing after 5s
Tests / bridge tests (push) Failing after 6s
Tests / frontend lib tests (push) Successful in 14s
Tests / writer-pipeline tests (pull_request) Successful in 11s
Tests / bridge tests (pull_request) Successful in 13s
Tests / frontend lib tests (pull_request) Successful in 14s
Add site-scoped WP credentials (NEWSPROJECT_* vs ANDEBOL_*), RSS sources
config, systemd oneshot/timer offset from andebol, env template, and
deployment docs so BIT-22288 covers both stacks.

Co-authored-by: Cursor <[email protected]>
2026-05-14 14:40:09 +00:00
spark 9d03d489e0 Merge pull request 'feat(writer-pipeline): WebDAV archive fallback + handball shortlist (BIT-22292 / BIT-22288)' (#11) from feat/bit-21912-cf-cache-rules-script into main
Tests / writer-pipeline tests (push) Failing after 10s
Tests / bridge tests (push) Successful in 14s
Tests / frontend lib tests (push) Successful in 16s
2026-05-14 15:27:09 +01:00
spark b4af1397b7 Merge pull request 'fix(frontend): auth redirects use strict false-check for auth_links (BIT-22298)' (#10) from fix/BIT-22298-auth-redirect into main
Tests / writer-pipeline tests (push) Successful in 11s
Tests / bridge tests (push) Successful in 11s
Tests / frontend lib tests (push) Successful in 12s
Merge fix/BIT-22298-auth-redirect: auth redirects strict false-check (BIT-22298)
2026-05-14 14:52:54 +01:00
Artur Moreira 11cea53dab fix(frontend): auth redirects use strict false-check for auth_links (BIT-22298)
Tests / writer-pipeline tests (push) Successful in 13s
Tests / bridge tests (push) Successful in 12s
Tests / frontend lib tests (push) Successful in 12s
Tests / writer-pipeline tests (pull_request) Successful in 11s
Tests / bridge tests (pull_request) Successful in 13s
Tests / frontend lib tests (pull_request) Successful in 14s
/entrar and /registar redirected to / because !config.auth_links is
truthy when auth_links is undefined (config fallback).  Change both
pages to config.auth_links === false so only an explicit opt-out sends
the user home; missing or true both forward to wp-login.php.

Also add Cache-Control: no-store to the redirect response so edge
proxies never cache auth flows, and extend smoke-andebol.sh to assert
/entrar and /registar resolve to a wp-login URL.

Paperclip-Issue: BIT-22298
Paperclip-Agent: d706f4e6-5d05-4cec-b6e8-f8fb1f203aae
2026-05-14 13:48:27 +00:00
spark 35e8b60684 Merge pull request 'feat: add Node.js CI workflow' (#9) from feature/add-ci-workflow into main
Tests / writer-pipeline tests (push) Successful in 13s
Tests / bridge tests (push) Successful in 13s
Tests / frontend lib tests (push) Successful in 14s
Merge feature/add-ci-workflow (branch cleanup BIT-22162)
2026-05-13 22:57:30 +01:00
spark da7a01a1c1 Merge pull request 'feat(deploy): cf-cache-rules-apply.sh for BIT-21912 / BIT-21847' (#8) from feat/bit-21912-cf-cache-rules-script into main
Tests / writer-pipeline tests (push) Successful in 12s
Tests / bridge tests (push) Successful in 14s
Tests / frontend lib tests (push) Successful in 15s
2026-05-12 12:33:47 +01:00
Artur Moreira dbf2d342a7 feat: add Node.js CI workflow for bridge
Node.js CI / build-and-test (18) (pull_request) Failing after 11s
Node.js CI / build-and-test (20) (pull_request) Failing after 13s
2026-04-27 22:45:43 +00:00
60 changed files with 3753 additions and 301 deletions

No files matched your search

+42
View File
@@ -0,0 +1,42 @@
# Node.js CI for news-platform bridge
# Runs on: PR and push to main/develop
# Checks: TypeScript build and type checking
name: Node.js CI
on:
push:
branches: [main, develop]
pull_request:
branches: [main, develop]
env:
CI: "true"
jobs:
build-and-test:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [18, 20]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
cache: npm
- name: Install dependencies
run: npm ci
working-directory: bridge
- name: TypeScript build
run: npm run build
working-directory: bridge
if: always()
- name: TypeScript type checking
run: npm run typecheck
working-directory: bridge
if: always()
+8
View File
@@ -20,3 +20,11 @@ RATE_LIMIT_WINDOW_MS=60000
# Log level: fatal | error | warn | info | debug | trace
LOG_LEVEL=info
# Error hub ingest (errors.bitreport.pt) — vault only; leave empty in Git examples
# ERROR_REPORTING_ENDPOINT=https://errors.bitreport.pt
# ERROR_REPORTING_TOKEN=
ERROR_REPORTING_PROJECT_NAME=news-platform-bridge
ERROR_REPORTING_PROJECT_SLUG=news-platform
ERROR_REPORTING_GITEA_REPO=BitReport.pt/news-platform
# ERROR_REPORTING_DISABLED=1
+162
View File
@@ -15,6 +15,7 @@
},
"devDependencies": {
"@types/node": "^20.14.0",
"pino-pretty": "^13.1.3",
"tsx": "^4.15.0",
"typescript": "^5.4.5"
}
@@ -631,6 +632,13 @@
"node": ">=0.10.0"
}
},
"node_modules/colorette": {
"version": "2.0.20",
"resolved": "https://registry.npmjs.org/colorette/-/colorette-2.0.20.tgz",
"integrity": "sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w==",
"dev": true,
"license": "MIT"
},
"node_modules/cookie": {
"version": "0.7.2",
"resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",
@@ -640,6 +648,16 @@
"node": ">= 0.6"
}
},
"node_modules/dateformat": {
"version": "4.6.3",
"resolved": "https://registry.npmjs.org/dateformat/-/dateformat-4.6.3.tgz",
"integrity": "sha512-2P0p0pFGzHS5EMnhdxQi7aJN+iMheud0UhG4dlE1DLAlvL8JHjJJTX/CSm4JXwV0Ka5nGk3zC5mcb5bUQUxxMA==",
"dev": true,
"license": "MIT",
"engines": {
"node": "*"
}
},
"node_modules/debug": {
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
@@ -666,6 +684,16 @@
"node": ">=0.10"
}
},
"node_modules/end-of-stream": {
"version": "1.4.5",
"resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz",
"integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==",
"dev": true,
"license": "MIT",
"dependencies": {
"once": "^1.4.0"
}
},
"node_modules/esbuild": {
"version": "0.27.4",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.4.tgz",
@@ -714,6 +742,13 @@
"integrity": "sha512-fBHHqSTFLVnR61C+gltJuE5GkVQMV0S2nqUO8TJ+5Z3qAKG8vAx4FKai1s5jq/inV1+sREynIWSuQ6HgoSXpDQ==",
"license": "MIT"
},
"node_modules/fast-copy": {
"version": "4.0.3",
"resolved": "https://registry.npmjs.org/fast-copy/-/fast-copy-4.0.3.tgz",
"integrity": "sha512-58apWr0GUiDFM8+3afrO6eYwJBn9ZAhDOzG3L+/9llab/haCARS2UIfffmOurYLwbgDRs8n0rfr6qAAPEAuAQw==",
"dev": true,
"license": "MIT"
},
"node_modules/fast-decode-uri-component": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/fast-decode-uri-component/-/fast-decode-uri-component-1.0.1.tgz",
@@ -767,6 +802,13 @@
"fast-decode-uri-component": "^1.0.1"
}
},
"node_modules/fast-safe-stringify": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/fast-safe-stringify/-/fast-safe-stringify-2.1.1.tgz",
"integrity": "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==",
"dev": true,
"license": "MIT"
},
"node_modules/fast-uri": {
"version": "2.4.0",
"resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-2.4.0.tgz",
@@ -873,6 +915,13 @@
"url": "https://github.com/privatenumber/get-tsconfig?sponsor=1"
}
},
"node_modules/help-me": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/help-me/-/help-me-5.0.0.tgz",
"integrity": "sha512-7xgomUX6ADmcYzFik0HzAxh/73YlKR9bmFzf51CZwR+b6YtzU2m0u49hQCqV6SvlqIqsaxovfwdvbnsw3b/zpg==",
"dev": true,
"license": "MIT"
},
"node_modules/ioredis": {
"version": "5.10.1",
"resolved": "https://registry.npmjs.org/ioredis/-/ioredis-5.10.1.tgz",
@@ -906,6 +955,16 @@
"node": ">= 0.10"
}
},
"node_modules/joycon": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/joycon/-/joycon-3.1.1.tgz",
"integrity": "sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=10"
}
},
"node_modules/json-schema-ref-resolver": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/json-schema-ref-resolver/-/json-schema-ref-resolver-1.0.1.tgz",
@@ -944,6 +1003,16 @@
"integrity": "sha512-chi4NHZlZqZD18a0imDHnZPrDeBbTtVN7GXMwuGdRH9qotxAjYs3aVLKc7zNOG9eddR5Ksd8rvFEBc9SsggPpg==",
"license": "MIT"
},
"node_modules/minimist": {
"version": "1.2.8",
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",
"integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",
"dev": true,
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/mnemonist": {
"version": "0.39.6",
"resolved": "https://registry.npmjs.org/mnemonist/-/mnemonist-0.39.6.tgz",
@@ -974,6 +1043,16 @@
"node": ">=14.0.0"
}
},
"node_modules/once": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
"integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
"dev": true,
"license": "ISC",
"dependencies": {
"wrappy": "1"
}
},
"node_modules/pino": {
"version": "9.14.0",
"resolved": "https://registry.npmjs.org/pino/-/pino-9.14.0.tgz",
@@ -1005,6 +1084,58 @@
"split2": "^4.0.0"
}
},
"node_modules/pino-pretty": {
"version": "13.1.3",
"resolved": "https://registry.npmjs.org/pino-pretty/-/pino-pretty-13.1.3.tgz",
"integrity": "sha512-ttXRkkOz6WWC95KeY9+xxWL6AtImwbyMHrL1mSwqwW9u+vLp/WIElvHvCSDg0xO/Dzrggz1zv3rN5ovTRVowKg==",
"dev": true,
"license": "MIT",
"dependencies": {
"colorette": "^2.0.7",
"dateformat": "^4.6.3",
"fast-copy": "^4.0.0",
"fast-safe-stringify": "^2.1.1",
"help-me": "^5.0.0",
"joycon": "^3.1.1",
"minimist": "^1.2.6",
"on-exit-leak-free": "^2.1.0",
"pino-abstract-transport": "^3.0.0",
"pump": "^3.0.0",
"secure-json-parse": "^4.0.0",
"sonic-boom": "^4.0.1",
"strip-json-comments": "^5.0.2"
},
"bin": {
"pino-pretty": "bin.js"
}
},
"node_modules/pino-pretty/node_modules/pino-abstract-transport": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/pino-abstract-transport/-/pino-abstract-transport-3.0.0.tgz",
"integrity": "sha512-wlfUczU+n7Hy/Ha5j9a/gZNy7We5+cXp8YL+X+PG8S0KXxw7n/JXA3c46Y0zQznIJ83URJiwy7Lh56WLokNuxg==",
"dev": true,
"license": "MIT",
"dependencies": {
"split2": "^4.0.0"
}
},
"node_modules/pino-pretty/node_modules/secure-json-parse": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/secure-json-parse/-/secure-json-parse-4.1.0.tgz",
"integrity": "sha512-l4KnYfEyqYJxDwlNVyRfO2E4NTHfMKAWdUuA8J0yve2Dz/E/PdBepY03RvyJpssIpRFwJoCD55wA+mEDs6ByWA==",
"dev": true,
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/fastify"
},
{
"type": "opencollective",
"url": "https://opencollective.com/fastify"
}
],
"license": "BSD-3-Clause"
},
"node_modules/pino-std-serializers": {
"version": "7.1.0",
"resolved": "https://registry.npmjs.org/pino-std-serializers/-/pino-std-serializers-7.1.0.tgz",
@@ -1046,6 +1177,17 @@
"node": ">= 0.10"
}
},
"node_modules/pump": {
"version": "3.0.4",
"resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz",
"integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==",
"dev": true,
"license": "MIT",
"dependencies": {
"end-of-stream": "^1.1.0",
"once": "^1.3.1"
}
},
"node_modules/quick-format-unescaped": {
"version": "4.0.4",
"resolved": "https://registry.npmjs.org/quick-format-unescaped/-/quick-format-unescaped-4.0.4.tgz",
@@ -1192,6 +1334,19 @@
"integrity": "sha512-qoRRSyROncaz1z0mvYqIE4lCd9p2R90i6GxW3uZv5ucSu8tU7B5HXUP1gG8pVZsYNVaXjk8ClXHPttLyxAL48A==",
"license": "MIT"
},
"node_modules/strip-json-comments": {
"version": "5.0.3",
"resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-5.0.3.tgz",
"integrity": "sha512-1tB5mhVo7U+ETBKNf92xT4hrQa3pm0MZ0PQvuDnWgAAGHDsfp4lPSpiS6psrSiet87wyGPh9ft6wmhOMQ0hDiw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=14.16"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/thread-stream": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-3.1.0.tgz",
@@ -1250,6 +1405,13 @@
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
"dev": true,
"license": "MIT"
},
"node_modules/wrappy": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
"dev": true,
"license": "ISC"
}
}
}
+1
View File
@@ -20,6 +20,7 @@
},
"devDependencies": {
"@types/node": "^20.14.0",
"pino-pretty": "^13.1.3",
"tsx": "^4.15.0",
"typescript": "^5.4.5"
}
+1 -5
View File
@@ -2,13 +2,9 @@ import type { FastifyRequest } from 'fastify';
/**
* Public site hostname for domain config + cache keys.
* SSR calls the bridge on loopback; the browser Host is forwarded via X-Site-Host.
* Resolved from the HTTP Host header (nginx preserves $host on /api/ proxy).
*/
export function resolve_site_host(req: FastifyRequest): string {
const raw = req.headers['x-site-host'];
if (typeof raw === 'string' && raw.trim()) {
return raw.split(':')[0].toLowerCase();
}
const hostname = req.hostname ?? 'localhost';
return hostname.replace(/:\d+$/, '').toLowerCase();
}
@@ -4,9 +4,7 @@
"role": "AI News Writer",
"domain": "andebol.net",
"topics": [
"Andebol",
"Futebol",
"Desportos"
"Andebol"
],
"sources": [
{
+4 -2
View File
@@ -120,6 +120,8 @@ chown -R www-data:www-data "$APP_DIR/frontend/dist" 2>/dev/null || true
chown -R www-data:www-data "$APP_DIR/bridge/dist" 2>/dev/null || true
mkdir -p "$APP_DIR/bridge/config/writers"
chown www-data:www-data "$APP_DIR/bridge/config/writers"
mkdir -p "$APP_DIR/writer-pipeline/var"
chown -R www-data:www-data "$APP_DIR/writer-pipeline/var"
log ""
log "=== Deployment complete ==="
@@ -129,7 +131,7 @@ log "WordPress: http://localhost:8080/wp-json/wp/v2/"
log "Nginx: http://localhost/"
log ""
log "Remaining manual steps:"
log " 1. Add DHCP reservation for 10.10.50.140 on the router"
log " 2. Configure NPM proxy host: newsproject.bitreport.pt → http://10.10.50.140"
log " 1. IP 10.10.50.204 is static (BIT-24053: systemd-networkd + PVE config; MAC BC:24:11:77:5B:E6) — no DHCP reservation needed"
log " 2. Configure NPM proxy host: newsproject.bitreport.pt → http://10.10.50.204 (NPM proxy #20)"
log " 3. Enable HTTPS in NPM (Let's Encrypt)"
log " 4. Review $ENV_DIR/frontend.env and $ENV_DIR/bridge.env"
+9
View File
@@ -53,4 +53,13 @@ _c="$(code_for "$BASE_URL/wp-json/wp/v2/")"
[[ "$_c" == "200" ]] || fail "GET $BASE_URL/wp-json/wp/v2/ expected 200, got $_c (WP andebol :8081)"
ok "GET /wp-json/wp/v2/ → $_c"
# Auth redirects — /entrar and /registar must NOT land on / (BIT-22298)
_final_entrar="$(curl -fsS -o /dev/null -w '%{url_effective}' --max-time 25 -L -H "Host: $HOST_HEADER" "$BASE_URL/entrar" 2>/dev/null || true)"
[[ "$_final_entrar" == *"wp-login"* ]] || fail "/entrar final URL must contain wp-login; got: $_final_entrar"
ok "GET /entrar → $_final_entrar"
_final_registar="$(curl -fsS -o /dev/null -w '%{url_effective}' --max-time 25 -L -H "Host: $HOST_HEADER" "$BASE_URL/registar" 2>/dev/null || true)"
[[ "$_final_registar" == *"wp-login"* ]] || fail "/registar final URL must contain wp-login; got: $_final_registar"
ok "GET /registar → $_final_registar"
echo "All smokes passed for BASE_URL=$BASE_URL (host: $HOST_HEADER)"
+12
View File
@@ -98,4 +98,16 @@ fi
bash "$APP_DIR/deploy/scripts/wordpress-sync-options-url.sh" || log "wordpress-sync-options-url skipped or failed"
# Rebuild writer-pipeline if changed (systemd oneshots run as www-data)
if git diff --name-only "$LOCAL" "$REMOTE" | grep -q "^writer-pipeline/"; then
log "Writer pipeline changed — rebuilding..."
cd "$APP_DIR/writer-pipeline"
npm ci --silent
npm run build
log "Writer pipeline rebuilt."
fi
mkdir -p "$APP_DIR/writer-pipeline/var"
chown -R www-data:www-data "$APP_DIR/writer-pipeline/var"
log "Deploy complete at $REMOTE."
+7
View File
@@ -4,6 +4,10 @@
NODE_ENV=production
PORT=3200
# Per-host domain JSON (andebol.net, newsproject.bitreport.pt)
DOMAINS_CONFIG_PATH=/opt/news-platform/config/domains
DEFAULT_HOST=andebol.net
HOST=127.0.0.1
# WordPress REST API base URL (Docker, internal)
@@ -12,6 +16,9 @@ WP_API_URL=http://127.0.0.1:8080/wp-json/wp/v2
# Redis cache (installed on host)
REDIS_URL=redis://127.0.0.1:6379
# Writer-pipeline aggregator (loopback — required for /writers/:id/candidates mix)
AGGREGATOR_URL=http://127.0.0.1:3310
# Cache TTL in seconds (default 5 min for articles, 1 min for homepage)
CACHE_TTL_ARTICLES=300
CACHE_TTL_HOMEPAGE=60
+8 -1
View File
@@ -5,8 +5,15 @@
HOST=0.0.0.0
PORT=4321
# Bridge API base URL (internal, from Astro server-side)
# Bridge API base URL — used by Astro SSR when BRIDGE_INTERNAL_URL is not set.
BRIDGE_API_URL=http://127.0.0.1:3200
# Domain JSON directory (SSR must resolve andebol.net vs newsproject — BIT-25555)
DOMAINS_CONFIG_PATH=/opt/news-platform/config/domains
# Direct loopback override for bridge calls. Set this when the CT cannot resolve the
# public hostname (e.g. andebol.net) back to itself via DNS. Overrides nginx-routed calls.
BRIDGE_INTERNAL_URL=http://127.0.0.1:3200
# Site domain (used for canonical URLs, sitemaps, etc.)
SITE_URL=https://newsproject.bitreport.pt
@@ -0,0 +1,17 @@
[Unit]
Description=News Platform — Writer Pipeline (newsproject.bitreport.pt) single cycle
After=network.target
[Service]
Type=oneshot
User=www-data
Group=www-data
WorkingDirectory=/opt/news-platform/writer-pipeline
EnvironmentFile=/etc/news-platform/writer-newsproject.env
ExecStart=/usr/bin/node dist/run-cycle.js --site newsproject.bitreport.pt --publish-max 2 --shortlist 8
StandardOutput=journal
StandardError=journal
SyslogIdentifier=news-writer-newsproject
NoNewPrivileges=true
PrivateTmp=true
@@ -0,0 +1,10 @@
[Unit]
Description=News Platform — Writer Pipeline (newsproject.bitreport.pt) daily timer
[Timer]
OnCalendar=*-*-* 06:45:00
RandomizedDelaySec=300
Persistent=true
[Install]
WantedBy=timers.target
@@ -18,3 +18,11 @@ ANDEBOL_WP_APP_PASSWORD=xxxx xxxx xxxx xxxx xxxx xxxx
# WRITER_WEBDAV_USER=
# WRITER_WEBDAV_PASSWORD=
# WRITER_WEBDAV_DEFAULT_CREDIT=Foto: … (line used as WP media caption when filename has no Credit___pattern)
# Error hub ingest (errors.bitreport.pt) — token from vault only; never commit real values (BIT-25125)
# ERROR_REPORTING_ENDPOINT=https://errors.bitreport.pt
# ERROR_REPORTING_TOKEN=
ERROR_REPORTING_PROJECT_NAME=news-platform-writer-pipeline
ERROR_REPORTING_PROJECT_SLUG=news-platform
ERROR_REPORTING_GITEA_REPO=BitReport.pt/news-platform
# ERROR_REPORTING_DISABLED=1
@@ -0,0 +1,22 @@
# Writer Pipeline — newsproject.bitreport.pt environment
# Deploy to /etc/news-platform/writer-newsproject.env on the LXC
# Secrets (WP app password) must be kept out of version control.
NODE_ENV=production
# WordPress REST API base (Docker compose default stack — port 8080)
NEWSPROJECT_WP_BASE=http://127.0.0.1:8080/wp-json
# WordPress application credentials — generate in WP Users → Application Passwords
NEWSPROJECT_WP_USER=writer-bot
NEWSPROJECT_WP_APP_PASSWORD=xxxx xxxx xxxx xxxx xxxx xxxx
# Optional — public hostname for X-Site-Domain when the REST stack is multi-tenant
# NEWSPROJECT_WP_SITE_DOMAIN=https://newsproject.bitreport.pt
# Optional — same WebDAV federation archive as andebol when enabled on the host (BIT-22292)
# WRITER_WEBDAV_ENABLED=1
# WRITER_WEBDAV_BASE_URL=https://…/remote.php/dav/files/<user>/<folder>/
# WRITER_WEBDAV_USER=
# WRITER_WEBDAV_PASSWORD=
# WRITER_WEBDAV_DEFAULT_CREDIT=Foto: …
+1
View File
@@ -40,6 +40,7 @@ Each aggregated item includes **source** (`sourceFeedId`, optional `sourceKind`)
## Sources, copyright, and wire services (Lusa)
- **Operational config:** `writer-pipeline/config/andebol.net.sources.json`. RSS feeds may set **`maxItems`** to limit how many recent entries are ingested per run (large highlight feeds such as SAPO).
- **PT imprensa (BIT-25559):** `html_listing` sources scrape handball-scoped sections (Record modalidades/andebol, A Bola /andebol). **`revista_imprensa`** parses FPA *Revista de Imprensa* PDFs from `portal.fpa.pt/media/` (Cision pressbook index) into story leads — titles + publisher labels, **without** republishing the PDF. ZeroZero listing is disabled when Cloudflare blocks the pipeline host.
- **Agência Lusa:** a direct, machine-readable **public Lusa wire feed suitable for unattended ingestion is not used here** — public endpoints are often HTML/portal pages or require a **commercial licence** and contractual terms. Syndicated PT feeds (e.g. SAPO highlights) may **credit Lusa or other agencies** in bylines; that does **not** replace checking rights for republication. Editors must follow `docs/ANDEBOL_EDITORIAL_BRIEF.md` (original rewrite, attribution, no verbatim copy).
- **Third-party RSS (Record, Guardian, BBC, etc.):** use only as **story leads**; comply with each site’s **terms of use** and robots/API policy; **English** items are for triage only — **andebol.net** publishes **European Portuguese (PT-PT)** only.
+1 -1
View File
@@ -29,7 +29,7 @@ See [`docs/ANDEBOL_EDITORIAL_BRIEF.md`](ANDEBOL_EDITORIAL_BRIEF.md) for detailed
- **Per feed:** a failing RSS URL is logged in `metrics.errors`; other feeds still run.
- **Per URL (legacy comparison):** failed HTML fetch does not block the cycle; aggregator metrics still apply for production reads.
- **WP publish:** if credentials are missing, the cycle completes with a clear error string and **no** draft creation.
- **Featured image (BIT-22288 / BIT-22292):** drafts require a rights-cleared image. The pipeline uses RSS enclosure / `og:image` / `twitter:image` first. If none are present, it can **list a WebDAV collection** (authenticated Basic auth) and pick the best-matching filename against the headline, then upload to WP with caption/alt. Configure with `WRITER_WEBDAV_*` env vars (see `deploy/systemd/writer-andebol.env.example`). If WebDAV is enabled but PROPFIND/GET fails, draft creation for that item fails with an explicit error (no silent fallback to a random web image).
- **Featured image (BIT-22288 / BIT-22292 / BIT-24388):** drafts require a rights-cleared image. The pipeline uses RSS enclosure / media:content / media:thumbnail / `og:image` / `twitter:image` first. If none are present, it can **list a WebDAV collection** (authenticated Basic auth) and pick the best-matching filename against the headline, then upload to WP with caption/alt. Configure with `WRITER_WEBDAV_*` env vars (see `deploy/systemd/writer-andebol.env.example`). When WebDAV is **not** enabled, the archive is never contacted (only RSS/HTML hints apply). If WebDAV is enabled but PROPFIND/GET fails, draft creation for that item fails with an explicit error (no silent fallback to a random web image) — operational fallback is to disable `WRITER_WEBDAV_ENABLED` or restore connectivity before retrying. **Note:** FPA RSS feed uses `<media:content>` for featured images (BIT-24388), which is now properly extracted and attached to WordPress posts.
## Commands
+56
View File
@@ -4,6 +4,22 @@
---
## `.env` preservation in deploy (BIT-25005)
> Canonical rule: **`docs/DEPLOY_STANDARD.md` §3.1** — meta-repo `paperclip`.
| Prohibited | Allowed |
|-----------|---------|
| `cp .env.example .env` over an **existing** `.env` in production | `git pull` / rsync **excluding** `.env` and `*.env` |
| Placeholder credentials (`changeme`, `secret`, `password`) in production | Vault values only; document new keys in `.env.example` **empty** |
| Changing `DB_*` / `DATABASE_*` without explicit issue, rollback plan, and log | Entry in `docs/PRODUCTION_ACCESS_SYNC_LOG.md` (meta-repo) before applying |
Deploy scripts must fail (`exit 1`) if they would overwrite an existing `.env` with example content.
> **Note:** any `cp .env.example .env` instructions in this document apply **only to initial server bootstrap** where no `.env` exists yet. On redeployments, the existing production `.env` must never be overwritten.
---
## Overview
The platform runs on a single LXC container on Proxmox for the initial test deployment. The container hosts all services: Nginx reverse proxy, Astro frontend (Node.js), Fastify bridge (Node.js), WordPress (Docker), MariaDB (Docker), and Redis.
@@ -288,6 +304,46 @@ Cycle output (metrics JSON) is also appended to `/opt/news-platform/writer-pipel
---
## Writer Pipeline — newsproject.bitreport.pt (systemd timer)
Same `run-cycle.js` binary as andebol.net, with **`--site newsproject.bitreport.pt`** and WordPress credentials from **`NEWSPROJECT_WP_*`** env vars (defaults to `http://127.0.0.1:8080/wp-json`). Source list: `writer-pipeline/config/newsproject.bitreport.pt.sources.json`.
The timer is offset from the andebol unit (**06:45** vs **06:00**) to reduce concurrent writes to the shared `var/aggregated-items.json` store.
### Files
| Repo path | CT destination |
|-----------|----------------|
| `deploy/systemd/news-writer-newsproject.service` | `/etc/systemd/system/news-writer-newsproject.service` |
| `deploy/systemd/news-writer-newsproject.timer` | `/etc/systemd/system/news-writer-newsproject.timer` |
| `deploy/systemd/writer-newsproject.env.example` | `/etc/news-platform/writer-newsproject.env` (fill secrets) |
### Install on the CT
```bash
sudo cp /opt/news-platform/deploy/systemd/writer-newsproject.env.example \
/etc/news-platform/writer-newsproject.env
sudo chmod 640 /etc/news-platform/writer-newsproject.env
sudo chown root:www-data /etc/news-platform/writer-newsproject.env
# Edit NEWSPROJECT_WP_USER and NEWSPROJECT_WP_APP_PASSWORD
sudo cp /opt/news-platform/deploy/systemd/news-writer-newsproject.service \
/etc/systemd/system/
sudo cp /opt/news-platform/deploy/systemd/news-writer-newsproject.timer \
/etc/systemd/system/
sudo systemctl daemon-reload
sudo systemctl enable --now news-writer-newsproject.timer
```
### Manual test run
```bash
sudo systemctl start news-writer-newsproject.service
journalctl -u news-writer-newsproject.service -n 50
```
---
## Future: Multi-Container
When the platform scales beyond a single test container, each service moves to its own LXC or VM:
+1 -1
View File
@@ -1,6 +1,6 @@
# Service Health Monitoring
Automated health monitoring and alerting for the news-platform services on **CT 222** (`news-project-test`, **10.10.50.140**).
Automated health monitoring and alerting for the news-platform services on **CT 222** (`news-project-test`, **10.10.50.204**).
**BIT-746** adds a **must-not-fail inventory**, optional **public URL** probing, optional **bridge deep** checks, and an **escalation runbook**: `docs/runbooks/NEWS_PLATFORM_MONITORING_ALERTS_BIT746.md`.
**BIT-3915** adds **pipeline incident** coverage (aggregator stall, lag signals, escalation): `docs/runbooks/NEWS_PLATFORM_INCIDENT_RUNBOOK_BIT3915.md`.
**Runbook index:** `docs/runbooks/README.md` (links deployment, smoke script, and company-wide **paperclip** runbooks).
@@ -1,6 +1,6 @@
# News platform — incident response (aggregator, lag, escalation) — BIT-3915
Operational incident guide for the **news-platform** stack (Astro SSR, Fastify bridge, headless WordPress, optional **writer-pipeline** aggregator). Default deployment context: **LXC CT 222** (`news-project-test`, **10.10.50.140**, VLAN 1050) — confirm VMID/IP against the current inventory in the **paperclip** meta-repo (`docs/environments/03-lxc.md`).
Operational incident guide for the **news-platform** stack (Astro SSR, Fastify bridge, headless WordPress, optional **writer-pipeline** aggregator). Default deployment context: **LXC CT 222** (`news-project-test`, **10.10.50.204**, VLAN 1050) — confirm VMID/IP against the current inventory in the **paperclip** meta-repo (`docs/environments/03-lxc.md`).
## How this runbook fits
@@ -114,6 +114,7 @@ Add for **aggregator / writer-pipeline**:
| Single failed ingest; self-heals on retry | Log in issue; no escalation. |
| Repeated ingest errors or copyright/licensing uncertainty | Pause automated ingest for the suspect feed; involve **editorial** + **CTO**. |
| Data corruption suspicion on `aggregated-items.json` | Stop aggregator; take a **file backup**; restore from known good or re-ingest; involve **CTO** before destructive deletes. |
| **`EACCES`** on `writer-pipeline/var/aggregated-items.json` (systemd `User=www-data`) | `var/` or the JSON store was created as **root** (manual run, deploy gap). On CT222: `sudo mkdir -p /opt/news-platform/writer-pipeline/var && sudo chown -R www-data:www-data /opt/news-platform/writer-pipeline/var`; re-run `news-writer-andebol.service` / `news-writer-newsproject.service`. Deploy scripts enforce ownership on every pull (**BIT-25140**). |
### 4.2 Paperclip and queue hygiene
@@ -1,6 +1,6 @@
# News platform — monitoring alerts and escalation (BIT-746)
Follow-up to incident **BIT-743** (public `/noticias` unavailable while internal checks looked fine). This runbook applies to **CT 222** (`news-project-test`, **10.10.50.140**) and the **news-platform** stack deployed under `/opt/news-platform`.
Follow-up to incident **BIT-743** (public `/noticias` unavailable while internal checks looked fine). This runbook applies to **CT 222** (`news-project-test`, **10.10.50.204**) and the **news-platform** stack deployed under `/opt/news-platform`.
## Must-not-fail inventory (MVP)
@@ -8,36 +8,49 @@ interface Props {
locale: string;
/** When false, parent layout already renders a localized breadcrumb (e.g. institutional theme). */
showBreadcrumb?: boolean;
/** meta-only: skip title/excerpt (rendered in masthead/hero); full: default article header */
variant?: 'full' | 'meta-only';
/** Light text for hero overlay */
theme?: 'default' | 'dark';
}
const { article, locale, showBreadcrumb = true } = Astro.props;
const {
article,
locale,
showBreadcrumb = true,
variant = 'full',
theme = 'default',
} = Astro.props;
const ui = getUiStrings(locale);
const is_meta_only = variant === 'meta-only';
const is_dark = theme === 'dark';
---
<header class="article-header">
{showBreadcrumb && (
<nav class="breadcrumb" aria-label={ui.aria_breadcrumb}>
<a href="/">{ui.breadcrumb_home}</a>
<span class="breadcrumb__sep" aria-hidden="true">/</span>
<a href={`/category/${article.category.slug}`}>{article.category.name}</a>
<span class="breadcrumb__sep" aria-hidden="true">/</span>
<span aria-current="page">{article.title}</span>
</nav>
<header class:list={['article-header', is_meta_only && 'article-header--meta', is_dark && 'article-header--dark']}>
{showBreadcrumb && !is_meta_only && (
<nav class="breadcrumb" aria-label={ui.aria_breadcrumb}>
<a href="/">{ui.breadcrumb_home}</a>
<span class="breadcrumb__sep" aria-hidden="true">/</span>
<a href={`/category/${article.category.slug}`}>{article.category.name}</a>
<span class="breadcrumb__sep" aria-hidden="true">/</span>
<span aria-current="page">{article.title}</span>
</nav>
)}
<!-- Category -->
<div class="article-header__cats">
<a href={`/category/${article.category.slug}`} class="badge">{article.category.name}</a>
{article.tags.slice(0, 3).map(tag => (
<span class="badge badge--muted">{tag.name}</span>
))}
</div>
{!is_meta_only && (
<>
<div class="article-header__cats">
<a href={`/category/${article.category.slug}`} class="badge">{article.category.name}</a>
{article.tags.slice(0, 3).map(tag => (
<span class="badge badge--muted">{tag.name}</span>
))}
</div>
<!-- Title -->
<h1 class="article-header__title">{article.title}</h1>
<h1 class="article-header__title">{article.title}</h1>
<!-- Excerpt -->
<p class="article-header__excerpt">{article.excerpt}</p>
{article.excerpt && <p class="article-header__excerpt">{article.excerpt}</p>}
</>
)}
<!-- Meta -->
<div class="article-header__meta">
<div class="article-header__author">
{article.author.avatar ? (
@@ -89,6 +102,24 @@ const ui = getUiStrings(locale);
margin-bottom: var(--space-6);
}
.article-header--meta {
padding-bottom: 0;
border-bottom: none;
margin-bottom: 0;
gap: var(--space-3);
}
.article-header--dark .article-header__author-name,
.article-header--dark .article-header__date,
.article-header--dark .article-header__reading {
color: rgba(255, 255, 255, 0.85);
}
.article-header--dark .article-header__avatar--placeholder {
background: rgba(255, 255, 255, 0.2);
border: 2px solid rgba(255, 255, 255, 0.4);
}
.article-header__cats {
display: flex;
gap: var(--space-2);
@@ -167,5 +198,23 @@ const ui = getUiStrings(locale);
font-size: var(--text-sm);
color: var(--color-text-muted);
white-space: nowrap;
padding: 0.35em 0.75em;
background: var(--color-bg-secondary);
border-radius: 999px;
font-weight: 600;
}
.article-header--dark .article-header__reading {
background: rgba(255, 255, 255, 0.12);
}
.article-header--meta .article-header__reading {
background: transparent;
padding: 0;
}
.article-header--dark.article-header--meta .article-header__reading {
background: rgba(255, 255, 255, 0.1);
padding: 0.35em 0.75em;
}
</style>
@@ -0,0 +1,143 @@
---
import { getUiStrings } from '../../lib/ui-i18n.js';
interface Props {
url: string;
title: string;
locale: string;
}
const { url, title, locale } = Astro.props;
const ui = getUiStrings(locale);
const encoded_url = encodeURIComponent(url);
const encoded_title = encodeURIComponent(title);
---
<div class="article-share" role="group" aria-label={ui.share_heading}>
<span class="article-share__label">{ui.share_heading}</span>
<div class="article-share__actions">
<button type="button" class="article-share__btn" data-share="copy" data-url={url} title={ui.share_copy}>
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true">
<rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
</svg>
<span class="article-share__btn-text">{ui.share_copy}</span>
</button>
<a
href={`https://twitter.com/intent/tweet?url=${encoded_url}&text=${encoded_title}`}
class="article-share__btn"
target="_blank"
rel="noopener noreferrer"
title={ui.share_twitter}
>
<svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
<path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"/>
</svg>
<span class="sr-only">{ui.share_twitter}</span>
</a>
<a
href={`https://www.facebook.com/sharer/sharer.php?u=${encoded_url}`}
class="article-share__btn"
target="_blank"
rel="noopener noreferrer"
title={ui.share_facebook}
>
<svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
<path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z"/>
</svg>
<span class="sr-only">{ui.share_facebook}</span>
</a>
<a
href={`https://wa.me/?text=${encoded_title}%20${encoded_url}`}
class="article-share__btn"
target="_blank"
rel="noopener noreferrer"
title={ui.share_whatsapp}
>
<svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
<path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 0 1-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 0 1-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 0 1 2.893 6.994c-.003 5.45-4.435 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0 0 12.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 0 0 5.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 0 0-3.48-8.413z"/>
</svg>
<span class="sr-only">{ui.share_whatsapp}</span>
</a>
</div>
</div>
<script>
document.querySelectorAll('[data-share="copy"]').forEach(btn => {
btn.addEventListener('click', async () => {
const url = btn.getAttribute('data-url');
if (!url) return;
try {
await navigator.clipboard.writeText(url);
btn.classList.add('article-share__btn--copied');
setTimeout(() => btn.classList.remove('article-share__btn--copied'), 2000);
} catch {
/* clipboard unavailable */
}
});
});
</script>
<style>
.article-share {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: var(--space-3);
padding: var(--space-4);
background: var(--inst-surface-muted, var(--color-bg-secondary));
border-radius: 10px;
border: 1px solid var(--color-border);
margin-bottom: var(--space-6);
}
.article-share__label {
font-size: var(--text-xs);
font-weight: 800;
text-transform: uppercase;
letter-spacing: 0.06em;
color: var(--color-text-muted);
flex-shrink: 0;
}
.article-share__actions {
display: flex;
flex-wrap: wrap;
gap: var(--space-2);
}
.article-share__btn {
display: inline-flex;
align-items: center;
gap: var(--space-2);
padding: 0.45em 0.75em;
border-radius: 8px;
border: 1px solid var(--color-border);
background: var(--color-bg);
color: var(--color-text);
font-size: var(--text-xs);
font-weight: 600;
text-decoration: none;
cursor: pointer;
transition: background var(--transition-fast), border-color var(--transition-fast), color var(--transition-fast);
}
.article-share__btn:hover {
border-color: var(--color-primary);
color: var(--color-primary);
}
.article-share__btn--copied {
border-color: var(--color-primary);
background: color-mix(in srgb, var(--color-primary) 12%, var(--color-bg));
color: var(--color-primary);
}
.article-share__btn-text {
display: none;
}
@media (min-width: 640px) {
.article-share__btn-text {
display: inline;
}
}
</style>
@@ -0,0 +1,288 @@
---
import type { Article, ArticleListItem, CategoryConfig } from '../../types/index.js';
import { truncate } from '../../lib/format.js';
import { getUiStrings } from '../../lib/ui-i18n.js';
interface Props {
article: Article;
trending: ArticleListItem[];
categories: CategoryConfig[];
locale: string;
ads_enabled?: boolean;
}
const { article, trending, categories, locale, ads_enabled = false } = Astro.props;
const ui = getUiStrings(locale);
const filtered_trending = trending.filter(t => t.slug !== article.slug).slice(0, 5);
---
<aside class="article-sidebar" aria-label={ui.aria_article_sidebar}>
{filtered_trending.length > 0 && (
<section class="article-sidebar__panel">
<div class="article-sidebar__header">
<h2 class="article-sidebar__title">{ui.news_most_read}</h2>
</div>
<ol class="article-sidebar__list">
{filtered_trending.map((item, i) => (
<li class="article-sidebar__item">
<span class="article-sidebar__rank">{String(i + 1).padStart(2, '0')}</span>
<div class="article-sidebar__body">
<a href={`/category/${item.category.slug}`} class="article-sidebar__cat">
{item.category.name}
</a>
<h3 class="article-sidebar__headline">
<a href={`/article/${item.slug}`}>{truncate(item.title, 80)}</a>
</h3>
</div>
</li>
))}
</ol>
</section>
)}
{categories.length > 0 && (
<section class="article-sidebar__panel article-sidebar__panel--muted">
<div class="article-sidebar__header">
<h2 class="article-sidebar__title">{ui.explore_sections}</h2>
</div>
<ul class="article-sidebar__chips">
{categories.map(cat => (
<li>
<a
href={`/category/${cat.slug}`}
class:list={['article-sidebar__chip', cat.slug === article.category.slug && 'article-sidebar__chip--active']}
>
{cat.label}
</a>
</li>
))}
</ul>
</section>
)}
<section class="article-sidebar__panel article-sidebar__panel--author">
<div class="article-sidebar__header">
<h2 class="article-sidebar__title">{ui.written_by}</h2>
</div>
<div class="article-sidebar__author">
{article.author.avatar ? (
<img
src={article.author.avatar}
alt=""
width="48"
height="48"
class="article-sidebar__avatar"
loading="lazy"
/>
) : (
<div class="article-sidebar__avatar article-sidebar__avatar--placeholder" aria-hidden="true">
{article.author.name.charAt(0).toUpperCase()}
</div>
)}
<div>
<p class="article-sidebar__author-name">{article.author.name}</p>
<a href={`/category/${article.category.slug}`} class="article-sidebar__author-more">
{ui.more_from_category(article.category.name)}
</a>
</div>
</div>
</section>
{ads_enabled && (
<div class="ad-slot ad-slot--sidebar sticky-top" aria-label={ui.ad_slot_aria}>{ui.ad_slot_text}</div>
)}
</aside>
<style>
.article-sidebar {
display: flex;
flex-direction: column;
gap: var(--space-5);
min-width: 0;
}
@media (min-width: 1024px) {
.article-sidebar {
position: sticky;
top: calc(var(--header-height) + var(--space-4));
align-self: start;
}
}
.article-sidebar__panel {
background: var(--color-bg-card);
border: 1px solid var(--color-border);
border-radius: 10px;
padding: var(--space-4);
box-shadow: var(--shadow-sm);
}
.article-sidebar__panel--muted {
background: var(--inst-surface-muted, var(--color-bg-secondary));
}
.article-sidebar__header {
padding-bottom: var(--space-3);
border-bottom: 3px solid var(--color-primary);
margin-bottom: var(--space-3);
}
.article-sidebar__title {
font-family: var(--font-heading, inherit);
font-size: var(--text-sm);
font-weight: 800;
text-transform: uppercase;
letter-spacing: 0.06em;
color: var(--color-primary);
margin: 0;
}
.article-sidebar__list {
list-style: none;
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
}
.article-sidebar__item {
display: flex;
gap: var(--space-3);
padding: var(--space-3) 0;
border-bottom: 1px solid var(--color-border);
align-items: start;
}
.article-sidebar__item:last-child {
border-bottom: none;
padding-bottom: 0;
}
.article-sidebar__rank {
flex-shrink: 0;
font-family: var(--font-heading, inherit);
font-size: 1.35rem;
font-weight: 800;
line-height: 1;
color: var(--color-primary);
opacity: 0.3;
min-width: 2ch;
}
.article-sidebar__body {
display: flex;
flex-direction: column;
gap: 2px;
min-width: 0;
}
.article-sidebar__cat {
font-size: 0.6rem;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.05em;
text-decoration: none;
color: var(--color-secondary);
}
.article-sidebar__cat:hover {
text-decoration: underline;
}
.article-sidebar__headline {
font-family: var(--font-heading, inherit);
font-size: var(--text-sm);
font-weight: 700;
line-height: 1.35;
margin: 0;
}
.article-sidebar__headline a {
color: var(--color-text);
text-decoration: none;
transition: color var(--transition-fast);
}
.article-sidebar__headline a:hover {
color: var(--color-primary);
}
.article-sidebar__chips {
list-style: none;
margin: 0;
padding: 0;
display: flex;
flex-wrap: wrap;
gap: var(--space-2);
}
.article-sidebar__chip {
display: inline-block;
padding: 0.35em 0.75em;
border-radius: 999px;
font-size: var(--text-xs);
font-weight: 700;
text-decoration: none;
background: var(--color-bg);
color: var(--color-text);
border: 1px solid var(--color-border);
transition: background var(--transition-fast), color var(--transition-fast), border-color var(--transition-fast);
}
.article-sidebar__chip:hover {
border-color: var(--color-primary);
color: var(--color-primary);
}
.article-sidebar__chip--active {
background: var(--color-primary);
color: #fff;
border-color: var(--color-primary);
}
.article-sidebar__author {
display: flex;
align-items: center;
gap: var(--space-3);
}
.article-sidebar__avatar {
width: 48px;
height: 48px;
border-radius: 50%;
object-fit: cover;
flex-shrink: 0;
}
.article-sidebar__avatar--placeholder {
background: var(--color-primary);
color: #fff;
display: flex;
align-items: center;
justify-content: center;
font-weight: 800;
font-size: var(--text-lg);
}
.article-sidebar__author-name {
font-weight: 700;
font-size: var(--text-sm);
margin: 0 0 var(--space-1);
}
.article-sidebar__author-more {
font-size: var(--text-xs);
color: var(--color-secondary);
font-weight: 600;
text-decoration: none;
}
.article-sidebar__author-more:hover {
text-decoration: underline;
color: var(--color-primary);
}
.sticky-top {
position: sticky;
top: calc(var(--header-height) + var(--space-4));
}
</style>
@@ -1,6 +1,7 @@
---
import type { ArticleListItem } from '../../types/index.js';
import { getThemeComponents } from '../../lib/theme.js';
import { relativeTime, truncate } from '../../lib/format.js';
import { getUiStrings } from '../../lib/ui-i18n.js';
interface Props {
@@ -14,8 +15,51 @@ const ui = getUiStrings(locale);
---
{articles.length > 0 && (
<section class="related-section" aria-labelledby="related-title">
<h2 class="section-title" id="related-title">{ui.related_articles_title}</h2>
<div class="related-grid">
<div class="related-section__header">
<h2 class="related-section__title" id="related-title">{ui.related_articles_title}</h2>
<span class="related-section__accent" aria-hidden="true"></span>
</div>
<div class="related-grid related-grid--rich">
{articles.map((article, i) => (
<article class="related-card">
<a href={`/article/${article.slug}`} class="related-card__media" tabindex="-1" aria-hidden="true">
{article.featured_image ? (
<img
src={article.featured_image}
alt={article.featured_image_alt}
class="related-card__img"
loading="lazy"
decoding="async"
width="400"
height="225"
/>
) : (
<div class="related-card__img img-placeholder" aria-hidden="true">
<svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" opacity="0.3">
<rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="8.5" cy="8.5" r="1.5"/>
<polyline points="21 15 16 10 5 21"/>
</svg>
</div>
)}
<span class="related-card__index">{String(i + 1).padStart(2, '0')}</span>
</a>
<div class="related-card__body">
<a href={`/category/${article.category.slug}`} class="related-card__cat">{article.category.name}</a>
<h3 class="related-card__title">
<a href={`/article/${article.slug}`}>{truncate(article.title, 90)}</a>
</h3>
<p class="related-card__excerpt">{truncate(article.excerpt, 100)}</p>
<footer class="related-card__meta">
<span>{article.author.name}</span>
<span aria-hidden="true">·</span>
<time datetime={article.published_at}>{relativeTime(article.published_at, locale)}</time>
</footer>
</div>
</article>
))}
</div>
<div class="related-grid related-grid--compact">
{articles.map(article => (
<ArticleCard article={article} size="md" show_excerpt={false} locale={locale} />
))}
@@ -30,10 +74,154 @@ const ui = getUiStrings(locale);
border-top: 1px solid var(--color-border);
}
.related-grid {
.related-section__header {
display: flex;
align-items: center;
gap: var(--space-4);
margin-bottom: var(--space-6);
}
.related-section__title {
font-family: var(--font-heading, inherit);
font-size: clamp(1.25rem, 3vw, 1.75rem);
font-weight: 900;
letter-spacing: -0.02em;
margin: 0;
color: var(--color-primary);
text-transform: uppercase;
}
.related-section__accent {
flex: 1;
height: 3px;
background: linear-gradient(90deg, var(--color-primary), transparent);
border-radius: 2px;
}
.related-grid--rich {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
gap: var(--space-5);
margin-top: var(--space-5);
}
.related-grid--compact {
display: none;
}
@media (max-width: 639px) {
.related-grid--rich {
display: none;
}
.related-grid--compact {
display: grid;
grid-template-columns: 1fr;
gap: var(--space-4);
}
}
.related-card {
display: flex;
flex-direction: column;
background: var(--color-bg-card);
border: 1px solid var(--color-border);
border-radius: 12px;
overflow: hidden;
transition: box-shadow var(--transition-fast), transform var(--transition-fast);
}
.related-card:hover {
box-shadow: var(--shadow-md);
transform: translateY(-3px);
}
.related-card__media {
position: relative;
display: block;
overflow: hidden;
}
.related-card__img {
width: 100%;
aspect-ratio: 16 / 9;
object-fit: cover;
display: block;
transition: transform 0.4s ease;
}
.related-card:hover .related-card__img {
transform: scale(1.04);
}
.related-card__index {
position: absolute;
top: var(--space-3);
left: var(--space-3);
font-family: var(--font-heading, inherit);
font-size: 1.5rem;
font-weight: 900;
color: #fff;
text-shadow: 0 2px 8px rgba(0, 0, 0, 0.5);
line-height: 1;
}
.related-card__body {
padding: var(--space-4);
display: flex;
flex-direction: column;
gap: var(--space-2);
flex: 1;
}
.related-card__cat {
font-size: 0.65rem;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.05em;
color: var(--color-secondary);
text-decoration: none;
}
.related-card__cat:hover {
color: var(--color-primary);
text-decoration: underline;
}
.related-card__title {
font-family: var(--font-heading, inherit);
font-size: var(--text-base);
font-weight: 800;
line-height: 1.3;
margin: 0;
}
.related-card__title a {
color: var(--color-text);
text-decoration: none;
transition: color var(--transition-fast);
}
.related-card__title a:hover {
color: var(--color-primary);
}
.related-card__excerpt {
font-size: var(--text-sm);
color: var(--color-text-muted);
line-height: 1.5;
margin: 0;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
flex: 1;
}
.related-card__meta {
display: flex;
gap: var(--space-2);
font-size: var(--text-xs);
color: var(--color-text-muted);
margin-top: auto;
padding-top: var(--space-2);
}
</style>
+61 -5
View File
@@ -29,14 +29,32 @@ const ui = getUiStrings(locale);
const heading = title ?? ui.latest_news;
---
<section
class:list={['latest-section', variant === 'band' && 'latest-section--band']}
class:list={[
'latest-section',
variant === 'band' && 'latest-section--band',
theme === 'institutional' && 'latest-section--institutional',
]}
aria-labelledby={titleId}
>
<div class="container">
<div class="latest-header">
<h2 class="section-title" id={titleId}>{heading}</h2>
<h2
class:list={[
theme === 'institutional' ? 'latest-section__title' : 'section-title',
]}
id={titleId}
>
{heading}
</h2>
{show_more_href && (
<a href={show_more_href} class="btn btn--ghost latest-more">{ui.view_all}</a>
<a
href={show_more_href}
class:list={[
theme === 'institutional' ? 'latest-section__more' : 'btn btn--ghost latest-more',
]}
>
{ui.view_all}
</a>
)}
</div>
@@ -65,8 +83,46 @@ const heading = title ?? ui.latest_news;
gap: var(--space-4);
}
.latest-header .section-title { margin-bottom: 0; }
.latest-more { white-space: nowrap; }
.latest-header .section-title,
.latest-header .latest-section__title { margin-bottom: 0; }
.latest-more,
.latest-section__more { white-space: nowrap; }
.latest-section--institutional .latest-header {
align-items: baseline;
padding-bottom: var(--space-3);
border-bottom: 2px solid var(--color-primary);
margin-bottom: var(--space-2);
}
.latest-section__title {
font-family: var(--font-heading, inherit);
font-size: clamp(1.25rem, 2.5vw, 1.75rem);
font-weight: 800;
letter-spacing: -0.01em;
color: var(--color-primary);
margin: 0;
}
.latest-section__more {
font-size: var(--text-sm);
font-weight: 500;
color: var(--color-secondary);
text-decoration: none;
}
.latest-section__more:hover {
text-decoration: underline;
}
.latest-section--institutional.latest-section--band {
background: linear-gradient(
180deg,
color-mix(in srgb, var(--color-primary) 5%, var(--color-bg)) 0%,
var(--color-bg-secondary) 40%,
var(--color-bg) 100%
);
}
.latest-grid {
display: grid;
+42
View File
@@ -0,0 +1,42 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
bridgeBaseForSite,
bridgeHealthUrl,
swrCacheKey,
} from './bridge.ts';
test('bridgeBaseForSite uses nginx vhost path for production domains', () => {
assert.equal(
bridgeBaseForSite('andebol.net', 'http://127.0.0.1:3200'),
'http://andebol.net/api',
);
assert.equal(
bridgeBaseForSite('newsproject.bitreport.pt', 'http://127.0.0.1:3200'),
'http://newsproject.bitreport.pt/api',
);
});
test('bridgeBaseForSite keeps loopback for local dev', () => {
assert.equal(
bridgeBaseForSite('localhost', 'http://localhost:3200'),
'http://localhost:3200',
);
assert.equal(
bridgeBaseForSite('127.0.0.1', 'http://127.0.0.1:3200'),
'http://127.0.0.1:3200',
);
});
test('bridgeHealthUrl uses vhost /health for production domains', () => {
assert.equal(
bridgeHealthUrl('andebol.net', 'http://127.0.0.1:3200'),
'http://andebol.net/health',
);
});
test('swrCacheKey scopes cache entries per site host', () => {
const url = 'http://andebol.net/api/homepage';
assert.equal(swrCacheKey(url, 'andebol.net'), 'andebol.net|http://andebol.net/api/homepage');
assert.notEqual(swrCacheKey(url, 'andebol.net'), swrCacheKey(url, 'newsproject.bitreport.pt'));
});
+88 -24
View File
@@ -18,19 +18,71 @@ const cache = new Map<string, CacheEntry>();
const FRESH_TTL = 60_000; // 60s before stale
const STALE_TTL = 300_000; // 5min before hard expiry
/** Forward public Host so the bridge loads the correct domain JSON on loopback SSR. */
export function bridgeRequestHeaders(site_host?: string | null): HeadersInit {
const headers: Record<string, string> = { Accept: 'application/json' };
const hostname = site_host?.split(':')[0];
if (hostname) {
headers['X-Site-Host'] = hostname;
}
return headers;
function isLoopbackHostname(hostname: string): boolean {
return hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '::1';
}
async function fetchWithSWR<T>(url: string, req_headers: HeadersInit): Promise<T> {
/**
* SSR bridge base URL.
* - `BRIDGE_INTERNAL_URL` env overrides everything — use when hostname DNS doesn't resolve
* from inside the LXC (e.g. `http://127.0.0.1:3200`).
* - Production multi-domain without override: call nginx via the public hostname so the
* `Host` header selects the correct domain JSON — no X-Site-Host (BIT-25555).
* - Local dev / loopback: direct to `bridge_endpoint`.
*/
export function bridgeBaseForSite(
site_host: string | null | undefined,
bridge_endpoint: string,
): string {
const internalUrl = typeof process !== 'undefined'
? process.env['BRIDGE_INTERNAL_URL']?.trim()
: undefined;
if (internalUrl) {
return internalUrl.replace(/\/$/, '');
}
const hostname = site_host?.split(':')[0]?.toLowerCase();
if (!hostname || isLoopbackHostname(hostname)) {
return bridge_endpoint.replace(/\/$/, '');
}
return `http://${hostname}/api`;
}
/** Health probe URL — nginx exposes /health per vhost on the CT. */
export function bridgeHealthUrl(
site_host: string | null | undefined,
bridge_endpoint: string,
): string {
const internalUrl = typeof process !== 'undefined'
? process.env['BRIDGE_INTERNAL_URL']?.trim()
: undefined;
if (internalUrl) {
return `${internalUrl.replace(/\/$/, '')}/health`;
}
const hostname = site_host?.split(':')[0]?.toLowerCase();
if (!hostname || isLoopbackHostname(hostname)) {
return `${bridge_endpoint.replace(/\/$/, '')}/health`;
}
return `http://${hostname}/health`;
}
export function bridgeRequestHeaders(): HeadersInit {
return { Accept: 'application/json' };
}
/** SWR keys must include site host — one Node process serves every domain (BIT-25555). */
export function swrCacheKey(url: string, site_host: string | null | undefined): string {
const hostname = site_host?.split(':')[0]?.toLowerCase();
return hostname ? `${hostname}|${url}` : url;
}
async function fetchWithSWR<T>(
url: string,
site_host: string | null | undefined,
req_headers: HeadersInit,
): Promise<T> {
const cache_key = swrCacheKey(url, site_host);
const now = Date.now();
const entry = cache.get(url);
const entry = cache.get(cache_key);
if (entry && now < entry.stale_at) {
return entry.data as T;
@@ -38,15 +90,20 @@ async function fetchWithSWR<T>(url: string, req_headers: HeadersInit): Promise<T
// Revalidate in background if stale but not expired
if (entry && now < entry.expires) {
revalidate(url, req_headers).catch(() => null);
revalidate(cache_key, url, site_host, req_headers).catch(() => null);
return entry.data as T;
}
// Blocking fetch (cold or hard-expired)
return revalidate<T>(url, req_headers);
return revalidate<T>(cache_key, url, site_host, req_headers);
}
async function revalidate<T>(url: string, req_headers: HeadersInit): Promise<T> {
async function revalidate<T>(
cache_key: string,
url: string,
site_host: string | null | undefined,
req_headers: HeadersInit,
): Promise<T> {
const res = await fetch(url, {
headers: req_headers,
});
@@ -54,7 +111,7 @@ async function revalidate<T>(url: string, req_headers: HeadersInit): Promise<T>
throw new Error(`Bridge API ${res.status}: ${url}`);
}
const data: T = await res.json();
cache.set(url, {
cache.set(cache_key, {
data,
stale_at: Date.now() + FRESH_TTL,
expires: Date.now() + STALE_TTL,
@@ -64,15 +121,17 @@ async function revalidate<T>(url: string, req_headers: HeadersInit): Promise<T>
export class BridgeClient {
private base: string;
private site_host: string | null | undefined;
private req_headers: HeadersInit;
constructor(bridge_endpoint: string, site_host?: string | null) {
this.base = bridge_endpoint.replace(/\/$/, '');
this.req_headers = bridgeRequestHeaders(site_host);
this.site_host = site_host ?? undefined;
this.base = bridgeBaseForSite(this.site_host, bridge_endpoint);
this.req_headers = bridgeRequestHeaders();
}
async getHomepage(): Promise<HomepageData> {
return fetchWithSWR<HomepageData>(`${this.base}/homepage`, this.req_headers);
return fetchWithSWR<HomepageData>(`${this.base}/homepage`, this.site_host, this.req_headers);
}
async getArticles(params: {
@@ -87,28 +146,33 @@ export class BridgeClient {
if (params.per_page) qs.set('per_page', String(params.per_page));
if (params.search) qs.set('search', params.search);
const url = `${this.base}/articles?${qs.toString()}`;
return fetchWithSWR<PaginatedResponse<ArticleListItem>>(url, this.req_headers);
return fetchWithSWR<PaginatedResponse<ArticleListItem>>(url, this.site_host, this.req_headers);
}
async getArticle(slug: string): Promise<Article> {
return fetchWithSWR<Article>(`${this.base}/articles/${slug}`, this.req_headers);
return fetchWithSWR<Article>(`${this.base}/articles/${slug}`, this.site_host, this.req_headers);
}
async getCategories(): Promise<Category[]> {
return fetchWithSWR<Category[]>(`${this.base}/categories`, this.req_headers);
return fetchWithSWR<Category[]>(`${this.base}/categories`, this.site_host, this.req_headers);
}
async getCategory(slug: string): Promise<Category> {
return fetchWithSWR<Category>(`${this.base}/categories/${slug}`, this.req_headers);
return fetchWithSWR<Category>(`${this.base}/categories/${slug}`, this.site_host, this.req_headers);
}
async getTrending(limit = 5): Promise<ArticleListItem[]> {
return fetchWithSWR<ArticleListItem[]>(`${this.base}/trending?limit=${limit}`, this.req_headers);
return fetchWithSWR<ArticleListItem[]>(
`${this.base}/trending?limit=${limit}`,
this.site_host,
this.req_headers,
);
}
async getRelated(slug: string, limit = 4): Promise<ArticleListItem[]> {
return fetchWithSWR<ArticleListItem[]>(
`${this.base}/articles/${slug}/related?limit=${limit}`,
this.site_host,
this.req_headers,
);
}
@@ -261,9 +325,9 @@ export async function resolveSsrBridge(
): Promise<BridgeClient> {
try {
const bridge = new BridgeClient(bridge_endpoint, site_host ?? undefined);
const health_url = `${bridge_endpoint.replace(/\/$/, '')}/health`;
const health_url = bridgeHealthUrl(site_host, bridge_endpoint);
const res = await fetch(health_url, {
headers: bridgeRequestHeaders(site_host),
headers: bridgeRequestHeaders(),
signal: AbortSignal.timeout(2000),
});
if (!res.ok) {
+32
View File
@@ -55,6 +55,9 @@ export type UiStrings = {
fpa_col_competition: string;
fpa_agenda_empty: string;
fpa_source_credit: string;
fpa_status_finished: string;
fpa_status_upcoming: string;
fpa_games_on_date: (count: number) => string;
/** News archive page title */
news_archive_title: string;
/** "All" filter label for category tabs */
@@ -80,6 +83,15 @@ export type UiStrings = {
tags_heading: string;
/** Prefix before updated timestamp in article byline */
article_updated_prefix: string;
/** Share bar heading on article pages */
share_heading: string;
share_copy: string;
share_twitter: string;
share_facebook: string;
share_whatsapp: string;
/** Sidebar author panel */
written_by: string;
more_from_category: (sectionName: string) => string;
/** Meta description when category has no WP description */
category_meta_latest: (sectionName: string) => string;
/** Search results could not be loaded from bridge */
@@ -135,6 +147,9 @@ const en: UiStrings = {
fpa_col_competition: 'Competition',
fpa_agenda_empty: 'Fixture list is temporarily unavailable.',
fpa_source_credit: 'Data: Portuguese Handball Federation (ws.fpa.pt).',
fpa_status_finished: 'FT',
fpa_status_upcoming: 'Upcoming',
fpa_games_on_date: count => (count === 1 ? '1 match' : `${count} matches`),
news_archive_title: 'News',
news_all_filter: 'All',
news_archive_desc: 'Latest news and stories across all sections.',
@@ -149,6 +164,13 @@ const en: UiStrings = {
aria_article_sidebar: 'Article sidebar',
tags_heading: 'Tags:',
article_updated_prefix: 'Updated',
share_heading: 'Share',
share_copy: 'Copy link',
share_twitter: 'Share on X',
share_facebook: 'Share on Facebook',
share_whatsapp: 'Share on WhatsApp',
written_by: 'Written by',
more_from_category: name => `More from ${name}`,
category_meta_latest: name => `Latest ${name} news`,
search_upstream_error: 'Results could not be loaded. Please try again shortly.',
};
@@ -202,6 +224,9 @@ const pt: UiStrings = {
fpa_col_competition: 'Competição',
fpa_agenda_empty: 'A agenda não está disponível de momento.',
fpa_source_credit: 'Dados: Federação Portuguesa de Andebol (ws.fpa.pt).',
fpa_status_finished: 'Fim',
fpa_status_upcoming: 'Por jogar',
fpa_games_on_date: count => (count === 1 ? '1 jogo' : `${count} jogos`),
news_archive_title: 'Notícias',
news_all_filter: 'Todas',
news_archive_desc: 'Últimas notícias e histórias de todas as secções.',
@@ -216,6 +241,13 @@ const pt: UiStrings = {
aria_article_sidebar: 'Barra lateral do artigo',
tags_heading: 'Etiquetas:',
article_updated_prefix: 'Atualizado',
share_heading: 'Partilhar',
share_copy: 'Copiar link',
share_twitter: 'Partilhar no X',
share_facebook: 'Partilhar no Facebook',
share_whatsapp: 'Partilhar no WhatsApp',
written_by: 'Escrito por',
more_from_category: name => `Mais de ${name}`,
category_meta_latest: name => `Últimas notícias: ${name}`,
search_upstream_error:
'Não foi possível obter resultados. Tenta novamente dentro de momentos.',
+295 -50
View File
@@ -1,6 +1,8 @@
---
import Base from '../../layouts/Base.astro';
import ArticleHeader from '../../components/article/ArticleHeader.astro';
import ArticleSidebar from '../../components/article/ArticleSidebar.astro';
import ArticleShareBar from '../../components/article/ArticleShareBar.astro';
import RelatedArticles from '../../components/article/RelatedArticles.astro';
import { getDomainConfig } from '../../lib/domain.js';
import { BridgeClient, resolveSsrBridge } from '../../lib/bridge.js';
@@ -15,7 +17,6 @@ const host = Astro.request.headers.get('host') ?? 'localhost';
const site_host = host.split(':')[0];
const config = getDomainConfig(host);
// Set cache headers for CDN
Astro.response.headers.set('Cache-Control', 's-maxage=60, stale-while-revalidate=300');
let bridge: BridgeClient;
@@ -27,11 +28,13 @@ try {
let article;
let related;
let trending;
try {
[article, related] = await Promise.all([
[article, related, trending] = await Promise.all([
bridge.getArticle(slug),
bridge.getRelated(slug, 4),
bridge.getTrending(6),
]);
} catch {
return Astro.redirect('/');
@@ -41,6 +44,7 @@ const public_origin = getPublicOrigin(Astro.request);
const canonical = `${public_origin}/article/${slug}`;
const ui = getUiStrings(config.locale);
const is_institutional = config.theme === 'institutional';
const has_hero_image = Boolean(article.featured_image);
const news_article_schema = {
'@context': 'https://schema.org',
@@ -90,26 +94,76 @@ const breadcrumb_schema = {
canonical={canonical}
schema={news_article_schema}
>
<!-- Additional schema for breadcrumbs -->
<script type="application/ld+json" set:html={JSON.stringify(breadcrumb_schema)} slot="head" />
<div class:list={['article-page', 'container', is_institutional && 'article-page--inst']}>
{is_institutional && (
<nav class="article-breadcrumb" aria-label={ui.aria_breadcrumb}>
<a href="/">{ui.breadcrumb_home}</a>
<span class="article-breadcrumb__sep" aria-hidden="true">/</span>
<a href={`/category/${article.category.slug}`}>{article.category.name}</a>
<span class="article-breadcrumb__sep" aria-hidden="true">/</span>
<span class="article-breadcrumb__current" aria-current="page">{article.title}</span>
</nav>
)}
<div class="article-layout">
<!-- Main article column -->
<div class="article-main">
<ArticleHeader article={article} locale={config.locale} showBreadcrumb={!is_institutional} />
<article class:list={['article-page', is_institutional && 'article-page--inst']}>
{is_institutional ? (
<header class="article-masthead">
<div class="container article-masthead__inner">
<nav class="article-breadcrumb" aria-label={ui.aria_breadcrumb}>
<a href="/">{ui.breadcrumb_home}</a>
<span class="article-breadcrumb__sep" aria-hidden="true">/</span>
<a href={`/category/${article.category.slug}`}>{article.category.name}</a>
<span class="article-breadcrumb__sep" aria-hidden="true">/</span>
<span class="article-breadcrumb__current" aria-current="page">{article.title}</span>
</nav>
<a href={`/category/${article.category.slug}`} class="article-masthead__cat badge">
{article.category.name}
</a>
<h1 class="article-masthead__title">{article.title}</h1>
{article.excerpt && <p class="article-masthead__excerpt">{article.excerpt}</p>}
<ArticleHeader article={article} locale={config.locale} variant="meta-only" />
</div>
</header>
) : has_hero_image ? (
<header class="article-hero">
<img
src={article.featured_image!}
alt={article.featured_image_alt}
class="article-hero__img"
loading="eager"
decoding="async"
fetchpriority="high"
width="1280"
height="720"
/>
<div class="article-hero__overlay">
<div class="container article-hero__content">
<nav class="article-breadcrumb article-breadcrumb--light" aria-label={ui.aria_breadcrumb}>
<a href="/">{ui.breadcrumb_home}</a>
<span class="article-breadcrumb__sep" aria-hidden="true">/</span>
<a href={`/category/${article.category.slug}`}>{article.category.name}</a>
</nav>
<a href={`/category/${article.category.slug}`} class="badge">{article.category.name}</a>
<h1 class="article-hero__title">{article.title}</h1>
<ArticleHeader article={article} locale={config.locale} variant="meta-only" theme="dark" />
</div>
</div>
</header>
) : null}
<!-- Featured image -->
{article.featured_image && (
<div class="container article-layout">
<div class="article-main">
{!is_institutional && !has_hero_image && (
<ArticleHeader article={article} locale={config.locale} showBreadcrumb />
)}
{is_institutional && has_hero_image && (
<figure class="article-figure article-figure--masthead">
<img
src={article.featured_image!}
alt={article.featured_image_alt}
class="article-figure__img"
loading="eager"
decoding="async"
fetchpriority="high"
width="900"
height="506"
/>
</figure>
)}
{!is_institutional && !has_hero_image && article.featured_image && (
<figure class="article-figure">
<img
src={article.featured_image}
@@ -124,48 +178,173 @@ const breadcrumb_schema = {
</figure>
)}
<!-- Ad slot: top of article -->
<ArticleShareBar url={canonical} title={article.title} locale={config.locale} />
{config.ads_enabled && (
<div class="ad-slot ad-slot--in-article" aria-label={ui.ad_slot_aria}>{ui.ad_slot_text}</div>
)}
<!-- Article body -->
<div class="article-body" set:html={article.content} />
<!-- Tags -->
{article.tags.length > 0 && (
<div class="article-tags">
<footer class="article-tags">
<span class="article-tags__label">{ui.tags_heading}</span>
{article.tags.map(tag => (
<span class="badge badge--muted">{tag.name}</span>
))}
</div>
</footer>
)}
<div class="article-byline-footer">
<div class="article-byline-footer__author">
{article.author.avatar ? (
<img
src={article.author.avatar}
alt=""
width="56"
height="56"
class="article-byline-footer__avatar"
loading="lazy"
/>
) : (
<div class="article-byline-footer__avatar article-byline-footer__avatar--placeholder" aria-hidden="true">
{article.author.name.charAt(0).toUpperCase()}
</div>
)}
<div>
<p class="article-byline-footer__label">{ui.written_by}</p>
<p class="article-byline-footer__name">{article.author.name}</p>
<p class="article-byline-footer__date">
<time datetime={article.published_at}>{formatDate(article.published_at, config.locale)}</time>
{article.updated_at !== article.published_at && (
<span> · {ui.article_updated_prefix}{' '}
<time datetime={article.updated_at}>{formatDate(article.updated_at, config.locale)}</time>
</span>
)}
</p>
</div>
</div>
</div>
</div>
<!-- Sidebar -->
<aside class="article-sidebar" aria-label={ui.aria_article_sidebar}>
{config.ads_enabled && (
<div class="ad-slot ad-slot--sidebar sticky-top" aria-label={ui.ad_slot_aria}>{ui.ad_slot_text}</div>
)}
</aside>
<ArticleSidebar
article={article}
trending={trending}
categories={config.categories}
locale={config.locale}
ads_enabled={config.ads_enabled}
/>
</div>
<!-- Related articles -->
<RelatedArticles theme={config.theme} articles={related} locale={config.locale} />
</div>
<div class="container">
<RelatedArticles theme={config.theme} articles={related} locale={config.locale} />
</div>
</article>
</Base>
<style>
.article-page {
padding-top: var(--space-6);
padding-bottom: var(--space-12);
}
.article-page--inst {
.article-page--inst .article-layout {
padding-top: var(--space-8);
}
.article-masthead {
background: linear-gradient(
135deg,
var(--color-primary-dark, #0f2640) 0%,
var(--color-primary) 55%,
color-mix(in srgb, var(--color-secondary) 80%, #000) 100%
);
color: #fff;
padding: var(--space-8) 0 var(--space-10);
border-bottom: 4px solid color-mix(in srgb, var(--color-secondary) 65%, #fff);
}
.article-masthead__inner {
display: flex;
flex-direction: column;
gap: var(--space-4);
max-width: min(900px, 100%);
}
.article-masthead__cat {
align-self: flex-start;
}
.article-masthead__title {
font-family: var(--font-heading, inherit);
font-size: clamp(1.85rem, 5vw, 3rem);
font-weight: 900;
line-height: 1.08;
letter-spacing: -0.03em;
margin: 0;
color: #fff;
}
.article-masthead__excerpt {
font-size: var(--text-lg);
line-height: 1.55;
color: rgba(255, 255, 255, 0.88);
margin: 0;
max-width: 65ch;
border-left: 3px solid rgba(255, 255, 255, 0.35);
padding-left: var(--space-4);
}
.article-hero {
position: relative;
min-height: clamp(280px, 50vw, 520px);
background: var(--color-bg-secondary);
overflow: hidden;
}
.article-hero__img {
width: 100%;
height: clamp(280px, 50vw, 520px);
object-fit: cover;
display: block;
}
.article-hero__overlay {
position: absolute;
inset: 0;
background: linear-gradient(
to top,
rgba(0, 0, 0, 0.92) 0%,
rgba(0, 0, 0, 0.55) 45%,
rgba(0, 0, 0, 0.15) 100%
);
display: flex;
align-items: flex-end;
padding-bottom: var(--space-8);
}
.article-hero__content {
display: flex;
flex-direction: column;
gap: var(--space-3);
}
.article-hero__title {
font-family: var(--font-heading, inherit);
font-size: clamp(1.75rem, 4.5vw, 2.85rem);
font-weight: 900;
line-height: 1.1;
letter-spacing: -0.025em;
color: #fff;
margin: 0;
max-width: 18ch;
}
@media (min-width: 768px) {
.article-hero__title {
max-width: 22ch;
}
}
.article-breadcrumb {
display: flex;
flex-wrap: wrap;
@@ -173,9 +352,10 @@ const breadcrumb_schema = {
gap: var(--space-2);
font-size: var(--text-sm);
color: var(--color-text-muted);
padding-bottom: var(--space-4);
margin-bottom: var(--space-2);
border-bottom: 1px solid var(--color-border);
}
.article-breadcrumb--light {
color: rgba(255, 255, 255, 0.75);
}
.article-breadcrumb a {
@@ -184,16 +364,28 @@ const breadcrumb_schema = {
text-decoration: none;
}
.article-breadcrumb--light a {
color: rgba(255, 255, 255, 0.9);
}
.article-breadcrumb a:hover {
text-decoration: underline;
color: var(--color-primary);
}
.article-breadcrumb--light a:hover {
color: #fff;
}
.article-breadcrumb__sep {
color: var(--color-border);
user-select: none;
}
.article-breadcrumb--light .article-breadcrumb__sep {
color: rgba(255, 255, 255, 0.4);
}
.article-breadcrumb__current {
color: var(--color-text);
font-weight: 600;
@@ -208,25 +400,35 @@ const breadcrumb_schema = {
display: grid;
grid-template-columns: 1fr;
gap: var(--space-8);
padding-top: var(--space-6);
}
@media (min-width: 1024px) {
.article-layout {
grid-template-columns: minmax(0, 2.5fr) 280px;
grid-template-columns: minmax(0, 1fr) 300px;
align-items: start;
gap: var(--space-10);
}
}
.article-figure {
margin-bottom: var(--space-8);
border-radius: 8px;
margin-bottom: var(--space-6);
border-radius: 12px;
overflow: hidden;
box-shadow: var(--inst-shadow-feature, var(--shadow-md));
}
.article-figure--masthead {
margin-top: 0;
margin-bottom: var(--space-8);
border-radius: 10px;
}
.article-figure__img {
width: 100%;
max-height: 520px;
max-height: 560px;
object-fit: cover;
display: block;
}
.article-tags {
@@ -241,20 +443,63 @@ const breadcrumb_schema = {
.article-tags__label {
font-size: var(--text-sm);
font-weight: 600;
font-weight: 700;
color: var(--color-text-muted);
text-transform: uppercase;
letter-spacing: 0.04em;
}
.sticky-top {
position: sticky;
top: calc(var(--header-height) + var(--space-4));
.article-byline-footer {
margin-top: var(--space-8);
padding: var(--space-5);
background: var(--inst-surface-muted, var(--color-bg-secondary));
border-radius: 12px;
border: 1px solid var(--color-border);
}
.article-sidebar {
display: none;
.article-byline-footer__author {
display: flex;
align-items: center;
gap: var(--space-4);
}
@media (min-width: 1024px) {
.article-sidebar { display: block; }
.article-byline-footer__avatar {
width: 56px;
height: 56px;
border-radius: 50%;
object-fit: cover;
flex-shrink: 0;
}
.article-byline-footer__avatar--placeholder {
background: var(--color-primary);
color: #fff;
display: flex;
align-items: center;
justify-content: center;
font-weight: 800;
font-size: var(--text-xl);
}
.article-byline-footer__label {
font-size: var(--text-xs);
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.05em;
color: var(--color-text-muted);
margin: 0 0 var(--space-1);
}
.article-byline-footer__name {
font-family: var(--font-heading, inherit);
font-size: var(--text-lg);
font-weight: 800;
margin: 0 0 var(--space-1);
}
.article-byline-footer__date {
font-size: var(--text-sm);
color: var(--color-text-muted);
margin: 0;
}
</style>
+2 -1
View File
@@ -2,8 +2,9 @@
import { getDomainConfig } from '../lib/domain.js';
const config = getDomainConfig(Astro.url.hostname);
if (!config.auth_links) {
if (config.auth_links === false) {
return Astro.redirect('/', 302);
}
Astro.response.headers.set('Cache-Control', 'no-store');
return Astro.redirect('/wp-login.php', 302);
---
+2 -1
View File
@@ -2,8 +2,9 @@
import { getDomainConfig } from '../lib/domain.js';
const config = getDomainConfig(Astro.url.hostname);
if (!config.auth_links) {
if (config.auth_links === false) {
return Astro.redirect('/', 302);
}
Astro.response.headers.set('Cache-Control', 'no-store');
return Astro.redirect('/wp-login.php?action=register', 302);
---
+96 -7
View File
@@ -339,22 +339,38 @@ img {
.article-body {
font-family: var(--font-serif);
font-size: 1.125rem;
line-height: 1.8;
line-height: 1.85;
color: var(--color-text);
}
.article-body > p:first-of-type::first-letter {
font-family: var(--font-heading, var(--font-sans));
font-size: 3.2em;
font-weight: 800;
float: left;
line-height: 0.85;
margin: 0.05em 0.12em 0 0;
color: var(--color-primary);
}
.article-body h2 {
font-family: var(--font-sans);
font-family: var(--font-heading, var(--font-sans));
font-size: var(--text-2xl);
margin-top: var(--space-8);
font-weight: 800;
margin-top: var(--space-10);
margin-bottom: var(--space-4);
padding-bottom: var(--space-2);
border-bottom: 2px solid var(--color-border);
letter-spacing: -0.02em;
}
.article-body h3 {
font-family: var(--font-sans);
font-family: var(--font-heading, var(--font-sans));
font-size: var(--text-xl);
margin-top: var(--space-6);
font-weight: 700;
margin-top: var(--space-8);
margin-bottom: var(--space-3);
color: var(--color-secondary);
}
.article-body p {
@@ -370,19 +386,92 @@ img {
margin-bottom: var(--space-2);
}
.article-body li::marker {
color: var(--color-primary);
}
.article-body a {
color: var(--color-primary);
text-decoration: underline;
text-decoration-thickness: 1px;
text-underline-offset: 3px;
font-weight: 600;
}
.article-body a:hover {
color: var(--color-primary-dark, var(--color-secondary));
}
.article-body blockquote {
border-left: 4px solid var(--color-primary);
padding-left: var(--space-4);
margin: var(--space-6) 0;
padding: var(--space-4) var(--space-5);
margin: var(--space-8) 0;
font-style: italic;
color: var(--color-text-muted);
background: var(--inst-surface-muted, var(--color-bg-secondary));
border-radius: 0 10px 10px 0;
font-size: 1.15em;
line-height: 1.7;
}
.article-body img,
.article-body figure img {
max-width: 100%;
height: auto;
border-radius: 10px;
margin: var(--space-6) auto;
display: block;
box-shadow: var(--shadow-md);
}
.article-body figure {
margin: var(--space-8) 0;
}
.article-body figcaption {
font-family: var(--font-sans);
font-size: var(--text-sm);
color: var(--color-text-muted);
text-align: center;
margin-top: var(--space-2);
font-style: italic;
}
.article-body hr {
border: none;
height: 2px;
background: linear-gradient(90deg, var(--color-primary), transparent);
margin: var(--space-10) 0;
}
.article-body table {
width: 100%;
border-collapse: collapse;
margin: var(--space-6) 0;
font-family: var(--font-sans);
font-size: var(--text-sm);
}
.article-body th,
.article-body td {
border: 1px solid var(--color-border);
padding: var(--space-3);
text-align: left;
}
.article-body th {
background: var(--color-bg-secondary);
font-weight: 700;
color: var(--color-primary);
}
.article-body strong {
font-weight: 700;
color: var(--color-text);
}
.article-body em {
font-style: italic;
}
/* ---- Scrollbar ---- */
@@ -10,54 +10,132 @@ interface Props {
const { games, locale } = Astro.props;
const ui = getUiStrings(locale);
function format_score(game: FpaAgendaGame): string {
if (game.home_goals !== null && game.away_goals !== null) {
return `${game.home_goals} – ${game.away_goals}`;
}
return '—';
function team_initials(name: string): string {
const parts = name.trim().split(/\s+/).filter(Boolean);
if (parts.length === 0) return '?';
if (parts.length === 1) return parts[0]!.slice(0, 2).toUpperCase();
return (parts[0]![0]! + parts[parts.length - 1]![0]!).toUpperCase();
}
function is_finished(game: FpaAgendaGame): boolean {
return game.home_goals !== null && game.away_goals !== null;
}
function format_score(game: FpaAgendaGame): string | null {
if (!is_finished(game)) return null;
return `${game.home_goals} – ${game.away_goals}`;
}
const by_date = new Map<string, FpaAgendaGame[]>();
for (const game of games) {
const list = by_date.get(game.date) ?? [];
list.push(game);
by_date.set(game.date, list);
}
const date_groups = [...by_date.entries()];
---
<section class="fpa-agenda" aria-labelledby="fpa-agenda-title">
<div class="container">
<header class="fpa-agenda__head">
<h2 id="fpa-agenda-title" class="fpa-agenda__title">{ui.fpa_agenda_title}</h2>
<p class="fpa-agenda__lead">{ui.fpa_agenda_lead}</p>
</header>
<header class="fpa-agenda__masthead">
<div class="container">
<div class="fpa-agenda__masthead-inner">
<div class="fpa-agenda__masthead-text">
<p class="fpa-agenda__eyebrow">{ui.fpa_col_competition}</p>
<h2 id="fpa-agenda-title" class="fpa-agenda__title">{ui.fpa_agenda_title}</h2>
<p class="fpa-agenda__lead">{ui.fpa_agenda_lead}</p>
</div>
{games.length > 0 && (
<div class="fpa-agenda__stat" aria-hidden="true">
<span class="fpa-agenda__stat-value">{games.length}</span>
<span class="fpa-agenda__stat-label">{ui.fpa_games_on_date(games.length)}</span>
</div>
)}
</div>
</div>
</header>
<div class="container fpa-agenda__body">
{games.length === 0 ? (
<p class="fpa-agenda__empty" role="status">{ui.fpa_agenda_empty}</p>
) : (
<div class="fpa-agenda__scroll" tabindex="0">
<table class="fpa-agenda__table">
<thead>
<tr>
<th scope="col">{ui.fpa_col_when}</th>
<th scope="col">{ui.fpa_col_match}</th>
<th scope="col">{ui.fpa_col_score}</th>
<th scope="col" class="fpa-agenda__hide-narrow">{ui.fpa_col_venue}</th>
<th scope="col" class="fpa-agenda__hide-narrow">{ui.fpa_col_competition}</th>
</tr>
</thead>
<tbody>
{games.map((g) => (
<tr>
<td class="fpa-agenda__when">
<span class="fpa-agenda__date">{g.date}</span>
<span class="fpa-agenda__time">{g.time}</span>
</td>
<td class="fpa-agenda__match">
<span class="fpa-agenda__team fpa-agenda__team--home">{g.home_team}</span>
<span class="fpa-agenda__vs" aria-hidden="true">vs</span>
<span class="fpa-agenda__team fpa-agenda__team--away">{g.away_team}</span>
{g.phase && <span class="fpa-agenda__phase">{g.phase}</span>}
</td>
<td class="fpa-agenda__score">{format_score(g)}</td>
<td class="fpa-agenda__hide-narrow">{g.venue}</td>
<td class="fpa-agenda__hide-narrow fpa-agenda__comp">{g.competition}</td>
</tr>
))}
</tbody>
</table>
<div class="fpa-agenda__days">
{date_groups.map(([date, day_games]) => (
<section class="fpa-agenda__day" aria-label={`${date}`}>
<header class="fpa-agenda__day-head">
<time class="fpa-agenda__day-date" datetime={date}>{date}</time>
<span class="fpa-agenda__day-count">{ui.fpa_games_on_date(day_games.length)}</span>
</header>
<ul class="fpa-agenda__cards" role="list">
{day_games.map((g) => {
const finished = is_finished(g);
const score = format_score(g);
return (
<li class="fpa-agenda__card" role="listitem">
<article class="fpa-agenda__match">
<header class="fpa-agenda__match-head">
<span class="fpa-agenda__comp">{g.competition}</span>
{g.phase && <span class="fpa-agenda__phase">{g.phase}</span>}
<span
class:list={[
'fpa-agenda__status',
finished && 'fpa-agenda__status--finished',
]}
>
{finished ? ui.fpa_status_finished : ui.fpa_status_upcoming}
</span>
</header>
<div class="fpa-agenda__faceoff">
<div class="fpa-agenda__side fpa-agenda__side--home">
<span class="fpa-agenda__crest" aria-hidden="true">
{team_initials(g.home_team)}
</span>
<span class="fpa-agenda__team">{g.home_team}</span>
</div>
<div class="fpa-agenda__center">
{score ? (
<span class="fpa-agenda__score" aria-label={`${ui.fpa_col_score}: ${score}`}>
{score}
</span>
) : (
<span class="fpa-agenda__kickoff">
<span class="fpa-agenda__kickoff-time">{g.time}</span>
</span>
)}
</div>
<div class="fpa-agenda__side fpa-agenda__side--away">
<span class="fpa-agenda__crest" aria-hidden="true">
{team_initials(g.away_team)}
</span>
<span class="fpa-agenda__team">{g.away_team}</span>
</div>
</div>
<footer class="fpa-agenda__meta">
<span class="fpa-agenda__meta-item">
<svg class="fpa-agenda__icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true">
<circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/>
</svg>
<span>{g.time}</span>
</span>
{g.venue && g.venue !== '—' && (
<span class="fpa-agenda__meta-item">
<svg class="fpa-agenda__icon" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true">
<path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"/><circle cx="12" cy="10" r="3"/>
</svg>
<span>{g.venue}</span>
</span>
)}
</footer>
</article>
</li>
);
})}
</ul>
</section>
))}
</div>
)}
@@ -67,142 +145,370 @@ function format_score(game: FpaAgendaGame): string {
<style>
.fpa-agenda {
padding: var(--space-10) 0;
background: var(--color-bg-card);
border-block: 1px solid var(--color-border);
background: var(--color-bg);
}
.fpa-agenda__head {
margin-bottom: var(--space-6);
max-width: 40rem;
.fpa-agenda__masthead {
background: linear-gradient(
135deg,
var(--color-primary-dark, #0f2640) 0%,
var(--color-primary) 52%,
color-mix(in srgb, var(--color-secondary) 80%, #000) 100%
);
color: #fff;
padding: var(--space-8) 0;
border-bottom: 4px solid color-mix(in srgb, var(--color-secondary) 65%, #fff);
}
.fpa-agenda__masthead-inner {
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: var(--space-6);
flex-wrap: wrap;
}
.fpa-agenda__eyebrow {
font-family: var(--font-heading, inherit);
font-size: var(--text-xs);
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.14em;
opacity: 0.82;
margin: 0 0 var(--space-2);
}
.fpa-agenda__title {
font-family: var(--font-heading, inherit);
font-size: clamp(1.25rem, 2.2vw, 1.65rem);
font-weight: 600;
color: var(--color-primary);
font-size: clamp(1.5rem, 3.5vw, 2.25rem);
font-weight: 900;
line-height: 1.1;
letter-spacing: -0.02em;
text-transform: uppercase;
margin: 0 0 var(--space-2);
line-height: 1.2;
}
.fpa-agenda__lead {
margin: 0;
font-size: var(--text-sm);
line-height: 1.55;
color: var(--color-text-muted);
color: rgba(255, 255, 255, 0.86);
max-width: 36rem;
}
.fpa-agenda__stat {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-width: 5.5rem;
padding: var(--space-3) var(--space-4);
border-radius: var(--inst-radius-lg, 10px);
background: rgba(255, 255, 255, 0.12);
border: 1px solid rgba(255, 255, 255, 0.2);
backdrop-filter: blur(6px);
}
.fpa-agenda__stat-value {
font-family: var(--font-heading, inherit);
font-size: clamp(1.75rem, 4vw, 2.5rem);
font-weight: 900;
line-height: 1;
letter-spacing: -0.03em;
}
.fpa-agenda__stat-label {
margin-top: var(--space-1);
font-size: var(--text-xs);
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.06em;
opacity: 0.85;
text-align: center;
}
.fpa-agenda__body {
padding: var(--space-8) 0 var(--space-10);
}
.fpa-agenda__empty {
margin: 0 0 var(--space-4);
padding: var(--space-8);
text-align: center;
color: var(--color-text-muted);
font-size: var(--text-sm);
font-size: var(--text-base);
background: var(--color-bg-secondary);
border: 1px dashed var(--color-border);
border-radius: var(--inst-radius-lg, 8px);
}
.fpa-agenda__scroll {
overflow-x: auto;
.fpa-agenda__days {
display: flex;
flex-direction: column;
gap: var(--space-8);
}
.fpa-agenda__day-head {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: var(--space-4);
margin-bottom: var(--space-4);
border: 1px solid var(--color-border);
border-radius: 8px;
background: var(--color-bg, #fff);
padding-bottom: var(--space-3);
border-bottom: 2px solid var(--color-primary);
}
.fpa-agenda__table {
width: 100%;
min-width: 520px;
border-collapse: collapse;
font-size: var(--text-sm);
}
.fpa-agenda__table th {
text-align: left;
padding: var(--space-3) var(--space-3);
.fpa-agenda__day-date {
font-family: var(--font-heading, inherit);
font-weight: 600;
font-size: clamp(1rem, 2vw, 1.2rem);
font-weight: 800;
letter-spacing: -0.01em;
color: var(--color-primary);
}
.fpa-agenda__day-count {
font-size: var(--text-xs);
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.04em;
letter-spacing: 0.05em;
color: var(--color-text-muted);
}
.fpa-agenda__cards {
list-style: none;
margin: 0;
padding: 0;
display: grid;
grid-template-columns: 1fr;
gap: var(--space-4);
}
@media (min-width: 640px) {
.fpa-agenda__cards {
grid-template-columns: repeat(2, 1fr);
}
}
@media (min-width: 1100px) {
.fpa-agenda__cards {
grid-template-columns: repeat(3, 1fr);
}
}
.fpa-agenda__match {
display: flex;
flex-direction: column;
height: 100%;
background: var(--color-bg-card);
border: 1px solid var(--color-border);
border-radius: var(--inst-radius-lg, 10px);
box-shadow: var(--shadow-sm);
overflow: hidden;
transition:
box-shadow 0.2s ease,
border-color 0.15s ease,
transform 0.2s ease;
}
.fpa-agenda__match:hover {
border-color: color-mix(in srgb, var(--color-secondary) 55%, var(--color-border));
box-shadow: var(--inst-shadow-feature, var(--shadow-md));
transform: translateY(-2px);
}
.fpa-agenda__match-head {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--space-2);
padding: var(--space-3) var(--space-4);
background: var(--inst-surface-muted, var(--color-bg-secondary));
border-bottom: 1px solid var(--color-border);
}
.fpa-agenda__table td {
padding: var(--space-3) var(--space-3);
vertical-align: top;
border-bottom: 1px solid var(--color-border);
color: var(--color-text);
}
.fpa-agenda__table tbody tr:last-child td {
border-bottom: none;
}
.fpa-agenda__when {
white-space: nowrap;
font-variant-numeric: tabular-nums;
}
.fpa-agenda__date {
display: block;
font-weight: 600;
}
.fpa-agenda__time {
display: block;
font-size: var(--text-xs);
color: var(--color-text-muted);
}
.fpa-agenda__match {
min-width: 12rem;
}
.fpa-agenda__team {
display: block;
line-height: 1.35;
}
.fpa-agenda__vs {
display: block;
font-size: var(--text-xs);
color: var(--color-text-muted);
margin: 0.15rem 0;
text-transform: lowercase;
.fpa-agenda__comp {
flex: 1;
min-width: 0;
font-family: var(--font-heading, inherit);
font-size: 0.65rem;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.05em;
color: var(--color-secondary);
line-height: 1.3;
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
}
.fpa-agenda__phase {
display: block;
margin-top: var(--space-2);
font-size: var(--text-xs);
color: var(--color-secondary);
line-height: 1.3;
}
.fpa-agenda__score {
font-variant-numeric: tabular-nums;
font-size: 0.65rem;
font-weight: 600;
padding: 0.15rem 0.5rem;
border-radius: 999px;
background: color-mix(in srgb, var(--color-primary) 10%, var(--color-bg-card));
color: var(--color-primary);
border: 1px solid color-mix(in srgb, var(--color-primary) 20%, transparent);
white-space: nowrap;
}
.fpa-agenda__comp {
max-width: 14rem;
line-height: 1.35;
.fpa-agenda__status {
margin-left: auto;
font-family: var(--font-heading, inherit);
font-size: 0.6rem;
font-weight: 800;
text-transform: uppercase;
letter-spacing: 0.08em;
padding: 0.2rem 0.55rem;
border-radius: 4px;
background: color-mix(in srgb, var(--color-secondary) 14%, var(--color-bg-card));
color: var(--color-secondary);
border: 1px solid color-mix(in srgb, var(--color-secondary) 25%, transparent);
white-space: nowrap;
}
.fpa-agenda__credit {
margin: 0;
.fpa-agenda__status--finished {
background: color-mix(in srgb, var(--color-primary) 12%, var(--color-bg-card));
color: var(--color-primary);
border-color: color-mix(in srgb, var(--color-primary) 22%, transparent);
}
.fpa-agenda__faceoff {
display: grid;
grid-template-columns: 1fr auto 1fr;
align-items: center;
gap: var(--space-3);
padding: var(--space-5) var(--space-4) var(--space-4);
}
.fpa-agenda__side {
display: flex;
flex-direction: column;
align-items: center;
gap: var(--space-2);
min-width: 0;
text-align: center;
}
.fpa-agenda__crest {
display: flex;
align-items: center;
justify-content: center;
width: 2.75rem;
height: 2.75rem;
border-radius: 50%;
font-family: var(--font-heading, inherit);
font-size: 0.8rem;
font-weight: 800;
letter-spacing: 0.02em;
color: #fff;
background: linear-gradient(
145deg,
var(--color-primary) 0%,
color-mix(in srgb, var(--color-secondary) 70%, var(--color-primary)) 100%
);
box-shadow: 0 4px 12px color-mix(in srgb, var(--color-primary) 25%, transparent);
flex-shrink: 0;
}
.fpa-agenda__side--away .fpa-agenda__crest {
background: linear-gradient(
145deg,
var(--color-secondary) 0%,
color-mix(in srgb, var(--color-primary) 55%, var(--color-secondary)) 100%
);
}
.fpa-agenda__team {
font-family: var(--font-heading, inherit);
font-size: var(--text-sm);
font-weight: 700;
line-height: 1.25;
letter-spacing: -0.01em;
color: var(--color-text);
display: -webkit-box;
-webkit-line-clamp: 2;
-webkit-box-orient: vertical;
overflow: hidden;
word-break: break-word;
}
.fpa-agenda__center {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-width: 4.5rem;
}
.fpa-agenda__score {
font-family: var(--font-heading, inherit);
font-size: clamp(1.25rem, 3vw, 1.6rem);
font-weight: 900;
font-variant-numeric: tabular-nums;
letter-spacing: -0.02em;
color: var(--color-primary);
padding: var(--space-2) var(--space-3);
border-radius: 8px;
background: color-mix(in srgb, var(--color-primary) 8%, var(--color-bg-card));
border: 1px solid color-mix(in srgb, var(--color-primary) 18%, transparent);
white-space: nowrap;
}
.fpa-agenda__kickoff {
display: flex;
flex-direction: column;
align-items: center;
gap: 0.15rem;
}
.fpa-agenda__kickoff-time {
font-family: var(--font-heading, inherit);
font-size: var(--text-lg);
font-weight: 800;
font-variant-numeric: tabular-nums;
color: var(--color-secondary);
padding: var(--space-2) var(--space-3);
border-radius: 8px;
border: 1px dashed color-mix(in srgb, var(--color-secondary) 40%, var(--color-border));
background: var(--color-bg);
white-space: nowrap;
}
.fpa-agenda__meta {
display: flex;
flex-wrap: wrap;
gap: var(--space-3) var(--space-4);
margin-top: auto;
padding: var(--space-3) var(--space-4);
border-top: 1px solid var(--color-border);
font-size: var(--text-xs);
color: var(--color-text-muted);
}
@media (max-width: 640px) {
.fpa-agenda__hide-narrow {
display: none;
}
.fpa-agenda__meta-item {
display: inline-flex;
align-items: center;
gap: var(--space-2);
min-width: 0;
}
.fpa-agenda__table {
min-width: 0;
}
.fpa-agenda__meta-item span:last-child {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
max-width: 14rem;
}
.fpa-agenda__icon {
flex-shrink: 0;
opacity: 0.7;
}
.fpa-agenda__credit {
margin: var(--space-6) 0 0;
font-size: var(--text-xs);
color: var(--color-text-muted);
}
</style>
+3 -3
View File
@@ -36,8 +36,8 @@ WP_ADMIN_PASSWORD=your_password docker compose exec wordpress bash /var/www/html
After setup, the REST API is available at:
```
http://10.10.50.140:8080/wp-json/wp/v2/posts
http://10.10.50.140:8080/wp-json/wp/v2/categories
http://10.10.50.204:8080/wp-json/wp/v2/posts
http://10.10.50.204:8080/wp-json/wp/v2/categories
```
The Fastify bridge (port 3200) proxies these endpoints and adds Redis caching.
@@ -82,7 +82,7 @@ Credenciais: cofre da equipa (nunca em git). Se ainda não existir utilizador ad
Para **restringir** o `/wp-admin/` a utilizadores reais em redes privadas (ou a IPs conhecidos), é preciso outra camada ou `real_ip` bem configurado: `set_real_ip_from` **apenas** para IPs dos proxies de confiança, `real_ip_header X-Forwarded-For`, e depois ajustar `allow` ao resultado — ou controlar acesso no **NPM** / Cloudflare / VPN. Ver `docs/deployment.md` (secção homónima).
**Directo ao LXC:** `http://10.10.50.140:8080/wp-admin/` — o `docker compose` publica `8080` em todas as interfaces por omissão; se não abre, verifica **firewall do CT**, **Proxmox**, e rota VPN até `10.10.50.0/24`.
**Directo ao LXC:** `http://10.10.50.204:8080/wp-admin/` — o `docker compose` publica `8080` em todas as interfaces por omissão; se não abre, verifica **firewall do CT**, **Proxmox**, e rota VPN até `10.10.50.0/24`.
**Redirects do WordPress:** define `WORDPRESS_PUBLIC_URL` no `.env` para o URL público (HTTPS + host). Em produção atrás do Nginx do CT, se ainda estiver o default `http://localhost:8080`, o `WORDPRESS_CONFIG_EXTRA` infere o URL a partir de `Host` e `X-Forwarded-Proto` **desde que** o pedido traga pelo menos um cabeçalho típico de proxy (`X-Forwarded-Proto`, `X-Forwarded-For`, ou `X-Real-IP`). Garante que o Nginx preserva o `X-Forwarded-Proto` enviado pelo NPM (ficheiro `deploy/nginx/newsproject.bitreport.pt.conf`). Acesso directo ao contentor na porta `:8080` sem esses cabeçalhos continua a precisar de `WORDPRESS_PUBLIC_URL` correcto.
+1
View File
@@ -216,6 +216,7 @@ services:
- "8081:80"
volumes:
- wp_andebol_html:/var/www/html:ro
- wp_andebol_content:/var/www/html/wp-content:ro
- ./nginx/wordpress-andebol.conf:/etc/nginx/conf.d/default.conf:ro
healthcheck:
test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1/wp-json/wp/v2/"]
+8
View File
@@ -6,3 +6,11 @@
# Optional: aggregator HTTP service (default 127.0.0.1:3310)
# AGGREGATOR_PORT=3310
# AGGREGATOR_STORE_PATH=/opt/bitreport/news-platform/writer-pipeline/var/aggregated-items.json
# Error hub (errors.bitreport.pt) — see deploy/systemd/writer-andebol.env.example (BIT-25125)
# ERROR_REPORTING_ENDPOINT=https://errors.bitreport.pt
# ERROR_REPORTING_TOKEN=
# ERROR_REPORTING_PROJECT_NAME=news-platform-writer-pipeline
# ERROR_REPORTING_PROJECT_SLUG=news-platform
# ERROR_REPORTING_GITEA_REPO=BitReport.pt/news-platform
# ERROR_REPORTING_DISABLED=1
@@ -9,6 +9,48 @@
"topics": ["handball", "pt", "fpa"],
"note": "FPA portal WordPress main feed."
},
{
"id": "fpa_revista_imprensa",
"kind": "revista_imprensa",
"url": "https://portal.fpa.pt/media/",
"enabled": true,
"topics": ["handball", "pt", "revista", "fpa"],
"maxPdfs": 2,
"pageTimeoutMs": 90000,
"note": "BIT-25559: daily Cision press-clipping PDFs — parse index for PT publisher leads (no PDF republication)."
},
{
"id": "record_andebol_html",
"kind": "html_listing",
"url": "https://www.record.pt/modalidades/andebol",
"enabled": true,
"topics": ["handball", "pt", "media"],
"maxItems": 20,
"pathIncludes": ["/modalidades/andebol/detalhe/"],
"pathExcludes": ["/iniciativas/"],
"note": "BIT-25559: Record andebol section listing (no reliable RSS)."
},
{
"id": "abola_andebol_html",
"kind": "html_listing",
"url": "https://www.abola.pt/andebol",
"enabled": true,
"topics": ["handball", "pt", "media"],
"maxItems": 20,
"pathIncludes": ["/noticias/", "/video/"],
"urlExcludes": ["videocasts", "manifest.json", "rss-"],
"note": "BIT-25559: A Bola andebol hub — handball-scoped article links."
},
{
"id": "zerozero_andebol_html",
"kind": "html_listing",
"url": "https://www.zerozero.pt/andebol/",
"enabled": false,
"topics": ["handball", "pt", "media"],
"maxItems": 15,
"pathIncludes": ["/andebol/"],
"note": "BIT-25559: Cloudflare 403 from pipeline host — enable when fetch path allows; revista PDF covers ZeroZero leads meanwhile."
},
{
"id": "ihf_rss",
"kind": "rss",
@@ -31,9 +73,11 @@
"url": "https://www.eurohandball.com/sitemap.xml",
"enabled": true,
"topics": ["handball", "ehf"],
"maxItems": 25,
"pathIncludes": ["/competitions/", "/news/", "/calendar/", "/match-center/"],
"note": "EHF/Eurohandball: main sitemap is huge; path filter skips /club/ noise; pages fetched for title/summary (no LLM)."
"maxItems": 20,
"pathIncludes": ["/news/", "/match-center/"],
"timeoutMs": 25000,
"pageTimeoutMs": 35000,
"note": "EHF/Eurohandball: main sitemap is huge; path filter keeps news/match pages only (competition index URLs are heavy and not article content — BIT-25342)."
},
{
"id": "record_pt_main",
@@ -42,7 +86,7 @@
"enabled": false,
"maxItems": 25,
"topics": ["pt", "sports", "media"],
"note": "Disabled BIT-22288: main Record feed mixes non-handball sports; shortlist is handball-tagged only. Re-enable only with a verified handball-only RSS (e.g. modalidades/andebol if Record publishes one)."
"note": "Disabled BIT-22288: main Record feed mixes non-handball sports; use record_andebol_html instead (BIT-25559)."
},
{
"id": "sapo_noticias",
@@ -0,0 +1,32 @@
{
"site": "newsproject.bitreport.pt",
"sources": [
{
"id": "record_pt_main",
"kind": "rss",
"url": "https://www.record.pt/rss/",
"enabled": true,
"maxItems": 20,
"topics": ["pt", "sports", "media"],
"note": "newsproject.bitreport.pt — general PT sports demo; not the andebol-only policy (see andebol.net.sources.json)."
},
{
"id": "sapo_noticias",
"kind": "rss",
"url": "https://noticias.sapo.pt/rss",
"enabled": true,
"maxItems": 25,
"topics": ["pt", "national", "international", "media"],
"note": "SAPO highlights; editorial rewrite PT-PT when publishing."
},
{
"id": "bbc_football",
"kind": "rss",
"url": "https://feeds.bbci.co.uk/sport/football/rss.xml",
"enabled": true,
"maxItems": 15,
"topics": ["football", "international", "en"],
"note": "BBC Sport football (EN); site locale is pt-PT — translate in downstream writer."
}
]
}
+35
View File
@@ -9,6 +9,7 @@
"version": "1.0.0",
"dependencies": {
"fastify": "^4.28.1",
"pdf-parse": "^1.1.1",
"rss-parser": "^3.13.0"
},
"devDependencies": {
@@ -593,6 +594,15 @@
"node": ">= 0.6"
}
},
"node_modules/debug": {
"version": "3.2.7",
"resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz",
"integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==",
"license": "MIT",
"dependencies": {
"ms": "^2.1.1"
}
},
"node_modules/entities": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/entities/-/entities-2.2.0.tgz",
@@ -838,6 +848,18 @@
"set-cookie-parser": "^2.4.1"
}
},
"node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"license": "MIT"
},
"node_modules/node-ensure": {
"version": "0.0.0",
"resolved": "https://registry.npmjs.org/node-ensure/-/node-ensure-0.0.0.tgz",
"integrity": "sha512-DRI60hzo2oKN1ma0ckc6nQWlHU69RH6xN0sjQTjMpChPfTYvKZdcQFfdYK2RWbJcKyUizSIy/l8OTGxMAM1QDw==",
"license": "MIT"
},
"node_modules/on-exit-leak-free": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.2.tgz",
@@ -847,6 +869,19 @@
"node": ">=14.0.0"
}
},
"node_modules/pdf-parse": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/pdf-parse/-/pdf-parse-1.1.1.tgz",
"integrity": "sha512-v6ZJ/efsBpGrGGknjtq9J/oC8tZWq0KWL5vQrk2GlzLEQPUDB1ex+13Rmidl1neNN358Jn9EHZw5y07FFtaC7A==",
"license": "MIT",
"dependencies": {
"debug": "^3.1.0",
"node-ensure": "^0.0.0"
},
"engines": {
"node": ">=6.8.1"
}
},
"node_modules/pino": {
"version": "9.14.0",
"resolved": "https://registry.npmjs.org/pino/-/pino-9.14.0.tgz",
+4 -1
View File
@@ -12,10 +12,13 @@
"aggregator": "node dist/aggregator-server.js",
"aggregator:dev": "tsx src/aggregator-server.ts",
"cycle": "node dist/run-cycle.js",
"cycle:dev": "tsx src/run-cycle.ts"
"cycle:dev": "tsx src/run-cycle.ts",
"backfill:featured": "node dist/backfill-featured-from-fpa.js",
"backfill:featured-smart": "node dist/backfill-featured-smart.js"
},
"dependencies": {
"fastify": "^4.28.1",
"pdf-parse": "^1.1.1",
"rss-parser": "^3.13.0"
},
"devDependencies": {
@@ -0,0 +1,156 @@
/**
* Backfill featured images on andebol.net posts by matching FPA source slugs (BIT-24384).
*
* Usage:
* node dist/backfill-featured-from-fpa.js [--dry-run] [--limit N] [--slug one-slug]
*
* Requires ANDEBOL_WP_USER + ANDEBOL_WP_APP_PASSWORD (see wp-site-env.ts).
*/
import { attachFeaturedImageToPost, type WpPublishConfig } from './wp-publish.js';
import { wpCredentialsForSite } from './wp-site-env.js';
const FPA_WP_BASE = 'https://portal.fpa.pt/wp-json';
const SITE_DOMAIN = 'andebol.net';
function argFlag(name: string, argv: string[]): boolean {
return argv.includes(name);
}
function argValue(name: string, argv: string[]): string | undefined {
const i = argv.indexOf(name);
return i >= 0 ? argv[i + 1] : undefined;
}
function wpHeaders(cfg: WpPublishConfig): Record<string, string> {
const auth = Buffer.from(`${cfg.username}:${cfg.appPassword}`, 'utf8').toString('base64');
const h: Record<string, string> = {
Accept: 'application/json',
Authorization: `Basic ${auth}`,
};
if (cfg.siteDomain) h['X-Site-Domain'] = cfg.siteDomain;
return h;
}
function toPublishConfig(creds: ReturnType<typeof wpCredentialsForSite>): WpPublishConfig {
return {
wpBase: creds.wpBase,
username: creds.wpUser,
appPassword: creds.wpPass,
siteDomain: creds.siteDomain ?? SITE_DOMAIN,
};
}
interface WpPostRow {
id: number;
slug: string;
featured_media: number;
}
async function listPostsMissingFeatured(
cfg: WpPublishConfig,
limit: number,
slugFilter?: string,
): Promise<WpPostRow[]> {
const base = cfg.wpBase.replace(/\/$/, '');
const out: WpPostRow[] = [];
let page = 1;
while (out.length < limit) {
const qs = new URLSearchParams({
per_page: '100',
page: String(page),
_fields: 'id,slug,featured_media',
});
if (slugFilter) qs.set('slug', slugFilter);
const res = await fetch(`${base}/wp/v2/posts?${qs}`, {
headers: wpHeaders(cfg),
signal: AbortSignal.timeout(20_000),
});
if (!res.ok) throw new Error(`WP list posts ${res.status}`);
const rows = (await res.json()) as WpPostRow[];
if (rows.length === 0) break;
for (const row of rows) {
if (!row.featured_media) out.push(row);
if (out.length >= limit) break;
}
if (slugFilter || rows.length < 100) break;
page += 1;
}
return out;
}
async function fpaFeaturedForSlug(slug: string): Promise<{ url: string; credit?: string } | null> {
const qs = new URLSearchParams({ slug, _embed: 'wp:featuredmedia' });
const res = await fetch(`${FPA_WP_BASE}/wp/v2/posts?${qs}`, {
headers: { Accept: 'application/json' },
signal: AbortSignal.timeout(15_000),
});
if (!res.ok) return null;
const rows = (await res.json()) as Array<{
title?: { rendered?: string };
_embedded?: { 'wp:featuredmedia'?: Array<{ source_url?: string; alt_text?: string }> };
}>;
const post = rows[0];
const media = post?._embedded?.['wp:featuredmedia']?.[0];
const url = media?.source_url?.trim();
if (!url) return null;
const credit = media?.alt_text?.trim() || undefined;
return { url, credit };
}
async function main(): Promise<void> {
const argv = process.argv.slice(2);
const dryRun = argFlag('--dry-run', argv);
const limit = Math.max(1, parseInt(argValue('--limit', argv) ?? '50', 10));
const slugFilter = argValue('--slug', argv)?.trim();
const creds = wpCredentialsForSite('andebol.net');
if (!creds.wpUser || !creds.wpPass) {
console.error(`Missing credentials: set ${creds.envHint}`);
process.exit(1);
}
const cfg = toPublishConfig(creds);
const posts = await listPostsMissingFeatured(cfg, limit, slugFilter);
console.log(`Posts without featured_media: ${posts.length}${dryRun ? ' (dry-run)' : ''}`);
let updated = 0;
let skipped = 0;
const errors: string[] = [];
for (const post of posts) {
const featured = await fpaFeaturedForSlug(post.slug);
if (!featured) {
skipped += 1;
console.log(`skip ${post.slug}: no FPA featured image`);
continue;
}
if (dryRun) {
console.log(`would attach ${post.slug} <- ${featured.url}`);
updated += 1;
continue;
}
try {
const mediaId = await attachFeaturedImageToPost(
post.id,
featured.url,
cfg,
featured.credit,
);
updated += 1;
console.log(`ok ${post.slug} post=${post.id} media=${mediaId}`);
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
errors.push(`${post.slug}: ${msg}`);
console.error(`fail ${post.slug}: ${msg}`);
}
}
console.log(JSON.stringify({ updated, skipped, errors: errors.length, dryRun }, null, 2));
if (errors.length > 0) process.exit(1);
}
main().catch(e => {
console.error(e);
process.exit(1);
});
@@ -0,0 +1,378 @@
/**
* Smart backfill: attach featured images to andebol.net posts using source URL extraction.
*
* Strategy:
* 1. Fetch WP posts without featured_media (with content)
* 2. Extract source URL from post content (FPA, IHF, EHF, Handball-Planet links)
* 3. For FPA sources: query FPA WP API for the article's featured image
* 4. For other sources: scrape og:image from the source page HTML
* 5. For FPA posts without source URL: title-based search on FPA API
* 6. Upload image to WP and set featured_media
*
* Usage:
* node dist/backfill-featured-smart.js [--dry-run] [--limit N] [--post-id N] [--skip-sourceless]
*
* Requires ANDEBOL_WP_USER + ANDEBOL_WP_APP_PASSWORD (see wp-site-env.ts).
* Optional: WRITER_WEBDAV_* for WebDAV archive fallback.
*/
import { attachFeaturedImageToPost, resolveFeaturedImageForDraft, type WpPublishConfig } from './wp-publish.js';
import { wpCredentialsForSite } from './wp-site-env.js';
import { fetchArticleHtmlForMeta } from './legacy-fetch.js';
import { absolutizeImageUrl, extractFeaturedImageFromHtml } from './html-meta.js';
import { readWebDavArchiveFromEnv, resolveFeaturedFromWebDavArchive, type WebDavArchiveConfig } from './webdav-archive.js';
const FPA_WP_BASE = 'https://portal.fpa.pt/wp-json';
const SITE_DOMAIN = 'andebol.net';
function argFlag(name: string, argv: string[]): boolean {
return argv.includes(name);
}
function argValue(name: string, argv: string[]): string | undefined {
const i = argv.indexOf(name);
return i >= 0 ? argv[i + 1] : undefined;
}
function wpHeaders(cfg: WpPublishConfig): Record<string, string> {
const auth = Buffer.from(`${cfg.username}:${cfg.appPassword}`, 'utf8').toString('base64');
const h: Record<string, string> = {
Accept: 'application/json',
Authorization: `Basic ${auth}`,
};
if (cfg.siteDomain) h['X-Site-Domain'] = cfg.siteDomain;
return h;
}
function toPublishConfig(creds: ReturnType<typeof wpCredentialsForSite>): WpPublishConfig {
return {
wpBase: creds.wpBase,
username: creds.wpUser,
appPassword: creds.wpPass,
siteDomain: creds.siteDomain ?? SITE_DOMAIN,
};
}
interface WpPostWithContent {
id: number;
slug: string;
featured_media: number;
status: string;
content: { rendered: string };
title: { rendered: string };
}
/** Extract source URLs from post content HTML */
function extractSourceUrls(html: string): { fpa: string[]; other: string[] } {
const fpa: string[] = [];
const other: string[] = [];
const hrefRe = /href="(https?:\/\/[^"]+)"/gi;
let m: RegExpExecArray | null;
while ((m = hrefRe.exec(html)) !== null) {
const url = m[1];
if (/portal\.fpa\.pt/.test(url) && !/\/feed\/?$/.test(url)) {
fpa.push(url);
} else if (!/andebol\.net/.test(url) && !/wordpress\.org/.test(url)) {
other.push(url);
}
}
// Dedupe
return {
fpa: [...new Set(fpa)],
other: [...new Set(other)],
};
}
async function listPostsMissingFeatured(cfg: WpPublishConfig, limit: number): Promise<WpPostWithContent[]> {
const base = cfg.wpBase.replace(/\/$/, '');
const out: WpPostWithContent[] = [];
let page = 1;
while (out.length < limit) {
const qs = new URLSearchParams({
per_page: '100',
page: String(page),
status: 'publish',
_fields: 'id,slug,featured_media,status,content,title',
});
const res = await fetch(`${base}/wp/v2/posts?${qs}`, {
headers: wpHeaders(cfg),
signal: AbortSignal.timeout(20_000),
});
if (!res.ok) throw new Error(`WP list posts ${res.status}: ${await res.text().catch(() => '')}`);
const rows = (await res.json()) as WpPostWithContent[];
if (rows.length === 0) break;
for (const row of rows) {
if (!row.featured_media && row.status === 'publish') {
out.push(row);
}
if (out.length >= limit) break;
}
if (rows.length < 100) break;
page += 1;
}
return out;
}
/** Fetch FPA featured image by article URL (not slug) */
async function fpaFeaturedForUrl(fpaUrl: string): Promise<{ url: string; credit?: string } | null> {
// Try to get the FPA post by its URL
const parsed = new URL(fpaUrl);
const pathParts = parsed.pathname.replace(/^\/|\/$/g, '').split('/');
// FPA URLs are like /2026/06/slug/ — extract the last path segment as potential slug
const slug = pathParts[pathParts.length - 1] || pathParts[pathParts.length - 2];
if (!slug) return null;
// Try searching by slug
const qs = new URLSearchParams({ slug, _embed: 'wp:featuredmedia' });
const res = await fetch(`${FPA_WP_BASE}/wp/v2/posts?${qs}`, {
headers: { Accept: 'application/json' },
signal: AbortSignal.timeout(15_000),
});
if (!res.ok) return null;
const rows = (await res.json()) as Array<{
link?: string;
_embedded?: { 'wp:featuredmedia'?: Array<{ source_url?: string; alt_text?: string }> };
}>;
// Find the row that matches our URL
const match = rows.find(r => r.link && r.link.replace(/\/$/, '') === fpaUrl.replace(/\/$/, ''));
if (!match && rows.length > 0) {
// Slug search might return a different article; try first result as best match
const first = rows[0];
const media = first?._embedded?.['wp:featuredmedia']?.[0];
const url = media?.source_url?.trim();
if (url) {
return { url, credit: media?.alt_text?.trim() || undefined };
}
return null;
}
const media = match?._embedded?.['wp:featuredmedia']?.[0];
const url = media?.source_url?.trim();
if (!url) return null;
return { url, credit: media?.alt_text?.trim() || undefined };
}
/** Search FPA by title keywords */
async function fpaFeaturedForTitle(title: string): Promise<{ url: string; credit?: string } | null> {
// Extract key words from title
const clean = title
.replace(/<[^>]+>/g, '')
.replace(/[^\wÀ-ÿ\s]/g, ' ')
.replace(/\s+/g, ' ')
.trim();
const search = clean.split(/\s+/).slice(0, 6).join('+');
const qs = new URLSearchParams({
search,
per_page: '5',
_embed: 'wp:featuredmedia',
});
const res = await fetch(`${FPA_WP_BASE}/wp/v2/posts?${qs}`, {
headers: { Accept: 'application/json' },
signal: AbortSignal.timeout(15_000),
});
if (!res.ok) return null;
const rows = (await res.json()) as Array<{
title?: { rendered?: string };
_embedded?: { 'wp:featuredmedia'?: Array<{ source_url?: string; alt_text?: string }> };
}>;
if (rows.length === 0) return null;
const media = rows[0]._embedded?.['wp:featuredmedia']?.[0];
const url = media?.source_url?.trim();
if (!url) return null;
return { url, credit: media?.alt_text?.trim() || undefined };
}
/** Scrape og:image from a non-FPA source URL */
async function scrapeFeaturedFromUrl(sourceUrl: string): Promise<{ url: string; credit?: string } | null> {
const html = await fetchArticleHtmlForMeta(sourceUrl);
if (!html) return null;
const parsed = extractFeaturedImageFromHtml(html);
if (!parsed.url) return null;
const abs = absolutizeImageUrl(parsed.url, sourceUrl);
if (!abs) return null;
return { url: abs, credit: parsed.credit };
}
async function main(): Promise<void> {
const argv = process.argv.slice(2);
const dryRun = argFlag('--dry-run', argv);
const limit = Math.max(1, parseInt(argValue('--limit', argv) ?? '200', 10));
const postIdFilter = argValue('--post-id', argv) ? parseInt(argValue('--post-id', argv)!, 10) : undefined;
const skipSourceless = argFlag('--skip-sourceless', argv);
const creds = wpCredentialsForSite('andebol.net');
if (!creds.wpUser || !creds.wpPass) {
console.error(`Missing credentials: set ${creds.envHint}`);
process.exit(1);
}
const cfg = toPublishConfig(creds);
// Optional WebDAV fallback
let webDavCfg: WebDavArchiveConfig | null = null;
try {
webDavCfg = readWebDavArchiveFromEnv();
} catch {
// WebDAV not configured — that's fine
}
console.log(`=== Smart Backfill: Featured Images for andebol.net ===`);
console.log(`Mode: ${dryRun ? 'DRY-RUN' : 'LIVE'}`);
console.log(`WebDAV: ${webDavCfg ? 'configured' : 'not configured'}`);
console.log();
const posts = await listPostsMissingFeatured(cfg, limit);
console.log(`Published posts without featured_media: ${posts.length}\n`);
let updated = 0;
let skipped = 0;
let failed = 0;
const errors: string[] = [];
for (const post of posts) {
if (postIdFilter && post.id !== postIdFilter) continue;
const title = post.title.rendered.replace(/<[^>]+>/g, '').trim();
console.log(`\n[${post.id}] ${post.slug}`);
console.log(` Title: ${title.slice(0, 80)}${title.length > 80 ? '…' : ''}`);
// Step 1: Extract source URLs from content
const content = post.content?.rendered || '';
const sources = extractSourceUrls(content);
let imageUrl: string | undefined;
let imageCredit: string | undefined;
let imageSource: string = 'none';
// Step 2: Try FPA source URL
if (sources.fpa.length > 0) {
const fpaUrl = sources.fpa[0];
console.log(` Source (FPA): ${fpaUrl}`);
const featured = await fpaFeaturedForUrl(fpaUrl);
if (featured) {
imageUrl = featured.url;
imageCredit = featured.credit;
imageSource = 'fpa-url';
console.log(` → Found FPA featured image: ${featured.url.slice(0, 70)}…`);
} else {
console.log(` → FPA article has no featured image`);
}
}
// Step 3: Try other source URLs (IHF, EHF, Handball-Planet) for og:image
if (!imageUrl && sources.other.length > 0) {
for (const srcUrl of sources.other.slice(0, 3)) {
console.log(` Source (other): ${srcUrl}`);
const featured = await scrapeFeaturedFromUrl(srcUrl);
if (featured) {
imageUrl = featured.url;
imageCredit = featured.credit || imageCredit;
imageSource = 'og-image';
console.log(` → Found og:image: ${featured.url.slice(0, 70)}…`);
break;
}
}
}
// Step 4: Try FPA title search for Portuguese articles
if (!imageUrl && !sources.fpa.length && !sources.other.length) {
// Only search FPA if the title looks Portuguese (contains accented chars or common PT words)
const looksPortuguese = /[àáâãéêíóôõúüç]/i.test(title) ||
/\b(e|de|do|da|no|na|em|para|com|por|segu|campe|selec|nacional|andebol)\b/i.test(title);
if (looksPortuguese && !skipSourceless) {
console.log(` Trying FPA title search for: ${title.slice(0, 50)}`);
const featured = await fpaFeaturedForTitle(title);
if (featured) {
imageUrl = featured.url;
imageCredit = featured.credit;
imageSource = 'fpa-title';
console.log(` → Found via FPA title search: ${featured.url.slice(0, 70)}…`);
}
}
// Step 5: Try WebDAV archive
if (!imageUrl && webDavCfg && !skipSourceless) {
console.log(` Trying WebDAV archive`);
try {
const davResult = await resolveFeaturedFromWebDavArchive(webDavCfg, {
id: `backfill-${post.id}`,
site: 'andebol.net',
title,
url: `https://andebol.net/${post.slug}/`,
sourceFeedId: 'backfill',
summary: '',
publishedAt: new Date().toISOString(),
ingestedAt: new Date().toISOString(),
});
imageUrl = davResult.url;
imageCredit = davResult.credit;
imageSource = 'webdav';
console.log(` → Found WebDAV image: ${davResult.url.slice(0, 70)}…`);
} catch (e) {
console.log(` → WebDAV: ${(e as Error).message}`);
}
}
}
// Step 6: Skip "html" and test posts
if (!imageUrl && /^(html|bit-|test)/i.test(post.slug)) {
console.log(` → Skipping test/html post`);
skipped += 1;
continue;
}
if (!imageUrl) {
if (skipSourceless) {
console.log(` → No image found (skip-sourceless)`);
} else {
console.log(` → No image found from any source`);
}
skipped += 1;
continue;
}
if (dryRun) {
console.log(` → [DRY-RUN] Would attach: ${imageUrl.slice(0, 80)}…`);
updated += 1;
continue;
}
try {
const mediaId = await attachFeaturedImageToPost(
post.id,
imageUrl,
cfg,
imageCredit,
);
updated += 1;
console.log(` → OK: media_id=${mediaId} (source: ${imageSource})`);
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
errors.push(`${post.slug}: ${msg}`);
console.error(` → FAIL: ${msg}`);
failed += 1;
}
}
console.log(`\n=== BACKFILL SUMMARY ===`);
console.log(JSON.stringify({
total: posts.length,
updated,
skipped,
failed,
dryRun,
}, null, 2));
if (errors.length > 0) {
console.error(`\nErrors:\n${errors.join('\n')}`);
process.exit(1);
}
}
main().catch(e => {
console.error(e);
process.exit(1);
});
@@ -0,0 +1,50 @@
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';
import { initReporter, reportMessage, flush } from './lib/errorReporter.js';
import { cycleErrorMessageLevel, reportCycleErrors } from './lib/cycle-error-report.js';
describe('errorReporter', () => {
it('no-ops when disabled without token', async () => {
initReporter({ disabled: true, token: '' });
reportMessage('test ingest failure', 'error', { site: 'andebol.net' });
await flush();
assert.ok(true);
});
});
describe('cycleErrorMessageLevel', () => {
it('downgrades per-page sitemap probe failures to warning', () => {
assert.equal(
cycleErrorMessageLevel(
'sitemap eurohandball_sitemap page (https://www.eurohandball.com/en/competitions/foo/): The operation was aborted due to timeout',
),
'warning',
);
});
it('keeps whole-source sitemap failures as error', () => {
assert.equal(
cycleErrorMessageLevel('sitemap eurohandball_sitemap (https://www.eurohandball.com/sitemap.xml): HTTP 503'),
'error',
);
});
it('keeps sitemap truncation as warning', () => {
assert.equal(
cycleErrorMessageLevel('sitemap fpa: no pathIncludes and 500 URLs — truncating to 200 before maxItems'),
'warning',
);
});
});
describe('reportCycleErrors', () => {
it('maps ingest error strings without throwing when reporter disabled', async () => {
initReporter({ disabled: true, token: '' });
reportCycleErrors('andebol.net', [
'rss fpa (https://example.com/feed): timeout',
'sitemap fpa: no pathIncludes and 500 URLs — truncating to 200 before maxItems',
]);
await flush();
assert.ok(true);
});
});
+78
View File
@@ -0,0 +1,78 @@
/**
* Extract article URLs from HTML listing pages (Record/A Bola andebol sections).
*/
const HREF_RE = /href=["']([^"']+)["']/gi;
export interface ListingLinkOptions {
/** Keep links whose pathname includes any of these fragments */
pathIncludes?: string[];
/** Drop links whose pathname includes any of these fragments */
pathExcludes?: string[];
/** Drop links whose full URL matches any of these substrings (case-insensitive) */
urlExcludes?: string[];
}
function normalizeHref(href: string, baseUrl: string): string | null {
const trimmed = href.trim();
if (!trimmed || trimmed.startsWith('#') || trimmed.startsWith('javascript:')) return null;
try {
return new URL(trimmed, baseUrl).href;
} catch {
return null;
}
}
function pathMatches(url: string, includes?: string[], excludes?: string[]): boolean {
try {
const path = new URL(url).pathname.toLowerCase();
if (excludes?.some((frag) => path.includes(frag.toLowerCase()))) return false;
if (!includes?.length) return true;
return includes.some((frag) => path.includes(frag.toLowerCase()));
} catch {
return false;
}
}
/**
* Scan listing HTML for unique article links matching path filters.
*/
export function extractListingLinks(
html: string,
listingUrl: string,
options: ListingLinkOptions = {},
): string[] {
const seen = new Set<string>();
const out: string[] = [];
const urlExcludes = options.urlExcludes ?? [];
let m: RegExpExecArray | null;
HREF_RE.lastIndex = 0;
while ((m = HREF_RE.exec(html)) !== null) {
const abs = normalizeHref(m[1], listingUrl);
if (!abs) continue;
const lower = abs.toLowerCase();
if (urlExcludes.some((frag) => lower.includes(frag.toLowerCase()))) continue;
if (!pathMatches(abs, options.pathIncludes, options.pathExcludes)) continue;
if (seen.has(abs)) continue;
seen.add(abs);
out.push(abs);
}
return out;
}
/** Human-readable title from a URL slug (fallback when article HTML is skipped). */
export function titleFromArticleUrl(url: string): string {
try {
const path = new URL(url).pathname;
const slug = path.split('/').filter(Boolean).pop() ?? '';
const base = slug.split('?')[0];
if (!base) return 'Sem título';
return base
.replace(/[-_]+/g, ' ')
.replace(/\b\w/g, (c) => c.toUpperCase())
.trim();
} catch {
return 'Sem título';
}
}
+40
View File
@@ -7,6 +7,13 @@ export interface FetchTextOptions {
accept?: string;
}
export interface FetchBinaryOptions {
timeoutMs?: number;
retries?: number;
userAgent?: string;
headers?: Record<string, string>;
}
function sleep(ms: number): Promise<void> {
return new Promise((r) => setTimeout(r, ms));
}
@@ -43,3 +50,36 @@ export async function fetchTextWithRetry(
}
throw lastErr instanceof Error ? lastErr : new Error(String(lastErr));
}
/**
* GET url as binary with bounded retries (transient network / 5xx).
* Caller validates status, content-type, and size.
*/
export async function fetchBinaryWithRetry(
url: string,
opts: FetchBinaryOptions = {},
): Promise<Response> {
const timeoutMs = opts.timeoutMs ?? 20_000;
const retries = Math.max(0, opts.retries ?? 2);
const ua = opts.userAgent ?? DEFAULT_UA;
const extraHeaders = opts.headers ?? {};
let lastErr: unknown;
for (let attempt = 0; attempt <= retries; attempt += 1) {
try {
const res = await fetch(url, {
redirect: 'follow',
headers: { 'User-Agent': ua, ...extraHeaders },
signal: AbortSignal.timeout(timeoutMs),
});
if (res.status >= 500 && attempt < retries) {
await sleep(400 * (attempt + 1));
continue;
}
return res;
} catch (e) {
lastErr = e;
if (attempt < retries) await sleep(500 * (attempt + 1));
}
}
throw lastErr instanceof Error ? lastErr : new Error(String(lastErr));
}
@@ -0,0 +1,97 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
extractListingLinks,
titleFromArticleUrl,
} from './html-listing.js';
import {
extractRevistaPdfUrls,
isHandballRevistaLead,
leadUrlForRevistaEntry,
parseRevistaIndexText,
publishedAtFromPtDate,
pdfDateFromRevistaUrl,
resolvePublisherUrl,
} from './revista-imprensa.js';
const RECORD_SNIPPET = `
<a href="/modalidades/andebol/detalhe/quatro-portugueses-nomeados?ref=x">A</a>
<a href="/modalidades/andebol/detalhe/benfica-oficializa-saida?ref=x">B</a>
<a href="/iniciativas/c-studio/detalhe/comercial">C</a>
`;
test('extractListingLinks keeps andebol detalhe URLs and drops iniciativas', () => {
const links = extractListingLinks(RECORD_SNIPPET, 'https://www.record.pt/modalidades/andebol', {
pathIncludes: ['/modalidades/andebol/detalhe/'],
pathExcludes: ['/iniciativas/'],
});
assert.equal(links.length, 2);
assert.ok(links[0].includes('quatro-portugueses-nomeados'));
assert.ok(links[1].includes('benfica-oficializa-saida'));
});
test('titleFromArticleUrl humanizes slug', () => {
const title = titleFromArticleUrl(
'https://www.record.pt/modalidades/andebol/detalhe/benfica-oficializa-saida-de-jota-gonzalez',
);
assert.ok(title.toLowerCase().includes('benfica'));
});
test('parseRevistaIndexText extracts numbered index lines', () => {
const sample = `
Revista de Imprensa
1. Marienses vence por falta de comparência do Afifense, Açoriano Oriental, 17/06/20261
2. ANDEBOL - Portugueses nomeados para distinções europeias, Bola (A), 17/06/20262
6. Académica fecha época no Arrabal, Diário de Coimbra, 17/06/20266
18. ANDEBOL - EHF nomeia quarteto luso, Record, 17/06/202619
A1
`;
const entries = parseRevistaIndexText(sample);
assert.equal(entries.length, 4);
assert.equal(entries[1].title, 'ANDEBOL - Portugueses nomeados para distinções europeias');
assert.equal(entries[1].source, 'Bola (A)');
assert.equal(entries[3].source, 'Record');
});
test('resolvePublisherUrl maps Record and A Bola', () => {
assert.equal(resolvePublisherUrl('Record Online'), 'https://www.record.pt/');
assert.equal(resolvePublisherUrl('Bola (A)'), 'https://www.abola.pt/');
});
test('leadUrlForRevistaEntry uses publisher host with stable path', () => {
const url = leadUrlForRevistaEntry('Record', 'https://portal.fpa.pt/media/x.pdf', {
index: 18,
title: 'EHF',
source: 'Record',
date: '17/06/2026',
});
assert.ok(url.startsWith('https://www.record.pt/'));
assert.ok(url.includes('17-06-2026'));
});
test('extractRevistaPdfUrls finds absolute and relative PDF hrefs', () => {
const html = `
<a href="https://portal.fpa.pt/wp-content/uploads/2026/06/Revista-de-Imprensa-18.06.2026.pdf">x</a>
<a href="/wp-content/uploads/2026/06/Revista-de-Imprensa-17.06.2026.pdf">y</a>
`;
const urls = extractRevistaPdfUrls(html, 'https://portal.fpa.pt/media/');
assert.equal(urls.length, 2);
assert.ok(urls[0].includes('18.06.2026'));
});
test('publishedAtFromPtDate parses DD/MM/YYYY', () => {
const iso = publishedAtFromPtDate('17/06/2026', '2026-01-01T00:00:00.000Z');
assert.equal(iso.slice(0, 10), '2026-06-17');
});
test('pdfDateFromRevistaUrl parses filename date', () => {
assert.equal(
pdfDateFromRevistaUrl('https://portal.fpa.pt/wp-content/uploads/2026/06/Revista-de-Imprensa-18.06.2026.pdf'),
'2026-06-18',
);
});
test('isHandballRevistaLead detects andebol keywords', () => {
assert.equal(isHandballRevistaLead('Quatro andebolistas lusos', 'Golo FM'), true);
assert.equal(isHandballRevistaLead('Nuno Mendes otimista', 'Record'), false);
});
@@ -0,0 +1,60 @@
/**
* Tests for RSS media:content and media:thumbnail extraction (BIT-24388).
*/
import { describe, it } from 'node:test';
import assert from 'node:assert';
describe('RSS media extraction', () => {
it('should extract media:content URL from FPA feed items', async () => {
// This test verifies that the RSS parser is configured to extract media:content
// and that the ingestion logic properly handles it.
// The actual feed fetching is tested in integration tests.
// Sample media:content structure as returned by rss-parser
const sampleMediaContent = {
$: {
url: 'https://portal.fpa.pt/wp-content/uploads/2026/06/Banner_Convocatoria.jpg',
medium: 'image'
}
};
assert.strictEqual(sampleMediaContent.$.medium, 'image');
assert.ok(sampleMediaContent.$.url.startsWith('https://'));
});
it('should extract media:thumbnail URL from BBC feed items', async () => {
// Sample media:thumbnail structure as returned by rss-parser
const sampleMediaThumbnail = {
$: {
width: '240',
height: '134',
url: 'https://ichef.bbci.co.uk/ace/standard/240/cpsprodpb/ddc9/live/4a0b8080-5815-11ef-aebc-6de4d31bf5cd.jpg'
}
};
assert.ok(sampleMediaThumbnail.$.url.startsWith('https://'));
assert.strictEqual(sampleMediaThumbnail.$.width, '240');
assert.strictEqual(sampleMediaThumbnail.$.height, '134');
});
it('should prefer enclosure over media:content when both present', async () => {
// This documents the priority order: enclosure > media:content > media:thumbnail
// The implementation in ingest-sources.ts follows this order.
const enclosure = { url: 'https://example.com/enclosure.jpg', type: 'image/jpeg' };
const mediaContent = { $: { url: 'https://example.com/media.jpg', medium: 'image' } };
const mediaThumbnail = { $: { url: 'https://example.com/thumb.jpg' } };
// Priority: enclosure should be checked first
assert.ok(enclosure.url);
assert.ok(enclosure.type?.startsWith('image/'));
// Fallback to media:content
assert.ok(mediaContent.$.url);
assert.strictEqual(mediaContent.$.medium, 'image');
// Fallback to media:thumbnail
assert.ok(mediaThumbnail.$.url);
});
});
+150 -4
View File
@@ -1,7 +1,7 @@
import Parser from 'rss-parser';
import type { AggregatedItem, IngestSource, SiteSourcesConfig, SourceKind, StoreFile } from './types.js';
import { canonicalUrl, itemId, upsertItem } from './store.js';
import { fetchTextWithRetry } from './http-retry.js';
import { fetchBinaryWithRetry, fetchTextWithRetry } from './http-retry.js';
import { extractTitleAndSummary, extractFeaturedImageFromHtml, absolutizeImageUrl } from './html-meta.js';
import {
isSitemapIndexXml,
@@ -10,8 +10,24 @@ import {
parseUrlsetEntries,
type SitemapUrlEntry,
} from './sitemap-parse.js';
import { extractListingLinks, titleFromArticleUrl } from './html-listing.js';
import {
extractRevistaPdfUrls,
isHandballRevistaLead,
leadUrlForRevistaEntry,
parseRevistaPdfBuffer,
pdfDateFromRevistaUrl,
publishedAtFromPtDate,
} from './revista-imprensa.js';
const parser = new Parser();
const parser = new Parser({
customFields: {
item: [
['media:content', 'mediaContent'],
['media:thumbnail', 'mediaThumbnail'],
],
},
});
const SITEMAP_MAX_CHILD_SITEMAPS = 10;
const SITEMAP_LOOSE_CAP = 250;
@@ -191,11 +207,17 @@ export async function ingestAllSources(
if (!link) continue;
const title = (entry.title || 'Sem título').replace(/\s+/g, ' ').trim();
const summary = pickSummary(entry);
const publishedAt = entry.isoDate || entry.pubDate || entry.date || now;
const publishedAt = entry.isoDate || entry.pubDate || now;
const enc = (entry as { enclosure?: { url?: string; type?: string } }).enclosure;
const mediaContent = (entry as { mediaContent?: { $?: { url?: string; medium?: string } } }).mediaContent;
const mediaThumbnail = (entry as { mediaThumbnail?: { $?: { url?: string } } }).mediaThumbnail;
let featured: { url?: string; credit?: string } | undefined;
if (enc?.url && enc.type?.toLowerCase().startsWith('image/')) {
featured = { url: enc.url };
} else if (mediaContent?.$?.url && mediaContent?.$?.medium === 'image') {
featured = { url: mediaContent.$.url };
} else if (mediaThumbnail?.$?.url) {
featured = { url: mediaThumbnail.$.url };
}
const item = buildItem(
config.site,
@@ -253,6 +275,129 @@ export async function ingestAllSources(
continue;
}
if (kind === 'html_listing') {
attempted += 1;
try {
const html = await fetchTextWithRetry(source.url, {
timeoutMs,
retries,
accept: 'text/html, application/xhtml+xml, */*',
});
const links = extractListingLinks(html, source.url, {
pathIncludes: source.pathIncludes,
pathExcludes: source.pathExcludes,
urlExcludes: source.urlExcludes,
});
const maxItems = source.maxItems ?? 25;
const slice = links.slice(0, maxItems);
if (!slice.length) {
succeeded += 1;
errors.push(`html_listing ${source.id}: no article links after filters`);
continue;
}
const pageTimeoutMs = source.pageTimeoutMs ?? source.timeoutMs ?? 20000;
let ok = 0;
for (const link of slice) {
try {
const pageHtml = await fetchTextWithRetry(link, {
timeoutMs: pageTimeoutMs,
retries,
accept: 'text/html, application/xhtml+xml, */*',
});
const { title, summary } = extractTitleAndSummary(pageHtml);
const img = extractFeaturedImageFromHtml(pageHtml);
const item = buildItem(
config.site,
source,
link,
title || titleFromArticleUrl(link),
summary || '(sem resumo)',
now,
now,
'html_listing',
img.url ? { url: img.url, credit: img.credit } : undefined,
);
const { store: next, isNew } = upsertItem(current, item);
current = next;
if (isNew) newItems += 1;
ok += 1;
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
errors.push(`html_listing ${source.id} page (${link}): ${msg}`);
}
}
if (ok > 0) succeeded += 1;
else failed += 1;
} catch (e) {
failed += 1;
const msg = e instanceof Error ? e.message : String(e);
errors.push(`html_listing ${source.id} (${source.url}): ${msg}`);
}
continue;
}
if (kind === 'revista_imprensa') {
attempted += 1;
try {
const html = await fetchTextWithRetry(source.url, {
timeoutMs,
retries,
accept: 'text/html, application/xhtml+xml, */*',
});
const pdfUrls = extractRevistaPdfUrls(html, source.url);
const maxPdfs = source.maxPdfs ?? 3;
const pdfs = pdfUrls.slice(0, maxPdfs);
if (!pdfs.length) {
succeeded += 1;
errors.push(`revista_imprensa ${source.id}: no Revista-de-Imprensa PDF links on page`);
continue;
}
let ok = 0;
for (const pdfUrl of pdfs) {
try {
const res = await fetchBinaryWithRetry(pdfUrl, { timeoutMs: source.pageTimeoutMs ?? 60000, retries });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const buf = Buffer.from(await res.arrayBuffer());
const entries = await parseRevistaPdfBuffer(buf);
const pdfFileDate = pdfDateFromRevistaUrl(pdfUrl);
const pdfPublishedBase =
pdfFileDate ? `${pdfFileDate}T18:00:00.000Z` : now;
for (const entry of entries) {
const leadUrl = leadUrlForRevistaEntry(entry.source, pdfUrl, entry);
const publishedAt = pdfFileDate ? pdfPublishedBase : publishedAtFromPtDate(entry.date, now);
const summary = `Fonte: ${entry.source} (${entry.date}). Lead da Revista de Imprensa FPA — reescrever; não republicar PDF.`;
const item = buildItem(
config.site,
source,
leadUrl,
entry.title,
summary,
publishedAt,
now,
'revista_imprensa',
);
if (source.topics?.length) item.topics = [...source.topics];
else item.topics = ['handball', 'pt', 'revista'];
const { store: next, isNew } = upsertItem(current, item);
current = next;
if (isNew) newItems += 1;
}
ok += 1;
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
errors.push(`revista_imprensa ${source.id} pdf (${pdfUrl}): ${msg}`);
}
}
if (ok > 0) succeeded += 1;
else failed += 1;
} catch (e) {
failed += 1;
const msg = e instanceof Error ? e.message : String(e);
errors.push(`revista_imprensa ${source.id} (${source.url}): ${msg}`);
}
continue;
}
if (kind === 'sitemap') {
attempted += 1;
try {
@@ -272,11 +417,12 @@ export async function ingestAllSources(
errors.push(`sitemap ${source.id}: no URLs after filters`);
continue;
}
const pageTimeoutMs = source.pageTimeoutMs ?? source.timeoutMs ?? 30000;
let ok = 0;
for (const entry of slice) {
try {
const html = await fetchTextWithRetry(entry.loc, {
timeoutMs,
timeoutMs: pageTimeoutMs,
retries,
accept: 'text/html, application/xhtml+xml, */*',
});
+6 -5
View File
@@ -1,3 +1,5 @@
import { fetchTextWithRetry } from './http-retry.js';
/**
* Raw HTML (capped) for OpenGraph / featured image extraction before publish.
*/
@@ -7,12 +9,11 @@ export async function fetchArticleHtmlForMeta(
maxBytes = 600_000,
): Promise<string | null> {
try {
const res = await fetch(url, {
headers: { 'User-Agent': 'BitReport-news-writer-pipeline/1.0 (featured-image)' },
signal: AbortSignal.timeout(timeoutMs),
const html = await fetchTextWithRetry(url, {
timeoutMs,
retries: 2,
userAgent: 'BitReport-news-writer-pipeline/1.0 (featured-image)',
});
if (!res.ok) return null;
const html = await res.text();
return html.slice(0, maxBytes);
} catch {
return null;
@@ -0,0 +1,35 @@
import { reportError, reportMessage } from './errorReporter.js';
/** Map ingest cycle strings to hub severity (partial sitemap page failures are warnings, not loops). */
export function cycleErrorMessageLevel(message: string): 'warning' | 'error' {
if (!message.startsWith('sitemap')) return 'error';
if (message.includes('truncating')) return 'warning';
// Per-URL HTML probe failed but other pages in the same source may have succeeded.
if (/^sitemap .+ page \(https?:\/\//.test(message)) return 'warning';
return 'error';
}
/** Report writer-pipeline cycle failures to errors.bitreport.pt (ingest, publish, config). */
export function reportCycleErrors(
site: string,
errors: string[],
context: Record<string, unknown> = {},
): void {
for (const message of errors) {
const level = cycleErrorMessageLevel(message);
reportMessage(message, level, {
site,
component: 'writer-pipeline',
...context,
});
}
}
export function reportCycleFailure(site: string, err: unknown, context: Record<string, unknown> = {}): void {
const error = err instanceof Error ? err : new Error(String(err));
reportError(error, {
site,
component: 'writer-pipeline',
...context,
});
}
+138
View File
@@ -0,0 +1,138 @@
/**
* BitReport Error Reporter — lightweight Node.js client for errors.bitreport.pt
*
* Shared implementation with bridge/src/lib/errorReporter.ts (keep in sync).
* Zero dependencies (uses native fetch).
*/
let _token = '';
let _endpoint = 'https://errors.bitreport.pt';
let _disabled = false;
let _projectName = process.env['ERROR_REPORTING_PROJECT_NAME'] || 'news-platform-writer-pipeline';
let _projectSlug = process.env['ERROR_REPORTING_PROJECT_SLUG'] || 'news-platform';
let _giteaRepo = process.env['ERROR_REPORTING_GITEA_REPO'] || 'BitReport.pt/news-platform';
const _queue: Record<string, unknown>[] = [];
let _flushTimer: ReturnType<typeof setTimeout> | null = null;
const BATCH_SIZE = 25;
const FLUSH_MS = 5000;
const TIMEOUT_MS = 8000;
type ReporterOpts = {
token?: string;
endpoint?: string;
disabled?: boolean;
projectName?: string;
projectSlug?: string;
giteaRepo?: string;
};
export function initReporter(opts: ReporterOpts = {}): void {
_token = opts.token || process.env['ERROR_REPORTING_TOKEN'] || '';
_endpoint = (opts.endpoint || process.env['ERROR_REPORTING_ENDPOINT'] || 'https://errors.bitreport.pt').replace(
/\/$/,
'',
);
_disabled = opts.disabled ?? process.env['ERROR_REPORTING_DISABLED'] === '1';
_projectName = opts.projectName || process.env['ERROR_REPORTING_PROJECT_NAME'] || _projectName;
_projectSlug = opts.projectSlug || process.env['ERROR_REPORTING_PROJECT_SLUG'] || _projectSlug;
_giteaRepo = opts.giteaRepo || process.env['ERROR_REPORTING_GITEA_REPO'] || _giteaRepo;
if (!_disabled && _token) {
process.on('uncaughtException', (err: Error) => {
reportError(err, { uncaught: true });
setTimeout(() => {
throw err;
}, 200);
});
process.on('unhandledRejection', (reason: unknown) => {
const err = reason instanceof Error ? reason : new Error(String(reason));
reportError(err, { unhandledRejection: true });
});
}
}
export function reportError(err: Error, context: Record<string, unknown> = {}): void {
if (_disabled || !_token) return;
const msg = err?.message || String(err);
const stack = err?.stack || '';
const fileMatch = stack.match(/at\s+.+?\((.+?):(\d+):\d+\)|at\s+(.+?):(\d+):\d+/);
const filePath = fileMatch?.[1] || fileMatch?.[3] || '';
const lineNumber = parseInt(fileMatch?.[2] || fileMatch?.[4] || '0', 10);
_enqueue({
schema_version: 1,
occurred_at: new Date().toISOString(),
level: 'error',
message: msg,
stacktrace: stack,
context: {
file_path: filePath,
line_number: lineNumber || undefined,
error_type: err?.constructor?.name || 'Error',
error_code: (err as NodeJS.ErrnoException)?.code || undefined,
project_name: _projectName,
project_slug: _projectSlug,
gitea_repo: _giteaRepo,
...context,
},
});
}
export function reportMessage(
message: string,
level: 'error' | 'warning' | 'info' | 'critical' = 'error',
context: Record<string, unknown> = {},
): void {
if (_disabled || !_token) return;
_enqueue({
schema_version: 1,
occurred_at: new Date().toISOString(),
level,
message,
context: { project_name: _projectName, project_slug: _projectSlug, gitea_repo: _giteaRepo, ...context },
});
}
export async function flush(): Promise<void> {
if (_flushTimer) {
clearTimeout(_flushTimer);
_flushTimer = null;
}
while (_queue.length > 0) {
const batch = _queue.splice(0, BATCH_SIZE);
await _send(batch);
}
}
function _enqueue(event: Record<string, unknown>): void {
_queue.push(event);
if (_queue.length >= BATCH_SIZE) {
void flush().catch(() => {});
} else if (!_flushTimer) {
_flushTimer = setTimeout(() => {
_flushTimer = null;
void flush().catch(() => {});
}, FLUSH_MS);
if (_flushTimer.unref) _flushTimer.unref();
}
}
async function _send(events: Record<string, unknown>[]): Promise<void> {
if (!events.length) return;
try {
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), TIMEOUT_MS);
await fetch(`${_endpoint}/v1/ingest/events`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${_token}`,
},
body: JSON.stringify({ events }),
signal: ctrl.signal,
});
clearTimeout(timer);
} catch {
// Fire-and-forget: never crash the host app
}
}
+137
View File
@@ -0,0 +1,137 @@
/**
* Parse FPA "Revista de Imprensa" press-clipping PDFs into story leads (BIT-25559).
* PDFs are ingested for metadata only — we do not republish the PDF.
*/
import { createRequire } from 'node:module';
const require = createRequire(import.meta.url);
const pdfParse = require('pdf-parse') as (buffer: Buffer) => Promise<{ text?: string; numpages?: number }>;
export interface RevistaEntry {
index: number;
title: string;
source: string;
date: string;
}
const DATE_TAIL_RE = /,\s*(\d{2}\/\d{2}\/\d{4})\d*$/;
const ENTRY_START_RE = /^\s*(\d+)\.\s+/;
/** Map clipping source labels to a PT publisher home URL (for dedup + bridge host diversity). */
const SOURCE_HOST_MAP: Array<{ pattern: RegExp; url: string }> = [
{ pattern: /\brecord\b/i, url: 'https://www.record.pt/' },
{ pattern: /\bbola\b|\ba bola\b/i, url: 'https://www.abola.pt/' },
{ pattern: /\bzero\s*zero\b/i, url: 'https://www.zerozero.pt/' },
{ pattern: /\bjogo\b/i, url: 'https://www.record.pt/' },
{ pattern: /\bojogo\b/i, url: 'https://www.ojogo.pt/' },
{ pattern: /\bexpresso\b/i, url: 'https://expresso.pt/' },
{ pattern: /\bpublico\b|\bpúblico\b/i, url: 'https://www.publico.pt/' },
{ pattern: /\bdn\b|diário de notícias/i, url: 'https://www.dn.pt/' },
];
const REVISTA_PDF_RE =
/https?:\/\/[^\s"'<>]*\/wp-content\/uploads\/[^"'<>]*Revista-de-Imprensa[^"'<>]*\.pdf/gi;
const REVISTA_PDF_REL_RE = /\/wp-content\/uploads\/[^"'<>]*Revista-de-Imprensa[^"'<>]*\.pdf/gi;
export function resolvePublisherUrl(sourceLabel: string): string {
const label = sourceLabel.trim();
for (const { pattern, url } of SOURCE_HOST_MAP) {
if (pattern.test(label)) return url;
}
return 'https://portal.fpa.pt/media/';
}
export function leadUrlForRevistaEntry(
sourceLabel: string,
pdfCanonicalUrl: string,
entry: RevistaEntry,
): string {
const base = resolvePublisherUrl(sourceLabel);
try {
const u = new URL(base);
u.pathname = `${u.pathname.replace(/\/$/, '')}/revista-imprensa/${entry.date.replace(/\//g, '-')}/${entry.index}`;
return u.href;
} catch {
return `${pdfCanonicalUrl}#item-${entry.index}`;
}
}
export function parseRevistaIndexText(text: string): RevistaEntry[] {
const normalized = text.replace(/\r\n/g, '\n');
const indexSection = normalized.split(/\n\s*A1\b/i)[0] ?? normalized;
const blocks = indexSection.split(/(?=^\s*\d+\.\s+)/m).filter((b) => ENTRY_START_RE.test(b));
const entries: RevistaEntry[] = [];
for (const block of blocks) {
const start = block.match(ENTRY_START_RE);
if (!start) continue;
const index = parseInt(start[1], 10);
let body = block.replace(ENTRY_START_RE, '').replace(/\s+/g, ' ').trim();
body = body.replace(/\s+\d+\s*$/, '').trim();
const dateMatch = body.match(DATE_TAIL_RE);
if (!dateMatch) continue;
const date = dateMatch[1];
const beforeDate = body.slice(0, dateMatch.index).trim();
const lastComma = beforeDate.lastIndexOf(',');
if (lastComma < 0) continue;
const title = beforeDate.slice(0, lastComma).trim();
const source = beforeDate.slice(lastComma + 1).trim();
if (!title || !source) continue;
entries.push({ index, title, source, date });
}
return entries;
}
export function isHandballRevistaLead(title: string, source: string): boolean {
const hay = `${title} ${source}`.toLowerCase();
return /andebol|handball|\behf\b|liga dos campeões de andebol|fpa\b/.test(hay);
}
export function extractRevistaPdfUrls(html: string, pageUrl: string): string[] {
const seen = new Set<string>();
const out: string[] = [];
const add = (raw: string) => {
try {
const href = new URL(raw, pageUrl).href;
if (!seen.has(href)) {
seen.add(href);
out.push(href);
}
} catch {
/* skip */
}
};
let m: RegExpExecArray | null;
REVISTA_PDF_RE.lastIndex = 0;
while ((m = REVISTA_PDF_RE.exec(html)) !== null) add(m[0]);
REVISTA_PDF_REL_RE.lastIndex = 0;
while ((m = REVISTA_PDF_REL_RE.exec(html)) !== null) add(m[0]);
return out;
}
export async function parseRevistaPdfBuffer(buffer: Buffer): Promise<RevistaEntry[]> {
const data = await pdfParse(buffer);
const text = (data.text ?? '').trim();
if (!text) return [];
return parseRevistaIndexText(text);
}
export function pdfDateFromRevistaUrl(pdfUrl: string): string | null {
const m = pdfUrl.match(/Revista-de-Imprensa-(\d{2})\.(\d{2})\.(\d{4})\.pdf/i);
if (!m) return null;
return `${m[3]}-${m[2]}-${m[1]}`;
}
export function publishedAtFromPtDate(date: string, fallback: string): string {
const m = date.match(/^(\d{2})\/(\d{2})\/(\d{4})$/);
if (!m) return fallback;
const iso = `${m[3]}-${m[2]}-${m[1]}T12:00:00.000Z`;
const d = new Date(iso);
return Number.isNaN(d.getTime()) ? fallback : d.toISOString();
}
+23 -13
View File
@@ -20,6 +20,11 @@ import {
} from './token-metrics.js';
import type { AggregatedItem, CycleMetrics } from './types.js';
import { createDraftFromAggregatedItem } from './wp-publish.js';
import { wpCredentialsForSite } from './wp-site-env.js';
import { initReporter, flush } from './lib/errorReporter.js';
import { reportCycleErrors, reportCycleFailure } from './lib/cycle-error-report.js';
initReporter();
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const PKG_ROOT = path.resolve(__dirname, '..');
@@ -84,19 +89,17 @@ async function main(): Promise<void> {
const errors = [...ingest.errors];
let draftsCreated = 0;
const wpBase = process.env.ANDEBOL_WP_BASE ?? 'http://127.0.0.1:8081/wp-json';
const wpUser = process.env.ANDEBOL_WP_USER ?? '';
const wpPass = process.env.ANDEBOL_WP_APP_PASSWORD ?? '';
const wp = wpCredentialsForSite(site);
if (!dryRun && publishMax > 0 && wpUser && wpPass) {
if (!dryRun && publishMax > 0 && wp.wpUser && wp.wpPass) {
const toPublish = list.slice(0, publishMax);
for (const item of toPublish) {
try {
const { id } = await createDraftFromAggregatedItem(item, {
wpBase,
username: wpUser,
appPassword: wpPass,
siteDomain: process.env.ANDEBOL_WP_SITE_DOMAIN,
wpBase: wp.wpBase,
username: wp.wpUser,
appPassword: wp.wpPass,
siteDomain: wp.siteDomain,
});
draftsCreated += 1;
const updated: AggregatedItem = { ...item, wpDraftId: id };
@@ -107,9 +110,7 @@ async function main(): Promise<void> {
}
await saveStore(storePath, store);
} else if (!dryRun && publishMax > 0) {
errors.push(
'Skipping WP publish: set ANDEBOL_WP_USER and ANDEBOL_WP_APP_PASSWORD (optional ANDEBOL_WP_BASE)',
);
errors.push(`Skipping WP publish: set ${wp.envHint}`);
}
const finishedAt = new Date().toISOString();
@@ -135,10 +136,19 @@ async function main(): Promise<void> {
await appendMetrics(metricsPath, metrics);
console.log(JSON.stringify(metrics, null, 2));
if (errors.length) process.exitCode = 1;
if (errors.length) {
reportCycleErrors(site, errors, { cycleId, dryRun });
await flush();
process.exitCode = 1;
}
}
main().catch((e) => {
main().catch(async (e) => {
console.error(e);
reportCycleFailure(argValue('--site', process.argv.slice(2)) ?? 'andebol.net', e, {
phase: 'run-cycle',
});
await flush();
process.exit(1);
});
+13 -2
View File
@@ -1,4 +1,4 @@
export type SourceKind = 'rss' | 'sitemap' | 'html_fetch';
export type SourceKind = 'rss' | 'sitemap' | 'html_fetch' | 'html_listing' | 'revista_imprensa';
export interface IngestSource {
id: string;
@@ -9,10 +9,21 @@ export interface IngestSource {
note?: string;
/** Cap per-source items (RSS entries, sitemap URLs processed, or single html page). Default: 30 sitemap, 1 html_fetch; RSS uncapped if omitted */
maxItems?: number;
/** For sitemap: keep URLs whose path includes any of these substrings */
/** For sitemap / html_listing: keep URLs whose path includes any of these substrings */
pathIncludes?: string[];
/** For html_listing: drop URLs whose path includes any of these substrings */
pathExcludes?: string[];
/** For html_listing: drop URLs containing these substrings (e.g. sponsored blocks) */
urlExcludes?: string[];
/** For revista_imprensa: max recent PDFs to parse per run (default 3) */
maxPdfs?: number;
/** For revista_imprensa: only store handball-scoped index lines (default true) */
handballOnly?: boolean;
retries?: number;
/** Timeout for fetching the sitemap XML (and RSS/HTML source URL). */
timeoutMs?: number;
/** Timeout for each HTML page fetched from sitemap URL entries (defaults to timeoutMs or 30s). */
pageTimeoutMs?: number;
}
/** @deprecated Use IngestSource with kind rss — kept for legacy JSON configs */
@@ -24,6 +24,15 @@ test('parsePropfindImageHrefs skips collection root and lists image files', () =
assert.equal(rows[0].lastMod, 'Wed, 01 Jan 2025 12:00:00 GMT');
});
test('parsePropfindImageHrefs handles ns0: namespace prefix (WsgiDAV / Python ElementTree)', () => {
const xml = `<?xml version="1.0" encoding="utf-8" ?>
<ns0:multistatus xmlns:ns0="DAV:"><ns0:response><ns0:href>/</ns0:href><ns0:propstat><ns0:prop><ns0:getlastmodified>Thu, 14 May 2026 16:11:04 GMT</ns0:getlastmodified><ns0:resourcetype><ns0:collection /></ns0:resourcetype></ns0:prop><ns0:status>HTTP/1.1 200 OK</ns0:status></ns0:propstat></ns0:response><ns0:response><ns0:href>/Foto_FPA___duplo-embate-croacia-m20-euro.jpg</ns0:href><ns0:propstat><ns0:prop><ns0:getlastmodified>Thu, 14 May 2026 16:11:26 GMT</ns0:getlastmodified><ns0:resourcetype /></ns0:prop><ns0:status>HTTP/1.1 200 OK</ns0:status></ns0:propstat></ns0:response></ns0:multistatus>`;
const rows = parsePropfindImageHrefs(xml, 'http://127.0.0.1:8088/');
assert.equal(rows.length, 1);
assert.match(rows[0].href, /Foto_FPA___duplo-embate-croacia-m20-euro\.jpg$/);
assert.equal(rows[0].lastMod, 'Thu, 14 May 2026 16:11:26 GMT');
});
test('pickBestArchiveImage prefers hrefs whose path matches title tokens', () => {
const item: AggregatedItem = {
id: '1',
+3 -3
View File
@@ -29,14 +29,14 @@ function decodeXmlText(s: string): string {
export function parsePropfindImageHrefs(xml: string, collectionUrl: string): { href: string; lastMod?: string }[] {
const base = new URL(collectionUrl.endsWith('/') ? collectionUrl : `${collectionUrl}/`);
const out: { href: string; lastMod?: string }[] = [];
const reResponse = /<(?:[a-z]+:)?response[^>]*>([\s\S]*?)<\/(?:[a-z]+:)?response>/gi;
const reResponse = /<(?:[a-z][a-z0-9]*:)?response[^>]*>([\s\S]*?)<\/(?:[a-z][a-z0-9]*:)?response>/gi;
let m: RegExpExecArray | null;
while ((m = reResponse.exec(xml))) {
const block = m[1];
const hrefM = /<(?:[a-z]+:)?href>([^<]+)<\/(?:[a-z]+:)?href>/i.exec(block);
const hrefM = /<(?:[a-z][a-z0-9]*:)?href>([^<]+)<\/(?:[a-z][a-z0-9]*:)?href>/i.exec(block);
if (!hrefM) continue;
const hrefRaw = decodeXmlText(hrefM[1].trim());
const lmM = /<(?:[a-z]+:)?getlastmodified>([^<]+)<\/(?:[a-z]+:)?getlastmodified>/i.exec(block);
const lmM = /<(?:[a-z][a-z0-9]*:)?getlastmodified>([^<]+)<\/(?:[a-z][a-z0-9]*:)?getlastmodified>/i.exec(block);
const lastMod = lmM ? decodeXmlText(lmM[1].trim()) : undefined;
if (!IMAGE_EXT_RE.test(hrefRaw)) continue;
let abs: string;
+28 -3
View File
@@ -1,6 +1,7 @@
import { Buffer } from 'node:buffer';
import type { AggregatedItem } from './types.js';
import { fetchArticleHtmlForMeta } from './legacy-fetch.js';
import { fetchBinaryWithRetry } from './http-retry.js';
import { absolutizeImageUrl, extractFeaturedImageFromHtml } from './html-meta.js';
import {
readWebDavArchiveFromEnv,
@@ -131,10 +132,11 @@ async function downloadBinaryImage(
'User-Agent': 'BitReport-news-writer-pipeline/1.0 (media)',
...(extraHeaders ?? {}),
};
const res = await fetch(imageUrl, {
const res = await fetchBinaryWithRetry(imageUrl, {
timeoutMs: 20_000,
retries: 2,
userAgent: headers['User-Agent'],
headers,
signal: AbortSignal.timeout(20_000),
redirect: 'follow',
});
if (!res.ok) {
throw new Error(`Featured image fetch failed ${res.status} for ${imageUrl}`);
@@ -235,6 +237,29 @@ async function resolveCategoryId(
return rows[0]?.id ?? null;
}
/** Attach a rights-cleared featured image to an existing WordPress post (BIT-24384 backfill). */
export async function attachFeaturedImageToPost(
postId: number,
imageUrl: string,
cfg: WpPublishConfig,
credit?: string,
fetchHeaders?: Record<string, string>,
): Promise<number> {
const base = cfg.wpBase.replace(/\/$/, '');
const mediaId = await uploadFeaturedMedia(cfg, base, imageUrl, credit, fetchHeaders);
const res = await fetch(`${base}/wp/v2/posts/${postId}`, {
method: 'POST',
headers: jsonHeaders(cfg),
body: JSON.stringify({ featured_media: mediaId }),
signal: AbortSignal.timeout(20_000),
});
if (!res.ok) {
const errText = await res.text().catch(() => '');
throw new Error(`WP post featured_media patch failed ${res.status}: ${errText.slice(0, 500)}`);
}
return mediaId;
}
export async function createDraftFromAggregatedItem(
item: AggregatedItem,
cfg: WpPublishConfig,
+54
View File
@@ -0,0 +1,54 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { wpCredentialsForSite } from './wp-site-env.js';
const keysNews = [
'NEWSPROJECT_WP_BASE',
'NEWSPROJECT_WP_USER',
'NEWSPROJECT_WP_APP_PASSWORD',
'NEWSPROJECT_WP_SITE_DOMAIN',
] as const;
const keysAndebol = ['ANDEBOL_WP_BASE', 'ANDEBOL_WP_USER', 'ANDEBOL_WP_APP_PASSWORD'] as const;
function snapshotEnv<K extends string>(keys: readonly K[]): Record<K, string | undefined> {
const o = {} as Record<K, string | undefined>;
for (const k of keys) o[k] = process.env[k];
return o;
}
function restoreEnv<K extends string>(snap: Record<K, string | undefined>) {
for (const k of Object.keys(snap) as K[]) {
const v = snap[k];
if (v === undefined) delete process.env[k];
else process.env[k] = v;
}
}
test('wpCredentialsForSite uses NEWSPROJECT_* for newsproject.bitreport.pt', () => {
const snap = snapshotEnv(keysNews);
try {
process.env.NEWSPROJECT_WP_BASE = 'http://example/wp-json';
process.env.NEWSPROJECT_WP_USER = 'u';
process.env.NEWSPROJECT_WP_APP_PASSWORD = 'p';
process.env.NEWSPROJECT_WP_SITE_DOMAIN = 'https://newsproject.bitreport.pt';
const c = wpCredentialsForSite('newsproject.bitreport.pt');
assert.equal(c.wpBase, 'http://example/wp-json');
assert.equal(c.wpUser, 'u');
assert.equal(c.wpPass, 'p');
assert.equal(c.siteDomain, 'https://newsproject.bitreport.pt');
} finally {
restoreEnv(snap);
}
});
test('wpCredentialsForSite defaults andebol WP base to 8081', () => {
const snap = snapshotEnv(keysAndebol);
try {
delete process.env.ANDEBOL_WP_BASE;
delete process.env.ANDEBOL_WP_USER;
const c = wpCredentialsForSite('andebol.net');
assert.equal(c.wpBase, 'http://127.0.0.1:8081/wp-json');
} finally {
restoreEnv(snap);
}
});
+41
View File
@@ -0,0 +1,41 @@
/**
* WordPress REST credentials per writer `--site` (BIT-22288: andebol.net + newsproject).
*/
export interface WpSiteCredentials {
wpBase: string;
wpUser: string;
wpPass: string;
siteDomain: string | undefined;
/** Shown when publish is skipped due to missing secrets */
envHint: string;
}
export function wpCredentialsForSite(site: string): WpSiteCredentials {
if (site === 'newsproject.bitreport.pt') {
const wpBase =
(process.env.NEWSPROJECT_WP_BASE ?? '').trim() || 'http://127.0.0.1:8080/wp-json';
const wpUser = (process.env.NEWSPROJECT_WP_USER ?? '').trim();
const wpPass = (process.env.NEWSPROJECT_WP_APP_PASSWORD ?? '').trim();
const siteDomain = (process.env.NEWSPROJECT_WP_SITE_DOMAIN ?? '').trim() || undefined;
return {
wpBase,
wpUser,
wpPass,
siteDomain,
envHint: 'NEWSPROJECT_WP_USER and NEWSPROJECT_WP_APP_PASSWORD (optional NEWSPROJECT_WP_BASE, NEWSPROJECT_WP_SITE_DOMAIN)',
};
}
const wpBase = (process.env.ANDEBOL_WP_BASE ?? '').trim() || 'http://127.0.0.1:8081/wp-json';
const wpUser = (process.env.ANDEBOL_WP_USER ?? '').trim();
const wpPass = (process.env.ANDEBOL_WP_APP_PASSWORD ?? '').trim();
const siteDomain = (process.env.ANDEBOL_WP_SITE_DOMAIN ?? '').trim() || undefined;
return {
wpBase,
wpUser,
wpPass,
siteDomain,
envHint: 'ANDEBOL_WP_USER and ANDEBOL_WP_APP_PASSWORD (optional ANDEBOL_WP_BASE, ANDEBOL_WP_SITE_DOMAIN)',
};
}