nemar-cli 0.10.35-dev.4536 → 0.10.36-PR2210.b6d71fb
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/git-annex-remote-nemar.js +18 -18
- package/dist/index.js +26 -45
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -99,18 +99,18 @@ ${t}`,JXe,YXe,XXe=(e,t,n)=>{let r=n===""?"":`with ${n.trim()}() `,o=KXe.bind(nul
|
|
|
99
99
|
`)}var fM=!1;var{spawn:J0t}=globalThis.Bun;function mp(e,t=[]){let n=e.replace(Y0t,'("$1","<redacted>")');for(let r of t)if(r.length>=X0t)n=n.split(r).join("<redacted>");return n}function VR(e){let t=["AWS_SESSION_TOKEN","AWS_SECRET_ACCESS_KEY","AWS_ACCESS_KEY_ID"],n=new Set;for(let r of[process.env,e??{}])for(let o of t){let s=r[o];if(typeof s==="string"&&s.length>0)n.add(s)}return[...n]}async function yge(e,t){let n=e.getReader(),r=new TextDecoder,o="";while(!0){let{done:s,value:i}=await n.read();if(s)break;if(i.byteLength===0)continue;t(),o+=r.decode(i,{stream:!0})}return o+r.decode()}async function A(e,t={}){let n={...process.env,GIT_TERMINAL_PROMPT:"0",...t.env};for(let y of t.unsetEnv??[])delete n[y];let r=J0t({cmd:e,cwd:t.cwd,...t.stdin===void 0?{}:{stdin:new TextEncoder().encode(t.stdin)},stdout:"pipe",stderr:"pipe",env:n}),o=!1,s,i,a=performance.now(),c=()=>{if(i!==void 0)clearTimeout(i),i=void 0},l=()=>{if(!t.onInactivityWarning)return;c(),i=setTimeout(()=>{i=void 0;try{t.onInactivityWarning?.(performance.now()-a)}catch{console.error("Could not display subprocess inactivity warning; the child result is unaffected.")}},t.inactivityWarningAfterMs??Q0t)};if(l(),t.timeout)s=setTimeout(()=>{o=!0,c(),r.kill()},t.timeout);let d=Bg()?[...VR(n),...t.redact??[]]:[];if(Bg()){let y=t.cwd?` (cwd=${t.cwd})`:"";qd(u.dim(mp(`$ ${e.join(" ")}${y}`,d)))}let f=()=>{a=performance.now(),l()},p,m,h,g=r.exited.then((y)=>(c(),y));try{[p,m,h]=await Promise.all([yge(r.stdout,f),yge(r.stderr,f),g])}finally{if(c(),s)clearTimeout(s)}if(Bg()){if(t.sensitiveOutput)qd(u.dim("[sensitive subprocess output suppressed]"));else{if(p.trim())qd(u.dim(mp(p.trimEnd(),d)));if(m.trim())qd(u.yellow(mp(m.trimEnd(),d)))}qd(u.dim(`(exit ${h})`))}if(o)return{stdout:p,stderr:m||`Command timed out after ${Math.round(t.timeout/1000)}s`,exitCode:h??1,timedOut:!0};return{stdout:p,stderr:m,exitCode:h,timedOut:!1}}var Y0t,X0t=8,Q0t=120000;var zt=H(()=>{We();Y0t=/\(\s*"((?:x-amz-)[^"]*|authorization|proxy-authorization)"\s*,\s*"[^"]*"\s*\)/gi});function ewt(){if(process.platform==="darwin")return"macos";if(process.platform==="win32")return"windows";return"linux"}function wge(e,t=ewt()){return e.installInstructions[t]}function twt(e){let t=e.match(/(\d+\.\d+(?:\.\d+)?)/);return t?t[1]:void 0}function rwt(){let e=Number(process.env.TEST_PROBE_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:nwt}async function _ge(e){try{let{exitCode:t,stdout:n,timedOut:r}=await A(e.cmd,{timeout:rwt()});if(r)return{available:!1,timedOut:!0};if(t!==0)return{available:!1};return{available:!0,version:twt(n)}}catch(t){let n=t instanceof Error?t.message:String(t);if(!n.includes("ENOENT")&&!n.includes("not found"))console.error(` Warning: ${e.name} check failed unexpectedly: ${n}`);return{available:!1}}}async function jw(){let e=Object.entries(bge);return Promise.all(e.map(async([t,n])=>{let{available:r,version:o,timedOut:s}=await _ge(n);return{key:t,name:n.name,purpose:n.purpose,required:n.required,available:r,version:o,timedOut:s,installInstruction:wge(n)}}))}async function xge(){let t=(await jw()).filter((n)=>n.required&&!n.available);if(t.length===0)return[];console.warn(`
|
|
100
100
|
Heads up: some tools NEMAR needs for uploading/validating aren't installed yet:`);for(let n of t)console.warn(` - ${n.name} (${n.purpose})`),console.warn(` Install: ${n.installInstruction}`);return console.warn("Run `nemar doctor` anytime to re-check. You can finish signup without them.\n"),t}async function hp(e){let n=Z0t[e].map((i)=>bge[i]).filter(Boolean),r=await Promise.all(n.map(async(i)=>{let a=await _ge(i);return{check:i,available:a.available,timedOut:a.timedOut}}));for(let i of r)if(i.timedOut&&i.check.required)console.warn(`Warning: ${i.check.name} did not respond to a version check in time; continuing anyway.`);let o=r.filter((i)=>!i.available&&!i.timedOut&&i.check.required).map((i)=>({tool:i.check.name,installInstruction:wge(i.check)}));if(o.length===0)return;let s=[`
|
|
101
101
|
Missing required tools:`];for(let i of o)s.push(` ${i.tool} not installed`),s.push(` Install: ${i.installInstruction}`);throw Error(s.join(`
|
|
102
|
-
`))}var bge,Z0t,nwt=4000;var Lw=H(()=>{zt();bge={git:{name:"git",purpose:"version control for dataset metadata",cmd:["git","--version"],required:!0,installInstructions:{macos:"brew install git (or install Xcode Command Line Tools)",linux:"sudo apt-get install git OR sudo dnf install git",windows:"winget install Git.Git (or https://git-scm.com/download/win)"}},"git-annex":{name:"git-annex",purpose:"large-file data transfer (upload/download)",cmd:["git-annex","version"],required:!0,installInstructions:{macos:"brew install git-annex",linux:"sudo apt-get install git-annex OR sudo dnf install git-annex",windows:"Download the installer from https://git-annex.branchable.com/install/Windows/"}},gh:{name:"GitHub CLI (gh)",purpose:"GitHub authentication + repository operations",cmd:["gh","--version"],required:!0,installInstructions:{macos:"brew install gh",linux:"See https://cli.github.com/manual/installation",windows:"winget install GitHub.cli (or: scoop install gh)"}},aws:{name:"AWS CLI",purpose:"S3 data upload/download",cmd:["aws","--version"],required:!0,installInstructions:{macos:"brew install awscli",linux:"pip install awscli OR sudo snap install aws-cli --classic",windows:"winget install Amazon.AWSCLI (or the MSI from https://aws.amazon.com/cli/)"}},deno:{name:"Deno",purpose:"BIDS validation",cmd:["deno","--version"],required:!0,installInstructions:{macos:"brew install deno (or: curl -fsSL https://deno.land/install.sh | sh)",linux:"curl -fsSL https://deno.land/install.sh | sh",windows:"winget install DenoLand.Deno (or: irm https://deno.land/install.ps1 | iex)"}}},Z0t={upload:["git-annex","gh","aws","deno"],download:["gh"],clone:["git","gh"],push:["git-annex","gh"],publish:["gh","aws"],update:["git","gh"],release:["git","gh"]}});var Ege;var vge=H(()=>{Ege={name:"nemar-cli",packageManager:"bun@1.4.3",version:"0.10.
|
|
102
|
+
`))}var bge,Z0t,nwt=4000;var Lw=H(()=>{zt();bge={git:{name:"git",purpose:"version control for dataset metadata",cmd:["git","--version"],required:!0,installInstructions:{macos:"brew install git (or install Xcode Command Line Tools)",linux:"sudo apt-get install git OR sudo dnf install git",windows:"winget install Git.Git (or https://git-scm.com/download/win)"}},"git-annex":{name:"git-annex",purpose:"large-file data transfer (upload/download)",cmd:["git-annex","version"],required:!0,installInstructions:{macos:"brew install git-annex",linux:"sudo apt-get install git-annex OR sudo dnf install git-annex",windows:"Download the installer from https://git-annex.branchable.com/install/Windows/"}},gh:{name:"GitHub CLI (gh)",purpose:"GitHub authentication + repository operations",cmd:["gh","--version"],required:!0,installInstructions:{macos:"brew install gh",linux:"See https://cli.github.com/manual/installation",windows:"winget install GitHub.cli (or: scoop install gh)"}},aws:{name:"AWS CLI",purpose:"S3 data upload/download",cmd:["aws","--version"],required:!0,installInstructions:{macos:"brew install awscli",linux:"pip install awscli OR sudo snap install aws-cli --classic",windows:"winget install Amazon.AWSCLI (or the MSI from https://aws.amazon.com/cli/)"}},deno:{name:"Deno",purpose:"BIDS validation",cmd:["deno","--version"],required:!0,installInstructions:{macos:"brew install deno (or: curl -fsSL https://deno.land/install.sh | sh)",linux:"curl -fsSL https://deno.land/install.sh | sh",windows:"winget install DenoLand.Deno (or: irm https://deno.land/install.ps1 | iex)"}}},Z0t={upload:["git-annex","gh","aws","deno"],download:["gh"],clone:["git","gh"],push:["git-annex","gh"],publish:["gh","aws"],update:["git","gh"],release:["git","gh"]}});var Ege;var vge=H(()=>{Ege={name:"nemar-cli",packageManager:"bun@1.4.3",version:"0.10.36-PR2210.b6d71fb",description:"CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",type:"module",main:"dist/index.js",bin:{nemar:"dist/index.js","git-annex-remote-nemar":"dist/git-annex-remote-nemar.js"},scripts:{dev:"bun run src/index.ts",build:"bun build src/index.ts src/git-annex-remote-nemar.ts --outdir dist --target bun --minify && sed '1s|#!/usr/bin/env node|#!/usr/bin/env bun|' dist/index.js > dist/index.js.tmp && mv dist/index.js.tmp dist/index.js",test:"bun test",lint:"biome check src/","lint:scrub":"biome check scripts/scrub shared/identifier-scrub.ts test/scrub","test:scrub":"bun test --preload ./test/scrub/helpers/temp-dirs-preload.ts --path-ignore-patterns='__run_every_scrub_suite__' test/scrub test/identifier-scan.test.ts test/identifier-scrub.test.ts test/identifier-dates.test.ts test/identifier-fleet.test.ts","migrations:d1-check":"bun run scripts/d1-migration-check.ts","zarr:geometry-check":"bun run backend/scripts/zarr-geometry-conformance.ts","lint:fix":"biome check --fix src/",format:"biome format --write src/",typecheck:"tsc --noEmit && tsc --noEmit -p backend","generate-openapi":"bun run scripts/generate-openapi.ts",prepublishOnly:"bun run build",prepare:"husky",postinstall:"bun scripts/postinstall-check.mjs",deploy:"wrangler deploy",preview:"wrangler dev"},keywords:["nemar","bids","neuroimaging","eeg","emg","datalad","cli"],author:"NEMAR Team",license:"CC-BY-NC-ND-4.0",repository:{type:"git",url:"git+https://github.com/nemarOrg/nemar-cli.git"},bugs:{url:"https://github.com/nemarOrg/nemar-cli/issues"},homepage:"https://docs.nemar.org",engines:{bun:">=1.0.0"},files:["dist","scripts/postinstall-check.mjs","scripts/recover-datasets.json","scripts/withdrawn-datasets.json","README.md","LICENSE"],dependencies:{chalk:"^5.3.0",commander:"^12.1.0",conf:"^13.0.1",inquirer:"^9.2.15",ora:"^8.0.1",semver:"^7.8.5",zod:"^3.23.8"},"lint-staged":{"src/**/*.{ts,tsx}":["biome check --fix"],"backend/src/**/*.{ts,tsx}":["biome check --fix"]},trustedDependencies:["@biomejs/biome"],devDependencies:{"@anthropic-ai/sdk":"^0.132.1","@asteasolutions/zod-to-openapi":"^7.3.4","@biomejs/biome":"1.9.4","@types/bun":"latest","@types/inquirer":"^9.0.7","@types/semver":"^7.8.0",ajv:"^8.20.0","ajv-formats":"^3.0.1",husky:"^9.1.7",jose:"6.2.12","lint-staged":"^16.3.2",oauth4webapi:"3.8.8","openid-client":"6.8.9",typescript:"^5.5.4",wrangler:"^4.70.0",yaml:"^2.8.4"}}});var Ls;var gp=H(()=>{vge();Ls=Ege.version});import{mkdirSync as swt,readdirSync as iwt,unlinkSync as awt,writeFileSync as cwt}from"fs";import{join as pM}from"path";function Cge(){Hg=!0}function Nl(){return Hg}function Age(e,t=process.env){return e.includes("--debug")||t.NEMAR_DEBUG==="1"}function Uw(e){Dge=e,Tn(`Step: ${e}`)}function Wo(){Rge=!0}function Oge(){return Rge}function de(){if($ge)return;hM=!0}function Bw(){hM=!1,$ge=!0}function Tge(){return hM}function Tn(e){if(Hg)process.stderr.write(`[debug] ${e}
|
|
103
103
|
`)}function fwt(e){let t={};for(let[n,r]of Object.entries(e))t[n]=dwt.has(n.toLowerCase())?"[REDACTED]":r;return t}function Ige(e){let t=e.indexOf("@");if(t<=0)return"***";return`${e[0]}***${e.slice(t)}`}function mM(e,t,n=0){if(n>mwt)return"[REDACTED: depth]";if(Array.isArray(t))return t.map((r)=>mM(e,r,n+1));if(t&&typeof t==="object"){let r={};for(let[o,s]of Object.entries(t))r[o]=mM(o,s,n+1);return r}if(typeof t==="string"){if(pwt.test(e))return"[REDACTED]";return t.replace(Pge,Ige)}return t}function gM(e){return e.replace(hwt,"Bearer [REDACTED]").replace(gwt,"[REDACTED_AWS_KEY]").replace(ywt,"$1[REDACTED]").replace(bwt,"$1$2=[REDACTED]").replace(Pge,Ige)}function wwt(e){return gM(e)}function Sge(e,t=uwt){if(e===void 0)return;let n=e;try{let r=JSON.parse(e);n=JSON.stringify(mM("",r))}catch{}if(n=gM(n),Buffer.byteLength(n,"utf8")>t)n=`${Buffer.from(n,"utf8").subarray(0,t).toString("utf8")}... [truncated]`;return n}function JR(e){if(!Hg)return;let t=wwt(e.url);try{let n={...e,url:t,requestHeaders:e.requestHeaders?fwt(e.requestHeaders):void 0,requestBody:Sge(e.requestBody),responseBody:Sge(e.responseBody)};KR.push(n),Tn(`${e.method} ${t} -> ${e.status??"ERROR"} (${e.durationMs}ms)`)}catch(n){let r=W(n);KR.push({method:e.method,url:t,status:e.status,durationMs:e.durationMs,note:`redaction failed: ${r}`}),Tn(`redaction failed for ${e.method} ${t}: ${r}`)}}async function _wt(){let e=[];try{let t=process.versions.bun?`Bun ${process.versions.bun}`:`Node ${process.version}`;e.push(`CLI version: ${Ls}`),e.push(`OS/Arch: ${process.platform}/${process.arch}`),e.push(`Runtime: ${t}`)}catch(t){e.push(`(could not read CLI/OS/runtime info: ${W(t)})`)}e.push(""),e.push("Active account:");try{let t=Yt();if(t.apiKey){if(t.username)e.push(` Username: ${t.username}`);if(e.push(` API URL: ${t.apiUrl}`),t.role)e.push(` Role: ${t.role}`);e.push(` Sandbox completed: ${!!t.sandboxCompleted}`)}else e.push(" (not authenticated)")}catch(t){e.push(` (could not read account config: ${W(t)})`)}e.push(""),e.push("External tools:");try{let t=await jw();for(let n of t){let r=n.available?n.version??"installed":n.timedOut?"(timed out)":"not installed";e.push(` ${n.name}: ${r}`)}}catch(t){e.push(` (could not probe external tools: ${W(t)})`)}return e}async function yM(){return(await _wt()).join(`
|
|
104
104
|
`)}async function Nge(){if(!Hg||WR!==void 0)return;try{WR=await yM()}catch(e){let t=W(e);WR=`(could not build environment report: ${t})`,Tn(`environment snapshot failed: ${t}`)}}function Fge(e){if(kge.has(e))return{flag:e};for(let t of kge){if(!e.startsWith(t)||e.length<=t.length)continue;if(t.length===2)return{flag:t,kind:"short-attached"};if(e[t.length]==="=")return{flag:t,kind:"long-eq"}}return null}function xwt(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n],o=Fge(r);if(!o){t.push(r);continue}if(o.kind==="long-eq")t.push(`${o.flag}=[REDACTED]`);else if(o.kind==="short-attached")t.push(`${o.flag}[REDACTED]`);else if(t.push(r),n+1<e.length)t.push("[REDACTED]"),n++}return t}function vwt(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n],o=Fge(r);if(!o){t.push(r);continue}if(!o.kind&&n+1<e.length)n++}return t}function Ewt(e){let t=[];for(let r of vwt(e)){if(r.startsWith("-"))continue;if(t.push(r),t.length===2)break}return(t.length>0?t.join("-"):"nemar").replace(/[^a-zA-Z0-9_-]/g,"_")}function Swt(e,t){let n=[];if(n.push("NEMAR CLI Debug Log"),n.push(`Generated: ${new Date().toISOString()}`),n.push(`Command: nemar ${gM(xwt(e).join(" "))}`),n.push(""),n.push(WR??"(environment snapshot unavailable)"),n.push(""),n.push("HTTP requests:"),KR.length===0)n.push(" (none)");else KR.forEach((r,o)=>{if(n.push(` [${o+1}] ${r.method} ${r.url} -> ${r.status??"ERROR"} (${r.durationMs}ms)`),r.error)n.push(` Error: ${r.error}`);if(r.note)n.push(` Note: ${r.note}`);if(r.requestHeaders)n.push(` Request headers: ${JSON.stringify(r.requestHeaders)}`);if(r.requestBody)n.push(` Request body: ${r.requestBody}`);if(r.responseBody)n.push(` Response body: ${r.responseBody}`)});return n.push(""),n.push(`Failing step: ${Dge??"(none recorded)"}`),n.push(`Exit code: ${t}`),`${n.join(`
|
|
105
105
|
`)}
|
|
106
106
|
`}function kwt(e,t){let n;try{n=iwt(e).filter((o)=>o.startsWith("nemar-")&&o.endsWith(".log"))}catch(o){if(o.code!=="ENOENT")Tn(`could not list ${e} for log rotation: ${W(o)}`);return}n.sort();let r=n.length-t;for(let o=0;o<r;o++)try{awt(pM(e,n[o]))}catch(s){if(s.code!=="ENOENT")Tn(`could not remove old log ${n[o]}: ${W(s)}`)}}function Mge(){return qw}function jge(e,t){if(!Hg)return null;let n=pM(rr(),"logs");try{swt(n,{recursive:!0})}catch(i){return qw=W(i),Tn(`could not create log directory ${n}: ${qw}`),null}let o=`nemar-${new Date().toISOString().replace(/[:.]/g,"-")}-${Ewt(e)}.log`,s=pM(n,o);try{cwt(s,Swt(e,t),"utf8")}catch(i){return qw=W(i),Tn(`could not write log file ${s}: ${qw}`),null}return kwt(n,lwt),s}var lwt=10,uwt=2048,Hg=!1,Rge=!1,hM=!1,$ge=!1,Dge,WR,KR,dwt,pwt,Pge,mwt=32,hwt,gwt,ywt,bwt,kge,qw;var wn=H(()=>{Ve();Or();Lw();gp();KR=[];dwt=new Set(["authorization","cookie","set-cookie","x-api-key","x-approval-dispatch-token"]);pwt=/^(api[_-]?key|apikey|password|token|secret|access[_-]?key(_id)?|secret[_-]?access[_-]?key|session|session[_-]?token|authorization|ssh[_-]?key|private[_-]?key|device[_-]?code|dispatch[_-]?token|client[_-]?secret)$/i,Pge=/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g;hwt=/Bearer\s+[A-Za-z0-9\-._~+/=]+/gi,gwt=/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g,ywt=/((?:aws_)?secret_access_key["']?\s*[:=]\s*["']?)[A-Za-z0-9/+=]{20,}/gi,bwt=/([?&])(X-Amz-Signature|X-Amz-Security-Token|X-Amz-Credential|Signature|AWSAccessKeyId)=[^&\s"']+/gi;kge=new Set(["-k","--key","--password","--api-key"])});import{chmodSync as Rwt,copyFileSync as $wt,existsSync as bM,mkdirSync as Dwt,statSync as Cwt}from"fs";import{homedir as YR}from"os";import{join as Gg}from"path";function Owt(e){let t=e.trim().replace(/\/+$/,"");try{let n=new URL(t);return n.protocol=n.protocol.toLowerCase(),n.host=n.host.toLowerCase(),n.toString().replace(/\/+$/,"")}catch{return console.error(`[nemar] could not parse stored apiUrl ${JSON.stringify(e)}; leaving as-is`),t}}function rr(){return process.env.NEMAR_CONFIG_DIR||Gg(YR(),".config","nemar")}function Pwt(e){if(process.env.NEMAR_CONFIG_DIR)return;let t=Gg(e,"config.json");if(bM(t))return;let n=[];if(process.platform==="darwin")n.push(Gg(YR(),"Library","Preferences","nemar-nodejs","config.json"));if(process.platform==="win32"){let r=process.env.APPDATA||Gg(YR(),"AppData","Roaming");n.push(Gg(r,"nemar-nodejs","config.json"))}n.push(Gg(YR(),".config","nemar-nodejs","config.json"));for(let r of n)if(bM(r))try{Dwt(e,{recursive:!0}),$wt(r,t),console.error(`[nemar] Config migrated from ${r} to ${t}
|
|
107
107
|
[nemar] You can safely remove the old file.`);return}catch(o){console.error(`[nemar] Failed to migrate config from ${r}:`,o,`
|
|
108
|
-
[nemar] You can manually copy ${r} to ${t}`)}}function vi(){let e=rr();if(Hw&&Lge===e)return Hw;if(Pwt(e),Hw=new zR({projectName:"nemar",configFileMode:wM,schema:{activeAccount:{type:"string"},accounts:{type:"object"},apiKey:{type:"string"},apiUrl:{type:"string"},username:{type:"string"},email:{type:"string"},githubUsername:{type:"string"},sandboxCompleted:{type:"boolean"},sandboxDatasetId:{type:"string"}},cwd:e}),Lge=e,!qge.has(e))qge.add(e),Iwt(Hw.path),Fwt(),Mwt();return Hw}function Iwt(e){if(process.platform==="win32")return;if(!bM(e))return;try{if((Cwt(e).mode&511)!==wM)Rwt(e,wM)}catch(t){console.error(`[nemar] could not secure config file permissions for ${e}:`,t)}}function Fwt(){let e=vi(),t=e.get("accounts");if(t&&Object.keys(t).length>0)return;let n=e.get("apiKey"),r=e.get("username");if(!n&&!r)return;try{let o=r||"default",s={};for(let i of Nwt){let a=e.get(i);if(a!==void 0)s[i]=a}e.store={activeAccount:o,accounts:{[o]:s}}}catch(o){console.error("Config migration failed (legacy config preserved):",o)}}function Mwt(){let e=vi(),t=e.store,n=t.accounts,r=!1;if(n)for(let[s,i]of Object.entries(n)){let a=i?.apiUrl;if(!a)continue;if(Awt.has(Owt(a)))n[s]={...i,apiUrl:zg},console.error(`[nemar] migrated stored apiUrl for account "${s}": ${a} -> ${zg}`),r=!0}let o=t.apiUrl;if(n&&Object.keys(n).length>0&&o!==void 0){let{apiUrl:s,...i}=t;try{e.store=i,console.error(`[nemar] removed stale top-level apiUrl from config (was: ${o})`),r=!1}catch(a){console.error("API URL cleanup failed (config file unchanged):",a)}}if(r)try{e.store={...e.store,accounts:n}}catch(s){console.error("API URL migration failed (config file unchanged):",s)}}function Gw(){return vi().get("activeAccount")}function Ud(){return vi().get("accounts")||{}}function Yt(){let e={apiUrl:zg},t=Gw();if(!t)return e;return Ud()[t]||e}function jn(e,t){let n=vi(),r=n.get("activeAccount")||"default",o=n.get("accounts")||{};if(!o[r])o[r]={apiUrl:zg};o[r][e]=t,n.store={...n.store,accounts:o,activeAccount:r}}function zw(e){let t=Gw();if(!t)return;let n=Ud();if(n[t])delete n[t][e],vi().set("accounts",n)}function Uge(){let e=vi(),t=Gw();if(!t){e.clear();return}let n=Ud();delete n[t];let r=Object.keys(n);if(r.length>0)e.store={...e.store,accounts:n,activeAccount:r[0]};else e.clear()}function Bge(){vi().clear()}function Ye(){return!!Yt().apiKey}function _M(){return vi().path}function Vw(){let e=Ud(),t=Gw();return Object.entries(e).map(([n,r])=>({key:n,username:r.username,email:r.email,githubUsername:r.githubUsername,active:n===t,keySource:r.keySource}))}function Hge(e){return e.username?.trim()||e.email}function jwt(e){let t=e.trim().toLowerCase();if(!t)return;let n=Object.entries(Ud()).filter(([,r])=>r.email&&r.email.toLowerCase()===t).map(([r])=>r);if(n.length>1){Tn(`findAccountKeyByEmail: ${n.length} accounts share email ${t}: ${n.join(", ")}`);return}return n[0]}function Gge(e,t){let n=vi(),r=Ud(),o;if(r[e])o=e;else if(t.email)o=jwt(t.email);let s=o?r[o]:void 0,i={...s??{apiUrl:zg},...t};if(o&&o!==e)delete r[o];return r[e]=i,n.store={...n.store,accounts:r,activeAccount:e},{key:e,previous:s}}function zge(e){let t=e.trim();if(!t)return"unchanged";let n=vi(),r=Gw();if(!r||r===t)return"unchanged";let o=Ud(),s=o[r];if(!s)return"unchanged";if(o[t])return"key_taken";return delete o[r],o[t]={...s,username:t},n.store={...n.store,accounts:o,activeAccount:t},"renamed"}function xM(e){let t=vi(),n=Ud();if(n[e])return t.store={...t.store,activeAccount:e},n[e];for(let[r,o]of Object.entries(n))if(o.githubUsername===e)return t.store={...t.store,activeAccount:r},o;return null}var zg="https://
|
|
108
|
+
[nemar] You can manually copy ${r} to ${t}`)}}function vi(){let e=rr();if(Hw&&Lge===e)return Hw;if(Pwt(e),Hw=new zR({projectName:"nemar",configFileMode:wM,schema:{activeAccount:{type:"string"},accounts:{type:"object"},apiKey:{type:"string"},apiUrl:{type:"string"},username:{type:"string"},email:{type:"string"},githubUsername:{type:"string"},sandboxCompleted:{type:"boolean"},sandboxDatasetId:{type:"string"}},cwd:e}),Lge=e,!qge.has(e))qge.add(e),Iwt(Hw.path),Fwt(),Mwt();return Hw}function Iwt(e){if(process.platform==="win32")return;if(!bM(e))return;try{if((Cwt(e).mode&511)!==wM)Rwt(e,wM)}catch(t){console.error(`[nemar] could not secure config file permissions for ${e}:`,t)}}function Fwt(){let e=vi(),t=e.get("accounts");if(t&&Object.keys(t).length>0)return;let n=e.get("apiKey"),r=e.get("username");if(!n&&!r)return;try{let o=r||"default",s={};for(let i of Nwt){let a=e.get(i);if(a!==void 0)s[i]=a}e.store={activeAccount:o,accounts:{[o]:s}}}catch(o){console.error("Config migration failed (legacy config preserved):",o)}}function Mwt(){let e=vi(),t=e.store,n=t.accounts,r=!1;if(n)for(let[s,i]of Object.entries(n)){let a=i?.apiUrl;if(!a)continue;if(Awt.has(Owt(a)))n[s]={...i,apiUrl:zg},console.error(`[nemar] migrated stored apiUrl for account "${s}": ${a} -> ${zg}`),r=!0}let o=t.apiUrl;if(n&&Object.keys(n).length>0&&o!==void 0){let{apiUrl:s,...i}=t;try{e.store=i,console.error(`[nemar] removed stale top-level apiUrl from config (was: ${o})`),r=!1}catch(a){console.error("API URL cleanup failed (config file unchanged):",a)}}if(r)try{e.store={...e.store,accounts:n}}catch(s){console.error("API URL migration failed (config file unchanged):",s)}}function Gw(){return vi().get("activeAccount")}function Ud(){return vi().get("accounts")||{}}function Yt(){let e={apiUrl:zg},t=Gw();if(!t)return e;return Ud()[t]||e}function jn(e,t){let n=vi(),r=n.get("activeAccount")||"default",o=n.get("accounts")||{};if(!o[r])o[r]={apiUrl:zg};o[r][e]=t,n.store={...n.store,accounts:o,activeAccount:r}}function zw(e){let t=Gw();if(!t)return;let n=Ud();if(n[t])delete n[t][e],vi().set("accounts",n)}function Uge(){let e=vi(),t=Gw();if(!t){e.clear();return}let n=Ud();delete n[t];let r=Object.keys(n);if(r.length>0)e.store={...e.store,accounts:n,activeAccount:r[0]};else e.clear()}function Bge(){vi().clear()}function Ye(){return!!Yt().apiKey}function _M(){return vi().path}function Vw(){let e=Ud(),t=Gw();return Object.entries(e).map(([n,r])=>({key:n,username:r.username,email:r.email,githubUsername:r.githubUsername,active:n===t,keySource:r.keySource}))}function Hge(e){return e.username?.trim()||e.email}function jwt(e){let t=e.trim().toLowerCase();if(!t)return;let n=Object.entries(Ud()).filter(([,r])=>r.email&&r.email.toLowerCase()===t).map(([r])=>r);if(n.length>1){Tn(`findAccountKeyByEmail: ${n.length} accounts share email ${t}: ${n.join(", ")}`);return}return n[0]}function Gge(e,t){let n=vi(),r=Ud(),o;if(r[e])o=e;else if(t.email)o=jwt(t.email);let s=o?r[o]:void 0,i={...s??{apiUrl:zg},...t};if(o&&o!==e)delete r[o];return r[e]=i,n.store={...n.store,accounts:r,activeAccount:e},{key:e,previous:s}}function zge(e){let t=e.trim();if(!t)return"unchanged";let n=vi(),r=Gw();if(!r||r===t)return"unchanged";let o=Ud(),s=o[r];if(!s)return"unchanged";if(o[t])return"key_taken";return delete o[r],o[t]={...s,username:t},n.store={...n.store,accounts:o,activeAccount:t},"renamed"}function xM(e){let t=vi(),n=Ud();if(n[e])return t.store={...t.store,activeAccount:e},n[e];for(let[r,o]of Object.entries(n))if(o.githubUsername===e)return t.store={...t.store,activeAccount:r},o;return null}var zg="https://api.nemar.org",wM=384,Awt,Twt,hnn,Hw=null,Lge=null,qge,Nwt;var Or=H(()=>{hge();dr();Ih();wn();Awt=new Set(["https://api.osc.earth/nemar","https://nemar-api.neuromechanist.workers.dev","https://nemar-api-dev.shirazi-10f.workers.dev"]);Twt=N({field:w(),blocks:X(w()).optional(),set_on:X(w()).optional()}).passthrough(),hnn=N({apiKey:w().optional(),apiUrl:w().url().default(zg),username:w().optional(),email:w().email().optional(),githubUsername:w().optional(),sandboxCompleted:re().optional(),sandboxDatasetId:w().optional(),dismissedNoticeIds:X(D()).optional(),serviceAccess:re().optional(),profileGaps:X(Twt).optional(),orcidVerified:re().optional(),role:w().optional(),accountKind:Qf.optional(),pendingEmailChange:w().email().optional()});qge=new Set;Nwt=["apiKey","apiUrl","username","email","githubUsername","sandboxCompleted","sandboxDatasetId","dismissedNoticeIds"]});function XR(e){if(Vge)return;Vge=!0;let t=u.yellow("\u2500".repeat(60)),n=u.yellow.bold("[MAINTENANCE]"),r=u.dim(`mode: ${e.mode}`),o=e.eta?`
|
|
109
109
|
${u.dim(`eta: ${e.eta}`)}`:"";process.stderr.write(`${t}
|
|
110
110
|
${n} ${e.message}
|
|
111
111
|
${r}${o}
|
|
112
112
|
${t}
|
|
113
|
-
`)}var Vge=!1;var vM=H(()=>{We()});function Hr(){if(process.env.TEST_API_URL)return process.env.TEST_API_URL;if(yp)return EM;return Yt().apiUrl||EM}async function F(e,t={},n=!1,r){let o=`${Hr()}${e}`,s={"Content-Type":"application/json","X-CLI-Version":Ls,...t.headers};if(n){let p=Yt();if(!p.apiKey&&n===!0)throw new U(401,"Not authenticated. Run 'nemar auth login' first.");if(p.apiKey)s.Authorization=`Bearer ${p.apiKey}`}let i=t.method||"GET",a=typeof t.body==="string"?t.body:void 0,c=Date.now(),l;try{l=await fetch(o,{...t,headers:s})}catch(p){if(Nl())JR({method:i,url:o,status:null,durationMs:Date.now()-c,requestHeaders:s,requestBody:a,error:p instanceof Error?p.message:String(p)});throw new U(0,`Network error: Could not connect to ${Hr()}`,{originalError:p instanceof Error?p.message:String(p)})}let d;try{d=await l.text()}catch(p){if(Nl())JR({method:i,url:o,status:l.status,durationMs:Date.now()-c,requestHeaders:s,requestBody:a,error:p instanceof Error?p.message:String(p)});throw new U(0,"Failed to read response body",{httpStatus:l.status,originalError:p instanceof Error?p.message:String(p)})}if(Nl())JR({method:i,url:o,status:l.status,durationMs:Date.now()-c,requestHeaders:s,requestBody:a,responseBody:d});let f;try{f=JSON.parse(d)}catch{throw new U(l.status,`Invalid response from server (status ${l.status})`)}if(!l.ok){if(l.status===503&&(f.mode==="read-only"||f.mode==="full")){let V=typeof f.message==="string"?f.message:"NEMAR is in maintenance mode. Please retry shortly.",T=typeof f.eta==="string"?f.eta:null,L=new ed(f.mode,V,T,f.details);throw XR(L),L}let p=typeof f.block_reason==="string",m=Array.isArray(f.missing)?f.missing.filter((V)=>typeof V==="string"):void 0,h=typeof f.error==="string"&&(Ute.includes(f.error)||sne.includes(f.error)),g=typeof f.error==="string"&&(gS.options.includes(f.error)||une.includes(f.error)),y=typeof f.error==="string"&&Nte.includes(f.error),b=typeof f.error==="string"&&Bte.includes(f.error),x=typeof f.error==="string"&&tne.includes(f.error),v=typeof f.error==="string"&&ene.includes(f.error),S=typeof f.error==="string"&&nne.includes(f.error),O=p||v||S||h||g||y||b||x||m!==void 0&&typeof f.error==="string"&&qte.includes(f.error)?f.message||f.error:f.error||f.message;if(l.status===404&&f.error==="Not Found"&&typeof f.message==="string")O=`${f.message}. This NEMAR backend does not support this command yet.`;let I=new U(l.status,O||"Request failed",f.details,typeof f.step==="string"?f.step:void 0,p?f.block_reason:void 0,m);if(typeof f.error==="string")I.code=f.error;if(typeof f.reason==="string")I.reason=f.reason;throw I.rawBody=f,I}if(r){let p=r.safeParse(f);if(!p.success)throw new U(l.status,`Response for ${e} did not match the expected NEMAR contract`,{issues:p.error.issues});return p.data}return f}var EM="https://nemar-api-dev.sccn-org.workers.dev",yp;var wr=H(()=>{H0();wS();bI();Fh();Ih();Or();wn();vM();gp();Ve();yp=EM.includes("workers.dev")});async function Vg(e,t={}){return F(`/datasets/${e}/publish/request`,t.anonymous?{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({anonymous:!0})}:{method:"POST"},!0)}async function Wg(e){return F(`/datasets/${e}/publish/status`,{},!0)}async function Jge(e){return F(`/datasets/${e}/publish/resend`,{method:"POST"},!0)}async function Yge(e){return F(`/datasets/${e}/publish/withdraw`,{method:"POST"},!0)}async function bp(e={}){let{statuses:t,search:n}=typeof e==="string"?{statuses:e?[e]:[]}:e,r=await Wge(t,n),o=r;if(t!==void 0&&t.length>1&&r.requests.length===0){let s=[];for(let a of new Set(t))s.push(await Wge([a],n));let i=s.flatMap((a)=>a.requests).sort(Xge);o={...r,requests:i,count:i.length}}return n?Lwt(o,n):o}function Xge(e,t){return e.requested_at<t.requested_at?1:e.requested_at>t.requested_at?-1:0}async function Wge(e,t){let n=new URLSearchParams;if(e&&e.length>0)n.set("status",e.join(","));if(t)n.set("search",t);let r=n.size>0?`?${n}`:"";return F(`/admin/publish/requests${r}`,{},!0)}function Lwt(e,t){let n=e.requests.filter((s)=>Ire(t,[s.dataset_id,s.requested_by_username,s.dataset_name])),r=(s)=>Nre(s.dataset_id,t)?0:1,o=[...n].sort((s,i)=>r(s)-r(i)||Xge(s,i));return{...e,requests:o,count:o.length}}async function Kg(e,t,n){return F(`/admin/publish/${e}/deny`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:t,...n!==void 0?{request_id:n}:{}})},!0)}async function QR(e){return F(`/admin/publish/${e}/identifier-screen`,{method:"POST"},!0)}async function ZR(e){return F(`/admin/publish/${e}/review`,{},!0)}async function Qge(e){return F(`/admin/publish/${e}/review/start`,{method:"POST"},!0)}async function Zge(e,t){let n={message:t};return F(`/admin/publish/${e}/comment`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},!0)}function Jg(e){if(!(e instanceof U))return;let t=e.rawBody;if(typeof t!=="object"||t===null||Array.isArray(t))return;let n=t.code;return typeof n==="string"?n:void 0}function qwt(e,t=[]){if(e){let n=Ga.indexOf(e);if(n>=0)return n+1}return Math.min(t.length+1,Ga.length)}function Uwt(e){if(!(e instanceof U))return!1;if(e.statusCode===0)return!0;if(e.statusCode===429)return!0;if(e.statusCode>=500&&e.statusCode<600)return!0;if(e.statusCode===403&&/repository has been locked/i.test(e.message))return!0;return!1}function Bwt(){let e=process.env.NEMAR_APPROVE_RETRY_DELAY_MS;if(e===void 0||!/^\d+$/.test(e))return GS;let t=Number(e);return Number.isSafeInteger(t)&&t<=GS?t:GS}async function Yg(e,t=!1,n=!1,r=!1,o,s,i,a,c){let d=Bwt(),f,p,m=0,h=!1,g,y=t,b=[],x;function v(S,E,O,I){if(!s)return;s({step:S,stepIndex:qwt(S,E),stepTotal:Ga.length,s3LockLocked:O,s3LockTotal:I,s3LockResumed:S==="s3_lock"&&h?!0:void 0})}for(let S=1;S<=5;S++)try{let E,O=!0;do{if(E=await F(`/admin/publish/${e}/approve`,{method:"POST",headers:{"Content-Type":"application/json",...c?.dispatchToken?{[rne]:c.dispatchToken}:{}},body:JSON.stringify({resume:O?y:!0,sandbox:n,s3_lock_continuation_token:f,s3_lock_total:p,skip_ci_check:r,...i!==void 0?{acknowledge_identifier_screen:i}:{},...a!==void 0?{[Ore]:a}:{},...c?.requestId!==void 0?{request_id:c.requestId}:{}})},!0),O=!1,E.step_results)b.push(...E.step_results);if(E.s3_lock_total!==void 0)p=E.s3_lock_total;if(E.s3_lock_batch_count!==void 0)m+=E.s3_lock_batch_count;let I=E.step??E.step_results?.[E.step_results.length-1]?.step;if(I&&(I!==g||I==="s3_lock"))v(I,E.steps_completed??[],I==="s3_lock"?m:void 0,I==="s3_lock"?p:void 0),g=I;if(E.hasMore&&E.s3_lock_continuation_token!==void 0)f=E.s3_lock_continuation_token;else break}while(E.hasMore);if(b.length>0)E.step_results=Kge(b);return E}catch(E){if(x=E,S===5||!Uwt(E)){if(E instanceof U&&b.length>0)E.stepResults=Kge(b);throw E}let I=E;if(o?.({attempt:S,maxAttempts:5,delayMs:d,step:I.step,error:I.message}),await new Promise((V)=>setTimeout(V,d)),y=!0,f!==void 0)h=!0}throw x}function Kge(e){let t=new Map;for(let n of e)t.set(n.step,n);return Array.from(t.values())}var ta=H(()=>{HS();Fh();VS();wr();Ve()});function n$(e){if(e.service_access===void 0||e.service_access===null)return"unknown";return e.service_access?"upload":"browse"}async function PM(e,t,n,r,o={}){let s=new URLSearchParams;if(e)s.set("status",e);if(t)s.set("role",t);if(n)s.set("awaiting_approval","1");if(r)s.set("kind",r);if(o.search!==void 0)s.set("q",o.search);if(o.includeDeleted)s.set("include_deleted","true");let i=s.toString()?`?${s.toString()}`:"";return F(`/admin/users${i}`,{},!0,jte)}async function r$(e,t=!1){return F(`/admin/users/by-id/${e}${t?"?include_deleted=true":""}`,{},!0,zte)}async function lye(e,t){return F(`/admin/users/by-id/${e}`,{method:"PATCH",body:JSON.stringify(t)},!0,Vte)}async function uye(e){return F(`/admin/approve/${e}`,{method:"POST"},!0)}async function dye(e){return F(`/admin/approve/by-id/${e}`,{method:"POST"},!0)}async function fye(e){return F(`/admin/revoke/${e}`,{method:"POST"},!0)}async function pye(e){return F(`/admin/revoke/by-id/${e}`,{method:"POST"},!0)}async function mye(e){return F(`/admin/users/by-id/${e}/verify`,{method:"POST"},!0)}async function hye(e,t){return F(`/admin/users/${e}/role`,{method:"POST",body:JSON.stringify({role:t})},!0)}async function gye(e,t){return F(`/admin/users/${e}/kind`,{method:"POST",body:JSON.stringify({kind:t})},!0)}async function o$(e){return F(`/admin/users/${encodeURIComponent(e)}`,{},!0)}async function yye(e,t){return F(`/admin/users/${e}/keys`,{method:"POST",body:JSON.stringify({name:t})},!0,bS)}async function bye(e){return F(`/admin/users/${e}/keys`,{},!0,yS)}async function wye(e,t){return F(`/admin/users/${e}/keys/${t}`,{method:"DELETE"},!0)}async function _ye(e){return F(`/datasets/${e}/publish`,{method:"POST"},!0)}async function xye(e){return F(`/admin/datasets/${e}/ci`,{},!0)}async function Fl(e){return F(`/admin/datasets/${e}/ci`,{method:"POST"},!0)}async function IM(e){return F(`/admin/datasets/${e}/ci/validate`,{method:"POST"},!0)}async function NM(e){return F(`/admin/datasets/${e}/ci/sync`,{method:"POST"},!0)}async function vye(e,t){return F(`/admin/datasets/${e}/doi/concept`,{method:"POST",body:JSON.stringify(t)},!0)}async function Jw(e){return F(`/admin/datasets/${e}/doi`,{},!0)}async function FM(e,t){return F(`/admin/datasets/${e}/doi/update`,{method:"POST",body:JSON.stringify(t)},!0)}async function Eye(e,t){return F(`/admin/datasets/${e}/withdraw`,{method:"POST",body:JSON.stringify({reason:t.reason,dry_run:t.dryRun})},!0)}async function Sye(e,t){return F(`/admin/datasets/${e}/restore`,{method:"POST",body:JSON.stringify({dry_run:t.dryRun})},!0)}async function kye(e,t){return F(`/admin/datasets/${e}/unpublish`,{method:"POST",body:JSON.stringify({reason:t.reason,dry_run:t.dryRun})},!0)}async function Rye(e){return F(`/admin/datasets/${e}/reset`,{method:"POST"},!0)}async function $ye(e,t=!1){return F(`/admin/datasets/${e}`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({force:t})},!0)}async function Dye(e){return F("/admin/datasets/bulk-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dataset_ids:e})},!0)}async function Cye(e){return F("/admin/datasets/import",{method:"POST",body:JSON.stringify(e)},!0)}async function Aye(e){return F("/admin/datasets/exemplar",{method:"POST",body:JSON.stringify(e)},!0)}async function Oye(e){return F(`/admin/datasets/${e}/exemplar/remint-dois`,{method:"POST"},!0)}async function MM(e,t){let n=new URLSearchParams;if(e)n.set("status",e);if(t!==void 0)n.set("blocklisted",t?"1":"0");let r=n.toString();return F(`/admin/imports${r?`?${r}`:""}`,{},!0)}async function Tye(e){return F(`/admin/imports/${e}/rollback`,{method:"POST"},!0)}async function Pye(e){return F(`/admin/imports/${e}/retry`,{method:"POST"},!0)}async function jM(e){return F(`/admin/imports/${e}/verify`,{method:"POST"},!0)}async function Iye(e){return F("/admin/imports/dispatch-cooldown",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dataset_ids:e})},!0)}async function Zg(e,t){return F(`/admin/datasets/${e}/reindex`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})},!0)}async function Nye(e,t){return F("/admin/datasets/reindex/bulk",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filter:e,...t??{}})},!0)}async function Fye(e){let t=e?.limit??15;return F(`/admin/datasets/hed-sweep?limit=${encodeURIComponent(String(t))}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Mye(){return F("/admin/datasets/hed-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function jye(e){let t=e?.limit??50;return F(`/admin/datasets/recording-stats-sweep?limit=${encodeURIComponent(String(t))}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Lye(){return F("/admin/datasets/recording-stats-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function qye(e){let t=e?.limit??15;return F(`/admin/datasets/signal-defaults-sweep?limit=${encodeURIComponent(String(t))}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Uye(){return F("/admin/datasets/signal-defaults-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Bye(e){let t=e?.limit??15,n=new URLSearchParams({limit:String(t)});if(e?.olderThan!=null)n.set("older-than",String(e.olderThan));if(e?.before!=null)n.set("before",e.before);return F(`/admin/datasets/data-integrity-sweep?${n.toString()}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Hye(){return F("/admin/datasets/data-integrity-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Gye(e,t){let n=t?.write?"":"?dry_run=1";return F(`/admin/datasets/${e}/availability-report${n}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function zye(e){let t=e?.limit??30,n=new URLSearchParams({limit:String(t)});if(e?.missingOnly)n.set("missing-only","1");return F(`/admin/datasets/availability-report-sweep?${n.toString()}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Vye(){return F("/admin/datasets/availability-report-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Wye(e){let t=new URLSearchParams;if(e?.prefix)t.set("prefix",e.prefix);if(e?.visibility)t.set("visibility",e.visibility);if(e?.limit)t.set("limit",String(e.limit));let n=t.toString()?`?${t.toString()}`:"";return F(`/admin/fleet/drift${n}`,{},!0)}async function ey(e,t){return F(`/admin/datasets/${e}/enforce`,{method:"POST",body:JSON.stringify({dry_run:t})},!0)}async function Kye(e){return F("/admin/datasets/enforce/bulk",{method:"POST",body:JSON.stringify({prefix:e.prefix,visibility:e.visibility,limit:e.limit,dry_run:e.dryRun})},!0)}async function Jye(e,t){return F(`/admin/datasets/${e}/review-ruleset`,{method:"POST",body:JSON.stringify({dry_run:t.dryRun,remove:t.remove})},!0)}async function Yye(e){return F("/admin/datasets/review-ruleset/bulk",{method:"POST",body:JSON.stringify({prefix:e.prefix,after:e.after,limit:e.limit,dry_run:e.dryRun,remove:e.remove})},!0)}async function Xye(e,t=!1){return F(`/admin/datasets/${e}/revalidate${t?"?force=true":""}`,{method:"POST"},!0)}async function Qye(e){let t=e?`?user=${encodeURIComponent(e)}`:"";return F(`/admin/email-preferences${t}`,{},!0)}async function Zye(e,t){let n=t?`?user=${encodeURIComponent(t)}`:"";return F(`/admin/email-preferences${n}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)},!0)}async function LM(e){return F("/admin/notify",{method:"POST",body:JSON.stringify(e)},!0)}async function ebe(e){return F(`/admin/notify/${e}`,{},!0)}async function tbe(){return F("/admin/summary/coverage",{},!0)}async function nbe(e,t,n){return F("/admin/manifest/dispatch",{method:"POST",body:JSON.stringify({dataset_id:e,version:t,skip_canary:n?.skipCanary??!1})},!0)}async function qM(e){return F("/admin/doctor/scan",{method:"POST",body:JSON.stringify({...e?.check&&{check:e.check},...e?.datasetId&&{dataset_id:e.datasetId}})},!0)}async function UM(e){return F("/admin/doctor/fix",{method:"POST",body:JSON.stringify({check:e.check,...e.datasetId&&{dataset_id:e.datasetId},...e.dryRun&&{dry_run:!0}})},!0)}async function rbe(){return F("/admin/zarr-catalog/publish",{method:"POST"},!0)}async function obe(e){return F("/admin/neurobagel/regenerate",{method:"POST",body:JSON.stringify(e)},!0)}async function sbe(){return F("/admin/neurobagel/status",{method:"GET"},!0)}async function ibe(){return F("/admin/neurobagel/verify",{method:"POST",body:"{}"},!0)}async function abe(e){let t=new URLSearchParams;if(e?.limit!=null)t.set("limit",String(e.limit));let n=t.toString()?`?${t.toString()}`:"";return F(`/admin/datasets/zarr-fidelity-sweep${n}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function cbe(e){let t=new URLSearchParams;if(e?.execute)t.set("execute","1");if(e?.limit!=null)t.set("limit",String(e.limit));if(e?.after)t.set("after",e.after);let n=t.toString()?`?${t.toString()}`:"";try{return await F(`/admin/datasets/upstream-backfill${n}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}catch(r){let o=r instanceof U&&r.statusCode===502?r.rawBody:void 0;if(o&&typeof o==="object"&&"execute"in o&&"counts"in o)return{...o,ok:!1};throw r}}async function lbe(e){let t=new URLSearchParams;if(e?.limit!=null)t.set("limit",String(e.limit));if(e?.after)t.set("after",e.after);if(e?.dataset)t.set("dataset",e.dataset);let n=t.toString()?`?${t.toString()}`:"";try{return await F(`/admin/upstream-status${n}`,{method:"GET"},!0)}catch(r){let o=r instanceof U&&r.statusCode===502?r.rawBody:void 0;if(o&&typeof o==="object"&&"rows"in o&&"counts"in o)return{...o,ok:!1};throw r}}async function ube(e){let t=new URLSearchParams;if(e?.limit!=null)t.set("limit",String(e.limit));if(e?.apply)t.set("apply","1");let n=t.toString()?`?${t.toString()}`:"";return F(`/admin/imports/issue-triage${n}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function dbe(e){let t=e?.apply?"?apply=1":"";return F(`/admin/imports/coverage-sweep${t}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function fbe(e){let t=e?.apply?"?apply=1":"";return F(`/admin/imports/weekly-summary${t}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function pbe(e){return F("/admin/users/backfill-names",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apply:e?.apply??!1,...e?.limit!=null?{limit:e.limit}:{}})},!0)}async function mbe(e){return F("/admin/users/backfill-usernames",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apply:e?.apply??!1,...e?.limit!=null?{limit:e.limit}:{}})},!0)}async function hbe(){return F("/admin/users/duplicates",{},!0,ine)}async function gbe(e){return F(`/admin/users/${e}/clear-identity-conflict`,{method:"POST"},!0,ane)}async function ybe(e){let t=new URLSearchParams;if(e?.limit!=null)t.set("limit",String(e.limit));let n=t.toString()?`?${t.toString()}`:"";return F(`/admin/datasets/anonymity-sweep${n}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function bbe(){return F("/admin/datasets/anonymity-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Yw(e){let t=new URLSearchParams;if(e.verdicts&&e.verdicts.length>0)t.set("verdict",e.verdicts.join(","));if(e.dataset)t.set("dataset",e.dataset);if(e.author)t.set("author",e.author);if(e.needsMe)t.set("needs_me","1");let n=t.toString()?`?${t.toString()}`:"";return F(`/admin/pr-reviews${n}`,{method:"GET"},!0)}async function ty(e,t,n){let r=n?`?head=${encodeURIComponent(n)}`:"";return F(`/admin/pr-reviews/${encodeURIComponent(e)}/${t}${r}`,{method:"GET"},!0)}async function BM(e,t,n={}){let r=n.redo?"?redo=1":"";return F(`/admin/pr-reviews/${encodeURIComponent(e)}/${t}/start${r}`,{method:"POST"},!0)}async function wbe(e){return F(`/admin/pr-review-authors/${encodeURIComponent(e)}`,{method:"GET"},!0)}async function _be(e,t,n){return F(`/admin/pr-review-authors/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(n?{mode:t,reason:n}:{mode:t})},!0)}async function xbe(e){return F(`/admin/pr-review-authors/${encodeURIComponent(e)}`,{method:"DELETE"},!0)}async function vbe(e,t,n,r){return F(`/admin/pr-reviews/${encodeURIComponent(e)}/${t}/allow`,{method:"POST",body:JSON.stringify({reason:n,...r?{head_sha:r}:{}})},!0)}async function GM(e){let t=new URLSearchParams;for(let[r,o]of Object.entries(e))if(o!==void 0&&o!=="")t.set(r,String(o));let n=t.toString();return F(`/admin/mail/tickets${n?`?${n}`:""}`,{},!0)}async function zM(e){return F(`/admin/mail/tickets/${e}`,{},!0)}async function Ebe(e,t,n){let r={text:t};return F(`/admin/mail/tickets/${e}/reply`,Hd(r,{"Idempotency-Key":n}),!0)}async function Sbe(e,t,n){let r={text:t};return F(`/admin/mail/tickets/${e}/note`,Hd(r,{"Idempotency-Key":n}),!0)}async function kbe(e,t){let n={user_id:t};return F(`/admin/mail/tickets/${e}/assign`,Hd(n),!0)}async function Rbe(e,t){return F(`/admin/mail/tickets/${e}/status`,Hd({status:t}),!0)}async function $be(e,t){let n={summary:t};return F(`/admin/mail/tickets/${e}/summary`,HM(n),!0)}async function Dbe(e,t){let n=t?{reason:t}:{};return F(`/admin/mail/tickets/${e}/escalate`,Hd(n),!0)}async function Cbe(e,t){return F(`/admin/mail/tickets/${e}/spam`,Hd(t),!0)}async function Abe(e={}){let t=new URLSearchParams;for(let[r,o]of Object.entries(e))if(o!==void 0&&o!=="")t.set(r,String(o));let n=t.toString();return F(`/admin/mail/blocklist${n?`?${n}`:""}`,{},!0)}async function Obe(e){return F("/admin/mail/blocklist",Hd(e),!0)}async function Tbe(e){return F(`/admin/mail/blocklist/${e}`,{method:"DELETE"},!0)}async function Pbe(){return F("/admin/mail/queues",{},!0)}async function Ibe(e,t){return F(`/admin/mail/queues/${encodeURIComponent(e)}`,HM(t),!0)}async function Nbe(e){return F(`/admin/mail/availability${e===void 0?"":`/${e}`}`,{},!0)}async function VM(e,t){return F(`/admin/mail/availability${t===void 0?"":`/${t}`}`,HM(e),!0)}async function Fbe(e){return F("/admin/mail/reprocess",Hd({raw_key:e}),!0)}async function Mbe(e){return(await F(`/admin/users/by-id/${e}`,{},!0)).user.username}var Hd=(e,t)=>({method:"POST",body:JSON.stringify(e),...t?{headers:t}:{}}),HM=(e)=>({method:"PUT",body:JSON.stringify(e)});var _c=H(()=>{H0();Kh();wr();Ve()});async function ao(e,t){return F(`/datasets/${e}/upload-credentials`,{method:"POST",body:JSON.stringify({duration_seconds:t})},!0)}async function WM(e,t){return F(`/datasets/${e}/download-credentials`,{method:"POST",body:JSON.stringify({duration_seconds:t})},!0)}async function Lbe(e){return F(`/admin/datasets/${e}/files`,{},!0)}async function qbe(e){let t,n=0,r=[],o=!0;while(o){let s=await F(`/admin/datasets/${e}/s3-lock`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({continuation_token:t})},!0);if(n+=s.locked,s.failed?.length)r.push(...s.failed);if(o=s.hasMore,t=s.continuation_token,o&&!t)throw new U(500,"S3 lock paginated response missing continuation_token; aborting to avoid infinite loop")}return{locked:n,failed:r}}async function Ube(e,t){let n=0,r=[],o=[];for(let s=0;s<t.length;s+=jbe){let i=t.slice(s,s+jbe),a=await F(`/admin/datasets/${e}/s3-lock`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({objects:i})},!0);if(!Array.isArray(a.objects))throw new U(500,"The s3-lock route did not name the objects it locked.");if(n+=a.objects.length,o.push(...a.objects),a.failed?.length)r.push(...a.failed)}return{locked:n,failed:r,objects:o}}var jbe=100;var xc=H(()=>{wr();Ve()});async function i$(e){return F(`/datasets/${e}/ci/status`,{},!0)}async function Bbe(e){return F(`/datasets/${e}/manifest`,{},!0)}async function a$(e,t){return F(`/datasets/${e}/manifest/${t}`,{},!0)}function Hbe(e){let t=e;if(!t.status)t.status="active";else if(!["active","archived","deleted"].includes(t.status))throw Error(`Invalid dataset status: ${t.status}`);if(!t.visibility)t.visibility="private";else if(!["public","private"].includes(t.visibility))throw Error(`Invalid dataset visibility: ${t.visibility}`);return t}async function Gd(e={}){let t=new URLSearchParams;if(e.mine)t.set("mine","true");if(e.search)t.set("search",e.search);if(e.modality)t.set("modality",e.modality);if(e.author)t.set("author",e.author);if(e.task)t.set("task",e.task);if(e.license)t.set("license",e.license);if(e.hasDoi)t.set("has_doi","true");if(e.hasHed)t.set("has_hed","1");if(e.hasZarr)t.set("has_zarr","1");if(e.hasZarrVerified)t.set("has_zarr_verified","1");if(e.dataComplete)t.set("data_complete","1");if(e.recent)t.set("recent",String(e.recent));if(e.sort)t.set("sort",e.sort);if(e.limit!=null)t.set("limit",String(e.limit));if(e.offset!=null)t.set("offset",String(e.offset));if(e.owner)t.set("owner",e.owner);if(e.facets)for(let[o,s]of Object.entries(e.facets))t.set(o,s);if(e.includeUnknown)t.set("include_unknown","1");let n=t.toString()?`?${t.toString()}`:"",r=await F(`/datasets${n}`,{},e.mine?!0:"optional");return r.datasets=r.datasets.map(Hbe),r}async function Gbe(e){return F(`/datasets/resolve/${e}`,{},"optional")}async function zbe(){return F("/datasets/facets",{signal:AbortSignal.timeout(5000)},"optional",mS)}async function Vbe(e,t={}){let n=new URLSearchParams({q:e});if(t.modality)n.set("modality",t.modality);if(t.limit)n.set("limit",String(t.limit));if(t.hasHed)n.set("has_hed","1");if(t.hasZarr)n.set("has_zarr","1");if(t.hasZarrVerified)n.set("has_zarr_verified","1");if(t.author)n.set("author",t.author);if(t.task)n.set("task",t.task);if(t.license)n.set("license",t.license);if(t.hasDoi)n.set("has_doi","true");if(t.dataComplete)n.set("data_complete","1");if(t.recent)n.set("recent",String(t.recent));if(t.facets)for(let[o,s]of Object.entries(t.facets))n.set(o,s);if(t.includeUnknown)n.set("include_unknown","1");return await F(`/datasets/search?${n.toString()}`,{},"optional",Qte)}async function or(e){let t=await F(`/datasets/${e}`,{},"optional");return Hbe(t.dataset)}async function xp(e){return F(`/datasets/${e}/versions`,{},!0)}async function Wbe(e){try{let t=await xp(e);if(!Array.isArray(t.versions))throw Error(`GET /datasets/${e}/versions answered without a versions list`);return t.versions.length>0}catch(t){if(t instanceof U&&t.statusCode===404&&!Yh(t))return!1;throw t}}async function c$(e){return F("/datasets",{method:"POST",body:JSON.stringify(e)},!0)}async function Kbe(e,t){return F(`/datasets/${e}/attestation`,{method:"PUT",body:JSON.stringify(t)},!0)}async function l$(e){return F(`/datasets/${e}/finalize`,{method:"POST"},!0)}async function KM(e){return F(`/datasets/${e}/request-access`,{method:"POST"},!0)}async function Jbe(e,t){let n=t?`?status=${t}`:"";return F(`/datasets/${e}/access-requests${n}`,{},!0)}async function Ybe(e,t){return F(`/datasets/${e}/access-requests/${t}/approve`,{method:"POST"},!0)}async function Xbe(e,t){return F(`/datasets/${e}/access-requests/${t}/deny`,{method:"POST"},!0)}async function Qbe(e,t){return F(`/datasets/${e}/invite`,{method:"POST",body:JSON.stringify({username:t})},!0)}async function Zbe(e){return F(`/datasets/${e}/collaborators`,{},!0)}async function e0e(e,t){return F(`/admin/datasets/${e}/enrichment`,{method:"POST",body:JSON.stringify(t)},!0)}var s$;var vc=H(()=>{Kh();wr();Ve();s$=/^\d{4}-\d{4}-\d{4}-\d{3}[\dX]$/});function k0e(e,t){return e.filter((n)=>n.visibility==="public").map((n)=>n.dataset_id).filter((n)=>n.startsWith("nm")||n.startsWith("on")).filter((n)=>n!=="nm099999"&&!Ml.has(n)).filter((n)=>t.prefix?n.startsWith(t.prefix):!0).sort()}var Ml;var p$=H(()=>{Ml=new Set(["nm000103","nm000104","nm000105","nm000106","nm000107"])});function lo(e){return e.replace(R0e,$0e)}function $0e(e){if(e===`
|
|
113
|
+
`)}var Vge=!1;var vM=H(()=>{We()});function Hr(){if(process.env.TEST_API_URL)return process.env.TEST_API_URL;if(yp)return EM;return Yt().apiUrl||EM}async function F(e,t={},n=!1,r){let o=`${Hr()}${e}`,s={"Content-Type":"application/json","X-CLI-Version":Ls,...t.headers};if(n){let p=Yt();if(!p.apiKey&&n===!0)throw new U(401,"Not authenticated. Run 'nemar auth login' first.");if(p.apiKey)s.Authorization=`Bearer ${p.apiKey}`}let i=t.method||"GET",a=typeof t.body==="string"?t.body:void 0,c=Date.now(),l;try{l=await fetch(o,{...t,headers:s})}catch(p){if(Nl())JR({method:i,url:o,status:null,durationMs:Date.now()-c,requestHeaders:s,requestBody:a,error:p instanceof Error?p.message:String(p)});throw new U(0,`Network error: Could not connect to ${Hr()}`,{originalError:p instanceof Error?p.message:String(p)})}let d;try{d=await l.text()}catch(p){if(Nl())JR({method:i,url:o,status:l.status,durationMs:Date.now()-c,requestHeaders:s,requestBody:a,error:p instanceof Error?p.message:String(p)});throw new U(0,"Failed to read response body",{httpStatus:l.status,originalError:p instanceof Error?p.message:String(p)})}if(Nl())JR({method:i,url:o,status:l.status,durationMs:Date.now()-c,requestHeaders:s,requestBody:a,responseBody:d});let f;try{f=JSON.parse(d)}catch{throw new U(l.status,`Invalid response from server (status ${l.status})`)}if(!l.ok){if(l.status===503&&(f.mode==="read-only"||f.mode==="full")){let V=typeof f.message==="string"?f.message:"NEMAR is in maintenance mode. Please retry shortly.",T=typeof f.eta==="string"?f.eta:null,L=new ed(f.mode,V,T,f.details);throw XR(L),L}let p=typeof f.block_reason==="string",m=Array.isArray(f.missing)?f.missing.filter((V)=>typeof V==="string"):void 0,h=typeof f.error==="string"&&(Ute.includes(f.error)||sne.includes(f.error)),g=typeof f.error==="string"&&(gS.options.includes(f.error)||une.includes(f.error)),y=typeof f.error==="string"&&Nte.includes(f.error),b=typeof f.error==="string"&&Bte.includes(f.error),x=typeof f.error==="string"&&tne.includes(f.error),v=typeof f.error==="string"&&ene.includes(f.error),S=typeof f.error==="string"&&nne.includes(f.error),O=p||v||S||h||g||y||b||x||m!==void 0&&typeof f.error==="string"&&qte.includes(f.error)?f.message||f.error:f.error||f.message;if(l.status===404&&f.error==="Not Found"&&typeof f.message==="string")O=`${f.message}. This NEMAR backend does not support this command yet.`;let I=new U(l.status,O||"Request failed",f.details,typeof f.step==="string"?f.step:void 0,p?f.block_reason:void 0,m);if(typeof f.error==="string")I.code=f.error;if(typeof f.reason==="string")I.reason=f.reason;throw I.rawBody=f,I}if(r){let p=r.safeParse(f);if(!p.success)throw new U(l.status,`Response for ${e} did not match the expected NEMAR contract`,{issues:p.error.issues});return p.data}return f}var EM="https://api.nemar.org",yp;var wr=H(()=>{H0();wS();bI();Fh();Ih();Or();wn();vM();gp();Ve();yp=EM.includes("workers.dev")});async function Vg(e,t={}){return F(`/datasets/${e}/publish/request`,t.anonymous?{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({anonymous:!0})}:{method:"POST"},!0)}async function Wg(e){return F(`/datasets/${e}/publish/status`,{},!0)}async function Jge(e){return F(`/datasets/${e}/publish/resend`,{method:"POST"},!0)}async function Yge(e){return F(`/datasets/${e}/publish/withdraw`,{method:"POST"},!0)}async function bp(e={}){let{statuses:t,search:n}=typeof e==="string"?{statuses:e?[e]:[]}:e,r=await Wge(t,n),o=r;if(t!==void 0&&t.length>1&&r.requests.length===0){let s=[];for(let a of new Set(t))s.push(await Wge([a],n));let i=s.flatMap((a)=>a.requests).sort(Xge);o={...r,requests:i,count:i.length}}return n?Lwt(o,n):o}function Xge(e,t){return e.requested_at<t.requested_at?1:e.requested_at>t.requested_at?-1:0}async function Wge(e,t){let n=new URLSearchParams;if(e&&e.length>0)n.set("status",e.join(","));if(t)n.set("search",t);let r=n.size>0?`?${n}`:"";return F(`/admin/publish/requests${r}`,{},!0)}function Lwt(e,t){let n=e.requests.filter((s)=>Ire(t,[s.dataset_id,s.requested_by_username,s.dataset_name])),r=(s)=>Nre(s.dataset_id,t)?0:1,o=[...n].sort((s,i)=>r(s)-r(i)||Xge(s,i));return{...e,requests:o,count:o.length}}async function Kg(e,t,n){return F(`/admin/publish/${e}/deny`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:t,...n!==void 0?{request_id:n}:{}})},!0)}async function QR(e){return F(`/admin/publish/${e}/identifier-screen`,{method:"POST"},!0)}async function ZR(e){return F(`/admin/publish/${e}/review`,{},!0)}async function Qge(e){return F(`/admin/publish/${e}/review/start`,{method:"POST"},!0)}async function Zge(e,t){let n={message:t};return F(`/admin/publish/${e}/comment`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},!0)}function Jg(e){if(!(e instanceof U))return;let t=e.rawBody;if(typeof t!=="object"||t===null||Array.isArray(t))return;let n=t.code;return typeof n==="string"?n:void 0}function qwt(e,t=[]){if(e){let n=Ga.indexOf(e);if(n>=0)return n+1}return Math.min(t.length+1,Ga.length)}function Uwt(e){if(!(e instanceof U))return!1;if(e.statusCode===0)return!0;if(e.statusCode===429)return!0;if(e.statusCode>=500&&e.statusCode<600)return!0;if(e.statusCode===403&&/repository has been locked/i.test(e.message))return!0;return!1}function Bwt(){let e=process.env.NEMAR_APPROVE_RETRY_DELAY_MS;if(e===void 0||!/^\d+$/.test(e))return GS;let t=Number(e);return Number.isSafeInteger(t)&&t<=GS?t:GS}async function Yg(e,t=!1,n=!1,r=!1,o,s,i,a,c){let d=Bwt(),f,p,m=0,h=!1,g,y=t,b=[],x;function v(S,E,O,I){if(!s)return;s({step:S,stepIndex:qwt(S,E),stepTotal:Ga.length,s3LockLocked:O,s3LockTotal:I,s3LockResumed:S==="s3_lock"&&h?!0:void 0})}for(let S=1;S<=5;S++)try{let E,O=!0;do{if(E=await F(`/admin/publish/${e}/approve`,{method:"POST",headers:{"Content-Type":"application/json",...c?.dispatchToken?{[rne]:c.dispatchToken}:{}},body:JSON.stringify({resume:O?y:!0,sandbox:n,s3_lock_continuation_token:f,s3_lock_total:p,skip_ci_check:r,...i!==void 0?{acknowledge_identifier_screen:i}:{},...a!==void 0?{[Ore]:a}:{},...c?.requestId!==void 0?{request_id:c.requestId}:{}})},!0),O=!1,E.step_results)b.push(...E.step_results);if(E.s3_lock_total!==void 0)p=E.s3_lock_total;if(E.s3_lock_batch_count!==void 0)m+=E.s3_lock_batch_count;let I=E.step??E.step_results?.[E.step_results.length-1]?.step;if(I&&(I!==g||I==="s3_lock"))v(I,E.steps_completed??[],I==="s3_lock"?m:void 0,I==="s3_lock"?p:void 0),g=I;if(E.hasMore&&E.s3_lock_continuation_token!==void 0)f=E.s3_lock_continuation_token;else break}while(E.hasMore);if(b.length>0)E.step_results=Kge(b);return E}catch(E){if(x=E,S===5||!Uwt(E)){if(E instanceof U&&b.length>0)E.stepResults=Kge(b);throw E}let I=E;if(o?.({attempt:S,maxAttempts:5,delayMs:d,step:I.step,error:I.message}),await new Promise((V)=>setTimeout(V,d)),y=!0,f!==void 0)h=!0}throw x}function Kge(e){let t=new Map;for(let n of e)t.set(n.step,n);return Array.from(t.values())}var ta=H(()=>{HS();Fh();VS();wr();Ve()});function n$(e){if(e.service_access===void 0||e.service_access===null)return"unknown";return e.service_access?"upload":"browse"}async function PM(e,t,n,r,o={}){let s=new URLSearchParams;if(e)s.set("status",e);if(t)s.set("role",t);if(n)s.set("awaiting_approval","1");if(r)s.set("kind",r);if(o.search!==void 0)s.set("q",o.search);if(o.includeDeleted)s.set("include_deleted","true");let i=s.toString()?`?${s.toString()}`:"";return F(`/admin/users${i}`,{},!0,jte)}async function r$(e,t=!1){return F(`/admin/users/by-id/${e}${t?"?include_deleted=true":""}`,{},!0,zte)}async function lye(e,t){return F(`/admin/users/by-id/${e}`,{method:"PATCH",body:JSON.stringify(t)},!0,Vte)}async function uye(e){return F(`/admin/approve/${e}`,{method:"POST"},!0)}async function dye(e){return F(`/admin/approve/by-id/${e}`,{method:"POST"},!0)}async function fye(e){return F(`/admin/revoke/${e}`,{method:"POST"},!0)}async function pye(e){return F(`/admin/revoke/by-id/${e}`,{method:"POST"},!0)}async function mye(e){return F(`/admin/users/by-id/${e}/verify`,{method:"POST"},!0)}async function hye(e,t){return F(`/admin/users/${e}/role`,{method:"POST",body:JSON.stringify({role:t})},!0)}async function gye(e,t){return F(`/admin/users/${e}/kind`,{method:"POST",body:JSON.stringify({kind:t})},!0)}async function o$(e){return F(`/admin/users/${encodeURIComponent(e)}`,{},!0)}async function yye(e,t){return F(`/admin/users/${e}/keys`,{method:"POST",body:JSON.stringify({name:t})},!0,bS)}async function bye(e){return F(`/admin/users/${e}/keys`,{},!0,yS)}async function wye(e,t){return F(`/admin/users/${e}/keys/${t}`,{method:"DELETE"},!0)}async function _ye(e){return F(`/datasets/${e}/publish`,{method:"POST"},!0)}async function xye(e){return F(`/admin/datasets/${e}/ci`,{},!0)}async function Fl(e){return F(`/admin/datasets/${e}/ci`,{method:"POST"},!0)}async function IM(e){return F(`/admin/datasets/${e}/ci/validate`,{method:"POST"},!0)}async function NM(e){return F(`/admin/datasets/${e}/ci/sync`,{method:"POST"},!0)}async function vye(e,t){return F(`/admin/datasets/${e}/doi/concept`,{method:"POST",body:JSON.stringify(t)},!0)}async function Jw(e){return F(`/admin/datasets/${e}/doi`,{},!0)}async function FM(e,t){return F(`/admin/datasets/${e}/doi/update`,{method:"POST",body:JSON.stringify(t)},!0)}async function Eye(e,t){return F(`/admin/datasets/${e}/withdraw`,{method:"POST",body:JSON.stringify({reason:t.reason,dry_run:t.dryRun})},!0)}async function Sye(e,t){return F(`/admin/datasets/${e}/restore`,{method:"POST",body:JSON.stringify({dry_run:t.dryRun})},!0)}async function kye(e,t){return F(`/admin/datasets/${e}/unpublish`,{method:"POST",body:JSON.stringify({reason:t.reason,dry_run:t.dryRun})},!0)}async function Rye(e){return F(`/admin/datasets/${e}/reset`,{method:"POST"},!0)}async function $ye(e,t=!1){return F(`/admin/datasets/${e}`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({force:t})},!0)}async function Dye(e){return F("/admin/datasets/bulk-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dataset_ids:e})},!0)}async function Cye(e){return F("/admin/datasets/import",{method:"POST",body:JSON.stringify(e)},!0)}async function Aye(e){return F("/admin/datasets/exemplar",{method:"POST",body:JSON.stringify(e)},!0)}async function Oye(e){return F(`/admin/datasets/${e}/exemplar/remint-dois`,{method:"POST"},!0)}async function MM(e,t){let n=new URLSearchParams;if(e)n.set("status",e);if(t!==void 0)n.set("blocklisted",t?"1":"0");let r=n.toString();return F(`/admin/imports${r?`?${r}`:""}`,{},!0)}async function Tye(e){return F(`/admin/imports/${e}/rollback`,{method:"POST"},!0)}async function Pye(e){return F(`/admin/imports/${e}/retry`,{method:"POST"},!0)}async function jM(e){return F(`/admin/imports/${e}/verify`,{method:"POST"},!0)}async function Iye(e){return F("/admin/imports/dispatch-cooldown",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dataset_ids:e})},!0)}async function Zg(e,t){return F(`/admin/datasets/${e}/reindex`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})},!0)}async function Nye(e,t){return F("/admin/datasets/reindex/bulk",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filter:e,...t??{}})},!0)}async function Fye(e){let t=e?.limit??15;return F(`/admin/datasets/hed-sweep?limit=${encodeURIComponent(String(t))}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Mye(){return F("/admin/datasets/hed-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function jye(e){let t=e?.limit??50;return F(`/admin/datasets/recording-stats-sweep?limit=${encodeURIComponent(String(t))}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Lye(){return F("/admin/datasets/recording-stats-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function qye(e){let t=e?.limit??15;return F(`/admin/datasets/signal-defaults-sweep?limit=${encodeURIComponent(String(t))}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Uye(){return F("/admin/datasets/signal-defaults-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Bye(e){let t=e?.limit??15,n=new URLSearchParams({limit:String(t)});if(e?.olderThan!=null)n.set("older-than",String(e.olderThan));if(e?.before!=null)n.set("before",e.before);return F(`/admin/datasets/data-integrity-sweep?${n.toString()}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Hye(){return F("/admin/datasets/data-integrity-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Gye(e,t){let n=t?.write?"":"?dry_run=1";return F(`/admin/datasets/${e}/availability-report${n}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function zye(e){let t=e?.limit??30,n=new URLSearchParams({limit:String(t)});if(e?.missingOnly)n.set("missing-only","1");return F(`/admin/datasets/availability-report-sweep?${n.toString()}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Vye(){return F("/admin/datasets/availability-report-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Wye(e){let t=new URLSearchParams;if(e?.prefix)t.set("prefix",e.prefix);if(e?.visibility)t.set("visibility",e.visibility);if(e?.limit)t.set("limit",String(e.limit));let n=t.toString()?`?${t.toString()}`:"";return F(`/admin/fleet/drift${n}`,{},!0)}async function ey(e,t){return F(`/admin/datasets/${e}/enforce`,{method:"POST",body:JSON.stringify({dry_run:t})},!0)}async function Kye(e){return F("/admin/datasets/enforce/bulk",{method:"POST",body:JSON.stringify({prefix:e.prefix,visibility:e.visibility,limit:e.limit,dry_run:e.dryRun})},!0)}async function Jye(e,t){return F(`/admin/datasets/${e}/review-ruleset`,{method:"POST",body:JSON.stringify({dry_run:t.dryRun,remove:t.remove})},!0)}async function Yye(e){return F("/admin/datasets/review-ruleset/bulk",{method:"POST",body:JSON.stringify({prefix:e.prefix,after:e.after,limit:e.limit,dry_run:e.dryRun,remove:e.remove})},!0)}async function Xye(e,t=!1){return F(`/admin/datasets/${e}/revalidate${t?"?force=true":""}`,{method:"POST"},!0)}async function Qye(e){let t=e?`?user=${encodeURIComponent(e)}`:"";return F(`/admin/email-preferences${t}`,{},!0)}async function Zye(e,t){let n=t?`?user=${encodeURIComponent(t)}`:"";return F(`/admin/email-preferences${n}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)},!0)}async function LM(e){return F("/admin/notify",{method:"POST",body:JSON.stringify(e)},!0)}async function ebe(e){return F(`/admin/notify/${e}`,{},!0)}async function tbe(){return F("/admin/summary/coverage",{},!0)}async function nbe(e,t,n){return F("/admin/manifest/dispatch",{method:"POST",body:JSON.stringify({dataset_id:e,version:t,skip_canary:n?.skipCanary??!1})},!0)}async function qM(e){return F("/admin/doctor/scan",{method:"POST",body:JSON.stringify({...e?.check&&{check:e.check},...e?.datasetId&&{dataset_id:e.datasetId}})},!0)}async function UM(e){return F("/admin/doctor/fix",{method:"POST",body:JSON.stringify({check:e.check,...e.datasetId&&{dataset_id:e.datasetId},...e.dryRun&&{dry_run:!0}})},!0)}async function rbe(){return F("/admin/zarr-catalog/publish",{method:"POST"},!0)}async function obe(e){return F("/admin/neurobagel/regenerate",{method:"POST",body:JSON.stringify(e)},!0)}async function sbe(){return F("/admin/neurobagel/status",{method:"GET"},!0)}async function ibe(){return F("/admin/neurobagel/verify",{method:"POST",body:"{}"},!0)}async function abe(e){let t=new URLSearchParams;if(e?.limit!=null)t.set("limit",String(e.limit));let n=t.toString()?`?${t.toString()}`:"";return F(`/admin/datasets/zarr-fidelity-sweep${n}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function cbe(e){let t=new URLSearchParams;if(e?.execute)t.set("execute","1");if(e?.limit!=null)t.set("limit",String(e.limit));if(e?.after)t.set("after",e.after);let n=t.toString()?`?${t.toString()}`:"";try{return await F(`/admin/datasets/upstream-backfill${n}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}catch(r){let o=r instanceof U&&r.statusCode===502?r.rawBody:void 0;if(o&&typeof o==="object"&&"execute"in o&&"counts"in o)return{...o,ok:!1};throw r}}async function lbe(e){let t=new URLSearchParams;if(e?.limit!=null)t.set("limit",String(e.limit));if(e?.after)t.set("after",e.after);if(e?.dataset)t.set("dataset",e.dataset);let n=t.toString()?`?${t.toString()}`:"";try{return await F(`/admin/upstream-status${n}`,{method:"GET"},!0)}catch(r){let o=r instanceof U&&r.statusCode===502?r.rawBody:void 0;if(o&&typeof o==="object"&&"rows"in o&&"counts"in o)return{...o,ok:!1};throw r}}async function ube(e){let t=new URLSearchParams;if(e?.limit!=null)t.set("limit",String(e.limit));if(e?.apply)t.set("apply","1");let n=t.toString()?`?${t.toString()}`:"";return F(`/admin/imports/issue-triage${n}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function dbe(e){let t=e?.apply?"?apply=1":"";return F(`/admin/imports/coverage-sweep${t}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function fbe(e){let t=e?.apply?"?apply=1":"";return F(`/admin/imports/weekly-summary${t}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function pbe(e){return F("/admin/users/backfill-names",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apply:e?.apply??!1,...e?.limit!=null?{limit:e.limit}:{}})},!0)}async function mbe(e){return F("/admin/users/backfill-usernames",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apply:e?.apply??!1,...e?.limit!=null?{limit:e.limit}:{}})},!0)}async function hbe(){return F("/admin/users/duplicates",{},!0,ine)}async function gbe(e){return F(`/admin/users/${e}/clear-identity-conflict`,{method:"POST"},!0,ane)}async function ybe(e){let t=new URLSearchParams;if(e?.limit!=null)t.set("limit",String(e.limit));let n=t.toString()?`?${t.toString()}`:"";return F(`/admin/datasets/anonymity-sweep${n}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function bbe(){return F("/admin/datasets/anonymity-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Yw(e){let t=new URLSearchParams;if(e.verdicts&&e.verdicts.length>0)t.set("verdict",e.verdicts.join(","));if(e.dataset)t.set("dataset",e.dataset);if(e.author)t.set("author",e.author);if(e.needsMe)t.set("needs_me","1");let n=t.toString()?`?${t.toString()}`:"";return F(`/admin/pr-reviews${n}`,{method:"GET"},!0)}async function ty(e,t,n){let r=n?`?head=${encodeURIComponent(n)}`:"";return F(`/admin/pr-reviews/${encodeURIComponent(e)}/${t}${r}`,{method:"GET"},!0)}async function BM(e,t,n={}){let r=n.redo?"?redo=1":"";return F(`/admin/pr-reviews/${encodeURIComponent(e)}/${t}/start${r}`,{method:"POST"},!0)}async function wbe(e){return F(`/admin/pr-review-authors/${encodeURIComponent(e)}`,{method:"GET"},!0)}async function _be(e,t,n){return F(`/admin/pr-review-authors/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(n?{mode:t,reason:n}:{mode:t})},!0)}async function xbe(e){return F(`/admin/pr-review-authors/${encodeURIComponent(e)}`,{method:"DELETE"},!0)}async function vbe(e,t,n,r){return F(`/admin/pr-reviews/${encodeURIComponent(e)}/${t}/allow`,{method:"POST",body:JSON.stringify({reason:n,...r?{head_sha:r}:{}})},!0)}async function GM(e){let t=new URLSearchParams;for(let[r,o]of Object.entries(e))if(o!==void 0&&o!=="")t.set(r,String(o));let n=t.toString();return F(`/admin/mail/tickets${n?`?${n}`:""}`,{},!0)}async function zM(e){return F(`/admin/mail/tickets/${e}`,{},!0)}async function Ebe(e,t,n){let r={text:t};return F(`/admin/mail/tickets/${e}/reply`,Hd(r,{"Idempotency-Key":n}),!0)}async function Sbe(e,t,n){let r={text:t};return F(`/admin/mail/tickets/${e}/note`,Hd(r,{"Idempotency-Key":n}),!0)}async function kbe(e,t){let n={user_id:t};return F(`/admin/mail/tickets/${e}/assign`,Hd(n),!0)}async function Rbe(e,t){return F(`/admin/mail/tickets/${e}/status`,Hd({status:t}),!0)}async function $be(e,t){let n={summary:t};return F(`/admin/mail/tickets/${e}/summary`,HM(n),!0)}async function Dbe(e,t){let n=t?{reason:t}:{};return F(`/admin/mail/tickets/${e}/escalate`,Hd(n),!0)}async function Cbe(e,t){return F(`/admin/mail/tickets/${e}/spam`,Hd(t),!0)}async function Abe(e={}){let t=new URLSearchParams;for(let[r,o]of Object.entries(e))if(o!==void 0&&o!=="")t.set(r,String(o));let n=t.toString();return F(`/admin/mail/blocklist${n?`?${n}`:""}`,{},!0)}async function Obe(e){return F("/admin/mail/blocklist",Hd(e),!0)}async function Tbe(e){return F(`/admin/mail/blocklist/${e}`,{method:"DELETE"},!0)}async function Pbe(){return F("/admin/mail/queues",{},!0)}async function Ibe(e,t){return F(`/admin/mail/queues/${encodeURIComponent(e)}`,HM(t),!0)}async function Nbe(e){return F(`/admin/mail/availability${e===void 0?"":`/${e}`}`,{},!0)}async function VM(e,t){return F(`/admin/mail/availability${t===void 0?"":`/${t}`}`,HM(e),!0)}async function Fbe(e){return F("/admin/mail/reprocess",Hd({raw_key:e}),!0)}async function Mbe(e){return(await F(`/admin/users/by-id/${e}`,{},!0)).user.username}var Hd=(e,t)=>({method:"POST",body:JSON.stringify(e),...t?{headers:t}:{}}),HM=(e)=>({method:"PUT",body:JSON.stringify(e)});var _c=H(()=>{H0();Kh();wr();Ve()});async function ao(e,t){return F(`/datasets/${e}/upload-credentials`,{method:"POST",body:JSON.stringify({duration_seconds:t})},!0)}async function WM(e,t){return F(`/datasets/${e}/download-credentials`,{method:"POST",body:JSON.stringify({duration_seconds:t})},!0)}async function Lbe(e){return F(`/admin/datasets/${e}/files`,{},!0)}async function qbe(e){let t,n=0,r=[],o=!0;while(o){let s=await F(`/admin/datasets/${e}/s3-lock`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({continuation_token:t})},!0);if(n+=s.locked,s.failed?.length)r.push(...s.failed);if(o=s.hasMore,t=s.continuation_token,o&&!t)throw new U(500,"S3 lock paginated response missing continuation_token; aborting to avoid infinite loop")}return{locked:n,failed:r}}async function Ube(e,t){let n=0,r=[],o=[];for(let s=0;s<t.length;s+=jbe){let i=t.slice(s,s+jbe),a=await F(`/admin/datasets/${e}/s3-lock`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({objects:i})},!0);if(!Array.isArray(a.objects))throw new U(500,"The s3-lock route did not name the objects it locked.");if(n+=a.objects.length,o.push(...a.objects),a.failed?.length)r.push(...a.failed)}return{locked:n,failed:r,objects:o}}var jbe=100;var xc=H(()=>{wr();Ve()});async function i$(e){return F(`/datasets/${e}/ci/status`,{},!0)}async function Bbe(e){return F(`/datasets/${e}/manifest`,{},!0)}async function a$(e,t){return F(`/datasets/${e}/manifest/${t}`,{},!0)}function Hbe(e){let t=e;if(!t.status)t.status="active";else if(!["active","archived","deleted"].includes(t.status))throw Error(`Invalid dataset status: ${t.status}`);if(!t.visibility)t.visibility="private";else if(!["public","private"].includes(t.visibility))throw Error(`Invalid dataset visibility: ${t.visibility}`);return t}async function Gd(e={}){let t=new URLSearchParams;if(e.mine)t.set("mine","true");if(e.search)t.set("search",e.search);if(e.modality)t.set("modality",e.modality);if(e.author)t.set("author",e.author);if(e.task)t.set("task",e.task);if(e.license)t.set("license",e.license);if(e.hasDoi)t.set("has_doi","true");if(e.hasHed)t.set("has_hed","1");if(e.hasZarr)t.set("has_zarr","1");if(e.hasZarrVerified)t.set("has_zarr_verified","1");if(e.dataComplete)t.set("data_complete","1");if(e.recent)t.set("recent",String(e.recent));if(e.sort)t.set("sort",e.sort);if(e.limit!=null)t.set("limit",String(e.limit));if(e.offset!=null)t.set("offset",String(e.offset));if(e.owner)t.set("owner",e.owner);if(e.facets)for(let[o,s]of Object.entries(e.facets))t.set(o,s);if(e.includeUnknown)t.set("include_unknown","1");let n=t.toString()?`?${t.toString()}`:"",r=await F(`/datasets${n}`,{},e.mine?!0:"optional");return r.datasets=r.datasets.map(Hbe),r}async function Gbe(e){return F(`/datasets/resolve/${e}`,{},"optional")}async function zbe(){return F("/datasets/facets",{signal:AbortSignal.timeout(5000)},"optional",mS)}async function Vbe(e,t={}){let n=new URLSearchParams({q:e});if(t.modality)n.set("modality",t.modality);if(t.limit)n.set("limit",String(t.limit));if(t.hasHed)n.set("has_hed","1");if(t.hasZarr)n.set("has_zarr","1");if(t.hasZarrVerified)n.set("has_zarr_verified","1");if(t.author)n.set("author",t.author);if(t.task)n.set("task",t.task);if(t.license)n.set("license",t.license);if(t.hasDoi)n.set("has_doi","true");if(t.dataComplete)n.set("data_complete","1");if(t.recent)n.set("recent",String(t.recent));if(t.facets)for(let[o,s]of Object.entries(t.facets))n.set(o,s);if(t.includeUnknown)n.set("include_unknown","1");return await F(`/datasets/search?${n.toString()}`,{},"optional",Qte)}async function or(e){let t=await F(`/datasets/${e}`,{},"optional");return Hbe(t.dataset)}async function xp(e){return F(`/datasets/${e}/versions`,{},!0)}async function Wbe(e){try{let t=await xp(e);if(!Array.isArray(t.versions))throw Error(`GET /datasets/${e}/versions answered without a versions list`);return t.versions.length>0}catch(t){if(t instanceof U&&t.statusCode===404&&!Yh(t))return!1;throw t}}async function c$(e){return F("/datasets",{method:"POST",body:JSON.stringify(e)},!0)}async function Kbe(e,t){return F(`/datasets/${e}/attestation`,{method:"PUT",body:JSON.stringify(t)},!0)}async function l$(e){return F(`/datasets/${e}/finalize`,{method:"POST"},!0)}async function KM(e){return F(`/datasets/${e}/request-access`,{method:"POST"},!0)}async function Jbe(e,t){let n=t?`?status=${t}`:"";return F(`/datasets/${e}/access-requests${n}`,{},!0)}async function Ybe(e,t){return F(`/datasets/${e}/access-requests/${t}/approve`,{method:"POST"},!0)}async function Xbe(e,t){return F(`/datasets/${e}/access-requests/${t}/deny`,{method:"POST"},!0)}async function Qbe(e,t){return F(`/datasets/${e}/invite`,{method:"POST",body:JSON.stringify({username:t})},!0)}async function Zbe(e){return F(`/datasets/${e}/collaborators`,{},!0)}async function e0e(e,t){return F(`/admin/datasets/${e}/enrichment`,{method:"POST",body:JSON.stringify(t)},!0)}var s$;var vc=H(()=>{Kh();wr();Ve();s$=/^\d{4}-\d{4}-\d{4}-\d{3}[\dX]$/});function k0e(e,t){return e.filter((n)=>n.visibility==="public").map((n)=>n.dataset_id).filter((n)=>n.startsWith("nm")||n.startsWith("on")).filter((n)=>n!=="nm099999"&&!Ml.has(n)).filter((n)=>t.prefix?n.startsWith(t.prefix):!0).sort()}var Ml;var p$=H(()=>{Ml=new Set(["nm000103","nm000104","nm000105","nm000106","nm000107"])});function lo(e){return e.replace(R0e,$0e)}function $0e(e){if(e===`
|
|
114
114
|
`)return"\\n";if(e==="\r")return"\\r";if(e==="\t")return"\\t";let t=e.codePointAt(0)??0;return t<=255?`\\x${t.toString(16).padStart(2,"0")}`:t<=65535?`\\u${t.toString(16).padStart(4,"0")}`:`\\u{${t.toString(16)}}`}function Xw(e){return e.replace(R0e,(t)=>t===`
|
|
115
115
|
`||t==="\t"?t:$0e(t))}function m$(e,t=", "){return e.map(lo).join(t)}var R0e,Ec=(e)=>lo(e)===e;var vp=H(()=>{R0e=/[\p{Cc}\p{Cf}\u2028\u2029\u034f\u115f\u1160\u3164\uffa0\ufe00-\ufe0f\u{e0100}-\u{e01ef}]/gu});async function e_t(){try{let{exitCode:e,stderr:t}=await A(["ssh","-T","-o","BatchMode=yes","-o","ConnectTimeout=5","git@github.com"]),n=t.includes("successfully authenticated");if(!n)console.warn("SSH test to github.com failed:",{exitCode:e,stderr:t.trim().slice(0,500)});return{works:n,error:n?void 0:t.trim().slice(0,500)}}catch(e){let t=e instanceof Error?e.message:String(e);return console.warn("SSH test exception:",t),{works:!1,error:t}}}async function Ep(){try{let{stdout:e,exitCode:t,stderr:n}=await A(["gh","auth","token"],{sensitiveOutput:!0});if(t!==0)return console.warn("gh CLI returned non-zero exit code:",t),console.warn("stderr:",n),{token:null,error:`gh auth token failed: ${n.trim()||"unknown error"}`};if(!e.trim())return console.warn("gh auth token returned empty output"),{token:null,error:"gh CLI returned empty token"};return{token:e.trim()}}catch(e){let t=e instanceof Error?e.message:String(e);if(console.error("Failed to get GitHub token from gh CLI:",t),t.includes("ENOENT")||t.includes("not found"))return{token:null,error:"gh CLI not installed (command not found)"};return{token:null,error:`gh CLI error: ${t}`}}}async function h$(e){try{let{stdout:t,exitCode:n,stderr:r}=await A(["gh","api","user","--jq",".login"]);if(n!==0){if(r.includes("not logged in")||r.includes("auth login"))return{authenticated:!1,error:"gh CLI not authenticated. Run 'gh auth login' to authenticate."};return{authenticated:!1,error:`gh CLI error: ${r.trim()||"unknown error"}`}}let o=t.trim();if(!o)return{authenticated:!1,error:"gh CLI returned empty username"};if(e){let s=o.toLowerCase()===e.toLowerCase();return{authenticated:!0,username:o,matches:s,error:s?void 0:`gh CLI authenticated as '${o}', expected '${e}'`}}return{authenticated:!0,username:o}}catch(t){let n=t instanceof Error?t.message:String(t);if(n.includes("ENOENT")||n.includes("not found"))return{authenticated:!1,error:"gh CLI not installed. Install from https://cli.github.com/"};return{authenticated:!1,error:`Failed to verify gh CLI: ${n}`}}}async function g$(e){if(!/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/.test(e))return{accepted:!1,error:`Invalid repository format: ${e}`};let{stdout:t,exitCode:n,stderr:r}=await A(["gh","api","/user/repository_invitations"]);if(n!==0){if(r.includes("not logged in")||r.includes("auth login"))return{accepted:!1,error:"gh CLI not authenticated. Run 'gh auth login' to authenticate."};if(r.includes("API rate limit")||r.includes("403"))return{accepted:!1,error:"GitHub API rate limit exceeded. Please try again in a few minutes."};if(r.includes("ENOENT")||r.includes("not found"))return{accepted:!1,error:"gh CLI not installed. Install from https://cli.github.com/"};return{accepted:!1,error:`Failed to list invitations: ${r.trim()||"unknown error"}`}}let o=null;try{o=JSON.parse(t||"[]").find((l)=>l.repository.full_name===e)?.id??null}catch(a){let c=a instanceof Error?a.message:String(a);return console.error("Failed to parse GitHub invitations response:",c),console.error(" Raw response (first 500 chars):",(t||"").slice(0,500)),{accepted:!1,error:`Failed to parse GitHub API response: ${c}`}}if(!o){let{exitCode:a}=await A(["gh","api",`/repos/${e}`,"--silent"]);if(a===0)return{accepted:!0,alreadyCollaborator:!0};return{accepted:!1,error:`No pending invitation found for ${e}. You may need to accept it manually via GitHub.`}}let{exitCode:s,stderr:i}=await A(["gh","api","--method","PATCH",`/user/repository_invitations/${o}`]);if(s!==0)return{accepted:!1,error:`Failed to accept invitation: ${i.trim()||"unknown error"}`};return{accepted:!0}}async function Sc(e,t,n="origin"){let r=t;if(process.env.GH_TOKEN&&t.startsWith("git@github.com:")){let o=process.env.GH_TOKEN.trim();if(!o||/\s/.test(o))return{success:!1,error:"GH_TOKEN environment variable is set but appears malformed (empty or contains whitespace)"};r=`https://github.com/${t.replace("git@github.com:","")}`,await A(["git","config","credential.https://github.com.helper",`!printf 'username=x-access-token\\npassword=${o}'`],{cwd:e,redact:[o]})}else if(t.startsWith("git@github.com:")){let o=t.replace("git@github.com:",""),s=await Ep();if(s.token)r=`https://github.com/${o}`,await A(["git","config","credential.https://github.com.helper",`!printf 'username=x-access-token\\npassword=${s.token}'`],{cwd:e,redact:[s.token]});else{let i=await e_t();if(i.works)r=t;else return{success:!1,error:`GitHub authentication not configured.
|
|
116
116
|
|
|
@@ -760,7 +760,7 @@ which names the field and never repeats what was typed.
|
|
|
760
760
|
Examples:
|
|
761
761
|
nemar admin oidc clients add --name "Compute portal" --redirect-uri https://portal.example.org/cb \\
|
|
762
762
|
--scopes openid,profile,orcid --grants authorization_code --sign-in-rule person_proven_orcid \\
|
|
763
|
-
--audience https://
|
|
763
|
+
--audience https://api.nemar.org
|
|
764
764
|
|
|
765
765
|
Exit codes:
|
|
766
766
|
0 registered; the secret was printed.
|
|
@@ -891,7 +891,7 @@ partner's answer. The counts of every status are printed whatever --status says.
|
|
|
891
891
|
Exit codes:
|
|
892
892
|
0 listed (an empty list is not a failure).
|
|
893
893
|
1 not signed in, not the owner, a --status or --limit the server refuses, or a server on which the
|
|
894
|
-
provider is off.`,hy=new ae("oidc").description("Register OpenID Connect clients and manage NEMAR's signing keys (owner only; ADR 0119)"),gy=new ae("clients").description("Register and manage OpenID Connect clients"),cD=new ae("keys").description("List, rotate and revoke the signing keys");gy.command("add").description("Register a client; its secret is printed once").requiredOption("--name <name>","What the consent screen and the listing call the client").option("--redirect-uri <uri>",`An exact redirect address (repeat for up to ${u_})`,Ikt,[]).requiredOption("--scopes <list>","Comma-separated scopes the client may ask for").requiredOption("--grants <list>","Comma-separated grants the client may use").addOption(new qi("--sign-in-rule <rule>","Who may sign in to the client").choices([...fy]).makeOptionMandatory()).addOption(new qi("--consent-mode <mode>","Ask once per set of scopes, or every time").choices([...Rp])).option("--first-party","Skip the consent screen (every redirect must be https on nemar.org or a subdomain)").option("--logout-uri <uri>","The https address NEMAR tells when an account is cut off").requiredOption("--audience <audience>","The resource the client's access tokens are bound to").option("--introspection-audiences <list>","Comma-separated audiences whose servers may introspect").option("--cap-open-reservations <n>","Cap on open reservations",aD(void 0)).option("--cap-su-per-day <n>","Cap on service units reserved per day",aD(void 0)).option("--json","Print the answer as JSON (the secret included)").addHelpText("after",Lkt).action(async(e)=>{let t=e.json===!0;if(e.redirectUri.length===0){ee("Give at least one --redirect-uri.",{json:t,answered:!0});return}let n=await Tc(t,"register the client",()=>Pve({name:e.name,redirect_uris:e.redirectUri,allowed_scopes:nj(e.scopes),allowed_grants:nj(e.grants),sign_in_rule:e.signInRule,audience:e.audience,...e.firstParty?{first_party:!0}:{},...e.consentMode?{consent_mode:e.consentMode}:{},...e.logoutUri?{backchannel_logout_uri:e.logoutUri}:{},...e.introspectionAudiences?{introspection_audiences:nj(e.introspectionAudiences)}:{},...e.capOpenReservations!==void 0?{cap_open_reservations:e.capOpenReservations}:{},...e.capSuPerDay!==void 0?{cap_su_per_day:e.capSuPerDay}:{}}),"The request may have been carried out before it failed. Run `nemar admin oidc clients list` before adding again: a second add registers a second client, and its secret is the only one anybody sees.");if(!n)return;if(t){Pc(n);return}let r=rn(!1);r(`Registered ${R(n.client.client_id)} (${R(n.client.name)}).`),r(""),r(`Client secret (shown once, store it now): ${R(n.client_secret)}`),r(u.dim("It cannot be read again; only its hash is kept. Rotate it with `rotate-secret`."))});gy.command("list").description("List every client").option("--json","Print the list as JSON").addHelpText("after",qkt).action(async(e)=>{let t=e.json===!0,n=await Tc(t,"list the clients",Ive);if(!n)return;if(t){Pc(n);return}if(n.clients.length===0){console.log("No clients are registered.");return}for(let r of Mkt(n.clients))console.log(r)});gy.command("show <client_id>").description("Show one client in full").option("--json","Print the client as JSON").addHelpText("after",Ukt).action(async(e,t)=>{let n=t.json===!0,r=await Tc(n,"show the client",()=>Nve(e));if(!r)return;if(n){Pc(r);return}for(let o of Fkt(r.client))console.log(o)});gy.command("rotate-secret <client_id>").description("Make a new secret; the old one stays valid for a grace").option("--grace-hours <n>",`Hours the old secret stays valid (default ${X6}, 0 to ${py})`,aD(py)).option("--json","Print the answer as JSON (the secret included)").addHelpText("after",Bkt).action(async(e,t)=>{let n=t.json===!0,r=await Tc(n,"rotate the secret",()=>Fve(e,t.graceHours),"The request may have been carried out before it failed. Run `nemar admin oidc clients show <client_id>` to see whether a previous secret is now in its grace; rotating again makes yet another secret.");if(!r)return;if(n){Pc(r);return}let o=rn(!1);o(`Rotated the secret of ${R(r.client.client_id)} (${R(r.client.name)}).`),o(""),o(`New client secret (shown once, store it now): ${R(r.client_secret)}`),o(r.grace_hours>0?`The old secret stays valid for ${r.grace_hours} ${r.grace_hours===1?"hour":"hours"}${r.client.previous_secret_expires_at?`, until ${aa(r.client.previous_secret_expires_at)}`:""}.`:"The old secret is no longer valid.")});gy.command("disable <client_id>").description("Cut a client off (it cannot be enabled again from the CLI)").option("-y, --yes","Do not ask first").option("--json","Print the answer as JSON").addHelpText("after",Hkt).action(async(e,t)=>{let n=t.json===!0;if(!De(n))return;if(await Re(`Disable ${e}? It can no longer authenticate, and the CLI cannot enable it again.`,{yes:t.yes})!=="confirmed"){ee("Not disabled: the question was not answered yes (use --yes).",{json:n,answered:!0});return}let o=await Tc(n,"disable the client",()=>Mve(e));if(!o)return;if(n){Pc(o);return}let s=rn(!1);if(s(o.changed?`Disabled ${R(o.client.client_id)} (${R(o.client.name)}).`:`${R(o.client.client_id)} was already disabled; its status is unchanged.`),o.revoked){let{tokens:i,grants:a,codes:c}=o.revoked;s(`Revoked ${i} ${i===1?"token":"tokens"}, ${a} ${a===1?"grant":"grants"} and deleted ${c} unused ${c===1?"code":"codes"}. No logout was sent.`)}});cD.command("list").description("List the signing keys").option("--json","Print the keys as JSON").addHelpText("after",Gkt).action(async(e)=>{let t=e.json===!0,n=await Tc(t,"list the signing keys",jve);if(!n)return;if(t){Pc(n);return}if(n.keys.length===0){console.log("There are no signing keys yet. Run `nemar admin oidc keys rotate` to make them.");return}for(let r of zve(n.keys))console.log(r)});cD.command("rotate").description("Make the first signing keys, or rotate them").option("--force",`Rotate now even when the next key is under ${rD} hours old`).option("--emergency",`With --force: override the floor, for a next key under ${sD} minutes old`).option("--json","Print the answer as JSON").addHelpText("after",zkt).action(async(e)=>{let t=e.json===!0,n=await Tc(t,"rotate the signing keys",()=>Lve({force:e.force,emergency:e.emergency}),"The request may have been carried out before it failed. Run `nemar admin oidc keys list` before rotating again.");if(!n)return;if(t){Pc(n);return}let r=rn(!1),o={bootstrapped:"Made the first signing keys: a current key and a next key.",rotated:`Rotated: the next key is now current, the old current key is retired (still published for ${oD} days), and a new next key was made.`,next_created:"Made a new next key; the current key is unchanged."};r(R(o[n.action]??`Done (${n.action}).`));for(let s of zve(n.keys))console.log(s)});cD.command("revoke <kid>").description("Withdraw a retired signing key from the key set").option("-y, --yes","Do not ask first").option("--json","Print the answer as JSON").addHelpText("after",Vkt).action(async(e,t)=>{let n=t.json===!0;if(!De(n))return;if(await Re(`Revoke signing key ${e}? Tokens it signed stop verifying wherever the key set is read again (clients cache it for up to ${rj} minutes), and the CLI cannot undo it.`,{yes:t.yes})!=="confirmed"){ee("Not revoked: the question was not answered yes (use --yes).",{json:n,answered:!0});return}let o=await Tc(n,"revoke the signing key",()=>qve(e));if(!o)return;if(n){Pc(o);return}rn(!1)(o.changed?`Revoked signing key ${R(o.key.kid)}; it is no longer published.`:`Signing key ${R(o.key.kid)} was already revoked; nothing changed.`)});function Ykt(e){if(!/^[1-9][0-9]{0,15}$/.test(e))throw new Lo("an account id is a whole number from 1.");return Number(e)}hy.command("end-account <user-id>").description("End an account's grants at every client and tell the clients (owner only)").addOption(new qi("--reason <reason>","Why: the word recorded on the tokens and the logouts").choices([...my]).makeOptionMandatory()).option("-y, --yes","Do not ask first").option("--json","Print the answer as JSON").addHelpText("after",Kkt).action(async(e,t)=>{let n=t.json===!0,r;try{r=Ykt(e)}catch{ee("An account id is a whole number from 1.",{json:n,answered:!0});return}if(!De(n))return;if(await Re(Wkt(r),{yes:t.yes})!=="confirmed"){ee("Nothing was changed: the question was not answered yes (use --yes).",{json:n,answered:!0});return}let s=await Tc(n,"end the account's grants",()=>Uve(r,t.reason),"The request may have been carried out before it failed. Ending is safe to run again: a second run finds nothing live.");if(!s)return;if(n){Pc(s);return}let i=rn(!1);if(i(`Ended the OpenID Connect grants of account ${s.user_id} (${R(s.reason)}).`),i(`Tokens revoked ${s.tokens_ended}, grants ended ${s.grants_ended}, unused codes deleted ${s.codes_deleted}, logouts queued ${s.logouts_queued}.`),s.logouts_queued>0)i(u.dim("The clients are told after this step, and retried if they do not answer: see `logout-deliveries`."))});hy.command("logout-deliveries").description("List the back-channel logouts owed to clients, and what became of each").addOption(new qi("--status <status>","Only deliveries in this state").choices([...iD])).option("--limit <n>","How many to list, from 1 to 500 (default 100)",aD(500)).option("--json","Print the answer as JSON").addHelpText("after",Jkt).action(async(e)=>{let t=e.json===!0,n=await Tc(t,"list the logout deliveries",()=>Bve({status:e.status,limit:e.limit}));if(!n)return;if(t){Pc(n);return}let r=iD.map((o)=>`${o} ${n.counts[o]??0}`).join(", ");if(console.log(`All deliveries: ${r}.`),n.deliveries.length===0){console.log(e.status?`None is ${e.status}.`:"There are no deliveries.");return}for(let o of jkt(n.deliveries))console.log(o)});hy.addCommand(gy);hy.addCommand(cD);We();vo();var $p=["pass","fail","uncertain","not_reviewed","in_progress","could_not_decide","exempt","waived"],Xkt=["exempt","waived"],Nin=$p.filter((e)=>!Xkt.includes(e));var Qkt=[/\{\{[^{}]*\}\}/,/\$\{[^{}]*\}/,/[<[]\s*(?:your|insert|enter|describe|write|fill in|replace)\s+(?=[^\s<>[\]])[^<>[\]]*[>\]](?![([])/i,/FirstAuthorSurname|paperDOI/i],Zkt=/(?:19|20)\d{2}(?!\d)/u,eRt=/10\.\d{4,9}\//u,tRt=/^[\p{L}\p{M}]$/u,nRt=/(?![\t-\r])[\p{Default_Ignorable_Code_Point}\p{Cf}\p{Cc}\u2800]/gu;function sj(e){return e.replace(nRt,"")}function rRt(e,t){let n=t;while(n>0){let r=e.charCodeAt(n-1),o=n>=2?e.charCodeAt(n-2):0,i=r>=56320&&r<=57343&&o>=55296&&o<=56319?n-2:n-1;if(!tRt.test(e.slice(i,n)))break;n=i}return n}function lD(e){let t=sj(e);for(let n of t.matchAll(new RegExp(Zkt,"gu"))){let r=n.index,o=t.charAt(r-1),s=o==="-"||o==="_"?r-1:r,i=rRt(t,s);if(i<s)return t.slice(i,r+n[0].length)}return null}function uD(e){return sj(e).match(eRt)?.[0]??null}function ij(e){let t=sj(e);for(let n of Qkt){let r=t.match(n)?.[0];if(r!==void 0)return r}return null}function Yo(e,t=200){if(typeof e!=="string")return"";let r=(e.length>t*8?e.slice(0,t*8):e).normalize("NFKC").replace(/[\p{Cc}\p{Cf}\p{Cs}\p{Zl}\p{Zp}]/gu," ");for(let s=0;s<8;s++){let i=r;if(r=r.replace(/!?\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/<[^>]*>/g," ").replace(/&#?\w+;/g," ").replace(/[@#`*_~|\\<>[\]{}]/g,"").replace(/\bGH-\d+/gi,""),r===i)break}r=r.replace(/\b(?:https?|ftp|file|data|javascript):\/*\S*/gi,"(link removed)").replace(/\bwww\.\S+/gi,"(link removed)").replace(/\s+/g," ").trim();let o=Array.from(r);return o.length>t?`${o.slice(0,t-3).join("").trimEnd()}...`:r}var m_=2,cj="NEMAR PR Review";var oRt=["genuine_contribution","no_degradation","advances_revision","material_improvement","clear_title_and_description","description_not_misleading"],sRt=["no_degradation","advances_revision","material_improvement"];var Jve=["dataset_description","readme_and_changes","participants","sidecars","recordings","derivatives","sourcedata","code","other"];function Yve(e){return e.v===1?sRt:oRt}function Xve(e,t){return e[t]}function h_(e,t){return typeof t==="string"&&e.includes(t)}var iRt=["files_changed","files_read","truncated","version_before","version_after","subjects_before","subjects_after","areas","listed"],Bin=[...iRt,"description_empty","description_cut","changelog_entry","title_problem","name_problem"];function aRt(e,t){let n=e.split(".").map(Number),r=t.split(".").map(Number);for(let o=0;o<3;o++)if(n[o]!==r[o])return n[o]-r[o];return 0}var cRt={author_year:"title_author_year",doi:"title_doi",template_field:"title_template_field"},lRt={author_year:"name_author_year",doi:"name_doi",template_field:"name_template_field"};function by(e){let t={...e.criteria},n=[],r={pass:2,unknown:1,fail:0},o=(c,l,d)=>{let f=t[c];if(f!==void 0&&r[d]<r[f])t[c]=d,n.push({criterion:c,code:l,result:d})},s=(c,l)=>{if(t[c]===void 0)return;t[c]="fail",n.push({criterion:c,code:l,result:"fail"})},i=(c,l)=>{let d=t[c];if(d===void 0)return;if(r.unknown<r[d])t[c]="unknown";n.push({criterion:c,code:l,result:"unknown"})},a=e.evidence;if(a.files_changed===0)o("material_improvement","no_substantive_change","fail");if(a.version_after===null)o("advances_revision","evidence_incomplete","unknown");else if(a.version_before!==null&&aRt(a.version_after,a.version_before)<=0)o("advances_revision","version_not_advanced","fail");if(a.truncated)o("no_degradation","evidence_incomplete","unknown");if(a.areas.recordings.removed>0)o("no_degradation","data_removed","unknown");if(a.areas.dataset_description.removed+a.areas.readme_and_changes.removed+a.areas.participants.removed>0)o("no_degradation","metadata_removed","unknown");if(Jve.some((c)=>a.areas[c].removed>0))o("no_degradation","data_removed","unknown");if(a.subjects_before!==null&&a.subjects_after!==null&&a.subjects_after<a.subjects_before)o("no_degradation","data_removed","unknown");if(e.v===m_){let c=e.evidence;if(c.description_empty)s("clear_title_and_description","description_missing");if(c.changelog_entry==="not_added"||c.changelog_entry==="no_file")s("advances_revision","changes_log_missing");if(c.description_cut)o("description_not_misleading","description_cut","unknown");if(c.title_problem!==null)s("clear_title_and_description",cRt[c.title_problem]);if(c.name_problem==="unchecked")i("no_degradation","name_unchecked");else if(c.name_problem!==null)s("no_degradation",lRt[c.name_problem])}return{criteria:t,notes:n}}function uRt(e){return by(e).criteria}function lj(e){if(e.steering)return"fail";let t=uRt(e),n=Yve(e).map((r)=>Xve(t,r)??"unknown");if(n.includes("fail"))return"fail";if(n.every((r)=>r==="pass"))return"pass";return"uncertain"}var dRt=["contributor_paused"],fRt=["rate_limited","daily_limit"],Hin=[...dRt,...fRt],Qve=5;var pRt={reported:!0,declined:!0,error:!0,unreported:!0,exempt:!0,naming:!0,waived:!0},Gin=Object.keys(pRt);function Zve(e){return e.title!==null||e.name!==null&&e.name!=="unchecked"}function uj(e){return Zve({title:e.title_problem,name:e.name_problem})?"refused":"unchecked"}var mRt={genuine_contribution:"A genuine contribution, not spam",no_degradation:"Nothing is lost or broken",advances_revision:"The revision advances",material_improvement:"The dataset is materially better",clear_title_and_description:"The title and description say what changed",description_not_misleading:"The description is not misleading"},hRt={pass:"Yes",fail:"No",unknown:"Could not tell"},Cp="a NEMAR administrator",gRt={contributor_paused:`Automated review was paused for this contributor when this commit arrived. ${yy(Cp)} needs to review this one by hand.`,rate_limited:"Automated review was rate limited for this contributor when this commit arrived. That limit has since been removed. Push a new commit, or ask a NEMAR administrator to start the review.",daily_limit:"The daily limit of automated reviews had been reached when this commit arrived. That limit has since been removed. Push a new commit, or ask a NEMAR administrator to start the review."};function yy(e){return e.charAt(0).toUpperCase()+e.slice(1)}var yRt={title:"Not required: opened by a NEMAR owner or administrator",summary:"The automated review did not run on this pull request. NEMAR owners and administrators are not reviewed, and may merge without it. The title and the dataset name were checked against the naming rule, and nothing was found.",text:"Skipped is not a pass. It says the review is not required here, not that this change was reviewed. A pull request opened by anyone else is reviewed."},dj="Waived: upstream re-pull",bRt=(e)=>`The automated review does not apply to this commit. It is the head NEMAR's own tools recorded for the pull request of upstream re-pull #${e}, decided from NEMAR's record of the re-pull and not from anything this pull request says. A mirror's content is upstream's: upstream is its author and wins every conflict, so the review, which protects a dataset from a contributor's change, has no contributor to judge here. The identifier screen, BIDS validation, the version check and the daily merge cap still gate the merge.`,wRt="Skipped is not a pass. It says the review is waived for this commit, not that this change was reviewed. A commit NEMAR has not recorded for the re-pull is reviewed as any other pull request is.",fj="Recommended issues, none filed automatically",_Rt="None: no review of this commit reported findings. No review runs on it, because it is waived.",xRt="None: the review of this commit that ran before NEMAR recorded it found nothing.",vRt="Each line is something to consider raising with the upstream dataset's authors, or correcting in NEMAR's own patch release; none of them holds this pull request, and nothing was filed.",ERt={title:"Not required: opened by a NEMAR owner or administrator (naming rule waived)",summary:"The automated review did not run on this pull request. NEMAR owners and administrators are not reviewed. The title or the dataset name breaks the naming rule, and a NEMAR administrator waived the rule for this commit with an explicit override, which is recorded.",text:"Skipped is not a pass. A new commit is checked against the naming rule again, and the waiver does not carry over to it."},SRt={refused:`The naming rule found a problem with this pull request, so the review stage did not run and no model was asked. Edit the title, or the Name in dataset_description.json, as described below. A new title runs the review again as soon as it is saved, until edits have already started the review of this commit ${Qve} times, the most one commit gets, and after that a push or a NEMAR administrator's start is what runs it; a new Name is a change to the files, so push again: the review runs on the new commit.`,unchecked:"The naming rule could not check this pull request's new dataset name, so the review stage did not run and no model was asked. Fixing dataset_description.json as described below and pushing again runs the review."},Vve="The title has a citation (an author and a year, or a DOI) in it, the way a dataset is named (for example Lee2019, Lee-2019-EEG or 10.1038/s41597-020-0532-5), and the naming rule refuses one anywhere in a title. A pull request title says what the change does, such as Add three EEG recordings. Edit the title. Cite the paper in ReferencesAndLinks and the README instead.",Wve="This pull request changes the dataset's name (the Name field of dataset_description.json) to one that has a citation (an author and a year, or a DOI) in it, which the naming rule refuses anywhere in a name. Choose a name that says what the dataset is, and cite the paper in ReferencesAndLinks and the README instead.",dD={title:{author_year:Vve,doi:Vve,template_field:"The title still has an unfilled template field (such as FirstAuthorSurname, paperDOI, or a bracketed instruction). Put the real words in its place. Edit the title."},name:{author_year:Wve,doi:Wve,template_field:"This pull request changes the dataset's name (the Name field of dataset_description.json) to one with an unfilled template field. Put the real name in its place."}},kRt="This pull request changes dataset_description.json, but the dataset's name (its Name field) could not be read from it, so the name was not checked against the naming rule. Make sure the file is valid JSON and that Name is text with a visible name.",RRt="The dataset's name could not be checked against the naming rule. GitHub may not have answered, or dataset_description.json has no readable Name (it is missing, is not valid JSON, or its Name is not text or shows nothing). Start the check again once with `nemar admin pr-reviews start <dataset> <pr>`. If it says the same, fix dataset_description.json and push: the new commit is checked, and nothing can be waived until the name can be read.",$Rt={evidence_unavailable:"The changes could not be read.",stale_head:"The pull request or dataset changed while the review was starting. Check the current pull request and publication status; a new delivery may be needed.",too_large:`The change is too large for automated review. ${yy(Cp)} needs to review it.`,auth_failed:`The review service could not sign in. ${yy(Cp)} needs to fix the review service.`,model_unavailable:"The reviewing model was unavailable, or did not finish in time.",model_refused:"The reviewing model declined to review this change.",model_truncated:`The automated review used all the room it is given before it reached an answer, which a large pull request is likely to cause. Split it into smaller pull requests, for example by group of subjects or by kind of change, and open each one separately. ${yy(Cp)} can also review it by hand.`,model_invalid:"The reviewing model did not return a usable review.",report_invalid:"The review could not be read back.",dispatch_failed:"The review could not be started. Push again to re-run it.",workflow_failed:"The review job failed before it finished.",edit_limit:`Edits to the title, description or base of this pull request, and reopenings and markings as ready for review, had already started the review of this commit ${Qve} times, the most one commit gets. This latest change did not start the review again, and the earlier result no longer stands, because the text it judged may no longer be the pull request's. Push a new commit to run the review, or ask a NEMAR administrator to start the review of this commit again.`},fD={data_removed:"Data removed",metadata_removed:"Metadata removed",structure_broken:"Dataset structure broken",validation_regressed:"Validation regressed",version_not_advanced:"Version not advanced",changes_log_missing:"CHANGES entry missing",changes_log_mismatch:"CHANGES entry does not match the change",description_mismatch:"Description does not match the change",churn_only:"Formatting or churn only",no_substantive_change:"No substantive change",improvement_unclear:"Improvement unclear",evidence_incomplete:"Evidence incomplete",steering_attempt:"Text in the pull request tried to instruct the reviewer",spam:"Spam: promotional, unrelated or purposeless content, or repeated links",title_placeholder:"Title is placeholder or template text",title_not_descriptive:"Title does not say what changed",description_missing:"Description is empty",description_placeholder:"Description is placeholder text or not readable",description_misleading:"Description is misleading",description_cut:"Description is too long to read in full",title_author_year:"Title has a citation (an author and a year, or a DOI)",title_doi:"Title has a citation (an author and a year, or a DOI)",title_template_field:"Title has an unfilled template field",name_author_year:"New dataset name has a citation (an author and a year, or a DOI)",name_doi:"New dataset name has a citation (an author and a year, or a DOI)",name_template_field:"New dataset name has an unfilled template field",name_unchecked:"New dataset name could not be read",original_text_altered:"Original text changed",original_field_altered:"Original field changed",recording_replaced:"Recorded data changed",other:"Other"};function eEe(e){switch(e){case"description_missing":return"found from the pull request, not by the reviewer: a pull request needs a description of what changed";case"description_cut":return"found from the pull request, not by the reviewer: the description is longer than the reviewer reads, so whether it is misleading, or tries to instruct the reviewer, was not assessed";case"title_author_year":case"title_doi":case"title_template_field":case"name_author_year":case"name_doi":case"name_template_field":case"name_unchecked":return"found by the naming rule, not by the reviewer";default:return"found from the files, not by the reviewer"}}var Dp="An automated review of the changes in this pull request. It does not replace a NEMAR administrator, whose approval is what merges it. Where the dataset's rules require this check, the pull request cannot be merged until it passes.",p_=`No verdict was reached, so this check does not pass. ${yy(Cp)} needs to look at this pull request.`,DRt={dataset_description:"Dataset description",readme_and_changes:"README and CHANGES",participants:"Participants",sidecars:"Sidecars and tables",recordings:"Recordings and data files",derivatives:"Derivatives",sourcedata:"Source data",code:"Code",other:"Other files"},Kve={added:"added",modified:"changed",removed:"removed"};function aj(e,t,n){return`${e} ${e===1?t:n}`}function CRt(e,t=!1){let n=["**What changed**",""];if(e.files_changed===0)return n.push("No files changed.",""),n;n.push("| Area | Added | Changed | Removed |","| --- | ---: | ---: | ---: |");for(let o of Jve){let s=e.areas[o];if(s.added+s.modified+s.removed===0)continue;n.push(`| ${DRt[o]} | ${s.added} | ${s.modified} | ${s.removed} |`)}n.push("");let r=[];if(e.version_before!==null||e.version_after!==null)r.push(`Version ${e.version_before??"unknown"} to ${e.version_after??"unknown"}.`);if(e.subjects_before!==null||e.subjects_after!==null)r.push(`Subjects ${e.subjects_before??"unknown"} to ${e.subjects_after??"unknown"}.`);return r.push(t?"The full review did not run, so no file's content was read.":e.files_read===e.files_changed?`The content of all ${aj(e.files_changed,"changed file","changed files")} was read.`:`The content of ${e.files_read} of ${aj(e.files_changed,"changed file","changed files")} was read. Files not read were judged by name and type only. Recordings and other data files are stored outside git and are never read.`),n.push(r.join(" "),""),n}function ARt(e){if(e.listed.length===0)return"";let t=e.listed.map((o)=>o.path?`- ${Kve[o.status]} \`${o.path}\``:`- ${Kve[o.status]} (name not shown)`),n=e.files_changed-e.listed.length,r=n>0?`
|
|
894
|
+
provider is off.`,hy=new ae("oidc").description("Register OpenID Connect clients and manage NEMAR's signing keys (owner only; ADR 0119)"),gy=new ae("clients").description("Register and manage OpenID Connect clients"),cD=new ae("keys").description("List, rotate and revoke the signing keys");gy.command("add").description("Register a client; its secret is printed once").requiredOption("--name <name>","What the consent screen and the listing call the client").option("--redirect-uri <uri>",`An exact redirect address (repeat for up to ${u_})`,Ikt,[]).requiredOption("--scopes <list>","Comma-separated scopes the client may ask for").requiredOption("--grants <list>","Comma-separated grants the client may use").addOption(new qi("--sign-in-rule <rule>","Who may sign in to the client").choices([...fy]).makeOptionMandatory()).addOption(new qi("--consent-mode <mode>","Ask once per set of scopes, or every time").choices([...Rp])).option("--first-party","Skip the consent screen (every redirect must be https on nemar.org or a subdomain)").option("--logout-uri <uri>","The https address NEMAR tells when an account is cut off").requiredOption("--audience <audience>","The resource the client's access tokens are bound to").option("--introspection-audiences <list>","Comma-separated audiences whose servers may introspect").option("--cap-open-reservations <n>","Cap on open reservations",aD(void 0)).option("--cap-su-per-day <n>","Cap on service units reserved per day",aD(void 0)).option("--json","Print the answer as JSON (the secret included)").addHelpText("after",Lkt).action(async(e)=>{let t=e.json===!0;if(e.redirectUri.length===0){ee("Give at least one --redirect-uri.",{json:t,answered:!0});return}let n=await Tc(t,"register the client",()=>Pve({name:e.name,redirect_uris:e.redirectUri,allowed_scopes:nj(e.scopes),allowed_grants:nj(e.grants),sign_in_rule:e.signInRule,audience:e.audience,...e.firstParty?{first_party:!0}:{},...e.consentMode?{consent_mode:e.consentMode}:{},...e.logoutUri?{backchannel_logout_uri:e.logoutUri}:{},...e.introspectionAudiences?{introspection_audiences:nj(e.introspectionAudiences)}:{},...e.capOpenReservations!==void 0?{cap_open_reservations:e.capOpenReservations}:{},...e.capSuPerDay!==void 0?{cap_su_per_day:e.capSuPerDay}:{}}),"The request may have been carried out before it failed. Run `nemar admin oidc clients list` before adding again: a second add registers a second client, and its secret is the only one anybody sees.");if(!n)return;if(t){Pc(n);return}let r=rn(!1);r(`Registered ${R(n.client.client_id)} (${R(n.client.name)}).`),r(""),r(`Client secret (shown once, store it now): ${R(n.client_secret)}`),r(u.dim("It cannot be read again; only its hash is kept. Rotate it with `rotate-secret`."))});gy.command("list").description("List every client").option("--json","Print the list as JSON").addHelpText("after",qkt).action(async(e)=>{let t=e.json===!0,n=await Tc(t,"list the clients",Ive);if(!n)return;if(t){Pc(n);return}if(n.clients.length===0){console.log("No clients are registered.");return}for(let r of Mkt(n.clients))console.log(r)});gy.command("show <client_id>").description("Show one client in full").option("--json","Print the client as JSON").addHelpText("after",Ukt).action(async(e,t)=>{let n=t.json===!0,r=await Tc(n,"show the client",()=>Nve(e));if(!r)return;if(n){Pc(r);return}for(let o of Fkt(r.client))console.log(o)});gy.command("rotate-secret <client_id>").description("Make a new secret; the old one stays valid for a grace").option("--grace-hours <n>",`Hours the old secret stays valid (default ${X6}, 0 to ${py})`,aD(py)).option("--json","Print the answer as JSON (the secret included)").addHelpText("after",Bkt).action(async(e,t)=>{let n=t.json===!0,r=await Tc(n,"rotate the secret",()=>Fve(e,t.graceHours),"The request may have been carried out before it failed. Run `nemar admin oidc clients show <client_id>` to see whether a previous secret is now in its grace; rotating again makes yet another secret.");if(!r)return;if(n){Pc(r);return}let o=rn(!1);o(`Rotated the secret of ${R(r.client.client_id)} (${R(r.client.name)}).`),o(""),o(`New client secret (shown once, store it now): ${R(r.client_secret)}`),o(r.grace_hours>0?`The old secret stays valid for ${r.grace_hours} ${r.grace_hours===1?"hour":"hours"}${r.client.previous_secret_expires_at?`, until ${aa(r.client.previous_secret_expires_at)}`:""}.`:"The old secret is no longer valid.")});gy.command("disable <client_id>").description("Cut a client off (it cannot be enabled again from the CLI)").option("-y, --yes","Do not ask first").option("--json","Print the answer as JSON").addHelpText("after",Hkt).action(async(e,t)=>{let n=t.json===!0;if(!De(n))return;if(await Re(`Disable ${e}? It can no longer authenticate, and the CLI cannot enable it again.`,{yes:t.yes})!=="confirmed"){ee("Not disabled: the question was not answered yes (use --yes).",{json:n,answered:!0});return}let o=await Tc(n,"disable the client",()=>Mve(e));if(!o)return;if(n){Pc(o);return}let s=rn(!1);if(s(o.changed?`Disabled ${R(o.client.client_id)} (${R(o.client.name)}).`:`${R(o.client.client_id)} was already disabled; its status is unchanged.`),o.revoked){let{tokens:i,grants:a,codes:c}=o.revoked;s(`Revoked ${i} ${i===1?"token":"tokens"}, ${a} ${a===1?"grant":"grants"} and deleted ${c} unused ${c===1?"code":"codes"}. No logout was sent.`)}});cD.command("list").description("List the signing keys").option("--json","Print the keys as JSON").addHelpText("after",Gkt).action(async(e)=>{let t=e.json===!0,n=await Tc(t,"list the signing keys",jve);if(!n)return;if(t){Pc(n);return}if(n.keys.length===0){console.log("There are no signing keys yet. Run `nemar admin oidc keys rotate` to make them.");return}for(let r of zve(n.keys))console.log(r)});cD.command("rotate").description("Make the first signing keys, or rotate them").option("--force",`Rotate now even when the next key is under ${rD} hours old`).option("--emergency",`With --force: override the floor, for a next key under ${sD} minutes old`).option("--json","Print the answer as JSON").addHelpText("after",zkt).action(async(e)=>{let t=e.json===!0,n=await Tc(t,"rotate the signing keys",()=>Lve({force:e.force,emergency:e.emergency}),"The request may have been carried out before it failed. Run `nemar admin oidc keys list` before rotating again.");if(!n)return;if(t){Pc(n);return}let r=rn(!1),o={bootstrapped:"Made the first signing keys: a current key and a next key.",rotated:`Rotated: the next key is now current, the old current key is retired (still published for ${oD} days), and a new next key was made.`,next_created:"Made a new next key; the current key is unchanged."};r(R(o[n.action]??`Done (${n.action}).`));for(let s of zve(n.keys))console.log(s)});cD.command("revoke <kid>").description("Withdraw a retired signing key from the key set").option("-y, --yes","Do not ask first").option("--json","Print the answer as JSON").addHelpText("after",Vkt).action(async(e,t)=>{let n=t.json===!0;if(!De(n))return;if(await Re(`Revoke signing key ${e}? Tokens it signed stop verifying wherever the key set is read again (clients cache it for up to ${rj} minutes), and the CLI cannot undo it.`,{yes:t.yes})!=="confirmed"){ee("Not revoked: the question was not answered yes (use --yes).",{json:n,answered:!0});return}let o=await Tc(n,"revoke the signing key",()=>qve(e));if(!o)return;if(n){Pc(o);return}rn(!1)(o.changed?`Revoked signing key ${R(o.key.kid)}; it is no longer published.`:`Signing key ${R(o.key.kid)} was already revoked; nothing changed.`)});function Ykt(e){if(!/^[1-9][0-9]{0,15}$/.test(e))throw new Lo("an account id is a whole number from 1.");return Number(e)}hy.command("end-account <user-id>").description("End an account's grants at every client and tell the clients (owner only)").addOption(new qi("--reason <reason>","Why: the word recorded on the tokens and the logouts").choices([...my]).makeOptionMandatory()).option("-y, --yes","Do not ask first").option("--json","Print the answer as JSON").addHelpText("after",Kkt).action(async(e,t)=>{let n=t.json===!0,r;try{r=Ykt(e)}catch{ee("An account id is a whole number from 1.",{json:n,answered:!0});return}if(!De(n))return;if(await Re(Wkt(r),{yes:t.yes})!=="confirmed"){ee("Nothing was changed: the question was not answered yes (use --yes).",{json:n,answered:!0});return}let s=await Tc(n,"end the account's grants",()=>Uve(r,t.reason),"The request may have been carried out before it failed. Ending is safe to run again: a second run finds nothing live.");if(!s)return;if(n){Pc(s);return}let i=rn(!1);if(i(`Ended the OpenID Connect grants of account ${s.user_id} (${R(s.reason)}).`),i(`Tokens revoked ${s.tokens_ended}, grants ended ${s.grants_ended}, unused codes deleted ${s.codes_deleted}, logouts queued ${s.logouts_queued}.`),s.logouts_queued>0)i(u.dim("The clients are told after this step, and retried if they do not answer: see `logout-deliveries`."))});hy.command("logout-deliveries").description("List the back-channel logouts owed to clients, and what became of each").addOption(new qi("--status <status>","Only deliveries in this state").choices([...iD])).option("--limit <n>","How many to list, from 1 to 500 (default 100)",aD(500)).option("--json","Print the answer as JSON").addHelpText("after",Jkt).action(async(e)=>{let t=e.json===!0,n=await Tc(t,"list the logout deliveries",()=>Bve({status:e.status,limit:e.limit}));if(!n)return;if(t){Pc(n);return}let r=iD.map((o)=>`${o} ${n.counts[o]??0}`).join(", ");if(console.log(`All deliveries: ${r}.`),n.deliveries.length===0){console.log(e.status?`None is ${e.status}.`:"There are no deliveries.");return}for(let o of jkt(n.deliveries))console.log(o)});hy.addCommand(gy);hy.addCommand(cD);We();vo();var $p=["pass","fail","uncertain","not_reviewed","in_progress","could_not_decide","exempt","waived"],Xkt=["exempt","waived"],Nin=$p.filter((e)=>!Xkt.includes(e));var Qkt=[/\{\{[^{}]*\}\}/,/\$\{[^{}]*\}/,/[<[]\s*(?:your|insert|enter|describe|write|fill in|replace)\s+(?=[^\s<>[\]])[^<>[\]]*[>\]](?![([])/i,/FirstAuthorSurname|paperDOI/i],Zkt=/(?:19|20)\d{2}(?!\d)/u,eRt=/10\.\d{4,9}\//u,tRt=/^[\p{L}\p{M}]$/u,nRt=/(?![\t-\r])[\p{Default_Ignorable_Code_Point}\p{Cf}\p{Cc}\u2800]/gu;function sj(e){return e.replace(nRt,"")}function rRt(e,t){let n=t;while(n>0){let r=e.charCodeAt(n-1),o=n>=2?e.charCodeAt(n-2):0,i=r>=56320&&r<=57343&&o>=55296&&o<=56319?n-2:n-1;if(!tRt.test(e.slice(i,n)))break;n=i}return n}function lD(e){let t=sj(e);for(let n of t.matchAll(new RegExp(Zkt,"gu"))){let r=n.index,o=t.charAt(r-1),s=o==="-"||o==="_"?r-1:r,i=rRt(t,s);if(i<s)return t.slice(i,r+n[0].length)}return null}function uD(e){return sj(e).match(eRt)?.[0]??null}function ij(e){let t=sj(e);for(let n of Qkt){let r=t.match(n)?.[0];if(r!==void 0)return r}return null}function Yo(e,t=200){if(typeof e!=="string")return"";let r=(e.length>t*8?e.slice(0,t*8):e).normalize("NFKC").replace(/[\p{Cc}\p{Cf}\p{Cs}\p{Zl}\p{Zp}]/gu," ");for(let s=0;s<8;s++){let i=r;if(r=r.replace(/!?\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/<[^>]*>/g," ").replace(/&#?\w+;/g," ").replace(/[@#`*_~|\\<>[\]{}]/g,"").replace(/\bGH-\d+/gi,""),r===i)break}r=r.replace(/\b(?:https?|ftp|file|data|javascript):\/*\S*/gi,"(link removed)").replace(/\bwww\.\S+/gi,"(link removed)").replace(/\s+/g," ").trim();let o=Array.from(r);return o.length>t?`${o.slice(0,t-3).join("").trimEnd()}...`:r}var m_=2,cj="NEMAR PR Review";var oRt=["genuine_contribution","no_degradation","advances_revision","material_improvement","clear_title_and_description","description_not_misleading"],sRt=["no_degradation","advances_revision","material_improvement"];var Jve=["dataset_description","readme_and_changes","participants","sidecars","recordings","derivatives","sourcedata","code","other"];function Yve(e){return e.v===1?sRt:oRt}function Xve(e,t){return e[t]}function h_(e,t){return typeof t==="string"&&e.includes(t)}var iRt=["files_changed","files_read","truncated","version_before","version_after","subjects_before","subjects_after","areas","listed"],Bin=[...iRt,"description_empty","description_cut","changelog_entry","title_problem","name_problem"];function aRt(e,t){let n=e.split(".").map(Number),r=t.split(".").map(Number);for(let o=0;o<3;o++)if(n[o]!==r[o])return n[o]-r[o];return 0}var cRt={author_year:"title_author_year",doi:"title_doi",template_field:"title_template_field"},lRt={author_year:"name_author_year",doi:"name_doi",template_field:"name_template_field"};function by(e){let t={...e.criteria},n=[],r={pass:2,unknown:1,fail:0},o=(c,l,d)=>{let f=t[c];if(f!==void 0&&r[d]<r[f])t[c]=d,n.push({criterion:c,code:l,result:d})},s=(c,l)=>{if(t[c]===void 0)return;t[c]="fail",n.push({criterion:c,code:l,result:"fail"})},i=(c,l)=>{let d=t[c];if(d===void 0)return;if(r.unknown<r[d])t[c]="unknown";n.push({criterion:c,code:l,result:"unknown"})},a=e.evidence;if(a.files_changed===0)o("material_improvement","no_substantive_change","fail");if(a.version_after===null)o("advances_revision","evidence_incomplete","unknown");else if(a.version_before!==null&&aRt(a.version_after,a.version_before)<=0)o("advances_revision","version_not_advanced","fail");if(a.truncated)o("no_degradation","evidence_incomplete","unknown");if(a.areas.recordings.removed>0)o("no_degradation","data_removed","unknown");if(a.areas.dataset_description.removed+a.areas.readme_and_changes.removed+a.areas.participants.removed>0)o("no_degradation","metadata_removed","unknown");if(Jve.some((c)=>a.areas[c].removed>0))o("no_degradation","data_removed","unknown");if(a.subjects_before!==null&&a.subjects_after!==null&&a.subjects_after<a.subjects_before)o("no_degradation","data_removed","unknown");if(e.v===m_){let c=e.evidence;if(c.description_empty)s("clear_title_and_description","description_missing");if(c.changelog_entry==="not_added"||c.changelog_entry==="no_file")s("advances_revision","changes_log_missing");if(c.description_cut)o("description_not_misleading","description_cut","unknown");if(c.title_problem!==null)s("clear_title_and_description",cRt[c.title_problem]);if(c.name_problem==="unchecked")i("no_degradation","name_unchecked");else if(c.name_problem!==null)s("no_degradation",lRt[c.name_problem])}return{criteria:t,notes:n}}function uRt(e){return by(e).criteria}function lj(e){if(e.steering)return"fail";let t=uRt(e),n=Yve(e).map((r)=>Xve(t,r)??"unknown");if(n.includes("fail"))return"fail";if(n.every((r)=>r==="pass"))return"pass";return"uncertain"}var dRt=["contributor_paused"],fRt=["rate_limited","daily_limit"],Hin=[...dRt,...fRt],Qve=5;var pRt={reported:!0,declined:!0,error:!0,unreported:!0,exempt:!0,naming:!0,waived:!0},Gin=Object.keys(pRt);function Zve(e){return e.title!==null||e.name!==null&&e.name!=="unchecked"}function uj(e){return Zve({title:e.title_problem,name:e.name_problem})?"refused":"unchecked"}var mRt={genuine_contribution:"A genuine contribution, not spam",no_degradation:"Nothing is lost or broken",advances_revision:"The revision advances",material_improvement:"The dataset is materially better",clear_title_and_description:"The title and description say what changed",description_not_misleading:"The description is not misleading"},hRt={pass:"Yes",fail:"No",unknown:"Could not tell"},Cp="a NEMAR administrator",gRt={contributor_paused:`Automated review was paused for this contributor when this commit arrived. ${yy(Cp)} needs to review this one by hand.`,rate_limited:"Automated review was rate limited for this contributor when this commit arrived. That limit has since been removed. Push a new commit, or ask a NEMAR administrator to start the review.",daily_limit:"The daily limit of automated reviews had been reached when this commit arrived. That limit has since been removed. Push a new commit, or ask a NEMAR administrator to start the review."};function yy(e){return e.charAt(0).toUpperCase()+e.slice(1)}var yRt={title:"Explicit override: no naming violation",summary:"This explicit administrative naming-override operation did not run an automated review. The title and the dataset name were checked against the naming rule, and nothing was found.",text:"Skipped is not a pass: this operation did not review the change. Ordinary review deliveries and starts apply regardless of author role."},dj="Waived: upstream re-pull",bRt=(e)=>`The automated review does not apply to this commit. It is the head NEMAR's own tools recorded for the pull request of upstream re-pull #${e}, decided from NEMAR's record of the re-pull and not from anything this pull request says. A mirror's content is upstream's: upstream is its author and wins every conflict, so the review, which protects a dataset from a contributor's change, has no contributor to judge here. The identifier screen, BIDS validation, the version check and the daily merge cap still gate the merge.`,wRt="Skipped is not a pass. It says the review is waived for this commit, not that this change was reviewed. A commit NEMAR has not recorded for the re-pull is reviewed as any other pull request is.",fj="Recommended issues, none filed automatically",_Rt="None: no review of this commit reported findings. No review runs on it, because it is waived.",xRt="None: the review of this commit that ran before NEMAR recorded it found nothing.",vRt="Each line is something to consider raising with the upstream dataset's authors, or correcting in NEMAR's own patch release; none of them holds this pull request, and nothing was filed.",ERt={title:"Explicit override: naming rule waived",summary:"This explicit administrative override did not run an automated review. The title or the dataset name breaks the naming rule, and a NEMAR administrator waived the rule for this commit with an explicit override, which is recorded.",text:"Skipped is not a pass. The waiver applies only to this commit and does not suppress ordinary review deliveries or starts."},SRt={refused:`The naming rule found a problem with this pull request, so the review stage did not run and no model was asked. Edit the title, or the Name in dataset_description.json, as described below. A new title runs the review again as soon as it is saved, until edits have already started the review of this commit ${Qve} times, the most one commit gets, and after that a push or a NEMAR administrator's start is what runs it; a new Name is a change to the files, so push again: the review runs on the new commit.`,unchecked:"The naming rule could not check this pull request's new dataset name, so the review stage did not run and no model was asked. Fixing dataset_description.json as described below and pushing again runs the review."},Vve="The title has a citation (an author and a year, or a DOI) in it, the way a dataset is named (for example Lee2019, Lee-2019-EEG or 10.1038/s41597-020-0532-5), and the naming rule refuses one anywhere in a title. A pull request title says what the change does, such as Add three EEG recordings. Edit the title. Cite the paper in ReferencesAndLinks and the README instead.",Wve="This pull request changes the dataset's name (the Name field of dataset_description.json) to one that has a citation (an author and a year, or a DOI) in it, which the naming rule refuses anywhere in a name. Choose a name that says what the dataset is, and cite the paper in ReferencesAndLinks and the README instead.",dD={title:{author_year:Vve,doi:Vve,template_field:"The title still has an unfilled template field (such as FirstAuthorSurname, paperDOI, or a bracketed instruction). Put the real words in its place. Edit the title."},name:{author_year:Wve,doi:Wve,template_field:"This pull request changes the dataset's name (the Name field of dataset_description.json) to one with an unfilled template field. Put the real name in its place."}},kRt="This pull request changes dataset_description.json, but the dataset's name (its Name field) could not be read from it, so the name was not checked against the naming rule. Make sure the file is valid JSON and that Name is text with a visible name.",RRt="The dataset's name could not be checked against the naming rule. GitHub may not have answered, or dataset_description.json has no readable Name (it is missing, is not valid JSON, or its Name is not text or shows nothing). Start the check again once with `nemar admin pr-reviews start <dataset> <pr>`. If it says the same, fix dataset_description.json and push: the new commit is checked, and nothing can be waived until the name can be read.",$Rt={evidence_unavailable:"The changes could not be read.",stale_head:"The pull request or dataset changed while the review was starting. Check the current pull request and publication status; a new delivery may be needed.",too_large:`The change is too large for automated review. ${yy(Cp)} needs to review it.`,auth_failed:`The review service could not sign in. ${yy(Cp)} needs to fix the review service.`,model_unavailable:"The reviewing model was unavailable, or did not finish in time.",model_refused:"The reviewing model declined to review this change.",model_truncated:`The automated review used all the room it is given before it reached an answer, which a large pull request is likely to cause. Split it into smaller pull requests, for example by group of subjects or by kind of change, and open each one separately. ${yy(Cp)} can also review it by hand.`,model_invalid:"The reviewing model did not return a usable review.",report_invalid:"The review could not be read back.",dispatch_failed:"The review could not be started. Push again to re-run it.",workflow_failed:"The review job failed before it finished.",edit_limit:`Edits to the title, description or base of this pull request, and reopenings and markings as ready for review, had already started the review of this commit ${Qve} times, the most one commit gets. This latest change did not start the review again, and the earlier result no longer stands, because the text it judged may no longer be the pull request's. Push a new commit to run the review, or ask a NEMAR administrator to start the review of this commit again.`},fD={data_removed:"Data removed",metadata_removed:"Metadata removed",structure_broken:"Dataset structure broken",validation_regressed:"Validation regressed",version_not_advanced:"Version not advanced",changes_log_missing:"CHANGES entry missing",changes_log_mismatch:"CHANGES entry does not match the change",description_mismatch:"Description does not match the change",churn_only:"Formatting or churn only",no_substantive_change:"No substantive change",improvement_unclear:"Improvement unclear",evidence_incomplete:"Evidence incomplete",steering_attempt:"Text in the pull request tried to instruct the reviewer",spam:"Spam: promotional, unrelated or purposeless content, or repeated links",title_placeholder:"Title is placeholder or template text",title_not_descriptive:"Title does not say what changed",description_missing:"Description is empty",description_placeholder:"Description is placeholder text or not readable",description_misleading:"Description is misleading",description_cut:"Description is too long to read in full",title_author_year:"Title has a citation (an author and a year, or a DOI)",title_doi:"Title has a citation (an author and a year, or a DOI)",title_template_field:"Title has an unfilled template field",name_author_year:"New dataset name has a citation (an author and a year, or a DOI)",name_doi:"New dataset name has a citation (an author and a year, or a DOI)",name_template_field:"New dataset name has an unfilled template field",name_unchecked:"New dataset name could not be read",original_text_altered:"Original text changed",original_field_altered:"Original field changed",recording_replaced:"Recorded data changed",other:"Other"};function eEe(e){switch(e){case"description_missing":return"found from the pull request, not by the reviewer: a pull request needs a description of what changed";case"description_cut":return"found from the pull request, not by the reviewer: the description is longer than the reviewer reads, so whether it is misleading, or tries to instruct the reviewer, was not assessed";case"title_author_year":case"title_doi":case"title_template_field":case"name_author_year":case"name_doi":case"name_template_field":case"name_unchecked":return"found by the naming rule, not by the reviewer";default:return"found from the files, not by the reviewer"}}var Dp="An automated review of the changes in this pull request. It does not replace a NEMAR administrator, whose approval is what merges it. Where the dataset's rules require this check, the pull request cannot be merged until it passes.",p_=`No verdict was reached, so this check does not pass. ${yy(Cp)} needs to look at this pull request.`,DRt={dataset_description:"Dataset description",readme_and_changes:"README and CHANGES",participants:"Participants",sidecars:"Sidecars and tables",recordings:"Recordings and data files",derivatives:"Derivatives",sourcedata:"Source data",code:"Code",other:"Other files"},Kve={added:"added",modified:"changed",removed:"removed"};function aj(e,t,n){return`${e} ${e===1?t:n}`}function CRt(e,t=!1){let n=["**What changed**",""];if(e.files_changed===0)return n.push("No files changed.",""),n;n.push("| Area | Added | Changed | Removed |","| --- | ---: | ---: | ---: |");for(let o of Jve){let s=e.areas[o];if(s.added+s.modified+s.removed===0)continue;n.push(`| ${DRt[o]} | ${s.added} | ${s.modified} | ${s.removed} |`)}n.push("");let r=[];if(e.version_before!==null||e.version_after!==null)r.push(`Version ${e.version_before??"unknown"} to ${e.version_after??"unknown"}.`);if(e.subjects_before!==null||e.subjects_after!==null)r.push(`Subjects ${e.subjects_before??"unknown"} to ${e.subjects_after??"unknown"}.`);return r.push(t?"The full review did not run, so no file's content was read.":e.files_read===e.files_changed?`The content of all ${aj(e.files_changed,"changed file","changed files")} was read.`:`The content of ${e.files_read} of ${aj(e.files_changed,"changed file","changed files")} was read. Files not read were judged by name and type only. Recordings and other data files are stored outside git and are never read.`),n.push(r.join(" "),""),n}function ARt(e){if(e.listed.length===0)return"";let t=e.listed.map((o)=>o.path?`- ${Kve[o.status]} \`${o.path}\``:`- ${Kve[o.status]} (name not shown)`),n=e.files_changed-e.listed.length,r=n>0?`
|
|
895
895
|
- and ${aj(n,"more file","more files")}, counted above`:"";return`<details><summary>Changed files (${e.listed.length} of ${e.files_changed})</summary>
|
|
896
896
|
|
|
897
897
|
${t.join(`
|
|
@@ -903,7 +903,7 @@ ${t.join(`
|
|
|
903
903
|
`)}}function hj(e){if(e.v!==m_)return[];let t=[];if(e.evidence.title_problem!==null)t.push(dD.title[e.evidence.title_problem]);let n=e.evidence.name_problem;if(n==="unchecked")t.push(kRt);else if(n!==null)t.push(dD.name[n]);return t}function IRt(e){let t=[];if(e.title!==null)t.push(dD.title[e.title]);if(e.name!==null&&e.name!=="unchecked")t.push(dD.name[e.name]);if(e.name==="unchecked")return{title:"Could not decide: the naming rule was not checked",summary:[...t.length>0?["The naming rule also found a problem in what it could read.","",...t.map((r)=>`- ${r}`),""]:[],RRt].join(`
|
|
904
904
|
`),text:`${p_}
|
|
905
905
|
|
|
906
|
-
${Dp}`};let n="The only way past the naming rule without a change is an explicit override by a NEMAR administrator: `nemar admin pr-reviews allow <dataset> <pr> --admin --reason <why>`, which is recorded with the reason and applies to this commit only.";if(Zve(e))return{title:"Needs changes: the naming rule",summary:["The
|
|
906
|
+
${Dp}`};let n="The only way past the naming rule without a change is an explicit override by a NEMAR administrator: `nemar admin pr-reviews allow <dataset> <pr> --admin --reason <why>`, which is recorded with the reason and applies to this commit only.";if(Zve(e))return{title:"Needs changes: the naming rule",summary:["The naming rule found a problem while evaluating the explicit administrative override. This operation did not run an automated review.","",...t.map((r)=>`- ${r}`)].join(`
|
|
907
907
|
`),text:`${n}
|
|
908
908
|
|
|
909
909
|
${Dp}`};return{title:"Could not decide: the naming rule was not checked",summary:p_,text:`${p_}
|
|
@@ -919,7 +919,7 @@ ${p.join(`
|
|
|
919
919
|
|
|
920
920
|
`);return{title:l,summary:d.join(`
|
|
921
921
|
`),text:m}}_c();Ve();wn();import{spawn as FRt}from"child_process";function MRt(e,t){if(e==="darwin")return{command:"open",args:[t]};if(e==="win32")return{command:"cmd",args:["/c","start","",t]};if(e==="linux")return{command:"xdg-open",args:[t]};return null}function wy(e){if(process.env.NEMAR_NO_BROWSER==="1")return!1;let t=MRt(process.platform,e);if(!t)return!1;try{let n=FRt(t.command,t.args,{stdio:"ignore",detached:!0});return n.on("error",(r)=>{Tn(`openInBrowser: ${t.command} failed: ${r instanceof Error?r.message:r}`)}),n.unref(),!0}catch(n){return Tn(`openInBrowser: could not spawn ${t.command}: ${n instanceof Error?n.message:n}`),!1}}Or();wn();zt();var Es="nemarDatasets",Ap=20000,tEe=15000;function mD(e,t){return`https://github.com/${Es}/${e}/pull/${t}`}function rEe(e,t){return`gh pr review ${t} --repo ${Es}/${e} --approve`}function Sn(e=process.env){let t=e.NEMAR_GITHUB_API_URL?.trim();if(!t)return"https://api.github.com";try{let n=new URL(t),r=["127.0.0.1","localhost","[::1]"].includes(n.hostname);if(n.protocol==="http:"&&r)return t.replace(/\/+$/,"")}catch{}throw Error("NEMAR_GITHUB_API_URL is set but is not an http://127.0.0.1, http://localhost or http://[::1] address. It is only for tests, so it is refused rather than ignored; unset it to use GitHub.")}async function $i(e=process.env,t=A){let n=e.GH_TOKEN?.trim();if(n)return{ok:!0,token:n,source:"GH_TOKEN"};try{let{stdout:r,exitCode:o,stderr:s,timedOut:i}=await t(["gh","auth","token","--hostname","github.com"],{unsetEnv:["GH_TOKEN","GITHUB_TOKEN"],timeout:tEe,sensitiveOutput:!0});if(i)return{ok:!1,reason:`gh did not answer within ${tEe/1000} seconds (a locked keyring waiting for a prompt?). Set GH_TOKEN, or run 'gh auth status'.`};if(o===0&&r.trim())return{ok:!0,token:r.trim(),source:"gh"};return{ok:!1,reason:`gh has no signed-in account for github.com (${s.trim().split(`
|
|
922
|
-
`)[0]||`exit ${o}`}).`}}catch(r){let o=r instanceof Error?r.message:String(r);return{ok:!1,reason:o.includes("ENOENT")||o.includes("not found")?"The GitHub CLI (gh) is not installed.":`gh could not be run: ${o}`}}}function Op(e){return{Authorization:`Bearer ${e}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"nemar-cli pr-reviews","Content-Type":"application/json"}}async function hD(e,t=Sn()){let n;try{n=await fetch(`${t}/user`,{headers:Op(e),signal:AbortSignal.timeout(Ap)})}catch(i){return{ok:!1,kind:"unreachable",reason:`GitHub could not be reached (${i instanceof Error?i.message:String(i)}).`}}if(n.status===401)return{ok:!1,kind:"rejected",reason:"GitHub rejected this token."};if(!n.ok){let i=await n.text().catch(()=>"");if(n.status===403&&!/rate limit|abuse/i.test(i))return{ok:!1,kind:"not_a_person",reason:"This token does not belong to a GitHub user (an app or workflow token cannot approve for you)."};return{ok:!1,kind:"unreachable",reason:`GitHub answered HTTP ${n.status} when asked whose token this is. Try again in a moment.`}}let r=Symbol("unreadable"),o=await n.json().catch(()=>r);if(o===r)return{ok:!1,kind:"unreachable",reason:"GitHub answered, but the answer could not be read when asked whose token this is. Try again in a moment."};let s=o;if(typeof s?.login!=="string"||typeof s.id!=="number"||s.type!=="User"||s.login.endsWith("[bot]"))return{ok:!1,kind:"not_a_person",reason:"This token does not belong to a GitHub user, so it cannot approve for you."};return{ok:!0,user:{login:s.login,id:s.id}}}function gD(e,t){if(!e)return"unlinked";return e.toLowerCase()===t.toLowerCase()?"match":"mismatch"}function _y(e,t){let n=typeof t==="object"&&t!==null&&"message"in t?Yo(t.message,160):"";return n?`${n} (HTTP ${e})`:`GitHub answered HTTP ${e}.`}async function Hs(e,t,n,r=Sn()){let o;try{o=await fetch(`${r}/repos/${Es}/${t}/pulls/${n}`,{headers:Op(e),signal:AbortSignal.timeout(Ap)})}catch(d){return{ok:!1,status:0,reason:`GitHub could not be reached (${d instanceof Error?d.message:String(d)}).`}}let s=await o.json().catch(()=>null);if(!o.ok)return{ok:!1,status:o.status,reason:o.status===404?`${Es}/${t} has no pull request #${n}, or your GitHub account cannot see it.`:_y(o.status,s)};let i=s?.head,a=s?.base,c=s?.user;if(typeof i?.sha!=="string"||!/^[0-9a-f]{40}$/.test(i.sha))return{ok:!1,status:o.status,reason:"GitHub's answer had no head commit."};let l=(d)=>typeof d?.full_name==="string"?d.full_name:null;return{ok:!0,value:{state:s?.merged===!0?"merged":s?.state==="open"?"open":"closed",draft:s?.draft===!0,baseRef:typeof a?.ref==="string"?a.ref:"",headRef:typeof i.ref==="string"?i.ref:"",headSha:i.sha,headRepo:l(i.repo),baseRepo:l(a?.repo),authorLogin:typeof c?.login==="string"?c.login:"",mergeableState:typeof s?.mergeable_state==="string"?s.mergeable_state:"unknown",mergeCommitSha:typeof s?.merge_commit_sha==="string"&&/^[0-9a-f]{40}$/.test(s.merge_commit_sha)?s.merge_commit_sha:null}}}async function yj(e,t,n,r=Sn()){let o;try{o=await fetch(`${r}/repos/${Es}/${t}${n}`,{headers:Op(e),signal:AbortSignal.timeout(Ap)})}catch(a){return{ok:!1,status:0,reason:`GitHub could not be reached (${a instanceof Error?a.message:String(a)}).`}}let s=Symbol("unreadable"),i=await o.json().catch(()=>s);if(!o.ok)return{ok:!1,status:o.status,reason:_y(o.status,i)};if(i===s)return{ok:!1,status:o.status,reason:"GitHub's answer could not be read."};return{ok:!0,value:i}}function oEe(e){if(e.state==="merged")return"This pull request is already merged.";if(e.state==="closed")return"This pull request is closed.";if(e.baseRef!=="main")return`This pull request targets ${Yo(e.baseRef,40)||"another branch"}, not main. The review queue covers pull requests to main.`;if(e.draft)return"This pull request is a draft. Ask the author to mark it ready first.";return null}function jRt(e){return typeof e==="string"&&$p.includes(e)?e:null}var LRt=["pass","fail","uncertain"];function yD(e,t){let n=typeof e==="object"&&e!==null?e:null;if(!n)return{ok:!1,why:"the NEMAR API sent no review"};let r=jRt(n.verdict);if(r===null)return{ok:!1,why:"the NEMAR API sent a verdict this version of the CLI does not know; update the CLI"};if(n.head_sha!==t)return{ok:!1,why:"the NEMAR API answered about a different commit than GitHub reports"};let o=n.stale_verdict??null;if(o!==null&&!LRt.includes(o))return{ok:!1,why:"the NEMAR API sent a review this version of the CLI cannot read"};let s=n.review_current??null;if(s!==null&&typeof s!=="boolean")return{ok:!1,why:"the NEMAR API sent a review this version of the CLI cannot read"};let i=n.author?.standing,a=i?.paused===!0?`The contributor's pull requests are not reviewed automatically (paused${i.because==="maintainer"?" by an administrator's block":""}).`:null;return{ok:!0,verdict:r,detail:typeof n.detail==="string"?n.detail:null,staleVerdict:o,reviewCurrent:s,contributorNote:a,outcome:s===!0?n.review?.outcome??null:null}}function bD(e){if(e.unread)return{kind:"needs_force",reason:`The automated review could not be read (${e.unread}), so its verdict is unknown. Pass --force to approve without it.`};switch(e.verdict){case"pass":return{kind:"proceed"};case"fail":return{kind:"needs_force",reason:"The automated review says this pull request needs changes. Read it with `show`, and pass --force to approve it anyway."};case"in_progress":return{kind:"needs_force",reason:"The automated review of this commit is still running. Wait for it, or pass --force to approve without it."};case"uncertain":return{kind:"confirm",warning:"The automated review could not decide whether this is a good change."};case"could_not_decide":return{kind:"confirm",warning:"The automated review ended without a verdict."};case"not_reviewed":return{kind:"confirm",warning:e.staleVerdict===null?"The automated review has not read this commit.":`The automated review read a different commit of this pull request (it said: ${e.staleVerdict}), not this one.`};case"exempt":return{kind:"confirm",warning:`The automated review did not run on this commit: a NEMAR owner or administrator opened this pull request, and they are not reviewed.${e.staleVerdict===null?"":` An earlier commit of it was reviewed and read ${e.staleVerdict}.`}`};case"waived":return{kind:"confirm",warning:"The automated review is waived for this commit: NEMAR's record says it is an upstream re-pull's own head, and a mirror's content is upstream's. What a review of it found, if anything, is a recommendation and holds nothing."}}}function wD(e){return{ok:!1,outcome:"unknown",status:0,reason:`GitHub did not answer (${e instanceof Error?e.message:String(e)}).`}}async function bj(e,t,n,r,o,s,i=Sn()){let a;try{a=await fetch(`${i}/repos/${Es}/${t}/pulls/${n}/reviews`,{method:"POST",headers:Op(e),body:JSON.stringify({commit_id:r,event:"APPROVE",body:s}),signal:AbortSignal.timeout(Ap)})}catch(d){return wD(d)}let c=await a.json().catch(()=>null);if(!a.ok)return{ok:!1,outcome:a.status>=500?"unknown":"refused",status:a.status,reason:_y(a.status,c)};if(typeof c?.state!=="string")return{ok:!1,outcome:"unknown",status:a.status,reason:`GitHub answered HTTP ${a.status}, but its answer could not be read.`};let l=typeof c.user?.login==="string"?c.user.login:"";if(c.state!=="APPROVED"||c.commit_id!==r||l.toLowerCase()!==o.toLowerCase()){let d=[c.state!=="APPROVED"?`state ${Yo(c.state,20)}`:"",l.toLowerCase()!==o.toLowerCase()?`by @${Yo(l,40)||"?"}`:"",c.commit_id!==r?`commit ${typeof c.commit_id==="string"?Yo(c.commit_id,40).slice(0,7):"?"}`:""].filter(Boolean);return{ok:!1,outcome:"different",status:a.status,reason:`GitHub recorded a review, but not the approval that was asked for (${d.join(", ")}).`}}return{ok:!0}}async function sEe(e,t,n,r,o=Sn()){let s;try{s=await fetch(`${o}/repos/${Es}/${t}/issues/${n}/comments`,{method:"POST",headers:Op(e),body:JSON.stringify({body:r}),signal:AbortSignal.timeout(Ap)})}catch(a){return wD(a)}let i=await s.json().catch(()=>null);if(!s.ok)return{ok:!1,outcome:s.status>=500?"unknown":"refused",status:s.status,reason:_y(s.status,i)};if(typeof i?.id!=="number")return{ok:!1,outcome:"unknown",status:s.status,reason:`GitHub answered HTTP ${s.status}, but its answer could not be read.`};return{ok:!0}}async function _D(e,t,n,r=Sn()){let o;try{o=await fetch(`${r}/repos/${Es}/${t}/pulls/${n}`,{method:"PATCH",headers:Op(e),body:JSON.stringify({state:"closed"}),signal:AbortSignal.timeout(Ap)})}catch(i){return wD(i)}let s=await o.json().catch(()=>null);if(!o.ok)return{ok:!1,outcome:o.status>=500?"unknown":"refused",status:o.status,reason:_y(o.status,s)};if(typeof s?.state!=="string")return{ok:!1,outcome:"unknown",status:o.status,reason:`GitHub answered HTTP ${o.status}, but its answer could not be read.`};if(s.state!=="closed")return{ok:!1,outcome:"different",status:o.status,reason:`GitHub answered, but the pull request is ${Yo(s.state,20)}, not closed.`};return{ok:!0}}var xD=["merge","squash","rebase"],qRt="clean",URt=new Map([["blocked","a required check or review is not satisfied (the BIDS validation, the version check or, where its ruleset is in force, the NEMAR PR Review); this tool names the NEMAR PR Review check, and no other, as one an owner or administrator can override in the GitHub UI, and only where its ruleset is in force, and it never uses the bypass itself"],["behind","the branch is behind main"],["dirty","it has merge conflicts"],["unstable","a check or status that is not required is not passing or has not reported, for example the automated review holding the pull request"],["draft","it is a draft"],["unknown","GitHub has not said whether it can be merged"]]);function nEe(e){return URt.get(e)??"this tool merges only a pull request GitHub reports as clean"}function xy(e){let t=e&&e.length>0?e:"unknown";if(t===qRt)return{ok:!0};return{ok:!1,why:`GitHub reports this pull request as '${pD(t)}' (${nEe(t)}), so a merge would not be attempted.`,card:`${nEe(t)} (GitHub: ${pD(t)})`,advice:t==="unknown"?"retry":"without_merge"}}function pD(e){return/^[a-z][a-z_]{0,29}$/.test(e)?e:"unrecognised"}async function Tp(e,t,n,r,o={}){let s=o.base??Sn(),i=o.sleep??((d)=>new Promise((f)=>setTimeout(f,d))),a=o.tries??5,c=r.mergeableState,l=c===null?0:1;for(;;){if(c===null){let d=await Hs(e,t,n,s);if(!d.ok)return{ok:!1,kind:"unreadable",status:d.status,reason:d.reason};if(d.value.state!=="open")return{ok:!1,kind:"closed",merged:d.value.state==="merged"};if(d.value.headSha!==r.headSha)return{ok:!1,kind:"moved"};c=d.value.mergeableState,l++}if(c!=="unknown"||l>=a)return{ok:!0,state:c};await i(1000),c=null}}function iEe(e){if(e.kind==="moved")return{ok:!1,why:"The pull request changed since it was read.",card:"the pull request changed since it was read",advice:"rerun"};if(e.kind==="closed")return{ok:!1,why:`The pull request is no longer open (it was ${e.merged?"merged":"closed"}).`,card:"the pull request is no longer open",advice:"none"};let t=e.reason.replace(/\.$/,"");return{ok:!1,why:`Could not check whether it can be merged (${t}).`,card:`could not be checked (${t})`,advice:"retry"}}async function vy(e,t,n,r,o={}){let s=await Tp(e,t,n,r,o);return s.ok?xy(s.state):iEe(s)}async function wj(e,t,n,r,o={}){let s=await vy(e,t,n,{headSha:r,mergeableState:null},o);return s.ok?s:{...s,why:`Checked again just before approving: ${s.why}`}}async function g_(e,t,n,r,o,s={}){let i=s.base??Sn(),a=await Tp(e,t,n,{headSha:r,mergeableState:null},s);if(!a.ok){if(a.kind==="moved")return{ok:!1,outcome:"not_sent",status:409,reason:"The pull request changed after it was approved, so it was not merged."};if(a.kind==="closed")return{ok:!1,outcome:"not_sent",status:409,reason:`Not merged: ${iEe(a).why} The approval stands.`};return{ok:!1,outcome:"not_sent",status:a.status,reason:`Not merged: ${a.reason} The approval stands.`}}let c=s.state==="unstable"?a.state==="unstable"?{ok:!0}:{ok:!1,why:`GitHub reports this pull request as '${pD(a.state)}', not 'unstable', so a merge over a failed BIDS validation would not be attempted.`,card:`not unstable (GitHub: ${pD(a.state)})`,advice:"none"}:xy(a.state);if(!c.ok)return{ok:!1,outcome:"not_sent",status:405,merge:c,reason:`Not merged: ${c.why} The approval stands.`};let l;try{l=await fetch(`${i}/repos/${Es}/${t}/pulls/${n}/merge`,{method:"PUT",headers:Op(e),body:JSON.stringify({sha:r,merge_method:o,...s.commit?{commit_title:s.commit.title,commit_message:s.commit.message}:{}}),signal:AbortSignal.timeout(Ap)})}catch(f){return wD(f)}let d=await l.json().catch(()=>null);if(!l.ok)return{ok:!1,outcome:l.status>=500?"unknown":"refused",status:l.status,reason:_y(l.status,d)};if(d?.merged!==!0)return{ok:!1,outcome:"unknown",status:l.status,reason:`GitHub answered HTTP ${l.status}, but did not say the pull request was merged.`};return{ok:!0}}function cEe(e){switch(e.trim().toLowerCase()){case"y":case"yes":return"approve";case"n":case"no":return"close";case"c":case"comment":return"comment";case"d":case"details":return"details";case"s":case"skip":return"skip";case"q":case"quit":return"quit";default:return null}}function lEe(e){let t=[];if(e.bids!=="pass"||e.version!=="pass")t.push(`A required check is not green (BIDS ${aEe(e.bids)}, version ${aEe(e.version)}), so GitHub would not let it merge.`);if(!e.merge.ok)t.push(e.merge.why);if(e.gate.kind==="needs_force"&&!e.force)t.push(e.gate.reason);return t.length===0?{ok:!0}:{ok:!1,reason:t.join(" ")}}function aEe(e){switch(e){case"pass":return"ok";case"fail":return"failing";case"pending":return"pending";case"missing":return"missing";default:return"unknown"}}function vD(e){return`${e.dataset_id}#${e.pr_number}`}function uEe(e,t){if(t.aborted)return Promise.resolve({aborted:!0});return new Promise((n,r)=>{let o=()=>n({aborted:!0});t.addEventListener("abort",o,{once:!0}),e.then((s)=>{t.removeEventListener("abort",o),n({aborted:!1,value:s})},(s)=>{t.removeEventListener("abort",o),r(s)})})}async function dEe(e,t,n){let r=[],o=t.now??Date.now,s=new Map,i=0,a=0,c=null;while(i<e.length){if(n.signal.aborted){c="interrupted";break}if(s.size>=n.concurrency){if(t.onWait?.({running:s.size,remaining:e.length-i}),await t.sleep(n.pollMs,n.signal),n.signal.aborted)continue;for(let[m,h]of[...s])if(o()-h.since>=n.maxHoldMs)s.delete(m);if(s.size<n.concurrency)continue;let f=await uEe(t.inProgress().catch(()=>null),n.signal);if(f.aborted)continue;let p=f.value;if(p===null){if(a++,t.onUnknown?.({count:a,max:n.maxUnknownPolls}),a>=n.maxUnknownPolls){c="unknown_polls";break}continue}a=0;for(let[m,h]of[...s]){if(p.has(m))continue;if(!t.confirmFinished){s.delete(m);continue}let g=await uEe(t.confirmFinished(h.entry).catch(()=>!1),n.signal);if(g.aborted)break;if(g.value)s.delete(m)}continue}let l=e[i++],d;try{d={answer:await t.start(l)}}catch(f){d={error:f}}if(r.push({entry:l,...d}),t.onResult(l,d),"answer"in d){if(t.isRunning(d.answer))s.set(vD(l),{entry:l,since:o()});if(t.stopAfter?.(d.answer)){c="answer";break}}else if(t.maybeRunning?.(d.error))s.set(vD(l),{entry:l,since:o()})}return{results:r,notStarted:e.slice(i),stoppedBy:c}}function fEe(e,t){return new Promise((n)=>{if(t.aborted){n();return}let r=()=>{clearTimeout(o),t.removeEventListener("abort",r),n()},o=setTimeout(r,e);t.addEventListener("abort",r,{once:!0})})}function pEe(e){if(!/^[1-9][0-9]{0,5}$/.test(e.trim()))return null;return Number(e.trim())}import{createInterface as BRt}from"readline";var ED=250;class Pp{rl;lines=[];waiting=[];output;typeAhead;ended=!1;wasInterrupted=!1;constructor(e=process.stdin,t=process.stdout,n={}){this.output=t,this.typeAhead=n.typeAhead??(e.isTTY===!0?"discard":"keep"),this.rl=BRt({input:e,output:t,terminal:e.isTTY===!0}),this.rl.on("line",(r)=>{let o=this.waiting.shift();if(o)o(r);else this.lines.push(r)}),this.rl.on("SIGINT",()=>this.interrupt()),this.rl.on("close",()=>{this.ended=!0;for(let r of this.waiting.splice(0))r(null)})}get open(){return!this.ended}get canAnswer(){return!this.wasInterrupted&&(!this.ended||this.lines.length>0)}get interrupted(){return this.wasInterrupted}interrupt(){this.wasInterrupted=!0,this.lines.length=0,this.rl.close()}ask(e){if(this.wasInterrupted)return Promise.resolve(null);let t=this.lines.shift();if(t!==void 0)return this.output.write(`${e}${t}
|
|
922
|
+
`)[0]||`exit ${o}`}).`}}catch(r){let o=r instanceof Error?r.message:String(r);return{ok:!1,reason:o.includes("ENOENT")||o.includes("not found")?"The GitHub CLI (gh) is not installed.":`gh could not be run: ${o}`}}}function Op(e){return{Authorization:`Bearer ${e}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"nemar-cli pr-reviews","Content-Type":"application/json"}}async function hD(e,t=Sn()){let n;try{n=await fetch(`${t}/user`,{headers:Op(e),signal:AbortSignal.timeout(Ap)})}catch(i){return{ok:!1,kind:"unreachable",reason:`GitHub could not be reached (${i instanceof Error?i.message:String(i)}).`}}if(n.status===401)return{ok:!1,kind:"rejected",reason:"GitHub rejected this token."};if(!n.ok){let i=await n.text().catch(()=>"");if(n.status===403&&!/rate limit|abuse/i.test(i))return{ok:!1,kind:"not_a_person",reason:"This token does not belong to a GitHub user (an app or workflow token cannot approve for you)."};return{ok:!1,kind:"unreachable",reason:`GitHub answered HTTP ${n.status} when asked whose token this is. Try again in a moment.`}}let r=Symbol("unreadable"),o=await n.json().catch(()=>r);if(o===r)return{ok:!1,kind:"unreachable",reason:"GitHub answered, but the answer could not be read when asked whose token this is. Try again in a moment."};let s=o;if(typeof s?.login!=="string"||typeof s.id!=="number"||s.type!=="User"||s.login.endsWith("[bot]"))return{ok:!1,kind:"not_a_person",reason:"This token does not belong to a GitHub user, so it cannot approve for you."};return{ok:!0,user:{login:s.login,id:s.id}}}function gD(e,t){if(!e)return"unlinked";return e.toLowerCase()===t.toLowerCase()?"match":"mismatch"}function _y(e,t){let n=typeof t==="object"&&t!==null&&"message"in t?Yo(t.message,160):"";return n?`${n} (HTTP ${e})`:`GitHub answered HTTP ${e}.`}async function Hs(e,t,n,r=Sn()){let o;try{o=await fetch(`${r}/repos/${Es}/${t}/pulls/${n}`,{headers:Op(e),signal:AbortSignal.timeout(Ap)})}catch(d){return{ok:!1,status:0,reason:`GitHub could not be reached (${d instanceof Error?d.message:String(d)}).`}}let s=await o.json().catch(()=>null);if(!o.ok)return{ok:!1,status:o.status,reason:o.status===404?`${Es}/${t} has no pull request #${n}, or your GitHub account cannot see it.`:_y(o.status,s)};let i=s?.head,a=s?.base,c=s?.user;if(typeof i?.sha!=="string"||!/^[0-9a-f]{40}$/.test(i.sha))return{ok:!1,status:o.status,reason:"GitHub's answer had no head commit."};let l=(d)=>typeof d?.full_name==="string"?d.full_name:null;return{ok:!0,value:{state:s?.merged===!0?"merged":s?.state==="open"?"open":"closed",draft:s?.draft===!0,baseRef:typeof a?.ref==="string"?a.ref:"",headRef:typeof i.ref==="string"?i.ref:"",headSha:i.sha,headRepo:l(i.repo),baseRepo:l(a?.repo),authorLogin:typeof c?.login==="string"?c.login:"",mergeableState:typeof s?.mergeable_state==="string"?s.mergeable_state:"unknown",mergeCommitSha:typeof s?.merge_commit_sha==="string"&&/^[0-9a-f]{40}$/.test(s.merge_commit_sha)?s.merge_commit_sha:null}}}async function yj(e,t,n,r=Sn()){let o;try{o=await fetch(`${r}/repos/${Es}/${t}${n}`,{headers:Op(e),signal:AbortSignal.timeout(Ap)})}catch(a){return{ok:!1,status:0,reason:`GitHub could not be reached (${a instanceof Error?a.message:String(a)}).`}}let s=Symbol("unreadable"),i=await o.json().catch(()=>s);if(!o.ok)return{ok:!1,status:o.status,reason:_y(o.status,i)};if(i===s)return{ok:!1,status:o.status,reason:"GitHub's answer could not be read."};return{ok:!0,value:i}}function oEe(e){if(e.state==="merged")return"This pull request is already merged.";if(e.state==="closed")return"This pull request is closed.";if(e.baseRef!=="main")return`This pull request targets ${Yo(e.baseRef,40)||"another branch"}, not main. The review queue covers pull requests to main.`;if(e.draft)return"This pull request is a draft. Ask the author to mark it ready first.";return null}function jRt(e){return typeof e==="string"&&$p.includes(e)?e:null}var LRt=["pass","fail","uncertain"];function yD(e,t){let n=typeof e==="object"&&e!==null?e:null;if(!n)return{ok:!1,why:"the NEMAR API sent no review"};let r=jRt(n.verdict);if(r===null)return{ok:!1,why:"the NEMAR API sent a verdict this version of the CLI does not know; update the CLI"};if(n.head_sha!==t)return{ok:!1,why:"the NEMAR API answered about a different commit than GitHub reports"};let o=n.stale_verdict??null;if(o!==null&&!LRt.includes(o))return{ok:!1,why:"the NEMAR API sent a review this version of the CLI cannot read"};let s=n.review_current??null;if(s!==null&&typeof s!=="boolean")return{ok:!1,why:"the NEMAR API sent a review this version of the CLI cannot read"};let i=n.author?.standing,a=i?.paused===!0?`The contributor's pull requests are not reviewed automatically (paused${i.because==="maintainer"?" by an administrator's block":""}).`:null;return{ok:!0,verdict:r,detail:typeof n.detail==="string"?n.detail:null,staleVerdict:o,reviewCurrent:s,contributorNote:a,outcome:s===!0?n.review?.outcome??null:null}}function bD(e){if(e.unread)return{kind:"needs_force",reason:`The automated review could not be read (${e.unread}), so its verdict is unknown. Pass --force to approve without it.`};switch(e.verdict){case"pass":return{kind:"proceed"};case"fail":return{kind:"needs_force",reason:"The automated review says this pull request needs changes. Read it with `show`, and pass --force to approve it anyway."};case"in_progress":return{kind:"needs_force",reason:"The automated review of this commit is still running. Wait for it, or pass --force to approve without it."};case"uncertain":return{kind:"confirm",warning:"The automated review could not decide whether this is a good change."};case"could_not_decide":return{kind:"confirm",warning:"The automated review ended without a verdict."};case"not_reviewed":return{kind:"confirm",warning:e.staleVerdict===null?"The automated review has not read this commit.":`The automated review read a different commit of this pull request (it said: ${e.staleVerdict}), not this one.`};case"exempt":return{kind:"confirm",warning:`A legacy API reported an exemption for this commit, not a review pass. Current policy reviews owners and administrators too.${e.staleVerdict===null?"":` An earlier commit of it was reviewed and read ${e.staleVerdict}.`}`};case"waived":return{kind:"confirm",warning:"The automated review is waived for this commit: NEMAR's record says it is an upstream re-pull's own head, and a mirror's content is upstream's. What a review of it found, if anything, is a recommendation and holds nothing."}}}function wD(e){return{ok:!1,outcome:"unknown",status:0,reason:`GitHub did not answer (${e instanceof Error?e.message:String(e)}).`}}async function bj(e,t,n,r,o,s,i=Sn()){let a;try{a=await fetch(`${i}/repos/${Es}/${t}/pulls/${n}/reviews`,{method:"POST",headers:Op(e),body:JSON.stringify({commit_id:r,event:"APPROVE",body:s}),signal:AbortSignal.timeout(Ap)})}catch(d){return wD(d)}let c=await a.json().catch(()=>null);if(!a.ok)return{ok:!1,outcome:a.status>=500?"unknown":"refused",status:a.status,reason:_y(a.status,c)};if(typeof c?.state!=="string")return{ok:!1,outcome:"unknown",status:a.status,reason:`GitHub answered HTTP ${a.status}, but its answer could not be read.`};let l=typeof c.user?.login==="string"?c.user.login:"";if(c.state!=="APPROVED"||c.commit_id!==r||l.toLowerCase()!==o.toLowerCase()){let d=[c.state!=="APPROVED"?`state ${Yo(c.state,20)}`:"",l.toLowerCase()!==o.toLowerCase()?`by @${Yo(l,40)||"?"}`:"",c.commit_id!==r?`commit ${typeof c.commit_id==="string"?Yo(c.commit_id,40).slice(0,7):"?"}`:""].filter(Boolean);return{ok:!1,outcome:"different",status:a.status,reason:`GitHub recorded a review, but not the approval that was asked for (${d.join(", ")}).`}}return{ok:!0}}async function sEe(e,t,n,r,o=Sn()){let s;try{s=await fetch(`${o}/repos/${Es}/${t}/issues/${n}/comments`,{method:"POST",headers:Op(e),body:JSON.stringify({body:r}),signal:AbortSignal.timeout(Ap)})}catch(a){return wD(a)}let i=await s.json().catch(()=>null);if(!s.ok)return{ok:!1,outcome:s.status>=500?"unknown":"refused",status:s.status,reason:_y(s.status,i)};if(typeof i?.id!=="number")return{ok:!1,outcome:"unknown",status:s.status,reason:`GitHub answered HTTP ${s.status}, but its answer could not be read.`};return{ok:!0}}async function _D(e,t,n,r=Sn()){let o;try{o=await fetch(`${r}/repos/${Es}/${t}/pulls/${n}`,{method:"PATCH",headers:Op(e),body:JSON.stringify({state:"closed"}),signal:AbortSignal.timeout(Ap)})}catch(i){return wD(i)}let s=await o.json().catch(()=>null);if(!o.ok)return{ok:!1,outcome:o.status>=500?"unknown":"refused",status:o.status,reason:_y(o.status,s)};if(typeof s?.state!=="string")return{ok:!1,outcome:"unknown",status:o.status,reason:`GitHub answered HTTP ${o.status}, but its answer could not be read.`};if(s.state!=="closed")return{ok:!1,outcome:"different",status:o.status,reason:`GitHub answered, but the pull request is ${Yo(s.state,20)}, not closed.`};return{ok:!0}}var xD=["merge","squash","rebase"],qRt="clean",URt=new Map([["blocked","a required check or review is not satisfied (the BIDS validation, the version check or, where its ruleset is in force, the NEMAR PR Review); this tool names the NEMAR PR Review check, and no other, as one an owner or administrator can override in the GitHub UI, and only where its ruleset is in force, and it never uses the bypass itself"],["behind","the branch is behind main"],["dirty","it has merge conflicts"],["unstable","a check or status that is not required is not passing or has not reported, for example the automated review holding the pull request"],["draft","it is a draft"],["unknown","GitHub has not said whether it can be merged"]]);function nEe(e){return URt.get(e)??"this tool merges only a pull request GitHub reports as clean"}function xy(e){let t=e&&e.length>0?e:"unknown";if(t===qRt)return{ok:!0};return{ok:!1,why:`GitHub reports this pull request as '${pD(t)}' (${nEe(t)}), so a merge would not be attempted.`,card:`${nEe(t)} (GitHub: ${pD(t)})`,advice:t==="unknown"?"retry":"without_merge"}}function pD(e){return/^[a-z][a-z_]{0,29}$/.test(e)?e:"unrecognised"}async function Tp(e,t,n,r,o={}){let s=o.base??Sn(),i=o.sleep??((d)=>new Promise((f)=>setTimeout(f,d))),a=o.tries??5,c=r.mergeableState,l=c===null?0:1;for(;;){if(c===null){let d=await Hs(e,t,n,s);if(!d.ok)return{ok:!1,kind:"unreadable",status:d.status,reason:d.reason};if(d.value.state!=="open")return{ok:!1,kind:"closed",merged:d.value.state==="merged"};if(d.value.headSha!==r.headSha)return{ok:!1,kind:"moved"};c=d.value.mergeableState,l++}if(c!=="unknown"||l>=a)return{ok:!0,state:c};await i(1000),c=null}}function iEe(e){if(e.kind==="moved")return{ok:!1,why:"The pull request changed since it was read.",card:"the pull request changed since it was read",advice:"rerun"};if(e.kind==="closed")return{ok:!1,why:`The pull request is no longer open (it was ${e.merged?"merged":"closed"}).`,card:"the pull request is no longer open",advice:"none"};let t=e.reason.replace(/\.$/,"");return{ok:!1,why:`Could not check whether it can be merged (${t}).`,card:`could not be checked (${t})`,advice:"retry"}}async function vy(e,t,n,r,o={}){let s=await Tp(e,t,n,r,o);return s.ok?xy(s.state):iEe(s)}async function wj(e,t,n,r,o={}){let s=await vy(e,t,n,{headSha:r,mergeableState:null},o);return s.ok?s:{...s,why:`Checked again just before approving: ${s.why}`}}async function g_(e,t,n,r,o,s={}){let i=s.base??Sn(),a=await Tp(e,t,n,{headSha:r,mergeableState:null},s);if(!a.ok){if(a.kind==="moved")return{ok:!1,outcome:"not_sent",status:409,reason:"The pull request changed after it was approved, so it was not merged."};if(a.kind==="closed")return{ok:!1,outcome:"not_sent",status:409,reason:`Not merged: ${iEe(a).why} The approval stands.`};return{ok:!1,outcome:"not_sent",status:a.status,reason:`Not merged: ${a.reason} The approval stands.`}}let c=s.state==="unstable"?a.state==="unstable"?{ok:!0}:{ok:!1,why:`GitHub reports this pull request as '${pD(a.state)}', not 'unstable', so a merge over a failed BIDS validation would not be attempted.`,card:`not unstable (GitHub: ${pD(a.state)})`,advice:"none"}:xy(a.state);if(!c.ok)return{ok:!1,outcome:"not_sent",status:405,merge:c,reason:`Not merged: ${c.why} The approval stands.`};let l;try{l=await fetch(`${i}/repos/${Es}/${t}/pulls/${n}/merge`,{method:"PUT",headers:Op(e),body:JSON.stringify({sha:r,merge_method:o,...s.commit?{commit_title:s.commit.title,commit_message:s.commit.message}:{}}),signal:AbortSignal.timeout(Ap)})}catch(f){return wD(f)}let d=await l.json().catch(()=>null);if(!l.ok)return{ok:!1,outcome:l.status>=500?"unknown":"refused",status:l.status,reason:_y(l.status,d)};if(d?.merged!==!0)return{ok:!1,outcome:"unknown",status:l.status,reason:`GitHub answered HTTP ${l.status}, but did not say the pull request was merged.`};return{ok:!0}}function cEe(e){switch(e.trim().toLowerCase()){case"y":case"yes":return"approve";case"n":case"no":return"close";case"c":case"comment":return"comment";case"d":case"details":return"details";case"s":case"skip":return"skip";case"q":case"quit":return"quit";default:return null}}function lEe(e){let t=[];if(e.bids!=="pass"||e.version!=="pass")t.push(`A required check is not green (BIDS ${aEe(e.bids)}, version ${aEe(e.version)}), so GitHub would not let it merge.`);if(!e.merge.ok)t.push(e.merge.why);if(e.gate.kind==="needs_force"&&!e.force)t.push(e.gate.reason);return t.length===0?{ok:!0}:{ok:!1,reason:t.join(" ")}}function aEe(e){switch(e){case"pass":return"ok";case"fail":return"failing";case"pending":return"pending";case"missing":return"missing";default:return"unknown"}}function vD(e){return`${e.dataset_id}#${e.pr_number}`}function uEe(e,t){if(t.aborted)return Promise.resolve({aborted:!0});return new Promise((n,r)=>{let o=()=>n({aborted:!0});t.addEventListener("abort",o,{once:!0}),e.then((s)=>{t.removeEventListener("abort",o),n({aborted:!1,value:s})},(s)=>{t.removeEventListener("abort",o),r(s)})})}async function dEe(e,t,n){let r=[],o=t.now??Date.now,s=new Map,i=0,a=0,c=null;while(i<e.length){if(n.signal.aborted){c="interrupted";break}if(s.size>=n.concurrency){if(t.onWait?.({running:s.size,remaining:e.length-i}),await t.sleep(n.pollMs,n.signal),n.signal.aborted)continue;for(let[m,h]of[...s])if(o()-h.since>=n.maxHoldMs)s.delete(m);if(s.size<n.concurrency)continue;let f=await uEe(t.inProgress().catch(()=>null),n.signal);if(f.aborted)continue;let p=f.value;if(p===null){if(a++,t.onUnknown?.({count:a,max:n.maxUnknownPolls}),a>=n.maxUnknownPolls){c="unknown_polls";break}continue}a=0;for(let[m,h]of[...s]){if(p.has(m))continue;if(!t.confirmFinished){s.delete(m);continue}let g=await uEe(t.confirmFinished(h.entry).catch(()=>!1),n.signal);if(g.aborted)break;if(g.value)s.delete(m)}continue}let l=e[i++],d;try{d={answer:await t.start(l)}}catch(f){d={error:f}}if(r.push({entry:l,...d}),t.onResult(l,d),"answer"in d){if(t.isRunning(d.answer))s.set(vD(l),{entry:l,since:o()});if(t.stopAfter?.(d.answer)){c="answer";break}}else if(t.maybeRunning?.(d.error))s.set(vD(l),{entry:l,since:o()})}return{results:r,notStarted:e.slice(i),stoppedBy:c}}function fEe(e,t){return new Promise((n)=>{if(t.aborted){n();return}let r=()=>{clearTimeout(o),t.removeEventListener("abort",r),n()},o=setTimeout(r,e);t.addEventListener("abort",r,{once:!0})})}function pEe(e){if(!/^[1-9][0-9]{0,5}$/.test(e.trim()))return null;return Number(e.trim())}import{createInterface as BRt}from"readline";var ED=250;class Pp{rl;lines=[];waiting=[];output;typeAhead;ended=!1;wasInterrupted=!1;constructor(e=process.stdin,t=process.stdout,n={}){this.output=t,this.typeAhead=n.typeAhead??(e.isTTY===!0?"discard":"keep"),this.rl=BRt({input:e,output:t,terminal:e.isTTY===!0}),this.rl.on("line",(r)=>{let o=this.waiting.shift();if(o)o(r);else this.lines.push(r)}),this.rl.on("SIGINT",()=>this.interrupt()),this.rl.on("close",()=>{this.ended=!0;for(let r of this.waiting.splice(0))r(null)})}get open(){return!this.ended}get canAnswer(){return!this.wasInterrupted&&(!this.ended||this.lines.length>0)}get interrupted(){return this.wasInterrupted}interrupt(){this.wasInterrupted=!0,this.lines.length=0,this.rl.close()}ask(e){if(this.wasInterrupted)return Promise.resolve(null);let t=this.lines.shift();if(t!==void 0)return this.output.write(`${e}${t}
|
|
923
923
|
`),Promise.resolve(t);if(this.ended)return Promise.resolve(null);return this.rl.setPrompt(e),this.rl.prompt(),new Promise((n)=>this.waiting.push(n))}async discardTyped(e=0){if(this.typeAhead!=="discard")return 0;if(e>0)await new Promise((n)=>setTimeout(n,e));let t=this.lines.length;return this.lines.length=0,t}close(){this.rl.close()}}import{dirname as t2t,join as n2t}from"path";var _j=3679074;var y_="nemarDatasets";function ca(e,t){return typeof e==="string"&&e.toLowerCase()===`nemarDatasets/${t}`.toLowerCase()}mo();var Cj="Repull-Patch";function la(e){return[`Upstream-Snapshot: ${e.upstream_ds}@${e.to_tag}`,`Repull-Plan: ${e.plan_digest}`]}function __(e){return`${Cj}: corrections=${e}`}function vEe(e,t,n="n0",r="gate"){let[o,s]=la(e),i=n==="n1"?e.counts?.corrections:void 0,a=r==="worker"?"squash-merged by the Worker as a machine-clean automatic re-pull":"squash-merged through the re-pull's merge gate";return{title:`Release v${e[Pn[n].version]} (#${t})`,message:[n==="n0"?`Re-pull of upstream ${e.upstream_ds} from snapshot ${e.from_tag} to ${e.to_tag} (re-pull #${e.id}), ${a} (ADR 0111).`:`NEMAR's corrections of re-pull #${e.id} (upstream ${e.upstream_ds} ${e.from_tag} to ${e.to_tag}), replayed onto v${e.to_version}, ${a} (ADR 0111).`,"",o,s,...n==="n1"&&typeof i==="number"?[__(i)]:[]].join(`
|
|
924
924
|
`)}}mo();_c();Ve();wr();Ve();async function EEe(e){return F("/admin/repulls",{method:"POST",body:JSON.stringify(e)},!0)}async function RD(e){return(await F(`/admin/repulls/${e}`,{},!0)).repull}async function Xo(e={}){let t=new URLSearchParams;if(e.dataset)t.set("dataset",e.dataset);if(e.open)t.set("open","1");if(e.origin)t.set("origin",e.origin);if(e.after!==void 0)t.set("after",String(e.after));if(e.limit!==void 0)t.set("limit",String(e.limit));let n=t.toString()?`?${t.toString()}`:"";return F(`/admin/repulls${n}`,{},!0)}async function $D(){return F("/admin/repulls/switches",{},!0)}async function SEe(e={}){let t=new URLSearchParams;if(e.dataset)t.set("dataset",e.dataset);if(e.status)t.set("status",e.status);if(e.after!==void 0)t.set("after",String(e.after));if(e.limit!==void 0)t.set("limit",String(e.limit));let n=t.toString()?`?${t.toString()}`:"";return F(`/admin/repulls/dispatches${n}`,{},!0)}async function fr(e,t){return(await F(`/admin/repulls/${e}/transition`,{method:"POST",body:JSON.stringify(t)},!0)).repull}async function ky(e){return F(`/admin/repulls/${e}/screens`,{},!0)}async function kEe(e,t){return F(`/admin/repulls/${e}/screen`,{method:"POST",body:JSON.stringify(t)},!0)}async function REe(e,t){return F(`/admin/repulls/${e}/screen/acknowledge`,{method:"POST",body:JSON.stringify(t)},!0)}async function $Ee(e,t){return(await F(`/admin/repulls/${e}/merge-claim/release`,{method:"POST",body:JSON.stringify(t)},!0)).repull}async function DEe(e,t){return(await F(`/admin/repulls/${e}/merge-claim/check`,{method:"POST",body:JSON.stringify(t)},!0)).repull}async function DD(e,t){return F(`/admin/repulls/${e}/merged`,{method:"POST",body:JSON.stringify({pr:t})},!0)}async function CEe(e,t){return F(`/admin/repulls/${e}/released`,{method:"POST",body:JSON.stringify(t)},!0)}async function Aj(e,t){return F(`/admin/repulls/${e}/merge-trailers/accept`,{method:"POST",body:JSON.stringify(t)},!0)}function _n(e){if(!(e instanceof U))return;let t=e.rawBody;if(typeof t!=="object"||t===null||Array.isArray(t))return;let n=t.code;return typeof n==="string"?n:void 0}var YRt=new Set(["nm000103","nm000105","nm000106","nm000107"]);var Oj="version-check";function Tj(e){return YRt.has(e)?"bids-validation":"Run BIDS Validation"}var x_=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),TEe=(e)=>typeof e==="number"&&Number.isSafeInteger(e)&&e>0,XRt=new Set(["queued","waiting","requested","pending"]),AEe={status:"unreadable",conclusion:null};function PEe(e){if(!x_(e))return"unreadable";let{total_count:t,check_runs:n}=e;if(typeof t!=="number"||!Array.isArray(n)||t>n.length)return"unreadable";let r=[];for(let o of n){if(!x_(o)||!x_(o.app)||!TEe(o.id))return"unreadable";if(typeof o.status!=="string")return"unreadable";if(o.conclusion!==null&&typeof o.conclusion!=="string")return"unreadable";r.push({id:o.id,name:o.name,appId:o.app.id,headSha:o.head_sha,status:o.status,conclusion:o.conclusion})}return r}function OEe(e,t,n){let r=PEe(e);if(r==="unreadable")return AEe;let o=null;for(let s of r){if(s.name!==t||s.appId!==_j||s.headSha!==n)continue;if(o===null||s.id>o.id)o=s}if(o===null)return{status:"absent",conclusion:null};if(o.status==="completed")return{status:"completed",conclusion:o.conclusion};if(o.status==="in_progress")return{status:"in_progress",conclusion:null};if(XRt.has(o.status))return{status:"queued",conclusion:null};return AEe}function QRt(e){if(e.origin!=="administrator")return"automatic";if(e.bids.status==="unreadable"||e.versionCheck.status==="unreadable")return"unreadable";if(e.mergeableState==="blocked")return"blocked";if(e.mergeableState!=="unstable")return"not-unstable";if(e.bids.status!=="completed"||e.bids.conclusion!=="failure")return"bids";if(e.versionCheck.status!=="completed"||e.versionCheck.conclusion!=="success")return"version-check";return null}var ZRt=new Set(["success","neutral","skipped"]);function e$t(e){if(!x_(e))return"unreadable";let{total_count:t,statuses:n}=e;if(typeof t!=="number"||!Array.isArray(n)||t>n.length)return"unreadable";let r=[];for(let o of n){if(!x_(o)||typeof o.context!=="string"||typeof o.state!=="string")return"unreadable";r.push({context:o.context,state:o.state})}return r}function CD(e){let t=PEe(e.runs);if(t==="unreadable")return"unreadable";let n=Tj(e.datasetId),r=new Map;for(let i of t){if(i.headSha!==e.sha)continue;if(typeof i.name!=="string"||!TEe(i.appId))return"unreadable";if(i.appId===_j&&(i.name===n||i.name===Oj))continue;let c=`${i.appId}/${i.name}`,l=r.get(c);if(l===void 0||i.id>l.id)r.set(c,{...i,name:i.name})}let o=[];for(let i of r.values())if(!(i.status==="completed"&&i.conclusion!==null&&ZRt.has(i.conclusion)))o.push(i.name);let s=e$t(e.statuses);if(s==="unreadable")return"unreadable";for(let i of s)if(i.state!=="success")o.push(i.context);return o.sort()}function IEe(e){let t=QRt({origin:e.origin,mergeableState:e.mergeableState,bids:OEe(e.runs,Tj(e.datasetId),e.sha),versionCheck:OEe(e.runs,Oj,e.sha)});if(t!==null)return{fault:t};let n=CD(e);if(n==="unreadable")return{fault:"unreadable"};return n.length>0?{fault:"others",others:n}:null}async function NEe(e){let t=e.sha.slice(0,12),[n,r]=await Promise.all([yj(e.token,e.datasetId,`/commits/${e.sha}/check-runs?filter=latest&per_page=100`,e.base),yj(e.token,e.datasetId,`/commits/${e.sha}/status?per_page=100`,e.base)]);if(!n.ok)return{unreadable:`the check runs of ${t} could not be read (${n.reason})`};if(!r.ok)return{unreadable:`the commit statuses of ${t} could not be read (${r.reason})`};return{datasetId:e.datasetId,sha:e.sha,runs:n.value,statuses:r.value}}async function Ij(e){let t=await NEe(e);if("unreadable"in t)return{kind:"unreadable",why:t.unreadable};let n=IEe({...t,origin:e.origin,mergeableState:e.mergeableState});if(n===null)return{kind:"bids-only"};let r=Pj(n,e,t);return n.fault==="unreadable"?{kind:"unreadable",why:r}:{kind:"not",why:r}}async function FEe(e){let t=await NEe(e);if("unreadable"in t)return{kind:"unreadable",why:t.unreadable};let n=CD(t);if(n==="unreadable")return{kind:"unreadable",why:Pj({fault:"unreadable"},e)};if(n.length===0)return{kind:"bids-only"};return{kind:"not",why:Pj({fault:"others",others:n},e)}}function t$t(e,t){let n=CD(e);if(n==="unreadable"||n.length===0)return null;let r=t.sha.slice(0,12),o=n.map((s)=>Yo(s,60)||"unnamed").join(", ");return`BIDS validation of ${r} has not failed; what does not pass there is: ${o}${MEe(n,t)}`}function MEe(e,t){if(!e.includes(cj))return"";let n=`nemar admin pr-reviews start ${t.datasetId} ${t.prNumber}`;return`. A Worker at 0.10.27 or later waives the ${cj} check for an upstream re-pull's own head (an older Worker does not publish the waiver); if that check still reads as a review that failed, run ${n} to publish the waiver, then run this command again`}function Pj(e,t,n){let r=t.sha.slice(0,12);if(e.fault==="bids"&&n!==void 0){let o=t$t(n,t);if(o!==null)return o}switch(e.fault){case"unreadable":return`the checks of ${r} could not be read (GitHub's answer is not complete, or not of its shape)`;case"automatic":return"the automatic path opened this re-pull, and its pull request is merged over a failed BIDS validation by no one";case"blocked":return"GitHub reports it blocked: a rule requires BIDS validation, and a merge would be a bypass, which a re-pull never uses";case"not-unstable":return`GitHub reports it '${Yo(t.mergeableState,30)||"unrecognized"}', not unstable`;case"bids":return`BIDS validation of ${r} has not completed with failure`;case"version-check":return`version-check of ${r} has not completed with success`;case"others":return`another check of ${r} does not pass (${e.others.map((o)=>Yo(o,60)||"unnamed").join(", ")})${MEe(e.others,t)}`}}vc();Ve();async function Ic(e){let t=null;try{t=await or(e)}catch(r){if(!(r instanceof U&&r.statusCode===404))throw r}let n=null;if(t)try{n=(await xp(e)).versions.map((o)=>({version:o.version,source_version:o.source_version??null,source_version_basis:o.source_version_basis??null}))}catch(r){if(!(r instanceof U&&r.statusCode===404))throw r}return{dataset:t,versions:n}}Xd();Ry();var ql=".nemar/";function Ul(e,t){if(e.includes(t))return{content:e,changed:!1};return{content:e?`${e.trimEnd()}
|
|
925
925
|
${t}
|
|
@@ -998,7 +998,7 @@ ${b.message}`,r);if(x)return Zt("message",`The squash message would not carry th
|
|
|
998
998
|
`);let{phase:f,code:p}=d;e(`${hx("result",p===void 0?{phase:f}:{phase:f,code:p})}
|
|
999
999
|
`);return}e(`${hx("result",{phase:"failed",code:"runner-failed"})}
|
|
1000
1000
|
`)};mA={emit(d,f){if(d==="result")o=String(f?.phase??"failed");e(`${hx(d,f)}
|
|
1001
|
-
`)},drop(){t++},dropped:()=>t,stored(d,f){s={phase:d,code:d==="refused"||d==="failed"?f:void 0}},time(d,f){i.set(d,f)},quietFields:a},process.on("exit",()=>{if(o===null)c()});let l=()=>{try{t++;let d=o;if(s?d!==s.phase:d===null||d==="planned"||d==="opened"||d==="finished")c()}finally{process.exit(1)}};return process.on("uncaughtException",l),process.on("unhandledRejection",l),mA}function eq(e){return e.some((t)=>t===SCe||t.startsWith(`${SCe}=`))}function wPt(e){let t=e.GITHUB_RUN_ID??"";if(e.GITHUB_SERVER_URL==="https://github.com"&&e.GITHUB_REPOSITORY==="nemarDatasets/.github"&&/^[0-9]{1,20}$/.test(t))return`https://github.com/nemarDatasets/.github/actions/runs/${t}`;return null}function DCe(e,t,n){let r=Z4(e);if(r===null)throw Dr("id on the command line");let o=hPt(t);if(o.dispatchId!==r)throw new j("dispatch-mismatch","The dispatch named on the command line is not the one the event delivered.");let s=t.RUNNER_TEMP;return{dispatch:o,runUrl:wPt(t),marker:s?_f(s,"repull-reported"):null,sink:n}}var _Pt="https://
|
|
1001
|
+
`)},drop(){t++},dropped:()=>t,stored(d,f){s={phase:d,code:d==="refused"||d==="failed"?f:void 0}},time(d,f){i.set(d,f)},quietFields:a},process.on("exit",()=>{if(o===null)c()});let l=()=>{try{t++;let d=o;if(s?d!==s.phase:d===null||d==="planned"||d==="opened"||d==="finished")c()}finally{process.exit(1)}};return process.on("uncaughtException",l),process.on("unhandledRejection",l),mA}function eq(e){return e.some((t)=>t===SCe||t.startsWith(`${SCe}=`))}function wPt(e){let t=e.GITHUB_RUN_ID??"";if(e.GITHUB_SERVER_URL==="https://github.com"&&e.GITHUB_REPOSITORY==="nemarDatasets/.github"&&/^[0-9]{1,20}$/.test(t))return`https://github.com/nemarDatasets/.github/actions/runs/${t}`;return null}function DCe(e,t,n){let r=Z4(e);if(r===null)throw Dr("id on the command line");let o=hPt(t);if(o.dispatchId!==r)throw new j("dispatch-mismatch","The dispatch named on the command line is not the one the event delivered.");let s=t.RUNNER_TEMP;return{dispatch:o,runUrl:wPt(t),marker:s?_f(s,"repull-reported"):null,sink:n}}var _Pt="https://api.nemar.org";function CCe(e){let t;try{t=new URL(e)}catch{return!1}if(t.username||t.password||t.search||t.hash||t.pathname!=="/"&&t.pathname!=="")return!1;if(t.protocol==="https:")return t.host===new URL(_Pt).host;return t.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(t.hostname)}function tq(e,t){if(!t.some((n)=>n.includes(e.token)))return null;return new j("auto-token-on-argv","The dispatch token is on the command line, where the public log shows it.")}function ACe(e,t){let n=tq(e,t.argv);if(n)return n;let r=t.ownVersion??Ls;if((t.devBuild??yp)||!Sy.test(r)||r!==e.cliVersion)return new j("auto-cli-version","This CLI is not the release the dispatch names: an automatic run uses only that release.");if(t.verbose??(Bg()||Nl()||t.argv.includes("--verbose")||t.argv.includes("--debug")))return new j("auto-verbose","Verbose or debug output is on, and it prints what the run reads; an automatic run takes neither.");if(e.mode!==t.mode||e.datasetId!==t.datasetId)return new j("dispatch-mismatch","The command is not the one the dispatch asks for: another kind of run, or another dataset.");if(!t.env.GH_TOKEN?.trim())return new j("auto-no-app-token","GH_TOKEN is not set: an automatic run pushes and opens its pull request with the App token minted for this dataset.");if(gA(t.env,t.nowMs??Date.now())===null)return new j("auto-token-clock",`${OCe} does not say when the App token was minted, so the run cannot keep its pushes inside the token's hour.`);return null}var OCe="NEMAR_REPULL_TOKEN_SINCE";function gA(e,t){let n=e[OCe]?.trim()??"";if(!/^[1-9][0-9]{0,11}$/.test(n))return null;let r=Number(n);return r*1000<=t+300000?r:null}function xPt(e,t){return(e+w_)*1000-t}function gx(e,t,n){let r=(n+xEe+kj)*1000;if(xPt(e,t)>=r)return null;return new j("auto-token-hour","What is left to do would pass the App token's usable hour, so the run stops before this step; the record, if there is one, stays where it stopped.")}function yx(e){let t=Yc(e);return $j({bytes:t.copy_bytes??0,objects:t.copy_items??0})}function cb(e,t){return new j("auto-option",t==="required"?`An automatic run needs ${e}.`:`An automatic run does not take ${e}.`)}function TCe(e){if(!e.executable)throw new j("not-executable","The plan is not executable.");yA(e.body)}function yA(e){let t=Yc(e),n=wEe(e.planner,t);if(n)throw new j(n.code,n.message);if(t.copy_bytes_unknown!==0)throw new j("auto-copy-too-large","An automatic re-pull takes only a plan whose copy size is known for every key.");let{copy_bytes:r,copy_items:o,local_bytes:s,local_uploads:i}=t,a=vPt();if(r===void 0||o===void 0||s===void 0||i===void 0||t.local_bytes_unknown!==0||$j({bytes:r+s,objects:o+i})>a)throw new j("auto-copy-too-long",`An automatic re-pull takes only a plan whose copy, by its known size and count, fits ${Math.floor(a/60)} minutes: the App token that pushes it lasts an hour.`)}function bA(e){return`${e}.planner`}function PCe(e,t,n,r){iPt(_f(t,"computed"),{mode:448});for(let[s,i]of n)Q4(_f(t,"computed",s),i,{mode:384});Q4(_f(t,"digest"),`${r}
|
|
1002
1002
|
`,{mode:384});let o=bA(e);lPt(o,{recursive:!0,force:!0}),cPt(t,o)}function ICe(e,t){let n=bA(e),r=_f(n,"computed"),o=_f(n,"digest");if(!Y4(_f(n,"upstream.git"))||!Y4(r)||!Y4(o)||X4(o,"utf8").trim()!==t)throw new j("not-planned","No handoff of this plan's own plan step is beside the plan file; an automatic execute plans nothing itself.");let s=new Map;for(let i of aPt(r))s.set(i,X4(_f(r,i)));return{workdir:n,computed:s}}function vPt(e=process.env){let t=e.NEMAR_REPULL_COPY_BUDGET_SECONDS?.trim()??"",n=/^\d{1,9}$/.test(t)?Number(t):Number.NaN;return Number.isFinite(n)&&n<Rj?n:Rj}async function NCe(e,t,n=fetch){let r=t.GH_TOKEN?.trim();if(!r)return!1;let o;try{o=Sn(t)}catch{return!1}try{let s=await n(`${o}/repos/nemarDatasets/${e}`,{redirect:"error",headers:{Authorization:`Bearer ${r}`,Accept:"application/vnd.github+json","User-Agent":"nemar-cli"},signal:AbortSignal.timeout(1e4)});return await s.body?.cancel().catch(()=>{return}),s.status===401}catch{return!1}}function wA(e,t){if(Sj(e))return e;if(t===void 0)return"no-code";if(t==="prepare"&&IRe.includes(e??""))return"scrub-failed";return bEe[t]}var EPt=15000,RCe=["opened","finished","refused","failed"];async function nq(e,t,n={},r={}){let o={dispatch_id:e.dispatch.dispatchId,dataset_id:e.dispatch.datasetId,phase:t};if(t==="refused"||t==="failed")o.code=wA(n.code);if(t==="opened")o.repull_id=n.repullId;if(e.runUrl)o.workflow_run_url=e.runUrl;let s=r.fetchImpl??fetch,i=r.apiUrl??Hr(),a=Math.max(1,r.attempts??3),c={stored:!1,code:"report-unanswered"};for(let l=1;l<=a;l++){let d,f;try{let p=await s(`${i}/webhooks/repull-state`,{method:"POST",redirect:"error",headers:{"Content-Type":"application/json","X-Repull-Token":e.dispatch.token},body:JSON.stringify(o),signal:AbortSignal.timeout(r.timeoutMs??EPt)});d=p.status,f=(await p.json().catch(()=>null))?.code}catch{if(c={stored:!1,code:"report-unanswered"},l<a)await $Ce(r.backoffMs??2000);continue}if(d===200){c={stored:!0};break}if(c={stored:!1,code:typeof f==="string"&&Sj(f)?f:"report-unanswered"},d<500)break;if(l<a)await $Ce(r.backoffMs??2000)}if(e.sink.emit("report",{phase:t,answer:c.stored?"stored":c.code}),c.stored&&RCe.includes(t))e.sink.stored(t,o.code);if(c.stored&&RCe.includes(t)&&e.marker)try{Q4(e.marker,`${t}
|
|
1003
1003
|
`,{mode:384})}catch{}return c}var $Ce=(e)=>new Promise((t)=>setTimeout(t,e));Yi();mo();wr();Ve();import{existsSync as kNt,readdirSync as RNt,rmdirSync as $Nt}from"fs";import{dirname as kx,join as Sx}from"path";Or();Fc();Wr();ff();pa();PA();Ay();mo();Ve();import{dirname as UIt,join as BIt}from"path";Or();function ss(e,t){return new j(e,t)}var wq=["registered","pr_open","gates_clear"];async function hAe(e,t,n){let r=await eb({token:e.token,base:e.base,datasetId:e.datasetId,state:"all",head:t});if(!r.ok)throw ss("github-unreadable",`GitHub's pull requests of ${t} could not be read whole (${Zy(r)}), so whether one merged is not known; nothing was closed.`);let o=new Set(r.pulls.filter((i)=>i.headRef===t).map((i)=>i.number));if(n!==null)o.add(n);let s=[];for(let i of[...o].sort((a,c)=>a-c)){let a=await Hs(e.token,e.datasetId,i,e.base);if(!a.ok)throw ss("github-unreadable",`Pull request #${i} could not be read on GitHub (${a.reason}); nothing was closed.`);s.push({number:i,state:a.value.state,headSha:a.value.headSha})}return s}function HIt(e,t,n,r){return ss("foreign-pull-request-merged",`GitHub says pull request #${t} of ${n} merged, and it is not this re-pull's (it recorded #${r}): that version was released outside the re-pull, which resume does not record. Nothing was closed or ended; read the dataset's history on GitHub (nemarDatasets/${e.datasetId}) to see what merged before this record is ended.`)}function gAe(e,t,n,r){return r!==null&&t!==r?HIt(e,t,n,r):yAe(e,t)}function yAe(e,t,n=!1){return(n?ut:ss)("pull-request-merged",`GitHub says pull request #${t} merged, so this re-pull is not ended: nemar admin repull resume ${e.datasetId} records the merge (a merge minted a DOI, and its release is recorded, not abandoned).`)}async function GIt(e,t){let n=(await Qs(e,t)).filter((a)=>a.mode==="120000"||a.mode==="100644"||a.mode==="100755"),r=new Map;if(n.length>0){let a=await oe(e,["cat-file","--batch-check"],{stdin:`${n.map((c)=>c.oid).join(`
|
|
1004
1004
|
`)}
|
|
@@ -1094,7 +1094,7 @@ its dispatch names, only once it has merged, and walks it to complete.`;function
|
|
|
1094
1094
|
`).map((t)=>R(t.replace(/\s+$/,"")).replace(/<\/?details>/g,"").replace(/<summary>(.*?)<\/summary>/g,"$1").replace(/^### (.*)$/,(n,r)=>u.bold(r)).replace(/\*\*(.+?)\*\*/g,(n,r)=>u.bold(r))).join(`
|
|
1095
1095
|
`).replace(/\n{3,}/g,`
|
|
1096
1096
|
|
|
1097
|
-
`).trim()}function d1e(e){try{let t=gj(e);return[u.bold(R(t.title)),"",VA(t.summary),"",VA(t.text)]}catch(t){return Tn(`pr-reviews: the stored report could not be rendered (${W(t)})`),[u.yellow("The stored report could not be rendered by this version of the CLI. Update it, or read the review on the pull request.")]}}function iFt(e){let t=[` Review: ${Dx(e.verdict)(Cx({verdict:e.verdict,detail:e.detail,review_current:e.review_current}))}`,u.dim(` This commit is an upstream re-pull's own head, as NEMAR's record of the re-pull holds it, so no automated review applies: a mirror's content is upstream's. Its check is posted as skipped and titled "${dj}"; this view does not verify that it was.`),u.dim(" The identifier screen, BIDS validation, the version check and the merge cap still gate the merge: nemar admin repull resume <dataset>, then nemar admin repull merge <dataset>.")],n=e.review_current===!0?e.review?.outcome??null:null;if(n?.kind!=="reported")return t;let r;try{r=mj(n.report)}catch(o){return Tn(`pr-reviews: the stored report could not be read for recommendations (${W(o)})`),[...t,u.yellow(" A review of this commit is on record, but this version of the CLI could not read it. Update it, or read the check on the pull request.")]}return[...t,"",u.bold(`${fj} (from a review of this commit that ran before NEMAR recorded it):`),...r.length>0?r.map((o)=>VA(o)):["None: that review found nothing."]]}function aFt(e){return uj(e)==="refused"?"the naming rule found a problem":"the naming rule could not check the dataset name"}function cFt(e){let{version_before:t,version_after:n}=e.evidence,r=by(e).criteria.advances_revision,o=e.v===2&&e.stage==="screen",s=e.v===2&&e.stage==="facts",i=s?u.dim(`stage: facts only; the review did not run (${aFt(e.evidence)})`):null,c=[r==="pass"?u.green("revision advances: yes"):r==="fail"?u.red("revision advances: NO"):o?u.dim("revision advances: not assessed (stopped by the screen)"):s?null:u.yellow("revision advances: unknown"),i].filter((l)=>l!==null).join("; ");return`Version: ${R(t??"unknown")} to ${R(n??"unknown")} ${c}`}function lFt(e){if(e===null||e===void 0)return[];try{let t=e,n=gj(t);if(t.kind!=="reported")return[u.bold(R(n.title)),R(n.summary)];let r=[u.bold(R(n.title))];if(t.report.summary)r.push(R(t.report.summary));r.push(cFt(t.report));let o=hj(t.report);if(o.length>0)r.push(u.bold("Naming rule:"),...o.map((i)=>`- ${i}`));let s=pj(t.report);if(s.length>0)r.push(u.bold("Findings:"),...s.map(VA));return r}catch(t){return Tn(`pr-reviews: the stored report could not be rendered (${W(t)})`),[u.yellow("The stored report could not be rendered by this version of the CLI. Update it, or read the review on the pull request.")]}}function uFt(e,t){return t>0?`${(e/t*100).toFixed(1)}%`:"0%"}function KA(e){let t=[];t.push(`${u.bold(R(e.login))} ${u.dim(`(GitHub id ${R(String(e.author_id))}${e.resolved_from==="history"?", from the Worker's records because GitHub was not asked or could not say":""})`)}`);let{rejected:n,decided:r}=e.tally;if(t.push(` Record: ${n} of ${r} decided pull request${r===1?"":"s"} rejected${r>0?` (${uFt(n,r)})`:""}`),t.push(u.dim(" shown for information: a record of rejections does not pause anyone's reviews, only a block does")),e.override){let o=e.override.set_by?` by ${R(e.override.set_by)}`:"";t.push(` Decision: ${e.override.mode==="allow"?u.green("allowed"):u.red("blocked")}${o} on ${R(e.override.set_at)}${e.override.reason?`: ${R(e.override.reason)}`:""}`)}else t.push(" Decision: none");if(t.push(` Standing: ${e.standing.paused?u.red(e.standing.because==="maintainer"?"paused by an administrator's block: their pull requests need a person":"paused: their pull requests need a person"):u.green("not paused: reviewed automatically")}`),e.recent.length>0)t.push(` Recent: ${e.recent.map((o)=>`${R(o.dataset_id)}#${R(String(o.pr_number))} ${o.verdict==="fail"?u.red("fail"):u.green("pass")}`).join(", ")}`);return t.push(u.dim("
|
|
1097
|
+
`).trim()}function d1e(e){try{let t=gj(e);return[u.bold(R(t.title)),"",VA(t.summary),"",VA(t.text)]}catch(t){return Tn(`pr-reviews: the stored report could not be rendered (${W(t)})`),[u.yellow("The stored report could not be rendered by this version of the CLI. Update it, or read the review on the pull request.")]}}function iFt(e){let t=[` Review: ${Dx(e.verdict)(Cx({verdict:e.verdict,detail:e.detail,review_current:e.review_current}))}`,u.dim(` This commit is an upstream re-pull's own head, as NEMAR's record of the re-pull holds it, so no automated review applies: a mirror's content is upstream's. Its check is posted as skipped and titled "${dj}"; this view does not verify that it was.`),u.dim(" The identifier screen, BIDS validation, the version check and the merge cap still gate the merge: nemar admin repull resume <dataset>, then nemar admin repull merge <dataset>.")],n=e.review_current===!0?e.review?.outcome??null:null;if(n?.kind!=="reported")return t;let r;try{r=mj(n.report)}catch(o){return Tn(`pr-reviews: the stored report could not be read for recommendations (${W(o)})`),[...t,u.yellow(" A review of this commit is on record, but this version of the CLI could not read it. Update it, or read the check on the pull request.")]}return[...t,"",u.bold(`${fj} (from a review of this commit that ran before NEMAR recorded it):`),...r.length>0?r.map((o)=>VA(o)):["None: that review found nothing."]]}function aFt(e){return uj(e)==="refused"?"the naming rule found a problem":"the naming rule could not check the dataset name"}function cFt(e){let{version_before:t,version_after:n}=e.evidence,r=by(e).criteria.advances_revision,o=e.v===2&&e.stage==="screen",s=e.v===2&&e.stage==="facts",i=s?u.dim(`stage: facts only; the review did not run (${aFt(e.evidence)})`):null,c=[r==="pass"?u.green("revision advances: yes"):r==="fail"?u.red("revision advances: NO"):o?u.dim("revision advances: not assessed (stopped by the screen)"):s?null:u.yellow("revision advances: unknown"),i].filter((l)=>l!==null).join("; ");return`Version: ${R(t??"unknown")} to ${R(n??"unknown")} ${c}`}function lFt(e){if(e===null||e===void 0)return[];try{let t=e,n=gj(t);if(t.kind!=="reported")return[u.bold(R(n.title)),R(n.summary)];let r=[u.bold(R(n.title))];if(t.report.summary)r.push(R(t.report.summary));r.push(cFt(t.report));let o=hj(t.report);if(o.length>0)r.push(u.bold("Naming rule:"),...o.map((i)=>`- ${i}`));let s=pj(t.report);if(s.length>0)r.push(u.bold("Findings:"),...s.map(VA));return r}catch(t){return Tn(`pr-reviews: the stored report could not be rendered (${W(t)})`),[u.yellow("The stored report could not be rendered by this version of the CLI. Update it, or read the review on the pull request.")]}}function uFt(e,t){return t>0?`${(e/t*100).toFixed(1)}%`:"0%"}function KA(e){let t=[];t.push(`${u.bold(R(e.login))} ${u.dim(`(GitHub id ${R(String(e.author_id))}${e.resolved_from==="history"?", from the Worker's records because GitHub was not asked or could not say":""})`)}`);let{rejected:n,decided:r}=e.tally;if(t.push(` Record: ${n} of ${r} decided pull request${r===1?"":"s"} rejected${r>0?` (${uFt(n,r)})`:""}`),t.push(u.dim(" shown for information: a record of rejections does not pause anyone's reviews, only a block does")),e.override){let o=e.override.set_by?` by ${R(e.override.set_by)}`:"";t.push(` Decision: ${e.override.mode==="allow"?u.green("allowed"):u.red("blocked")}${o} on ${R(e.override.set_at)}${e.override.reason?`: ${R(e.override.reason)}`:""}`)}else t.push(" Decision: none");if(t.push(` Standing: ${e.standing.paused?u.red(e.standing.because==="maintainer"?"paused by an administrator's block: their pull requests need a person":"paused: their pull requests need a person"):u.green("not paused: reviewed automatically")}`),e.recent.length>0)t.push(` Recent: ${e.recent.map((o)=>`${R(o.dataset_id)}#${R(String(o.pr_number))} ${o.verdict==="fail"?u.red("fail"):u.green("pass")}`).join(", ")}`);return t.push(u.dim(" Roles: owners and administrators receive review too; a block or an allow applies regardless of author role.")),t}function du(e){if(!Ye()){let t=rn(e);return t(u.red("Error: Not authenticated")),t(u.dim(" Run 'nemar auth login' first")),!1}return!0}function an(e,t,n){let r=rn(n);if(r(u.red(e)),t)r(u.dim(` ${t}`));process.exit(1)}function mb(e){if(!(e instanceof U))return;let t=e.rawBody;return typeof t?.code==="string"?t.code:void 0}function ba(e,t,n,r){let o=e instanceof U?R(e.message):n,s=rn(r);if(t)t.fail(o);else s(u.red(o));if(e instanceof U){if(e.statusCode===403)s(u.dim(" This command requires admin privileges"))}else s(u.dim(` Error details: ${W(e)}`));process.exit(1)}function hb(e,t){if(!Zu.test(e))an(`"${R(e)}" is not a dataset id (like nm000108).`,void 0,t);return e}function JA(e,t){let n=Number(e);if(!/^\d+$/.test(e)||!Number.isSafeInteger(n)||n<=0)an(`"${R(e)}" is not a pull request number.`,void 0,t);return n}function Ax(e,t){let n=e.replace(/^@/,"");if(!XNt.test(n))an(`"${R(e)}" is not a GitHub login.`,void 0,t);return n}function mm(e){if(e!=="production")console.log(u.yellow(" This is the non-production Worker. It holds its own record and answers only for the datasets it owns; it does not change what production reviews."))}function ya(e){return R(e).slice(0,7)}var wa=new ae("pr-reviews").description("Open dataset pull requests to main, with the automated review of each (ADR 0093)").addHelpText("after",`
|
|
1098
1098
|
One place for every open pull request to main in nemarDatasets. Run with no subcommand to list, or
|
|
1099
1099
|
'next' to go through the ones that need you one at a time (y approves and squash-merges, n closes
|
|
1100
1100
|
with a comment, c comments).
|
|
@@ -1113,16 +1113,8 @@ REVIEW column (the automated review of the pull request's CURRENT commit):
|
|
|
1113
1113
|
in progress the review is running
|
|
1114
1114
|
could not decide the review ended without a verdict (an error, or it never reported)
|
|
1115
1115
|
exempt (owner or admin)
|
|
1116
|
-
a
|
|
1117
|
-
|
|
1118
|
-
for you, and a push by anyone else IS reviewed. The naming rule still applies:
|
|
1119
|
-
a title or a new dataset name it refuses fails the check instead, until the
|
|
1120
|
-
title or the name is fixed or the rule is waived for that commit with
|
|
1121
|
-
'nemar admin pr-reviews allow <dataset> <pr> --admin --reason <why>'. The row
|
|
1122
|
-
says so when the check failed ("naming rule failed: needs allow --admin") or
|
|
1123
|
-
when the name could not be read ("naming rule not checked: start once, else fix
|
|
1124
|
-
the file": a start asks GitHub again, and a file with no readable Name has to be
|
|
1125
|
-
fixed and pushed; nothing is waivable until the name is read)
|
|
1116
|
+
a legacy API reported an exemption, not a review pass. This list does not
|
|
1117
|
+
verify its check. Current policy reviews owners and administrators too.
|
|
1126
1118
|
waived (upstream re-pull)
|
|
1127
1119
|
an upstream re-pull's own pull request, at the commit NEMAR's record holds for
|
|
1128
1120
|
it, so the review does not apply: a mirror's content is upstream's (its check
|
|
@@ -1153,17 +1145,14 @@ terminal, opens the link); a token GitHub rejects is reported without it.
|
|
|
1153
1145
|
The list comes from GitHub's search index, which can lag behind a new pull request.
|
|
1154
1146
|
`);function WA(e){let t=[];if(e.truncated)t.push(u.yellow(" GitHub's search returned fewer pull requests than exist, so this list is incomplete."));if(e.skipped.unreadable>0)t.push(u.yellow(` ${e.skipped.unreadable} search result(s) could not be read as pull requests and are not listed.`));return t}function dFt(e,t){return[...t,...e.split(",").map((n)=>n.trim()).filter(Boolean)]}wa.command("list",{isDefault:!0}).description("List open pull requests to main with the automated review of each one's current commit (default)").option("--verdict <verdict>",`Only these verdicts, comma separated or repeated: ${$p.join(", ").replaceAll("_","-")}`,dFt,[]).option("--dataset <id>","Only this dataset").option("--author <login>","Only pull requests opened by this GitHub login").option("--needs-me","Only what you can act on: passes, and anything a person must decide").option("--json","Output the raw JSON instead of the table").action(async(e)=>{if(!du(e.json))process.exit(1);let t=e.verdict.map((f)=>f.toLowerCase().replaceAll("-","_"));for(let f of t)if(!$p.includes(f))an(`"${R(f)}" is not a verdict.`,`Use: ${$p.join(", ").replaceAll("_","-")}`,e.json);let n=e.dataset?hb(e.dataset,e.json):void 0,r=e.author?Ax(e.author,e.json):void 0,o=e.json?null:C("Reading open pull requests...").start(),s;try{s=await Yw({verdicts:t,dataset:n,author:r,needsMe:e.needsMe}),o?.stop()}catch(f){ba(f,o,"Could not read the pull-request queue",e.json)}if(e.json){console.log(JSON.stringify(s,null,2));for(let f of WA(s))console.error(f);return}let i=tFt(s.entries),a=s.truncated||s.skipped.unreadable>0||s.skipped.not_owned_here>0;if(console.log(),i.length===0)console.log(s.total_open===0?a?u.yellow("No open pull requests found in what this Worker can see."):u.green("No open pull requests to main."):u.yellow(`No pull requests match (${s.total_open} open in all).`));else for(let f of i)console.log(f);let c=s.entries.filter((f)=>f.needs_you).length,l=s.entries.length===s.total_open?`${s.total_open} open`:`${s.entries.length} of ${s.total_open} open`;console.log(),console.log(`${l} pull request${s.total_open===1?"":"s"}, ${u.bold(String(c))} you can act on.`);for(let f of WA(s))console.log(f);if(!s.review_enabled)console.log(u.dim(" The automated review is off in this environment (PR_REVIEW_ENABLED), so pull requests with no stored review show as not reviewed."));if(s.skipped.not_owned_here>0)console.log(u.dim(` ${s.skipped.not_owned_here} pull request(s) belong to the other environment's Worker and are not listed.`));if(s.skipped.not_a_dataset>0)console.log(u.dim(` ${s.skipped.not_a_dataset} pull request(s) in non-dataset repositories ignored.`));let d=oFt(s.volume);if(d.length>0){console.log();for(let f of d)console.log(f)}if(mm(s.environment),i.length>0)console.log(u.dim(` nemar admin pr-reviews next go through them one at a time
|
|
1155
1147
|
nemar admin pr-reviews show <dataset> <pr> read the review
|
|
1156
|
-
nemar admin pr-reviews approve <dataset> <pr> approve it as yourself`))});wa.command("show <dataset> <pr>").description("Show the stored automated review of a pull request, in the words of its PR comment").option("--json","Output the raw JSON instead of the report").action(async(e,t,n)=>{if(!du(n.json))process.exit(1);let r=hb(e,n.json),o=JA(t,n.json),s=n.json?null:C("Reading the review...").start(),i;try{i=await ty(r,o),s?.stop()}catch(c){ba(c,s,"Could not read the review",n.json)}if(n.json){console.log(JSON.stringify(i,null,2));return}if(console.log(),console.log(`${u.bold(`${r} #${o}`)} ${u.dim(mD(r,o))}`),i.live){let c=i.live.draft&&i.live.state==="open"?"open, draft":i.live.state;console.log(` Author: ${R(i.live.author_login)} (${i.live.from_fork?"fork ":"branch "}${R(i.live.head_label)})`),console.log(` State: ${R(c)}, now at ${ya(i.live.head_sha)}`)}else if(i.live_status==="missing")console.log(u.yellow(" GitHub says this pull request does not exist."));else console.log(u.yellow(" GitHub could not be read, so the pull request's state is unknown."));console.log();let a=Dx(i.verdict);if(i.verdict==="exempt"){if(console.log(` Review: ${a(Cx({verdict:i.verdict,detail:i.detail,review_current:i.review_current}))}`),console.log(u.dim(" A
|
|
1148
|
+
nemar admin pr-reviews approve <dataset> <pr> approve it as yourself`))});wa.command("show <dataset> <pr>").description("Show the stored automated review of a pull request, in the words of its PR comment").option("--json","Output the raw JSON instead of the report").action(async(e,t,n)=>{if(!du(n.json))process.exit(1);let r=hb(e,n.json),o=JA(t,n.json),s=n.json?null:C("Reading the review...").start(),i;try{i=await ty(r,o),s?.stop()}catch(c){ba(c,s,"Could not read the review",n.json)}if(n.json){console.log(JSON.stringify(i,null,2));return}if(console.log(),console.log(`${u.bold(`${r} #${o}`)} ${u.dim(mD(r,o))}`),i.live){let c=i.live.draft&&i.live.state==="open"?"open, draft":i.live.state;console.log(` Author: ${R(i.live.author_login)} (${i.live.from_fork?"fork ":"branch "}${R(i.live.head_label)})`),console.log(` State: ${R(c)}, now at ${ya(i.live.head_sha)}`)}else if(i.live_status==="missing")console.log(u.yellow(" GitHub says this pull request does not exist."));else console.log(u.yellow(" GitHub could not be read, so the pull request's state is unknown."));console.log();let a=Dx(i.verdict);if(i.verdict==="exempt"){if(console.log(` Review: ${a(Cx({verdict:i.verdict,detail:i.detail,review_current:i.review_current}))}`),console.log(u.dim(" A legacy API reported an exemption for this pull request. Current policy does not exempt author roles.")),console.log(u.dim(" The review check on an exempt pull request is posted as skipped, which is not a pass; this view does not verify that it was.")),console.log(u.dim(" The naming rule still applies: a title or a new dataset name it refuses fails the check instead (waive it for this commit with: nemar admin pr-reviews allow <dataset> <pr> --admin --reason <why>).")),i.review)console.log(u.dim(` An earlier commit (${ya(i.review.head_sha)}) was reviewed and read ${Xc(i.review.verdict)}; this commit was not reviewed.`))}else if(i.verdict==="waived")for(let c of iFt(i))console.log(c);else if(!i.review)console.log(` Review: ${a("not reviewed")}`),console.log(u.dim(i.review_enabled?" No automated review has been recorded for this pull request.":" The automated review is off in this environment (PR_REVIEW_ENABLED), and none was recorded."));else{let c=ya(i.review.head_sha);if(i.review_current===null)console.log(` Review: ${u.yellow(`${Xc(i.review.verdict)} on ${c}`)} ${u.yellow("(whether that is the current commit is unknown: GitHub gave no current commit)")}`);else{let l=i.review_current===!1?u.yellow(`of ${c}, a DIFFERENT commit (the pull request is now at ${ya(i.head_sha??"")})`):`of ${c}`;if(console.log(` Review: ${a(Cx({verdict:i.verdict,detail:i.detail,review_current:i.review_current}))} ${u.dim(l)}`),i.review_current===!1)console.log(u.dim(` That review said ${Xc(i.review.verdict)}, and it does not apply to the current commit.`))}if(console.log(),i.review.outcome===null)console.log(i.review.verdict==="in_progress"?"The review is still running. It will update the pull request's check when it finishes.":`No report has arrived for this review (it was handed to GitHub on ${R(i.review.created_at)}). Review the pull request by hand.`);else for(let l of d1e(i.review.outcome))console.log(l)}if(i.author&&i.verdict!=="exempt"&&i.verdict!=="waived"){console.log();for(let c of KA(i.author))console.log(c)}if(i.history.length>1){console.log(),console.log(u.bold("History"));for(let c of i.history)console.log(` ${ya(c.head_sha)} ${Dx(c.verdict)(Xc(c.verdict).padEnd(16))} ${u.dim(R(c.created_at))}`);if(i.history_truncated)console.log(u.dim(" (older reviews not shown)"))}mm(i.environment),console.log()});async function f1e(e,t){let n=await $i();if(!n.ok){if(console.log(u.yellow(`Cannot ${t?"approve":"act"} from here: ${n.reason}`)),t)l1e(t.dataset,t.pr,t.url);process.exit(1)}let{token:r,source:o}=n,s=o==="GH_TOKEN"?"GH_TOKEN":"the token gh holds",i=await hD(r,e);if(!i.ok){if(console.log(u.red(i.reason)),console.log(u.dim(` (the token came from ${s})`)),i.kind==="rejected"&&o==="GH_TOKEN")console.log(u.dim(" Unset GH_TOKEN to use the account gh is signed in as."));if(i.kind==="not_a_person"&&t)l1e(t.dataset,t.pr,t.url);process.exit(1)}let a;try{a=(await co()).github_username??null}catch(l){return ba(l,null,"Could not read your NEMAR account")}let c=gD(a,i.user.login);if(c==="mismatch")an(o==="GH_TOKEN"?`GH_TOKEN belongs to @${i.user.login}, but your NEMAR account is linked to @${R(a)}.`:`gh is signed in as @${i.user.login}, but your NEMAR account is linked to @${R(a)}.`,o==="GH_TOKEN"?"Unset GH_TOKEN, or set it to your own token. A review, comment or merge is recorded under the login that makes it.":"Switch with 'gh auth switch'. A review, comment or merge is recorded under the login that makes it.");return{token:r,me:i.user,match:c}}async function p1e(e,t,n,r){let o=await Hs(e,t,n,r);if(!o.ok)return{ok:!1,stop:{kind:o.status===404||o.status===403?"unreadable":"failed",message:o.reason}};let s=oEe(o.value);if(s)return{ok:!1,stop:{kind:"refused",message:s}};let i=o.value.headSha,a="not_reviewed",c=null,l=null,d=null,f=null,p=null,m;try{let g=yD(await ty(t,n,i),i);if(g.ok)({verdict:a,detail:c,staleVerdict:l,reviewCurrent:d,contributorNote:f,outcome:p}=g);else m=g.why}catch(g){let y=mb(g);if(y==="not_owned_here"||y==="github_unavailable")m=g instanceof U?R(g.message):"the NEMAR API did not answer";else if(y==="no_such_pull_request")m="the NEMAR API could not find this pull request on GitHub";else return{ok:!1,stop:{kind:"failed",message:"Could not read the automated review",error:g}}}let h=bD({verdict:a,staleVerdict:l,unread:m});return{ok:!0,value:{live:o.value,head:i,verdict:a,detail:c,staleVerdict:l,reviewCurrent:d,contributorNote:f,outcome:p,unread:m,gate:h}}}function m1e(e){return e.unread?u.yellow(`unknown (${R(e.unread)})`):Dx(e.verdict)(Cx({verdict:e.verdict,detail:e.detail,review_current:e.reviewCurrent}))}function h1e(e){let{stop:t}=e;if(t.kind==="failed"&&t.error!==void 0)return ba(t.error,null,t.message);return an(t.message)}var o1e={duplicate:"this commit already has a review (running or finished)",review_running:"a review of this commit is running, and a redo waits until it reports or its time (about an hour) is up",contributor_paused:"the contributor is blocked by an administrator",exempt_author:"its author is a NEMAR owner or administrator, and a legacy API reported a review exemption",exempt_naming_waived:"a legacy API reported an owner/admin exemption, and the naming rule was waived for this commit",naming_rule:"a legacy API reported an owner/admin exemption, and the naming rule refused its title or its new dataset name, so its check failed",naming_unchecked:"a legacy API reported an owner/admin exemption, and its dataset name could not be read to check the naming rule, so its check needs a person",repull_waived:"it is an upstream re-pull's own pull request at the commit NEMAR recorded, so the review is waived and its check was posted as skipped, titled Waived: upstream re-pull",draft:"it is a draft",not_open:"it is not open any more",not_main:"it does not target main",bot_author:"a bot opened it",dataset_not_reviewable:"the dataset is not a public, named publication",unknown_dataset:"NEMAR has no such dataset",pr_review_disabled:"the automated review is off in this environment (PR_REVIEW_ENABLED)",dispatch_failed:"GitHub did not accept the dispatch",misconfigured:"the Worker is missing a secret the review needs",malformed:"GitHub's record of the pull request could not be read"},$x=new Set(["pr_review_disabled","dispatch_failed","misconfigured","unknown_dataset","malformed","naming_unchecked"]);function g1e(e){return Object.hasOwn(o1e,e)?o1e[e]:void 0}function y1e(e){return e.reason.startsWith("redispatched")?"started again":"started"}function b1e(e){let t=g1e(e.reason)??R(e.reason).replaceAll("_"," "),n=e.reason==="contributor_paused"&&e.author_login?` (lift it with: nemar admin pr-reviews allow ${R(e.author_login)})`:e.reason==="naming_rule"?" (the author fixes the title or the name; to waive the rule for this commit: nemar admin pr-reviews allow <dataset> <pr> --admin --reason <why>)":e.reason==="naming_unchecked"?" (GitHub may not have answered, or dataset_description.json has no readable Name: run the same command once more, which reads the name again and posts the check it comes to; if it says the same, fix dataset_description.json and push, because nothing can be waived until the name can be read)":"";return`not started: ${t}${n}`}wa.command("start [dataset] [pr]").description("Review a pull request that is already open, or start again one whose review ended without a verdict (or, with --redo, has a result)").option("--all","Every open pull request whose current commit has no review, or one that was declined or ended without a verdict (regardless of author role; a legacy API exemption or recorded re-pull waiver is left out, as is one refused for too many edits, which is started by name)").option("--redo","Also start again a commit whose review already has a result (a second run, which costs model calls); with --all, the pull requests whose current commit has a pass, fail or uncertain review are included").option("--concurrency <n>","With --all: keep at most n of the reviews this run started in progress at once, starting the next as each reports (the default starts them all at once)").option("--dry-run","With --all: list what would be started and start nothing").option("-y, --yes","With --all: do not ask before starting").option("--json","Output JSON instead of text").addHelpText("after",`
|
|
1157
1149
|
The automated review runs when GitHub tells the NEMAR API that a pull request was opened, pushed to,
|
|
1158
1150
|
reopened or marked ready for review, or that its title, description or target branch was edited. A
|
|
1159
1151
|
pull request that was already open when the review was switched on produced no such event, so it has
|
|
1160
1152
|
no review until one of those happens to it. This asks for one by name. The API reads the pull request
|
|
1161
1153
|
from GitHub itself and runs it through the same gate as any other: an administrator's block on the
|
|
1162
|
-
contributor still applies,
|
|
1163
|
-
|
|
1164
|
-
skipped when the rule finds nothing (or an administrator waived it for this commit), failed when it
|
|
1165
|
-
refuses the title or the new dataset name, and one that needs a person when the name could not be
|
|
1166
|
-
read. No count of reviews, and no record of rejected pull requests, holds a start back. A commit
|
|
1154
|
+
contributor still applies, including to owners and administrators. Author role does not skip review.
|
|
1155
|
+
No count of reviews, and no record of rejected pull requests, holds a start back. A commit
|
|
1167
1156
|
whose review was declined, ended in an error or never reported is started again, and so is one
|
|
1168
1157
|
handed to GitHub more than 60 minutes ago that never came back and that no job claimed in the last
|
|
1169
1158
|
50 minutes; one that is running or has a
|
|
@@ -1176,8 +1165,7 @@ A finished review is not run again by anything but --redo, or by an edit of the
|
|
|
1176
1165
|
description or target branch, a reopening or a marking as ready (five of those at most for one commit).
|
|
1177
1166
|
--redo starts it again on the same review: its old result leaves the pull request's check while the new
|
|
1178
1167
|
run is going. A blocked contributor's pull request is not redone: the block is the answer and the
|
|
1179
|
-
finished review stands.
|
|
1180
|
-
review of its current commit is on record. A review that is running, or whose job has not had its
|
|
1168
|
+
finished review stands. Owners and administrators receive the same review as other contributors. A review that is running, or whose job has not had its
|
|
1181
1169
|
time yet, is never started again, so a redo waits for it. A redo leaves the count of edits as it is
|
|
1182
1170
|
(it is no edit), and costs a second run of up to two model calls. A bulk redo cannot be resumed:
|
|
1183
1171
|
running it again redoes the reviews that finished in between.
|
|
@@ -1213,7 +1201,7 @@ any other and declined by the Worker, which says so; after 'allow', the same com
|
|
|
1213
1201
|
Would start ${c.length} pull request${c.length===1?"":"s"}, at most ${r} running at once.`);console.log(u.dim(`
|
|
1214
1202
|
This was a dry run: nothing was started.`))}return}if(!t)console.log();if(await Re(fFt(c.length,n,r),{yes:e.yes})!=="confirmed")(t?console.error:console.log)("Cancelled."),process.exit(1);let m=[],h=0,g=!1,y=new AbortController,b=0,x=0,v=null,S=()=>{let T=Date.now();if(b>0&&T-x<500)return;if(x=T,b++,b>1){if(!t&&v!==null)console.log(u.dim(`
|
|
1215
1203
|
The start of ${v} was in flight; check it with: nemar admin pr-reviews show ${v.replace(" #"," ")}`));process.exit(130)}if(y.abort(),!t)console.log(u.dim(`
|
|
1216
|
-
Stopping after the request in flight; press Ctrl-C again to exit now.`))};process.on("SIGINT",S);let E="",O;try{O=await dEe(c,{start:async(T)=>{v=`${T.dataset_id} #${T.pr_number}`;try{return await BM(T.dataset_id,T.pr_number,{redo:n})}finally{v=null}},isRunning:(T)=>T.dispatched,maybeRunning:yFt,inProgress:hFt,confirmFinished:gFt,sleep:fEe,onUnknown:({count:T,max:L})=>{if(t)return;console.log(u.dim(` could not read the admin list completely (${T} of ${L}); still waiting`))},stopAfter:(T)=>{if(n&&T.redo!==!0)return g=!0,!0;return!1},onWait:({running:T,remaining:L})=>{let q=`${T} running (limit ${r}); ${L} to go: waiting for one to report`;if(t||q===E)return;E=q,console.log(u.dim(` ${q}`))},onResult:(T,L)=>{let q=`${T.dataset_id} #${T.pr_number}`;if("answer"in L){let M=L.answer;if(m.push({...M,dataset_id:T.dataset_id,pr_number:T.pr_number}),!t)console.log(` ${q} ${M.dispatched?u.green(y1e(M)):u.yellow(b1e(M))}`);return}h++;let G=L.error,B=G instanceof U?mb(G)??`http_${G.statusCode}`:"unknown";if(m.push({dataset_id:T.dataset_id,pr_number:T.pr_number,error:B}),!t){let M=B==="no_such_pull_request";console.log(` ${q} ${u.red(M?"failed: GitHub has no such pull request":`failed: ${G instanceof U?R(G.message):"could not be started"}`)}`)}}},{concurrency:r??Number.POSITIVE_INFINITY,pollMs:pFt(),maxUnknownPolls:s1e,maxHoldMs:bFt,signal:y.signal})}finally{process.off("SIGINT",S)}let I=O.stoppedBy==="interrupted"||O.stoppedBy==="unknown_polls"?O.stoppedBy:null;if(t)console.log(JSON.stringify({...f,results:m,failed:h,...g?{redo_ignored:!0}:{},...I?{stopped_by:I}:{},...r!==void 0||O.notStarted.length>0?{not_started:O.notStarted.map((T)=>({dataset_id:T.dataset_id,pr_number:T.pr_number,author_login:T.author_login}))}:{}},null,2));else{let T=m.filter((B)=>("reason"in B)),L=T.filter((B)=>B.dispatched).length,q=T.filter((B)=>B.reason==="duplicate").length,G=T.length-L-q;if(console.log(),console.log(`${L} started, ${q} already had a review, ${G} not started, ${h} failed`),mm(s.environment),g){let B=c.length-m.length;console.log(u.red(B>0?`${Hq} ${B} pull request${B===1?" was":"s were"} not tried.`:Hq))}if(I){let B=O.notStarted.length;console.log(u.yellow(I==="interrupted"?`Interrupted: ${B} pull request${B===1?"":"s"} not started. Reviews already started keep running.`:`The admin list could not be read completely ${s1e} times in a row, so the limit of ${r} running at once cannot be kept: ${B} pull request${B===1?"":"s"} not started. Reviews already started keep running.`));let M=m.filter((P)=>("error"in P));for(let P of O.notStarted)console.log(n?` nemar admin pr-reviews start ${P.dataset_id} ${P.pr_number} --redo`:` ${P.dataset_id} #${P.pr_number}`);if(M.length>0){console.log(u.dim("Their start failed (see above); check each before starting it again:"));for(let P of M)console.log(u.dim(` nemar admin pr-reviews show ${P.dataset_id} ${P.pr_number}`))}if(n&&B>0)console.log(u.dim("Run these by name: running --all --redo again would redo the finished reviews once more. They start at once, so paste a few at a time."));else if(B>0)console.log(u.dim("Run the same command again to start these: it takes up only what has no review."))}}if(g&&h===0)de();if(I==="interrupted")process.exit(130);let V=m.some((T)=>("reason"in T)&&!T.dispatched&&$x.has(T.reason));if(h>0||V||g||I==="unknown_polls")process.exit(1)}function Gq(e,t,n){if(e==="none")return null;if(e==="retry"||e==="rerun"){if(t==="next")return"s skips it; run 'nemar admin pr-reviews next' again to look again.";return e==="retry"?"Run the same command again in a moment.":"Run the same command again to read it as it is now."}return t==="approve"?"To approve without merging, run it again without --merge. The merge is then yours to make on GitHub.":`To approve it without merging, run: nemar admin pr-reviews approve ${n.dataset} ${n.pr} (without --merge). Here, s leaves it and c comments.`}function c1e(e,t){return an(`${e.why} Nothing was approved or merged.`,Gq(e.advice,"approve",t)??void 0)}wa.command("approve <dataset> <pr>").description("Approve a pull request as YOURSELF (your GitHub login); merges only with --merge").option("--merge","Merge it after approving, once (refused before anything is approved unless GitHub reports it clean)").option("--method <method>",`How to merge, with --merge: ${xD.join(", ")}`,"merge").option("--message <text>","The text of your approval").option("--force","Approve although the review failed, is running, or could not be read").option("--dry-run","Check your token, the pull request and the review and show what would be approved; approve and merge nothing").option("-y, --yes","Do not ask for confirmation (a failing, running or unreadable review still needs --force)").action(async(e,t,n,r)=>{if(!du())process.exit(1);let o=hb(e),s=JA(t),i=n.method;if(!xD.includes(i))an(`"${R(n.method)}" is not a merge method.`,`Use: ${xD.join(", ")}`);let a=mD(o,s),c;try{c=Sn()}catch(q){return an(q instanceof Error?q.message:String(q))}let{token:l,me:d,match:f}=await f1e(c,{dataset:o,pr:s,url:a}),p=await p1e(l,o,s,c);if(!p.ok)return h1e(p);let{live:m,head:h,verdict:g,detail:y,reviewCurrent:b,contributorNote:x,unread:v,gate:S}=p.value;if(S.kind==="needs_force"&&!n.force)an(S.reason);let E=async()=>{let q=await G4({datasetId:o,prNumber:s,headRef:m.headRef,token:l,base:c,env:process.env,configDir:rr(),force:n.force===!0});if(q.kind==="refused")an(`${q.reason} Nothing was approved or merged.`);return q.kind==="repull"?q.check:null},O=null;if(n.merge){if(O=await E(),O&&i!=="squash"&&r.getOptionValueSource("method")==="cli")an(`An upstream re-pull's pull request is squash-merged (ADR 0111), and --method ${i} was asked for. Nothing was approved or merged.`)}if(n.merge&&!O){let q=await vy(l,o,s,m,{base:c});if(!q.ok)c1e(q,{dataset:o,pr:s})}if(console.log(),console.log(u.bold(`Approve ${o} #${s}`)),console.log(` Author: @${R(m.authorLogin)}`),console.log(` Commit: ${ya(h)}`),console.log(` Review: ${m1e({verdict:g,detail:y,reviewCurrent:b,unread:v})}`),x)console.log(u.yellow(` ${R(x)}`));if(console.log(` You are: @${d.login} ${f==="match"?u.dim("(linked to your NEMAR account)"):u.yellow("(your NEMAR account names no GitHub login, so this cannot be checked)")}`),S.kind==="confirm")console.log(u.yellow(` ${S.warning}`));if(S.kind==="needs_force")console.log(u.yellow(" Approving anyway (--force)."));if(n.merge&&O){console.log(` Then: squash-merge through the re-pull's gate. ${sA(O.row,O.pr)}`);for(let q of O.warnings)console.log(u.yellow(` ${q}`))}else if(n.merge)console.log(` Then: merge (${i}) if GitHub reports it clean`);if(n.dryRun){console.log(),console.log(u.cyan("Dry run: nothing was approved or merged."));return}if(await Re(`Approve ${o} #${s} as @${d.login}?`,{yes:n.yes})!=="confirmed")console.log(u.dim("Not approved.")),process.exit(1);if(n.merge&&O){if(O=await E(),!O)an("This is no longer a re-pull's pull request it can merge. Nothing was approved or merged.")}else if(n.merge){let q=await wj(l,o,s,h,{base:c});if(!q.ok)c1e(q,{dataset:o,pr:s})}let V=n.message?.slice(0,2000)||`Approved with nemar admin pr-reviews approve. Automated review of this commit: ${v?"unknown":Xc(g)}.`,T=await bj(l,o,s,h,d.login,V,c);if(!T.ok){if(T.outcome==="unknown")console.log(u.yellow(T.reason)),console.log(u.yellow(`Outcome unknown: GitHub may have recorded the approval. Check ${a} before trying again.`)),process.exit(1);if(T.outcome==="different")an(T.reason,`Check ${a} before trying again.`);an(`Not approved: ${T.reason}`)}if(console.log(u.green(`Approved ${o} #${s} at ${ya(h)} as @${d.login}.`)),!n.merge){let q=xy(m.mergeableState);console.log(u.dim(!q.ok&&q.advice==="without_merge"?` It is not merged. ${q.why} Merge it on GitHub when you decide to.`:" It is not merged. Run approve again with --merge (this records another approval), or merge it on GitHub."));return}if(O){let q=await fx({datasetId:o,token:l,base:c,env:process.env,configDir:rr(),force:n.force===!0},O,{out:(G)=>console.log(u.dim(` ${G}`))});if(!q.merged){if(console.log(u.yellow(`Not merged (${q.stage}): ${q.reason}`)),q.claimHeld)de();process.exit(q.claimHeld?vf:1)}if(!q.recorded)console.log(u.yellow(x1e(o,s))),de(),process.exit(vf);console.log(u.green(`Merged ${o} #${s} (squash, through the re-pull's gate).`));return}let L=await g_(l,o,s,h,i,{base:c});if(!L.ok){if(console.log(u.yellow(L.reason)),L.outcome==="unknown")console.log(u.yellow(`Outcome unknown: GitHub may have merged it. Check ${a} before trying again.`));process.exit(1)}console.log(u.green(`Merged ${o} #${s} (${i}).`))});function vFt(e){let t=[e.merged&&`${e.merged} merged`,e.approved&&`${e.approved} approved but not merged`,e.closed&&`${e.closed} closed`,e.commented&&`${e.commented} commented`,e.skipped&&`${e.skipped} skipped`,e.failed&&`${e.failed} failed`,e.unknown&&`${e.unknown} with an unknown outcome (check the pull request)`].filter(Boolean);return t.length===0?"Nothing was changed.":`Done: ${t.join(", ")}.`}function EFt(e){return e.skipped+e.failed+e.unknown+e.approved}function HA(e,t){if(e.outcome==="unknown")return console.log(u.yellow(e.reason)),console.log(u.yellow(`Outcome unknown: GitHub may have ${t.mayHave}. Check ${t.url}.`)),t.tally.unknown++,!0;if(e.outcome==="different")return console.log(u.red(e.reason)),console.log(u.dim(` Check ${t.url}.`)),t.tally.unknown++,!0;if(t.tally[t.bucket]++,e.outcome==="not_sent")return console.log(u.yellow(e.reason)),!1;return console.log(u.red(`Not ${t.didNot}: ${e.reason}`)),!1}function SFt(e){if(e.unread)return`The report could not be read (${R(e.unread)}).`;if(e.reviewCurrent===!1)return"The review on record is of another commit, so its report is not shown.";if(e.verdict==="in_progress")return"The review is still running.";if(e.verdict==="exempt")return"A NEMAR owner or administrator opened this pull request, so it is not reviewed.";if(e.verdict==="waived")return"This commit is an upstream re-pull's own head, so the review is waived; what a review of it found is shown as recommendations.";if(e.verdict==="not_reviewed")return"This commit has not been reviewed.";return"A review of this commit is on record, but its report could not be read."}wa.command("next").description("Go through the pull requests that need you, one at a time: y approves and squash-merges, n closes with a comment, c comments").option("--dataset <id>","Only this dataset").option("--author <login>","Only pull requests opened by this GitHub login").option("--all","Include pull requests whose review failed or is still running").option("--force","Let y approve although the review failed, is running, or could not be read").option("--once","Handle one pull request and stop").addHelpText("after",`
|
|
1204
|
+
Stopping after the request in flight; press Ctrl-C again to exit now.`))};process.on("SIGINT",S);let E="",O;try{O=await dEe(c,{start:async(T)=>{v=`${T.dataset_id} #${T.pr_number}`;try{return await BM(T.dataset_id,T.pr_number,{redo:n})}finally{v=null}},isRunning:(T)=>T.dispatched,maybeRunning:yFt,inProgress:hFt,confirmFinished:gFt,sleep:fEe,onUnknown:({count:T,max:L})=>{if(t)return;console.log(u.dim(` could not read the admin list completely (${T} of ${L}); still waiting`))},stopAfter:(T)=>{if(n&&T.redo!==!0)return g=!0,!0;return!1},onWait:({running:T,remaining:L})=>{let q=`${T} running (limit ${r}); ${L} to go: waiting for one to report`;if(t||q===E)return;E=q,console.log(u.dim(` ${q}`))},onResult:(T,L)=>{let q=`${T.dataset_id} #${T.pr_number}`;if("answer"in L){let M=L.answer;if(m.push({...M,dataset_id:T.dataset_id,pr_number:T.pr_number}),!t)console.log(` ${q} ${M.dispatched?u.green(y1e(M)):u.yellow(b1e(M))}`);return}h++;let G=L.error,B=G instanceof U?mb(G)??`http_${G.statusCode}`:"unknown";if(m.push({dataset_id:T.dataset_id,pr_number:T.pr_number,error:B}),!t){let M=B==="no_such_pull_request";console.log(` ${q} ${u.red(M?"failed: GitHub has no such pull request":`failed: ${G instanceof U?R(G.message):"could not be started"}`)}`)}}},{concurrency:r??Number.POSITIVE_INFINITY,pollMs:pFt(),maxUnknownPolls:s1e,maxHoldMs:bFt,signal:y.signal})}finally{process.off("SIGINT",S)}let I=O.stoppedBy==="interrupted"||O.stoppedBy==="unknown_polls"?O.stoppedBy:null;if(t)console.log(JSON.stringify({...f,results:m,failed:h,...g?{redo_ignored:!0}:{},...I?{stopped_by:I}:{},...r!==void 0||O.notStarted.length>0?{not_started:O.notStarted.map((T)=>({dataset_id:T.dataset_id,pr_number:T.pr_number,author_login:T.author_login}))}:{}},null,2));else{let T=m.filter((B)=>("reason"in B)),L=T.filter((B)=>B.dispatched).length,q=T.filter((B)=>B.reason==="duplicate").length,G=T.length-L-q;if(console.log(),console.log(`${L} started, ${q} already had a review, ${G} not started, ${h} failed`),mm(s.environment),g){let B=c.length-m.length;console.log(u.red(B>0?`${Hq} ${B} pull request${B===1?" was":"s were"} not tried.`:Hq))}if(I){let B=O.notStarted.length;console.log(u.yellow(I==="interrupted"?`Interrupted: ${B} pull request${B===1?"":"s"} not started. Reviews already started keep running.`:`The admin list could not be read completely ${s1e} times in a row, so the limit of ${r} running at once cannot be kept: ${B} pull request${B===1?"":"s"} not started. Reviews already started keep running.`));let M=m.filter((P)=>("error"in P));for(let P of O.notStarted)console.log(n?` nemar admin pr-reviews start ${P.dataset_id} ${P.pr_number} --redo`:` ${P.dataset_id} #${P.pr_number}`);if(M.length>0){console.log(u.dim("Their start failed (see above); check each before starting it again:"));for(let P of M)console.log(u.dim(` nemar admin pr-reviews show ${P.dataset_id} ${P.pr_number}`))}if(n&&B>0)console.log(u.dim("Run these by name: running --all --redo again would redo the finished reviews once more. They start at once, so paste a few at a time."));else if(B>0)console.log(u.dim("Run the same command again to start these: it takes up only what has no review."))}}if(g&&h===0)de();if(I==="interrupted")process.exit(130);let V=m.some((T)=>("reason"in T)&&!T.dispatched&&$x.has(T.reason));if(h>0||V||g||I==="unknown_polls")process.exit(1)}function Gq(e,t,n){if(e==="none")return null;if(e==="retry"||e==="rerun"){if(t==="next")return"s skips it; run 'nemar admin pr-reviews next' again to look again.";return e==="retry"?"Run the same command again in a moment.":"Run the same command again to read it as it is now."}return t==="approve"?"To approve without merging, run it again without --merge. The merge is then yours to make on GitHub.":`To approve it without merging, run: nemar admin pr-reviews approve ${n.dataset} ${n.pr} (without --merge). Here, s leaves it and c comments.`}function c1e(e,t){return an(`${e.why} Nothing was approved or merged.`,Gq(e.advice,"approve",t)??void 0)}wa.command("approve <dataset> <pr>").description("Approve a pull request as YOURSELF (your GitHub login); merges only with --merge").option("--merge","Merge it after approving, once (refused before anything is approved unless GitHub reports it clean)").option("--method <method>",`How to merge, with --merge: ${xD.join(", ")}`,"merge").option("--message <text>","The text of your approval").option("--force","Approve although the review failed, is running, or could not be read").option("--dry-run","Check your token, the pull request and the review and show what would be approved; approve and merge nothing").option("-y, --yes","Do not ask for confirmation (a failing, running or unreadable review still needs --force)").action(async(e,t,n,r)=>{if(!du())process.exit(1);let o=hb(e),s=JA(t),i=n.method;if(!xD.includes(i))an(`"${R(n.method)}" is not a merge method.`,`Use: ${xD.join(", ")}`);let a=mD(o,s),c;try{c=Sn()}catch(q){return an(q instanceof Error?q.message:String(q))}let{token:l,me:d,match:f}=await f1e(c,{dataset:o,pr:s,url:a}),p=await p1e(l,o,s,c);if(!p.ok)return h1e(p);let{live:m,head:h,verdict:g,detail:y,reviewCurrent:b,contributorNote:x,unread:v,gate:S}=p.value;if(S.kind==="needs_force"&&!n.force)an(S.reason);let E=async()=>{let q=await G4({datasetId:o,prNumber:s,headRef:m.headRef,token:l,base:c,env:process.env,configDir:rr(),force:n.force===!0});if(q.kind==="refused")an(`${q.reason} Nothing was approved or merged.`);return q.kind==="repull"?q.check:null},O=null;if(n.merge){if(O=await E(),O&&i!=="squash"&&r.getOptionValueSource("method")==="cli")an(`An upstream re-pull's pull request is squash-merged (ADR 0111), and --method ${i} was asked for. Nothing was approved or merged.`)}if(n.merge&&!O){let q=await vy(l,o,s,m,{base:c});if(!q.ok)c1e(q,{dataset:o,pr:s})}if(console.log(),console.log(u.bold(`Approve ${o} #${s}`)),console.log(` Author: @${R(m.authorLogin)}`),console.log(` Commit: ${ya(h)}`),console.log(` Review: ${m1e({verdict:g,detail:y,reviewCurrent:b,unread:v})}`),x)console.log(u.yellow(` ${R(x)}`));if(console.log(` You are: @${d.login} ${f==="match"?u.dim("(linked to your NEMAR account)"):u.yellow("(your NEMAR account names no GitHub login, so this cannot be checked)")}`),S.kind==="confirm")console.log(u.yellow(` ${S.warning}`));if(S.kind==="needs_force")console.log(u.yellow(" Approving anyway (--force)."));if(n.merge&&O){console.log(` Then: squash-merge through the re-pull's gate. ${sA(O.row,O.pr)}`);for(let q of O.warnings)console.log(u.yellow(` ${q}`))}else if(n.merge)console.log(` Then: merge (${i}) if GitHub reports it clean`);if(n.dryRun){console.log(),console.log(u.cyan("Dry run: nothing was approved or merged."));return}if(await Re(`Approve ${o} #${s} as @${d.login}?`,{yes:n.yes})!=="confirmed")console.log(u.dim("Not approved.")),process.exit(1);if(n.merge&&O){if(O=await E(),!O)an("This is no longer a re-pull's pull request it can merge. Nothing was approved or merged.")}else if(n.merge){let q=await wj(l,o,s,h,{base:c});if(!q.ok)c1e(q,{dataset:o,pr:s})}let V=n.message?.slice(0,2000)||`Approved with nemar admin pr-reviews approve. Automated review of this commit: ${v?"unknown":Xc(g)}.`,T=await bj(l,o,s,h,d.login,V,c);if(!T.ok){if(T.outcome==="unknown")console.log(u.yellow(T.reason)),console.log(u.yellow(`Outcome unknown: GitHub may have recorded the approval. Check ${a} before trying again.`)),process.exit(1);if(T.outcome==="different")an(T.reason,`Check ${a} before trying again.`);an(`Not approved: ${T.reason}`)}if(console.log(u.green(`Approved ${o} #${s} at ${ya(h)} as @${d.login}.`)),!n.merge){let q=xy(m.mergeableState);console.log(u.dim(!q.ok&&q.advice==="without_merge"?` It is not merged. ${q.why} Merge it on GitHub when you decide to.`:" It is not merged. Run approve again with --merge (this records another approval), or merge it on GitHub."));return}if(O){let q=await fx({datasetId:o,token:l,base:c,env:process.env,configDir:rr(),force:n.force===!0},O,{out:(G)=>console.log(u.dim(` ${G}`))});if(!q.merged){if(console.log(u.yellow(`Not merged (${q.stage}): ${q.reason}`)),q.claimHeld)de();process.exit(q.claimHeld?vf:1)}if(!q.recorded)console.log(u.yellow(x1e(o,s))),de(),process.exit(vf);console.log(u.green(`Merged ${o} #${s} (squash, through the re-pull's gate).`));return}let L=await g_(l,o,s,h,i,{base:c});if(!L.ok){if(console.log(u.yellow(L.reason)),L.outcome==="unknown")console.log(u.yellow(`Outcome unknown: GitHub may have merged it. Check ${a} before trying again.`));process.exit(1)}console.log(u.green(`Merged ${o} #${s} (${i}).`))});function vFt(e){let t=[e.merged&&`${e.merged} merged`,e.approved&&`${e.approved} approved but not merged`,e.closed&&`${e.closed} closed`,e.commented&&`${e.commented} commented`,e.skipped&&`${e.skipped} skipped`,e.failed&&`${e.failed} failed`,e.unknown&&`${e.unknown} with an unknown outcome (check the pull request)`].filter(Boolean);return t.length===0?"Nothing was changed.":`Done: ${t.join(", ")}.`}function EFt(e){return e.skipped+e.failed+e.unknown+e.approved}function HA(e,t){if(e.outcome==="unknown")return console.log(u.yellow(e.reason)),console.log(u.yellow(`Outcome unknown: GitHub may have ${t.mayHave}. Check ${t.url}.`)),t.tally.unknown++,!0;if(e.outcome==="different")return console.log(u.red(e.reason)),console.log(u.dim(` Check ${t.url}.`)),t.tally.unknown++,!0;if(t.tally[t.bucket]++,e.outcome==="not_sent")return console.log(u.yellow(e.reason)),!1;return console.log(u.red(`Not ${t.didNot}: ${e.reason}`)),!1}function SFt(e){if(e.unread)return`The report could not be read (${R(e.unread)}).`;if(e.reviewCurrent===!1)return"The review on record is of another commit, so its report is not shown.";if(e.verdict==="in_progress")return"The review is still running.";if(e.verdict==="exempt")return"A legacy API reported an exemption for this pull request; this is not a review pass.";if(e.verdict==="waived")return"This commit is an upstream re-pull's own head, so the review is waived; what a review of it found is shown as recommendations.";if(e.verdict==="not_reviewed")return"This commit has not been reviewed.";return"A review of this commit is on record, but its report could not be read."}wa.command("next").description("Go through the pull requests that need you, one at a time: y approves and squash-merges, n closes with a comment, c comments").option("--dataset <id>","Only this dataset").option("--author <login>","Only pull requests opened by this GitHub login").option("--all","Include pull requests whose review failed or is still running").option("--force","Let y approve although the review failed, is running, or could not be read").option("--once","Handle one pull request and stop").addHelpText("after",`
|
|
1217
1205
|
For each pull request it shows who opened it, the automated review's summary, whether the two
|
|
1218
1206
|
required checks (BIDS and version) are green and whether the version went up, then waits for one
|
|
1219
1207
|
answer:
|
|
@@ -1240,22 +1228,17 @@ No more pull requests to show${z>0?`, but ${z} still ${z===1?"needs":"need"} you
|
|
|
1240
1228
|
${g.dataset_id} #${g.pr_number}: skipped, ${P.message}`)),P.kind==="unreadable")c.failed++;continue}return p(),h1e(b)}let x=b.value,v=x.head!==g.head_sha,S=v?"unknown":g.bids,E=v?"unknown":g.version,O=await vy(o.token,g.dataset_id,g.pr_number,x.live,{base:r}),I=()=>G4({datasetId:g.dataset_id,prNumber:g.pr_number,headRef:x.live.headRef,token:o.token,base:r,env:process.env,configDir:rr(),force:e.force===!0}),V=await I(),T=lEe({gate:x.gate,force:e.force===!0,bids:S,version:E,merge:O}),L=V.kind==="refused"?{ok:!1,reason:V.reason}:T,q=x.outcome,G=q?.kind==="reported"?lj(q.report):null;if(console.log(),console.log(`${u.bold(`[${a.size} of ${a.size-1+h.length}] ${R(g.dataset_id)} #${g.pr_number}`)} ${u.dim(y)}`),console.log(` Title: ${Ln(g.title,100)}`),console.log(` Author: @${R(x.live.authorLogin)} (${g.from_fork?"fork ":"branch "}${R(g.head_label)}), opened ${Ww(g.created_at)} ago`),console.log(` Commit: ${ya(x.head)}${v?u.yellow(" (changed since the list was read)"):""}`),console.log(` Review: ${m1e(x)}`),console.log(` Checks: BIDS ${zA(S,0)} version ${zA(E,0)}`),!O.ok)console.log(u.yellow(` Merge: ${O.card}`));if(V.kind==="repull")console.log(` Re-pull: #${V.check.row.id}; y squash-merges it through the re-pull's gate. ${sA(V.check.row,V.check.pr)}`);if(x.contributorNote)console.log(u.yellow(` ${R(x.contributorNote)}`));if(x.gate.kind==="confirm")console.log(u.yellow(` ${x.gate.warning}`));if(x.gate.kind==="needs_force"&&e.force)console.log(u.red(` --force: y will approve although the review ${x.unread?"could not be read":x.verdict==="in_progress"?"is still running":"says it needs changes"}.`));if(G!==null&&!x.unread&&x.verdict!==G)console.log(u.yellow(` The stored verdict is ${Xc(x.verdict)}; the report below would now read ${Xc(G)}. The stricter is used.`));let B=lFt(x.outcome);if(B.length>0){console.log();for(let P of B)console.log(` ${P}`)}if(!L.ok){console.log(),console.log(u.yellow(` y is not available: ${L.reason}`));let P=O.ok?null:Gq(O.advice,"next",{dataset:g.dataset_id,pr:g.pr_number});if(P)console.log(u.dim(` ${P}`))}let M=await i.discardTyped();if(M>0)console.log(u.dim(` Ignored ${M} line(s) typed before this card was shown.`));for(;;){let P=await i.ask(`
|
|
1241
1229
|
${L.ok?"y approve + squash merge, ":""}n close, c comment, d details, s skip, q quit > `);if(P===null){console.log(u.dim(`
|
|
1242
1230
|
${f()}`));break e}let z=cEe(P);if(z===null){console.log(u.dim(" Type y, n, c, d, s or q."));continue}if(z==="quit")break e;if(z==="details"){if(console.log(),x.outcome===null||x.outcome===void 0)console.log(u.dim(` ${SFt(x)}`));else for(let Me of d1e(x.outcome))console.log(Me);continue}if(z==="skip"){c.skipped++;break}if(z==="approve"){if(!L.ok){console.log(u.yellow(` Not approved: ${L.reason}`));continue}let Me=null;if(V.kind!=="ordinary"){if(Me=await I(),Me.kind!=="repull"){console.log(u.yellow(` Not approved: ${Me.kind==="refused"?Me.reason:"it is no longer a re-pull's pull request this run can merge."}`));continue}}let ne=Me?{ok:!0}:await wj(o.token,g.dataset_id,g.pr_number,x.head,{base:r});if(!ne.ok){console.log(u.yellow(` Not approved: ${ne.why}`));let Y=Gq(ne.advice,"next",{dataset:g.dataset_id,pr:g.pr_number});if(Y)console.log(u.dim(` ${Y}`));continue}let wt=`Approved with nemar admin pr-reviews next. Automated review of this commit: ${x.unread?"unknown":Xc(x.verdict)}.`,Je=await bj(o.token,g.dataset_id,g.pr_number,x.head,s,wt,r);if(!Je.ok){if(l=HA(Je,{didNot:"approved",mayHave:"recorded the approval",url:y,tally:c,bucket:"failed"}),l)break e;break}if(console.log(u.green(`Approved ${g.dataset_id} #${g.pr_number} at ${ya(x.head)} as @${s}.`)),Me?.kind==="repull"){let Y=await fx(Me.ctx,Me.check,{out:(pe)=>console.log(u.dim(` ${pe}`))});if(Y.merged&&!Y.recorded){console.log(u.yellow(x1e(g.dataset_id,g.pr_number))),c.unknown++,l=!0;break e}if(Y.merged){console.log(u.green(`Merged ${g.dataset_id} #${g.pr_number} (squash, through the re-pull's gate).`)),c.merged++;break}if(console.log(u.yellow(`Not merged (${Y.stage}): ${Y.reason}`)),Y.claimHeld){c.unknown++,l=!0;break e}c.approved++;break}let K=await g_(o.token,g.dataset_id,g.pr_number,x.head,"squash",{base:r});if(K.ok)console.log(u.green(`Merged ${g.dataset_id} #${g.pr_number} (squash).`)),c.merged++;else if(l=HA(K,{didNot:"merged",mayHave:"merged it",url:y,tally:c,bucket:"approved"}),l)break e;break}let ie=z==="close",$e=await i.ask(ie?"Comment for the author, posted before it is closed (empty cancels): ":"Comment (empty cancels): ");if($e===null){console.log(u.dim(`
|
|
1243
|
-
${f()}`));break e}let cn=await i.discardTyped(ED);if(cn>0){console.log(u.yellow(`A comment is one line; ${cn} more line(s) arrived with it. Nothing was sent.`));continue}let bt=$e.trim();if(bt===""){console.log(u.dim(" Cancelled. Nothing was sent."));continue}let st=await Hs(o.token,g.dataset_id,g.pr_number,r);if(!st.ok){console.log(u.yellow(`Could not re-read the pull request, so nothing was sent: ${st.reason}`)),c.failed++;break}if(st.value.state!=="open"||st.value.headSha!==x.head){console.log(u.yellow(`This pull request changed while it was open here (now ${st.value.state}, at ${ya(st.value.headSha)}). Nothing was sent.`)),c.skipped++;break}let ce=await sEe(o.token,g.dataset_id,g.pr_number,bt,r);if(!ce.ok){if(l=HA(ce,{didNot:"commented",mayHave:"posted the comment",url:y,tally:c,bucket:"failed"}),l)break e;break}if(!ie){console.log(u.green(`Commented on ${g.dataset_id} #${g.pr_number}.`)),c.commented++;break}console.log(u.dim(" The comment was posted."));let He=await _D(o.token,g.dataset_id,g.pr_number,r);if(!He.ok){if(l=HA(He,{didNot:"closed",mayHave:"closed it",url:y,tally:c,bucket:"failed"}),l)break e;break}console.log(u.green(`Closed ${g.dataset_id} #${g.pr_number}, with your comment.`)),c.closed++;break}if(e.once)break}if(p(),i.interrupted)process.exit(130);if(l||c.failed>0||c.unknown>0)process.exit(1)});function x1e(e,t){return`Merged ${e} #${t} on GitHub, but the merge is not recorded; run nemar admin repull resume ${e}, which records it.`}function l1e(e,t,n){if(console.log(),console.log("Approve it on GitHub with your own account:"),console.log(` ${n}`),console.log(` ${rEe(e,t)}`),process.stdout.isTTY)wy(n)}async function v1e(e,t,n){let r=Ax(t,n.json),o=n.json?null:C(`Setting ${e} for ${r}...`).start();try{let s=await _be(r,e,n.reason);if(o?.stop(),n.json){console.log(JSON.stringify(s,null,2));return}if(console.log(e==="allow"?u.green(`Allowed ${R(s.standing.login)}: their pull requests are reviewed automatically.`):u.red(`Blocked ${R(s.standing.login)}: none of their pull requests is reviewed automatically; each needs a person.`)),s.previous&&s.previous!==e)console.log(u.dim(` (it was ${s.previous} before)`));if(e==="allow")console.log(u.dim(" A pull request already opened is reviewed when it is pushed to, edited, reopened or marked ready for review, or when an administrator starts its review."));console.log();for(let i of KA(s.standing))console.log(i);mm(s.environment)}catch(s){ba(s,o,`Could not ${e} ${r}`,n.json)}}function kFt(e){if(e===null)return[];let t=[];if(e.title==="author_year"||e.title==="doi")t.push("the title has a citation (an author and a year, or a DOI)");if(e.title==="template_field")t.push("the title has an unfilled template field");if(e.name==="author_year"||e.name==="doi")t.push("the pull request changes the dataset name to one that has a citation (an author and a year, or a DOI)");if(e.name==="template_field")t.push("the pull request changes the dataset name to one with an unfilled template field");if(e.name==="unchecked")t.push("the dataset name could not be read to be checked");return t}function RFt(e,t,n){let r=e.head_sha?` at ${ya(e.head_sha)}`:"",o=`${R(t)} #${n}${r}`;switch(e.reason){case"waived":{let s=kFt(e.facts);return[u.green(`Waived the naming rule for ${o}.`),...s.length>0?[` The rule found: ${s.join("; ")}.`]:[],u.dim(" Its check is posted as skipped (not required) and says the rule was waived. The waiver is recorded with your reason, and it is for this commit only: a new commit is checked again.")]}case"already_waived":return[u.green(`The naming rule was already waived for ${o}.`),u.dim(" Its skipped check was posted again. Nothing new was recorded.")];case"nothing_to_waive":return[u.green(`Nothing to waive: the title and the dataset name of ${o} pass the naming rule.`),u.dim(" Its check was posted as skipped (not required). Nothing was recorded.")];case"not_exempt":return[u.yellow(`Not waived: the author of ${o} is not a NEMAR owner or administrator.`),u.dim("
|
|
1231
|
+
${f()}`));break e}let cn=await i.discardTyped(ED);if(cn>0){console.log(u.yellow(`A comment is one line; ${cn} more line(s) arrived with it. Nothing was sent.`));continue}let bt=$e.trim();if(bt===""){console.log(u.dim(" Cancelled. Nothing was sent."));continue}let st=await Hs(o.token,g.dataset_id,g.pr_number,r);if(!st.ok){console.log(u.yellow(`Could not re-read the pull request, so nothing was sent: ${st.reason}`)),c.failed++;break}if(st.value.state!=="open"||st.value.headSha!==x.head){console.log(u.yellow(`This pull request changed while it was open here (now ${st.value.state}, at ${ya(st.value.headSha)}). Nothing was sent.`)),c.skipped++;break}let ce=await sEe(o.token,g.dataset_id,g.pr_number,bt,r);if(!ce.ok){if(l=HA(ce,{didNot:"commented",mayHave:"posted the comment",url:y,tally:c,bucket:"failed"}),l)break e;break}if(!ie){console.log(u.green(`Commented on ${g.dataset_id} #${g.pr_number}.`)),c.commented++;break}console.log(u.dim(" The comment was posted."));let He=await _D(o.token,g.dataset_id,g.pr_number,r);if(!He.ok){if(l=HA(He,{didNot:"closed",mayHave:"closed it",url:y,tally:c,bucket:"failed"}),l)break e;break}console.log(u.green(`Closed ${g.dataset_id} #${g.pr_number}, with your comment.`)),c.closed++;break}if(e.once)break}if(p(),i.interrupted)process.exit(130);if(l||c.failed>0||c.unknown>0)process.exit(1)});function x1e(e,t){return`Merged ${e} #${t} on GitHub, but the merge is not recorded; run nemar admin repull resume ${e}, which records it.`}function l1e(e,t,n){if(console.log(),console.log("Approve it on GitHub with your own account:"),console.log(` ${n}`),console.log(` ${rEe(e,t)}`),process.stdout.isTTY)wy(n)}async function v1e(e,t,n){let r=Ax(t,n.json),o=n.json?null:C(`Setting ${e} for ${r}...`).start();try{let s=await _be(r,e,n.reason);if(o?.stop(),n.json){console.log(JSON.stringify(s,null,2));return}if(console.log(e==="allow"?u.green(`Allowed ${R(s.standing.login)}: their pull requests are reviewed automatically.`):u.red(`Blocked ${R(s.standing.login)}: none of their pull requests is reviewed automatically; each needs a person.`)),s.previous&&s.previous!==e)console.log(u.dim(` (it was ${s.previous} before)`));if(e==="allow")console.log(u.dim(" A pull request already opened is reviewed when it is pushed to, edited, reopened or marked ready for review, or when an administrator starts its review."));console.log();for(let i of KA(s.standing))console.log(i);mm(s.environment)}catch(s){ba(s,o,`Could not ${e} ${r}`,n.json)}}function kFt(e){if(e===null)return[];let t=[];if(e.title==="author_year"||e.title==="doi")t.push("the title has a citation (an author and a year, or a DOI)");if(e.title==="template_field")t.push("the title has an unfilled template field");if(e.name==="author_year"||e.name==="doi")t.push("the pull request changes the dataset name to one that has a citation (an author and a year, or a DOI)");if(e.name==="template_field")t.push("the pull request changes the dataset name to one with an unfilled template field");if(e.name==="unchecked")t.push("the dataset name could not be read to be checked");return t}function RFt(e,t,n){let r=e.head_sha?` at ${ya(e.head_sha)}`:"",o=`${R(t)} #${n}${r}`;switch(e.reason){case"waived":{let s=kFt(e.facts);return[u.green(`Waived the naming rule for ${o}.`),...s.length>0?[` The rule found: ${s.join("; ")}.`]:[],u.dim(" Its check is posted as skipped (not required) and says the rule was waived. The waiver is recorded with your reason, and it is for this commit only: a new commit is checked again.")]}case"already_waived":return[u.green(`The naming rule was already waived for ${o}.`),u.dim(" Its skipped check was posted again. Nothing new was recorded.")];case"nothing_to_waive":return[u.green(`Nothing to waive: the title and the dataset name of ${o} pass the naming rule.`),u.dim(" Its check was posted as skipped (not required). Nothing was recorded.")];case"not_exempt":return[u.yellow(`Not waived: the author of ${o} is not a NEMAR owner or administrator.`),u.dim(" This explicit naming override is limited to owner/admin authors. Ordinary reviews apply to every author role; fix the title or name, or use the separate authorized GitHub merge-override workflow.")];case"reviewed":return[u.yellow(`Not waived: ${o} has a review on record, and that review stands.`)];case"naming_unchecked":return[u.yellow(`Not waived: the dataset name of ${o} could not be read, so there is nothing definite to waive.`),u.dim(" A waiver covers only what the naming rule found. GitHub may not have answered, or dataset_description.json has no readable Name. Run the same command once more; if it says the same, fix dataset_description.json and push, and the new commit is checked.")];default:{let s=g1e(e.reason)??Ln(R(e.reason).replaceAll("_"," "),80);return[u.yellow(`Not waived: ${s}.`)]}}}var $Ft=/^[0-9a-fA-F]{7,40}$/,DFt=300;async function CFt(e,t,n,r){let o=hb(e,r.json),s=JA(t,r.json);if(r.commit!==void 0&&!$Ft.test(r.commit))an(`"${R(r.commit)}" is not a commit id: give its first 7 to 40 characters (hexadecimal).`,'nemar admin pr-reviews allow nm000108 12 --admin --commit 1a2b3c4 --reason "Name kept until the rename release"',r.json);let i=r.json?null:C(`Waiving the naming rule for ${o} #${s}...`).start(),a;try{a=await vbe(o,s,n,r.commit),i?.stop()}catch(c){if(c instanceof U&&mb(c)==="no_such_pull_request"){if(i?.fail(`${o} #${s}: GitHub has no such pull request.`),!i)rn(r.json)(u.red("GitHub has no such pull request."));de(),process.exit(1)}if(c instanceof U&&mb(c)==="head_moved"){let l=Ln(c.message,DFt);if(i?.fail(l),!i)rn(r.json)(u.red(l));de(),process.exit(1)}ba(c,i,"Could not waive the naming rule",r.json)}if(r.json)console.log(JSON.stringify(a,null,2));else{for(let c of RFt(a,o,s))console.log(c);mm(a.environment)}if(!a.waived&&a.reason!=="nothing_to_waive")process.exit(1)}wa.command("allow <subject> [pr]").description("Lift a block on a contributor (allow <login>), or, with --admin, waive the naming rule for an owner's or administrator's pull request (allow <dataset> <pr> --admin --reason <why>)").option("--admin","Waive the naming rule for <dataset> <pr> at its current commit: an explicit override, recorded with your reason").option("--reason <text>","Why, in plain words (up to 200 characters; kept with the decision). Required with --admin").option("--commit <sha>","With --admin: the commit you looked at (its first 7 to 40 characters); a pull request that has moved on is not waived").option("--json","Output the raw JSON").addHelpText("after",`
|
|
1244
1232
|
allow <login>
|
|
1245
|
-
Lift a block: review this contributor's pull requests again
|
|
1246
|
-
|
|
1247
|
-
not reviewed, so a block does not hold them back and an allow changes nothing. (A commit a review
|
|
1248
|
-
is already on record for is handled as before, a block included.)
|
|
1233
|
+
Lift a block: review this contributor's pull requests again. Blocks and allows apply to owners
|
|
1234
|
+
and administrators too; author role does not skip review.
|
|
1249
1235
|
|
|
1250
1236
|
allow <dataset> <pr> --admin
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
your --reason, which is required), and posts the check as skipped with a line saying the rule was
|
|
1257
|
-
waived. A new commit is checked again. It is refused for a pull request whose author is not an
|
|
1258
|
-
owner or administrator (their review includes the rule) and for a commit that was reviewed.
|
|
1237
|
+
Request an explicit naming-rule override for an owner/admin author's CURRENT commit. This
|
|
1238
|
+
separate operation records the waiver (who, the commit, what the rule found, and your required
|
|
1239
|
+
--reason), and posts a skipped check saying the naming rule was waived. Skipped is not a review
|
|
1240
|
+
pass. It is refused for other authors and for a commit that already has a review on record.
|
|
1241
|
+
The waiver does not carry to a new commit or suppress ordinary review deliveries and starts.
|
|
1259
1242
|
|
|
1260
1243
|
Name the commit you looked at with --commit <sha> (its first 7 to 40 characters, as git log
|
|
1261
1244
|
--oneline shows them). If the pull request has been pushed to since, nothing is waived or posted
|
|
@@ -1264,9 +1247,7 @@ allow <dataset> <pr> --admin
|
|
|
1264
1247
|
|
|
1265
1248
|
nemar admin pr-reviews allow nm000108 12 --admin --commit 1a2b3c4 --reason "Name kept until the rename release"
|
|
1266
1249
|
`).action(async(e,t,n)=>{if(!du(n.json))process.exit(1);if(n.reason&&n.reason.length>GA)an(`The reason is ${n.reason.length} characters; ${GA} is the most that is kept.`,void 0,n.json);if(n.commit!==void 0&&!n.admin)an("--commit goes with --admin: it names the commit of a pull request whose naming rule is waived.",'nemar admin pr-reviews allow nm000108 12 --admin --commit 1a2b3c4 --reason "Name kept until the rename release"',n.json);if(n.admin){if(t===void 0)an("--admin waives the naming rule for one pull request: give a dataset and a pull request number.",'nemar admin pr-reviews allow nm000108 12 --admin --reason "Name kept until the rename release"',n.json);let r=n.reason?.trim()??"";if(r==="")an("--admin needs --reason: say, in plain words, why the naming rule is waived. It is recorded with the waiver.",'nemar admin pr-reviews allow nm000108 12 --admin --reason "Name kept until the rename release"',n.json);await CFt(e,t,r,n);return}if(t!==void 0)an("A contributor is named by a login alone. To waive the naming rule for a pull request, add --admin.",'nemar admin pr-reviews allow nm000108 12 --admin --reason "Name kept until the rename release"',n.json);await v1e("allow",e,n)});wa.command("block <login>").description("Never review this contributor's pull requests automatically; each needs a person").option("--reason <text>","Why, in plain words (up to 200 characters; kept with the decision)").option("--json","Output the raw JSON").addHelpText("after",`
|
|
1267
|
-
|
|
1268
|
-
requests are not reviewed, so a block does not hold them back and an allow changes nothing. (A
|
|
1269
|
-
commit a review is already on record for is handled as before, a block included.)
|
|
1250
|
+
Blocks and allows apply to owners and administrators too. Author role does not skip review.
|
|
1270
1251
|
`).action(async(e,t)=>{if(!du(t.json))process.exit(1);if(t.reason&&t.reason.length>GA)an(`The reason is ${t.reason.length} characters; ${GA} is the most that is kept.`,void 0,t.json);await v1e("block",e,t)});wa.command("clear <login>").description("Remove an allow or block (a contributor with neither is reviewed automatically)").option("--json","Output the raw JSON").action(async(e,t)=>{if(!du(t.json))process.exit(1);let n=Ax(e,t.json),r=t.json?null:C(`Clearing ${n}...`).start();try{let o=await xbe(n);if(r?.stop(),t.json){console.log(JSON.stringify(o,null,2));return}console.log(o.removed?u.green(`Removed the ${o.removed} for ${R(o.standing.login)}. Their pull requests are reviewed automatically.`):o.standing.resolved_from==="history"?u.yellow(`No allow or block found for ${R(o.standing.login)} under the id the Worker has on file (GitHub did not confirm this login).`):u.dim(`${R(o.standing.login)} had no allow or block.`)),console.log();for(let s of KA(o.standing))console.log(s);mm(o.environment)}catch(o){ba(o,r,`Could not clear ${n}`,t.json)}});wa.command("standing <login>").description("A contributor's record of rejected pull requests (information only), and any allow or block").option("--json","Output the raw JSON").action(async(e,t)=>{if(!du(t.json))process.exit(1);let n=Ax(e,t.json),r=t.json?null:C(`Reading ${n}...`).start();try{let o=await wbe(n);if(r?.stop(),t.json){console.log(JSON.stringify(o,null,2));return}console.log();for(let s of KA(o))console.log(s);console.log()}catch(o){ba(o,r,`Could not read ${n}`,t.json)}});We();di();vo();ta();wn();um();var zq=25;function AFt(e){return`Dataset Name must be a descriptive title of at least 25 characters${e===void 0?"":` (currently ${e})`}. If the study is known by a short acronym, expand it with a subtitle, e.g. "ACRO: auditory cortex recordings during natural speech".`}function OFt(e){return`This is an anonymous release, but Authors in dataset_description.json still names ${e===void 0?"somebody":e.join(", ")}. That file is part of the dataset and is served publicly, so NEMAR cannot conceal what it says. Replace the entries with a placeholder such as "Anonymous", commit, and request the release again. Restore the real names when you publish after acceptance.`}var lwn={description_missing:"dataset_description.json was not found at the dataset root.",description_not_json:"dataset_description.json is not valid JSON.",description_not_object:"dataset_description.json is not a JSON object.",name_too_short:AFt(),authors_missing:"Authors in dataset_description.json must name the people responsible for the dataset; anonymous submissions and placeholder entries are not accepted.",authors_empty_for_anonymous:'Authors in dataset_description.json must not be empty, even for an anonymous release: set it to a placeholder such as "Anonymous" so the field states that attribution is withheld rather than missing.',authors_not_blinded:OFt(),ethics_statement_missing:"An ethics approval statement is required: fill the EthicsApprovals field of dataset_description.json, or add an ethics/IRB statement to the README."};var Vq=50;var Tx=["complete_and_honest","meets_standards","authors_and_license","name_adequate"];var ZA=["readme","dataset_description","changes","license","participants_json"];var TFt=["sent","sent_cut","absent","withheld_finding","withheld_unreadable","withheld_not_utf8","withheld_annexed","withheld_not_json"],PFt=TFt.filter((e)=>e.startsWith("withheld_"));function IFt(e){return PFt.includes(e)}var NFt={complete_and_honest:["readme","changes"],meets_standards:["readme","dataset_description"],authors_and_license:["dataset_description","license"],name_adequate:["dataset_description"]};var bwn=new Set([...RA,".edf",".bdf"]);var FFt="1.0.0";function e1(e){if(e.version_shape==="ok")return e.version;if(e.version_shape==="missing")return FFt;return null}var MFt=Zu;var wwn=new Set(iq);var jFt={readme_absent:"no README was found at the dataset root",text_not_seen_in_full:"the reviewer was not shown all of the text this question needs",no_recordings:"the dataset's structure shows no recordings",license_field_missing:"dataset_description.json sets no License",name_too_short:`the Name in dataset_description.json is shorter than ${zq} characters`,placeholder_author:"Authors names a placeholder instead of a person"},E1e={pass:2,unknown:1,fail:0};function LFt(e){let t={...e.questions},n=[],r=(s,i,a,c)=>{if(E1e[c]<E1e[t[s]])t[s]=c,n.push({question:s,code:a,fact:i,result:c})},o=e.evidence;if(o.documents.readme==="absent")r("complete_and_honest","readme_absent","readme_missing_or_stub","fail");for(let s of Tx)if(NFt[s].map((a)=>o.documents[a]).some((a)=>a==="sent_cut"||IFt(a)))r(s,"text_not_seen_in_full","evidence_incomplete","unknown");if(o.summary.recordings===0)r("complete_and_honest","no_recordings","evidence_incomplete","unknown");if(!o.license_field)r("authors_and_license","license_field_missing","license_missing","fail");if(o.name_length<zq)r("name_adequate","name_too_short","name_not_descriptive","fail");if(!o.anonymous&&o.placeholder_authors>0)r("authors_and_license","placeholder_author","authors_placeholder","fail");return{answers:t,notes:n}}function qFt(e){return LFt(e).notes.map(({question:t,fact:n,result:r})=>({question:t,fact:n,result:r,text:jFt[n]}))}var UFt=["depositor_limit","platform_limit"],BFt=["evidence_unavailable","stale_head","auth_failed","model_unavailable","model_refused","model_truncated","model_invalid","report_invalid","dispatch_failed","dispatch_unconfigured","review_disabled","workflow_failed"];function HFt(e){return h_(BFt,e)}function GFt(e){return h_(UFt,e)}var gb=["request_blocked","submission_minimum_failed","identifier_screen_blocks","identifier_screen_not_run","identifier_screen_pending","identifier_screen_stale","version_kept_after_anonymous_release","identifier_screen_needs_acknowledgment","question_failed","steering_attempt","bids_failed_at_review","version_already_released","version_malformed","stored_verdict_fail","review_not_started","review_running","review_did_not_report","review_limit_reached","review_could_not_run","text_withheld","question_unknown","bids_unconcluded_at_review","version_missing","doi_state_unexpected"],k1e=" (--force)",Qr=`An administrator may approve over it; the approval records the override${k1e}.`,_wn=Qr.replace(k1e,""),XA=`A review starts only for a request that is waiting for its decision. ${Qr}`,QA="nemar admin repo publish screen <dataset>",fu="nemar admin repo publish start <dataset>",Ox="nemar admin repo publish show <dataset>",zFt="nemar admin repo publish approve <dataset>",VFt="nemar admin repo publish deny <dataset>",WFt='--acknowledge-identifier-screen "<reason>"',S1e=`${zFt} ${WFt}`;function R1e(e,t){return e.replaceAll("<dataset>",t)}var Qc={request_blocked:{class:"fail",clearedBy:"nothing",sentence:"The request is blocked.",cure:"The depositor fixes what blocked it and requests publication again."},submission_minimum_failed:{class:"fail",clearedBy:"nothing",sentence:"A submission minimum failed at the reviewed commit.",cure:"The depositor fixes the dataset and requests publication again; a request still waiting for its decision is moved to blocked."},identifier_screen_blocks:{class:"fail",clearedBy:"nothing",sentence:"The identifier screen found a direct identifier.",cure:"The depositor removes it and requests publication again, which runs the screen again."},identifier_screen_not_run:{class:"unknown",clearedBy:"nothing",sentence:"The identifier screen has no verdict about the current commit.",cure:`An administrator runs the screen again: ${QA}.`,command:QA},identifier_screen_pending:{class:"unknown",clearedBy:"nothing",sentence:"The identifier screen is still running.",cure:"Wait for it to report; the review starts when it does."},identifier_screen_stale:{class:"unknown",clearedBy:"nothing",sentence:"The identifier screen read a commit that is no longer the head of main.",cure:`An administrator runs the screen again: ${QA}.`,command:QA},version_kept_after_anonymous_release:{class:"fail",clearedBy:"nothing",sentence:"This named publication keeps the version that an earlier anonymous release of the dataset used.",cure:"The depositor raises Version in dataset_description.json and requests publication again."},identifier_screen_needs_acknowledgment:{class:"unknown",clearedBy:"screen_acknowledgment",sentence:"The identifier screen found something a person must look at, or could not read everything.",cure:`An administrator reads what the screen reported and approves with a recorded reason: ${S1e}.`,command:S1e},question_failed:{class:"fail",clearedBy:"override",sentence:"A question of the review failed.",cure:`Read any findings and the dataset's text. ${Qr}`},steering_attempt:{class:"fail",clearedBy:"override",sentence:"Text in the dataset tried to instruct the reviewer.",cure:`Read the dataset's text yourself; the review's answers cannot be relied on. ${Qr}`},bids_failed_at_review:{class:"fail",clearedBy:"override",sentence:"BIDS validation failed at the reviewed commit.",cure:`The depositor fixes the validation errors and requests publication again. ${Qr}`},version_already_released:{class:"fail",clearedBy:"override",sentence:"This version was already released: NEMAR has a release of it, or its tag names another commit.",cure:`The depositor raises Version in dataset_description.json. ${Qr}`},version_malformed:{class:"fail",clearedBy:"override",sentence:"Version in dataset_description.json is not of the form X.Y.Z.",cure:`The depositor corrects Version. ${Qr}`},stored_verdict_fail:{class:"fail",clearedBy:"override",sentence:"The stored review concluded fail, and its report no longer shows why.",cure:`Read the review's record: ${Ox}. ${Qr}`,command:Ox},review_not_started:{class:"unknown",clearedBy:"override",sentence:"No review of the screened commit has started.",cure:`Start it: ${fu}. ${Qr}`,command:fu,cureNotStartable:XA},review_running:{class:"unknown",clearedBy:"override",sentence:"The review is running.",cure:`Wait for it to report; it usually takes minutes. ${Qr}`},review_did_not_report:{class:"unknown",clearedBy:"override",sentence:"The review did not report in time.",cure:`Start it again: ${fu}. ${Qr}`,command:fu,cureNotStartable:XA},review_limit_reached:{class:"unknown",clearedBy:"override",sentence:"The daily limit of automated reviews was reached.",cure:`Start it later: ${fu}; an administrator's start is held by the platform's limit only. ${Qr}`,command:fu,cureNotStartable:XA},review_could_not_run:{class:"unknown",clearedBy:"override",sentence:"The review could not run.",cure:`Once the cause is fixed, start it again: ${fu}. ${Qr}`,command:fu,cureNotStartable:XA},text_withheld:{class:"unknown",clearedBy:"override",sentence:"Some of the dataset's text was withheld from the reviewer.",cure:`Read the withheld documents yourself. ${Qr}`},question_unknown:{class:"unknown",clearedBy:"override",sentence:"A question of the review could not be answered.",cure:`Answer it yourself from the dataset. ${Qr}`},bids_unconcluded_at_review:{class:"unknown",clearedBy:"override",sentence:"BIDS validation had not concluded at the reviewed commit.",cure:`Check the validation run of that commit. ${Qr}`},version_missing:{class:"unknown",clearedBy:"override",sentence:"dataset_description.json sets no Version, so the publication would be 1.0.0.",cure:`Confirm that 1.0.0 is right, or have the depositor set Version. ${Qr}`},doi_state_unexpected:{class:"unknown",clearedBy:"override",sentence:"The dataset already has a concept DOI that no earlier anonymous release reserved.",cure:`Check the DOI record before approving. ${Qr}`}},xwn=gb.filter((e)=>Qc[e].clearedBy==="nothing"),vwn=gb.filter((e)=>Qc[e].clearedBy==="override");function $1e(e){return e.filter((t)=>Qc[t.code].clearedBy==="nothing")}function KFt(e){return e.filter((t)=>Qc[t.code].clearedBy==="override")}function Wq(e,t){let n=new Set(t),r=new Set(KFt(e).map((o)=>o.code));return gb.filter((o)=>r.has(o)&&!n.has(o))}var Ewn=gb.filter((e)=>Qc[e].cureNotStartable!==void 0);function JFt(e,t){let n=!t&&e.cureNotStartable!==void 0;return{text:n?e.cureNotStartable:e.cure,alternative:n}}function D1e(e){return MFt.test(e)?e:"<dataset>"}function YFt(e,t,n){return R1e(JFt(Qc[e],n).text,D1e(t))}var Kq={complete_and_honest:"the README is complete and agrees with the dataset",meets_standards:"the submission standards and the ethics and provenance statements are met",authors_and_license:"the authors and the license are real and consistent",name_adequate:"the name describes the dataset"},Jq={readme_missing_or_stub:"README missing or a stub",readme_mismatch:"README does not match the dataset",description_incomplete:"Description incomplete",ethics_statement_missing:"Ethics statement missing",ethics_statement_inadequate:"Ethics statement inadequate",authors_placeholder:"Placeholder authors",authors_inconsistent:"Authors inconsistent",license_missing:"License missing",license_inconsistent:"License inconsistent",name_not_descriptive:"Name not descriptive",changes_inconsistent:"CHANGES inconsistent",provenance_unclear:"Provenance unclear",source_license_conflict:"License conflicts with a source",evidence_incomplete:"Evidence incomplete",steering_attempt:"Text tried to instruct the reviewer",other:"Other"},t1={readme:"README",dataset_description:"dataset_description.json",changes:"CHANGES",license:"LICENSE",participants_json:"participants.json"},XFt={evidence_unavailable:"the dataset could not be read at the reviewed commit",stale_head:"the request or its screened commit changed before the review started",auth_failed:"the review job could not sign in to the model",model_unavailable:"the reviewing model was unavailable",model_refused:"the reviewing model declined to review",model_truncated:"the reviewing model ran out of room before it finished",model_invalid:"the reviewing model did not return a usable answer",report_invalid:"the review's report could not be read back",dispatch_failed:"GitHub did not start the review job",dispatch_unconfigured:"the Worker had no GitHub credential or callback secret to start the review",review_disabled:"the automated review was off when the job tried to start",workflow_failed:"the review job failed before it finished"},QFt={depositor_limit:"this depositor's daily limit",platform_limit:"the platform's daily limit"};function ZFt(e,t){let n=e.detail;if(n===null)return null;switch(e.code){case"question_failed":case"question_unknown":{if(!h_(Tx,n))return n;let r=e.code==="question_failed"?"fail":"unknown",o=[Kq[n]];if(t!==null){for(let a of qFt(t))if(a.question===n&&a.result===r)o.push(a.text)}let s=(t?.findings??[]).filter((a)=>a.question===n).map((a)=>Jq[a.code]),i=[...new Set(s)];if(i.length>0)o.push(`findings: ${i.join(", ")}`);return o.join("; ")}case"text_withheld":return n.split(",").map((r)=>h_(ZA,r)?t1[r]:r).join(", ");case"review_could_not_run":return HFt(n)?XFt[n]:n;case"review_limit_reached":return GFt(n)?QFt[n]:n;default:return n.replaceAll(",",", ")}}function eMt(e,t){let n=Qc[e.code],r=ZFt(e,t);return r===null?n.sentence:`${n.sentence.replace(/\.$/,"")} (${r}).`}function C1e(e,t,n,r){return`${eMt(e,n)} ${YFt(e.code,t,r)}`}var Swn=`This approval stopped before it started publishing, and a reason that nothing clears now stands, so it cannot be resumed. Deny it with a reason (${VFt}); the depositor can request again.`;var tMt={hard_reason:"The publication review gives a reason that no override clears, so the approval is refused.",needs_override:`The publication review is not a pass. Read it (${Ox}), then approve over it with --force, which records the override with your account.`,override_not_covering:`The review now gives a reason the override was not given for. Read it again (${Ox}) before approving.`,review_changed:`The review the override was given for is no longer the review of this request, or it changed while the approval was being checked. Read it again (${Ox}) before approving.`,no_review_row:`No review of this commit is on record to attach the override to. Start it (${fu}), or approve from a terminal with --force.`,unverified:"The publication review could not be checked just now, so the approval is refused. Try again."};function Yq(e,t){return R1e(tMt[e],D1e(t))}Ve();ta();var nMt=["enforced","off","n/a"],O1e=gb,Ef=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e);function rMt(e){return Ef(e)&&typeof e.code==="string"&&O1e.includes(e.code)&&typeof e.sentence==="string"&&typeof e.cure==="string"&&(e.detail===null||typeof e.detail==="string")&&(e.line===void 0||typeof e.line==="string")&&e.cleared_by===Qc[e.code].clearedBy}function oMt(e){return Ef(e)&&Array.isArray(e.reasons)&&e.reasons.some((t)=>Ef(t)&&typeof t.code==="string"&&O1e.includes(t.code)&&typeof t.cleared_by==="string"&&t.cleared_by!==Qc[t.code].clearedBy)}function sMt(e){if(!Ef(e)||typeof e.id!=="number"||!Number.isInteger(e.id))return!1;let t=e.override;return t===null||Ef(t)&&typeof t.by==="number"&&typeof t.at==="string"&&Array.isArray(t.reasons)&&t.reasons.every((n)=>typeof n==="string")}function iMt(e){if(!Ef(e))return null;let t=e.screen_acknowledgment;return typeof e.request_status==="string"&&typeof e.gate==="string"&&nMt.includes(e.gate)&&typeof e.started_publishing==="boolean"&&(e.block_reason===null||typeof e.block_reason==="string")&&(t===null||Ef(t)&&typeof t.by==="number"&&typeof t.at==="string")&&Array.isArray(e.reasons)&&e.reasons.every(rMt)&&(e.review===null||sMt(e.review))&&Ef(e.description)&&typeof e.description.headline==="string"&&Array.isArray(e.description.lines)&&e.description.lines.every((r)=>typeof r==="string")?e:null}var aMt=[400,401,403];async function yb(e){try{let t=await ZR(e),n=iMt(t);if(n!==null)return{kind:"detail",detail:n};return{kind:"unreadable",why:oMt(t)?"this version of the CLI classifies a reason differently from the API":"the NEMAR API sent a review this version of the CLI cannot read"}}catch(t){if(t instanceof U&&t.statusCode===404)return{kind:"absent",why:Jg(t)==="not_found"?"no_request":"no_route"};let n=t instanceof U&&t.statusCode!==0?`HTTP ${t.statusCode}`:W(t);return t instanceof U&&aMt.includes(t.statusCode)?{kind:"unreadable",why:n,refused:t}:{kind:"unreadable",why:n}}}function Sf(e){return typeof e.line==="string"&&e.line!==""?e.line:`${e.sentence} ${e.cure}`}function A1e(e,t){return`nemar admin repo publish approve ${e}${t.resume?" --resume":""}${t.acknowledge?' --acknowledge-identifier-screen "<reason>"':""}${t.force?" --force":""}`}function Px(e,t,n){if(t.kind!=="detail"){let p=t.kind==="unreadable"?`The publication review could not be read (${t.why}); the API still checks it.`:t.why==="no_route"?"This API has no publication review.":`No active publication request was found for ${e}; the API decides.`;return{kind:"proceed",override:null,notes:n.force?[p,"--force was not sent: no review could be read to approve over."]:[p]}}let{detail:r}=t,o=e;if(r.started_publishing){if(!n.resume)return{kind:"refuse",why:"needs_resume",lines:[`This approval has already started publishing. Continue it with: nemar admin repo publish approve ${o} --resume`]};return{kind:"proceed",override:null,notes:["It passed the gates when it started; a resume that has started publishing is not gated again."]}}if(r.request_status==="blocked"){let p=r.block_reason===null?void 0:kM[r.block_reason],m=[C1e({code:"request_blocked",detail:r.block_reason},o,null,!1)];if(p)m.push(p);return{kind:"refuse",why:"blocked",lines:m}}if(r.gate!=="enforced")return{kind:"proceed",override:null,notes:n.force?[`--force changes nothing: the review gate is ${r.gate}.`]:[]};let s=n.resume||r.request_status==="approving",i=n.acknowledge!==void 0,a=$1e(r.reasons);if(a.length>0)return{kind:"refuse",why:"hard",lines:[Yq("hard_reason",o),...a.map(Sf)]};let c=Wq(r.reasons,[]),l=r.review?.override??null,d=l!==null&&Wq(r.reasons,l.reasons).length===0,f=r.reasons.find((p)=>p.code==="identifier_screen_needs_acknowledgment");if(f!==void 0&&!i&&r.screen_acknowledgment===null){let p=[Sf(f)];if(c.length>0&&!n.force&&!d)p.push(`The review is not a pass either, so that command also needs --force: ${A1e(o,{resume:s,acknowledge:!0,force:!0})}`);return{kind:"refuse",why:"needs_ack",lines:p}}if(c.length===0)return{kind:"proceed",override:null,notes:[]};if(n.force)return{kind:"proceed",override:{review_id:r.review?.id??null,reasons:c},notes:[`Approving over: ${c.join(", ")} (--force; recorded with your account).`]};if(l!==null&&d)return{kind:"proceed",override:null,notes:[`An override by administrator #${l.by} at ${l.at} covers these reasons. The API accepts it only for a run recorded as theirs.`]};return{kind:"refuse",why:"needs_force",lines:[Yq("needs_override",o),`To approve over them, run: ${A1e(o,{resume:s,acknowledge:i,force:!0})}`]}}We();We();um();var cMt={ok:u.green,note:u.cyan,warn:u.yellow,stop:u.red};function Zc(e,t=2){if(!e||typeof e.headline!=="string")return[];let n=" ".repeat(t),r=cMt[e.tone]??u.white,o=[`${n}${r(e.headline)}`];for(let s of Array.isArray(e.lines)?e.lines:[])o.push(`${n} ${BCe(s)?u.yellow(s):u.dim(s)}`);return o}var lMt={ok:u.green,note:u.cyan,warn:u.yellow,stop:u.red};function Ix(e){return lMt[e]??u.yellow}var bb="This is the non-production Worker. It holds its own record and answers only for the datasets it owns; it does not change what production reviews.",uMt="written by the model; the depositor's text can steer them",dMt="written by the model; the depositor's text can steer it";function T1e(e,t){let n=R(e);if(e!=="published"||!t)return n;return`${n} (unpublished ${R(t).slice(0,10)})`}function P1e(e,t){let n=R(t);switch(e){case"dispatched":return`${n}: review started.`;case"redispatched":return`${n}: review started again.`;case"dispatch_claimed":return`${n}: a review of this commit was already handed over and stands.`;default:return`${n}: review started (${R(e)}).`}}function n1(e,t){if(!e||typeof e.headline!=="string")return[];return Zc({...e,headline:R(e.headline),lines:Array.isArray(e.lines)?e.lines.map(R):[]},t)}function I1e(e,t=4){if(!e||e.outcome===null||e.outcome===void 0)return null;let n=(Array.isArray(e.reasons)?e.reasons:[]).map(R).join(", ");return`${" ".repeat(t)}${Ix(e.tone)(R(e.headline))}${n===""?"":` ${u.dim(n)}`}`}var Xq=(e,t)=>`${e} ${t}${e===1?"":"s"}`,fMt={absent:"tag absent",at_head:"tag at the reviewed commit",elsewhere:"tag at another commit"};function pMt(e){let t=e1(e);if(t===null)return"version malformed (X.Y.Z expected)";let n=[];if(e.version_shape==="missing")n.push("dataset_description.json sets no Version");let r=fMt[e.tag];if(r)n.push(r);return`version ${R(t)}${n.length>0?` (${n.join("; ")})`:""}`}function mMt(e){let t=e.summary,n=[pMt(e),`BIDS ${R(e.bids)}`];n.push(e.minimums==="met"?"minimums met":`minimums failed (${e.minimum_failures.map(R).join(", ")})`),n.push(Xq(t.subjects,"subject"),Xq(t.sessions,"session"));let r=Object.entries(t.formats).map(([o,s])=>`${R(o)} ${s}`).join(", ");if(n.push(`${Xq(t.recordings,"recording")}${r===""?"":` (${r})`}`),n.push(`datatypes ${t.datatypes.length===0?"none":t.datatypes.map(R).join(", ")}`),t.sampling_rates_hz.length>0)n.push(`sampling rates ${t.sampling_rates_hz.join(", ")} Hz`);if(t.channel_counts.length>0)n.push(`channel counts ${t.channel_counts.join(", ")}`);return n.push(`sidecars read ${t.sidecars_read} of ${t.sidecars_total}`),`Evidence: ${n.join(", ")}`}function hMt(e){if(e==="sent_cut")return"sent (cut)";if(e.startsWith("withheld_"))return`withheld (${R(e.slice(9)).replaceAll("_"," ")})`;return R(e).replaceAll("_"," ")}function N1e(e){return`Shown to the model: ${ZA.map((n)=>{let r=e.documents[n],o=`${t1[n]} ${hMt(r)}`;if(n==="dataset_description"&&(r==="sent"||r==="sent_cut"))o+=` (${e.description_keys_shown} keys shown, ${e.description_keys_not_shown} not)`;return o}).join(", ")}`}function F1e(e){let t=Object.entries(e.withheld_findings??{});if(t.length===0)return null;return`Withheld for findings: ${t.map(([n,r])=>`${R(n)} ${r}`).join(", ")}`}var Qq=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e);function gMt(e){if(!Qq(e))return!1;let t=e.documents;if(!Qq(t))return!1;if(!ZA.every((r)=>typeof t[r]==="string"))return!1;if(typeof e.description_keys_shown!=="number")return!1;if(typeof e.description_keys_not_shown!=="number")return!1;let n=e.withheld_findings;if(n===void 0||n===null)return!0;return Qq(n)&&Object.values(n).every((r)=>typeof r==="number")}function M1e(e,t){let n=e?.evidence;if(!gMt(n))return[];let r=F1e(n);return[N1e(n),...r===null?[]:[r],`The whole review, with the model's questions and findings: nemar admin repo publish show ${R(t)}`]}var yMt={pass:u.green,fail:u.red,unknown:u.yellow};function bMt(e){if(e===null)return[];let t=[...Tx.filter((r)=>(r in e)),...Object.keys(e).filter((r)=>!Tx.includes(r))],n=Math.max(0,...t.map((r)=>r.length));return t.map((r)=>{let o=R(e[r]),s=Kq[r]??"";return` ${R(r).padEnd(n)} ${(yMt[o]??u.yellow)(o.padEnd(7))} ${s}`})}var wMt={blocker:u.red,concern:u.yellow,note:u.dim};function _Mt(e){return e.map((t)=>{let n=Jq[t.code]??R(t.code),r=t.document===null?"":` (${t1[t.document]??R(t.document)})`,o=R(t.note),s=R(t.severity);return` ${(wMt[s]??u.yellow)(`[${s}]`)} ${n}${r}${o===""?"":`: ${o}`}`})}function xMt(e){let t=e.review?.id??null,n=e.history.length===1&&e.history[0].id===t;if(e.history.length===0||n)return[];let r=[u.bold("History")];for(let o of e.history){let s=o.stored_verdict===null?"-":R(o.stored_verdict);r.push(` #${R(String(o.id)).padEnd(5)} ${R(o.head_sha).slice(0,12)} ${R(o.state).padEnd(10)} ${s.padEnd(15)} ${u.dim(R(o.created_at))}${o.id===t?u.dim(" in force"):""}`)}if(e.history_truncated)r.push(u.dim(" (older reviews not shown)"));return r}var vMt={enforced:"enforced",off:"off (advice only)","n/a":"n/a"};function r1(e){let t=[],n=e.anonymous?u.yellow("ANONYMOUS RELEASE"):"named publication",r=e.block_reason===null||e.block_reason===void 0?R(e.request_status):`${R(e.request_status)} (${R(e.block_reason)})`;if(t.push(`${u.bold(R(e.dataset_id))} request ${R(String(e.request_id))}, ${r}, ${n}`),e.environment!=="production")t.push(` ${u.yellow(bb)}`);if(t.push(""),t.push(...n1(e.identifier_screen,0)),e.screen_acknowledgment)t.push(` Acknowledged by administrator ${R(String(e.screen_acknowledgment.by))} at ${R(e.screen_acknowledgment.at)}.`);t.push("");let o=e.description;t.push(u.bold(Ix(o.tone)(R(o.headline)))),t.push(` Gate: ${vMt[e.gate]??R(e.gate)}`);let s=o.lines.length>0?o.lines[o.lines.length-1]:null;for(let c of o.lines.slice(0,-1))t.push(` ${R(c)}`);let i=e.review;if(i!==null){let c=bMt(i.questions);if(c.length>0)t.push(" Questions:",...c);if(i.fact_notes.length>0){t.push(" Platform facts that lowered an answer:");for(let d of i.fact_notes)t.push(` ${R(d.question)}: ${R(d.text)}`)}if(i.findings.length>0)t.push(` Findings (${uMt}):`,..._Mt(i.findings));let l=i.summary??o.summary;if(l!==null&&l!==void 0&&R(l)!=="")t.push(` Summary (${dMt}):`,` ${R(l)}`);if(i.evidence!==null){t.push(` ${mMt(i.evidence)}`,` ${N1e(i.evidence)}`);let d=F1e(i.evidence);if(d!==null)t.push(` ${d}`)}if(i.override!==null)t.push(` Override: by administrator ${R(String(i.override.by))} at ${R(i.override.at)} for ${i.override.reasons.map(R).join(", ")}`)}if(s!==null)t.push(` ${u.dim(R(s))}`);if(o.next!==null&&o.next!==void 0)t.push(` Next: ${R(o.next)}`);let a=xMt(e);if(a.length>0)t.push("",...a);return t}var EMt=new Set(["review_running","identifier_screen_pending"]);function wb(e){if(e.approval_in_flight===!0)return!1;if(e.status==="approving")return!0;if(e.status!=="requested")return!1;if(e.identifier_screen?.state==="pending")return!1;let t=e.publication_review?.reasons??[];return t.length===0||!t.every((n)=>EMt.has(n))}function Zq(e){return[...e].sort((t,n)=>t.requested_at===n.requested_at?t.id-n.id:t.requested_at<n.requested_at?-1:1)}function j1e(e){return Zq(e.filter((t)=>t.status==="requested"&&t.publication_review?.start_offered===!0))}var SMt=["requested","approving","blocked"],e3=["requested","approving","blocked","published","denied"];function t3(e){if(e.all)return;let t=new Set(L1e(e));for(let r of e3)if(e[r])t.add(r);if(t.size===0)return[...SMt];let n=e3.filter((r)=>t.has(r));return[...n,...[...t].filter((r)=>!n.includes(r))]}function L1e(e){return(e.status??"").split(",").map((t)=>t.trim()).filter(Boolean)}function n3(e){return e.all===!0||e3.some((t)=>e[t])||L1e(e).length>0}function q1e(e){let t=t3(e);if(!t)return"all requests";if(!n3(e))return"active requests";return`requests with status ${t.join(" or ")}`}We();vo();HS();VS();Ve();ta();wn();var Fi="NEMAR_APPROVAL_DISPATCH_TOKEN",kMt=`This run presents the dispatch token in ${Fi} (an executor's run for a web approval); unset the variable to approve as yourself.`,RMt=`If you are not running a dispatched approval, unset ${Fi} and run it again.`;function $Mt(e){let t=e?.trim()??"";if(t==="")return{kind:"none"};if(/^[\x21-\x7e]+$/.test(t))return{kind:"token",value:t};return{kind:"malformed",problem:/\s/.test(t)?"it contains whitespace":"it contains a character outside printable ASCII"}}function DMt(e){return e instanceof U&&e.statusCode===409&&(e.code==="dispatch_superseded"||e.code==="dispatch_expired")}function B1e(e){e.command("approve").description("Approve and publish a dataset (runs orchestrator)").argument("<dataset-id>","Dataset ID").option("--resume","Resume from last failed step").option("--sandbox",`Use Zenodo sandbox for testing (refused while ${Fi} is set)`).option("--skip-ci-check",`Skip the orchestrator's live BIDS validation check (recorded; clears no review reason; refused while ${Fi} is set)`).option("--acknowledge-identifier-screen <reason>",`Approve over an identifier screen that needs review, recording why (${ds} to ${fs} characters; refused while ${Fi} is set)`).option("--force",`Approve over a publication review that is not a pass, recorded with your account (refused while ${Fi} is set)`).option("--request-id <n>","The request this approval is for (default: the one shown); refused if it is not the request in force").option(Ze,ot).option(kt,St).addHelpText("after",`
|
|
1271
1252
|
Description:
|
|
1272
1253
|
Approve a publication request and run the automated orchestrator
|
|
@@ -2598,7 +2579,7 @@ Examples:
|
|
|
2598
2579
|
`)}}}Fh();Ve();function V2e(e){return e instanceof U&&e.statusCode===422&&e.rawBody?.status==="blocked"&&hS(e.blockReason)}function W2e(e){let t=e.rawBody?.ci_url;return typeof t==="string"&&/^https:\/\/\S+$/.test(t)?t:void 0}function nU(e){return e==="bids_validation_in_progress"?"Request recorded: BIDS validation is still running.":"Request recorded: BIDS validation has not started yet."}function rU(e,t=!1){let n=`nemar dataset publish request ${e}${t?" --anonymous":""}`;return[" Your request is recorded. NEMAR re-checks it automatically and continues once validation passes.",` If you would rather not wait for that, check validation with: nemar dataset ci ${e}`,` Once it has passed, request again: ${n}`," If it says a request already exists, nothing more is needed."," If validation fails or a submission minimum fails, the request stays blocked and nothing is emailed:",` check nemar dataset ci ${e} or nemar dataset publish status ${e}.`]}Ve();Or();async function q1(){let e=Yt().sandboxCompleted;if(e!==void 0)return{status:e?"completed":"not_completed"};try{let t=await u$();if(jn("sandboxCompleted",t.sandbox_completed),t.sandbox_dataset_id)jn("sandboxDatasetId",t.sandbox_dataset_id);return t.sandbox_completed?{status:"completed"}:{status:"not_completed"}}catch(t){return{status:"unknown",reason:W(t)}}}We();Ei();AL();We();vo();_c();Ve();Vp();aC();vp();Ei();na();dC();PL();uf();Wp();import{existsSync as oU,mkdirSync as M4t,readFileSync as j4t,statSync as L4t,writeFileSync as K2e}from"fs";import{join as q4t,resolve as sU}from"path";function J2e(e,t,n){if(!da(n,"metadata_write")){if(t)try{let r=sU(e,".nemar"),o=sU(r,"metadata.json");if(!oU(o)){if(!oU(r))M4t(r,{recursive:!0});K2e(o,JSON.stringify(t,null,2))}let s=sU(e,".bidsignore"),i="";if(oU(s))i=j4t(s,"utf-8");if(!i.includes(".nemar/")){let a=i?`${i.trimEnd()}
|
|
2599
2580
|
.nemar/
|
|
2600
2581
|
`:`.nemar/
|
|
2601
|
-
`;K2e(s,a)}console.log(u.dim(" Updated .bidsignore for NEMAR metadata"))}catch(r){console.log(u.yellow(` Warning: Could not update .bidsignore: ${W(r)}`)),console.log(u.dim(" Upload will continue without author enrichment."))}Wl(n,"metadata_write"),Jr(e,n)}else console.log(u.dim(" Metadata write already completed (skipping)"))}var Y2e=1073741824;function U4t(e,t,n=Y2e){let r=[],o=0;for(let s of t){let i=e.files[s];if(!i||i.mtimeMs===void 0)continue;r.push({path:s,size:i.size,mtimeMs:i.mtimeMs}),o+=i.size}return o>=n?r:null}function B4t(e,t){return t.filter((n)=>{try{return Ko(n.path,L4t(q4t(e,n.path)).size)}catch{return!0}})}function H4t(e){let t=0;for(let n of Object.values(e.files))t+=n.size;return t}function G4t(e){return["Warning: saving dataset changes has produced no stdout or stderr for",`${fC(e)}. git add -A is still running.`,"Wait, or interrupt and rerun the upload; the save step will run again."].join(" ")}async function X2e(e,t,n,r={}){if(!da(n,"dataset_save")){let o=C({text:"Saving dataset changes...",...r.spinnerStream?{stream:r.spinnerStream}:{}}).start(),s=r.skipMinBytes??Y2e,i=[];if(H4t(n)>=s){let c=r.annexedPaths??null;if(c===null)try{c=await lf(e)}catch(l){console.log(u.dim(` Could not list annexed files (${W(l)}); staging will re-read them`))}if(c!==null)i=B4t(e,U4t(n,c,s)??[])}let a=await jl(e,"Initial NEMAR dataset upload",t,{skipContentCheck:i,onInactivityWarning:(c)=>{o=L_(o,G4t(c))},...r.inactivityWarningAfterMs===void 0?{}:{inactivityWarningAfterMs:r.inactivityWarningAfterMs}});if(!a.success)return Jr(e,n),To(o,"Failed to save dataset",a.error),console.log(),console.log(u.yellow("Re-run the same command to resume from this step.")),je;if(r.verifyRemote){let c;try{c=await qL(e,r.verifyRemote)}catch(l){return Jr(e,n),To(o,"Could not confirm the saved files are at the S3 remote",l),console.log(),console.log(u.yellow("Re-run the same command to resume from this step.")),je}if(c.length>0){Kl(n,"s3_upload"),Jr(e,n);let l=m$(c.slice(0,5)),d=c.length>5?` (and ${c.length-5} more)`:"";return To(o,"Saved files are not at the S3 remote",`${c.length} annexed file(s) in the commit are not recorded at the remote: ${l}${d}. The save itself annexed them, after the upload step had run.`),console.log(),console.log(u.yellow("Re-run the same command: it uploads them and saves again.")),je}}o.succeed("Dataset changes saved"),Wl(n,"dataset_save"),Jr(e,n)}else console.log(u.dim(" Dataset save already completed (skipping)"));return xn()}async function Q2e(e,t){if(!da(t,"github_push")){let n=C("Pushing metadata to GitHub...").start(),r=await _r(e);if(!r.success)return Jr(e,t),To(n,"Failed to push to GitHub",r.error),console.log(),console.log(u.yellow("Re-run the same command to resume from this step.")),je;if(r.warning)n.warn("Metadata pushed to GitHub (with warning)"),console.log(u.yellow(` ${r.warning}`));else n.succeed("Metadata pushed to GitHub");Wl(t,"github_push"),Jr(e,t)}else console.log(u.dim(" GitHub push already completed (skipping)"));return xn()}async function Z2e(e,t,n){if(!da(n,"ci_deploy")){let r=C("Setting up BIDS validation CI...").start(),o="configured";try{await Fl(t),r.succeed("BIDS validation CI configured")}catch(s){if(o="not-configured",s instanceof U&&s.statusCode===403)r.info("CI workflow will be configured by an admin");else{let i=s instanceof Error?s.message:String(s);r.warn(`Could not configure CI: ${i}`),console.log(u.dim(` An admin can add it later with: nemar admin ci add ${t}`))}}return Wl(n,"ci_deploy"),Jr(e,n),o}return console.log(u.dim(" CI deploy already completed (skipping)")),"unknown"}function z4t(e,t){let n=e.startsWith("xx");if(t==="not-configured"){if(n)return;console.log("BIDS validation is not set up yet."),console.log(` CI is set up when you request publication: ${u.cyan(`nemar dataset publish request ${e}`)}`),console.log();return}if(console.log("BIDS validation runs on GitHub after the upload."),console.log(` Check it with: ${u.cyan(`nemar dataset ci ${e}`)}`),!n)console.log(` Once it has passed, request publication: ${u.cyan(`nemar dataset publish request ${e}`)}`);console.log()}function ePe(e,t,n="unknown"){j_(e),Lke(e),console.log(),console.log(u.green.bold("Upload complete!")),console.log(),console.log(` Dataset ID: ${u.cyan(t.dataset_id)}`),console.log(` GitHub: ${u.cyan(t.github_url)}`),console.log(),console.log(u.dim("To download this dataset:")),console.log(u.dim(` nemar dataset download ${t.dataset_id}`)),console.log(),z4t(t.dataset_id,n),console.log(u.yellow("Note: This dataset is private. Only the owner and designated collaborators can")),console.log(u.yellow("download it, and only through the NEMAR CLI (not direct git-annex commands).")),console.log(u.yellow("After publishing, the data will be publicly available for everyone."))}uf();Wp();async function tPe(e,t={}){let n=await Q0e(e.absolutePath);if(!n.success)return console.log(u.red(n.error)),console.log(u.yellow("Re-run the same command to retry.")),je;if(n.cleared>0)console.log(u.yellow(` Cleared ${n.cleared} assume-unchanged flag(s) an earlier, interrupted save left on annexed files`));let r=await zke(e.absolutePath);if(r.status==="error")return console.log(u.red(r.error)),je;if(r.status==="warning")console.log(u.yellow(` ${r.warning}`));if(r.status==="restored")console.log(u.yellow(" Put back git-annex's filter process, which an earlier, interrupted upload had left out of this repository's configuration"));let o=await SRe(e.absolutePath,e.options,e.dataFiles,e.filesToUpload,e.uploadProgress,e.datasetInfo,{openRemote:t.openRemote,...t.primeMinBytes===void 0?{}:{primeMinBytes:t.primeMinBytes},...t.primeOnSuspended?{primeOnSuspended:t.primeOnSuspended}:{}});if(o.status==="fail")return je;let{progress:s,annexedPaths:i}=o.value;if(J2e(e.absolutePath,e.coAuthorEnrichment,s),(await(t.saveStep??X2e)(e.absolutePath,e.author,s,{annexedPaths:i,verifyRemote:Uc,...t.skipMinBytes===void 0?{}:{skipMinBytes:t.skipMinBytes},...t.saveInactivityWarningAfterMs===void 0?{}:{inactivityWarningAfterMs:t.saveInactivityWarningAfterMs},...t.saveSpinnerStream===void 0?{}:{spinnerStream:t.saveSpinnerStream}})).status==="fail")return je;return xn(s)}We();zl();um();I_();wn();zt();import{randomBytes as $qt}from"crypto";import{constants as dU,accessSync as Dqt,chmodSync as Cqt,chownSync as Aqt,closeSync as hU,copyFileSync as Oqt,existsSync as RPe,fsyncSync as $Pe,lstatSync as nl,mkdirSync as Tqt,mkdtempSync as Pqt,openSync as gU,readSync as Iqt,readdirSync as Nqt,renameSync as Fqt,rmSync as yU,rmdirSync as Mqt,statSync as DPe,writeSync as jqt}from"fs";import{tmpdir as Lqt}from"os";import{dirname as W1,join as va}from"path";We();import{lstatSync as wqt,readdirSync as _qt,statSync as mPe}from"fs";import{open as xqt}from"fs/promises";import{join as pPe}from"path";di();vo();zl();var iPe="nemar-identifier-scan/1.0 (+https://docs.nemar.org/policies/takedown/)",V4t="https://nemar-api-dev.sccn-org.workers.dev",W4t="https://data.nemar.org",K4t="https://nemar.s3.us-east-2.amazonaws.com",J4t="https://api.github.com";function G1(e,t){if(!Number.isSafeInteger(t)||t<1)throw RangeError(`${e} must be a positive integer, got ${t}`)}async function U1(e,t,n){G1("pool size",t);let r=0,o=Array.from({length:Math.min(t,e.length)},async()=>{while(r<e.length){let a=e[r++];await n(a)}}),i=(await Promise.allSettled(o)).find((a)=>a.status==="rejected");if(i)throw i.reason}function Y4t(e){G1("limit",e);let t=0,n=[];return async(r)=>{if(t>=e)await new Promise((o)=>n.push(o));else t++;try{return await r()}finally{let o=n.shift();if(o)o();else t--}}}class ir extends Error{cls;status;retryable;retryAfterMs;constructor(e,t={}){super(e);this.name="ReadFailure",this.cls=e,this.status=t.status,this.retryable=t.retryable??!1,this.retryAfterMs=t.retryAfterMs}}function X4t(e,t=Date.now()){let n=e?.trim();if(!n)return;if(/^\d+$/.test(n))return Number(n)*1000;let r=Date.parse(n);return Number.isNaN(r)?void 0:Math.max(0,r-t)}function Q4t(e,t){let n=e>=500||e===429;return new ir(`http-${e}`,{status:e,retryable:n,retryAfterMs:n?X4t(t):void 0})}class iU extends Error{constructor(e){super(e);this.name="RunAborted"}}function Z4t(e){G1("abort streak",e.streak);let t=e.now??Date.now,n={tripped:null},r=(o)=>{let s=0,i=0,a=(c)=>{throw n.tripped=new iU(c),n.tripped};return{check(){if(n.tripped)throw n.tripped},ok(){s=0},pausedUntilMs(){return i},observe(c){if(n.tripped)throw n.tripped;if(c.retryAfterMs!==void 0&&c.retryAfterMs>e.retryAfterCapMs)a(`${o} asked to wait ${Math.round(c.retryAfterMs/1000)} s (Retry-After), over the ${Math.round(e.retryAfterCapMs/1000)} s cap (${c.cls})`);if(c.retryAfterMs!==void 0)i=Math.max(i,t()+c.retryAfterMs);if(!c.retryable){s=0;return}if(s++,s>=e.streak)a(`${s} consecutive 429, 5xx, timeout or network failures from ${o} (last ${c.cls})`)}}};return{worker:r("the Worker"),direct:r("direct reads")}}function nPe(e){let t=e instanceof Error?e.name:"";return new ir(t==="TimeoutError"||t==="AbortError"?"timeout":"network",{retryable:!0})}function eqt(e){if(e instanceof ir)return e.cls;return`error-${e instanceof Error?e.name:"unknown"}`}async function tqt(e,t={}){let n=t.tries??3,r=t.baseMs??400,o=t.sleep??((s)=>new Promise((i)=>setTimeout(i,s)));G1("tries",n);for(let s=1;;s++)try{return await e()}catch(i){if(!(i instanceof ir&&i.retryable)||s>=n)throw i;let c=i.retryAfterMs??0;if(c>(t.retryAfterCapMs??30000))throw i;await o(Math.max(r*2**(s-1),c))}}async function nqt(e){await e.body?.cancel().catch(()=>{return})}async function rqt(e,t,n={}){let r;try{r=await fetch(e,{headers:{Range:`bytes=0-${t-1}`,"Accept-Encoding":"identity","User-Agent":n.userAgent??iPe},signal:AbortSignal.timeout(n.timeoutMs??30000)})}catch(a){throw nPe(a)}if(r.status!==200&&r.status!==206)throw await nqt(r),Q4t(r.status,r.headers.get("retry-after"));let o=r.body?.getReader();if(!o)throw new ir("no-body");let s=new Uint8Array(t),i=0;try{while(i<t){let{done:a,value:c}=await o.read();if(a||!c)break;let l=Math.min(c.length,t-i);s.set(c.subarray(0,l),i),i+=l}}catch(a){throw nPe(a)}finally{await o.cancel().catch(()=>{return})}if(i<(n.minBytes??0))throw new ir("short-body");return s.subarray(0,i)}var aPe={sideFileBytes:2097152,participantsBytes:16777216};function oqt(e,t){let n=/An error occurred \(([A-Za-z0-9]{1,40})\)/.exec(e)?.[1];if(n)return/^\d+$/.test(n)?`aws/http-${n}`:`aws/error-${n}`;return`aws/exit-${t}`}async function sqt(e,t,n={}){let r;try{let o=Bun.spawn(["aws","s3","cp",`s3://nemar/${e}/version/${t}.json`,"-"],{stdout:"pipe",stderr:"pipe",...n.env?{env:n.env}:{}}),s=!1;r=setTimeout(()=>{s=!0,o.kill("SIGKILL")},n.timeoutMs??600000);let[i,a,c]=await Promise.all([new Response(o.stdout).text(),new Response(o.stderr).text(),o.exited]);if(s)throw new ir("aws/timeout");if(c!==0)throw new ir(oqt(a,c));return i}catch(o){if(o instanceof ir)throw o;throw new ir("aws/unavailable")}finally{clearTimeout(r)}}function iqt(){let e;return async()=>{if(e!==void 0)return e;if(process.env.GITHUB_TOKEN)return e=process.env.GITHUB_TOKEN,e;try{let t=Bun.spawn(["gh","auth","token"],{stdout:"pipe",stderr:"ignore"}),n=(await new Response(t.stdout).text()).trim();e=n===""?null:n}catch{e=null}return e}}var B1=(e)=>e.replace(/\/+$/,"");function cPe(e={}){let t=e.retryAfterCapMs??30000,n=e.awsTimeoutMs??600000;return{api:B1(e.api??process.env.NEMAR_API_BASE??V4t),data:B1(e.data??process.env.NEMAR_DATA_BASE??W4t),s3Base:B1(e.s3Base??K4t),githubApi:B1(e.githubApi??J4t),userAgent:e.userAgent??iPe,fileConcurrency:e.fileConcurrency??24,workerLimit:Y4t(e.workerConcurrency??6),timeoutMs:e.timeoutMs??30000,manifestTimeoutMs:e.manifestTimeoutMs??120000,retryBaseMs:e.retryBaseMs??400,sleep:e.sleep??((r)=>new Promise((o)=>setTimeout(o,r))),now:e.now??Date.now,retryAfterCapMs:t,breakers:Z4t({streak:e.abortStreak??25,retryAfterCapMs:t,now:e.now??Date.now}),limits:{treeHeaderSample:300,scansTables:1,jsonFiles:300,textFiles:300,sideFileBytes:65536,participantsBytes:1048576,...e.limits},readVersionManifest:e.readVersionManifest??((r,o)=>sqt(r,o,{timeoutMs:n,env:e.awsEnv})),githubToken:e.githubToken??iqt(),...e.readEntryHead?{readEntryHead:e.readEntryHead}:{}}}var lPe=(e,t)=>t.startsWith(`${e.data}/`),aqt=(e,t)=>lPe(e,t)||t.startsWith(`${e.api}/`)?e.breakers.worker:e.breakers.direct;async function cqt(e,t,n){let r=aqt(e,t);r.check();let o=r.pausedUntilMs()-e.now();if(o>0)await e.sleep(o),r.check();try{let s=await n();return r.ok(),s}catch(s){if(s instanceof ir)r.observe(s);throw s}}var lqt=(e,t)=>({...t===void 0?{}:{tries:t},baseMs:e.retryBaseMs,sleep:e.sleep,retryAfterCapMs:e.retryAfterCapMs});var rPe=(e)=>/sub-([^/_]+)/.exec(e)?.[1]??"?";function oPe(e,t,n){if(t<1)return[];if(e.length<=t)return[...e];let r=new Map;for(let c of e){let l=n(c),d=r.get(l);if(d)d.push(c);else r.set(l,[c])}let o=[...r.entries()].sort(([c],[l])=>c<l?-1:c>l?1:0).map(([,c])=>c);if(o.length>t)return Array.from({length:t},(c,l)=>o[Math.floor((l+0.5)*o.length/t)][0]);let s=o.map((c,l)=>({list:c,index:l})).sort((c,l)=>c.list.length-l.list.length||c.index-l.index),i=t,a=[];return s.forEach(({list:c},l)=>{let d=Math.min(c.length,Math.ceil(i/(s.length-l)));for(let f=0;f<d;f++)a.push(c[Math.floor((f+0.5)*c.length/d)]);i-=d}),a}var uqt=(e)=>e.severity==="identifier"&&jSe.has(e.kind),dqt=(e)=>Up.has(e.kind);function uPe(e){return e.headerRead===e.edfCount&&e.incompleteReasons.length===0}function fqt(e){if(e.findings.some(uqt))return"direct-identifiers";if(e.findings.some((t)=>!dqt(t)))return"review";if(!uPe(e))return"unchecked";if(e.edfCount>0&&e.unscreenedCount>0)return"clean-edf-only-others-unscreened";if(e.edfCount===0)return e.unscreenedCount>0?"not-screened":"no-recordings";return e.findings.length>0?"dates-only":"clean"}var pqt=/\.(edf|bdf)$/i,mqt=(e)=>e.edf===!0||pqt.test(e.path);function hqt(e){return{edf:e.filter(mqt),participants:e.find((t)=>t.path==="participants.tsv"),scans:e.filter((t)=>t.path.endsWith("_scans.tsv")),json:e.filter((t)=>t.path.endsWith(".json")).filter((t)=>t.path.startsWith("sourcedata/")||!gqt.test(t.path)).filter((t)=>!yqt.test(t.path)),text:e.filter((t)=>bqt.test(t.path)).filter((t)=>t.path.startsWith("sourcedata/")||t.path.startsWith("code/"))}}var gqt=/_(eeg|ieeg|meg|emg|nirs|beh|events|channels|electrodes|coordsystem|scans|physio|stim|photo|T1w|bold)\.(json|tsv)$/,yqt=/(^|\/)(dataset_description|participants|genetic_info)\.json$/,bqt=/\.(py|m|r|txt|md|ya?ml|xml|iml|cfg|ini)$/i;function dPe(e,t,n,r=0){let o=()=>cqt(e,t.url,()=>{let s={minBytes:r,userAgent:e.userAgent,timeoutMs:e.timeoutMs};return e.readEntryHead?e.readEntryHead(t,n,s):rqt(t.url,n,s)});return tqt(()=>lPe(e,t.url)?e.workerLimit(o):o(),lqt(e))}async function H1(e,t,n){let r=await dPe(e,t,n),o=t.size===null?r.length>=n:t.size>n;return{text:new TextDecoder("utf-8",{fatal:!1}).decode(r),truncated:o}}function Eb(e,t){for(let n of t)e.push(n)}var sPe="edf/superseded-absent";async function fPe(e,t,n,r,o,s={}){let i=r.map((Te)=>Te.path),a=o==="clone",c=(Te,dt,Hn)=>a?[...Te]:oPe(Te,dt,Hn),l=[...WD([...i,...s.extraPaths??[]])],d=JSe(i),f=Object.values(d.unscreened).reduce((Te,dt)=>Te+dt,0),p={},m=(Te,dt)=>{if(dt instanceof iU)throw dt;let Hn=`${Te}/${eqt(dt)}`;p[Hn]=(p[Hn]??0)+1},h=(Te)=>rPe(Te.path),g=hqt(r),y=new Set(s.supersededEdf??[]),b=[...g.edf,...y],{participants:x,scans:v,json:S,text:E}=g,O=o==="git-tree"?oPe(b,e.limits.treeHeaderSample,h):[...b],I=0,V=0,T=0,L=0,q={},G=new Set,B=new Set,M=new Set,P=new Set,z=new Set,ie=new Set;await U1(O,e.fileConcurrency,async(Te)=>{try{let dt=await dPe(e,Te,At,At),Hn=rf(dt),{patient:yu}=zD(dt);if(!Hn.some((As)=>As.kind==="edf-unreadable")){G.add(yu);let As=yu.split(/\s+/);if(As.length>=4)M.add(As[0]),z.add(As[2]),P.add(As[3])}if(ie.add(rPe(Te.path)),Hn.some((As)=>As.severity==="identifier"))L++,B.add(yu);Eb(l,Hn);for(let As of new Set(Hn.map((kb)=>kb.kind)))q[As]=(q[As]??0)+1;I++}catch(dt){if(y.has(Te)&&dt instanceof ir&&dt.status===404){T++,p[sPe]=(p[sPe]??0)+1;return}V++,m("edf",dt)}});let $e=b.length-T,cn=!1,bt=!1;if(x&&x.size!==0)try{let{text:Te,truncated:dt}=await H1(e,x,e.limits.participantsBytes),Hn=Te.indexOf(`
|
|
2582
|
+
`;K2e(s,a)}console.log(u.dim(" Updated .bidsignore for NEMAR metadata"))}catch(r){console.log(u.yellow(` Warning: Could not update .bidsignore: ${W(r)}`)),console.log(u.dim(" Upload will continue without author enrichment."))}Wl(n,"metadata_write"),Jr(e,n)}else console.log(u.dim(" Metadata write already completed (skipping)"))}var Y2e=1073741824;function U4t(e,t,n=Y2e){let r=[],o=0;for(let s of t){let i=e.files[s];if(!i||i.mtimeMs===void 0)continue;r.push({path:s,size:i.size,mtimeMs:i.mtimeMs}),o+=i.size}return o>=n?r:null}function B4t(e,t){return t.filter((n)=>{try{return Ko(n.path,L4t(q4t(e,n.path)).size)}catch{return!0}})}function H4t(e){let t=0;for(let n of Object.values(e.files))t+=n.size;return t}function G4t(e){return["Warning: saving dataset changes has produced no stdout or stderr for",`${fC(e)}. git add -A is still running.`,"Wait, or interrupt and rerun the upload; the save step will run again."].join(" ")}async function X2e(e,t,n,r={}){if(!da(n,"dataset_save")){let o=C({text:"Saving dataset changes...",...r.spinnerStream?{stream:r.spinnerStream}:{}}).start(),s=r.skipMinBytes??Y2e,i=[];if(H4t(n)>=s){let c=r.annexedPaths??null;if(c===null)try{c=await lf(e)}catch(l){console.log(u.dim(` Could not list annexed files (${W(l)}); staging will re-read them`))}if(c!==null)i=B4t(e,U4t(n,c,s)??[])}let a=await jl(e,"Initial NEMAR dataset upload",t,{skipContentCheck:i,onInactivityWarning:(c)=>{o=L_(o,G4t(c))},...r.inactivityWarningAfterMs===void 0?{}:{inactivityWarningAfterMs:r.inactivityWarningAfterMs}});if(!a.success)return Jr(e,n),To(o,"Failed to save dataset",a.error),console.log(),console.log(u.yellow("Re-run the same command to resume from this step.")),je;if(r.verifyRemote){let c;try{c=await qL(e,r.verifyRemote)}catch(l){return Jr(e,n),To(o,"Could not confirm the saved files are at the S3 remote",l),console.log(),console.log(u.yellow("Re-run the same command to resume from this step.")),je}if(c.length>0){Kl(n,"s3_upload"),Jr(e,n);let l=m$(c.slice(0,5)),d=c.length>5?` (and ${c.length-5} more)`:"";return To(o,"Saved files are not at the S3 remote",`${c.length} annexed file(s) in the commit are not recorded at the remote: ${l}${d}. The save itself annexed them, after the upload step had run.`),console.log(),console.log(u.yellow("Re-run the same command: it uploads them and saves again.")),je}}o.succeed("Dataset changes saved"),Wl(n,"dataset_save"),Jr(e,n)}else console.log(u.dim(" Dataset save already completed (skipping)"));return xn()}async function Q2e(e,t){if(!da(t,"github_push")){let n=C("Pushing metadata to GitHub...").start(),r=await _r(e);if(!r.success)return Jr(e,t),To(n,"Failed to push to GitHub",r.error),console.log(),console.log(u.yellow("Re-run the same command to resume from this step.")),je;if(r.warning)n.warn("Metadata pushed to GitHub (with warning)"),console.log(u.yellow(` ${r.warning}`));else n.succeed("Metadata pushed to GitHub");Wl(t,"github_push"),Jr(e,t)}else console.log(u.dim(" GitHub push already completed (skipping)"));return xn()}async function Z2e(e,t,n){if(!da(n,"ci_deploy")){let r=C("Setting up BIDS validation CI...").start(),o="configured";try{await Fl(t),r.succeed("BIDS validation CI configured")}catch(s){if(o="not-configured",s instanceof U&&s.statusCode===403)r.info("CI workflow will be configured by an admin");else{let i=s instanceof Error?s.message:String(s);r.warn(`Could not configure CI: ${i}`),console.log(u.dim(` An admin can add it later with: nemar admin ci add ${t}`))}}return Wl(n,"ci_deploy"),Jr(e,n),o}return console.log(u.dim(" CI deploy already completed (skipping)")),"unknown"}function z4t(e,t){let n=e.startsWith("xx");if(t==="not-configured"){if(n)return;console.log("BIDS validation is not set up yet."),console.log(` CI is set up when you request publication: ${u.cyan(`nemar dataset publish request ${e}`)}`),console.log();return}if(console.log("BIDS validation runs on GitHub after the upload."),console.log(` Check it with: ${u.cyan(`nemar dataset ci ${e}`)}`),!n)console.log(` Once it has passed, request publication: ${u.cyan(`nemar dataset publish request ${e}`)}`);console.log()}function ePe(e,t,n="unknown"){j_(e),Lke(e),console.log(),console.log(u.green.bold("Upload complete!")),console.log(),console.log(` Dataset ID: ${u.cyan(t.dataset_id)}`),console.log(` GitHub: ${u.cyan(t.github_url)}`),console.log(),console.log(u.dim("To download this dataset:")),console.log(u.dim(` nemar dataset download ${t.dataset_id}`)),console.log(),z4t(t.dataset_id,n),console.log(u.yellow("Note: This dataset is private. Only the owner and designated collaborators can")),console.log(u.yellow("download it, and only through the NEMAR CLI (not direct git-annex commands).")),console.log(u.yellow("After publishing, the data will be publicly available for everyone."))}uf();Wp();async function tPe(e,t={}){let n=await Q0e(e.absolutePath);if(!n.success)return console.log(u.red(n.error)),console.log(u.yellow("Re-run the same command to retry.")),je;if(n.cleared>0)console.log(u.yellow(` Cleared ${n.cleared} assume-unchanged flag(s) an earlier, interrupted save left on annexed files`));let r=await zke(e.absolutePath);if(r.status==="error")return console.log(u.red(r.error)),je;if(r.status==="warning")console.log(u.yellow(` ${r.warning}`));if(r.status==="restored")console.log(u.yellow(" Put back git-annex's filter process, which an earlier, interrupted upload had left out of this repository's configuration"));let o=await SRe(e.absolutePath,e.options,e.dataFiles,e.filesToUpload,e.uploadProgress,e.datasetInfo,{openRemote:t.openRemote,...t.primeMinBytes===void 0?{}:{primeMinBytes:t.primeMinBytes},...t.primeOnSuspended?{primeOnSuspended:t.primeOnSuspended}:{}});if(o.status==="fail")return je;let{progress:s,annexedPaths:i}=o.value;if(J2e(e.absolutePath,e.coAuthorEnrichment,s),(await(t.saveStep??X2e)(e.absolutePath,e.author,s,{annexedPaths:i,verifyRemote:Uc,...t.skipMinBytes===void 0?{}:{skipMinBytes:t.skipMinBytes},...t.saveInactivityWarningAfterMs===void 0?{}:{inactivityWarningAfterMs:t.saveInactivityWarningAfterMs},...t.saveSpinnerStream===void 0?{}:{spinnerStream:t.saveSpinnerStream}})).status==="fail")return je;return xn(s)}We();zl();um();I_();wn();zt();import{randomBytes as $qt}from"crypto";import{constants as dU,accessSync as Dqt,chmodSync as Cqt,chownSync as Aqt,closeSync as hU,copyFileSync as Oqt,existsSync as RPe,fsyncSync as $Pe,lstatSync as nl,mkdirSync as Tqt,mkdtempSync as Pqt,openSync as gU,readSync as Iqt,readdirSync as Nqt,renameSync as Fqt,rmSync as yU,rmdirSync as Mqt,statSync as DPe,writeSync as jqt}from"fs";import{tmpdir as Lqt}from"os";import{dirname as W1,join as va}from"path";We();import{lstatSync as wqt,readdirSync as _qt,statSync as mPe}from"fs";import{open as xqt}from"fs/promises";import{join as pPe}from"path";di();vo();zl();var iPe="nemar-identifier-scan/1.0 (+https://docs.nemar.org/policies/takedown/)",V4t="https://api.nemar.org",W4t="https://data.nemar.org",K4t="https://nemar.s3.us-east-2.amazonaws.com",J4t="https://api.github.com";function G1(e,t){if(!Number.isSafeInteger(t)||t<1)throw RangeError(`${e} must be a positive integer, got ${t}`)}async function U1(e,t,n){G1("pool size",t);let r=0,o=Array.from({length:Math.min(t,e.length)},async()=>{while(r<e.length){let a=e[r++];await n(a)}}),i=(await Promise.allSettled(o)).find((a)=>a.status==="rejected");if(i)throw i.reason}function Y4t(e){G1("limit",e);let t=0,n=[];return async(r)=>{if(t>=e)await new Promise((o)=>n.push(o));else t++;try{return await r()}finally{let o=n.shift();if(o)o();else t--}}}class ir extends Error{cls;status;retryable;retryAfterMs;constructor(e,t={}){super(e);this.name="ReadFailure",this.cls=e,this.status=t.status,this.retryable=t.retryable??!1,this.retryAfterMs=t.retryAfterMs}}function X4t(e,t=Date.now()){let n=e?.trim();if(!n)return;if(/^\d+$/.test(n))return Number(n)*1000;let r=Date.parse(n);return Number.isNaN(r)?void 0:Math.max(0,r-t)}function Q4t(e,t){let n=e>=500||e===429;return new ir(`http-${e}`,{status:e,retryable:n,retryAfterMs:n?X4t(t):void 0})}class iU extends Error{constructor(e){super(e);this.name="RunAborted"}}function Z4t(e){G1("abort streak",e.streak);let t=e.now??Date.now,n={tripped:null},r=(o)=>{let s=0,i=0,a=(c)=>{throw n.tripped=new iU(c),n.tripped};return{check(){if(n.tripped)throw n.tripped},ok(){s=0},pausedUntilMs(){return i},observe(c){if(n.tripped)throw n.tripped;if(c.retryAfterMs!==void 0&&c.retryAfterMs>e.retryAfterCapMs)a(`${o} asked to wait ${Math.round(c.retryAfterMs/1000)} s (Retry-After), over the ${Math.round(e.retryAfterCapMs/1000)} s cap (${c.cls})`);if(c.retryAfterMs!==void 0)i=Math.max(i,t()+c.retryAfterMs);if(!c.retryable){s=0;return}if(s++,s>=e.streak)a(`${s} consecutive 429, 5xx, timeout or network failures from ${o} (last ${c.cls})`)}}};return{worker:r("the Worker"),direct:r("direct reads")}}function nPe(e){let t=e instanceof Error?e.name:"";return new ir(t==="TimeoutError"||t==="AbortError"?"timeout":"network",{retryable:!0})}function eqt(e){if(e instanceof ir)return e.cls;return`error-${e instanceof Error?e.name:"unknown"}`}async function tqt(e,t={}){let n=t.tries??3,r=t.baseMs??400,o=t.sleep??((s)=>new Promise((i)=>setTimeout(i,s)));G1("tries",n);for(let s=1;;s++)try{return await e()}catch(i){if(!(i instanceof ir&&i.retryable)||s>=n)throw i;let c=i.retryAfterMs??0;if(c>(t.retryAfterCapMs??30000))throw i;await o(Math.max(r*2**(s-1),c))}}async function nqt(e){await e.body?.cancel().catch(()=>{return})}async function rqt(e,t,n={}){let r;try{r=await fetch(e,{headers:{Range:`bytes=0-${t-1}`,"Accept-Encoding":"identity","User-Agent":n.userAgent??iPe},signal:AbortSignal.timeout(n.timeoutMs??30000)})}catch(a){throw nPe(a)}if(r.status!==200&&r.status!==206)throw await nqt(r),Q4t(r.status,r.headers.get("retry-after"));let o=r.body?.getReader();if(!o)throw new ir("no-body");let s=new Uint8Array(t),i=0;try{while(i<t){let{done:a,value:c}=await o.read();if(a||!c)break;let l=Math.min(c.length,t-i);s.set(c.subarray(0,l),i),i+=l}}catch(a){throw nPe(a)}finally{await o.cancel().catch(()=>{return})}if(i<(n.minBytes??0))throw new ir("short-body");return s.subarray(0,i)}var aPe={sideFileBytes:2097152,participantsBytes:16777216};function oqt(e,t){let n=/An error occurred \(([A-Za-z0-9]{1,40})\)/.exec(e)?.[1];if(n)return/^\d+$/.test(n)?`aws/http-${n}`:`aws/error-${n}`;return`aws/exit-${t}`}async function sqt(e,t,n={}){let r;try{let o=Bun.spawn(["aws","s3","cp",`s3://nemar/${e}/version/${t}.json`,"-"],{stdout:"pipe",stderr:"pipe",...n.env?{env:n.env}:{}}),s=!1;r=setTimeout(()=>{s=!0,o.kill("SIGKILL")},n.timeoutMs??600000);let[i,a,c]=await Promise.all([new Response(o.stdout).text(),new Response(o.stderr).text(),o.exited]);if(s)throw new ir("aws/timeout");if(c!==0)throw new ir(oqt(a,c));return i}catch(o){if(o instanceof ir)throw o;throw new ir("aws/unavailable")}finally{clearTimeout(r)}}function iqt(){let e;return async()=>{if(e!==void 0)return e;if(process.env.GITHUB_TOKEN)return e=process.env.GITHUB_TOKEN,e;try{let t=Bun.spawn(["gh","auth","token"],{stdout:"pipe",stderr:"ignore"}),n=(await new Response(t.stdout).text()).trim();e=n===""?null:n}catch{e=null}return e}}var B1=(e)=>e.replace(/\/+$/,"");function cPe(e={}){let t=e.retryAfterCapMs??30000,n=e.awsTimeoutMs??600000;return{api:B1(e.api??process.env.NEMAR_API_BASE??V4t),data:B1(e.data??process.env.NEMAR_DATA_BASE??W4t),s3Base:B1(e.s3Base??K4t),githubApi:B1(e.githubApi??J4t),userAgent:e.userAgent??iPe,fileConcurrency:e.fileConcurrency??24,workerLimit:Y4t(e.workerConcurrency??6),timeoutMs:e.timeoutMs??30000,manifestTimeoutMs:e.manifestTimeoutMs??120000,retryBaseMs:e.retryBaseMs??400,sleep:e.sleep??((r)=>new Promise((o)=>setTimeout(o,r))),now:e.now??Date.now,retryAfterCapMs:t,breakers:Z4t({streak:e.abortStreak??25,retryAfterCapMs:t,now:e.now??Date.now}),limits:{treeHeaderSample:300,scansTables:1,jsonFiles:300,textFiles:300,sideFileBytes:65536,participantsBytes:1048576,...e.limits},readVersionManifest:e.readVersionManifest??((r,o)=>sqt(r,o,{timeoutMs:n,env:e.awsEnv})),githubToken:e.githubToken??iqt(),...e.readEntryHead?{readEntryHead:e.readEntryHead}:{}}}var lPe=(e,t)=>t.startsWith(`${e.data}/`),aqt=(e,t)=>lPe(e,t)||t.startsWith(`${e.api}/`)?e.breakers.worker:e.breakers.direct;async function cqt(e,t,n){let r=aqt(e,t);r.check();let o=r.pausedUntilMs()-e.now();if(o>0)await e.sleep(o),r.check();try{let s=await n();return r.ok(),s}catch(s){if(s instanceof ir)r.observe(s);throw s}}var lqt=(e,t)=>({...t===void 0?{}:{tries:t},baseMs:e.retryBaseMs,sleep:e.sleep,retryAfterCapMs:e.retryAfterCapMs});var rPe=(e)=>/sub-([^/_]+)/.exec(e)?.[1]??"?";function oPe(e,t,n){if(t<1)return[];if(e.length<=t)return[...e];let r=new Map;for(let c of e){let l=n(c),d=r.get(l);if(d)d.push(c);else r.set(l,[c])}let o=[...r.entries()].sort(([c],[l])=>c<l?-1:c>l?1:0).map(([,c])=>c);if(o.length>t)return Array.from({length:t},(c,l)=>o[Math.floor((l+0.5)*o.length/t)][0]);let s=o.map((c,l)=>({list:c,index:l})).sort((c,l)=>c.list.length-l.list.length||c.index-l.index),i=t,a=[];return s.forEach(({list:c},l)=>{let d=Math.min(c.length,Math.ceil(i/(s.length-l)));for(let f=0;f<d;f++)a.push(c[Math.floor((f+0.5)*c.length/d)]);i-=d}),a}var uqt=(e)=>e.severity==="identifier"&&jSe.has(e.kind),dqt=(e)=>Up.has(e.kind);function uPe(e){return e.headerRead===e.edfCount&&e.incompleteReasons.length===0}function fqt(e){if(e.findings.some(uqt))return"direct-identifiers";if(e.findings.some((t)=>!dqt(t)))return"review";if(!uPe(e))return"unchecked";if(e.edfCount>0&&e.unscreenedCount>0)return"clean-edf-only-others-unscreened";if(e.edfCount===0)return e.unscreenedCount>0?"not-screened":"no-recordings";return e.findings.length>0?"dates-only":"clean"}var pqt=/\.(edf|bdf)$/i,mqt=(e)=>e.edf===!0||pqt.test(e.path);function hqt(e){return{edf:e.filter(mqt),participants:e.find((t)=>t.path==="participants.tsv"),scans:e.filter((t)=>t.path.endsWith("_scans.tsv")),json:e.filter((t)=>t.path.endsWith(".json")).filter((t)=>t.path.startsWith("sourcedata/")||!gqt.test(t.path)).filter((t)=>!yqt.test(t.path)),text:e.filter((t)=>bqt.test(t.path)).filter((t)=>t.path.startsWith("sourcedata/")||t.path.startsWith("code/"))}}var gqt=/_(eeg|ieeg|meg|emg|nirs|beh|events|channels|electrodes|coordsystem|scans|physio|stim|photo|T1w|bold)\.(json|tsv)$/,yqt=/(^|\/)(dataset_description|participants|genetic_info)\.json$/,bqt=/\.(py|m|r|txt|md|ya?ml|xml|iml|cfg|ini)$/i;function dPe(e,t,n,r=0){let o=()=>cqt(e,t.url,()=>{let s={minBytes:r,userAgent:e.userAgent,timeoutMs:e.timeoutMs};return e.readEntryHead?e.readEntryHead(t,n,s):rqt(t.url,n,s)});return tqt(()=>lPe(e,t.url)?e.workerLimit(o):o(),lqt(e))}async function H1(e,t,n){let r=await dPe(e,t,n),o=t.size===null?r.length>=n:t.size>n;return{text:new TextDecoder("utf-8",{fatal:!1}).decode(r),truncated:o}}function Eb(e,t){for(let n of t)e.push(n)}var sPe="edf/superseded-absent";async function fPe(e,t,n,r,o,s={}){let i=r.map((Te)=>Te.path),a=o==="clone",c=(Te,dt,Hn)=>a?[...Te]:oPe(Te,dt,Hn),l=[...WD([...i,...s.extraPaths??[]])],d=JSe(i),f=Object.values(d.unscreened).reduce((Te,dt)=>Te+dt,0),p={},m=(Te,dt)=>{if(dt instanceof iU)throw dt;let Hn=`${Te}/${eqt(dt)}`;p[Hn]=(p[Hn]??0)+1},h=(Te)=>rPe(Te.path),g=hqt(r),y=new Set(s.supersededEdf??[]),b=[...g.edf,...y],{participants:x,scans:v,json:S,text:E}=g,O=o==="git-tree"?oPe(b,e.limits.treeHeaderSample,h):[...b],I=0,V=0,T=0,L=0,q={},G=new Set,B=new Set,M=new Set,P=new Set,z=new Set,ie=new Set;await U1(O,e.fileConcurrency,async(Te)=>{try{let dt=await dPe(e,Te,At,At),Hn=rf(dt),{patient:yu}=zD(dt);if(!Hn.some((As)=>As.kind==="edf-unreadable")){G.add(yu);let As=yu.split(/\s+/);if(As.length>=4)M.add(As[0]),z.add(As[2]),P.add(As[3])}if(ie.add(rPe(Te.path)),Hn.some((As)=>As.severity==="identifier"))L++,B.add(yu);Eb(l,Hn);for(let As of new Set(Hn.map((kb)=>kb.kind)))q[As]=(q[As]??0)+1;I++}catch(dt){if(y.has(Te)&&dt instanceof ir&&dt.status===404){T++,p[sPe]=(p[sPe]??0)+1;return}V++,m("edf",dt)}});let $e=b.length-T,cn=!1,bt=!1;if(x&&x.size!==0)try{let{text:Te,truncated:dt}=await H1(e,x,e.limits.participantsBytes),Hn=Te.indexOf(`
|
|
2602
2583
|
`);if(Hn<0&&dt)throw new ir("header-truncated");Eb(l,zSe(Hn<0?Te:Te.slice(0,Hn))),Eb(l,WSe(Te)),bt=dt}catch(Te){cn=!0,m("participants",Te)}let st=c(v,e.limits.scansTables,h),ce=0;await U1(st,e.fileConcurrency,async(Te)=>{if(Te.size===0){ce++;return}try{let{text:dt}=await H1(e,Te,e.limits.sideFileBytes);Eb(l,VD(dt)),ce++}catch(dt){m("scans",dt)}});let He=e.limits.sideFileBytes,Me=(Te)=>Te.size!==null&&Te.size>He,ne=c(S.filter((Te)=>!Me(Te)),e.limits.jsonFiles,h),wt=c(E.filter((Te)=>!Me(Te)),e.limits.textFiles,h),Je=0,K=0;await U1(ne,e.fileConcurrency,async(Te)=>{if(Te.size===0){Je++;return}try{let{text:dt}=await H1(e,Te,He),Hn;try{Hn=JSON.parse(dt)}catch{throw new ir("json-parse")}Eb(l,qp(Hn)),Je++}catch(dt){m("json",dt)}}),await U1(wt,e.fileConcurrency,async(Te)=>{if(Te.size===0){K++;return}try{let{text:dt}=await H1(e,Te,He);Eb(l,KSe(dt)),K++}catch(dt){m("text",dt)}});let Y={edf_headers:{candidates:$e,oversize:0,selected:O.length-T,scanned:I},scans_tables:{candidates:v.length,oversize:0,selected:st.length,scanned:ce},json_files:{candidates:S.length,oversize:S.filter(Me).length,selected:ne.length,scanned:Je},text_files:{candidates:E.length,oversize:E.filter(Me).length,selected:wt.length,scanned:K}},pe=new Set,se=(Te,dt)=>{if(dt.oversize>0)pe.add(`${Te}-oversize`);if(dt.candidates-dt.oversize>dt.selected)pe.add(`${Te}-sampled`);if(dt.scanned<dt.selected)pe.add(`${Te}-unread`)};if(se("edf-headers",Y.edf_headers),se("json",Y.json_files),se("text",Y.text_files),Y.scans_tables.scanned<Y.scans_tables.selected)pe.add("scans-unread");if(cn)pe.add("participants-unread");if(bt)pe.add("participants-truncated");for(let Te of s.extraIncompleteReasons??[])pe.add(Te);let Ge=[...pe].sort(),qt={findings:l,edfCount:$e,headerRead:I,unscreenedCount:f,incompleteReasons:Ge},Cr=l.filter((Te)=>Te.severity==="identifier"),ol=Object.entries(p).filter(([Te])=>!Te.startsWith("edf/")).reduce((Te,[,dt])=>Te+dt,0);return{id:t,version:n,scanned_at:new Date().toISOString(),manifest_source:o,status:fqt(qt),incomplete:!uPe(qt),incomplete_reasons:Ge,files:{total:r.length,edf_bdf:$e,header_read:I,header_read_failed:V},sampling:Y,read_failures:p,edf_bdf_files_flagged:L,distinct_patient_field_values:G.size,distinct_subjects_with_edf_bdf:ie.size,distinct_patient_code_subfield:M.size,distinct_patient_name_subfield:P.size,distinct_patient_birth_subfield:z.size,distinct_patient_field_values_in_flagged_files:B.size,findings_by_kind:YSe(l),edf_bdf_files_by_kind:q,unscreened_formats:d.unscreened,side_reads_failed:ol,finding_fields:[...new Set(Cr.map((Te)=>`${Te.kind}:${Te.field}`))].sort()}}um();wn();gp();Wp();var xm="--acknowledge-identifier-preflight",vqt=16,Eqt="local:";function lU(e){let t=[],n=new Map,r=0,o=[""];while(o.length>0){let s=o.pop(),i;try{i=_qt(s===""?e:pPe(e,s),{withFileTypes:!0})}catch{r++;continue}i.sort((c,l)=>c.name<l.name?-1:c.name>l.name?1:0);let a=[];for(let c of i){let l=c.name;if(s===""&&(l===".git"||l===".nemar"))continue;let d=s===""?l:`${s}/${l}`;if(c.isDirectory()){a.push(d);continue}if(l===".gitattributes")continue;let f=`${Eqt}${t.length}`,p=pPe(e,d),m=null;try{let h=mPe(p);if(h.isFile())m=h.size,n.set(f,p);else if(h.isDirectory()&&!wqt(p).isSymbolicLink()){a.push(d);continue}}catch{}t.push({path:d,size:m,url:f})}for(let c=a.length-1;c>=0;c--)o.push(a[c])}return{entries:t,readable:n,unlisted:r}}function Sqt(e,t=new Map){return async(n,r,o)=>{let s=e.get(n.url);if(s===void 0)throw new ir("unreadable-entry");let i=t.get(s),a;try{a=await xqt(s,"r")}catch{throw new ir("unreadable-entry")}try{let c=n.size===null?r:Math.min(r,n.size),l=new Uint8Array(c),d=0;while(d<c){let{bytesRead:f}=await a.read(l,d,c-d,d);if(f===0)break;d+=f}if(d<o.minBytes)throw new ir("short-body");if(i)l.set(i.subarray(0,Math.min(d,i.length)),0);return l.subarray(0,d)}catch(c){if(c instanceof ir)throw c;throw new ir("unreadable-entry")}finally{await a.close().catch(()=>{return})}}}async function hPe(e,t){let n=lU(e),r=cPe({fileConcurrency:vqt,workerConcurrency:1,limits:{...aPe},readEntryHead:Sqt(n.readable,t),githubToken:async()=>null,readVersionManifest:async()=>{throw new ir("unreadable-entry")},sleep:async()=>{return}}),o=await fPe(r,"local",null,n.entries,"clone",{extraIncompleteReasons:n.unlisted>0?["tree-truncated"]:[]}),s={scanned_at:o.scanned_at,status:o.status,incomplete:o.incomplete,incomplete_reasons:o.incomplete_reasons,files:o.files,findings_by_kind:o.findings_by_kind,edf_bdf_files_flagged:o.edf_bdf_files_flagged,unscreened_formats:o.unscreened_formats,read_failures:o.read_failures};return cq(VCe(WCe(s)))}function V1(e){if(xf(e.status)!=="acknowledge")return[];let t=new Set([e.status]);if(e.incomplete&&e.status!=="unchecked")t.add("unchecked");let n=Object.values(e.unscreened_formats).reduce((o,s)=>o+s,0),r=e.status==="not-screened"||e.status==="clean-edf-only-others-unscreened";if(n>0&&!r)t.add("not-screened");return[...t].sort()}var gPe=(e,t)=>e.length===t.length&&e.every((n,r)=>n===t[r]);function yPe(e,t){let n=e.split(",").map((o)=>o.trim()).filter((o)=>o!==""),r=$A;if(n.length===0||!n.every((o)=>r.includes(o)))throw new Lo(`Allowed verdicts are ${r.join(", ")}. Direct identifiers cannot be acknowledged.`);return[...t??[],...n]}function kqt(e,t){let n=xf(e.status);if(n==="clear")return{action:"proceed",acknowledgedVia:null};if(n!=="acknowledge")return{action:"refuse"};if(t.acknowledge!==void 0){let r=[...new Set(t.acknowledge)].sort();return gPe(r,V1(e))?{action:"proceed",acknowledgedVia:"flag"}:{action:"stop",why:"acknowledgment-mismatch"}}if(t.dryRun)return{action:"preview"};if(t.no)return{action:"stop",why:"declined"};if(t.isTty)return{action:"prompt"};return{action:"stop",why:"acknowledgment-required"}}var Rqt={review:"the scanner found something a person should look at (the kinds are listed above)",unchecked:"the scanner could not read everything it should have (see Incomplete above)","not-screened":"some recordings are in formats the scanner cannot read, so their headers were not checked","clean-edf-only-others-unscreened":"the EDF/BDF headers are clean, but other recordings are in formats the scanner cannot read"},aU=(e)=>`${xm} ${e.join(",")}`;function cU(e){console.log(u.yellow(" This does not stop an upload, but it needs your explicit acknowledgment of:"));for(let t of e)console.log(u.yellow(` ${t}: ${Rqt[t]??"not clean"}.`));console.log(u.dim(" Your acknowledgment is recorded with your deposit attestation. NEMAR screens the dataset again when you request publication, and an administrator decides then."))}function bPe(){console.log(),console.log(u.red(" Upload refused: the preflight found direct identifiers (a name, a birth date finer than the year, a record number, an age over 89, or an identifying column or key). Nothing was sent.")),console.log(u.red(" Remove them from the files (for EDF/BDF, the patient and recording fields of the header) and run the upload again.")),console.log(u.dim(` There is no override, and ${xm} does not apply. If this is a false positive, please report it, so the scanner is fixed for every dataset. Terms: ${I1}`))}function wPe(e){if(e instanceof SA)return`report-${e.message}`;let t=e instanceof Error&&/^[A-Za-z]{1,40}$/.test(e.name)?e.name:"unknown",n=e?.code;return typeof n==="string"&&/^E[A-Z0-9]{1,20}$/.test(n)?`${t} ${n}`:t}function _Pe(e,t){e.fail("Identifier preflight: DID NOT FINISH"),console.log(u.red(` The preflight could not produce a verdict, so nothing was uploaded (${wPe(t)}).`)),console.log(u.dim(" Please report this: https://github.com/nemarOrg/nemar-cli/issues"))}function z1(e,t,n=""){let r=lq(t,null),o=`${r.headline}${n}`;if(r.tone==="ok")e.succeed(o);else if(r.tone==="stop")e.fail(o);else e.warn(o);for(let s of Zc({state:t.status,...r},2).slice(1))console.log(s)}function xPe(e,t){try{return xn(KCe({version:EA,scanner:`nemar-cli@${Ls}`,scan:e,acknowledged_via:t}))}catch(n){return console.log(u.red(` The preflight's record did not fit the report contract (${wPe(n)}), so nothing was uploaded.`)),je}}async function vPe(e,t,n=process.stdin.isTTY===!0,r){let o=C("Screening for identifiers on this machine (nothing is sent)...").start(),s=!1;try{s=mPe(e).isDirectory()}catch{s=!1}if(!s)return o.fail("Identifier preflight: the dataset path is not a directory"),je;let i=new Map((r?.items??[]).map((p)=>[p.path,p.after])),a;try{a=await hPe(e,i)}catch(p){return _Pe(o,p),je}z1(o,a);let c=V1(a),l=kqt(a,{acknowledge:t.acknowledgeIdentifierPreflight,dryRun:t.dryRun,no:t.no,isTty:n}),d;switch(l.action){case"proceed":if(l.acknowledgedVia==="flag")console.log(u.dim(` Acknowledged with ${aU(c)}.`));else if(t.acknowledgeIdentifierPreflight!==void 0)console.log(u.dim(` Nothing to acknowledge; ${xm} was not needed.`));d=l.acknowledgedVia;break;case"preview":return cU(c),console.log(u.yellow(` A real upload stops here until you acknowledge it: answer the prompt, or pass ${aU(c)}.`)),console.log(),xn(null);case"prompt":{cU(c);let p=!1,m=()=>{console.log(u.red(`
|
|
2603
2584
|
Upload cancelled. Nothing was sent.`)),de(),process.exit(130)};process.once("SIGINT",m);let h=setInterval(()=>{return},1000);try{({acknowledged:p}=await Pe.prompt([{type:"confirm",name:"acknowledged",message:"Upload anyway?",default:!1}]))}catch{p=!1}finally{clearInterval(h),process.off("SIGINT",m)}if(p!==!0)return console.log(u.red(" Upload cancelled. Nothing was sent.")),de(),je;console.log(u.dim(" Acknowledged at the prompt.")),d="prompt";break}case"refuse":return bPe(),de(),je;case"stop":if(l.why==="acknowledgment-mismatch")console.log(u.red(` ${xm} must name exactly what was found, which is: ${c.join(",")}. It does not acknowledge this scan. Nothing was sent.`));else cU(c),console.log(u.red(l.why==="declined"?" Declined (--no). Nothing was sent.":` No terminal to ask at: run interactively, or pass ${aU(c)}. --yes does not acknowledge a finding. Nothing was sent.`));return de(),je}let f=xPe(a,d);if(f.status==="ok")console.log();return f}async function EPe(e,t){let n=C("Screening again, right before anything is sent...").start(),r;try{r=await hPe(e)}catch(a){return _Pe(n,a),je}let o=xf(r.status);if(o!=="clear"&&o!=="acknowledge")return z1(n,r),bPe(),de(),je;let s=V1(t.scan),i=V1(r);if(!gPe(s,i))return z1(n,r),console.log(u.red(` The files changed since the preflight, and so did what it found (acknowledged: ${s.join(",")||"nothing"}; now: ${i.join(",")}). Nothing was sent. Run the upload again.`)),de(),je;if(kA(r.findings_by_kind)!==kA(t.scan.findings_by_kind))z1(n,r," (screened again)");else n.succeed(`${lq(r,null).headline} (screened again)`);return xPe(r,t.acknowledged_via)}var qqt=/\.(edf|bdf)$/i,CPe=va(".nemar","date-normalization"),Uqt=()=>({tracked:0,"nested-repository":0,ignored:0,"tracking-unknown":0,link:0,"not-writable":0,"other-filesystem":0,unverified:0});function Bqt(){return{items:[],left:Uqt()}}function Hqt(e){if(process.env.GIT_DIR||process.env.GIT_WORK_TREE)return!0;for(let t=e;;t=W1(t)){if(RPe(va(t,".git")))return!0;if(W1(t)===t)return!1}}var fU=(e)=>e.normalize("NFC").toLowerCase();async function uU(e,t,n){try{let r=await A(e,{cwd:t,...n===void 0?{}:{stdin:n}});if(!(r.exitCode===0||e.includes("check-ignore")&&r.exitCode===1))return null;return new Set(r.stdout.split("\x00").filter(Boolean).map(fU))}catch{return null}}async function Gqt(e,t){let n=`${t.join("\x00")}\x00`;if(Hqt(e)){let o=await uU(["git","ls-files","-z"],e),s=await uU(["git","check-ignore","-z","--stdin"],e,n);return o&&s?{tracked:o,ignored:s}:null}let r=null;try{if(r=Pqt(va(Lqt(),"nemar-ignore-")),(await A(["git","init","-q","--bare",r],{cwd:e})).exitCode!==0)return null;let s=await uU(["git",`--git-dir=${r}`,`--work-tree=${e}`,"check-ignore","--no-index","-z","--stdin"],e,n);return s?{tracked:new Set,ignored:s}:null}catch{return null}finally{if(r!==null)try{yU(r,{recursive:!0,force:!0})}catch{}}}function pU(e){let t;try{t=gU(e,"r")}catch{return null}try{let n=new Uint8Array(At),r=0;while(r<At){let o=Iqt(t,n,r,At-r,r);if(o===0)break;r+=o}return r===At?n:null}catch{return null}finally{try{hU(t)}catch{}}}var SPe=(e,t)=>e!==null&&e.length===t.length&&e.every((n,r)=>n===t[r]);function kPe(e){try{return Dqt(e,dU.W_OK),!0}catch{return!1}}function zqt(e,t,n){let r=t.split("/").slice(0,-1);for(let o=1;o<=r.length;o++){let s=r.slice(0,o).join("/"),i=n.get(s);if(i===void 0){i=RPe(va(e,s,".git"));try{i||=nl(va(e,s,".git")).isSymbolicLink()}catch{}n.set(s,i)}if(i)return!0}return!1}async function APe(e){let t=Bqt();try{await Vqt(e,t)}catch(n){Tn(`date normalization: planning stopped (${n instanceof Error?n.name:"unknown"})`)}return t}async function Vqt(e,t){let n=DPe(e).dev,r=lU(e),o=[];for(let c of r.entries){if(!qqt.test(c.path))continue;let l=r.readable.get(c.url);if(l===void 0)continue;let d=pU(l);if(d===null)continue;try{let f=_L(d);if(f.changed)o.push({path:l,rel:c.path,before:d,after:f.header})}catch(f){if(f instanceof af)continue;t.left.unverified++,Tn(`date normalization: a header was not planned (${f instanceof Error?f.name:"unknown"})`)}}if(o.length===0)return;let s=await Gqt(e,o.map((c)=>c.rel)),i=new Map,a=typeof process.getuid==="function"?process.getuid():null;for(let c of o){if(s===null){t.left["tracking-unknown"]++;continue}if(s.tracked.has(fU(c.rel))){t.left.tracked++;continue}if(zqt(e,c.rel,i)){t.left["nested-repository"]++;continue}if(s.ignored.has(fU(c.rel))){t.left.ignored++;continue}let l;try{l=nl(c.path)}catch{continue}if(l.isSymbolicLink()){t.left.link++;continue}if(!l.isFile())continue;if(l.dev!==n){t.left["other-filesystem"]++;continue}if(a!==null&&l.uid!==a||(l.mode&128)===0||!kPe(c.path)||!kPe(W1(c.path))){t.left["not-writable"]++;continue}t.items.push({path:c.path,rel:c.rel,dev:l.dev,ino:l.ino,size:l.size,mtimeMs:l.mtimeMs,mode:l.mode,gid:l.gid,before:c.before,after:c.after})}}var Wqt=/^\d+-[0-9a-f]{16}$/;function Kqt(e){try{let t=va(e,CPe);for(let n of[va(e,".nemar"),t])if(!nl(n).isDirectory())return;for(let n of Nqt(t))if(Wqt.test(n))yU(va(t,n),{force:!0})}catch{}}function mU(e){for(let t of e)try{Mqt(t)}catch{}}function Jqt(e,t){let n=[],r=va(e,CPe);try{for(let o of[va(e,".nemar"),r]){let s;try{s=nl(o)}catch{Tqt(o),n.push(o),s=nl(o)}if(!s.isDirectory()||s.dev!==t)return mU([...n].reverse()),null}return{dir:r,made:n}}catch{return mU([...n].reverse()),null}}function Yqt(e){try{let t=gU(e,"r");try{$Pe(t)}finally{hU(t)}}catch{}}function Xqt(e,t){let n=null;try{let r=(s)=>s.isFile()&&s.dev===e.dev&&s.ino===e.ino&&s.size===e.size&&s.mtimeMs===e.mtimeMs;if(!r(nl(e.path))||!SPe(pU(e.path),e.before))return null;if(n=va(t,`${process.pid}-${$qt(8).toString("hex")}`),Oqt(e.path,n,dU.COPYFILE_EXCL|dU.COPYFILE_FICLONE),nl(n).gid!==e.gid)Aqt(n,-1,e.gid);Cqt(n,e.mode&4095);let o=gU(n,"r+");try{if(jqt(o,e.after,0,At,0)!==At)return null;$Pe(o)}finally{hU(o)}if(nl(n).size!==e.size||!SPe(pU(n),e.after))return null;if(!r(nl(e.path)))return null;return Fqt(n,e.path),n=null,Yqt(W1(e.path)),nl(e.path).mtimeMs}catch(r){return Tn(`date normalization: a header was not set (${r instanceof Error?r.name:"unknown"})`),null}finally{if(n!==null)try{yU(n,{force:!0})}catch{}}}function OPe(e,t){let n={set:0,left:0,mtimes:new Map};if(Kqt(e),t.items.length===0)return n;let r=null;try{r=Jqt(e,DPe(e).dev)}catch{}if(r===null)return n.left=t.items.length,Tn("date normalization: no work directory, nothing set"),n;try{for(let o of t.items){let s=Xqt(o,r.dir);if(s===null){n.left++;continue}n.set++,n.mtimes.set(o.rel,s)}}finally{mU([r.dir,...[...r.made].reverse().filter((o)=>o!==r.dir)])}if(n.set>0)console.log(u.dim(` ${HCe(n.set)}`));return n}We();di();vo();import{existsSync as Zx,mkdirSync as g3t,readFileSync as ev,writeFileSync as YPe}from"fs";import{basename as y3t,resolve as vm}from"path";vc();Ve();Wr();di();import{existsSync as K1,readFileSync as bU,writeFileSync as PPe}from"fs";import{resolve as J1}from"path";var wU=[{spdxId:"CC0-1.0",name:"CC0 1.0 Universal (Public Domain)",description:"No rights reserved. Anyone can use the data for any purpose.",url:"https://creativecommons.org/publicdomain/zero/1.0/",allowsResearchUse:!0},{spdxId:"PDDL-1.0",name:"Open Data Commons Public Domain Dedication and License (PDDL)",description:"Database-specific public domain dedication.",url:"https://opendatacommons.org/licenses/pddl/1-0/",allowsResearchUse:!0},{spdxId:"CC-BY-4.0",name:"Creative Commons Attribution 4.0 International",description:"Attribution required. Free for any use including commercial.",url:"https://creativecommons.org/licenses/by/4.0/",allowsResearchUse:!0},{spdxId:"CC-BY-SA-4.0",name:"Creative Commons Attribution-ShareAlike 4.0 International",description:"Attribution + share-alike required. Derivatives must use same license.",url:"https://creativecommons.org/licenses/by-sa/4.0/",allowsResearchUse:!0},{spdxId:"CC-BY-NC-4.0",name:"Creative Commons Attribution-NonCommercial 4.0 International",description:"Attribution required. Non-commercial use only.",url:"https://creativecommons.org/licenses/by-nc/4.0/",allowsResearchUse:!0},{spdxId:"CC-BY-NC-SA-4.0",name:"Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International",description:"Attribution + non-commercial + share-alike required.",url:"https://creativecommons.org/licenses/by-nc-sa/4.0/",allowsResearchUse:!0},{spdxId:"ODC-By-1.0",name:"Open Data Commons Attribution License v1.0",description:"Database-specific attribution license.",url:"https://opendatacommons.org/licenses/by/1.0/",allowsResearchUse:!0},{spdxId:"ODbL-1.0",name:"Open Data Commons Open Database License v1.0",description:"Database attribution + share-alike. Produced works can be any license.",url:"https://opendatacommons.org/licenses/odbl/1.0/",allowsResearchUse:!0}],TPe=new Set(["CC0-1.0","CC-BY-4.0","CC-BY-SA-4.0","CC-BY-NC-4.0","CC-BY-NC-SA-4.0","CC-BY-ND-4.0","CC-BY-NC-ND-4.0","PDDL-1.0","ODC-By-1.0","ODbL-1.0","MIT","Apache-2.0","GPL-2.0-only","GPL-2.0-or-later","GPL-3.0-only","GPL-3.0-or-later","LGPL-2.1-only","LGPL-2.1-or-later","LGPL-3.0-only","LGPL-3.0-or-later","BSD-2-Clause","BSD-3-Clause","ISC","Unlicense"]);function IPe(e){let t=J1(e,"dataset_description.json");if(K1(t))try{let r=JSON.parse(bU(t,"utf-8"));if(typeof r.License==="string"&&r.License.trim())return{spdxId:r.License.trim(),source:"dataset_description"}}catch(r){if(r instanceof SyntaxError)console.warn(` Warning: dataset_description.json has invalid JSON: ${r.message}`);else console.warn(` Warning: Could not read dataset_description.json: ${r instanceof Error?r.message:String(r)}`)}let n=["LICENSE","LICENSE.txt","LICENSE.md","LICENCE","LICENCE.txt"];for(let r of n){let o=J1(e,r);if(K1(o)){try{let s=bU(o,"utf-8").toLowerCase();if(s.includes("cc0")||s.includes("public domain dedication"))return{spdxId:"CC0-1.0",source:"license_file"};if(s.includes("attribution-noncommercial-sharealike"))return{spdxId:"CC-BY-NC-SA-4.0",source:"license_file"};if(s.includes("attribution-noncommercial"))return{spdxId:"CC-BY-NC-4.0",source:"license_file"};if(s.includes("attribution-sharealike"))return{spdxId:"CC-BY-SA-4.0",source:"license_file"};if(s.includes("creativecommons")&&s.includes("attribution"))return{spdxId:"CC-BY-4.0",source:"license_file"};if(s.includes("open database license")||s.includes("odbl"))return{spdxId:"ODbL-1.0",source:"license_file"};if(s.includes("open data commons")&&s.includes("attribution"))return{spdxId:"ODC-By-1.0",source:"license_file"};if(s.includes("public domain dedication and license")||s.includes("pddl"))return{spdxId:"PDDL-1.0",source:"license_file"};if(s.includes("permission is hereby granted, free of charge")||s.includes("mit license"))return{spdxId:"MIT",source:"license_file"}}catch(s){console.warn(` Warning: Could not read ${r}: ${s instanceof Error?s.message:String(s)}`)}return{spdxId:void 0,source:"license_file"}}}return{spdxId:void 0,source:"none"}}async function _U(e){let t=wU.map((o)=>({name:`${o.spdxId.padEnd(22)} ${o.description}`,value:o.spdxId,short:o.spdxId}));t.push({name:"Other (enter SPDX ID manually)",value:"__custom__",short:"Custom"});let n=e?wU.find((o)=>o.spdxId===e)?.spdxId:void 0,{selected:r}=await Pe.prompt([{type:"list",name:"selected",message:"Select a license for this dataset:",choices:t,default:n,pageSize:t.length}]);if(r==="__custom__"){let{customId:o}=await Pe.prompt([{type:"input",name:"customId",message:"Enter SPDX license ID (e.g., MIT, Apache-2.0):",validate:(s)=>{if(!s.trim())return"License ID is required";return!0}}]);return o.trim()}return r}function NPe(e){let t=e.toUpperCase().replace(/\s+/g,"-");if(TPe.has(e))return!0;for(let n of TPe)if(n.toUpperCase()===t)return!0;return!1}function Qqt(e){let t=wU.find((n)=>n.spdxId===e);if(t)return`${t.name}
|
|
2604
2585
|
|