@preventive/triage 1.0.0-alpha.84 → 1.0.0-alpha.86

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/out/view.js CHANGED
@@ -1,4 +1,4 @@
1
- import"./chunk-R3NZFXVR.js";import{a as e,b as t,c as n,f as r,g as i,h as a,j as o}from"./chunk-K4D3BWQA.js";import{$a as s,$b as c,$c as l,A as u,Ab as d,Ac as f,B as p,Bb as m,Bc as h,Cb as g,Cc as ee,Db as te,Dc as ne,E as re,Eb as ie,Eg as ae,F as oe,Fb as se,Ff as ce,Fg as le,G as ue,Gb as de,Ge as fe,Gf as pe,Gg as me,Hg as he,I as ge,Ib as _e,Ig as ve,J as ye,Jb as be,Jg as xe,Kb as Se,Kg as Ce,L as we,La as Te,Lb as Ee,Lg as De,Ma as Oe,Mb as ke,Mg as _,N as Ae,Na as je,Nb as Me,Ng as Ne,O as Pe,Oa as Fe,Ob as Ie,Oc as Le,Og as Re,P as ze,Pa as Be,Pb as Ve,Pc as He,Q as Ue,R as v,Rb as We,Rg as Ge,Sb as Ke,Sg as qe,T as Je,Tb as Ye,Tg as Xe,Ub as Ze,Uc as Qe,Ug as $e,Vb as et,Vc as tt,Vf as y,Vg as nt,Wb as rt,Wc as it,Xa as at,Xb as ot,Xc as st,Yb as b,Yc as ct,Zb as lt,Zc as ut,_a as dt,_b as ft,_c as pt,a as mt,ab as ht,ac as gt,ad as _t,af as vt,b as x,bb as yt,bc as bt,bf as xt,c as St,cb as Ct,cc as wt,cf as Tt,d as Et,db as Dt,dc as Ot,de as kt,eb as At,ec as jt,ed as Mt,ef as Nt,f as Pt,fc as Ft,fd as It,fe as Lt,ff as Rt,g as zt,ga as Bt,gc as Vt,gd as Ht,ge as Ut,gf as Wt,ha as Gt,hc as Kt,he as qt,hf as S,i as Jt,ia as Yt,ic as Xt,ie as Zt,if as Qt,j as $t,ja as en,jb as tn,jc as nn,jf as rn,k as an,ka as on,kc as sn,kf as cn,lb as ln,lc as un,lf as dn,m as fn,mc as C,mf as pn,n as mn,na as hn,nb as gn,ne as _n,nf as vn,o as yn,ob as bn,of as xn,p as Sn,pb as Cn,pf as wn,q as Tn,qb as En,qe as Dn,qf as On,r as kn,rb as An,rc as jn,rf as Mn,sb as Nn,sc as Pn,sf as Fn,t as In,tb as Ln,td as Rn,u as w,ud as zn,uf as Bn,v as T,vc as Vn,vf as Hn,w as Un,wa as Wn,wc as E,wf as Gn,xc as Kn,yc as qn,zc as Jn}from"./chunk-7BLPGSCC.js";import"./chunk-A4BBBHQU.js";import"./chunk-6WMQVUT2.js";import"./chunk-VYYUMYVW.js";import"./chunk-7HP2VYIC.js";import"./chunk-N57OWFKY.js";import"./chunk-7YFJUT2P.js";import"./chunk-PXK7EU4V.js";import{d as Yn}from"./chunk-XHYX3Q34.js";import{$ as Xn,A as Zn,B as Qn,G as $n,O as er,Q as tr,W as nr,d as rr,ga as D,ja as ir,la as ar,q as or,w as sr,x as cr,y as lr}from"./chunk-V4U7URJF.js";import{f as ur,g as dr}from"./chunk-KP2XM324.js";import"./chunk-DUASGS2O.js";import"./chunk-NRPC74AM.js";import"./chunk-7BKKYVWR.js";import{f as O}from"./chunk-7C7DWL7I.js";import"./chunk-PNHBZGDD.js";import{$ as fr,G as pr,H as mr,P as hr,Q as gr,S as _r,a as k,ca as vr,e as yr,g as A,ga as br,h as j,ha as xr,i as Sr,n as Cr,na as wr,pa as Tr,sa as Er,w as Dr,z as Or}from"./chunk-LFPRRRJE.js";import{g as kr}from"./chunk-CE2FMDK3.js";import"./chunk-74JZTGTO.js";import"./chunk-IYPY47MC.js";import{d as Ar,i as jr,k as Mr,l as Nr,t as Pr,z as Fr}from"./chunk-G5JKKNZF.js";import{a as Ir,d as Lr}from"./chunk-PWFUOLZK.js";import"./chunk-C4Z6ZBXV.js";import{a as Rr,e as zr,f as Br,p as Vr,q as Hr,v as Ur,x as Wr,z as Gr}from"./chunk-ZQQALNFP.js";import{B as Kr,I as qr,h as Jr,l as Yr}from"./chunk-QRKFPLA4.js";import{a as M,b as Xr,c as N,g as P,i as Zr,j as F}from"./chunk-2XUEZHIP.js";import"./chunk-TUII34K2.js";import"./chunk-OOJM4CTU.js";var Qr={importedSideLabel:`Apply from chain`,applyButton:`Apply`},$r={attach:{title:`Synced triage on report attach`,intro:`have triage from your workspace that disagrees with your local view on`,trailingNote:`Other findings in this report whose chain value didn't conflict were applied automatically; this list only covers disagreements. Pick which side to keep.`,...Qr},chain:{title:`Triage conflict from peer update`,intro:`were changed by a peer (or by another tab) in a way that disagrees with your local triage on`,trailingNote:`Other findings whose remote value didn't conflict were applied automatically; this list only covers disagreements. Pick which side to keep for each — a "keep current" pick re-publishes your local value to the chain on your next save.`,...Qr}};function ei(){Ln(async(e,t,n)=>{let r=Ae(e);try{return await gn(e,r,$r[n]??$r.attach)}catch{let t=e.length;return alert(`${n===`attach`?`A report attach`:`A workspace sync`} had ${t} triage disagreement${t===1?``:`s`} with your local view. Kept your local values because another dialog is open. ${n===`attach`?`Detach and re-attach the report to pick again.`:`Your local values will re-publish to the chain on the next change.`}`),null}})}var ti=class extends Dt{static properties={_value:{state:!0}};static secrets={_value:``};constructor(){super(),this._value=``}_onInput=e=>{this._value=e.target.value};_onSubmit=()=>{this._value&&this._finish(this._value)};_onKeydown=tn(this._onSubmit);render(){return N`<dialog @close="${this._onClose}"><header><h3>Sync server password</h3></header><p class="nwd-intro">${this.retry?`That password didn't match. Try again, or cancel to leave the workspace unsynced for now.`:`This sync server requires a password before it accepts a new workspace. Enter it to create the workspace on the server.`}</p>${ln({name:`dv-sync-auth`,maxlength:4096,placeholder:`Password`,value:this._value,input:this._onInput,keydown:this._onKeydown})}<footer class="nwd-actions"><span class="nwd-spacer"></span> <button type="button" @click="${this._onCancel}">Cancel</button> <button type="button" class="primary" ?disabled="${!this._value}" @click="${this._onSubmit}">${this.retry?`Retry`:`Authenticate`}</button></footer></dialog>`}};customElements.define(`sync-auth-dialog`,ti);function ni({retry:e=!1}={}){return At(`sync-auth-dialog`,{retry:!!e})}function ri(){Nn(async({retry:e})=>{try{return await ni({retry:e})}catch(e){return console.warn(`Sync auth dialog failed to open:`,e),null}})}var ii=`https://triage.space/`,ai=[{hostname:`deepaudit.dev`,pathPrefix:`/`,supportsSync:!0},{hostname:`chalker.github.io`,pathPrefix:`/deepview/`,supportsSync:!1}];function oi(){return ai.find(e=>location.hostname===e.hostname&&location.pathname.startsWith(e.pathPrefix))??null}var si=[`deepview.triage`,`deepview.triage.pending`],ci=`deepview.repoUrls`;function li(){try{if(si.some(e=>localStorage.getItem(e)))return!0;let e=localStorage.getItem(ci);if(!e)return!1;let t=JSON.parse(e);return!!(t&&typeof t==`object`&&Object.keys(t).length>0)}catch{return!0}}async function ui(){if(li())return!0;let e=[];try{e=await Un()}catch{return!0}if(e.length>0)return!0;try{if(ye().length>0)return!0}catch{return!0}try{return await u()}catch{return!0}}var di=class extends F{static properties={supportsSync:{attribute:!1}};createRenderRoot(){return this}constructor(){super(),this.supportsSync=!1}firstUpdated(){this.querySelector(`dialog`)?.showModal(),this.querySelector(`button.om-stay`)?.focus()}_finish(e){this._settled||(this._settled=!0,this.querySelector(`dialog`)?.close(),this.dispatchEvent(new CustomEvent(`resolve`,{detail:e})))}_onStay=()=>this._finish(!1);_onMigrate=()=>this._finish(!0);render(){let e=()=>N`<a class="om-link" href="${ii}" target="_blank" rel="noopener noreferrer">${ii}</a>`;return N`<dialog class="origin-migration-dialog" @close="${this._onStay}"><header class="om-head"><h3>This deepview build has moved</h3><p><code>${location.host}${location.pathname}</code> has moved to ${e()}.</p></header><section class="om-body"><p>Workspaces and reports don't migrate automatically — they live in this origin's browser storage (OPFS where available, localStorage as a fallback) and have to be re-imported on ${e()}.</p>${this.supportsSync?N`<p>For each workspace, use the <strong>Export workspace</strong> button in the sidebar to download a <code>.gz</code> bundle (workspace + its reports + its triage), then drop that file on ${e()}. Workspaces that had sync configured will pick their triage state back up from the sync server once you re-import them with the same key.</p><p>For triage attached to loose reports (or as a top-up after re-importing workspaces), call <code>DeepView.export()</code> in the browser console — that downloads just the triage entries plus saved repo URLs, no reports or workspaces.</p>`:N`<p>This build has no sync layer. For each workspace, use the <strong>Export workspace</strong> button in the sidebar to download a <code>.gz</code> bundle (workspace + its reports + its triage), then drop that file on ${e()}.</p><p>For triage attached to loose reports, call <code>DeepView.export()</code> in the browser console — that downloads just the triage entries plus saved repo URLs, no reports or workspaces. Reports themselves need to be re-dropped from their original JSON on the new origin.</p>`}</section><footer class="om-actions"><button type="button" class="om-stay" @click="${this._onStay}">Keep editing on ${location.host}</button> <button type="button" class="primary om-go" @click="${this._onMigrate}">Switch to triage.space</button></footer></dialog>`}};customElements.define(`origin-migration-dialog`,di);function fi(e){return new Promise(t=>{let n=document.createElement(`origin-migration-dialog`);n.supportsSync=e.supportsSync,n.addEventListener(`resolve`,e=>{n.remove(),t(!!e.detail)}),document.body.append(n)})}async function pi(){let e=oi();return e?await ui()?await fi(e)?(location.assign(ii),!0):!1:(location.replace(ii),!0):!1}var I=null,mi=!1,hi=null,gi={NotAllowedError:``,AbortError:``,SecurityError:`The site identity does not match the one this passkey was registered for. If you opened DeepView through a different URL (different subdomain, different port), reload via the original URL.`,InvalidStateError:`The passkey state on this device is inconsistent. Try reloading the page or removing and re-creating the passkey.`,NotSupportedError:`This browser does not support the WebAuthn PRF extension this site needs. Try a recent Chrome, Safari, or Edge with a platform authenticator.`,NetworkError:`A network error prevented the passkey from completing. Check your connection and try again.`,UnknownError:`The authenticator returned an unknown error. Try again, or use a different passkey.`};function _i(e){if(!e)return`Could not unlock. Try again.`;let t=e.name??``;if(Object.hasOwn(gi,t))return gi[t];let n=e.message??String(e);return n.length>200?n.slice(0,197)+`…`:n}function vi(){if(I)return I;I=document.createElement(`div`),I.id=`lock-overlay`,I.setAttribute(`role`,`dialog`),I.setAttribute(`aria-modal`,`true`),I.setAttribute(`aria-label`,`Unlock DeepView`),Zr(N`<div class="lock-overlay-card"><div class="lock-overlay-icon" aria-hidden="true"><svg viewBox="0 0 32 32" width="40" height="40" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="7" y="15" width="18" height="12" rx="1.5"/><path d="M11 15v-4a5 5 0 0 1 10 0v4"/></svg></div><h2 class="lock-overlay-title">DeepView is locked</h2><p class="lock-overlay-body">Your triage data and reports are encrypted with a passkey on this device. Unlock to continue.</p><p class="lock-overlay-error" hidden></p><button type="button" class="lock-overlay-button primary">Unlock with passkey</button><p class="lock-overlay-footer">Lost your passkey? <a href="#" class="lock-overlay-wipe">Wipe local data and start over</a></p></div>`,I);let e=I.querySelector(`button`),t=I.querySelector(`.lock-overlay-error`);return e.addEventListener(`click`,async()=>{if(!mi&&yi()){mi=!0,t.hidden=!0,t.textContent=``,e.disabled=!0,e.textContent=`Waiting…`,hi=new AbortController;try{await zt({signal:hi.signal})}catch(e){let n=_i(e);t.textContent=n,t.hidden=!n}finally{mi=!1,hi=null,e.disabled=!1,e.textContent=`Unlock with passkey`}}}),I.querySelector(`.lock-overlay-wipe`).addEventListener(`click`,async e=>{if(e.preventDefault(),!mi&&yi()&&confirm(`Wipe ALL local DeepView data and start over?
1
+ import"./chunk-R3NZFXVR.js";import{a as e,b as t,c as n,f as r,g as i,h as a,j as o}from"./chunk-GM6GP6TA.js";import{$a as s,$b as c,$c as l,A as u,Ab as d,Ac as f,B as p,Bb as m,Bc as h,Cb as g,Cc as ee,Db as te,Dc as ne,E as re,Eb as ie,Eg as ae,F as oe,Fb as se,Ff as ce,Fg as le,G as ue,Gb as de,Ge as fe,Gf as pe,Gg as me,Hg as he,I as ge,Ib as _e,Ig as ve,J as ye,Jb as be,Jg as xe,Kb as Se,Kg as Ce,L as we,La as Te,Lb as Ee,Lg as De,Ma as Oe,Mb as ke,Mg as _,N as Ae,Na as je,Nb as Me,Ng as Ne,O as Pe,Oa as Fe,Ob as Ie,Oc as Le,Og as Re,P as ze,Pa as Be,Pb as Ve,Pc as He,Q as Ue,R as v,Rb as We,Rg as Ge,Sb as Ke,Sg as qe,T as Je,Tb as Ye,Tg as Xe,Ub as Ze,Uc as Qe,Ug as $e,Vb as et,Vc as tt,Vf as y,Vg as nt,Wb as rt,Wc as it,Xa as at,Xb as ot,Xc as st,Yb as b,Yc as ct,Zb as lt,Zc as ut,_a as dt,_b as ft,_c as pt,a as mt,ab as ht,ac as gt,ad as _t,af as vt,b as x,bb as yt,bc as bt,bf as xt,c as St,cb as Ct,cc as wt,cf as Tt,d as Et,db as Dt,dc as Ot,de as kt,eb as At,ec as jt,ed as Mt,ef as Nt,f as Pt,fc as Ft,fd as It,fe as Lt,ff as Rt,g as zt,ga as Bt,gc as Vt,gd as Ht,ge as Ut,gf as Wt,ha as Gt,hc as Kt,he as qt,hf as S,i as Jt,ia as Yt,ic as Xt,ie as Zt,if as Qt,j as $t,ja as en,jb as tn,jc as nn,jf as rn,k as an,ka as on,kc as sn,kf as cn,lb as ln,lc as un,lf as dn,m as fn,mc as C,mf as pn,n as mn,na as hn,nb as gn,ne as _n,nf as vn,o as yn,ob as bn,of as xn,p as Sn,pb as Cn,pf as wn,q as Tn,qb as En,qe as Dn,qf as On,r as kn,rb as An,rc as jn,rf as Mn,sb as Nn,sc as Pn,sf as Fn,t as In,tb as Ln,td as Rn,u as w,ud as zn,uf as Bn,v as T,vc as Vn,vf as Hn,w as Un,wa as Wn,wc as E,wf as Gn,xc as Kn,yc as qn,zc as Jn}from"./chunk-2F7GGMMR.js";import"./chunk-A4BBBHQU.js";import"./chunk-6WMQVUT2.js";import"./chunk-VYYUMYVW.js";import"./chunk-7HP2VYIC.js";import"./chunk-N57OWFKY.js";import"./chunk-7YFJUT2P.js";import"./chunk-PXK7EU4V.js";import{d as Yn}from"./chunk-XHYX3Q34.js";import{$ as Xn,A as Zn,B as Qn,G as $n,O as er,Q as tr,W as nr,d as rr,ga as D,ja as ir,la as ar,q as or,w as sr,x as cr,y as lr}from"./chunk-V4U7URJF.js";import{f as ur,g as dr}from"./chunk-KP2XM324.js";import"./chunk-DUASGS2O.js";import"./chunk-NRPC74AM.js";import"./chunk-7BKKYVWR.js";import{f as O}from"./chunk-7C7DWL7I.js";import"./chunk-PNHBZGDD.js";import{$ as fr,G as pr,H as mr,P as hr,Q as gr,S as _r,a as k,ca as vr,e as yr,g as A,ga as br,h as j,ha as xr,i as Sr,n as Cr,na as wr,pa as Tr,sa as Er,w as Dr,z as Or}from"./chunk-ULI2BIWN.js";import{g as kr}from"./chunk-CE2FMDK3.js";import"./chunk-74JZTGTO.js";import"./chunk-IYPY47MC.js";import{d as Ar,i as jr,k as Mr,l as Nr,t as Pr,z as Fr}from"./chunk-G5JKKNZF.js";import{a as Ir,d as Lr}from"./chunk-PWFUOLZK.js";import"./chunk-C4Z6ZBXV.js";import{a as Rr,e as zr,f as Br,p as Vr,q as Hr,v as Ur,x as Wr,z as Gr}from"./chunk-ZQQALNFP.js";import{B as Kr,I as qr,h as Jr,l as Yr}from"./chunk-QRKFPLA4.js";import{a as M,b as Xr,c as N,g as P,i as Zr,j as F}from"./chunk-2XUEZHIP.js";import"./chunk-TUII34K2.js";import"./chunk-OOJM4CTU.js";var Qr={importedSideLabel:`Apply from chain`,applyButton:`Apply`},$r={attach:{title:`Synced triage on report attach`,intro:`have triage from your workspace that disagrees with your local view on`,trailingNote:`Other findings in this report whose chain value didn't conflict were applied automatically; this list only covers disagreements. Pick which side to keep.`,...Qr},chain:{title:`Triage conflict from peer update`,intro:`were changed by a peer (or by another tab) in a way that disagrees with your local triage on`,trailingNote:`Other findings whose remote value didn't conflict were applied automatically; this list only covers disagreements. Pick which side to keep for each — a "keep current" pick re-publishes your local value to the chain on your next save.`,...Qr}};function ei(){Ln(async(e,t,n)=>{let r=Ae(e);try{return await gn(e,r,$r[n]??$r.attach)}catch{let t=e.length;return alert(`${n===`attach`?`A report attach`:`A workspace sync`} had ${t} triage disagreement${t===1?``:`s`} with your local view. Kept your local values because another dialog is open. ${n===`attach`?`Detach and re-attach the report to pick again.`:`Your local values will re-publish to the chain on the next change.`}`),null}})}var ti=class extends Dt{static properties={_value:{state:!0}};static secrets={_value:``};constructor(){super(),this._value=``}_onInput=e=>{this._value=e.target.value};_onSubmit=()=>{this._value&&this._finish(this._value)};_onKeydown=tn(this._onSubmit);render(){return N`<dialog @close="${this._onClose}"><header><h3>Sync server password</h3></header><p class="nwd-intro">${this.retry?`That password didn't match. Try again, or cancel to leave the workspace unsynced for now.`:`This sync server requires a password before it accepts a new workspace. Enter it to create the workspace on the server.`}</p>${ln({name:`dv-sync-auth`,maxlength:4096,placeholder:`Password`,value:this._value,input:this._onInput,keydown:this._onKeydown})}<footer class="nwd-actions"><span class="nwd-spacer"></span> <button type="button" @click="${this._onCancel}">Cancel</button> <button type="button" class="primary" ?disabled="${!this._value}" @click="${this._onSubmit}">${this.retry?`Retry`:`Authenticate`}</button></footer></dialog>`}};customElements.define(`sync-auth-dialog`,ti);function ni({retry:e=!1}={}){return At(`sync-auth-dialog`,{retry:!!e})}function ri(){Nn(async({retry:e})=>{try{return await ni({retry:e})}catch(e){return console.warn(`Sync auth dialog failed to open:`,e),null}})}var ii=`https://triage.space/`,ai=[{hostname:`deepaudit.dev`,pathPrefix:`/`,supportsSync:!0},{hostname:`chalker.github.io`,pathPrefix:`/deepview/`,supportsSync:!1}];function oi(){return ai.find(e=>location.hostname===e.hostname&&location.pathname.startsWith(e.pathPrefix))??null}var si=[`deepview.triage`,`deepview.triage.pending`],ci=`deepview.repoUrls`;function li(){try{if(si.some(e=>localStorage.getItem(e)))return!0;let e=localStorage.getItem(ci);if(!e)return!1;let t=JSON.parse(e);return!!(t&&typeof t==`object`&&Object.keys(t).length>0)}catch{return!0}}async function ui(){if(li())return!0;let e=[];try{e=await Un()}catch{return!0}if(e.length>0)return!0;try{if(ye().length>0)return!0}catch{return!0}try{return await u()}catch{return!0}}var di=class extends F{static properties={supportsSync:{attribute:!1}};createRenderRoot(){return this}constructor(){super(),this.supportsSync=!1}firstUpdated(){this.querySelector(`dialog`)?.showModal(),this.querySelector(`button.om-stay`)?.focus()}_finish(e){this._settled||(this._settled=!0,this.querySelector(`dialog`)?.close(),this.dispatchEvent(new CustomEvent(`resolve`,{detail:e})))}_onStay=()=>this._finish(!1);_onMigrate=()=>this._finish(!0);render(){let e=()=>N`<a class="om-link" href="${ii}" target="_blank" rel="noopener noreferrer">${ii}</a>`;return N`<dialog class="origin-migration-dialog" @close="${this._onStay}"><header class="om-head"><h3>This deepview build has moved</h3><p><code>${location.host}${location.pathname}</code> has moved to ${e()}.</p></header><section class="om-body"><p>Workspaces and reports don't migrate automatically — they live in this origin's browser storage (OPFS where available, localStorage as a fallback) and have to be re-imported on ${e()}.</p>${this.supportsSync?N`<p>For each workspace, use the <strong>Export workspace</strong> button in the sidebar to download a <code>.gz</code> bundle (workspace + its reports + its triage), then drop that file on ${e()}. Workspaces that had sync configured will pick their triage state back up from the sync server once you re-import them with the same key.</p><p>For triage attached to loose reports (or as a top-up after re-importing workspaces), call <code>DeepView.export()</code> in the browser console — that downloads just the triage entries plus saved repo URLs, no reports or workspaces.</p>`:N`<p>This build has no sync layer. For each workspace, use the <strong>Export workspace</strong> button in the sidebar to download a <code>.gz</code> bundle (workspace + its reports + its triage), then drop that file on ${e()}.</p><p>For triage attached to loose reports, call <code>DeepView.export()</code> in the browser console — that downloads just the triage entries plus saved repo URLs, no reports or workspaces. Reports themselves need to be re-dropped from their original JSON on the new origin.</p>`}</section><footer class="om-actions"><button type="button" class="om-stay" @click="${this._onStay}">Keep editing on ${location.host}</button> <button type="button" class="primary om-go" @click="${this._onMigrate}">Switch to triage.space</button></footer></dialog>`}};customElements.define(`origin-migration-dialog`,di);function fi(e){return new Promise(t=>{let n=document.createElement(`origin-migration-dialog`);n.supportsSync=e.supportsSync,n.addEventListener(`resolve`,e=>{n.remove(),t(!!e.detail)}),document.body.append(n)})}async function pi(){let e=oi();return e?await ui()?await fi(e)?(location.assign(ii),!0):!1:(location.replace(ii),!0):!1}var I=null,mi=!1,hi=null,gi={NotAllowedError:``,AbortError:``,SecurityError:`The site identity does not match the one this passkey was registered for. If you opened DeepView through a different URL (different subdomain, different port), reload via the original URL.`,InvalidStateError:`The passkey state on this device is inconsistent. Try reloading the page or removing and re-creating the passkey.`,NotSupportedError:`This browser does not support the WebAuthn PRF extension this site needs. Try a recent Chrome, Safari, or Edge with a platform authenticator.`,NetworkError:`A network error prevented the passkey from completing. Check your connection and try again.`,UnknownError:`The authenticator returned an unknown error. Try again, or use a different passkey.`};function _i(e){if(!e)return`Could not unlock. Try again.`;let t=e.name??``;if(Object.hasOwn(gi,t))return gi[t];let n=e.message??String(e);return n.length>200?n.slice(0,197)+`…`:n}function vi(){if(I)return I;I=document.createElement(`div`),I.id=`lock-overlay`,I.setAttribute(`role`,`dialog`),I.setAttribute(`aria-modal`,`true`),I.setAttribute(`aria-label`,`Unlock DeepView`),Zr(N`<div class="lock-overlay-card"><div class="lock-overlay-icon" aria-hidden="true"><svg viewBox="0 0 32 32" width="40" height="40" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="7" y="15" width="18" height="12" rx="1.5"/><path d="M11 15v-4a5 5 0 0 1 10 0v4"/></svg></div><h2 class="lock-overlay-title">DeepView is locked</h2><p class="lock-overlay-body">Your triage data and reports are encrypted with a passkey on this device. Unlock to continue.</p><p class="lock-overlay-error" hidden></p><button type="button" class="lock-overlay-button primary">Unlock with passkey</button><p class="lock-overlay-footer">Lost your passkey? <a href="#" class="lock-overlay-wipe">Wipe local data and start over</a></p></div>`,I);let e=I.querySelector(`button`),t=I.querySelector(`.lock-overlay-error`);return e.addEventListener(`click`,async()=>{if(!mi&&yi()){mi=!0,t.hidden=!0,t.textContent=``,e.disabled=!0,e.textContent=`Waiting…`,hi=new AbortController;try{await zt({signal:hi.signal})}catch(e){let n=_i(e);t.textContent=n,t.hidden=!n}finally{mi=!1,hi=null,e.disabled=!1,e.textContent=`Unlock with passkey`}}}),I.querySelector(`.lock-overlay-wipe`).addEventListener(`click`,async e=>{if(e.preventDefault(),!mi&&yi()&&confirm(`Wipe ALL local DeepView data and start over?
2
2
 
3
3
  This deletes your encrypted triage, all reports, and the passkey registration on this device. The data CANNOT be recovered after this — there is no backup.
4
4
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@preventive/triage",
3
- "version": "1.0.0-alpha.84",
3
+ "version": "1.0.0-alpha.86",
4
4
  "description": "Client & relay server for triaging of automated reports",
5
5
  "license": "MIT OR Apache-2.0",
6
6
  "author": {
@@ -205,6 +205,7 @@
205
205
  "server-managed/repository-squashes.ts",
206
206
  "server-managed/repository-issues.ts",
207
207
  "server-managed/repository-pulse.ts",
208
+ "server-managed/pulse-walk.ts",
208
209
  "server-managed/repository-pulls.ts",
209
210
  "server-managed/listed-activity.ts",
210
211
  "server-managed/repository-stamp.ts",
@@ -299,6 +300,8 @@
299
300
  "common/github-issue-labels.js",
300
301
  "common/github-issue-labels.d.ts",
301
302
  "common/gzip.js",
303
+ "common/npm-token.d.ts",
304
+ "common/npm-token.js",
302
305
  "common/pretty-json.js",
303
306
  "common/pretty-kinds.js",
304
307
  "common/pretty-print.d.ts",
@@ -465,7 +468,7 @@
465
468
  "@preventive/publishers": "^1.1.0",
466
469
  "@preventive/report": "^1.0.1",
467
470
  "@preventive/sourcemap": "1.0.0-alpha.1",
468
- "@preventive/upstream": "^1.12.0",
471
+ "@preventive/upstream": "^1.13.1",
469
472
  "css-tree": "^3.2.1",
470
473
  "oxc-minify": "^0.159.0",
471
474
  "oxc-parser": "^0.152.0",
@@ -22,8 +22,8 @@
22
22
  // days, `{ start, end, days }`, or `{ none: true }` where npm counts none.
23
23
  //
24
24
  // The package assessed is asked for as upstream asks, with the npm token the
25
- // environment has for a scoped one (PREVENTIVE_MEASURES_NPM_TOKEN,
26
- // STASIS_NPM_TOKEN or NPM_TOKEN), so a private one can be read; its
25
+ // environment has for a scoped one (npm-token.js npmTokenFor), so a private
26
+ // one can be read; its
27
27
  // dependencies' public facts and downloads with none. A caller may ask for
28
28
  // packages' documents (`packument`) and versions' tarballs (`tarball`)
29
29
  // itself, as the managed server does, within the bounds it holds every read
@@ -36,6 +36,7 @@
36
36
  import { advisories } from '@preventive/upstream/advisories.js'
37
37
  import { getTarball } from '@preventive/upstream/npm.js'
38
38
  import { compareVersions, satisfies, validRange } from '@preventive/upstream/semver.js'
39
+ import { npmTokenFor } from '../../common/npm-token.js'
39
40
  import { npmVersionManifest } from './manifest.js'
40
41
  import { npmAlias } from './specs.js'
41
42
  import { npmPlaceholder } from './malware.js'
@@ -76,8 +77,6 @@ const plainObject = value => Boolean(value) && typeof value === 'object' && !Arr
76
77
 
77
78
  // A scoped name in a downloads API path, its slash escaped.
78
79
  const encoded = name => name.replace('/', '%2f')
79
- const token = () => typeof process === 'undefined' ? null
80
- : ['PREVENTIVE_MEASURES_NPM_TOKEN', 'STASIS_NPM_TOKEN', 'NPM_TOKEN'].map(key => process.env[key]).find(Boolean) ?? null
81
80
 
82
81
  // A value kept under `type` and `key`, else `ask`ed and kept; one `fresh`
83
82
  // says is stale asked again.
@@ -129,7 +128,7 @@ async function askNpm(url, headers, limit, what, { signal }) {
129
128
  // caller's (`packument`) where it gives one, else risk's own.
130
129
  function packageDocument(name, context, authorized) {
131
130
  if (context.packument) return context.packument(name, { authorized, signal: context.signal })
132
- const secret = authorized && name.startsWith('@') ? token() : null
131
+ const secret = authorized && name.startsWith('@') ? npmTokenFor(name) : null
133
132
  return askNpm(`${REGISTRY}/${name}`, secret ? { authorization: `Bearer ${secret}` } : {}, PACKUMENT_BYTES, name, context)
134
133
  }
135
134
 
@@ -147,7 +147,7 @@ export async function buildStasisBundle({ input, github, token, maxBytes, scopes
147
147
  // Upstream's disk cache keeps the npm tarballs and version documents, and
148
148
  // the repo's tree, in `cacheDir`; without one (Vercel), what it downloads
149
149
  // of npm is kept in `instanceDir` (cacheOf), where one is given. This fresh
150
- // worker inherits no application credentials but NPM_TOKEN.
150
+ // worker inherits no application credentials but the npm tokens (workerEnv).
151
151
  setCacheDir(cacheDir ?? false)
152
152
  progress('build')
153
153
  // Entries stasis.config.json lists are built from its directory, where
@@ -3,6 +3,7 @@ import { createHash, randomUUID } from 'node:crypto'
3
3
  import { tmpdir, totalmem } from 'node:os'
4
4
  import { join, posix } from 'node:path'
5
5
  import { Worker } from 'node:worker_threads'
6
+ import { isNpmTokenName } from '../common/npm-token.js'
6
7
  import { BUNDLE_BUILD_TIMEOUT_MS, type BundleBuildLeaseStore } from './bundle-build-leases.ts'
7
8
  import { type BundleBuildDiagnostic, type BundleBuildStage, bundleBuildDiagnostic } from './bundle-build-diagnostics.js'
8
9
  import type { BundleBuildConditions } from './db-methods.ts'
@@ -124,8 +125,7 @@ interface BuiltBundle { bytes: Buffer; directory: string; filename: string }
124
125
  interface BuildRequest {
125
126
  input: BundleBuildInput; github: string; token: string | null; maxBytes: number; scopes: (string | null)[]
126
127
  // Upstream's disk cache for what a build fetches (setCacheDir), or null for
127
- // none, as on Vercel. Resolved here: the worker's env holds NPM_TOKEN and
128
- // VERCEL_ENV alone.
128
+ // none, as on Vercel. Resolved here, as the worker's env is workerEnv's.
129
129
  cacheDir: string | null
130
130
  }
131
131
  // A version a Stasis lockfile holds, as the worker tells it in place of a
@@ -203,6 +203,13 @@ export async function withBundleBuildLease<T>(db: BundleBuildLeaseStore, userId:
203
203
  }
204
204
  }
205
205
 
206
+ // The npm tokens, for private scoped packages, and VERCEL_ENV, by which Stasis
207
+ // skips oxc-parser's raw transfer on Vercel; no other credential.
208
+ export function workerEnv(env: NodeJS.ProcessEnv = process.env): Record<string, string> {
209
+ const passed = Object.entries(env).filter((entry): entry is [string, string] => isNpmTokenName(entry[0]) && Boolean(entry[1]))
210
+ return Object.fromEntries(env['VERCEL_ENV'] === undefined ? passed : [...passed, ['VERCEL_ENV', env['VERCEL_ENV']]])
211
+ }
212
+
206
213
  // Parsing repositories and compressing bundles stays off the HTTP event loop.
207
214
  // Cap concurrent builds, terminate disconnected/timed-out work, and share no
208
215
  // credentials or mutable Stasis state between requests.
@@ -269,15 +276,8 @@ async function runBuild<M, T>(owner: string, request: { token: string | null },
269
276
  try {
270
277
  workerUrl = new URL('./bundle-build-worker.js', import.meta.url)
271
278
  log('started')
272
- // Upstream reads NPM_TOKEN from the env for scoped packages, which npm
273
- // answers with 404 when private and asked without it. Stasis reads
274
- // VERCEL_ENV, set or not as here, to parse without oxc-parser's raw
275
- // transfer on Vercel, whose functions can't reserve its 6 GiB buffer.
276
- // Nothing else passes.
277
- const npmToken = process.env['NPM_TOKEN'], vercelEnv = process.env['VERCEL_ENV']
278
- const env = { ...(npmToken ? { NPM_TOKEN: npmToken } : {}), ...(vercelEnv === undefined ? {} : { VERCEL_ENV: vercelEnv }) }
279
279
  worker = new Worker(workerUrl, {
280
- workerData: { ...request, type: 'managed-bundle-build' }, env, execArgv: [], resourceLimits: { maxOldGenerationSizeMb: heapLimitMib },
280
+ workerData: { ...request, type: 'managed-bundle-build' }, env: workerEnv(), execArgv: [], resourceLimits: { maxOldGenerationSizeMb: heapLimitMib },
281
281
  })
282
282
  const running = worker
283
283
  return await new Promise((resolve, reject) => {
@@ -162,7 +162,7 @@ import { pipeline } from 'node:stream/promises'
162
162
  import { setTimeout as delay } from 'node:timers/promises'
163
163
  import { type KeptStore, REPOSITORY_READ_KEPT_MS, authoredCommitStore, branchTipStore, bundleValidationStore, codeHeadStore, codeTreeStore, commitPullStore, githubTagStore, historyChangeStore, historyPageStore, historySquashStore, historyTreeStore,
164
164
  issueListStore, lockfileReadStore,
165
- npmDeltaStore, npmPublishTimeStore, npmVersionDeltaStore, npmVersionStore, ownKeptPrunes, patchStore, privateVersionDeltaStore, pullDependencyStore, pullListStore, repositoryReadStore,
165
+ npmDeltaStore, npmPublishTimeStore, npmVersionDeltaStore, npmVersionStore, ownKeptPrunes, patchStore, privateVersionDeltaStore, pullDependencyStore, pullListStore, pulseWalkStore, repositoryReadStore,
166
166
  reviewBaselineStore, riskKeptStore, riskLineStore,
167
167
  scanReadStore, stasisDependencyStore, teamDependencyStore } from './npm-kept.ts'
168
168
  import { plainObject } from './npm-manifest.ts'
@@ -218,6 +218,7 @@ import { keptRepositories } from './repository-risk-kept.ts'
218
218
  import { type RiskStasisRead, lockfileOf, stasisConfigRow } from './repository-risk-read.ts'
219
219
  import { WORKFLOWS_DIR } from './repository-actions.ts'
220
220
  import { githubActionsSource } from './github-actions.ts'
221
+ import { type KeptWalk, keptWalk } from './pulse-walk.ts'
221
222
  import { type RepositoryEntry, createRepositoryBrowser, repositoryTreeFiles, scopedDirectory } from './repository-browser.ts'
222
223
  import { type Lru, lru } from './lru.ts'
223
224
  import { CALLBACK_PATH, LOGIN_PATH, OAuthError, buildLoginRedirect, cacheAvatar, ensureUserAccessToken, handleCallback } from './github-oauth.ts'
@@ -3324,10 +3325,14 @@ async function handleRepositoryPulse(res: ServerResponse, deps: ManagedHttpDeps,
3324
3325
  // counted), the year read on behind it (`behind`, for the client to ask
3325
3326
  // again till it is, however long a page of it takes to read); those
3326
3327
  // asking meanwhile, by the database, the repository and the period, waiting
3327
- // on that read, not one of their own, unless it began PULSE_YEAR_HELD_MS ago
3328
- // or longer.
3328
+ // on that read, not one of their own, unless its last part began
3329
+ // PULSE_YEAR_HELD_MS ago or longer. Off serverless, read on part after part
3330
+ // behind its answers till the year is read whole, as long as each part reads
3331
+ // more, as many as PULSE_YEAR_PARTS; on serverless, a part an answer, each
3332
+ // going on from the last (keptWalk).
3329
3333
  const PULSE_YEAR_WAIT_MS = 1500
3330
3334
  const PULSE_YEAR_HELD_MS = 60_000
3335
+ const PULSE_YEAR_PARTS = 200
3331
3336
  type PulseYear = Awaited<ReturnType<typeof pulseCommits>>
3332
3337
  type PulseYearRead = { reading: Promise<PulseYear>; progress: { commits: number }; began: number }
3333
3338
  const pulseYearReads = new WeakMap<ManagedDb, Map<string, PulseYearRead>>()
@@ -3338,7 +3343,20 @@ function pulseYearRead(deps: ManagedHttpDeps, repoId: number, fullName: string,
3338
3343
  const held = reads.get(key)
3339
3344
  if (held && Date.now() - held.began < PULSE_YEAR_HELD_MS) return held
3340
3345
  const progress = { commits: 0 }
3341
- const year = { reading: pulseCommits(deps, repoId, fullName, token, weeks, progress), progress, began: Date.now() }
3346
+ // How far a part read: its commits, else the pull requests merged; null, whole.
3347
+ const reached = (part: PulseYear) => part.reading ?? part.pulls
3348
+ const readOn = async () => {
3349
+ let part = await pulseCommits(deps, repoId, fullName, token, weeks, progress)
3350
+ for (let parts = 1; !deps.config.serverless && reached(part) !== null && parts < PULSE_YEAR_PARTS; parts++) {
3351
+ year.began = Date.now()
3352
+ const next = await pulseCommits(deps, repoId, fullName, token, weeks, progress)
3353
+ const further = reached(next) === null || reached(next)! > reached(part)! || (part.reading === null) !== (next.reading === null)
3354
+ part = next
3355
+ if (!further) break
3356
+ }
3357
+ return part
3358
+ }
3359
+ const year: PulseYearRead = { reading: readOn(), progress, began: Date.now() }
3342
3360
  reads.set(key, year)
3343
3361
  const settled = year.reading.catch((err: unknown) => { console.warn('managed: pulse year read failed:', err) })
3344
3362
  .finally(() => { if (reads.get(key) === year) reads.delete(key) })
@@ -3440,6 +3458,18 @@ async function pulseCommits(deps: ManagedHttpDeps, repoId: number, fullName: str
3440
3458
  const mergesKey = pulseMergesKey(repoId)
3441
3459
  const last = () => lastPulseYear(deps, repoId, first)
3442
3460
  const sha = head.sha
3461
+ // What walks of its year found, from this head or one before, gone on from
3462
+ // (pulse-walk.ts keptWalk), as the pages of its history every tab reads
3463
+ // hold them: a walk cut short not begun again, a head moved on read only as
3464
+ // far as what is new.
3465
+ const walk = keptWalk(pulseWalkStore<KeptWalk>(deps.db, deps.config.debug), `${repoId}\0${COAUTHORS_READ}\0${PULSE_YEAR_VERSION}`,
3466
+ historyPages(deps, repoId, true))
3467
+ const walkTo = async (back: number, progressed: (read: number) => void = () => {}) => {
3468
+ const known = await walk.read()
3469
+ const year = await yearCommits(fullName, token, sha, first, walk.pages, globalThis.fetch, back, progressed, known)
3470
+ await walk.write(known, year.walked, first)
3471
+ return year
3472
+ }
3443
3473
  // What tells whose the year's commits are, kept as read: the agents' pull
3444
3474
  // requests merged (agentMerges), as the pull requests kept tell, read as
3445
3475
  // far back as `whole` (keptPulls), and the commits that release the
@@ -3484,7 +3514,7 @@ async function pulseCommits(deps: ManagedHttpDeps, repoId: number, fullName: str
3484
3514
  const read = await attribution(whole)
3485
3515
  const same = kept && sameMerges(read, kept) && read.releases!.join() === (kept.releases ?? []).join() && readTo(kept) <= readTo(read)
3486
3516
  if (readTo(read) >= whole || same) return read
3487
- const year = await yearCommits(fullName, token, sha, first, historyPages(deps, repoId, true), globalThis.fetch, whole)
3517
+ const year = await walkTo(whole)
3488
3518
  if (year.complete) recounted.stats = await count(year, read, whole)
3489
3519
  return read
3490
3520
  }, () => true, false, stampOf(deps, repoId, fullName, token, today())).catch((err: unknown) => { console.warn('managed: pulse attribution read failed:', err) })
@@ -3508,8 +3538,7 @@ async function pulseCommits(deps: ManagedHttpDeps, repoId: number, fullName: str
3508
3538
  // period's count takes its place.
3509
3539
  if (!tooMany && held && 'tooMany' in held) await store.write(tooManyKey, { within: first }, Date.now())
3510
3540
  if (need > tooManyWithin) {
3511
- const [year, read] = await Promise.all([yearCommits(fullName, token, sha, first, historyPages(deps, repoId, true), globalThis.fetch, need,
3512
- commits => { progress.commits = commits }), attribution(need)])
3541
+ const [year, read] = await Promise.all([walkTo(need, commits => { progress.commits = commits }), attribution(need)])
3513
3542
  await store.write(mergesKey, read, Date.now())
3514
3543
  if (year.complete) {
3515
3544
  if (readTo(read) >= need) return { stats: await last(), reading: null, pulls: read.next?.read ?? 0, pending: false, kept: false }
@@ -166,6 +166,9 @@ export const githubTagStore = <T>(db: UpstreamCacheStore, debug = false): KeptSt
166
166
  // they were last read from GitHub.
167
167
  const HISTORY_PAGE_KEPT_MS = 30 * 24 * 60 * 60_000
168
168
  export const historyPageStore = <T>(db: UpstreamCacheStore, debug = false): KeptStore<T> => keptStore<T>(db, 'repository/history', HISTORY_PAGE_KEPT_MS, debug)
169
+ // What the Pulse's walks of a repository's year found (pulse-walk.ts
170
+ // keptWalk), as the history pages holding it, kept as those pages are.
171
+ export const pulseWalkStore = <T>(db: UpstreamCacheStore, debug = false): KeptStore<T> => keptStore<T>(db, 'repository/pulse-walk', HISTORY_PAGE_KEPT_MS, debug)
169
172
  // The pull requests squashed into a repository's commits, by the commit
170
173
  // (repository-squashes.ts squashedPulls): kept as its history's pages are.
171
174
  export const historySquashStore = <T>(db: UpstreamCacheStore, debug = false): KeptStore<T> => keptStore<T>(db, 'repository/squashes', HISTORY_PAGE_KEPT_MS, debug)
@@ -7,10 +7,11 @@ import { Buffer } from 'node:buffer'
7
7
  import { homedir } from 'node:os'
8
8
  import { join, resolve } from 'node:path'
9
9
  import { CompressionError, decompress } from '@preventive/archive/compression.js'
10
+ import { npmTokenFor } from '../common/npm-token.js'
10
11
  import { encodeBrotli } from './brotli.ts'
11
12
  import { keptBriefly } from './kept-briefly.ts'
12
13
  import { MAX_NPM_PACKAGE_BYTES, MAX_NPM_PACKAGE_FILES, NPM_REGISTRY, NpmPackageError, type NpmPackageFile, type NpmVersionDocument, type TarReading,
13
- askUpstream, npmExecutablePaths, npmFileRows, npmPublishTime, npmToken, readNpmTar } from './npm-packages.ts'
14
+ askUpstream, npmExecutablePaths, npmFileRows, npmPublishTime, readNpmTar } from './npm-packages.ts'
14
15
  import { keepFile, readKeptFile, upstreamCachePath } from './upstream-cache.ts'
15
16
 
16
17
  // The tar stream a package's files may come in, headers and padding included.
@@ -142,10 +143,9 @@ function npmCachePath(hash: string): string | null {
142
143
  return join(root, '_cacache', 'content-v2', 'sha512', hex.slice(0, 2), hex.slice(2, 4), hex.slice(4))
143
144
  }
144
145
 
145
- // The version's tarball from the registry, at the package's own path: with
146
- // the token only for a private version, and its size bounded as it arrives.
147
- async function downloadTarball(url: string, isPrivate: boolean): Promise<Buffer> {
148
- const token = isPrivate ? npmToken() : null
146
+ // The version's tarball from the registry, at the package's own path, its
147
+ // size bounded as it arrives.
148
+ async function downloadTarball(url: string, token: string | null): Promise<Buffer> {
149
149
  const bytes = await askUpstream(url, { headers: token ? { authorization: `Bearer ${token}` } : {}, limit: MAX_TAR_BYTES, ms: TARBALL_TIMEOUT_MS, absent: [401, 403, 404] })
150
150
  .catch((err: unknown) => { throw err instanceof NpmPackageError && err.message === 'upstream-too-large' ? new NpmPackageError(413, 'package-too-large') : err })
151
151
  if (bytes === null) throw new NpmPackageError(404, 'package-not-found')
@@ -169,7 +169,7 @@ async function readTarball(doc: NpmVersionDocument): Promise<Uint8Array> {
169
169
  if (bytes && await hashedAs(bytes, expected, shasum)) return bytes
170
170
  }
171
171
  }
172
- const bytes = await downloadTarball(url, doc.private)
172
+ const bytes = await downloadTarball(url, doc.private ? npmTokenFor(doc.name) : null)
173
173
  if (!await hashedAs(bytes, expected, shasum)) throw new NpmPackageError(502, 'upstream-invalid')
174
174
  if (kept !== null) await keepFile(kept, bytes)
175
175
  return bytes
@@ -2,8 +2,9 @@
2
2
  // registry's tarball, for the Overview and Code tabs the bundle view shows.
3
3
  //
4
4
  // Anyone with workspace access may read a public package. A private one also
5
- // needs NPM_TOKEN on the server, and a reader with access to it: an admin or
6
- // manager, or a member of a visible team listing its scope (team-npm-scopes.ts).
5
+ // needs an npm token for its scope on the server (npm-token.js), and a reader
6
+ // with access to it: an admin or manager, or a member of a visible team
7
+ // listing its scope (team-npm-scopes.ts).
7
8
  // For everyone else, a version is public only when the registry answers for
8
9
  // it without credentials, asked on every request and never from a cache:
9
10
  // upstream's caches, which bundle builds fill using the token, hold no
@@ -17,6 +18,7 @@ import { resolve } from 'node:path'
17
18
  import { ArchiveError, type Entry, unpack } from '@preventive/archive/tar.js'
18
19
  import { isExactVersion } from '@preventive/upstream/semver.js'
19
20
  import { isNpmPackageName, isNpmPackageSpec, npmPackageScope } from '../common/managed/npm-packages.js'
21
+ import { npmTokenFor } from '../common/npm-token.js'
20
22
  import { NPM_SYMLINKS_ABOVE, npmTarLayout } from '../risk/index.js'
21
23
  import type { Role } from '../common/managed/roles.ts'
22
24
  import { npmManifest, npmVersionFields, plainObject, stringRecord } from './npm-manifest.ts'
@@ -62,13 +64,11 @@ export function canReadPrivateNpm(reader: NpmReader, name: string): boolean {
62
64
  export const npmScopesCount = (role: Role, names: readonly string[]): boolean =>
63
65
  role !== 'admin' && role !== 'manage' && names.some(name => npmPackageScope(name) !== null)
64
66
 
65
- export const npmToken = () => process.env['NPM_TOKEN'] || null
66
-
67
67
  // Whether a read of `name` that npm answers none anonymously is asked again
68
68
  // with the server's token: by a reader with private access (`privileged`),
69
69
  // where there is a token and the package is scoped, as npm's private packages
70
70
  // always are. Else the anonymous answer is the reader's.
71
- export const npmTokenReads = (name: string, privileged: boolean): boolean => privileged && npmToken() !== null && npmPackageScope(name) !== null
71
+ export const npmTokenReads = (name: string, privileged: boolean): boolean => privileged && npmPackageScope(name) !== null && npmTokenFor(name) !== null
72
72
 
73
73
  function registryUrl(name: string, spec?: string): string {
74
74
  return `${NPM_REGISTRY}/${name}${spec === undefined ? '' : `/${encodeURIComponent(spec)}`}`
@@ -215,7 +215,7 @@ async function readDocument(name: string, url: string, privileged: boolean,
215
215
  const open = anonymous ? whole ? await sharedWholeDocument(name, url, options) : await registryDocument(url, { ...options, token: null }) : null
216
216
  if (open) return { json: open, private: false }
217
217
  if (!npmTokenReads(name, privileged)) return null
218
- const json = await registryDocument(url, { ...options, token: npmToken() })
218
+ const json = await registryDocument(url, { ...options, token: npmTokenFor(name) })
219
219
  return json ? { json, private: true } : null
220
220
  }
221
221
 
@@ -0,0 +1,164 @@
1
+ // The default branch's year as the Pulse reads it from its commits
2
+ // (repository-pulse.ts): walked from its head as the Commits tab reads and
3
+ // keeps its pages (yearCommits), and what a walk found kept as those pages,
4
+ // for the next to go on from (keptWalk).
5
+ import { windowsOn } from './history-windows.ts'
6
+ import type { KeptStore } from './npm-kept.ts'
7
+ import { type HistoryCommit, type HistoryPages, historyFrom } from './repository-history.ts'
8
+
9
+ const DAY_MS = 24 * 60 * 60_000
10
+ // A year of more commits than this is counted by GitHub's statistics: read a
11
+ // page at a time, it would take a hundred queries. Of those not kept, as
12
+ // many queries are made an answer as YEAR_QUERIES, each reading on from as
13
+ // many commits as YEAR_STARTS.
14
+ export const YEAR_COMMITS = 10_000
15
+ const YEAR_QUERIES = 5
16
+ const YEAR_STARTS = 10
17
+ // Commits are read on from as far as this before the year, a commit's clock
18
+ // not always later than its parents': one dated before the year may have a
19
+ // parent dated in it.
20
+ const YEAR_SKEW_MS = 30 * DAY_MS
21
+
22
+ // The year's commits read so far: all of them, or as far back as asked
23
+ // (`commits`, `from`), else how many (`read`), and whether past
24
+ // YEAR_COMMITS (`tooMany`); and every one walked within it, for the next
25
+ // walk to go on from (`walked`).
26
+ type YearCommits = ({ complete: true; commits: HistoryCommit[]; passed: HistoryCommit[]; from: number | null } | { complete: false; read: number; tooMany: boolean })
27
+ & { walked: HistoryCommit[] }
28
+
29
+ // The commits from `head` made since `since`, as the Commits tab reads and
30
+ // keeps them (`pages`, historyFrom): on from the parents of those since (or
31
+ // as much as YEAR_SKEW_MS before), not yet listed, YEAR_STARTS at a time,
32
+ // till none is left; the pages kept read
33
+ // of the store, those not of GitHub, as many queries of them as
34
+ // YEAR_QUERIES, the rest left for the next to ask (`complete` false, how
35
+ // many are `read`); more than YEAR_COMMITS, too many (`tooMany`). Read
36
+ // whole, those it was read on past besides (`passed`): undated, or dated
37
+ // before it, a clock behind, the branch's commits since beneath them. Read
38
+ // no further than `need` asks, those since it read whole (`complete`, `from`
39
+ // the newest of those read whose parents are not, every commit after it
40
+ // read; null, the year read whole). How many are read so far `told` as they
41
+ // are. Those a walk before found (`known`, from this head or another) taken
42
+ // as they are wherever it reaches one, and every one beneath it found, none
43
+ // read again: a walk cut short goes on where it stopped, and one from a head
44
+ // moved on reads only what is new.
45
+ export async function yearCommits(fullName: string, token: string, head: string, since: number, pages: HistoryPages,
46
+ fetchImpl: typeof fetch = globalThis.fetch, need = since, told: (read: number) => void = () => {},
47
+ known: ReadonlyMap<string, HistoryCommit> = new Map()): Promise<YearCommits> {
48
+ const found = new Map<string, HistoryCommit>()
49
+ const tried = new Set<string>()
50
+ const within = (commit: HistoryCommit) => commit.committedAt === null || commit.committedAt >= since - YEAR_SKEW_MS
51
+ const dated = (commit: HistoryCommit) => commit.committedAt !== null && commit.committedAt >= since
52
+ const read = () => [...found.values()].filter(dated).length
53
+ const passed = () => [...found.values()].filter(commit => !dated(commit) && within(commit))
54
+ // Those within it, and the parents beneath them read past it, where a walk stops.
55
+ const walked = () => onEdge([...found.values()], within)
56
+ const parentsUnread = () => [...new Set([...found.values()].filter(within).flatMap(commit => commit.parents))].filter(sha => !found.has(sha) && !tried.has(sha))
57
+ // Those of `shas` found before taken, and those beneath them as far back
58
+ // as it needs, no further, as a walk reading them stops: whether any was.
59
+ const needed = (commit: HistoryCommit) => within(commit) && (need <= since || commit.committedAt === null || commit.committedAt >= need)
60
+ const take = (shas: string[]) => {
61
+ const waiting = shas.filter(sha => known.has(sha) && !found.has(sha))
62
+ const any = waiting.length > 0
63
+ for (let sha = waiting.pop(); sha !== undefined; sha = waiting.pop()) {
64
+ const commit = known.get(sha)!
65
+ if (found.has(sha)) continue
66
+ found.set(sha, commit)
67
+ if (needed(commit)) for (const parent of commit.parents) if (known.has(parent) && !found.has(parent)) waiting.push(parent)
68
+ }
69
+ return any
70
+ }
71
+ let queries = 0
72
+ let windowed = false
73
+ let starts = [head]
74
+ while (starts.length > 0) {
75
+ // Those not read yet, the head before any, else the parents of those
76
+ // read, no later than the newest of them (but for a clock behind): read
77
+ // whole after it.
78
+ const unread = new Set(starts)
79
+ const from = found.size === 0 ? Number.POSITIVE_INFINITY : Math.max(Number.NEGATIVE_INFINITY, ...[...found.values()]
80
+ .filter(commit => commit.parents.some(sha => unread.has(sha))).map(commit => commit.committedAt ?? Number.POSITIVE_INFINITY))
81
+ if (need > since && from < need) return { complete: true, commits: [...found.values()].filter(dated), passed: passed(), from, walked: walked() }
82
+ if (take(starts)) {
83
+ told(read())
84
+ if (read() > YEAR_COMMITS) return { complete: false, read: read(), tooMany: true, walked: walked() }
85
+ starts = parentsUnread()
86
+ continue
87
+ }
88
+ if (queries >= YEAR_QUERIES) return { complete: false, read: read(), tooMany: false, walked: walked() }
89
+ // The pages kept read first; once past them, the rest read at once by
90
+ // when its commits were made (history-windows.ts windowsOn), as far back
91
+ // as it needs, the year's as far as its commits are followed.
92
+ const next: Awaited<ReturnType<typeof windowsOn>> | null = windowed || found.size === 0 ? null
93
+ : await windowsOn(fullName, token, head, starts, found, need > since ? need : since - YEAR_SKEW_MS, from, pages, fetchImpl, queries)
94
+ windowed ||= next?.windowed === true
95
+ queries += next?.queries ?? 0
96
+ const batch = (next?.batch ?? starts).slice(0, YEAR_STARTS)
97
+ for (const sha of batch) tried.add(sha)
98
+ const got = batch.length > 0 ? await historyFrom(fullName, token, batch, pages, fetchImpl) : { commits: [], read: 0 }
99
+ if (got.read > 0) queries++
100
+ for (const commit of got.commits) if (!found.has(commit.sha)) found.set(commit.sha, commit)
101
+ told(read())
102
+ if (read() > YEAR_COMMITS) return { complete: false, read: read(), tooMany: true, walked: walked() }
103
+ starts = parentsUnread()
104
+ }
105
+ return { complete: true, commits: [...found.values()].filter(dated), passed: passed(), from: null, walked: walked() }
106
+ }
107
+
108
+ // Of `commits`, those `within` a year and the parents of those beneath it.
109
+ function onEdge(commits: HistoryCommit[], within: (commit: HistoryCommit) => boolean) {
110
+ const beneath = new Set(commits.filter(within).flatMap(commit => commit.parents))
111
+ return commits.filter(commit => within(commit) || beneath.has(commit.sha))
112
+ }
113
+
114
+ // What walks of a repository's year found (yearCommits `walked`), kept in
115
+ // `store` by `key`, not as its commits but as the pages of its history that
116
+ // hold them (`tops`), every tab's, read as any reads them (`pages`), and only
117
+ // those none holds as they are (`extra`, read in windows of time and kept as
118
+ // no page): read as a walk begins, for it to go on from (`known`), and kept
119
+ // as one ends with what it found, those before the year read (`since`, and
120
+ // YEAR_SKEW_MS more) let go; none kept past WALK_BYTES. A walk reads and
121
+ // keeps its pages through the `pages` it gives, each told as it is.
122
+ export type KeptWalk = { tops: string[]; extra: HistoryCommit[] }
123
+ const WALK_BYTES = 8 * 1024 * 1024
124
+ const walkedCommit = (commit: Partial<HistoryCommit> | null) => typeof commit?.sha === 'string' && Array.isArray(commit.parents) && Array.isArray(commit.named)
125
+ && commit.additions != null
126
+ export function keptWalk(store: KeptStore<KeptWalk>, key: string, pages: HistoryPages) {
127
+ // The pages read or kept, by their tops, each its commits' ids.
128
+ const held = new Map<string, string[]>()
129
+ const told = (read: Map<string, HistoryCommit[]>) => {
130
+ for (const [top, commits] of read) held.set(top, commits.map(commit => commit.sha))
131
+ return read
132
+ }
133
+ const walking: HistoryPages = {
134
+ read: async tops => told(await pages.read(tops)),
135
+ ...pages.readFirst ? { readFirst: async (first: string[], then: string[]) => {
136
+ const read = await pages.readFirst!(first, then)
137
+ told(read.pages)
138
+ return read
139
+ } } : {},
140
+ write: (top, commits) => {
141
+ told(new Map([[top, commits]]))
142
+ return pages.write(top, commits)
143
+ },
144
+ }
145
+ return {
146
+ pages: walking,
147
+ async read(): Promise<Map<string, HistoryCommit>> {
148
+ const walk = (await store.read(key))?.value
149
+ if (!Array.isArray(walk?.tops) || !Array.isArray(walk.extra)) return new Map()
150
+ const read = await walking.read(walk.tops.filter(top => typeof top === 'string'))
151
+ return new Map([...walk.extra.filter(walkedCommit), ...[...read.values()].flat()].map(commit => [commit.sha, commit]))
152
+ },
153
+ async write(known: ReadonlyMap<string, HistoryCommit>, walked: HistoryCommit[], since: number) {
154
+ if (walked.every(commit => known.has(commit.sha))) return
155
+ const all = new Map(known)
156
+ for (const commit of walked) all.set(commit.sha, commit)
157
+ const commits = new Set(onEdge([...all.values()], commit => commit.committedAt === null || commit.committedAt >= since - YEAR_SKEW_MS).map(commit => commit.sha))
158
+ const tops = [...held].filter(([, shas]) => shas.some(sha => commits.has(sha))).map(([top]) => top)
159
+ const covered = new Set(tops.flatMap(top => held.get(top)!))
160
+ const walk = { tops, extra: [...commits].filter(sha => !covered.has(sha)).map(sha => all.get(sha)!) }
161
+ if (JSON.stringify(walk).length <= WALK_BYTES) await store.write(key, walk, Date.now())
162
+ },
163
+ }
164
+ }
@@ -200,7 +200,7 @@ export const commitsQuery = (count: number, alias: string, fields: string) => `q
200
200
  export const commitIds = (shas: string[]) => Object.fromEntries(shas.map((sha, at) => [`o${at}`, sha]))
201
201
 
202
202
  // The latest commits of each tip, by its id, `b<n>` the `n`th's.
203
- const historiesQuery = (count: number) => `${commitsQuery(count, 'b', `history(first: ${ALL_DEPTH}) { pageInfo { hasNextPage } nodes { ...historyCommit } }`)}
203
+ const historiesQuery = (count: number, depth = ALL_DEPTH) => `${commitsQuery(count, 'b', `history(first: ${depth}) { pageInfo { hasNextPage } nodes { ...historyCommit } }`)}
204
204
  ${COMMIT_FRAGMENT}`
205
205
 
206
206
  export type GraphCommit = { oid?: unknown; message?: unknown; committedDate?: unknown; additions?: unknown; deletions?: unknown
@@ -261,7 +261,8 @@ async function readPages(fullName: string, token: string | null, tops: string[],
261
261
  }
262
262
  const [owner, name] = fullName.split('/') as [string, string]
263
263
  await inBatches(tops, PAGES_PER_QUERY, PAGES_PARALLEL, async batch => {
264
- const data = await githubGraphql(historiesQuery(batch.length), { owner, name, ...commitIds(batch) }, token, fetchImpl) as Histories
264
+ const ask = async (depth: number) => await githubGraphql(historiesQuery(batch.length, depth), { owner, name, ...commitIds(batch) }, token, fetchImpl) as Histories
265
+ const data = batch.length === 1 ? await shorter(ask) : await ask(ALL_DEPTH)
265
266
  const nodes = batch.map((_, at) => data?.repository?.[`b${at}`]?.history?.nodes ?? [])
266
267
  await linkNoreplyUsers(nodes.flat().flatMap(commitActors), token, fetchImpl)
267
268
  await Promise.all(batch.map((top, at) => got(top, nodes[at]!.flatMap(node => graphCommit(node) ?? []))))
@@ -372,6 +373,21 @@ const chunked = <T>(items: T[], size: number) => Array.from({ length: Math.ceil(
372
373
  // GitHub stopping a query past its time: in its answer's errors, or as a 502
373
374
  // or 504 of its own.
374
375
  const SLOW = new Set(['github-timeout', 'github-status-502', 'github-status-504'])
376
+ // A page asked for (`ask`, as deep as it is asked) ALL_DEPTH deep, else,
377
+ // GitHub stopping it past its time though asked alone (inBatches), as deep as
378
+ // each of SHORTER_PAGES in turn: its commits' lines are what GitHub takes
379
+ // long on, as a commit changing many large files makes it. A page read
380
+ // shorter is kept so, those beneath it read on from its last as any are.
381
+ const SHORTER_PAGES = [50, 20, 5, 1]
382
+ async function shorter<T>(ask: (depth: number) => Promise<T>, depths = [ALL_DEPTH, ...SHORTER_PAGES]): Promise<T> {
383
+ try {
384
+ return await ask(depths[0]!)
385
+ } catch (err) {
386
+ if (depths.length === 1 || !(err instanceof GithubApiError && SLOW.has(err.message))) throw err
387
+ return await shorter(ask, depths.slice(1))
388
+ }
389
+ }
390
+
375
391
  // `run` for `items` in batches of `size`, as many at once as `parallel`; a
376
392
  // batch GitHub stops past its time run again in halves, down to one alone,
377
393
  // so that one too slow to read fails alone, the others read. The halves