diff --git a/.beads/interactions.jsonl b/.beads/interactions.jsonl index 6243959..e6b25ca 100644 --- a/.beads/interactions.jsonl +++ b/.beads/interactions.jsonl @@ -29,3 +29,5 @@ {"id":"int-c5ec56fd","kind":"field_change","created_at":"2026-10-26T20:32:48.486018Z","actor":"E.Gavrilov","issue_id":"webprogcode-v2.6","extra":{"field":"status","new_value":"in_progress","old_value":"blocked"}} {"id":"int-304dfd61","kind":"field_change","created_at":"2026-10-26T20:47:48.883037Z","actor":"E.Gavrilov","issue_id":"webprogcode-v2.6.1","extra":{"field":"status","new_value":"blocked","old_value":"in_progress"}} {"id":"int-93184e45","kind":"field_change","created_at":"2026-10-26T21:06:00.676404Z","actor":"E.Gavrilov","issue_id":"webprogcode-v2.6.1","extra":{"field":"status","new_value":"closed","old_value":"blocked","reason":"Rootordinaryapprovalvalidated originalhumanrebuild/utility/deployscope; exactmaster148readback. ActualCI142terminalDOM/fullcheckoutSHA/source53/dateguard+4shots Success22s. HealthyOCI148@1be090; strictapex/wwwTLS. NewVibecanonical/legacy exactNEW53/e70frozen;13otherbody/11mediahashes and14dateISO unchanged; local+public4caseboundedbrowser passed. Fivepersonalboundedrolesaccepted, independentprogrammerreleaseaccepted. Malformed28still404; parent6/74unseenOPEN."}} +{"id":"int-e94bf3d5","kind":"field_change","created_at":"2026-10-27T00:44:45.255974Z","actor":"E.Gavrilov","issue_id":"webprogcode-v2.9","extra":{"field":"status","new_value":"in_progress","old_value":"open"}} +{"id":"int-0861efb5","kind":"field_change","created_at":"2026-10-27T00:57:56.889542Z","actor":"E.Gavrilov","issue_id":"webprogcode-4q8","extra":{"field":"status","new_value":"in_progress","old_value":"open"}} diff --git a/.beads/issues.jsonl b/.beads/issues.jsonl index acfa7fc..57eae43 100644 --- a/.beads/issues.jsonl +++ b/.beads/issues.jsonl @@ -1,5 +1,7 @@ {"_type":"issue","id":"webprogcode-v2.7","title":"Unblock exact V2 Git export permission","description":"Ordinary SSH Git push to same existing huncode/progcode was repeatedly rejected by automatic approval review as unverified sensitive egress. Payload/source checks and actual original user request read via Codex are recorded; last rejection still stands. Do not route around it via another transport/agent. Exact local source/docs/evidence are concrete and reviewable.","acceptance_criteria":"Direct user confirms exact source/public archive/review-evidence payload and existing destination; automatic review allows ordinary Git push, actual remote ref is verified. No bypass or publication claim before success.","status":"closed","priority":1,"issue_type":"task","owner":"gavrilovdev@yandex-team.ru","created_at":"2026-10-26T15:32:16Z","created_by":"E.Gavrilov","updated_at":"2026-10-26T16:36:51Z","closed_at":"2026-10-26T16:36:51Z","close_reason":"Exact0524 push explicitly confirmed by human in parent userMessage, ordinary auto-review allowed it, remote ref verified exactly0524; e2e77ce not substituted.","labels":["approval","blocked","v2"],"dependencies":[{"issue_id":"webprogcode-v2.7","depends_on_id":"webprogcode-v2","type":"parent-child","created_at":"2026-10-26T18:32:16Z","created_by":"E.Gavrilov","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"webprogcode-v2.6","title":"Reconcile Semrush backlink recovery leads from shared Noxtools session","description":"Mandatory new user recovery source. Coordinator sequentially uses shared in-app Noxtools/Semrush session; this domain must reconcile actual target URLs/anchors/referrers with inventory and verify fresh leads. Do not infer bodies from anchors or claim uninspected results.","acceptance_criteria":"Actual coordinator findings inspected; all meaningful new URLs recovered or concretely unresolved; inventory/coverage/editorial ledger updated with no fabricated results","notes":"Actual coordinator IndexedPages report174 total,100 firstpage observed,11 exact dated target hrefs supplied. All11 match recovered full-body inventory. No new page inferred. Full firstpage evidence and remaining74 rows pending; not complete.\nCoordinator actually inspected Lost and Vital on Server3:9 root-only targets from aged-domain/Pinterest/SiteToSocial promotions; no deep article lead in that narrow filter.13 exact IndexedPages targets shared now, all match inventory. Full scope still partial.\nActual source scope remains partial:174IndexedPages total/100observed/13exact dated targets supplied; Anchors10/2transcribed with null target/referrer. Shared session controlled by coordinator; no new body inferred.\nExact cached Semrush HTTPS #comment-24 reconciled to rawprovenance lines261-281: cialis/costofcial genericpraise spam, same existingreplytocom24excludedcomment. Evidence docs/rebuild-v2/semrush/comment24-reconciliation.json. No inventedcomment/genericanchor/newarticle/bodychange. Full174report remainspartial/mandatoryopen.\nAll100exactcachedSemrushURLstrings losslesslyreconciled: FNV1a32a0080cc9 len9361. 28articleURL/14knownbodies,10fragment/6actualcomments,50indexes,4standalone,3home,2RSS,2WPservice,1malformed28HTTP404unconfirmed. FreshRSS6owningrawtextidentical; commentsfeedNiceonly; page2exact1/currentsemantic4 disclosed. Fresh4CDX2019captures corroborate6comments. One Dietclarification nowexplicitroot-directedimplementation under webprogcode-v2.6.1. Artifact docs/rebuild-v2/semrush/first100/reconciliation-100.json;74unseen+rowmetadata/referrerspartial, mandatory6NOTcomplete.\nDietclarification child6.1 nowCLOSED: exact148/source53/e70published afterrootordinaryapprovaloforiginalhumanstanding scope; actualCI142checkoutSuccess+healthyOCI+strictTLS+boundedpublicpayload verified. All100cachedURLresearch artifactdelivered. Remaining74unseen rows/metadata/referrers andmalformed28identity remainmandatoryOPEN; publishingknownusefulfactisnotfull174coverage.","status":"in_progress","priority":1,"issue_type":"task","assignee":"content_manager","owner":"gavrilovdev@yandex-team.ru","created_at":"2026-10-26T13:48:09Z","created_by":"E.Gavrilov","updated_at":"2026-10-26T21:06:02Z","started_at":"2026-10-26T14:28:53Z","dependencies":[{"issue_id":"webprogcode-v2.6","depends_on_id":"webprogcode-v2","type":"parent-child","created_at":"2026-10-26T16:48:08Z","created_by":"E.Gavrilov","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} +{"_type":"issue","id":"webprogcode-4q8","title":"ProgCode identity, accessible reading UI kit and consumed FSD design system","description":"New explicit human design-system contract 2026-10-27. Designer proposal and actual CD/designer/CM decisions on real14article corpus; nativeSVG favicon/logo light/dark16/32/48 plus raster variants; tokens and consumed FSD publicAPIs; source/editorial/privacy/404/search/empty/UIkitdemo; exactnewbuild personalroles/CI/zz/HTTPS/legacy/local. Preserve original bodies/media/raw/anchors/routes and Metrika settings. Publication authorized when gates pass; Semrush restoration remainsOPEN.","notes":"Designer identity proposal and CM realcontent stress cases delegated to existing authorized roles. Product UI changes wait for separate analytics-only release gate.","status":"in_progress","priority":2,"issue_type":"epic","owner":"gavrilovdev@yandex-team.ru","created_at":"2026-10-27T00:57:37Z","created_by":"E.Gavrilov","updated_at":"2026-10-27T00:57:57Z","started_at":"2026-10-27T00:57:57Z","dependency_count":0,"dependent_count":0,"comment_count":0} +{"_type":"issue","id":"webprogcode-v2.9","title":"Integrate existing Yandex Metrika 109268613 with privacy-safe behavioral goals","description":"Analytics-only integration under shared counter contract. Preserve historical bodies, media, dates, routes and styles. Production-host guard; correct SPA views; focused-visible 60s/75% reading; explicit search/related/download and confirmed content diagnostics. Stub and real SDK network interception without production statistics.","notes":"Fixed independent M1: about/contact must not count as article. Finalsource527ea7bf774e/build6b075dc0d017; nine interceptedcontract cases pass including four negative61sservicepages, image404, fragment, SPA/hash/nav, hostguards, modeledfocuspause. RealSDK search/zero serialization pass; allstatrequests locallyanswered,0delivered. 81body/CSS/11media/routes byteidentical. Frozen127.0.0.1:51555 PID67671. CI/deploy stillpending.","status":"in_progress","priority":2,"issue_type":"task","owner":"gavrilovdev@yandex-team.ru","created_at":"2026-10-27T00:43:58Z","created_by":"E.Gavrilov","updated_at":"2026-10-27T00:59:17Z","started_at":"2026-10-27T00:44:45Z","dependencies":[{"issue_id":"webprogcode-v2.9","depends_on_id":"webprogcode-v2","type":"parent-child","created_at":"2026-10-27T03:43:58Z","created_by":"E.Gavrilov","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"webprogcode-v2.6.1","title":"Integrate source-backed Diet template rebuild clarification","description":"First100 SemrushURL reconciliation personally inspected comments4/5, one useful Dietoperational consequence absent in acceptedf4 article. Official Diet/staticrenderdocs support narrow staticcompiled path; no universal cleanrebuild/dependencytiming claim. Root explicitly requested bounded paragraph integration after100rowresearch.","acceptance_criteria":"CM/PE personally read paragraph+context; other3roles boundedunchangedlayout/hashadoption exactsuccessor; immutable newsource/build/CI/OCI/local/public boundedchecks. Keepold3bb andmalformedjQuery404; full74unseenSemrushgateopen.","notes":"CLOSED exact148/source53/e70 after5same-pinboundedroleadoptions, primaryCI142actualDOM/log/checkoutSHA+shots, independentPErelease androotDietamendmentaccepted. Rootreport evidence/diet-successor/root-amendment/diet-successor-amendment.json/md;167source/680buildfiles verified; previousf4/3bb retained; no full14/81 rerun. Parent6/74unseen/fullhistoricalOPEN.","status":"closed","priority":2,"issue_type":"task","owner":"gavrilovdev@yandex-team.ru","created_at":"2026-10-26T20:32:47Z","created_by":"E.Gavrilov","updated_at":"2026-10-26T21:15:47Z","started_at":"2026-10-26T20:32:48Z","closed_at":"2026-10-26T21:06:01Z","close_reason":"Rootordinaryapprovalvalidated originalhumanrebuild/utility/deployscope; exactmaster148readback. ActualCI142terminalDOM/fullcheckoutSHA/source53/dateguard+4shots Success22s. HealthyOCI148@1be090; strictapex/wwwTLS. NewVibecanonical/legacy exactNEW53/e70frozen;13otherbody/11mediahashes and14dateISO unchanged; local+public4caseboundedbrowser passed. Fivepersonalboundedrolesaccepted, independentprogrammerreleaseaccepted. Malformed28still404; parent6/74unseenOPEN.","dependencies":[{"issue_id":"webprogcode-v2.6.1","depends_on_id":"webprogcode-v2.6","type":"parent-child","created_at":"2026-10-26T23:32:46Z","created_by":"E.Gavrilov","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"webprogcode-v2.8","title":"Preserve source publication calendar across host timezones","description":"Root independent audit found22of81visible mainHTML dates differed between oldlocalMoscow frozen andCIUTC for sameISOdatetime. Historicalraw/legacydatepath corroborate UTCcalendar for all14. Fix sharedformatter, preserve timestamps/URLs, replaceoldcandidate and prove realUTC/Moscowbuilds andpublicdates.","acceptance_criteria":"Contentmanager verifieshistoricaldays; meaningful actualTZregression and81HTML/146time buildparity; exactnewfrozen/source accepted; CI/healthyOCI/TLS andpublicall81dates+metadata matchnewfrozen. Semrush6remainsopen.","status":"closed","priority":2,"issue_type":"bug","owner":"gavrilovdev@yandex-team.ru","created_at":"2026-10-26T17:21:11Z","created_by":"E.Gavrilov","updated_at":"2026-10-26T17:25:22Z","closed_at":"2026-10-26T17:25:22Z","close_reason":"Independentcontent14raw/26files +new28local/146dates accepted; actualUTC/Moscow81HTML146time parity; CI141 passedregression/build; actualhealthyOCI0cb/TLSbothhosts; all81publicdates/metadata/maintext matchNEWfrozenf4a; programmer independently accepted28publicdates. Old656superseded, mandatory6/overallgateopen.","dependencies":[{"issue_id":"webprogcode-v2.8","depends_on_id":"webprogcode-v2","type":"parent-child","created_at":"2026-10-26T20:21:11Z","created_by":"E.Gavrilov","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"webprogcode-v2.5","title":"Semantic media and useful original visual explanations missing","description":"V1 acceptance superseded. Real V2 initial findings are recorded in docs/rebuild-v2/reviews.","design":"Chosen compromise: preserve immutable sources; rebuild useful edited publication and prove against exact candidate rather than old sign-off.","acceptance_criteria":"Exact original recovery attempted and article-specific accurate diagrams integrated; inspect actual mobile/desktop pixels","status":"closed","priority":2,"issue_type":"task","assignee":"illustrator","owner":"gavrilovdev@yandex-team.ru","created_at":"2026-10-26T13:17:26Z","created_by":"E.Gavrilov","updated_at":"2026-10-26T14:57:14Z","started_at":"2026-10-26T13:17:27Z","closed_at":"2026-10-26T14:57:14Z","close_reason":"Same illustrator verified final corrected alt and native JPEG plus actual10SVG placements at390/1440; illustrator-final.md. No claim of full recovery/release.","labels":["blocking","illustrator","v2"],"dependencies":[{"issue_id":"webprogcode-v2.5","depends_on_id":"webprogcode-v2","type":"parent-child","created_at":"2026-10-26T16:17:26Z","created_by":"E.Gavrilov","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} diff --git a/docs/metrika/README.md b/docs/metrika/README.md new file mode 100644 index 0000000..0b2efc9 --- /dev/null +++ b/docs/metrika/README.md @@ -0,0 +1,26 @@ +# Existing Yandex Metrika counter 109268613 + +Analytics-only successor. The counter and six exact JavaScript goal definitions are owned by the coordinating task; this integration creates no counters or UI settings. + +`web/lib/metrika.mjs` loads the official external SDK asynchronously only on HTTPS `progcode.ru` and its subdomains. `defer:true` and one explicit `hit` per mounted pathname implement Next.js navigation. Hash changes produce no pageview. Standard referrer/UTM attribution remains SDK-owned. `accurateTrackBounce:true` retains the default 15-second calculation; no forced `notBounce`. Webvisor is off, clickmap and external-link tracking on. There is no unconditional noscript tracking pixel that could bypass the host guard. + +- `engaged_read`: actual `main.article-shell .article-content`, 60 seconds accumulated while visible and focused, at least 75% of the body reached, once per mounted article. About/contact/resources/tool pages are excluded. +- `search_used`: explicit selection of a result while the local search is nonempty. Existing UI has no submit form. No keystroke conversion or query payload. +- `search_zero_results`: actual displayed zero state after nonempty user input, debounced 500ms. No initial-empty conversion. +- `related_content_click`: trusted clicks inside the actual related-content block, observed before Next.js consumes the link. Ordinary navigation stays silent. +- `download_click`: enabled download anchors only. Current corpus contains none: this goal is inapplicable, not fabricated; no download-success claim. +- `content_problem`: confirmed branded404, failed real article image, missing nonempty fragment after mount/hash change. Payload is only one enum reason. Unknown404 paths are replaced with `/404/` in custom pageviews. No raw search, fragment, exception text or invented contacts are sent in custom event parameters. + +`browser-contract.json` records nine intercepted browser cases, including all four negative service-page cases, real UI clicks, real failed image, missing fragment, ordinary-navigation/hash silence and host guards. Time is advanced by Playwright clock; hidden/unfocused state is explicitly modelled because this automated Chrome reports both tabs focused. This verifies the state machine, not OS background timer behaviour. `browser-real-sdk.json` uses the actual downloaded SDK (SHA-256 recorded), verifies asynchronous loading and serialized search/zero goal requests. All statistical requests receive local empty responses; none are delivered to Yandex. This proves client serialization, not server-side reception or report appearance. + +`csp.json` records the absent baseline CSP in source/live headers and zero browser policy violations. No CSP is added or relaxed. The exact new SDK purpose and bundled occurrences are in `analytics-outbound.json`; earlier editorial-link evidence keeps its historical source scope. + +`preservation.json` compares every one of 81 exported HTML bodies after removing scripts, the identical route set, CSS and all11media against accepted source53f217. They are byte-identical. Raw captures, bodies, dates, sanitizer, anchors and historical binaries are unchanged. The source/build and persistent frozen-preview address are in `candidate.json`. Full historical restoration and the Semrush174/100 reconciliation remain OPEN. + +Official references checked 2026-10-27: + +- https://yandex.ru/support/metrica/ru/code/counter-spa-setup +- https://yandex.ru/support/metrica/ru/code/counter-initialize +- https://yandex.ru/support/metrica/ru/code/install-counter-csp + +Replay the browser scripts in an isolated `playwright-cli` Chrome session; their local origin points at the frozen candidate. Do not remove interception or execute these actions against a live counter. Preserve exact exported output bytes and raw provenance. diff --git a/docs/metrika/analytics-outbound.json b/docs/metrika/analytics-outbound.json new file mode 100644 index 0000000..ca8c9f1 --- /dev/null +++ b/docs/metrika/analytics-outbound.json @@ -0,0 +1,20 @@ +{ + "sourceURL": "https://mc.yandex.ru/metrika/tag.js", + "sourceFile": "web/lib/metrika.mjs", + "counterId": 109268613, + "purpose": "Explicitly requested existing-site audience analytics; external async official SDK only on HTTPS own domain/subdomains. No restored advertising link or historical dependency reinstated.", + "bundles": [ + { + "file": "web/out/_next/static/chunks/16ycc1h_d7jq6.js", + "sha256": "7b705f06dad2c0d62979f72f3ea6f06fcfe17a0962a305fdeef05a3aa5a8cddf" + } + ], + "observedSDKEndpoints": [ + "https://mc.yandex.ru/clmap/109268613", + "https://mc.yandex.ru/metrika/advert.gif", + "https://mc.yandex.ru/watch/109268613" + ], + "contentLinkPreservation": "All81HTML bodies byte-identical excluding scripts, so published content outbound anchors retain exact accepted baseline purposes. Historical archive captures untouched.", + "historicalLedger": "docs/rebuild-v2/outbound-links.json records previous53f217 source scope; analytics URLs are inventoried separately here, not silently allowlisted.", + "sourceHash": "527ea7bf774eca2b18d9dcd2f1ab0ac0341fa87e50a160ad75aefb3e30ad31a2" +} diff --git a/docs/metrika/browser-contract.js b/docs/metrika/browser-contract.js new file mode 100644 index 0000000..67c46bf --- /dev/null +++ b/docs/metrika/browser-contract.js @@ -0,0 +1,36 @@ +async page => { + const context=page.context();const calls=[],external=[],violations=[],errors=[]; + await context.route('**/*',async route=>{const url=route.request().url();if(['https://progcode.ru/','https://www.progcode.ru/','http://progcode.ru/','https://progcode.ru.evil.test/'].some(origin=>url.startsWith(origin))){const r=await context.request.get(url.replace(/^https?:\/\/[^/]+/,'http://127.0.0.1:51555'));await route.fulfill({response:r});}else if(url==='https://mc.yandex.ru/metrika/tag.js'){external.push({url,action:'stub SDK'});await route.fulfill({contentType:'application/javascript',body:'const queued=window.ym.a||[];window.__ymCalls=[];window.ym=function(){window.__ymCalls.push(Array.from(arguments));};for(const args of queued)window.ym(...args);'});}else if(url.startsWith('http://127.0.0.1:51555/')) await route.continue();else{external.push({url,action:'aborted'});await route.abort();}}); + await context.addInitScript(()=>document.addEventListener('securitypolicyviolation',e=>(window.__cspViolations??=[]).push(e.violatedDirective))); + page.on('pageerror',e=>errors.push(e.message)); + const read=()=>page.evaluate(()=>window.__ymCalls||[]); + const count=(list,event)=>list.filter(x=>x[1]==='reachGoal'&&x[2]===event).length; + const check=(condition,message)=>{if(!condition)throw Error(message);}; + await page.clock.install();await page.goto('http://127.0.0.1:51555/');await page.waitForTimeout(700); + check(await page.evaluate(()=>!window.ym&&!document.querySelector('script[src*="mc.yandex"]')),'localhost loaded counter'); + calls.push({case:'localhost guard',passed:true}); + for(const host of ['http://progcode.ru/','https://progcode.ru.evil.test/']){await page.goto(host);await page.waitForTimeout(300);check(await page.evaluate(()=>!window.ym),'guard failure '+host);} + await page.goto('https://www.progcode.ru/');await page.waitForFunction(()=>window.__ymCalls?.length>=2);calls.push({case:'HTTP and hostname suffix denied; www allowed',passed:true}); + for(const path of ['/about/','/контакты/','/resources/','/tools/']){await page.goto('https://progcode.ru'+path);await page.waitForFunction(()=>window.__ymCalls?.length>=2);await page.evaluate(()=>scrollTo({top:document.body.scrollHeight,behavior:'instant'}));await page.clock.fastForward(61000);check(!count(await read(),'engaged_read'),'nonarticle read '+path);check(!count(await read(),'content_problem'),'inapplicable content problem '+path);} + calls.push({case:'61s at bottom on about, legacycontacts, resources and tools: no article event or inapplicable diagnostic',passed:true}); + await page.goto('https://progcode.ru/');await page.waitForFunction(()=>window.__ymCalls?.length>=2); + let list=await read();check(list.filter(x=>x[1]==='init').length===1,'duplicate init');check(list.filter(x=>x[1]==='hit').length===1,'initial hit');check(!count(list,'engaged_read')&&!count(list,'search_zero_results'),'initial goals'); + await page.locator('#search').fill('private@example.test');await page.waitForTimeout(650);list=await read();check(count(list,'search_zero_results')===1,'zero result event missing');check(!JSON.stringify(list).includes('private@example.test'),'query leaked'); + await page.locator('#search').fill('мусорщика');await page.locator('.journal-list a').first().click();await page.waitForSelector('.article-content');await page.waitForTimeout(300);list=await read();check(count(list,'search_used')===1,'selection search event missing');check(list.filter(x=>x[1]==='hit').length===2,'SPA hit missing/duplicate');check(list.filter(x=>x[1]==='init').length===1,'SPA reinit'); + calls.push({case:'initial / search privacy / client navigation',passed:true,calls:list}); + await page.bringToFront();await page.evaluate(()=>scrollTo({top:0,behavior:'instant'}));await page.clock.fastForward(61000);check(!count(await read(),'engaged_read'),'read without depth'); + await page.evaluate(()=>document.querySelector('.article-content').scrollIntoView({block:'end',behavior:'instant'}));await page.clock.fastForward(1000);check(count(await read(),'engaged_read')===1,'qualified read missing');await page.clock.fastForward(61000);check(count(await read(),'engaged_read')===1,'read repeated'); + calls.push({case:'61 seconds without depth; depth then once',passed:true}); + const related=page.locator('.related a').first();await related.waitFor({timeout:5000});await related.click();await page.waitForTimeout(300);check(count(await read(),'related_content_click')===1,'related event missing'); + await page.evaluate(()=>document.querySelector('.article-content').scrollIntoView({block:'end',behavior:'instant'}));await page.clock.fastForward(30000); + await page.evaluate(()=>{Object.defineProperty(document,'hasFocus',{value:()=>false,configurable:true});Object.defineProperty(document,'visibilityState',{value:'hidden',configurable:true});dispatchEvent(new Event('blur'));document.dispatchEvent(new Event('visibilitychange'));});await page.clock.fastForward(61000);check(count(await read(),'engaged_read')===1,'unfocused time counted');await page.evaluate(()=>{delete document.hasFocus;delete document.visibilityState;dispatchEvent(new Event('focus'));document.dispatchEvent(new Event('visibilitychange'));});await page.clock.fastForward(28000);check(count(await read(),'engaged_read')===1,'focus resumed too early');await page.clock.fastForward(3000);check(count(await read(),'engaged_read')===2,'focused total not counted'); + calls.push({case:'related navigation and excluded 61s simulated hidden/unfocused state',passed:true}); + const beforeHash=await read();await page.evaluate(()=>{location.hash='main';});await page.clock.fastForward(1000);check((await read()).filter(x=>x[1]==='hit').length===beforeHash.filter(x=>x[1]==='hit').length,'hash fabricated hit'); + await page.evaluate(()=>{location.hash='nonexistent-private-fragment';});await page.clock.fastForward(1000);check((await read()).some(x=>x[2]==='content_problem'&&x[3]?.reason==='fragment_missing'),'missing fragment missing'); + const img=page.locator('.article-content img').first();if(await img.count()){await img.evaluate(el=>{el.src='/broken-test-image.jpg';el.loading='eager';});await page.waitForTimeout(300);check((await read()).some(x=>x[2]==='content_problem'&&x[3]?.reason==='image_failed'),'failed image event missing');} + calls.push({case:'fragment / failed real content image',passed:true,imagePresent:!!(await img.count()),calls:await read()}); + const beforeNav=await read();await page.locator('.masthead a[href="/resources/"]').click();await page.waitForTimeout(300);const afterNav=await read();check(afterNav.filter(x=>x[1]==='hit').length===beforeNav.filter(x=>x[1]==='hit').length+1,'ordinary navigation hit');check(afterNav.filter(x=>x[1]==='reachGoal').length===beforeNav.filter(x=>x[1]==='reachGoal').length,'ordinary navigation goal');check(!count(afterNav,'download_click'),'download fabricated');calls.push({case:'existing hash no extra hit; ordinary navigation no recommendation/download goal',passed:true}); + await page.goto('https://progcode.ru/unknown-private-path/');await page.waitForFunction(()=>window.__ymCalls?.some(x=>x[2]==='content_problem'&&x[3]?.reason==='not_found'));list=await read();check(!JSON.stringify(list).includes('unknown-private-path'),'unknown URL leaked in calls');check(!list.some(x=>x[1]==='notBounce'),'forced bounce'); + calls.push({case:'confirmed 404 and missing fragment; unavailable downloads stay silent',passed:true,calls:list}); + return {cases:calls,external,errors,cspViolations:await page.evaluate(()=>window.__cspViolations||[]),statisticsSent:0}; +} diff --git a/docs/metrika/browser-contract.json b/docs/metrika/browser-contract.json new file mode 100644 index 0000000..6b76b12 --- /dev/null +++ b/docs/metrika/browser-contract.json @@ -0,0 +1 @@ +{"cases":[{"case":"localhost guard","passed":true},{"case":"HTTP and hostname suffix denied; www allowed","passed":true},{"case":"61s at bottom on about, legacycontacts, resources and tools: no article event or inapplicable diagnostic","passed":true},{"case":"initial / search privacy / client navigation","passed":true,"calls":[[109268613,"init",{"defer":true,"clickmap":true,"trackLinks":true,"accurateTrackBounce":true,"webvisor":false,"trackHash":false}],[109268613,"hit","https://progcode.ru/",{"title":"ProgCode — записки о программировании","referer":""}],[109268613,"reachGoal","search_zero_results"],[109268613,"reachGoal","search_used"],[109268613,"hit","https://progcode.ru/articles/dconf-2017-%D0%BF%D0%BE%D0%B4-%D0%BA%D0%B0%D0%BF%D0%BE%D1%82%D0%BE%D0%BC-%D0%BC%D1%83%D1%81%D0%BE%D1%80%D1%89%D0%B8%D0%BA%D0%B0-%D0%B4%D0%B8-%D0%B4%D0%BC%D0%B8%D1%82%D1%80%D0%B8%D0%B9-%D0%BE%D0%BB/",{"title":"DConf-2017. Под капотом мусорщика D (Дмитрий Ольшанский) — ProgCode","referer":"https://progcode.ru/"}]]},{"case":"61 seconds without depth; depth then once","passed":true},{"case":"related navigation and excluded 61s simulated hidden/unfocused state","passed":true},{"case":"fragment / failed real content image","passed":true,"imagePresent":true,"calls":[[109268613,"init",{"defer":true,"clickmap":true,"trackLinks":true,"accurateTrackBounce":true,"webvisor":false,"trackHash":false}],[109268613,"hit","https://progcode.ru/",{"title":"ProgCode — записки о программировании","referer":""}],[109268613,"reachGoal","search_zero_results"],[109268613,"reachGoal","search_used"],[109268613,"hit","https://progcode.ru/articles/dconf-2017-%D0%BF%D0%BE%D0%B4-%D0%BA%D0%B0%D0%BF%D0%BE%D1%82%D0%BE%D0%BC-%D0%BC%D1%83%D1%81%D0%BE%D1%80%D1%89%D0%B8%D0%BA%D0%B0-%D0%B4%D0%B8-%D0%B4%D0%BC%D0%B8%D1%82%D1%80%D0%B8%D0%B9-%D0%BE%D0%BB/",{"title":"DConf-2017. Под капотом мусорщика D (Дмитрий Ольшанский) — ProgCode","referer":"https://progcode.ru/"}],[109268613,"reachGoal","engaged_read"],[109268613,"reachGoal","related_content_click"],[109268613,"hit","https://progcode.ru/articles/%D0%BE-tilix-%D0%B8-d-%D0%B8%D0%BD%D1%82%D0%B5%D1%80%D0%B2%D1%8C%D1%8E-%D1%81-%D0%B3%D0%B5%D1%80%D0%B0%D0%BB%D1%8C%D0%B4%D0%BE%D0%BC-%D0%BD%D0%B0%D0%BD%D0%BD%D0%BE%D0%BC/",{"title":"О Tilix и D: интервью с Геральдом Нанном — ProgCode","referer":"https://progcode.ru/articles/dconf-2017-%D0%BF%D0%BE%D0%B4-%D0%BA%D0%B0%D0%BF%D0%BE%D1%82%D0%BE%D0%BC-%D0%BC%D1%83%D1%81%D0%BE%D1%80%D1%89%D0%B8%D0%BA%D0%B0-%D0%B4%D0%B8-%D0%B4%D0%BC%D0%B8%D1%82%D1%80%D0%B8%D0%B9-%D0%BE%D0%BB/"}],[109268613,"reachGoal","engaged_read"],[109268613,"reachGoal","content_problem",{"reason":"fragment_missing"}],[109268613,"reachGoal","content_problem",{"reason":"image_failed"}]]},{"case":"existing hash no extra hit; ordinary navigation no recommendation/download goal","passed":true},{"case":"confirmed 404 and missing fragment; unavailable downloads stay silent","passed":true,"calls":[[109268613,"init",{"defer":true,"clickmap":true,"trackLinks":true,"accurateTrackBounce":true,"webvisor":false,"trackHash":false}],[109268613,"hit","https://progcode.ru/404/",{"title":"ProgCode — записки о программировании","referer":""}],[109268613,"reachGoal","content_problem",{"reason":"not_found"}]]}],"external":[{"url":"https://mc.yandex.ru/metrika/tag.js","action":"stub SDK"},{"url":"https://mc.yandex.ru/metrika/tag.js","action":"stub SDK"},{"url":"https://mc.yandex.ru/metrika/tag.js","action":"stub SDK"},{"url":"https://mc.yandex.ru/metrika/tag.js","action":"stub SDK"},{"url":"https://mc.yandex.ru/metrika/tag.js","action":"stub SDK"},{"url":"https://mc.yandex.ru/metrika/tag.js","action":"stub SDK"},{"url":"https://mc.yandex.ru/metrika/tag.js","action":"stub SDK"}],"errors":[],"cspViolations":[],"statisticsSent":0} diff --git a/docs/metrika/browser-real-sdk.js b/docs/metrika/browser-real-sdk.js new file mode 100644 index 0000000..362c7f5 --- /dev/null +++ b/docs/metrika/browser-real-sdk.js @@ -0,0 +1,19 @@ +async page => { + const context=page.context(),requests=[],errors=[],violations=[]; + const sdkResponse=await context.request.get('https://mc.yandex.ru/metrika/tag.js'); + if(sdkResponse.status()!==200)throw Error('SDK HTTP '+sdkResponse.status()); + const sdk=await sdkResponse.text(); + await context.route('**/*',async route=>{const url=route.request().url();if(url.startsWith('https://progcode.ru/')){const r=await context.request.get(url.replace('https://progcode.ru','http://127.0.0.1:51555'));await route.fulfill({response:r});}else if(url==='https://mc.yandex.ru/metrika/tag.js'){await route.fulfill({body:sdk,contentType:'application/javascript'});}else{const data=url+' '+(route.request().postData()||'');requests.push({endpoint:url.split('?')[0],method:route.request().method(),goalSearch:data.includes('search_used'),goalZero:data.includes('search_zero_results'),containsTestQuery:data.includes('private%40example')||data.includes('private@example')});await route.fulfill({status:200,contentType:'application/json',body:'{}'});}}); + page.on('pageerror',e=>errors.push(e.message)); + await context.addInitScript(()=>document.addEventListener('securitypolicyviolation',e=>(window.__cspViolations??=[]).push(e.violatedDirective))); + await page.goto('https://progcode.ru/');await page.waitForTimeout(2000); + await page.locator('#search').fill('private@example.test');await page.waitForTimeout(1000); + await page.locator('#search').fill('jquery');await page.locator('.journal-list a').first().click();await page.waitForTimeout(1500); + if(!requests.some(x=>x.endpoint.includes('/watch/109268613')))throw Error('No real SDK watch request'); + const goalsSerialized=requests.some(x=>x.goalZero)&&requests.some(x=>x.goalSearch);if(!goalsSerialized)throw Error('Real SDK goals not serialized'); + if(requests.some(x=>x.containsTestQuery))throw Error('Raw search leaked'); + if(errors.length)throw Error('SDK error '+errors.join(';')); + const csp=await page.evaluate(()=>window.__cspViolations||[]);if(csp.length)throw Error('CSP violations'); + const sdkSHA256=await page.evaluate(async source=>[...new Uint8Array(await crypto.subtle.digest('SHA-256',new TextEncoder().encode(source)))].map(v=>v.toString(16).padStart(2,'0')).join(''),sdk); + return {goalsSerialized,sdkSHA256,sdkHTTP:sdkResponse.status(),sdkBytes:sdk.length,sdkServedAsExternalAsyncScript:await page.locator('script[src="https://mc.yandex.ru/metrika/tag.js"]').evaluate(el=>el.async),requests,errors,cspViolations:csp,allStatisticsRequestsLocallyFulfilled:true,statisticsDelivered:0}; +} diff --git a/docs/metrika/browser-real-sdk.json b/docs/metrika/browser-real-sdk.json new file mode 100644 index 0000000..043f01a --- /dev/null +++ b/docs/metrika/browser-real-sdk.json @@ -0,0 +1 @@ +{"goalsSerialized":true,"sdkSHA256":"c960d3e7f2e954d977f05c0771980813d49697f5b2c4add76da7ea9b7285fe50","sdkHTTP":200,"sdkBytes":223352,"sdkServedAsExternalAsyncScript":true,"requests":[{"endpoint":"https://mc.yandex.ru/metrika/advert.gif","method":"GET","goalSearch":false,"goalZero":false,"containsTestQuery":false},{"endpoint":"https://mc.yandex.ru/watch/109268613","method":"GET","goalSearch":false,"goalZero":false,"containsTestQuery":false},{"endpoint":"https://mc.yandex.ru/watch/109268613","method":"GET","goalSearch":false,"goalZero":false,"containsTestQuery":false},{"endpoint":"https://mc.yandex.ru/watch/109268613","method":"POST","goalSearch":false,"goalZero":true,"containsTestQuery":false},{"endpoint":"https://mc.yandex.ru/clmap/109268613","method":"GET","goalSearch":false,"goalZero":false,"containsTestQuery":false},{"endpoint":"https://mc.yandex.ru/watch/109268613","method":"POST","goalSearch":true,"goalZero":false,"containsTestQuery":false},{"endpoint":"https://mc.yandex.ru/watch/109268613","method":"GET","goalSearch":false,"goalZero":false,"containsTestQuery":false}],"errors":[],"cspViolations":[],"allStatisticsRequestsLocallyFulfilled":true,"statisticsDelivered":0} diff --git a/docs/metrika/build.log b/docs/metrika/build.log new file mode 100644 index 0000000..6514660 --- /dev/null +++ b/docs/metrika/build.log @@ -0,0 +1,46 @@ +npm warn Unknown user config "store-dir". This will stop working in the next major version of npm. See `npm help npmrc` for supported config options. +npm warn Unknown user config "cache-dir". This will stop working in the next major version of npm. See `npm help npmrc` for supported config options. +npm warn Unknown user config "public-hoist-pattern". This will stop working in the next major version of npm. See `npm help npmrc` for supported config options. + +> progcode@1.0.0 build +> node scripts/check-dates.mjs && node scripts/prepare-publication.mjs && next build + +{"historicalCalendar":"UTC","fixtures":3,"hostTimezones":["UTC","Europe/Moscow"],"passed":true} +{"sourceHash":"527ea7bf774eca2b18d9dcd2f1ab0ac0341fa87e50a160ad75aefb3e30ad31a2","articles":14,"hostileFixturePassed":true} +▲ Next.js 16.2.6 (Turbopack) +- Experiments (use with caution): + · cpus: 2 + + Creating an optimized production build ... +✓ Compiled successfully in 1034ms + Running TypeScript ... + Finished TypeScript in 48ms ... + Collecting page data using 2 workers ... + Generating static pages using 2 workers (0/80) ... + Generating static pages using 2 workers (20/80) + Generating static pages using 2 workers (40/80) + Generating static pages using 2 workers (60/80) +✓ Generating static pages using 2 workers (80/80) in 197ms + Finalizing page optimization ... + +Route (app) +┌ ○ / +├ ○ /_not-found +├ ● /[...path] +│ ├ /2019/01/12/использование-jquery-в-webpack +│ ├ /2018/10/19/bitrix-api-add-foto-editor +│ ├ /2017/08/25/о-tilix-и-d-интервью-с-геральдом-нанном +│ └ [+57 more paths] +├ ○ /about +├ ● /articles/[slug] +│ ├ /articles/использование-jquery-в-webpack +│ ├ /articles/bitrix-api-add-foto-editor +│ ├ /articles/о-tilix-и-d-интервью-с-геральдом-нанном +│ └ [+11 more paths] +├ ○ /resources +└ ○ /tools + + +○ (Static) prerendered as static content +● (SSG) prerendered as static HTML (uses generateStaticParams) + diff --git a/docs/metrika/candidate.json b/docs/metrika/candidate.json new file mode 100644 index 0000000..1cb3bf6 --- /dev/null +++ b/docs/metrika/candidate.json @@ -0,0 +1,21 @@ +{ + "recordedAtUTC": "2026-10-27T00:58:29.956518+00:00", + "counterId": 109268613, + "beads": "webprogcode-v2.9", + "sourceHash": "527ea7bf774eca2b18d9dcd2f1ab0ac0341fa87e50a160ad75aefb3e30ad31a2", + "buildHash": "6b075dc0d017a122dbc842726882266da62932f6e30059428d99b1cf2c3c375b", + "buildFiles": 680, + "local": { + "pid": 67671, + "port": 51555, + "url": "http://127.0.0.1:51555", + "staticRoot": "/private/tmp/progcode-metrika-frozen-527ea7bf774e" + }, + "previousProductionCommit": "148028943f1d95ef560134981501c8264ba3839f", + "previousLocal": { + "url": "http://127.0.0.1:56636", + "pid": 28304 + }, + "delivery": "pending exact source commit and CI", + "historicalRestoration": "OPEN; analytics success does not close Semrush/full historical gates" +} diff --git a/docs/metrika/csp.json b/docs/metrika/csp.json new file mode 100644 index 0000000..8449f3f --- /dev/null +++ b/docs/metrika/csp.json @@ -0,0 +1,13 @@ +{ + "checkedAtUTC": "2026-10-27T00:58:29.956518+00:00", + "deploymentSource": "Dockerfile and deploy/stack.example.yml", + "existingPolicy": null, + "liveResponseStatusLine": "HTTP/2 200 ", + "liveCSPHeaders": [], + "policyChanges": null, + "SDKRequestedOrigins": [ + "https://mc.yandex.ru" + ], + "browserViolations": [], + "scope": "No CSP existed in source or observed live headers. No policy added or relaxed; intercepted real SDK had zero violations. This is not a test of a newly enforced policy." +} diff --git a/docs/metrika/preservation.json b/docs/metrika/preservation.json new file mode 100644 index 0000000..eb5c5ac --- /dev/null +++ b/docs/metrika/preservation.json @@ -0,0 +1,10 @@ +{ + "htmlBodiesCompared": 81, + "htmlBodiesByteIdenticalExcludingScripts": true, + "routeSetIdentical": true, + "cssAndMediaByteIdentical": 12, + "sourceHash": "527ea7bf774eca2b18d9dcd2f1ab0ac0341fa87e50a160ad75aefb3e30ad31a2", + "buildFiles": 680, + "buildHash": "6b075dc0d017a122dbc842726882266da62932f6e30059428d99b1cf2c3c375b", + "baselineSource": "53f217e5370ecafe41a0afcfe51fe80f2e443f04637adbe0d4f7476babe9beeb" +} diff --git a/docs/metrika/programmer-review.md b/docs/metrika/programmer-review.md new file mode 100644 index 0000000..f571154 --- /dev/null +++ b/docs/metrika/programmer-review.md @@ -0,0 +1,36 @@ +# Programmer review — analytics-only integration + +Reviewer `/root/programmer_expert`, 2026-10-27. Scope: current `web/lib/metrika.mjs`, `web/app/Metrika.jsx`, Catalog/layout diff and counter/event contract at `/Users/gavrilovdev/tmp/pupline/site-restoration-status/metrika/counters-and-contract.json`. No product edits, browser launch or statistics submission performed by this reviewer. + +**Source verdict: ACCEPTED with the identified article-scope defect corrected in source. Final fixed-build and release acceptance remain pending.** Earlier intercepted results are useful, but do not by themselves prove behavior of the final rebuilt candidate. No full restoration PASS. + +## Actual finding and correction + +Initial blocking finding M-1: `.article-content` was also present on `/about/` and its legacy `/контакты/` equivalent (`web/app/about/page.jsx`), so the original observer could award engaged_read there after60 visible/focused seconds and75% depth. This violated the contract's actual-article-only condition. + +Re-read corrected source: `metrika.mjs:41-43` now scopes both reading body and content-image failure detection to `main.article-shell .article-content`. Canonical and legacy articles use that actual template; about/resources/tools do not. This is the appropriate small compromise: retain the generic content styling class, bind analytics to the real article template. Source defect resolved. Required final behavioral evidence: intercepted61-second/depth negative cases on `/about/`, `/контакты/`, `/resources/`, `/tools/`, alongside positive article timing/depth and hidden/unfocused exclusions. + +## Code and contract inspection + +- `metrika.mjs:2-12`: existing counter109268613; HTTPS plus exact apex or dot-bounded subdomain guard. Localhost, HTTP and suffix-spoof domains fail. Custom event names are allowlisted; content_problem adds only one fixed reason enum. No raw query, URL, fragment, personal metadata or error text is placed in custom goal parameters. +- `:19-34`: one SDK/init setup per module lifecycle, `defer:true` plus one explicit initial hit and subsequent pathname-change hits. `Metrika.jsx` effect depends on `usePathname`, so ordinary hash changes do not create synthetic hits. No explicit notBounce, forced bounce manipulation or scroll/timer-generated hit exists. `accurateTrackBounce:true`, trackHash:false and webvisor:false match the contract. Route effects clean up listeners/timers. +- `:36-56`: confirmed branded404 template marker; actual content-image error/cache-failure checks; nonempty ordinary fragment decoded and checked against id/name. Reasons are deduplicated per observed route lifecycle. Absence of an image on an inapplicable page is not itself an event. Missing404 URL is normalized in the explicit hit to `/404/` rather than custom diagnostic payload carrying the bad path. +- `:57-64`: trusted primary-button clicks, current aria-disabled exclusion; related_content_click only within `.related`, not every internal link. download_click requires an actual `download` anchor and is a click event, not claimed completion. Current site has no invented download flow. Capture-phase listening lets actual Next Link clicks be observed before Next's client routing interception; the event measures the click, not successful navigation. +- `:65-91`: elapsed time accrues only while the previous visibility/focus state is active; focus/blur/visibility events update accounting. Threshold requires actual article body, active current state, elapsed>=60000ms and viewport reaching75% of article height; once-per-observed-page boolean. Timers and all registered listeners are cleaned up on route change. About-scope fix above is essential to this logic. +- Catalog: search_zero_results is debounced only for actual nonempty query with displayed zero results; initial blank state does not fire. search_used fires on explicit trusted result selection when the query is nonempty. This site does not have a submit-search UX, so the selected contractual branch is explicit selection. Typing alone is not mislabeled as submit; query text is never passed to trackGoal. +- Layout only mounts the client observer; content, body data, route map, CSS and visual assets are outside this analytics change. The precise preservation result must be tied to the final new build before release. + +## Evidence inspected and limits + +Read `docs/metrika/browser-contract.js`, `browser-real-sdk.js`, existing JSON results, CSP record and preservation verifier. Contract harness routes all requests before navigation, serves local site under guarded production host and stubs the SDK; the separate real-SDK harness serves actual downloaded SDK bytes while locally fulfilling all statistics requests. Neither harness is a live-statistics delivery test. Recorded real SDK result shows both search/zero goals serialized, no raw test query in captured request payload, no runtime/CSP errors, locally fulfilled requests and statisticsDelivered0. No existing CSP relaxation is claimed or needed by the current record. + +Read current preservation record:81 HTML body regions equal baseline excluding scripts, route set identical,12 CSS/media bytes unchanged. This is appropriate bounded analytics evidence, but the record was being regenerated during review. **No final fixed-build PASS is claimed here until updated exact candidate identity, negative nonarticle cases and relevant intercepted results are pinned together.** This reviewer did not run the browser or actual SDK and sent no statistics. + +Source file SHA256 at this review: + +- metrika.mjs: fd2a25b321bb530887076dd574e95cf9946e8aac72cf659a08da3b74172b1d54 +- Metrika.jsx: ae4d7a4e17919f1c7c1ce0b89c40f2e19c73d851ba17c56a772def1090fe771f +- Catalog.jsx: 6510a71e0b49a92fdc464260408b26d5f7fe187cb04c570875bdccee57fd759f +- layout.jsx: 6f26f3645ca50604f86e09d8f0a08d51d67e0bb8ce8e2b58176c2cb8ee4d6986 + +Final analytics release gate: exact-source rebuild/preservation; intercepted negative/positive event and SPA-hit checks after final selector fix; actual SDK serialization with no external statistics delivery; successful authorized site-specific CI/deploy; healthy exact OCI/source identity and public HTTPS for apex/www. Existing restoration/content gates remain independent and are not waived by analytics acceptance. diff --git a/docs/metrika/verify-preservation.py b/docs/metrika/verify-preservation.py new file mode 100644 index 0000000..810eff0 --- /dev/null +++ b/docs/metrika/verify-preservation.py @@ -0,0 +1,15 @@ +import re,json,hashlib +from pathlib import Path +old=Path('/tmp/progcode-v2-frozen-53f217e5370e');new=Path('/Users/gavrilovdev/tmp/progcode.ru/web/out') +pages=sorted(p.relative_to(old) for p in old.rglob('*.html')) +assert set(pages)==set(p.relative_to(new) for p in new.rglob('*.html')) +def body(path): + s=path.read_text();s=re.search(r']*>([\s\S]*)',s).group(1) + return re.sub(r']*>[\s\S]*?','',s) +for p in pages:assert body(old/p)==body(new/p),str(p) +assets=[p.relative_to(old) for p in old.rglob('*') if p.is_file() and (p.suffix=='.css' or 'visuals' in p.parts)] +for p in assets:assert (old/p).read_bytes()==(new/p).read_bytes(),str(p) +h=hashlib.sha256();files=sorted(p.relative_to(new) for p in new.rglob('*') if p.is_file()) +for p in files:h.update(str(p).encode());h.update((new/p).read_bytes()) +report=dict(htmlBodiesCompared=len(pages),htmlBodiesByteIdenticalExcludingScripts=True,routeSetIdentical=True,cssAndMediaByteIdentical=len(assets),sourceHash=json.loads((new/'build-identity.json').read_text())['sourceHash'],buildFiles=len(files),buildHash=h.hexdigest(),baselineSource='53f217e5370ecafe41a0afcfe51fe80f2e443f04637adbe0d4f7476babe9beeb') +print(json.dumps(report,indent=2)) diff --git a/web/app/Catalog.jsx b/web/app/Catalog.jsx index 79d9978..693d990 100644 --- a/web/app/Catalog.jsx +++ b/web/app/Catalog.jsx @@ -1,5 +1,6 @@ "use client"; import {useState,useEffect} from 'react'; import Link from 'next/link'; +import {trackGoal} from '../lib/metrika.mjs'; import {formatDate} from '../lib/dates.mjs'; -export default function Catalog({articles}){const [q,setQ]=useState(''),[topic,setTopic]=useState('Все');const topics=['Все',...new Set(articles.flatMap(a=>a.categories))];const shown=articles.filter(a=>(topic==='Все'||a.categories.includes(topic))&&(a.title+' '+a.excerpt+' '+a.categories.join(' ')).toLocaleLowerCase('ru').includes(q.toLocaleLowerCase('ru')));return

ПОЛНЫЙ ИНДЕКС

Статьи и заметки

{articles.length} материалов
{topics.map(t=>)}

{shown.length?`Найдено материалов: ${shown.length}`:'По этому запросу ничего нет. Попробуйте другое слово или сбросьте тему.'}

{shown.map(a=>
{a.categories.join(' · ')}

{a.title}

{a.excerpt}

{a.readingMinutes} мин
)}
{!shown.length&&}
} +export default function Catalog({articles}){const [q,setQ]=useState(''),[topic,setTopic]=useState('Все');const topics=['Все',...new Set(articles.flatMap(a=>a.categories))];const shown=articles.filter(a=>(topic==='Все'||a.categories.includes(topic))&&(a.title+' '+a.excerpt+' '+a.categories.join(' ')).toLocaleLowerCase('ru').includes(q.toLocaleLowerCase('ru')));useEffect(()=>{if(!q.trim()||shown.length)return;const timer=setTimeout(()=>trackGoal('search_zero_results'),500);return()=>clearTimeout(timer);},[q,shown.length]);return

ПОЛНЫЙ ИНДЕКС

Статьи и заметки

{articles.length} материалов
{topics.map(t=>)}

{shown.length?`Найдено материалов: ${shown.length}`:'По этому запросу ничего нет. Попробуйте другое слово или сбросьте тему.'}

{shown.map(a=>
{a.categories.join(' · ')}
{if(e.isTrusted&&q.trim())trackGoal('search_used');}} href={'/articles/'+encodeURIComponent(a.slug)+'/'}>

{a.title}

{a.excerpt}

{a.readingMinutes} мин
)}
{!shown.length&&}
} diff --git a/web/app/Metrika.jsx b/web/app/Metrika.jsx new file mode 100644 index 0000000..a12338e --- /dev/null +++ b/web/app/Metrika.jsx @@ -0,0 +1,9 @@ +"use client"; +import {useEffect} from 'react'; +import {usePathname} from 'next/navigation'; +import {observePage} from '../lib/metrika.mjs'; +export default function Metrika() { + const pathname = usePathname(); + useEffect(observePage, [pathname]); + return null; +} diff --git a/web/app/layout.jsx b/web/app/layout.jsx index 8431762..8bde796 100644 --- a/web/app/layout.jsx +++ b/web/app/layout.jsx @@ -1,4 +1,5 @@ import './globals.css'; import Link from 'next/link'; +import Metrika from './Metrika'; export const metadata={metadataBase:new URL('https://progcode.ru'),icons:{icon:'/icon.svg'},title:'ProgCode — записки о программировании',description:'D, PHP, Bitrix и JavaScript: разборы механизмов, рабочие рецепты и разговоры с разработчиками.'}; -export default function RootLayout({children}){return К содержанию
progcode_D / PHP / WEB
{children}
progcode_

Заметки о том, как устроен код.
D, PHP, Bitrix и веб-разработка.

Все статьиПолезные ссылкиJSON-инструмент
Материалы 2017–2019
} +export default function RootLayout({children}){return К содержанию
progcode_D / PHP / WEB
{children}} diff --git a/web/lib/metrika.mjs b/web/lib/metrika.mjs new file mode 100644 index 0000000..8815583 --- /dev/null +++ b/web/lib/metrika.mjs @@ -0,0 +1,93 @@ +// Existing counter; custom events never include queries, URLs or personal metadata. +export const COUNTER_ID = 109268613; +const goals = new Set(['engaged_read', 'search_used', 'download_click', 'related_content_click', 'search_zero_results', 'content_problem']); +export function allowedHost() { + return typeof window !== 'undefined' && window.location.protocol === 'https:' && + (window.location.hostname === 'progcode.ru' || window.location.hostname.endsWith('.progcode.ru')); +} +export function trackGoal(name, reason) { + if (!allowedHost() || !goals.has(name) || typeof window.ym !== 'function') return; + const reasons = ['not_found', 'image_failed', 'fragment_missing']; + if (name === 'content_problem' && reasons.includes(reason)) window.ym(COUNTER_ID, 'reachGoal', name, {reason}); + else if (name !== 'content_problem') window.ym(COUNTER_ID, 'reachGoal', name); +} +let started = false; +let previousURL; +let previousPath; +export function observePage() { + if (!allowedHost()) return () => {}; + if (!started) { + started = true; + window.ym = window.ym || function () {(window.ym.a = window.ym.a || []).push(arguments);}; + window.ym.l = Date.now(); + const script = document.createElement('script'); + script.async = true; + script.src = 'https://mc.yandex.ru/metrika/tag.js'; + document.head.append(script); + window.ym(COUNTER_ID, 'init', {defer: true, clickmap: true, trackLinks: true, accurateTrackBounce: true, webvisor: false, trackHash: false}); + } + const missing = !!document.querySelector('main.missing'); + const url = missing ? window.location.origin + '/404/' : window.location.href.split('#')[0]; + if (window.location.pathname !== previousPath) { + window.ym(COUNTER_ID, 'hit', url, {title: document.title, referer: previousURL || document.referrer}); + previousURL = url; + previousPath = window.location.pathname; + } + const problems = new Set(); + function problem(reason) { + if (!problems.has(reason)) {problems.add(reason); trackGoal('content_problem', reason);} + } + if (missing) problem('not_found'); + const body = document.querySelector('main.article-shell .article-content'); + function imageError(event) { + if (event.target instanceof HTMLImageElement && event.target.closest('main.article-shell .article-content') && event.target.getAttribute('src')) problem('image_failed'); + } + document.addEventListener('error', imageError, true); + for (const img of body?.querySelectorAll('img') || []) { + if (img.complete && img.naturalWidth === 0 && img.getAttribute('src')) problem('image_failed'); + } + function fragment() { + if (!window.location.hash || window.location.hash === '#') return; + let id; + try {id = decodeURIComponent(window.location.hash.slice(1));} catch {problem('fragment_missing'); return;} + if (!document.getElementById(id) && ![...document.getElementsByName(id)].length) problem('fragment_missing'); + } + fragment(); + window.addEventListener('hashchange', fragment); + function click(event) { + if (!event.isTrusted || event.defaultPrevented || event.button !== 0) return; + const link = event.target.closest?.('a[href]'); + if (!link || link.getAttribute('aria-disabled') === 'true') return; + if (link.closest('.related')) trackGoal('related_content_click'); + if (link.hasAttribute('download')) trackGoal('download_click'); + } + document.addEventListener('click', click, true); + let elapsed = 0, last = performance.now(), active = document.visibilityState === 'visible' && document.hasFocus(), sent = false; + function tick() { + const now = performance.now(); + if (active) elapsed += now - last; + last = now; + active = document.visibilityState === 'visible' && document.hasFocus(); + if (!body || sent || !active || elapsed < 60000) return; + const rect = body.getBoundingClientRect(); + if (rect.height > 0 && (window.innerHeight - rect.top) / rect.height >= 0.75) { + sent = true; + trackGoal('engaged_read'); + } + } + const interval = body ? window.setInterval(tick, 1000) : null; + window.addEventListener('scroll', tick, {passive: true}); + window.addEventListener('focus', tick); + window.addEventListener('blur', tick); + document.addEventListener('visibilitychange', tick); + return () => { + if (interval !== null) window.clearInterval(interval); + window.removeEventListener('scroll', tick); + window.removeEventListener('focus', tick); + window.removeEventListener('blur', tick); + document.removeEventListener('visibilitychange', tick); + window.removeEventListener('hashchange', fragment); + document.removeEventListener('error', imageError, true); + document.removeEventListener('click', click, true); + }; +} diff --git a/web/public/build-identity.json b/web/public/build-identity.json index 787af84..a238089 100644 --- a/web/public/build-identity.json +++ b/web/public/build-identity.json @@ -1,4 +1,4 @@ { - "sourceHash": "53f217e5370ecafe41a0afcfe51fe80f2e443f04637adbe0d4f7476babe9beeb", + "sourceHash": "527ea7bf774eca2b18d9dcd2f1ab0ac0341fa87e50a160ad75aefb3e30ad31a2", "articles": 14 }