@preventive/triage 1.0.0-alpha.82 → 1.0.0-alpha.83

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.
@@ -1,4 +1,4 @@
1
- import{b as e,d as t,i as n}from"./chunk-SUFRZ5U7.js";import{a as r}from"./chunk-6VOB5WXX.js";import{A as i,B as a,a as o,b as s,c,d as l,e as u,f as d,g as ee,h as te,i as ne,j as re,k as ie,l as ae,m as oe,n as se,o as ce,p as le,q as ue,r as de,s as fe,t as pe,u as me,v as he,w as ge,x as _e,y as ve,z as ye}from"./chunk-FNFWBAJO.js";import"./chunk-6CCSTJWB.js";import{$a as be,H as xe,I as Se,Ka as Ce,Sa as we,Ta as Te,X as Ee,Ya as De,Za as f,a as Oe,ab as ke,bb as Ae,cb as je,db as Me,eb as Ne,fb as Pe,g as Fe,gb as p,hb as Ie,i as Le,ib as m,ja as Re,jb as ze,ka as Be,m as Ve,ma as He,n as h,z as Ue}from"./chunk-UP3ADVQN.js";import{y as We}from"./chunk-KP2XM324.js";import"./chunk-DUASGS2O.js";import{b as Ge}from"./chunk-NRPC74AM.js";import"./chunk-PNHBZGDD.js";import{a as Ke,e as qe}from"./chunk-74JZTGTO.js";import"./chunk-IYPY47MC.js";import{D as Je,E as Ye,d as g,h as Xe,i as Ze,j as Qe,y as _,z as $e}from"./chunk-WOLGZ2PE.js";import{a as et,d as tt}from"./chunk-PWFUOLZK.js";import"./chunk-C4Z6ZBXV.js";import{m as nt,s as rt}from"./chunk-ZQQALNFP.js";import{B as it,D as at,J as ot}from"./chunk-QRKFPLA4.js";import{a as v,b as st,c as y,d as ct,g as b,j as lt}from"./chunk-2XUEZHIP.js";import"./chunk-TUII34K2.js";import"./chunk-OOJM4CTU.js";function ut(e){let t=document.createElement(`input`);t.type=`file`,t.multiple=!0,t.addEventListener(`change`,()=>{e([...t.files])},{once:!0}),t.click()}function dt(e,t,n){let r=0,i=e=>Array.from(e.dataTransfer?.types??[]).includes(`Files`),a=e=>{i(e)&&(e.preventDefault(),r+=1,n(!0))},o=e=>{i(e)&&e.preventDefault()},s=e=>{i(e)&&(r=Math.max(0,r-1),r===0&&n(!1))},c=e=>{i(e)&&(e.preventDefault(),e.stopPropagation(),r=0,n(!1),t([...e.dataTransfer.files]))};return e.addEventListener(`dragenter`,a),e.addEventListener(`dragover`,o),e.addEventListener(`dragleave`,s),e.addEventListener(`drop`,c),()=>{e.removeEventListener(`dragenter`,a),e.removeEventListener(`dragover`,o),e.removeEventListener(`dragleave`,s),e.removeEventListener(`drop`,c)}}async function ft(e,t,n,r){let i=e.appState.generation;try{return await e.appState.mutate(()=>n(t),r)}catch(t){throw i===e.appState.generation&&e.appState.invalidate(r),t}}async function pt(e,t,n,r){if(e._busy||!e._csrf)throw Error(`Wait for the current operation to finish, then try again.`);e._busy=!0;try{await ft(e,t,n,r)}finally{await e._load(),e._busy=!1;let t=e._queue.splice(0);t.length>0&&e._upload(t)}}async function mt(e,t,n,r){if(t.length===0||(e._queue.push(...t),e._busy))return;e._busy=!0,e._error=null;let i=e.appState.generation,a=[],o=0;try{for(;e._queue.length>0;){if(e.appState.generation!==i){e._queue=[];break}let t=e._queue.shift();try{await ft(e,t,n,r)}catch(n){if(n?.name===`AbortError`||e.appState.generation!==i){e._queue=[];break}a.push(`${t.name}: ${String(n?.message??n)}`)}o++}}finally{a.length>0&&(e._error=o===1?`Upload failed: ${a[0]}`:`Upload failed for ${a.length} of ${o} files: ${a.join(`; `)}`),e._busy=!1,await e._load({preserveError:!0})}}var x=class extends lt{static properties={session:{attribute:!1},allowShare:{attribute:!1},_loading:{state:!0},_data:{state:!0},_error:{state:!0}};constructor(){super(),this.session=null,this.allowShare=!1,this.appState=u,this._loading=!1,this._loadRequest=null,this._data=null,this._error=null}get _role(){return this.session?.role??null}get _csrf(){return this.session?.csrfToken??null}get _me(){return this.session?.id??null}connectedCallback(){super.connectedCallback(),this._load()}disconnectedCallback(){this._loadRequest?.abort(),super.disconnectedCallback()}async _load({preserveError:e=!1}={}){let{collection:t}=this.constructor;if(!t)return;e||(this._error=null);let[n,r,i]=t;await this._loadCollection(n,r,i,e=>this._show(e))}_show(e){this._data=e}async _loadCollection(e,t,n,r){this._loading=!0,await this._read(`_loadRequest`,e,t,n,{apply:r,settled:()=>{this._loading=!1},failed:t=>{this.appState.read(e)===void 0&&(this._error=String(t?.message??t))}})}async _read(e,t,n,r,{apply:i,answered:a,failed:o,settled:s}){this[e]?.abort();let c=this[e]=new AbortController;try{await this.appState.load(t,n,r,{signal:c.signal,apply:i}),c.signal.aborted||a?.()}catch(e){!c.signal.aborted&&e?.name!==`AbortError`&&o(e)}finally{this[e]===c&&s()}}_nav(){return Ie(this.constructor.view,this._role,this.allowShare)}_emit(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0,composed:!0}))}_list(e,t,n){return y`<div class="manage-list" aria-busy="${this._loading}">${e==null?this._error?b:S(t):n()}</div>`}},ht=class{constructor(e,t=()=>!0){this.host=e,this.accepts=t,this.active=!1,e.addController(this)}hostConnected(){this.teardown=dt(this.host,e=>{this.accepts()&&this.host._upload(e)},e=>{this.active=this.accepts()&&e,this.host.requestUpdate()})}hostDisconnected(){this.teardown?.()}overlay(e){return this.active?y`<div class="dropzone">${e}</div>`:b}card(e,t,n,r=`Uploading…`){return y`<span class="drop-icon" aria-hidden="true">${m(`upload`)}</span><span class="drop-copy"><strong>${e}</strong><span>${t}</span></span><button type="button" class="drop-browse" ?disabled="${n}" @click="${()=>ut(e=>{this.host._upload(e)})}">${this.host._busy?r:`Browse files`}</button>`}};function S(e){return y`<div class="loading-rows" role="status"><span class="sr-only">${e}</span><div aria-hidden="true">${[0,1,2,3].map(()=>y`<div class="loading-row"><span></span><span></span></div>`)}</div></div>`}var C=e=>e?y`<p class="msg error" role="alert">${e}</p>`:b,w=(e,t)=>y`<div class="empty"><strong>${e}</strong><p>${t}</p></div>`;function gt(e){let t=e.split(`/`);return t.at(-1)===`stasis.config.json`&&!t.includes(`node_modules`)}var _t=class extends Te{get changeEvent(){return`local-item-change`}get searchLabel(){return`Search local files`}get optionsLabel(){return`Local files`}get noMatchesLabel(){return`No matching files.`}get emptyLabel(){return`No local files available.`}choices(){let e=this._query.trim().toLocaleLowerCase(),t=this.options.filter(t=>`${t.label} ${t.secondary??``}`.toLocaleLowerCase().includes(e));return{pinned:[],sections:[{options:t}],count:t.length,total:this.options.length,showFacets:!1}}};customElements.define(`managed-local-item-selector`,_t);var vt=class{constructor(e,t,n){this.host=e,this.kind=t,this.upload=n,this.source=null,this.hasData=!1,this.open=!1,this.options=[],this.value=null,this.busy=!1,this.loading=!1,this.error=``,this.success=``,this.generation=0,this.readAbort=null,this.onChange=e=>{if(e?.kind){if(e.kind!==this.kind)return;if(e.value!==this.value){this.refresh();return}}this.readAbort&&!this.readAbort.signal.aborted&&(this.readAbort.abort(),this.error=`The local ${this.kind} changed or the list was refreshed. Select it again before importing.`),this.options=[],this.value=null,this.success=``,this.refresh()},this.onBlur=()=>{this.readAbort&&!this.readAbort.signal.aborted&&this.onChange()},this.onVisibilityChange=()=>{globalThis.document?.visibilityState===`hidden`&&this.onBlur()},e.addController(this)}listeners(){return[[globalThis,`focus`,this.onChange],[globalThis,`blur`,this.onBlur],[globalThis,`storage`,this.onChange],[globalThis.document,`visibilitychange`,this.onVisibilityChange]]}hostConnected(){for(let[e,t,n]of this.listeners())e?.addEventListener(t,n);this.connectSource()}hostUpdated(){this.connectSource()}connectSource(){this.source!==this.host.localImportSource&&(this.unsubscribe?.(),this.abort?.abort(),this.source=this.host.localImportSource,this.unsubscribe=this.source?.subscribe(this.onChange),this.onChange())}hostDisconnected(){++this.generation,this.abort?.abort(),this.unsubscribe?.(),this.source=null;for(let[e,t,n]of this.listeners())e?.removeEventListener(t,n)}async refresh(){let e=++this.generation,t=this.source;this.loading=!0,this.host.requestUpdate();try{let n=t?await t.hasData(this.kind):!1;if(e!==this.generation)return;this.hasData=n;let r=this.open&&!t?.locked?await t?.list(this.kind)??[]:[];if(e!==this.generation)return;this.options=r,r.some(e=>e.value===this.value)||(this.value=null)}catch(t){e===this.generation&&(this.error=String(t?.message??t))}finally{e===this.generation&&(this.loading=!1,this.host.requestUpdate())}}toggle(){this.busy||(this.open=!this.open,this.error=``,this.success=``,this.options=[],this.value=null,this.refresh())}async busyWith(e){let t=this.abort=new AbortController;this.busy=!0,this.error=``,this.host.requestUpdate();try{await e(t)}catch(e){t.signal.aborted||(this.error=String(e?.message??e))}finally{this.readAbort===t&&(this.readAbort=null),this.busy=!1,this.host.requestUpdate()}}async unlock(){this.busy||await this.busyWith(async e=>{await this.source.unlock({signal:e.signal})&&!e.signal.aborted&&await this.refresh()})}async importSelected(){if(this.busy||this.loading||!this.value||this.source?.locked)return;this.success=``;let e=this.options.find(e=>e.value===this.value)?.label;await this.busyWith(async t=>{this.readAbort=t,await this.source.importItem(this.kind,this.value,e=>(this.readAbort=null,this.upload(e)),{signal:t.signal}),!t.signal.aborted&&!this.source?.locked&&(this.success=`Imported ${e}.`,this.value=null)})}renderAction(){return this.hasData||this.open?y`<button type="button" class="local-import-toggle" aria-expanded="${this.open}" aria-controls="local-import-panel" ?disabled="${this.busy}" @click="${()=>this.toggle()}">Import</button>`:b}renderPanel(e){if(!this.open)return b;let t=this.source?.locked;return y`<section class="local-import-panel" id="local-import-panel" aria-label="${`Import local ${this.kind}`}"><div class="local-import-copy"><strong>Import local ${this.kind}</strong><p>${t?`Unlock local data with your passkey to choose a file.`:`Copy a file from this browser to the managed workspace. The local copy stays on this device.`}</p></div><div class="local-import-controls">${t?y`<button type="button" class="local-import-submit" ?disabled="${this.busy}" @click="${()=>this.unlock()}">${this.busy?`Waiting for passkey…`:`Unlock with passkey`}</button>`:y`<managed-local-item-selector label="${`Choose local ${this.kind}`}" placeholder="${this.loading?`Loading local files…`:`Choose local ${this.kind}\u2026`}" .options="${this.options}" .value="${this.value}" ?disabled="${this.busy||this.loading}" @local-item-change="${e=>{this.value=e.detail.value,this.success=``,this.host.requestUpdate()}}"></managed-local-item-selector><button type="button" class="local-import-submit" ?disabled="${e||this.busy||this.loading||!this.value}" @click="${()=>this.importSelected()}">${this.busy?`Importing…`:`Import ${this.kind}`}</button>`} <button type="button" class="local-import-close" ?disabled="${this.busy}" @click="${()=>this.toggle()}">Close</button></div>${!t&&!this.loading&&this.options.length===0?y`<p class="local-import-message">No local ${this.kind}s available.</p>`:b} ${this.error?y`<p class="local-import-message error" role="alert">${this.error} <button type="button" ?disabled="${this.busy}" @click="${()=>{this.error=``,this.refresh()}}">Retry</button></p>`:b} ${this.success?y`<p class="local-import-message" role="status">${this.success}</p>`:b}</section>`}},T=e=>e?AbortSignal.any([e,u.sessionController.signal]):u.sessionController.signal,yt=()=>new DOMException(`Managed session changed`,`AbortError`),E=e=>e.json();async function bt({signal:e}={}){e=T(e),e.throwIfAborted();let t=await l(`/api/admin/bundles`,{credentials:`same-origin`,signal:e});if(e.throwIfAborted(),!t.ok)throw Object.assign(Error(`Bundle catalogue request failed (${t.status})`),{status:t.status});let n=await t.json();return e.throwIfAborted(),n.bundles??[]}async function xt(e,t,n){let r=u.generation,i=await l(`/api/bundles/${encodeURIComponent(e)}/${t}`,{credentials:`same-origin`,signal:n});if(n?.throwIfAborted(),!i.ok)throw Object.assign(Error(`Bundle ${t} request failed (${i.status})`),{status:i.status});let a=t===`contents`?await i.text():await i.json();if(n?.throwIfAborted(),r!==u.generation)throw yt();return a}function St(e,{signal:t}={}){return u.load(`bundle-metadata:${e}`,`bundle metadata`,t=>xt(e,`metadata`,t),{signal:t,retryInvalidated:!0})}async function Ct(e,{signal:t}={}){t=T(t);let n=await xt(e,`metadata`,t),r=n?.bundle?.repo??null,i=at({repo:r});if(!i)return r;let a=new URLSearchParams({repo:i,directory:r.directory??``}),o=new Set(n.unsized??[]),s=Ge((n.files??[]).filter(([e,t])=>t!=null||o.has(e)).map(([e])=>e));s&&a.set(`filePrefix`,s);let c=await l(`/api/admin/repositories/resolve?${a}`,{credentials:`same-origin`,cache:`no-store`,signal:t});if(t.throwIfAborted(),!c.ok)throw Error(`Repository suggestion request failed (${c.status})`);let{location:u}=await c.json();return t.throwIfAborted(),u?{...r,github:u.github,...u.mapped?{directory:u.directory}:{},repoId:u.repoId}:r}async function wt(e,{signal:t}={}){t=T(t);try{return await xt(e,`contents`,t)}catch(e){throw e.name!==`AbortError`&&u.notify(`Couldn't load bundle contents: ${e.message}`),e}}function Tt(e,t,n=``,r=!1,i=!1){let a=n?`${n.startsWith(`entry:`)?`entry`:`reason`}=${encodeURIComponent(n.slice(n.indexOf(`:`)+1))}`:``,o=[t?`team=${encodeURIComponent(t)}`:``,a,r?`repoAdvisories=true`:``,i?`details=true`:``].filter(Boolean).join(`&`);return xt(e,`advisories${o?`?${o}`:``}`,u.sessionController.signal)}var Et={"patch-not-found":`The patch isn’t at the commit it was looked for at.`,"patch-mismatch":`The file at the commit the patch was read at isn’t the patch its lockfile names.`,"patch-unreadable":`The patch is written so that pnpm versions, or macOS and Windows, may apply it differently.`,"patch-unsupported":`The patch changes a file’s bytes, or gives it a mode other than 644 or 755, which isn’t reviewed here.`,"patch-does-not-apply":`The patch doesn’t apply to this version, though pnpm may still install part of it.`,"patch-too-large":`The patch is too large to read here.`,"no-repository":`The repository the patch is in isn’t available to you.`,"no-directory":`Only some of the repository the patch is in is available to you.`,"github-token-required":`Reading the patch needs your GitHub sign-in.`,"patch-not-kept":`The patch isn’t kept here: a review of a version it patches keeps it, as does a team’s Dependencies tab of its repository’s default branch.`},Dt=e=>e?{patchHash:e.hash,...e.repoId==null?{}:{patchRepoId:String(e.repoId),patchCommit:e.commit},...e.path==null?{}:{patchPath:e.path}}:{},D={...Et,"bad-tarball":`This package's tarball couldn't be read.`,"tarball-conflict":`This package's tarball isn't shown, as it doesn't install as one set of files: it holds two different files at one path, or at paths that are one on macOS or Windows, or a file within another, which installers each install their own way.`,"upstream-invalid":`The npm registry's answer for this package couldn't be read.`,"upstream-too-large":`The npm registry's answer for this package is too large to read here.`,400:`Not an npm package name and version.`,404:`No such package version, or it is not available to you.`,413:`This package is too large to open here.`,429:`Too many packages are loading. Try again shortly.`,502:`The npm registry couldn't be reached.`},Ot=15e3,O=new Map;function kt(e){if(O.has(e))return;let t=new AbortController,n=l(e,{credentials:`same-origin`,signal:AbortSignal.any([t.signal,u.sessionController.signal])});n.catch(()=>{});let r={reading:n,until:Date.now()+Ot,generation:u.generation};O.set(e,r),setTimeout(()=>{O.get(e)===r&&(O.delete(e),t.abort())},Ot)}function At(e,t){let n=O.get(e);return n?(O.delete(e),n.until>Date.now()&&n.generation===t?n.reading:null):null}var jt=(e,t)=>new Promise((n,r)=>{let i=()=>r(t.reason);t.aborted?i():(t.addEventListener(`abort`,i,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener(`abort`,i)))});async function k(e,t,n,r,i={}){r=T(r);let a=u.generation,o=()=>l(e,{credentials:`same-origin`,...i,signal:r}),s=i.method?null:At(e,a),c=s&&await jt(s,r).then(e=>e.ok?e:null,e=>{if(r.aborted)throw e;return null})||await o();if(r.throwIfAborted(),!c.ok){let e=await c.json().catch(()=>null),n=e?.error??null;throw Object.assign(Error(t[n]??t[c.status]??`Request failed (${c.status})`),{status:c.status,code:n,...typeof e?.commit==`string`?{commit:e.commit}:{}})}let d=await n(c);if(r.throwIfAborted(),a!==u.generation)throw yt();return d}var A=(e,t,n)=>k(`/api/npm/${e}?${new URLSearchParams(t)}`,D,E,n),Mt={"no-repository":`This repository is not available to you.`,"no-directory":`This directory is not at that commit, or not available to you.`,"directory-too-large":`This directory is too large to open here. Open one of its directories instead.`,"directory-unreadable":`GitHub’s archive of this directory couldn’t be read here, as when a symlink in it points outside the repository.`,"repository-busy":`Too many directories and packages are loading. Try again shortly.`,"repository-changed":`The repository changed while it was read. Try again.`,"github-rate-limited":`GitHub’s API rate limit has been reached. Try again later.`,"github-unauthorized":`GitHub authentication has expired or was revoked. Sign in again.`,"github-status-403":`GitHub denied this request. Check repository access and the GitHub App’s read permissions.`,"github-malformed":`GitHub’s archive of this directory could not be verified against its commit.`,"github-unreachable":`Could not connect to GitHub. Try again shortly.`,"github-moved":`GitHub moved this repository, as when it is renamed. Try again shortly.`,"github-timeout":`GitHub took too long to answer. Try again shortly.`,400:`Not a repository directory and commit.`,403:`Repository access is required to read its files.`,404:`This repository, commit or directory is unavailable.`,413:`This directory is too large to open here.`,429:`Too many directories and packages are loading. Try again shortly.`,502:`GitHub couldn’t be reached.`},j=(e,t,n,r=Mt)=>k(`/api/admin/repositories/${e}?${new URLSearchParams(t)}`,r,E,n);function Nt(e,t,n,{signal:r}={}){return j(`code`,{repoId:e,ref:t,path:n},r)}async function Pt({signal:e}={}){return(await j(`browsable`,{},e)).repos??[]}function Ft(e,{signal:t}={}){return j(`refs`,{repoId:e},t)}function It(e,t,n,{signal:r,commitOnly:i=!1}={}){return j(`contents`,{repoId:e,ref:t,path:n,...i?{listing:`none`}:{}},r)}var Lt={...Mt,"no-directory":`This directory’s history is not available to you.`,"github-malformed":`GitHub answered with a history that couldn’t be read.`,"github-token-required":`Reading every branch needs your GitHub sign-in.`,400:`Not a repository’s history.`};function Rt(e,t,n,{page:r=1,all:i=!1,fresh:a=!1,from:o=null,signal:s}={}){return j(`history`,{repoId:e,ref:t,path:n,page:r,...i?{all:`true`}:{},...a?{fresh:`true`}:{},...o?{from:o.join(`,`)}:{}},s,Lt)}var zt={...Lt,"no-directory":`This directory’s changes are not available to you.`,"github-malformed":`GitHub answered with a commit’s files that couldn’t be read.`,400:`Not a repository’s commits.`};function Bt(e,t,n,{signal:r}={}){return j(`changes`,{repoId:e,path:t,shas:n.join(`,`)},r,zt)}function Vt(e,t,n,{signal:r}={}){return j(`tree`,{repoId:e,path:t,commit:n},r,zt)}var M={...Mt,"no-directory":`Issues and pull requests show only with access to the whole repository.`,"github-malformed":`GitHub answered with a list that couldn’t be read.`,"github-token-required":`Reading issues and pull requests needs your GitHub sign-in.`,"github-status-403":`GitHub refused to list these. The GitHub App reading this repository needs Issues: read and Pull requests: read, which an owner of its installation approves.`,400:`Not a repository’s issues or pull requests.`},Ht=(e,t,n,r)=>`/api/admin/repositories/issues?${new URLSearchParams({repoId:e,kind:t,state:n,...r?{after:r}:{}})}`;function Ut(e,t,{state:n=`open`,after:r=null,signal:i}={}){return k(Ht(e,t,n,r),M,E,i)}var Wt={...M,"no-directory":`Agents show only with access to the whole repository.`,"github-token-required":`Reading what the agents did needs your GitHub sign-in.`,400:`Not a repository’s agents.`},Gt=(e,t,n)=>`/api/admin/repositories/agents?${new URLSearchParams({repoId:e,...t?{pulls:t}:{},...n?{commits:n}:{}})}`;function Kt(e,{pulls:t=null,commits:n=null,signal:r}={}){return k(Gt(e,t,n),Wt,E,r)}var qt={...M,"github-not-found":`GitHub has no issue or pull request of that number here.`,400:`Not an issue or pull request of a repository.`};function Jt(e,t,{signal:n}={}){return j(`item`,{repoId:e,number:t},n,qt)}var Yt={...qt,"github-not-found":`GitHub has no pull request of that number here.`,"github-malformed":`GitHub answered with a pull request or lockfile that couldn’t be read.`,"github-status-403":`GitHub refused to read its lockfiles. The GitHub App reading this repository needs Contents: read and Pull requests: read, which an owner of its installation approves.`,400:`Not a pull request of a repository.`},Xt=({review:e,listed:t})=>({...e?{review:`1`}:{},...t?{listed:`1`}:{}});function Zt(e,t,{review:n=!1,listed:r=!1,signal:i}={}){return j(`pull-dependencies`,{repoId:e,number:t,...Xt({review:n,listed:r})},i,Yt)}async function Qt(e,t,{review:n=!1,listed:r=!1,signal:i}={}){let{pulls:a,users:o,deltas:s}=await j(`pull-dependencies`,{repoId:e,numbers:t.join(`,`),...Xt({review:n,listed:r})},i,Yt);return $t(a,o,s)}var $t=(e,t,n)=>new Map((Array.isArray(e)?e:[]).filter(e=>Number.isSafeInteger(e?.number)).map(e=>[e.number,typeof e.error==`string`?Object.assign(Error(Yt[e.error]??`It couldn\u2019t be read (${e.error}).`),{code:e.error}):{...e,...t?{users:t}:{},...Array.isArray(n)&&n.length>0?{deltas:n}:{}}])),en={...qt,"github-not-found":`GitHub has none of a lockfile it lists on the default branch.`,"github-malformed":`GitHub answered with a lockfile that couldn’t be read.`,"github-status-403":`GitHub refused to read its lockfiles. The GitHub App reading this repository needs Contents: read, which an owner of its installation approves.`,400:`Not a repository.`},tn={...en,"no-bundle":`This bundle is not available to you.`,"bundle-unavailable":`This bundle’s packages couldn’t be read.`,"directory-package-malformed":`This bundle records a package installed from a directory with an integrity, or naming no directory.`,"payload-too-large":`This bundle holds too many packages to check here.`,"repository-changed":`The bundle or its repository changed while it was read. Try again.`,"github-not-found":`GitHub has none of the commit this bundle was built from, or of a lockfile it lists there.`,400:`Not a bundle.`};function nn(e,{signal:t}={}){return k(`/api/bundles/${encodeURIComponent(e)}/dependency-review`,tn,E,t)}var rn={...tn,"unsupported-bundle":`Only Stasis bundles are validated.`,"validation-busy":`Other bundles are being validated. Try again shortly.`,"validation-failed":`The validation failed. Try again.`,"csrf-missing":`Your session is missing its request token. Reload the page.`,"csrf-mismatch":`Your session changed. Reload the page.`,429:`Other bundles are being validated. Try again shortly.`},an=e=>`/api/bundles/${encodeURIComponent(e)}/validation`;function on(e,{signal:t}={}){return k(an(e),rn,E,t)}function sn(e,t,{signal:n}={}){return k(an(e),rn,e=>e.json().catch(()=>null),n,{method:`POST`,headers:{"x-csrf-token":t}})}var cn={"no-team":`This team is not available to you.`,400:`Not a team’s repositories.`},ln=`GitHub failed to answer. Try again shortly.`,un={...M,"github-status-502":ln,"github-status-504":ln,"time-up":`Reading them took too long.`},dn=e=>`Not all its open pull requests were read. ${un[e]??`(${e})`}`;function fn(e,t,{repoIds:n=null,kept:r=!1,signal:i}={}){let a=new URLSearchParams({...n?{repoIds:n.join(`,`)}:{},...r?{kept:`1`}:{}}),o=a.size>0?`?${a}`:``;return k(`/api/teams/${encodeURIComponent(e)}/dependencies${o}`,cn,async e=>{for await(let n of jn(e))typeof n.error==`string`?t({...n,error:en[n.error]??en[n.status]??`It couldn\u2019t be read (${n.error}).`,code:n.error}):t({...n,...Array.isArray(n.dependencies)?{dependencies:$t(n.dependencies,n.users)}:{},...typeof n.pulls?.error==`string`?{pulls:{...n.pulls,error:dn(n.pulls.error)}}:{}})},i)}function pn(e,t,n,r,{signal:i}={}){let a=JSON.stringify({since:t,versions:n.map(({name:e,version:t})=>[e,t])});return k(`/api/teams/${encodeURIComponent(e)}/dependency-reviews/changed`,cn,e=>e.json().then(e=>({now:Number.isSafeInteger(e?.now)?e.now:null,versions:Array.isArray(e?.versions)?e.versions.flatMap(e=>Array.isArray(e)&&typeof e[0]==`string`&&typeof e[1]==`string`?[{name:e[0],version:e[1]}]:[]):[]})),i,{method:`POST`,headers:{"content-type":`application/json`,"x-csrf-token":r},body:a})}var mn={...M,"no-directory":`Pulse shows only with access to the whole repository.`,"github-malformed":`GitHub answered with statistics that couldn’t be read.`,"github-token-required":`Reading a repository’s pulse needs your GitHub sign-in.`,"github-status-403":`GitHub refused to read these. The GitHub App reading this repository needs Contents, Issues and Pull requests: read, which an owner of its installation approves.`,400:`Not a repository’s pulse.`},hn=(e,t)=>`/api/admin/repositories/pulse?${new URLSearchParams({repoId:e,weeks:t})}`;function gn(e,t,{signal:n}={}){return k(hn(e,t),mn,E,n)}function _n(e,t,{state:n=`open`,weeks:r=4}={}){t===`issues`||t===`pulls`?kt(Ht(e,t,n,null)):t===`agents`?kt(Gt(e,null,null)):t===`pulse`&&kt(hn(e,r))}function vn(e,t,{from:n,to:r=null,authors:i=[]},{signal:a}={}){return j(`pulse/items`,{repoId:e,weeks:t,from:n,...r===null?{}:{to:r},...i.length>0?{authors:i.join(`,`)}:{}},a,mn)}function yn(e,t,{signal:n,patch:r=null}={}){return A(`package`,{name:e,version:t,...Dt(r)},n)}function bn(e,{signal:t}={}){return A(`versions`,{name:e},t)}function xn(e,{signal:t}={}){return A(`stats`,{name:e},t)}function Sn(e,{signal:t}={}){return A(`advisories`,{name:e},t)}function Cn(e,t,{signal:n}={}){return A(`tags`,{name:e,version:t},n)}function wn(e,t,{signal:n}={}){return A(`socket`,{name:e,version:t},n)}function Tn(e,t,n=null,{signal:r}={}){return A(`risk`,{name:e,version:t,...n===null?{}:{otherVersion:n}},r)}function En(e,t,{signal:n}={}){return A(`provenance`,{name:e,version:t},n)}var N={404:`This file is no longer available.`,409:`This file has changed since it was opened.`,413:`This file is too large to pretty-print.`,422:`This file couldn't be read as code.`,"pretty-mismatch":`Pretty-printing would change more than its layout, so it is shown as published.`,unsupported:`This kind of file can't be checked once pretty-printed, so it is shown as published.`,429:`Too many files are being pretty-printed. Try again shortly.`,502:`The npm registry couldn't be reached.`};function Dn(e,t,n,{signal:r}={}){return k(`/api/bundles/${encodeURIComponent(e)}/pretty?${new URLSearchParams({path:t,hash:n})}`,N,kn,r)}function On(e,t,n,r,{signal:i}={}){return k(`/api/npm/pretty?${new URLSearchParams({name:e,version:t,path:n,hash:r})}`,{...D,...N},kn,i)}var kn=async e=>({...await e.json(),source:e.headers.get(`x-source-hash`)});async function*An(e){let t=e.body.pipeThrough(new TextDecoderStream).getReader(),n=[];for(;;){let{done:e,value:r}=await t.read();if(e)return;let i=0;for(let e=r.indexOf(`
1
+ import{b as e,d as t,i as n}from"./chunk-R7HUX4PF.js";import{a as r}from"./chunk-6VOB5WXX.js";import{A as i,B as a,a as o,b as s,c,d as l,e as u,f as d,g as ee,h as te,i as ne,j as re,k as ie,l as ae,m as oe,n as se,o as ce,p as le,q as ue,r as de,s as fe,t as pe,u as me,v as he,w as ge,x as _e,y as ve,z as ye}from"./chunk-LVVIDDT6.js";import"./chunk-6CCSTJWB.js";import{$a as be,H as xe,I as Se,Ka as Ce,Sa as we,Ta as Te,X as Ee,Ya as De,Za as f,a as Oe,ab as ke,bb as Ae,cb as je,db as Me,eb as Ne,fb as Pe,g as Fe,gb as p,hb as Ie,i as Le,ib as m,ja as Re,jb as ze,ka as Be,m as Ve,ma as He,n as h,z as Ue}from"./chunk-V4U7URJF.js";import{y as We}from"./chunk-KP2XM324.js";import"./chunk-DUASGS2O.js";import{b as Ge}from"./chunk-NRPC74AM.js";import"./chunk-PNHBZGDD.js";import{a as Ke,e as qe}from"./chunk-74JZTGTO.js";import"./chunk-IYPY47MC.js";import{A as Je,E as Ye,F as Xe,d as g,h as Ze,i as Qe,j as $e,z as _}from"./chunk-G5JKKNZF.js";import{a as et,d as tt}from"./chunk-PWFUOLZK.js";import"./chunk-C4Z6ZBXV.js";import{m as nt,s as rt}from"./chunk-ZQQALNFP.js";import{B as it,D as at,J as ot}from"./chunk-QRKFPLA4.js";import{a as v,b as st,c as y,d as ct,g as b,j as lt}from"./chunk-2XUEZHIP.js";import"./chunk-TUII34K2.js";import"./chunk-OOJM4CTU.js";function ut(e){let t=document.createElement(`input`);t.type=`file`,t.multiple=!0,t.addEventListener(`change`,()=>{e([...t.files])},{once:!0}),t.click()}function dt(e,t,n){let r=0,i=e=>Array.from(e.dataTransfer?.types??[]).includes(`Files`),a=e=>{i(e)&&(e.preventDefault(),r+=1,n(!0))},o=e=>{i(e)&&e.preventDefault()},s=e=>{i(e)&&(r=Math.max(0,r-1),r===0&&n(!1))},c=e=>{i(e)&&(e.preventDefault(),e.stopPropagation(),r=0,n(!1),t([...e.dataTransfer.files]))};return e.addEventListener(`dragenter`,a),e.addEventListener(`dragover`,o),e.addEventListener(`dragleave`,s),e.addEventListener(`drop`,c),()=>{e.removeEventListener(`dragenter`,a),e.removeEventListener(`dragover`,o),e.removeEventListener(`dragleave`,s),e.removeEventListener(`drop`,c)}}async function ft(e,t,n,r){let i=e.appState.generation;try{return await e.appState.mutate(()=>n(t),r)}catch(t){throw i===e.appState.generation&&e.appState.invalidate(r),t}}async function pt(e,t,n,r){if(e._busy||!e._csrf)throw Error(`Wait for the current operation to finish, then try again.`);e._busy=!0;try{await ft(e,t,n,r)}finally{await e._load(),e._busy=!1;let t=e._queue.splice(0);t.length>0&&e._upload(t)}}async function mt(e,t,n,r){if(t.length===0||(e._queue.push(...t),e._busy))return;e._busy=!0,e._error=null;let i=e.appState.generation,a=[],o=0;try{for(;e._queue.length>0;){if(e.appState.generation!==i){e._queue=[];break}let t=e._queue.shift();try{await ft(e,t,n,r)}catch(n){if(n?.name===`AbortError`||e.appState.generation!==i){e._queue=[];break}a.push(`${t.name}: ${String(n?.message??n)}`)}o++}}finally{a.length>0&&(e._error=o===1?`Upload failed: ${a[0]}`:`Upload failed for ${a.length} of ${o} files: ${a.join(`; `)}`),e._busy=!1,await e._load({preserveError:!0})}}var x=class extends lt{static properties={session:{attribute:!1},allowShare:{attribute:!1},_loading:{state:!0},_data:{state:!0},_error:{state:!0}};constructor(){super(),this.session=null,this.allowShare=!1,this.appState=u,this._loading=!1,this._loadRequest=null,this._data=null,this._error=null}get _role(){return this.session?.role??null}get _csrf(){return this.session?.csrfToken??null}get _me(){return this.session?.id??null}connectedCallback(){super.connectedCallback(),this._load()}disconnectedCallback(){this._loadRequest?.abort(),super.disconnectedCallback()}async _load({preserveError:e=!1}={}){let{collection:t}=this.constructor;if(!t)return;e||(this._error=null);let[n,r,i]=t;await this._loadCollection(n,r,i,e=>this._show(e))}_show(e){this._data=e}async _loadCollection(e,t,n,r){this._loading=!0,await this._read(`_loadRequest`,e,t,n,{apply:r,settled:()=>{this._loading=!1},failed:t=>{this.appState.read(e)===void 0&&(this._error=String(t?.message??t))}})}async _read(e,t,n,r,{apply:i,answered:a,failed:o,settled:s}){this[e]?.abort();let c=this[e]=new AbortController;try{await this.appState.load(t,n,r,{signal:c.signal,apply:i}),c.signal.aborted||a?.()}catch(e){!c.signal.aborted&&e?.name!==`AbortError`&&o(e)}finally{this[e]===c&&s()}}_nav(){return Ie(this.constructor.view,this._role,this.allowShare)}_emit(e,t){this.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!0,composed:!0}))}_list(e,t,n){return y`<div class="manage-list" aria-busy="${this._loading}">${e==null?this._error?b:S(t):n()}</div>`}},ht=class{constructor(e,t=()=>!0){this.host=e,this.accepts=t,this.active=!1,e.addController(this)}hostConnected(){this.teardown=dt(this.host,e=>{this.accepts()&&this.host._upload(e)},e=>{this.active=this.accepts()&&e,this.host.requestUpdate()})}hostDisconnected(){this.teardown?.()}overlay(e){return this.active?y`<div class="dropzone">${e}</div>`:b}card(e,t,n,r=`Uploading…`){return y`<span class="drop-icon" aria-hidden="true">${m(`upload`)}</span><span class="drop-copy"><strong>${e}</strong><span>${t}</span></span><button type="button" class="drop-browse" ?disabled="${n}" @click="${()=>ut(e=>{this.host._upload(e)})}">${this.host._busy?r:`Browse files`}</button>`}};function S(e){return y`<div class="loading-rows" role="status"><span class="sr-only">${e}</span><div aria-hidden="true">${[0,1,2,3].map(()=>y`<div class="loading-row"><span></span><span></span></div>`)}</div></div>`}var C=e=>e?y`<p class="msg error" role="alert">${e}</p>`:b,w=(e,t)=>y`<div class="empty"><strong>${e}</strong><p>${t}</p></div>`;function gt(e){let t=e.split(`/`);return t.at(-1)===`stasis.config.json`&&!t.includes(`node_modules`)}var _t=class extends Te{get changeEvent(){return`local-item-change`}get searchLabel(){return`Search local files`}get optionsLabel(){return`Local files`}get noMatchesLabel(){return`No matching files.`}get emptyLabel(){return`No local files available.`}choices(){let e=this._query.trim().toLocaleLowerCase(),t=this.options.filter(t=>`${t.label} ${t.secondary??``}`.toLocaleLowerCase().includes(e));return{pinned:[],sections:[{options:t}],count:t.length,total:this.options.length,showFacets:!1}}};customElements.define(`managed-local-item-selector`,_t);var vt=class{constructor(e,t,n){this.host=e,this.kind=t,this.upload=n,this.source=null,this.hasData=!1,this.open=!1,this.options=[],this.value=null,this.busy=!1,this.loading=!1,this.error=``,this.success=``,this.generation=0,this.readAbort=null,this.onChange=e=>{if(e?.kind){if(e.kind!==this.kind)return;if(e.value!==this.value){this.refresh();return}}this.readAbort&&!this.readAbort.signal.aborted&&(this.readAbort.abort(),this.error=`The local ${this.kind} changed or the list was refreshed. Select it again before importing.`),this.options=[],this.value=null,this.success=``,this.refresh()},this.onBlur=()=>{this.readAbort&&!this.readAbort.signal.aborted&&this.onChange()},this.onVisibilityChange=()=>{globalThis.document?.visibilityState===`hidden`&&this.onBlur()},e.addController(this)}listeners(){return[[globalThis,`focus`,this.onChange],[globalThis,`blur`,this.onBlur],[globalThis,`storage`,this.onChange],[globalThis.document,`visibilitychange`,this.onVisibilityChange]]}hostConnected(){for(let[e,t,n]of this.listeners())e?.addEventListener(t,n);this.connectSource()}hostUpdated(){this.connectSource()}connectSource(){this.source!==this.host.localImportSource&&(this.unsubscribe?.(),this.abort?.abort(),this.source=this.host.localImportSource,this.unsubscribe=this.source?.subscribe(this.onChange),this.onChange())}hostDisconnected(){++this.generation,this.abort?.abort(),this.unsubscribe?.(),this.source=null;for(let[e,t,n]of this.listeners())e?.removeEventListener(t,n)}async refresh(){let e=++this.generation,t=this.source;this.loading=!0,this.host.requestUpdate();try{let n=t?await t.hasData(this.kind):!1;if(e!==this.generation)return;this.hasData=n;let r=this.open&&!t?.locked?await t?.list(this.kind)??[]:[];if(e!==this.generation)return;this.options=r,r.some(e=>e.value===this.value)||(this.value=null)}catch(t){e===this.generation&&(this.error=String(t?.message??t))}finally{e===this.generation&&(this.loading=!1,this.host.requestUpdate())}}toggle(){this.busy||(this.open=!this.open,this.error=``,this.success=``,this.options=[],this.value=null,this.refresh())}async busyWith(e){let t=this.abort=new AbortController;this.busy=!0,this.error=``,this.host.requestUpdate();try{await e(t)}catch(e){t.signal.aborted||(this.error=String(e?.message??e))}finally{this.readAbort===t&&(this.readAbort=null),this.busy=!1,this.host.requestUpdate()}}async unlock(){this.busy||await this.busyWith(async e=>{await this.source.unlock({signal:e.signal})&&!e.signal.aborted&&await this.refresh()})}async importSelected(){if(this.busy||this.loading||!this.value||this.source?.locked)return;this.success=``;let e=this.options.find(e=>e.value===this.value)?.label;await this.busyWith(async t=>{this.readAbort=t,await this.source.importItem(this.kind,this.value,e=>(this.readAbort=null,this.upload(e)),{signal:t.signal}),!t.signal.aborted&&!this.source?.locked&&(this.success=`Imported ${e}.`,this.value=null)})}renderAction(){return this.hasData||this.open?y`<button type="button" class="local-import-toggle" aria-expanded="${this.open}" aria-controls="local-import-panel" ?disabled="${this.busy}" @click="${()=>this.toggle()}">Import</button>`:b}renderPanel(e){if(!this.open)return b;let t=this.source?.locked;return y`<section class="local-import-panel" id="local-import-panel" aria-label="${`Import local ${this.kind}`}"><div class="local-import-copy"><strong>Import local ${this.kind}</strong><p>${t?`Unlock local data with your passkey to choose a file.`:`Copy a file from this browser to the managed workspace. The local copy stays on this device.`}</p></div><div class="local-import-controls">${t?y`<button type="button" class="local-import-submit" ?disabled="${this.busy}" @click="${()=>this.unlock()}">${this.busy?`Waiting for passkey…`:`Unlock with passkey`}</button>`:y`<managed-local-item-selector label="${`Choose local ${this.kind}`}" placeholder="${this.loading?`Loading local files…`:`Choose local ${this.kind}\u2026`}" .options="${this.options}" .value="${this.value}" ?disabled="${this.busy||this.loading}" @local-item-change="${e=>{this.value=e.detail.value,this.success=``,this.host.requestUpdate()}}"></managed-local-item-selector><button type="button" class="local-import-submit" ?disabled="${e||this.busy||this.loading||!this.value}" @click="${()=>this.importSelected()}">${this.busy?`Importing…`:`Import ${this.kind}`}</button>`} <button type="button" class="local-import-close" ?disabled="${this.busy}" @click="${()=>this.toggle()}">Close</button></div>${!t&&!this.loading&&this.options.length===0?y`<p class="local-import-message">No local ${this.kind}s available.</p>`:b} ${this.error?y`<p class="local-import-message error" role="alert">${this.error} <button type="button" ?disabled="${this.busy}" @click="${()=>{this.error=``,this.refresh()}}">Retry</button></p>`:b} ${this.success?y`<p class="local-import-message" role="status">${this.success}</p>`:b}</section>`}},T=e=>e?AbortSignal.any([e,u.sessionController.signal]):u.sessionController.signal,yt=()=>new DOMException(`Managed session changed`,`AbortError`),E=e=>e.json();async function bt({signal:e}={}){e=T(e),e.throwIfAborted();let t=await l(`/api/admin/bundles`,{credentials:`same-origin`,signal:e});if(e.throwIfAborted(),!t.ok)throw Object.assign(Error(`Bundle catalogue request failed (${t.status})`),{status:t.status});let n=await t.json();return e.throwIfAborted(),n.bundles??[]}async function xt(e,t,n){let r=u.generation,i=await l(`/api/bundles/${encodeURIComponent(e)}/${t}`,{credentials:`same-origin`,signal:n});if(n?.throwIfAborted(),!i.ok)throw Object.assign(Error(`Bundle ${t} request failed (${i.status})`),{status:i.status});let a=t===`contents`?await i.text():await i.json();if(n?.throwIfAborted(),r!==u.generation)throw yt();return a}function St(e,{signal:t}={}){return u.load(`bundle-metadata:${e}`,`bundle metadata`,t=>xt(e,`metadata`,t),{signal:t,retryInvalidated:!0})}async function Ct(e,{signal:t}={}){t=T(t);let n=await xt(e,`metadata`,t),r=n?.bundle?.repo??null,i=at({repo:r});if(!i)return r;let a=new URLSearchParams({repo:i,directory:r.directory??``}),o=new Set(n.unsized??[]),s=Ge((n.files??[]).filter(([e,t])=>t!=null||o.has(e)).map(([e])=>e));s&&a.set(`filePrefix`,s);let c=await l(`/api/admin/repositories/resolve?${a}`,{credentials:`same-origin`,cache:`no-store`,signal:t});if(t.throwIfAborted(),!c.ok)throw Error(`Repository suggestion request failed (${c.status})`);let{location:u}=await c.json();return t.throwIfAborted(),u?{...r,github:u.github,...u.mapped?{directory:u.directory}:{},repoId:u.repoId}:r}async function wt(e,{signal:t}={}){t=T(t);try{return await xt(e,`contents`,t)}catch(e){throw e.name!==`AbortError`&&u.notify(`Couldn't load bundle contents: ${e.message}`),e}}function Tt(e,t,n=``,r=!1,i=!1){let a=n?`${n.startsWith(`entry:`)?`entry`:`reason`}=${encodeURIComponent(n.slice(n.indexOf(`:`)+1))}`:``,o=[t?`team=${encodeURIComponent(t)}`:``,a,r?`repoAdvisories=true`:``,i?`details=true`:``].filter(Boolean).join(`&`);return xt(e,`advisories${o?`?${o}`:``}`,u.sessionController.signal)}var Et={"patch-not-found":`The patch isn’t at the commit it was looked for at.`,"patch-mismatch":`The file at the commit the patch was read at isn’t the patch its lockfile names.`,"patch-unreadable":`The patch is written so that pnpm versions, or macOS and Windows, may apply it differently.`,"patch-unsupported":`The patch changes a file’s bytes, or gives it a mode other than 644 or 755, which isn’t reviewed here.`,"patch-does-not-apply":`The patch doesn’t apply to this version, though pnpm may still install part of it.`,"patch-too-large":`The patch is too large to read here.`,"no-repository":`The repository the patch is in isn’t available to you.`,"no-directory":`Only some of the repository the patch is in is available to you.`,"github-token-required":`Reading the patch needs your GitHub sign-in.`,"patch-not-kept":`The patch isn’t kept here: a review of a version it patches keeps it, as does a team’s Dependencies tab of its repository’s default branch.`},Dt=e=>e?{patchHash:e.hash,...e.repoId==null?{}:{patchRepoId:String(e.repoId),patchCommit:e.commit},...e.path==null?{}:{patchPath:e.path}}:{},D={...Et,"bad-tarball":`This package's tarball couldn't be read.`,"tarball-conflict":`This package's tarball isn't shown, as it doesn't install as one set of files: it holds two different files at one path, or at paths that are one on macOS or Windows, or a file within another, which installers each install their own way.`,"upstream-invalid":`The npm registry's answer for this package couldn't be read.`,"upstream-too-large":`The npm registry's answer for this package is too large to read here.`,400:`Not an npm package name and version.`,404:`No such package version, or it is not available to you.`,413:`This package is too large to open here.`,429:`Too many packages are loading. Try again shortly.`,502:`The npm registry couldn't be reached.`},Ot=15e3,O=new Map;function kt(e){if(O.has(e))return;let t=new AbortController,n=l(e,{credentials:`same-origin`,signal:AbortSignal.any([t.signal,u.sessionController.signal])});n.catch(()=>{});let r={reading:n,until:Date.now()+Ot,generation:u.generation};O.set(e,r),setTimeout(()=>{O.get(e)===r&&(O.delete(e),t.abort())},Ot)}function At(e,t){let n=O.get(e);return n?(O.delete(e),n.until>Date.now()&&n.generation===t?n.reading:null):null}var jt=(e,t)=>new Promise((n,r)=>{let i=()=>r(t.reason);t.aborted?i():(t.addEventListener(`abort`,i,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener(`abort`,i)))});async function k(e,t,n,r,i={}){r=T(r);let a=u.generation,o=()=>l(e,{credentials:`same-origin`,...i,signal:r}),s=i.method?null:At(e,a),c=s&&await jt(s,r).then(e=>e.ok?e:null,e=>{if(r.aborted)throw e;return null})||await o();if(r.throwIfAborted(),!c.ok){let e=await c.json().catch(()=>null),n=e?.error??null;throw Object.assign(Error(t[n]??t[c.status]??`Request failed (${c.status})`),{status:c.status,code:n,...typeof e?.commit==`string`?{commit:e.commit}:{}})}let d=await n(c);if(r.throwIfAborted(),a!==u.generation)throw yt();return d}var A=(e,t,n)=>k(`/api/npm/${e}?${new URLSearchParams(t)}`,D,E,n),Mt={"no-repository":`This repository is not available to you.`,"no-directory":`This directory is not at that commit, or not available to you.`,"directory-too-large":`This directory is too large to open here. Open one of its directories instead.`,"directory-unreadable":`GitHub’s archive of this directory couldn’t be read here, as when a symlink in it points outside the repository.`,"repository-busy":`Too many directories and packages are loading. Try again shortly.`,"repository-changed":`The repository changed while it was read. Try again.`,"github-rate-limited":`GitHub’s API rate limit has been reached. Try again later.`,"github-unauthorized":`GitHub authentication has expired or was revoked. Sign in again.`,"github-status-403":`GitHub denied this request. Check repository access and the GitHub App’s read permissions.`,"github-malformed":`GitHub’s archive of this directory could not be verified against its commit.`,"github-unreachable":`Could not connect to GitHub. Try again shortly.`,"github-moved":`GitHub moved this repository, as when it is renamed. Try again shortly.`,"github-timeout":`GitHub took too long to answer. Try again shortly.`,400:`Not a repository directory and commit.`,403:`Repository access is required to read its files.`,404:`This repository, commit or directory is unavailable.`,413:`This directory is too large to open here.`,429:`Too many directories and packages are loading. Try again shortly.`,502:`GitHub couldn’t be reached.`},j=(e,t,n,r=Mt)=>k(`/api/admin/repositories/${e}?${new URLSearchParams(t)}`,r,E,n);function Nt(e,t,n,{signal:r}={}){return j(`code`,{repoId:e,ref:t,path:n},r)}async function Pt({signal:e}={}){return(await j(`browsable`,{},e)).repos??[]}function Ft(e,{signal:t}={}){return j(`refs`,{repoId:e},t)}function It(e,t,n,{signal:r,commitOnly:i=!1}={}){return j(`contents`,{repoId:e,ref:t,path:n,...i?{listing:`none`}:{}},r)}var Lt={...Mt,"no-directory":`This directory’s history is not available to you.`,"github-malformed":`GitHub answered with a history that couldn’t be read.`,"github-token-required":`Reading every branch needs your GitHub sign-in.`,400:`Not a repository’s history.`};function Rt(e,t,n,{page:r=1,all:i=!1,fresh:a=!1,from:o=null,signal:s}={}){return j(`history`,{repoId:e,ref:t,path:n,page:r,...i?{all:`true`}:{},...a?{fresh:`true`}:{},...o?{from:o.join(`,`)}:{}},s,Lt)}var zt={...Lt,"no-directory":`This directory’s changes are not available to you.`,"github-malformed":`GitHub answered with a commit’s files that couldn’t be read.`,400:`Not a repository’s commits.`};function Bt(e,t,n,{signal:r}={}){return j(`changes`,{repoId:e,path:t,shas:n.join(`,`)},r,zt)}function Vt(e,t,n,{signal:r}={}){return j(`tree`,{repoId:e,path:t,commit:n},r,zt)}var M={...Mt,"no-directory":`Issues and pull requests show only with access to the whole repository.`,"github-malformed":`GitHub answered with a list that couldn’t be read.`,"github-token-required":`Reading issues and pull requests needs your GitHub sign-in.`,"github-status-403":`GitHub refused to list these. The GitHub App reading this repository needs Issues: read and Pull requests: read, which an owner of its installation approves.`,400:`Not a repository’s issues or pull requests.`},Ht=(e,t,n,r)=>`/api/admin/repositories/issues?${new URLSearchParams({repoId:e,kind:t,state:n,...r?{after:r}:{}})}`;function Ut(e,t,{state:n=`open`,after:r=null,signal:i}={}){return k(Ht(e,t,n,r),M,E,i)}var Wt={...M,"no-directory":`Agents show only with access to the whole repository.`,"github-token-required":`Reading what the agents did needs your GitHub sign-in.`,400:`Not a repository’s agents.`},Gt=(e,t,n)=>`/api/admin/repositories/agents?${new URLSearchParams({repoId:e,...t?{pulls:t}:{},...n?{commits:n}:{}})}`;function Kt(e,{pulls:t=null,commits:n=null,signal:r}={}){return k(Gt(e,t,n),Wt,E,r)}var qt={...M,"github-not-found":`GitHub has no issue or pull request of that number here.`,400:`Not an issue or pull request of a repository.`};function Jt(e,t,{signal:n}={}){return j(`item`,{repoId:e,number:t},n,qt)}var Yt={...qt,"github-not-found":`GitHub has no pull request of that number here.`,"github-malformed":`GitHub answered with a pull request or lockfile that couldn’t be read.`,"github-status-403":`GitHub refused to read its lockfiles. The GitHub App reading this repository needs Contents: read and Pull requests: read, which an owner of its installation approves.`,400:`Not a pull request of a repository.`},Xt=({review:e,listed:t})=>({...e?{review:`1`}:{},...t?{listed:`1`}:{}});function Zt(e,t,{review:n=!1,listed:r=!1,signal:i}={}){return j(`pull-dependencies`,{repoId:e,number:t,...Xt({review:n,listed:r})},i,Yt)}async function Qt(e,t,{review:n=!1,listed:r=!1,signal:i}={}){let{pulls:a,users:o,deltas:s}=await j(`pull-dependencies`,{repoId:e,numbers:t.join(`,`),...Xt({review:n,listed:r})},i,Yt);return $t(a,o,s)}var $t=(e,t,n)=>new Map((Array.isArray(e)?e:[]).filter(e=>Number.isSafeInteger(e?.number)).map(e=>[e.number,typeof e.error==`string`?Object.assign(Error(Yt[e.error]??`It couldn\u2019t be read (${e.error}).`),{code:e.error}):{...e,...t?{users:t}:{},...Array.isArray(n)&&n.length>0?{deltas:n}:{}}])),en={...qt,"github-not-found":`GitHub has none of a lockfile it lists on the default branch.`,"github-malformed":`GitHub answered with a lockfile that couldn’t be read.`,"github-status-403":`GitHub refused to read its lockfiles. The GitHub App reading this repository needs Contents: read, which an owner of its installation approves.`,400:`Not a repository.`},tn={...en,"no-bundle":`This bundle is not available to you.`,"bundle-unavailable":`This bundle’s packages couldn’t be read.`,"directory-package-malformed":`This bundle records a package installed from a directory with an integrity, or naming no directory.`,"payload-too-large":`This bundle holds too many packages to check here.`,"repository-changed":`The bundle or its repository changed while it was read. Try again.`,"github-not-found":`GitHub has none of the commit this bundle was built from, or of a lockfile it lists there.`,400:`Not a bundle.`};function nn(e,{signal:t}={}){return k(`/api/bundles/${encodeURIComponent(e)}/dependency-review`,tn,E,t)}var rn={...tn,"unsupported-bundle":`Only Stasis bundles are validated.`,"validation-busy":`Other bundles are being validated. Try again shortly.`,"validation-failed":`The validation failed. Try again.`,"csrf-missing":`Your session is missing its request token. Reload the page.`,"csrf-mismatch":`Your session changed. Reload the page.`,429:`Other bundles are being validated. Try again shortly.`},an=e=>`/api/bundles/${encodeURIComponent(e)}/validation`;function on(e,{signal:t}={}){return k(an(e),rn,E,t)}function sn(e,t,{signal:n}={}){return k(an(e),rn,e=>e.json().catch(()=>null),n,{method:`POST`,headers:{"x-csrf-token":t}})}var cn={"no-team":`This team is not available to you.`,400:`Not a team’s repositories.`},ln=`GitHub failed to answer. Try again shortly.`,un={...M,"github-status-502":ln,"github-status-504":ln,"time-up":`Reading them took too long.`},dn=e=>`Not all its open pull requests were read. ${un[e]??`(${e})`}`;function fn(e,t,{repoIds:n=null,kept:r=!1,signal:i}={}){let a=new URLSearchParams({...n?{repoIds:n.join(`,`)}:{},...r?{kept:`1`}:{}}),o=a.size>0?`?${a}`:``;return k(`/api/teams/${encodeURIComponent(e)}/dependencies${o}`,cn,async e=>{for await(let n of jn(e))typeof n.error==`string`?t({...n,error:en[n.error]??en[n.status]??`It couldn\u2019t be read (${n.error}).`,code:n.error}):t({...n,...Array.isArray(n.dependencies)?{dependencies:$t(n.dependencies,n.users)}:{},...typeof n.pulls?.error==`string`?{pulls:{...n.pulls,error:dn(n.pulls.error)}}:{}})},i)}function pn(e,t,n,r,{signal:i}={}){let a=JSON.stringify({since:t,versions:n.map(({name:e,version:t})=>[e,t])});return k(`/api/teams/${encodeURIComponent(e)}/dependency-reviews/changed`,cn,e=>e.json().then(e=>({now:Number.isSafeInteger(e?.now)?e.now:null,versions:Array.isArray(e?.versions)?e.versions.flatMap(e=>Array.isArray(e)&&typeof e[0]==`string`&&typeof e[1]==`string`?[{name:e[0],version:e[1]}]:[]):[]})),i,{method:`POST`,headers:{"content-type":`application/json`,"x-csrf-token":r},body:a})}var mn={...M,"no-directory":`Pulse shows only with access to the whole repository.`,"github-malformed":`GitHub answered with statistics that couldn’t be read.`,"github-token-required":`Reading a repository’s pulse needs your GitHub sign-in.`,"github-status-403":`GitHub refused to read these. The GitHub App reading this repository needs Contents, Issues and Pull requests: read, which an owner of its installation approves.`,400:`Not a repository’s pulse.`},hn=(e,t)=>`/api/admin/repositories/pulse?${new URLSearchParams({repoId:e,weeks:t})}`;function gn(e,t,{signal:n}={}){return k(hn(e,t),mn,E,n)}function _n(e,t,{state:n=`open`,weeks:r=4}={}){t===`issues`||t===`pulls`?kt(Ht(e,t,n,null)):t===`agents`?kt(Gt(e,null,null)):t===`pulse`&&kt(hn(e,r))}function vn(e,t,{from:n,to:r=null,authors:i=[]},{signal:a}={}){return j(`pulse/items`,{repoId:e,weeks:t,from:n,...r===null?{}:{to:r},...i.length>0?{authors:i.join(`,`)}:{}},a,mn)}function yn(e,t,{signal:n,patch:r=null}={}){return A(`package`,{name:e,version:t,...Dt(r)},n)}function bn(e,{signal:t}={}){return A(`versions`,{name:e},t)}function xn(e,{signal:t}={}){return A(`stats`,{name:e},t)}function Sn(e,{signal:t}={}){return A(`advisories`,{name:e},t)}function Cn(e,t,{signal:n}={}){return A(`tags`,{name:e,version:t},n)}function wn(e,t,{signal:n}={}){return A(`socket`,{name:e,version:t},n)}function Tn(e,t,n=null,{signal:r}={}){return A(`risk`,{name:e,version:t,...n===null?{}:{otherVersion:n}},r)}function En(e,t,{signal:n}={}){return A(`provenance`,{name:e,version:t},n)}var N={404:`This file is no longer available.`,409:`This file has changed since it was opened.`,413:`This file is too large to pretty-print.`,422:`This file couldn't be read as code.`,"pretty-mismatch":`Pretty-printing would change more than its layout, so it is shown as published.`,unsupported:`This kind of file can't be checked once pretty-printed, so it is shown as published.`,429:`Too many files are being pretty-printed. Try again shortly.`,502:`The npm registry couldn't be reached.`};function Dn(e,t,n,{signal:r}={}){return k(`/api/bundles/${encodeURIComponent(e)}/pretty?${new URLSearchParams({path:t,hash:n})}`,N,kn,r)}function On(e,t,n,r,{signal:i}={}){return k(`/api/npm/pretty?${new URLSearchParams({name:e,version:t,path:n,hash:r})}`,{...D,...N},kn,i)}var kn=async e=>({...await e.json(),source:e.headers.get(`x-source-hash`)});async function*An(e){let t=e.body.pipeThrough(new TextDecoderStream).getReader(),n=[];for(;;){let{done:e,value:r}=await t.read();if(e)return;let i=0;for(let e=r.indexOf(`
2
2
  `);e!==-1;i=e+1,e=r.indexOf(`
3
3
  `,i))n.push(r.slice(i,e)),yield JSON.parse(n.join(``)),n=[];n.push(r.slice(i))}}async function*jn(e){let t=u.generation;for await(let n of An(e)){if(t!==u.generation)throw yt();yield n}}function Mn(e,t,n,{signal:r}={}){return P(`/api/npm/pretty?${new URLSearchParams({name:e,version:t})}`,D,n,r)}function Nn(e,t,n,{signal:r}={}){return P(`/api/bundles/${encodeURIComponent(e)}/pretty?${new URLSearchParams({other:t})}`,N,n,r)}function Pn(e,t,n,r,{signal:i}={}){return P(`/api/npm/pretty?${new URLSearchParams({name:e,version:t,otherVersion:n})}`,D,r,i)}function P(e,t,n,r,i=N){return k(e,t,async e=>{for await(let{error:t,status:r,...a}of jn(e))await n(t?{...a,status:r,message:i[t]??i[r]??`Request failed (${r})`}:a)},r)}var Fn={...N,413:`This file is too large to compare with renamed names hidden.`,422:`This file couldn't be compared as code.`,"diff-busy":`Too many files are being compared. Try again shortly.`,504:`Comparing this file took too long.`},In=(e,t)=>k(e,Fn,E,t);function Ln(e,t,{path:n,hash:r,otherPath:i,otherHash:a},{signal:o}={}){return In(`/api/bundles/${encodeURIComponent(e)}/rename-diff?${new URLSearchParams({path:n,hash:r,other:t,otherPath:i,otherHash:a})}`,o)}function Rn(e,t,n,{path:r,hash:i,otherPath:a,otherHash:o},{signal:s}={}){return In(`/api/npm/rename-diff?${new URLSearchParams({name:e,version:t,path:r,hash:i,otherVersion:n,otherPath:a,otherHash:o})}`,s)}var zn=(e,t)=>new URLSearchParams({other:e,...t?{scope:t}:{}});function Bn(e,t,n,{signal:r,scope:i=``}={}){return P(`/api/bundles/${encodeURIComponent(e)}/rename-diff?${zn(t,i)}`,N,n,r,Fn)}function Vn(e,t,n,r,{signal:i}={}){return P(`/api/npm/rename-diff?${new URLSearchParams({name:e,version:t,otherVersion:n})}`,D,r,i,Fn)}function Hn(e,t,n,{signal:r,scope:i=``}={}){return P(`/api/bundles/${encodeURIComponent(e)}/type-only?${zn(t,i)}&runs=1`,N,n,r)}function Un(e,t,n,r,{signal:i}={}){return P(`/api/npm/type-only?${new URLSearchParams({name:e,version:t,otherVersion:n,runs:`1`})}`,D,r,i)}var Wn={...D,"delta-busy":`Too many packages are being counted. Try again shortly.`,"delta-timeout":`Counting its lines took too long.`,"delta-failed":`Its lines couldn’t be counted.`};function Gn(e,t,{signal:n}={}){return k(`/api/npm/deltas?${new URLSearchParams({versions:JSON.stringify(e)})}`,Wn,async e=>{for await(let{error:n,status:r,...i}of jn(e))t(n?{...i,error:Wn[n]??Wn[r]??`Request failed (${r})`}:i)},n)}var Kn={404:`This bundle is no longer available.`,422:`This bundle couldn't be read.`,429:`Too many bundles are being compared. Try again shortly.`},qn=async e=>{let t=await e.json();return t.files.basePaths=new Map(t.files.basePaths),t};function Jn(e,t,{signal:n,scope:r=``}={}){return k(`/api/bundles/${encodeURIComponent(e)}/comparison?${zn(t,r)}`,Kn,qn,n)}function Yn(e,t,n,{signal:r,otherName:i=e,patch:a=null,otherPatch:o=null}={}){return k(`/api/npm/comparison?${new URLSearchParams({name:e,version:t,otherVersion:n,...i===e?{}:{otherName:i},...Dt(a),...o?{otherPatchHash:o.hash}:{}})}`,D,qn,r)}async function F(e,t){let n=await l(e,{signal:t,credentials:`same-origin`,headers:{accept:`application/json`}});if(!n.ok)throw Error(`HTTP ${n.status}`);return n.json()}function I(e,t,n,{signal:r,token:i=!!t}={}){let a={"content-type":`application/json`};return i&&(a[`x-csrf-token`]=t),l(e,{method:`POST`,credentials:`same-origin`,...r?{signal:r}:{},headers:a,body:JSON.stringify(n)})}async function L(e,t,n){let r=await I(e,t,n);if(!r.ok)throw Error(`HTTP ${r.status}`);return r}function Xn(e,t){return async(n=``,r={})=>{let i=await l(`${e}${n}`,{credentials:`same-origin`,...r}),a=await i.json();if(!i.ok)throw Error(t[a?.error]??`HTTP ${i.status}`);return a}}async function R(e){let t=await e.json().then(e=>typeof e?.error==`string`?e.error:``,()=>``);return[`repo-forbidden`,`forbidden`].includes(t)?`choose a repository and directory within your team access`:`HTTP 403${t?`: ${t}`:``}`}async function Zn(e,t,n){let r=n?{"x-csrf-token":n}:{},i=await l(`/api/admin/${e}/${encodeURIComponent(t)}`,{method:`DELETE`,credentials:`same-origin`,headers:r});if(!i.ok)throw Error(`HTTP ${i.status}`)}function Qn(e,t,n,r){let i={"content-type":r,[`x-${e}-filename`]:encodeURIComponent(t.name)};return n&&(i[`x-csrf-token`]=n),l(`/api/admin/${e}s`,{method:`POST`,credentials:`same-origin`,headers:i,body:t})}async function $n(e,t,n,r,i,a){let o=new URLSearchParams({page:String(t),limit:`100`,kind:n,q:r.trim()});i&&o.set(`repo`,i),a&&o.set(`actor`,a);let s=await F(`/api/admin/history?${o}`,e);if(!Array.isArray(s?.history)||!Number.isSafeInteger(s.total)||s.total<0||!Number.isSafeInteger(s.page)||s.page<1)throw Error(`No history returned`);return s}async function er(e){let t=await F(`/api/admin/users`,e);return Array.isArray(t?.users)?t.users:[]}async function tr(e,t,n){await L(`/api/admin/set-role`,n,{userId:e,role:t})}function nr(e,t,n,r){let i=new URLSearchParams({scope:e});return e===`installed`&&i.set(`showAll`,String(t)),n&&i.set(`refresh`,`true`),F(`/api/admin/repositories?${i}`,r)}async function rr(e,t,n){await L(`/api/admin/repositories/select`,n,{repoId:e,selected:t})}async function ir(e,{enabled:t,required:n,since:r,lockfiles:i},a){let o=await I(`/api/admin/repositories/dependency-review`,a,{repoId:e,enabled:t,required:n,since:r,...i?{lockfiles:i}:{}});if(!o.ok)throw Error(o.status===400?`Enter 1 to 10 required reviews, the commit as its full 40-character id, and at most 100 lockfiles by their paths in the repository; a stasis.config.json only among those reviewed alone.`:`HTTP ${o.status}`);return(await o.json()).dependencyReview}async function ar(e,t){let n=await F(`/api/admin/repositories/lockfiles?repoId=${encodeURIComponent(e)}`,t);return{paths:Array.isArray(n?.lockfiles)?n.lockfiles.flatMap(e=>typeof e?.path==`string`?[e.path]:[]):[],configs:Array.isArray(n?.configs)?n.configs.filter(e=>typeof e==`string`):[]}}var or={400:`Enter a repository as owner/repo or a GitHub repository URL.`,403:`You do not have permission to add arbitrary public repositories.`,404:`No public repository was found at that address.`,409:`Choose a public, non-archived repository.`};async function sr(e,t){let n=await I(`/api/admin/repositories/add-public`,t,{repository:e},{token:!0});if(!n.ok)throw Error(or[n.status]??`GitHub lookup failed (HTTP ${n.status}). Try again.`)}async function cr(e,t){let n=await F(`/api/admin/repositories/impact?repoId=${encodeURIComponent(e)}`,t);if(n?.repoId!==e||!Array.isArray(n.reports)||!Array.isArray(n.bundles)||!Number.isSafeInteger(n.triageCount)||n.triageCount<0)throw Error(`Invalid repository data`);return n}var lr={"github-app-not-configured":`The GitHub App is not configured on this server.`,"repo-identity-changed":`The repository has changed on GitHub. Refresh and check its connection.`,"repo-connection-changed":`The connection or your permissions changed. Refresh and try again.`,"repo-not-connected":`This repository is no longer connected.`,forbidden:`Administrator access is required to connect the GitHub App.`};async function ur(e,t){let n=await I(`/api/admin/repositories/connect-app`,t,{repoId:e},{token:!0}),r=await n.json();if(!n.ok)throw Error(lr[r.error]??`Could not connect the GitHub App (HTTP ${n.status}). Try again.`);if(r.connected===!0)return r;if(r.connected!==!1||typeof r.installUrl!=`string`||!/^https:\/\/github\.com\/apps\/[^/?#]+\/installations\/new$/u.test(r.installUrl))throw Error(`Invalid GitHub installation response.`);return r}async function dr(e,t,n,r){return(await L(`/api/admin/repositories/remove`,r,{repoId:e,fullName:t,acknowledge:!0,deleteTriage:n})).json()}function fr(e){return F(`/api/admin/reports`,e)}var pr={"unsupported-entries":`Select JavaScript/TypeScript files (including JSX/TSX) or Solidity files. Stasis cannot mix languages or use JSON or Rust as remote entry points.`,"bad-conditions":`Check the export conditions and selected platforms.`,"metro-conditions":`Stasis’s Metro preset requires the react-native condition without manual changes.`,"config-invalid":`Stasis can’t read the stasis.config.json these entry points are under, build them with the options it sets, or lay out the lockfiles it names. Check it at this revision.`,"config-mixed":`Entry points listed in a stasis.config.json are built with its options, alone. Select only those it lists, or only other files.`,"config-conditions":`These entry points are listed in stasis.config.json, which sets their options, so they take no conditions. Reload the directory and try again.`,"config-runs-code":`stasis.config.json sets an option for these entry points that runs the repository’s code, such as babel. Bundles built here never run it.`,"config-policy":`The bundle holds a path or package that stasis.config.json’s allowedPaths, disallowedPaths, allowedModules or disallowedModules refuses, or that its excludeModules excludes.`,"stasis-lock":`The build doesn’t agree with the repository’s stasis.lock.json, or stasis.config.json’s lock = frozen needs one that isn’t there. Update it at this revision.`,"commit-not-own":`Stasis can’t find this commit in the history of the repository’s branches or tags: it may be a fork’s, which GitHub serves through the repository too. Pick a commit of its default branch, a branch or a tag.`,"build-lockfile":`Stasis needs a supported lockfile: pnpm-lock.yaml, yarn.lock (Yarn 1), package-lock.json, or soldeer.lock.`,"build-scope":`Your team needs access to the bundle’s project root, including its lockfile and dependencies.`,"build-busy":`A bundle is already being built, or the server is busy. Try again shortly.`,"build-timeout":`The bundle build timed out. Try a smaller selection or retry.`,"too-large":`This bundle exceeds the server’s size limit.`,"build-memory":`Building this selection needs more memory than the server gives a build. Select fewer entry points, or build it with stasis github-bundle and upload the bundle.`,"github-rate-limited":`GitHub’s API rate limit has been reached. Retry after the limit resets.`,"github-build-failed":`Could not fetch the repository from GitHub. Check access and retry.`,"repository-changed":`The repository connection changed during the build. Reload and try again.`,"bundle-conflict":`This bundle already exists but is outside your current access.`,"build-failed":`Stasis could not build this selection. Check that its lockfile is supported and all entry points and imports exist at this commit.`};async function mr(e,t,n){let r=await I(`/api/admin/bundles/create`,t,e,{signal:n,token:!0}),i=await r.json();if(!r.ok)throw Error(pr[i.error]??(r.status===401?`Sign in again to create a bundle.`:r.status===403||r.status===404?`Repository access is required to create this bundle.`:`Could not create the bundle. Try again.`));return i}async function hr(e,t){let n=(await F(`/api/config`)).managed?.uploadMaxBytes?.reports;if(Number.isSafeInteger(n)&&n>0){if(e.size>n)throw Error(`too large`)}else if(e.size>3145728)return gr(e,t);let r=Ae(await e.text(),e.name);if(!r)return gr(e,t);let i=[],a=[];for(let{name:e,content:n}of r)try{a.push(await gr(new File([n],e,{type:`application/json`}),t))}catch(t){i.push(`${e}: ${String(t?.message??t)}`)}if(i.length>0)throw Error(`${i.length} of ${r.length} products failed (${i.join(`; `)})`);return a.at(-1)}async function gr(e,t){let n=await Qn(`report`,e,t,e.type||`application/json`);if(!n.ok){if(n.status===413)throw Error(`too large`);if(n.status===403)throw Error(await R(n));let e=await n.json().catch(()=>null);if(e?.error===`storage-encryption-required`)throw Error(`Link reports require managed storage encryption. Configure MANAGED_STORAGE_ENCRYPTION_KEY.`);if(e?.error===`invalid-report`)throw Error(typeof e.reason==`string`&&e.reason?`This file is not a report: ${e.reason}`:`This file is not a recognized report.`);let t=e?.error===`repo-not-connected`&&typeof e.repo==`string`?`: ${e.repo} is not connected`:``;throw Error(`HTTP ${n.status}${t}`)}return n.json()}async function _r(e,t,n){await L(`/api/admin/reports/set-visible`,n,{reportId:e,visible:t})}async function vr(e,t,n){let r=await I(`/api/admin/reports/set-opening`,n,{reportId:e,confirmedDefault:t});if(!r.ok)throw Error(r.status===409?`this report already opens as an App view, or has no Confirmed findings`:`HTTP ${r.status}`)}async function yr(e,t,n,r){let i=await I(`/api/admin/reports/set-repo`,r,{reportId:e,repoId:t,directory:n});if(!i.ok)throw i.status===409?Error(`this report already defines its repository`):i.status===403?Error(await R(i)):Error(i.status===400?`invalid repository or directory`:`HTTP ${i.status}`);return i.json()}async function br(e,t){let n=await l(`/api/admin/reports/${encodeURIComponent(e)}/location`,{signal:t,credentials:`same-origin`});if(!n.ok)throw Error(`Report location suggestion request failed (${n.status})`);return(await n.json())?.location??null}function xr(e,t){return Zn(`reports`,e,t)}function Sr(e){return F(`/api/admin/bundles`,e)}async function Cr(e,t){let n=await Qn(`bundle`,e,t,`application/octet-stream`);if(!n.ok)throw Error(n.status===413?`too large`:n.status===403?await R(n):`HTTP ${n.status}`);return n.json()}async function wr(e,t){let n=await F(`/api/admin/bundles/${encodeURIComponent(e)}/usage`,t);if(n?.bundleId!==e||!Array.isArray(n.reports)||!n.reports.every(e=>typeof e?.filename==`string`)||!Number.isSafeInteger(n.otherReports)||n.otherReports<0)throw Error(`Invalid bundle usage`);return n}function Tr(e,t){return Zn(`bundles`,e,t)}async function Er(e,t,n){await L(`/api/admin/bundles/set-visible`,n,{bundleId:e,visible:t})}async function Dr(e,t,n,r){let i=await I(`/api/admin/bundles/set-repo`,r,{bundleId:e,repoId:t,directory:n});if(!i.ok)throw Error(i.status===403?await R(i):i.status===400?`invalid repository or directory`:`HTTP ${i.status}`)}function Or(e){return F(`/api/admin/teams`,e)}var kr={"name-taken":`name already taken`,"not-team-organization":`that organization owns none of the team’s repositories`,"github-unavailable":`GitHub couldn’t be reached to check the organization`};async function Ar(e,t,n){let r=await I(`/api/admin/teams${e}`,t,n);if(!r.ok)throw Error(kr[await r.json().then(e=>e?.error,()=>null)]??`HTTP ${r.status}`)}async function jr(e,t){let{organizations:n,unchecked:r}=await F(`/api/admin/teams/icons?teamId=${encodeURIComponent(e)}`,t);return{organizations:Array.isArray(n)?n:[],unchecked:Array.isArray(r)?r:[]}}var Mr=`.local-import-toggle{flex-shrink:0;margin-block:calc(-.25rem - 1px);margin-left:auto;padding:.25rem .6rem;border:1px solid var(--border);border-radius:var(--ui-radius, 6px);background:transparent;color:var(--muted);font:inherit;font-size:.75rem;line-height:1.5}.local-import-toggle:hover,.local-import-toggle[aria-expanded=true]{color:var(--text);background:rgb(from var(--text) r g b / .06)}.local-import-panel{display:grid;gap:.8rem;padding:1rem;margin-bottom:1.25rem;border:1px solid var(--border);border-radius:var(--ui-radius, 8px);background:rgb(from var(--accent) r g b / .025)}.local-import-copy strong{font-size:.82rem;font-weight:600}.local-import-copy p,.local-import-message{margin:.3rem 0 0;color:var(--muted);font-size:.75rem;line-height:1.5}.local-import-controls{display:flex;align-items:center;flex-wrap:wrap;gap:.5rem}managed-local-item-selector{flex:1 1 16rem;min-width:0}.local-import-controls button,.local-import-message button{padding:.35rem .7rem;border:1px solid var(--border);border-radius:var(--ui-radius, 5px);background:transparent;color:var(--text);font:inherit;font-size:.75rem;line-height:1.5}.local-import-controls .local-import-submit{border-color:rgb(from var(--accent) r g b / .4);background:rgb(from var(--accent) r g b / .1);color:var(--accent)}.local-import-controls .local-import-close{color:var(--muted)}.local-import-panel button:disabled,.local-import-toggle:disabled{opacity:.5}.local-import-panel button:focus-visible,.local-import-toggle:focus-visible{outline:2px solid var(--accent);outline-offset:2px}.local-import-message.error{color:var(--critical)}
4
4
  `,Nr=`.home-section{margin-block:1.1rem 2rem}.section-heading{display:flex;align-items:baseline;gap:1rem;margin-bottom:.85rem}.section-heading h2{margin:0;font-size:.86rem;font-weight:600}.section-heading>span{color:var(--muted);font-size:.75rem}.pages{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:.9rem}.page{display:flex;flex-direction:column;gap:.85rem;padding:1.35rem;border:1px solid var(--border);border-radius:var(--ui-radius, 12px);color:var(--text);background:var(--panel);text-align:left;font:inherit}.page:hover{background:var(--panel-hover);border-color:color-mix(in srgb,var(--muted) 60%,var(--border))}.page-top{display:flex;align-items:center;gap:.75rem;width:100%}.page-icon{display:grid;place-items:center;flex-shrink:0;width:2.5rem;height:2.5rem;border:1px solid color-mix(in srgb,var(--accent) 16%,var(--border));border-radius:var(--ui-radius, 9px);background:color-mix(in srgb,var(--accent) 7%,var(--panel));color:var(--accent)}.page-bundle .page-icon{color:var(--green);border-color:color-mix(in srgb,var(--green) 18%,var(--border));background:color-mix(in srgb,var(--green) 6%,var(--panel))}.page-scan .page-icon{color:var(--scan-icon-color, var(--yellow));border-color:color-mix(in srgb,var(--scan-icon-color, var(--yellow)) 18%,var(--border));background:color-mix(in srgb,var(--scan-icon-color, var(--yellow)) 6%,var(--panel))}:host-context(body.theme-light) .page-scan .page-icon{--scan-icon-color: #bf8700}:host-context(body.theme-green) :is(.page-bundle,.page-scan) .page-icon,:host-context(body.theme-pink) :is(.page-bundle,.page-scan) .page-icon{color:var(--accent);border-color:color-mix(in srgb,var(--accent) 16%,var(--border));background:color-mix(in srgb,var(--accent) 7%,var(--panel))}.page-icon svg{width:1.2rem;height:1.2rem}.arrow{display:flex;margin-left:auto;flex-shrink:0;color:var(--muted)}.arrow svg{width:1rem;height:1rem}.page:hover .arrow{color:var(--text)}.page-copy{display:grid;gap:.45rem}.page>.page-copy{margin-inline-start:3.25rem}.page-copy strong,.page-title{font-size:1rem;font-weight:600;letter-spacing:-.015em}.page-copy>span{color:var(--muted);font-size:.8rem;line-height:1.65}.workspace-pages .page{padding:1.2rem 1.35rem}.workspace-pages .page-icon{width:2rem;height:2rem;color:var(--muted);background:transparent;border-color:var(--border)}.workspace-pages .page-title{font-size:.9rem}.workspace-pages .page-copy{margin-inline-start:2.75rem}.history-link{display:flex;align-items:center;gap:1rem;width:100%;padding:1.25rem 0;border:0;border-top:1px solid var(--border);text-align:left;color:var(--text);background:transparent}.history-link>.page-icon{color:var(--muted);background:transparent;border-color:var(--border)}.history-link .page-copy strong{font-size:.85rem}.history-cta{display:flex;align-items:center;gap:.6rem;flex-shrink:0;margin-left:auto;color:var(--muted);font-size:.78rem}.history-cta svg{width:1rem;height:1rem}.history-link:hover .history-cta{color:var(--accent)}@container (max-width: 48rem){.pages{grid-template-columns:1fr;gap:.65rem}.page,.workspace-pages .page{gap:.65rem;padding:1.15rem}.page-top .arrow{display:none}.workspace-pages .page-icon{width:2.5rem;height:2.5rem}.workspace-pages .page-copy{margin-inline-start:3.25rem}.page-copy{gap:.2rem}.page-copy strong,.page-title{font-size:.95rem}.section-heading>span{display:none}.history-cta{font-size:0}}
@@ -10,23 +10,23 @@ import{b as e,d as t,i as n}from"./chunk-SUFRZ5U7.js";import{a as r}from"./chunk
10
10
  `,zr=`.location-editor{display:grid;grid-template-columns:minmax(0,1fr) minmax(10rem,.7fr) auto;align-items:end;gap:.75rem;padding:.85rem;border-top:1px solid var(--border);background:rgb(from var(--bg) r g b / .35)}.location-field{display:grid;gap:.35rem;min-width:0}.location-field>span,.location-field label{color:var(--muted);font-size:.75rem}.location-field input{width:100%}.location-field input[type=text],.location-actions .action{height:2rem;min-height:2rem;padding-block:.28rem}.location-actions{display:flex;gap:.4rem}.location-actions .action{width:auto;padding-inline:.65rem;border:1px solid var(--border);border-radius:var(--ui-radius, 6px);color:var(--text);background:var(--bg);font-size:.78rem}.location-field-header{display:flex;align-items:baseline;justify-content:space-between;gap:.5rem;min-width:0;color:var(--muted);font-size:.75rem}.location-field-header>:first-child{flex-shrink:0}.location-metadata{display:flex;align-items:baseline;gap:.25rem;min-width:0;padding:0;border:0;color:inherit;background:none;font:inherit}.location-metadata>.ui-hint{flex-shrink:0}.location-metadata-value{min-width:0;user-select:text;-webkit-user-select:text;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}button.location-metadata:hover:not(:disabled){color:var(--text)}.location-origin{grid-column:1 / -1;margin:0;color:var(--muted);font-size:.72rem;overflow-wrap:anywhere}.origin-retry{padding:0;border:0;background:none;color:var(--accent);font:inherit}
11
11
  `,Br=`.avatar{position:relative;display:inline-grid;place-items:center;flex:0 0 auto;width:2rem;height:2rem;border-radius:50%;overflow:hidden;font-family:system-ui,-apple-system,BlinkMacSystemFont,sans-serif;font-size:.8rem;font-weight:600;user-select:none}.create-team{display:flex;flex-wrap:wrap;align-items:center;gap:.5rem;margin-bottom:1rem}.new-name{flex:1 1 14rem;width:16rem;max-width:24rem}.access-note{flex:1 1 24rem;margin:0 0 0 auto;color:var(--muted);font-size:.75rem;text-align:right}.team .icon-btn{width:1.8rem;height:1.8rem}.team{border:1px solid var(--border);border-radius:var(--ui-radius, 8px);margin-bottom:.85rem;background:var(--panel);overflow:hidden}.team-head{display:flex;align-items:center;gap:.5rem;min-height:2.75rem;padding:.4rem .85rem;border-bottom:1px solid var(--border);background:rgb(from var(--text) r g b / .025)}.team-icon{display:grid;place-items:center;flex:0 0 auto;width:1.6rem;height:1.6rem;margin:0 -.175rem;padding:0;border:1px solid transparent;border-radius:var(--ui-radius, 5px);color:var(--muted);background:transparent}.team-icon:hover,.team-icon[aria-expanded=true]{color:var(--text);background:var(--surface-active)}.team-icon svg,.icon-choice-image svg{width:1.05rem;height:1.05rem}.team-avatar-frame{--team-avatar-bleed: .15rem;--team-avatar-radius: var(--ui-radius, 4px)}.icon-picker{padding:.6rem .85rem .2rem;border-bottom:1px solid var(--border)}.icon-choices{display:flex;flex-wrap:wrap;gap:.35rem}.icon-choice{display:inline-flex;align-items:center;gap:.45rem;padding:.3rem .55rem .3rem .35rem;border:1px solid var(--border);border-radius:var(--ui-radius, 5px);color:var(--text);background:transparent;font:inherit}.icon-choice:hover:not(:disabled){background:var(--surface-active)}.icon-choice[aria-pressed=true]{background:rgb(from var(--accent) r g b / .07);border-color:rgb(from var(--accent) r g b / .45)}.icon-choice-image{display:grid;place-items:center;width:1.25rem;height:1.25rem;color:var(--muted)}.team-name{margin:0;min-width:0;font-size:.875rem;font-weight:600;letter-spacing:-.015em;overflow-wrap:anywhere}.team-actions{display:flex;gap:.25rem;margin-left:auto}.rename-input{flex:1;max-width:22rem;width:0}.team-body{display:grid;grid-template-columns:minmax(0,.9fr) minmax(0,1.1fr)}.sub{min-width:0;padding:.75rem .85rem}.sub+.sub{border-left:1px solid var(--border)}.sub-title{display:flex;align-items:center;gap:.5rem;margin:0 0 .4rem;font-size:.75rem;font-weight:600}.sub-title .count{height:1.1rem;min-width:1.1rem;font-size:.75rem;padding:0 .3rem}.links{list-style:none;margin:0 0 .5rem;padding:0}.links li{display:flex;align-items:center;gap:.5rem;min-height:2.25rem;padding:.25rem 0;cursor:default}.links li+li{border-top:1px solid var(--border)}.repo-icon{flex:0 0 auto;color:var(--muted);width:.95rem;height:.95rem}.repo-copy{display:flex;min-width:0;flex-direction:column;gap:.1rem}.ln{min-width:0;font-size:.8rem;font-weight:500;overflow-wrap:anywhere}.path{color:var(--muted);font-family:var(--mono);font-size:.75rem;overflow-wrap:anywhere}.repo-row .icon-btn{margin-left:auto}.links .member-row{display:grid;grid-template-columns:minmax(0,1fr) auto 1.8rem;gap:.45rem}.member{display:flex;align-items:center;gap:.45rem;min-width:0}.member .avatar{width:1.6rem;height:1.6rem;font-size:.75rem}.perms{display:flex;flex-wrap:wrap;gap:.3rem}.perm{display:inline-flex;align-items:center;gap:.3rem;padding:.15rem .3rem;border:1px solid var(--border);border-radius:4px;font-size:.7rem;color:var(--muted);user-select:none}.perm:has(:checked){color:var(--text);background:rgb(from var(--accent) r g b / .07);border-color:rgb(from var(--accent) r g b / .2)}.perm:has(:disabled){opacity:.5}.sub.npm-scopes{grid-column:1 / -1;border-top:1px solid var(--border);border-left:0}.npm-scopes .sub-head{display:flex;flex-wrap:wrap;align-items:center;gap:.15rem .75rem;margin-bottom:.4rem}.npm-scopes .sub-head>.sub-title,.npm-scopes .sub-head>.ui-hint{margin:0}.npm-scopes .sub-head>.ui-hint{margin-left:auto;text-align:right}.npm-scope-row{flex-wrap:wrap;padding-top:0}.npm-scope-list{display:flex;flex:1 1 12rem;flex-wrap:wrap;align-items:center;gap:.35rem;min-width:0;margin:0;padding:0;list-style:none}.npm-scope{display:inline-flex;align-items:center;gap:.45rem;padding:.35rem .35rem .35rem .45rem;border:1px solid var(--border);border-radius:4px;font-family:var(--mono);font-size:.75rem}.npm-scope .icon-btn{width:1.3rem;height:1.3rem}.add-npm-scope{flex:1;width:0;max-width:18rem}.npm-scope-row>.add-npm-scope{min-width:8rem}.add-row{display:flex;align-items:center;gap:.5rem;padding-top:.45rem}.add-row select,.add-row repository-selector,.add-row user-selector{flex:1;width:0}.add-repo-path{flex:.75;width:0}.add-row .btn{flex:0 0 auto}.muted{color:var(--muted);font-size:.78rem;margin:.5rem 0}@container (max-width: 50rem){.access-note,.npm-scopes .sub-head>.ui-hint{flex-basis:100%;margin-left:0;text-align:left}.team-body{grid-template-columns:1fr}.sub+.sub{border-left:0;border-top:1px solid var(--border)}.add-row{max-width:36rem}}@container (max-width: 32rem){.create-team{flex-wrap:wrap}.new-name{flex:1;width:0}.team-head,.sub{padding-left:.75rem;padding-right:.75rem}.add-row:has(.add-repo-sel){display:grid;grid-template-columns:minmax(0,1fr) auto}.add-row .add-repo-sel{width:100%}.add-repo-path{grid-column:1 / -1;grid-row:2;width:100%}}@container (max-width: 26rem){.links .member-row{grid-template-columns:minmax(0,1fr) 1.8rem}.perms{grid-row:2;padding-left:2.05rem}.member-row>.icon-btn{grid-column:2;grid-row:1}}.npm-review-toggle{display:inline-flex;align-items:center;gap:.35rem;margin-left:.75rem;font-size:.85rem;font-weight:400}
12
12
  `,Vr=`:host{padding:0;margin:1.2rem 0}.conditions-head{display:flex;align-items:center;flex-wrap:wrap;gap:.65rem 1rem}.conditions-head[data-conditions-hidden]>:not(slot){visibility:hidden}slot[name=actions]::slotted(*){flex:none}h2{margin:0;font-size:.8rem;font-weight:500}.presets{display:flex;gap:2px;padding:3px;border:1px solid var(--border);border-radius:var(--ui-radius, 6px);background:var(--bg)}.presets button{display:inline-flex;align-items:center;gap:.35rem;padding:.3rem .65rem;border:0;border-radius:var(--ui-radius, 3px);background:transparent;color:var(--muted);font-size:.75rem}.presets button:hover{background:var(--surface-active);color:var(--text)}.presets button[aria-pressed=true]{background:color-mix(in srgb,var(--accent) 15%,var(--bg));color:var(--accent)}.presets button:focus-visible{outline-offset:-1px}svg{width:1rem;height:1rem;flex:none}.platforms{display:flex;align-items:center;flex-wrap:wrap;gap:.75rem;font-size:.75rem}.platforms>span{color:var(--muted)}.platforms label{display:inline-flex;align-items:center;gap:.35rem}.platforms input{margin:0;width:.85rem;height:.85rem}.manual-toggle{display:flex;align-items:center;gap:.25rem;margin-left:auto;padding:.25rem 0;border:0;border-radius:var(--ui-radius, 2px);background:transparent;color:var(--muted);font-size:.75rem;white-space:nowrap}.manual-toggle:hover{color:var(--text)}.manual-toggle[hidden]{visibility:hidden}.manual-toggle[aria-expanded=true] svg{transform:rotate(90deg)}#manual-conditions{margin-top:.75rem}.condition-editor{display:flex;align-items:center;flex-wrap:wrap;gap:.35rem;min-height:2.25rem;padding:.3rem;border:1px solid var(--border);border-radius:var(--ui-radius, 5px);background:var(--bg)}.condition-editor:focus-within{border-color:var(--accent)}ul{display:flex;flex-wrap:wrap;gap:.35rem;max-width:100%;margin:0;padding:0;list-style:none}li{display:inline-flex;align-items:center;gap:.35rem;min-width:0;max-width:100%;min-height:1.5rem;padding:0 .25rem 0 .5rem;border:1px solid var(--border);border-radius:var(--ui-radius, 4px);background:var(--surface);color:var(--text);font-size:.73rem}li.preset{padding-right:.5rem}li code{overflow-wrap:anywhere}li button{display:grid;place-items:center;flex:none;width:1.3rem;height:1.3rem;padding:0;border:0;border-radius:var(--ui-radius, 3px);background:transparent;color:var(--muted)}li button:hover{color:var(--critical);background:color-mix(in srgb,var(--critical) 12%,transparent)}.condition-input{display:flex;align-items:center;flex:1;min-width:9rem}.condition-editor input{flex:1;width:0;min-width:0;min-height:1.5rem;padding:.15rem .4rem;border:0;border-radius:0;background:transparent;font-size:.75rem}.condition-editor input:focus-visible{outline:none}p{margin:.5rem 0 0;color:var(--muted);font-size:.7rem}.error{color:var(--critical)}@container (width <= 30rem){.conditions-head{gap:.6rem}.presets{margin-left:auto}.presets button{padding-inline:.4rem}.platforms{flex-basis:100%}}
13
- `,Hr=[`import`,`require`,`default`],z=[{id:`node`,label:`Node.js`,conditions:[`node`],automatic:[...Hr,`node`,`node-addons`,`module-sync`],icon:ct`<path transform="scale(.6667)" fill="currentColor" stroke="none" d=${Xe}/>`},{id:`browser`,label:`Browser`,conditions:[`browser`,`module`],automatic:Hr,icon:ct`<rect x="1.5" y="2.5" width="13" height="11" rx="1.5"/><path d="M1.5 6h13M4 4.3h.1m2 0h.1"/>`},{id:`metro`,label:`Metro`,conditions:[`react-native`],automatic:Hr,icon:ct`<rect x="4" y="1.5" width="8" height="13" rx="2"/><path d="M6.5 3.5h3M7 12.5h2"/>`}],Ur=16-Math.max(...z.map(e=>e.conditions.length)),Wr=[{id:`ios`,label:`iOS`},{id:`android`,label:`Android`}],Gr=new Intl.ListFormat(`en`,{type:`conjunction`});function Kr(){return{preset:`node`,conditions:[`node`],platforms:[]}}var qr=class extends lt{static styles=[v(r),v(Vr)];static properties={showConditions:{attribute:!1},_preset:{state:!0},_manual:{state:!0},_platforms:{state:!0},_draft:{state:!0},_error:{state:!0},_manualOpen:{state:!0}};constructor(){super(),this.showConditions=!0,this._preset=`node`,this._manual=[],this._platforms=[`ios`,`android`],this._draft=``,this._error=``,this._manualOpen=!1}get value(){return{preset:this._preset,conditions:this.conditions,platforms:this._preset===`metro`?[...this._platforms]:[]}}get presetConditions(){return z.find(e=>e.id===this._preset).conditions}get automaticConditions(){return z.find(e=>e.id===this._preset).automatic}get conditions(){return[...new Set([...this.presetConditions,...this._preset===`metro`?[]:this._manual])]}notifyChange(){this.dispatchEvent(new CustomEvent(`conditions-change`,{detail:this.value,bubbles:!0,composed:!0}))}selectPreset(e){z.some(t=>t.id===e)&&(this._preset=e,this._draft=``,this._error=``,this.notifyChange())}togglePlatform(e){if(!Wr.some(t=>t.id===e))return;let t=this._platforms.includes(e);t&&this._platforms.length===1||(this._platforms=Wr.map(e=>e.id).filter(n=>n===e?!t:this._platforms.includes(n)),this.notifyChange())}addConditions(){if(this._preset===`metro`)return;let e=this._draft.trim().split(/[\s,]+/u).filter(Boolean);if(e.length===0)return;if(e.some(e=>this.automaticConditions.includes(e)&&!this.presetConditions.includes(e))){this._error=`${Gr.format(this.automaticConditions)} are handled automatically.`;return}if(e.some(e=>e.length>64||e.startsWith(`.`)||/^\d+$/u.test(e))){this._error=`Use condition names of up to 64 characters, without a leading dot or an all-numeric name.`;return}let t=[...new Set([...this._manual,...e.filter(e=>!this.presetConditions.includes(e))])];t.length>Ur?this._error=`Use up to ${Ur} manual conditions.`:(this._manual=t,this._draft=``,this._error=``,this.notifyChange())}removeCondition(e){this.presetConditions.includes(e)||(this._manual=this._manual.filter(t=>t!==e),this._error=``,this.notifyChange())}render(){let e=this._preset!==`metro`,t=this.automaticConditions.filter(e=>e!==`import`&&e!==`require`);return y`<section aria-label="${this.showConditions?`Conditions`:`Bundle actions`}"><div class="conditions-head" ?data-conditions-hidden="${!this.showConditions}"><h2 id="conditions-heading">Conditions</h2><div class="presets" role="group" aria-label="Condition preset">${z.map(e=>y`<button type="button" aria-pressed="${this._preset===e.id}" @click="${()=>this.selectPreset(e.id)}"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${e.icon}</svg>${e.label}</button>`)}</div>${this._preset===`metro`?y`<div class="platforms" role="group" aria-label="Metro platforms"><span>Platforms</span>${Wr.map(({id:e,label:t})=>y`<label><input type="checkbox" .checked="${this._platforms.includes(e)}" ?disabled="${this._platforms.includes(e)&&this._platforms.length===1}" @change="${()=>this.togglePlatform(e)}">${t}</label>`)}</div>`:b} <button type="button" class="manual-toggle" ?hidden="${!e}" aria-expanded="${this._manualOpen}" aria-controls="manual-conditions" @click="${()=>{this._manualOpen=!this._manualOpen}}"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m6 4 4 4-4 4"/></svg>Manual conditions</button><slot name="actions"></slot></div><div id="manual-conditions" ?hidden="${!this.showConditions||!e||!this._manualOpen}"><form class="condition-editor" @submit="${e=>{e.preventDefault(),this.addConditions()}}"><ul aria-label="Export conditions">${this.conditions.map(e=>this.presetConditions.includes(e)?y`<li class="preset"><code>${e}</code></li>`:y`<li><code>${e}</code><button type="button" aria-label="${`Remove condition ${e}`}" @click="${()=>this.removeCondition(e)}"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" aria-hidden="true"><path d="m4 4 8 8m0-8-8 8"/></svg></button></li>`)}</ul><div class="condition-input"><input type="text" aria-label="Add conditions" aria-describedby="conditions-help" aria-invalid="${!!this._error}" aria-errormessage="condition-error" placeholder="Add condition…" autocomplete="off" maxlength="1040" .value="${this._draft}" @input="${e=>{this._draft=e.target.value,this._error=``}}" @keydown="${e=>{e.key===` `&&!e.isComposing&&(e.preventDefault(),this.addConditions())}}" @blur="${()=>this.addConditions()}"></div></form><p id="conditions-help">Package export conditions. <code>import</code> / <code>require</code>${t.map((e,n)=>y`${n<t.length-1?`, `:t.length>1?`, and `:` and `}<code>${e}</code>`)} are automatic.</p>${this._error?y`<p id="condition-error" class="error" role="alert">${this._error}</p>`:b}</div></section>`}};customElements.define(`bundle-conditions`,qr);var Jr=`:host{padding:0}.field,.browser{line-height:1.5}.source-fields{display:grid;grid-template-columns:minmax(12rem,1fr) minmax(0,1.6fr);align-items:end;gap:1rem;margin:1rem 0}.field{display:flex;flex-direction:column;gap:.4rem;min-width:0;font-size:.75rem;color:var(--muted)}button:disabled,input:disabled{opacity:.5}.browser{border:1px solid var(--border);border-radius:var(--ui-radius, 7px);overflow:hidden}.browser-head{display:flex;align-items:center;gap:.75rem;padding:.65rem .8rem;border-bottom:1px solid var(--border);background:var(--bg);font-size:.75rem}.commit-link{display:inline-flex;align-items:center;flex:none;gap:.3rem;margin-left:auto;color:var(--muted);text-decoration:none}.commit-link svg{width:1rem;height:1rem}.commit-link code{cursor:inherit}.commit-link:hover{color:var(--accent)}.commit-link:focus-visible{outline:1px solid var(--accent);outline-offset:3px;border-radius:var(--ui-radius, 2px)}.breadcrumbs{display:flex;align-items:center;flex-wrap:wrap;gap:.35rem;min-width:0}.breadcrumbs button{border:0;padding:.1rem;background:transparent;color:var(--muted);overflow-wrap:anywhere}.breadcrumbs button[aria-current]{color:var(--text)}.breadcrumbs button:hover:not(:disabled){color:var(--accent)}.file-browser{min-height:18rem;max-height:50vh;overflow:auto;padding:.75rem}.file-browser:has(>.empty){display:grid;place-items:center}.file-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(min(100%,16rem),1fr));gap:.5rem}.file-tile{display:flex;align-items:center;gap:.5rem;min-width:0;height:2.05rem;padding:.4rem .6rem;border:1px solid var(--border);border-radius:var(--ui-radius, 5px);background:var(--bg);color:var(--text);font-size:.75rem}.file-tile>span:not(.arrow){overflow:hidden;text-overflow:ellipsis;white-space:nowrap;text-align:left}.file-tile input{width:.85rem;height:.85rem;margin:0;accent-color:var(--accent);flex:none}.file-tile:hover,.file-tile:focus-within{border-color:var(--accent)}.file-tile.selected{border-color:var(--accent);background:color-mix(in srgb,var(--accent) 10%,var(--bg))}.directory{color:var(--muted)}.directory .arrow{margin-left:auto}.unsupported{opacity:.55}.empty{margin:0;padding:1rem;border:0;border-radius:0;text-align:center;color:var(--muted);font-size:.8rem;line-height:1.5}.error{color:var(--critical)}.message{padding:.5rem .8rem;color:var(--muted);font-size:.75rem;line-height:1.5}.text-action{border:0;padding:.1rem .2rem;color:var(--accent);background:transparent;font-size:.75rem}@container (width <= 45rem){.source-fields{grid-template-columns:1fr}}
13
+ `,Hr=[`import`,`require`,`default`],z=[{id:`node`,label:`Node.js`,conditions:[`node`],automatic:[...Hr,`node`,`node-addons`,`module-sync`],icon:ct`<path transform="scale(.6667)" fill="currentColor" stroke="none" d=${Ze}/>`},{id:`browser`,label:`Browser`,conditions:[`browser`,`module`],automatic:Hr,icon:ct`<rect x="1.5" y="2.5" width="13" height="11" rx="1.5"/><path d="M1.5 6h13M4 4.3h.1m2 0h.1"/>`},{id:`metro`,label:`Metro`,conditions:[`react-native`],automatic:Hr,icon:ct`<rect x="4" y="1.5" width="8" height="13" rx="2"/><path d="M6.5 3.5h3M7 12.5h2"/>`}],Ur=16-Math.max(...z.map(e=>e.conditions.length)),Wr=[{id:`ios`,label:`iOS`},{id:`android`,label:`Android`}],Gr=new Intl.ListFormat(`en`,{type:`conjunction`});function Kr(){return{preset:`node`,conditions:[`node`],platforms:[]}}var qr=class extends lt{static styles=[v(r),v(Vr)];static properties={showConditions:{attribute:!1},_preset:{state:!0},_manual:{state:!0},_platforms:{state:!0},_draft:{state:!0},_error:{state:!0},_manualOpen:{state:!0}};constructor(){super(),this.showConditions=!0,this._preset=`node`,this._manual=[],this._platforms=[`ios`,`android`],this._draft=``,this._error=``,this._manualOpen=!1}get value(){return{preset:this._preset,conditions:this.conditions,platforms:this._preset===`metro`?[...this._platforms]:[]}}get presetConditions(){return z.find(e=>e.id===this._preset).conditions}get automaticConditions(){return z.find(e=>e.id===this._preset).automatic}get conditions(){return[...new Set([...this.presetConditions,...this._preset===`metro`?[]:this._manual])]}notifyChange(){this.dispatchEvent(new CustomEvent(`conditions-change`,{detail:this.value,bubbles:!0,composed:!0}))}selectPreset(e){z.some(t=>t.id===e)&&(this._preset=e,this._draft=``,this._error=``,this.notifyChange())}togglePlatform(e){if(!Wr.some(t=>t.id===e))return;let t=this._platforms.includes(e);t&&this._platforms.length===1||(this._platforms=Wr.map(e=>e.id).filter(n=>n===e?!t:this._platforms.includes(n)),this.notifyChange())}addConditions(){if(this._preset===`metro`)return;let e=this._draft.trim().split(/[\s,]+/u).filter(Boolean);if(e.length===0)return;if(e.some(e=>this.automaticConditions.includes(e)&&!this.presetConditions.includes(e))){this._error=`${Gr.format(this.automaticConditions)} are handled automatically.`;return}if(e.some(e=>e.length>64||e.startsWith(`.`)||/^\d+$/u.test(e))){this._error=`Use condition names of up to 64 characters, without a leading dot or an all-numeric name.`;return}let t=[...new Set([...this._manual,...e.filter(e=>!this.presetConditions.includes(e))])];t.length>Ur?this._error=`Use up to ${Ur} manual conditions.`:(this._manual=t,this._draft=``,this._error=``,this.notifyChange())}removeCondition(e){this.presetConditions.includes(e)||(this._manual=this._manual.filter(t=>t!==e),this._error=``,this.notifyChange())}render(){let e=this._preset!==`metro`,t=this.automaticConditions.filter(e=>e!==`import`&&e!==`require`);return y`<section aria-label="${this.showConditions?`Conditions`:`Bundle actions`}"><div class="conditions-head" ?data-conditions-hidden="${!this.showConditions}"><h2 id="conditions-heading">Conditions</h2><div class="presets" role="group" aria-label="Condition preset">${z.map(e=>y`<button type="button" aria-pressed="${this._preset===e.id}" @click="${()=>this.selectPreset(e.id)}"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.25" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${e.icon}</svg>${e.label}</button>`)}</div>${this._preset===`metro`?y`<div class="platforms" role="group" aria-label="Metro platforms"><span>Platforms</span>${Wr.map(({id:e,label:t})=>y`<label><input type="checkbox" .checked="${this._platforms.includes(e)}" ?disabled="${this._platforms.includes(e)&&this._platforms.length===1}" @change="${()=>this.togglePlatform(e)}">${t}</label>`)}</div>`:b} <button type="button" class="manual-toggle" ?hidden="${!e}" aria-expanded="${this._manualOpen}" aria-controls="manual-conditions" @click="${()=>{this._manualOpen=!this._manualOpen}}"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m6 4 4 4-4 4"/></svg>Manual conditions</button><slot name="actions"></slot></div><div id="manual-conditions" ?hidden="${!this.showConditions||!e||!this._manualOpen}"><form class="condition-editor" @submit="${e=>{e.preventDefault(),this.addConditions()}}"><ul aria-label="Export conditions">${this.conditions.map(e=>this.presetConditions.includes(e)?y`<li class="preset"><code>${e}</code></li>`:y`<li><code>${e}</code><button type="button" aria-label="${`Remove condition ${e}`}" @click="${()=>this.removeCondition(e)}"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" aria-hidden="true"><path d="m4 4 8 8m0-8-8 8"/></svg></button></li>`)}</ul><div class="condition-input"><input type="text" aria-label="Add conditions" aria-describedby="conditions-help" aria-invalid="${!!this._error}" aria-errormessage="condition-error" placeholder="Add condition…" autocomplete="off" maxlength="1040" .value="${this._draft}" @input="${e=>{this._draft=e.target.value,this._error=``}}" @keydown="${e=>{e.key===` `&&!e.isComposing&&(e.preventDefault(),this.addConditions())}}" @blur="${()=>this.addConditions()}"></div></form><p id="conditions-help">Package export conditions. <code>import</code> / <code>require</code>${t.map((e,n)=>y`${n<t.length-1?`, `:t.length>1?`, and `:` and `}<code>${e}</code>`)} are automatic.</p>${this._error?y`<p id="condition-error" class="error" role="alert">${this._error}</p>`:b}</div></section>`}};customElements.define(`bundle-conditions`,qr);var Jr=`:host{padding:0}.field,.browser{line-height:1.5}.source-fields{display:grid;grid-template-columns:minmax(12rem,1fr) minmax(0,1.6fr);align-items:end;gap:1rem;margin:1rem 0}.field{display:flex;flex-direction:column;gap:.4rem;min-width:0;font-size:.75rem;color:var(--muted)}button:disabled,input:disabled{opacity:.5}.browser{border:1px solid var(--border);border-radius:var(--ui-radius, 7px);overflow:hidden}.browser-head{display:flex;align-items:center;gap:.75rem;padding:.65rem .8rem;border-bottom:1px solid var(--border);background:var(--bg);font-size:.75rem}.commit-link{display:inline-flex;align-items:center;flex:none;gap:.3rem;margin-left:auto;color:var(--muted);text-decoration:none}.commit-link svg{width:1rem;height:1rem}.commit-link code{cursor:inherit}.commit-link:hover{color:var(--accent)}.commit-link:focus-visible{outline:1px solid var(--accent);outline-offset:3px;border-radius:var(--ui-radius, 2px)}.breadcrumbs{display:flex;align-items:center;flex-wrap:wrap;gap:.35rem;min-width:0}.breadcrumbs button{border:0;padding:.1rem;background:transparent;color:var(--muted);overflow-wrap:anywhere}.breadcrumbs button[aria-current]{color:var(--text)}.breadcrumbs button:hover:not(:disabled){color:var(--accent)}.file-browser{min-height:18rem;max-height:50vh;overflow:auto;padding:.75rem}.file-browser:has(>.empty){display:grid;place-items:center}.file-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(min(100%,16rem),1fr));gap:.5rem}.file-tile{display:flex;align-items:center;gap:.5rem;min-width:0;height:2.05rem;padding:.4rem .6rem;border:1px solid var(--border);border-radius:var(--ui-radius, 5px);background:var(--bg);color:var(--text);font-size:.75rem}.file-tile>span:not(.arrow){overflow:hidden;text-overflow:ellipsis;white-space:nowrap;text-align:left}.file-tile input{width:.85rem;height:.85rem;margin:0;accent-color:var(--accent);flex:none}.file-tile:hover,.file-tile:focus-within{border-color:var(--accent)}.file-tile.selected{border-color:var(--accent);background:color-mix(in srgb,var(--accent) 10%,var(--bg))}.directory{color:var(--muted)}.directory .arrow{margin-left:auto}.unsupported{opacity:.55}.empty{margin:0;padding:1rem;border:0;border-radius:0;text-align:center;color:var(--muted);font-size:.8rem;line-height:1.5}.error{color:var(--critical)}.message{padding:.5rem .8rem;color:var(--muted);font-size:.75rem;line-height:1.5}.text-action{border:0;padding:.1rem .2rem;color:var(--accent);background:transparent;font-size:.75rem}@container (width <= 45rem){.source-fields{grid-template-columns:1fr}}
14
14
  `,Yr=`.note{color:var(--muted);font-size:.75rem}.entry-points{display:flex;align-items:center;gap:1rem;margin-top:1rem;line-height:1.5}.package-suggestions{display:flex;align-items:center;gap:1rem;margin-top:1rem;color:var(--muted);font-size:.75rem}.package-suggestions>div{flex:1;min-width:0}.package-suggestions p{margin:0 0 .4rem}.package-suggestions .suggestions-note{margin:.4rem 0 0}.package-suggestions ul{display:flex;flex-wrap:wrap;gap:.4rem .8rem;padding:0;margin:0;list-style:none;max-height:6rem;overflow:auto}.package-suggestions li{min-width:0;max-width:100%}.package-suggestions li code{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--text)}.package-suggestions .btn{flex:none;font-size:.72rem}.selection{flex:1;min-width:0}.selection .note{margin:.5rem 0 0}.selection .note.error{color:var(--critical)}.selection-head{display:flex;align-items:center;gap:.75rem}.btn.clear-selection{min-height:1.65rem;padding:.2rem .5rem;font-size:.72rem}h2{margin:0;font-size:.8rem;font-weight:500}h2 span{color:var(--muted);margin-left:.4rem}.entry-points ul{padding:0;display:flex;flex-wrap:wrap;gap:.4rem;list-style:none;max-height:7rem;overflow:auto;margin:.6rem 0 0}.entry-points li{display:flex;align-items:center;gap:.4rem;min-width:0;max-width:100%;padding:.2rem .4rem;border:1px solid var(--border);border-radius:var(--ui-radius, 4px);background:var(--bg);font-size:.72rem}.entry-points li span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.entry-points li button{display:grid;place-items:center;flex:none;width:1.3rem;height:1.3rem;padding:0;border:0;border-radius:var(--ui-radius, 3px);background:transparent;color:var(--muted);cursor:default}.entry-points li button svg{width:1rem;height:1rem}.entry-points li button:hover{color:var(--critical);background:color-mix(in srgb,var(--critical) 12%,transparent)}.entry-points li button:focus-visible{outline:1px solid var(--accent);outline-offset:1px}
15
15
  `,Xr=100,Zr={"github-status-403":`GitHub denied this request. Check repository access and the GitHub App’s read permissions.`,"github-unauthorized":`GitHub authentication has expired or was revoked. Sign in again and check the repository App installation.`,"github-unreachable":`Could not connect to GitHub. Try again shortly.`,"github-moved":`GitHub moved this repository, as when it is renamed. Try again shortly.`};async function Qr(e,t,n){let r=await l(`/api/admin/repositories/${e}?${new URLSearchParams(t)}`,{credentials:`same-origin`,headers:{accept:`application/json`},signal:n});if(r.ok)return r.json();let i=await r.json().catch(()=>null);if(i?.error===`github-rate-limited`){let e=Number(r.headers.get(`retry-after`)),t=Math.ceil(e/60),n=Number.isFinite(e)&&e>0?` Try again in about ${t} ${t===1?`minute`:`minutes`}.`:` Try again after the limit resets.`;throw Error(`GitHub\u2019s API rate limit has been reached.${n}`)}throw Error(Zr[i?.error]??(r.status===404?`This repository, revision, or directory is unavailable.`:r.status===403?`Repository access is required to browse files.`:`Could not load repository files from GitHub. Try again.`))}function $r(e,t,n,r,i,a=!1){let o=e.filter(e=>!t.has(e));return o.length===0&&!a?b:y`<aside class="package-suggestions" aria-label="${i}"><div><p>${r}</p>${o.length>0?y`<ul>${o.map(e=>y`<li><code data-tooltip-truncated data-tooltip="${e}">${e}</code></li>`)}</ul>`:b} ${a?y`<p class="suggestions-note ui-hint">Suggestions are limited. Browse the source directories to select more files.</p>`:b}</div>${o.length>0?y`<button type="button" class="btn" @click="${()=>n(o)}">Use suggestions</button>`:b}</aside>`}var ei=class extends lt{static styles=[v(r),v(Jr),v(Yr)];static properties={installTooltips:{attribute:!1},initialRepoId:{attribute:!1},createBundle:{attribute:!1},_repos:{state:!0},_loadingRepos:{state:!0},_reposError:{state:!0},_repoId:{state:!0},_refs:{state:!0},_refKind:{state:!0},_refName:{state:!0},_path:{state:!0},_entries:{state:!0},_commit:{state:!0},_loadingRefs:{state:!0},_loading:{state:!0},_error:{state:!0},_refsError:{state:!0},_limited:{state:!0},_building:{state:!0},_opening:{state:!0},_buildError:{state:!0},_selected:{state:!0},_configEntryPoints:{state:!0},_packageEntryPoints:{state:!0},_solidityEntryPoints:{state:!0},_soliditySuggestionsLimited:{state:!0}};constructor(){super(),Object.assign(this,{_repos:[],_loadingRepos:!0,_reposError:``,initialRepoId:null,_repoId:null,_refs:{branches:[],tags:[]},_refKind:`branch`,_refName:``,_path:``,_entries:null,_commit:``,_loadingRefs:!1,_loading:!1,_error:``,_refsError:``,_limited:!1,_building:!1,_opening:!1,_buildError:``,_selected:new Set}),this._directories=new Map,this._dismissedSuggestions=new Set,this._suggested=new Set,this._bundleConditions=Kr(),this._configs=new Map,this.showDirectory(null)}updated(e){e.has(`installTooltips`)&&this.installTooltips?.(this.renderRoot)}firstUpdated(){this.loadRepositories()}disconnectedCallback(){this._buildRequest?.abort(),this._opening=!1,this._dismissedSuggestions.clear(),this._suggested.clear(),this.showDirectory(null),clearTimeout(this._browseTimer),this._reposRequest?.abort(),this._refsRequest?.abort(),this._request?.abort(),this._directories.clear(),super.disconnectedCallback()}async loadRepositories(){this._reposRequest?.abort(),this.selectRepository(null),this._repos=[],this._reposError=``,this._loadingRepos=!0;let e=new AbortController;this._reposRequest=e;try{let t=await Qr(`browsable`,{},e.signal);if(e.signal.aborted)return;this._repos=t.repos,this._repos.some(e=>e.repoId===this.initialRepoId)&&this.selectRepository(this.initialRepoId)}catch{e.signal.aborted||(this._reposError=`Could not load repositories. Try again.`)}finally{e.signal.aborted||(this._loadingRepos=!1)}}showDirectory(e){this._configEntryPoints=e?.configEntryPoints??[],this._packageEntryPoints=e?.packageEntryPoints??[],this._solidityEntryPoints=e?.solidityEntryPoints??[],this._soliditySuggestionsLimited=e?.soliditySuggestionsLimited??!1}resetFiles(){this._buildError=``,clearTimeout(this._browseTimer),this._request?.abort(),this._directories.clear(),Object.assign(this,{_loading:!1,_entries:null,_path:``,_commit:``,_error:``,_limited:!1}),this.showDirectory(null),this._selected=new Set,this._dismissedSuggestions.clear(),this._suggested.clear(),this._configs.clear()}async selectRepository(e){if(this._refsRequest?.abort(),this.resetFiles(),Object.assign(this,{_repoId:e,_refs:{branches:[],tags:[]},_refsError:``,_refKind:`branch`,_refName:``}),e==null){this._loadingRefs=!1;return}let t=new AbortController;this._refsRequest=t,this._loadingRefs=!0;try{let{defaultContents:n,configContents:r,...i}=await Qr(`refs`,{repoId:e,withDefault:`true`},t.signal);if(t.signal.aborted)return;this._refs=i,this._refName=i.defaultBranch||i.branches[0]||``,n?(this.useDirectory(n,``),r?.commit===n.commit&&r.path&&this.useDirectory(r,r.path)):this._refName&&this.loadDirectory(``)}catch(e){t.signal.aborted||(this._refsError=e.message)}finally{t.signal.aborted||(this._loadingRefs=!1)}}changeRevision(e,t){this._refsRequest?.abort(),this._loadingRefs=!1,this.resetFiles(),this._refKind=e,this._refName=t}selectRevisionType(e){this._refKind!==e&&(this.changeRevision(e,e===`branch`&&this._refs.defaultBranch||``),this._refName&&this.loadDirectory(``))}editRevision(e){this.changeRevision(this._refKind,e);let t=e.trim();if(!t)return;let n=this._refKind===`branch`?this._refs.branches:this._refs.tags;this._refKind!==`commit`&&(n.includes(t)||this._refKind===`branch`&&t===this._refs.defaultBranch)?this.loadDirectory(``):this._browseTimer=setTimeout(()=>{this.loadDirectory(``)},350)}revisionChanged({detail:{how:e,kind:t,name:n}}){e===`kind`?this.selectRevisionType(t):e===`submit`?this.loadDirectory(``,!0):this.editRevision(n)}async loadDirectory(e,t=!1){if(clearTimeout(this._browseTimer),this._repoId==null||!this._refName.trim())return;t&&this.resetFiles(),this._request?.abort();let n=new AbortController;this._request=n,Object.assign(this,{_path:e,_entries:null,_error:``,_limited:!1}),this.showDirectory(null),this._loading=!1;let r=this._refName.trim();if(this._refKind===`commit`&&!/^[a-f\d]{7,40}$/iu.test(r)){this._error=`Enter a commit SHA with 7 to 40 hexadecimal characters.`;return}let i=this._commit||(this._refKind===`commit`?r:`${this._refKind===`branch`?`heads`:`tags`}/${r}`),a=JSON.stringify([this._repoId,this._commit,e]),o=this._commit&&this._directories.get(a);if(o)this._directories.delete(a),this._directories.set(a,o),this._entries=o.entries,this._limited=o.limited,this.showDirectory(o);else{this._loading=!0;try{let t=await Qr(`contents`,{repoId:this._repoId,ref:i,path:e},n.signal);if(n.signal.aborted)return;this.useDirectory(t,e)}catch(e){n.signal.aborted||(this._directories.clear(),this._error=e.message)}finally{n.signal.aborted||(this._loading=!1)}}}useDirectory(e,t){this._path=t,this._commit=e.commit,this._entries=e.entries.toSorted((e,t)=>+(t.type===`dir`)-(e.type===`dir`)||e.name.localeCompare(t.name)),this._limited=e.limited,this.showDirectory(e),/^[a-f\d]{40}$/iu.test(e.commit)&&(this._directories.set(JSON.stringify([this._repoId,e.commit,t]),{...e,entries:this._entries}),this._directories.size>Xr&&this._directories.delete(this._directories.keys().next().value));for(let e of this._configEntryPoints){let n=this._configs.get(e);(n===void 0||n.length<t.length)&&this._configs.set(e,t)}let n=[...this._configEntryPoints,...this._packageEntryPoints,...this._solidityEntryPoints].filter(e=>!this._dismissedSuggestions.has(e)),r=this._configEntryPoints.length>0&&this.configOf([...this._selected,...n])===void 0,i=new Set([...[...this._selected].filter(e=>!r||!this._suggested.has(e)),...n]);if(this.configOf(i)!==void 0){for(let e of this._suggested)i.has(e)||this._suggested.delete(e);for(let e of n)this._selected.has(e)||this._suggested.add(e);this._selected=i}}repository(){return this._repos.find(e=>e.repoId===this._repoId)}configOf(e=this._selected){let t=new Set([...e].map(e=>this._configs.get(e)??null));return t.size>1?void 0:t.size===0?null:[...t][0]}toggleFile(e){this._suggested.delete(e);let t=new Set(this._selected);t.has(e)?(t.delete(e),this._dismissedSuggestions.add(e)):(t.add(e),this._dismissedSuggestions.delete(e)),this._selected=t}clearFiles(){for(let e of this._selected)this._dismissedSuggestions.add(e);this._selected=new Set,this._suggested.clear()}hasScriptEntryPoints(){return[...this._selected].some(e=>/\.[cm]?[tj]sx?$/iu.test(e))}async buildBundle(){let e=this.configOf();if(this._building||this._opening||!this.createBundle||!this._commit||this._selected.size===0||e===void 0)return;let t=new AbortController;this._buildRequest=t,this._building=!0,this._buildError=``;try{let n=this._refKind===`branch`?this._refName.trim():``,r=await this.createBundle({repoId:this._repoId,commit:this._commit,...n&&{branch:n},entries:[...this._selected],...e===null&&{conditions:this._bundleConditions}},t.signal);t.signal.aborted||(this._opening=!0,this.dispatchEvent(new CustomEvent(`bundle-created`,{detail:r,bubbles:!0,composed:!0})))}catch(e){t.signal.aborted||(this._buildError=e.message)}finally{this._building=!1}}renderSource(){let e=this.repository();return y`<div class="source-fields"><div class="field"><span>Repository</span><repository-selector label="Repository" ?disabled="${this._loadingRepos}" .options="${this._repos.map(e=>({value:e.repoId,label:e.fullName}))}" .value="${this._repoId}" @repository-change="${e=>this.selectRepository(e.detail.value)}"></repository-selector></div><revision-select .refs="${this._refs}" .kind="${this._refKind}" .name="${this._refName}" ?disabled="${!e||this._loadingRefs}" .installTooltips="${this.installTooltips}" @revision-change="${this.revisionChanged}"></revision-select></div>${this._reposError?y`<p class="message" role="alert">${this._reposError} <button type="button" class="text-action" @click="${()=>this.loadRepositories()}">Retry</button></p>`:b} ${this._refsError?y`<p class="message" role="status">${this._refsError} <button type="button" class="text-action" @click="${()=>this.selectRepository(this._repoId)}">Retry</button></p>`:b}`}renderBrowser(){let e=this.repository(),t=this._path.split(`/`).filter(Boolean),n=e&&this._commit?`https://github.com/${[...e.fullName.split(`/`),`tree`,this._commit,...t].map(encodeURIComponent).join(`/`)}`:null;return y`<section class="browser" aria-label="Repository files" aria-busy="${this._loadingRepos||this._loading||this._loadingRefs}"><div class="browser-head"><nav class="breadcrumbs" aria-label="Repository directory"><button type="button" ?disabled="${!this._commit}" aria-current="${be(this._path?void 0:`location`)}" @click="${()=>this.loadDirectory(``)}">${e?.fullName??`Repository`}</button>${t.map((e,n)=>y`<span aria-hidden="true">/</span><button type="button" aria-current="${be(n===t.length-1?`location`:void 0)}" @click="${()=>this.loadDirectory(t.slice(0,n+1).join(`/`))}">${e}</button>`)}</nav>${n?y`<a class="commit-link" href="${n}" target="_blank" rel="noopener noreferrer" data-tooltip="${this._commit}" data-tooltip-icon="commit" aria-label="${`View directory at commit ${this._commit.slice(0,7)} on GitHub`}">${ke}<code>${this._commit.slice(0,7)}</code></a>`:b}</div><div class="file-browser">${this._loadingRepos||this._loading||this._loadingRefs?y`<p class="empty" role="status">${this._loadingRepos?`Loading repositories…`:this._loadingRefs?`Loading revisions…`:`Loading files…`}</p>`:this._error?y`<p class="empty error" role="alert">${this._error} <button type="button" class="text-action" @click="${()=>this.loadDirectory(this._path)}">Retry</button></p>`:this._entries==null?y`<p class="empty">${e?`Choose a revision to browse its files.`:this._repos.length>0?`Select a repository to browse its files.`:`No accessible repositories available.`}</p>`:this._entries.length===0?y`<p class="empty">This directory is empty.</p>`:y`<div class="file-grid">${this._entries.map(e=>e.type===`dir`?y`<button type="button" class="file-tile directory" @click="${()=>this.loadDirectory(e.path)}">${Be}<span data-tooltip-truncated data-tooltip="${e.path}">${e.name}</span><span class="arrow" aria-hidden="true">›</span></button>`:this._fileTile(e))}</div>`}</div>${this._limited?y`<p class="message ui-hint">Showing GitHub’s first 1,000 entries in this directory.</p>`:b}</section>`}_fileTile(e){return y`<label class="${`file-tile ${this._selected.has(e.path)?`selected`:``} ${e.type===`file`?``:`unsupported`}`}" data-tooltip="${e.type===`file`?b:`${e.path} (${e.type})`}"><input type="checkbox" aria-label="${`Select ${e.path} as an entry point`}" .checked="${this._selected.has(e.path)}" ?disabled="${e.type!==`file`}" @change="${()=>this.toggleFile(e.path)}">${Re(e.name)}<span data-tooltip-truncated data-tooltip="${e.type===`file`?e.path:b}">${e.name}</span></label>`}render(){let e=this._building||this._opening,t=this.configOf(),n=e=>{this._selected=new Set([...this._selected,...e])};return y`<p class="intro ui-hint">Choose a repository and revision, then select files to use as entry points.</p><div ?inert="${e}">${this.renderSource()} ${this.renderBrowser()} ${$r(this._configEntryPoints,this._selected,n,y`Entry points listed in <code>stasis.config.json</code>`,`Configured entry points`)} ${$r(this._packageEntryPoints,this._selected,n,y`Entry points declared in <code>package.json</code>`,`Suggested entry points`)} ${$r(this._solidityEntryPoints,this._selected,n,`Suggested Solidity sources`,`Suggested Solidity sources`,this._soliditySuggestionsLimited)}<section class="entry-points" aria-label="Selected entry points"><div class="selection"><div class="selection-head"><h2>Entry points <span aria-live="polite">${this._selected.size}</span></h2>${this._selected.size>0?y`<button type="button" class="btn clear-selection" @click="${this.clearFiles}">Clear all</button>`:b}</div>${this._selected.size>0?y`<ul>${[...this._selected].map(e=>y`<li>${Re(e)}<span data-tooltip-truncated data-tooltip="${e}">${e}</span><button type="button" aria-label="${`Remove ${e}`}" @click="${()=>this.toggleFile(e)}"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" aria-hidden="true"><path d="m4 4 8 8m0-8-8 8"/></svg></button></li>`)}</ul>`:y`<p class="note ui-hint">Select files above. You can choose entry points from multiple directories.</p>`} ${t===void 0?y`<p class="note error" role="alert">Entry points listed in a <code>stasis.config.json</code> are built with its options, alone. Select only those it lists, or only other files.</p>`:b}</div></section><bundle-conditions .showConditions="${this.hasScriptEntryPoints()&&typeof t!=`string`}" @conditions-change="${e=>{this._bundleConditions=e.detail}}"><button type="button" slot="actions" class="btn primary" ?disabled="${e||!this.createBundle||!this._commit||this._selected.size===0||t===void 0||this._loading||this._loadingRefs}" @click="${this.buildBundle}">${this._opening?`Opening…`:this._building?`Creating…`:`Create a bundle`}</button></bundle-conditions></div>${e?y`<p class="message" role="status">${this._opening?`Opening bundle…`:`Building the selected entry points with Stasis…`}</p>`:b} ${this._buildError?y`<p class="message error" role="alert">${this._buildError}</p>`:b}`}};customElements.define(`managed-create-bundle`,ei);function ti(e){let t=new Map((e.repos??[]).map(e=>[e.repoId,{id:e.repoId,label:e.fullName}])),n=(e.bundles??[]).map(e=>{let n=e.repoId??`unattached`;return t.has(n)||t.set(n,{id:n,label:n===`unattached`?`Unattached`:e.repoFullName??String(n)}),{...e,repoId:n,repo:t.get(n).label,size:Ke(e.byteSize),files:null,reasons:[]}});return{repositories:[...t.values()],bundles:n,scans:[]}}async function ni(t,n){let r=await St(t.id,{signal:n});n?.throwIfAborted();let i=We(r,t.integrity);return e(t,i)}function ri(e){return e.map(e=>{let t=e.login||String(e.id),n=e.name?.trim()||`@${t}`,r=n===`@${t}`?``:`@${t}`,i=n.replace(/^@/u,``).split(/\s+/u).filter(Boolean).slice(0,2).map(e=>e[0]).join(``).toUpperCase(),a=e.userId===void 0?e.id:e.userId;return{value:e.id,avatar:a,label:r?`${n} ${r}`:n,displayLabel:n,secondary:r,initials:i,disabled:e.disabled,detail:e.detail}})}function ii(e,t){return we(e.filter(e=>!e.reset),t,{pinned:e.filter(e=>e.reset)})}var ai=class extends Te{static properties={users:{attribute:!1},resetLabel:{type:String,attribute:`reset-label`}};static styles=[Te.styles,st`.avatar{position:relative;overflow:hidden}.avatar img{position:absolute;inset:0;width:100%;height:100%;object-fit:cover}`];constructor(){super(),this.users=[],this.resetLabel=``,this.label=`Choose user`,this.placeholder=`Choose user`}get searchLabel(){return`Search users`}get optionsLabel(){return`Users`}get noMatchesLabel(){return`No matching users`}get emptyLabel(){return`No users available`}get changeEvent(){return`user-change`}willUpdate(e){(e.has(`users`)||e.has(`resetLabel`))&&(this.options=[...this.resetLabel?[{value:``,label:this.resetLabel,reset:!0}]:[],...ri(this.users)])}choices(){return ii(this.options,this._query)}optionIcon(e){return e.initials?y`<span class="avatar" aria-hidden="true">${e.initials}${s()||!e.avatar?b:qe(e.avatar,y`<img alt="" loading="lazy" decoding="async" src="${`/api/avatar/${encodeURIComponent(e.avatar)}`}" @error="${e=>{e.currentTarget.hidden=!0}}">`)}</span>`:b}};customElements.get(`user-selector`)||customElements.define(`user-selector`,ai);var oi=`:host{padding:0;container-type:normal}.alias-table{overflow-x:auto;padding-bottom:.5rem}table{width:100%;border-collapse:collapse;text-align:left}th,td{padding:.35rem .5rem;border-bottom:1px solid var(--border)}th{color:var(--muted);font-weight:500}td:not(.actions,.empty){overflow-wrap:anywhere}input{width:100%;min-width:7rem;padding:.3rem .45rem;border:1px solid var(--border);border-radius:.375rem;background:var(--bg);color:var(--text);font:inherit}.actions{white-space:nowrap;text-align:right}.actions .btn{min-height:1.75rem;padding:.2rem .55rem}.actions .btn+.btn{margin-left:.25rem}
16
- `,si=Xn(`/api/admin/repositories/aliases`,{"alias-exists":`An alias already exists for this old repository and path. Edit that row instead.`,"bad-old-repo":`Enter the old repository as owner/name or a GitHub URL.`,"bad-directory":`Enter repository directories without parent segments, backslashes, or surrounding whitespace.`,"bad-repo":`Choose a connected repository.`,"no-alias":`This alias was removed. Refresh the list and try again.`}),ci=class extends x{static properties={repositories:{attribute:!1},_edit:{state:!0},_busy:{state:!0}};static styles=[v(r),v(oi)];static collection=[`repository-aliases`,`repository aliases`,e=>si(``,{signal:e})];constructor(){super(),this._edit=null,this._busy=!1}updated(e){e.has(`repositories`)&&e.get(`repositories`)!==void 0&&(this.appState.invalidate([`repository-aliases`]),this._load())}_start(e=null){this._error=null,this._edit=e?{...e}:{id:null,oldRepo:``,oldPath:``,repoId:null,newPath:``}}async _mutate(e,t,n){if(!this._busy&&this._csrf&&this._role===`admin`){this._busy=!0,this._error=null;try{await this.appState.mutate(()=>si(t?`/${encodeURIComponent(t)}`:``,{method:e,headers:{"content-type":`application/json`,"x-csrf-token":this._csrf},...n?{body:JSON.stringify(n)}:{}}),[`repository-aliases`,`workspace-import`]),this._edit=null,await this._load()}catch(e){this._error=String(e?.message??e)}finally{this._busy=!1}}}_save(){let{id:e,...t}=this._edit;return this._mutate(e?`PATCH`:`POST`,e,t)}_field(e,t,n){return y`<td><input type="text" aria-label="${t}" placeholder="${n}" .value="${this._edit[e]}" ?disabled="${this._busy}" @input="${t=>{this._edit={...this._edit,[e]:t.target.value}}}"></td>`}_editor(){let e=(this._data?.repos??[]).filter(e=>e.active!==!1).map(e=>({value:e.repoId,label:e.fullName}));return y`<tr>${this._field(`oldRepo`,`Old repository`,`owner/repository`)}${this._field(`oldPath`,`Old path`,`Repository root`)}<td><repository-selector label="New repository" placeholder="Choose repository…" .options="${e}" .value="${this._edit.repoId}" ?disabled="${this._busy}" @repository-change="${e=>{this._edit={...this._edit,repoId:e.detail.value}}}"></repository-selector></td>${this._field(`newPath`,`New path`,`Repository root`)}<td class="actions"><button type="button" class="btn" ?disabled="${this._busy||!this._edit.oldRepo.trim()||this._edit.repoId==null}" @click="${()=>{this._save()}}">${this._busy?`Saving…`:`Save`}</button> <button type="button" class="btn" ?disabled="${this._busy}" @click="${()=>{this._edit=null,this._error=null}}">Cancel</button></td></tr>`}render(){let e=this._data?.aliases??[],t=this._data?.repos??[],n=e=>{let n=t.find(t=>t.repoId===e);return`${n?.fullName??`Removed repository`}${n?.active===!1?` (inactive)`:``}`};return y`<section aria-label="Repository aliases"><div class="page-intro"><p class="intro">Map repository locations when importing new reports and bundles.</p><button type="button" class="btn" ?disabled="${this._busy||this._edit!=null||!this._data}" @click="${()=>this._start()}">Add alias</button></div>${C(this._error)}<div aria-busy="${this._loading}">${this._data===null?this._error?y`<button type="button" class="btn" @click="${()=>{this._load()}}">Try again</button>`:S(`Loading repository aliases…`):y`<div class="alias-table"><table><thead><tr><th>Old repository</th><th>Old path</th><th>New repository</th><th>New path</th><th><span class="sr-only">Actions</span></th></tr></thead><tbody>${e.map(e=>this._edit?.id===e.id?this._editor():y`<tr><td>${e.oldRepo}</td><td class="mono">${e.oldPath||`/`}</td><td>${n(e.repoId)}</td><td class="mono">${e.newPath||`/`}</td><td class="actions"><button type="button" class="btn" ?disabled="${this._busy||this._edit!=null}" @click="${()=>this._start(e)}">Edit</button> <button type="button" class="btn" ?disabled="${this._busy||this._edit!=null}" @click="${()=>{this._mutate(`DELETE`,e.id)}}">Delete</button></td></tr>`)} ${this._edit?.id===null?this._editor():b} ${e.length===0&&!this._edit?y`<tr><td colspan="5" class="empty">No repository aliases yet.</td></tr>`:b}</tbody></table></div>`}</div></section>`}};customElements.define(`managed-repository-aliases`,ci);function li(e,t){return y`<span class="avatar" aria-hidden="true"><span>${(t?.[0]??`?`).toUpperCase()}</span> ${s()?b:y`<img alt="" src="${`/api/avatar/${encodeURIComponent(e)}`}" @error="${e=>e.currentTarget.classList.add(`broken`)}">`}</span>`}function ui(e,t){return y`<span class="avatar" aria-hidden="true"><span>${(t?.[0]??`?`).toUpperCase()}</span>${!e||s()?b:qe(e,y`<img alt="" loading="lazy" decoding="async" src="${`/api/avatar/${encodeURIComponent(e)}`}" @error="${e=>{e.currentTarget.hidden=!0}}">`)}</span>`}var di=[`triage`,`review`,`visibility`,`upload`,`repository`,`access`,`delete`],fi=e=>{let t=e??`activity`;return y`<span class="${`kind ${e??``}`}">${t[0].toUpperCase()}${t.slice(1)}</span>`},pi=g(Je),mi=g(Ye),hi=y`<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" aria-hidden="true"><path d="m4 4 8 8m0-8-8 8"/></svg>`,B=y`<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" aria-hidden="true"><path d="M8 3v10M3 8h10"/></svg>`,gi=m(`repo`),_i={admin:[`Admin`,`Manage workspace access and teams`],manage:[`Manager`,`Manage content and triage within team access`],triage:[`Triage`,`Review and triage findings`],view:[`Viewer`,`Read-only access`],none:[`No access`,`No workspace access`]};function vi(e,t,n,r){return y`<div class="breadcrumb"><button type="button" class="breadcrumb-manage" @click="${()=>p(`manage`)}">Manage</button> <span class="breadcrumb-separator" aria-hidden="true">›</span> <button type="button" class="breadcrumb-manage" aria-label="${t}" @click="${n}">${e}</button> <span class="breadcrumb-separator" aria-hidden="true">›</span> ${r?y`<h1 class="breadcrumb-current">${r}</h1>`:b}</div>`}var yi=[[`manage-bundles`,`Bundles`,`Keep source archives ready for review.`,`bundle`],[`manage-scans`,`Scans`,`Run and monitor scans from stored bundles.`,`scan`],[`manage-reports`,`Reports`,`Review, publish, and organize findings.`,`report`]],bi=[[`manage-repos`,`Repositories`,`Connect sources and manage repository settings.`,`repo`],[`admin-users`,`Users`,`Manage accounts, roles, and workspace access.`,`users`],[`manage-teams`,`Teams`,`Bring people and repositories together.`,`team`]];function xi([e,t,n,r]){return y`<button type="button" class="${`page page-${r}`}" @click="${()=>p(e)}"><span class="page-top"><span class="page-icon" aria-hidden="true">${m(r)}</span><strong class="page-title">${t}</strong><span class="arrow" aria-hidden="true">${m(`arrow`)}</span></span> <span class="page-copy"><span>${n}</span></span></button>`}var Si=class extends x{static view=`manage`;static styles=[v(Nr),v(r)];render(){return y`<div class="wrap">${this._nav()}<h1 class="sr-only">Manage</h1>${this._role==null?y`<p class="msg" role="status">Loading management pages…</p>`:y`<section class="home-section" aria-labelledby="content-heading"><div class="section-heading"><h2 id="content-heading">Content & activity</h2><span>From source to findings</span></div><div class="pages">${yi.filter(([e])=>e!==`manage-scans`||[`admin`,`manage`].includes(this._role)).map(xi)}</div></section>${this._role===`admin`?y`<section class="home-section" aria-labelledby="workspace-heading"><div class="section-heading"><h2 id="workspace-heading">Workspace & access</h2><span>Sources, people, and permissions</span></div><div class="pages workspace-pages">${bi.map(xi)}</div></section>`:b} <button type="button" class="history-link" @click="${()=>p(`manage-history`)}"><span class="page-icon" aria-hidden="true">${m(`history`)}</span> <span class="page-copy"><strong>Workspace history</strong><span>Follow activity and triage changes across your workspace.</span></span> <span class="history-cta">View history ${m(`arrow`)}</span></button>`}</div>`}};customElements.define(`managed-admin-home`,Si);var Ci=class extends x{static view=`manage-history`;static properties={_page:{state:!0},_history:{state:!0},_total:{state:!0},_filter:{state:!0},_query:{state:!0},_repo:{state:!0},_actor:{state:!0},_options:{state:!0}};static styles=[v(Pr),v(r)];constructor(){super(),Object.assign(this,{_history:null,_total:0,_page:1,_filter:`all`,_query:``,_repo:``,_actor:``,_options:{repos:[],users:[]}}),this._searchTimer=null,this._onActorFilter=e=>{let t=e.detail?.actor;if(typeof t!=`string`)return;let n=t.startsWith(`user:`)||t.startsWith(`legacy:`);this._query=n?``:t,this._filter=`all`,this._repo=``,this._actor=n?t:``,this._load()}}connectedCallback(){super.connectedCallback(),document.addEventListener(`managed-history-filter`,this._onActorFilter)}disconnectedCallback(){clearTimeout(this._searchTimer),document.removeEventListener(`managed-history-filter`,this._onActorFilter),super.disconnectedCallback()}async _load(e=1){clearTimeout(this._searchTimer),this._error=null;let t=this._filter,n=this._query.trim(),r=this._actor,i=this._repo,a=`history:${JSON.stringify([e,t,n,i,r])}`;await this._loadCollection(a,`history`,a=>$n(a,e,t,n,i,r),e=>{this._history=e.history,this._total=e.total,this._page=e.page,this._options=e.filters??{repos:[],users:[]}})}_search(e){this._query=e,clearTimeout(this._searchTimer),this._loadRequest?.abort(),this._loadRequest=null,this._loading=!0,this._searchTimer=setTimeout(()=>{this._load()},250)}_setRepo(e){return this._repo=e,this._load()}_setActor(e){return this._actor=e,this._load()}_clearContext(){return this._repo=``,this._actor=``,this._load()}_contextFilters(){let e=this._options.repos,t=this._options.users??[],n=[{value:``,label:`All repositories`,special:!0,reset:!0},...this._repo&&!e.includes(this._repo)?[{value:this._repo,label:this._repo}]:[],...e.map(e=>({value:e,label:e}))];return y`<repository-selector label="Filter history by repository" .options="${n}" .value="${this._repo}" @repository-change="${e=>{this._setRepo(e.detail.value)}}"></repository-selector><user-selector label="Filter history by user" reset-label="All users" placeholder="${this._actor?`Selected user`:`All users`}" .users="${t}" .value="${this._actor}" @user-change="${e=>{this._setActor(e.detail.value)}}"></user-selector><button type="button" class="btn" aria-label="Clear repository and user filters" ?disabled="${!this._repo&&!this._actor}" @click="${()=>{this._clearContext()}}">Clear selection</button>`}render(){let e=this._history??[],t=this._page,n=(t-1)*100;return y`<div class="wrap">${this._nav()}<h1 class="sr-only">History</h1><div class="page-intro"><p class="intro">${this._role===`admin`?`Uploads, builds, access changes, repository changes, deletions, triage, and package reviews.`:`Bundle, report, triage, and package review history within your team access.`}</p><span class="result-count">${this._history?this._total:`…`} entries</span></div><div class="toolbar" role="search"><input type="search" maxlength="500" aria-label="Search history" placeholder="Search history…" .value="${this._query}" @input="${e=>this._search(e.target.value)}"> ${this._kindFilter()} ${this._contextFilters()} <button type="button" class="btn" ?disabled="${this._loading}" @click="${()=>this._load(t)}">Refresh</button></div>${this._error?y`<p class="msg error" role="alert">Couldn’t load history: ${this._error} <button type="button" class="btn" @click="${()=>this._load()}">Retry</button></p>`:b} ${this._list(this._history,`Loading history…`,()=>e.length===0?y`<div class="history"><p class="empty">${this._query.trim()||this._filter!==`all`||this._repo||this._actor?`No activity matches your filters.`:`No history available yet.`}</p></div>`:y`<div class="history" aria-label="Workspace history"><div class="history-head" aria-hidden="true"><span>Type</span><span>Activity</span><span>Repository / report / finding</span><span>Time</span></div>${e.map(e=>this._row(e))}</div>`)} ${this._total>100?y`<nav class="pagination" aria-label="History pages"><span role="status">${n+1}–${Math.min(n+100,this._total)} of ${this._total} entries</span><button type="button" class="btn" ?disabled="${this._loading||t===1}" @click="${()=>this._changePage(t-1)}">Previous</button><span>Page ${t} of ${Math.ceil(this._total/100)}</span><button type="button" class="btn" ?disabled="${this._loading||n+100>=this._total}" @click="${()=>this._changePage(t+1)}">Next</button></nav>`:b}</div>`}_kindFilter(){let e=di.filter(e=>e!==`access`||this._role===`admin`);return y`<select class="kind-filter" aria-label="Filter history by type" .value="${this._filter}" @change="${e=>{this._filter=e.target.value,this._load()}}"><button type="button"><selectedcontent></selectedcontent><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><path d="m4 6 4 4 4-4"/></svg></button><option value="all" ?selected="${this._filter===`all`}">All activity</option>${e.map(e=>y`<option value="${e}" ?selected="${this._filter===e}">${fi(e)}</option>`)}</select>`}async _changePage(e){await this._load(e),await this.updateComplete,this.renderRoot.querySelector(`.manage-list`)?.scrollTo({top:0})}_row(e){let t=[e.repo??e.repository,e.report,e.finding].filter(Boolean).join(` · `),n=e.actor??e.user??null,r=e.actorName?.trim()||n||`Unknown user`,i=e.action??`updated workspace data`;return y`<div class="row">${fi(e.kind)}<span class="activity">${ui(e.actorId,r)}<span class="activity-description" data-tooltip-truncated data-tooltip="${`${r} ${i}`}"><strong class="actor" data-tooltip="${n&&n!==r?`@${n} on GitHub`:b}">${r}</strong> <span class="action">${i}</span></span></span><span class="detail" data-tooltip-truncated data-tooltip="${t}">${t||`—`}</span><span class="history-time">${Ti(e.at)}</span></div>`}};customElements.define(`managed-admin-history`,Ci);var wi=e=>{if(e==null||e===``)return null;let t=new Date(Number(e));return Number.isNaN(t.getTime())?null:t};function Ti(e){let t=wi(e);return t?y`<time datetime="${t.toISOString()}">${t.toLocaleDateString(void 0,{year:`numeric`,month:`short`,day:`numeric`})}</time><span>${t.toLocaleTimeString(void 0,{hour:`numeric`,minute:`2-digit`})}</span>`:y`<span>Unknown</span>`}var Ei=e=>e?.lastActivityAt??e?.lastActivity??e?.lastWriteAt??e?.lastActiveAt,Di=class extends x{static view=`admin-users`;static properties={_query:{state:!0},_users:{state:!0},_teams:{state:!0}};static styles=[v(Fr),v(r)];static collection=[`users`,`users`,e=>Promise.all([er(e),Or(e)])];constructor(){super(),Object.assign(this,{_users:null,_query:``,_teams:null})}_show([e,t]){this._users=e,this._teams=Array.isArray(t?.teams)?t.teams:[]}_memberships(e){return(this._teams??[]).flatMap(t=>{let n=t.members?.find(t=>t.userId===e.id);return n==null?[]:[{team:t,member:n}]})}_filteredUsers(){let e=this._query.trim().toLocaleLowerCase();return(this._users??[]).filter(t=>[t.name,t.login,t.role,...this._memberships(t).map(({team:e})=>e.name)].filter(Boolean).join(` `).toLocaleLowerCase().includes(e))}render(){let e=this._filteredUsers();return y`<div class="wrap">${this._nav()}<h1 class="sr-only">Users</h1><div class="page-intro"><p class="intro">Manage workspace access and roles.</p></div><div class="collection-toolbar" role="search"><input type="search" aria-label="Search users" placeholder="Search by name, username, or team…" .value="${this._query}" @input="${e=>{this._query=e.target.value}}"><span class="result-count" role="status">${this._users&&this._query.trim()?`${e.length} matching out of `:``}${this._users?.length??`…`} users</span></div>${C(this._error&&`Couldn't load users: ${this._error}`)} ${this._list(this._users,`Loading users…`,()=>this._directory(e))}</div>`}_directory(e){return this._users.length===0?y`<p class="msg">No users yet.</p>`:e.length===0?w(`No matching users`,`Try another name, username, or team.`):y`<div class="directory"><div class="list-head" aria-hidden="true"><span>Account</span><span>Team access</span><span>Last seen</span><span>Last activity</span><span>Role</span><span></span></div><ul class="users">${e.map(e=>this._row(e))}</ul></div>${this._users.some(e=>e.id===this._me)?y`<p class="self-note ui-hint">Your own role can only be changed by another admin.</p>`:b}`}_row(e){let t=e.id===this._me,n=this._memberships(e),r=wi(Ei(e)),i=wi(e.lastSeenAt);return y`<li><span class="person">${li(e.id,e.login)} <span class="who"><span class="name"><span class="name-text">${e.name||e.login}</span>${t?y`<span class="you">You</span>`:b}</span> <span class="login">@${e.login}</span> </span></span><span class="memberships">${Le(e.role,`manage`)?y`<span class="team-access"><strong class="team-access-role">${e.role===`admin`?`All reports`:`Owned and team reports`}</strong><span class="team-perms"><span class="permission-granted">+ Deps</span><span class="permission-granted">+ Security</span></span></span>`:n.length===0?y`<span class="no-team">No team access</span>`:n.map(({team:e,member:t})=>y`<span class="team-access"><strong>${m(`team`)}<span>${e.name}</span></strong><span class="team-perms">${[`dependencies`,`security`].map(e=>y`<span class="${t[e]===!0?`permission-granted`:`permission-denied`}">${t[e]===!0?`+`:`−`} ${e===`dependencies`?`Deps`:`Security`}</span>`)}</span></span>`)} </span><span class="last-seen" aria-label="${i?`Last seen ${i.toLocaleString()}`:`Unknown`}">${Ti(e.lastSeenAt)}</span> <button type="button" class="activity-link" aria-label="${`Show activity by ${e.login}`}" @click="${()=>p(`manage-history`,{actor:`user:${e.id}`})}"><span class="last-activity" aria-label="${`Last activity ${r?r.toLocaleString():`Unknown`}`}">${Ti(Ei(e))}</span></button> <span class="access"><select class="role" ?disabled="${t}" aria-label="${`Change ${e.login}\u2019s role`}" aria-description="${_i[e.role]?.[1]??``}" @change="${t=>this._changeRole(e,t.target.value,t.target)}">${Fe.map(t=>y`<option value="${t}" ?selected="${t===e.role}">${_i[t][0]}</option>`)}</select> </span><span class="view-as">${t?b:y`<button type="button" class="icon-btn" aria-label="${`View as ${e.login}`}" data-tooltip="See the app as this user" @click="${t=>{this._viewAs(e,t.currentTarget)}}">${m(`show`)}</button>`}</span></li>`}async _viewAs(e,t){t.disabled=!0;try{await _e(e.id,this._csrf)}catch(n){t.disabled=!1,this.appState.notify(`Couldn't view as @${e.login}: ${n?.message??n}`)}}async _changeRole(e,t,n){let r=e.role;if(t!==r){try{await this.appState.mutate(()=>tr(e.id,t,this._csrf),[`users`,`teams`,`reports`,`history`]),e.role=t,await this._load()}catch(e){console.warn(`admin: set role failed:`,e),n.value=r}this.requestUpdate()}}};customElements.define(`managed-admin-users`,Di);var Oi=e=>!e||e.mode===`exclude`&&e.paths.length===0?{mode:`all`,paths:[]}:{mode:e.mode,paths:[...e.paths].toSorted()},ki=e=>e.mode===`all`?{mode:`exclude`,paths:[]}:{mode:e.mode,paths:e.paths},Ai={private:y`<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="7" width="10" height="7" rx="1"/><path d="M5 7V5a3 3 0 0 1 6 0v2"/></svg>`,public:y`<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="8" cy="8" r="6"/><path d="M2.5 8h11M8 2c1.5 1.7 2.2 3.7 2.2 6S9.5 12.3 8 14c-1.5-1.7-2.2-3.7-2.2-6S6.5 3.7 8 2Z"/></svg>`},ji=class extends x{static view=`manage-repos`;static properties={_publicRepoOpen:{state:!0},_publicRepository:{state:!0},_publicRepoError:{state:!0},_addingPublic:{state:!0},_actionError:{state:!0},_scope:{state:!0},_showAll:{state:!0},_query:{state:!0},_organization:{state:!0},_busy:{state:!0},_connectingApp:{state:!0},_detail:{state:!0},_aliases:{state:!0},_impact:{state:!0},_impactLoading:{state:!0},_removeOpen:{state:!0},_acknowledge:{state:!0},_deleteTriage:{state:!0},_confirmName:{state:!0},_reviewDraft:{state:!0}};static styles=[v(Ir),v(r)];constructor(){super(),Object.assign(this,{_publicRepoOpen:!1,_publicRepository:``,_publicRepoError:null,_addingPublic:!1,_actionError:null,_scope:`connected`,_showAll:!1,_query:``,_organization:null,_loading:!0,_busy:null,_connectingApp:!1,_detail:null,_aliases:!1,_impact:null,_impactLoading:!1,_impactFresh:!1,_impactRequest:null}),this._resetRemoval()}disconnectedCallback(){super.disconnectedCallback(),this._impactRequest?.abort()}_resetRemoval(e=!1){Object.assign(this,{_removeOpen:e,_acknowledge:!1,_deleteTriage:!1,_confirmName:``})}async _load(e=!1){this._error=null;let{_scope:t,_showAll:n}=this;await this._loadCollection(`repos:${JSON.stringify([t,n])}`,`repositories`,r=>nr(t,n,e,r),e=>{this._data=e,this._organization=this._repositoryChoices().activeFacet})}_open(e){this._impactRequest?.abort(),Object.assign(this,{_publicRepoOpen:!1,_scope:e,_showAll:!1,_query:``,_organization:null,_detail:null,_aliases:!1,_impact:null,_data:null,_actionError:null}),this._resetRemoval(),this._load()}_setShowAll(e){Object.assign(this,{_showAll:e,_organization:null,_data:null}),this._load()}_search(e){this._query=e}_repositoryChoices(){let e=(this._data?.repositories??[]).map(e=>({value:e.id,label:e.fullName,repo:e}));return ze(e,this._query,this._organization,{includeSingletonOrganizations:!0})}_back(e=null){return vi(`Repositories`,`Back to repositories`,()=>{this._detail?(this._impactRequest?.abort(),this._detail=null,this._actionError=null):this._aliases?this._aliases=!1:this._open(`connected`)},e)}_openDetail(e){let t=`repo-impact:${e.id}`;Object.assign(this,{_detail:e,_reviewDraft:null,_actionError:null,_impact:this.appState.read(t)??null,_impactFresh:!1,_impactLoading:!0}),this._resetRemoval(),this._read(`_impactRequest`,t,`repository data`,t=>cr(e.id,t),{apply:e=>{this._impact=e},answered:()=>{this._impactFresh=!0},settled:()=>{this._impactLoading=!1},failed:e=>{this._impact||(this._actionError=`Couldn't load repository data: ${e?.message??e}`)}})}render(){if(this._detail)return this._detailPage(this._detail);if(this._aliases)return this._aliasesPage();let e=this._scope===`connected`,t=e?`Repositories`:`Add ${this._scope} repository`,n=this._repositoryChoices();return y`<div class="wrap">${this._nav()} ${e?y`<h1 class="sr-only">${t}</h1>`:this._back(t)}<div class="page-intro"><p class="intro">${e?`Manage connected repositories and their settings.`:this._scope===`installed`?this._showAll?`Showing all repositories the GitHub App can read.`:`Showing installed repositories you can access on GitHub.`:`Choose a public repository your GitHub account is involved with.`}</p>${e?y`<div class="repository-actions"><button type="button" class="btn" @click="${()=>this._open(`installed`)}">${Ai.private} Add installed repository</button> <button type="button" class="btn" @click="${()=>this._open(`public`)}">${Ai.public} Add your public repository</button> ${this._role===`admin`&&this._data?.canAddAnyPublicRepository?y`<button type="button" class="btn" aria-expanded="${this._publicRepoOpen}" @click="${()=>this._openPublicRepository()}">${Ai.public} Add a public repository</button>`:b}</div>`:b}</div>${!e&&this._scope===`installed`?y`<div class="access-note"><p class="ui-hint">Installed repositories are readable through the GitHub App. Install it on a repository or organization to make it available here.</p><span class="access-action">${this._data?.installUrl?y`<a class="btn" href="${this._data.installUrl}" target="_blank" rel="noopener noreferrer">Configure GitHub access</a>`:y`<button type="button" class="btn" disabled="disabled">Configure GitHub access</button>`}</span></div>`:b}<div class="toolbar"><label class="search"><input type="search" aria-label="${e?`Search connected repositories`:`Search ${this._scope} repositories`}" placeholder="Search by repository or owner…" .value="${this._query}" @input="${e=>this._search(e.target.value)}"></label> ${this._scope===`installed`?y`<label class="show-all"><input type="checkbox" role="switch" .checked="${this._showAll}" @change="${e=>this._setShowAll(e.target.checked)}"><span>Show all</span></label><label class="show-all-paper"><input type="checkbox" .checked="${this._showAll}" @change="${e=>this._setShowAll(e.target.checked)}"><span>Show all</span></label>`:b} ${e?y`<span class="result-count" role="status">${this._data&&(this._query.trim()||n.activeFacet!=null)?`${n.count} ${n.count===1?`repository`:`repositories`} out of `:``}${this._data?.connectedCount??`…`} connected</span>`:y`<button type="button" class="btn" ?disabled="${this._loading}" @click="${()=>{this._load(!0)}}">Refresh</button>`}</div>${e&&this._publicRepoOpen&&this._role===`admin`&&this._data?.canAddAnyPublicRepository?this._publicRepositoryForm():b} ${C(this._actionError)} ${this._error?y`<p class="msg error" role="alert">Couldn't load repositories: ${this._error}</p><button type="button" class="btn" @click="${()=>{this._load()}}">Try again</button>`:b} ${!e&&this._data?y`<p class="repository-count" role="status">${n.count}${n.count===n.total?``:` of ${n.total}`} ${n.total===1?`repository`:`repositories`}</p>`:b}<div class="manage-list"><div aria-busy="${this._loading}">${this._body(n)}</div>${e&&this._role===`admin`?y`<div class="repository-pages"><button type="button" class="btn" @click="${()=>{this._publicRepoOpen=!1,this._actionError=null,this._aliases=!0}}">Aliases</button></div>`:b}</div></div>`}_aliasesPage(){return y`<div class="wrap">${this._nav()} ${this._back(`Aliases`)}<div class="manage-list has-intro"><managed-repository-aliases .session="${this.session}" .repositories="${this._data?.repositories}"></managed-repository-aliases></div></div>`}_body(e){if(!this._data)return this._error?b:S(`Loading repositories…`);let t=this._scope;return y`${this._data.tokenMissing&&!this._showAll&&t!==`connected`?y`<p class="msg">Log out and back in to refresh your GitHub membership access.</p>`:b}<div class="repository-browser">${e.showFacets?y`<nav class="organization-list" aria-label="Filter by organization"><button type="button" class="organization" aria-pressed="${e.activeFacet==null}" @click="${()=>{this._organization=null}}"><span class="organization-name">All organizations</span><span class="organization-count">${e.total}</span></button> ${e.facets.map(t=>y`<button type="button" class="organization" aria-pressed="${e.activeFacet===t.value}" @click="${()=>{this._organization=t.value}}"><span class="organization-name" data-tooltip-truncated data-tooltip="${t.name}">${t.name}</span><span class="organization-count">${t.count}</span></button>`)}</nav>`:b}<div class="repo-results">${e.sections.map(e=>y`<section class="repo-group" aria-label="${e.label??`Repositories`}">${e.label?y`<h2 class="owner-head"><span class="owner-icon" aria-hidden="true">${e.label[0]??`?`}</span>${e.label}</h2>`:b}<ul class="repos">${e.options.map(t=>this._row(t.repo,e.organization?t.name:t.label))}</ul></section>`)} ${e.count?b:w(e.total?`No matching repositories`:t===`connected`?`No connected repositories yet`:`No ${t} repositories available`,e.total?`Try a different search or organization.`:t===`connected`?`Add an installed or public repository to get started.`:t===`installed`?this._showAll?`Install the GitHub App, then refresh this list.`:`No installed repositories match your GitHub access. Turn on Show all to browse every installation.`:`Public repositories associated with your GitHub account will appear here.`)}</div></div>`}_openPublicRepository(){this._publicRepoOpen=!0,this._publicRepoError=null,this.updateComplete.then(()=>this.renderRoot?.querySelector(`#public-repository`)?.focus())}_publicRepositoryForm(){return y`<form class="public-repository-form" aria-label="Add a public repository" @submit="${e=>{e.preventDefault(),this._addPublicRepository()}}"><label class="confirm-field" for="public-repository"><span>Public GitHub repository</span> <input id="public-repository" class="confirm-name" type="text" placeholder="owner/repo or https://github.com/owner/repo" autocomplete="off" required .value="${this._publicRepository}" ?disabled="${this._addingPublic}" @input="${e=>{this._publicRepository=e.target.value}}"></label><div class="dialog-actions"><button type="button" class="btn" ?disabled="${this._addingPublic}" @click="${()=>{this._publicRepoOpen=!1}}">Cancel</button><button type="submit" class="btn" ?disabled="${this._addingPublic||!this._publicRepository.trim()}">${this._addingPublic?`Adding…`:`Add repository`}</button></div>${C(this._publicRepoError)}</form>`}async _addPublicRepository(){if(!this._addingPublic&&this._publicRepository.trim()){this._addingPublic=!0,this._publicRepoError=null;try{await this.appState.mutate(()=>sr(this._publicRepository.trim(),this._csrf),[`repos`,`reports`,`bundles`,`teams`,`users`,`history`,`scan-sources`]),this._publicRepoOpen=!1,this._publicRepository=``,await this._load()}catch(e){this._publicRepoError=e?.message??String(e)}finally{this._addingPublic=!1}}}_row(e,t){let n=`${this._accessLabel(e)}${this._scope===`connected`&&e.active===!1?` · Deactivated`:``}`,r=y`${gi}<span class="repo-copy"><span class="repo-name">${t}</span><span class="repo-meta">${n}</span></span>`;return this._scope===`connected`?y`<li class="repo-item"><button type="button" class="repo-row" aria-label="${`Manage ${e.fullName}`}" @click="${()=>this._openDetail(e)}">${r}<span class="repo-code-slot" aria-hidden="true"></span><svg class="arrow" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" aria-hidden="true"><path d="m6 4 4 4-4 4"/></svg></button>${e.active===!1?b:y`<a class="repo-code" href="${rt({view:`repository-code`,repoId:e.id})}" aria-label="${`Open ${e.fullName}'s code`}" @click="${t=>this._openCode(t,e)}">${m(`code`)}</a>`}</li>`:y`<li class="repo-row">${r} ${e.selected?y`<span class="connected"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><path d="m3 8 3 3 7-7"/></svg>Connected</span>`:e.private&&!e.installed?y`<span class="repo-meta">Needs App access</span>`:y`<button type="button" class="btn" aria-label="${`Add ${e.fullName}`}" ?disabled="${this._busy!=null}" @click="${()=>{this._setActive(e,!0)}}">${this._busy===e.id?`Adding…`:`Add`}</button>`}</li>`}_openCode(e,t){e.button!==0||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||(e.preventDefault(),this._emit(`managed-repository-code-open`,{repoId:t.id}))}_accessLabel(e){let t=e.visibility===`public`?`Public`:e.visibility===`internal`?`Internal`:e.private?`Private`:null,n=e.installed?`GitHub App`:`GitHub`;return t?`${t} \xB7 ${n}`:n}async _act(e,t,n){if(this._busy==null){this._busy=e.id,this._actionError=null;try{await n()}catch(e){this._actionError=`Couldn't ${t}: ${e?.message??e}`}finally{this._busy=null}}}_patchRepo(e,t){this._detail?.id===e&&(this._detail={...this._detail,...t}),this._data&&={...this._data,repositories:this._data.repositories.map(n=>n.id===e?{...n,...t}:n)}}async _connectApp(e){this._busy!=null||e.installed||(this._connectingApp=!0,await this._act(e,`connect ${e.fullName}`,async()=>{let t=await this.appState.mutate(()=>ur(e.id,this._csrf),[`repos`,`history`,`scan-sources`]);if(this.isConnected){if(!t.connected){globalThis.location.assign(t.installUrl);return}this._patchRepo(e.id,{installed:!0}),await this._load()}}),this._connectingApp=!1)}_detailPage(e){let t=e.active!==!1,n=this._impact?.reports??[],r=this._impact?.bundles??[];return y`<div class="wrap">${this._nav()}<div class="head">${this._back()}<h1>${e.fullName}</h1></div><p class="intro ui-hint">Repository settings and stored data.</p>${C(this._actionError)}<div class="manage-list repository-detail"><section class="section" aria-label="Repository connection"><h2>Connection</h2><div class="settings-row"><div class="settings-copy"><strong>${this._accessLabel(e)}</strong><p>${t?`Active for new scans and uploads.`:`Deactivated. Stored reports and bundles are retained.`}</p></div><span class="${`status-line ${t?``:`inactive`}`}">${t?`Active`:`Deactivated`}</span> ${e.installed?b:y`<button type="button" class="btn connect-app" aria-label="${`Connect GitHub App to ${e.fullName}`}" ?disabled="${this._busy!=null}" @click="${()=>{this._connectApp(e)}}">${this._connectingApp&&this._busy===e.id?`Connecting…`:`Connect GitHub App`}</button>`} ${e.htmlUrl?y`<a class="btn" href="${e.htmlUrl}" target="_blank" rel="noopener noreferrer">View on GitHub</a>`:b}</div><div class="settings-row"><div class="settings-copy"><strong>${t?`Deactivate repository`:`Reactivate repository`}</strong><p>${t?`Pause new scans while preserving all stored data and attachments.`:`Make this repository available for new scans and bundle attachments again.`}</p></div><button type="button" class="btn" ?disabled="${this._busy!=null}" @click="${()=>{this._setActive(e,!t)}}">${this._busy===e.id&&!this._connectingApp?t?`Deactivating…`:`Reactivating…`:t?`Deactivate`:`Reactivate`}</button></div></section>${this._dependencyReviewSection(e)}<section class="data-section" aria-label="Stored repository data"><h2>Stored data</h2><div class="dialog-data" aria-busy="${this._impactLoading}">${[[`Reports`,n],[`Bundles`,r]].map(([t,n])=>y`<section><h3>${t} (${this._impact==null?`…`:n.length})</h3>${this._impactLoading&&this._impact==null?y`<p class="data-empty" role="status">Loading ${t.toLowerCase()}…</p>`:this._impact==null?y`<p class="data-empty">Attached data could not be loaded.</p><button type="button" class="btn" @click="${()=>this._openDetail(e)}">Try again</button>`:n.length>0?y`<ul>${n.map(e=>y`<li>${e.filename}${e.repoDirectory?` \xB7 ${e.repoDirectory}`:b}</li>`)}</ul>`:y`<p class="data-empty">No ${t.toLowerCase()} attached.</p>`}</section>`)}</div></section><section class="section" aria-label="Permanent repository removal"><h2>Permanent removal</h2><div class="settings-row"><div class="settings-copy"><strong>Delete repository and stored data</strong><p>Deactivation is reversible. Permanent removal deletes this repository’s attached reports and bundles; it cannot be undone.</p></div><button type="button" class="btn danger" ?disabled="${this._busy!=null||this._impactLoading||!this._impactFresh||this._impact==null}" @click="${()=>this._resetRemoval(!0)}">Remove permanently</button></div></section></div>${this._removeOpen&&this._impact!=null&&!this._impactLoading?this._removeDialog(e,n,r):b}</div>`}_dependencyReviewSection(e){let t=this._data?.reviewedDependencies===!0,n=e.dependencyReview??{enabled:!1,required:1,since:null},r=Oi(n.lockfiles),i={required:String(n.required),since:n.since??``,scope:r,adding:``,...this._reviewDraft},a=i.required!==String(n.required)||!t&&i.since.trim()!==(n.since??``)||JSON.stringify(i.scope)!==JSON.stringify(r),o=this._busy!=null;return y`<section class="section" aria-label="Dependency review"><div class="section-head"><h2>Dependency review</h2><mode-switch label="${n.enabled?`On`:`Off`}" accessible-label="Review dependencies" .checked="${n.enabled}" .disabled="${o}" @click="${()=>{o||this._saveDependencyReview(e,this._reviewSetting(!n.enabled,n.required,n.since))}}"></mode-switch></div>${n.enabled?y`<form class="settings-row dependency-review-settings" aria-label="Dependency review settings" @submit="${t=>{t.preventDefault(),this._saveDependencyReview(e,this._reviewSetting(!0,Number(i.required),i.since.trim().toLowerCase()||null,ki(i.scope)))}}"><label><span>Reviews each version needs</span><input type="number" min="1" max="10" required .value="${i.required}" ?disabled="${o}" @input="${e=>{this._reviewDraft={...i,required:e.target.value}}}"></label> ${t?b:y`<label class="dependency-review-since"><span>Reviewed since commit (optional)</span><input type="text" placeholder="Full commit id" autocomplete="off" spellcheck="false" pattern="[0-9a-fA-F]{40}" .value="${i.since}" ?disabled="${o}" @input="${e=>{this._reviewDraft={...i,since:e.target.value}}}"></label>`} ${this._lockfileScope(e,i,o)} <button type="submit" class="btn" ?disabled="${o||!a}">Save</button> ${Array.isArray(e.reviewTeams)&&e.reviewTeams.length===0?y`<p class="dependency-review-hint is-warning" role="status">No team that reviews dependencies has this repository, so its pull requests show no review. Add it to such a team, or turn dependency review on for a team that has it.</p>`:t||i.since.trim()?y`<p class="dependency-review-hint">${t?`Versions this server’s reviewed dependencies pass need no reviews here.`:`Versions the repository’s lockfiles locked at this commit need no review.`}</p>`:b}</form>`:b}</section>`}_lockfileScope(e,t,n){let{mode:r,paths:i}=t.scope,a=r===`all`?{status:`ready`,paths:[],configs:[]}:this._lockfilesFor(e),o=e=>{this._reviewDraft={...t,scope:e}},s=r===`include`?a.configs:[],c=new Set([...a.paths,...s]),l=[...new Set([...c,...i])].toSorted(),u=e=>e===`include`?i:i.filter(e=>!gt(e)),d=()=>{let e=t.adding.trim().replace(/^\.?\/+/u,``);e&&(this._reviewDraft={...t,adding:``,scope:{mode:r,paths:[...new Set([...i,e])].toSorted()}})};return y`<fieldset class="dependency-review-lockfiles" ?disabled="${n}"><legend>Lockfiles reviewed</legend><select aria-label="Lockfiles reviewed" .value="${r}" @change="${e=>o({mode:e.target.value,paths:u(e.target.value)})}"><option value="all">Every lockfile</option><option value="exclude">All but those selected</option><option value="include">Only those selected</option></select> ${r===`all`?b:y`${a.status===`loading`?y`<p class="dependency-review-hint" role="status">Reading the default branch’s lockfiles…</p>`:a.status===`error`?y`<p class="dependency-review-hint is-warning" role="alert">Its lockfiles couldn’t be read (${a.error}); name them below.</p>`:b} ${l.length>0?y`<ul class="dependency-review-lockfile-list">${l.map(e=>y`<li><label><input type="checkbox" .checked="${i.includes(e)}" @change="${t=>o({mode:r,paths:t.target.checked?[...i,e].toSorted():i.filter(t=>t!==e)})}"> <code>${e}</code>${a.status===`ready`&&!c.has(e)?y`<span>${e.endsWith(`/`)?`every lockfile under it`:`not on the default branch`}</span>`:b}</label></li>`)}</ul>`:a.status===`ready`?y`<p class="dependency-review-hint">Its default branch has no lockfile its review reads.</p>`:b} ${i.some(gt)?y`<p class="dependency-review-hint">A <code>stasis.config.json</code> holds the review to the versions its entries reach, in place of all a lockfile locks. Stasis builds them for each commit as it is first asked for, which can take minutes; until then they show as being worked out.</p>`:b} <label class="dependency-review-lockfile-add"><span>${r===`include`?`Another lockfile, a directory ending in /, or a stasis.config.json`:`Another lockfile, or a directory ending in /`}</span> <input type="text" placeholder="examples/" autocomplete="off" spellcheck="false" .value="${t.adding}" @input="${e=>{this._reviewDraft={...t,adding:e.target.value}}}" @keydown="${e=>{e.key===`Enter`&&(e.preventDefault(),d())}}"></label> <button type="button" class="btn" ?disabled="${!t.adding.trim()}" @click="${d}">Add</button>`}</fieldset>`}_lockfilesFor(e){if(this._lockfileRead?.repoId!==e.id){let t={repoId:e.id,status:`loading`,paths:[],configs:[]};this._lockfileRead=t,ar(e.id).then(({paths:e,configs:n})=>Object.assign(t,{status:`ready`,paths:e,configs:n}),e=>Object.assign(t,{status:`error`,error:e?.message??String(e)})).finally(()=>{this._lockfileRead===t&&this.requestUpdate()})}return this._lockfileRead}_reviewSetting(e,t,n,r){return{...this._data?.reviewedDependencies===!0?{enabled:e,required:t}:{enabled:e,required:t,since:n},...r?{lockfiles:r}:{}}}async _saveDependencyReview(e,t){await this._act(e,`save ${e.fullName}'s dependency review`,async()=>{let n=await this.appState.mutate(()=>ir(e.id,t,this._csrf),[`repos`]);globalThis.dispatchEvent?.(new Event(`dependency-review-changed`)),this.isConnected&&(this._patchRepo(e.id,{dependencyReview:n}),this._reviewDraft=null)})}_removeDialog(e,t,n){let r=t.length>0||n.length>0,i=this._canRemove(e);return y`<div class="dialog-backdrop" role="presentation" @click="${e=>{e.target===e.currentTarget&&(this._removeOpen=!1)}}"><section class="${`dialog ${r?``:`small`}`}" role="dialog" aria-modal="true" aria-labelledby="remove-repo-title"><h2 id="remove-repo-title">Remove ${e.fullName} permanently?</h2><p class="dialog-copy">${r?`This destructive action will remove the repository and the stored data listed below. Deactivation keeps all of it.`:`This repository has no attached reports or bundles. Permanent removal deletes its connection record.`}</p>${r?y`<div class="dialog-data"><section><h3>Reports to delete (${t.length})</h3><ul>${t.map(e=>y`<li>${h(e.filename)}${e.repoDirectory?` \xB7 ${e.repoDirectory}`:b}</li>`)}</ul></section><section><h3>Bundles to delete (${n.length})</h3><ul>${n.map(e=>y`<li>${e.filename}</li>`)}</ul></section></div>`:b} <label class="confirm-line"><input type="checkbox" .checked="${this._acknowledge}" @change="${e=>{this._acknowledge=e.target.checked}}"><span>I understand this permanently deletes the repository connection${r?`, reports, and bundles`:``}.</span></label> ${(this._impact?.triageCount??0)>0?y`<label class="confirm-line"><input type="checkbox" .checked="${this._deleteTriage}" @change="${e=>{this._deleteTriage=e.target.checked}}"><span>Also delete ${this._impact.triageCount} triage entr${this._impact.triageCount===1?`y`:`ies`} belonging only to this repository.</span></label>`:b} ${r?y`<label class="confirm-field"><span>Type <strong>${e.fullName}</strong> to confirm.</span><input class="confirm-name" type="text" autocomplete="off" .value="${this._confirmName}" @input="${e=>{this._confirmName=e.target.value}}"></label>`:b}<div class="dialog-actions"><button type="button" class="btn" @click="${()=>{this._removeOpen=!1}}">Cancel</button><button type="button" class="btn danger" ?disabled="${!i}" @click="${()=>{this._remove(e)}}">${this._busy===e.id?`Removing…`:`Remove permanently`}</button></div></section></div>`}async _setActive(e,t){let n=t?e.active===!1?`reactivate`:`add`:`deactivate`;await this._act(e,`${n} ${e.fullName}`,async()=>{await this.appState.mutate(()=>rr(e.id,t,this._csrf),[`repos`,`reports`,`bundles`,`teams`,`users`,`history`]),this.isConnected&&(this._patchRepo(e.id,{active:t}),await this._load())})}_canRemove(e){return this._busy!=null||this._impactLoading||!this._impactFresh||this._impact?.repoId!==e.id||!this._acknowledge?!1:!(this._impact.reports.length>0||this._impact.bundles.length>0)||this._confirmName===e.fullName}async _remove(e){this._canRemove(e)&&await this._act(e,`remove ${e.fullName}`,async()=>{await this.appState.mutate(()=>dr(e.id,e.fullName,this._deleteTriage,this._csrf),[`repos`,`repo-impact`,`reports`,`report-preview`,`bundles`,`teams`,`users`,`history`,`scan-sources`]),this._removeOpen=!1,this._detail=null,this._impact=null,await this._load()})}};customElements.define(`managed-admin-repos`,ji);function Mi(e){return[{value:null,label:`No repository`,special:!0},...e.map(e=>({value:e.repoId,label:e.fullName}))]}function Ni(e,t,n,r,i){let a=y`<span class="ui-hint">${e}: </span><span class="location-metadata-value" data-tooltip-truncated data-tooltip="${t}">${t}</span>`;return r?y`<button type="button" class="location-metadata" aria-label="${`Use ${n} from ${e}: ${t}`}" ?disabled="${i}" @click="${r}">${a}</button>`:y`<span class="location-metadata">${a}</span>`}var Pi=e=>Number.isFinite(e.uploadedAt)?new Date(e.uploadedAt).toLocaleDateString(void 0,{year:`numeric`,month:`short`,day:`numeric`}):``,Fi=e=>e.repoFullName?`${e.repoFullName}${e.repoDirectory?`/${e.repoDirectory}`:``}`:`No repository assigned`,Ii=class extends x{static properties={localImportSource:{attribute:!1},_query:{state:!0},_visibility:{state:!0},_busy:{state:!0},_locationId:{state:!0},_locationOrigin:{state:!0},_locationOriginError:{state:!0},_locationRepo:{state:!0},_locationDirectory:{state:!0},_locationBusy:{state:!0}};constructor(){super();let{kind:e,upload:t,importFamilies:n,uploadFamilies:r}=this.constructor;Object.assign(this,{_query:``,_visibility:`all`,_busy:!1,_locationId:null,_locationOrigin:null,_locationOriginError:null,_locationRepo:null,_locationDirectory:``,_locationBusy:!1}),this._locationOriginRequest=null,this._queue=[],this._localImport=new vt(this,e,e=>pt(this,e,e=>t(e,this._csrf),n??r)),this._drop=new ht(this,()=>this._acceptsDrop())}_acceptsDrop(){return!0}disconnectedCallback(){super.disconnectedCallback(),this._closeLocation()}_show(e){this._data=e,this._locationId&&!e[`${this.constructor.kind}s`]?.some(e=>e.id===this._locationId)&&this._closeLocation()}_upload(e){let{upload:t,uploadFamilies:n}=this.constructor;return mt(this,e,e=>t(e,this._csrf),n)}_filtered(){let{kind:e}=this.constructor,t=Array.isArray(this._data?.[`${e}s`])?this._data[`${e}s`]:[],n=this._query.trim().toLocaleLowerCase(),r=t.filter(e=>this._searchText(e).filter(Boolean).join(` `).toLocaleLowerCase().includes(n)&&(this._visibility===`all`||this._visible(e)===(this._visibility===`visible`)));return{items:t,filtered:r,count:`${n||this._visibility!==`all`?`${r.length} of `:``}${t.length} ${t.length===1?e:`${e}s`}`}}_page(e,t){let{kind:n}=this.constructor;return y`${this._drop.overlay(`Drop ${n}s to upload`)}<div class="wrap">${this._nav()}<h1 class="sr-only">${`${n[0].toUpperCase()}${n.slice(1)}s`}</h1><div class="page-intro">${e}</div>${this._localImport.renderPanel(this._busy||!this._csrf)}${t}${this._body()}</div>`}_body(){let{kind:e,uploadCopy:t}=this.constructor,{items:n,filtered:r,count:i}=this._filtered(),a=y`<div class="collection-toolbar" role="search"><input type="search" aria-label="${`Search ${e}s`}" placeholder="${`Search ${e}s or repositories\u2026`}" .value="${this._query}" @input="${e=>{this._query=e.target.value}}"> <select aria-label="${`${e[0].toUpperCase()}${e.slice(1)} visibility`}" .value="${this._visibility}" @change="${e=>{this._visibility=e.target.value}}"><option value="all">${`All ${e}s`}</option><option value="visible">Visible to teams</option><option value="hidden">${`Hidden ${e}s`}</option></select> ${this._count(r,i)}</div>`;return y`${a} ${C(this._error)} ${this._list(this._data,`Loading ${e}s\u2026`,()=>r.length>0?this._items(r):n.length===0?w(`No ${e}s uploaded yet`,t):w(`No matching ${e}s`,`Try a different search or visibility filter.`))}`}async _attempt(e,t){this._error=null;try{await t()}catch(t){this._error=`${e}: ${String(t?.message??t)}`}}_setVisible(e,t){let{kind:n,setVisible:r,visibleFamilies:i}=this.constructor;return this._attempt(`Couldn't change ${n} visibility`,async()=>{await this.appState.mutate(()=>r(e.id,t,this._csrf),i),e.visible=t,this.requestUpdate(),await this._load()})}_openLocation(e){e.canChangeRepo!==!1&&(this._closeLocation(),Object.assign(this,{_locationId:e.id,_locationRepo:e.repoId??null,_locationDirectory:e.repoDirectory??``,_error:null}),this._suggests(e)&&this._loadLocationOrigin(e))}_suggests(){return!0}_closeLocation(){this._locationOriginRequest?.abort(),this._locationOriginRequest=null,Object.assign(this,{_locationId:null,_locationOrigin:null,_locationOriginError:null})}async _loadLocationOrigin(e){this._locationOriginRequest?.abort();let t=new AbortController;this._locationOriginRequest=t,this._locationOrigin=void 0,this._locationOriginError=null;try{let n=await this._fetchOrigin(e.id,t.signal);if(this._locationOriginRequest!==t)return;n?.repoId!=null&&this._data&&(this._data={...this._data,repos:[...(this._data.repos??[]).filter(e=>e.repoId!==n.repoId),{repoId:n.repoId,fullName:n.github}]}),this._locationOrigin=typeof n?.github==`string`&&n.github?this._suggestion(n):null}catch(e){if(this._locationOriginRequest!==t)return;this._locationOrigin=null,e?.name!==`AbortError`&&(this._locationOriginError=`Couldn't load the ${this.constructor.kind}\u2019s suggested location.`)}}_locationEditor(e){let{kind:t,hintSource:n}=this.constructor,r=Array.isArray(this._data?.repos)?this._data.repos:[],i=this._locationOrigin,a=i&&this._originRepo(i,r),o=(e,t,r)=>Ni(n,e,t,r,this._locationBusy);return y`<div class="location-editor"><div class="location-field"><div class="location-field-header"><span class="ui-hint">Repository</span>${i?o(i.github,`repository`,a?()=>{this._locationRepo=a.repoId,i.directory!=null&&(this._locationDirectory=i.directory)}:null):b}</div><repository-selector label="${`Repository for ${t}`}" .options="${Mi(r)}" .value="${this._locationRepo}" ?disabled="${this._locationBusy}" @repository-change="${e=>{this._locationRepo=e.detail.value}}"></repository-selector></div><div class="location-field"><div class="location-field-header"><label for="${`${t}-dir-${e.id}`}">Directory (optional)</label>${i?o(i.directory??`Directory not specified`,`directory`,i.directory==null?null:()=>{this._locationDirectory=i.directory}):b}</div><input id="${`${t}-dir-${e.id}`}" type="text" placeholder="Repository root" .value="${this._locationDirectory}" ?disabled="${this._locationBusy}" @input="${e=>{this._locationDirectory=e.target.value}}"></div><div class="location-actions"><button type="button" class="action" ?disabled="${this._locationBusy}" @click="${()=>this._closeLocation()}">Cancel</button><button type="button" class="action" ?disabled="${this._locationBusy}" @click="${()=>{this._saveLocation(e)}}">Save</button></div>${this._locationOriginError?y`<p class="location-origin" role="status">${this._locationOriginError} <button type="button" class="origin-retry" @click="${()=>{this._loadLocationOrigin(e)}}">Retry</button></p>`:b}</div>`}async _saveLocation(e){if(this._locationBusy)return;this._locationBusy=!0;let{kind:t,setRepo:n,locationFamilies:r}=this.constructor;try{await this._attempt(`Couldn't set ${t} location`,async()=>{await this.appState.mutate(()=>n(e.id,this._locationRepo,this._locationDirectory.trim(),this._csrf),r),this._closeLocation(),await this._load({preserveError:!0})})}finally{this._locationBusy=!1}}},Li=class extends Ii{static kind=`report`;static view=`manage-reports`;static collection=[`reports`,`reports`,fr];static upload=hr;static uploadFamilies=[`reports`,`repo-impact`,`history`,`scan-sources`];static setVisible=_r;static visibleFamilies=[`reports`,`history`,`scan-sources`];static setRepo=yr;static locationFamilies=[`reports`,`repo-impact`,`history`,`scan-sources`];static hintSource=`report`;static uploadCopy=`Drop a report here or browse files above.`;static properties={_preview:{state:!0},_previewLoading:{state:!0},_openingBusy:{state:!0}};static styles=[v(Lr),v(zr),v(r),v(Mr)];constructor(){super(),this._preview=null,this._previewLoading=null,this._previewRequest=null,this._openingBusy=null}disconnectedCallback(){super.disconnectedCallback(),this._cancelPreview()}_show(e){this._preview&&!e.reports?.some(e=>e.id===this._preview)&&this._cancelPreview(),super._show(e)}_searchText(e){return[e.filename,h(e.filename),e.repoFullName,e.repoDirectory,e.uploadedByLogin]}_visible(e){return!!e.visible}_fetchOrigin(e,t){return br(e,AbortSignal.any([t,this.appState.sessionController.signal]))}_suggestion(e){return{github:e.github,repoId:e.repoId??null,directory:typeof e.directory==`string`?e.directory||`/`:null}}_originRepo(e,t){return e.repoId!=null&&t.find(t=>t.repoId===e.repoId)}render(){return this._page(y`<p class="intro">Upload reports. New reports stay hidden until you make them visible.</p>${this._localImport.renderAction()}`,y`<div class="drop-card">${this._drop.card(`Upload reports`,`Drop files anywhere on this page.`,this._busy)}</div>${this._data?.repoScopes?.length?y`<p class="intro">Team paths: ${this._data.repoScopes.map(e=>`${this._data.repos.find(t=>t.repoId===e.repoId)?.fullName??e.repoId}/${e.path??``}`).join(`, `)}</p>`:b} `)}_count(e,t){return y`<span class="result-count" role="status">${this._data==null?`… reports`:t}</span>`}_items(e){return y`<div class="report-list"><div class="report-list-head" aria-hidden="true"><span class="report-heading">Report</span><span>Repository</span><span>Uploaded by</span><span>Date</span><span class="size-heading">Size</span><span>Visibility</span><span class="actions-heading">Actions</span></div><ul class="reports">${e.map(e=>this._row(e))}</ul></div>`}_row(e){let t=h(e.filename),n=e.analyzer??e.source??e.producer??`default`,r=Ve[n]??Ve.default,i=e.repoEmbedded!==!0&&e.canChangeRepo!==!1,a=e.repoEmbedded===!0||e.repoId!=null,o=Fi(e),s=e.confirmedOffered===!0||e.confirmedDefault===!0;return y`<li class="${`report${e.visible===!1?` content-hidden`:``}`}"><div class="report-main"><span class="report-mark" aria-hidden="true">${g(r)}</span> <span class="report-name" data-tooltip-truncated data-tooltip="${t}">${t}</span> <span class="report-location" data-tooltip-truncated data-tooltip="${o}">${o}</span> <span class="report-meta report-uploader" data-tooltip-truncated data-tooltip="${e.uploadedByLogin??`Uploader removed`}">${e.uploadedByLogin??`Uploader removed`}</span> <span class="report-meta report-date">${Pi(e)}</span> <span class="report-meta report-size">${Ke(e.byteSize)}</span> <span class="${`status ${e.visible?`visible`:`hidden`}`}">${e.visible?`Visible`:`Hidden`}</span> <span class="report-actions">${i?y`<button type="button" class="action" data-tooltip="Set repository location" aria-label="${`Set location for ${t}`}" @click="${()=>this._openLocation(e)}">${m(`repo`)}</button>`:y`<span class="action-spacer"></span>`} ${s?y`<button type="button" class="action opening" aria-pressed="${e.confirmedDefault===!0?`true`:`false`}" aria-label="${`Open ${t} on Confirmed by default`}" data-tooltip="${e.confirmedDefault?`Opens on Confirmed by default. Click to open as detected`:`Open on Confirmed by default, hiding findings the pass did not confirm`}" ?disabled="${e.canChangeRepo===!1||this._openingBusy===e.id}" @click="${()=>{this._setOpening(e,!e.confirmedDefault)}}">${m(`confirmed`)}</button>`:y`<span class="action-spacer"></span>`} <button type="button" class="action" aria-label="${`Preview ${t}`}" aria-expanded="${this._preview===e.id}" @click="${()=>{this._togglePreview(e)}}">${m(`preview`)}</button> <button type="button" class="action" data-tooltip="${e.visible?`Hide from teams`:a?`Make visible to teams`:`Assign a repository before publishing`}" aria-label="${`${e.visible?`Hide`:`Make visible`} ${t}`}" ?disabled="${e.canChangeRepo===!1||!a&&!e.visible}" @click="${()=>{this._setVisible(e,!e.visible)}}">${m(e.visible?`hide`:`show`)}</button> <a class="action" aria-label="${`Download ${t}`}" href="${`/api/admin/reports/${encodeURIComponent(e.id)}`}">${m(`download`)}</a> <button type="button" class="action danger" aria-label="${`Delete ${t}`}" ?disabled="${e.canChangeRepo===!1}" @click="${()=>this._delete(e)}">${mi}</button></span></div>${this._preview===e.id?y`<div class="preview">${this._previewLoading===e.id?y`<span class="preview-loading">Loading preview…</span>`:y`<pre>${this._previewText??``}</pre>`}</div>`:b} ${this._locationId===e.id?this._locationEditor(e):b}</li>`}_cancelPreview(){this._previewRequest?.abort(),this._previewRequest=null,this._preview=null,this._previewLoading=null,this._previewText=``}async _togglePreview(e){let t=this._preview===e.id;if(this._cancelPreview(),t)return;let n=`report-preview:${e.id}`;this._preview=e.id,this._previewText=this.appState.read(n)??``,this._previewLoading=this.appState.read(n)===void 0?e.id:null,await this._read(`_previewRequest`,n,`report preview`,async t=>{let n=await l(`/api/admin/reports/${encodeURIComponent(e.id)}`,{credentials:`same-origin`,signal:t});if(!n.ok)throw Error(`HTTP ${n.status}`);let r=await n.text();return r.slice(0,4e3)+(r.length>4e3?`
16
+ `,si=Xn(`/api/admin/repositories/aliases`,{"alias-exists":`An alias already exists for this old repository and path. Edit that row instead.`,"bad-old-repo":`Enter the old repository as owner/name or a GitHub URL.`,"bad-directory":`Enter repository directories without parent segments, backslashes, or surrounding whitespace.`,"bad-repo":`Choose a connected repository.`,"no-alias":`This alias was removed. Refresh the list and try again.`}),ci=class extends x{static properties={repositories:{attribute:!1},_edit:{state:!0},_busy:{state:!0}};static styles=[v(r),v(oi)];static collection=[`repository-aliases`,`repository aliases`,e=>si(``,{signal:e})];constructor(){super(),this._edit=null,this._busy=!1}updated(e){e.has(`repositories`)&&e.get(`repositories`)!==void 0&&(this.appState.invalidate([`repository-aliases`]),this._load())}_start(e=null){this._error=null,this._edit=e?{...e}:{id:null,oldRepo:``,oldPath:``,repoId:null,newPath:``}}async _mutate(e,t,n){if(!this._busy&&this._csrf&&this._role===`admin`){this._busy=!0,this._error=null;try{await this.appState.mutate(()=>si(t?`/${encodeURIComponent(t)}`:``,{method:e,headers:{"content-type":`application/json`,"x-csrf-token":this._csrf},...n?{body:JSON.stringify(n)}:{}}),[`repository-aliases`,`workspace-import`]),this._edit=null,await this._load()}catch(e){this._error=String(e?.message??e)}finally{this._busy=!1}}}_save(){let{id:e,...t}=this._edit;return this._mutate(e?`PATCH`:`POST`,e,t)}_field(e,t,n){return y`<td><input type="text" aria-label="${t}" placeholder="${n}" .value="${this._edit[e]}" ?disabled="${this._busy}" @input="${t=>{this._edit={...this._edit,[e]:t.target.value}}}"></td>`}_editor(){let e=(this._data?.repos??[]).filter(e=>e.active!==!1).map(e=>({value:e.repoId,label:e.fullName}));return y`<tr>${this._field(`oldRepo`,`Old repository`,`owner/repository`)}${this._field(`oldPath`,`Old path`,`Repository root`)}<td><repository-selector label="New repository" placeholder="Choose repository…" .options="${e}" .value="${this._edit.repoId}" ?disabled="${this._busy}" @repository-change="${e=>{this._edit={...this._edit,repoId:e.detail.value}}}"></repository-selector></td>${this._field(`newPath`,`New path`,`Repository root`)}<td class="actions"><button type="button" class="btn" ?disabled="${this._busy||!this._edit.oldRepo.trim()||this._edit.repoId==null}" @click="${()=>{this._save()}}">${this._busy?`Saving…`:`Save`}</button> <button type="button" class="btn" ?disabled="${this._busy}" @click="${()=>{this._edit=null,this._error=null}}">Cancel</button></td></tr>`}render(){let e=this._data?.aliases??[],t=this._data?.repos??[],n=e=>{let n=t.find(t=>t.repoId===e);return`${n?.fullName??`Removed repository`}${n?.active===!1?` (inactive)`:``}`};return y`<section aria-label="Repository aliases"><div class="page-intro"><p class="intro">Map repository locations when importing new reports and bundles.</p><button type="button" class="btn" ?disabled="${this._busy||this._edit!=null||!this._data}" @click="${()=>this._start()}">Add alias</button></div>${C(this._error)}<div aria-busy="${this._loading}">${this._data===null?this._error?y`<button type="button" class="btn" @click="${()=>{this._load()}}">Try again</button>`:S(`Loading repository aliases…`):y`<div class="alias-table"><table><thead><tr><th>Old repository</th><th>Old path</th><th>New repository</th><th>New path</th><th><span class="sr-only">Actions</span></th></tr></thead><tbody>${e.map(e=>this._edit?.id===e.id?this._editor():y`<tr><td>${e.oldRepo}</td><td class="mono">${e.oldPath||`/`}</td><td>${n(e.repoId)}</td><td class="mono">${e.newPath||`/`}</td><td class="actions"><button type="button" class="btn" ?disabled="${this._busy||this._edit!=null}" @click="${()=>this._start(e)}">Edit</button> <button type="button" class="btn" ?disabled="${this._busy||this._edit!=null}" @click="${()=>{this._mutate(`DELETE`,e.id)}}">Delete</button></td></tr>`)} ${this._edit?.id===null?this._editor():b} ${e.length===0&&!this._edit?y`<tr><td colspan="5" class="empty">No repository aliases yet.</td></tr>`:b}</tbody></table></div>`}</div></section>`}};customElements.define(`managed-repository-aliases`,ci);function li(e,t){return y`<span class="avatar" aria-hidden="true"><span>${(t?.[0]??`?`).toUpperCase()}</span> ${s()?b:y`<img alt="" src="${`/api/avatar/${encodeURIComponent(e)}`}" @error="${e=>e.currentTarget.classList.add(`broken`)}">`}</span>`}function ui(e,t){return y`<span class="avatar" aria-hidden="true"><span>${(t?.[0]??`?`).toUpperCase()}</span>${!e||s()?b:qe(e,y`<img alt="" loading="lazy" decoding="async" src="${`/api/avatar/${encodeURIComponent(e)}`}" @error="${e=>{e.currentTarget.hidden=!0}}">`)}</span>`}var di=[`triage`,`review`,`visibility`,`upload`,`repository`,`access`,`delete`],fi=e=>{let t=e??`activity`;return y`<span class="${`kind ${e??``}`}">${t[0].toUpperCase()}${t.slice(1)}</span>`},pi=g(Ye),mi=g(Xe),hi=y`<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" aria-hidden="true"><path d="m4 4 8 8m0-8-8 8"/></svg>`,B=y`<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" aria-hidden="true"><path d="M8 3v10M3 8h10"/></svg>`,gi=m(`repo`),_i={admin:[`Admin`,`Manage workspace access and teams`],manage:[`Manager`,`Manage content and triage within team access`],triage:[`Triage`,`Review and triage findings`],view:[`Viewer`,`Read-only access`],none:[`No access`,`No workspace access`]};function vi(e,t,n,r){return y`<div class="breadcrumb"><button type="button" class="breadcrumb-manage" @click="${()=>p(`manage`)}">Manage</button> <span class="breadcrumb-separator" aria-hidden="true">›</span> <button type="button" class="breadcrumb-manage" aria-label="${t}" @click="${n}">${e}</button> <span class="breadcrumb-separator" aria-hidden="true">›</span> ${r?y`<h1 class="breadcrumb-current">${r}</h1>`:b}</div>`}var yi=[[`manage-bundles`,`Bundles`,`Keep source archives ready for review.`,`bundle`],[`manage-scans`,`Scans`,`Run and monitor scans from stored bundles.`,`scan`],[`manage-reports`,`Reports`,`Review, publish, and organize findings.`,`report`]],bi=[[`manage-repos`,`Repositories`,`Connect sources and manage repository settings.`,`repo`],[`admin-users`,`Users`,`Manage accounts, roles, and workspace access.`,`users`],[`manage-teams`,`Teams`,`Bring people and repositories together.`,`team`]];function xi([e,t,n,r]){return y`<button type="button" class="${`page page-${r}`}" @click="${()=>p(e)}"><span class="page-top"><span class="page-icon" aria-hidden="true">${m(r)}</span><strong class="page-title">${t}</strong><span class="arrow" aria-hidden="true">${m(`arrow`)}</span></span> <span class="page-copy"><span>${n}</span></span></button>`}var Si=class extends x{static view=`manage`;static styles=[v(Nr),v(r)];render(){return y`<div class="wrap">${this._nav()}<h1 class="sr-only">Manage</h1>${this._role==null?y`<p class="msg" role="status">Loading management pages…</p>`:y`<section class="home-section" aria-labelledby="content-heading"><div class="section-heading"><h2 id="content-heading">Content & activity</h2><span>From source to findings</span></div><div class="pages">${yi.filter(([e])=>e!==`manage-scans`||[`admin`,`manage`].includes(this._role)).map(xi)}</div></section>${this._role===`admin`?y`<section class="home-section" aria-labelledby="workspace-heading"><div class="section-heading"><h2 id="workspace-heading">Workspace & access</h2><span>Sources, people, and permissions</span></div><div class="pages workspace-pages">${bi.map(xi)}</div></section>`:b} <button type="button" class="history-link" @click="${()=>p(`manage-history`)}"><span class="page-icon" aria-hidden="true">${m(`history`)}</span> <span class="page-copy"><strong>Workspace history</strong><span>Follow activity and triage changes across your workspace.</span></span> <span class="history-cta">View history ${m(`arrow`)}</span></button>`}</div>`}};customElements.define(`managed-admin-home`,Si);var Ci=class extends x{static view=`manage-history`;static properties={_page:{state:!0},_history:{state:!0},_total:{state:!0},_filter:{state:!0},_query:{state:!0},_repo:{state:!0},_actor:{state:!0},_options:{state:!0}};static styles=[v(Pr),v(r)];constructor(){super(),Object.assign(this,{_history:null,_total:0,_page:1,_filter:`all`,_query:``,_repo:``,_actor:``,_options:{repos:[],users:[]}}),this._searchTimer=null,this._onActorFilter=e=>{let t=e.detail?.actor;if(typeof t!=`string`)return;let n=t.startsWith(`user:`)||t.startsWith(`legacy:`);this._query=n?``:t,this._filter=`all`,this._repo=``,this._actor=n?t:``,this._load()}}connectedCallback(){super.connectedCallback(),document.addEventListener(`managed-history-filter`,this._onActorFilter)}disconnectedCallback(){clearTimeout(this._searchTimer),document.removeEventListener(`managed-history-filter`,this._onActorFilter),super.disconnectedCallback()}async _load(e=1){clearTimeout(this._searchTimer),this._error=null;let t=this._filter,n=this._query.trim(),r=this._actor,i=this._repo,a=`history:${JSON.stringify([e,t,n,i,r])}`;await this._loadCollection(a,`history`,a=>$n(a,e,t,n,i,r),e=>{this._history=e.history,this._total=e.total,this._page=e.page,this._options=e.filters??{repos:[],users:[]}})}_search(e){this._query=e,clearTimeout(this._searchTimer),this._loadRequest?.abort(),this._loadRequest=null,this._loading=!0,this._searchTimer=setTimeout(()=>{this._load()},250)}_setRepo(e){return this._repo=e,this._load()}_setActor(e){return this._actor=e,this._load()}_clearContext(){return this._repo=``,this._actor=``,this._load()}_contextFilters(){let e=this._options.repos,t=this._options.users??[],n=[{value:``,label:`All repositories`,special:!0,reset:!0},...this._repo&&!e.includes(this._repo)?[{value:this._repo,label:this._repo}]:[],...e.map(e=>({value:e,label:e}))];return y`<repository-selector label="Filter history by repository" .options="${n}" .value="${this._repo}" @repository-change="${e=>{this._setRepo(e.detail.value)}}"></repository-selector><user-selector label="Filter history by user" reset-label="All users" placeholder="${this._actor?`Selected user`:`All users`}" .users="${t}" .value="${this._actor}" @user-change="${e=>{this._setActor(e.detail.value)}}"></user-selector><button type="button" class="btn" aria-label="Clear repository and user filters" ?disabled="${!this._repo&&!this._actor}" @click="${()=>{this._clearContext()}}">Clear selection</button>`}render(){let e=this._history??[],t=this._page,n=(t-1)*100;return y`<div class="wrap">${this._nav()}<h1 class="sr-only">History</h1><div class="page-intro"><p class="intro">${this._role===`admin`?`Uploads, builds, access changes, repository changes, deletions, triage, and package reviews.`:`Bundle, report, triage, and package review history within your team access.`}</p><span class="result-count">${this._history?this._total:`…`} entries</span></div><div class="toolbar" role="search"><input type="search" maxlength="500" aria-label="Search history" placeholder="Search history…" .value="${this._query}" @input="${e=>this._search(e.target.value)}"> ${this._kindFilter()} ${this._contextFilters()} <button type="button" class="btn" ?disabled="${this._loading}" @click="${()=>this._load(t)}">Refresh</button></div>${this._error?y`<p class="msg error" role="alert">Couldn’t load history: ${this._error} <button type="button" class="btn" @click="${()=>this._load()}">Retry</button></p>`:b} ${this._list(this._history,`Loading history…`,()=>e.length===0?y`<div class="history"><p class="empty">${this._query.trim()||this._filter!==`all`||this._repo||this._actor?`No activity matches your filters.`:`No history available yet.`}</p></div>`:y`<div class="history" aria-label="Workspace history"><div class="history-head" aria-hidden="true"><span>Type</span><span>Activity</span><span>Repository / report / finding</span><span>Time</span></div>${e.map(e=>this._row(e))}</div>`)} ${this._total>100?y`<nav class="pagination" aria-label="History pages"><span role="status">${n+1}–${Math.min(n+100,this._total)} of ${this._total} entries</span><button type="button" class="btn" ?disabled="${this._loading||t===1}" @click="${()=>this._changePage(t-1)}">Previous</button><span>Page ${t} of ${Math.ceil(this._total/100)}</span><button type="button" class="btn" ?disabled="${this._loading||n+100>=this._total}" @click="${()=>this._changePage(t+1)}">Next</button></nav>`:b}</div>`}_kindFilter(){let e=di.filter(e=>e!==`access`||this._role===`admin`);return y`<select class="kind-filter" aria-label="Filter history by type" .value="${this._filter}" @change="${e=>{this._filter=e.target.value,this._load()}}"><button type="button"><selectedcontent></selectedcontent><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><path d="m4 6 4 4 4-4"/></svg></button><option value="all" ?selected="${this._filter===`all`}">All activity</option>${e.map(e=>y`<option value="${e}" ?selected="${this._filter===e}">${fi(e)}</option>`)}</select>`}async _changePage(e){await this._load(e),await this.updateComplete,this.renderRoot.querySelector(`.manage-list`)?.scrollTo({top:0})}_row(e){let t=[e.repo??e.repository,e.report,e.finding].filter(Boolean).join(` · `),n=e.actor??e.user??null,r=e.actorName?.trim()||n||`Unknown user`,i=e.action??`updated workspace data`;return y`<div class="row">${fi(e.kind)}<span class="activity">${ui(e.actorId,r)}<span class="activity-description" data-tooltip-truncated data-tooltip="${`${r} ${i}`}"><strong class="actor" data-tooltip="${n&&n!==r?`@${n} on GitHub`:b}">${r}</strong> <span class="action">${i}</span></span></span><span class="detail" data-tooltip-truncated data-tooltip="${t}">${t||`—`}</span><span class="history-time">${Ti(e.at)}</span></div>`}};customElements.define(`managed-admin-history`,Ci);var wi=e=>{if(e==null||e===``)return null;let t=new Date(Number(e));return Number.isNaN(t.getTime())?null:t};function Ti(e){let t=wi(e);return t?y`<time datetime="${t.toISOString()}">${t.toLocaleDateString(void 0,{year:`numeric`,month:`short`,day:`numeric`})}</time><span>${t.toLocaleTimeString(void 0,{hour:`numeric`,minute:`2-digit`})}</span>`:y`<span>Unknown</span>`}var Ei=e=>e?.lastActivityAt??e?.lastActivity??e?.lastWriteAt??e?.lastActiveAt,Di=class extends x{static view=`admin-users`;static properties={_query:{state:!0},_users:{state:!0},_teams:{state:!0}};static styles=[v(Fr),v(r)];static collection=[`users`,`users`,e=>Promise.all([er(e),Or(e)])];constructor(){super(),Object.assign(this,{_users:null,_query:``,_teams:null})}_show([e,t]){this._users=e,this._teams=Array.isArray(t?.teams)?t.teams:[]}_memberships(e){return(this._teams??[]).flatMap(t=>{let n=t.members?.find(t=>t.userId===e.id);return n==null?[]:[{team:t,member:n}]})}_filteredUsers(){let e=this._query.trim().toLocaleLowerCase();return(this._users??[]).filter(t=>[t.name,t.login,t.role,...this._memberships(t).map(({team:e})=>e.name)].filter(Boolean).join(` `).toLocaleLowerCase().includes(e))}render(){let e=this._filteredUsers();return y`<div class="wrap">${this._nav()}<h1 class="sr-only">Users</h1><div class="page-intro"><p class="intro">Manage workspace access and roles.</p></div><div class="collection-toolbar" role="search"><input type="search" aria-label="Search users" placeholder="Search by name, username, or team…" .value="${this._query}" @input="${e=>{this._query=e.target.value}}"><span class="result-count" role="status">${this._users&&this._query.trim()?`${e.length} matching out of `:``}${this._users?.length??`…`} users</span></div>${C(this._error&&`Couldn't load users: ${this._error}`)} ${this._list(this._users,`Loading users…`,()=>this._directory(e))}</div>`}_directory(e){return this._users.length===0?y`<p class="msg">No users yet.</p>`:e.length===0?w(`No matching users`,`Try another name, username, or team.`):y`<div class="directory"><div class="list-head" aria-hidden="true"><span>Account</span><span>Team access</span><span>Last seen</span><span>Last activity</span><span>Role</span><span></span></div><ul class="users">${e.map(e=>this._row(e))}</ul></div>${this._users.some(e=>e.id===this._me)?y`<p class="self-note ui-hint">Your own role can only be changed by another admin.</p>`:b}`}_row(e){let t=e.id===this._me,n=this._memberships(e),r=wi(Ei(e)),i=wi(e.lastSeenAt);return y`<li><span class="person">${li(e.id,e.login)} <span class="who"><span class="name"><span class="name-text">${e.name||e.login}</span>${t?y`<span class="you">You</span>`:b}</span> <span class="login">@${e.login}</span> </span></span><span class="memberships">${Le(e.role,`manage`)?y`<span class="team-access"><strong class="team-access-role">${e.role===`admin`?`All reports`:`Owned and team reports`}</strong><span class="team-perms"><span class="permission-granted">+ Deps</span><span class="permission-granted">+ Security</span></span></span>`:n.length===0?y`<span class="no-team">No team access</span>`:n.map(({team:e,member:t})=>y`<span class="team-access"><strong>${m(`team`)}<span>${e.name}</span></strong><span class="team-perms">${[`dependencies`,`security`].map(e=>y`<span class="${t[e]===!0?`permission-granted`:`permission-denied`}">${t[e]===!0?`+`:`−`} ${e===`dependencies`?`Deps`:`Security`}</span>`)}</span></span>`)} </span><span class="last-seen" aria-label="${i?`Last seen ${i.toLocaleString()}`:`Unknown`}">${Ti(e.lastSeenAt)}</span> <button type="button" class="activity-link" aria-label="${`Show activity by ${e.login}`}" @click="${()=>p(`manage-history`,{actor:`user:${e.id}`})}"><span class="last-activity" aria-label="${`Last activity ${r?r.toLocaleString():`Unknown`}`}">${Ti(Ei(e))}</span></button> <span class="access"><select class="role" ?disabled="${t}" aria-label="${`Change ${e.login}\u2019s role`}" aria-description="${_i[e.role]?.[1]??``}" @change="${t=>this._changeRole(e,t.target.value,t.target)}">${Fe.map(t=>y`<option value="${t}" ?selected="${t===e.role}">${_i[t][0]}</option>`)}</select> </span><span class="view-as">${t?b:y`<button type="button" class="icon-btn" aria-label="${`View as ${e.login}`}" data-tooltip="See the app as this user" @click="${t=>{this._viewAs(e,t.currentTarget)}}">${m(`show`)}</button>`}</span></li>`}async _viewAs(e,t){t.disabled=!0;try{await _e(e.id,this._csrf)}catch(n){t.disabled=!1,this.appState.notify(`Couldn't view as @${e.login}: ${n?.message??n}`)}}async _changeRole(e,t,n){let r=e.role;if(t!==r){try{await this.appState.mutate(()=>tr(e.id,t,this._csrf),[`users`,`teams`,`reports`,`history`]),e.role=t,await this._load()}catch(e){console.warn(`admin: set role failed:`,e),n.value=r}this.requestUpdate()}}};customElements.define(`managed-admin-users`,Di);var Oi=e=>!e||e.mode===`exclude`&&e.paths.length===0?{mode:`all`,paths:[]}:{mode:e.mode,paths:[...e.paths].toSorted()},ki=e=>e.mode===`all`?{mode:`exclude`,paths:[]}:{mode:e.mode,paths:e.paths},Ai={private:y`<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="7" width="10" height="7" rx="1"/><path d="M5 7V5a3 3 0 0 1 6 0v2"/></svg>`,public:y`<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="8" cy="8" r="6"/><path d="M2.5 8h11M8 2c1.5 1.7 2.2 3.7 2.2 6S9.5 12.3 8 14c-1.5-1.7-2.2-3.7-2.2-6S6.5 3.7 8 2Z"/></svg>`},ji=class extends x{static view=`manage-repos`;static properties={_publicRepoOpen:{state:!0},_publicRepository:{state:!0},_publicRepoError:{state:!0},_addingPublic:{state:!0},_actionError:{state:!0},_scope:{state:!0},_showAll:{state:!0},_query:{state:!0},_organization:{state:!0},_busy:{state:!0},_connectingApp:{state:!0},_detail:{state:!0},_aliases:{state:!0},_impact:{state:!0},_impactLoading:{state:!0},_removeOpen:{state:!0},_acknowledge:{state:!0},_deleteTriage:{state:!0},_confirmName:{state:!0},_reviewDraft:{state:!0}};static styles=[v(Ir),v(r)];constructor(){super(),Object.assign(this,{_publicRepoOpen:!1,_publicRepository:``,_publicRepoError:null,_addingPublic:!1,_actionError:null,_scope:`connected`,_showAll:!1,_query:``,_organization:null,_loading:!0,_busy:null,_connectingApp:!1,_detail:null,_aliases:!1,_impact:null,_impactLoading:!1,_impactFresh:!1,_impactRequest:null}),this._resetRemoval()}disconnectedCallback(){super.disconnectedCallback(),this._impactRequest?.abort()}_resetRemoval(e=!1){Object.assign(this,{_removeOpen:e,_acknowledge:!1,_deleteTriage:!1,_confirmName:``})}async _load(e=!1){this._error=null;let{_scope:t,_showAll:n}=this;await this._loadCollection(`repos:${JSON.stringify([t,n])}`,`repositories`,r=>nr(t,n,e,r),e=>{this._data=e,this._organization=this._repositoryChoices().activeFacet})}_open(e){this._impactRequest?.abort(),Object.assign(this,{_publicRepoOpen:!1,_scope:e,_showAll:!1,_query:``,_organization:null,_detail:null,_aliases:!1,_impact:null,_data:null,_actionError:null}),this._resetRemoval(),this._load()}_setShowAll(e){Object.assign(this,{_showAll:e,_organization:null,_data:null}),this._load()}_search(e){this._query=e}_repositoryChoices(){let e=(this._data?.repositories??[]).map(e=>({value:e.id,label:e.fullName,repo:e}));return ze(e,this._query,this._organization,{includeSingletonOrganizations:!0})}_back(e=null){return vi(`Repositories`,`Back to repositories`,()=>{this._detail?(this._impactRequest?.abort(),this._detail=null,this._actionError=null):this._aliases?this._aliases=!1:this._open(`connected`)},e)}_openDetail(e){let t=`repo-impact:${e.id}`;Object.assign(this,{_detail:e,_reviewDraft:null,_actionError:null,_impact:this.appState.read(t)??null,_impactFresh:!1,_impactLoading:!0}),this._resetRemoval(),this._read(`_impactRequest`,t,`repository data`,t=>cr(e.id,t),{apply:e=>{this._impact=e},answered:()=>{this._impactFresh=!0},settled:()=>{this._impactLoading=!1},failed:e=>{this._impact||(this._actionError=`Couldn't load repository data: ${e?.message??e}`)}})}render(){if(this._detail)return this._detailPage(this._detail);if(this._aliases)return this._aliasesPage();let e=this._scope===`connected`,t=e?`Repositories`:`Add ${this._scope} repository`,n=this._repositoryChoices();return y`<div class="wrap">${this._nav()} ${e?y`<h1 class="sr-only">${t}</h1>`:this._back(t)}<div class="page-intro"><p class="intro">${e?`Manage connected repositories and their settings.`:this._scope===`installed`?this._showAll?`Showing all repositories the GitHub App can read.`:`Showing installed repositories you can access on GitHub.`:`Choose a public repository your GitHub account is involved with.`}</p>${e?y`<div class="repository-actions"><button type="button" class="btn" @click="${()=>this._open(`installed`)}">${Ai.private} Add installed repository</button> <button type="button" class="btn" @click="${()=>this._open(`public`)}">${Ai.public} Add your public repository</button> ${this._role===`admin`&&this._data?.canAddAnyPublicRepository?y`<button type="button" class="btn" aria-expanded="${this._publicRepoOpen}" @click="${()=>this._openPublicRepository()}">${Ai.public} Add a public repository</button>`:b}</div>`:b}</div>${!e&&this._scope===`installed`?y`<div class="access-note"><p class="ui-hint">Installed repositories are readable through the GitHub App. Install it on a repository or organization to make it available here.</p><span class="access-action">${this._data?.installUrl?y`<a class="btn" href="${this._data.installUrl}" target="_blank" rel="noopener noreferrer">Configure GitHub access</a>`:y`<button type="button" class="btn" disabled="disabled">Configure GitHub access</button>`}</span></div>`:b}<div class="toolbar"><label class="search"><input type="search" aria-label="${e?`Search connected repositories`:`Search ${this._scope} repositories`}" placeholder="Search by repository or owner…" .value="${this._query}" @input="${e=>this._search(e.target.value)}"></label> ${this._scope===`installed`?y`<label class="show-all"><input type="checkbox" role="switch" .checked="${this._showAll}" @change="${e=>this._setShowAll(e.target.checked)}"><span>Show all</span></label><label class="show-all-paper"><input type="checkbox" .checked="${this._showAll}" @change="${e=>this._setShowAll(e.target.checked)}"><span>Show all</span></label>`:b} ${e?y`<span class="result-count" role="status">${this._data&&(this._query.trim()||n.activeFacet!=null)?`${n.count} ${n.count===1?`repository`:`repositories`} out of `:``}${this._data?.connectedCount??`…`} connected</span>`:y`<button type="button" class="btn" ?disabled="${this._loading}" @click="${()=>{this._load(!0)}}">Refresh</button>`}</div>${e&&this._publicRepoOpen&&this._role===`admin`&&this._data?.canAddAnyPublicRepository?this._publicRepositoryForm():b} ${C(this._actionError)} ${this._error?y`<p class="msg error" role="alert">Couldn't load repositories: ${this._error}</p><button type="button" class="btn" @click="${()=>{this._load()}}">Try again</button>`:b} ${!e&&this._data?y`<p class="repository-count" role="status">${n.count}${n.count===n.total?``:` of ${n.total}`} ${n.total===1?`repository`:`repositories`}</p>`:b}<div class="manage-list"><div aria-busy="${this._loading}">${this._body(n)}</div>${e&&this._role===`admin`?y`<div class="repository-pages"><button type="button" class="btn" @click="${()=>{this._publicRepoOpen=!1,this._actionError=null,this._aliases=!0}}">Aliases</button></div>`:b}</div></div>`}_aliasesPage(){return y`<div class="wrap">${this._nav()} ${this._back(`Aliases`)}<div class="manage-list has-intro"><managed-repository-aliases .session="${this.session}" .repositories="${this._data?.repositories}"></managed-repository-aliases></div></div>`}_body(e){if(!this._data)return this._error?b:S(`Loading repositories…`);let t=this._scope;return y`${this._data.tokenMissing&&!this._showAll&&t!==`connected`?y`<p class="msg">Log out and back in to refresh your GitHub membership access.</p>`:b}<div class="repository-browser">${e.showFacets?y`<nav class="organization-list" aria-label="Filter by organization"><button type="button" class="organization" aria-pressed="${e.activeFacet==null}" @click="${()=>{this._organization=null}}"><span class="organization-name">All organizations</span><span class="organization-count">${e.total}</span></button> ${e.facets.map(t=>y`<button type="button" class="organization" aria-pressed="${e.activeFacet===t.value}" @click="${()=>{this._organization=t.value}}"><span class="organization-name" data-tooltip-truncated data-tooltip="${t.name}">${t.name}</span><span class="organization-count">${t.count}</span></button>`)}</nav>`:b}<div class="repo-results">${e.sections.map(e=>y`<section class="repo-group" aria-label="${e.label??`Repositories`}">${e.label?y`<h2 class="owner-head"><span class="owner-icon" aria-hidden="true">${e.label[0]??`?`}</span>${e.label}</h2>`:b}<ul class="repos">${e.options.map(t=>this._row(t.repo,e.organization?t.name:t.label))}</ul></section>`)} ${e.count?b:w(e.total?`No matching repositories`:t===`connected`?`No connected repositories yet`:`No ${t} repositories available`,e.total?`Try a different search or organization.`:t===`connected`?`Add an installed or public repository to get started.`:t===`installed`?this._showAll?`Install the GitHub App, then refresh this list.`:`No installed repositories match your GitHub access. Turn on Show all to browse every installation.`:`Public repositories associated with your GitHub account will appear here.`)}</div></div>`}_openPublicRepository(){this._publicRepoOpen=!0,this._publicRepoError=null,this.updateComplete.then(()=>this.renderRoot?.querySelector(`#public-repository`)?.focus())}_publicRepositoryForm(){return y`<form class="public-repository-form" aria-label="Add a public repository" @submit="${e=>{e.preventDefault(),this._addPublicRepository()}}"><label class="confirm-field" for="public-repository"><span>Public GitHub repository</span> <input id="public-repository" class="confirm-name" type="text" placeholder="owner/repo or https://github.com/owner/repo" autocomplete="off" required .value="${this._publicRepository}" ?disabled="${this._addingPublic}" @input="${e=>{this._publicRepository=e.target.value}}"></label><div class="dialog-actions"><button type="button" class="btn" ?disabled="${this._addingPublic}" @click="${()=>{this._publicRepoOpen=!1}}">Cancel</button><button type="submit" class="btn" ?disabled="${this._addingPublic||!this._publicRepository.trim()}">${this._addingPublic?`Adding…`:`Add repository`}</button></div>${C(this._publicRepoError)}</form>`}async _addPublicRepository(){if(!this._addingPublic&&this._publicRepository.trim()){this._addingPublic=!0,this._publicRepoError=null;try{await this.appState.mutate(()=>sr(this._publicRepository.trim(),this._csrf),[`repos`,`reports`,`bundles`,`teams`,`users`,`history`,`scan-sources`]),this._publicRepoOpen=!1,this._publicRepository=``,await this._load()}catch(e){this._publicRepoError=e?.message??String(e)}finally{this._addingPublic=!1}}}_row(e,t){let n=`${this._accessLabel(e)}${this._scope===`connected`&&e.active===!1?` · Deactivated`:``}`,r=y`${gi}<span class="repo-copy"><span class="repo-name">${t}</span><span class="repo-meta">${n}</span></span>`;return this._scope===`connected`?y`<li class="repo-item"><button type="button" class="repo-row" aria-label="${`Manage ${e.fullName}`}" @click="${()=>this._openDetail(e)}">${r}<span class="repo-code-slot" aria-hidden="true"></span><svg class="arrow" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" aria-hidden="true"><path d="m6 4 4 4-4 4"/></svg></button>${e.active===!1?b:y`<a class="repo-code" href="${rt({view:`repository-code`,repoId:e.id})}" aria-label="${`Open ${e.fullName}'s code`}" @click="${t=>this._openCode(t,e)}">${m(`code`)}</a>`}</li>`:y`<li class="repo-row">${r} ${e.selected?y`<span class="connected"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><path d="m3 8 3 3 7-7"/></svg>Connected</span>`:e.private&&!e.installed?y`<span class="repo-meta">Needs App access</span>`:y`<button type="button" class="btn" aria-label="${`Add ${e.fullName}`}" ?disabled="${this._busy!=null}" @click="${()=>{this._setActive(e,!0)}}">${this._busy===e.id?`Adding…`:`Add`}</button>`}</li>`}_openCode(e,t){e.button!==0||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||(e.preventDefault(),this._emit(`managed-repository-code-open`,{repoId:t.id}))}_accessLabel(e){let t=e.visibility===`public`?`Public`:e.visibility===`internal`?`Internal`:e.private?`Private`:null,n=e.installed?`GitHub App`:`GitHub`;return t?`${t} \xB7 ${n}`:n}async _act(e,t,n){if(this._busy==null){this._busy=e.id,this._actionError=null;try{await n()}catch(e){this._actionError=`Couldn't ${t}: ${e?.message??e}`}finally{this._busy=null}}}_patchRepo(e,t){this._detail?.id===e&&(this._detail={...this._detail,...t}),this._data&&={...this._data,repositories:this._data.repositories.map(n=>n.id===e?{...n,...t}:n)}}async _connectApp(e){this._busy!=null||e.installed||(this._connectingApp=!0,await this._act(e,`connect ${e.fullName}`,async()=>{let t=await this.appState.mutate(()=>ur(e.id,this._csrf),[`repos`,`history`,`scan-sources`]);if(this.isConnected){if(!t.connected){globalThis.location.assign(t.installUrl);return}this._patchRepo(e.id,{installed:!0}),await this._load()}}),this._connectingApp=!1)}_detailPage(e){let t=e.active!==!1,n=this._impact?.reports??[],r=this._impact?.bundles??[];return y`<div class="wrap">${this._nav()}<div class="head">${this._back()}<h1>${e.fullName}</h1></div><p class="intro ui-hint">Repository settings and stored data.</p>${C(this._actionError)}<div class="manage-list repository-detail"><section class="section" aria-label="Repository connection"><h2>Connection</h2><div class="settings-row"><div class="settings-copy"><strong>${this._accessLabel(e)}</strong><p>${t?`Active for new scans and uploads.`:`Deactivated. Stored reports and bundles are retained.`}</p></div><span class="${`status-line ${t?``:`inactive`}`}">${t?`Active`:`Deactivated`}</span> ${e.installed?b:y`<button type="button" class="btn connect-app" aria-label="${`Connect GitHub App to ${e.fullName}`}" ?disabled="${this._busy!=null}" @click="${()=>{this._connectApp(e)}}">${this._connectingApp&&this._busy===e.id?`Connecting…`:`Connect GitHub App`}</button>`} ${e.htmlUrl?y`<a class="btn" href="${e.htmlUrl}" target="_blank" rel="noopener noreferrer">View on GitHub</a>`:b}</div><div class="settings-row"><div class="settings-copy"><strong>${t?`Deactivate repository`:`Reactivate repository`}</strong><p>${t?`Pause new scans while preserving all stored data and attachments.`:`Make this repository available for new scans and bundle attachments again.`}</p></div><button type="button" class="btn" ?disabled="${this._busy!=null}" @click="${()=>{this._setActive(e,!t)}}">${this._busy===e.id&&!this._connectingApp?t?`Deactivating…`:`Reactivating…`:t?`Deactivate`:`Reactivate`}</button></div></section>${this._dependencyReviewSection(e)}<section class="data-section" aria-label="Stored repository data"><h2>Stored data</h2><div class="dialog-data" aria-busy="${this._impactLoading}">${[[`Reports`,n],[`Bundles`,r]].map(([t,n])=>y`<section><h3>${t} (${this._impact==null?`…`:n.length})</h3>${this._impactLoading&&this._impact==null?y`<p class="data-empty" role="status">Loading ${t.toLowerCase()}…</p>`:this._impact==null?y`<p class="data-empty">Attached data could not be loaded.</p><button type="button" class="btn" @click="${()=>this._openDetail(e)}">Try again</button>`:n.length>0?y`<ul>${n.map(e=>y`<li>${e.filename}${e.repoDirectory?` \xB7 ${e.repoDirectory}`:b}</li>`)}</ul>`:y`<p class="data-empty">No ${t.toLowerCase()} attached.</p>`}</section>`)}</div></section><section class="section" aria-label="Permanent repository removal"><h2>Permanent removal</h2><div class="settings-row"><div class="settings-copy"><strong>Delete repository and stored data</strong><p>Deactivation is reversible. Permanent removal deletes this repository’s attached reports and bundles; it cannot be undone.</p></div><button type="button" class="btn danger" ?disabled="${this._busy!=null||this._impactLoading||!this._impactFresh||this._impact==null}" @click="${()=>this._resetRemoval(!0)}">Remove permanently</button></div></section></div>${this._removeOpen&&this._impact!=null&&!this._impactLoading?this._removeDialog(e,n,r):b}</div>`}_dependencyReviewSection(e){let t=this._data?.reviewedDependencies===!0,n=e.dependencyReview??{enabled:!1,required:1,since:null},r=Oi(n.lockfiles),i={required:String(n.required),since:n.since??``,scope:r,adding:``,...this._reviewDraft},a=i.required!==String(n.required)||!t&&i.since.trim()!==(n.since??``)||JSON.stringify(i.scope)!==JSON.stringify(r),o=this._busy!=null;return y`<section class="section" aria-label="Dependency review"><div class="section-head"><h2>Dependency review</h2><mode-switch label="${n.enabled?`On`:`Off`}" accessible-label="Review dependencies" .checked="${n.enabled}" .disabled="${o}" @click="${()=>{o||this._saveDependencyReview(e,this._reviewSetting(!n.enabled,n.required,n.since))}}"></mode-switch></div>${n.enabled?y`<form class="settings-row dependency-review-settings" aria-label="Dependency review settings" @submit="${t=>{t.preventDefault(),this._saveDependencyReview(e,this._reviewSetting(!0,Number(i.required),i.since.trim().toLowerCase()||null,ki(i.scope)))}}"><label><span>Reviews each version needs</span><input type="number" min="1" max="10" required .value="${i.required}" ?disabled="${o}" @input="${e=>{this._reviewDraft={...i,required:e.target.value}}}"></label> ${t?b:y`<label class="dependency-review-since"><span>Reviewed since commit (optional)</span><input type="text" placeholder="Full commit id" autocomplete="off" spellcheck="false" pattern="[0-9a-fA-F]{40}" .value="${i.since}" ?disabled="${o}" @input="${e=>{this._reviewDraft={...i,since:e.target.value}}}"></label>`} ${this._lockfileScope(e,i,o)} <button type="submit" class="btn" ?disabled="${o||!a}">Save</button> ${Array.isArray(e.reviewTeams)&&e.reviewTeams.length===0?y`<p class="dependency-review-hint is-warning" role="status">No team that reviews dependencies has this repository, so its pull requests show no review. Add it to such a team, or turn dependency review on for a team that has it.</p>`:t||i.since.trim()?y`<p class="dependency-review-hint">${t?`Versions this server’s reviewed dependencies pass need no reviews here.`:`Versions the repository’s lockfiles locked at this commit need no review.`}</p>`:b}</form>`:b}</section>`}_lockfileScope(e,t,n){let{mode:r,paths:i}=t.scope,a=r===`all`?{status:`ready`,paths:[],configs:[]}:this._lockfilesFor(e),o=e=>{this._reviewDraft={...t,scope:e}},s=r===`include`?a.configs:[],c=new Set([...a.paths,...s]),l=[...new Set([...c,...i])].toSorted(),u=e=>e===`include`?i:i.filter(e=>!gt(e)),d=()=>{let e=t.adding.trim().replace(/^\.?\/+/u,``);e&&(this._reviewDraft={...t,adding:``,scope:{mode:r,paths:[...new Set([...i,e])].toSorted()}})};return y`<fieldset class="dependency-review-lockfiles" ?disabled="${n}"><legend>Lockfiles reviewed</legend><select aria-label="Lockfiles reviewed" .value="${r}" @change="${e=>o({mode:e.target.value,paths:u(e.target.value)})}"><option value="all">Every lockfile</option><option value="exclude">All but those selected</option><option value="include">Only those selected</option></select> ${r===`all`?b:y`${a.status===`loading`?y`<p class="dependency-review-hint" role="status">Reading the default branch’s lockfiles…</p>`:a.status===`error`?y`<p class="dependency-review-hint is-warning" role="alert">Its lockfiles couldn’t be read (${a.error}); name them below.</p>`:b} ${l.length>0?y`<ul class="dependency-review-lockfile-list">${l.map(e=>y`<li><label><input type="checkbox" .checked="${i.includes(e)}" @change="${t=>o({mode:r,paths:t.target.checked?[...i,e].toSorted():i.filter(t=>t!==e)})}"> <code>${e}</code>${a.status===`ready`&&!c.has(e)?y`<span>${e.endsWith(`/`)?`every lockfile under it`:`not on the default branch`}</span>`:b}</label></li>`)}</ul>`:a.status===`ready`?y`<p class="dependency-review-hint">Its default branch has no lockfile its review reads.</p>`:b} ${i.some(gt)?y`<p class="dependency-review-hint">A <code>stasis.config.json</code> holds the review to the versions its entries reach, in place of all a lockfile locks. Stasis builds them for each commit as it is first asked for, which can take minutes; until then they show as being worked out.</p>`:b} <label class="dependency-review-lockfile-add"><span>${r===`include`?`Another lockfile, a directory ending in /, or a stasis.config.json`:`Another lockfile, or a directory ending in /`}</span> <input type="text" placeholder="examples/" autocomplete="off" spellcheck="false" .value="${t.adding}" @input="${e=>{this._reviewDraft={...t,adding:e.target.value}}}" @keydown="${e=>{e.key===`Enter`&&(e.preventDefault(),d())}}"></label> <button type="button" class="btn" ?disabled="${!t.adding.trim()}" @click="${d}">Add</button>`}</fieldset>`}_lockfilesFor(e){if(this._lockfileRead?.repoId!==e.id){let t={repoId:e.id,status:`loading`,paths:[],configs:[]};this._lockfileRead=t,ar(e.id).then(({paths:e,configs:n})=>Object.assign(t,{status:`ready`,paths:e,configs:n}),e=>Object.assign(t,{status:`error`,error:e?.message??String(e)})).finally(()=>{this._lockfileRead===t&&this.requestUpdate()})}return this._lockfileRead}_reviewSetting(e,t,n,r){return{...this._data?.reviewedDependencies===!0?{enabled:e,required:t}:{enabled:e,required:t,since:n},...r?{lockfiles:r}:{}}}async _saveDependencyReview(e,t){await this._act(e,`save ${e.fullName}'s dependency review`,async()=>{let n=await this.appState.mutate(()=>ir(e.id,t,this._csrf),[`repos`]);globalThis.dispatchEvent?.(new Event(`dependency-review-changed`)),this.isConnected&&(this._patchRepo(e.id,{dependencyReview:n}),this._reviewDraft=null)})}_removeDialog(e,t,n){let r=t.length>0||n.length>0,i=this._canRemove(e);return y`<div class="dialog-backdrop" role="presentation" @click="${e=>{e.target===e.currentTarget&&(this._removeOpen=!1)}}"><section class="${`dialog ${r?``:`small`}`}" role="dialog" aria-modal="true" aria-labelledby="remove-repo-title"><h2 id="remove-repo-title">Remove ${e.fullName} permanently?</h2><p class="dialog-copy">${r?`This destructive action will remove the repository and the stored data listed below. Deactivation keeps all of it.`:`This repository has no attached reports or bundles. Permanent removal deletes its connection record.`}</p>${r?y`<div class="dialog-data"><section><h3>Reports to delete (${t.length})</h3><ul>${t.map(e=>y`<li>${h(e.filename)}${e.repoDirectory?` \xB7 ${e.repoDirectory}`:b}</li>`)}</ul></section><section><h3>Bundles to delete (${n.length})</h3><ul>${n.map(e=>y`<li>${e.filename}</li>`)}</ul></section></div>`:b} <label class="confirm-line"><input type="checkbox" .checked="${this._acknowledge}" @change="${e=>{this._acknowledge=e.target.checked}}"><span>I understand this permanently deletes the repository connection${r?`, reports, and bundles`:``}.</span></label> ${(this._impact?.triageCount??0)>0?y`<label class="confirm-line"><input type="checkbox" .checked="${this._deleteTriage}" @change="${e=>{this._deleteTriage=e.target.checked}}"><span>Also delete ${this._impact.triageCount} triage entr${this._impact.triageCount===1?`y`:`ies`} belonging only to this repository.</span></label>`:b} ${r?y`<label class="confirm-field"><span>Type <strong>${e.fullName}</strong> to confirm.</span><input class="confirm-name" type="text" autocomplete="off" .value="${this._confirmName}" @input="${e=>{this._confirmName=e.target.value}}"></label>`:b}<div class="dialog-actions"><button type="button" class="btn" @click="${()=>{this._removeOpen=!1}}">Cancel</button><button type="button" class="btn danger" ?disabled="${!i}" @click="${()=>{this._remove(e)}}">${this._busy===e.id?`Removing…`:`Remove permanently`}</button></div></section></div>`}async _setActive(e,t){let n=t?e.active===!1?`reactivate`:`add`:`deactivate`;await this._act(e,`${n} ${e.fullName}`,async()=>{await this.appState.mutate(()=>rr(e.id,t,this._csrf),[`repos`,`reports`,`bundles`,`teams`,`users`,`history`]),this.isConnected&&(this._patchRepo(e.id,{active:t}),await this._load())})}_canRemove(e){return this._busy!=null||this._impactLoading||!this._impactFresh||this._impact?.repoId!==e.id||!this._acknowledge?!1:!(this._impact.reports.length>0||this._impact.bundles.length>0)||this._confirmName===e.fullName}async _remove(e){this._canRemove(e)&&await this._act(e,`remove ${e.fullName}`,async()=>{await this.appState.mutate(()=>dr(e.id,e.fullName,this._deleteTriage,this._csrf),[`repos`,`repo-impact`,`reports`,`report-preview`,`bundles`,`teams`,`users`,`history`,`scan-sources`]),this._removeOpen=!1,this._detail=null,this._impact=null,await this._load()})}};customElements.define(`managed-admin-repos`,ji);function Mi(e){return[{value:null,label:`No repository`,special:!0},...e.map(e=>({value:e.repoId,label:e.fullName}))]}function Ni(e,t,n,r,i){let a=y`<span class="ui-hint">${e}: </span><span class="location-metadata-value" data-tooltip-truncated data-tooltip="${t}">${t}</span>`;return r?y`<button type="button" class="location-metadata" aria-label="${`Use ${n} from ${e}: ${t}`}" ?disabled="${i}" @click="${r}">${a}</button>`:y`<span class="location-metadata">${a}</span>`}var Pi=e=>Number.isFinite(e.uploadedAt)?new Date(e.uploadedAt).toLocaleDateString(void 0,{year:`numeric`,month:`short`,day:`numeric`}):``,Fi=e=>e.repoFullName?`${e.repoFullName}${e.repoDirectory?`/${e.repoDirectory}`:``}`:`No repository assigned`,Ii=class extends x{static properties={localImportSource:{attribute:!1},_query:{state:!0},_visibility:{state:!0},_busy:{state:!0},_locationId:{state:!0},_locationOrigin:{state:!0},_locationOriginError:{state:!0},_locationRepo:{state:!0},_locationDirectory:{state:!0},_locationBusy:{state:!0}};constructor(){super();let{kind:e,upload:t,importFamilies:n,uploadFamilies:r}=this.constructor;Object.assign(this,{_query:``,_visibility:`all`,_busy:!1,_locationId:null,_locationOrigin:null,_locationOriginError:null,_locationRepo:null,_locationDirectory:``,_locationBusy:!1}),this._locationOriginRequest=null,this._queue=[],this._localImport=new vt(this,e,e=>pt(this,e,e=>t(e,this._csrf),n??r)),this._drop=new ht(this,()=>this._acceptsDrop())}_acceptsDrop(){return!0}disconnectedCallback(){super.disconnectedCallback(),this._closeLocation()}_show(e){this._data=e,this._locationId&&!e[`${this.constructor.kind}s`]?.some(e=>e.id===this._locationId)&&this._closeLocation()}_upload(e){let{upload:t,uploadFamilies:n}=this.constructor;return mt(this,e,e=>t(e,this._csrf),n)}_filtered(){let{kind:e}=this.constructor,t=Array.isArray(this._data?.[`${e}s`])?this._data[`${e}s`]:[],n=this._query.trim().toLocaleLowerCase(),r=t.filter(e=>this._searchText(e).filter(Boolean).join(` `).toLocaleLowerCase().includes(n)&&(this._visibility===`all`||this._visible(e)===(this._visibility===`visible`)));return{items:t,filtered:r,count:`${n||this._visibility!==`all`?`${r.length} of `:``}${t.length} ${t.length===1?e:`${e}s`}`}}_page(e,t){let{kind:n}=this.constructor;return y`${this._drop.overlay(`Drop ${n}s to upload`)}<div class="wrap">${this._nav()}<h1 class="sr-only">${`${n[0].toUpperCase()}${n.slice(1)}s`}</h1><div class="page-intro">${e}</div>${this._localImport.renderPanel(this._busy||!this._csrf)}${t}${this._body()}</div>`}_body(){let{kind:e,uploadCopy:t}=this.constructor,{items:n,filtered:r,count:i}=this._filtered(),a=y`<div class="collection-toolbar" role="search"><input type="search" aria-label="${`Search ${e}s`}" placeholder="${`Search ${e}s or repositories\u2026`}" .value="${this._query}" @input="${e=>{this._query=e.target.value}}"> <select aria-label="${`${e[0].toUpperCase()}${e.slice(1)} visibility`}" .value="${this._visibility}" @change="${e=>{this._visibility=e.target.value}}"><option value="all">${`All ${e}s`}</option><option value="visible">Visible to teams</option><option value="hidden">${`Hidden ${e}s`}</option></select> ${this._count(r,i)}</div>`;return y`${a} ${C(this._error)} ${this._list(this._data,`Loading ${e}s\u2026`,()=>r.length>0?this._items(r):n.length===0?w(`No ${e}s uploaded yet`,t):w(`No matching ${e}s`,`Try a different search or visibility filter.`))}`}async _attempt(e,t){this._error=null;try{await t()}catch(t){this._error=`${e}: ${String(t?.message??t)}`}}_setVisible(e,t){let{kind:n,setVisible:r,visibleFamilies:i}=this.constructor;return this._attempt(`Couldn't change ${n} visibility`,async()=>{await this.appState.mutate(()=>r(e.id,t,this._csrf),i),e.visible=t,this.requestUpdate(),await this._load()})}_openLocation(e){e.canChangeRepo!==!1&&(this._closeLocation(),Object.assign(this,{_locationId:e.id,_locationRepo:e.repoId??null,_locationDirectory:e.repoDirectory??``,_error:null}),this._suggests(e)&&this._loadLocationOrigin(e))}_suggests(){return!0}_closeLocation(){this._locationOriginRequest?.abort(),this._locationOriginRequest=null,Object.assign(this,{_locationId:null,_locationOrigin:null,_locationOriginError:null})}async _loadLocationOrigin(e){this._locationOriginRequest?.abort();let t=new AbortController;this._locationOriginRequest=t,this._locationOrigin=void 0,this._locationOriginError=null;try{let n=await this._fetchOrigin(e.id,t.signal);if(this._locationOriginRequest!==t)return;n?.repoId!=null&&this._data&&(this._data={...this._data,repos:[...(this._data.repos??[]).filter(e=>e.repoId!==n.repoId),{repoId:n.repoId,fullName:n.github}]}),this._locationOrigin=typeof n?.github==`string`&&n.github?this._suggestion(n):null}catch(e){if(this._locationOriginRequest!==t)return;this._locationOrigin=null,e?.name!==`AbortError`&&(this._locationOriginError=`Couldn't load the ${this.constructor.kind}\u2019s suggested location.`)}}_locationEditor(e){let{kind:t,hintSource:n}=this.constructor,r=Array.isArray(this._data?.repos)?this._data.repos:[],i=this._locationOrigin,a=i&&this._originRepo(i,r),o=(e,t,r)=>Ni(n,e,t,r,this._locationBusy);return y`<div class="location-editor"><div class="location-field"><div class="location-field-header"><span class="ui-hint">Repository</span>${i?o(i.github,`repository`,a?()=>{this._locationRepo=a.repoId,i.directory!=null&&(this._locationDirectory=i.directory)}:null):b}</div><repository-selector label="${`Repository for ${t}`}" .options="${Mi(r)}" .value="${this._locationRepo}" ?disabled="${this._locationBusy}" @repository-change="${e=>{this._locationRepo=e.detail.value}}"></repository-selector></div><div class="location-field"><div class="location-field-header"><label for="${`${t}-dir-${e.id}`}">Directory (optional)</label>${i?o(i.directory??`Directory not specified`,`directory`,i.directory==null?null:()=>{this._locationDirectory=i.directory}):b}</div><input id="${`${t}-dir-${e.id}`}" type="text" placeholder="Repository root" .value="${this._locationDirectory}" ?disabled="${this._locationBusy}" @input="${e=>{this._locationDirectory=e.target.value}}"></div><div class="location-actions"><button type="button" class="action" ?disabled="${this._locationBusy}" @click="${()=>this._closeLocation()}">Cancel</button><button type="button" class="action" ?disabled="${this._locationBusy}" @click="${()=>{this._saveLocation(e)}}">Save</button></div>${this._locationOriginError?y`<p class="location-origin" role="status">${this._locationOriginError} <button type="button" class="origin-retry" @click="${()=>{this._loadLocationOrigin(e)}}">Retry</button></p>`:b}</div>`}async _saveLocation(e){if(this._locationBusy)return;this._locationBusy=!0;let{kind:t,setRepo:n,locationFamilies:r}=this.constructor;try{await this._attempt(`Couldn't set ${t} location`,async()=>{await this.appState.mutate(()=>n(e.id,this._locationRepo,this._locationDirectory.trim(),this._csrf),r),this._closeLocation(),await this._load({preserveError:!0})})}finally{this._locationBusy=!1}}},Li=class extends Ii{static kind=`report`;static view=`manage-reports`;static collection=[`reports`,`reports`,fr];static upload=hr;static uploadFamilies=[`reports`,`repo-impact`,`history`,`scan-sources`];static setVisible=_r;static visibleFamilies=[`reports`,`history`,`scan-sources`];static setRepo=yr;static locationFamilies=[`reports`,`repo-impact`,`history`,`scan-sources`];static hintSource=`report`;static uploadCopy=`Drop a report here or browse files above.`;static properties={_preview:{state:!0},_previewLoading:{state:!0},_openingBusy:{state:!0}};static styles=[v(Lr),v(zr),v(r),v(Mr)];constructor(){super(),this._preview=null,this._previewLoading=null,this._previewRequest=null,this._openingBusy=null}disconnectedCallback(){super.disconnectedCallback(),this._cancelPreview()}_show(e){this._preview&&!e.reports?.some(e=>e.id===this._preview)&&this._cancelPreview(),super._show(e)}_searchText(e){return[e.filename,h(e.filename),e.repoFullName,e.repoDirectory,e.uploadedByLogin]}_visible(e){return!!e.visible}_fetchOrigin(e,t){return br(e,AbortSignal.any([t,this.appState.sessionController.signal]))}_suggestion(e){return{github:e.github,repoId:e.repoId??null,directory:typeof e.directory==`string`?e.directory||`/`:null}}_originRepo(e,t){return e.repoId!=null&&t.find(t=>t.repoId===e.repoId)}render(){return this._page(y`<p class="intro">Upload reports. New reports stay hidden until you make them visible.</p>${this._localImport.renderAction()}`,y`<div class="drop-card">${this._drop.card(`Upload reports`,`Drop files anywhere on this page.`,this._busy)}</div>${this._data?.repoScopes?.length?y`<p class="intro">Team paths: ${this._data.repoScopes.map(e=>`${this._data.repos.find(t=>t.repoId===e.repoId)?.fullName??e.repoId}/${e.path??``}`).join(`, `)}</p>`:b} `)}_count(e,t){return y`<span class="result-count" role="status">${this._data==null?`… reports`:t}</span>`}_items(e){return y`<div class="report-list"><div class="report-list-head" aria-hidden="true"><span class="report-heading">Report</span><span>Repository</span><span>Uploaded by</span><span>Date</span><span class="size-heading">Size</span><span>Visibility</span><span class="actions-heading">Actions</span></div><ul class="reports">${e.map(e=>this._row(e))}</ul></div>`}_row(e){let t=h(e.filename),n=e.analyzer??e.source??e.producer??`default`,r=Ve[n]??Ve.default,i=e.repoEmbedded!==!0&&e.canChangeRepo!==!1,a=e.repoEmbedded===!0||e.repoId!=null,o=Fi(e),s=e.confirmedOffered===!0||e.confirmedDefault===!0;return y`<li class="${`report${e.visible===!1?` content-hidden`:``}`}"><div class="report-main"><span class="report-mark" aria-hidden="true">${g(r)}</span> <span class="report-name" data-tooltip-truncated data-tooltip="${t}">${t}</span> <span class="report-location" data-tooltip-truncated data-tooltip="${o}">${o}</span> <span class="report-meta report-uploader" data-tooltip-truncated data-tooltip="${e.uploadedByLogin??`Uploader removed`}">${e.uploadedByLogin??`Uploader removed`}</span> <span class="report-meta report-date">${Pi(e)}</span> <span class="report-meta report-size">${Ke(e.byteSize)}</span> <span class="${`status ${e.visible?`visible`:`hidden`}`}">${e.visible?`Visible`:`Hidden`}</span> <span class="report-actions">${i?y`<button type="button" class="action" data-tooltip="Set repository location" aria-label="${`Set location for ${t}`}" @click="${()=>this._openLocation(e)}">${m(`repo`)}</button>`:y`<span class="action-spacer"></span>`} ${s?y`<button type="button" class="action opening" aria-pressed="${e.confirmedDefault===!0?`true`:`false`}" aria-label="${`Open ${t} on Confirmed by default`}" data-tooltip="${e.confirmedDefault?`Opens on Confirmed by default. Click to open as detected`:`Open on Confirmed by default, hiding findings the pass did not confirm`}" ?disabled="${e.canChangeRepo===!1||this._openingBusy===e.id}" @click="${()=>{this._setOpening(e,!e.confirmedDefault)}}">${m(`confirmed`)}</button>`:y`<span class="action-spacer"></span>`} <button type="button" class="action" aria-label="${`Preview ${t}`}" aria-expanded="${this._preview===e.id}" @click="${()=>{this._togglePreview(e)}}">${m(`preview`)}</button> <button type="button" class="action" data-tooltip="${e.visible?`Hide from teams`:a?`Make visible to teams`:`Assign a repository before publishing`}" aria-label="${`${e.visible?`Hide`:`Make visible`} ${t}`}" ?disabled="${e.canChangeRepo===!1||!a&&!e.visible}" @click="${()=>{this._setVisible(e,!e.visible)}}">${m(e.visible?`hide`:`show`)}</button> <a class="action" aria-label="${`Download ${t}`}" href="${`/api/admin/reports/${encodeURIComponent(e.id)}`}">${m(`download`)}</a> <button type="button" class="action danger" aria-label="${`Delete ${t}`}" ?disabled="${e.canChangeRepo===!1}" @click="${()=>this._delete(e)}">${mi}</button></span></div>${this._preview===e.id?y`<div class="preview">${this._previewLoading===e.id?y`<span class="preview-loading">Loading preview…</span>`:y`<pre>${this._previewText??``}</pre>`}</div>`:b} ${this._locationId===e.id?this._locationEditor(e):b}</li>`}_cancelPreview(){this._previewRequest?.abort(),this._previewRequest=null,this._preview=null,this._previewLoading=null,this._previewText=``}async _togglePreview(e){let t=this._preview===e.id;if(this._cancelPreview(),t)return;let n=`report-preview:${e.id}`;this._preview=e.id,this._previewText=this.appState.read(n)??``,this._previewLoading=this.appState.read(n)===void 0?e.id:null,await this._read(`_previewRequest`,n,`report preview`,async t=>{let n=await l(`/api/admin/reports/${encodeURIComponent(e.id)}`,{credentials:`same-origin`,signal:t});if(!n.ok)throw Error(`HTTP ${n.status}`);let r=await n.text();return r.slice(0,4e3)+(r.length>4e3?`
17
17
  …`:``)},{apply:e=>{this._previewText=e},settled:()=>{this._previewLoading=null},failed:e=>{this._previewText||=`Preview unavailable: ${e?.message??e}`}})}async _setOpening(e,t){if(!this._openingBusy){this._openingBusy=e.id;try{await this._attempt(`Couldn't change how the report opens`,async()=>{await this.appState.mutate(()=>vr(e.id,t,this._csrf),[`reports`,`history`]),e.confirmedDefault=t,this.requestUpdate(),await this._load()})}finally{this._openingBusy=null}}}async _delete(e){globalThis.confirm?.(`Delete \u201C${h(e.filename)}\u201D? This can't be undone.`)&&(await this._attempt(`Delete failed`,()=>this.appState.mutate(()=>xr(e.id,this._csrf),[`reports`,`report-preview:${e.id}`,`repo-impact`,`history`,`scan-sources`])),await this._load({preserveError:!0}))}};customElements.define(`managed-admin-reports`,Li);var Ri=y`<svg class="report-icon" viewBox="0 0 16 16" width="16" height="16" fill="currentColor" aria-hidden="true"><path d="M8.878.392a1.75 1.75 0 0 0-1.756 0l-5.25 3.045A1.75 1.75 0 0 0 1 4.951v6.098c0 .624.332 1.2.872 1.514l5.25 3.045a1.75 1.75 0 0 0 1.756 0l5.25-3.045c.54-.313.872-.89.872-1.514V4.951c0-.624-.332-1.2-.872-1.514ZM7.875 1.69a.25.25 0 0 1 .25 0l4.63 2.685L8 7.133 3.245 4.375Zm-5.125 4.4 4.5 2.61v5.317l-4.375-2.537a.25.25 0 0 1-.125-.216Zm6 7.927V8.7l4.5-2.61v3.96a.25.25 0 0 1-.125.216Z"/></svg>`,zi=5;function Bi(e,{reports:t,otherReports:n}){let r=t.length+n;if(r===0)return`Delete \u201C${e.filename}\u201D? No reports use it.`;let i=t.slice(0,zi).map(e=>`\u2022 ${h(e.filename)}`),a=t.length-i.length,o=`${n} ${n===1?`report`:`reports`} you can't access`;return a>0?i.push(`\u2022 ${a} more${n>0?`, and ${o}`:``}`):n>0&&i.push(`\u2022 ${o}`),[`Delete \u201C${e.filename}\u201D?`,``,`${r===1?`1 report uses`:`${r} reports use`} this bundle:`,...i,``,`${r===1?`Its`:`Their`} findings will show no code from it until the same bundle is uploaded again.`].join(`
18
- `)}var Vi=class extends Ii{static kind=`bundle`;static view=`manage-bundles`;static collection=[`bundles`,`bundles`,Sr];static upload=Cr;static uploadFamilies=[`bundles`,`bundle-metadata`,`reports`,`repo-impact`,`history`,`scan-sources`];static importFamilies=[`bundles`,`reports`,`repo-impact`,`history`,`scan-sources`];static setVisible=Er;static visibleFamilies=[`bundles`,`teams`,`history`,`scan-sources`];static setRepo=Dr;static locationFamilies=[`bundles`,`teams`,`repo-impact`,`history`,`scan-sources`];static hintSource=`metadata`;static uploadCopy=`Drop source archives here or browse files above.`;static properties={createRepoId:{attribute:!1},installTooltips:{attribute:!1},_visibilityBusy:{state:!0},_deleting:{state:!0},_creating:{state:!0}};static styles=[v(Rr),v(zr),v(r),v(Mr)];constructor(){super(),Object.assign(this,{_visibilityBusy:null,_deleting:null,_creating:!1})}_acceptsDrop(){return!this._creating}_searchText(e){return[e.filename,e.repoFullName,e.repoDirectory,e.kind,e.provenance===`build`?`built`:null,e.uploadedByLogin]}_visible(e){return e.visible!==!1}_suggests(e){return e.kind===`stasis`}_fetchOrigin(e,t){return Ct(e,{signal:t})}_suggestion(e){return{github:e.github,directory:typeof e.directory==`string`?e.directory:e.root===!0?`/`:null}}_originRepo(e,t){let n=at({repo:e})?.toLowerCase();return n&&t.find(e=>e.fullName.toLowerCase()===n)}_showCreate(e){!e&&this.createRepoId!=null?p(`manage-bundles`):(this._creating=e,this._drop.active=!1,e||this.updateComplete.then(()=>this.renderRoot.querySelector(`.create-bundle-action`)?.focus()))}willUpdate(e){e.has(`createRepoId`)&&(this._creating=this.createRepoId!=null)}render(){return this._creating?y`<div class="wrap">${this._nav()} ${vi(`Bundles`,`Back to bundles`,()=>this._showCreate(!1),`Create a bundle`)}<managed-create-bundle .initialRepoId="${this.createRepoId??null}" .installTooltips="${this.installTooltips}" .createBundle="${this._csrf?(e,t)=>this.appState.mutate(()=>mr(e,this._csrf,t),[`bundles`,`bundle-metadata`,`reports`,`repo-impact`,`history`,`scan-sources`]):void 0}" @bundle-created="${e=>this._emit(`managed-bundle-open`,e.detail)}"></managed-create-bundle></div>`:this._page(y`<p class="intro">Source bundles for your repositories.</p><div class="bundle-actions">${this._localImport.renderAction()}<button type="button" class="local-import-toggle create-bundle-action" ?disabled="${!this._data}" @click="${()=>this._showCreate(!0)}">Create</button></div>`,y`<section class="drop-card" aria-label="Upload bundles">${this._drop.card(`Upload source bundles`,`Drop source archives anywhere on this page.`,this._busy)}</section>`)}_count(e,t){let n=this._data!=null,r=e.filter(e=>e.repoId==null).length,i=e.reduce((e,t)=>e+(Number.isFinite(t.byteSize)?t.byteSize:0),0);return y`<span class="summary result-count" role="status"><span>${n?t:`… bundles`}</span><span>${n?Ke(i):`…`}</span> ${!n||r?y`<span class="unassigned">${n?`${r} unattached`:`… unattached`}</span>`:b}</span>`}_items(e){let t=[...Map.groupBy(e,e=>e.repoFullName||`Unattached`)].toSorted(([e],[t])=>e===`Unattached`?-1:t===`Unattached`?1:e.localeCompare(t));return y`<div class="bundle-groups">${t.map(([e,t])=>y`<section class="bundle-group"><div class="bundle-group-head"><strong>${e}</strong><span>${t.length} ${t.length===1?`bundle`:`bundles`}</span></div><ul class="bundles">${t.map(e=>this._row(e))}</ul></section>`)}</div>`}_row(e){let t=e.visible!==!1,n=Fi(e);return y`<li class="${`bundle-row${t?``:` content-hidden`}`}"><span class="identity"><span class="bundle-icon" aria-hidden="true">${e.kind===`stasis`?y`<img src="./stasis.svg" width="16" height="16" alt="">`:Ri}</span> <button type="button" class="filename bundle-open" data-tooltip-truncated data-tooltip="${e.filename}" @click="${()=>this._emit(`managed-bundle-open`,e)}">${e.filename}</button> ${e.provenance===`build`?y`<span class="bundle-provenance" data-tooltip="Generated on this server from the repository">Built</span>`:b} </span><span class="meta bundle-uploader" data-tooltip-truncated data-tooltip="${e.uploadedByLogin?`@${e.uploadedByLogin}`:``}">${e.uploadedByLogin?`@${e.uploadedByLogin}`:``}</span> <span class="meta bundle-date">${Pi(e)}</span> <span class="meta bundle-size">${Ke(e.byteSize)}</span> <span class="bundle-location" data-tooltip-truncated data-tooltip="${n}">${n}</span> <span class="${`status ${t?`visible`:`hidden`}`}">${t?`Visible`:`Hidden`}</span> <span class="actions">${e.canChangeRepo===!1?b:y`<button type="button" class="action" aria-label="${`Set location for ${e.filename}`}" data-tooltip="Set repository location" ?disabled="${this._locationBusy}" @click="${()=>this._openLocation(e)}">${m(`repo`)}</button>`} <button type="button" class="action" aria-label="${`${t?`Hide`:`Make visible`} ${e.filename}`}" data-tooltip="${t?`Hide from teams`:e.repoId==null?`Assign a repository before publishing`:`Make visible to teams`}" ?disabled="${this._visibilityBusy!=null||e.canChangeRepo===!1||!t&&e.repoId==null}" @click="${()=>{this._setVisible(e,!t)}}">${m(t?`hide`:`show`)}</button> <a class="action" aria-label="${`Download ${e.filename}`}" href="${`/api/admin/bundles/${encodeURIComponent(e.id)}`}"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M8 2v8m-3-3 3 3 3-3M3 11v3h10v-3"/></svg></a><button type="button" class="action danger" aria-label="${`Delete ${e.filename}`}" ?disabled="${e.canChangeRepo===!1||this._deleting!=null}" data-tooltip="${e.canChangeRepo===!1?`Repository access is required to detach or delete this bundle`:b}" @click="${()=>this._delete(e)}">${mi}</button> </span>${this._locationId===e.id?this._locationEditor(e):b}</li>`}async _setVisible(e,t){if(this._visibilityBusy==null&&e.canChangeRepo!==!1){this._visibilityBusy=e.id;try{await super._setVisible(e,t)}finally{this._visibilityBusy=null}}}_openLocation(e){this._locationBusy||super._openLocation(e)}_saveLocation(e){return e.canChangeRepo===!1?Promise.resolve():super._saveLocation(e)}async _delete(e){if(this._deleting==null&&e.canChangeRepo!==!1){this._deleting=e.id,this._error=null;try{let t;try{t=await wr(e.id)}catch(t){this._error=`Couldn't check which reports use \u201C${e.filename}\u201D: ${String(t?.message??t)}`;return}if(!globalThis.confirm?.(Bi(e,t)))return;try{await this.appState.mutate(()=>Tr(e.id,this._csrf),[`bundles`,`bundle-metadata`,`reports`,`repo-impact`,`history`,`scan-sources`])}catch(e){this._error=`Delete failed: ${String(e?.message??e)}`}await this._load({preserveError:!0})}finally{this._deleting=null}}}};customElements.define(`managed-admin-bundles`,Vi);var Hi=class extends x{static view=`manage-scans`;static properties={selection:{attribute:!1},_source:{state:!0}};static styles=v(r);static collection=[`bundles`,`bundles`,Sr];constructor(){super(),this._source=null,this._loadModels=(e,t)=>this.appState.load(`models`,`scan models`,e=>n(e,l),{signal:e,apply:t}),this._loadReportSources=(e,n)=>this.appState.load(`scan-sources`,`scan report inputs`,async e=>{let[n,r]=await Promise.all([l(`/api/admin/reports`,{signal:e,credentials:`same-origin`}),l(`/api/admin/scan-results`,{signal:e,credentials:`same-origin`})]);if(!n.ok)throw Error(`Reports: HTTP ${n.status}`);if(!r.ok&&r.status!==404)throw Error(`Scan results: HTTP ${r.status}`);let i=await n.json();return i.reports=await Promise.all((i.reports??[]).filter(e=>e.visible&&e.repoId!=null).map(async t=>{let n=await l(`/api/admin/reports/${encodeURIComponent(t.id)}`,{signal:e,credentials:`same-origin`});if(!n.ok)throw Error(`Report ${h(t.filename)}: HTTP ${n.status}`);return{...t,content:await n.text()}})),t(i,r.ok?await r.json():{bundles:[],results:[]})},{signal:e,apply:n})}_load(){return Pe().catch(e=>{this._error=String(e?.message??e)}),super._load()}_show(e){this._source=ti(e)}render(){return y`<div class="wrap">${this._nav()} ${this._error?y`<p class="msg error" role="alert">Couldn’t load scan sources: ${this._error} <button type="button" class="btn" @click="${()=>{this._load()}}">Retry</button></p>`:b}<deepview-scan-page hide-heading .selection="${this.selection}" .source="${this._source}" .sourceLoading="${this._loading&&this._source==null}" .loadBundle="${ni}" .loadModels="${this._loadModels}" .loadReportSources="${this._loadReportSources}" .createBundleHref="${e=>Number.isSafeInteger(e)&&e>0?rt({view:`manage-bundles`,createRepoId:e}):null}"></deepview-scan-page></div>`}};customElements.define(`managed-admin-scans`,Hi);var Ui=(e,t)=>new Map([...e].filter(([e])=>e!==t)),Wi=y`<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="6" cy="5" r="2.5"/><path d="M1.5 13v-1c0-2 1.8-3.5 4.5-3.5s4.5 1.5 4.5 3.5v1M11 2.5a2.5 2.5 0 0 1 0 5M12 9c1.7.5 2.5 1.5 2.5 3v1"/></svg>`,Gi=(e,t)=>(e.icon?.id??null)===(t?.id??null);function Ki(e,{organizations:t,unchecked:n}){return[t.length>0?`Organizations that own this team’s repositories.`:e.repos.length===0?`Link a repository owned by an organization to use its avatar.`:n.length===0?`None of this team’s repositories belong to an organization.`:``,n.length>0?`Couldn\u2019t check ${n.join(`, `)} on GitHub.`:``].filter(Boolean).join(` `)}var qi=class extends x{static view=`manage-teams`;static properties={_busy:{state:!0},_renamingId:{state:!0},_repoChoices:{state:!0},_memberChoices:{state:!0},_iconPicker:{state:!0}};static styles=[v(Br),v(Me),v(r)];static collection=[`teams`,`teams`,Or];constructor(){super(),Object.assign(this,{_busy:!1,_renamingId:null,_repoChoices:new Map,_memberChoices:new Map,_iconPicker:null})}async _do(e){if(!this._busy){this._busy=!0,this._error=null;try{await this.appState.mutate(e,[`teams`,`users`,`reports`,`history`,`repos`]),globalThis.dispatchEvent?.(new Event(`dependency-review-changed`))}catch(e){this._error=String(e?.message??e)}finally{this._busy=!1,await this._load({preserveError:!0})}}}_post(e,t,n=()=>{}){return this._do(async()=>{await Ar(e,this._csrf,t),n()})}render(){return y`<div class="wrap">${this._nav()}<h1 class="sr-only">Teams</h1><div class="page-intro"><p class="intro">Manage repository and finding access for each team.</p><span class="result-count">${this._data?.teams?.length??`…`} teams</span></div><div class="create-team"><label class="sr-only" for="new-team-name">New team</label> <input id="new-team-name" class="new-name" type="text" placeholder="Team name" maxlength="100" ?disabled="${this._busy}" @keydown="${e=>{e.key===`Enter`&&this._create()}}"> <button class="btn primary" ?disabled="${this._busy}" @click="${()=>this._create()}">${B} Create team</button><p class="access-note ui-hint">All members can view standard findings. Set dependencies and security access per member.</p></div><div class="manage-list" aria-busy="${this._loading}">${this._body()}</div></div>`}_body(){if(this._error!=null&&this._data==null)return y`<p class="msg error">Couldn't load teams: ${this._error}</p>`;if(this._data==null)return S(`Loading teams…`);let e=Array.isArray(this._data.teams)?this._data.teams:[];return y`${this._error==null?b:y`<p class="msg error">${this._error}</p>`} ${e.length===0?y`<p class="msg">No teams yet. Create one above.</p>`:e.map(e=>this._team(e))}`}_team(e){return y`<section class="team" aria-label="${e.name}"><div class="team-head"><button type="button" class="team-icon" aria-label="${`Change icon of ${e.name}`}" title="Change icon" aria-expanded="${String(this._iconPicker?.teamId===e.id)}" @click="${()=>{this._toggleIconPicker(e)}}">${je(e,Wi)}</button> ${this._renamingId===e.id?y`<input class="rename-input" type="text" .value="${e.name}" maxlength="100" aria-label="Team name" @keydown="${t=>this._renameKey(t,e)}"> <button class="btn" ?disabled="${this._busy}" @click="${t=>this._saveRename(e,t)}">Save</button> <button class="btn" @click="${()=>{this._renamingId=null}}">Cancel</button>`:y`<h2 class="team-name">${e.name}</h2>${e.hidden?y`<span class="muted ui-hint">Disabled</span>`:b} <span class="team-actions"><button class="icon-btn" aria-label="${`${e.hidden?`Restore`:`Hide`} ${e.name}`}" ?disabled="${this._busy}" @click="${()=>this._post(`/set-hidden`,{teamId:e.id,hidden:!e.hidden})}">${m(e.hidden?`show`:`hide`)}</button> <button class="icon-btn" aria-label="${`Rename ${e.name}`}" ?disabled="${this._busy}" @click="${()=>{this._renamingId=e.id}}">${pi}</button> <button class="icon-btn danger" aria-label="${`Delete ${e.name}`}" ?disabled="${this._busy}" @click="${()=>this._deleteTeam(e)}">${mi}</button></span>`}</div>${this._iconChoices(e)}<div class="team-body">${[[`Repositories`,e.repos,`No repositories linked.`,t=>this._repoRow(e,t),this._addRepoRow(e)],[`Members`,e.members,`No members.`,t=>this._memberRow(e,t),this._addMemberRow(e)]].map(([e,t,n,r,i])=>y`<div class="sub"><h3 class="sub-title">${e} <span class="count">${t.length}</span></h3>${t.length===0?y`<p class="muted ui-hint">${n}</p>`:y`<ul class="links">${t.map(r)}</ul>`} ${i}</div>`)}${this._npmScopes(e)}</div></section>`}async _toggleIconPicker(e){if(this._iconPicker?.teamId===e.id){this._iconPicker=null;return}let t={teamId:e.id,choices:null,error:null};this._iconPicker=t;try{let n=await jr(e.id);this._iconPicker===t&&(this._iconPicker={...t,choices:n})}catch(e){this._iconPicker===t&&(this._iconPicker={...t,error:String(e?.message??e)})}}_iconChoices(e){let t=this._iconPicker;if(t?.teamId!==e.id)return b;let n=t.choices?.organizations??[],r=e.icon&&!n.some(t=>t.id===e.icon.id)?[e.icon,...n]:n,i=(t,n)=>y`<button type="button" class="icon-choice" aria-pressed="${String(Gi(e,t))}" ?disabled="${this._busy}" @click="${()=>this._chooseIcon(e,t)}"><span class="icon-choice-image">${je({icon:t},Wi)}</span><span class="ln">${n}</span></button>`;return y`<div class="icon-picker" role="group" aria-label="${`Icon of ${e.name}`}"><div class="icon-choices">${i(null,`No icon`)}${r.map(e=>i(e,e.login))}</div>${t.error?C(`Couldn\u2019t load organizations: ${t.error}`):t.choices==null?y`<p class="muted ui-hint" role="status">Loading organizations…</p>`:y`<p class="muted ui-hint">${Ki(e,t.choices)}</p>`}</div>`}_chooseIcon(e,t){Gi(e,t)?this._iconPicker=null:this._post(`/set-icon`,{teamId:e.id,organization:t?.login??null},()=>{this._iconPicker=null})}_npmScopes(e){let t=Array.isArray(e.npmScopes)?e.npmScopes:[];return y`<div class="sub npm-scopes"><div class="sub-head"><h3 class="sub-title">npm scopes <span class="count">${t.length}</span><mode-switch class="npm-review-toggle" label="Enable dependency review" .checked="${!!e.dependencyReview}" .disabled="${this._busy}" @click="${()=>{this._busy||this._post(`/set-dependency-review`,{teamId:e.id,enabled:!e.dependencyReview})}}"></mode-switch></h3><p class="muted ui-hint">Members can open private packages in these scopes. Everyone can open public packages.</p></div><div class="add-row npm-scope-row"><input class="add-npm-scope" type="text" placeholder="@scope" aria-label="${`npm scope to add to ${e.name}`}" maxlength="215" ?disabled="${this._busy}" @keydown="${t=>{t.key===`Enter`&&this._addNpmScope(e,t)}}"> <button class="btn" aria-label="${`Add npm scope to ${e.name}`}" ?disabled="${this._busy}" @click="${t=>this._addNpmScope(e,t)}">${B} Add</button> ${t.length===0?b:y`<ul class="npm-scope-list">${t.map(n=>y`<li class="npm-scope"><span>${n}</span> <button class="icon-btn danger" aria-label="${`Remove ${n} from ${e.name}`}" ?disabled="${this._busy}" @click="${()=>this._post(`/set-npm-scopes`,{teamId:e.id,scopes:t.filter(e=>e!==n)})}">${hi}</button></li>`)}</ul>`}</div></div>`}_addNpmScope(e,t){let n=t.target.closest(`.add-row`)?.querySelector(`.add-npm-scope`);if(!n?.value.trim())return;let r=nt(n.value);if(r===null){this._error=`\u201C${n.value.trim()}\u201D is not an npm scope. Scopes look like @example.`;return}let i=Array.isArray(e.npmScopes)?e.npmScopes:[];i.includes(r)?n.value=``:this._post(`/set-npm-scopes`,{teamId:e.id,scopes:[...i,r]},()=>{n.value=``})}_repoRow(e,t){return y`<li class="repo-row">${gi} <span class="repo-copy"><span class="ln">${t.fullName}</span>${t.path?y`<span class="path">/${t.path.replace(/^\/+/u,``)}</span>`:b}</span> <button class="icon-btn danger" aria-label="${`Remove ${t.fullName}${t.path?`/${t.path}`:``} from ${e.name}`}" ?disabled="${this._busy}" @click="${()=>this._post(`/remove-repo`,{teamId:e.id,repoId:t.repoId,path:t.path??null})}">${hi}</button></li>`}_addRepoRow(e){let t=Array.isArray(this._data.repos)?this._data.repos:[];return t.length===0?y`<p class="muted ui-hint">No selected repositories to link — pick some on “Manage repositories”.</p>`:y`<div class="add-row"><repository-selector class="add-repo-sel" label="${`Repository to add to ${e.name}`}" placeholder="Add repository…" ?disabled="${this._busy}" .options="${t.map(e=>({value:e.repoId,label:e.fullName}))}" .value="${this._repoChoices.get(e.id)??null}" @repository-change="${t=>{this._repoChoices=new Map(this._repoChoices).set(e.id,t.detail.value)}}"></repository-selector><input class="add-repo-path" type="text" placeholder="Path (optional)" aria-label="${`Repository path in ${e.name} (optional)`}" maxlength="500" ?disabled="${this._busy}"> <button class="btn" aria-label="${`Add repository to ${e.name}`}" ?disabled="${this._busy||!this._repoChoices.has(e.id)}" @click="${t=>this._addRepo(e,t)}">${B} Add</button></div>`}_fullAccess(e){return this._data.users?.some(t=>t.id===e.userId&&Le(t.role,`manage`))}_memberRow(e,t){let n=Array.isArray(this._data.permissions)?this._data.permissions:[],r=this._fullAccess(t);return y`<li class="member-row"><span class="member">${li(t.userId,t.login)}<span class="ln">${t.login}</span></span> <span class="perms">${n.map(n=>y`<label class="perm"><input type="checkbox" .checked="${r||t[n]===!0}" ?disabled="${this._busy||r}" aria-label="${`${o[n]??n} access for ${t.login} in ${e.name}`}" @change="${r=>this._togglePerm(e,t,n,r.target.checked)}"> ${o[n]??n}</label>`)} </span><button class="icon-btn danger" aria-label="${`Remove ${t.login} from ${e.name}`}" ?disabled="${this._busy}" @click="${()=>this._post(`/remove-member`,{teamId:e.id,userId:t.userId})}">${hi}</button></li>`}_addMemberRow(e){let t=Array.isArray(this._data.users)?this._data.users:[],n=new Set(e.members.map(e=>e.userId));return y`<div class="add-row"><user-selector class="add-member-sel" label="${`Member to add to ${e.name}`}" placeholder="Add member…" ?disabled="${this._busy}" .users="${t.map(e=>({...e,disabled:n.has(e.id),detail:n.has(e.id)?`Member`:``}))}" .value="${this._memberChoices.get(e.id)??null}" @user-change="${t=>{this._memberChoices=new Map(this._memberChoices).set(e.id,t.detail.value)}}"></user-selector><button class="btn" aria-label="${`Add member to ${e.name}`}" ?disabled="${this._busy||!this._memberChoices.has(e.id)||n.has(this._memberChoices.get(e.id))}" @click="${()=>this._addMember(e)}">${B} Add</button></div>`}_create(){let e=this.renderRoot.querySelector(`.new-name`),t=e?.value.trim();t&&this._post(``,{name:t},()=>{e&&(e.value=``)})}_deleteTeam(e){globalThis.confirm?.(`Delete team \u201C${e.name}\u201D? Its repo + member links are removed.`)&&this._post(`/delete`,{teamId:e.id})}_renameKey(e,t){e.key===`Enter`?this._saveRename(t,e):e.key===`Escape`&&(this._renamingId=null)}_saveRename(e,t){if(this._busy)return;let n=t.target.closest(`.team-head`)?.querySelector(`.rename-input`)?.value.trim()??``;this._renamingId=null,n!==``&&n!==e.name&&this._post(`/rename`,{teamId:e.id,name:n})}_addRepo(e,t){let n=t.target.closest(`.add-row`)?.querySelector(`.add-repo-path`),r=this._repoChoices.get(e.id);!Number.isSafeInteger(r)||r<=0||this._post(`/set-repo`,{teamId:e.id,repoId:r,path:n?.value??``},()=>{this._repoChoices=Ui(this._repoChoices,e.id),n&&(n.value=``)})}_addMember(e){let t=this._memberChoices.get(e.id);!t||e.members.some(e=>e.userId===t)||this._post(`/set-member`,{teamId:e.id,userId:t},()=>{this._memberChoices=Ui(this._memberChoices,e.id)})}_togglePerm(e,t,n,r){if(this._fullAccess(t))return;let i={...Object.fromEntries((this._data.permissions??[]).map(e=>[e,t[e]===!0])),[n]:r};this._post(`/set-member`,{teamId:e.id,userId:t.userId,...i})}};customElements.define(`managed-admin-teams`,qi);var Ji=`.link-team{margin-top:1.5rem}.link-team h2{margin:0 0 .5rem;font-size:1rem;font-weight:600}.link-table{overflow-x:auto}table{width:100%;border-collapse:collapse;text-align:left;font-size:.8rem}th{color:var(--muted);font-weight:500}th,td{padding:.6rem .65rem;border-bottom:1px solid var(--border);white-space:nowrap}th:first-child,td:first-child{padding-left:0}th:last-child,td:last-child{padding-right:0;text-align:right}
19
- `;async function Yi(e){let t=await l(`/api/admin/links`,{signal:e,credentials:`same-origin`});if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();if(!Array.isArray(n?.shares))throw TypeError(`No public links returned`);return n}var Xi=class extends x{static view=`manage-links`;static styles=[v(r),v(Ji)];static collection=[`links`,`public links`,Yi];async _edit(e){await Se({id:e.teamId,name:e.teamName},e.id,this.session),this.isConnected&&await this._load()}_groups(){return[...Map.groupBy(this._data?.shares??[],e=>e.teamId).values()].map(e=>({name:e[0].teamName,links:e}))}_body(){return this._data==null?this._error?y`<p class="msg error">Couldn't load public links: ${this._error}</p>`:S(`Loading public links…`):this._data.shares.length===0?y`<p class="msg">No public links. Create one with the share button beside a workspace in the sidebar.</p>`:this._groups().map(e=>y`<section class="link-team" aria-label="${e.name}"><h2>${e.name}</h2><div class="link-table"><table><thead><tr><th>Link</th><th>Created by</th><th>Created</th><th>Security</th><th>Dependencies</th><th><span class="sr-only">Actions</span></th></tr></thead><tbody>${e.links.map(t=>y`<tr><td><span data-tooltip="${t.id}">${t.id.slice(0,8)}</span></td><td>${t.createdBy}</td><td>${new Date(t.createdAt).toLocaleString()}</td><td>${t.permissions.security?`On`:`Off`}</td><td>${t.permissions.dependencies?`On`:`Off`}</td><td><button class="btn" aria-label="${`Edit public link ${t.id.slice(0,8)} for ${e.name}`}" @click="${()=>this._edit(t)}">Edit</button></td></tr>`)}</tbody></table></div></section>`)}render(){return y`<div class="wrap">${this._nav()}<h1 class="sr-only">Public links</h1><div class="page-intro"><p class="intro">Manage public links and the findings each link can show.</p><span class="result-count">${this._data?.shares.length??`…`} links</span></div>${this._loading&&this._data?y`<span class="sr-only" role="status">Refreshing public links…</span>`:b}<div class="manage-list" aria-busy="${this._loading}">${this._body()}</div></div>`}};customElements.define(`managed-admin-links`,Xi);var Zi=Xn(`/api/admin/deduplication`,{"storage-encryption-required":`Configure MANAGED_STORAGE_ENCRYPTION_KEY on the server to import encrypted link reports.`,"invalid-link-report":`Choose a link report containing arrays of finding IDs, such as [["id1", "id2"]].`,"too-large":`This link report exceeds the server upload limit.`}),Qi=[`deduplication`,`reports`,`teams`],$i=class extends x{static view=`manage-deduplication`;static properties={_busy:{state:!0}};static styles=[v(r),v(Lr),v(Ji)];static collection=[`deduplication`,`deduplication reports`,e=>Zi(``,{signal:e})];constructor(){super(),this._busy=!1,this._queue=[],this._drop=new ht(this)}_upload(e){if(this._csrf&&this._role===`admin`)return mt(this,e,e=>Zi(``,{method:`POST`,headers:{"content-type":`application/json`,"x-report-filename":encodeURIComponent(e.name),"x-csrf-token":this._csrf},body:e}),Qi)}async _toggle(e){if(!this._busy&&this._csrf){this._busy=!0,this._error=null;try{await this.appState.mutate(()=>Zi(`/${encodeURIComponent(e.id)}`,{method:`PATCH`,headers:{"content-type":`application/json`,"x-csrf-token":this._csrf},body:JSON.stringify({enabled:!e.enabled})}),Qi)}catch(e){this._error=String(e?.message??e)}finally{this._busy=!1,await this._load({preserveError:!0});let e=this._queue.splice(0);e.length>0&&this._upload(e)}}}render(){let e=this._data?.reports??[];return y`${this._drop.overlay(`Drop link reports to import`)}<div class="wrap">${this._nav()}<h1 class="sr-only">Deduplication</h1><div class="page-intro"><p class="intro">Link duplicate findings across all teams.</p><span class="result-count">${this._data?e.length:`…`} reports</span><button type="button" class="btn" @click="${()=>p(`manage-scans`,{scanMode:`link`})}">Link reports</button></div><div class="drop-card">${this._drop.card(`Import link reports`,`Drop *.link.json files anywhere on this page.`,this._busy||!this._csrf,`Saving…`)}</div>${C(this._error)} ${this._list(this._data,`Loading deduplication reports…`,()=>e.length===0?w(`No link reports imported yet`,`Each row in a link report lists IDs for the same finding.`):y`<div class="link-table"><table><thead><tr><th>Report</th><th>Groups</th><th>Finding IDs</th><th>Imported by</th><th>Imported</th><th>Status</th><th><span class="sr-only">Actions</span></th></tr></thead><tbody>${e.map(e=>y`<tr><td>${e.filename}</td><td>${e.groupCount}</td><td>${e.findingCount}</td><td>${e.uploadedByLogin??`Removed user`}</td><td>${new Date(e.uploadedAt).toLocaleDateString()}</td><td>${e.enabled?`Enabled`:`Disabled`}</td><td><button type="button" class="btn" aria-label="${`View ${e.filename}`}" @click="${()=>p(`manage-deduplication`,{linkId:e.id})}">View</button> <button type="button" class="btn" ?disabled="${this._busy}" aria-label="${`${e.enabled?`Disable`:`Enable`} ${e.filename}`}" @click="${()=>{this._toggle(e)}}">${e.enabled?`Disable`:`Enable`}</button></td></tr>`)}</tbody></table></div>`)}</div>`}};customElements.define(`managed-admin-deduplication`,$i);var ea=[[75,`critical`],[50,`high`],[25,`moderate`],[0,`low`]],ta=e=>ea.find(([t])=>e>=t)[1],na={osv:`OSV`,repository:`The repository’s own GitHub advisories`,registry:`npm registry`,packagist:`Packagist`,rubysec:`RubySec`,dependabot:`Dependabot`},ra=e=>e===`dependabot`?g($e):De(e),ia={critical:`Critical`,high:`High`,moderate:`Moderate`,low:`Low`},aa=e=>typeof e==`string`&&/^GHSA(?:-[\da-z]{4}){3}$/iu.test(e),oa=e=>typeof e==`string`&&/^CVE-\d{4}-\d{4,}$/iu.test(e);function sa(e){if(!aa(e.id))return[e.id];let t=[...new Set((e.aliases??[]).filter(oa).map(e=>e.toUpperCase()))];return t.length>0?t:[e.id]}var ca=e=>typeof e.url==`string`&&/^https:\/\//iu.test(e.url)?e.url:null;function la(e,t){return new Set([e.id,...e.aliases??[]].filter(aa).map(e=>e.toUpperCase())).size>1?`https://github.com/advisories?query=${encodeURIComponent(t)}`:ca(e)}var ua=e=>[...new Set([...e.ranges??[],...e.range?[e.range]:[]].flatMap(e=>e.split(/\s*\|\|\s*/u)).filter(Boolean))];function da(e,t=sa(e)[0]){let n=ua(e),r=[...new Set([e.id,...e.aliases??[]].filter(e=>typeof e==`string`).map(e=>oa(e)?e.toUpperCase():e))].filter(e=>e.toUpperCase()!==t.toUpperCase()),i=[...new Set((e.related??[]).filter(e=>typeof e==`string`))].filter(e=>!r.includes(e)&&e.toUpperCase()!==t.toUpperCase()),a=e.malware?`critical`:!e.unrated&&Object.hasOwn(ia,e.severity)?e.severity:`unrated`,o=e.malware?`Malware`:e.informational?`${e.informational[0].toUpperCase()}${e.informational.slice(1)}`:null;return{meta:[t],chips:[...o?[{level:e.malware?`critical`:`unrated`,said:o}]:[],{level:a,said:`${ia[a]??`Unrated`}${Number.isFinite(e.cvss)?`, CVSS ${e.cvss.toFixed(1)}`:``}`}],title:e.title||null,rows:[n.length>0?[`Affected`,n]:null,e.versions?.length?[`Versions`,e.versions.join(`, `)]:null,e.cwe?.length?[`CWE`,e.cwe.join(`, `)]:null,r.length>0?[`Also`,r]:null,i.length>0?[`Related`,i]:null].filter(Boolean),source:e.source?{said:na[e.source]??e.source,icon:ra(e.source)}:null}}var fa=({meta:e,chips:t,title:n,rows:r,source:i})=>[[...e,...t.map(e=>e.said)].join(` · `),n,...r.map(([e,t])=>`${e}: ${Array.isArray(t)?t.join(e===`Affected`?` || `:`, `):t}`),i&&`Source: ${i.said}`].filter(Boolean).join(`
18
+ `)}var Vi=class extends Ii{static kind=`bundle`;static view=`manage-bundles`;static collection=[`bundles`,`bundles`,Sr];static upload=Cr;static uploadFamilies=[`bundles`,`bundle-metadata`,`reports`,`repo-impact`,`history`,`scan-sources`];static importFamilies=[`bundles`,`reports`,`repo-impact`,`history`,`scan-sources`];static setVisible=Er;static visibleFamilies=[`bundles`,`teams`,`history`,`scan-sources`];static setRepo=Dr;static locationFamilies=[`bundles`,`teams`,`repo-impact`,`history`,`scan-sources`];static hintSource=`metadata`;static uploadCopy=`Drop source archives here or browse files above.`;static properties={createRepoId:{attribute:!1},installTooltips:{attribute:!1},_visibilityBusy:{state:!0},_deleting:{state:!0},_creating:{state:!0}};static styles=[v(Rr),v(zr),v(r),v(Mr)];constructor(){super(),Object.assign(this,{_visibilityBusy:null,_deleting:null,_creating:!1})}_acceptsDrop(){return!this._creating}_searchText(e){return[e.filename,e.repoFullName,e.repoDirectory,e.kind,e.provenance===`build`?`built`:null,e.uploadedByLogin]}_visible(e){return e.visible!==!1}_suggests(e){return e.kind===`stasis`}_fetchOrigin(e,t){return Ct(e,{signal:t})}_suggestion(e){return{github:e.github,directory:typeof e.directory==`string`?e.directory:e.root===!0?`/`:null}}_originRepo(e,t){let n=at({repo:e})?.toLowerCase();return n&&t.find(e=>e.fullName.toLowerCase()===n)}_showCreate(e){!e&&this.createRepoId!=null?p(`manage-bundles`):(this._creating=e,this._drop.active=!1,e||this.updateComplete.then(()=>this.renderRoot.querySelector(`.create-bundle-action`)?.focus()))}willUpdate(e){e.has(`createRepoId`)&&(this._creating=this.createRepoId!=null)}render(){return this._creating?y`<div class="wrap">${this._nav()} ${vi(`Bundles`,`Back to bundles`,()=>this._showCreate(!1),`Create a bundle`)}<managed-create-bundle .initialRepoId="${this.createRepoId??null}" .installTooltips="${this.installTooltips}" .createBundle="${this._csrf?(e,t)=>this.appState.mutate(()=>mr(e,this._csrf,t),[`bundles`,`bundle-metadata`,`reports`,`repo-impact`,`history`,`scan-sources`]):void 0}" @bundle-created="${e=>this._emit(`managed-bundle-open`,e.detail)}"></managed-create-bundle></div>`:this._page(y`<p class="intro">Source bundles for your repositories.</p><div class="bundle-actions">${this._localImport.renderAction()}<button type="button" class="local-import-toggle create-bundle-action" ?disabled="${!this._data}" @click="${()=>this._showCreate(!0)}">Create</button></div>`,y`<section class="drop-card" aria-label="Upload bundles">${this._drop.card(`Upload source bundles`,`Drop source archives anywhere on this page.`,this._busy)}</section>`)}_count(e,t){let n=this._data!=null,r=e.filter(e=>e.repoId==null).length,i=e.reduce((e,t)=>e+(Number.isFinite(t.byteSize)?t.byteSize:0),0);return y`<span class="summary result-count" role="status"><span>${n?t:`… bundles`}</span><span>${n?Ke(i):`…`}</span> ${!n||r?y`<span class="unassigned">${n?`${r} unattached`:`… unattached`}</span>`:b}</span>`}_items(e){let t=[...Map.groupBy(e,e=>e.repoFullName||`Unattached`)].toSorted(([e],[t])=>e===`Unattached`?-1:t===`Unattached`?1:e.localeCompare(t));return y`<div class="bundle-groups">${t.map(([e,t])=>y`<section class="bundle-group"><div class="bundle-group-head"><strong>${e}</strong><span>${t.length} ${t.length===1?`bundle`:`bundles`}</span></div><ul class="bundles">${t.map(e=>this._row(e))}</ul></section>`)}</div>`}_row(e){let t=e.visible!==!1,n=Fi(e);return y`<li class="${`bundle-row${t?``:` content-hidden`}`}"><span class="identity"><span class="bundle-icon" aria-hidden="true">${e.kind===`stasis`?y`<img src="./stasis.svg" width="16" height="16" alt="">`:Ri}</span> <button type="button" class="filename bundle-open" data-tooltip-truncated data-tooltip="${e.filename}" @click="${()=>this._emit(`managed-bundle-open`,e)}">${e.filename}</button> ${e.provenance===`build`?y`<span class="bundle-provenance" data-tooltip="Generated on this server from the repository">Built</span>`:b} </span><span class="meta bundle-uploader" data-tooltip-truncated data-tooltip="${e.uploadedByLogin?`@${e.uploadedByLogin}`:``}">${e.uploadedByLogin?`@${e.uploadedByLogin}`:``}</span> <span class="meta bundle-date">${Pi(e)}</span> <span class="meta bundle-size">${Ke(e.byteSize)}</span> <span class="bundle-location" data-tooltip-truncated data-tooltip="${n}">${n}</span> <span class="${`status ${t?`visible`:`hidden`}`}">${t?`Visible`:`Hidden`}</span> <span class="actions">${e.canChangeRepo===!1?b:y`<button type="button" class="action" aria-label="${`Set location for ${e.filename}`}" data-tooltip="Set repository location" ?disabled="${this._locationBusy}" @click="${()=>this._openLocation(e)}">${m(`repo`)}</button>`} <button type="button" class="action" aria-label="${`${t?`Hide`:`Make visible`} ${e.filename}`}" data-tooltip="${t?`Hide from teams`:e.repoId==null?`Assign a repository before publishing`:`Make visible to teams`}" ?disabled="${this._visibilityBusy!=null||e.canChangeRepo===!1||!t&&e.repoId==null}" @click="${()=>{this._setVisible(e,!t)}}">${m(t?`hide`:`show`)}</button> <a class="action" aria-label="${`Download ${e.filename}`}" href="${`/api/admin/bundles/${encodeURIComponent(e.id)}`}"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M8 2v8m-3-3 3 3 3-3M3 11v3h10v-3"/></svg></a><button type="button" class="action danger" aria-label="${`Delete ${e.filename}`}" ?disabled="${e.canChangeRepo===!1||this._deleting!=null}" data-tooltip="${e.canChangeRepo===!1?`Repository access is required to detach or delete this bundle`:b}" @click="${()=>this._delete(e)}">${mi}</button> </span>${this._locationId===e.id?this._locationEditor(e):b}</li>`}async _setVisible(e,t){if(this._visibilityBusy==null&&e.canChangeRepo!==!1){this._visibilityBusy=e.id;try{await super._setVisible(e,t)}finally{this._visibilityBusy=null}}}_openLocation(e){this._locationBusy||super._openLocation(e)}_saveLocation(e){return e.canChangeRepo===!1?Promise.resolve():super._saveLocation(e)}async _delete(e){if(this._deleting==null&&e.canChangeRepo!==!1){this._deleting=e.id,this._error=null;try{let t;try{t=await wr(e.id)}catch(t){this._error=`Couldn't check which reports use \u201C${e.filename}\u201D: ${String(t?.message??t)}`;return}if(!globalThis.confirm?.(Bi(e,t)))return;try{await this.appState.mutate(()=>Tr(e.id,this._csrf),[`bundles`,`bundle-metadata`,`reports`,`repo-impact`,`history`,`scan-sources`])}catch(e){this._error=`Delete failed: ${String(e?.message??e)}`}await this._load({preserveError:!0})}finally{this._deleting=null}}}};customElements.define(`managed-admin-bundles`,Vi);var Hi=class extends x{static view=`manage-scans`;static properties={selection:{attribute:!1},_source:{state:!0}};static styles=v(r);static collection=[`bundles`,`bundles`,Sr];constructor(){super(),this._source=null,this._loadModels=(e,t)=>this.appState.load(`models`,`scan models`,e=>n(e,l),{signal:e,apply:t}),this._loadReportSources=(e,n)=>this.appState.load(`scan-sources`,`scan report inputs`,async e=>{let[n,r]=await Promise.all([l(`/api/admin/reports`,{signal:e,credentials:`same-origin`}),l(`/api/admin/scan-results`,{signal:e,credentials:`same-origin`})]);if(!n.ok)throw Error(`Reports: HTTP ${n.status}`);if(!r.ok&&r.status!==404)throw Error(`Scan results: HTTP ${r.status}`);let i=await n.json();return i.reports=await Promise.all((i.reports??[]).filter(e=>e.visible&&e.repoId!=null).map(async t=>{let n=await l(`/api/admin/reports/${encodeURIComponent(t.id)}`,{signal:e,credentials:`same-origin`});if(!n.ok)throw Error(`Report ${h(t.filename)}: HTTP ${n.status}`);return{...t,content:await n.text()}})),t(i,r.ok?await r.json():{bundles:[],results:[]})},{signal:e,apply:n})}_load(){return Pe().catch(e=>{this._error=String(e?.message??e)}),super._load()}_show(e){this._source=ti(e)}render(){return y`<div class="wrap">${this._nav()} ${this._error?y`<p class="msg error" role="alert">Couldn’t load scan sources: ${this._error} <button type="button" class="btn" @click="${()=>{this._load()}}">Retry</button></p>`:b}<deepview-scan-page hide-heading .selection="${this.selection}" .source="${this._source}" .sourceLoading="${this._loading&&this._source==null}" .loadBundle="${ni}" .loadModels="${this._loadModels}" .loadReportSources="${this._loadReportSources}" .createBundleHref="${e=>Number.isSafeInteger(e)&&e>0?rt({view:`manage-bundles`,createRepoId:e}):null}"></deepview-scan-page></div>`}};customElements.define(`managed-admin-scans`,Hi);var Ui=(e,t)=>new Map([...e].filter(([e])=>e!==t)),Wi=y`<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="6" cy="5" r="2.5"/><path d="M1.5 13v-1c0-2 1.8-3.5 4.5-3.5s4.5 1.5 4.5 3.5v1M11 2.5a2.5 2.5 0 0 1 0 5M12 9c1.7.5 2.5 1.5 2.5 3v1"/></svg>`,Gi=(e,t)=>(e.icon?.id??null)===(t?.id??null);function Ki(e,{organizations:t,unchecked:n}){return[t.length>0?`Organizations that own this team’s repositories.`:e.repos.length===0?`Link a repository owned by an organization to use its avatar.`:n.length===0?`None of this team’s repositories belong to an organization.`:``,n.length>0?`Couldn\u2019t check ${n.join(`, `)} on GitHub.`:``].filter(Boolean).join(` `)}var qi=class extends x{static view=`manage-teams`;static properties={_busy:{state:!0},_renamingId:{state:!0},_repoChoices:{state:!0},_memberChoices:{state:!0},_iconPicker:{state:!0}};static styles=[v(Br),v(Me),v(r)];static collection=[`teams`,`teams`,Or];constructor(){super(),Object.assign(this,{_busy:!1,_renamingId:null,_repoChoices:new Map,_memberChoices:new Map,_iconPicker:null})}async _do(e){if(!this._busy){this._busy=!0,this._error=null;try{await this.appState.mutate(e,[`teams`,`users`,`reports`,`history`,`repos`]),globalThis.dispatchEvent?.(new Event(`dependency-review-changed`))}catch(e){this._error=String(e?.message??e)}finally{this._busy=!1,await this._load({preserveError:!0})}}}_post(e,t,n=()=>{}){return this._do(async()=>{await Ar(e,this._csrf,t),n()})}render(){return y`<div class="wrap">${this._nav()}<h1 class="sr-only">Teams</h1><div class="page-intro"><p class="intro">Manage repository and finding access for each team.</p><span class="result-count">${this._data?.teams?.length??`…`} teams</span></div><div class="create-team"><label class="sr-only" for="new-team-name">New team</label> <input id="new-team-name" class="new-name" type="text" placeholder="Team name" maxlength="100" ?disabled="${this._busy}" @keydown="${e=>{e.key===`Enter`&&this._create()}}"> <button class="btn primary" ?disabled="${this._busy}" @click="${()=>this._create()}">${B} Create team</button><p class="access-note ui-hint">All members can view standard findings. Set dependencies and security access per member.</p></div><div class="manage-list" aria-busy="${this._loading}">${this._body()}</div></div>`}_body(){if(this._error!=null&&this._data==null)return y`<p class="msg error">Couldn't load teams: ${this._error}</p>`;if(this._data==null)return S(`Loading teams…`);let e=Array.isArray(this._data.teams)?this._data.teams:[];return y`${this._error==null?b:y`<p class="msg error">${this._error}</p>`} ${e.length===0?y`<p class="msg">No teams yet. Create one above.</p>`:e.map(e=>this._team(e))}`}_team(e){return y`<section class="team" aria-label="${e.name}"><div class="team-head"><button type="button" class="team-icon" aria-label="${`Change icon of ${e.name}`}" title="Change icon" aria-expanded="${String(this._iconPicker?.teamId===e.id)}" @click="${()=>{this._toggleIconPicker(e)}}">${je(e,Wi)}</button> ${this._renamingId===e.id?y`<input class="rename-input" type="text" .value="${e.name}" maxlength="100" aria-label="Team name" @keydown="${t=>this._renameKey(t,e)}"> <button class="btn" ?disabled="${this._busy}" @click="${t=>this._saveRename(e,t)}">Save</button> <button class="btn" @click="${()=>{this._renamingId=null}}">Cancel</button>`:y`<h2 class="team-name">${e.name}</h2>${e.hidden?y`<span class="muted ui-hint">Disabled</span>`:b} <span class="team-actions"><button class="icon-btn" aria-label="${`${e.hidden?`Restore`:`Hide`} ${e.name}`}" ?disabled="${this._busy}" @click="${()=>this._post(`/set-hidden`,{teamId:e.id,hidden:!e.hidden})}">${m(e.hidden?`show`:`hide`)}</button> <button class="icon-btn" aria-label="${`Rename ${e.name}`}" ?disabled="${this._busy}" @click="${()=>{this._renamingId=e.id}}">${pi}</button> <button class="icon-btn danger" aria-label="${`Delete ${e.name}`}" ?disabled="${this._busy}" @click="${()=>this._deleteTeam(e)}">${mi}</button></span>`}</div>${this._iconChoices(e)}<div class="team-body">${[[`Repositories`,e.repos,`No repositories linked.`,t=>this._repoRow(e,t),this._addRepoRow(e)],[`Members`,e.members,`No members.`,t=>this._memberRow(e,t),this._addMemberRow(e)]].map(([e,t,n,r,i])=>y`<div class="sub"><h3 class="sub-title">${e} <span class="count">${t.length}</span></h3>${t.length===0?y`<p class="muted ui-hint">${n}</p>`:y`<ul class="links">${t.map(r)}</ul>`} ${i}</div>`)}${this._npmScopes(e)}</div></section>`}async _toggleIconPicker(e){if(this._iconPicker?.teamId===e.id){this._iconPicker=null;return}let t={teamId:e.id,choices:null,error:null};this._iconPicker=t;try{let n=await jr(e.id);this._iconPicker===t&&(this._iconPicker={...t,choices:n})}catch(e){this._iconPicker===t&&(this._iconPicker={...t,error:String(e?.message??e)})}}_iconChoices(e){let t=this._iconPicker;if(t?.teamId!==e.id)return b;let n=t.choices?.organizations??[],r=e.icon&&!n.some(t=>t.id===e.icon.id)?[e.icon,...n]:n,i=(t,n)=>y`<button type="button" class="icon-choice" aria-pressed="${String(Gi(e,t))}" ?disabled="${this._busy}" @click="${()=>this._chooseIcon(e,t)}"><span class="icon-choice-image">${je({icon:t},Wi)}</span><span class="ln">${n}</span></button>`;return y`<div class="icon-picker" role="group" aria-label="${`Icon of ${e.name}`}"><div class="icon-choices">${i(null,`No icon`)}${r.map(e=>i(e,e.login))}</div>${t.error?C(`Couldn\u2019t load organizations: ${t.error}`):t.choices==null?y`<p class="muted ui-hint" role="status">Loading organizations…</p>`:y`<p class="muted ui-hint">${Ki(e,t.choices)}</p>`}</div>`}_chooseIcon(e,t){Gi(e,t)?this._iconPicker=null:this._post(`/set-icon`,{teamId:e.id,organization:t?.login??null},()=>{this._iconPicker=null})}_npmScopes(e){let t=Array.isArray(e.npmScopes)?e.npmScopes:[];return y`<div class="sub npm-scopes"><div class="sub-head"><h3 class="sub-title">npm scopes <span class="count">${t.length}</span><mode-switch class="npm-review-toggle" label="Enable dependency review" .checked="${!!e.dependencyReview}" .disabled="${this._busy}" @click="${()=>{this._busy||this._post(`/set-dependency-review`,{teamId:e.id,enabled:!e.dependencyReview})}}"></mode-switch></h3><p class="muted ui-hint">Members can open private packages in these scopes. Everyone can open public packages.</p></div><div class="add-row npm-scope-row"><input class="add-npm-scope" type="text" placeholder="@scope" aria-label="${`npm scope to add to ${e.name}`}" maxlength="215" ?disabled="${this._busy}" @keydown="${t=>{t.key===`Enter`&&this._addNpmScope(e,t)}}"> <button class="btn" aria-label="${`Add npm scope to ${e.name}`}" ?disabled="${this._busy}" @click="${t=>this._addNpmScope(e,t)}">${B} Add</button> ${t.length===0?b:y`<ul class="npm-scope-list">${t.map(n=>y`<li class="npm-scope"><span>${n}</span> <button class="icon-btn danger" aria-label="${`Remove ${n} from ${e.name}`}" ?disabled="${this._busy}" @click="${()=>this._post(`/set-npm-scopes`,{teamId:e.id,scopes:t.filter(e=>e!==n)})}">${hi}</button></li>`)}</ul>`}</div></div>`}_addNpmScope(e,t){let n=t.target.closest(`.add-row`)?.querySelector(`.add-npm-scope`);if(!n?.value.trim())return;let r=nt(n.value);if(r===null){this._error=`\u201C${n.value.trim()}\u201D is not an npm scope. Scopes look like @example.`;return}let i=Array.isArray(e.npmScopes)?e.npmScopes:[];i.includes(r)?n.value=``:this._post(`/set-npm-scopes`,{teamId:e.id,scopes:[...i,r]},()=>{n.value=``})}_repoRow(e,t){return y`<li class="repo-row">${gi} <span class="repo-copy"><span class="ln">${t.fullName}</span>${t.path?y`<span class="path">/${t.path.replace(/^\/+/u,``)}</span>`:b}</span> <button class="icon-btn danger" aria-label="${`Remove ${t.fullName}${t.path?`/${t.path}`:``} from ${e.name}`}" ?disabled="${this._busy}" @click="${()=>this._post(`/remove-repo`,{teamId:e.id,repoId:t.repoId,path:t.path??null})}">${hi}</button></li>`}_addRepoRow(e){let t=Array.isArray(this._data.repos)?this._data.repos:[];if(t.length===0)return y`<p class="muted ui-hint">No selected repositories to link — pick some on “Manage repositories”.</p>`;let n=new Set(e.repos.filter(e=>!e.path).map(e=>e.repoId)),r=t.filter(e=>!n.has(e.repoId));return r.length===0?y`<p class="muted ui-hint">Every selected repository is linked.</p>`:y`<div class="add-row"><repository-selector class="add-repo-sel" label="${`Repository to add to ${e.name}`}" placeholder="Add repository…" ?disabled="${this._busy}" .options="${r.map(e=>({value:e.repoId,label:e.fullName}))}" .value="${this._repoChoices.get(e.id)??null}" @repository-change="${t=>{this._repoChoices=new Map(this._repoChoices).set(e.id,t.detail.value)}}"></repository-selector><input class="add-repo-path" type="text" placeholder="Path (optional)" aria-label="${`Repository path in ${e.name} (optional)`}" maxlength="500" ?disabled="${this._busy}"> <button class="btn" aria-label="${`Add repository to ${e.name}`}" ?disabled="${this._busy||!this._repoChoices.has(e.id)}" @click="${t=>this._addRepo(e,t)}">${B} Add</button></div>`}_fullAccess(e){return this._data.users?.some(t=>t.id===e.userId&&Le(t.role,`manage`))}_memberRow(e,t){let n=Array.isArray(this._data.permissions)?this._data.permissions:[],r=this._fullAccess(t);return y`<li class="member-row"><span class="member">${li(t.userId,t.login)}<span class="ln">${t.login}</span></span> <span class="perms">${n.map(n=>y`<label class="perm"><input type="checkbox" .checked="${r||t[n]===!0}" ?disabled="${this._busy||r}" aria-label="${`${o[n]??n} access for ${t.login} in ${e.name}`}" @change="${r=>this._togglePerm(e,t,n,r.target.checked)}"> ${o[n]??n}</label>`)} </span><button class="icon-btn danger" aria-label="${`Remove ${t.login} from ${e.name}`}" ?disabled="${this._busy}" @click="${()=>this._post(`/remove-member`,{teamId:e.id,userId:t.userId})}">${hi}</button></li>`}_addMemberRow(e){let t=Array.isArray(this._data.users)?this._data.users:[],n=new Set(e.members.map(e=>e.userId));return y`<div class="add-row"><user-selector class="add-member-sel" label="${`Member to add to ${e.name}`}" placeholder="Add member…" ?disabled="${this._busy}" .users="${t.map(e=>({...e,disabled:n.has(e.id),detail:n.has(e.id)?`Member`:``}))}" .value="${this._memberChoices.get(e.id)??null}" @user-change="${t=>{this._memberChoices=new Map(this._memberChoices).set(e.id,t.detail.value)}}"></user-selector><button class="btn" aria-label="${`Add member to ${e.name}`}" ?disabled="${this._busy||!this._memberChoices.has(e.id)||n.has(this._memberChoices.get(e.id))}" @click="${()=>this._addMember(e)}">${B} Add</button></div>`}_create(){let e=this.renderRoot.querySelector(`.new-name`),t=e?.value.trim();t&&this._post(``,{name:t},()=>{e&&(e.value=``)})}_deleteTeam(e){globalThis.confirm?.(`Delete team \u201C${e.name}\u201D? Its repo + member links are removed.`)&&this._post(`/delete`,{teamId:e.id})}_renameKey(e,t){e.key===`Enter`?this._saveRename(t,e):e.key===`Escape`&&(this._renamingId=null)}_saveRename(e,t){if(this._busy)return;let n=t.target.closest(`.team-head`)?.querySelector(`.rename-input`)?.value.trim()??``;this._renamingId=null,n!==``&&n!==e.name&&this._post(`/rename`,{teamId:e.id,name:n})}_addRepo(e,t){let n=t.target.closest(`.add-row`)?.querySelector(`.add-repo-path`),r=this._repoChoices.get(e.id);!Number.isSafeInteger(r)||r<=0||this._post(`/set-repo`,{teamId:e.id,repoId:r,path:n?.value??``},()=>{this._repoChoices=Ui(this._repoChoices,e.id),n&&(n.value=``)})}_addMember(e){let t=this._memberChoices.get(e.id);!t||e.members.some(e=>e.userId===t)||this._post(`/set-member`,{teamId:e.id,userId:t},()=>{this._memberChoices=Ui(this._memberChoices,e.id)})}_togglePerm(e,t,n,r){if(this._fullAccess(t))return;let i={...Object.fromEntries((this._data.permissions??[]).map(e=>[e,t[e]===!0])),[n]:r};this._post(`/set-member`,{teamId:e.id,userId:t.userId,...i})}};customElements.define(`managed-admin-teams`,qi);var Ji=`.link-team{margin-top:1.5rem}.link-team h2{margin:0 0 .5rem;font-size:1rem;font-weight:600}.link-table{overflow-x:auto}table{width:100%;border-collapse:collapse;text-align:left;font-size:.8rem}th{color:var(--muted);font-weight:500}th,td{padding:.6rem .65rem;border-bottom:1px solid var(--border);white-space:nowrap}th:first-child,td:first-child{padding-left:0}th:last-child,td:last-child{padding-right:0;text-align:right}
19
+ `;async function Yi(e){let t=await l(`/api/admin/links`,{signal:e,credentials:`same-origin`});if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();if(!Array.isArray(n?.shares))throw TypeError(`No public links returned`);return n}var Xi=class extends x{static view=`manage-links`;static styles=[v(r),v(Ji)];static collection=[`links`,`public links`,Yi];async _edit(e){await Se({id:e.teamId,name:e.teamName},e.id,this.session),this.isConnected&&await this._load()}_groups(){return[...Map.groupBy(this._data?.shares??[],e=>e.teamId).values()].map(e=>({name:e[0].teamName,links:e}))}_body(){return this._data==null?this._error?y`<p class="msg error">Couldn't load public links: ${this._error}</p>`:S(`Loading public links…`):this._data.shares.length===0?y`<p class="msg">No public links. Create one with the share button beside a workspace in the sidebar.</p>`:this._groups().map(e=>y`<section class="link-team" aria-label="${e.name}"><h2>${e.name}</h2><div class="link-table"><table><thead><tr><th>Link</th><th>Created by</th><th>Created</th><th>Security</th><th>Dependencies</th><th><span class="sr-only">Actions</span></th></tr></thead><tbody>${e.links.map(t=>y`<tr><td><span data-tooltip="${t.id}">${t.id.slice(0,8)}</span></td><td>${t.createdBy}</td><td>${new Date(t.createdAt).toLocaleString()}</td><td>${t.permissions.security?`On`:`Off`}</td><td>${t.permissions.dependencies?`On`:`Off`}</td><td><button class="btn" aria-label="${`Edit public link ${t.id.slice(0,8)} for ${e.name}`}" @click="${()=>this._edit(t)}">Edit</button></td></tr>`)}</tbody></table></div></section>`)}render(){return y`<div class="wrap">${this._nav()}<h1 class="sr-only">Public links</h1><div class="page-intro"><p class="intro">Manage public links and the findings each link can show.</p><span class="result-count">${this._data?.shares.length??`…`} links</span></div>${this._loading&&this._data?y`<span class="sr-only" role="status">Refreshing public links…</span>`:b}<div class="manage-list" aria-busy="${this._loading}">${this._body()}</div></div>`}};customElements.define(`managed-admin-links`,Xi);var Zi=Xn(`/api/admin/deduplication`,{"storage-encryption-required":`Configure MANAGED_STORAGE_ENCRYPTION_KEY on the server to import encrypted link reports.`,"invalid-link-report":`Choose a link report containing arrays of finding IDs, such as [["id1", "id2"]].`,"too-large":`This link report exceeds the server upload limit.`}),Qi=[`deduplication`,`reports`,`teams`],$i=class extends x{static view=`manage-deduplication`;static properties={_busy:{state:!0}};static styles=[v(r),v(Lr),v(Ji)];static collection=[`deduplication`,`deduplication reports`,e=>Zi(``,{signal:e})];constructor(){super(),this._busy=!1,this._queue=[],this._drop=new ht(this)}_upload(e){if(this._csrf&&this._role===`admin`)return mt(this,e,e=>Zi(``,{method:`POST`,headers:{"content-type":`application/json`,"x-report-filename":encodeURIComponent(e.name),"x-csrf-token":this._csrf},body:e}),Qi)}async _toggle(e){if(!this._busy&&this._csrf){this._busy=!0,this._error=null;try{await this.appState.mutate(()=>Zi(`/${encodeURIComponent(e.id)}`,{method:`PATCH`,headers:{"content-type":`application/json`,"x-csrf-token":this._csrf},body:JSON.stringify({enabled:!e.enabled})}),Qi)}catch(e){this._error=String(e?.message??e)}finally{this._busy=!1,await this._load({preserveError:!0});let e=this._queue.splice(0);e.length>0&&this._upload(e)}}}render(){let e=this._data?.reports??[];return y`${this._drop.overlay(`Drop link reports to import`)}<div class="wrap">${this._nav()}<h1 class="sr-only">Deduplication</h1><div class="page-intro"><p class="intro">Link duplicate findings across all teams.</p><span class="result-count">${this._data?e.length:`…`} reports</span><button type="button" class="btn" @click="${()=>p(`manage-scans`,{scanMode:`link`})}">Link reports</button></div><div class="drop-card">${this._drop.card(`Import link reports`,`Drop *.link.json files anywhere on this page.`,this._busy||!this._csrf,`Saving…`)}</div>${C(this._error)} ${this._list(this._data,`Loading deduplication reports…`,()=>e.length===0?w(`No link reports imported yet`,`Each row in a link report lists IDs for the same finding.`):y`<div class="link-table"><table><thead><tr><th>Report</th><th>Groups</th><th>Finding IDs</th><th>Imported by</th><th>Imported</th><th>Status</th><th><span class="sr-only">Actions</span></th></tr></thead><tbody>${e.map(e=>y`<tr><td>${e.filename}</td><td>${e.groupCount}</td><td>${e.findingCount}</td><td>${e.uploadedByLogin??`Removed user`}</td><td>${new Date(e.uploadedAt).toLocaleDateString()}</td><td>${e.enabled?`Enabled`:`Disabled`}</td><td><button type="button" class="btn" aria-label="${`View ${e.filename}`}" @click="${()=>p(`manage-deduplication`,{linkId:e.id})}">View</button> <button type="button" class="btn" ?disabled="${this._busy}" aria-label="${`${e.enabled?`Disable`:`Enable`} ${e.filename}`}" @click="${()=>{this._toggle(e)}}">${e.enabled?`Disable`:`Enable`}</button></td></tr>`)}</tbody></table></div>`)}</div>`}};customElements.define(`managed-admin-deduplication`,$i);var ea=[[75,`critical`],[50,`high`],[25,`moderate`],[0,`low`]],ta=e=>ea.find(([t])=>e>=t)[1],na={osv:`OSV`,repository:`The repository’s own GitHub advisories`,registry:`npm registry`,packagist:`Packagist`,rubysec:`RubySec`,dependabot:`Dependabot`},ra=e=>e===`dependabot`?g(Je):De(e),ia={critical:`Critical`,high:`High`,moderate:`Moderate`,low:`Low`},aa=e=>typeof e==`string`&&/^GHSA(?:-[\da-z]{4}){3}$/iu.test(e),oa=e=>typeof e==`string`&&/^CVE-\d{4}-\d{4,}$/iu.test(e);function sa(e){if(!aa(e.id))return[e.id];let t=[...new Set((e.aliases??[]).filter(oa).map(e=>e.toUpperCase()))];return t.length>0?t:[e.id]}var ca=e=>typeof e.url==`string`&&/^https:\/\//iu.test(e.url)?e.url:null;function la(e,t){return new Set([e.id,...e.aliases??[]].filter(aa).map(e=>e.toUpperCase())).size>1?`https://github.com/advisories?query=${encodeURIComponent(t)}`:ca(e)}var ua=e=>[...new Set([...e.ranges??[],...e.range?[e.range]:[]].flatMap(e=>e.split(/\s*\|\|\s*/u)).filter(Boolean))];function da(e,t=sa(e)[0]){let n=ua(e),r=[...new Set([e.id,...e.aliases??[]].filter(e=>typeof e==`string`).map(e=>oa(e)?e.toUpperCase():e))].filter(e=>e.toUpperCase()!==t.toUpperCase()),i=[...new Set((e.related??[]).filter(e=>typeof e==`string`))].filter(e=>!r.includes(e)&&e.toUpperCase()!==t.toUpperCase()),a=e.malware?`critical`:!e.unrated&&Object.hasOwn(ia,e.severity)?e.severity:`unrated`,o=e.malware?`Malware`:e.informational?`${e.informational[0].toUpperCase()}${e.informational.slice(1)}`:null;return{meta:[t],chips:[...o?[{level:e.malware?`critical`:`unrated`,said:o}]:[],{level:a,said:`${ia[a]??`Unrated`}${Number.isFinite(e.cvss)?`, CVSS ${e.cvss.toFixed(1)}`:``}`}],title:e.title||null,rows:[n.length>0?[`Affected`,n]:null,e.versions?.length?[`Versions`,e.versions.join(`, `)]:null,e.cwe?.length?[`CWE`,e.cwe.join(`, `)]:null,r.length>0?[`Also`,r]:null,i.length>0?[`Related`,i]:null].filter(Boolean),source:e.source?{said:na[e.source]??e.source,icon:ra(e.source)}:null}}var fa=({meta:e,chips:t,title:n,rows:r,source:i})=>[[...e,...t.map(e=>e.said)].join(` · `),n,...r.map(([e,t])=>`${e}: ${Array.isArray(t)?t.join(e===`Affected`?` || `:`, `):t}`),i&&`Source: ${i.said}`].filter(Boolean).join(`
20
20
  `),pa=({meta:e,chips:t,title:n,rows:r,source:i})=>y`<div class="advisory-tip"><div class="advisory-tip-head"><div class="advisory-tip-meta">${e.map(e=>y`<span>${e}</span>`)}</div><span class="advisory-tip-chips">${t.map(({level:e,said:t})=>y`<span class="${`advisory-tip-chip is-${e}`}">${t}</span>`)}</span></div>${n?y`<div class="advisory-tip-title">${n}</div>`:b} ${r.length>0||i?y`<div class="advisory-tip-rows">${r.map(([e,t])=>Array.isArray(t)?y`<span class="advisory-tip-label">${e}</span><div>${t.map(e=>y`<div class="advisory-tip-line">${e}</div>`)}</div>`:y`<span class="advisory-tip-label">${e}</span><span>${t}</span>`)}${i?y`<span class="advisory-tip-label">Source</span><span class="advisory-tip-source">${i.icon?y`<span class="advisory-tip-source-icon" aria-hidden="true">${i.icon}</span>`:b}${i.said}</span>`:b}</div>`:b}</div>`;function ma(e){let t=e.severity?`risk-${e.severity}`:``,n=n=>{let r=oa(n)?la(e,n):ca(e),i=da(e,n);return r?y`<a class="${`risk-advisory ${t}`.trim()}" href="${r}" target="_blank" rel="noopener noreferrer" data-tooltip="${fa(i)}" .tooltipContent="${pa(i)}">${n}${f}</a>`:y`<span class="${`risk-advisory ${t}`.trim()}" data-tooltip="${fa(i)}" .tooltipContent="${pa(i)}">${n}</span>`},r=sa(e);return r.length===1?n(r[0]):y`<span class="risk-advisory-ids">${r.map(n)}</span>`}var ha={unpinned:[`Unpinned`,`By a tag or a branch, which its repository’s owner can point anywhere, not a full commit sha.`],"short-sha":[`Short sha`,`A short sha, which GitHub reads as a branch or tag named so too.`],"unpinned-image":[`Image by tag`,`An image by a tag, which its publisher can move, not a digest.`],"fetched-package":[`Fetched package`,`A package fetched and run as it resolves now, past what a lockfile locks.`],"unlocked-install":[`Unlocked install`,`An install that resolves anew where package.json and the lockfile disagree; npm ci holds to the lockfile.`],"remote-script":[`Remote script`,`A script fetched and run as it is fetched.`],clone:[`Clone`,`A repository cloned at whatever its branch has.`],hosts:[`Host`,`A service malicious code sends what it takes to, or fetches what it runs from.`],"script-injection":[`Script injection`,`An expression anyone can write, in a script: what it holds runs as the script’s own code.`],"pwn-request":[`Runs a fork’s code`,`Checks out a pull request’s own code where the workflow runs with the base repository’s secrets.`],"untrusted-artifact":[`Untrusted artifact`,`Takes another run’s artifacts, which a fork’s pull request writes, where the workflow runs with secrets.`],"secrets-inherited":[`Inherits secrets`,`Another owner’s reusable workflow handed every secret.`],"invalid-uses":[`Invalid`,`A uses: GitHub can’t read.`],"deprecated-runtime":[`Old Node.js`,`A Node.js GitHub no longer runs actions on.`],"repo-missing":[`Repository missing`,`No such repository on GitHub: anyone who takes its owner’s name can publish one.`],"repo-moved":[`Repository moved`,`Renamed or transferred: GitHub redirects the old name until someone takes it.`],"repo-fork":[`Fork`,`A fork of another repository.`],"repo-archived":[`Archived`,`Archived by its owner.`],"branch-ref":[`Branch`,`A branch, which moves with every push.`],"ambiguous-ref":[`Tag and branch`,`A tag and a branch of the same name.`],"ref-missing":[`Ref missing`,`Neither a tag nor a branch: GitHub runs whichever is pushed first.`],"not-version":[`Not a version`,`A tag that is no version.`],"tag-off-release":[`Tag off release`,`A major or minor tag on a commit no release of its line is on, as a tag moved by whoever took the repository is.`],"tag-off-branch":[`Tag off branch`,`The tag’s commit is on none of its branches, as a release’s built files may be.`],outdated:[`Outdated`,`An older major version than the latest release.`],"imposter-commit":[`Imposter commit`,`In the history of none of the repository’s branches and releases: GitHub serves a fork’s commit under the name of the repository it forked.`],"unverified-commit":[`Unverified commit`,`In the history of none of the branches and releases looked at; it has more.`],"commit-missing":[`Commit missing`,`GitHub has no such commit.`],"untagged-commit":[`Untagged commit`,`A commit no tag names: no release.`],"comment-mismatch":[`Comment mismatch`,`The version or branch the comment beside it names isn’t this commit’s.`],"action-missing":[`No action.yml`,`No action.yml where it names, at the commit.`],unreadable:[`Unreadable`,`Its file couldn’t be read as GitHub reads it.`],advisory:[`Advisory`],"advisories-unavailable":[`Advisories unavailable`,`Its advisories couldn’t be had: asked again by the next scan.`]},ga={all:`All`,actions:`Actions`,steps:`Steps`},V=e=>Ce.includes(e)?Ce.indexOf(e):Ce.length,_a=e=>e.reduce((e,{severity:t})=>V(t)<V(e)?t:e,null);function va(e){return e.id===`hosts`?e.tag===`IP lookup`?e.tag:`${e.tag??``} host`.trimStart():e.id===`advisory`?e.advisory:ha[e.id]?.[0]??e.id}function ya(e){let t=[];if(e.id===`fetched-package`&&t.push(ba(e),...e.localFirst?[e.locked?e.installed?``:`locked, but run before any install`:`no lockfile here locks it`]:[]),e.services&&t.push(e.services.join(`, `)),e.expression&&t.push(`\${{ ${e.expression} }}`),e.to&&t.push(`now ${e.to}`),e.parent&&t.push(`of ${e.parent}`),e.latest&&t.push(`latest ${e.latest}`),e.release&&t.push(`its line\u2019s latest release is ${e.release}`),e.comment){let n=e.tags?.length?`tags here: ${e.tags.join(`, `)}`:`no tag is on it`;t.push(`# ${e.comment}, ${e.branch?`not in the history of branch ${e.branch}; ${n}`:n}`)}return e.image&&t.push(e.image),e.file&&t.push(`in ${e.file}${e.line?`, line ${e.line}`:``}`),e.detail&&t.push(e.detail),[ha[e.id]?.[1],...t.filter(Boolean)].filter(Boolean).join(`
21
- `)}function ba(e){return e.id===`fetched-package`?`${e.tool} ${e.name}${e.spec?`@${e.spec}`:``}`:e.id===`unlocked-install`?e.tool:e.id===`unpinned-image`?e.image:e.id===`clone`?`git clone ${e.url??``}`.trim():e.id===`hosts`?e.services.join(`, `):e.id===`script-injection`?`\${{ ${e.expression} }}`:e.id===`secrets-inherited`||e.id===`invalid-uses`?e.uses:e.id===`deprecated-runtime`?`runs.using: ${e.using}`:e.id===`remote-script`&&e.command?e.command:e.id===`pwn-request`&&e.ref?e.ref===`gh pr checkout`?e.ref:`actions/checkout ref: ${e.ref}`:va(e)}var xa=class{constructor(){this.listed=new Map,this.files=new Map,this.actions=new Map,this.built=null}apply(e){this.built=null,e.type===`workflows`?(this.forget(e.repo),this.listed.set(e.repo,e)):e.type===`workflow`?(this.files.get(e.repo)??this.files.set(e.repo,new Map).get(e.repo)).set(e.path,e):e.type!==`action`||e.error&&this.actions.has(e.key)||this.actions.set(e.key,e)}forget(e){this.listed.delete(e),this.files.delete(e),this.built=null}filesOf(e){return[...this.files.get(e)?.values()??[]]}told(){return this.listed.size+this.rows(`actions`).filter(e=>e.line).length+[...this.files.values()].reduce((e,t)=>e+t.size,0)}counts(){let e=this.rows(`actions`);return{workflows:[...this.listed.values()].reduce((e,t)=>e+(t.paths?.length??0),0),workflowsRead:[...this.files.values()].reduce((e,t)=>e+[...t.values()].filter(e=>e.kind===`workflow`).length,0),actions:e.length,resolved:e.filter(e=>e.line).length}}#e(){let e=new Map,t=new Map,n=t=>e.get(t)??e.set(t,{key:t,kind:`action`,usedIn:[],local:[]}).get(t);for(let[e,r]of this.files)for(let i of r.values()){for(let t of i.uses??[])t.key&&Object.assign(n(t.key),{uses:t}).usedIn.push({repo:e,path:i.path,line:t.line});for(let r of i.findings??[]){if(r.key){n(r.key).local.push(r);continue}let a=ba(r),o=`${r.id}\0${r.tag??``}\0${a}`,s=t.get(o)??t.set(o,{key:o,kind:`step`,name:a,findings:[r],severity:r.severity,usedIn:[]}).get(o);V(r.severity)<V(s.severity)&&Object.assign(s,{severity:r.severity,findings:[r]}),s.usedIn.push({repo:e,path:i.path,line:r.line})}}let r=[...e.keys()];for(let t=0;t<r.length;t++)for(let i of this.actions.get(r[t])?.uses??[])e.has(i)||r.push(i),n(i).usedIn.push({via:r[t]});for(let t of e.values()){let e=new Map;t.line=this.actions.get(t.key)??null;for(let n of[...t.local,...t.line?.findings??[]]){let t=`${n.id}\0${ba(n)}\0${n.file??``}\0${n.file?n.line:``}`;(!e.has(t)||V(n.severity)<V(e.get(t).severity))&&e.set(t,n)}t.findings=[...e.values()],t.severity=_a(t.findings)}let i=e=>e.findings.length>0?0:e.line?.error?1:e.line||e.kind===`step`?3:2;return[...e.values(),...t.values()].toSorted((e,t)=>V(e.severity)-V(t.severity)||i(e)-i(t)||t.findings.length-e.findings.length||(e.name??e.key).localeCompare(t.name??t.key))}rows(e,t=``){this.built??=this.#e();let n=t.trim().toLowerCase();return this.built.filter(t=>(e===`all`||e===`actions`==(t.kind===`action`))&&(!n||(t.name??t.key).toLowerCase().includes(n)))}};function Sa(e){if(!e||e.error||!e.commit)return null;let t=e.commit.slice(0,7),n=e.tags?.length?` (${e.tags.join(`, `)})`:``;return e.at===`sha`?`${t}${n}`:`${e.at} \u2192 ${t}${n}`}function Ca(e){return y`<ul class="risk-findings">${e.map(e=>e.id===`advisory`?y`<li class="${`risk-${e.severity}`}">${ma({...e,id:e.advisory})}</li>`:y`<li class="${`risk-${e.severity}`}" data-tooltip="${ya(e)||b}">${va(e)}${e.file?y`<span class="risk-in-code">in code</span>`:b}</li>`)}</ul>`}function wa({uses:e,line:t}){let n=t?.commit??e?.ref??t?.ref,r=t?.repository?.fullName??e?.repo??t?.repo;return r&&n?H(r,n,e?.path??t?.path,t?.kind===`workflow`||e?.kind===`workflow`?`blob`:`tree`):null}var H=(e,t,n,r=`blob`)=>`https://github.com/${e}/${r}/${encodeURIComponent(t)}${n?`/${He(n)}`:``}`,Ta=`.wrap{max-width:none}.wrap>:not(.manage-list,.sr-only),.manage-list>.risk-files,.risk-section>:not(.link-table,.risk-results-head),.risk-results-head>*{max-width:var(--page-width);margin-left:max(0px,(100cqw - var(--page-width)) / 2)}.wrap.team-risk{--page-width: 100cqw}.wrap.team-risk .page-intro>.btn{margin-block:0}.risk-progress{display:flex;flex-wrap:wrap;align-items:center;gap:.5rem 1.25rem;margin:0 0 1rem;color:var(--muted);font-size:.8rem}.risk-progress-line{display:flex;align-items:center;gap:.5rem 1.25rem;min-height:2.25rem;margin:0 0 1rem}.risk-progress-line>.risk-progress{flex:1;margin:0}.risk-files-toggle{position:relative;display:inline-grid;flex:none;place-items:center;width:2.25rem;height:2.25rem;padding:0;border:0;border-radius:var(--ui-radius, 6px);background:transparent;color:var(--muted)}.risk-files-toggle:hover,.risk-files-toggle[aria-expanded=true]{color:var(--text)}.risk-files-toggle:hover{background:var(--surface-active)}.risk-files-toggle .n{position:absolute;top:1px;right:1px;min-width:11px;padding:0 3px;border-radius:999px;background:color-mix(in srgb,var(--critical) 14%,var(--bg));color:var(--critical);font-size:8.5px;font-variant-numeric:tabular-nums;font-weight:600;line-height:11px;text-align:center}.risk-files-chevron{width:1.35rem;height:1.35rem;transition:transform .15s}.risk-files-toggle[aria-expanded=true] .risk-files-chevron{transform:rotate(180deg)}@media(prefers-reduced-motion:reduce){.risk-files-chevron{transition:none}}.risk-progress-idle{margin:0}.risk-state{display:inline-flex;align-items:center;gap:.4rem;margin-block:calc(-.15rem - 1px);margin-left:auto;padding:.15rem .6rem;border:1px solid var(--border);border-radius:999px;color:var(--text);font-weight:500;white-space:nowrap;user-select:none;-webkit-user-select:none}.risk-state:before{width:.5rem;height:.5rem;border-radius:50%;background:var(--muted);content:""}.risk-state[data-state=running]:before{background:var(--accent);animation:risk-pulse 1.4s ease-in-out infinite}.risk-state[data-state=done]:before{background:var(--green)}@keyframes risk-pulse{50%{opacity:.3}}@media(prefers-reduced-motion:reduce){.risk-state[data-state=running]:before{animation:none}}.risk-metric{display:grid;grid-template-columns:auto auto;justify-content:start;align-items:baseline;gap:.35rem .45rem;min-width:6rem;line-height:1}.risk-metric-label{font-size:.7rem;letter-spacing:.02em;text-transform:uppercase}.risk-metric-value{color:var(--text);font-size:.95rem;font-weight:600;font-variant-numeric:tabular-nums;white-space:nowrap}.risk-metric-value:not(:has(.risk-metric-of)){min-width:3ch}.risk-metric-of{color:var(--muted);font-weight:400}.risk-metric-slash{margin:0 .1em}.risk-metric.risk-high .risk-metric-value{color:var(--high)}.risk-bar{display:flex;grid-column:1 / -1;height:3px;overflow:hidden;border-radius:2px;background:var(--border)}.risk-bar>span{height:100%;transition:width .25s}.risk-bar-read{background:var(--accent)}.risk-bar-prod{background:color-mix(in srgb,var(--accent) 70%,var(--text))}.risk-bar-dev{background:color-mix(in srgb,var(--accent) 50%,var(--bg))}.risk-bar-malware{background:var(--critical)}.risk-section{margin-top:1rem}.risk-section:first-child{margin-top:0}.risk-files{margin-bottom:1rem;padding:.5rem .75rem .25rem;border:1px solid var(--border);border-radius:6px}.risk-files-head{display:flex;flex-wrap:wrap;align-items:center;gap:.5rem .75rem;margin-bottom:.25rem}.risk-files-head .risk-tabs{margin-bottom:0}.risk-files-head h2{margin:0;font-size:.875rem;font-weight:600}.risk-files .risk-repos>li:last-child{border-bottom:0}.risk-results-head{position:sticky;top:0;z-index:1;padding-bottom:.25rem;background:var(--bg)}.risk-results-head .collection-toolbar,.risk-results-head .risk-tabs{margin-bottom:0}.risk-search{display:flex;flex:1 1 18rem;align-items:center;gap:.75rem;min-width:0}a{color:var(--accent);text-decoration:none}a:hover{text-decoration:underline}.risk-name,.risk-name:visited{color:var(--text)}.risk-name:hover{color:var(--accent);text-decoration:none}.risk-icon{display:inline-flex;flex:none;color:var(--muted)}.risk-icon svg{display:block;width:14px;height:14px}.risk-package,.risk-used,.risk-used-why{display:inline-flex;align-items:center;gap:.4rem;max-width:100%}.risk-version{color:var(--muted);font-variant-numeric:tabular-nums}.risk-package .risk-dev{margin-left:0}.risk-package-name{width:max-content;max-width:26ch;white-space:normal;overflow-wrap:break-word}.risk-used .risk-clip{min-width:0}.risk-used-why{min-width:0;padding:0;border:0;font:inherit;background:none}.risk-used-external{display:inline-flex;flex:none;color:var(--muted)}.risk-used .external-link-icon{flex:none;opacity:.6}.risk-used-external:hover .external-link-icon,a.risk-used:hover .external-link-icon{color:var(--accent);opacity:1}.risk-used.is-dismissed,.risk-used.is-dismissed:visited{color:var(--muted)}.risk-used.is-dismissed .risk-used-in{text-decoration:line-through}.risk-name:hover .risk-icon{color:inherit}.risk-used-all summary{list-style:none}.risk-used-all summary::-webkit-details-marker{display:none}.risk-used-all summary:hover,.risk-used-all[open] summary{color:var(--accent)}.risk-used-lines{display:grid;gap:.15rem;margin:0;padding:0;list-style:none}.risk-used-all .risk-used-lines{margin-top:.25rem}.risk-repos{margin:0;padding:0;list-style:none;font-size:.8rem}.risk-repos>li{display:grid;grid-template-columns:minmax(8rem,16rem) 1fr;gap:.75rem;align-items:baseline;padding:.3rem 0;border-bottom:1px solid var(--border)}.risk-repo-name{overflow:hidden;font-weight:500;text-overflow:ellipsis;white-space:nowrap}.risk-repo-name .risk-icon{display:inline-block;margin-right:.4rem;vertical-align:-.2em}.risk-lockfiles{display:flex;flex-wrap:wrap;gap:.15rem 1.5rem;margin:0;padding:0;list-style:none}.risk-lockfiles li{white-space:nowrap}.risk-lockfile-meta{margin-left:.5rem;color:var(--muted)}@container (max-width: 40rem){.risk-repos>li{grid-template-columns:1fr;gap:0}}th:last-child,td:last-child{text-align:left}td{padding-block:.35rem;vertical-align:top}.risk-used-column{width:100%}.risk-advisories :is(th,td){padding-inline:.375rem}.risk-advisories :is(th,td):first-child{padding-left:0}.risk-advisories :is(th,td):last-child{padding-right:0}.risk-versions{width:calc(22ch + .75rem);min-width:calc(22ch + .75rem);max-width:calc(22ch + .75rem);white-space:normal}.risk-pin{white-space:nowrap}.risk-clip{display:block;max-width:18rem;overflow:hidden;text-overflow:ellipsis}.risk-used-in{max-width:14rem}.risk-pending,.risk-none{color:var(--muted)}.risk-step{min-width:20rem;white-space:normal;overflow-wrap:anywhere}.risk-step .risk-package{align-items:flex-start}.risk-step .risk-icon{margin-top:.15em}.risk-dependabot,.risk-stasis{display:flex;flex-wrap:wrap;align-items:center;gap:.25rem .5rem;margin:.25rem 0 .5rem;color:var(--muted);font-size:.75rem}.risk-dependabot-failed{color:var(--high)}.risk-icon img{display:block;width:14px;height:14px}.risk-builds{flex:none;width:6rem;height:4px;overflow:hidden;border-radius:2px;background:var(--border)}.risk-builds>span{display:block;height:100%;background:var(--accent);transition:width .3s ease}.risk-builds-n{font-variant-numeric:tabular-nums}@media(prefers-reduced-motion:reduce){.risk-builds>span{transition:none}}.risk-error{color:var(--critical)}.risk-chip,.risk-score{display:inline-block;border-radius:999px;font-weight:600;color:var(--sev);background:color-mix(in srgb,var(--sev) 14%,transparent)}.risk-chip{padding:0 .45rem;white-space:nowrap}.risk-score{min-width:2.25rem;padding:0 .4rem;font-variant-numeric:tabular-nums;text-align:center}.risk-score.risk-low{color:var(--muted);background:none;font-weight:400}.is-stale .risk-score,.is-stale .risk-findings{opacity:.55}.risk-stale,.risk-dev{margin-left:.35rem;padding:0 .35rem;border:1px solid var(--border);border-radius:999px;color:var(--muted);font-size:.7rem}.risk-findings{display:flex;flex-wrap:wrap;width:max-content;max-width:24rem;gap:.25rem .75rem;margin:0;padding:0;list-style:none}.risk-findings li{color:var(--sev);white-space:nowrap}.risk-advisory{color:var(--sev, currentcolor);text-decoration:none;&:hover{text-decoration:underline}.external-link-icon{margin-left:.2em;vertical-align:-.05em;opacity:.6}&:hover .external-link-icon{opacity:1}}.risk-advisory-ids{display:inline-flex;flex-direction:column;align-items:flex-start;gap:.1rem;vertical-align:top}.risk-critical{--sev: var(--critical)}.risk-high{--sev: var(--high)}.risk-moderate{--sev: var(--yellow)}.risk-low,.risk-notice{--sev: var(--muted)}.risk-scope-bar{display:flex;flex-wrap:wrap;align-items:center;gap:.75rem;margin:0 0 1rem}.risk-scope,.risk-tabs{display:flex;gap:2px;padding:3px;border:1px solid var(--border);border-radius:var(--ui-radius, 6px);background:var(--bg)}.risk-scope button,.risk-tabs button{display:inline-flex;align-items:center;gap:.35rem;padding:.3rem .65rem;border:0;border-radius:var(--ui-radius, 3px);background:transparent;color:var(--muted);font-size:.75rem}.risk-scope button:hover:not(:disabled),.risk-tabs button:hover{background:var(--surface-active);color:var(--text)}.risk-scope button[aria-pressed=true],.risk-tabs button[aria-selected=true]{background:color-mix(in srgb,var(--accent) 15%,var(--bg));color:var(--accent)}.risk-scope button:focus-visible,.risk-tabs button:focus-visible{outline-offset:-1px}.risk-scope .n,.risk-tabs .n{align-self:flex-start;margin:-1px -5px 0;color:var(--muted);font-variant-numeric:tabular-nums;font-size:8.5px;font-weight:600;background:var(--bg);border-radius:999px;padding:0 3px;min-width:11px;text-align:center;line-height:11px}.risk-scope button[aria-pressed=true] .n,.risk-tabs button[aria-selected=true] .n{color:inherit}.risk-scope{flex-wrap:wrap;max-width:100%}.risk-scope-bar select{min-width:14rem}.risk-scope-bar repository-selector{flex:0 1 20rem;min-width:14rem}.risk-tabs{width:fit-content;margin-bottom:.5rem}.risk-in-code{margin-left:.3em;color:var(--muted);font-size:.9em}
22
- `,Ea={malware:`Malware`,deprecated:`Deprecated`,publisher:`Publisher changed`,"provenance-lost":`Provenance lost`,"too-new":`Too new`,popularity:`Unpopular`,"held-install-scripts":`Install scripts`,"held-runs-code":`Runs code`,"held-credentials":`Credentials`,"held-exfiltration":`Exfiltration host`,"held-remote":`Remote host`,"held-ip-lookup":`IP lookup`,"held-obfuscated":`Obfuscated`,"held-symlinks":`Symlinks`,"held-non-registry-deps":`Non-registry dependencies`,"held-unused-deps":`Unused deps`,"large-code":`Large new code`,"now-unreadable":`Now unreadable`,"binary-code":`Binary code`,"new-hosts":`New hosts`},Da={"no-repository":`No GitHub access`,"github-not-found":`Not found on GitHub`,"github-unauthorized":`GitHub sign-in expired`,"github-rate-limited":`GitHub rate limit reached`,"github-unreachable":`GitHub unreachable`,"github-moved":`Moved on GitHub`,"github-malformed":`GitHub answered unexpectedly`,"unsupported-format":`Format not read`,"lockfile-unreadable":`Unreadable`,"package-not-found":`Not on npm`,"version-not-found":`Version not on npm`,"integrity-mismatch":`Differs from npm’s`,"npm-busy":`Server busy`,"package-too-large":`Too large to assess`,"upstream-busy":`npm busy`,"upstream-unavailable":`npm unavailable`,"upstream-too-large":`npm answered too much`,"upstream-invalid":`npm answered unexpectedly`,"dependabot-disabled":`Dependabot alerts off`,"dependabot-forbidden":`No access to Dependabot alerts`,"dependabot-app-permission":`App lacks Dependabot alerts permission`,"dependabot-not-installed":`App not installed`,"dependabot-unverified":`Sign-in not verified, sign in again`,"github-app-not-configured":`GitHub App not configured`,"workflow-unreadable":`Unreadable`,"workflow-too-large":`Too large to read`,"invalid-uses":`Not a reference GitHub reads`,"stasis-failed":`Stasis build failed`,"no-config":`No longer at this commit`,"github-token-required":`GitHub sign-in required`},U=e=>Da[e]??e,W=({error:e,detail:t})=>y`<span class="risk-error" data-tooltip="${t??b}">${U(e)}</span>`,Oa={401:`Sign in again to scan repositories.`,403:`Only admins can scan repositories.`,404:`That team or repository is no longer connected. Choose again.`},ka={...Oa,403:`Only the team’s managers and admins can scan its risk.`,404:`This team is no longer listed.`},Aa=e=>e?.team?{team:e.team}:{},ja=[[`all`,`All repositories`],[`team`,`Team`],[`repo`,`Repository`]],Ma=5,Na={registry:`npm`,mirror:`Mirror`,git:`Git`,tarball:`Tarball`,file:`File`},G=e=>e===`registry`||e===`mirror`,Pa=e=>K(e)?null:e.malware??null,K=e=>e.risk?.error===`integrity-mismatch`,Fa=e=>Pa(e)||K(e)?`critical`:e.risk?.severity??null,Ia=e=>Pa(e)?100:e.risk&&!e.risk.error?e.risk.score??null:null,La=e=>{let t=e.risk?.findings??[];return Pa(e)?[{id:`malware`,severity:`critical`},...t.filter(({id:e})=>e!==`malware`)]:t},Ra=e=>[...Pa(e)??[],...e.risk?.findings?.some(({id:e,takenDown:t})=>e===`malware`&&t)?[`Taken down by npm`]:[]],za=e=>La(e).some(({id:e})=>e===`malware`),Ba=e=>K(e)||za(e),q=({name:e,version:t})=>`${e}@${t}`,Va=(e,t,n)=>{let r=[...e].filter(e=>n.at.get(e)?.has(t));return r.length>0?r:[...e]},Ha=(e,t,n)=>t===`all`||Ba(e)||(t===`stasis`?n.versions.has(q(e)):!!e.dev==(t===`development`)),Ua=(e,t,n)=>Ba(e)?e.usedIn:t===`production`?e.neededIn:t===`stasis`?Va(e.usedIn,q(e),n):e.usedIn,Wa=e=>`${e[0].toUpperCase()}${e.slice(1)}`,Ga=e=>!!e.risk?.error&&!K(e),Ka={all:[`All`,()=>!0],flagged:[`Flagged`,e=>!!Fa(e)||Ga(e)],failed:[`Failed`,Ga],elsewhere:[`Not from npm`,e=>!G(e.source)]},qa=`Out of 100: what its findings call for, lowered by how long the version has been out among how many download its package. Malware is 100.`,Ja=`Only devDependencies need it, in every lockfile that locks it: an install without them leaves it out. Assessed after the rest, unless a Stasis build installs it.`,Ya=`Only devDependencies need these versions, in every lockfile that locks them: an install without them leaves them out.`,Xa=`Its lockfile’s integrity, a mirror’s, isn’t npm’s of this name and version: not npm’s package, as a private one of a public one’s name is, or one tampered with.`,Za={all:`All`,production:`Prod`,development:`Dev`},Qa={...Za,actions:`Actions`},$a={all:[`All`,()=>!0],flagged:[`Flagged`,e=>e.findings.length>0||!!e.line?.error]},eo=e=>e===`running`?`None flagged yet.`:`None flagged.`,to=(e,t)=>t?Object.fromEntries(Object.entries(e).flatMap(e=>e[0]===`production`?[[`stasis`,`Stasis`],e]:[e])):e,no=3e4,ro=50,io=e=>({path:e.path,dependencies:e.dependencies??null,pending:e.pending===!0,error:e.error??null,detail:e.detail??null,lockfiles:e.lockfiles??null}),ao=e=>y`<span class="risk-dev" data-tooltip="${e}">dev</span>`;function oo({name:e,source:t,dev:n},r,i,a){let o=y`${e}${r?y`<span class="risk-version">@${r}</span>`:b}`;return y`<span class="risk-package">${Y(G(t)?Qe:Ze)}${i?y`<a class="risk-name risk-package-name" href="${i}">${o}</a>`:y`<span class="risk-package-name">${o}</span>`}${n?ao(a):b}</span>`}var so=e=>!e.error||e.error===`integrity-mismatch`;function co(e,t){let n=e.stale??null;return!so(e)&&!n&&t?.stale&&so(t)?{...t,refreshFailed:e.detail?`${U(e.error)}: ${e.detail}`:U(e.error)}:e.error?{error:e.error,detail:e.detail??null,stale:n}:{severity:e.severity,score:e.score??null,findings:e.findings,published:e.published,stale:n}}var lo=new Intl.RelativeTimeFormat(`en`,{numeric:`auto`});function uo(e,t=Date.now()){let n=Math.round((e-t)/6e4);if(Math.abs(n)<60)return lo.format(n,`minute`);let r=Math.round(n/60);return Math.abs(r)<48?lo.format(r,`hour`):lo.format(Math.round(r/24),`day`)}var fo=100,po=3,mo=5e3,ho=250,J=new Intl.NumberFormat,go=e=>({total:e.length,told:e.filter(e=>e.risk).length,flagged:e.filter(Fa).length,stale:e.filter(e=>e.risk?.stale).length,wasStale:e.filter(e=>e.wasStale).length}),Y=e=>y`<span class="risk-icon" aria-hidden="true">${g(e)}</span>`,_o={fix_started:`A fix has already been started`,inaccurate:`This alert is inaccurate or incorrect`,no_bandwidth:`No bandwidth to fix this`,not_used:`Vulnerable code is not actually used`,tolerable_risk:`Risk is tolerable to this project`};function vo({number:e,dismissed:t}){if(!t)return`Dependabot alert #${e}`;let n=t.auto?`auto-dismissed by a rule`:`dismissed${_o[t.reason]?`: ${_o[t.reason]}`:``}`,r=[t.by?`by @${t.by}`:``,t.at?.slice(0,10)??``].filter(Boolean).join(`, `);return[`Dependabot alert #${e}, ${n}${r?` (${r})`:``}`,...t.comment?[`\u201C${t.comment}\u201D`]:[]].join(`
23
- `)}var X=Oe({page:null});function yo(e,{repoId:t,commit:n,path:r,format:i},a,o){let s=X.page,c=k(`/api/admin/repositories/risk/lockfile?${new URLSearchParams({repoId:t,commit:n,path:r,...Aa(s)})}`,{"github-not-found":`GitHub has it no longer.`},e=>e.json()).then(async({text:e,manifest:t})=>{let[{readLockfile:n},{lockfileWhy:r}]=await Promise.all([import(`./chunk-UR4WYMIP.js`),import(`./chunk-SSPDMA6D.js`)]);return r(await n(i,e,{manifest:t,env:!0}),{name:a,versions:o})});Ee({lockfile:e,packageKey:a,version:o.length===1?o[0]:void 0,load:c,isCurrent:()=>X.page===s})}var bo=(e,t)=>t&&e.toLowerCase().startsWith(`${t}/`)?e.slice(t.length):e;function xo(e){let t=new Set([...e].map(e=>e.fullName.split(`/`)[0].toLowerCase()));return t.size===1?[...t][0]:null}function So(e,t,n,r,i){let a=bo(e,i),o=n?.get(e);if(o&&it(o.url))return y`<a class="${o.dismissed?`risk-name risk-used is-dismissed`:`risk-name risk-used`}" href="${o.url}" target="_blank" rel="noopener noreferrer">${Y($e)}<span class="risk-clip risk-used-in" data-tooltip="${`${a}
24
- ${vo(o)}`}">${a}</span>${o.dismissed?y`<span class="sr-only">(dismissed)</span>`:b}${f}</a>`;let s=t.get(e),c=s?.href,l=y`<span class="risk-clip risk-used-in" data-tooltip-truncated data-tooltip="${a}">${a}</span>`;if(r&&[`npm`,`pnpm`,`yarn`].includes(s?.format)){let[t,n]=r(e);return y`<span class="risk-used"><button type="button" class="risk-name risk-used-why" aria-haspopup="dialog" aria-label="${`What depends on ${t} in ${e}`}" @click="${()=>yo(e,s,t,n)}">${Y(_)}${l}</button><a class="risk-used-external" href="${c}" target="_blank" rel="noopener noreferrer" aria-label="${`${e} on GitHub`}">${f}</a></span>`}return c?y`<a class="risk-name risk-used" href="${c}" target="_blank" rel="noopener noreferrer">${Y(_)}${l}${f}</a>`:l}function Co(e,t,n,r=`lockfiles`,i=null,a=null){let o=[...e];if(o.length===1)return So(o[0],t,n,i,a);let s=o.map(e=>y`<li>${So(e,t,n,i,a)}</li>`);if(o.length===2)return y`<ul class="risk-used-lines">${s}</ul>`;let c=o.filter(e=>n?.get(e)?.dismissed).length;return y`<details class="risk-used-all"><summary>${J.format(o.length)} ${r}${c>0?`, ${J.format(c)} dismissed`:``}</summary><ul class="risk-used-lines">${s}</ul></details>`}var wo=e=>typeof e==`string`&&/^GHSA(?:-[\da-z]{4}){3}$/iu.test(e),To=(e,t,n,r=Oa)=>k(`/api/admin/repositories/risk${e.size>0?`?${e}`:``}`,r,async e=>{for await(let t of An(e))n(t)},t),Eo=({name:e,version:t,integrity:n})=>`${e}@${t}\0${n??``}`,Do=e=>G(e.source)?Eo(e):`${e.source}\0${e.name}@${e.version??``}\0${e.from??``}`,Oo=e=>[...e.lockfiles?.keys()??[]].map(t=>`${e.fullName}/${t}`);function ko(e,t,n){let r=e.versionsIn.get(t)??e.versionsIn.set(t,new Set).get(t);for(let t of n)r.add(t),e.versions.add(t)}function Ao(e){if(za(e))return-102;if(K(e))return-101;let t=Ia(e);return t>0?-t:G(e.source)?t===0?3:e.risk?2:1:4}var jo=(e,t,n,r)=>y`<div class="risk-tabs" role="tablist" aria-label="${e}">${t.map(([e,t])=>y`<button type="button" role="tab" aria-selected="${n===e}" @click="${()=>r(e)}">${t}</button>`)}</div>`,Mo={stasis:`Stasis`,lockfiles:`Lockfiles`,workflows:`Workflows`},Z=(e,t)=>y`${e}${t>0?y`<span class="n">${J.format(t)}</span>`:b}`,Q=(e,t,n=`${t}s`)=>`${J.format(e)} ${e===1?t:n}`,No=y`<svg class="risk-files-chevron" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m4 6 4 4 4-4"/></svg>`,Po=class extends x{static view=`manage-repo-risk`;static properties={selection:{attribute:!1},team:{attribute:!1},installTooltips:{attribute:!1},_state:{state:!0},_filter:{state:!0},_kind:{state:!0},_packageKind:{state:!0},_query:{state:!0},_tab:{state:!0},_actionKind:{state:!0},_actionFilter:{state:!0},_files:{state:!0},_scope:{state:!0},_target:{state:!0},_choices:{state:!0},_unlisted:{state:!0},_filesOpen:{state:!0},_filesShown:{state:!0}};static styles=[v(r),v(Ji),v(Ta)];constructor(){super(),Object.assign(this,{selection:null,team:null,installTooltips:null,_state:`idle`,_filter:`flagged`,_kind:`production`,_packageKind:`all`,_actionKind:`all`,_actionFilter:`flagged`,_query:``,_tab:`advisories`,_files:`lockfiles`,_filesOpen:!1,_filesShown:`all`,_scope:`all`,_target:``,_choices:null,_unlisted:null}),this._awaiting=!1,this._scan=null,this._asking=null,this._drawTimer=null,this._parts=0,this._reset()}_load(){if(this.hasUpdated)return this._loadChoices()}_loadChoices(){if(!this.team)return this._loadCollection(`teams`,`teams`,Or,e=>{this._choices=e})}willUpdate(e){this.hasUpdated||this._loadChoices(),this.team?e.has(`team`)&&this._followTeam():(e.has(`selection`)||e.has(`_choices`)&&this._awaiting)&&this._follow()}updated(e){e.has(`installTooltips`)&&this.installTooltips?.(this.renderRoot),this.team&&this._state===`idle`&&this.isConnected&&queueMicrotask(()=>{this._state===`idle`&&this.isConnected&&this.start()})}_followTeam(){this._state===`running`&&this._target!==this.team&&this.stop(),this._choose(`team`,this.team)}_follow(){let{riskScope:e=`team`,riskTarget:t=null}=this.selection??{},n=t==null?null:e===`team`?this._choices&&this._shownTeams().filter(e=>e.slug===t).map(e=>e.id):this._choices?.repos?.filter(e=>e.repoId===t).map(e=>String(e.repoId)),r=n?.length===1?n[0]:``;this._awaiting=t!=null&&!this._choices,this._unlisted=t!=null&&this._choices&&!r?e:null,this._state===`running`&&(e!==this._scope||r!==this._target)&&this.stop(),this._choose(e,r)}_shownTeams(){return(this._choices?.teams??[]).filter(e=>!e.hidden)}_pick(e,t=``){if(this._state===`running`)return;this._choose(e,t),Object.assign(this,{_awaiting:!1,_unlisted:null});let n=t&&(e===`repo`?Number(t):this._choices?.teams?.find(e=>e.id===t)?.slug);p(`manage-repo-risk`,{riskScope:e,...n?{riskTarget:n}:{}})}_choose(e,t=``){this._state===`running`||e===this._scope&&t===this._target||(this._scope=e,this._target=t,this._reset(),this._error=null,this._state=`idle`)}_reset(){this._repos=new Map,this._archived=new Map,this._packages=new Map,this._advisories=new Map,this._actions=new xa,this._reach=null,this._stopAsking()}connectedCallback(){super.connectedCallback(),X.page=this}disconnectedCallback(){this.stop(),this._stopAsking(),X.page===this&&(X.page=null),super.disconnectedCallback()}async start(){if(this._state===`running`||this._scope!==`all`&&!this._target)return;let e=new URLSearchParams({...this._scope===`all`?{}:{[this._scope]:this._target},scan:crypto.randomUUID()});this._reset(),this._error=null,this._state=`running`;let t=new AbortController;this._scan=t,this._parts=0;try{for(let n=`continue`,r=0;n===`continue`;){if(++this._parts>fo)throw Error(`Stopped after ${J.format(fo)} parts. Scan again to go on from where it stopped.`);n=null;let i=this._told();if(await To(e,t.signal,e=>{(e.type===`done`||e.type===`continue`)&&(n=e.type),this._apply(e),this._draw()},this.team?ka:Oa),n===null)throw Error(`The scan ended before it finished. Try again.`);if(r=this._told()>i?0:r+1,n===`continue`&&r>=po)throw Error(`Stopped: the last ${J.format(po)} parts found nothing more. Scan again to try once more.`)}this._state=`done`}catch(e){if(t.signal.aborted||e?.name===`AbortError`)return;this._error=e?.message??String(e),this._state=`stopped`}finally{this._scan===t&&(this._scan=null,this._state===`running`&&(this._state=`stopped`)),this._draw(!0)}}stop(){this._scan&&(this._scan.abort(),this._scan=null,this._state=`stopped`,this._draw(!0))}_draw(e=!1){e?(clearTimeout(this._drawTimer),this._drawTimer=null,this.requestUpdate()):this._drawTimer??=setTimeout(()=>{this._drawTimer=null,this.requestUpdate()},ho)}_told(){let e=this._archived.size;for(let t of this._repos.values()){(t.lockfiles||t.error)&&e++,t.dependabot&&e++,t.stasis&&e++;for(let n of t.lockfiles?.values()??[])e+=+(n.packages!==null||!!n.error)+ +!!(n.advisories||n.advisoriesError)}for(let t of this._packages.values())t.risk&&!t.risk.stale&&e++;return e+this._actions.told()}_apply(e){if(e.type===`repos`){let t=new Map(e.repos.map(({id:e,fullName:t})=>[e,t]));for(let[e,n]of this._archived)t.get(e)!==n&&this._archived.delete(e);let n=[...this._repos.values()].filter(e=>t.get(e.id)!==e.fullName);for(let e of n)this._repos.delete(e.id),this._actions.forget(e.id);this._forget(n.flatMap(Oo),n.some(e=>e.dependabot?.alerts));for(let{id:t,fullName:n}of e.repos)!this._repos.has(t)&&!this._archived.has(t)&&this._repos.set(t,{id:t,fullName:n,commit:null,lockfiles:null,error:null,detail:null,dependabot:null,stasis:null});this._reach=null}else if(e.type===`repo`){let t=this._repos.get(e.id);if(!t)return;if(e.archived){this._archived.set(t.id,t.fullName),this._repos.delete(t.id),this._actions.forget(t.id),this._forget(Oo(t),!!t.dependabot?.alerts),this._reach=null;return}if(e.error){let n=Oo(t),r=!!t.dependabot?.alerts;Object.assign(t,{lockfiles:null,error:e.error,detail:e.detail??null,dependabot:null,stasis:null}),this._reach=null,this._actions.forget(t.id),this._forget(n,r);return}let n=t.commit!==null&&t.commit!==e.commit,r=new Set(n?[]:e.lockfiles.map(({path:e})=>e)),i=[...t.lockfiles?.keys()??[]].filter(e=>!r.has(e)).map(e=>`${t.fullName}/${e}`);Object.assign(t,{commit:e.commit,error:null,detail:null}),n&&(t.stasis=null),this._reach=null,t.lockfiles=new Map(e.lockfiles.map(e=>[e.path,!n&&t.lockfiles?.get(e.path)||{...e,packages:null,error:null}])),this._forget(i)}else if(e.type===`lockfile`){let t=this._repos.get(e.repo),n=t?.lockfiles?.get(e.path);if(!n)return;if(e.error){Object.assign(n,{error:e.error,detail:e.detail??null});return}Object.assign(n,{packages:e.packages.length,error:null,detail:null});let r=`${t.fullName}/${e.path}`;for(let t of e.packages){let e=Do(t),n=this._packages.get(e);n||this._packages.set(e,n={...t,usedIn:new Set,neededIn:new Set,risk:null}),n.usedIn.add(r),t.dev!==!0&&n.neededIn.add(r),n.dev=n.neededIn.size===0}}else if(e.type===`risk`){let t=this._packages.get(Eo(e));t&&(t.risk=co(e,t.risk),t.wasStale||=!!t.risk.stale)}else if(e.type===`advisories`)this._applyAdvisories(e);else if(e.type===`dependabot`)this._applyDependabot(e);else if(e.type===`stasis`){let t=this._repos.get(e.repo);if(!t)return;t.stasis=e.error?{error:e.error,detail:e.detail??null,configs:new Map}:{error:null,detail:null,configs:new Map(e.configs.map(e=>[e.path,io(e)]))},this._reach=null,this._askStasis()}else(e.type===`action`||(e.type===`workflows`||e.type===`workflow`)&&this._repos.has(e.repo))&&this._actions.apply(e)}_forget(e,t=!1){if(e.length===0)t&&this._readvise();else{for(let[t,n]of this._packages){for(let t of e)n.usedIn.delete(t),n.neededIn.delete(t);n.usedIn.size===0&&this._packages.delete(t),n.dev=n.neededIn.size===0}this._readvise()}}_readvise(){this._advisories=new Map;for(let e of this._packages.values())e.malware=void 0;for(let e of this._repos.values())for(let[t,n]of e.lockfiles??[])n.advisories&&this._advise(`${e.fullName}/${t}`,n.advisories);this._alert()}_alerted(){return[...this._repos.values()].some(e=>e.dependabot?.alerts?.length>0)}_applyAdvisories(e){let t=this._repos.get(e.repo),n=t?.lockfiles?.get(e.path);if(!n)return;if(e.error){n.advisoriesError=e.error;return}let r=n.advisories;Object.assign(n,{advisories:e.advisories,advisoriesError:null}),!r&&!this._alerted()?this._advise(`${t.fullName}/${e.path}`,e.advisories):JSON.stringify(r)!==JSON.stringify(e.advisories)&&this._readvise()}_applyDependabot(e){let t=this._repos.get(e.repo);if(!t)return;let n=t.dependabot;t.dependabot=e.error?{...n?.alerts&&{alerts:n.alerts},error:e.error,detail:e.detail??null}:{alerts:e.alerts},JSON.stringify(n?.alerts??null)!==JSON.stringify(t.dependabot.alerts??null)&&this._readvise()}_alert(){let e=new Map,t=(e,t)=>`${e.toUpperCase()}\0${t}`;for(let n of this._advisories.values())for(let r of[n.id,n.ghsa,...n.aliases??[]])wo(r)&&!e.has(t(r,n.name))&&e.set(t(r,n.name),n);let n=[...this._repos.values()].flatMap(e=>(e.dependabot?.alerts??[]).map(t=>({repo:e,alert:t})));for(let{repo:r,alert:i}of[...n.filter(e=>!e.alert.dismissed),...n.filter(e=>e.alert.dismissed)]){let n=`${r.fullName}/${i.manifest}`,a=e.get(t(i.ghsa,i.name));!a&&i.dismissed||(a||(a={id:i.ghsa,ghsa:i.ghsa,name:i.name,title:i.title,severity:i.severity,url:`https://github.com/advisories/${i.ghsa}`,aliases:i.aliases,cwe:i.cwe,malware:!1,dependabot:!0,ranges:new Set,versions:new Set,usedIn:new Set,versionsIn:new Map},this._advisories.set(`${i.ghsa}\0${i.name}`,a),e.set(t(i.ghsa,i.name),a)),a.dependabot&&i.range&&a.ranges.add(i.range),a.alerts??=new Map,a.alerts.set(n,i),a.usedIn.add(n),i.versions.length>0&&ko(a,n,i.versions),a.malware||=i.malware,this._markMalware(a))}}_advise(e,t){for(let{range:n,versions:r,...i}of t){let t=`${i.id}\0${i.name}`,a=this._advisories.get(t);a||this._advisories.set(t,a={...i,ranges:new Set,versions:new Set,usedIn:new Set,versionsIn:new Map}),n&&a.ranges.add(n),a.malware||=i.malware,a.usedIn.add(e),ko(a,e,r),this._markMalware(a)}}_markMalware(e){if(e.malware){for(let t of this._packages.values())if(G(t.source)&&t.name===e.name&&e.versions.has(t.version))for(let n of sa(e))(t.malware??=new Set).add(n)}}_counts(){let e=[...this._repos.values()],t=e.flatMap(e=>[...e.lockfiles?.values()??[]]),n=[...this._packages.values()].filter(e=>G(e.source));return{repos:e.length,reposRead:e.filter(e=>e.lockfiles||e.error).length,archived:this._archived.size,lockfiles:t.length,lockfilesRead:t.filter(e=>e.packages!==null||e.error).length,needed:go(n.filter(e=>!e.dev)),dev:go(n.filter(e=>e.dev)),advisories:this._adviseCounts()}}_adviseCounts(){let e=this._advisoryKinds(),t=new Set(e.production.filter(e=>!e.malware).map(e=>`${e.id}\0${e.name}`)),n=[...this._advisories.values()].filter(e=>e.malware).length;return{total:this._advisories.size,malware:n,needed:t.size,dev:this._advisories.size-n-t.size}}_hasStasis(){return[...this._repos.values()].some(e=>e.stasis&&(e.stasis.error||e.stasis.configs.size>0))}_packageKindShown(){return this._packageKind===`stasis`&&!this._hasStasis()?`all`:this._packageKind}_kindShown(){return this._kind===`stasis`&&!this._hasStasis()?`production`:this._kind}_stasisConfigs(){return[...this._repos.values()].flatMap(e=>[...e.stasis?.configs.values()??[]].map(t=>({repo:e,config:t})))}_stasisReach(){if(this._reach)return this._reach;let e={versions:new Set,at:new Map};for(let{repo:t,config:n}of this._stasisConfigs()){for(let t of n.dependencies??[])e.versions.add(q(t));let r=e=>e.slice(0,Math.max(e.lastIndexOf(`/`),0)),i=r(n.path),a=[...t.lockfiles?.keys()??[]].filter(e=>r(e)===``||i===r(e)||i.startsWith(`${r(e)}/`)),o=Math.max(...a.map(e=>r(e).length));for(let i of n.lockfiles??a.filter(e=>r(e).length===o)){let r=e.at.get(`${t.fullName}/${i}`)??e.at.set(`${t.fullName}/${i}`,new Set).get(`${t.fullName}/${i}`);for(let e of n.dependencies??[])r.add(q(e))}}return this._reach=e}_stasisCounts(){let e=this._stasisConfigs().map(({config:e})=>e);return{total:e.length,built:e.filter(e=>e.dependencies).length,pending:e.filter(e=>e.pending).length,failed:e.filter(e=>e.error).length+[...this._repos.values()].filter(e=>e.stasis?.error).length}}_stasisNote(){let{total:e,pending:t,failed:n}=this._stasisCounts();if(t===0&&n===0)return b;let r=e-t,i=[...this._repos.values()].flatMap(e=>e.stasis?.error?[`${e.fullName}: ${U(e.stasis.error)}`]:[...e.stasis?.configs.values()??[]].filter(e=>e.error).map(t=>`${e.fullName}/${t.path}: ${U(t.error)}${t.detail?` (${t.detail})`:``}`));return y`<p class="risk-stasis" role="status"><span class="risk-icon" aria-hidden="true"><img src="./stasis.svg" alt=""></span>${t>0?y`<span>Stasis is still building ${Q(t,`project`)}.</span> <span class="risk-builds" role="progressbar" aria-label="Stasis builds made" aria-valuemin="0" aria-valuemax="${e}" aria-valuenow="${r}"><span style="${et({width:`${e?r/e*100:0}%`})}"></span></span><span class="risk-builds-n">${J.format(r)}/${J.format(e)}</span>`:b} ${n>0?y`<span class="risk-dependabot-failed" data-tooltip="${i.join(`
21
+ `)}function ba(e){return e.id===`fetched-package`?`${e.tool} ${e.name}${e.spec?`@${e.spec}`:``}`:e.id===`unlocked-install`?e.tool:e.id===`unpinned-image`?e.image:e.id===`clone`?`git clone ${e.url??``}`.trim():e.id===`hosts`?e.services.join(`, `):e.id===`script-injection`?`\${{ ${e.expression} }}`:e.id===`secrets-inherited`||e.id===`invalid-uses`?e.uses:e.id===`deprecated-runtime`?`runs.using: ${e.using}`:e.id===`remote-script`&&e.command?e.command:e.id===`pwn-request`&&e.ref?e.ref===`gh pr checkout`?e.ref:`actions/checkout ref: ${e.ref}`:va(e)}var xa=class{constructor(){this.listed=new Map,this.files=new Map,this.actions=new Map,this.built=null}apply(e){this.built=null,e.type===`workflows`?(this.forget(e.repo),this.listed.set(e.repo,e)):e.type===`workflow`?(this.files.get(e.repo)??this.files.set(e.repo,new Map).get(e.repo)).set(e.path,e):e.type!==`action`||e.error&&this.actions.has(e.key)||this.actions.set(e.key,e)}forget(e){this.listed.delete(e),this.files.delete(e),this.built=null}filesOf(e){return[...this.files.get(e)?.values()??[]]}told(){return this.listed.size+this.rows(`actions`).filter(e=>e.line).length+[...this.files.values()].reduce((e,t)=>e+t.size,0)}counts(){let e=this.rows(`actions`);return{workflows:[...this.listed.values()].reduce((e,t)=>e+(t.paths?.length??0),0),workflowsRead:[...this.files.values()].reduce((e,t)=>e+[...t.values()].filter(e=>e.kind===`workflow`).length,0),actions:e.length,resolved:e.filter(e=>e.line).length}}#e(){let e=new Map,t=new Map,n=t=>e.get(t)??e.set(t,{key:t,kind:`action`,usedIn:[],local:[]}).get(t);for(let[e,r]of this.files)for(let i of r.values()){for(let t of i.uses??[])t.key&&Object.assign(n(t.key),{uses:t}).usedIn.push({repo:e,path:i.path,line:t.line});for(let r of i.findings??[]){if(r.key){n(r.key).local.push(r);continue}let a=ba(r),o=`${r.id}\0${r.tag??``}\0${a}`,s=t.get(o)??t.set(o,{key:o,kind:`step`,name:a,findings:[r],severity:r.severity,usedIn:[]}).get(o);V(r.severity)<V(s.severity)&&Object.assign(s,{severity:r.severity,findings:[r]}),s.usedIn.push({repo:e,path:i.path,line:r.line})}}let r=[...e.keys()];for(let t=0;t<r.length;t++)for(let i of this.actions.get(r[t])?.uses??[])e.has(i)||r.push(i),n(i).usedIn.push({via:r[t]});for(let t of e.values()){let e=new Map;t.line=this.actions.get(t.key)??null;for(let n of[...t.local,...t.line?.findings??[]]){let t=`${n.id}\0${ba(n)}\0${n.file??``}\0${n.file?n.line:``}`;(!e.has(t)||V(n.severity)<V(e.get(t).severity))&&e.set(t,n)}t.findings=[...e.values()],t.severity=_a(t.findings)}let i=e=>e.findings.length>0?0:e.line?.error?1:e.line||e.kind===`step`?3:2;return[...e.values(),...t.values()].toSorted((e,t)=>V(e.severity)-V(t.severity)||i(e)-i(t)||t.findings.length-e.findings.length||(e.name??e.key).localeCompare(t.name??t.key))}rows(e,t=``){this.built??=this.#e();let n=t.trim().toLowerCase();return this.built.filter(t=>(e===`all`||e===`actions`==(t.kind===`action`))&&(!n||(t.name??t.key).toLowerCase().includes(n)))}};function Sa(e){if(!e||e.error||!e.commit)return null;let t=e.commit.slice(0,7),n=e.tags?.length?` (${e.tags.join(`, `)})`:``;return e.at===`sha`?`${t}${n}`:`${e.at} \u2192 ${t}${n}`}function Ca(e){return y`<ul class="risk-findings">${e.map(e=>e.id===`advisory`?y`<li class="${`risk-${e.severity}`}">${ma({...e,id:e.advisory})}</li>`:y`<li class="${`risk-${e.severity}`}" data-tooltip="${ya(e)||b}">${va(e)}${e.file?y`<span class="risk-in-code">in code</span>`:b}</li>`)}</ul>`}function wa({uses:e,line:t}){let n=t?.commit??e?.ref??t?.ref,r=t?.repository?.fullName??e?.repo??t?.repo;return r&&n?H(r,n,e?.path??t?.path,t?.kind===`workflow`||e?.kind===`workflow`?`blob`:`tree`):null}var H=(e,t,n,r=`blob`)=>`https://github.com/${e}/${r}/${encodeURIComponent(t)}${n?`/${He(n)}`:``}`,Ta=`.wrap{max-width:none}.wrap>:not(.manage-list,.sr-only),.manage-list>.risk-files,.risk-section>:not(.link-table,.risk-results-head),.risk-results-head>*{max-width:var(--page-width);margin-left:max(0px,(100cqw - var(--page-width)) / 2)}.wrap.team-risk{--page-width: 100cqw}.wrap.team-risk .page-intro>.btn{margin-block:0}.risk-progress{display:flex;flex-wrap:wrap;align-items:center;gap:.5rem 1.25rem;margin:0 0 1rem;color:var(--muted);font-size:.8rem}.risk-progress-line{display:flex;align-items:center;gap:.5rem 1.25rem;min-height:2.25rem;margin:0 0 1rem}.risk-progress-line>.risk-progress{flex:1;margin:0}.risk-files-toggle{position:relative;display:inline-grid;flex:none;place-items:center;width:2.25rem;height:2.25rem;padding:0;border:0;border-radius:var(--ui-radius, 6px);background:transparent;color:var(--muted)}.risk-files-toggle:hover,.risk-files-toggle[aria-expanded=true]{color:var(--text)}.risk-files-toggle:hover{background:var(--surface-active)}.risk-files-toggle .n{position:absolute;top:1px;right:1px;min-width:11px;padding:0 3px;border-radius:999px;background:color-mix(in srgb,var(--critical) 14%,var(--bg));color:var(--critical);font-size:8.5px;font-variant-numeric:tabular-nums;font-weight:600;line-height:11px;text-align:center}.risk-files-chevron{width:1.35rem;height:1.35rem;transition:transform .15s}.risk-files-toggle[aria-expanded=true] .risk-files-chevron{transform:rotate(180deg)}@media(prefers-reduced-motion:reduce){.risk-files-chevron{transition:none}}.risk-progress-idle{margin:0}.risk-state{display:inline-flex;align-items:center;gap:.4rem;margin-block:calc(-.15rem - 1px);margin-left:auto;padding:.15rem .6rem;border:1px solid var(--border);border-radius:999px;color:var(--text);font-weight:500;white-space:nowrap;user-select:none;-webkit-user-select:none}.risk-state:before{width:.5rem;height:.5rem;border-radius:50%;background:var(--muted);content:""}.risk-state[data-state=running]:before{background:var(--accent);animation:risk-pulse 1.4s ease-in-out infinite}.risk-state[data-state=done]:before{background:var(--green)}@keyframes risk-pulse{50%{opacity:.3}}@media(prefers-reduced-motion:reduce){.risk-state[data-state=running]:before{animation:none}}.risk-metric{display:grid;grid-template-columns:auto auto;justify-content:start;align-items:baseline;gap:.35rem .45rem;min-width:6rem;line-height:1}.risk-metric-label{font-size:.7rem;letter-spacing:.02em;text-transform:uppercase}.risk-metric-value{color:var(--text);font-size:.95rem;font-weight:600;font-variant-numeric:tabular-nums;white-space:nowrap}.risk-metric-value:not(:has(.risk-metric-of)){min-width:3ch}.risk-metric-of{color:var(--muted);font-weight:400}.risk-metric-slash{margin:0 .1em}.risk-metric.risk-high .risk-metric-value{color:var(--high)}.risk-bar{display:flex;grid-column:1 / -1;height:3px;overflow:hidden;border-radius:2px;background:var(--border)}.risk-bar>span{height:100%;transition:width .25s}.risk-bar-read{background:var(--accent)}.risk-bar-prod{background:color-mix(in srgb,var(--accent) 70%,var(--text))}.risk-bar-dev{background:color-mix(in srgb,var(--accent) 50%,var(--bg))}.risk-bar-malware{background:var(--critical)}.risk-section{margin-top:1rem}.risk-section:first-child{margin-top:0}.risk-files{margin-bottom:1rem;padding:.5rem .75rem .25rem;border:1px solid var(--border);border-radius:6px}.risk-files-head{display:flex;flex-wrap:wrap;align-items:center;gap:.5rem .75rem;margin-bottom:.25rem}.risk-files-head .risk-tabs{margin-bottom:0}.risk-files-head h2{margin:0;font-size:.875rem;font-weight:600}.risk-files .risk-repos>li:last-child{border-bottom:0}.risk-results-head{position:sticky;top:0;z-index:1;padding-bottom:.25rem;background:var(--bg)}.risk-results-head .collection-toolbar,.risk-results-head .risk-tabs{margin-bottom:0}.risk-search{display:flex;flex:1 1 18rem;align-items:center;gap:.75rem;min-width:0}a{color:var(--accent);text-decoration:none}a:hover{text-decoration:underline}.risk-name,.risk-name:visited{color:var(--text)}.risk-name:hover{color:var(--accent);text-decoration:none}.risk-icon{display:inline-flex;flex:none;color:var(--muted)}.risk-icon svg{display:block;width:14px;height:14px}.risk-package,.risk-used,.risk-used-why{display:inline-flex;align-items:center;gap:.4rem;max-width:100%}.risk-version{color:var(--muted);font-variant-numeric:tabular-nums}.risk-package .risk-dev{margin-left:0}.risk-package-name{width:max-content;max-width:26ch;white-space:normal;overflow-wrap:break-word}.risk-used .risk-clip{min-width:0}.risk-used-why{min-width:0;padding:0;border:0;font:inherit;background:none}.risk-used-external{display:inline-flex;flex:none;color:var(--muted)}.risk-used .external-link-icon{flex:none;opacity:.6}.risk-used-external:hover .external-link-icon,a.risk-used:hover .external-link-icon{color:var(--accent);opacity:1}.risk-used.is-dismissed,.risk-used.is-dismissed:visited{color:var(--muted)}.risk-used.is-dismissed .risk-used-in{text-decoration:line-through}.risk-name:hover .risk-icon{color:inherit}.risk-used-all summary{list-style:none}.risk-used-all summary::-webkit-details-marker{display:none}.risk-used-all summary:hover,.risk-used-all[open] summary{color:var(--accent)}.risk-used-lines{display:grid;gap:.15rem;margin:0;padding:0;list-style:none}.risk-used-all .risk-used-lines{margin-top:.25rem}.risk-repos{margin:0;padding:0;list-style:none;font-size:.8rem}.risk-repos>li{display:grid;grid-template-columns:minmax(8rem,16rem) 1fr;gap:.75rem;align-items:baseline;padding:.3rem 0;border-bottom:1px solid var(--border)}.risk-repo-name{overflow:hidden;font-weight:500;text-overflow:ellipsis;white-space:nowrap}.risk-repo-name .risk-icon{display:inline-block;margin-right:.4rem;vertical-align:-.2em}.risk-lockfiles{display:flex;flex-wrap:wrap;gap:.15rem 1.5rem;margin:0;padding:0;list-style:none}.risk-lockfiles li{white-space:nowrap}.risk-lockfile-meta{margin-left:.5rem;color:var(--muted)}@container (max-width: 40rem){.risk-repos>li{grid-template-columns:1fr;gap:0}}th:last-child,td:last-child{text-align:left}td{padding-block:.35rem;vertical-align:top}.risk-used-column{width:100%}.risk-advisories :is(th,td){padding-inline:.375rem}.risk-advisories :is(th,td):first-child{padding-left:0}.risk-advisories :is(th,td):last-child{padding-right:0}.risk-versions{width:calc(22ch + .75rem);min-width:calc(22ch + .75rem);max-width:calc(22ch + .75rem);white-space:normal}.risk-pin{white-space:nowrap}.risk-clip{display:block;max-width:18rem;overflow:hidden;text-overflow:ellipsis}.risk-used-in{max-width:14rem}.risk-pending,.risk-none{color:var(--muted)}.risk-step{min-width:20rem;white-space:normal;overflow-wrap:anywhere}.risk-step .risk-package{align-items:flex-start}.risk-step .risk-icon{margin-top:.15em}.risk-dependabot,.risk-stasis{display:flex;flex-wrap:wrap;align-items:center;gap:.25rem .5rem;margin:.25rem 0 .5rem;color:var(--muted);font-size:.75rem}.risk-dependabot-failed{color:var(--high)}.risk-icon img{display:block;width:14px;height:14px}.risk-builds{flex:none;width:6rem;height:4px;overflow:hidden;border-radius:2px;background:var(--border)}.risk-builds>span{display:block;height:100%;background:var(--accent);transition:width .3s ease}.risk-builds-n{font-variant-numeric:tabular-nums}@media(prefers-reduced-motion:reduce){.risk-builds>span{transition:none}}.risk-error{color:var(--critical)}.risk-chip,.risk-score{display:inline-block;border-radius:999px;cursor:default;font-weight:600;color:var(--sev);background:color-mix(in srgb,var(--sev) 14%,transparent)}.risk-chip{padding:0 .45rem;white-space:nowrap}.risk-score{min-width:2.25rem;padding:0 .4rem;font-variant-numeric:tabular-nums;text-align:center}.risk-score.risk-low{color:var(--muted);background:none;font-weight:400}.is-stale .risk-score,.is-stale .risk-findings{opacity:.55}.risk-stale,.risk-dev{margin-left:.35rem;padding:0 .35rem;border:1px solid var(--border);border-radius:999px;color:var(--muted);font-size:.7rem}.risk-findings{display:flex;flex-wrap:wrap;width:max-content;max-width:24rem;gap:.25rem .75rem;margin:0;padding:0;list-style:none}.risk-findings li{color:var(--sev);white-space:nowrap}.risk-advisory{color:var(--sev, currentcolor);text-decoration:none;&:hover{text-decoration:none}.external-link-icon{margin-left:.2em;vertical-align:-.05em;opacity:.6}&:hover .external-link-icon{opacity:1}}.risk-advisory-ids{display:inline-flex;flex-direction:column;align-items:flex-start;gap:.1rem;vertical-align:top}.risk-critical{--sev: var(--critical)}.risk-high{--sev: var(--high)}.risk-moderate{--sev: var(--yellow)}.risk-low,.risk-notice{--sev: var(--muted)}.risk-scope-bar{display:flex;flex-wrap:wrap;align-items:center;gap:.75rem;margin:0 0 1rem}.risk-scope,.risk-tabs{display:flex;gap:2px;padding:3px;border:1px solid var(--border);border-radius:var(--ui-radius, 6px);background:var(--bg)}.risk-scope button,.risk-tabs button{display:inline-flex;align-items:center;gap:.35rem;padding:.3rem .65rem;border:0;border-radius:var(--ui-radius, 3px);background:transparent;color:var(--muted);font-size:.75rem}.risk-scope button:hover:not(:disabled),.risk-tabs button:hover{background:var(--surface-active);color:var(--text)}.risk-scope button[aria-pressed=true],.risk-tabs button[aria-selected=true]{background:color-mix(in srgb,var(--accent) 15%,var(--bg));color:var(--accent)}.risk-scope button:focus-visible,.risk-tabs button:focus-visible{outline-offset:-1px}.risk-scope .n,.risk-tabs .n{align-self:flex-start;margin:-1px -5px 0;color:var(--muted);font-variant-numeric:tabular-nums;font-size:8.5px;font-weight:600;background:var(--bg);border-radius:999px;padding:0 3px;min-width:11px;text-align:center;line-height:11px}.risk-scope button[aria-pressed=true] .n,.risk-tabs button[aria-selected=true] .n{color:inherit}.risk-scope{flex-wrap:wrap;max-width:100%}.risk-scope-bar select{min-width:14rem}.risk-scope-bar repository-selector{flex:0 1 20rem;min-width:14rem}.risk-tabs{width:fit-content;margin-bottom:.5rem}.risk-in-code{margin-left:.3em;color:var(--muted);font-size:.9em}
22
+ `,Ea={malware:`Malware`,deprecated:`Deprecated`,publisher:`Publisher changed`,"provenance-lost":`Provenance lost`,"too-new":`Too new`,popularity:`Unpopular`,"held-install-scripts":`Install scripts`,"held-runs-code":`Runs code`,"held-credentials":`Credentials`,"held-exfiltration":`Exfiltration host`,"held-remote":`Remote host`,"held-ip-lookup":`IP lookup`,"held-obfuscated":`Obfuscated`,"held-symlinks":`Symlinks`,"held-non-registry-deps":`Non-registry dependencies`,"held-unused-deps":`Unused deps`,"large-code":`Large new code`,"now-unreadable":`Now unreadable`,"binary-code":`Binary code`,"new-hosts":`New hosts`},Da={"no-repository":`No GitHub access`,"github-not-found":`Not found on GitHub`,"github-unauthorized":`GitHub sign-in expired`,"github-rate-limited":`GitHub rate limit reached`,"github-unreachable":`GitHub unreachable`,"github-moved":`Moved on GitHub`,"github-malformed":`GitHub answered unexpectedly`,"unsupported-format":`Format not read`,"lockfile-unreadable":`Unreadable`,"package-not-found":`Not on npm`,"version-not-found":`Version not on npm`,"integrity-mismatch":`Differs from npm’s`,"npm-busy":`Server busy`,"package-too-large":`Too large to assess`,"upstream-busy":`npm busy`,"upstream-unavailable":`npm unavailable`,"upstream-too-large":`npm answered too much`,"upstream-invalid":`npm answered unexpectedly`,"dependabot-disabled":`Dependabot alerts off`,"dependabot-forbidden":`No access to Dependabot alerts`,"dependabot-app-permission":`App lacks Dependabot alerts permission`,"dependabot-not-installed":`App not installed`,"dependabot-unverified":`Sign-in not verified, sign in again`,"github-app-not-configured":`GitHub App not configured`,"workflow-unreadable":`Unreadable`,"workflow-too-large":`Too large to read`,"invalid-uses":`Not a reference GitHub reads`,"stasis-failed":`Stasis build failed`,"no-config":`No longer at this commit`,"github-token-required":`GitHub sign-in required`},U=e=>Da[e]??e,W=({error:e,detail:t})=>y`<span class="risk-error" data-tooltip="${t??b}">${U(e)}</span>`,Oa={401:`Sign in again to scan repositories.`,403:`Only admins can scan repositories.`,404:`That team or repository is no longer connected. Choose again.`},ka={...Oa,403:`Only the team’s managers and admins can scan its risk.`,404:`This team is no longer listed.`},Aa=e=>e?.team?{team:e.team}:{},ja=[[`all`,`All repositories`],[`team`,`Team`],[`repo`,`Repository`]],Ma=5,Na={registry:`npm`,mirror:`Mirror`,git:`Git`,tarball:`Tarball`,file:`File`},G=e=>e===`registry`||e===`mirror`,Pa=e=>K(e)?null:e.malware??null,K=e=>e.risk?.error===`integrity-mismatch`,Fa=e=>Pa(e)||K(e)?`critical`:e.risk?.severity??null,Ia=e=>Pa(e)?100:e.risk&&!e.risk.error?e.risk.score??null:null,La=e=>{let t=e.risk?.findings??[];return Pa(e)?[{id:`malware`,severity:`critical`},...t.filter(({id:e})=>e!==`malware`)]:t},Ra=e=>[...Pa(e)??[],...e.risk?.findings?.some(({id:e,takenDown:t})=>e===`malware`&&t)?[`Taken down by npm`]:[]],za=e=>La(e).some(({id:e})=>e===`malware`),Ba=e=>K(e)||za(e),q=({name:e,version:t})=>`${e}@${t}`,Va=(e,t,n)=>{let r=[...e].filter(e=>n.at.get(e)?.has(t));return r.length>0?r:[...e]},Ha=(e,t,n)=>t===`all`||Ba(e)||(t===`stasis`?n.versions.has(q(e)):!!e.dev==(t===`development`)),Ua=(e,t,n)=>Ba(e)?e.usedIn:t===`production`?e.neededIn:t===`stasis`?Va(e.usedIn,q(e),n):e.usedIn,Wa=e=>`${e[0].toUpperCase()}${e.slice(1)}`,Ga=e=>!!e.risk?.error&&!K(e),Ka={all:[`All`,()=>!0],flagged:[`Flagged`,e=>!!Fa(e)||Ga(e)],failed:[`Failed`,Ga],elsewhere:[`Not from npm`,e=>!G(e.source)]},qa=`Out of 100: what its findings call for, lowered by how long the version has been out among how many download its package. Malware is 100.`,Ja=`Only devDependencies need it, in every lockfile that locks it: an install without them leaves it out. Assessed after the rest, unless a Stasis build installs it.`,Ya=`Only devDependencies need these versions, in every lockfile that locks them: an install without them leaves them out.`,Xa=`Its lockfile’s integrity, a mirror’s, isn’t npm’s of this name and version: not npm’s package, as a private one of a public one’s name is, or one tampered with.`,Za={all:`All`,production:`Prod`,development:`Dev`},Qa={...Za,actions:`Actions`},$a={all:[`All`,()=>!0],flagged:[`Flagged`,e=>e.findings.length>0||!!e.line?.error]},eo=e=>e===`running`?`None flagged yet.`:`None flagged.`,to=(e,t)=>t?Object.fromEntries(Object.entries(e).flatMap(e=>e[0]===`production`?[[`stasis`,`Stasis`],e]:[e])):e,no=3e4,ro=50,io=e=>({path:e.path,dependencies:e.dependencies??null,pending:e.pending===!0,error:e.error??null,detail:e.detail??null,lockfiles:e.lockfiles??null}),ao=e=>y`<span class="risk-dev" data-tooltip="${e}">dev</span>`;function oo({name:e,source:t,dev:n},r,i,a){let o=y`${e}${r?y`<span class="risk-version">@${r}</span>`:b}`;return y`<span class="risk-package">${Y(G(t)?$e:Qe)}${i?y`<a class="risk-name risk-package-name" href="${i}">${o}</a>`:y`<span class="risk-package-name">${o}</span>`}${n?ao(a):b}</span>`}var so=e=>!e.error||e.error===`integrity-mismatch`;function co(e,t){let n=e.stale??null;return!so(e)&&!n&&t?.stale&&so(t)?{...t,refreshFailed:e.detail?`${U(e.error)}: ${e.detail}`:U(e.error)}:e.error?{error:e.error,detail:e.detail??null,stale:n}:{severity:e.severity,score:e.score??null,findings:e.findings,published:e.published,stale:n}}var lo=new Intl.RelativeTimeFormat(`en`,{numeric:`auto`});function uo(e,t=Date.now()){let n=Math.round((e-t)/6e4);if(Math.abs(n)<60)return lo.format(n,`minute`);let r=Math.round(n/60);return Math.abs(r)<48?lo.format(r,`hour`):lo.format(Math.round(r/24),`day`)}var fo=100,po=3,mo=5e3,ho=250,J=new Intl.NumberFormat,go=e=>({total:e.length,told:e.filter(e=>e.risk).length,flagged:e.filter(Fa).length,stale:e.filter(e=>e.risk?.stale).length,wasStale:e.filter(e=>e.wasStale).length}),Y=e=>y`<span class="risk-icon" aria-hidden="true">${g(e)}</span>`,_o={fix_started:`A fix has already been started`,inaccurate:`This alert is inaccurate or incorrect`,no_bandwidth:`No bandwidth to fix this`,not_used:`Vulnerable code is not actually used`,tolerable_risk:`Risk is tolerable to this project`};function vo({number:e,dismissed:t}){if(!t)return`Dependabot alert #${e}`;let n=t.auto?`auto-dismissed by a rule`:`dismissed${_o[t.reason]?`: ${_o[t.reason]}`:``}`,r=[t.by?`by @${t.by}`:``,t.at?.slice(0,10)??``].filter(Boolean).join(`, `);return[`Dependabot alert #${e}, ${n}${r?` (${r})`:``}`,...t.comment?[`\u201C${t.comment}\u201D`]:[]].join(`
23
+ `)}var X=Oe({page:null,shown:null});function yo(e,{repoId:t,commit:n,path:r,format:i},a,o){let{page:s,shown:c}=X,l=k(`/api/admin/repositories/risk/lockfile?${new URLSearchParams({repoId:t,commit:n,path:r,...Aa(s)})}`,{"github-not-found":`GitHub has it no longer.`},e=>e.json()).then(async({text:e,manifest:t})=>{let[{readLockfile:n},{lockfileWhy:r}]=await Promise.all([import(`./chunk-UR4WYMIP.js`),import(`./chunk-SSPDMA6D.js`)]);return r(await n(i,e,{manifest:t,env:!0}),{name:a,versions:o})});Ee({lockfile:e,packageKey:a,version:o.length===1?o[0]:void 0,load:l,isCurrent:()=>X.shown===c})}var bo=(e,t)=>t&&e.toLowerCase().startsWith(`${t}/`)?e.slice(t.length):e;function xo(e){let t=new Set([...e].map(e=>e.fullName.split(`/`)[0].toLowerCase()));return t.size===1?[...t][0]:null}function So(e,t,n,r,i){let a=bo(e,i),o=n?.get(e);if(o&&it(o.url))return y`<a class="${o.dismissed?`risk-name risk-used is-dismissed`:`risk-name risk-used`}" href="${o.url}" target="_blank" rel="noopener noreferrer">${Y(Je)}<span class="risk-clip risk-used-in" data-tooltip="${`${a}
24
+ ${vo(o)}`}">${a}</span>${o.dismissed?y`<span class="sr-only">(dismissed)</span>`:b}${f}</a>`;let s=t.get(e),c=s?.href,l=y`<span class="risk-clip risk-used-in" data-tooltip-truncated data-tooltip="${a}">${a}</span>`;if(r&&[`npm`,`pnpm`,`yarn`].includes(s?.format)){let[t,n]=r(e);return y`<span class="risk-used"><button type="button" class="risk-name risk-used-why" aria-haspopup="dialog" aria-label="${`What depends on ${t} in ${e}`}" @click="${()=>yo(e,s,t,n)}">${Y(_)}${l}</button><a class="risk-used-external" href="${c}" target="_blank" rel="noopener noreferrer" aria-label="${`${e} on GitHub`}">${f}</a></span>`}return c?y`<a class="risk-name risk-used" href="${c}" target="_blank" rel="noopener noreferrer">${Y(_)}${l}${f}</a>`:l}function Co(e,t,n,r=`lockfiles`,i=null,a=null){let o=[...e];if(o.length===1)return So(o[0],t,n,i,a);let s=o.map(e=>y`<li>${So(e,t,n,i,a)}</li>`);if(o.length===2)return y`<ul class="risk-used-lines">${s}</ul>`;let c=o.filter(e=>n?.get(e)?.dismissed).length;return y`<details class="risk-used-all"><summary>${J.format(o.length)} ${r}${c>0?`, ${J.format(c)} dismissed`:``}</summary><ul class="risk-used-lines">${s}</ul></details>`}var wo=e=>typeof e==`string`&&/^GHSA(?:-[\da-z]{4}){3}$/iu.test(e),To=(e,t,n,r=Oa)=>k(`/api/admin/repositories/risk${e.size>0?`?${e}`:``}`,r,async e=>{for await(let t of An(e))n(t)},t),Eo=({name:e,version:t,integrity:n})=>`${e}@${t}\0${n??``}`,Do=e=>G(e.source)?Eo(e):`${e.source}\0${e.name}@${e.version??``}\0${e.from??``}`,Oo=e=>[...e.lockfiles?.keys()??[]].map(t=>`${e.fullName}/${t}`);function ko(e,t,n){let r=e.versionsIn.get(t)??e.versionsIn.set(t,new Set).get(t);for(let t of n)r.add(t),e.versions.add(t)}function Ao(e){if(za(e))return-102;if(K(e))return-101;let t=Ia(e);return t>0?-t:G(e.source)?t===0?3:e.risk?2:1:4}var jo=(e,t,n,r)=>y`<div class="risk-tabs" role="tablist" aria-label="${e}">${t.map(([e,t])=>y`<button type="button" role="tab" aria-selected="${n===e}" @click="${()=>r(e)}">${t}</button>`)}</div>`,Mo={stasis:`Stasis`,lockfiles:`Lockfiles`,workflows:`Workflows`},Z=(e,t)=>y`${e}${t>0?y`<span class="n">${J.format(t)}</span>`:b}`,Q=(e,t,n=`${t}s`)=>`${J.format(e)} ${e===1?t:n}`,No=y`<svg class="risk-files-chevron" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m4 6 4 4 4-4"/></svg>`,Po=class extends x{static view=`manage-repo-risk`;static properties={selection:{attribute:!1},team:{attribute:!1},installTooltips:{attribute:!1},_state:{state:!0},_filter:{state:!0},_kind:{state:!0},_packageKind:{state:!0},_query:{state:!0},_tab:{state:!0},_actionKind:{state:!0},_actionFilter:{state:!0},_files:{state:!0},_scope:{state:!0},_target:{state:!0},_choices:{state:!0},_unlisted:{state:!0},_filesOpen:{state:!0},_filesShown:{state:!0}};static styles=[v(r),v(Ji),v(Ta)];constructor(){super(),Object.assign(this,{selection:null,team:null,installTooltips:null,_state:`idle`,_filter:`flagged`,_kind:`production`,_packageKind:`all`,_actionKind:`all`,_actionFilter:`flagged`,_query:``,_tab:`advisories`,_files:`lockfiles`,_filesOpen:!1,_filesShown:`all`,_scope:`all`,_target:``,_choices:null,_unlisted:null}),this._awaiting=!1,this._scan=null,this._asking=null,this._drawTimer=null,this._parts=0,this._reset()}_load(){if(this.hasUpdated)return this._loadChoices()}_loadChoices(){if(!this.team)return this._loadCollection(`teams`,`teams`,Or,e=>{this._choices=e})}willUpdate(e){this.hasUpdated||this._loadChoices(),this.team?e.has(`team`)&&this._followTeam():(e.has(`selection`)||e.has(`_choices`)&&this._awaiting)&&this._follow()}updated(e){e.has(`installTooltips`)&&this.installTooltips?.(this.renderRoot),this.team&&this._state===`idle`&&this.isConnected&&queueMicrotask(()=>{this._state===`idle`&&this.isConnected&&this.start()})}_followTeam(){this._state===`running`&&this._target!==this.team&&this.stop(),this._choose(`team`,this.team)}_follow(){let{riskScope:e=`team`,riskTarget:t=null}=this.selection??{},n=t==null?null:e===`team`?this._choices&&this._shownTeams().filter(e=>e.slug===t).map(e=>e.id):this._choices?.repos?.filter(e=>e.repoId===t).map(e=>String(e.repoId)),r=n?.length===1?n[0]:``;this._awaiting=t!=null&&!this._choices,this._unlisted=t!=null&&this._choices&&!r?e:null,this._state===`running`&&(e!==this._scope||r!==this._target)&&this.stop(),this._choose(e,r)}_shownTeams(){return(this._choices?.teams??[]).filter(e=>!e.hidden)}_pick(e,t=``){if(this._state===`running`)return;this._choose(e,t),Object.assign(this,{_awaiting:!1,_unlisted:null});let n=t&&(e===`repo`?Number(t):this._choices?.teams?.find(e=>e.id===t)?.slug);p(`manage-repo-risk`,{riskScope:e,...n?{riskTarget:n}:{}})}_choose(e,t=``){this._state===`running`||e===this._scope&&t===this._target||(this._scope=e,this._target=t,this._reset(),this._error=null,this._state=`idle`)}_reset(){this._repos=new Map,this._archived=new Map,this._packages=new Map,this._advisories=new Map,this._actions=new xa,this._reach=null,this._stopAsking()}connectedCallback(){super.connectedCallback(),Object.assign(X,{page:this,shown:this._shown=Symbol(`shown`)})}disconnectedCallback(){this.stop(),this._stopAsking(),X.shown===this._shown&&Object.assign(X,{page:null,shown:null}),super.disconnectedCallback()}async start(){if(this._state===`running`||this._scope!==`all`&&!this._target)return;let e=new URLSearchParams({...this._scope===`all`?{}:{[this._scope]:this._target},scan:crypto.randomUUID()});this._reset(),this._error=null,this._state=`running`;let t=new AbortController;this._scan=t,this._parts=0;try{for(let n=`continue`,r=0;n===`continue`;){if(++this._parts>fo)throw Error(`Stopped after ${J.format(fo)} parts. Scan again to go on from where it stopped.`);n=null;let i=this._told();if(await To(e,t.signal,e=>{(e.type===`done`||e.type===`continue`)&&(n=e.type),this._apply(e),this._draw()},this.team?ka:Oa),n===null)throw Error(`The scan ended before it finished. Try again.`);if(r=this._told()>i?0:r+1,n===`continue`&&r>=po)throw Error(`Stopped: the last ${J.format(po)} parts found nothing more. Scan again to try once more.`)}this._state=`done`}catch(e){if(t.signal.aborted||e?.name===`AbortError`)return;this._error=e?.message??String(e),this._state=`stopped`}finally{this._scan===t&&(this._scan=null,this._state===`running`&&(this._state=`stopped`)),this._draw(!0)}}stop(){this._scan&&(this._scan.abort(),this._scan=null,this._state=`stopped`,this._draw(!0))}_draw(e=!1){e?(clearTimeout(this._drawTimer),this._drawTimer=null,this.requestUpdate()):this._drawTimer??=setTimeout(()=>{this._drawTimer=null,this.requestUpdate()},ho)}_told(){let e=this._archived.size;for(let t of this._repos.values()){(t.lockfiles||t.error)&&e++,t.dependabot&&e++,t.stasis&&e++;for(let n of t.lockfiles?.values()??[])e+=+(n.packages!==null||!!n.error)+ +!!(n.advisories||n.advisoriesError)}for(let t of this._packages.values())t.risk&&!t.risk.stale&&e++;return e+this._actions.told()}_apply(e){if(e.type===`repos`){let t=new Map(e.repos.map(({id:e,fullName:t})=>[e,t]));for(let[e,n]of this._archived)t.get(e)!==n&&this._archived.delete(e);let n=[...this._repos.values()].filter(e=>t.get(e.id)!==e.fullName);for(let e of n)this._repos.delete(e.id),this._actions.forget(e.id);this._forget(n.flatMap(Oo),n.some(e=>e.dependabot?.alerts));for(let{id:t,fullName:n}of e.repos)!this._repos.has(t)&&!this._archived.has(t)&&this._repos.set(t,{id:t,fullName:n,commit:null,lockfiles:null,error:null,detail:null,dependabot:null,stasis:null});this._reach=null}else if(e.type===`repo`){let t=this._repos.get(e.id);if(!t)return;if(e.archived){this._archived.set(t.id,t.fullName),this._repos.delete(t.id),this._actions.forget(t.id),this._forget(Oo(t),!!t.dependabot?.alerts),this._reach=null;return}if(e.error){let n=Oo(t),r=!!t.dependabot?.alerts;Object.assign(t,{lockfiles:null,error:e.error,detail:e.detail??null,dependabot:null,stasis:null}),this._reach=null,this._actions.forget(t.id),this._forget(n,r);return}let n=t.commit!==null&&t.commit!==e.commit,r=new Set(n?[]:e.lockfiles.map(({path:e})=>e)),i=[...t.lockfiles?.keys()??[]].filter(e=>!r.has(e)).map(e=>`${t.fullName}/${e}`);Object.assign(t,{commit:e.commit,error:null,detail:null}),n&&(t.stasis=null),this._reach=null,t.lockfiles=new Map(e.lockfiles.map(e=>[e.path,!n&&t.lockfiles?.get(e.path)||{...e,packages:null,error:null}])),this._forget(i)}else if(e.type===`lockfile`){let t=this._repos.get(e.repo),n=t?.lockfiles?.get(e.path);if(!n)return;if(e.error){Object.assign(n,{error:e.error,detail:e.detail??null});return}Object.assign(n,{packages:e.packages.length,error:null,detail:null});let r=`${t.fullName}/${e.path}`;for(let t of e.packages){let e=Do(t),n=this._packages.get(e);n||this._packages.set(e,n={...t,usedIn:new Set,neededIn:new Set,risk:null}),n.usedIn.add(r),t.dev!==!0&&n.neededIn.add(r),n.dev=n.neededIn.size===0}}else if(e.type===`risk`){let t=this._packages.get(Eo(e));t&&(t.risk=co(e,t.risk),t.wasStale||=!!t.risk.stale)}else if(e.type===`advisories`)this._applyAdvisories(e);else if(e.type===`dependabot`)this._applyDependabot(e);else if(e.type===`stasis`){let t=this._repos.get(e.repo);if(!t)return;t.stasis=e.error?{error:e.error,detail:e.detail??null,configs:new Map}:{error:null,detail:null,configs:new Map(e.configs.map(e=>[e.path,io(e)]))},this._reach=null,this._askStasis()}else(e.type===`action`||(e.type===`workflows`||e.type===`workflow`)&&this._repos.has(e.repo))&&this._actions.apply(e)}_forget(e,t=!1){if(e.length===0)t&&this._readvise();else{for(let[t,n]of this._packages){for(let t of e)n.usedIn.delete(t),n.neededIn.delete(t);n.usedIn.size===0&&this._packages.delete(t),n.dev=n.neededIn.size===0}this._readvise()}}_readvise(){this._advisories=new Map;for(let e of this._packages.values())e.malware=void 0;for(let e of this._repos.values())for(let[t,n]of e.lockfiles??[])n.advisories&&this._advise(`${e.fullName}/${t}`,n.advisories);this._alert()}_alerted(){return[...this._repos.values()].some(e=>e.dependabot?.alerts?.length>0)}_applyAdvisories(e){let t=this._repos.get(e.repo),n=t?.lockfiles?.get(e.path);if(!n)return;if(e.error){n.advisoriesError=e.error;return}let r=n.advisories;Object.assign(n,{advisories:e.advisories,advisoriesError:null}),!r&&!this._alerted()?this._advise(`${t.fullName}/${e.path}`,e.advisories):JSON.stringify(r)!==JSON.stringify(e.advisories)&&this._readvise()}_applyDependabot(e){let t=this._repos.get(e.repo);if(!t)return;let n=t.dependabot;t.dependabot=e.error?{...n?.alerts&&{alerts:n.alerts},error:e.error,detail:e.detail??null}:{alerts:e.alerts},JSON.stringify(n?.alerts??null)!==JSON.stringify(t.dependabot.alerts??null)&&this._readvise()}_alert(){let e=new Map,t=(e,t)=>`${e.toUpperCase()}\0${t}`;for(let n of this._advisories.values())for(let r of[n.id,n.ghsa,...n.aliases??[]])wo(r)&&!e.has(t(r,n.name))&&e.set(t(r,n.name),n);let n=[...this._repos.values()].flatMap(e=>(e.dependabot?.alerts??[]).map(t=>({repo:e,alert:t})));for(let{repo:r,alert:i}of[...n.filter(e=>!e.alert.dismissed),...n.filter(e=>e.alert.dismissed)]){let n=`${r.fullName}/${i.manifest}`,a=e.get(t(i.ghsa,i.name));!a&&i.dismissed||(a||(a={id:i.ghsa,ghsa:i.ghsa,name:i.name,title:i.title,severity:i.severity,url:`https://github.com/advisories/${i.ghsa}`,aliases:i.aliases,cwe:i.cwe,malware:!1,dependabot:!0,ranges:new Set,versions:new Set,usedIn:new Set,versionsIn:new Map},this._advisories.set(`${i.ghsa}\0${i.name}`,a),e.set(t(i.ghsa,i.name),a)),a.dependabot&&i.range&&a.ranges.add(i.range),a.alerts??=new Map,a.alerts.set(n,i),a.usedIn.add(n),i.versions.length>0&&ko(a,n,i.versions),a.malware||=i.malware,this._markMalware(a))}}_advise(e,t){for(let{range:n,versions:r,...i}of t){let t=`${i.id}\0${i.name}`,a=this._advisories.get(t);a||this._advisories.set(t,a={...i,ranges:new Set,versions:new Set,usedIn:new Set,versionsIn:new Map}),n&&a.ranges.add(n),a.malware||=i.malware,a.usedIn.add(e),ko(a,e,r),this._markMalware(a)}}_markMalware(e){if(e.malware){for(let t of this._packages.values())if(G(t.source)&&t.name===e.name&&e.versions.has(t.version))for(let n of sa(e))(t.malware??=new Set).add(n)}}_counts(){let e=[...this._repos.values()],t=e.flatMap(e=>[...e.lockfiles?.values()??[]]),n=[...this._packages.values()].filter(e=>G(e.source));return{repos:e.length,reposRead:e.filter(e=>e.lockfiles||e.error).length,archived:this._archived.size,lockfiles:t.length,lockfilesRead:t.filter(e=>e.packages!==null||e.error).length,needed:go(n.filter(e=>!e.dev)),dev:go(n.filter(e=>e.dev)),advisories:this._adviseCounts()}}_adviseCounts(){let e=this._advisoryKinds(),t=new Set(e.production.filter(e=>!e.malware).map(e=>`${e.id}\0${e.name}`)),n=[...this._advisories.values()].filter(e=>e.malware).length;return{total:this._advisories.size,malware:n,needed:t.size,dev:this._advisories.size-n-t.size}}_hasStasis(){return[...this._repos.values()].some(e=>e.stasis&&(e.stasis.error||e.stasis.configs.size>0))}_packageKindShown(){return this._packageKind===`stasis`&&!this._hasStasis()?`all`:this._packageKind}_kindShown(){return this._kind===`stasis`&&!this._hasStasis()?`production`:this._kind}_stasisConfigs(){return[...this._repos.values()].flatMap(e=>[...e.stasis?.configs.values()??[]].map(t=>({repo:e,config:t})))}_stasisReach(){if(this._reach)return this._reach;let e={versions:new Set,at:new Map};for(let{repo:t,config:n}of this._stasisConfigs()){for(let t of n.dependencies??[])e.versions.add(q(t));let r=e=>e.slice(0,Math.max(e.lastIndexOf(`/`),0)),i=r(n.path),a=[...t.lockfiles?.keys()??[]].filter(e=>r(e)===``||i===r(e)||i.startsWith(`${r(e)}/`)),o=Math.max(...a.map(e=>r(e).length));for(let i of n.lockfiles??a.filter(e=>r(e).length===o)){let r=e.at.get(`${t.fullName}/${i}`)??e.at.set(`${t.fullName}/${i}`,new Set).get(`${t.fullName}/${i}`);for(let e of n.dependencies??[])r.add(q(e))}}return this._reach=e}_stasisCounts(){let e=this._stasisConfigs().map(({config:e})=>e);return{total:e.length,built:e.filter(e=>e.dependencies).length,pending:e.filter(e=>e.pending).length,failed:e.filter(e=>e.error).length+[...this._repos.values()].filter(e=>e.stasis?.error).length}}_stasisNote(){let{total:e,pending:t,failed:n}=this._stasisCounts();if(t===0&&n===0)return b;let r=e-t,i=[...this._repos.values()].flatMap(e=>e.stasis?.error?[`${e.fullName}: ${U(e.stasis.error)}`]:[...e.stasis?.configs.values()??[]].filter(e=>e.error).map(t=>`${e.fullName}/${t.path}: ${U(t.error)}${t.detail?` (${t.detail})`:``}`));return y`<p class="risk-stasis" role="status"><span class="risk-icon" aria-hidden="true"><img src="./stasis.svg" alt=""></span>${t>0?y`<span>Stasis is still building ${Q(t,`project`)}.</span> <span class="risk-builds" role="progressbar" aria-label="Stasis builds made" aria-valuemin="0" aria-valuemax="${e}" aria-valuenow="${r}"><span style="${et({width:`${e?r/e*100:0}%`})}"></span></span><span class="risk-builds-n">${J.format(r)}/${J.format(e)}</span>`:b} ${n>0?y`<span class="risk-dependabot-failed" data-tooltip="${i.join(`
25
25
  `)}">${Q(n,`build`)} failed</span>`:b}</p>`}_askStasis(){this._asking||!this.isConnected||this._stasisConfigs().some(({config:e})=>e.pending)&&(this._asking={timer:setTimeout(()=>{this._pollStasis()},no),controller:new AbortController})}_stopAsking(){this._asking&&=(clearTimeout(this._asking.timer),this._asking.controller.abort(),null)}async _pollStasis(){let e=this._asking;if(!e)return;let{signal:t}=e.controller,n=[...this._repos.values()].flatMap(e=>{let t=[...e.stasis?.configs.values()??[]].filter(e=>e.pending).map(e=>e.path);return Array.from({length:Math.ceil(t.length/ro)},(n,r)=>({repo:e,commit:e.commit,paths:t.slice(r*ro,(r+1)*ro)}))});await Promise.all(n.map(async({repo:e,commit:n,paths:r})=>{let i=new URLSearchParams([[`repoId`,String(e.id)],[`commit`,n],...r.map(e=>[`path`,e]),...Object.entries(Aa(this))]);try{let{configs:r}=await k(`/api/admin/repositories/risk/stasis?${i}`,{},e=>e.json(),t);if(t.aborted||e.commit!==n||!e.stasis||this._repos.get(e.id)!==e)return;for(let t of r)e.stasis.configs.has(t.path)&&e.stasis.configs.set(t.path,{...io(t),lockfiles:e.stasis.configs.get(t.path).lockfiles});this._reach=null}catch{}})),this._asking===e&&(this._asking=null,this._draw(!0),this._askStasis())}_rows(){let e=this._query.trim().toLowerCase(),[,t]=Ka[this._filter],n=this._packageKindShown(),r=this._stasisReach();return[...this._packages.values()].filter(i=>Ha(i,n,r)&&t(i)&&(!e||i.name.toLowerCase().includes(e))).toSorted((e,t)=>Ao(e)-Ao(t)||La(t).length-La(e).length||e.name.localeCompare(t.name)||(e.version??``).localeCompare(t.version??``))}_advisoryKinds(){let e=new Set,t=new Set;for(let n of this._packages.values())if(G(n.source)){for(let t of n.usedIn)e.add(`${n.name}@${n.version}\0${t}`);for(let e of n.neededIn)t.add(`${n.name}@${n.version}\0${e}`)}let n=this._stasisReach(),r={all:[],production:[],development:[],stasis:[]};for(let i of this._advisories.values()){let a=[...i.versions],o={production:new Map,development:new Map},s=(e,t,n)=>(e.get(t)??e.set(t,new Set).get(t)).add(n);for(let[n,r]of i.versionsIn)for(let a of r){let r=`${i.name}@${a}\0${n}`;s(o[(e.has(r)?!t.has(r):i.alerts?.get(n)?.dev)?`development`:`production`],n,a)}for(let[e,t]of i.alerts??[])i.versionsIn.get(e)?.size||o[t.dev?`development`:`production`].set(e,new Set);let c={...i,dev:o.production.size===0};if(r.all.push(c),i.malware){r.production.push(c),r.development.push(c),r.stasis.push(c);continue}let l=(e,t)=>({...i,dev:t,versions:new Set(a.filter(t=>[...e.values()].some(e=>e.has(t)))),usedIn:new Set([...i.usedIn].filter(t=>e.has(t)))});o.production.size>0&&r.production.push(l(o.production,!1)),o.development.size>0&&r.development.push(l(o.development,!0));let u=a.filter(e=>n.versions.has(q({name:i.name,version:e})));if(u.length>0){let e=new Map;for(let t of u){let r=[...i.versionsIn].flatMap(([e,n])=>n.has(t)?[e]:[]);for(let a of Va(r,q({name:i.name,version:t}),n))s(e,a,t)}r.stasis.push({...l(e,!1),versions:new Set(u)})}}return r.actions=this._actionAdvisories(),r.all.push(...r.actions),r}_actionAdvisories(){let e=new Map;for(let t of this._actions.rows(`actions`)){let n=t.line?.repository?.fullName??t.line?.repo??t.uses?.repo;for(let r of n?t.findings:[]){if(r.id!==`advisory`)continue;let i=`${r.advisory}\0${n.toLowerCase()}`,a=e.get(i);if(!a){let{id:t,advisory:o,range:s,versions:c,...l}=r;e.set(i,a={...l,kind:`action`,id:o,name:n,severity:r.unrated?void 0:r.severity,malware:!!r.malware,ranges:new Set,versions:new Set,usedIn:[]})}r.range&&a.ranges.add(r.range),t.line?.commit&&a.versions.add(`${t.line.commit.slice(0,7)}${t.line.tags?.length?` (${t.line.tags.join(`, `)})`:``}`),a.usedIn.push(...t.usedIn.filter(e=>!a.usedIn.some(t=>JSON.stringify(t)===JSON.stringify(e))))}}return[...e.values()]}_advisoryRows(e=this._advisoryKinds()){let t=this._query.trim().toLowerCase();return e[this._kindShown()].filter(e=>!t||e.name.toLowerCase().includes(t)).toSorted((e,t)=>Number(t.malware)-Number(e.malware)||V(e.severity)-V(t.severity)||e.name.localeCompare(t.name)||e.id.localeCompare(t.id))}_kindToggle(e,t,n,r,i){return y`<div class="risk-scope" role="group" aria-label="${e}">${Object.entries(t).map(([e,t])=>y`<button type="button" aria-pressed="${r===e}" @click="${()=>i(e)}">${t}<span class="n">${J.format(n[e])}</span></button>`)}</div>`}_filterToggle(e){let t=Object.fromEntries(Object.entries(Ka).map(([t,[,n]])=>[t,e.filter(n).length])),n=Object.entries(Ka).filter(([e])=>e===`all`||e===this._filter||t[e]>0);return n.length===1?b:this._kindToggle(`Show packages`,Object.fromEntries(n.map(([e,[t]])=>[e,t])),t,this._filter,e=>{this._filter=e})}_lockfileLinks(){let e=new Map;for(let t of this._repos.values())for(let n of t.commit?t.lockfiles?.keys()??[]:[])e.set(`${t.fullName}/${n}`,{href:H(t.fullName,t.commit,n),repoId:t.id,commit:t.commit,path:n,format:t.lockfiles.get(n).format});return e}render(){let e=!!this.team;return y`<div class="${e?`wrap team-risk`:`wrap`}">${e?b:y`${this._nav()}<h1 class="sr-only">Repository risk</h1>`}<div class="page-intro"><p class="intro">${e?`Risks in the team’s repositories’ npm dependencies and GitHub Actions.`:`Risks in each repository’s npm dependencies and GitHub Actions.`}</p>${this._stateBadge()}${this._state===`running`?y`<button type="button" class="btn" @click="${()=>this.stop()}">Stop</button>`:y`<button type="button" class="${e?`btn`:`btn primary`}" ?disabled="${this._scope!==`all`&&!this._target}" @click="${()=>{this.start()}}">${this._state===`idle`?`Start scan`:`Scan again`}</button>`}</div>${e?b:this._scopeBar()} ${this._progress()} ${this._error?y`<p class="msg error" role="alert">${this._error}</p>`:b} ${this._repos.size===0?b:y`<div class="manage-list">${this._lockfiles()} ${this._packages.size===0&&this._actions.files.size===0?b:this._tab===`advisories`?this._advisoryTable():this._tab===`actions`?this._actionsTable():this._packageTable()}</div>`}</div>`}_tabs(){return jo(`Results`,[[`advisories`,Z(`Advisories`,this._advisories.size+this._actionAdvisories().length)],[`packages`,Z(`Packages`,this._packages.size)],[`actions`,Z(`Actions`,this._actions.rows(`actions`).length)]],this._tab,e=>{this._tab=e})}_search(e,t,n,r=`package`){return y`<div class="risk-search"><input type="search" aria-label="${`Search ${n}`}" placeholder="${`Search by ${r}\u2026`}" .value="${this._query}" @input="${e=>{this._query=e.target.value}}"> <span class="result-count">${e===t?``:`${J.format(e)} of `}${J.format(t)} ${n}</span></div>`}_scopeBar(){let e=this._state===`running`,t=this._choices?``:`Loading…`;return y`<div class="risk-scope-bar"><div class="risk-scope" role="group" aria-label="What to scan">${ja.map(([t,n])=>y`<button type="button" aria-pressed="${this._scope===t}" ?disabled="${e}" @click="${()=>this._pick(t)}">${n}</button>`)}</div>${this._scope===`team`?this._teamPicker(e,t):b} ${this._scope===`repo`?y`<repository-selector label="Which repository" placeholder="${t||`Choose a repository…`}" ?disabled="${e||!this._choices}" .options="${(this._choices?.repos??[]).map(e=>({value:String(e.repoId),label:e.fullName}))}" .value="${this._target||null}" @repository-change="${e=>this._pick(`repo`,e.detail.value)}"></repository-selector>`:b}</div>${this._unlisted?y`<p class="msg" role="status">${this._unlisted===`team`?`This link’s team isn’t listed. Choose a team.`:`This link’s repository isn’t connected. Choose a repository.`}</p>`:b}`}_teamPicker(e,t){let n=e=>new Set((e.repos??[]).map(e=>e.repoId)).size,r=this._shownTeams().toSorted((e,t)=>n(t)-n(e)),i=e=>e.name;return r.length>0&&r.length<=Ma?y`<div class="risk-scope" role="group" aria-label="Which team">${r.map(t=>y`<button type="button" aria-pressed="${t.id===this._target}" ?disabled="${e}" @click="${()=>this._pick(`team`,t.id)}">${i(t)}</button>`)}</div>`:y`<select aria-label="Which team" ?disabled="${e}" @change="${e=>this._pick(`team`,e.target.value)}"><option value="" ?selected="${!this._target}">${t||`Choose a team…`}</option>${r.map(e=>y`<option value="${e.id}" ?selected="${e.id===this._target}">${i(e)}</option>`)}</select>`}_metrics(){let e=this._counts(),{needed:t,dev:n,advisories:r}=e,i=e=>J.format(e),a=e=>({bar:e.map(([e,t])=>[e,t]),split:e.filter(([,e,t=e])=>t>0)}),o=t.flagged+n.flagged,s=t.stale+n.stale,c=t.wasStale+n.wasStale,{workflows:l,workflowsRead:u}=this._actions.counts();return[{label:`Repositories`,value:e.reposRead,of:e.repos,bar:[[`read`,e.reposRead]],split:[[`lockfiles`,e.lockfilesRead,e.lockfiles],[`workflows`,u,l]].filter(([,,e])=>e>0),note:e.archived>0?[`${Q(e.archived,`archived repository`,`archived repositories`)} left out.`]:[]},{label:`Packages`,value:t.told+n.told,of:t.total+n.total,...a([[`prod`,t.told,t.total],[`dev`,n.told,n.total]])},{label:`Flagged`,value:o,...a([[`prod`,t.flagged],[`dev`,n.flagged]]),tone:o>0?`high`:null},...c>0?[{label:`Stale`,value:s,scale:c,bar:[[`prod`,t.wasStale-t.stale],[`dev`,n.wasStale-n.stale]],split:a([[`prod`,t.stale],[`dev`,n.stale]]).split,note:[...s>0?[`Assessed over an hour ago; ${this._state===`running`?`to be assessed again once the rest are`:`not assessed again yet`}.`]:[],`${i(c-s)} of ${i(c)} assessed again.`]}]:[],...r.total>0?[{label:`Advisories`,value:r.total,...a([[`malware`,r.malware],[`prod`,r.needed],[`dev`,r.dev]])}]:[],...this._stasisMetrics(),...this._actionsMetrics()]}_stasisMetrics(){let{total:e,built:t,pending:n,failed:r}=this._stasisCounts();return e===0&&r===0?[]:[{label:`Stasis`,value:t,of:e,bar:[[`read`,t]],note:[...n>0?[`${Q(n,`build`)} still to be made, asked for again every 30 seconds while this page shows them.`]:[],...r>0?[`${Q(r,`build`)} failed.`]:[]]}]}_actionsMetrics(){if(this._actions.listed.size===0)return[];let{actions:e,resolved:t}=this._actions.counts(),n=this._actions.rows(`all`).filter(e=>e.severity&&e.severity!==`notice`&&e.severity!==`low`).length;return[{label:`Actions`,value:t,of:e,bar:[[`read`,t]]},{label:`Actions flagged`,value:n,bar:[],tone:n>0?`high`:null}]}_stateBadge(){if(this._state===`idle`)return b;let e=this._state===`running`&&this._parts>1?`Scanning \xB7 part ${J.format(this._parts)}`:{running:`Scanning`,stopped:`Stopped`,done:`Done`}[this._state];return y`<span class="risk-state" role="status" data-state="${this._state}">${e}</span>`}_progress(){if(this._state===`idle`)return y`<div class="risk-progress-line"><div class="risk-progress" role="status"><p class="risk-progress-idle">Not scanned yet. A scan reads each repository from GitHub and assesses each npm package it locks, which can take a while; a scan again within the hour is quicker.</p></div></div>`;let e=e=>J.format(e),t=({split:t=[],note:n=[]})=>[t.length>0?`${t.map(([t,n,r])=>`${e(n)}${r===void 0?``:`/${e(r)}`} ${t}`).join(`, `)}.`:``,...n].filter(Boolean).join(` `),n=({split:t=[],note:n=[]})=>y`${t.length>0?y`<div class="tooltip-counts">${t.map(([t,n,r])=>y`<span class="tooltip-count">${e(n)}${r===void 0?b:y`<span class="tooltip-count-of"><span class="tooltip-slash">/</span>${e(r)}</span>`}</span><span>${t}</span>`)}</div>`:b}${n.map(e=>y`<div class="tooltip-counts-note">${e}</div>`)}`;return y`<div class="risk-progress-line"><div class="risk-progress" role="status">${this._metrics().map(r=>{let{label:i,value:a,of:o,scale:s=o??a,bar:c,tone:l}=r,u=t(r);return y`<span class="${l?`risk-metric risk-${l}`:`risk-metric`}" data-tooltip="${u||b}" .tooltipContent="${u?n(r):null}"><span class="risk-metric-label">${i}</span> <span class="risk-metric-value">${e(a)}${o===void 0?b:y`<span class="risk-metric-of"><span class="risk-metric-slash">/</span>${e(o)}</span>`}${u?y`<span class="sr-only">${u}</span>`:b}</span> <span class="risk-bar" aria-hidden="true">${c.filter(([,e])=>e>0).map(([e,t])=>y`<span class="${`risk-bar-${e}`}" style="${et({width:`${t/s*100}%`})}"></span>`)}</span></span>`})}</div>${this._filesToggle()}</div>`}_pending(e,t){return y`<span class="risk-pending">${this._state===`running`?e:t}</span>`}_repoStatus(e,t=`lockfiles`){if(e.error)return W(e);if(e.lockfiles===null)return this._pending(`Waiting…`,`Not read`);if(t===`stasis`)return null;if(t===`lockfiles`)return e.lockfiles.size===0?y`<span class="risk-none">No npm lockfiles</span>`:null;let n=this._actions.listed.get(e.id);return n?n.error||this._actions.filesOf(e.id).length>0?null:y`<span class="risk-none">No workflows</span>`:this._pending(`Waiting…`,`Not read`)}_lockfileStatus(e){return e.error?W(e):e.packages===null?this._pending(`Reading…`,`Not read`):`${J.format(e.packages)} packages`}_lockfiles(){if(!this._filesOpen)return b;let{lockfiles:e,workflows:t}=this._filesTold(),n=[...this._hasStasis()?[[`stasis`,Z(`Stasis`,this._stasisCounts().total)]]:[],[`lockfiles`,Z(`Lockfiles`,e)],...this._actions.listed.size>0?[[`workflows`,Z(`Workflows`,t)]]:[]],r=n.some(([e])=>e===this._files)?this._files:`lockfiles`,i=[...this._repos.values()].filter(e=>r!==`stasis`||e.stasis),a=i.filter(e=>this._failed(e,r)),o=this._filesShown===`failed`&&a.length>0?a:i,s=n.map(([e],t)=>t===0?Mo[e]:Mo[e].toLowerCase());return y`<section id="risk-files" class="risk-files" aria-label="${s.length>1?`${s.slice(0,-1).join(`, `)} and ${s.at(-1)}`:s[0]}"><div class="risk-files-head">${n.length>1?jo(`Files`,n,r,e=>{this._files=e}):y`<h2>${Z(`Lockfiles`,e)}</h2>`} ${a.length>0?this._kindToggle(`Show repositories`,{all:`All`,failed:`Couldn’t be read`},{all:i.length,failed:a.length},o===a?`failed`:`all`,e=>{this._filesShown=e}):b}</div><ul class="risk-repos">${tt(o,e=>e.id,e=>y`<li>${e.commit?y`<a class="risk-repo-name risk-name" href="${H(e.fullName,e.commit,``,`tree`)}" target="_blank" rel="noopener noreferrer" data-tooltip-truncated data-tooltip="${e.fullName}">${Y(_)}${e.fullName}</a>`:y`<span class="risk-repo-name" data-tooltip-truncated data-tooltip="${e.fullName}">${Y(_)}${e.fullName}</span>`} ${this._repoStatus(e,r)??y`<ul class="risk-lockfiles">${r===`workflows`?this._workflowItems(e):r===`stasis`?this._stasisItems(e):[...e.lockfiles.values()].map(t=>y`<li>${this._fileLink(e,t.path)}<span class="risk-lockfile-meta">${t.format} · ${this._lockfileStatus(t)}</span></li>`)}</ul>`}</li>`)}</ul></section>`}_filesTold(){let e=[...this._repos.values()],t=e.flatMap(e=>[...e.lockfiles?.values()??[]]),n=[...this._actions.listed.values()],r=[...this._actions.files.values()].flatMap(e=>[...e.values()]);return{lockfiles:t.length,workflows:this._actions.counts().workflows,reposFailed:e.filter(e=>e.error).length,filesFailed:t.filter(e=>e.error).length+n.filter(e=>e.error).length+r.filter(e=>e.error).length+this._stasisCounts().failed}}_filesToggle(){if(this._repos.size===0)return b;let{reposFailed:e,filesFailed:t}=this._filesTold(),n=[e>0?Q(e,`repository`,`repositories`):``,t>0?Q(t,`file`):``].filter(Boolean).join(` and `),r=n&&`${n} couldn\u2019t be read`;return y`<button type="button" class="risk-files-toggle" aria-label="${[`Progress details`,...r?[r]:[]].join(`, `)}" aria-expanded="${this._filesOpen}" aria-controls="${this._filesOpen?`risk-files`:b}" data-tooltip="${[`Progress details`,...r?[r]:[]].join(`
26
26
  `)}" @click="${()=>{this._filesOpen=!this._filesOpen}}">${No}${r?y`<span class="n" aria-hidden="true">${J.format(e+t)}</span>`:b}</button>`}_stasisItems(e){let{stasis:t}=e;return t?t.error?y`<li><span class="mono">stasis.config.json</span><span class="risk-lockfile-meta">${W(t)}</span></li>`:[...t.configs.values()].map(t=>y`<li>${this._fileLink(e,t.path)}<span class="risk-lockfile-meta">${t.error?W(t):t.pending?y`<span class="risk-pending">Building…</span>`:`${J.format(t.dependencies.length)} packages`}</span></li>`):b}_failed(e,t){return e.error?!0:t===`lockfiles`?[...e.lockfiles?.values()??[]].some(e=>e.error):t===`stasis`?!!e.stasis?.error||[...e.stasis?.configs.values()??[]].some(e=>e.error):!!this._actions.listed.get(e.id)?.error||this._actions.filesOf(e.id).some(e=>e.error)}_fileLink(e,t){return e.commit?y`<a class="mono risk-name" href="${H(e.fullName,e.commit,t)}" target="_blank" rel="noopener noreferrer">${t}</a>`:y`<span class="mono">${t}</span>`}_workflowItems(e){let t=this._actions.listed.get(e.id);return t?t.error?y`<li><span class="mono">.github/workflows</span><span class="risk-lockfile-meta">${W(t)}</span></li>`:this._actions.filesOf(e.id).map(t=>y`<li>${this._fileLink(e,t.path)}<span class="risk-lockfile-meta">${t.kind} · ${t.error?W(t):`${J.format(t.findings.length)} findings`}</span></li>`):b}_resultsHead(e){return y`<div class="risk-results-head"><div class="collection-toolbar">${this._tabs()}${e}</div></div>`}_packageTable(){let e=this._rows(),t=[...this._packages.values()],n=this._packageKindShown(),r=to(Za,this._hasStasis()),i=this._stasisReach(),a=Object.fromEntries(Object.keys(r).map(e=>[e,t.filter(t=>Ha(t,e,i)).length])),o=this._lockfileLinks(),s=xo(this._repos.values()),c=t.some(e=>e.source!==`registry`);return y`<section class="risk-section" aria-label="Packages">${this._resultsHead(y`${this._kindToggle(`Which packages`,r,a,n,e=>{this._packageKind=e})} ${this._filterToggle(t.filter(e=>Ha(e,n,i)))} ${this._search(e.length,a[n],`packages`)}`)} ${n===`stasis`?this._stasisNote():b} ${this._table(e,this._filter===`flagged`&&!this._query.trim()?eo(this._state):null,y`<th>Package</th><th><span data-tooltip="${qa}">Risk</span></th><th>Findings</th>${c?y`<th>Source</th>`:b}<th class="risk-used-column">Used in</th>`,Do,e=>this._packageRow(e,o,c,Ua(e,n,i),s),`Search or filter to see others.`)}</section>`}_packageRow(e,t,n,r=e.usedIn,i=null){let a=G(e.source)?rt({view:`npm`,packageName:e.name,packageSpec:e.version}):null;return y`<tr class="${e.risk?.stale?`is-stale`:``}"><td>${oo(e,e.version,a,Ja)}</td><td>${this._score(e)}</td><td>${this._findings(e)}</td>${n?y`<td><span data-tooltip="${e.from??b}">${Na[e.source]??e.source}${e.source===`mirror`&&e.from?` (${new URL(e.from).host})`:``}</span></td>`:b}<td>${Co(r,t,void 0,`lockfiles`,()=>[e.name,e.version?[e.version]:[]],i)}</td></tr>`}_score(e){let t=Ia(e),n=t===null?b:y`<span class="${`risk-score risk-${ta(t)}`}">${t}</span>`;return e.risk?.stale?y`${n}<span class="risk-stale" data-tooltip="${this._staleSaid(e.risk)}">stale</span>`:n}_staleSaid({stale:e,refreshFailed:t}){let n=t?`couldn\u2019t be assessed again: ${t}`:this._state===`running`?`to be assessed again once the rest are`:`not assessed again yet`;return`Assessed ${uo(e.assessedAt)}; ${n}`}_findings(e){let t=La(e);return t.length>0?y`<ul class="risk-findings">${t.map(t=>y`<li class="${`risk-${t.severity}`}" data-tooltip="${t.id===`malware`?Ra(e).join(`
27
27
  `):b}">${Ea[t.id]??t.id}</li>`)}</ul>`:G(e.source)?e.risk?K(e)?y`<ul class="risk-findings"><li class="risk-critical" data-tooltip="${Xa}">${U(e.risk.error)}</li></ul>`:e.risk.error?W(e.risk):y`<span class="risk-none">None found</span>`:this._pending(`Waiting…`,`Not assessed`):y`<span class="risk-none">Not assessed</span>`}_advisoryTable(){let e=this._advisoryKinds(),t=this._lockfileLinks(),n=xo(this._repos.values()),r=this._advisoryRows(e),i=[...this._repos.values()].flatMap(e=>[...e.lockfiles?.values()??[]].filter(e=>e.advisoriesError).map(t=>`${e.fullName}/${t.path}`)),a=this._kindShown(),o={all:`any version locked`,production:`the versions an install for production takes`,development:`the versions only devDependencies need`,stasis:`the versions Stasis builds install`}[a],s=a===`actions`?`GitHub tells of no advisories of the actions the workflows use.`:this._alerted()?`Neither npm nor Dependabot tells of advisories of ${o}.`:`npm has no advisories of ${o}.`,c=Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.length]));return y`<section class="risk-section risk-advisories" aria-label="Advisories">${this._resultsHead(y`${this._kindToggle(`Which advisories`,to(Qa,this._hasStasis()),c,a,e=>{this._kind=e})}${this._search(r.length,e[a].length,`advisories`)}`)} ${a===`stasis`?this._stasisNote():b} ${this._dependabotStatus()} ${i.length>0?y`<p class="msg error">npm’s advisories couldn’t be had for <span data-tooltip="${i.join(`
28
- `)}">${i.length===1?i[0]:`${J.format(i.length)} lockfiles`}</span>.</p>`:b} ${this._table(r,this._state===`running`?`None yet.`:s,y`<th>Package</th><th>Versions</th><th>Severity</th><th>Advisory</th><th>Title</th><th>Used in</th>`,e=>`${e.kind??`npm`}\0${e.id}\0${e.name}`,e=>this._advisoryRow(e,t,n))}</section>`}_actionsTable(){let e=Object.fromEntries(Object.keys(ga).map(e=>[e,this._actions.rows(e).length])),t=this._actions.rows(this._actionKind),n=Object.fromEntries(Object.entries($a).map(([e,[,n]])=>[e,t.filter(n).length])),r=this._actions.rows(this._actionKind,this._query).filter($a[this._actionFilter][1]),i=xo(this._repos.values()),a=this._state===`running`&&this._actionFilter===`all`?`None yet.`:this._actions.listed.size===0?`No workflows were read.`:this._actionFilter===`flagged`&&!this._query.trim()?eo(this._state):`Nothing found.`;return y`<section class="risk-section" aria-label="Actions">${this._resultsHead(y`${this._kindToggle(`Which`,ga,e,this._actionKind,e=>{this._actionKind=e})} ${this._kindToggle(`Show rows`,Object.fromEntries(Object.entries($a).map(([e,[t]])=>[e,t])),n,this._actionFilter,e=>{this._actionFilter=e})} ${this._search(r.length,e[this._actionKind],`rows`,`name`)}`)} ${this._table(r,a,y`<th>Uses</th><th>Pinned to</th><th>Findings</th><th class="risk-used-column">Used in</th>`,e=>e.key,e=>this._actionRow(e,i))}</section>`}_table(e,t,n,r,i,a=`Search to see others.`){return y`${e.length===0&&t!=null?y`<p class="msg">${t}</p>`:y`<div class="link-table"><table><thead><tr>${n}</tr></thead><tbody>${tt(e.slice(0,mo),r,i)}</tbody></table></div>`} ${e.length>mo?y`<p class="msg">Showing the first ${J.format(mo)}. ${a}</p>`:b}`}_actionRow(e,t=null){let n=e.kind===`action`?wa(e):null,r=e.key.replace(/^[^@]*@/u,``).replace(/^([\da-f]{7})[\da-f]{33}\b/u,`$1`),i=e.kind===`action`?y`<span data-tooltip="${e.key}">${e.key.replace(/@.*$/u,``)}<span class="risk-version">@${r}</span></span>`:e.name,a=e.line?.error?W(e.line):e.kind===`action`&&!e.line?this._pending(`Resolving…`,`Not resolved`):b;return y`<tr><td class="${e.kind===`step`?`risk-step`:b}"><span class="risk-package">${Y(e.kind===`action`?_:Ze)}${n?y`<a class="risk-name mono" href="${n}" target="_blank" rel="noopener noreferrer">${i}</a>`:y`<span class="mono">${i}</span>`}</span></td><td class="mono">${Sa(e.line)??a}</td><td>${e.findings.length>0?Ca(e.findings):e.line&&!e.line.error?y`<span class="risk-none">None found</span>`:b}</td><td>${this._actionUsedIn(e.usedIn,t)}</td></tr>`}_actionUsedIn(e,t=null){let n=new Map;return Co(e.map(({repo:e,path:t,line:r,via:i})=>{if(i)return`via ${i}`;let{fullName:a=String(e),commit:o}=this._repos.get(e)??{},s=`${a}/${t}:${r}`;return o&&n.set(s,{href:`${H(a,o,t)}${r?`#L${r}`:``}`}),s}),n,void 0,`places`,null,t)}_advisoryRow(e,t,n=null){let r=e.kind===`action`,i=[...e.versions],a=e.malware?`critical`:e.severity;return y`<tr><td>${r?y`<span class="risk-package">${Y(_)}<a class="risk-name mono" href="${`https://github.com/${e.name}`}" target="_blank" rel="noopener noreferrer">${e.name}</a></span>`:oo({...e,source:`registry`},null,rt({view:`npm`,packageName:e.name,packageSpec:i[0]}),Ya)}</td><td class="mono risk-versions">${r?i.map((e,t)=>y`${t===0?``:`, `}<span class="risk-pin">${e}</span>`):i.join(`, `)}</td><td>${e.malware?y`<span class="risk-chip risk-critical">Malware</span>`:a?y`<span class="${`risk-chip risk-${a}`}">${Wa(a)}</span>`:b}</td><td class="mono">${ma({...e,severity:a,versions:i,ranges:[...e.ranges],source:e.dependabot?`dependabot`:e.source})}</td><td><span class="risk-clip" data-tooltip-truncated data-tooltip="${e.title??b}">${e.title??``}</span></td><td>${r?this._actionUsedIn(e.usedIn,n):Co(e.usedIn,t,e.alerts,`lockfiles`,t=>[e.name,[...e.versionsIn?.get(t)??e.versions]],n)}</td></tr>`}_dependabotStatus(){let e=[...this._repos.values()].filter(e=>e.dependabot);if(e.length===0)return b;let t=e.filter(e=>e.dependabot.alerts),n=e.filter(e=>e.dependabot.error),r=(e,t,n=`${t}s`)=>`${J.format(e)} ${e===1?t:n}`,i=e=>{let t=e.filter(e=>e.dismissed).length,n=e.length-t;return t===0?r(n,`open alert`):`${J.format(n)} open and ${J.format(t)} dismissed ${e.length===1?`alert`:`alerts`}`},a=n.map(({fullName:e,dependabot:{error:t,detail:n}})=>`${e}: ${U(t)}${n?` (${n})`:``}`).join(`
29
- `);return y`<p class="risk-dependabot" role="status">${Y($e)}<span>Dependabot</span> ${t.length>0?y`<span data-tooltip="${t.map(e=>`${e.fullName}: ${i(e.dependabot.alerts)}`).join(`
28
+ `)}">${i.length===1?i[0]:`${J.format(i.length)} lockfiles`}</span>.</p>`:b} ${this._table(r,this._state===`running`?`None yet.`:s,y`<th>Package</th><th>Versions</th><th>Severity</th><th>Advisory</th><th>Title</th><th>Used in</th>`,e=>`${e.kind??`npm`}\0${e.id}\0${e.name}`,e=>this._advisoryRow(e,t,n))}</section>`}_actionsTable(){let e=Object.fromEntries(Object.keys(ga).map(e=>[e,this._actions.rows(e).length])),t=this._actions.rows(this._actionKind),n=Object.fromEntries(Object.entries($a).map(([e,[,n]])=>[e,t.filter(n).length])),r=this._actions.rows(this._actionKind,this._query).filter($a[this._actionFilter][1]),i=xo(this._repos.values()),a=this._state===`running`&&this._actionFilter===`all`?`None yet.`:this._actions.listed.size===0?`No workflows were read.`:this._actionFilter===`flagged`&&!this._query.trim()?eo(this._state):`Nothing found.`;return y`<section class="risk-section" aria-label="Actions">${this._resultsHead(y`${this._kindToggle(`Which`,ga,e,this._actionKind,e=>{this._actionKind=e})} ${this._kindToggle(`Show rows`,Object.fromEntries(Object.entries($a).map(([e,[t]])=>[e,t])),n,this._actionFilter,e=>{this._actionFilter=e})} ${this._search(r.length,e[this._actionKind],`rows`,`name`)}`)} ${this._table(r,a,y`<th>Uses</th><th>Pinned to</th><th>Findings</th><th class="risk-used-column">Used in</th>`,e=>e.key,e=>this._actionRow(e,i))}</section>`}_table(e,t,n,r,i,a=`Search to see others.`){return y`${e.length===0&&t!=null?y`<p class="msg">${t}</p>`:y`<div class="link-table"><table><thead><tr>${n}</tr></thead><tbody>${tt(e.slice(0,mo),r,i)}</tbody></table></div>`} ${e.length>mo?y`<p class="msg">Showing the first ${J.format(mo)}. ${a}</p>`:b}`}_actionRow(e,t=null){let n=e.kind===`action`?wa(e):null,r=e.key.replace(/^[^@]*@/u,``).replace(/^([\da-f]{7})[\da-f]{33}\b/u,`$1`),i=e.kind===`action`?y`<span data-tooltip="${e.key}">${e.key.replace(/@.*$/u,``)}<span class="risk-version">@${r}</span></span>`:e.name,a=e.line?.error?W(e.line):e.kind===`action`&&!e.line?this._pending(`Resolving…`,`Not resolved`):b;return y`<tr><td class="${e.kind===`step`?`risk-step`:b}"><span class="risk-package">${Y(e.kind===`action`?_:Qe)}${n?y`<a class="risk-name mono" href="${n}" target="_blank" rel="noopener noreferrer">${i}</a>`:y`<span class="mono">${i}</span>`}</span></td><td class="mono">${Sa(e.line)??a}</td><td>${e.findings.length>0?Ca(e.findings):e.line&&!e.line.error?y`<span class="risk-none">None found</span>`:b}</td><td>${this._actionUsedIn(e.usedIn,t)}</td></tr>`}_actionUsedIn(e,t=null){let n=new Map;return Co(e.map(({repo:e,path:t,line:r,via:i})=>{if(i)return`via ${i}`;let{fullName:a=String(e),commit:o}=this._repos.get(e)??{},s=`${a}/${t}:${r}`;return o&&n.set(s,{href:`${H(a,o,t)}${r?`#L${r}`:``}`}),s}),n,void 0,`places`,null,t)}_advisoryRow(e,t,n=null){let r=e.kind===`action`,i=[...e.versions],a=e.malware?`critical`:e.severity;return y`<tr><td>${r?y`<span class="risk-package">${Y(_)}<a class="risk-name mono" href="${`https://github.com/${e.name}`}" target="_blank" rel="noopener noreferrer">${e.name}</a></span>`:oo({...e,source:`registry`},null,rt({view:`npm`,packageName:e.name,packageSpec:i[0]}),Ya)}</td><td class="mono risk-versions">${r?i.map((e,t)=>y`${t===0?``:`, `}<span class="risk-pin">${e}</span>`):i.join(`, `)}</td><td>${e.malware?y`<span class="risk-chip risk-critical">Malware</span>`:a?y`<span class="${`risk-chip risk-${a}`}">${Wa(a)}</span>`:b}</td><td class="mono">${ma({...e,severity:a,versions:i,ranges:[...e.ranges],source:e.dependabot?`dependabot`:e.source})}</td><td><span class="risk-clip" data-tooltip-truncated data-tooltip="${e.title??b}">${e.title??``}</span></td><td>${r?this._actionUsedIn(e.usedIn,n):Co(e.usedIn,t,e.alerts,`lockfiles`,t=>[e.name,[...e.versionsIn?.get(t)??e.versions]],n)}</td></tr>`}_dependabotStatus(){let e=[...this._repos.values()].filter(e=>e.dependabot);if(e.length===0)return b;let t=e.filter(e=>e.dependabot.alerts),n=e.filter(e=>e.dependabot.error),r=(e,t,n=`${t}s`)=>`${J.format(e)} ${e===1?t:n}`,i=e=>{let t=e.filter(e=>e.dismissed).length,n=e.length-t;return t===0?r(n,`open alert`):`${J.format(n)} open and ${J.format(t)} dismissed ${e.length===1?`alert`:`alerts`}`},a=n.map(({fullName:e,dependabot:{error:t,detail:n}})=>`${e}: ${U(t)}${n?` (${n})`:``}`).join(`
29
+ `);return y`<p class="risk-dependabot" role="status">${Y(Je)}<span>Dependabot</span> ${t.length>0?y`<span data-tooltip="${t.map(e=>`${e.fullName}: ${i(e.dependabot.alerts)}`).join(`
30
30
  `)}">${i(t.flatMap(e=>e.dependabot.alerts))} of ${r(t.length,`repository`,`repositories`)}</span>`:b} ${n.length>0?y`<span class="risk-dependabot-failed" data-tooltip="${a}">${t.length>0?`unavailable for `:`alerts unavailable for `}${n.length===1?n[0].fullName:r(n.length,`repository`,`repositories`)}${n.length===1?y`: ${U(n[0].dependabot.error)}`:b}</span>`:b}</p>`}};customElements.define(`managed-admin-repo-risk`,Po);function Fo({signal:e}={}){return Ro(`/api/auth/profile`,{signal:e},`load your profile`)}function Io(e,t,{signal:n}={}){return Ro(`/api/auth/profile`,{method:`POST`,body:JSON.stringify(e),csrfToken:t,signal:n},`save your profile`)}function Lo(e,t,{signal:n}={}){return Ro(`/api/auth/profile/accounts/${encodeURIComponent(e)}`,{method:`DELETE`,csrfToken:t,signal:n},`unlink the account`)}async function Ro(e,{method:t=`GET`,body:n,csrfToken:r,signal:i},a){let o=await l(e,{method:t,credentials:`same-origin`,signal:i,...n?{body:n}:{},headers:{accept:`application/json`,...n?{"content-type":`application/json`}:{},...r?{"x-csrf-token":r}:{}}}),s=await o.json().catch(()=>null),c=o.ok?zo(s?.profile):null;if(!c)throw Error(`Could not ${a} (${o.ok?`unreadable answer`:s?.error??o.status}).`);return c}function zo(e){let t=e=>typeof e==`string`?e:null;return typeof e?.login!=`string`||!Array.isArray(e.accounts)?null:{login:e.login,name:t(e.name),githubName:t(e.githubName),nameAccount:t(e.nameAccount),avatarAccount:t(e.avatarAccount),accounts:e.accounts.filter(e=>typeof e?.id==`string`&&typeof e.login==`string`).map(e=>({id:e.id,login:e.login,name:t(e.name),linkedAt:Number.isSafeInteger(e.linkedAt)?e.linkedAt:null}))}}function Bo(e,t){return new Promise(n=>{if(t.aborted){n();return}let r=()=>{clearTimeout(i),t.removeEventListener(`abort`,r),n()},i=setTimeout(r,e);t.addEventListener(`abort`,r,{once:!0})})}async function Vo(e,{signal:t,onUpdate:n,onTeams:r,onClose:i,onDrop:a,reportId:o=null}){if(s())return;let c=1e3,u=async(e,t,a)=>{if(a.throwIfAborted(),e===`close`)return await i(),!1;if(e===`triage`||e===`teams`){let i=null;try{let e=JSON.parse(t);typeof e?.revision==`string`&&(i=e.revision)}catch{}if(await(e===`teams`?r?.(a,i):n(a,i))===!1)throw Error(`Team refresh failed`);a.throwIfAborted(),c=1e3}return!0};for(;!t.aborted;){let n=new AbortController,r=()=>n.abort();t.addEventListener(`abort`,r,{once:!0});let s,d,ee=()=>{clearTimeout(d),d=setTimeout(r,45e3)};try{ee();let r=o===null?``:`?reportId=${encodeURIComponent(o)}`,a=await l(e?`/api/teams/${encodeURIComponent(e)}/feed${r}`:`/api/teams/feed`,{credentials:`same-origin`,headers:{accept:`text/event-stream`},signal:n.signal});if([401,403,404].includes(a.status)){await a.body?.cancel(),t.aborted||await i();return}if(!a.ok||!a.headers.get(`content-type`)?.startsWith(`text/event-stream`))throw await a.body?.cancel(),Error(`Team feed unavailable`);if(s=a.body.getReader(),await Ho(s,t,ee,(e,t)=>u(e,t,n.signal)))return}catch{}finally{clearTimeout(d),r(),await s?.cancel().catch(()=>{}),t.removeEventListener(`abort`,r),a?.()}await Bo(c,t),c=Math.min(c*2,3e4)}}async function Ho(e,t,n,r){let i=new TextDecoder,a=``;for(;!t.aborted;){let{done:o,value:s}=await e.read();if(o)return!1;if(n(),a=(a+i.decode(s,{stream:!0})).replaceAll(`\r
31
31
  `,`
32
32
  `),a.length>16384)throw Error(`Team feed frame too large`);let c;for(;(c=a.indexOf(`