nemar-cli 0.10.20-dev.3732 → 0.10.20
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/index.js +4 -4
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -99,18 +99,18 @@ ${t}`,g4e,y4e,b4e=(e,t,r)=>{let n=r===""?"":`with ${r.trim()}() `,i=h4e.bind(nul
|
|
|
99
99
|
`)}var TC=!1;var{spawn:ZQe}=globalThis.Bun;function lu(e,t=[]){let r=e.replace(eZe,'("$1","<redacted>")');for(let n of t)if(n.length>=tZe)r=r.split(n).join("<redacted>");return r}function Gx(e){let t=["AWS_SESSION_TOKEN","AWS_SECRET_ACCESS_KEY","AWS_ACCESS_KEY_ID"],r=new Set;for(let n of[process.env,e??{}])for(let i of t){let o=n[i];if(typeof o==="string"&&o.length>0)r.add(o)}return[...r]}async function Lne(e,t){let r=e.getReader(),n=new TextDecoder,i="";while(!0){let{done:o,value:s}=await r.read();if(o)break;if(s.byteLength===0)continue;t(),i+=n.decode(s,{stream:!0})}return i+n.decode()}async function k(e,t={}){let r={...process.env,GIT_TERMINAL_PROMPT:"0",...t.env};for(let b of t.unsetEnv??[])delete r[b];let n=ZQe({cmd:e,cwd:t.cwd,...t.stdin===void 0?{}:{stdin:new TextEncoder().encode(t.stdin)},stdout:"pipe",stderr:"pipe",env:r}),i=!1,o,s,a=performance.now(),c=()=>{if(s!==void 0)clearTimeout(s),s=void 0},u=()=>{if(!t.onInactivityWarning)return;c(),s=setTimeout(()=>{s=void 0;try{t.onInactivityWarning?.(performance.now()-a)}catch{console.error("Could not display subprocess inactivity warning; the child result is unaffected.")}},t.inactivityWarningAfterMs??rZe)};if(u(),t.timeout)o=setTimeout(()=>{i=!0,c(),n.kill()},t.timeout);let d=Hx()?[...Gx(r),...t.redact??[]]:[];if(Hx()){let b=t.cwd?` (cwd=${t.cwd})`:"";Xc(l.dim(lu(`$ ${e.join(" ")}${b}`,d)))}let f=()=>{a=performance.now(),u()},p,m,g,h=n.exited.then((b)=>(c(),b));try{[p,m,g]=await Promise.all([Lne(n.stdout,f),Lne(n.stderr,f),h])}finally{if(c(),o)clearTimeout(o)}if(Hx()){if(t.sensitiveOutput)Xc(l.dim("[sensitive subprocess output suppressed]"));else{if(p.trim())Xc(l.dim(lu(p.trimEnd(),d)));if(m.trim())Xc(l.yellow(lu(m.trimEnd(),d)))}Xc(l.dim(`(exit ${g})`))}if(i)return{stdout:p,stderr:m||`Command timed out after ${Math.round(t.timeout/1000)}s`,exitCode:g??1,timedOut:!0};return{stdout:p,stderr:m,exitCode:g,timedOut:!1}}var eZe,tZe=8,rZe=120000;var Lt=F(()=>{je();eZe=/\(\s*"((?:x-amz-)[^"]*|authorization|proxy-authorization)"\s*,\s*"[^"]*"\s*\)/gi});function iZe(){if(process.platform==="darwin")return"macos";if(process.platform==="win32")return"windows";return"linux"}function Une(e,t=iZe()){return e.installInstructions[t]}function oZe(e){let t=e.match(/(\d+\.\d+(?:\.\d+)?)/);return t?t[1]:void 0}function aZe(){let e=Number(process.env.TEST_PROBE_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:sZe}async function zne(e){try{let{exitCode:t,stdout:r,timedOut:n}=await k(e.cmd,{timeout:aZe()});if(n)return{available:!1,timedOut:!0};if(t!==0)return{available:!1};return{available:!0,version:oZe(r)}}catch(t){let r=t instanceof Error?t.message:String(t);if(!r.includes("ENOENT")&&!r.includes("not found"))console.error(` Warning: ${e.name} check failed unexpectedly: ${r}`);return{available:!1}}}async function Hh(){let e=Object.entries(Bne);return Promise.all(e.map(async([t,r])=>{let{available:n,version:i,timedOut:o}=await zne(r);return{key:t,name:r.name,purpose:r.purpose,required:r.required,available:n,version:i,timedOut:o,installInstruction:Une(r)}}))}async function Vne(){let t=(await Hh()).filter((r)=>r.required&&!r.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 r of t)console.warn(` - ${r.name} (${r.purpose})`),console.warn(` Install: ${r.installInstruction}`);return console.warn("Run `nemar doctor` anytime to re-check. You can finish signup without them.\n"),t}async function uu(e){let r=nZe[e].map((s)=>Bne[s]).filter(Boolean),n=await Promise.all(r.map(async(s)=>{let a=await zne(s);return{check:s,available:a.available,timedOut:a.timedOut}}));for(let s of n)if(s.timedOut&&s.check.required)console.warn(`Warning: ${s.check.name} did not respond to a version check in time; continuing anyway.`);let i=n.filter((s)=>!s.available&&!s.timedOut&&s.check.required).map((s)=>({tool:s.check.name,installInstruction:Une(s.check)}));if(i.length===0)return;let o=[`
|
|
101
101
|
Missing required tools:`];for(let s of i)o.push(` ${s.tool} not installed`),o.push(` Install: ${s.installInstruction}`);throw Error(o.join(`
|
|
102
|
-
`))}var Bne,nZe,sZe=4000;var Gh=F(()=>{Lt();Bne={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)"}}},nZe={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 Gne;var Hne=F(()=>{Gne={name:"nemar-cli",packageManager:"bun@1.4.3",version:"0.10.20
|
|
102
|
+
`))}var Bne,nZe,sZe=4000;var Gh=F(()=>{Lt();Bne={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)"}}},nZe={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 Gne;var Hne=F(()=>{Gne={name:"nemar-cli",packageManager:"bun@1.4.3",version:"0.10.20",description:"CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",type:"module",main:"dist/index.js",bin:{nemar:"dist/index.js"},scripts:{dev:"bun run src/index.ts",build:"bun build src/index.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"]},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","lint-staged":"^16.3.2",typescript:"^5.5.4",wrangler:"^4.70.0",yaml:"^2.8.4"}}});var ao;var Zf=F(()=>{Hne();ao=Gne.version});import{mkdirSync as lZe,readdirSync as uZe,unlinkSync as dZe,writeFileSync as fZe}from"fs";import{join as PC}from"path";function Qne(){ep=!0}function du(){return ep}function Zne(e,t=process.env){return e.includes("--debug")||t.NEMAR_DEBUG==="1"}function Kh(e){Xne=e,rr(`Step: ${e}`)}function Qc(){Yne=!0}function eie(){return Yne}function ke(){if(Jne)return;FC=!0}function NC(){FC=!1,Jne=!0}function tie(){return FC}function rr(e){if(ep)process.stderr.write(`[debug] ${e}
|
|
103
103
|
`)}function gZe(e){let t={};for(let[r,n]of Object.entries(e))t[r]=hZe.has(r.toLowerCase())?"[REDACTED]":n;return t}function nie(e){let t=e.indexOf("@");if(t<=0)return"***";return`${e[0]}***${e.slice(t)}`}function IC(e,t,r=0){if(r>bZe)return"[REDACTED: depth]";if(Array.isArray(t))return t.map((n)=>IC(e,n,r+1));if(t&&typeof t==="object"){let n={};for(let[i,o]of Object.entries(t))n[i]=IC(i,o,r+1);return n}if(typeof t==="string"){if(yZe.test(e))return"[REDACTED]";return t.replace(rie,nie)}return t}function jC(e){return e.replace(wZe,"Bearer [REDACTED]").replace(xZe,"[REDACTED_AWS_KEY]").replace(vZe,"$1[REDACTED]").replace(_Ze,"$1$2=[REDACTED]").replace(rie,nie)}function DZe(e){return jC(e)}function Wne(e,t=mZe){if(e===void 0)return;let r=e;try{let n=JSON.parse(e);r=JSON.stringify(IC("",n))}catch{}if(r=jC(r),Buffer.byteLength(r,"utf8")>t)r=`${Buffer.from(r,"utf8").subarray(0,t).toString("utf8")}... [truncated]`;return r}function Yx(e){if(!ep)return;let t=DZe(e.url);try{let r={...e,url:t,requestHeaders:e.requestHeaders?gZe(e.requestHeaders):void 0,requestBody:Wne(e.requestBody),responseBody:Wne(e.responseBody)};Kx.push(r),rr(`${e.method} ${t} -> ${e.status??"ERROR"} (${e.durationMs}ms)`)}catch(r){let n=M(r);Kx.push({method:e.method,url:t,status:e.status,durationMs:e.durationMs,note:`redaction failed: ${n}`}),rr(`redaction failed for ${e.method} ${t}: ${n}`)}}async function EZe(){let e=[];try{let t=process.versions.bun?`Bun ${process.versions.bun}`:`Node ${process.version}`;e.push(`CLI version: ${ao}`),e.push(`OS/Arch: ${process.platform}/${process.arch}`),e.push(`Runtime: ${t}`)}catch(t){e.push(`(could not read CLI/OS/runtime info: ${M(t)})`)}e.push(""),e.push("Active account:");try{let t=jt();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: ${M(t)})`)}e.push(""),e.push("External tools:");try{let t=await Hh();for(let r of t){let n=r.available?r.version??"installed":r.timedOut?"(timed out)":"not installed";e.push(` ${r.name}: ${n}`)}}catch(t){e.push(` (could not probe external tools: ${M(t)})`)}return e}async function MC(){return(await EZe()).join(`
|
|
104
104
|
`)}async function iie(){if(!ep||Wx!==void 0)return;try{Wx=await MC()}catch(e){let t=M(e);Wx=`(could not build environment report: ${t})`,rr(`environment snapshot failed: ${t}`)}}function oie(e){if(Kne.has(e))return{flag:e};for(let t of Kne){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 SZe(e){let t=[];for(let r=0;r<e.length;r++){let n=e[r],i=oie(n);if(!i){t.push(n);continue}if(i.kind==="long-eq")t.push(`${i.flag}=[REDACTED]`);else if(i.kind==="short-attached")t.push(`${i.flag}[REDACTED]`);else if(t.push(n),r+1<e.length)t.push("[REDACTED]"),r++}return t}function $Ze(e){let t=[];for(let r=0;r<e.length;r++){let n=e[r],i=oie(n);if(!i){t.push(n);continue}if(!i.kind&&r+1<e.length)r++}return t}function kZe(e){let t=[];for(let n of $Ze(e)){if(n.startsWith("-"))continue;if(t.push(n),t.length===2)break}return(t.length>0?t.join("-"):"nemar").replace(/[^a-zA-Z0-9_-]/g,"_")}function RZe(e,t){let r=[];if(r.push("NEMAR CLI Debug Log"),r.push(`Generated: ${new Date().toISOString()}`),r.push(`Command: nemar ${jC(SZe(e).join(" "))}`),r.push(""),r.push(Wx??"(environment snapshot unavailable)"),r.push(""),r.push("HTTP requests:"),Kx.length===0)r.push(" (none)");else Kx.forEach((n,i)=>{if(r.push(` [${i+1}] ${n.method} ${n.url} -> ${n.status??"ERROR"} (${n.durationMs}ms)`),n.error)r.push(` Error: ${n.error}`);if(n.note)r.push(` Note: ${n.note}`);if(n.requestHeaders)r.push(` Request headers: ${JSON.stringify(n.requestHeaders)}`);if(n.requestBody)r.push(` Request body: ${n.requestBody}`);if(n.responseBody)r.push(` Response body: ${n.responseBody}`)});return r.push(""),r.push(`Failing step: ${Xne??"(none recorded)"}`),r.push(`Exit code: ${t}`),`${r.join(`
|
|
105
105
|
`)}
|
|
106
106
|
`}function CZe(e,t){let r;try{r=uZe(e).filter((i)=>i.startsWith("nemar-")&&i.endsWith(".log"))}catch(i){if(i.code!=="ENOENT")rr(`could not list ${e} for log rotation: ${M(i)}`);return}r.sort();let n=r.length-t;for(let i=0;i<n;i++)try{dZe(PC(e,r[i]))}catch(o){if(o.code!=="ENOENT")rr(`could not remove old log ${r[i]}: ${M(o)}`)}}function sie(){return Wh}function aie(e,t){if(!ep)return null;let r=PC(qC(),"logs");try{lZe(r,{recursive:!0})}catch(s){return Wh=M(s),rr(`could not create log directory ${r}: ${Wh}`),null}let i=`nemar-${new Date().toISOString().replace(/[:.]/g,"-")}-${kZe(e)}.log`,o=PC(r,i);try{fZe(o,RZe(e,t),"utf8")}catch(s){return Wh=M(s),rr(`could not write log file ${o}: ${Wh}`),null}return CZe(r,pZe),o}var pZe=10,mZe=2048,ep=!1,Yne=!1,FC=!1,Jne=!1,Xne,Wx,Kx,hZe,yZe,rie,bZe=32,wZe,xZe,vZe,_Ze,Kne,Wh;var Br=F(()=>{Tt();Ii();Gh();Zf();Kx=[];hZe=new Set(["authorization","cookie","set-cookie","x-api-key","x-approval-dispatch-token"]);yZe=/^(api[_-]?key|apikey|password|token|secret|access[_-]?key(_id)?|secret[_-]?access[_-]?key|session|session[_-]?token|authorization|ssh[_-]?key|private[_-]?key|device[_-]?code)$/i,rie=/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g;wZe=/Bearer\s+[A-Za-z0-9\-._~+/=]+/gi,xZe=/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g,vZe=/((?:aws_)?secret_access_key["']?\s*[:=]\s*["']?)[A-Za-z0-9/+=]{20,}/gi,_Ze=/([?&])(X-Amz-Signature|X-Amz-Security-Token|X-Amz-Credential|Signature|AWSAccessKeyId)=[^&\s"']+/gi;Kne=new Set(["-k","--key","--password","--api-key"])});import{chmodSync as AZe,copyFileSync as OZe,existsSync as LC,mkdirSync as TZe,statSync as PZe}from"fs";import{homedir as Jx}from"os";import{join as tp}from"path";function FZe(e){let t=e.trim().replace(/\/+$/,"");try{let r=new URL(t);return r.protocol=r.protocol.toLowerCase(),r.host=r.host.toLowerCase(),r.toString().replace(/\/+$/,"")}catch{return console.error(`[nemar] could not parse stored apiUrl ${JSON.stringify(e)}; leaving as-is`),t}}function qC(){return process.env.NEMAR_CONFIG_DIR||tp(Jx(),".config","nemar")}function jZe(e){if(process.env.NEMAR_CONFIG_DIR)return;let t=tp(e,"config.json");if(LC(t))return;let r=[];if(process.platform==="darwin")r.push(tp(Jx(),"Library","Preferences","nemar-nodejs","config.json"));if(process.platform==="win32"){let n=process.env.APPDATA||tp(Jx(),"AppData","Roaming");r.push(tp(n,"nemar-nodejs","config.json"))}r.push(tp(Jx(),".config","nemar-nodejs","config.json"));for(let n of r)if(LC(n))try{TZe(e,{recursive:!0}),OZe(n,t),console.error(`[nemar] Config migrated from ${n} to ${t}
|
|
107
107
|
[nemar] You can safely remove the old file.`);return}catch(i){console.error(`[nemar] Failed to migrate config from ${n}:`,i,`
|
|
108
|
-
[nemar] You can manually copy ${n} to ${t}`)}}function Fi(){let e=qC();if(Yh&&cie===e)return Yh;if(jZe(e),Yh=new Vx({projectName:"nemar",configFileMode:BC,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}),cie=e,!lie.has(e))lie.add(e),MZe(Yh.path),LZe(),BZe();return Yh}function MZe(e){if(process.platform==="win32")return;if(!LC(e))return;try{if((PZe(e).mode&511)!==BC)AZe(e,BC)}catch(t){console.error(`[nemar] could not secure config file permissions for ${e}:`,t)}}function LZe(){let e=Fi(),t=e.get("accounts");if(t&&Object.keys(t).length>0)return;let r=e.get("apiKey"),n=e.get("username");if(!r&&!n)return;try{let i=n||"default",o={};for(let s of qZe){let a=e.get(s);if(a!==void 0)o[s]=a}e.store={activeAccount:i,accounts:{[i]:o}}}catch(i){console.error("Config migration failed (legacy config preserved):",i)}}function BZe(){let e=Fi(),t=e.store,r=t.accounts,n=!1;if(r)for(let[o,s]of Object.entries(r)){let a=s?.apiUrl;if(!a)continue;if(IZe.has(FZe(a)))r[o]={...s,apiUrl:rp},console.error(`[nemar] migrated stored apiUrl for account "${o}": ${a} -> ${rp}`),n=!0}let i=t.apiUrl;if(r&&Object.keys(r).length>0&&i!==void 0){let{apiUrl:o,...s}=t;try{e.store=s,console.error(`[nemar] removed stale top-level apiUrl from config (was: ${i})`),n=!1}catch(a){console.error("API URL cleanup failed (config file unchanged):",a)}}if(n)try{e.store={...e.store,accounts:r}}catch(o){console.error("API URL migration failed (config file unchanged):",o)}}function Jh(){return Fi().get("activeAccount")}function Zc(){return Fi().get("accounts")||{}}function jt(){let e={apiUrl:rp},t=Jh();if(!t)return e;return Zc()[t]||e}function nr(e,t){let r=Fi(),n=r.get("activeAccount")||"default",i=r.get("accounts")||{};if(!i[n])i[n]={apiUrl:rp};i[n][e]=t,r.store={...r.store,accounts:i,activeAccount:n}}function Xh(e){let t=Jh();if(!t)return;let r=Zc();if(r[t])delete r[t][e],Fi().set("accounts",r)}function uie(){let e=Fi(),t=Jh();if(!t){e.clear();return}let r=Zc();delete r[t];let n=Object.keys(r);if(n.length>0)e.store={...e.store,accounts:r,activeAccount:n[0]};else e.clear()}function die(){Fi().clear()}function tt(){return!!jt().apiKey}function UC(){return Fi().path}function Qh(){let e=Zc(),t=Jh();return Object.entries(e).map(([r,n])=>({key:r,username:n.username,email:n.email,githubUsername:n.githubUsername,active:r===t,keySource:n.keySource}))}function fie(e){return e.username?.trim()||e.email}function UZe(e){let t=e.trim().toLowerCase();if(!t)return;let r=Object.entries(Zc()).filter(([,n])=>n.email&&n.email.toLowerCase()===t).map(([n])=>n);if(r.length>1){rr(`findAccountKeyByEmail: ${r.length} accounts share email ${t}: ${r.join(", ")}`);return}return r[0]}function pie(e,t){let r=Fi(),n=Zc(),i;if(n[e])i=e;else if(t.email)i=UZe(t.email);let o=i?n[i]:void 0,s={...o??{apiUrl:rp},...t};if(i&&i!==e)delete n[i];return n[e]=s,r.store={...r.store,accounts:n,activeAccount:e},{key:e,previous:o}}function mie(e){let t=e.trim();if(!t)return"unchanged";let r=Fi(),n=Jh();if(!n||n===t)return"unchanged";let i=Zc(),o=i[n];if(!o)return"unchanged";if(i[t])return"key_taken";return delete i[n],i[t]={...o,username:t},r.store={...r.store,accounts:i,activeAccount:t},"renamed"}function zC(e){let t=Fi(),r=Zc();if(r[e])return t.store={...t.store,activeAccount:e},r[e];for(let[n,i]of Object.entries(r))if(i.githubUsername===e)return t.store={...t.store,activeAccount:n},i;return null}var rp="https://
|
|
108
|
+
[nemar] You can manually copy ${n} to ${t}`)}}function Fi(){let e=qC();if(Yh&&cie===e)return Yh;if(jZe(e),Yh=new Vx({projectName:"nemar",configFileMode:BC,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}),cie=e,!lie.has(e))lie.add(e),MZe(Yh.path),LZe(),BZe();return Yh}function MZe(e){if(process.platform==="win32")return;if(!LC(e))return;try{if((PZe(e).mode&511)!==BC)AZe(e,BC)}catch(t){console.error(`[nemar] could not secure config file permissions for ${e}:`,t)}}function LZe(){let e=Fi(),t=e.get("accounts");if(t&&Object.keys(t).length>0)return;let r=e.get("apiKey"),n=e.get("username");if(!r&&!n)return;try{let i=n||"default",o={};for(let s of qZe){let a=e.get(s);if(a!==void 0)o[s]=a}e.store={activeAccount:i,accounts:{[i]:o}}}catch(i){console.error("Config migration failed (legacy config preserved):",i)}}function BZe(){let e=Fi(),t=e.store,r=t.accounts,n=!1;if(r)for(let[o,s]of Object.entries(r)){let a=s?.apiUrl;if(!a)continue;if(IZe.has(FZe(a)))r[o]={...s,apiUrl:rp},console.error(`[nemar] migrated stored apiUrl for account "${o}": ${a} -> ${rp}`),n=!0}let i=t.apiUrl;if(r&&Object.keys(r).length>0&&i!==void 0){let{apiUrl:o,...s}=t;try{e.store=s,console.error(`[nemar] removed stale top-level apiUrl from config (was: ${i})`),n=!1}catch(a){console.error("API URL cleanup failed (config file unchanged):",a)}}if(n)try{e.store={...e.store,accounts:r}}catch(o){console.error("API URL migration failed (config file unchanged):",o)}}function Jh(){return Fi().get("activeAccount")}function Zc(){return Fi().get("accounts")||{}}function jt(){let e={apiUrl:rp},t=Jh();if(!t)return e;return Zc()[t]||e}function nr(e,t){let r=Fi(),n=r.get("activeAccount")||"default",i=r.get("accounts")||{};if(!i[n])i[n]={apiUrl:rp};i[n][e]=t,r.store={...r.store,accounts:i,activeAccount:n}}function Xh(e){let t=Jh();if(!t)return;let r=Zc();if(r[t])delete r[t][e],Fi().set("accounts",r)}function uie(){let e=Fi(),t=Jh();if(!t){e.clear();return}let r=Zc();delete r[t];let n=Object.keys(r);if(n.length>0)e.store={...e.store,accounts:r,activeAccount:n[0]};else e.clear()}function die(){Fi().clear()}function tt(){return!!jt().apiKey}function UC(){return Fi().path}function Qh(){let e=Zc(),t=Jh();return Object.entries(e).map(([r,n])=>({key:r,username:n.username,email:n.email,githubUsername:n.githubUsername,active:r===t,keySource:n.keySource}))}function fie(e){return e.username?.trim()||e.email}function UZe(e){let t=e.trim().toLowerCase();if(!t)return;let r=Object.entries(Zc()).filter(([,n])=>n.email&&n.email.toLowerCase()===t).map(([n])=>n);if(r.length>1){rr(`findAccountKeyByEmail: ${r.length} accounts share email ${t}: ${r.join(", ")}`);return}return r[0]}function pie(e,t){let r=Fi(),n=Zc(),i;if(n[e])i=e;else if(t.email)i=UZe(t.email);let o=i?n[i]:void 0,s={...o??{apiUrl:rp},...t};if(i&&i!==e)delete n[i];return n[e]=s,r.store={...r.store,accounts:n,activeAccount:e},{key:e,previous:o}}function mie(e){let t=e.trim();if(!t)return"unchanged";let r=Fi(),n=Jh();if(!n||n===t)return"unchanged";let i=Zc(),o=i[n];if(!o)return"unchanged";if(i[t])return"key_taken";return delete i[n],i[t]={...o,username:t},r.store={...r.store,accounts:i,activeAccount:t},"renamed"}function zC(e){let t=Fi(),r=Zc();if(r[e])return t.store={...t.store,activeAccount:e},r[e];for(let[n,i]of Object.entries(r))if(i.githubUsername===e)return t.store={...t.store,activeAccount:n},i;return null}var rp="https://api.nemar.org",BC=384,IZe,NZe,OTt,Yh=null,cie=null,lie,qZe;var Ii=F(()=>{Mne();Nn();Zd();Br();IZe=new Set(["https://api.osc.earth/nemar","https://nemar-api.neuromechanist.workers.dev","https://nemar-api-dev.shirazi-10f.workers.dev"]);NZe=Y({field:D(),blocks:ce(D()).optional(),set_on:ce(D()).optional()}).passthrough(),OTt=Y({apiKey:D().optional(),apiUrl:D().url().default(rp),username:D().optional(),email:D().email().optional(),githubUsername:D().optional(),sandboxCompleted:Be().optional(),sandboxDatasetId:D().optional(),dismissedNoticeIds:ce(C()).optional(),serviceAccess:Be().optional(),profileGaps:ce(NZe).optional(),orcidVerified:Be().optional(),role:D().optional(),accountKind:Yl.optional(),pendingEmailChange:D().email().optional()});lie=new Set;qZe=["apiKey","apiUrl","username","email","githubUsername","sandboxCompleted","sandboxDatasetId","dismissedNoticeIds"]});function Xx(e){if(hie)return;hie=!0;let t=l.yellow("\u2500".repeat(60)),r=l.yellow.bold("[MAINTENANCE]"),n=l.dim(`mode: ${e.mode}`),i=e.eta?`
|
|
109
109
|
${l.dim(`eta: ${e.eta}`)}`:"";process.stderr.write(`${t}
|
|
110
110
|
${r} ${e.message}
|
|
111
111
|
${n}${i}
|
|
112
112
|
${t}
|
|
113
|
-
`)}var hie=!1;var VC=F(()=>{je()});function Qx(){if(process.env.TEST_API_URL)return process.env.TEST_API_URL;if(GC)return HC;return jt().apiUrl||HC}async function N(e,t={},r=!1,n){let i=`${Qx()}${e}`,o={"Content-Type":"application/json","X-CLI-Version":ao,...t.headers};if(r){let p=jt();if(!p.apiKey&&r===!0)throw new q(401,"Not authenticated. Run 'nemar auth login' first.");if(p.apiKey)o.Authorization=`Bearer ${p.apiKey}`}let s=t.method||"GET",a=typeof t.body==="string"?t.body:void 0,c=Date.now(),u;try{u=await fetch(i,{...t,headers:o})}catch(p){if(du())Yx({method:s,url:i,status:null,durationMs:Date.now()-c,requestHeaders:o,requestBody:a,error:p instanceof Error?p.message:String(p)});throw new q(0,`Network error: Could not connect to ${Qx()}`,{originalError:p instanceof Error?p.message:String(p)})}let d;try{d=await u.text()}catch(p){if(du())Yx({method:s,url:i,status:u.status,durationMs:Date.now()-c,requestHeaders:o,requestBody:a,error:p instanceof Error?p.message:String(p)});throw new q(0,"Failed to read response body",{httpStatus:u.status,originalError:p instanceof Error?p.message:String(p)})}if(du())Yx({method:s,url:i,status:u.status,durationMs:Date.now()-c,requestHeaders:o,requestBody:a,responseBody:d});let f;try{f=JSON.parse(d)}catch{throw new q(u.status,`Invalid response from server (status ${u.status})`)}if(!u.ok){if(u.status===503&&(f.mode==="read-only"||f.mode==="full")){let L=typeof f.message==="string"?f.message:"NEMAR is in maintenance mode. Please retry shortly.",P=typeof f.eta==="string"?f.eta:null,j=new dc(f.mode,L,P,f.details);throw Xx(j),j}let p=typeof f.block_reason==="string",m=Array.isArray(f.missing)?f.missing.filter((L)=>typeof L==="string"):void 0,g=typeof f.error==="string"&&(lV.includes(f.error)||$V.includes(f.error)),h=typeof f.error==="string"&&(Cb.options.includes(f.error)||OV.includes(f.error)),b=typeof f.error==="string"&&nV.includes(f.error),w=typeof f.error==="string"&&uV.includes(f.error),x=typeof f.error==="string"&&DV.includes(f.error),v=typeof f.error==="string"&&_V.includes(f.error),R=typeof f.error==="string"&&EV.includes(f.error),T=p||v||R||g||h||b||w||x||m!==void 0&&typeof f.error==="string"&&cV.includes(f.error)?f.message||f.error:f.error||f.message;if(u.status===404&&f.error==="Not Found"&&typeof f.message==="string")T=`${f.message}. This NEMAR backend does not support this command yet.`;let A=new q(u.status,T||"Request failed",f.details,typeof f.step==="string"?f.step:void 0,p?f.block_reason:void 0,m);if(typeof f.error==="string")A.code=f.error;if(typeof f.reason==="string")A.reason=f.reason;throw A.rawBody=f,A}if(n){let p=n.safeParse(f);if(!p.success)throw new q(u.status,`Response for ${e} did not match the expected NEMAR contract`,{issues:p.error.issues});return p.data}return f}var HC="https://nemar-api-dev.sccn-org.workers.dev",GC;var aa=F(()=>{oh();Tb();h1();sh();Zd();Ii();Br();VC();Zf();Tt();GC=HC.includes("workers.dev")});async function np(e,t={}){return N(`/datasets/${e}/publish/request`,t.anonymous?{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({anonymous:!0})}:{method:"POST"},!0)}async function ip(e){return N(`/datasets/${e}/publish/status`,{},!0)}async function bie(e){return N(`/datasets/${e}/publish/resend`,{method:"POST"},!0)}async function wie(e){return N(`/datasets/${e}/publish/withdraw`,{method:"POST"},!0)}async function fu(e={}){let{statuses:t,search:r}=typeof e==="string"?{statuses:e?[e]:[]}:e,n=await gie(t,r),i=n;if(t!==void 0&&t.length>1&&n.requests.length===0){let o=[];for(let a of new Set(t))o.push(await gie([a],r));let s=o.flatMap((a)=>a.requests).sort(xie);i={...n,requests:s,count:s.length}}return r?zZe(i,r):i}function xie(e,t){return e.requested_at<t.requested_at?1:e.requested_at>t.requested_at?-1:0}async function gie(e,t){let r=new URLSearchParams;if(e&&e.length>0)r.set("status",e.join(","));if(t)r.set("search",t);let n=r.size>0?`?${r}`:"";return N(`/admin/publish/requests${n}`,{},!0)}function zZe(e,t){let r=e.requests.filter((o)=>nH(t,[o.dataset_id,o.requested_by_username,o.dataset_name])),n=(o)=>iH(o.dataset_id,t)?0:1,i=[...r].sort((o,s)=>n(o)-n(s)||xie(o,s));return{...e,requests:i,count:i.length}}async function op(e,t,r){return N(`/admin/publish/${e}/deny`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:t,...r!==void 0?{request_id:r}:{}})},!0)}async function Zx(e){return N(`/admin/publish/${e}/identifier-screen`,{method:"POST"},!0)}async function ev(e){return N(`/admin/publish/${e}/review`,{},!0)}async function vie(e){return N(`/admin/publish/${e}/review/start`,{method:"POST"},!0)}async function _ie(e,t){let r={message:t};return N(`/admin/publish/${e}/comment`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},!0)}function sp(e){if(!(e instanceof q))return;let t=e.rawBody;if(typeof t!=="object"||t===null||Array.isArray(t))return;let r=t.code;return typeof r==="string"?r:void 0}function VZe(e,t=[]){if(e){let r=Bo.indexOf(e);if(r>=0)return r+1}return Math.min(t.length+1,Bo.length)}function HZe(e){if(!(e instanceof q))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 GZe(){let e=process.env.NEMAR_APPROVE_RETRY_DELAY_MS;if(e===void 0||!/^\d+$/.test(e))return zb;let t=Number(e);return Number.isSafeInteger(t)&&t<=zb?t:zb}async function ap(e,t=!1,r=!1,n=!1,i,o,s,a,c){let d=GZe(),f,p,m=0,g=!1,h,b=t,w=[],x;function v(R,E,T,A){if(!o)return;o({step:R,stepIndex:VZe(R,E),stepTotal:Bo.length,s3LockLocked:T,s3LockTotal:A,s3LockResumed:R==="s3_lock"&&g?!0:void 0})}for(let R=1;R<=5;R++)try{let E,T=!0;do{if(E=await N(`/admin/publish/${e}/approve`,{method:"POST",headers:{"Content-Type":"application/json",...c?.dispatchToken?{[SV]:c.dispatchToken}:{}},body:JSON.stringify({resume:T?b:!0,sandbox:r,s3_lock_continuation_token:f,s3_lock_total:p,skip_ci_check:n,...s!==void 0?{acknowledge_identifier_screen:s}:{},...a!==void 0?{[eH]:a}:{},...c?.requestId!==void 0?{request_id:c.requestId}:{}})},!0),T=!1,E.step_results)w.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 A=E.step??E.step_results?.[E.step_results.length-1]?.step;if(A&&(A!==h||A==="s3_lock"))v(A,E.steps_completed??[],A==="s3_lock"?m:void 0,A==="s3_lock"?p:void 0),h=A;if(E.hasMore&&E.s3_lock_continuation_token!==void 0)f=E.s3_lock_continuation_token;else break}while(E.hasMore);if(w.length>0)E.step_results=yie(w);return E}catch(E){if(x=E,R===5||!HZe(E)){if(E instanceof q&&w.length>0)E.stepResults=yie(w);throw E}let A=E;if(i?.({attempt:R,maxAttempts:5,delayMs:d,step:A.step,error:A.message}),await new Promise((L)=>setTimeout(L,d)),b=!0,f!==void 0)g=!0}throw x}function yie(e){let t=new Map;for(let r of e)t.set(r.step,r);return Array.from(t.values())}var co=F(()=>{Ub();sh();Hb();aa();Tt()});function nv(e){if(e.service_access===void 0||e.service_access===null)return"unknown";return e.service_access?"upload":"browse"}async function t2(e,t,r,n,i={}){let o=new URLSearchParams;if(e)o.set("status",e);if(t)o.set("role",t);if(r)o.set("awaiting_approval","1");if(n)o.set("kind",n);if(i.search!==void 0)o.set("q",i.search);if(i.includeDeleted)o.set("include_deleted","true");let s=o.toString()?`?${o.toString()}`:"";return N(`/admin/users${s}`,{},!0,sV)}async function iv(e,t=!1){return N(`/admin/users/by-id/${e}${t?"?include_deleted=true":""}`,{},!0,pV)}async function Tie(e,t){return N(`/admin/users/by-id/${e}`,{method:"PATCH",body:JSON.stringify(t)},!0,mV)}async function Pie(e){return N(`/admin/approve/${e}`,{method:"POST"},!0)}async function Iie(e){return N(`/admin/approve/by-id/${e}`,{method:"POST"},!0)}async function Fie(e){return N(`/admin/revoke/${e}`,{method:"POST"},!0)}async function Nie(e){return N(`/admin/revoke/by-id/${e}`,{method:"POST"},!0)}async function jie(e){return N(`/admin/users/by-id/${e}/verify`,{method:"POST"},!0)}async function Mie(e,t){return N(`/admin/users/${e}/role`,{method:"POST",body:JSON.stringify({role:t})},!0)}async function qie(e,t){return N(`/admin/users/${e}/kind`,{method:"POST",body:JSON.stringify({kind:t})},!0)}async function Lie(e){return N(`/admin/users/${e}`,{},!0)}async function Bie(e,t){return N(`/admin/users/${e}/keys`,{method:"POST",body:JSON.stringify({name:t})},!0,Ob)}async function Uie(e){return N(`/admin/users/${e}/keys`,{},!0,Ab)}async function zie(e,t){return N(`/admin/users/${e}/keys/${t}`,{method:"DELETE"},!0)}async function r2(e,t){return N(`/admin/datasets/${e}/visibility`,{method:"PATCH",body:JSON.stringify({visibility:t})},!0)}async function Vie(e){return N(`/datasets/${e}/publish`,{method:"POST"},!0)}async function Hie(e){return N(`/admin/datasets/${e}/ci`,{},!0)}async function ca(e){return N(`/admin/datasets/${e}/ci`,{method:"POST"},!0)}async function n2(e){return N(`/admin/datasets/${e}/ci/validate`,{method:"POST"},!0)}async function i2(e){return N(`/admin/datasets/${e}/ci/sync`,{method:"POST"},!0)}async function Gie(e,t){return N(`/admin/datasets/${e}/doi/concept`,{method:"POST",body:JSON.stringify(t)},!0)}async function tg(e){return N(`/admin/datasets/${e}/doi`,{},!0)}async function o2(e,t){return N(`/admin/datasets/${e}/doi/update`,{method:"POST",body:JSON.stringify(t)},!0)}async function Wie(e,t){return N(`/admin/datasets/${e}/withdraw`,{method:"POST",body:JSON.stringify({reason:t.reason,dry_run:t.dryRun})},!0)}async function Kie(e,t){return N(`/admin/datasets/${e}/restore`,{method:"POST",body:JSON.stringify({dry_run:t.dryRun})},!0)}async function Yie(e){return N(`/admin/datasets/${e}/reset`,{method:"POST"},!0)}async function Jie(e,t=!1){return N(`/admin/datasets/${e}`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({force:t})},!0)}async function Xie(e){return N("/admin/datasets/bulk-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dataset_ids:e})},!0)}async function Qie(e){return N("/admin/datasets/import",{method:"POST",body:JSON.stringify(e)},!0)}async function Zie(e){return N("/admin/datasets/exemplar",{method:"POST",body:JSON.stringify(e)},!0)}async function eoe(e){return N(`/admin/datasets/${e}/exemplar/remint-dois`,{method:"POST"},!0)}async function s2(e,t){let r=new URLSearchParams;if(e)r.set("status",e);if(t!==void 0)r.set("blocklisted",t?"1":"0");let n=r.toString();return N(`/admin/imports${n?`?${n}`:""}`,{},!0)}async function toe(e){return N(`/admin/imports/${e}/rollback`,{method:"POST"},!0)}async function roe(e){return N(`/admin/imports/${e}/retry`,{method:"POST"},!0)}async function a2(e){return N(`/admin/imports/${e}/verify`,{method:"POST"},!0)}async function noe(e){return N("/admin/imports/dispatch-cooldown",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dataset_ids:e})},!0)}async function up(e,t){return N(`/admin/datasets/${e}/reindex`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})},!0)}async function ioe(e,t){return N("/admin/datasets/reindex/bulk",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filter:e,...t??{}})},!0)}async function ooe(e){let t=e?.limit??15;return N(`/admin/datasets/hed-sweep?limit=${encodeURIComponent(String(t))}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function soe(){return N("/admin/datasets/hed-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function aoe(e){let t=e?.limit??50;return N(`/admin/datasets/recording-stats-sweep?limit=${encodeURIComponent(String(t))}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function coe(){return N("/admin/datasets/recording-stats-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function loe(e){let t=e?.limit??15;return N(`/admin/datasets/signal-defaults-sweep?limit=${encodeURIComponent(String(t))}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function uoe(){return N("/admin/datasets/signal-defaults-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function doe(e){let t=e?.limit??15,r=new URLSearchParams({limit:String(t)});if(e?.olderThan!=null)r.set("older-than",String(e.olderThan));if(e?.before!=null)r.set("before",e.before);return N(`/admin/datasets/data-integrity-sweep?${r.toString()}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function foe(){return N("/admin/datasets/data-integrity-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function poe(e,t){let r=t?.write?"":"?dry_run=1";return N(`/admin/datasets/${e}/availability-report${r}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function moe(e){let t=e?.limit??30,r=new URLSearchParams({limit:String(t)});if(e?.missingOnly)r.set("missing-only","1");return N(`/admin/datasets/availability-report-sweep?${r.toString()}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function hoe(){return N("/admin/datasets/availability-report-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function goe(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 r=t.toString()?`?${t.toString()}`:"";return N(`/admin/fleet/drift${r}`,{},!0)}async function dp(e,t){return N(`/admin/datasets/${e}/enforce`,{method:"POST",body:JSON.stringify({dry_run:t})},!0)}async function yoe(e){return N("/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 boe(e,t){return N(`/admin/datasets/${e}/review-ruleset`,{method:"POST",body:JSON.stringify({dry_run:t.dryRun,remove:t.remove})},!0)}async function woe(e){return N("/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 xoe(e,t=!1){return N(`/admin/datasets/${e}/revalidate${t?"?force=true":""}`,{method:"POST"},!0)}async function voe(e){let t=e?`?user=${encodeURIComponent(e)}`:"";return N(`/admin/email-preferences${t}`,{},!0)}async function _oe(e,t){let r=t?`?user=${encodeURIComponent(t)}`:"";return N(`/admin/email-preferences${r}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)},!0)}async function c2(e){return N("/admin/notify",{method:"POST",body:JSON.stringify(e)},!0)}async function Doe(){return N("/admin/summary/coverage",{},!0)}async function Eoe(e,t,r){return N("/admin/manifest/dispatch",{method:"POST",body:JSON.stringify({dataset_id:e,version:t,skip_canary:r?.skipCanary??!1})},!0)}async function l2(e){return N("/admin/doctor/scan",{method:"POST",body:JSON.stringify({...e?.check&&{check:e.check},...e?.datasetId&&{dataset_id:e.datasetId}})},!0)}async function u2(e){return N("/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 Soe(){return N("/admin/zarr-catalog/publish",{method:"POST"},!0)}async function $oe(e){return N("/admin/neurobagel/regenerate",{method:"POST",body:JSON.stringify(e)},!0)}async function koe(){return N("/admin/neurobagel/status",{method:"GET"},!0)}async function Roe(){return N("/admin/neurobagel/verify",{method:"POST",body:"{}"},!0)}async function Coe(e){let t=new URLSearchParams;if(e?.limit!=null)t.set("limit",String(e.limit));let r=t.toString()?`?${t.toString()}`:"";return N(`/admin/datasets/zarr-fidelity-sweep${r}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Aoe(e){let t=new URLSearchParams;if(e?.limit!=null)t.set("limit",String(e.limit));if(e?.apply)t.set("apply","1");let r=t.toString()?`?${t.toString()}`:"";return N(`/admin/imports/issue-triage${r}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Ooe(e){let t=e?.apply?"?apply=1":"";return N(`/admin/imports/coverage-sweep${t}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Toe(e){let t=e?.apply?"?apply=1":"";return N(`/admin/imports/weekly-summary${t}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Poe(e){return N("/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 Ioe(e){return N("/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 Foe(){return N("/admin/users/duplicates",{},!0,kV)}async function Noe(e){return N(`/admin/users/${e}/clear-identity-conflict`,{method:"POST"},!0,RV)}async function joe(e){let t=new URLSearchParams;if(e?.limit!=null)t.set("limit",String(e.limit));let r=t.toString()?`?${t.toString()}`:"";return N(`/admin/datasets/anonymity-sweep${r}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Moe(){return N("/admin/datasets/anonymity-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function ov(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 r=t.toString()?`?${t.toString()}`:"";return N(`/admin/pr-reviews${r}`,{method:"GET"},!0)}async function d2(e,t,r){let n=r?`?head=${encodeURIComponent(r)}`:"";return N(`/admin/pr-reviews/${encodeURIComponent(e)}/${t}${n}`,{method:"GET"},!0)}async function f2(e,t){return N(`/admin/pr-reviews/${encodeURIComponent(e)}/${t}/start`,{method:"POST"},!0)}async function qoe(e){return N(`/admin/pr-review-authors/${encodeURIComponent(e)}`,{method:"GET"},!0)}async function Loe(e,t,r){return N(`/admin/pr-review-authors/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(r?{mode:t,reason:r}:{mode:t})},!0)}async function Boe(e){return N(`/admin/pr-review-authors/${encodeURIComponent(e)}`,{method:"DELETE"},!0)}async function Uoe(e,t,r,n){return N(`/admin/pr-reviews/${encodeURIComponent(e)}/${t}/allow`,{method:"POST",body:JSON.stringify({reason:r,...n?{head_sha:n}:{}})},!0)}var hu=F(()=>{oh();sf();aa()});async function Xr(e,t){return N(`/datasets/${e}/upload-credentials`,{method:"POST",body:JSON.stringify({duration_seconds:t})},!0)}async function p2(e,t){return N(`/datasets/${e}/download-credentials`,{method:"POST",body:JSON.stringify({duration_seconds:t})},!0)}async function zoe(e){return N(`/admin/datasets/${e}/files`,{},!0)}async function Voe(e){let t,r=0,n=[],i=!0;while(i){let o=await N(`/admin/datasets/${e}/s3-lock`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({continuation_token:t})},!0);if(r+=o.locked,o.failed?.length)n.push(...o.failed);if(i=o.hasMore,t=o.continuation_token,i&&!t)throw new q(500,"S3 lock paginated response missing continuation_token; aborting to avoid infinite loop")}return{locked:r,failed:n}}var la=F(()=>{aa();Tt()});async function av(e){return N(`/datasets/${e}/ci/status`,{},!0)}async function Hoe(e){return N(`/datasets/${e}/manifest`,{},!0)}async function cv(e,t){return N(`/datasets/${e}/manifest/${t}`,{},!0)}function Goe(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 rl(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[i,o]of Object.entries(e.facets))t.set(i,o);if(e.includeUnknown)t.set("include_unknown","1");let r=t.toString()?`?${t.toString()}`:"",n=await N(`/datasets${r}`,{},e.mine?!0:"optional");return n.datasets=n.datasets.map(Goe),n}async function Woe(e){return N(`/datasets/resolve/${e}`,{},"optional")}async function Koe(){return N("/datasets/facets",{signal:AbortSignal.timeout(5000)},"optional",kb)}async function Yoe(e,t={}){let r=new URLSearchParams({q:e});if(t.modality)r.set("modality",t.modality);if(t.limit)r.set("limit",String(t.limit));if(t.hasHed)r.set("has_hed","1");if(t.hasZarr)r.set("has_zarr","1");if(t.hasZarrVerified)r.set("has_zarr_verified","1");if(t.author)r.set("author",t.author);if(t.task)r.set("task",t.task);if(t.license)r.set("license",t.license);if(t.hasDoi)r.set("has_doi","true");if(t.dataComplete)r.set("data_complete","1");if(t.recent)r.set("recent",String(t.recent));if(t.facets)for(let[i,o]of Object.entries(t.facets))r.set(i,o);if(t.includeUnknown)r.set("include_unknown","1");return await N(`/datasets/search?${r.toString()}`,{},"optional",xV)}async function Sr(e){let t=await N(`/datasets/${e}`,{},"optional");return Goe(t.dataset)}async function Joe(e){return N(`/datasets/${e}/versions`,{},!0)}async function lv(e){return N("/datasets",{method:"POST",body:JSON.stringify(e)},!0)}async function Xoe(e,t){return N(`/datasets/${e}/attestation`,{method:"PUT",body:JSON.stringify(t)},!0)}async function uv(e){return N(`/datasets/${e}/finalize`,{method:"POST"},!0)}async function m2(e){return N(`/datasets/${e}/request-access`,{method:"POST"},!0)}async function Qoe(e,t){let r=t?`?status=${t}`:"";return N(`/datasets/${e}/access-requests${r}`,{},!0)}async function Zoe(e,t){return N(`/datasets/${e}/access-requests/${t}/approve`,{method:"POST"},!0)}async function ese(e,t){return N(`/datasets/${e}/access-requests/${t}/deny`,{method:"POST"},!0)}async function tse(e,t){return N(`/datasets/${e}/invite`,{method:"POST",body:JSON.stringify({username:t})},!0)}async function rse(e){return N(`/datasets/${e}/collaborators`,{},!0)}async function nse(e,t){return N(`/admin/datasets/${e}/enrichment`,{method:"POST",body:JSON.stringify(t)},!0)}var sv;var nl=F(()=>{sf();aa();sv=/^\d{4}-\d{4}-\d{4}-\d{3}[\dX]$/});function Rse(e,t){return e.filter((r)=>r.visibility==="public").map((r)=>r.dataset_id).filter((r)=>r.startsWith("nm")||r.startsWith("on")).filter((r)=>r!=="nm099999"&&!ua.has(r)).filter((r)=>t.prefix?r.startsWith(t.prefix):!0).sort()}var ua;var mv=F(()=>{ua=new Set(["nm000103","nm000104","nm000105","nm000106","nm000107"])});function Qr(e){return e.replace(oet,(t)=>{if(t===`
|
|
113
|
+
`)}var hie=!1;var VC=F(()=>{je()});function Qx(){if(process.env.TEST_API_URL)return process.env.TEST_API_URL;if(GC)return HC;return jt().apiUrl||HC}async function N(e,t={},r=!1,n){let i=`${Qx()}${e}`,o={"Content-Type":"application/json","X-CLI-Version":ao,...t.headers};if(r){let p=jt();if(!p.apiKey&&r===!0)throw new q(401,"Not authenticated. Run 'nemar auth login' first.");if(p.apiKey)o.Authorization=`Bearer ${p.apiKey}`}let s=t.method||"GET",a=typeof t.body==="string"?t.body:void 0,c=Date.now(),u;try{u=await fetch(i,{...t,headers:o})}catch(p){if(du())Yx({method:s,url:i,status:null,durationMs:Date.now()-c,requestHeaders:o,requestBody:a,error:p instanceof Error?p.message:String(p)});throw new q(0,`Network error: Could not connect to ${Qx()}`,{originalError:p instanceof Error?p.message:String(p)})}let d;try{d=await u.text()}catch(p){if(du())Yx({method:s,url:i,status:u.status,durationMs:Date.now()-c,requestHeaders:o,requestBody:a,error:p instanceof Error?p.message:String(p)});throw new q(0,"Failed to read response body",{httpStatus:u.status,originalError:p instanceof Error?p.message:String(p)})}if(du())Yx({method:s,url:i,status:u.status,durationMs:Date.now()-c,requestHeaders:o,requestBody:a,responseBody:d});let f;try{f=JSON.parse(d)}catch{throw new q(u.status,`Invalid response from server (status ${u.status})`)}if(!u.ok){if(u.status===503&&(f.mode==="read-only"||f.mode==="full")){let L=typeof f.message==="string"?f.message:"NEMAR is in maintenance mode. Please retry shortly.",P=typeof f.eta==="string"?f.eta:null,j=new dc(f.mode,L,P,f.details);throw Xx(j),j}let p=typeof f.block_reason==="string",m=Array.isArray(f.missing)?f.missing.filter((L)=>typeof L==="string"):void 0,g=typeof f.error==="string"&&(lV.includes(f.error)||$V.includes(f.error)),h=typeof f.error==="string"&&(Cb.options.includes(f.error)||OV.includes(f.error)),b=typeof f.error==="string"&&nV.includes(f.error),w=typeof f.error==="string"&&uV.includes(f.error),x=typeof f.error==="string"&&DV.includes(f.error),v=typeof f.error==="string"&&_V.includes(f.error),R=typeof f.error==="string"&&EV.includes(f.error),T=p||v||R||g||h||b||w||x||m!==void 0&&typeof f.error==="string"&&cV.includes(f.error)?f.message||f.error:f.error||f.message;if(u.status===404&&f.error==="Not Found"&&typeof f.message==="string")T=`${f.message}. This NEMAR backend does not support this command yet.`;let A=new q(u.status,T||"Request failed",f.details,typeof f.step==="string"?f.step:void 0,p?f.block_reason:void 0,m);if(typeof f.error==="string")A.code=f.error;if(typeof f.reason==="string")A.reason=f.reason;throw A.rawBody=f,A}if(n){let p=n.safeParse(f);if(!p.success)throw new q(u.status,`Response for ${e} did not match the expected NEMAR contract`,{issues:p.error.issues});return p.data}return f}var HC="https://api.nemar.org",GC;var aa=F(()=>{oh();Tb();h1();sh();Zd();Ii();Br();VC();Zf();Tt();GC=HC.includes("workers.dev")});async function np(e,t={}){return N(`/datasets/${e}/publish/request`,t.anonymous?{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({anonymous:!0})}:{method:"POST"},!0)}async function ip(e){return N(`/datasets/${e}/publish/status`,{},!0)}async function bie(e){return N(`/datasets/${e}/publish/resend`,{method:"POST"},!0)}async function wie(e){return N(`/datasets/${e}/publish/withdraw`,{method:"POST"},!0)}async function fu(e={}){let{statuses:t,search:r}=typeof e==="string"?{statuses:e?[e]:[]}:e,n=await gie(t,r),i=n;if(t!==void 0&&t.length>1&&n.requests.length===0){let o=[];for(let a of new Set(t))o.push(await gie([a],r));let s=o.flatMap((a)=>a.requests).sort(xie);i={...n,requests:s,count:s.length}}return r?zZe(i,r):i}function xie(e,t){return e.requested_at<t.requested_at?1:e.requested_at>t.requested_at?-1:0}async function gie(e,t){let r=new URLSearchParams;if(e&&e.length>0)r.set("status",e.join(","));if(t)r.set("search",t);let n=r.size>0?`?${r}`:"";return N(`/admin/publish/requests${n}`,{},!0)}function zZe(e,t){let r=e.requests.filter((o)=>nH(t,[o.dataset_id,o.requested_by_username,o.dataset_name])),n=(o)=>iH(o.dataset_id,t)?0:1,i=[...r].sort((o,s)=>n(o)-n(s)||xie(o,s));return{...e,requests:i,count:i.length}}async function op(e,t,r){return N(`/admin/publish/${e}/deny`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:t,...r!==void 0?{request_id:r}:{}})},!0)}async function Zx(e){return N(`/admin/publish/${e}/identifier-screen`,{method:"POST"},!0)}async function ev(e){return N(`/admin/publish/${e}/review`,{},!0)}async function vie(e){return N(`/admin/publish/${e}/review/start`,{method:"POST"},!0)}async function _ie(e,t){let r={message:t};return N(`/admin/publish/${e}/comment`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},!0)}function sp(e){if(!(e instanceof q))return;let t=e.rawBody;if(typeof t!=="object"||t===null||Array.isArray(t))return;let r=t.code;return typeof r==="string"?r:void 0}function VZe(e,t=[]){if(e){let r=Bo.indexOf(e);if(r>=0)return r+1}return Math.min(t.length+1,Bo.length)}function HZe(e){if(!(e instanceof q))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 GZe(){let e=process.env.NEMAR_APPROVE_RETRY_DELAY_MS;if(e===void 0||!/^\d+$/.test(e))return zb;let t=Number(e);return Number.isSafeInteger(t)&&t<=zb?t:zb}async function ap(e,t=!1,r=!1,n=!1,i,o,s,a,c){let d=GZe(),f,p,m=0,g=!1,h,b=t,w=[],x;function v(R,E,T,A){if(!o)return;o({step:R,stepIndex:VZe(R,E),stepTotal:Bo.length,s3LockLocked:T,s3LockTotal:A,s3LockResumed:R==="s3_lock"&&g?!0:void 0})}for(let R=1;R<=5;R++)try{let E,T=!0;do{if(E=await N(`/admin/publish/${e}/approve`,{method:"POST",headers:{"Content-Type":"application/json",...c?.dispatchToken?{[SV]:c.dispatchToken}:{}},body:JSON.stringify({resume:T?b:!0,sandbox:r,s3_lock_continuation_token:f,s3_lock_total:p,skip_ci_check:n,...s!==void 0?{acknowledge_identifier_screen:s}:{},...a!==void 0?{[eH]:a}:{},...c?.requestId!==void 0?{request_id:c.requestId}:{}})},!0),T=!1,E.step_results)w.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 A=E.step??E.step_results?.[E.step_results.length-1]?.step;if(A&&(A!==h||A==="s3_lock"))v(A,E.steps_completed??[],A==="s3_lock"?m:void 0,A==="s3_lock"?p:void 0),h=A;if(E.hasMore&&E.s3_lock_continuation_token!==void 0)f=E.s3_lock_continuation_token;else break}while(E.hasMore);if(w.length>0)E.step_results=yie(w);return E}catch(E){if(x=E,R===5||!HZe(E)){if(E instanceof q&&w.length>0)E.stepResults=yie(w);throw E}let A=E;if(i?.({attempt:R,maxAttempts:5,delayMs:d,step:A.step,error:A.message}),await new Promise((L)=>setTimeout(L,d)),b=!0,f!==void 0)g=!0}throw x}function yie(e){let t=new Map;for(let r of e)t.set(r.step,r);return Array.from(t.values())}var co=F(()=>{Ub();sh();Hb();aa();Tt()});function nv(e){if(e.service_access===void 0||e.service_access===null)return"unknown";return e.service_access?"upload":"browse"}async function t2(e,t,r,n,i={}){let o=new URLSearchParams;if(e)o.set("status",e);if(t)o.set("role",t);if(r)o.set("awaiting_approval","1");if(n)o.set("kind",n);if(i.search!==void 0)o.set("q",i.search);if(i.includeDeleted)o.set("include_deleted","true");let s=o.toString()?`?${o.toString()}`:"";return N(`/admin/users${s}`,{},!0,sV)}async function iv(e,t=!1){return N(`/admin/users/by-id/${e}${t?"?include_deleted=true":""}`,{},!0,pV)}async function Tie(e,t){return N(`/admin/users/by-id/${e}`,{method:"PATCH",body:JSON.stringify(t)},!0,mV)}async function Pie(e){return N(`/admin/approve/${e}`,{method:"POST"},!0)}async function Iie(e){return N(`/admin/approve/by-id/${e}`,{method:"POST"},!0)}async function Fie(e){return N(`/admin/revoke/${e}`,{method:"POST"},!0)}async function Nie(e){return N(`/admin/revoke/by-id/${e}`,{method:"POST"},!0)}async function jie(e){return N(`/admin/users/by-id/${e}/verify`,{method:"POST"},!0)}async function Mie(e,t){return N(`/admin/users/${e}/role`,{method:"POST",body:JSON.stringify({role:t})},!0)}async function qie(e,t){return N(`/admin/users/${e}/kind`,{method:"POST",body:JSON.stringify({kind:t})},!0)}async function Lie(e){return N(`/admin/users/${e}`,{},!0)}async function Bie(e,t){return N(`/admin/users/${e}/keys`,{method:"POST",body:JSON.stringify({name:t})},!0,Ob)}async function Uie(e){return N(`/admin/users/${e}/keys`,{},!0,Ab)}async function zie(e,t){return N(`/admin/users/${e}/keys/${t}`,{method:"DELETE"},!0)}async function r2(e,t){return N(`/admin/datasets/${e}/visibility`,{method:"PATCH",body:JSON.stringify({visibility:t})},!0)}async function Vie(e){return N(`/datasets/${e}/publish`,{method:"POST"},!0)}async function Hie(e){return N(`/admin/datasets/${e}/ci`,{},!0)}async function ca(e){return N(`/admin/datasets/${e}/ci`,{method:"POST"},!0)}async function n2(e){return N(`/admin/datasets/${e}/ci/validate`,{method:"POST"},!0)}async function i2(e){return N(`/admin/datasets/${e}/ci/sync`,{method:"POST"},!0)}async function Gie(e,t){return N(`/admin/datasets/${e}/doi/concept`,{method:"POST",body:JSON.stringify(t)},!0)}async function tg(e){return N(`/admin/datasets/${e}/doi`,{},!0)}async function o2(e,t){return N(`/admin/datasets/${e}/doi/update`,{method:"POST",body:JSON.stringify(t)},!0)}async function Wie(e,t){return N(`/admin/datasets/${e}/withdraw`,{method:"POST",body:JSON.stringify({reason:t.reason,dry_run:t.dryRun})},!0)}async function Kie(e,t){return N(`/admin/datasets/${e}/restore`,{method:"POST",body:JSON.stringify({dry_run:t.dryRun})},!0)}async function Yie(e){return N(`/admin/datasets/${e}/reset`,{method:"POST"},!0)}async function Jie(e,t=!1){return N(`/admin/datasets/${e}`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({force:t})},!0)}async function Xie(e){return N("/admin/datasets/bulk-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dataset_ids:e})},!0)}async function Qie(e){return N("/admin/datasets/import",{method:"POST",body:JSON.stringify(e)},!0)}async function Zie(e){return N("/admin/datasets/exemplar",{method:"POST",body:JSON.stringify(e)},!0)}async function eoe(e){return N(`/admin/datasets/${e}/exemplar/remint-dois`,{method:"POST"},!0)}async function s2(e,t){let r=new URLSearchParams;if(e)r.set("status",e);if(t!==void 0)r.set("blocklisted",t?"1":"0");let n=r.toString();return N(`/admin/imports${n?`?${n}`:""}`,{},!0)}async function toe(e){return N(`/admin/imports/${e}/rollback`,{method:"POST"},!0)}async function roe(e){return N(`/admin/imports/${e}/retry`,{method:"POST"},!0)}async function a2(e){return N(`/admin/imports/${e}/verify`,{method:"POST"},!0)}async function noe(e){return N("/admin/imports/dispatch-cooldown",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dataset_ids:e})},!0)}async function up(e,t){return N(`/admin/datasets/${e}/reindex`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})},!0)}async function ioe(e,t){return N("/admin/datasets/reindex/bulk",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filter:e,...t??{}})},!0)}async function ooe(e){let t=e?.limit??15;return N(`/admin/datasets/hed-sweep?limit=${encodeURIComponent(String(t))}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function soe(){return N("/admin/datasets/hed-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function aoe(e){let t=e?.limit??50;return N(`/admin/datasets/recording-stats-sweep?limit=${encodeURIComponent(String(t))}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function coe(){return N("/admin/datasets/recording-stats-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function loe(e){let t=e?.limit??15;return N(`/admin/datasets/signal-defaults-sweep?limit=${encodeURIComponent(String(t))}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function uoe(){return N("/admin/datasets/signal-defaults-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function doe(e){let t=e?.limit??15,r=new URLSearchParams({limit:String(t)});if(e?.olderThan!=null)r.set("older-than",String(e.olderThan));if(e?.before!=null)r.set("before",e.before);return N(`/admin/datasets/data-integrity-sweep?${r.toString()}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function foe(){return N("/admin/datasets/data-integrity-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function poe(e,t){let r=t?.write?"":"?dry_run=1";return N(`/admin/datasets/${e}/availability-report${r}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function moe(e){let t=e?.limit??30,r=new URLSearchParams({limit:String(t)});if(e?.missingOnly)r.set("missing-only","1");return N(`/admin/datasets/availability-report-sweep?${r.toString()}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function hoe(){return N("/admin/datasets/availability-report-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function goe(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 r=t.toString()?`?${t.toString()}`:"";return N(`/admin/fleet/drift${r}`,{},!0)}async function dp(e,t){return N(`/admin/datasets/${e}/enforce`,{method:"POST",body:JSON.stringify({dry_run:t})},!0)}async function yoe(e){return N("/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 boe(e,t){return N(`/admin/datasets/${e}/review-ruleset`,{method:"POST",body:JSON.stringify({dry_run:t.dryRun,remove:t.remove})},!0)}async function woe(e){return N("/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 xoe(e,t=!1){return N(`/admin/datasets/${e}/revalidate${t?"?force=true":""}`,{method:"POST"},!0)}async function voe(e){let t=e?`?user=${encodeURIComponent(e)}`:"";return N(`/admin/email-preferences${t}`,{},!0)}async function _oe(e,t){let r=t?`?user=${encodeURIComponent(t)}`:"";return N(`/admin/email-preferences${r}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)},!0)}async function c2(e){return N("/admin/notify",{method:"POST",body:JSON.stringify(e)},!0)}async function Doe(){return N("/admin/summary/coverage",{},!0)}async function Eoe(e,t,r){return N("/admin/manifest/dispatch",{method:"POST",body:JSON.stringify({dataset_id:e,version:t,skip_canary:r?.skipCanary??!1})},!0)}async function l2(e){return N("/admin/doctor/scan",{method:"POST",body:JSON.stringify({...e?.check&&{check:e.check},...e?.datasetId&&{dataset_id:e.datasetId}})},!0)}async function u2(e){return N("/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 Soe(){return N("/admin/zarr-catalog/publish",{method:"POST"},!0)}async function $oe(e){return N("/admin/neurobagel/regenerate",{method:"POST",body:JSON.stringify(e)},!0)}async function koe(){return N("/admin/neurobagel/status",{method:"GET"},!0)}async function Roe(){return N("/admin/neurobagel/verify",{method:"POST",body:"{}"},!0)}async function Coe(e){let t=new URLSearchParams;if(e?.limit!=null)t.set("limit",String(e.limit));let r=t.toString()?`?${t.toString()}`:"";return N(`/admin/datasets/zarr-fidelity-sweep${r}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Aoe(e){let t=new URLSearchParams;if(e?.limit!=null)t.set("limit",String(e.limit));if(e?.apply)t.set("apply","1");let r=t.toString()?`?${t.toString()}`:"";return N(`/admin/imports/issue-triage${r}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Ooe(e){let t=e?.apply?"?apply=1":"";return N(`/admin/imports/coverage-sweep${t}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Toe(e){let t=e?.apply?"?apply=1":"";return N(`/admin/imports/weekly-summary${t}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Poe(e){return N("/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 Ioe(e){return N("/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 Foe(){return N("/admin/users/duplicates",{},!0,kV)}async function Noe(e){return N(`/admin/users/${e}/clear-identity-conflict`,{method:"POST"},!0,RV)}async function joe(e){let t=new URLSearchParams;if(e?.limit!=null)t.set("limit",String(e.limit));let r=t.toString()?`?${t.toString()}`:"";return N(`/admin/datasets/anonymity-sweep${r}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Moe(){return N("/admin/datasets/anonymity-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function ov(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 r=t.toString()?`?${t.toString()}`:"";return N(`/admin/pr-reviews${r}`,{method:"GET"},!0)}async function d2(e,t,r){let n=r?`?head=${encodeURIComponent(r)}`:"";return N(`/admin/pr-reviews/${encodeURIComponent(e)}/${t}${n}`,{method:"GET"},!0)}async function f2(e,t){return N(`/admin/pr-reviews/${encodeURIComponent(e)}/${t}/start`,{method:"POST"},!0)}async function qoe(e){return N(`/admin/pr-review-authors/${encodeURIComponent(e)}`,{method:"GET"},!0)}async function Loe(e,t,r){return N(`/admin/pr-review-authors/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(r?{mode:t,reason:r}:{mode:t})},!0)}async function Boe(e){return N(`/admin/pr-review-authors/${encodeURIComponent(e)}`,{method:"DELETE"},!0)}async function Uoe(e,t,r,n){return N(`/admin/pr-reviews/${encodeURIComponent(e)}/${t}/allow`,{method:"POST",body:JSON.stringify({reason:r,...n?{head_sha:n}:{}})},!0)}var hu=F(()=>{oh();sf();aa()});async function Xr(e,t){return N(`/datasets/${e}/upload-credentials`,{method:"POST",body:JSON.stringify({duration_seconds:t})},!0)}async function p2(e,t){return N(`/datasets/${e}/download-credentials`,{method:"POST",body:JSON.stringify({duration_seconds:t})},!0)}async function zoe(e){return N(`/admin/datasets/${e}/files`,{},!0)}async function Voe(e){let t,r=0,n=[],i=!0;while(i){let o=await N(`/admin/datasets/${e}/s3-lock`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({continuation_token:t})},!0);if(r+=o.locked,o.failed?.length)n.push(...o.failed);if(i=o.hasMore,t=o.continuation_token,i&&!t)throw new q(500,"S3 lock paginated response missing continuation_token; aborting to avoid infinite loop")}return{locked:r,failed:n}}var la=F(()=>{aa();Tt()});async function av(e){return N(`/datasets/${e}/ci/status`,{},!0)}async function Hoe(e){return N(`/datasets/${e}/manifest`,{},!0)}async function cv(e,t){return N(`/datasets/${e}/manifest/${t}`,{},!0)}function Goe(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 rl(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[i,o]of Object.entries(e.facets))t.set(i,o);if(e.includeUnknown)t.set("include_unknown","1");let r=t.toString()?`?${t.toString()}`:"",n=await N(`/datasets${r}`,{},e.mine?!0:"optional");return n.datasets=n.datasets.map(Goe),n}async function Woe(e){return N(`/datasets/resolve/${e}`,{},"optional")}async function Koe(){return N("/datasets/facets",{signal:AbortSignal.timeout(5000)},"optional",kb)}async function Yoe(e,t={}){let r=new URLSearchParams({q:e});if(t.modality)r.set("modality",t.modality);if(t.limit)r.set("limit",String(t.limit));if(t.hasHed)r.set("has_hed","1");if(t.hasZarr)r.set("has_zarr","1");if(t.hasZarrVerified)r.set("has_zarr_verified","1");if(t.author)r.set("author",t.author);if(t.task)r.set("task",t.task);if(t.license)r.set("license",t.license);if(t.hasDoi)r.set("has_doi","true");if(t.dataComplete)r.set("data_complete","1");if(t.recent)r.set("recent",String(t.recent));if(t.facets)for(let[i,o]of Object.entries(t.facets))r.set(i,o);if(t.includeUnknown)r.set("include_unknown","1");return await N(`/datasets/search?${r.toString()}`,{},"optional",xV)}async function Sr(e){let t=await N(`/datasets/${e}`,{},"optional");return Goe(t.dataset)}async function Joe(e){return N(`/datasets/${e}/versions`,{},!0)}async function lv(e){return N("/datasets",{method:"POST",body:JSON.stringify(e)},!0)}async function Xoe(e,t){return N(`/datasets/${e}/attestation`,{method:"PUT",body:JSON.stringify(t)},!0)}async function uv(e){return N(`/datasets/${e}/finalize`,{method:"POST"},!0)}async function m2(e){return N(`/datasets/${e}/request-access`,{method:"POST"},!0)}async function Qoe(e,t){let r=t?`?status=${t}`:"";return N(`/datasets/${e}/access-requests${r}`,{},!0)}async function Zoe(e,t){return N(`/datasets/${e}/access-requests/${t}/approve`,{method:"POST"},!0)}async function ese(e,t){return N(`/datasets/${e}/access-requests/${t}/deny`,{method:"POST"},!0)}async function tse(e,t){return N(`/datasets/${e}/invite`,{method:"POST",body:JSON.stringify({username:t})},!0)}async function rse(e){return N(`/datasets/${e}/collaborators`,{},!0)}async function nse(e,t){return N(`/admin/datasets/${e}/enrichment`,{method:"POST",body:JSON.stringify(t)},!0)}var sv;var nl=F(()=>{sf();aa();sv=/^\d{4}-\d{4}-\d{4}-\d{3}[\dX]$/});function Rse(e,t){return e.filter((r)=>r.visibility==="public").map((r)=>r.dataset_id).filter((r)=>r.startsWith("nm")||r.startsWith("on")).filter((r)=>r!=="nm099999"&&!ua.has(r)).filter((r)=>t.prefix?r.startsWith(t.prefix):!0).sort()}var ua;var mv=F(()=>{ua=new Set(["nm000103","nm000104","nm000105","nm000106","nm000107"])});function Qr(e){return e.replace(oet,(t)=>{if(t===`
|
|
114
114
|
`)return"\\n";if(t==="\r")return"\\r";if(t==="\t")return"\\t";let r=t.codePointAt(0)??0;return r<=255?`\\x${r.toString(16).padStart(2,"0")}`:`\\u${r.toString(16).padStart(4,"0")}`})}function hv(e,t=", "){return e.map(Qr).join(t)}var oet,ys=(e)=>Qr(e)===e;var fp=F(()=>{oet=/[\p{Cc}\u2028\u2029\u202a-\u202e\u2066-\u2069]/gu});async function set(){try{let{exitCode:e,stderr:t}=await k(["ssh","-T","-o","BatchMode=yes","-o","ConnectTimeout=5","git@github.com"]),r=t.includes("successfully authenticated");if(!r)console.warn("SSH test to github.com failed:",{exitCode:e,stderr:t.trim().slice(0,500)});return{works:r,error:r?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 gu(){try{let{stdout:e,exitCode:t,stderr:r}=await k(["gh","auth","token"],{sensitiveOutput:!0});if(t!==0)return console.warn("gh CLI returned non-zero exit code:",t),console.warn("stderr:",r),{token:null,error:`gh auth token failed: ${r.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 gv(e){try{let{stdout:t,exitCode:r,stderr:n}=await k(["gh","api","user","--jq",".login"]);if(r!==0){if(n.includes("not logged in")||n.includes("auth login"))return{authenticated:!1,error:"gh CLI not authenticated. Run 'gh auth login' to authenticate."};return{authenticated:!1,error:`gh CLI error: ${n.trim()||"unknown error"}`}}let i=t.trim();if(!i)return{authenticated:!1,error:"gh CLI returned empty username"};if(e){let o=i.toLowerCase()===e.toLowerCase();return{authenticated:!0,username:i,matches:o,error:o?void 0:`gh CLI authenticated as '${i}', expected '${e}'`}}return{authenticated:!0,username:i}}catch(t){let r=t instanceof Error?t.message:String(t);if(r.includes("ENOENT")||r.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: ${r}`}}}async function yv(e){if(!/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/.test(e))return{accepted:!1,error:`Invalid repository format: ${e}`};let{stdout:t,exitCode:r,stderr:n}=await k(["gh","api","/user/repository_invitations"]);if(r!==0){if(n.includes("not logged in")||n.includes("auth login"))return{accepted:!1,error:"gh CLI not authenticated. Run 'gh auth login' to authenticate."};if(n.includes("API rate limit")||n.includes("403"))return{accepted:!1,error:"GitHub API rate limit exceeded. Please try again in a few minutes."};if(n.includes("ENOENT")||n.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: ${n.trim()||"unknown error"}`}}let i=null;try{i=JSON.parse(t||"[]").find((u)=>u.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(!i){let{exitCode:a}=await k(["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:o,stderr:s}=await k(["gh","api","--method","PATCH",`/user/repository_invitations/${i}`]);if(o!==0)return{accepted:!1,error:`Failed to accept invitation: ${s.trim()||"unknown error"}`};return{accepted:!0}}async function bs(e,t,r="origin"){let n=t;if(process.env.GH_TOKEN&&t.startsWith("git@github.com:")){let i=process.env.GH_TOKEN.trim();if(!i||/\s/.test(i))return{success:!1,error:"GH_TOKEN environment variable is set but appears malformed (empty or contains whitespace)"};n=`https://github.com/${t.replace("git@github.com:","")}`,await k(["git","config","credential.https://github.com.helper",`!printf 'username=x-access-token\\npassword=${i}'`],{cwd:e,redact:[i]})}else if(t.startsWith("git@github.com:")){let i=t.replace("git@github.com:",""),o=await gu();if(o.token)n=`https://github.com/${i}`,await k(["git","config","credential.https://github.com.helper",`!printf 'username=x-access-token\\npassword=${o.token}'`],{cwd:e,redact:[o.token]});else{let s=await set();if(s.works)n=t;else return{success:!1,error:`GitHub authentication not configured.
|
|
115
115
|
|
|
116
116
|
gh CLI failed: ${o.error||"could not get token"}
|
|
@@ -1550,7 +1550,7 @@ ${o}
|
|
|
1550
1550
|
`)}}}sh();Tt();function Dge(e){return e instanceof q&&e.statusCode===422&&e.rawBody?.status==="blocked"&&Rb(e.blockReason)}function Ege(e){let t=e.rawBody?.ci_url;return typeof t==="string"&&/^https:\/\/\S+$/.test(t)?t:void 0}function LT(e){return e==="bids_validation_in_progress"?"Request recorded: BIDS validation is still running.":"Request recorded: BIDS validation has not started yet."}function BT(e,t=!1){let r=`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: ${r}`," 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}.`]}Tt();Ii();async function UD(){let e=jt().sandboxCompleted;if(e!==void 0)return{status:e?"completed":"not_completed"};try{let t=await dv();if(nr("sandboxCompleted",t.sandbox_completed),t.sandbox_dataset_id)nr("sandboxDatasetId",t.sandbox_dataset_id);return t.sandbox_completed?{status:"completed"}:{status:"not_completed"}}catch(t){return{status:"unknown",reason:M(t)}}}var UT=Ue(Vv(),1);function zD(e){if(e!==e.trim())return null;let t=UT.default.parse(e);if(!t)return null;if(t.prerelease.length>0||t.build.length>0)return null;return{major:t.major,minor:t.minor,patch:t.patch}}function kl(e,t){let r=zD(e);if(!r)throw Error(`Invalid version: ${e}`);let n=UT.default.inc(`${r.major}.${r.minor}.${r.patch}`,t);if(!n)throw Error(`Invalid version: ${e}`);return n}function zT(e){return zD(e)!==null}je();Ni();cO();je();sn();hu();Tt();Ip();j_();fp();Ni();ol();B_();dO();xl();Cu();import{existsSync as VT,mkdirSync as Jmt,readFileSync as Xmt,statSync as Qmt,writeFileSync as Sge}from"fs";import{join as Zmt,resolve as HT}from"path";function $ge(e,t,r){if(!go(r,"metadata_write")){if(t)try{let n=HT(e,".nemar"),i=HT(n,"metadata.json");if(!VT(i)){if(!VT(n))Jmt(n,{recursive:!0});Sge(i,JSON.stringify(t,null,2))}let o=HT(e,".bidsignore"),s="";if(VT(o))s=Xmt(o,"utf-8");if(!s.includes(".nemar/")){let a=s?`${s.trimEnd()}
|
|
1551
1551
|
.nemar/
|
|
1552
1552
|
`:`.nemar/
|
|
1553
|
-
`;Sge(o,a)}console.log(l.dim(" Updated .bidsignore for NEMAR metadata"))}catch(n){console.log(l.yellow(` Warning: Could not update .bidsignore: ${M(n)}`)),console.log(l.dim(" Upload will continue without author enrichment."))}wa(r,"metadata_write"),zr(e,r)}else console.log(l.dim(" Metadata write already completed (skipping)"))}var kge=1073741824;function eht(e,t,r=kge){let n=[],i=0;for(let o of t){let s=e.files[o];if(!s||s.mtimeMs===void 0)continue;n.push({path:o,size:s.size,mtimeMs:s.mtimeMs}),i+=s.size}return i>=r?n:null}function tht(e,t){return t.filter((r)=>{try{return il(r.path,Qmt(Zmt(e,r.path)).size)}catch{return!0}})}function rht(e){let t=0;for(let r of Object.values(e.files))t+=r.size;return t}function nht(e){return["Warning: saving dataset changes has produced no stdout or stderr for",`${U_(e)}. git add -A is still running.`,"Wait, or interrupt and rerun the upload; the save step will run again."].join(" ")}async function Rge(e,t,r,n={}){if(!go(r,"dataset_save")){let i=S({text:"Saving dataset changes...",...n.spinnerStream?{stream:n.spinnerStream}:{}}).start(),o=n.skipMinBytes??kge,s=[];if(rht(r)>=o){let c=n.annexedPaths??null;if(c===null)try{c=await wl(e)}catch(u){console.log(l.dim(` Could not list annexed files (${M(u)}); staging will re-read them`))}if(c!==null)s=tht(e,eht(r,c,o)??[])}let a=await da(e,"Initial NEMAR dataset upload",t,{skipContentCheck:s,onInactivityWarning:(c)=>{i=qg(i,nht(c))},...n.inactivityWarningAfterMs===void 0?{}:{inactivityWarningAfterMs:n.inactivityWarningAfterMs}});if(!a.success)return zr(e,r),yn(i,"Failed to save dataset",a.error),console.log(),console.log(l.yellow("Re-run the same command to resume from this step.")),$e;if(n.verifyRemote){let c;try{c=await bO(e,n.verifyRemote)}catch(u){return zr(e,r),yn(i,"Could not confirm the saved files are at the S3 remote",u),console.log(),console.log(l.yellow("Re-run the same command to resume from this step.")),$e}if(c.length>0){xa(r,"s3_upload"),zr(e,r);let u=hv(c.slice(0,5)),d=c.length>5?` (and ${c.length-5} more)`:"";return yn(i,"Saved files are not at the S3 remote",`${c.length} annexed file(s) in the commit are not recorded at the remote: ${u}${d}. The save itself annexed them, after the upload step had run.`),console.log(),console.log(l.yellow("Re-run the same command: it uploads them and saves again.")),$e}}i.succeed("Dataset changes saved"),wa(r,"dataset_save"),zr(e,r)}else console.log(l.dim(" Dataset save already completed (skipping)"));return Ut()}async function Cge(e,t){if(!go(t,"github_push")){let r=S("Pushing metadata to GitHub...").start(),n=await $r(e);if(!n.success)return zr(e,t),yn(r,"Failed to push to GitHub",n.error),console.log(),console.log(l.yellow("Re-run the same command to resume from this step.")),$e;if(n.warning)r.warn("Metadata pushed to GitHub (with warning)"),console.log(l.yellow(` ${n.warning}`));else r.succeed("Metadata pushed to GitHub");wa(t,"github_push"),zr(e,t)}else console.log(l.dim(" GitHub push already completed (skipping)"));return Ut()}async function Age(e,t,r){if(!go(r,"ci_deploy")){let n=S("Setting up BIDS validation CI...").start(),i="configured";try{await ca(t),n.succeed("BIDS validation CI configured")}catch(o){if(i="not-configured",o instanceof q&&o.statusCode===403)n.info("CI workflow will be configured by an admin");else{let s=o instanceof Error?o.message:String(o);n.warn(`Could not configure CI: ${s}`),console.log(l.dim(` An admin can add it later with: nemar admin ci add ${t}`))}}return wa(r,"ci_deploy"),zr(e,r),i}return console.log(l.dim(" CI deploy already completed (skipping)")),"unknown"}function iht(e,t){let r=e.startsWith("xx");if(t==="not-configured"){if(r)return;console.log("BIDS validation is not set up yet."),console.log(` CI is set up when you request publication: ${l.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: ${l.cyan(`nemar dataset ci ${e}`)}`),!r)console.log(` Once it has passed, request publication: ${l.cyan(`nemar dataset publish request ${e}`)}`);console.log()}function Oge(e,t,r="unknown"){Mg(e),Ade(e),console.log(),console.log(l.green.bold("Upload complete!")),console.log(),console.log(` Dataset ID: ${l.cyan(t.dataset_id)}`),console.log(` GitHub: ${l.cyan(t.github_url)}`),console.log(),console.log(l.dim("To download this dataset:")),console.log(l.dim(` nemar dataset download ${t.dataset_id}`)),console.log(),iht(t.dataset_id,r),console.log(l.yellow("Note: This dataset is private. Only the owner and designated collaborators can")),console.log(l.yellow("download it, and only through the NEMAR CLI (not direct git-annex commands).")),console.log(l.yellow("After publishing, the data will be publicly available for everyone."))}xl();Cu();async function Tge(e,t={}){let r=await tae(e.absolutePath);if(!r.success)return console.log(l.red(r.error)),console.log(l.yellow("Re-run the same command to retry.")),$e;if(r.cleared>0)console.log(l.yellow(` Cleared ${r.cleared} assume-unchanged flag(s) an earlier, interrupted save left on annexed files`));let n=await Nde(e.absolutePath);if(n.status==="error")return console.log(l.red(n.error)),$e;if(n.status==="warning")console.log(l.yellow(` ${n.warning}`));if(n.status==="restored")console.log(l.yellow(" Put back git-annex's filter process, which an earlier, interrupted upload had left out of this repository's configuration"));let i=await hfe(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(i.status==="fail")return $e;let{progress:o,annexedPaths:s}=i.value;if($ge(e.absolutePath,e.coAuthorEnrichment,o),(await(t.saveStep??Rge)(e.absolutePath,e.author,o,{annexedPaths:s,verifyRemote:Cs,...t.skipMinBytes===void 0?{}:{skipMinBytes:t.skipMinBytes},...t.saveInactivityWarningAfterMs===void 0?{}:{inactivityWarningAfterMs:t.saveInactivityWarningAfterMs},...t.saveSpinnerStream===void 0?{}:{spinnerStream:t.saveSpinnerStream}})).status==="fail")return $e;return Ut(o)}je();$u();ku();RO();Br();Lt();import{randomBytes as Lht}from"crypto";import{constants as XT,accessSync as Bht,chmodSync as Uht,chownSync as zht,closeSync as tP,copyFileSync as Vht,existsSync as n0e,fsyncSync as i0e,lstatSync as Ps,mkdirSync as Hht,mkdtempSync as Ght,openSync as rP,readSync as Wht,readdirSync as Kht,renameSync as Yht,rmSync as nP,rmdirSync as Jht,statSync as o0e,writeSync as Xht}from"fs";import{tmpdir as Qht}from"os";import{dirname as JD,join as xo}from"path";je();import{lstatSync as Tht,readdirSync as Pht,statSync as Hge}from"fs";import{open as Iht}from"fs/promises";import{join as Vge}from"path";_i();sn();$u();var jge="nemar-identifier-scan/1.0 (+https://docs.nemar.org/policies/takedown/)",oht="https://nemar-api-dev.sccn-org.workers.dev",sht="https://data.nemar.org",aht="https://nemar.s3.us-east-2.amazonaws.com",cht="https://api.github.com";function WD(e,t){if(!Number.isSafeInteger(t)||t<1)throw RangeError(`${e} must be a positive integer, got ${t}`)}async function VD(e,t,r){WD("pool size",t);let n=0,i=Array.from({length:Math.min(t,e.length)},async()=>{while(n<e.length){let a=e[n++];await r(a)}}),s=(await Promise.allSettled(i)).find((a)=>a.status==="rejected");if(s)throw s.reason}function lht(e){WD("limit",e);let t=0,r=[];return async(n)=>{if(t>=e)await new Promise((i)=>r.push(i));else t++;try{return await n()}finally{let i=r.shift();if(i)i();else t--}}}class yr 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 uht(e,t=Date.now()){let r=e?.trim();if(!r)return;if(/^\d+$/.test(r))return Number(r)*1000;let n=Date.parse(r);return Number.isNaN(n)?void 0:Math.max(0,n-t)}function dht(e,t){let r=e>=500||e===429;return new yr(`http-${e}`,{status:e,retryable:r,retryAfterMs:r?uht(t):void 0})}class GT extends Error{constructor(e){super(e);this.name="RunAborted"}}function fht(e){WD("abort streak",e.streak);let t=e.now??Date.now,r={tripped:null},n=(i)=>{let o=0,s=0,a=(c)=>{throw r.tripped=new GT(c),r.tripped};return{check(){if(r.tripped)throw r.tripped},ok(){o=0},pausedUntilMs(){return s},observe(c){if(r.tripped)throw r.tripped;if(c.retryAfterMs!==void 0&&c.retryAfterMs>e.retryAfterCapMs)a(`${i} 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)s=Math.max(s,t()+c.retryAfterMs);if(!c.retryable){o=0;return}if(o++,o>=e.streak)a(`${o} consecutive 429, 5xx, timeout or network failures from ${i} (last ${c.cls})`)}}};return{worker:n("the Worker"),direct:n("direct reads")}}function Pge(e){let t=e instanceof Error?e.name:"";return new yr(t==="TimeoutError"||t==="AbortError"?"timeout":"network",{retryable:!0})}function pht(e){if(e instanceof yr)return e.cls;return`error-${e instanceof Error?e.name:"unknown"}`}async function mht(e,t={}){let r=t.tries??3,n=t.baseMs??400,i=t.sleep??((o)=>new Promise((s)=>setTimeout(s,o)));WD("tries",r);for(let o=1;;o++)try{return await e()}catch(s){if(!(s instanceof yr&&s.retryable)||o>=r)throw s;let c=s.retryAfterMs??0;if(c>(t.retryAfterCapMs??30000))throw s;await i(Math.max(n*2**(o-1),c))}}async function hht(e){await e.body?.cancel().catch(()=>{return})}async function ght(e,t,r={}){let n;try{n=await fetch(e,{headers:{Range:`bytes=0-${t-1}`,"Accept-Encoding":"identity","User-Agent":r.userAgent??jge},signal:AbortSignal.timeout(r.timeoutMs??30000)})}catch(a){throw Pge(a)}if(n.status!==200&&n.status!==206)throw await hht(n),dht(n.status,n.headers.get("retry-after"));let i=n.body?.getReader();if(!i)throw new yr("no-body");let o=new Uint8Array(t),s=0;try{while(s<t){let{done:a,value:c}=await i.read();if(a||!c)break;let u=Math.min(c.length,t-s);o.set(c.subarray(0,u),s),s+=u}}catch(a){throw Pge(a)}finally{await i.cancel().catch(()=>{return})}if(s<(r.minBytes??0))throw new yr("short-body");return o.subarray(0,s)}var Mge={sideFileBytes:2097152,participantsBytes:16777216};function yht(e,t){let r=/An error occurred \(([A-Za-z0-9]{1,40})\)/.exec(e)?.[1];if(r)return/^\d+$/.test(r)?`aws/http-${r}`:`aws/error-${r}`;return`aws/exit-${t}`}async function bht(e,t,r={}){let n;try{let i=Bun.spawn(["aws","s3","cp",`s3://nemar/${e}/version/${t}.json`,"-"],{stdout:"pipe",stderr:"pipe",...r.env?{env:r.env}:{}}),o=!1;n=setTimeout(()=>{o=!0,i.kill("SIGKILL")},r.timeoutMs??600000);let[s,a,c]=await Promise.all([new Response(i.stdout).text(),new Response(i.stderr).text(),i.exited]);if(o)throw new yr("aws/timeout");if(c!==0)throw new yr(yht(a,c));return s}catch(i){if(i instanceof yr)throw i;throw new yr("aws/unavailable")}finally{clearTimeout(n)}}function wht(){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"}),r=(await new Response(t.stdout).text()).trim();e=r===""?null:r}catch{e=null}return e}}var HD=(e)=>e.replace(/\/+$/,"");function qge(e={}){let t=e.retryAfterCapMs??30000,r=e.awsTimeoutMs??600000;return{api:HD(e.api??process.env.NEMAR_API_BASE??oht),data:HD(e.data??process.env.NEMAR_DATA_BASE??sht),s3Base:HD(e.s3Base??aht),githubApi:HD(e.githubApi??cht),userAgent:e.userAgent??jge,fileConcurrency:e.fileConcurrency??24,workerLimit:lht(e.workerConcurrency??6),timeoutMs:e.timeoutMs??30000,manifestTimeoutMs:e.manifestTimeoutMs??120000,retryBaseMs:e.retryBaseMs??400,sleep:e.sleep??((n)=>new Promise((i)=>setTimeout(i,n))),now:e.now??Date.now,retryAfterCapMs:t,breakers:fht({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??((n,i)=>bht(n,i,{timeoutMs:r,env:e.awsEnv})),githubToken:e.githubToken??wht(),...e.readEntryHead?{readEntryHead:e.readEntryHead}:{}}}var Lge=(e,t)=>t.startsWith(`${e.data}/`),xht=(e,t)=>Lge(e,t)||t.startsWith(`${e.api}/`)?e.breakers.worker:e.breakers.direct;async function vht(e,t,r){let n=xht(e,t);n.check();let i=n.pausedUntilMs()-e.now();if(i>0)await e.sleep(i),n.check();try{let o=await r();return n.ok(),o}catch(o){if(o instanceof yr)n.observe(o);throw o}}var _ht=(e,t)=>({...t===void 0?{}:{tries:t},baseMs:e.retryBaseMs,sleep:e.sleep,retryAfterCapMs:e.retryAfterCapMs});var Ige=(e)=>/sub-([^/_]+)/.exec(e)?.[1]??"?";function Fge(e,t,r){if(t<1)return[];if(e.length<=t)return[...e];let n=new Map;for(let c of e){let u=r(c),d=n.get(u);if(d)d.push(c);else n.set(u,[c])}let i=[...n.entries()].sort(([c],[u])=>c<u?-1:c>u?1:0).map(([,c])=>c);if(i.length>t)return Array.from({length:t},(c,u)=>i[Math.floor((u+0.5)*i.length/t)][0]);let o=i.map((c,u)=>({list:c,index:u})).sort((c,u)=>c.list.length-u.list.length||c.index-u.index),s=t,a=[];return o.forEach(({list:c},u)=>{let d=Math.min(c.length,Math.ceil(s/(o.length-u)));for(let f=0;f<d;f++)a.push(c[Math.floor((f+0.5)*c.length/d)]);s-=d}),a}var Dht=(e)=>e.severity==="identifier"&&Hle.has(e.kind),Eht=(e)=>Su.has(e.kind);function Bge(e){return e.headerRead===e.edfCount&&e.incompleteReasons.length===0}function Sht(e){if(e.findings.some(Dht))return"direct-identifiers";if(e.findings.some((t)=>!Eht(t)))return"review";if(!Bge(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 $ht=/\.(edf|bdf)$/i,kht=(e)=>e.edf===!0||$ht.test(e.path);function Rht(e){return{edf:e.filter(kht),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/")||!Cht.test(t.path)).filter((t)=>!Aht.test(t.path)),text:e.filter((t)=>Oht.test(t.path)).filter((t)=>t.path.startsWith("sourcedata/")||t.path.startsWith("code/"))}}var Cht=/_(eeg|ieeg|meg|emg|nirs|beh|events|channels|electrodes|coordsystem|scans|physio|stim|photo|T1w|bold)\.(json|tsv)$/,Aht=/(^|\/)(dataset_description|participants|genetic_info)\.json$/,Oht=/\.(py|m|r|txt|md|ya?ml|xml|iml|cfg|ini)$/i;function Uge(e,t,r,n=0){let i=()=>vht(e,t.url,()=>{let o={minBytes:n,userAgent:e.userAgent,timeoutMs:e.timeoutMs};return e.readEntryHead?e.readEntryHead(t,r,o):ght(t.url,r,o)});return mht(()=>Lge(e,t.url)?e.workerLimit(i):i(),_ht(e))}async function GD(e,t,r){let n=await Uge(e,t,r),i=t.size===null?n.length>=r:t.size>r;return{text:new TextDecoder("utf-8",{fatal:!1}).decode(n),truncated:i}}function Lp(e,t){for(let r of t)e.push(r)}var Nge="edf/superseded-absent";async function zge(e,t,r,n,i,o={}){let s=n.map((Se)=>Se.path),a=i==="clone",c=(Se,nt,rn)=>a?[...Se]:Fge(Se,nt,rn),u=[...h_([...s,...o.extraPaths??[]])],d=rue(s),f=Object.values(d.unscreened).reduce((Se,nt)=>Se+nt,0),p={},m=(Se,nt)=>{if(nt instanceof GT)throw nt;let rn=`${Se}/${pht(nt)}`;p[rn]=(p[rn]??0)+1},g=(Se)=>Ige(Se.path),h=Rht(n),b=new Set(o.supersededEdf??[]),w=[...h.edf,...b],{participants:x,scans:v,json:R,text:E}=h,T=i==="git-tree"?Fge(w,e.limits.treeHeaderSample,g):[...w],A=0,L=0,P=0,j=0,W={},I=new Set,H=new Set,ne=new Set,G=new Set,U=new Set,Ae=new Set;await VD(T,e.fileConcurrency,async(Se)=>{try{let nt=await Uge(e,Se,Et,Et),rn=ha(nt),{patient:iE}=p_(nt);if(!rn.some((Wi)=>Wi.kind==="edf-unreadable")){I.add(iE);let Wi=iE.split(/\s+/);if(Wi.length>=4)ne.add(Wi[0]),U.add(Wi[2]),G.add(Wi[3])}if(Ae.add(Ige(Se.path)),rn.some((Wi)=>Wi.severity==="identifier"))j++,H.add(iE);Lp(u,rn);for(let Wi of new Set(rn.map((Tye)=>Tye.kind)))W[Wi]=(W[Wi]??0)+1;A++}catch(nt){if(b.has(Se)&&nt instanceof yr&&nt.status===404){P++,p[Nge]=(p[Nge]??0)+1;return}L++,m("edf",nt)}});let we=w.length-P,Cr=!1,vr=!1;if(x&&x.size!==0)try{let{text:Se,truncated:nt}=await GD(e,x,e.limits.participantsBytes),rn=Se.indexOf(`
|
|
1553
|
+
`;Sge(o,a)}console.log(l.dim(" Updated .bidsignore for NEMAR metadata"))}catch(n){console.log(l.yellow(` Warning: Could not update .bidsignore: ${M(n)}`)),console.log(l.dim(" Upload will continue without author enrichment."))}wa(r,"metadata_write"),zr(e,r)}else console.log(l.dim(" Metadata write already completed (skipping)"))}var kge=1073741824;function eht(e,t,r=kge){let n=[],i=0;for(let o of t){let s=e.files[o];if(!s||s.mtimeMs===void 0)continue;n.push({path:o,size:s.size,mtimeMs:s.mtimeMs}),i+=s.size}return i>=r?n:null}function tht(e,t){return t.filter((r)=>{try{return il(r.path,Qmt(Zmt(e,r.path)).size)}catch{return!0}})}function rht(e){let t=0;for(let r of Object.values(e.files))t+=r.size;return t}function nht(e){return["Warning: saving dataset changes has produced no stdout or stderr for",`${U_(e)}. git add -A is still running.`,"Wait, or interrupt and rerun the upload; the save step will run again."].join(" ")}async function Rge(e,t,r,n={}){if(!go(r,"dataset_save")){let i=S({text:"Saving dataset changes...",...n.spinnerStream?{stream:n.spinnerStream}:{}}).start(),o=n.skipMinBytes??kge,s=[];if(rht(r)>=o){let c=n.annexedPaths??null;if(c===null)try{c=await wl(e)}catch(u){console.log(l.dim(` Could not list annexed files (${M(u)}); staging will re-read them`))}if(c!==null)s=tht(e,eht(r,c,o)??[])}let a=await da(e,"Initial NEMAR dataset upload",t,{skipContentCheck:s,onInactivityWarning:(c)=>{i=qg(i,nht(c))},...n.inactivityWarningAfterMs===void 0?{}:{inactivityWarningAfterMs:n.inactivityWarningAfterMs}});if(!a.success)return zr(e,r),yn(i,"Failed to save dataset",a.error),console.log(),console.log(l.yellow("Re-run the same command to resume from this step.")),$e;if(n.verifyRemote){let c;try{c=await bO(e,n.verifyRemote)}catch(u){return zr(e,r),yn(i,"Could not confirm the saved files are at the S3 remote",u),console.log(),console.log(l.yellow("Re-run the same command to resume from this step.")),$e}if(c.length>0){xa(r,"s3_upload"),zr(e,r);let u=hv(c.slice(0,5)),d=c.length>5?` (and ${c.length-5} more)`:"";return yn(i,"Saved files are not at the S3 remote",`${c.length} annexed file(s) in the commit are not recorded at the remote: ${u}${d}. The save itself annexed them, after the upload step had run.`),console.log(),console.log(l.yellow("Re-run the same command: it uploads them and saves again.")),$e}}i.succeed("Dataset changes saved"),wa(r,"dataset_save"),zr(e,r)}else console.log(l.dim(" Dataset save already completed (skipping)"));return Ut()}async function Cge(e,t){if(!go(t,"github_push")){let r=S("Pushing metadata to GitHub...").start(),n=await $r(e);if(!n.success)return zr(e,t),yn(r,"Failed to push to GitHub",n.error),console.log(),console.log(l.yellow("Re-run the same command to resume from this step.")),$e;if(n.warning)r.warn("Metadata pushed to GitHub (with warning)"),console.log(l.yellow(` ${n.warning}`));else r.succeed("Metadata pushed to GitHub");wa(t,"github_push"),zr(e,t)}else console.log(l.dim(" GitHub push already completed (skipping)"));return Ut()}async function Age(e,t,r){if(!go(r,"ci_deploy")){let n=S("Setting up BIDS validation CI...").start(),i="configured";try{await ca(t),n.succeed("BIDS validation CI configured")}catch(o){if(i="not-configured",o instanceof q&&o.statusCode===403)n.info("CI workflow will be configured by an admin");else{let s=o instanceof Error?o.message:String(o);n.warn(`Could not configure CI: ${s}`),console.log(l.dim(` An admin can add it later with: nemar admin ci add ${t}`))}}return wa(r,"ci_deploy"),zr(e,r),i}return console.log(l.dim(" CI deploy already completed (skipping)")),"unknown"}function iht(e,t){let r=e.startsWith("xx");if(t==="not-configured"){if(r)return;console.log("BIDS validation is not set up yet."),console.log(` CI is set up when you request publication: ${l.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: ${l.cyan(`nemar dataset ci ${e}`)}`),!r)console.log(` Once it has passed, request publication: ${l.cyan(`nemar dataset publish request ${e}`)}`);console.log()}function Oge(e,t,r="unknown"){Mg(e),Ade(e),console.log(),console.log(l.green.bold("Upload complete!")),console.log(),console.log(` Dataset ID: ${l.cyan(t.dataset_id)}`),console.log(` GitHub: ${l.cyan(t.github_url)}`),console.log(),console.log(l.dim("To download this dataset:")),console.log(l.dim(` nemar dataset download ${t.dataset_id}`)),console.log(),iht(t.dataset_id,r),console.log(l.yellow("Note: This dataset is private. Only the owner and designated collaborators can")),console.log(l.yellow("download it, and only through the NEMAR CLI (not direct git-annex commands).")),console.log(l.yellow("After publishing, the data will be publicly available for everyone."))}xl();Cu();async function Tge(e,t={}){let r=await tae(e.absolutePath);if(!r.success)return console.log(l.red(r.error)),console.log(l.yellow("Re-run the same command to retry.")),$e;if(r.cleared>0)console.log(l.yellow(` Cleared ${r.cleared} assume-unchanged flag(s) an earlier, interrupted save left on annexed files`));let n=await Nde(e.absolutePath);if(n.status==="error")return console.log(l.red(n.error)),$e;if(n.status==="warning")console.log(l.yellow(` ${n.warning}`));if(n.status==="restored")console.log(l.yellow(" Put back git-annex's filter process, which an earlier, interrupted upload had left out of this repository's configuration"));let i=await hfe(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(i.status==="fail")return $e;let{progress:o,annexedPaths:s}=i.value;if($ge(e.absolutePath,e.coAuthorEnrichment,o),(await(t.saveStep??Rge)(e.absolutePath,e.author,o,{annexedPaths:s,verifyRemote:Cs,...t.skipMinBytes===void 0?{}:{skipMinBytes:t.skipMinBytes},...t.saveInactivityWarningAfterMs===void 0?{}:{inactivityWarningAfterMs:t.saveInactivityWarningAfterMs},...t.saveSpinnerStream===void 0?{}:{spinnerStream:t.saveSpinnerStream}})).status==="fail")return $e;return Ut(o)}je();$u();ku();RO();Br();Lt();import{randomBytes as Lht}from"crypto";import{constants as XT,accessSync as Bht,chmodSync as Uht,chownSync as zht,closeSync as tP,copyFileSync as Vht,existsSync as n0e,fsyncSync as i0e,lstatSync as Ps,mkdirSync as Hht,mkdtempSync as Ght,openSync as rP,readSync as Wht,readdirSync as Kht,renameSync as Yht,rmSync as nP,rmdirSync as Jht,statSync as o0e,writeSync as Xht}from"fs";import{tmpdir as Qht}from"os";import{dirname as JD,join as xo}from"path";je();import{lstatSync as Tht,readdirSync as Pht,statSync as Hge}from"fs";import{open as Iht}from"fs/promises";import{join as Vge}from"path";_i();sn();$u();var jge="nemar-identifier-scan/1.0 (+https://docs.nemar.org/policies/takedown/)",oht="https://api.nemar.org",sht="https://data.nemar.org",aht="https://nemar.s3.us-east-2.amazonaws.com",cht="https://api.github.com";function WD(e,t){if(!Number.isSafeInteger(t)||t<1)throw RangeError(`${e} must be a positive integer, got ${t}`)}async function VD(e,t,r){WD("pool size",t);let n=0,i=Array.from({length:Math.min(t,e.length)},async()=>{while(n<e.length){let a=e[n++];await r(a)}}),s=(await Promise.allSettled(i)).find((a)=>a.status==="rejected");if(s)throw s.reason}function lht(e){WD("limit",e);let t=0,r=[];return async(n)=>{if(t>=e)await new Promise((i)=>r.push(i));else t++;try{return await n()}finally{let i=r.shift();if(i)i();else t--}}}class yr 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 uht(e,t=Date.now()){let r=e?.trim();if(!r)return;if(/^\d+$/.test(r))return Number(r)*1000;let n=Date.parse(r);return Number.isNaN(n)?void 0:Math.max(0,n-t)}function dht(e,t){let r=e>=500||e===429;return new yr(`http-${e}`,{status:e,retryable:r,retryAfterMs:r?uht(t):void 0})}class GT extends Error{constructor(e){super(e);this.name="RunAborted"}}function fht(e){WD("abort streak",e.streak);let t=e.now??Date.now,r={tripped:null},n=(i)=>{let o=0,s=0,a=(c)=>{throw r.tripped=new GT(c),r.tripped};return{check(){if(r.tripped)throw r.tripped},ok(){o=0},pausedUntilMs(){return s},observe(c){if(r.tripped)throw r.tripped;if(c.retryAfterMs!==void 0&&c.retryAfterMs>e.retryAfterCapMs)a(`${i} 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)s=Math.max(s,t()+c.retryAfterMs);if(!c.retryable){o=0;return}if(o++,o>=e.streak)a(`${o} consecutive 429, 5xx, timeout or network failures from ${i} (last ${c.cls})`)}}};return{worker:n("the Worker"),direct:n("direct reads")}}function Pge(e){let t=e instanceof Error?e.name:"";return new yr(t==="TimeoutError"||t==="AbortError"?"timeout":"network",{retryable:!0})}function pht(e){if(e instanceof yr)return e.cls;return`error-${e instanceof Error?e.name:"unknown"}`}async function mht(e,t={}){let r=t.tries??3,n=t.baseMs??400,i=t.sleep??((o)=>new Promise((s)=>setTimeout(s,o)));WD("tries",r);for(let o=1;;o++)try{return await e()}catch(s){if(!(s instanceof yr&&s.retryable)||o>=r)throw s;let c=s.retryAfterMs??0;if(c>(t.retryAfterCapMs??30000))throw s;await i(Math.max(n*2**(o-1),c))}}async function hht(e){await e.body?.cancel().catch(()=>{return})}async function ght(e,t,r={}){let n;try{n=await fetch(e,{headers:{Range:`bytes=0-${t-1}`,"Accept-Encoding":"identity","User-Agent":r.userAgent??jge},signal:AbortSignal.timeout(r.timeoutMs??30000)})}catch(a){throw Pge(a)}if(n.status!==200&&n.status!==206)throw await hht(n),dht(n.status,n.headers.get("retry-after"));let i=n.body?.getReader();if(!i)throw new yr("no-body");let o=new Uint8Array(t),s=0;try{while(s<t){let{done:a,value:c}=await i.read();if(a||!c)break;let u=Math.min(c.length,t-s);o.set(c.subarray(0,u),s),s+=u}}catch(a){throw Pge(a)}finally{await i.cancel().catch(()=>{return})}if(s<(r.minBytes??0))throw new yr("short-body");return o.subarray(0,s)}var Mge={sideFileBytes:2097152,participantsBytes:16777216};function yht(e,t){let r=/An error occurred \(([A-Za-z0-9]{1,40})\)/.exec(e)?.[1];if(r)return/^\d+$/.test(r)?`aws/http-${r}`:`aws/error-${r}`;return`aws/exit-${t}`}async function bht(e,t,r={}){let n;try{let i=Bun.spawn(["aws","s3","cp",`s3://nemar/${e}/version/${t}.json`,"-"],{stdout:"pipe",stderr:"pipe",...r.env?{env:r.env}:{}}),o=!1;n=setTimeout(()=>{o=!0,i.kill("SIGKILL")},r.timeoutMs??600000);let[s,a,c]=await Promise.all([new Response(i.stdout).text(),new Response(i.stderr).text(),i.exited]);if(o)throw new yr("aws/timeout");if(c!==0)throw new yr(yht(a,c));return s}catch(i){if(i instanceof yr)throw i;throw new yr("aws/unavailable")}finally{clearTimeout(n)}}function wht(){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"}),r=(await new Response(t.stdout).text()).trim();e=r===""?null:r}catch{e=null}return e}}var HD=(e)=>e.replace(/\/+$/,"");function qge(e={}){let t=e.retryAfterCapMs??30000,r=e.awsTimeoutMs??600000;return{api:HD(e.api??process.env.NEMAR_API_BASE??oht),data:HD(e.data??process.env.NEMAR_DATA_BASE??sht),s3Base:HD(e.s3Base??aht),githubApi:HD(e.githubApi??cht),userAgent:e.userAgent??jge,fileConcurrency:e.fileConcurrency??24,workerLimit:lht(e.workerConcurrency??6),timeoutMs:e.timeoutMs??30000,manifestTimeoutMs:e.manifestTimeoutMs??120000,retryBaseMs:e.retryBaseMs??400,sleep:e.sleep??((n)=>new Promise((i)=>setTimeout(i,n))),now:e.now??Date.now,retryAfterCapMs:t,breakers:fht({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??((n,i)=>bht(n,i,{timeoutMs:r,env:e.awsEnv})),githubToken:e.githubToken??wht(),...e.readEntryHead?{readEntryHead:e.readEntryHead}:{}}}var Lge=(e,t)=>t.startsWith(`${e.data}/`),xht=(e,t)=>Lge(e,t)||t.startsWith(`${e.api}/`)?e.breakers.worker:e.breakers.direct;async function vht(e,t,r){let n=xht(e,t);n.check();let i=n.pausedUntilMs()-e.now();if(i>0)await e.sleep(i),n.check();try{let o=await r();return n.ok(),o}catch(o){if(o instanceof yr)n.observe(o);throw o}}var _ht=(e,t)=>({...t===void 0?{}:{tries:t},baseMs:e.retryBaseMs,sleep:e.sleep,retryAfterCapMs:e.retryAfterCapMs});var Ige=(e)=>/sub-([^/_]+)/.exec(e)?.[1]??"?";function Fge(e,t,r){if(t<1)return[];if(e.length<=t)return[...e];let n=new Map;for(let c of e){let u=r(c),d=n.get(u);if(d)d.push(c);else n.set(u,[c])}let i=[...n.entries()].sort(([c],[u])=>c<u?-1:c>u?1:0).map(([,c])=>c);if(i.length>t)return Array.from({length:t},(c,u)=>i[Math.floor((u+0.5)*i.length/t)][0]);let o=i.map((c,u)=>({list:c,index:u})).sort((c,u)=>c.list.length-u.list.length||c.index-u.index),s=t,a=[];return o.forEach(({list:c},u)=>{let d=Math.min(c.length,Math.ceil(s/(o.length-u)));for(let f=0;f<d;f++)a.push(c[Math.floor((f+0.5)*c.length/d)]);s-=d}),a}var Dht=(e)=>e.severity==="identifier"&&Hle.has(e.kind),Eht=(e)=>Su.has(e.kind);function Bge(e){return e.headerRead===e.edfCount&&e.incompleteReasons.length===0}function Sht(e){if(e.findings.some(Dht))return"direct-identifiers";if(e.findings.some((t)=>!Eht(t)))return"review";if(!Bge(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 $ht=/\.(edf|bdf)$/i,kht=(e)=>e.edf===!0||$ht.test(e.path);function Rht(e){return{edf:e.filter(kht),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/")||!Cht.test(t.path)).filter((t)=>!Aht.test(t.path)),text:e.filter((t)=>Oht.test(t.path)).filter((t)=>t.path.startsWith("sourcedata/")||t.path.startsWith("code/"))}}var Cht=/_(eeg|ieeg|meg|emg|nirs|beh|events|channels|electrodes|coordsystem|scans|physio|stim|photo|T1w|bold)\.(json|tsv)$/,Aht=/(^|\/)(dataset_description|participants|genetic_info)\.json$/,Oht=/\.(py|m|r|txt|md|ya?ml|xml|iml|cfg|ini)$/i;function Uge(e,t,r,n=0){let i=()=>vht(e,t.url,()=>{let o={minBytes:n,userAgent:e.userAgent,timeoutMs:e.timeoutMs};return e.readEntryHead?e.readEntryHead(t,r,o):ght(t.url,r,o)});return mht(()=>Lge(e,t.url)?e.workerLimit(i):i(),_ht(e))}async function GD(e,t,r){let n=await Uge(e,t,r),i=t.size===null?n.length>=r:t.size>r;return{text:new TextDecoder("utf-8",{fatal:!1}).decode(n),truncated:i}}function Lp(e,t){for(let r of t)e.push(r)}var Nge="edf/superseded-absent";async function zge(e,t,r,n,i,o={}){let s=n.map((Se)=>Se.path),a=i==="clone",c=(Se,nt,rn)=>a?[...Se]:Fge(Se,nt,rn),u=[...h_([...s,...o.extraPaths??[]])],d=rue(s),f=Object.values(d.unscreened).reduce((Se,nt)=>Se+nt,0),p={},m=(Se,nt)=>{if(nt instanceof GT)throw nt;let rn=`${Se}/${pht(nt)}`;p[rn]=(p[rn]??0)+1},g=(Se)=>Ige(Se.path),h=Rht(n),b=new Set(o.supersededEdf??[]),w=[...h.edf,...b],{participants:x,scans:v,json:R,text:E}=h,T=i==="git-tree"?Fge(w,e.limits.treeHeaderSample,g):[...w],A=0,L=0,P=0,j=0,W={},I=new Set,H=new Set,ne=new Set,G=new Set,U=new Set,Ae=new Set;await VD(T,e.fileConcurrency,async(Se)=>{try{let nt=await Uge(e,Se,Et,Et),rn=ha(nt),{patient:iE}=p_(nt);if(!rn.some((Wi)=>Wi.kind==="edf-unreadable")){I.add(iE);let Wi=iE.split(/\s+/);if(Wi.length>=4)ne.add(Wi[0]),U.add(Wi[2]),G.add(Wi[3])}if(Ae.add(Ige(Se.path)),rn.some((Wi)=>Wi.severity==="identifier"))j++,H.add(iE);Lp(u,rn);for(let Wi of new Set(rn.map((Tye)=>Tye.kind)))W[Wi]=(W[Wi]??0)+1;A++}catch(nt){if(b.has(Se)&&nt instanceof yr&&nt.status===404){P++,p[Nge]=(p[Nge]??0)+1;return}L++,m("edf",nt)}});let we=w.length-P,Cr=!1,vr=!1;if(x&&x.size!==0)try{let{text:Se,truncated:nt}=await GD(e,x,e.limits.participantsBytes),rn=Se.indexOf(`
|
|
1554
1554
|
`);if(rn<0&&nt)throw new yr("header-truncated");Lp(u,Qle(rn<0?Se:Se.slice(0,rn))),Lp(u,eue(Se)),vr=nt}catch(Se){Cr=!0,m("participants",Se)}let wr=c(v,e.limits.scansTables,g),ge=0;await VD(wr,e.fileConcurrency,async(Se)=>{if(Se.size===0){ge++;return}try{let{text:nt}=await GD(e,Se,e.limits.sideFileBytes);Lp(u,m_(nt)),ge++}catch(nt){m("scans",nt)}});let ut=e.limits.sideFileBytes,ht=(Se)=>Se.size!==null&&Se.size>ut,X=c(R.filter((Se)=>!ht(Se)),e.limits.jsonFiles,g),B=c(E.filter((Se)=>!ht(Se)),e.limits.textFiles,g),ee=0,te=0;await VD(X,e.fileConcurrency,async(Se)=>{if(Se.size===0){ee++;return}try{let{text:nt}=await GD(e,Se,ut),rn;try{rn=JSON.parse(nt)}catch{throw new yr("json-parse")}Lp(u,Eu(rn)),ee++}catch(nt){m("json",nt)}}),await VD(B,e.fileConcurrency,async(Se)=>{if(Se.size===0){te++;return}try{let{text:nt}=await GD(e,Se,ut);Lp(u,tue(nt)),te++}catch(nt){m("text",nt)}});let J={edf_headers:{candidates:we,oversize:0,selected:T.length-P,scanned:A},scans_tables:{candidates:v.length,oversize:0,selected:wr.length,scanned:ge},json_files:{candidates:R.length,oversize:R.filter(ht).length,selected:X.length,scanned:ee},text_files:{candidates:E.length,oversize:E.filter(ht).length,selected:B.length,scanned:te}},st=new Set,di=(Se,nt)=>{if(nt.oversize>0)st.add(`${Se}-oversize`);if(nt.candidates-nt.oversize>nt.selected)st.add(`${Se}-sampled`);if(nt.scanned<nt.selected)st.add(`${Se}-unread`)};if(di("edf-headers",J.edf_headers),di("json",J.json_files),di("text",J.text_files),J.scans_tables.scanned<J.scans_tables.selected)st.add("scans-unread");if(Cr)st.add("participants-unread");if(vr)st.add("participants-truncated");for(let Se of o.extraIncompleteReasons??[])st.add(Se);let Is=[...st].sort(),bP={findings:u,edfCount:we,headerRead:A,unscreenedCount:f,incompleteReasons:Is},Aye=u.filter((Se)=>Se.severity==="identifier"),Oye=Object.entries(p).filter(([Se])=>!Se.startsWith("edf/")).reduce((Se,[,nt])=>Se+nt,0);return{id:t,version:r,scanned_at:new Date().toISOString(),manifest_source:i,status:Sht(bP),incomplete:!Bge(bP),incomplete_reasons:Is,files:{total:n.length,edf_bdf:we,header_read:A,header_read_failed:L},sampling:J,read_failures:p,edf_bdf_files_flagged:j,distinct_patient_field_values:I.size,distinct_subjects_with_edf_bdf:Ae.size,distinct_patient_code_subfield:ne.size,distinct_patient_name_subfield:G.size,distinct_patient_birth_subfield:U.size,distinct_patient_field_values_in_flagged_files:H.size,findings_by_kind:nue(u),edf_bdf_files_by_kind:W,unscreened_formats:d.unscreened,side_reads_failed:Oye,finding_fields:[...new Set(Aye.map((Se)=>`${Se.kind}:${Se.field}`))].sort()}}ku();Br();Zf();Cu();var qu="--acknowledge-identifier-preflight",Fht=16,Nht="local:";function YT(e){let t=[],r=new Map,n=0,i=[""];while(i.length>0){let o=i.pop(),s;try{s=Pht(o===""?e:Vge(e,o),{withFileTypes:!0})}catch{n++;continue}s.sort((c,u)=>c.name<u.name?-1:c.name>u.name?1:0);let a=[];for(let c of s){let u=c.name;if(o===""&&(u===".git"||u===".nemar"))continue;let d=o===""?u:`${o}/${u}`;if(c.isDirectory()){a.push(d);continue}if(u===".gitattributes")continue;let f=`${Nht}${t.length}`,p=Vge(e,d),m=null;try{let g=Hge(p);if(g.isFile())m=g.size,r.set(f,p);else if(g.isDirectory()&&!Tht(p).isSymbolicLink()){a.push(d);continue}}catch{}t.push({path:d,size:m,url:f})}for(let c=a.length-1;c>=0;c--)i.push(a[c])}return{entries:t,readable:r,unlisted:n}}function jht(e,t=new Map){return async(r,n,i)=>{let o=e.get(r.url);if(o===void 0)throw new yr("unreadable-entry");let s=t.get(o),a;try{a=await Iht(o,"r")}catch{throw new yr("unreadable-entry")}try{let c=r.size===null?n:Math.min(n,r.size),u=new Uint8Array(c),d=0;while(d<c){let{bytesRead:f}=await a.read(u,d,c-d,d);if(f===0)break;d+=f}if(d<i.minBytes)throw new yr("short-body");if(s)u.set(s.subarray(0,Math.min(d,s.length)),0);return u.subarray(0,d)}catch(c){if(c instanceof yr)throw c;throw new yr("unreadable-entry")}finally{await a.close().catch(()=>{return})}}}async function Gge(e,t){let r=YT(e),n=qge({fileConcurrency:Fht,workerConcurrency:1,limits:{...Mge},readEntryHead:jht(r.readable,t),githubToken:async()=>null,readVersionManifest:async()=>{throw new yr("unreadable-entry")},sleep:async()=>{return}}),i=await zge(n,"local",null,r.entries,"clone",{extraIncompleteReasons:r.unlisted>0?["tree-truncated"]:[]}),o={scanned_at:i.scanned_at,status:i.status,incomplete:i.incomplete,incomplete_reasons:i.incomplete_reasons,files:i.files,findings_by_kind:i.findings_by_kind,edf_bdf_files_flagged:i.edf_bdf_files_flagged,unscreened_formats:i.unscreened_formats,read_failures:i.read_failures};return DA(fue(pue(o)))}function YD(e){if(dl(e.status)!=="acknowledge")return[];let t=new Set([e.status]);if(e.incomplete&&e.status!=="unchecked")t.add("unchecked");let r=Object.values(e.unscreened_formats).reduce((i,o)=>i+o,0),n=e.status==="not-screened"||e.status==="clean-edf-only-others-unscreened";if(r>0&&!n)t.add("not-screened");return[...t].sort()}var Wge=(e,t)=>e.length===t.length&&e.every((r,n)=>r===t[n]);function Kge(e,t){let r=e.split(",").map((i)=>i.trim()).filter((i)=>i!==""),n=x_;if(r.length===0||!r.every((i)=>n.includes(i)))throw new Hp(`Allowed verdicts are ${n.join(", ")}. Direct identifiers cannot be acknowledged.`);return[...t??[],...r]}function Mht(e,t){let r=dl(e.status);if(r==="clear")return{action:"proceed",acknowledgedVia:null};if(r!=="acknowledge")return{action:"refuse"};if(t.acknowledge!==void 0){let n=[...new Set(t.acknowledge)].sort();return Wge(n,YD(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 qht={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"},WT=(e)=>`${qu} ${e.join(",")}`;function KT(e){console.log(l.yellow(" This does not stop an upload, but it needs your explicit acknowledgment of:"));for(let t of e)console.log(l.yellow(` ${t}: ${qht[t]??"not clean"}.`));console.log(l.dim(" Your acknowledgment is recorded with your deposit attestation. NEMAR screens the dataset again when you request publication, and an administrator decides then."))}function Yge(){console.log(),console.log(l.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(l.red(" Remove them from the files (for EDF/BDF, the patient and recording fields of the header) and run the upload again.")),console.log(l.dim(` There is no override, and ${qu} does not apply. If this is a false positive, please report it, so the scanner is fixed for every dataset. Terms: ${TD}`))}function Jge(e){if(e instanceof y_)return`report-${e.message}`;let t=e instanceof Error&&/^[A-Za-z]{1,40}$/.test(e.name)?e.name:"unknown",r=e?.code;return typeof r==="string"&&/^E[A-Z0-9]{1,20}$/.test(r)?`${t} ${r}`:t}function Xge(e,t){e.fail("Identifier preflight: DID NOT FINISH"),console.log(l.red(` The preflight could not produce a verdict, so nothing was uploaded (${Jge(t)}).`)),console.log(l.dim(" Please report this: https://github.com/nemarOrg/nemar-cli/issues"))}function KD(e,t,r=""){let n=EA(t,null),i=`${n.headline}${r}`;if(n.tone==="ok")e.succeed(i);else if(n.tone==="stop")e.fail(i);else e.warn(i);for(let o of Rs({state:t.status,...n},2).slice(1))console.log(o)}function Qge(e,t){try{return Ut(mue({version:g_,scanner:`nemar-cli@${ao}`,scan:e,acknowledged_via:t}))}catch(r){return console.log(l.red(` The preflight's record did not fit the report contract (${Jge(r)}), so nothing was uploaded.`)),$e}}async function Zge(e,t,r=process.stdin.isTTY===!0,n){let i=S("Screening for identifiers on this machine (nothing is sent)...").start(),o=!1;try{o=Hge(e).isDirectory()}catch{o=!1}if(!o)return i.fail("Identifier preflight: the dataset path is not a directory"),$e;let s=new Map((n?.items??[]).map((p)=>[p.path,p.after])),a;try{a=await Gge(e,s)}catch(p){return Xge(i,p),$e}KD(i,a);let c=YD(a),u=Mht(a,{acknowledge:t.acknowledgeIdentifierPreflight,dryRun:t.dryRun,no:t.no,isTty:r}),d;switch(u.action){case"proceed":if(u.acknowledgedVia==="flag")console.log(l.dim(` Acknowledged with ${WT(c)}.`));else if(t.acknowledgeIdentifierPreflight!==void 0)console.log(l.dim(` Nothing to acknowledge; ${qu} was not needed.`));d=u.acknowledgedVia;break;case"preview":return KT(c),console.log(l.yellow(` A real upload stops here until you acknowledge it: answer the prompt, or pass ${WT(c)}.`)),console.log(),Ut(null);case"prompt":{KT(c);let p=!1,m=()=>{console.log(l.red(`
|
|
1555
1555
|
Upload cancelled. Nothing was sent.`)),ke(),process.exit(130)};process.once("SIGINT",m);let g=setInterval(()=>{return},1000);try{({acknowledged:p}=await ve.prompt([{type:"confirm",name:"acknowledged",message:"Upload anyway?",default:!1}]))}catch{p=!1}finally{clearInterval(g),process.off("SIGINT",m)}if(p!==!0)return console.log(l.red(" Upload cancelled. Nothing was sent.")),ke(),$e;console.log(l.dim(" Acknowledged at the prompt.")),d="prompt";break}case"refuse":return Yge(),ke(),$e;case"stop":if(u.why==="acknowledgment-mismatch")console.log(l.red(` ${qu} must name exactly what was found, which is: ${c.join(",")}. It does not acknowledge this scan. Nothing was sent.`));else KT(c),console.log(l.red(u.why==="declined"?" Declined (--no). Nothing was sent.":` No terminal to ask at: run interactively, or pass ${WT(c)}. --yes does not acknowledge a finding. Nothing was sent.`));return ke(),$e}let f=Qge(a,d);if(f.status==="ok")console.log();return f}async function e0e(e,t){let r=S("Screening again, right before anything is sent...").start(),n;try{n=await Gge(e)}catch(a){return Xge(r,a),$e}let i=dl(n.status);if(i!=="clear"&&i!=="acknowledge")return KD(r,n),Yge(),ke(),$e;let o=YD(t.scan),s=YD(n);if(!Wge(o,s))return KD(r,n),console.log(l.red(` The files changed since the preflight, and so did what it found (acknowledged: ${o.join(",")||"nothing"}; now: ${s.join(",")}). Nothing was sent. Run the upload again.`)),ke(),$e;if(b_(n.findings_by_kind)!==b_(t.scan.findings_by_kind))KD(r,n," (screened again)");else r.succeed(`${EA(n,null).headline} (screened again)`);return Qge(n,t.acknowledged_via)}var Zht=/\.(edf|bdf)$/i,s0e=xo(".nemar","date-normalization"),egt=()=>({tracked:0,"nested-repository":0,ignored:0,"tracking-unknown":0,link:0,"not-writable":0,"other-filesystem":0,unverified:0});function tgt(){return{items:[],left:egt()}}function rgt(e){if(process.env.GIT_DIR||process.env.GIT_WORK_TREE)return!0;for(let t=e;;t=JD(t)){if(n0e(xo(t,".git")))return!0;if(JD(t)===t)return!1}}var QT=(e)=>e.normalize("NFC").toLowerCase();async function JT(e,t,r){try{let n=await k(e,{cwd:t,...r===void 0?{}:{stdin:r}});if(!(n.exitCode===0||e.includes("check-ignore")&&n.exitCode===1))return null;return new Set(n.stdout.split("\x00").filter(Boolean).map(QT))}catch{return null}}async function ngt(e,t){let r=`${t.join("\x00")}\x00`;if(rgt(e)){let i=await JT(["git","ls-files","-z"],e),o=await JT(["git","check-ignore","-z","--stdin"],e,r);return i&&o?{tracked:i,ignored:o}:null}let n=null;try{if(n=Ght(xo(Qht(),"nemar-ignore-")),(await k(["git","init","-q","--bare",n],{cwd:e})).exitCode!==0)return null;let o=await JT(["git",`--git-dir=${n}`,`--work-tree=${e}`,"check-ignore","--no-index","-z","--stdin"],e,r);return o?{tracked:new Set,ignored:o}:null}catch{return null}finally{if(n!==null)try{nP(n,{recursive:!0,force:!0})}catch{}}}function ZT(e){let t;try{t=rP(e,"r")}catch{return null}try{let r=new Uint8Array(Et),n=0;while(n<Et){let i=Wht(t,r,n,Et-n,n);if(i===0)break;n+=i}return n===Et?r:null}catch{return null}finally{try{tP(t)}catch{}}}var t0e=(e,t)=>e!==null&&e.length===t.length&&e.every((r,n)=>r===t[n]);function r0e(e){try{return Bht(e,XT.W_OK),!0}catch{return!1}}function igt(e,t,r){let n=t.split("/").slice(0,-1);for(let i=1;i<=n.length;i++){let o=n.slice(0,i).join("/"),s=r.get(o);if(s===void 0){s=n0e(xo(e,o,".git"));try{s||=Ps(xo(e,o,".git")).isSymbolicLink()}catch{}r.set(o,s)}if(s)return!0}return!1}async function a0e(e){let t=tgt();try{await ogt(e,t)}catch(r){rr(`date normalization: planning stopped (${r instanceof Error?r.name:"unknown"})`)}return t}async function ogt(e,t){let r=o0e(e).dev,n=YT(e),i=[];for(let c of n.entries){if(!Zht.test(c.path))continue;let u=n.readable.get(c.url);if(u===void 0)continue;let d=ZT(u);if(d===null)continue;try{let f=rD(d);if(f.changed)i.push({path:u,rel:c.path,before:d,after:f.header})}catch(f){if(f instanceof va)continue;t.left.unverified++,rr(`date normalization: a header was not planned (${f instanceof Error?f.name:"unknown"})`)}}if(i.length===0)return;let o=await ngt(e,i.map((c)=>c.rel)),s=new Map,a=typeof process.getuid==="function"?process.getuid():null;for(let c of i){if(o===null){t.left["tracking-unknown"]++;continue}if(o.tracked.has(QT(c.rel))){t.left.tracked++;continue}if(igt(e,c.rel,s)){t.left["nested-repository"]++;continue}if(o.ignored.has(QT(c.rel))){t.left.ignored++;continue}let u;try{u=Ps(c.path)}catch{continue}if(u.isSymbolicLink()){t.left.link++;continue}if(!u.isFile())continue;if(u.dev!==r){t.left["other-filesystem"]++;continue}if(a!==null&&u.uid!==a||(u.mode&128)===0||!r0e(c.path)||!r0e(JD(c.path))){t.left["not-writable"]++;continue}t.items.push({path:c.path,rel:c.rel,dev:u.dev,ino:u.ino,size:u.size,mtimeMs:u.mtimeMs,mode:u.mode,gid:u.gid,before:c.before,after:c.after})}}var sgt=/^\d+-[0-9a-f]{16}$/;function agt(e){try{let t=xo(e,s0e);for(let r of[xo(e,".nemar"),t])if(!Ps(r).isDirectory())return;for(let r of Kht(t))if(sgt.test(r))nP(xo(t,r),{force:!0})}catch{}}function eP(e){for(let t of e)try{Jht(t)}catch{}}function cgt(e,t){let r=[],n=xo(e,s0e);try{for(let i of[xo(e,".nemar"),n]){let o;try{o=Ps(i)}catch{Hht(i),r.push(i),o=Ps(i)}if(!o.isDirectory()||o.dev!==t)return eP([...r].reverse()),null}return{dir:n,made:r}}catch{return eP([...r].reverse()),null}}function lgt(e){try{let t=rP(e,"r");try{i0e(t)}finally{tP(t)}}catch{}}function ugt(e,t){let r=null;try{let n=(o)=>o.isFile()&&o.dev===e.dev&&o.ino===e.ino&&o.size===e.size&&o.mtimeMs===e.mtimeMs;if(!n(Ps(e.path))||!t0e(ZT(e.path),e.before))return null;if(r=xo(t,`${process.pid}-${Lht(8).toString("hex")}`),Vht(e.path,r,XT.COPYFILE_EXCL|XT.COPYFILE_FICLONE),Ps(r).gid!==e.gid)zht(r,-1,e.gid);Uht(r,e.mode&4095);let i=rP(r,"r+");try{if(Xht(i,e.after,0,Et,0)!==Et)return null;i0e(i)}finally{tP(i)}if(Ps(r).size!==e.size||!t0e(ZT(r),e.after))return null;if(!n(Ps(e.path)))return null;return Yht(r,e.path),r=null,lgt(JD(e.path)),Ps(e.path).mtimeMs}catch(n){return rr(`date normalization: a header was not set (${n instanceof Error?n.name:"unknown"})`),null}finally{if(r!==null)try{nP(r,{force:!0})}catch{}}}function c0e(e,t){let r={set:0,left:0,mtimes:new Map};if(agt(e),t.items.length===0)return r;let n=null;try{n=cgt(e,o0e(e).dev)}catch{}if(n===null)return r.left=t.items.length,rr("date normalization: no work directory, nothing set"),r;try{for(let i of t.items){let o=ugt(i,n.dir);if(o===null){r.left++;continue}r.set++,r.mtimes.set(i.rel,o)}}finally{eP([n.dir,...[...n.made].reverse().filter((i)=>i!==n.dir)])}if(r.set>0)console.log(l.dim(` ${lue(r.set)}`));return r}je();_i();sn();import{existsSync as y0,mkdirSync as Cgt,readFileSync as b0,writeFileSync as k0e}from"fs";import{basename as Agt,resolve as Lu}from"path";nl();Tt();ai();_i();import{existsSync as XD,readFileSync as iP,writeFileSync as u0e}from"fs";import{resolve as QD}from"path";var oP=[{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}],l0e=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 d0e(e){let t=QD(e,"dataset_description.json");if(XD(t))try{let n=JSON.parse(iP(t,"utf-8"));if(typeof n.License==="string"&&n.License.trim())return{spdxId:n.License.trim(),source:"dataset_description"}}catch(n){if(n instanceof SyntaxError)console.warn(` Warning: dataset_description.json has invalid JSON: ${n.message}`);else console.warn(` Warning: Could not read dataset_description.json: ${n instanceof Error?n.message:String(n)}`)}let r=["LICENSE","LICENSE.txt","LICENSE.md","LICENCE","LICENCE.txt"];for(let n of r){let i=QD(e,n);if(XD(i)){try{let o=iP(i,"utf-8").toLowerCase();if(o.includes("cc0")||o.includes("public domain dedication"))return{spdxId:"CC0-1.0",source:"license_file"};if(o.includes("attribution-noncommercial-sharealike"))return{spdxId:"CC-BY-NC-SA-4.0",source:"license_file"};if(o.includes("attribution-noncommercial"))return{spdxId:"CC-BY-NC-4.0",source:"license_file"};if(o.includes("attribution-sharealike"))return{spdxId:"CC-BY-SA-4.0",source:"license_file"};if(o.includes("creativecommons")&&o.includes("attribution"))return{spdxId:"CC-BY-4.0",source:"license_file"};if(o.includes("open database license")||o.includes("odbl"))return{spdxId:"ODbL-1.0",source:"license_file"};if(o.includes("open data commons")&&o.includes("attribution"))return{spdxId:"ODC-By-1.0",source:"license_file"};if(o.includes("public domain dedication and license")||o.includes("pddl"))return{spdxId:"PDDL-1.0",source:"license_file"};if(o.includes("permission is hereby granted, free of charge")||o.includes("mit license"))return{spdxId:"MIT",source:"license_file"}}catch(o){console.warn(` Warning: Could not read ${n}: ${o instanceof Error?o.message:String(o)}`)}return{spdxId:void 0,source:"license_file"}}}return{spdxId:void 0,source:"none"}}async function sP(e){let t=oP.map((i)=>({name:`${i.spdxId.padEnd(22)} ${i.description}`,value:i.spdxId,short:i.spdxId}));t.push({name:"Other (enter SPDX ID manually)",value:"__custom__",short:"Custom"});let r=e?oP.find((i)=>i.spdxId===e)?.spdxId:void 0,{selected:n}=await ve.prompt([{type:"list",name:"selected",message:"Select a license for this dataset:",choices:t,default:r,pageSize:t.length}]);if(n==="__custom__"){let{customId:i}=await ve.prompt([{type:"input",name:"customId",message:"Enter SPDX license ID (e.g., MIT, Apache-2.0):",validate:(o)=>{if(!o.trim())return"License ID is required";return!0}}]);return i.trim()}return n}function f0e(e){let t=e.toUpperCase().replace(/\s+/g,"-");if(l0e.has(e))return!0;for(let r of l0e)if(r.toUpperCase()===t)return!0;return!1}function dgt(e){let t=oP.find((r)=>r.spdxId===e);if(t)return`${t.name}
|
|
1556
1556
|
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "nemar-cli",
|
|
3
3
|
"packageManager": "bun@1.4.3",
|
|
4
|
-
"version": "0.10.20
|
|
4
|
+
"version": "0.10.20",
|
|
5
5
|
"description": "CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"main": "dist/index.js",
|