@capagents/forgeqe 3.3.8 → 3.3.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/HOW_TO_USE.md +92 -0
- package/dist/a11y-runtime.mjs +3204 -0
- package/dist/docs-site/docs/area-quality/index.html +90 -2
- package/dist/docs-site/docs/overview/index.html +1 -1
- package/dist/docs-site/docs/search.js +1 -1
- package/dist/forgeqe.js +2215 -2094
- package/dist/template.html +69 -70
- package/dist/web/assets/{3d-force-graph-bqf5EzgX.js → 3d-force-graph-BPsVSYjw.js} +1 -1
- package/dist/web/assets/Agent-DY6pRvcD.js +10 -0
- package/dist/web/assets/{AgentWork-Dqa1UKaU.js → AgentWork-Brch_Mn3.js} +1 -1
- package/dist/web/assets/ApiTests-BtWKVPw5.js +17 -0
- package/dist/web/assets/{Browse-W54t28gX.js → Browse-DbIFxsy8.js} +1 -1
- package/dist/web/assets/Chat-BWiH0XGV.js +3 -0
- package/dist/web/assets/{CommandPalette-DnIxy2ga.js → CommandPalette-DfoEUEL6.js} +1 -1
- package/dist/web/assets/{Compare-VdisgqmY.js → Compare-DTZ_BW1P.js} +1 -1
- package/dist/web/assets/Cost-DDghPWch.js +1 -0
- package/dist/web/assets/Data-DZlKsTwA.js +6 -0
- package/dist/web/assets/Desktop-DTIZ62Pi.js +1 -0
- package/dist/web/assets/DesktopReview-B8-dSGJH.js +2 -0
- package/dist/web/assets/Evidence-BYw_Q4Ul.js +1 -0
- package/dist/web/assets/Explore-BL_c5WK1.js +2 -0
- package/dist/web/assets/{Features-CIhQJMAK.js → Features-DrFNrvbh.js} +1 -1
- package/dist/web/assets/Flags-CHrDwhqG.js +2 -0
- package/dist/web/assets/Flaky-DtcLf8h6.js +1 -0
- package/dist/web/assets/Impact-CMU_ijo2.js +3 -0
- package/dist/web/assets/Jobs-BjybdQb_.js +5 -0
- package/dist/web/assets/KindPage-VK-Vgkzv.js +6 -0
- package/dist/web/assets/{LiveDevice-CZZRu6xl.js → LiveDevice-BqL1P33F.js} +1 -1
- package/dist/web/assets/Migration-7BI7iXIv.js +8 -0
- package/dist/web/assets/Mobile-AgAhvlVL.js +1 -0
- package/dist/web/assets/Observability-5r36Xf3d.js +1 -0
- package/dist/web/assets/{OwnItems-BinKnGAs.js → OwnItems-CqCOuvba.js} +4 -4
- package/dist/web/assets/PageAgent-00NQxK49.js +1 -0
- package/dist/web/assets/Product-B75ztJFn.js +6 -0
- package/dist/web/assets/Production-lIUlcjf0.js +1 -0
- package/dist/web/assets/Quality-BlRpB6mx.js +1 -0
- package/dist/web/assets/Readiness-CesaSDtp.js +1 -0
- package/dist/web/assets/Record-CLy9jQ5N.js +1 -0
- package/dist/web/assets/Regression-BjpZrkfK.js +5 -0
- package/dist/web/assets/{RelationGraph-CszRGlEp.js → RelationGraph-ClPBGuMw.js} +1 -1
- package/dist/web/assets/{Reports-BPD6ODz4.js → Reports-Du8SNiHM.js} +2 -2
- package/dist/web/assets/Requirements-Dr1iLoMc.js +2 -0
- package/dist/web/assets/Responsive-DcD6MLzG.js +3 -0
- package/dist/web/assets/{RunDiff-aEt4BZYX.js → RunDiff-cLSFOsfC.js} +1 -1
- package/dist/web/assets/{Settings-D188FdLb.js → Settings-CUT5ggDd.js} +16 -16
- package/dist/web/assets/SiteScan-iUfWBeLV.js +5 -0
- package/dist/web/assets/{Steps-CgQ8E_Vv.js → Steps-DJYwIiDu.js} +2 -2
- package/dist/web/assets/{TestData-Dj73b-hW.js → TestData-DqEcL5o4.js} +2 -2
- package/dist/web/assets/TestManagement-mBcfWTVH.js +4 -0
- package/dist/web/assets/{WhatsNew-D-5E8NFV.js → WhatsNew-DrPf6l9-.js} +1 -1
- package/dist/web/assets/{agentSettingsSheet-5JMUsoLi.js → agentSettingsSheet-DyaVNewv.js} +1 -1
- package/dist/web/assets/api-Dr3U7W5w.js +1 -0
- package/dist/web/assets/{choice-C4-yW2x9.js → choice-W0qOx_1k.js} +1 -1
- package/dist/web/assets/{coverage-pqIlfEP0.js → coverage-DbHm8BUP.js} +3 -3
- package/dist/web/assets/{dataParts-bqVlyE0X.js → dataParts-Bdf97ZOD.js} +3 -3
- package/dist/web/assets/{desktopAppPath-BDSG0kvw.js → desktopAppPath-kQmQOW6a.js} +1 -1
- package/dist/web/assets/{flowTheme-DU5XjJr-.js → flowTheme-CVnIjV_m.js} +1 -1
- package/dist/web/assets/frame-CavkQick.js +13 -0
- package/dist/web/assets/index-BaEsXdFc.css +2 -0
- package/dist/web/assets/index-C1kXcI0E.js +57 -0
- package/dist/web/assets/line-icons-Cwj9OmCz.js +1 -0
- package/dist/web/assets/{logos-P2LOMyTK.js → logos-Cf-Wf5ex.js} +1 -1
- package/dist/web/assets/{markdown-DgUpsCX8.js → markdown-Bvv6oj4v.js} +3 -3
- package/dist/web/assets/{nav-IMBXh0Jg.js → nav-DVPiPhOy.js} +1 -1
- package/dist/web/assets/pageBack-Blig1Uqs.js +3 -0
- package/dist/web/assets/{palette-CeG8IIbL.js → palette-DwrGI2Fp.js} +1 -1
- package/dist/web/assets/{paletteCommands-Isq1rLs-.js → paletteCommands-DOF2o-rv.js} +1 -1
- package/dist/web/assets/parts-DgJ2y_ic.js +1 -0
- package/dist/web/assets/{productParts-ClDOvIlz.js → productParts-B78jij3z.js} +1 -1
- package/dist/web/assets/qualityParts-t5t9kEKG.js +2 -0
- package/dist/web/assets/{recordTest-BBDRjct0.js → recordTest-BbXVOuGZ.js} +1 -1
- package/dist/web/assets/{route-oDy8sV6H.js → route-9BkoTWUE.js} +1 -1
- package/dist/web/assets/{sectionList-B651VPon.js → sectionList-DMyhAqst.js} +1 -1
- package/dist/web/assets/{step-mark-CaKf4dAR.js → step-mark-Bu6fNKW8.js} +1 -1
- package/dist/web/assets/stepper-CE4yOLqn.js +1 -0
- package/dist/web/assets/wizardParts-Bxb9UG5k.js +1 -0
- package/dist/web/index.html +11 -11
- package/docs/ForgeQE-Static-Analysis-Report-4008e9ee.html +207 -0
- package/docs/ForgeQE-Static-Analysis-Report-4008e9ee.pdf +0 -0
- package/docs/user-guide.html +89 -1
- package/forgeqe.example.yaml +1 -1
- package/package.json +2 -2
- package/prompts/brain.md +7 -0
- package/py/forgeqe_engine/cli.py +57 -0
- package/py/forgeqe_engine/diagnostics.py +32 -2
- package/py/forgeqe_engine/logins.py +11 -0
- package/py/forgeqe_engine/persona.py +90 -1
- package/py/forgeqe_engine/scan.py +202 -0
- package/py/forgeqe_engine/seo.py +95 -0
- package/py/forgeqe_engine/seo_analytics.mjs +59 -0
- package/py/forgeqe_engine/seo_facts.mjs +63 -0
- package/py/forgeqe_engine/seo_site.mjs +36 -0
- package/py/forgeqe_engine/service.py +3 -2
- package/dist/web/assets/Agent-8Y47YLdR.js +0 -10
- package/dist/web/assets/ApiTests-BOdFugGs.js +0 -17
- package/dist/web/assets/Chat-DiIxGONU.js +0 -3
- package/dist/web/assets/Cost-qfQZZB7-.js +0 -1
- package/dist/web/assets/Data-CDyRsQ0U.js +0 -6
- package/dist/web/assets/Desktop-DEYZusRQ.js +0 -1
- package/dist/web/assets/DesktopReview-4YU21PCr.js +0 -2
- package/dist/web/assets/Evidence-l0_yQUpE.js +0 -1
- package/dist/web/assets/Explore-DkybdJjI.js +0 -2
- package/dist/web/assets/Flags-OCOPCt4-.js +0 -2
- package/dist/web/assets/Flaky-B9EYZK9j.js +0 -1
- package/dist/web/assets/Impact-BXDjDf_Q.js +0 -3
- package/dist/web/assets/Jobs-COZhEsxq.js +0 -5
- package/dist/web/assets/KindPage-DIeBVPZA.js +0 -6
- package/dist/web/assets/Migration-BTCG2m5B.js +0 -8
- package/dist/web/assets/Mobile-CLT5OlqS.js +0 -1
- package/dist/web/assets/Observability-Nd9uj2hQ.js +0 -1
- package/dist/web/assets/PageAgent-DrELdLct.js +0 -1
- package/dist/web/assets/Product-1SMtAUqO.js +0 -6
- package/dist/web/assets/Production-C5q3LjAR.js +0 -1
- package/dist/web/assets/Quality-DVb1L07l.js +0 -1
- package/dist/web/assets/Readiness-BN1VQDip.js +0 -1
- package/dist/web/assets/Record-C8ohbDBp.js +0 -1
- package/dist/web/assets/Regression-mAzdSpwD.js +0 -5
- package/dist/web/assets/Requirements-D1xVywdV.js +0 -2
- package/dist/web/assets/Responsive-DnK0Myzs.js +0 -3
- package/dist/web/assets/TestManagement-DxPMUroR.js +0 -4
- package/dist/web/assets/api-D_HT-I9y.js +0 -1
- package/dist/web/assets/frame-Dt9QcYNX.js +0 -13
- package/dist/web/assets/index-BdWLAq_n.js +0 -57
- package/dist/web/assets/index-CpAtlS2x.css +0 -2
- package/dist/web/assets/line-icons-CwCZidXs.js +0 -1
- package/dist/web/assets/pageBack-DwhsvsK7.js +0 -3
- package/dist/web/assets/parts-DVUUpFdW.js +0 -1
- package/dist/web/assets/qualityParts-DF3ZMgo5.js +0 -1
- package/dist/web/assets/stepper-uX1iUWez.js +0 -1
- package/dist/web/assets/wizardParts-qs3g8O6h.js +0 -1
|
@@ -142,6 +142,17 @@ def use_logins(logins: List[Login]) -> Tuple[Dict[str, Dict[str, str]], List[str
|
|
|
142
142
|
_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,63}$")
|
|
143
143
|
|
|
144
144
|
|
|
145
|
+
def login_values_by_env(data: Dict[str, Dict[str, str]]) -> Dict[str, str]:
|
|
146
|
+
"""Each saved value of use_logins' data by its environment variable's name (a one-time code's secret left out)."""
|
|
147
|
+
out: Dict[str, str] = {}
|
|
148
|
+
for per in data.values():
|
|
149
|
+
for key, value in per.items():
|
|
150
|
+
kind_env = _PLACEHOLDERS.get(key)
|
|
151
|
+
if kind_env and kind_env[0] != "totp" and value:
|
|
152
|
+
out[kind_env[1]] = value
|
|
153
|
+
return out
|
|
154
|
+
|
|
155
|
+
|
|
145
156
|
def use_env_secrets(data: Dict[str, Dict[str, str]], items: Any) -> List[str]:
|
|
146
157
|
"""
|
|
147
158
|
Add the environment's secret variables (env.yaml ``TestPassword: password``) to ``data``, the library's sensitive_data,
|
|
@@ -461,9 +461,89 @@ def save_findings(out_dir: str, persona: Dict[str, Any], findings: List[Dict[str
|
|
|
461
461
|
logger.warning("%s not written: %s", FINDINGS_FILE, ex)
|
|
462
462
|
|
|
463
463
|
|
|
464
|
-
|
|
464
|
+
JOURNEY_FILE = "persona-journey.json"
|
|
465
|
+
MAX_JOURNEY = 400
|
|
466
|
+
|
|
467
|
+
_IDENTITY_FN = """function () {
|
|
468
|
+
const a = (n) => (this.getAttribute(n) || '').slice(0, 200);
|
|
469
|
+
return { tag: this.tagName.toLowerCase(), id: (this.id || '').slice(0, 200), testid: a('data-testid') || a('data-test') || a('data-cy'), href: a('href') };
|
|
470
|
+
}"""
|
|
471
|
+
|
|
472
|
+
|
|
473
|
+
async def identity(browser_session: BrowserSession, *, backend: Optional[int] = None, active: bool = False) -> Dict[str, str]:
|
|
474
|
+
"""
|
|
475
|
+
An element as a replay finds it again: its accessible role and name (as the screen reader has them), and its tag,
|
|
476
|
+
id, test id and link. Of a DOM node by its backend id, or of what has focus. Every value plain text, clipped.
|
|
477
|
+
"""
|
|
478
|
+
out: Dict[str, str] = {}
|
|
479
|
+
try:
|
|
480
|
+
cdp = await _cdp(browser_session)
|
|
481
|
+
send, sid = cdp.cdp_client.send, cdp.session_id
|
|
482
|
+
if active:
|
|
483
|
+
ref = (await send.Runtime.evaluate(params={"expression": "document.activeElement", "returnByValue": False}, session_id=sid)).get("result") or {}
|
|
484
|
+
object_id = ref.get("objectId")
|
|
485
|
+
else:
|
|
486
|
+
await send.DOM.getDocument(params={"depth": 0}, session_id=sid)
|
|
487
|
+
object_id = (((await send.DOM.resolveNode(params={"backendNodeId": backend}, session_id=sid)) or {}).get("object") or {}).get("objectId")
|
|
488
|
+
if not object_id:
|
|
489
|
+
return out
|
|
490
|
+
tree = await send.Accessibility.getPartialAXTree(params={"objectId": object_id, "fetchRelatives": False}, session_id=sid)
|
|
491
|
+
nodes = [n for n in tree.get("nodes") or [] if not n.get("ignored")]
|
|
492
|
+
if nodes:
|
|
493
|
+
out["role"] = _ax_value(nodes[0].get("role"))[:40]
|
|
494
|
+
out["name"] = " ".join(_ax_value(nodes[0].get("name")).split())[:150]
|
|
495
|
+
dom = ((await send.Runtime.callFunctionOn(params={"objectId": object_id, "functionDeclaration": _IDENTITY_FN, "returnByValue": True}, session_id=sid)) or {}).get("result") or {}
|
|
496
|
+
for k, v in (dom.get("value") or {}).items():
|
|
497
|
+
if k in ("tag", "id", "testid", "href") and isinstance(v, str) and v:
|
|
498
|
+
out[k] = " ".join(v.split())[:200]
|
|
499
|
+
except Exception as ex:
|
|
500
|
+
logger.debug("identity not read: %s", ex)
|
|
501
|
+
return out
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
class Journey:
|
|
505
|
+
"""
|
|
506
|
+
What a keyboard or screen reader persona did, step by step, for a replay with no model (src/a11y/journeys.ts writes
|
|
507
|
+
it as a JavaScript test): each key, swipe, tap and typed text, the page it was on and the page it led to, and what
|
|
508
|
+
it reached (the focus after a key, the item a swipe landed on, the item a tap activated). Typed text that holds a
|
|
509
|
+
saved login's value is kept as that value's name, never the value.
|
|
510
|
+
"""
|
|
511
|
+
|
|
512
|
+
def __init__(self, out_dir: str, persona_id: str, secrets: Optional[Dict[str, str]] = None) -> None:
|
|
513
|
+
self.file = Path(out_dir) / JOURNEY_FILE if out_dir else None
|
|
514
|
+
self.persona = persona_id
|
|
515
|
+
self.steps: List[Dict[str, Any]] = []
|
|
516
|
+
# Longest first, so a value inside another is not named for the shorter one.
|
|
517
|
+
self.secrets = sorted(((n, v) for n, v in (secrets or {}).items() if isinstance(v, str) and len(v) >= 3), key=lambda x: -len(x[1]))
|
|
518
|
+
|
|
519
|
+
def text(self, raw: str) -> Dict[str, str]:
|
|
520
|
+
for name, value in self.secrets:
|
|
521
|
+
if value and value in raw:
|
|
522
|
+
return {"secret": name}
|
|
523
|
+
return {"text": raw[:500]}
|
|
524
|
+
|
|
525
|
+
def add(self, step: Dict[str, Any]) -> None:
|
|
526
|
+
if len(self.steps) >= MAX_JOURNEY or self.file is None:
|
|
527
|
+
return
|
|
528
|
+
self.steps.append(step)
|
|
529
|
+
try:
|
|
530
|
+
self.file.parent.mkdir(parents=True, exist_ok=True)
|
|
531
|
+
self.file.write_text(json.dumps({"persona": self.persona, "steps": self.steps}, indent=1, ensure_ascii=False), encoding="utf-8")
|
|
532
|
+
except OSError as ex:
|
|
533
|
+
logger.warning("%s not written: %s", JOURNEY_FILE, ex)
|
|
534
|
+
|
|
535
|
+
|
|
536
|
+
async def _url(browser_session: BrowserSession) -> str:
|
|
537
|
+
try:
|
|
538
|
+
return str(await browser_session.get_current_page_url() or "")[:600]
|
|
539
|
+
except Exception:
|
|
540
|
+
return ""
|
|
541
|
+
|
|
542
|
+
|
|
543
|
+
def register_persona_tools(tools: Any, persona: Dict[str, Any], findings: List[Dict[str, Any]], out_dir: str, secrets: Optional[Dict[str, str]] = None) -> None:
|
|
465
544
|
"""record_accessibility_issue always; the keyboard and screen reader actions for a persona that uses them."""
|
|
466
545
|
sighted = uses_vision(persona)
|
|
546
|
+
journey = Journey(out_dir, str(persona.get("id") or ""), secrets)
|
|
467
547
|
|
|
468
548
|
@tools.action(
|
|
469
549
|
"Record one accessibility barrier that this person met, as soon as you meet it: title (a few words), "
|
|
@@ -508,6 +588,7 @@ def register_persona_tools(tools: Any, persona: Dict[str, Any], findings: List[D
|
|
|
508
588
|
return ActionResult(error=f"Not a key this person presses: {raw!r}. Use one of: {', '.join(KEYS)}, Shift+Tab.")
|
|
509
589
|
name = next(k for k, v in KEYS.items() if v is spec)
|
|
510
590
|
k, code, vk, txt = spec
|
|
591
|
+
before = await _url(browser_session)
|
|
511
592
|
try:
|
|
512
593
|
cdp = await _cdp(browser_session)
|
|
513
594
|
send, sid = cdp.cdp_client.send, cdp.session_id
|
|
@@ -518,6 +599,7 @@ def register_persona_tools(tools: Any, persona: Dict[str, Any], findings: List[D
|
|
|
518
599
|
except Exception as ex:
|
|
519
600
|
return ActionResult(error=f"The key was not pressed: {ex}")
|
|
520
601
|
said = f"Pressed {'Shift+' if shift else ''}{name}. {focus_line(f, sighted)}"
|
|
602
|
+
journey.add({"op": "press", "key": f"{'Shift+' if shift else ''}{name}", "url": before, "after": await _url(browser_session), "focus": {} if f.get("none") else await identity(browser_session, active=True)})
|
|
521
603
|
return ActionResult(extracted_content=said, long_term_memory=said)
|
|
522
604
|
|
|
523
605
|
if touch_reader(persona):
|
|
@@ -558,6 +640,8 @@ def register_persona_tools(tools: Any, persona: Dict[str, Any], findings: List[D
|
|
|
558
640
|
if at < 0 or at >= len(items):
|
|
559
641
|
return ActionResult(extracted_content="Start of the page: nothing before this." if at < 0 else "End of the page: nothing after this.")
|
|
560
642
|
cursor.update({"at": at, "line": items[at]["line"], "backend": items[at]["backend"]})
|
|
643
|
+
url = await _url(browser_session)
|
|
644
|
+
journey.add({"op": "swipe", "dir": "next" if step > 0 else "previous", "url": url, "after": url, "item": await identity(browser_session, backend=items[at]["backend"]) if items[at]["backend"] else {"name": str(items[at]["line"])[:150]}})
|
|
561
645
|
said = f"{'Swiped right' if step > 0 else 'Swiped left'}. {items[at]['line']}"
|
|
562
646
|
return ActionResult(extracted_content=said, long_term_memory=said)
|
|
563
647
|
|
|
@@ -573,6 +657,8 @@ def register_persona_tools(tools: Any, persona: Dict[str, Any], findings: List[D
|
|
|
573
657
|
async def double_tap(browser_session: BrowserSession) -> ActionResult:
|
|
574
658
|
if cursor["backend"] is None:
|
|
575
659
|
return ActionResult(error="The cursor is on nothing that can be activated: move to an item with swipe_next first.")
|
|
660
|
+
before = await _url(browser_session)
|
|
661
|
+
target = await identity(browser_session, backend=cursor["backend"])
|
|
576
662
|
try:
|
|
577
663
|
cdp = await _cdp(browser_session)
|
|
578
664
|
send, sid = cdp.cdp_client.send, cdp.session_id
|
|
@@ -596,12 +682,14 @@ def register_persona_tools(tools: Any, persona: Dict[str, Any], findings: List[D
|
|
|
596
682
|
except Exception as ex:
|
|
597
683
|
return ActionResult(error=f"Double tap did not reach {cursor['line']}: {ex}")
|
|
598
684
|
said = f"Double tapped {cursor['line']}. {focus_line(f, False)}"
|
|
685
|
+
journey.add({"op": "tap", "url": before, "after": await _url(browser_session), "target": target, "focus": {} if f.get("none") else await identity(browser_session, active=True)})
|
|
599
686
|
return ActionResult(extracted_content=said, long_term_memory=said)
|
|
600
687
|
|
|
601
688
|
if touch_reader(persona) or keyboard_only(persona):
|
|
602
689
|
|
|
603
690
|
@tools.action("Type text into the field that has focus, as on the on-screen or a real keyboard. Put focus in the field first (press_key, or double_tap on a touchscreen).")
|
|
604
691
|
async def type_text(text: str, browser_session: BrowserSession) -> ActionResult:
|
|
692
|
+
before = await _url(browser_session)
|
|
605
693
|
try:
|
|
606
694
|
f = await focused(browser_session)
|
|
607
695
|
if f.get("none"):
|
|
@@ -611,6 +699,7 @@ def register_persona_tools(tools: Any, persona: Dict[str, Any], findings: List[D
|
|
|
611
699
|
f = await focused(browser_session)
|
|
612
700
|
except Exception as ex:
|
|
613
701
|
return ActionResult(error=f"Not typed: {ex}")
|
|
702
|
+
journey.add({"op": "type", **journey.text(str(text or "")), "url": before, "after": await _url(browser_session), "focus": await identity(browser_session, active=True)})
|
|
614
703
|
said = f"Typed into {f.get('announce', 'the field')}."
|
|
615
704
|
return ActionResult(extracted_content=said, long_term_memory=said)
|
|
616
705
|
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
"""
|
|
2
|
+
forgeqe scan: open each address in ForgeQE's browser, one after another in one tab, and check what is there, with no
|
|
3
|
+
model and no step on the page (nothing clicked, typed or submitted): the rule engine's accessibility checks, the Core
|
|
4
|
+
Web Vitals, and what the page tells search engines and which analytics tags it loads (seo.py). The browser starts as a
|
|
5
|
+
run's does (the same providers, saved signed-in sessions of the logins given), only on the hosts allowed.
|
|
6
|
+
|
|
7
|
+
stdin line 1: {urls, out_dir, browser, headed, axe | ibm, logins, allowed_hosts}; a later "stop" ends it, keeping what
|
|
8
|
+
it checked. Each page is a "page" event; the last line is {"type": "done", "result": {...}}.
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import asyncio
|
|
13
|
+
import json
|
|
14
|
+
import logging
|
|
15
|
+
import re
|
|
16
|
+
import time
|
|
17
|
+
from urllib.parse import urlsplit
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Any, Callable, Dict, List, Optional
|
|
20
|
+
|
|
21
|
+
from .browser import (
|
|
22
|
+
_shutdown_browser_instance,
|
|
23
|
+
browser_launch_kwargs,
|
|
24
|
+
browser_name,
|
|
25
|
+
explain_browser_start,
|
|
26
|
+
local_launch_candidates,
|
|
27
|
+
settle_page,
|
|
28
|
+
start_local_browser,
|
|
29
|
+
window_launch_kwargs,
|
|
30
|
+
)
|
|
31
|
+
from .diagnostics import Diagnostics, _page_key
|
|
32
|
+
from .logins import load_sessions, parse_logins
|
|
33
|
+
from .settings import resolve_browser_headless
|
|
34
|
+
from .urls import _allowed_hosts_violation_for_url, _parse_allowed_domains, normalize_http_base_url
|
|
35
|
+
|
|
36
|
+
logger = logging.getLogger(__name__)
|
|
37
|
+
|
|
38
|
+
MAX_URLS = 25
|
|
39
|
+
_HOST = re.compile(r"\[[0-9a-f:.]+\]|[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*", re.I)
|
|
40
|
+
# After the page settles: time for late scripts, analytics hits and the largest paint before it is read.
|
|
41
|
+
LINGER_SECONDS = 2.5
|
|
42
|
+
NAVIGATE_SECONDS = 45.0
|
|
43
|
+
|
|
44
|
+
Emit = Callable[[Dict[str, Any]], None]
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def scan_urls(raw: Any, allowed: Optional[List[str]]) -> "tuple[List[str], List[str]]":
|
|
48
|
+
"""The addresses to open, http(s) only, each once, at most MAX_URLS; and why each other one was left out."""
|
|
49
|
+
urls: List[str] = []
|
|
50
|
+
skipped: List[str] = []
|
|
51
|
+
for item in raw if isinstance(raw, list) else []:
|
|
52
|
+
# Written with its scheme and a host name of a host name's shape: never a bare word made into an address.
|
|
53
|
+
u = normalize_http_base_url(item) if isinstance(item, str) and re.match(r"^https?://", item.strip(), re.I) else None
|
|
54
|
+
host = urlsplit(u).hostname if u else None
|
|
55
|
+
if u and (not host or not _HOST.fullmatch(host) or urlsplit(u).username or urlsplit(u).password):
|
|
56
|
+
u = None
|
|
57
|
+
if not u:
|
|
58
|
+
skipped.append(f"{str(item)[:120]}: not an http(s) address")
|
|
59
|
+
continue
|
|
60
|
+
why = _allowed_hosts_violation_for_url(u, allowed)
|
|
61
|
+
if why:
|
|
62
|
+
skipped.append(why)
|
|
63
|
+
continue
|
|
64
|
+
if u not in urls:
|
|
65
|
+
urls.append(u)
|
|
66
|
+
if len(urls) > MAX_URLS:
|
|
67
|
+
skipped.append(f"{len(urls) - MAX_URLS} more addresses: a scan opens at most {MAX_URLS}")
|
|
68
|
+
urls = urls[:MAX_URLS]
|
|
69
|
+
return urls, skipped
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
async def run_scan(payload: Dict[str, Any], emit: Emit, cancel: asyncio.Event) -> Dict[str, Any]:
|
|
73
|
+
from browser_use import Browser
|
|
74
|
+
|
|
75
|
+
allowed = _parse_allowed_domains(payload.get("allowed_hosts"))
|
|
76
|
+
urls, skipped = scan_urls(payload.get("urls"), allowed)
|
|
77
|
+
for s in skipped:
|
|
78
|
+
emit({"type": "log", "level": "warn", "text": f"Not scanned: {s}"})
|
|
79
|
+
if not urls:
|
|
80
|
+
return {"success": False, "error": "No address to scan.", "pages": []}
|
|
81
|
+
out_dir = Path(str(payload.get("out_dir") or ""))
|
|
82
|
+
if not str(payload.get("out_dir") or "") or not out_dir.is_dir():
|
|
83
|
+
return {"success": False, "error": "No output folder.", "pages": []}
|
|
84
|
+
|
|
85
|
+
axe = payload.get("axe") if isinstance(payload.get("axe"), dict) else None
|
|
86
|
+
ibm = payload.get("ibm") if isinstance(payload.get("ibm"), dict) else None
|
|
87
|
+
diag = Diagnostics(accessibility=True, network=False, axe=axe, ibm=ibm, vitals=True, visual=None, seo=True)
|
|
88
|
+
|
|
89
|
+
headless = resolve_browser_headless(payload.get("headed") is True)
|
|
90
|
+
cfg = payload.get("browser") if isinstance(payload.get("browser"), dict) else {}
|
|
91
|
+
provider = str(cfg.get("provider") or "local")
|
|
92
|
+
remote = cfg.get("remote") if isinstance(cfg.get("remote"), dict) else {}
|
|
93
|
+
kw = browser_launch_kwargs(provider=provider, remote=remote, headless=headless)
|
|
94
|
+
kw.update(window_launch_kwargs(cfg, headless=headless))
|
|
95
|
+
if allowed is not None:
|
|
96
|
+
kw["allowed_domains"] = allowed
|
|
97
|
+
# Signed-in pages: the saved sessions of the logins given, never a password typed (a scan signs in to nothing).
|
|
98
|
+
stored = load_sessions(parse_logins(payload.get("logins")))
|
|
99
|
+
if stored:
|
|
100
|
+
kw["storage_state"] = stored
|
|
101
|
+
emit({"type": "log", "level": "info", "progress": True, "text": f"Starting the browser to scan {len(urls)} page{'s' if len(urls) != 1 else ''}"})
|
|
102
|
+
|
|
103
|
+
try:
|
|
104
|
+
if provider == "local":
|
|
105
|
+
browser, _ = await start_local_browser(
|
|
106
|
+
[{**c, **{k: v for k, v in kw.items() if k not in ("channel", "executable_path")}} for c in local_launch_candidates(headless=headless, choice=cfg.get("local_browser"), method=cfg.get("launch"), port=cfg.get("attach_port"))],
|
|
107
|
+
make=lambda k: Browser(**k),
|
|
108
|
+
on_fallback=lambda failed, nxt, reason: emit({"type": "log", "level": "warn", "text": f"{browser_name(failed)} did not start ({reason}); trying {browser_name(nxt)}"}),
|
|
109
|
+
)
|
|
110
|
+
else:
|
|
111
|
+
browser = Browser(**kw)
|
|
112
|
+
await browser.start()
|
|
113
|
+
except Exception as e:
|
|
114
|
+
return {"success": False, "error": explain_browser_start(str(e)), "pages": []}
|
|
115
|
+
|
|
116
|
+
pages: List[Dict[str, Any]] = []
|
|
117
|
+
try:
|
|
118
|
+
await diag.start(browser)
|
|
119
|
+
for i, url in enumerate(urls, 1):
|
|
120
|
+
if cancel.is_set():
|
|
121
|
+
emit({"type": "log", "level": "warn", "text": f"Stopped: {len(urls) - i + 1} page(s) not scanned"})
|
|
122
|
+
break
|
|
123
|
+
emit({"type": "log", "level": "info", "progress": True, "text": f"Scanning page {i} of {len(urls)}: {url}"})
|
|
124
|
+
t0 = time.monotonic()
|
|
125
|
+
page: Dict[str, Any] = {"url": url}
|
|
126
|
+
try:
|
|
127
|
+
await asyncio.wait_for(browser.navigate_to(url), timeout=NAVIGATE_SECONDS)
|
|
128
|
+
await settle_page(browser)
|
|
129
|
+
await asyncio.sleep(LINGER_SECONDS)
|
|
130
|
+
page["final_url"] = str(await browser.get_current_page_url() or "")[:600]
|
|
131
|
+
await diag.sample(browser)
|
|
132
|
+
page["checked"] = _page_key(page["final_url"]) in diag.pages
|
|
133
|
+
except Exception as e:
|
|
134
|
+
page["error"] = str(e).splitlines()[0][:300] if str(e) else type(e).__name__
|
|
135
|
+
page["seconds"] = round(time.monotonic() - t0, 1)
|
|
136
|
+
pages.append(page)
|
|
137
|
+
emit({"type": "page", **page})
|
|
138
|
+
finally:
|
|
139
|
+
files = [f for f in (diag.write(out_dir), diag.write_perf(out_dir), diag.write_seo(out_dir)) if f]
|
|
140
|
+
(out_dir / "scan.json").write_text(json.dumps({"urls": urls, "skipped": skipped, "pages": pages}, indent=2), encoding="utf-8")
|
|
141
|
+
files.append(str((out_dir / "scan.json").resolve()))
|
|
142
|
+
try:
|
|
143
|
+
await _shutdown_browser_instance(browser)
|
|
144
|
+
except Exception:
|
|
145
|
+
logger.debug("browser not shut down", exc_info=True)
|
|
146
|
+
ok = [p for p in pages if not p.get("error")]
|
|
147
|
+
return {"success": bool(ok), "pages": pages, "files": files, **({} if ok else {"error": "No page could be opened."})}
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
async def print_pdf(payload: Dict[str, Any], emit: Emit) -> Dict[str, Any]:
|
|
151
|
+
"""
|
|
152
|
+
A report ForgeQE wrote, printed to PDF by the local browser: an .html file of ForgeQE's own report app, whose own
|
|
153
|
+
inline scripts draw it (its data is embedded as JSON it only reads), written as the .pdf named once the app says it
|
|
154
|
+
has drawn (``document.body.dataset.ready``). Nothing outside the file is loaded: every http(s) and websocket address
|
|
155
|
+
is blocked (Network.setBlockedURLs). Both paths come from ForgeQE, never from a page.
|
|
156
|
+
"""
|
|
157
|
+
import base64
|
|
158
|
+
|
|
159
|
+
from browser_use import Browser
|
|
160
|
+
|
|
161
|
+
html = Path(str(payload.get("html") or ""))
|
|
162
|
+
pdf = Path(str(payload.get("pdf") or ""))
|
|
163
|
+
if html.suffix.lower() != ".html" or not html.is_file() or html.is_symlink() or pdf.suffix.lower() != ".pdf" or not pdf.parent.is_dir():
|
|
164
|
+
return {"success": False, "error": "A report .html and a .pdf in an existing folder are needed."}
|
|
165
|
+
cfg = payload.get("browser") if isinstance(payload.get("browser"), dict) else {}
|
|
166
|
+
try:
|
|
167
|
+
browser, _ = await start_local_browser(
|
|
168
|
+
local_launch_candidates(headless=True, choice=cfg.get("local_browser"), method=cfg.get("launch"), port=None),
|
|
169
|
+
make=lambda k: Browser(**k),
|
|
170
|
+
)
|
|
171
|
+
except Exception as e:
|
|
172
|
+
return {"success": False, "error": explain_browser_start(str(e))}
|
|
173
|
+
try:
|
|
174
|
+
session = await browser.get_or_create_cdp_session()
|
|
175
|
+
send = session.cdp_client.send
|
|
176
|
+
own = html.resolve().as_uri()
|
|
177
|
+
sid = session.session_id
|
|
178
|
+
|
|
179
|
+
# Nothing on the network: every http(s) and websocket address is blocked, so only the file and data: load.
|
|
180
|
+
await send.Network.enable(params={}, session_id=sid)
|
|
181
|
+
await send.Network.setBlockedURLs(params={"urls": ["http://*", "https://*", "ws://*", "wss://*"]}, session_id=sid)
|
|
182
|
+
await send.Page.navigate(params={"url": own}, session_id=sid)
|
|
183
|
+
await settle_page(browser)
|
|
184
|
+
# The report app marks the page drawn after its first render; a page that never does is printed as it is.
|
|
185
|
+
for _ in range(60):
|
|
186
|
+
r = await send.Runtime.evaluate(params={"expression": "document.body && document.body.dataset.ready === '1'", "returnByValue": True}, session_id=sid)
|
|
187
|
+
if ((r or {}).get("result") or {}).get("value") is True:
|
|
188
|
+
break
|
|
189
|
+
await asyncio.sleep(0.25)
|
|
190
|
+
await asyncio.sleep(0.5)
|
|
191
|
+
r = await send.Page.printToPDF(params={"printBackground": True, "preferCSSPageSize": True}, session_id=session.session_id)
|
|
192
|
+
data = base64.b64decode((r or {}).get("data") or "")
|
|
193
|
+
if not data.startswith(b"%PDF"):
|
|
194
|
+
return {"success": False, "error": "The browser did not print a PDF."}
|
|
195
|
+
pdf.write_bytes(data)
|
|
196
|
+
emit({"type": "log", "level": "info", "text": f"PDF written: {pdf.name}"})
|
|
197
|
+
return {"success": True, "pdf": str(pdf.resolve()), "bytes": len(data)}
|
|
198
|
+
finally:
|
|
199
|
+
try:
|
|
200
|
+
await _shutdown_browser_instance(browser)
|
|
201
|
+
except Exception:
|
|
202
|
+
logger.debug("browser not shut down", exc_info=True)
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""
|
|
2
|
+
What a page tells search engines and which analytics tags it loads, read by two fixed scripts in the page (no page code
|
|
3
|
+
is run by name, nothing is clicked or typed): the page's own facts (title, description, headings, canonical, robots,
|
|
4
|
+
Open Graph, structured data, links) and, from its scripts, globals and resource timing, the analytics tools it loads,
|
|
5
|
+
their ids, the hits they sent and whether a consent banner was there. ForgeQE judges them (src/seo/checks.ts); here
|
|
6
|
+
they are only collected, clipped and made plain. robots.txt and the sitemap are read once per site, from the page's own
|
|
7
|
+
origin, without credentials.
|
|
8
|
+
"""
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import logging
|
|
12
|
+
import re
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any, Dict, List, Optional
|
|
15
|
+
|
|
16
|
+
logger = logging.getLogger(__name__)
|
|
17
|
+
|
|
18
|
+
MAX_PAGES = 25
|
|
19
|
+
|
|
20
|
+
def _script(name: str) -> str:
|
|
21
|
+
"""One of the fixed page scripts shipped beside this file (seo_*.mjs), which the generated JavaScript tests run too."""
|
|
22
|
+
return (Path(__file__).with_name(f"{name}.mjs")).read_text(encoding="utf-8")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
PAGE_FACTS_JS = _script("seo_facts")
|
|
26
|
+
# The analytics tools: what loads them (a script or a global) and the hits they send, matched on resource and script
|
|
27
|
+
# addresses inside the page. Only a tool's name, its ids of their own shape and counts leave the page, never an address.
|
|
28
|
+
ANALYTICS_JS = _script("seo_analytics")
|
|
29
|
+
SITE_JS = _script("seo_site")
|
|
30
|
+
|
|
31
|
+
_ID = re.compile(r"^[A-Za-z0-9-]{1,30}$")
|
|
32
|
+
_TOOLS = {
|
|
33
|
+
"Google Analytics 4", "Universal Analytics", "Google Tag Manager", "Google Ads", "Adobe Analytics", "Meta Pixel", "Microsoft Clarity",
|
|
34
|
+
"Hotjar", "Segment", "Mixpanel", "Amplitude", "Heap", "Matomo", "Plausible", "PostHog", "LinkedIn Insight", "TikTok Pixel",
|
|
35
|
+
"Microsoft Advertising UET", "Piano Analytics",
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def clean_analytics(raw: Any) -> Dict[str, Any]:
|
|
40
|
+
"""The page's answer in its shape only: known tools, ids of an id's shape, counts."""
|
|
41
|
+
raw = raw if isinstance(raw, dict) else {}
|
|
42
|
+
tools: List[Dict[str, Any]] = []
|
|
43
|
+
for t in raw.get("tools") or []:
|
|
44
|
+
if not isinstance(t, dict) or t.get("tool") not in _TOOLS:
|
|
45
|
+
continue
|
|
46
|
+
tools.append({
|
|
47
|
+
"tool": t["tool"],
|
|
48
|
+
"ids": [str(i) for i in (t.get("ids") or []) if isinstance(i, str) and _ID.fullmatch(i)][:10],
|
|
49
|
+
"loaded": t.get("loaded") is True,
|
|
50
|
+
"scripts": int(t.get("scripts") or 0) if isinstance(t.get("scripts"), (int, float)) else 0,
|
|
51
|
+
"hits": int(t.get("hits") or 0) if isinstance(t.get("hits"), (int, float)) else 0,
|
|
52
|
+
"consent_mode": t.get("consent_mode") if t.get("consent_mode") in ("granted", "denied", "mixed") else None,
|
|
53
|
+
})
|
|
54
|
+
cmp = raw.get("consent_manager")
|
|
55
|
+
dl = raw.get("data_layer")
|
|
56
|
+
return {"tools": tools, "data_layer": int(dl) if isinstance(dl, (int, float)) else None, "consent_manager": str(cmp)[:40] if isinstance(cmp, str) else None}
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class SeoCollector:
|
|
60
|
+
"""Each page's facts and analytics, and each site's robots.txt and sitemap, for seo.json."""
|
|
61
|
+
|
|
62
|
+
def __init__(self) -> None:
|
|
63
|
+
self.pages: Dict[str, Dict[str, Any]] = {}
|
|
64
|
+
self.sites: Dict[str, Dict[str, Any]] = {}
|
|
65
|
+
|
|
66
|
+
async def collect(self, evaluate: Any, key: str) -> None:
|
|
67
|
+
"""`evaluate(expression, await_promise)` runs a fixed script in the page and returns its value."""
|
|
68
|
+
if key in self.pages or len(self.pages) >= MAX_PAGES:
|
|
69
|
+
return
|
|
70
|
+
try:
|
|
71
|
+
facts = await evaluate(PAGE_FACTS_JS, False)
|
|
72
|
+
except Exception:
|
|
73
|
+
logger.debug("page facts not read", exc_info=True)
|
|
74
|
+
return
|
|
75
|
+
if not isinstance(facts, dict) or not str(facts.get("url") or "").startswith("http"):
|
|
76
|
+
return
|
|
77
|
+
try:
|
|
78
|
+
analytics = clean_analytics(await evaluate(ANALYTICS_JS, False))
|
|
79
|
+
except Exception:
|
|
80
|
+
logger.debug("analytics not read", exc_info=True)
|
|
81
|
+
analytics = clean_analytics(None)
|
|
82
|
+
self.pages[key] = {**facts, "analytics": analytics}
|
|
83
|
+
origin = re.match(r"^https?://[^/]+", str(facts["url"]))
|
|
84
|
+
if origin and origin.group(0) not in self.sites:
|
|
85
|
+
try:
|
|
86
|
+
site = await evaluate(SITE_JS, True)
|
|
87
|
+
if isinstance(site, dict):
|
|
88
|
+
self.sites[origin.group(0)] = site
|
|
89
|
+
except Exception:
|
|
90
|
+
logger.debug("robots.txt and sitemap not read", exc_info=True)
|
|
91
|
+
|
|
92
|
+
def result(self) -> Optional[Dict[str, Any]]:
|
|
93
|
+
if not self.pages:
|
|
94
|
+
return None
|
|
95
|
+
return {"pages": list(self.pages.values()), "sites": list(self.sites.values())}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
// A fixed script ForgeQE runs in a page under test (py/forgeqe_engine/seo.py, and the JavaScript tests src/a11y/suitetests.ts writes).
|
|
2
|
+
// One expression; it reads the page and changes nothing.
|
|
3
|
+
(() => {
|
|
4
|
+
const TOOLS = [
|
|
5
|
+
{ tool: 'Google Analytics 4', load: /googletagmanager\.com\/gtag\/js\?(?:[^#]*&)?id=G-/i, hit: /(?:google-analytics\.com|analytics\.google\.com|\/g\/collect)\b.*[?&]tid=G-|\/g\/collect\?/i, id: /\b(G-[A-Z0-9]{4,12})\b/g, globals: [] },
|
|
6
|
+
{ tool: 'Universal Analytics', load: /google-analytics\.com\/(?:analytics|ga)\.js/i, hit: /google-analytics\.com\/(?:r\/)?collect\?(?!.*tid=G-)/i, id: /\b(UA-\d{4,10}-\d{1,4})\b/g, globals: ['ga'] },
|
|
7
|
+
{ tool: 'Google Tag Manager', load: /googletagmanager\.com\/gtm\.js/i, hit: null, id: /\b(GTM-[A-Z0-9]{4,10})\b/g, globals: ['google_tag_manager'] },
|
|
8
|
+
{ tool: 'Google Ads', load: /googletagmanager\.com\/gtag\/js\?(?:[^#]*&)?id=AW-/i, hit: /googleadservices\.com\/pagead\/conversion|google\.com\/pagead\/1p-conversion/i, id: /\b(AW-\d{6,12})\b/g, globals: [] },
|
|
9
|
+
{ tool: 'Adobe Analytics', load: /assets\.adobedtm\.com|\/AppMeasurement(?:\.min)?\.js/i, hit: /\.(?:omtrdc\.net|2o7\.net)\/b\/ss\/|\/b\/ss\/[^/]+\/\d/i, id: null, globals: ['_satellite', 's_c_il'] },
|
|
10
|
+
{ tool: 'Meta Pixel', load: /connect\.facebook\.net\/[^/]+\/fbevents\.js/i, hit: /facebook\.com\/tr\/?\?/i, id: /[?&]id=(\d{10,20})\b/g, globals: ['fbq'] },
|
|
11
|
+
{ tool: 'Microsoft Clarity', load: /clarity\.ms\/tag\//i, hit: /\.clarity\.ms\/collect/i, id: /clarity\.ms\/tag\/([a-z0-9]{6,14})\b/gi, globals: ['clarity'] },
|
|
12
|
+
{ tool: 'Hotjar', load: /static\.hotjar\.com\/c\/hotjar-/i, hit: /(?:in|vc|metrics)\.hotjar\.(?:com|io)/i, id: /hotjar-(\d{5,10})\.js/g, globals: ['hj'] },
|
|
13
|
+
{ tool: 'Segment', load: /cdn\.segment\.com\/analytics\.js/i, hit: /api\.segment\.io\/v1\//i, id: null, globals: [] },
|
|
14
|
+
{ tool: 'Mixpanel', load: /cdn\.mxpnl\.com|mixpanel-[\d.]+(?:\.min)?\.js/i, hit: /api(?:-js)?\.mixpanel\.com\/(?:track|engage)/i, id: null, globals: ['mixpanel'] },
|
|
15
|
+
{ tool: 'Amplitude', load: /cdn\.amplitude\.com/i, hit: /api2?\.amplitude\.com\/(?:2\/)?httpapi|api2\.amplitude\.com/i, id: null, globals: ['amplitude'] },
|
|
16
|
+
{ tool: 'Heap', load: /cdn\.heapanalytics\.com/i, hit: /heapanalytics\.com\/h\?/i, id: null, globals: ['heap'] },
|
|
17
|
+
{ tool: 'Matomo', load: /\/(?:matomo|piwik)\.js/i, hit: /\/(?:matomo|piwik)\.php\?/i, id: /[?&]idsite=(\d{1,6})\b/g, globals: ['_paq', 'Matomo'] },
|
|
18
|
+
{ tool: 'Plausible', load: /plausible\.io\/js\//i, hit: /plausible\.io\/api\/event/i, id: null, globals: ['plausible'] },
|
|
19
|
+
{ tool: 'PostHog', load: /posthog(?:-js)?[./]|\/static\/array\.js/i, hit: /(?:i\.)?posthog\.com\/(?:e|batch|i\/v0\/e)\//i, id: null, globals: ['posthog'] },
|
|
20
|
+
{ tool: 'LinkedIn Insight', load: /snap\.licdn\.com\/li\.lms-analytics/i, hit: /px\.ads\.linkedin\.com/i, id: null, globals: ['_linkedin_data_partner_ids'] },
|
|
21
|
+
{ tool: 'TikTok Pixel', load: /analytics\.tiktok\.com\/i18n\/pixel/i, hit: /analytics\.tiktok\.com\/api\/v2\/pixel/i, id: null, globals: ['ttq'] },
|
|
22
|
+
{ tool: 'Microsoft Advertising UET', load: /bat\.bing\.com\/bat\.js/i, hit: /bat\.bing\.com\/action\//i, id: null, globals: ['uetq'] },
|
|
23
|
+
{ tool: 'Piano Analytics', load: /tag\.aticdn\.net|\/piano-analytics(?:\.min)?\.js|\/smarttag\.js/i, hit: /\.xiti\.com\/hit\.xiti|\.pa-cd\.com\/(?:event|hit)/i, id: /[?&]s=(\d{4,10})\b/g, globals: ['ATInternet'] },
|
|
24
|
+
];
|
|
25
|
+
const CMPS = [
|
|
26
|
+
['OneTrust', () => window.OneTrust || window.OptanonWrapper || document.getElementById('onetrust-banner-sdk')],
|
|
27
|
+
['Cookiebot', () => window.Cookiebot || document.getElementById('CybotCookiebotDialog')],
|
|
28
|
+
['Didomi', () => window.Didomi || document.getElementById('didomi-host')],
|
|
29
|
+
['Usercentrics', () => window.UC_UI || document.getElementById('usercentrics-root')],
|
|
30
|
+
['TrustArc', () => window.truste || document.getElementById('truste-consent-track')],
|
|
31
|
+
['Osano', () => window.Osano || document.querySelector('.osano-cm-window')],
|
|
32
|
+
['CookieYes', () => document.querySelector('.cky-consent-container')],
|
|
33
|
+
['iubenda', () => window._iub || document.getElementById('iubenda-cs-banner')],
|
|
34
|
+
['Termly', () => window.Termly || document.getElementById('termly-code-snippet-support')],
|
|
35
|
+
['Quantcast Choice', () => document.querySelector('.qc-cmp2-container')],
|
|
36
|
+
['TCF consent API', () => typeof window.__tcfapi === 'function'],
|
|
37
|
+
];
|
|
38
|
+
// A script tag counts once per tag (two tags of one tool load it twice); an address counts once, however it was seen.
|
|
39
|
+
const tags = [...document.scripts].map((s) => s.src).filter(Boolean).slice(0, 1000);
|
|
40
|
+
const urls = [...new Set(tags.concat(performance.getEntriesByType('resource').map((r) => r.name)))].slice(0, 3000);
|
|
41
|
+
const inline = [...document.scripts].filter((s) => !s.src).map((s) => (s.textContent || '').slice(0, 20000)).join('\n').slice(0, 400000);
|
|
42
|
+
const found = [];
|
|
43
|
+
for (const t of TOOLS) {
|
|
44
|
+
const loads = urls.filter((u) => t.load.test(u));
|
|
45
|
+
const hits = t.hit ? urls.filter((u) => t.hit.test(u)) : [];
|
|
46
|
+
const global = t.globals.some((g) => { try { return typeof window[g] !== 'undefined'; } catch (e) { return false; } });
|
|
47
|
+
if (!loads.length && !hits.length && !global) continue;
|
|
48
|
+
const ids = new Set();
|
|
49
|
+
if (t.id) for (const s of [...loads, ...hits, ...(t.tool === 'Google Tag Manager' || t.tool === 'Google Analytics 4' ? [inline] : [])]) for (const m of s.matchAll(t.id)) ids.add(m[1]);
|
|
50
|
+
// Google's consent mode says in each hit what the person allowed: gcs=G1xy, x for ads and y for analytics storage.
|
|
51
|
+
const gcs = [...new Set(hits.map((u) => { const m = /[?&]gcs=G1([01])([01])/.exec(u); return m ? (m[2] === '1' ? 'granted' : 'denied') : null; }).filter(Boolean))];
|
|
52
|
+
found.push({ tool: t.tool, ids: [...ids].slice(0, 10), loaded: loads.length > 0 || global, scripts: tags.filter((u) => t.load.test(u)).length, hits: hits.length, consent_mode: gcs.length === 1 ? gcs[0] : gcs.length ? 'mixed' : null });
|
|
53
|
+
}
|
|
54
|
+
let dataLayer = null;
|
|
55
|
+
try { if (Array.isArray(window.dataLayer)) dataLayer = window.dataLayer.length; } catch (e) {}
|
|
56
|
+
let cmp = null;
|
|
57
|
+
for (const [name, test] of CMPS) { try { if (test()) { cmp = name; break; } } catch (e) {} }
|
|
58
|
+
return { tools: found, data_layer: dataLayer, consent_manager: cmp };
|
|
59
|
+
})()
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// A fixed script ForgeQE runs in a page under test (py/forgeqe_engine/seo.py, and the JavaScript tests src/a11y/suitetests.ts writes).
|
|
2
|
+
// One expression; it reads the page and changes nothing.
|
|
3
|
+
(() => {
|
|
4
|
+
const clip = (s, n) => String(s == null ? '' : s).replace(/\s+/g, ' ').trim().slice(0, n);
|
|
5
|
+
const metaName = (n) => { const m = [...document.querySelectorAll('meta[name]')].find((x) => (x.getAttribute('name') || '').toLowerCase() === n); return m ? clip(m.getAttribute('content'), 600) : null; };
|
|
6
|
+
const metaProp = (n) => { const m = document.querySelector('meta[property="' + n + '"]') || document.querySelector('meta[name="' + n + '"]'); return m ? clip(m.getAttribute('content'), 600) : null; };
|
|
7
|
+
const nav = performance.getEntriesByType('navigation')[0] || {};
|
|
8
|
+
const heads = [...document.querySelectorAll('h1,h2,h3,h4,h5,h6')].map((h) => Number(h.tagName[1]));
|
|
9
|
+
let skips = 0;
|
|
10
|
+
for (let i = 1; i < heads.length; i++) if (heads[i] > heads[i - 1] + 1) skips++;
|
|
11
|
+
const here = location.origin;
|
|
12
|
+
let internal = 0, external = 0, nofollow = 0, emptyText = 0;
|
|
13
|
+
for (const a of document.querySelectorAll('a[href]')) {
|
|
14
|
+
let u; try { u = new URL(a.getAttribute('href'), location.href); } catch (e) { continue; }
|
|
15
|
+
if (!/^https?:$/.test(u.protocol)) continue;
|
|
16
|
+
if (u.origin === here) internal++; else external++;
|
|
17
|
+
if (/\bnofollow\b/i.test(a.getAttribute('rel') || '')) nofollow++;
|
|
18
|
+
if (!clip(a.innerText || a.textContent, 5) && !a.getAttribute('aria-label') && !a.querySelector('img[alt]:not([alt=""])')) emptyText++;
|
|
19
|
+
}
|
|
20
|
+
const types = [], ldErrors = [];
|
|
21
|
+
for (const s of document.querySelectorAll('script[type="application/ld+json"]')) {
|
|
22
|
+
try {
|
|
23
|
+
const walk = (v) => { if (Array.isArray(v)) v.forEach(walk); else if (v && typeof v === 'object') { const t = v['@type']; (Array.isArray(t) ? t : [t]).forEach((x) => typeof x === 'string' && types.push(clip(x, 60))); if (v['@graph']) walk(v['@graph']); } };
|
|
24
|
+
walk(JSON.parse(s.textContent || ''));
|
|
25
|
+
} catch (e) { ldErrors.push(clip(e && e.message, 120)); }
|
|
26
|
+
}
|
|
27
|
+
const imgs = [...document.images];
|
|
28
|
+
const resources = performance.getEntriesByType('resource');
|
|
29
|
+
return {
|
|
30
|
+
url: location.href,
|
|
31
|
+
status: Number(nav.responseStatus || 0),
|
|
32
|
+
title: clip(document.title, 300),
|
|
33
|
+
titles: document.querySelectorAll('head title').length,
|
|
34
|
+
description: metaName('description'),
|
|
35
|
+
descriptions: [...document.querySelectorAll('meta[name]')].filter((x) => (x.getAttribute('name') || '').toLowerCase() === 'description').length,
|
|
36
|
+
robots: metaName('robots'),
|
|
37
|
+
googlebot: metaName('googlebot'),
|
|
38
|
+
viewport: metaName('viewport'),
|
|
39
|
+
charset: clip(document.characterSet, 40),
|
|
40
|
+
lang: clip(document.documentElement.getAttribute('lang'), 40),
|
|
41
|
+
canonical: [...document.querySelectorAll('link[rel]')].filter((l) => /\bcanonical\b/i.test(l.getAttribute('rel') || '')).map((l) => clip(l.href, 600)).slice(0, 5),
|
|
42
|
+
h1: [...document.querySelectorAll('h1')].map((h) => clip(h.innerText || h.textContent, 150)).slice(0, 10),
|
|
43
|
+
h1_count: document.querySelectorAll('h1').length,
|
|
44
|
+
headings: heads.length,
|
|
45
|
+
heading_skips: skips,
|
|
46
|
+
words: clip(document.body ? document.body.innerText : '', 200000).split(' ').filter(Boolean).length,
|
|
47
|
+
images: imgs.length,
|
|
48
|
+
images_no_alt: imgs.filter((i) => !i.hasAttribute('alt')).length,
|
|
49
|
+
links_internal: internal,
|
|
50
|
+
links_external: external,
|
|
51
|
+
links_nofollow: nofollow,
|
|
52
|
+
links_empty: emptyText,
|
|
53
|
+
og: { title: metaProp('og:title'), description: metaProp('og:description'), image: metaProp('og:image'), url: metaProp('og:url'), type: metaProp('og:type') },
|
|
54
|
+
twitter: { card: metaProp('twitter:card'), title: metaProp('twitter:title'), image: metaProp('twitter:image') },
|
|
55
|
+
jsonld_types: [...new Set(types)].slice(0, 30),
|
|
56
|
+
jsonld_errors: ldErrors.slice(0, 5),
|
|
57
|
+
hreflang: [...document.querySelectorAll('link[rel="alternate"][hreflang]')].map((l) => ({ lang: clip(l.getAttribute('hreflang'), 20), href: clip(l.href, 600) })).slice(0, 50),
|
|
58
|
+
favicon: Boolean(document.querySelector('link[rel~="icon" i]')),
|
|
59
|
+
mixed: location.protocol === 'https:' ? resources.filter((r) => /^http:/i.test(r.name)).length : 0,
|
|
60
|
+
bytes: Math.round(resources.reduce((a, r) => a + (r.transferSize || 0), 0) + (nav.transferSize || 0)),
|
|
61
|
+
requests: resources.length + 1,
|
|
62
|
+
};
|
|
63
|
+
})()
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// A fixed script ForgeQE runs in a page under test (py/forgeqe_engine/seo.py, and the JavaScript tests src/a11y/suitetests.ts writes).
|
|
2
|
+
// One expression; it reads the page and changes nothing.
|
|
3
|
+
(async () => {
|
|
4
|
+
const get = async (path, max) => {
|
|
5
|
+
try {
|
|
6
|
+
const ctl = new AbortController();
|
|
7
|
+
const t = setTimeout(() => ctl.abort(), 8000);
|
|
8
|
+
const r = await fetch(path, { credentials: 'omit', redirect: 'follow', signal: ctl.signal, cache: 'no-store' });
|
|
9
|
+
clearTimeout(t);
|
|
10
|
+
const text = r.ok ? (await r.text()).slice(0, max) : '';
|
|
11
|
+
return { status: r.status, text, type: (r.headers.get('content-type') || '').slice(0, 80) };
|
|
12
|
+
} catch (e) { return { status: 0, text: '', type: '' }; }
|
|
13
|
+
};
|
|
14
|
+
const robots = await get('/robots.txt', 200000);
|
|
15
|
+
const lines = robots.text.split(/\r?\n/).map((l) => l.replace(/#.*/, '').trim()).filter(Boolean);
|
|
16
|
+
const disallow = [], sitemaps = [];
|
|
17
|
+
// Groups: user-agent lines in a row, then their rules; the rules for every crawler are the group naming *.
|
|
18
|
+
let star = false, agents = [], lastUa = false;
|
|
19
|
+
for (const l of lines) {
|
|
20
|
+
const m = /^([A-Za-z-]+)\s*:\s*(.*)$/.exec(l);
|
|
21
|
+
if (!m) continue;
|
|
22
|
+
const k = m[1].toLowerCase(), v = m[2].trim();
|
|
23
|
+
if (k === 'user-agent') { if (!lastUa) agents = []; agents.push(v); if (v === '*') star = true; lastUa = true; continue; }
|
|
24
|
+
lastUa = false;
|
|
25
|
+
if (k === 'sitemap' && /^https?:\/\//i.test(v)) sitemaps.push(v.slice(0, 600));
|
|
26
|
+
if (agents.includes('*') && k === 'disallow' && v) disallow.push(v.slice(0, 200));
|
|
27
|
+
}
|
|
28
|
+
let mapUrl = sitemaps.find((s) => { try { return new URL(s).origin === location.origin; } catch (e) { return false; } }) || '/sitemap.xml';
|
|
29
|
+
const map = await get(mapUrl, 5000000);
|
|
30
|
+
const isXml = /<(urlset|sitemapindex)\b/i.test(map.text.slice(0, 2000));
|
|
31
|
+
return {
|
|
32
|
+
origin: location.origin,
|
|
33
|
+
robots: { status: robots.status, user_agent_star: star, disallow: disallow.slice(0, 100), sitemaps: sitemaps.slice(0, 20) },
|
|
34
|
+
sitemap: { url: new URL(mapUrl, location.href).href.slice(0, 600), status: map.status, xml: isXml, index: /<sitemapindex\b/i.test(map.text.slice(0, 2000)), urls: isXml ? (map.text.match(/<loc>/gi) || []).length : 0 },
|
|
35
|
+
};
|
|
36
|
+
})()
|