nemar-cli 0.10.38-PR2280.9090eea → 0.10.38-dev.4682

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.
@@ -23,18 +23,18 @@ ${t}`,zM,GM,KM=(e,t,r)=>{let n=r===""?"":`with ${r.trim()}() `,s=VM.bind(null,n,
23
23
  `)}var Fl=!1;var{spawn:WF}=globalThis.Bun;function Vl(e,t=[]){let r=e.replace(YF,'("$1","<redacted>")');for(let n of t)if(n.length>=XF)r=r.split(n).join("<redacted>");return r}function QF(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 s of t){let o=n[s];if(typeof o==="string"&&o.length>0)r.add(o)}return[...r]}async function hb(e,t){let r=e.getReader(),n=new TextDecoder,s="";while(!0){let{done:o,value:i}=await r.read();if(o)break;if(i.byteLength===0)continue;t(),s+=n.decode(i,{stream:!0})}return s+n.decode()}async function mb(e,t={}){let r={...process.env,GIT_TERMINAL_PROMPT:"0",...t.env};for(let y of t.unsetEnv??[])delete r[y];let n=WF({cmd:e,cwd:t.cwd,...t.stdin===void 0?{}:{stdin:new TextEncoder().encode(t.stdin)},stdout:"pipe",stderr:"pipe",env:r}),s=!1,o,i,a=performance.now(),c=()=>{if(i!==void 0)clearTimeout(i),i=void 0},u=()=>{if(!t.onInactivityWarning)return;c(),i=setTimeout(()=>{i=void 0;try{t.onInactivityWarning?.(performance.now()-a)}catch{console.error("Could not display subprocess inactivity warning; the child result is unaffected.")}},t.inactivityWarningAfterMs??JF)};if(u(),t.timeout)o=setTimeout(()=>{s=!0,c(),n.kill()},t.timeout);let d=ic()?[...QF(r),...t.redact??[]]:[];if(ic()){let y=t.cwd?` (cwd=${t.cwd})`:"";qs(Nt.dim(Vl(`$ ${e.join(" ")}${y}`,d)))}let l=()=>{a=performance.now(),u()},p,f,h,m=n.exited.then((y)=>(c(),y));try{[p,f,h]=await Promise.all([hb(n.stdout,l),hb(n.stderr,l),m])}finally{if(c(),o)clearTimeout(o)}if(ic()){if(t.sensitiveOutput)qs(Nt.dim("[sensitive subprocess output suppressed]"));else{if(p.trim())qs(Nt.dim(Vl(p.trimEnd(),d)));if(f.trim())qs(Nt.yellow(Vl(f.trimEnd(),d)))}qs(Nt.dim(`(exit ${h})`))}if(s)return{stdout:p,stderr:f||`Command timed out after ${Math.round(t.timeout/1000)}s`,exitCode:h??1,timedOut:!0};return{stdout:p,stderr:f,exitCode:h,timedOut:!1}}var YF,XF=8,JF=120000;var gb=F(()=>{Ul();YF=/\(\s*"((?:x-amz-)[^"]*|authorization|proxy-authorization)"\s*,\s*"[^"]*"\s*\)/gi});function eV(){if(process.platform==="darwin")return"macos";if(process.platform==="win32")return"windows";return"linux"}function _b(e,t=eV()){return e.installInstructions[t]}function tV(e){let t=e.match(/(\d+\.\d+(?:\.\d+)?)/);return t?t[1]:void 0}function nV(){let e=Number(process.env.TEST_PROBE_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:rV}async function vb(e){try{let{exitCode:t,stdout:r,timedOut:n}=await mb(e.cmd,{timeout:nV()});if(n)return{available:!1,timedOut:!0};if(t!==0)return{available:!1};return{available:!0,version:tV(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 zl(){let e=Object.entries(yb);return Promise.all(e.map(async([t,r])=>{let{available:n,version:s,timedOut:o}=await vb(r);return{key:t,name:r.name,purpose:r.purpose,required:r.required,available:n,version:s,timedOut:o,installInstruction:_b(r)}}))}async function Z3(){let t=(await zl()).filter((r)=>r.required&&!r.available);if(t.length===0)return[];console.warn(`
24
24
  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 eB(e){let r=ZF[e].map((i)=>yb[i]).filter(Boolean),n=await Promise.all(r.map(async(i)=>{let a=await vb(i);return{check:i,available:a.available,timedOut:a.timedOut}}));for(let i of n)if(i.timedOut&&i.check.required)console.warn(`Warning: ${i.check.name} did not respond to a version check in time; continuing anyway.`);let s=n.filter((i)=>!i.available&&!i.timedOut&&i.check.required).map((i)=>({tool:i.check.name,installInstruction:_b(i.check)}));if(s.length===0)return;let o=[`
25
25
  Missing required tools:`];for(let i of s)o.push(` ${i.tool} not installed`),o.push(` Install: ${i.installInstruction}`);throw Error(o.join(`
26
- `))}var yb,ZF,rV=4000;var $b=F(()=>{gb();yb={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)"}}},ZF={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 wb;var Eb=F(()=>{wb={name:"nemar-cli",packageManager:"bun@1.4.3",version:"0.10.38-PR2280.9090eea",description:"CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",type:"module",main:"dist/index.js",bin:{nemar:"dist/index.js","git-annex-remote-nemar":"dist/git-annex-remote-nemar.js"},scripts:{dev:"bun run src/index.ts",build:"bun build src/index.ts src/git-annex-remote-nemar.ts --outdir dist --target bun --minify && sed '1s|#!/usr/bin/env node|#!/usr/bin/env bun|' dist/index.js > dist/index.js.tmp && mv dist/index.js.tmp dist/index.js",test:"bun test",lint:"biome check src/","lint:scrub":"biome check scripts/scrub shared/identifier-scrub.ts test/scrub","test:scrub":"bun test --preload ./test/scrub/helpers/temp-dirs-preload.ts --path-ignore-patterns='__run_every_scrub_suite__' test/scrub test/identifier-scan.test.ts test/identifier-scrub.test.ts test/identifier-dates.test.ts test/identifier-fleet.test.ts","migrations:d1-check":"bun run scripts/d1-migration-check.ts","zarr:geometry-check":"bun run backend/scripts/zarr-geometry-conformance.ts","lint:fix":"biome check --fix src/",format:"biome format --write src/",typecheck:"tsc --noEmit && tsc --noEmit -p backend","generate-openapi":"bun run scripts/generate-openapi.ts",prepublishOnly:"bun run build",prepare:"husky",postinstall:"bun scripts/postinstall-check.mjs",deploy:"wrangler deploy",preview:"wrangler dev"},keywords:["nemar","bids","neuroimaging","eeg","emg","datalad","cli"],author:"NEMAR Team",license:"CC-BY-NC-ND-4.0",repository:{type:"git",url:"git+https://github.com/nemarOrg/nemar-cli.git"},bugs:{url:"https://github.com/nemarOrg/nemar-cli/issues"},homepage:"https://docs.nemar.org",engines:{bun:">=1.0.0"},files:["dist","scripts/postinstall-check.mjs","scripts/recover-datasets.json","scripts/withdrawn-datasets.json","README.md","LICENSE"],dependencies:{chalk:"^5.3.0",commander:"^12.1.0",conf:"^13.0.1",inquirer:"^9.2.15",ora:"^8.0.1",semver:"^7.8.5",zod:"^3.23.8"},"lint-staged":{"src/**/*.{ts,tsx}":["biome check --fix"],"backend/src/**/*.{ts,tsx}":["biome check --fix"]},trustedDependencies:["@biomejs/biome"],devDependencies:{"@anthropic-ai/sdk":"^0.132.1","@asteasolutions/zod-to-openapi":"^7.3.4","@biomejs/biome":"1.9.4","@types/bun":"latest","@types/inquirer":"^9.0.7","@types/semver":"^7.8.0",ajv:"^8.20.0","ajv-formats":"^3.0.1",husky:"^9.1.7",jose:"6.2.12","lint-staged":"^16.3.2",oauth4webapi:"3.8.8","openid-client":"6.8.9",typescript:"^5.5.4",wrangler:"^4.70.0",yaml:"^2.8.4"}}});var ac;var Gl=F(()=>{Eb();ac=wb.version});import{mkdirSync as oV,readdirSync as iV,unlinkSync as aV,writeFileSync as cV}from"fs";import{join as Kl}from"path";function dB(){Ds=!0}function lc(){return Ds}function fB(e,t=process.env){return e.includes("--debug")||t.NEMAR_DEBUG==="1"}function pB(e){Tb=e,pr(`Step: ${e}`)}function hB(){xb=!0}function mB(){return xb}function gB(){if(Rb)return;Bl=!0}function yB(){Bl=!1,Rb=!0}function _B(){return Bl}function pr(e){if(Ds)process.stderr.write(`[debug] ${e}
26
+ `))}var yb,ZF,rV=4000;var $b=F(()=>{gb();yb={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)"}}},ZF={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 wb;var Eb=F(()=>{wb={name:"nemar-cli",packageManager:"bun@1.4.3",version:"0.10.38-dev.4682",description:"CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",type:"module",main:"dist/index.js",bin:{nemar:"dist/index.js","git-annex-remote-nemar":"dist/git-annex-remote-nemar.js"},scripts:{dev:"bun run src/index.ts",build:"bun build src/index.ts src/git-annex-remote-nemar.ts --outdir dist --target bun --minify && sed '1s|#!/usr/bin/env node|#!/usr/bin/env bun|' dist/index.js > dist/index.js.tmp && mv dist/index.js.tmp dist/index.js",test:"bun test",lint:"biome check src/","lint:scrub":"biome check scripts/scrub shared/identifier-scrub.ts test/scrub","test:scrub":"bun test --preload ./test/scrub/helpers/temp-dirs-preload.ts --path-ignore-patterns='__run_every_scrub_suite__' test/scrub test/identifier-scan.test.ts test/identifier-scrub.test.ts test/identifier-dates.test.ts test/identifier-fleet.test.ts","migrations:d1-check":"bun run scripts/d1-migration-check.ts","zarr:geometry-check":"bun run backend/scripts/zarr-geometry-conformance.ts","lint:fix":"biome check --fix src/",format:"biome format --write src/",typecheck:"tsc --noEmit && tsc --noEmit -p backend","generate-openapi":"bun run scripts/generate-openapi.ts",prepublishOnly:"bun run build",prepare:"husky",postinstall:"bun scripts/postinstall-check.mjs",deploy:"wrangler deploy",preview:"wrangler dev"},keywords:["nemar","bids","neuroimaging","eeg","emg","datalad","cli"],author:"NEMAR Team",license:"CC-BY-NC-ND-4.0",repository:{type:"git",url:"git+https://github.com/nemarOrg/nemar-cli.git"},bugs:{url:"https://github.com/nemarOrg/nemar-cli/issues"},homepage:"https://docs.nemar.org",engines:{bun:">=1.0.0"},files:["dist","scripts/postinstall-check.mjs","scripts/recover-datasets.json","scripts/withdrawn-datasets.json","README.md","LICENSE"],dependencies:{chalk:"^5.3.0",commander:"^12.1.0",conf:"^13.0.1",inquirer:"^9.2.15",ora:"^8.0.1",semver:"^7.8.5",zod:"^3.23.8"},"lint-staged":{"src/**/*.{ts,tsx}":["biome check --fix"],"backend/src/**/*.{ts,tsx}":["biome check --fix"]},trustedDependencies:["@biomejs/biome"],devDependencies:{"@anthropic-ai/sdk":"^0.132.1","@asteasolutions/zod-to-openapi":"^7.3.4","@biomejs/biome":"1.9.4","@types/bun":"latest","@types/inquirer":"^9.0.7","@types/semver":"^7.8.0",ajv:"^8.20.0","ajv-formats":"^3.0.1",husky:"^9.1.7",jose:"6.2.12","lint-staged":"^16.3.2",oauth4webapi:"3.8.8","openid-client":"6.8.9",typescript:"^5.5.4",wrangler:"^4.70.0",yaml:"^2.8.4"}}});var ac;var Gl=F(()=>{Eb();ac=wb.version});import{mkdirSync as oV,readdirSync as iV,unlinkSync as aV,writeFileSync as cV}from"fs";import{join as Kl}from"path";function dB(){Ds=!0}function lc(){return Ds}function fB(e,t=process.env){return e.includes("--debug")||t.NEMAR_DEBUG==="1"}function pB(e){Tb=e,pr(`Step: ${e}`)}function hB(){xb=!0}function mB(){return xb}function gB(){if(Rb)return;Bl=!0}function yB(){Bl=!1,Rb=!0}function _B(){return Bl}function pr(e){if(Ds)process.stderr.write(`[debug] ${e}
27
27
  `)}function fV(e){let t={};for(let[r,n]of Object.entries(e))t[r]=dV.has(r.toLowerCase())?"[REDACTED]":n;return t}function Ob(e){let t=e.indexOf("@");if(t<=0)return"***";return`${e[0]}***${e.slice(t)}`}function Hl(e,t,r=0){if(r>hV)return"[REDACTED: depth]";if(Array.isArray(t))return t.map((n)=>Hl(e,n,r+1));if(t&&typeof t==="object"){let n={};for(let[s,o]of Object.entries(t))n[s]=Hl(s,o,r+1);return n}if(typeof t==="string"){if(pV.test(e))return"[REDACTED]";return t.replace(kb,Ob)}return t}function Wl(e){return e.replace(mV,"Bearer [REDACTED]").replace(gV,"[REDACTED_AWS_KEY]").replace(yV,"$1[REDACTED]").replace(_V,"$1$2=[REDACTED]").replace(kb,Ob)}function vV(e){return Wl(e)}function bb(e,t=lV){if(e===void 0)return;let r=e;try{let n=JSON.parse(e);r=JSON.stringify(Hl("",n))}catch{}if(r=Wl(r),Buffer.byteLength(r,"utf8")>t)r=`${Buffer.from(r,"utf8").subarray(0,t).toString("utf8")}... [truncated]`;return r}function dc(e){if(!Ds)return;let t=vV(e.url);try{let r={...e,url:t,requestHeaders:e.requestHeaders?fV(e.requestHeaders):void 0,requestBody:bb(e.requestBody),responseBody:bb(e.responseBody)};uc.push(r),pr(`${e.method} ${t} -> ${e.status??"ERROR"} (${e.durationMs}ms)`)}catch(r){let n=dr(r);uc.push({method:e.method,url:t,status:e.status,durationMs:e.durationMs,note:`redaction failed: ${n}`}),pr(`redaction failed for ${e.method} ${t}: ${n}`)}}async function $V(){let e=[];try{let t=process.versions.bun?`Bun ${process.versions.bun}`:`Node ${process.version}`;e.push(`CLI version: ${ac}`),e.push(`OS/Arch: ${process.platform}/${process.arch}`),e.push(`Runtime: ${t}`)}catch(t){e.push(`(could not read CLI/OS/runtime info: ${dr(t)})`)}e.push(""),e.push("Active account:");try{let t=hn();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: ${dr(t)})`)}e.push(""),e.push("External tools:");try{let t=await zl();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: ${dr(t)})`)}return e}async function EV(){return(await $V()).join(`
28
28
  `)}async function vB(){if(!Ds||cc!==void 0)return;try{cc=await EV()}catch(e){let t=dr(e);cc=`(could not build environment report: ${t})`,pr(`environment snapshot failed: ${t}`)}}function Ab(e){if(Sb.has(e))return{flag:e};for(let t of Sb){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 wV(e){let t=[];for(let r=0;r<e.length;r++){let n=e[r],s=Ab(n);if(!s){t.push(n);continue}if(s.kind==="long-eq")t.push(`${s.flag}=[REDACTED]`);else if(s.kind==="short-attached")t.push(`${s.flag}[REDACTED]`);else if(t.push(n),r+1<e.length)t.push("[REDACTED]"),r++}return t}function bV(e){let t=[];for(let r=0;r<e.length;r++){let n=e[r],s=Ab(n);if(!s){t.push(n);continue}if(!s.kind&&r+1<e.length)r++}return t}function SV(e){let t=[];for(let n of bV(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 xV(e,t){let r=[];if(r.push("NEMAR CLI Debug Log"),r.push(`Generated: ${new Date().toISOString()}`),r.push(`Command: nemar ${Wl(wV(e).join(" "))}`),r.push(""),r.push(cc??"(environment snapshot unavailable)"),r.push(""),r.push("HTTP requests:"),uc.length===0)r.push(" (none)");else uc.forEach((n,s)=>{if(r.push(` [${s+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: ${Tb??"(none recorded)"}`),r.push(`Exit code: ${t}`),`${r.join(`
29
29
  `)}
30
30
  `}function RV(e,t){let r;try{r=iV(e).filter((s)=>s.startsWith("nemar-")&&s.endsWith(".log"))}catch(s){if(s.code!=="ENOENT")pr(`could not list ${e} for log rotation: ${dr(s)}`);return}r.sort();let n=r.length-t;for(let s=0;s<n;s++)try{aV(Kl(e,r[s]))}catch(o){if(o.code!=="ENOENT")pr(`could not remove old log ${r[s]}: ${dr(o)}`)}}function $B(){return zo}function EB(e,t){if(!Ds)return null;let r=Kl(Xl(),"logs");try{oV(r,{recursive:!0})}catch(i){return zo=dr(i),pr(`could not create log directory ${r}: ${zo}`),null}let s=`nemar-${new Date().toISOString().replace(/[:.]/g,"-")}-${SV(e)}.log`,o=Kl(r,s);try{cV(o,xV(e,t),"utf8")}catch(i){return zo=dr(i),pr(`could not write log file ${o}: ${zo}`),null}return RV(r,uV),o}var uV=10,lV=2048,Ds=!1,xb=!1,Bl=!1,Rb=!1,Tb,cc,uc,dV,pV,kb,hV=32,mV,gV,yV,_V,Sb,zo;var Yl=F(()=>{Cl();fc();$b();Gl();uc=[];dV=new Set(["authorization","cookie","set-cookie","x-api-key","x-approval-dispatch-token"]);pV=/^(api[_-]?key|apikey|password|token|secret|access[_-]?key(_id)?|secret[_-]?access[_-]?key|session|session[_-]?token|authorization|ssh[_-]?key|private[_-]?key|device[_-]?code|dispatch[_-]?token|client[_-]?secret)$/i,kb=/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g;mV=/Bearer\s+[A-Za-z0-9\-._~+/=]+/gi,gV=/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g,yV=/((?:aws_)?secret_access_key["']?\s*[:=]\s*["']?)[A-Za-z0-9/+=]{20,}/gi,_V=/([?&])(X-Amz-Signature|X-Amz-Security-Token|X-Amz-Credential|Signature|AWSAccessKeyId)=[^&\s"']+/gi;Sb=new Set(["-k","--key","--password","--api-key"])});import{chmodSync as TV,copyFileSync as kV,existsSync as Jl,mkdirSync as OV,statSync as AV}from"fs";import{homedir as pc}from"os";import{join as Ms}from"path";function NV(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 Xl(){return process.env.NEMAR_CONFIG_DIR||Ms(pc(),".config","nemar")}function CV(e){if(process.env.NEMAR_CONFIG_DIR)return;let t=Ms(e,"config.json");if(Jl(t))return;let r=[];if(process.platform==="darwin")r.push(Ms(pc(),"Library","Preferences","nemar-nodejs","config.json"));if(process.platform==="win32"){let n=process.env.APPDATA||Ms(pc(),"AppData","Roaming");r.push(Ms(n,"nemar-nodejs","config.json"))}r.push(Ms(pc(),".config","nemar-nodejs","config.json"));for(let n of r)if(Jl(n))try{OV(e,{recursive:!0}),kV(n,t),console.error(`[nemar] Config migrated from ${n} to ${t}
31
31
  [nemar] You can safely remove the old file.`);return}catch(s){console.error(`[nemar] Failed to migrate config from ${n}:`,s,`
32
- [nemar] You can manually copy ${n} to ${t}`)}}function St(){let e=Xl();if(Go&&Pb===e)return Go;if(CV(e),Go=new Ka({projectName:"nemar",configFileMode:Ql,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}),Pb=e,!Nb.has(e))Nb.add(e),jV(Go.path),DV(),MV();return Go}function jV(e){if(process.platform==="win32")return;if(!Jl(e))return;try{if((AV(e).mode&511)!==Ql)TV(e,Ql)}catch(t){console.error(`[nemar] could not secure config file permissions for ${e}:`,t)}}function DV(){let e=St(),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 s=n||"default",o={};for(let i of qV){let a=e.get(i);if(a!==void 0)o[i]=a}e.store={activeAccount:s,accounts:{[s]:o}}}catch(s){console.error("Config migration failed (legacy config preserved):",s)}}function MV(){let e=St(),t=e.store,r=t.accounts,n=!1;if(r)for(let[o,i]of Object.entries(r)){let a=i?.apiUrl;if(!a)continue;if(PV.has(NV(a)))r[o]={...i,apiUrl:Ls},console.error(`[nemar] migrated stored apiUrl for account "${o}": ${a} -> ${Ls}`),n=!0}let s=t.apiUrl;if(r&&Object.keys(r).length>0&&s!==void 0){let{apiUrl:o,...i}=t;try{e.store=i,console.error(`[nemar] removed stale top-level apiUrl from config (was: ${s})`),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 Ko(){return St().get("activeAccount")}function mn(){return St().get("accounts")||{}}function hn(){let e={apiUrl:Ls},t=Ko();if(!t)return e;return mn()[t]||e}function PB(e,t){let r=St(),n=r.get("activeAccount")||"default",s=r.get("accounts")||{};if(!s[n])s[n]={apiUrl:Ls};s[n][e]=t,r.store={...r.store,accounts:s,activeAccount:n}}function NB(e){let t=Ko();if(!t)return;let r=mn();if(r[t])delete r[t][e],St().set("accounts",r)}function IB(){let e=St(),t=Ko();if(!t){e.clear();return}let r=mn();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 CB(){St().clear()}function jB(){return!!hn().apiKey}function qB(){return St().path}function DB(){let e=mn(),t=Ko();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 MB(e){return e.username?.trim()||e.email}function LV(e){let t=e.trim().toLowerCase();if(!t)return;let r=Object.entries(mn()).filter(([,n])=>n.email&&n.email.toLowerCase()===t).map(([n])=>n);if(r.length>1){pr(`findAccountKeyByEmail: ${r.length} accounts share email ${t}: ${r.join(", ")}`);return}return r[0]}function LB(e,t){let r=St(),n=mn(),s;if(n[e])s=e;else if(t.email)s=LV(t.email);let o=s?n[s]:void 0,i={...o??{apiUrl:Ls},...t};if(s&&s!==e)delete n[s];return n[e]=i,r.store={...r.store,accounts:n,activeAccount:e},{key:e,previous:o}}function UB(e){let t=e.trim();if(!t)return"unchanged";let r=St(),n=Ko();if(!n||n===t)return"unchanged";let s=mn(),o=s[n];if(!o)return"unchanged";if(s[t])return"key_taken";return delete s[n],s[t]={...o,username:t},r.store={...r.store,accounts:s,activeAccount:t},"renamed"}function FB(e){let t=St(),r=mn();if(r[e])return t.store={...t.store,activeAccount:e},r[e];for(let[n,s]of Object.entries(r))if(s.githubUsername===e)return t.store={...t.store,activeAccount:n},s;return null}var Ls="https://api.nemar.org",Ql=384,PV,IV,AB,Go=null,Pb=null,Nb,qV;var fc=F(()=>{Fw();jn();nc();Yl();PV=new Set(["https://api.osc.earth/nemar","https://nemar-api.neuromechanist.workers.dev","https://nemar-api-dev.shirazi-10f.workers.dev"]);IV=ne({field:v(),blocks:Ze(v()).optional(),set_on:Ze(v()).optional()}).passthrough(),AB=ne({apiKey:v().optional(),apiUrl:v().url().default(Ls),username:v().optional(),email:v().email().optional(),githubUsername:v().optional(),sandboxCompleted:Ue().optional(),sandboxDatasetId:v().optional(),dismissedNoticeIds:Ze(fe()).optional(),serviceAccess:Ue().optional(),profileGaps:Ze(IV).optional(),orcidVerified:Ue().optional(),role:v().optional(),accountKind:qn.optional(),pendingEmailChange:v().email().optional()});Nb=new Set;qV=["apiKey","apiUrl","username","email","githubUsername","sandboxCompleted","sandboxDatasetId","dismissedNoticeIds"]});var UV,FV,KB,VV,HB,zV,Ib,BB,WB=8,YB=100,Cb,XB,GV,JB;var jb=F(()=>{jn();nc();UV=["given_name","family_name","affiliation","city","country"],FV=["username","github_username","email","orcid"],KB=[...UV,...FV],VV={given_name:v().max(200).optional(),family_name:v().max(200).optional(),affiliation:v().max(500).optional(),city:v().max(200).optional(),country:v().max(200).optional(),username:v().max(100).optional(),github_username:v().max(100).optional(),email:v().max(320).optional(),orcid:v().max(40).optional()},HB=ne(VV),zV=Ve(["field_not_editable","owner_only_field","edit_own_account","owner_account","system_account","invalid_edit","orcid_already_proven","invalid_search","invalid_user_id"]),Ib=zV.options,BB=["exact","name","prefix","substring","fuzzy"],Cb=ne({id:fe().int(),username:v().nullable(),email:v(),github_username:v().nullable(),status:v(),role:v().nullable(),account_kind:qn.optional(),email_verified:fe().int().nullable().optional(),orcid:v().nullable().optional(),orcid_verified:fe().int().nullable().optional(),given_name:v().nullable().optional(),family_name:v().nullable().optional(),affiliation:v().nullable().optional(),city:v().nullable().optional(),country:v().nullable().optional(),description:v().nullable().optional(),signup_source:v().nullable().optional(),created_at:v(),updated_at:v().nullable().optional(),approved_at:v().nullable().optional(),revoked_at:v().nullable().optional(),deleted_at:v().nullable().optional(),service_access:fe().int().nullable().optional(),service_access_granted_at:v().nullable().optional(),service_access_granted_by:fe().int().nullable().optional(),upload_access_requested_at:v().nullable().optional(),upload_access_notified_at:v().nullable().optional(),identity_conflict:fe().int().nullable().optional(),username_auto_assigned:fe().int().nullable().optional(),sandbox_completed:fe().int().nullable().optional(),sandbox_completed_at:v().nullable().optional(),sandbox_dataset_id:v().nullable().optional(),aws_iam_username:v().nullable().optional(),dataset_count:fe().int().optional(),active_tokens:fe().int().optional(),linked_identities:Ze(v()).optional()}).passthrough(),XB=ne({user:Cb}).passthrough(),GV=ne({from:v().nullable(),to:v().nullable()}),JB=ne({message:v(),changed:wF(v(),GV),notes:Ze(v()).optional(),old_address_notified:Ue().optional(),user:Cb}).passthrough()});var e6=120,t6=64,r6="unnamed machine",KV=25,qb,n6,Us,Db,s6,o6,i6,HV,BV,a6,Zl,c6,u6,l6,d6,f6;var Mb=F(()=>{jn();qb=Ve(["authorization_pending","slow_down","expired_token","access_denied","invalid_grant"]),n6={authorization_pending:"Waiting for you to authorize this machine in the browser.",slow_down:"Polling too quickly; the CLI will slow down automatically.",expired_token:"The code expired. Run `nemar auth login` again for a new one.",access_denied:"This sign-in was declined in the browser. Run `nemar auth login` again if that was a mistake.",invalid_grant:"That code is no longer valid. Run `nemar auth login` again for a new one."},Us=Ve(["device_code_unknown","device_code_expired","device_code_used","device_code_denied","account_pending","account_revoked","identity_conflict","service_account","person_account","too_many_keys","key_not_found"]),Db=Us.options,s6={device_code_unknown:"That code was not found. Check the code shown in your terminal, or run `nemar auth login` again for a new one.",device_code_expired:"The code expired. Run `nemar auth login` again for a new one.",device_code_used:"That code has already been used. Run `nemar auth login` again for a new one.",device_code_denied:"This sign-in was declined in the browser. Run `nemar auth login` again if that was a mistake.",account_pending:"Verify your email address first. Check your inbox for the NEMAR verification code, then authorize again.",account_revoked:"Your NEMAR account access has been revoked. Contact the NEMAR team if you think this is a mistake.",identity_conflict:"This account shares an identifier with another NEMAR account and cannot sign in until that is resolved. Fix it in Settings on nemar.org or contact the NEMAR team.",service_account:"This is a service or test account, and it cannot sign in this way. Ask an owner to create a key for it with `nemar admin keys create`.",person_account:"This account belongs to a person. A person creates their own keys with `nemar auth login` or in Settings on nemar.org.",too_many_keys:`This account already has ${KV} active keys. Revoke one in Settings on nemar.org or with \`nemar auth keys\`, then try again.`,key_not_found:"That key was not found on this account, or it is already revoked. Run `nemar auth keys` to see the active ones."},o6=ne({error:Us,message:v()}).passthrough(),i6=ne({device_code:v(),user_code:v(),verification_uri:v(),verification_uri_complete:v(),expires_in:fe().int(),interval:fe().int()}).passthrough(),HV=Yw("error",[ne({error:In("authorization_pending"),message:v()}).passthrough(),ne({error:In("slow_down"),message:v()}).passthrough()]),BV=Yw("error",[ne({error:In("expired_token"),reason:Us,message:v()}).passthrough(),ne({error:In("access_denied"),reason:Us,message:v()}).passthrough(),ne({error:In("invalid_grant"),reason:Us,message:v()}).passthrough()]),a6=EF([HV,BV]),Zl=ne({id:fe().int(),name:v().nullable(),prefix:v(),created_at:v(),last_used_at:v().nullable(),current:Ue()}).passthrough(),c6=ne({api_key:v(),key:Zl,user:ne({username:v().nullable(),email:v(),github_username:v().nullable(),role:v(),sandbox_completed:Ue(),sandbox_dataset_id:v().nullable()}).passthrough()}).passthrough(),u6=ne({user_code:v(),machine_name:v(),requested_at:v(),expires_in:fe().int(),account:ne({username:v().nullable(),email_masked:v()}).passthrough(),refusal:ne({code:Us,message:v()}).passthrough().nullable()}).passthrough(),l6=ne({ok:In(!0),machine_name:v()}).passthrough(),d6=ne({keys:Ze(Zl)}).passthrough(),f6=ne({api_key:v(),key:Zl}).passthrough()});var WV,Lb,Ho="https://nemar.org/settings",m6,YV,XV,JV,g6,y6;var Ub=F(()=>{jn();WV=Ve(["orcid_in_use","orcid_already_linked","orcid_linked_other","email_in_use","github_in_use","identity_conflict_remains"]),Lb=WV.options,m6={orcid_in_use:`That ORCID iD already belongs to a NEMAR account. Sign in to that account instead; if you want the iD on a different account, unlink it there first (Settings, ${Ho}).`,orcid_already_linked:`That ORCID iD already belongs to a NEMAR account. Sign in to that account instead; if you want the iD on a different account, unlink it there first (Settings, ${Ho}).`,orcid_linked_other:`That ORCID iD is linked to a different NEMAR account. Unlink it there first (Settings, ${Ho}), then link it here.`,email_in_use:`That email address already belongs to a NEMAR account. Sign in to that account instead, or change its address first (Settings, ${Ho}).`,github_in_use:`That GitHub account is already linked to a NEMAR account. Sign in to that account instead, or change its GitHub username first (Settings, ${Ho}).`,identity_conflict_remains:"The collision that flagged this account is still there. Resolve it on the other account first (change its email or GitHub username, or unlink its ORCID iD), or delete that account, then clear the flag."},YV=Ve(["orcid","email","github"]),XV=ne({id:fe().int(),username:v().nullable(),email:v(),created_at:v(),has_oauth_identity:Ue(),dataset_count:fe().int(),identity_conflict:fe().int(),canonical:Ue()}).passthrough(),JV=ne({kind:YV,value:v(),canonical_user_id:fe().int(),accounts:Ze(XV)}).passthrough(),g6=ne({groups:Ze(JV),group_count:fe().int(),flagged_count:fe().int()}).passthrough(),y6=ne({ok:In(!0),id:fe().int(),cleared:Ue()}).passthrough()});function b6(e){return typeof e==="string"&&ZV.includes(e)}var QV,$6,E6,w6,ZV,e9="ci_check_unavailable",Fb,Vb,zb,S6="X-Approval-Dispatch-Token",x6,R6="Search reflects this at once; the public dataset page and catalog list are cached at the edge and can keep showing the dataset for several minutes.";var Gb=F(()=>{jn();QV=/^\d{4}-\d{4}-\d{4}-\d{3}[\dX]$/,$6=v().regex(QV,"ORCID must be in format 0000-0000-0000-000X"),E6=Ve(["found","no_public_name","lookup_failed"]),w6=Ve(["bids_validation_failed","bids_validation_pending","bids_validation_in_progress","prescreen_failed","min_requirements_failed","owner_name_missing","identifier_screen_findings"]),ZV=["bids_validation_pending","bids_validation_in_progress"];Fb=[e9],Vb=["identifier_screen_pending","identifier_screen_not_clear","identifier_screen_not_applicable"],zb=["publication_review_not_clear","request_blocked","request_changed","request_mismatch","dispatch_superseded","dispatch_expired","decision_with_dispatch_token","approval_in_flight","deny_after_publishing","invalid_dataset_id","approval_closed_during_run"],x6=Ve(["filled","would_fill","no_public_name","lookup_failed","write_failed"])});function Hb(e){if(Kb)return;Kb=!0;let t=Nt.yellow("\u2500".repeat(60)),r=Nt.yellow.bold("[MAINTENANCE]"),n=Nt.dim(`mode: ${e.mode}`),s=e.eta?`
32
+ [nemar] You can manually copy ${n} to ${t}`)}}function St(){let e=Xl();if(Go&&Pb===e)return Go;if(CV(e),Go=new Ka({projectName:"nemar",configFileMode:Ql,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}),Pb=e,!Nb.has(e))Nb.add(e),jV(Go.path),DV(),MV();return Go}function jV(e){if(process.platform==="win32")return;if(!Jl(e))return;try{if((AV(e).mode&511)!==Ql)TV(e,Ql)}catch(t){console.error(`[nemar] could not secure config file permissions for ${e}:`,t)}}function DV(){let e=St(),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 s=n||"default",o={};for(let i of qV){let a=e.get(i);if(a!==void 0)o[i]=a}e.store={activeAccount:s,accounts:{[s]:o}}}catch(s){console.error("Config migration failed (legacy config preserved):",s)}}function MV(){let e=St(),t=e.store,r=t.accounts,n=!1;if(r)for(let[o,i]of Object.entries(r)){let a=i?.apiUrl;if(!a)continue;if(PV.has(NV(a)))r[o]={...i,apiUrl:Ls},console.error(`[nemar] migrated stored apiUrl for account "${o}": ${a} -> ${Ls}`),n=!0}let s=t.apiUrl;if(r&&Object.keys(r).length>0&&s!==void 0){let{apiUrl:o,...i}=t;try{e.store=i,console.error(`[nemar] removed stale top-level apiUrl from config (was: ${s})`),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 Ko(){return St().get("activeAccount")}function mn(){return St().get("accounts")||{}}function hn(){let e={apiUrl:Ls},t=Ko();if(!t)return e;return mn()[t]||e}function PB(e,t){let r=St(),n=r.get("activeAccount")||"default",s=r.get("accounts")||{};if(!s[n])s[n]={apiUrl:Ls};s[n][e]=t,r.store={...r.store,accounts:s,activeAccount:n}}function NB(e){let t=Ko();if(!t)return;let r=mn();if(r[t])delete r[t][e],St().set("accounts",r)}function IB(){let e=St(),t=Ko();if(!t){e.clear();return}let r=mn();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 CB(){St().clear()}function jB(){return!!hn().apiKey}function qB(){return St().path}function DB(){let e=mn(),t=Ko();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 MB(e){return e.username?.trim()||e.email}function LV(e){let t=e.trim().toLowerCase();if(!t)return;let r=Object.entries(mn()).filter(([,n])=>n.email&&n.email.toLowerCase()===t).map(([n])=>n);if(r.length>1){pr(`findAccountKeyByEmail: ${r.length} accounts share email ${t}: ${r.join(", ")}`);return}return r[0]}function LB(e,t){let r=St(),n=mn(),s;if(n[e])s=e;else if(t.email)s=LV(t.email);let o=s?n[s]:void 0,i={...o??{apiUrl:Ls},...t};if(s&&s!==e)delete n[s];return n[e]=i,r.store={...r.store,accounts:n,activeAccount:e},{key:e,previous:o}}function UB(e){let t=e.trim();if(!t)return"unchanged";let r=St(),n=Ko();if(!n||n===t)return"unchanged";let s=mn(),o=s[n];if(!o)return"unchanged";if(s[t])return"key_taken";return delete s[n],s[t]={...o,username:t},r.store={...r.store,accounts:s,activeAccount:t},"renamed"}function FB(e){let t=St(),r=mn();if(r[e])return t.store={...t.store,activeAccount:e},r[e];for(let[n,s]of Object.entries(r))if(s.githubUsername===e)return t.store={...t.store,activeAccount:n},s;return null}var Ls="https://nemar-api-dev.sccn-org.workers.dev",Ql=384,PV,IV,AB,Go=null,Pb=null,Nb,qV;var fc=F(()=>{Fw();jn();nc();Yl();PV=new Set(["https://api.osc.earth/nemar","https://nemar-api.neuromechanist.workers.dev","https://nemar-api-dev.shirazi-10f.workers.dev"]);IV=ne({field:v(),blocks:Ze(v()).optional(),set_on:Ze(v()).optional()}).passthrough(),AB=ne({apiKey:v().optional(),apiUrl:v().url().default(Ls),username:v().optional(),email:v().email().optional(),githubUsername:v().optional(),sandboxCompleted:Ue().optional(),sandboxDatasetId:v().optional(),dismissedNoticeIds:Ze(fe()).optional(),serviceAccess:Ue().optional(),profileGaps:Ze(IV).optional(),orcidVerified:Ue().optional(),role:v().optional(),accountKind:qn.optional(),pendingEmailChange:v().email().optional()});Nb=new Set;qV=["apiKey","apiUrl","username","email","githubUsername","sandboxCompleted","sandboxDatasetId","dismissedNoticeIds"]});var UV,FV,KB,VV,HB,zV,Ib,BB,WB=8,YB=100,Cb,XB,GV,JB;var jb=F(()=>{jn();nc();UV=["given_name","family_name","affiliation","city","country"],FV=["username","github_username","email","orcid"],KB=[...UV,...FV],VV={given_name:v().max(200).optional(),family_name:v().max(200).optional(),affiliation:v().max(500).optional(),city:v().max(200).optional(),country:v().max(200).optional(),username:v().max(100).optional(),github_username:v().max(100).optional(),email:v().max(320).optional(),orcid:v().max(40).optional()},HB=ne(VV),zV=Ve(["field_not_editable","owner_only_field","edit_own_account","owner_account","system_account","invalid_edit","orcid_already_proven","invalid_search","invalid_user_id"]),Ib=zV.options,BB=["exact","name","prefix","substring","fuzzy"],Cb=ne({id:fe().int(),username:v().nullable(),email:v(),github_username:v().nullable(),status:v(),role:v().nullable(),account_kind:qn.optional(),email_verified:fe().int().nullable().optional(),orcid:v().nullable().optional(),orcid_verified:fe().int().nullable().optional(),given_name:v().nullable().optional(),family_name:v().nullable().optional(),affiliation:v().nullable().optional(),city:v().nullable().optional(),country:v().nullable().optional(),description:v().nullable().optional(),signup_source:v().nullable().optional(),created_at:v(),updated_at:v().nullable().optional(),approved_at:v().nullable().optional(),revoked_at:v().nullable().optional(),deleted_at:v().nullable().optional(),service_access:fe().int().nullable().optional(),service_access_granted_at:v().nullable().optional(),service_access_granted_by:fe().int().nullable().optional(),upload_access_requested_at:v().nullable().optional(),upload_access_notified_at:v().nullable().optional(),identity_conflict:fe().int().nullable().optional(),username_auto_assigned:fe().int().nullable().optional(),sandbox_completed:fe().int().nullable().optional(),sandbox_completed_at:v().nullable().optional(),sandbox_dataset_id:v().nullable().optional(),aws_iam_username:v().nullable().optional(),dataset_count:fe().int().optional(),active_tokens:fe().int().optional(),linked_identities:Ze(v()).optional()}).passthrough(),XB=ne({user:Cb}).passthrough(),GV=ne({from:v().nullable(),to:v().nullable()}),JB=ne({message:v(),changed:wF(v(),GV),notes:Ze(v()).optional(),old_address_notified:Ue().optional(),user:Cb}).passthrough()});var e6=120,t6=64,r6="unnamed machine",KV=25,qb,n6,Us,Db,s6,o6,i6,HV,BV,a6,Zl,c6,u6,l6,d6,f6;var Mb=F(()=>{jn();qb=Ve(["authorization_pending","slow_down","expired_token","access_denied","invalid_grant"]),n6={authorization_pending:"Waiting for you to authorize this machine in the browser.",slow_down:"Polling too quickly; the CLI will slow down automatically.",expired_token:"The code expired. Run `nemar auth login` again for a new one.",access_denied:"This sign-in was declined in the browser. Run `nemar auth login` again if that was a mistake.",invalid_grant:"That code is no longer valid. Run `nemar auth login` again for a new one."},Us=Ve(["device_code_unknown","device_code_expired","device_code_used","device_code_denied","account_pending","account_revoked","identity_conflict","service_account","person_account","too_many_keys","key_not_found"]),Db=Us.options,s6={device_code_unknown:"That code was not found. Check the code shown in your terminal, or run `nemar auth login` again for a new one.",device_code_expired:"The code expired. Run `nemar auth login` again for a new one.",device_code_used:"That code has already been used. Run `nemar auth login` again for a new one.",device_code_denied:"This sign-in was declined in the browser. Run `nemar auth login` again if that was a mistake.",account_pending:"Verify your email address first. Check your inbox for the NEMAR verification code, then authorize again.",account_revoked:"Your NEMAR account access has been revoked. Contact the NEMAR team if you think this is a mistake.",identity_conflict:"This account shares an identifier with another NEMAR account and cannot sign in until that is resolved. Fix it in Settings on nemar.org or contact the NEMAR team.",service_account:"This is a service or test account, and it cannot sign in this way. Ask an owner to create a key for it with `nemar admin keys create`.",person_account:"This account belongs to a person. A person creates their own keys with `nemar auth login` or in Settings on nemar.org.",too_many_keys:`This account already has ${KV} active keys. Revoke one in Settings on nemar.org or with \`nemar auth keys\`, then try again.`,key_not_found:"That key was not found on this account, or it is already revoked. Run `nemar auth keys` to see the active ones."},o6=ne({error:Us,message:v()}).passthrough(),i6=ne({device_code:v(),user_code:v(),verification_uri:v(),verification_uri_complete:v(),expires_in:fe().int(),interval:fe().int()}).passthrough(),HV=Yw("error",[ne({error:In("authorization_pending"),message:v()}).passthrough(),ne({error:In("slow_down"),message:v()}).passthrough()]),BV=Yw("error",[ne({error:In("expired_token"),reason:Us,message:v()}).passthrough(),ne({error:In("access_denied"),reason:Us,message:v()}).passthrough(),ne({error:In("invalid_grant"),reason:Us,message:v()}).passthrough()]),a6=EF([HV,BV]),Zl=ne({id:fe().int(),name:v().nullable(),prefix:v(),created_at:v(),last_used_at:v().nullable(),current:Ue()}).passthrough(),c6=ne({api_key:v(),key:Zl,user:ne({username:v().nullable(),email:v(),github_username:v().nullable(),role:v(),sandbox_completed:Ue(),sandbox_dataset_id:v().nullable()}).passthrough()}).passthrough(),u6=ne({user_code:v(),machine_name:v(),requested_at:v(),expires_in:fe().int(),account:ne({username:v().nullable(),email_masked:v()}).passthrough(),refusal:ne({code:Us,message:v()}).passthrough().nullable()}).passthrough(),l6=ne({ok:In(!0),machine_name:v()}).passthrough(),d6=ne({keys:Ze(Zl)}).passthrough(),f6=ne({api_key:v(),key:Zl}).passthrough()});var WV,Lb,Ho="https://nemar.org/settings",m6,YV,XV,JV,g6,y6;var Ub=F(()=>{jn();WV=Ve(["orcid_in_use","orcid_already_linked","orcid_linked_other","email_in_use","github_in_use","identity_conflict_remains"]),Lb=WV.options,m6={orcid_in_use:`That ORCID iD already belongs to a NEMAR account. Sign in to that account instead; if you want the iD on a different account, unlink it there first (Settings, ${Ho}).`,orcid_already_linked:`That ORCID iD already belongs to a NEMAR account. Sign in to that account instead; if you want the iD on a different account, unlink it there first (Settings, ${Ho}).`,orcid_linked_other:`That ORCID iD is linked to a different NEMAR account. Unlink it there first (Settings, ${Ho}), then link it here.`,email_in_use:`That email address already belongs to a NEMAR account. Sign in to that account instead, or change its address first (Settings, ${Ho}).`,github_in_use:`That GitHub account is already linked to a NEMAR account. Sign in to that account instead, or change its GitHub username first (Settings, ${Ho}).`,identity_conflict_remains:"The collision that flagged this account is still there. Resolve it on the other account first (change its email or GitHub username, or unlink its ORCID iD), or delete that account, then clear the flag."},YV=Ve(["orcid","email","github"]),XV=ne({id:fe().int(),username:v().nullable(),email:v(),created_at:v(),has_oauth_identity:Ue(),dataset_count:fe().int(),identity_conflict:fe().int(),canonical:Ue()}).passthrough(),JV=ne({kind:YV,value:v(),canonical_user_id:fe().int(),accounts:Ze(XV)}).passthrough(),g6=ne({groups:Ze(JV),group_count:fe().int(),flagged_count:fe().int()}).passthrough(),y6=ne({ok:In(!0),id:fe().int(),cleared:Ue()}).passthrough()});function b6(e){return typeof e==="string"&&ZV.includes(e)}var QV,$6,E6,w6,ZV,e9="ci_check_unavailable",Fb,Vb,zb,S6="X-Approval-Dispatch-Token",x6,R6="Search reflects this at once; the public dataset page and catalog list are cached at the edge and can keep showing the dataset for several minutes.";var Gb=F(()=>{jn();QV=/^\d{4}-\d{4}-\d{4}-\d{3}[\dX]$/,$6=v().regex(QV,"ORCID must be in format 0000-0000-0000-000X"),E6=Ve(["found","no_public_name","lookup_failed"]),w6=Ve(["bids_validation_failed","bids_validation_pending","bids_validation_in_progress","prescreen_failed","min_requirements_failed","owner_name_missing","identifier_screen_findings"]),ZV=["bids_validation_pending","bids_validation_in_progress"];Fb=[e9],Vb=["identifier_screen_pending","identifier_screen_not_clear","identifier_screen_not_applicable"],zb=["publication_review_not_clear","request_blocked","request_changed","request_mismatch","dispatch_superseded","dispatch_expired","decision_with_dispatch_token","approval_in_flight","deny_after_publishing","invalid_dataset_id","approval_closed_during_run"],x6=Ve(["filled","would_fill","no_public_name","lookup_failed","write_failed"])});function Hb(e){if(Kb)return;Kb=!0;let t=Nt.yellow("\u2500".repeat(60)),r=Nt.yellow.bold("[MAINTENANCE]"),n=Nt.dim(`mode: ${e.mode}`),s=e.eta?`
33
33
  ${Nt.dim(`eta: ${e.eta}`)}`:"";process.stderr.write(`${t}
34
34
  ${r} ${e.message}
35
35
  ${n}${s}
36
36
  ${t}
37
- `)}var Kb=!1;var Bb=F(()=>{Ul()});function Wb(){if(process.env.TEST_API_URL)return process.env.TEST_API_URL;if(td)return ed;return hn().apiUrl||ed}async function U6(e,t={},r=!1,n){let s=`${Wb()}${e}`,o={"Content-Type":"application/json","X-CLI-Version":ac,...t.headers};if(r){let p=hn();if(!p.apiKey&&r===!0)throw new fr(401,"Not authenticated. Run 'nemar auth login' first.");if(p.apiKey)o.Authorization=`Bearer ${p.apiKey}`}let i=t.method||"GET",a=typeof t.body==="string"?t.body:void 0,c=Date.now(),u;try{u=await fetch(s,{...t,headers:o})}catch(p){if(lc())dc({method:i,url:s,status:null,durationMs:Date.now()-c,requestHeaders:o,requestBody:a,error:p instanceof Error?p.message:String(p)});throw new fr(0,`Network error: Could not connect to ${Wb()}`,{originalError:p instanceof Error?p.message:String(p)})}let d;try{d=await u.text()}catch(p){if(lc())dc({method:i,url:s,status:u.status,durationMs:Date.now()-c,requestHeaders:o,requestBody:a,error:p instanceof Error?p.message:String(p)});throw new fr(0,"Failed to read response body",{httpStatus:u.status,originalError:p instanceof Error?p.message:String(p)})}if(lc())dc({method:i,url:s,status:u.status,durationMs:Date.now()-c,requestHeaders:o,requestBody:a,responseBody:d});let l;try{l=JSON.parse(d)}catch{throw new fr(u.status,`Invalid response from server (status ${u.status})`)}if(!u.ok){if(u.status===503&&(l.mode==="read-only"||l.mode==="full")){let xt=typeof l.message==="string"?l.message:"NEMAR is in maintenance mode. Please retry shortly.",hr=typeof l.eta==="string"?l.eta:null,et=new Il(l.mode,xt,hr,l.details);throw Hb(et),et}let p=typeof l.block_reason==="string",f=Array.isArray(l.missing)?l.missing.filter((xt)=>typeof xt==="string"):void 0,h=typeof l.error==="string"&&(eb.includes(l.error)||Lb.includes(l.error)),m=typeof l.error==="string"&&(qb.options.includes(l.error)||Db.includes(l.error)),y=typeof l.error==="string"&&Jw.includes(l.error),_=typeof l.error==="string"&&Ib.includes(l.error),O=typeof l.error==="string"&&Vb.includes(l.error),T=typeof l.error==="string"&&Fb.includes(l.error),M=typeof l.error==="string"&&zb.includes(l.error),_e=p||T||M||h||m||y||_||O||f!==void 0&&typeof l.error==="string"&&Zw.includes(l.error)?l.message||l.error:l.error||l.message;if(u.status===404&&l.error==="Not Found"&&typeof l.message==="string")_e=`${l.message}. This NEMAR backend does not support this command yet.`;let ve=new fr(u.status,_e||"Request failed",l.details,typeof l.step==="string"?l.step:void 0,p?l.block_reason:void 0,f);if(typeof l.error==="string")ve.code=l.error;if(typeof l.reason==="string")ve.reason=l.reason;throw ve.rawBody=l,ve}if(n){let p=n.safeParse(l);if(!p.success)throw new fr(u.status,`Response for ${e} did not match the expected NEMAR contract`,{issues:p.error.issues});return p.data}return l}var ed="https://api.nemar.org",td;var Yb=F(()=>{jb();Mb();Ub();Gb();nc();fc();Yl();Bb();Gl();Cl();td=ed.includes("workers.dev")});fc();import{open as c9,rm as u9}from"fs/promises";Yb();var Xb="NEMAR_DATA_HOSTS",t9="NEMAR_DATA_HOSTS_ONLY",r9="https://private.nemar.org",n9="https://private-test.nemar.org",s9=/^[a-z]{2,3}[0-9]{6}$/;function Jb(e){return s9.test(e)}function o9(e){return e}function Qb(e){return e==="127.0.0.1"||e==="localhost"||e==="[::1]"}function Zb(e){let t=e.trim();if(t===""||/[?#@]/.test(t))return null;let r;try{r=new URL(t)}catch{return null}if(r.username!==""||r.password!=="")return null;if(r.pathname!=="/")return null;if(r.protocol==="https:")return r.origin;if(r.protocol==="http:"&&Qb(r.hostname))return r.origin;return null}function eS(e){let t=[],r=[];for(let n of(e??"").split(",")){let s=n.trim();if(s==="")continue;let o=Zb(s);if(o===null)r.push(s);else if(!t.includes(o))t.push(o)}return{origins:t,rejected:r}}function tS(e){return e.env??process.env}function i9(e={}){let t=tS(e),r=e.isDevBuild??td,n=t[t9]==="1"?[]:[r?n9:r9],{origins:s}=eS(t[Xb]);return[...n,...s.filter((o)=>!n.includes(o))].map(o9)}function z6(e={}){return eS(tS(e)[Xb]).rejected}function hc(e,t={}){let r=Zb(e);if(r===null)return null;return i9(t).find((n)=>n===r)??null}function rS(e,t={}){return hc(e,t)!==null}function G6(e,t={}){let r;try{r=new URL(e)}catch{return null}if(r.username!==""||r.password!=="")return null;return hc(r.origin,t)}function nS(e,t){if(e.protocol==="https:")return!0;return e.protocol==="http:"&&Qb(e.hostname)&&new URL(t).protocol==="http:"}var a9="NEMAR_DATA_HOST_TIMEOUT_MS";function rd(e,t=process.env){let r=t[a9];if(r===void 0||!/^[0-9]+$/.test(r))return e;let n=Number(r);return n>0&&n<e?n:e}function nd(e){if(!(e instanceof Error))return"error";let t=e.code;return typeof t==="string"&&/^[A-Z][A-Z0-9_]+$/.test(t)?`${e.name} ${t}`:e.name}var sS=3,iS=60000,l9=262144,aS=255,cS=/^[A-Z0-9][A-Z0-9_]*-s([0-9]{1,16})(?:-S([0-9]{1,16})-C([0-9]{1,16}))?--[A-Za-z0-9._-]+$/;function uS(e){return e.length<=aS&&cS.test(e)}function d9(e){if(e.length>aS)return null;let t=cS.exec(e);if(!t||t[2]!==void 0)return null;let r=Number(t[1]);return Number.isSafeInteger(r)?r:null}function f9(e,t,r={}){if(!e)return{ok:!1,message:"The remote has no host setting."};if(!t)return{ok:!1,message:"The remote has no dataset setting."};if(!Jb(t))return{ok:!1,message:"The dataset setting is not a dataset id (two or three letters and six digits)."};let n=hc(e,r);if(n===null)return{ok:!1,message:`The host setting ${It(e)} is not an https origin on this CLI's list of data hosts. The remote's host setting is part of the repository, so it cannot add one.`};return{ok:!0,settings:{origin:n,dataset:t,options:r}}}function It(e,t=200){let r=e.replace(/[^\x20-\x7e]/g,"?");return r.length>t?`${r.slice(0,t)}...`:r}function p9(e,t){return new URL(`${e.origin}/o/${encodeURIComponent(e.dataset)}/${encodeURIComponent(t)}`)}function lS(e,t){if(t)return`The storage address was refused (status ${e}).`;if(e===401)return"The data host refused the API key. Run 'nemar auth login' to sign in again.";if(e===404)return"The data host has no such object, or this account has no access to the dataset.";if(e===429)return"The data host is limiting requests; try again shortly.";return`The data host answered status ${e}.`}async function dS(e,t,r,n,s,o){if(!rS(e.origin,e.options))return{kind:"failed",message:"The host is not on this CLI's list of data hosts."};let i=p9(e,t),a=!1;for(let c=0;;c++){let u={"Accept-Encoding":"identity"};if(i.origin===e.origin)u.Authorization=`Bearer ${r}`;let d;try{d=await fetch(i,{method:n,headers:u,redirect:"manual",signal:o})}catch(f){if(o.aborted)return{kind:"failed",message:"The request timed out."};return{kind:"failed",message:`Could not reach the host (${nd(f)}).`}}if(d.status<300||d.status>=400)return{kind:"response",response:d,redirected:a};if(await d.body?.cancel().catch(()=>{}),!s)return{kind:"response",response:d,redirected:a};if(c>=sS)return{kind:"failed",message:`More than ${sS} redirects.`};let l=d.headers.get("location");if(!l)return{kind:"failed",message:"A redirect named no address."};let p;try{p=new URL(l,i)}catch{return{kind:"failed",message:"A redirect named an address that is not a URL."}}if(!nS(p,e.origin))return{kind:"failed",message:"A redirect named an address that is not https."};i=p,a=!0}}async function fS(e,t){let r=new AbortController,n=setTimeout(()=>r.abort(),e),s=()=>{clearTimeout(n),n=setTimeout(()=>r.abort(),e)};try{return await t(r.signal,s)}finally{clearTimeout(n)}}async function h9(e,t,r,n,s){if(!uS(t))return{ok:!1,message:"The key is not one a data host serves."};let o=d9(t);return fS(rd(iS,e.options?.env),async(i,a)=>{let c=await dS(e,t,r,"GET",!0,i);if(c.kind==="failed")return{ok:!1,message:c.message};let{response:u,redirected:d}=c;if(u.status!==200||!u.body)return await u.body?.cancel().catch(()=>{}),{ok:!1,message:lS(u.status,d)};let l=u.headers.get("content-length");if(o!==null&&l!==null&&Number(l)!==o)return await u.body.cancel().catch(()=>{}),{ok:!1,message:`The object is ${It(l,20)} bytes but its key says ${o}.`};a();let p,f=0,h=0;try{p=await c9(n,"w");let m=u.body.getReader();while(!0){let{done:y,value:_}=await m.read();if(y)break;if(a(),f+=_.byteLength,o!==null&&f>o)throw await m.cancel().catch(()=>{}),new mc(`More bytes arrived than the key's ${o}.`);if(await p.write(_),f-h>=l9)h=f,s(f)}if(await p.close(),p=void 0,o!==null&&f!==o)throw new mc(`The object ended after ${f} bytes; its key says ${o}.`);if(f!==h)s(f);return{ok:!0,bytes:f}}catch(m){if(await p?.close().catch(()=>{}),await u9(n,{force:!0}).catch(()=>{}),m instanceof mc)return{ok:!1,message:m.message};if(i.aborted)return{ok:!1,message:"The transfer stalled and timed out."};return{ok:!1,message:`The transfer failed (${nd(m)}).`}}})}class mc extends Error{constructor(e){super(e);this.name="SizeError"}}async function m9(e,t,r){if(!uS(t))return{state:"unknown",message:"The key is not one a data host serves."};return fS(rd(iS,e.options?.env),async(n)=>{let s=await dS(e,t,r,"HEAD",!1,n);if(s.kind==="failed")return{state:"unknown",message:s.message};let{status:o}=s.response;if(await s.response.body?.cancel().catch(()=>{}),o===200)return{state:"present"};if(o===404)return{state:"absent"};return{state:"unknown",message:lS(o,!1)}})}class gc extends Error{constructor(e){super(e);this.name="ProtocolAbort"}}async function pS(e,t){let r=e.lines[Symbol.asyncIterator](),n=[],s=null,o=null,i=async()=>{let d=n.shift();if(d!==void 0)return d;let l=await r.next();return l.done?null:l.value},a=async(d)=>{await e.send(`GETCONFIG ${d}`);while(!0){let l=await r.next();if(l.done)throw new gc("git-annex closed the connection");let p=l.value;if(p==="VALUE"||p.startsWith("VALUE ")){let f=p.slice(5).trimStart();return f===""?void 0:f}if(p.startsWith("ERROR"))throw new gc(p);n.push(p)}},c=async()=>{let d=await a("host"),l=await a("dataset");return f9(d,l,t.options)},u=async(d,l)=>{if(!s||!o){await e.send(`TRANSFER-FAILURE RETRIEVE ${It(d)} The remote has not been prepared.`);return}let p=Promise.resolve(),f=await h9(s,d,o,l,(h)=>{p=p.then(()=>e.send(`PROGRESS ${h}`))});if(await p,f.ok)await e.send(`TRANSFER-SUCCESS RETRIEVE ${d}`);else await e.send(`TRANSFER-FAILURE RETRIEVE ${It(d)} ${It(f.message)}`)};await e.send("VERSION 1");while(!0){let d=await i();if(d===null)return 0;if(d.trim()==="")continue;let[l,...p]=oS(d,1),f=p[0]??"";try{switch(l){case"EXTENSIONS":await e.send("EXTENSIONS");break;case"INITREMOTE":{let h=await c();await e.send(h.ok?"INITREMOTE-SUCCESS":`INITREMOTE-FAILURE ${It(h.message)}`);break}case"PREPARE":{let h=await c();if(!h.ok){s=null,await e.send(`PREPARE-FAILURE ${It(h.message)}`);break}let m=t.loadApiKey();if(!m){s=null,await e.send("PREPARE-FAILURE No NEMAR API key is stored. Run 'nemar auth login' first.");break}s=h.settings,o=m,await e.send("PREPARE-SUCCESS");break}case"LISTCONFIGS":await e.send("CONFIG host The https origin of the NEMAR data host"),await e.send("CONFIG dataset The dataset id on that host"),await e.send("CONFIGEND");break;case"GETCOST":await e.send("COST 200");break;case"GETAVAILABILITY":await e.send("AVAILABILITY GLOBAL");break;case"GETINFO":if(s)await e.send("INFOFIELD host"),await e.send(`INFOVALUE ${s.origin}`),await e.send("INFOFIELD dataset"),await e.send(`INFOVALUE ${s.dataset}`);await e.send("INFOEND");break;case"EXPORTSUPPORTED":await e.send("EXPORTSUPPORTED-FAILURE");break;case"IMPORTSUPPORTED":await e.send("IMPORTSUPPORTED-FAILURE");break;case"WHEREIS":await e.send("WHEREIS-FAILURE");break;case"CLAIMURL":await e.send("CLAIMURL-FAILURE");break;case"CHECKURL":await e.send("CHECKURL-FAILURE");break;case"TRANSFER":{let[h,m,...y]=oS(f,2);if(h==="STORE")await e.send(`TRANSFER-FAILURE STORE ${It(m??"")} This remote is read-only for now.`);else if(h==="RETRIEVE"&&m&&y[0])await u(m,y[0]);else await e.send("UNSUPPORTED-REQUEST");break}case"CHECKPRESENT":{if(!f){await e.send("UNSUPPORTED-REQUEST");break}if(!s||!o){await e.send(`CHECKPRESENT-UNKNOWN ${It(f)} The remote has not been prepared.`);break}let h=await m9(s,f,o);if(h.state==="present")await e.send(`CHECKPRESENT-SUCCESS ${f}`);else if(h.state==="absent")await e.send(`CHECKPRESENT-FAILURE ${f}`);else await e.send(`CHECKPRESENT-UNKNOWN ${It(f)} ${h.message}`);break}case"REMOVE":await e.send(`REMOVE-FAILURE ${It(f)} This remote is read-only for now.`);break;case"ERROR":return 1;case"VALUE":break;default:await e.send("UNSUPPORTED-REQUEST")}}catch(h){if(h instanceof gc)return 1;throw h}}}function oS(e,t){let r=[],n=e;for(let s=0;s<t;s++){let o=n.indexOf(" ");if(o<0)break;r.push(n.slice(0,o)),n=n.slice(o+1)}return r.push(n),r}async function*g9(){let e=new TextDecoder,t="";for await(let r of Bun.stdin.stream()){t+=e.decode(r,{stream:!0});let n=t.indexOf(`
37
+ `)}var Kb=!1;var Bb=F(()=>{Ul()});function Wb(){if(process.env.TEST_API_URL)return process.env.TEST_API_URL;if(td)return ed;return hn().apiUrl||ed}async function U6(e,t={},r=!1,n){let s=`${Wb()}${e}`,o={"Content-Type":"application/json","X-CLI-Version":ac,...t.headers};if(r){let p=hn();if(!p.apiKey&&r===!0)throw new fr(401,"Not authenticated. Run 'nemar auth login' first.");if(p.apiKey)o.Authorization=`Bearer ${p.apiKey}`}let i=t.method||"GET",a=typeof t.body==="string"?t.body:void 0,c=Date.now(),u;try{u=await fetch(s,{...t,headers:o})}catch(p){if(lc())dc({method:i,url:s,status:null,durationMs:Date.now()-c,requestHeaders:o,requestBody:a,error:p instanceof Error?p.message:String(p)});throw new fr(0,`Network error: Could not connect to ${Wb()}`,{originalError:p instanceof Error?p.message:String(p)})}let d;try{d=await u.text()}catch(p){if(lc())dc({method:i,url:s,status:u.status,durationMs:Date.now()-c,requestHeaders:o,requestBody:a,error:p instanceof Error?p.message:String(p)});throw new fr(0,"Failed to read response body",{httpStatus:u.status,originalError:p instanceof Error?p.message:String(p)})}if(lc())dc({method:i,url:s,status:u.status,durationMs:Date.now()-c,requestHeaders:o,requestBody:a,responseBody:d});let l;try{l=JSON.parse(d)}catch{throw new fr(u.status,`Invalid response from server (status ${u.status})`)}if(!u.ok){if(u.status===503&&(l.mode==="read-only"||l.mode==="full")){let xt=typeof l.message==="string"?l.message:"NEMAR is in maintenance mode. Please retry shortly.",hr=typeof l.eta==="string"?l.eta:null,et=new Il(l.mode,xt,hr,l.details);throw Hb(et),et}let p=typeof l.block_reason==="string",f=Array.isArray(l.missing)?l.missing.filter((xt)=>typeof xt==="string"):void 0,h=typeof l.error==="string"&&(eb.includes(l.error)||Lb.includes(l.error)),m=typeof l.error==="string"&&(qb.options.includes(l.error)||Db.includes(l.error)),y=typeof l.error==="string"&&Jw.includes(l.error),_=typeof l.error==="string"&&Ib.includes(l.error),O=typeof l.error==="string"&&Vb.includes(l.error),T=typeof l.error==="string"&&Fb.includes(l.error),M=typeof l.error==="string"&&zb.includes(l.error),_e=p||T||M||h||m||y||_||O||f!==void 0&&typeof l.error==="string"&&Zw.includes(l.error)?l.message||l.error:l.error||l.message;if(u.status===404&&l.error==="Not Found"&&typeof l.message==="string")_e=`${l.message}. This NEMAR backend does not support this command yet.`;let ve=new fr(u.status,_e||"Request failed",l.details,typeof l.step==="string"?l.step:void 0,p?l.block_reason:void 0,f);if(typeof l.error==="string")ve.code=l.error;if(typeof l.reason==="string")ve.reason=l.reason;throw ve.rawBody=l,ve}if(n){let p=n.safeParse(l);if(!p.success)throw new fr(u.status,`Response for ${e} did not match the expected NEMAR contract`,{issues:p.error.issues});return p.data}return l}var ed="https://nemar-api-dev.sccn-org.workers.dev",td;var Yb=F(()=>{jb();Mb();Ub();Gb();nc();fc();Yl();Bb();Gl();Cl();td=ed.includes("workers.dev")});fc();import{open as c9,rm as u9}from"fs/promises";Yb();var Xb="NEMAR_DATA_HOSTS",t9="NEMAR_DATA_HOSTS_ONLY",r9="https://private.nemar.org",n9="https://private-test.nemar.org",s9=/^[a-z]{2,3}[0-9]{6}$/;function Jb(e){return s9.test(e)}function o9(e){return e}function Qb(e){return e==="127.0.0.1"||e==="localhost"||e==="[::1]"}function Zb(e){let t=e.trim();if(t===""||/[?#@]/.test(t))return null;let r;try{r=new URL(t)}catch{return null}if(r.username!==""||r.password!=="")return null;if(r.pathname!=="/")return null;if(r.protocol==="https:")return r.origin;if(r.protocol==="http:"&&Qb(r.hostname))return r.origin;return null}function eS(e){let t=[],r=[];for(let n of(e??"").split(",")){let s=n.trim();if(s==="")continue;let o=Zb(s);if(o===null)r.push(s);else if(!t.includes(o))t.push(o)}return{origins:t,rejected:r}}function tS(e){return e.env??process.env}function i9(e={}){let t=tS(e),r=e.isDevBuild??td,n=t[t9]==="1"?[]:[r?n9:r9],{origins:s}=eS(t[Xb]);return[...n,...s.filter((o)=>!n.includes(o))].map(o9)}function z6(e={}){return eS(tS(e)[Xb]).rejected}function hc(e,t={}){let r=Zb(e);if(r===null)return null;return i9(t).find((n)=>n===r)??null}function rS(e,t={}){return hc(e,t)!==null}function G6(e,t={}){let r;try{r=new URL(e)}catch{return null}if(r.username!==""||r.password!=="")return null;return hc(r.origin,t)}function nS(e,t){if(e.protocol==="https:")return!0;return e.protocol==="http:"&&Qb(e.hostname)&&new URL(t).protocol==="http:"}var a9="NEMAR_DATA_HOST_TIMEOUT_MS";function rd(e,t=process.env){let r=t[a9];if(r===void 0||!/^[0-9]+$/.test(r))return e;let n=Number(r);return n>0&&n<e?n:e}function nd(e){if(!(e instanceof Error))return"error";let t=e.code;return typeof t==="string"&&/^[A-Z][A-Z0-9_]+$/.test(t)?`${e.name} ${t}`:e.name}var sS=3,iS=60000,l9=262144,aS=255,cS=/^[A-Z0-9][A-Z0-9_]*-s([0-9]{1,16})(?:-S([0-9]{1,16})-C([0-9]{1,16}))?--[A-Za-z0-9._-]+$/;function uS(e){return e.length<=aS&&cS.test(e)}function d9(e){if(e.length>aS)return null;let t=cS.exec(e);if(!t||t[2]!==void 0)return null;let r=Number(t[1]);return Number.isSafeInteger(r)?r:null}function f9(e,t,r={}){if(!e)return{ok:!1,message:"The remote has no host setting."};if(!t)return{ok:!1,message:"The remote has no dataset setting."};if(!Jb(t))return{ok:!1,message:"The dataset setting is not a dataset id (two or three letters and six digits)."};let n=hc(e,r);if(n===null)return{ok:!1,message:`The host setting ${It(e)} is not an https origin on this CLI's list of data hosts. The remote's host setting is part of the repository, so it cannot add one.`};return{ok:!0,settings:{origin:n,dataset:t,options:r}}}function It(e,t=200){let r=e.replace(/[^\x20-\x7e]/g,"?");return r.length>t?`${r.slice(0,t)}...`:r}function p9(e,t){return new URL(`${e.origin}/o/${encodeURIComponent(e.dataset)}/${encodeURIComponent(t)}`)}function lS(e,t){if(t)return`The storage address was refused (status ${e}).`;if(e===401)return"The data host refused the API key. Run 'nemar auth login' to sign in again.";if(e===404)return"The data host has no such object, or this account has no access to the dataset.";if(e===429)return"The data host is limiting requests; try again shortly.";return`The data host answered status ${e}.`}async function dS(e,t,r,n,s,o){if(!rS(e.origin,e.options))return{kind:"failed",message:"The host is not on this CLI's list of data hosts."};let i=p9(e,t),a=!1;for(let c=0;;c++){let u={"Accept-Encoding":"identity"};if(i.origin===e.origin)u.Authorization=`Bearer ${r}`;let d;try{d=await fetch(i,{method:n,headers:u,redirect:"manual",signal:o})}catch(f){if(o.aborted)return{kind:"failed",message:"The request timed out."};return{kind:"failed",message:`Could not reach the host (${nd(f)}).`}}if(d.status<300||d.status>=400)return{kind:"response",response:d,redirected:a};if(await d.body?.cancel().catch(()=>{}),!s)return{kind:"response",response:d,redirected:a};if(c>=sS)return{kind:"failed",message:`More than ${sS} redirects.`};let l=d.headers.get("location");if(!l)return{kind:"failed",message:"A redirect named no address."};let p;try{p=new URL(l,i)}catch{return{kind:"failed",message:"A redirect named an address that is not a URL."}}if(!nS(p,e.origin))return{kind:"failed",message:"A redirect named an address that is not https."};i=p,a=!0}}async function fS(e,t){let r=new AbortController,n=setTimeout(()=>r.abort(),e),s=()=>{clearTimeout(n),n=setTimeout(()=>r.abort(),e)};try{return await t(r.signal,s)}finally{clearTimeout(n)}}async function h9(e,t,r,n,s){if(!uS(t))return{ok:!1,message:"The key is not one a data host serves."};let o=d9(t);return fS(rd(iS,e.options?.env),async(i,a)=>{let c=await dS(e,t,r,"GET",!0,i);if(c.kind==="failed")return{ok:!1,message:c.message};let{response:u,redirected:d}=c;if(u.status!==200||!u.body)return await u.body?.cancel().catch(()=>{}),{ok:!1,message:lS(u.status,d)};let l=u.headers.get("content-length");if(o!==null&&l!==null&&Number(l)!==o)return await u.body.cancel().catch(()=>{}),{ok:!1,message:`The object is ${It(l,20)} bytes but its key says ${o}.`};a();let p,f=0,h=0;try{p=await c9(n,"w");let m=u.body.getReader();while(!0){let{done:y,value:_}=await m.read();if(y)break;if(a(),f+=_.byteLength,o!==null&&f>o)throw await m.cancel().catch(()=>{}),new mc(`More bytes arrived than the key's ${o}.`);if(await p.write(_),f-h>=l9)h=f,s(f)}if(await p.close(),p=void 0,o!==null&&f!==o)throw new mc(`The object ended after ${f} bytes; its key says ${o}.`);if(f!==h)s(f);return{ok:!0,bytes:f}}catch(m){if(await p?.close().catch(()=>{}),await u9(n,{force:!0}).catch(()=>{}),m instanceof mc)return{ok:!1,message:m.message};if(i.aborted)return{ok:!1,message:"The transfer stalled and timed out."};return{ok:!1,message:`The transfer failed (${nd(m)}).`}}})}class mc extends Error{constructor(e){super(e);this.name="SizeError"}}async function m9(e,t,r){if(!uS(t))return{state:"unknown",message:"The key is not one a data host serves."};return fS(rd(iS,e.options?.env),async(n)=>{let s=await dS(e,t,r,"HEAD",!1,n);if(s.kind==="failed")return{state:"unknown",message:s.message};let{status:o}=s.response;if(await s.response.body?.cancel().catch(()=>{}),o===200)return{state:"present"};if(o===404)return{state:"absent"};return{state:"unknown",message:lS(o,!1)}})}class gc extends Error{constructor(e){super(e);this.name="ProtocolAbort"}}async function pS(e,t){let r=e.lines[Symbol.asyncIterator](),n=[],s=null,o=null,i=async()=>{let d=n.shift();if(d!==void 0)return d;let l=await r.next();return l.done?null:l.value},a=async(d)=>{await e.send(`GETCONFIG ${d}`);while(!0){let l=await r.next();if(l.done)throw new gc("git-annex closed the connection");let p=l.value;if(p==="VALUE"||p.startsWith("VALUE ")){let f=p.slice(5).trimStart();return f===""?void 0:f}if(p.startsWith("ERROR"))throw new gc(p);n.push(p)}},c=async()=>{let d=await a("host"),l=await a("dataset");return f9(d,l,t.options)},u=async(d,l)=>{if(!s||!o){await e.send(`TRANSFER-FAILURE RETRIEVE ${It(d)} The remote has not been prepared.`);return}let p=Promise.resolve(),f=await h9(s,d,o,l,(h)=>{p=p.then(()=>e.send(`PROGRESS ${h}`))});if(await p,f.ok)await e.send(`TRANSFER-SUCCESS RETRIEVE ${d}`);else await e.send(`TRANSFER-FAILURE RETRIEVE ${It(d)} ${It(f.message)}`)};await e.send("VERSION 1");while(!0){let d=await i();if(d===null)return 0;if(d.trim()==="")continue;let[l,...p]=oS(d,1),f=p[0]??"";try{switch(l){case"EXTENSIONS":await e.send("EXTENSIONS");break;case"INITREMOTE":{let h=await c();await e.send(h.ok?"INITREMOTE-SUCCESS":`INITREMOTE-FAILURE ${It(h.message)}`);break}case"PREPARE":{let h=await c();if(!h.ok){s=null,await e.send(`PREPARE-FAILURE ${It(h.message)}`);break}let m=t.loadApiKey();if(!m){s=null,await e.send("PREPARE-FAILURE No NEMAR API key is stored. Run 'nemar auth login' first.");break}s=h.settings,o=m,await e.send("PREPARE-SUCCESS");break}case"LISTCONFIGS":await e.send("CONFIG host The https origin of the NEMAR data host"),await e.send("CONFIG dataset The dataset id on that host"),await e.send("CONFIGEND");break;case"GETCOST":await e.send("COST 200");break;case"GETAVAILABILITY":await e.send("AVAILABILITY GLOBAL");break;case"GETINFO":if(s)await e.send("INFOFIELD host"),await e.send(`INFOVALUE ${s.origin}`),await e.send("INFOFIELD dataset"),await e.send(`INFOVALUE ${s.dataset}`);await e.send("INFOEND");break;case"EXPORTSUPPORTED":await e.send("EXPORTSUPPORTED-FAILURE");break;case"IMPORTSUPPORTED":await e.send("IMPORTSUPPORTED-FAILURE");break;case"WHEREIS":await e.send("WHEREIS-FAILURE");break;case"CLAIMURL":await e.send("CLAIMURL-FAILURE");break;case"CHECKURL":await e.send("CHECKURL-FAILURE");break;case"TRANSFER":{let[h,m,...y]=oS(f,2);if(h==="STORE")await e.send(`TRANSFER-FAILURE STORE ${It(m??"")} This remote is read-only for now.`);else if(h==="RETRIEVE"&&m&&y[0])await u(m,y[0]);else await e.send("UNSUPPORTED-REQUEST");break}case"CHECKPRESENT":{if(!f){await e.send("UNSUPPORTED-REQUEST");break}if(!s||!o){await e.send(`CHECKPRESENT-UNKNOWN ${It(f)} The remote has not been prepared.`);break}let h=await m9(s,f,o);if(h.state==="present")await e.send(`CHECKPRESENT-SUCCESS ${f}`);else if(h.state==="absent")await e.send(`CHECKPRESENT-FAILURE ${f}`);else await e.send(`CHECKPRESENT-UNKNOWN ${It(f)} ${h.message}`);break}case"REMOVE":await e.send(`REMOVE-FAILURE ${It(f)} This remote is read-only for now.`);break;case"ERROR":return 1;case"VALUE":break;default:await e.send("UNSUPPORTED-REQUEST")}}catch(h){if(h instanceof gc)return 1;throw h}}}function oS(e,t){let r=[],n=e;for(let s=0;s<t;s++){let o=n.indexOf(" ");if(o<0)break;r.push(n.slice(0,o)),n=n.slice(o+1)}return r.push(n),r}async function*g9(){let e=new TextDecoder,t="";for await(let r of Bun.stdin.stream()){t+=e.decode(r,{stream:!0});let n=t.indexOf(`
38
38
  `);while(n>=0)yield t.slice(0,n).replace(/\r$/,""),t=t.slice(n+1),n=t.indexOf(`
39
39
  `)}if(t+=e.decode(),t!=="")yield t}var sd=Bun.stdout.writer(),y9=await pS({lines:g9(),send:async(e)=>{sd.write(`${e}
40
40
  `),await sd.flush()}},{loadApiKey:()=>hn().apiKey||void 0});await sd.end();process.exit(y9);
package/dist/index.js CHANGED
@@ -99,18 +99,18 @@ ${t}`,vQe,EQe,SQe=(e,t,n)=>{let r=n===""?"":`with ${n.trim()}() `,o=xQe.bind(nul
99
99
  `)}var xM=!1;var{spawn:vwt}=globalThis.Bun;function bp(e,t=[]){let n=e.replace(Ewt,'("$1","<redacted>")');for(let r of t)if(r.length>=Swt)n=n.split(r).join("<redacted>");return n}function ZR(e){let t=["AWS_SESSION_TOKEN","AWS_SECRET_ACCESS_KEY","AWS_ACCESS_KEY_ID"],n=new Set;for(let r of[process.env,e??{}])for(let o of t){let s=r[o];if(typeof s==="string"&&s.length>0)n.add(s)}return[...n]}async function Ige(e,t){let n=e.getReader(),r=new TextDecoder,o="";while(!0){let{done:s,value:i}=await n.read();if(s)break;if(i.byteLength===0)continue;t(),o+=r.decode(i,{stream:!0})}return o+r.decode()}async function O(e,t={}){let n={...process.env,GIT_TERMINAL_PROMPT:"0",...t.env};for(let y of t.unsetEnv??[])delete n[y];let r=vwt({cmd:e,cwd:t.cwd,...t.stdin===void 0?{}:{stdin:new TextEncoder().encode(t.stdin)},stdout:"pipe",stderr:"pipe",env:n}),o=!1,s,i,a=performance.now(),c=()=>{if(i!==void 0)clearTimeout(i),i=void 0},l=()=>{if(!t.onInactivityWarning)return;c(),i=setTimeout(()=>{i=void 0;try{t.onInactivityWarning?.(performance.now()-a)}catch{console.error("Could not display subprocess inactivity warning; the child result is unaffected.")}},t.inactivityWarningAfterMs??kwt)};if(l(),t.timeout)s=setTimeout(()=>{o=!0,c(),r.kill()},t.timeout);let d=Gg()?[...ZR(n),...t.redact??[]]:[];if(Gg()){let y=t.cwd?` (cwd=${t.cwd})`:"";Gd(u.dim(bp(`$ ${e.join(" ")}${y}`,d)))}let f=()=>{a=performance.now(),l()},p,m,h,g=r.exited.then((y)=>(c(),y));try{[p,m,h]=await Promise.all([Ige(r.stdout,f),Ige(r.stderr,f),g])}finally{if(c(),s)clearTimeout(s)}if(Gg()){if(t.sensitiveOutput)Gd(u.dim("[sensitive subprocess output suppressed]"));else{if(p.trim())Gd(u.dim(bp(p.trimEnd(),d)));if(m.trim())Gd(u.yellow(bp(m.trimEnd(),d)))}Gd(u.dim(`(exit ${h})`))}if(o)return{stdout:p,stderr:m||`Command timed out after ${Math.round(t.timeout/1000)}s`,exitCode:h??1,timedOut:!0};return{stdout:p,stderr:m,exitCode:h,timedOut:!1}}var Ewt,Swt=8,kwt=120000;var Gt=z(()=>{We();Ewt=/\(\s*"((?:x-amz-)[^"]*|authorization|proxy-authorization)"\s*,\s*"[^"]*"\s*\)/gi});function $wt(){if(process.platform==="darwin")return"macos";if(process.platform==="win32")return"windows";return"linux"}function Fge(e,t=$wt()){return e.installInstructions[t]}function Dwt(e){let t=e.match(/(\d+\.\d+(?:\.\d+)?)/);return t?t[1]:void 0}function Awt(){let e=Number(process.env.TEST_PROBE_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:Cwt}async function Mge(e){try{let{exitCode:t,stdout:n,timedOut:r}=await O(e.cmd,{timeout:Awt()});if(r)return{available:!1,timedOut:!0};if(t!==0)return{available:!1};return{available:!0,version:Dwt(n)}}catch(t){let n=t instanceof Error?t.message:String(t);if(!n.includes("ENOENT")&&!n.includes("not found"))console.error(` Warning: ${e.name} check failed unexpectedly: ${n}`);return{available:!1}}}async function zw(){let e=Object.entries(Nge);return Promise.all(e.map(async([t,n])=>{let{available:r,version:o,timedOut:s}=await Mge(n);return{key:t,name:n.name,purpose:n.purpose,required:n.required,available:r,version:o,timedOut:s,installInstruction:Fge(n)}}))}async function jge(){let t=(await zw()).filter((n)=>n.required&&!n.available);if(t.length===0)return[];console.warn(`
100
100
  Heads up: some tools NEMAR needs for uploading/validating aren't installed yet:`);for(let n of t)console.warn(` - ${n.name} (${n.purpose})`),console.warn(` Install: ${n.installInstruction}`);return console.warn("Run `nemar doctor` anytime to re-check. You can finish signup without them.\n"),t}async function wp(e){let n=Rwt[e].map((i)=>Nge[i]).filter(Boolean),r=await Promise.all(n.map(async(i)=>{let a=await Mge(i);return{check:i,available:a.available,timedOut:a.timedOut}}));for(let i of r)if(i.timedOut&&i.check.required)console.warn(`Warning: ${i.check.name} did not respond to a version check in time; continuing anyway.`);let o=r.filter((i)=>!i.available&&!i.timedOut&&i.check.required).map((i)=>({tool:i.check.name,installInstruction:Fge(i.check)}));if(o.length===0)return;let s=[`
101
101
  Missing required tools:`];for(let i of o)s.push(` ${i.tool} not installed`),s.push(` Install: ${i.installInstruction}`);throw Error(s.join(`
102
- `))}var Nge,Rwt,Cwt=4000;var Vw=z(()=>{Gt();Nge={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)"}}},Rwt={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 qge;var Lge=z(()=>{qge={name:"nemar-cli",packageManager:"bun@1.4.3",version:"0.10.38-PR2280.9090eea",description:"CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",type:"module",main:"dist/index.js",bin:{nemar:"dist/index.js","git-annex-remote-nemar":"dist/git-annex-remote-nemar.js"},scripts:{dev:"bun run src/index.ts",build:"bun build src/index.ts src/git-annex-remote-nemar.ts --outdir dist --target bun --minify && sed '1s|#!/usr/bin/env node|#!/usr/bin/env bun|' dist/index.js > dist/index.js.tmp && mv dist/index.js.tmp dist/index.js",test:"bun test",lint:"biome check src/","lint:scrub":"biome check scripts/scrub shared/identifier-scrub.ts test/scrub","test:scrub":"bun test --preload ./test/scrub/helpers/temp-dirs-preload.ts --path-ignore-patterns='__run_every_scrub_suite__' test/scrub test/identifier-scan.test.ts test/identifier-scrub.test.ts test/identifier-dates.test.ts test/identifier-fleet.test.ts","migrations:d1-check":"bun run scripts/d1-migration-check.ts","zarr:geometry-check":"bun run backend/scripts/zarr-geometry-conformance.ts","lint:fix":"biome check --fix src/",format:"biome format --write src/",typecheck:"tsc --noEmit && tsc --noEmit -p backend","generate-openapi":"bun run scripts/generate-openapi.ts",prepublishOnly:"bun run build",prepare:"husky",postinstall:"bun scripts/postinstall-check.mjs",deploy:"wrangler deploy",preview:"wrangler dev"},keywords:["nemar","bids","neuroimaging","eeg","emg","datalad","cli"],author:"NEMAR Team",license:"CC-BY-NC-ND-4.0",repository:{type:"git",url:"git+https://github.com/nemarOrg/nemar-cli.git"},bugs:{url:"https://github.com/nemarOrg/nemar-cli/issues"},homepage:"https://docs.nemar.org",engines:{bun:">=1.0.0"},files:["dist","scripts/postinstall-check.mjs","scripts/recover-datasets.json","scripts/withdrawn-datasets.json","README.md","LICENSE"],dependencies:{chalk:"^5.3.0",commander:"^12.1.0",conf:"^13.0.1",inquirer:"^9.2.15",ora:"^8.0.1",semver:"^7.8.5",zod:"^3.23.8"},"lint-staged":{"src/**/*.{ts,tsx}":["biome check --fix"],"backend/src/**/*.{ts,tsx}":["biome check --fix"]},trustedDependencies:["@biomejs/biome"],devDependencies:{"@anthropic-ai/sdk":"^0.132.1","@asteasolutions/zod-to-openapi":"^7.3.4","@biomejs/biome":"1.9.4","@types/bun":"latest","@types/inquirer":"^9.0.7","@types/semver":"^7.8.0",ajv:"^8.20.0","ajv-formats":"^3.0.1",husky:"^9.1.7",jose:"6.2.12","lint-staged":"^16.3.2",oauth4webapi:"3.8.8","openid-client":"6.8.9",typescript:"^5.5.4",wrangler:"^4.70.0",yaml:"^2.8.4"}}});var Gs;var _p=z(()=>{Lge();Gs=qge.version});import{mkdirSync as Twt,readdirSync as Pwt,unlinkSync as Iwt,writeFileSync as Nwt}from"fs";import{join as vM}from"path";function Vge(){zg=!0}function jl(){return zg}function Wge(e,t=process.env){return e.includes("--debug")||t.NEMAR_DEBUG==="1"}function Kw(e){zge=e,In(`Step: ${e}`)}function Yo(){Hge=!0}function Kge(){return Hge}function ue(){if(Gge)return;SM=!0}function Jw(){SM=!1,Gge=!0}function Jge(){return SM}function In(e){if(zg)process.stderr.write(`[debug] ${e}
102
+ `))}var Nge,Rwt,Cwt=4000;var Vw=z(()=>{Gt();Nge={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)"}}},Rwt={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 qge;var Lge=z(()=>{qge={name:"nemar-cli",packageManager:"bun@1.4.3",version:"0.10.38-dev.4682",description:"CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",type:"module",main:"dist/index.js",bin:{nemar:"dist/index.js","git-annex-remote-nemar":"dist/git-annex-remote-nemar.js"},scripts:{dev:"bun run src/index.ts",build:"bun build src/index.ts src/git-annex-remote-nemar.ts --outdir dist --target bun --minify && sed '1s|#!/usr/bin/env node|#!/usr/bin/env bun|' dist/index.js > dist/index.js.tmp && mv dist/index.js.tmp dist/index.js",test:"bun test",lint:"biome check src/","lint:scrub":"biome check scripts/scrub shared/identifier-scrub.ts test/scrub","test:scrub":"bun test --preload ./test/scrub/helpers/temp-dirs-preload.ts --path-ignore-patterns='__run_every_scrub_suite__' test/scrub test/identifier-scan.test.ts test/identifier-scrub.test.ts test/identifier-dates.test.ts test/identifier-fleet.test.ts","migrations:d1-check":"bun run scripts/d1-migration-check.ts","zarr:geometry-check":"bun run backend/scripts/zarr-geometry-conformance.ts","lint:fix":"biome check --fix src/",format:"biome format --write src/",typecheck:"tsc --noEmit && tsc --noEmit -p backend","generate-openapi":"bun run scripts/generate-openapi.ts",prepublishOnly:"bun run build",prepare:"husky",postinstall:"bun scripts/postinstall-check.mjs",deploy:"wrangler deploy",preview:"wrangler dev"},keywords:["nemar","bids","neuroimaging","eeg","emg","datalad","cli"],author:"NEMAR Team",license:"CC-BY-NC-ND-4.0",repository:{type:"git",url:"git+https://github.com/nemarOrg/nemar-cli.git"},bugs:{url:"https://github.com/nemarOrg/nemar-cli/issues"},homepage:"https://docs.nemar.org",engines:{bun:">=1.0.0"},files:["dist","scripts/postinstall-check.mjs","scripts/recover-datasets.json","scripts/withdrawn-datasets.json","README.md","LICENSE"],dependencies:{chalk:"^5.3.0",commander:"^12.1.0",conf:"^13.0.1",inquirer:"^9.2.15",ora:"^8.0.1",semver:"^7.8.5",zod:"^3.23.8"},"lint-staged":{"src/**/*.{ts,tsx}":["biome check --fix"],"backend/src/**/*.{ts,tsx}":["biome check --fix"]},trustedDependencies:["@biomejs/biome"],devDependencies:{"@anthropic-ai/sdk":"^0.132.1","@asteasolutions/zod-to-openapi":"^7.3.4","@biomejs/biome":"1.9.4","@types/bun":"latest","@types/inquirer":"^9.0.7","@types/semver":"^7.8.0",ajv:"^8.20.0","ajv-formats":"^3.0.1",husky:"^9.1.7",jose:"6.2.12","lint-staged":"^16.3.2",oauth4webapi:"3.8.8","openid-client":"6.8.9",typescript:"^5.5.4",wrangler:"^4.70.0",yaml:"^2.8.4"}}});var Gs;var _p=z(()=>{Lge();Gs=qge.version});import{mkdirSync as Twt,readdirSync as Pwt,unlinkSync as Iwt,writeFileSync as Nwt}from"fs";import{join as vM}from"path";function Vge(){zg=!0}function jl(){return zg}function Wge(e,t=process.env){return e.includes("--debug")||t.NEMAR_DEBUG==="1"}function Kw(e){zge=e,In(`Step: ${e}`)}function Yo(){Hge=!0}function Kge(){return Hge}function ue(){if(Gge)return;SM=!0}function Jw(){SM=!1,Gge=!0}function Jge(){return SM}function In(e){if(zg)process.stderr.write(`[debug] ${e}
103
103
  `)}function Lwt(e){let t={};for(let[n,r]of Object.entries(e))t[n]=jwt.has(n.toLowerCase())?"[REDACTED]":r;return t}function Xge(e){let t=e.indexOf("@");if(t<=0)return"***";return`${e[0]}***${e.slice(t)}`}function EM(e,t,n=0){if(n>Uwt)return"[REDACTED: depth]";if(Array.isArray(t))return t.map((r)=>EM(e,r,n+1));if(t&&typeof t==="object"){let r={};for(let[o,s]of Object.entries(t))r[o]=EM(o,s,n+1);return r}if(typeof t==="string"){if(qwt.test(e))return"[REDACTED]";return t.replace(Yge,Xge)}return t}function kM(e){return e.replace(Bwt,"Bearer [REDACTED]").replace(Hwt,"[REDACTED_AWS_KEY]").replace(Gwt,"$1[REDACTED]").replace(zwt,"$1$2=[REDACTED]").replace(Yge,Xge)}function Vwt(e){return kM(e)}function Uge(e,t=Mwt){if(e===void 0)return;let n=e;try{let r=JSON.parse(e);n=JSON.stringify(EM("",r))}catch{}if(n=kM(n),Buffer.byteLength(n,"utf8")>t)n=`${Buffer.from(n,"utf8").subarray(0,t).toString("utf8")}... [truncated]`;return n}function n$(e){if(!zg)return;let t=Vwt(e.url);try{let n={...e,url:t,requestHeaders:e.requestHeaders?Lwt(e.requestHeaders):void 0,requestBody:Uge(e.requestBody),responseBody:Uge(e.responseBody)};t$.push(n),In(`${e.method} ${t} -> ${e.status??"ERROR"} (${e.durationMs}ms)`)}catch(n){let r=W(n);t$.push({method:e.method,url:t,status:e.status,durationMs:e.durationMs,note:`redaction failed: ${r}`}),In(`redaction failed for ${e.method} ${t}: ${r}`)}}async function Wwt(){let e=[];try{let t=process.versions.bun?`Bun ${process.versions.bun}`:`Node ${process.version}`;e.push(`CLI version: ${Gs}`),e.push(`OS/Arch: ${process.platform}/${process.arch}`),e.push(`Runtime: ${t}`)}catch(t){e.push(`(could not read CLI/OS/runtime info: ${W(t)})`)}e.push(""),e.push("Active account:");try{let t=Yt();if(t.apiKey){if(t.username)e.push(` Username: ${t.username}`);if(e.push(` API URL: ${t.apiUrl}`),t.role)e.push(` Role: ${t.role}`);e.push(` Sandbox completed: ${!!t.sandboxCompleted}`)}else e.push(" (not authenticated)")}catch(t){e.push(` (could not read account config: ${W(t)})`)}e.push(""),e.push("External tools:");try{let t=await zw();for(let n of t){let r=n.available?n.version??"installed":n.timedOut?"(timed out)":"not installed";e.push(` ${n.name}: ${r}`)}}catch(t){e.push(` (could not probe external tools: ${W(t)})`)}return e}async function RM(){return(await Wwt()).join(`
104
104
  `)}async function Qge(){if(!zg||e$!==void 0)return;try{e$=await RM()}catch(e){let t=W(e);e$=`(could not build environment report: ${t})`,In(`environment snapshot failed: ${t}`)}}function Zge(e){if(Bge.has(e))return{flag:e};for(let t of Bge){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 Kwt(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n],o=Zge(r);if(!o){t.push(r);continue}if(o.kind==="long-eq")t.push(`${o.flag}=[REDACTED]`);else if(o.kind==="short-attached")t.push(`${o.flag}[REDACTED]`);else if(t.push(r),n+1<e.length)t.push("[REDACTED]"),n++}return t}function Jwt(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n],o=Zge(r);if(!o){t.push(r);continue}if(!o.kind&&n+1<e.length)n++}return t}function Ywt(e){let t=[];for(let r of Jwt(e)){if(r.startsWith("-"))continue;if(t.push(r),t.length===2)break}return(t.length>0?t.join("-"):"nemar").replace(/[^a-zA-Z0-9_-]/g,"_")}function Xwt(e,t){let n=[];if(n.push("NEMAR CLI Debug Log"),n.push(`Generated: ${new Date().toISOString()}`),n.push(`Command: nemar ${kM(Kwt(e).join(" "))}`),n.push(""),n.push(e$??"(environment snapshot unavailable)"),n.push(""),n.push("HTTP requests:"),t$.length===0)n.push(" (none)");else t$.forEach((r,o)=>{if(n.push(` [${o+1}] ${r.method} ${r.url} -> ${r.status??"ERROR"} (${r.durationMs}ms)`),r.error)n.push(` Error: ${r.error}`);if(r.note)n.push(` Note: ${r.note}`);if(r.requestHeaders)n.push(` Request headers: ${JSON.stringify(r.requestHeaders)}`);if(r.requestBody)n.push(` Request body: ${r.requestBody}`);if(r.responseBody)n.push(` Response body: ${r.responseBody}`)});return n.push(""),n.push(`Failing step: ${zge??"(none recorded)"}`),n.push(`Exit code: ${t}`),`${n.join(`
105
105
  `)}
106
106
  `}function Qwt(e,t){let n;try{n=Pwt(e).filter((o)=>o.startsWith("nemar-")&&o.endsWith(".log"))}catch(o){if(o.code!=="ENOENT")In(`could not list ${e} for log rotation: ${W(o)}`);return}n.sort();let r=n.length-t;for(let o=0;o<r;o++)try{Iwt(vM(e,n[o]))}catch(s){if(s.code!=="ENOENT")In(`could not remove old log ${n[o]}: ${W(s)}`)}}function eye(){return Ww}function tye(e,t){if(!zg)return null;let n=vM(sr(),"logs");try{Twt(n,{recursive:!0})}catch(i){return Ww=W(i),In(`could not create log directory ${n}: ${Ww}`),null}let o=`nemar-${new Date().toISOString().replace(/[:.]/g,"-")}-${Ywt(e)}.log`,s=vM(n,o);try{Nwt(s,Xwt(e,t),"utf8")}catch(i){return Ww=W(i),In(`could not write log file ${s}: ${Ww}`),null}return Qwt(n,Fwt),s}var Fwt=10,Mwt=2048,zg=!1,Hge=!1,SM=!1,Gge=!1,zge,e$,t$,jwt,qwt,Yge,Uwt=32,Bwt,Hwt,Gwt,zwt,Bge,Ww;var _n=z(()=>{Ve();Pr();Vw();_p();t$=[];jwt=new Set(["authorization","cookie","set-cookie","x-api-key","x-approval-dispatch-token"]);qwt=/^(api[_-]?key|apikey|password|token|secret|access[_-]?key(_id)?|secret[_-]?access[_-]?key|session|session[_-]?token|authorization|ssh[_-]?key|private[_-]?key|device[_-]?code|dispatch[_-]?token|client[_-]?secret)$/i,Yge=/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g;Bwt=/Bearer\s+[A-Za-z0-9\-._~+/=]+/gi,Hwt=/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g,Gwt=/((?:aws_)?secret_access_key["']?\s*[:=]\s*["']?)[A-Za-z0-9/+=]{20,}/gi,zwt=/([?&])(X-Amz-Signature|X-Amz-Security-Token|X-Amz-Credential|Signature|AWSAccessKeyId)=[^&\s"']+/gi;Bge=new Set(["-k","--key","--password","--api-key"])});import{chmodSync as Zwt,copyFileSync as e_t,existsSync as $M,mkdirSync as t_t,statSync as n_t}from"fs";import{homedir as r$}from"os";import{join as Vg}from"path";function o_t(e){let t=e.trim().replace(/\/+$/,"");try{let n=new URL(t);return n.protocol=n.protocol.toLowerCase(),n.host=n.host.toLowerCase(),n.toString().replace(/\/+$/,"")}catch{return console.error(`[nemar] could not parse stored apiUrl ${JSON.stringify(e)}; leaving as-is`),t}}function sr(){return process.env.NEMAR_CONFIG_DIR||Vg(r$(),".config","nemar")}function i_t(e){if(process.env.NEMAR_CONFIG_DIR)return;let t=Vg(e,"config.json");if($M(t))return;let n=[];if(process.platform==="darwin")n.push(Vg(r$(),"Library","Preferences","nemar-nodejs","config.json"));if(process.platform==="win32"){let r=process.env.APPDATA||Vg(r$(),"AppData","Roaming");n.push(Vg(r,"nemar-nodejs","config.json"))}n.push(Vg(r$(),".config","nemar-nodejs","config.json"));for(let r of n)if($M(r))try{t_t(e,{recursive:!0}),e_t(r,t),console.error(`[nemar] Config migrated from ${r} to ${t}
107
107
  [nemar] You can safely remove the old file.`);return}catch(o){console.error(`[nemar] Failed to migrate config from ${r}:`,o,`
108
- [nemar] You can manually copy ${r} to ${t}`)}}function Ri(){let e=sr();if(Yw&&nye===e)return Yw;if(i_t(e),Yw=new QR({projectName:"nemar",configFileMode:DM,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}),nye=e,!rye.has(e))rye.add(e),a_t(Yw.path),l_t(),u_t();return Yw}function a_t(e){if(process.platform==="win32")return;if(!$M(e))return;try{if((n_t(e).mode&511)!==DM)Zwt(e,DM)}catch(t){console.error(`[nemar] could not secure config file permissions for ${e}:`,t)}}function l_t(){let e=Ri(),t=e.get("accounts");if(t&&Object.keys(t).length>0)return;let n=e.get("apiKey"),r=e.get("username");if(!n&&!r)return;try{let o=r||"default",s={};for(let i of c_t){let a=e.get(i);if(a!==void 0)s[i]=a}e.store={activeAccount:o,accounts:{[o]:s}}}catch(o){console.error("Config migration failed (legacy config preserved):",o)}}function u_t(){let e=Ri(),t=e.store,n=t.accounts,r=!1;if(n)for(let[s,i]of Object.entries(n)){let a=i?.apiUrl;if(!a)continue;if(r_t.has(o_t(a)))n[s]={...i,apiUrl:Wg},console.error(`[nemar] migrated stored apiUrl for account "${s}": ${a} -> ${Wg}`),r=!0}let o=t.apiUrl;if(n&&Object.keys(n).length>0&&o!==void 0){let{apiUrl:s,...i}=t;try{e.store=i,console.error(`[nemar] removed stale top-level apiUrl from config (was: ${o})`),r=!1}catch(a){console.error("API URL cleanup failed (config file unchanged):",a)}}if(r)try{e.store={...e.store,accounts:n}}catch(s){console.error("API URL migration failed (config file unchanged):",s)}}function Xw(){return Ri().get("activeAccount")}function zd(){return Ri().get("accounts")||{}}function Yt(){let e={apiUrl:Wg},t=Xw();if(!t)return e;return zd()[t]||e}function Un(e,t){let n=Ri(),r=n.get("activeAccount")||"default",o=n.get("accounts")||{};if(!o[r])o[r]={apiUrl:Wg};o[r][e]=t,n.store={...n.store,accounts:o,activeAccount:r}}function Qw(e){let t=Xw();if(!t)return;let n=zd();if(n[t])delete n[t][e],Ri().set("accounts",n)}function oye(){let e=Ri(),t=Xw();if(!t){e.clear();return}let n=zd();delete n[t];let r=Object.keys(n);if(r.length>0)e.store={...e.store,accounts:n,activeAccount:r[0]};else e.clear()}function sye(){Ri().clear()}function Je(){return!!Yt().apiKey}function CM(){return Ri().path}function Zw(){let e=zd(),t=Xw();return Object.entries(e).map(([n,r])=>({key:n,username:r.username,email:r.email,githubUsername:r.githubUsername,active:n===t,keySource:r.keySource}))}function iye(e){return e.username?.trim()||e.email}function d_t(e){let t=e.trim().toLowerCase();if(!t)return;let n=Object.entries(zd()).filter(([,r])=>r.email&&r.email.toLowerCase()===t).map(([r])=>r);if(n.length>1){In(`findAccountKeyByEmail: ${n.length} accounts share email ${t}: ${n.join(", ")}`);return}return n[0]}function aye(e,t){let n=Ri(),r=zd(),o;if(r[e])o=e;else if(t.email)o=d_t(t.email);let s=o?r[o]:void 0,i={...s??{apiUrl:Wg},...t};if(o&&o!==e)delete r[o];return r[e]=i,n.store={...n.store,accounts:r,activeAccount:e},{key:e,previous:s}}function cye(e){let t=e.trim();if(!t)return"unchanged";let n=Ri(),r=Xw();if(!r||r===t)return"unchanged";let o=zd(),s=o[r];if(!s)return"unchanged";if(o[t])return"key_taken";return delete o[r],o[t]={...s,username:t},n.store={...n.store,accounts:o,activeAccount:t},"renamed"}function AM(e){let t=Ri(),n=zd();if(n[e])return t.store={...t.store,activeAccount:e},n[e];for(let[r,o]of Object.entries(n))if(o.githubUsername===e)return t.store={...t.store,activeAccount:r},o;return null}var Wg="https://api.nemar.org",DM=384,r_t,s_t,prn,Yw=null,nye=null,rye,c_t;var Pr=z(()=>{Tge();fr();Fh();_n();r_t=new Set(["https://api.osc.earth/nemar","https://nemar-api.neuromechanist.workers.dev","https://nemar-api-dev.shirazi-10f.workers.dev"]);s_t=N({field:w(),blocks:X(w()).optional(),set_on:X(w()).optional()}).passthrough(),prn=N({apiKey:w().optional(),apiUrl:w().url().default(Wg),username:w().optional(),email:w().email().optional(),githubUsername:w().optional(),sandboxCompleted:oe().optional(),sandboxDatasetId:w().optional(),dismissedNoticeIds:X(D()).optional(),serviceAccess:oe().optional(),profileGaps:X(s_t).optional(),orcidVerified:oe().optional(),role:w().optional(),accountKind:np.optional(),pendingEmailChange:w().email().optional()});rye=new Set;c_t=["apiKey","apiUrl","username","email","githubUsername","sandboxCompleted","sandboxDatasetId","dismissedNoticeIds"]});function o$(e){if(lye)return;lye=!0;let t=u.yellow("\u2500".repeat(60)),n=u.yellow.bold("[MAINTENANCE]"),r=u.dim(`mode: ${e.mode}`),o=e.eta?`
108
+ [nemar] You can manually copy ${r} to ${t}`)}}function Ri(){let e=sr();if(Yw&&nye===e)return Yw;if(i_t(e),Yw=new QR({projectName:"nemar",configFileMode:DM,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}),nye=e,!rye.has(e))rye.add(e),a_t(Yw.path),l_t(),u_t();return Yw}function a_t(e){if(process.platform==="win32")return;if(!$M(e))return;try{if((n_t(e).mode&511)!==DM)Zwt(e,DM)}catch(t){console.error(`[nemar] could not secure config file permissions for ${e}:`,t)}}function l_t(){let e=Ri(),t=e.get("accounts");if(t&&Object.keys(t).length>0)return;let n=e.get("apiKey"),r=e.get("username");if(!n&&!r)return;try{let o=r||"default",s={};for(let i of c_t){let a=e.get(i);if(a!==void 0)s[i]=a}e.store={activeAccount:o,accounts:{[o]:s}}}catch(o){console.error("Config migration failed (legacy config preserved):",o)}}function u_t(){let e=Ri(),t=e.store,n=t.accounts,r=!1;if(n)for(let[s,i]of Object.entries(n)){let a=i?.apiUrl;if(!a)continue;if(r_t.has(o_t(a)))n[s]={...i,apiUrl:Wg},console.error(`[nemar] migrated stored apiUrl for account "${s}": ${a} -> ${Wg}`),r=!0}let o=t.apiUrl;if(n&&Object.keys(n).length>0&&o!==void 0){let{apiUrl:s,...i}=t;try{e.store=i,console.error(`[nemar] removed stale top-level apiUrl from config (was: ${o})`),r=!1}catch(a){console.error("API URL cleanup failed (config file unchanged):",a)}}if(r)try{e.store={...e.store,accounts:n}}catch(s){console.error("API URL migration failed (config file unchanged):",s)}}function Xw(){return Ri().get("activeAccount")}function zd(){return Ri().get("accounts")||{}}function Yt(){let e={apiUrl:Wg},t=Xw();if(!t)return e;return zd()[t]||e}function Un(e,t){let n=Ri(),r=n.get("activeAccount")||"default",o=n.get("accounts")||{};if(!o[r])o[r]={apiUrl:Wg};o[r][e]=t,n.store={...n.store,accounts:o,activeAccount:r}}function Qw(e){let t=Xw();if(!t)return;let n=zd();if(n[t])delete n[t][e],Ri().set("accounts",n)}function oye(){let e=Ri(),t=Xw();if(!t){e.clear();return}let n=zd();delete n[t];let r=Object.keys(n);if(r.length>0)e.store={...e.store,accounts:n,activeAccount:r[0]};else e.clear()}function sye(){Ri().clear()}function Je(){return!!Yt().apiKey}function CM(){return Ri().path}function Zw(){let e=zd(),t=Xw();return Object.entries(e).map(([n,r])=>({key:n,username:r.username,email:r.email,githubUsername:r.githubUsername,active:n===t,keySource:r.keySource}))}function iye(e){return e.username?.trim()||e.email}function d_t(e){let t=e.trim().toLowerCase();if(!t)return;let n=Object.entries(zd()).filter(([,r])=>r.email&&r.email.toLowerCase()===t).map(([r])=>r);if(n.length>1){In(`findAccountKeyByEmail: ${n.length} accounts share email ${t}: ${n.join(", ")}`);return}return n[0]}function aye(e,t){let n=Ri(),r=zd(),o;if(r[e])o=e;else if(t.email)o=d_t(t.email);let s=o?r[o]:void 0,i={...s??{apiUrl:Wg},...t};if(o&&o!==e)delete r[o];return r[e]=i,n.store={...n.store,accounts:r,activeAccount:e},{key:e,previous:s}}function cye(e){let t=e.trim();if(!t)return"unchanged";let n=Ri(),r=Xw();if(!r||r===t)return"unchanged";let o=zd(),s=o[r];if(!s)return"unchanged";if(o[t])return"key_taken";return delete o[r],o[t]={...s,username:t},n.store={...n.store,accounts:o,activeAccount:t},"renamed"}function AM(e){let t=Ri(),n=zd();if(n[e])return t.store={...t.store,activeAccount:e},n[e];for(let[r,o]of Object.entries(n))if(o.githubUsername===e)return t.store={...t.store,activeAccount:r},o;return null}var Wg="https://nemar-api-dev.sccn-org.workers.dev",DM=384,r_t,s_t,prn,Yw=null,nye=null,rye,c_t;var Pr=z(()=>{Tge();fr();Fh();_n();r_t=new Set(["https://api.osc.earth/nemar","https://nemar-api.neuromechanist.workers.dev","https://nemar-api-dev.shirazi-10f.workers.dev"]);s_t=N({field:w(),blocks:X(w()).optional(),set_on:X(w()).optional()}).passthrough(),prn=N({apiKey:w().optional(),apiUrl:w().url().default(Wg),username:w().optional(),email:w().email().optional(),githubUsername:w().optional(),sandboxCompleted:oe().optional(),sandboxDatasetId:w().optional(),dismissedNoticeIds:X(D()).optional(),serviceAccess:oe().optional(),profileGaps:X(s_t).optional(),orcidVerified:oe().optional(),role:w().optional(),accountKind:np.optional(),pendingEmailChange:w().email().optional()});rye=new Set;c_t=["apiKey","apiUrl","username","email","githubUsername","sandboxCompleted","sandboxDatasetId","dismissedNoticeIds"]});function o$(e){if(lye)return;lye=!0;let t=u.yellow("\u2500".repeat(60)),n=u.yellow.bold("[MAINTENANCE]"),r=u.dim(`mode: ${e.mode}`),o=e.eta?`
109
109
  ${u.dim(`eta: ${e.eta}`)}`:"";process.stderr.write(`${t}
110
110
  ${n} ${e.message}
111
111
  ${r}${o}
112
112
  ${t}
113
- `)}var lye=!1;var OM=z(()=>{We()});function zr(){if(process.env.TEST_API_URL)return process.env.TEST_API_URL;if(xp)return TM;return Yt().apiUrl||TM}async function F(e,t={},n=!1,r){let o=`${zr()}${e}`,s={"Content-Type":"application/json","X-CLI-Version":Gs,...t.headers};if(n){let p=Yt();if(!p.apiKey&&n===!0)throw new U(401,"Not authenticated. Run 'nemar auth login' first.");if(p.apiKey)s.Authorization=`Bearer ${p.apiKey}`}let i=t.method||"GET",a=typeof t.body==="string"?t.body:void 0,c=Date.now(),l;try{l=await fetch(o,{...t,headers:s})}catch(p){if(jl())n$({method:i,url:o,status:null,durationMs:Date.now()-c,requestHeaders:s,requestBody:a,error:p instanceof Error?p.message:String(p)});throw new U(0,`Network error: Could not connect to ${zr()}`,{originalError:p instanceof Error?p.message:String(p)})}let d;try{d=await l.text()}catch(p){if(jl())n$({method:i,url:o,status:l.status,durationMs:Date.now()-c,requestHeaders:s,requestBody:a,error:p instanceof Error?p.message:String(p)});throw new U(0,"Failed to read response body",{httpStatus:l.status,originalError:p instanceof Error?p.message:String(p)})}if(jl())n$({method:i,url:o,status:l.status,durationMs:Date.now()-c,requestHeaders:s,requestBody:a,responseBody:d});let f;try{f=JSON.parse(d)}catch{throw new U(l.status,`Invalid response from server (status ${l.status})`)}if(!l.ok){if(l.status===503&&(f.mode==="read-only"||f.mode==="full")){let H=typeof f.message==="string"?f.message:"NEMAR is in maintenance mode. Please retry shortly.",T=typeof f.eta==="string"?f.eta:null,L=new od(f.mode,H,T,f.details);throw o$(L),L}let p=typeof f.block_reason==="string",m=Array.isArray(f.missing)?f.missing.filter((H)=>typeof H==="string"):void 0,h=typeof f.error==="string"&&(one.includes(f.error)||vne.includes(f.error)),g=typeof f.error==="string"&&(ES.options.includes(f.error)||$ne.includes(f.error)),y=typeof f.error==="string"&&Qte.includes(f.error),b=typeof f.error==="string"&&sne.includes(f.error),x=typeof f.error==="string"&&bne.includes(f.error),v=typeof f.error==="string"&&yne.includes(f.error),S=typeof f.error==="string"&&wne.includes(f.error),A=p||v||S||h||g||y||b||x||m!==void 0&&typeof f.error==="string"&&rne.includes(f.error)?f.message||f.error:f.error||f.message;if(l.status===404&&f.error==="Not Found"&&typeof f.message==="string")A=`${f.message}. This NEMAR backend does not support this command yet.`;let I=new U(l.status,A||"Request failed",f.details,typeof f.step==="string"?f.step:void 0,p?f.block_reason:void 0,m);if(typeof f.error==="string")I.code=f.error;if(typeof f.reason==="string")I.reason=f.reason;throw I.rawBody=f,I}if(r){let p=r.safeParse(f);if(!p.success)throw new U(l.status,`Response for ${e} did not match the expected NEMAR contract`,{issues:p.error.issues});return p.data}return f}var TM="https://api.nemar.org",xp;var wr=z(()=>{Y0();RS();$I();jh();Fh();Pr();_n();OM();_p();Ve();xp=TM.includes("workers.dev")});async function Kg(e,t={}){return F(`/datasets/${e}/publish/request`,t.anonymous?{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({anonymous:!0})}:{method:"POST"},!0)}async function Jg(e){return F(`/datasets/${e}/publish/status`,{},!0)}async function fye(e){return F(`/datasets/${e}/publish/resend`,{method:"POST"},!0)}async function pye(e){return F(`/datasets/${e}/publish/withdraw`,{method:"POST"},!0)}async function vp(e={}){let{statuses:t,search:n}=typeof e==="string"?{statuses:e?[e]:[]}:e,r=await uye(t,n),o=r;if(t!==void 0&&t.length>1&&r.requests.length===0){let s=[];for(let a of new Set(t))s.push(await uye([a],n));let i=s.flatMap((a)=>a.requests).sort(mye);o={...r,requests:i,count:i.length}}return n?f_t(o,n):o}function mye(e,t){return e.requested_at<t.requested_at?1:e.requested_at>t.requested_at?-1:0}async function uye(e,t){let n=new URLSearchParams;if(e&&e.length>0)n.set("status",e.join(","));if(t)n.set("search",t);let r=n.size>0?`?${n}`:"";return F(`/admin/publish/requests${r}`,{},!0)}function f_t(e,t){let n=e.requests.filter((s)=>Xre(t,[s.dataset_id,s.requested_by_username,s.dataset_name])),r=(s)=>Qre(s.dataset_id,t)?0:1,o=[...n].sort((s,i)=>r(s)-r(i)||mye(s,i));return{...e,requests:o,count:o.length}}async function Yg(e,t,n){return F(`/admin/publish/${e}/deny`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:t,...n!==void 0?{request_id:n}:{}})},!0)}async function s$(e){return F(`/admin/publish/${e}/identifier-screen`,{method:"POST"},!0)}async function i$(e){return F(`/admin/publish/${e}/review`,{},!0)}async function hye(e){return F(`/admin/publish/${e}/review/start`,{method:"POST"},!0)}async function gye(e,t){let n={message:t};return F(`/admin/publish/${e}/comment`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},!0)}function Xg(e){if(!(e instanceof U))return;let t=e.rawBody;if(typeof t!=="object"||t===null||Array.isArray(t))return;let n=t.code;return typeof n==="string"?n:void 0}function p_t(e,t=[]){if(e){let n=Wa.indexOf(e);if(n>=0)return n+1}return Math.min(t.length+1,Wa.length)}function m_t(e){if(!(e instanceof U))return!1;if(e.statusCode===0)return!0;if(e.statusCode===429)return!0;if(e.statusCode>=500&&e.statusCode<600)return!0;if(e.statusCode===403&&/repository has been locked/i.test(e.message))return!0;return!1}function h_t(){let e=process.env.NEMAR_APPROVE_RETRY_DELAY_MS;if(e===void 0||!/^\d+$/.test(e))return XS;let t=Number(e);return Number.isSafeInteger(t)&&t<=XS?t:XS}async function Qg(e,t=!1,n=!1,r=!1,o,s,i,a,c){let d=h_t(),f,p,m=0,h=!1,g,y=t,b=[],x;function v(S,E,A,I){if(!s)return;s({step:S,stepIndex:p_t(S,E),stepTotal:Wa.length,s3LockLocked:A,s3LockTotal:I,s3LockResumed:S==="s3_lock"&&h?!0:void 0})}for(let S=1;S<=5;S++)try{let E,A=!0;do{if(E=await F(`/admin/publish/${e}/approve`,{method:"POST",headers:{"Content-Type":"application/json",...c?.dispatchToken?{[_ne]:c.dispatchToken}:{}},body:JSON.stringify({resume:A?y:!0,sandbox:n,s3_lock_continuation_token:f,s3_lock_total:p,skip_ci_check:r,...i!==void 0?{acknowledge_identifier_screen:i}:{},...a!==void 0?{[Kre]:a}:{},...c?.requestId!==void 0?{request_id:c.requestId}:{}})},!0),A=!1,E.step_results)b.push(...E.step_results);if(E.s3_lock_total!==void 0)p=E.s3_lock_total;if(E.s3_lock_batch_count!==void 0)m+=E.s3_lock_batch_count;let I=E.step??E.step_results?.[E.step_results.length-1]?.step;if(I&&(I!==g||I==="s3_lock"))v(I,E.steps_completed??[],I==="s3_lock"?m:void 0,I==="s3_lock"?p:void 0),g=I;if(E.hasMore&&E.s3_lock_continuation_token!==void 0)f=E.s3_lock_continuation_token;else break}while(E.hasMore);if(b.length>0)E.step_results=dye(b);return E}catch(E){if(x=E,S===5||!m_t(E)){if(E instanceof U&&b.length>0)E.stepResults=dye(b);throw E}let I=E;if(o?.({attempt:S,maxAttempts:5,delayMs:d,step:I.step,error:I.message}),await new Promise((H)=>setTimeout(H,d)),y=!0,f!==void 0)h=!0}throw x}function dye(e){let t=new Map;for(let n of e)t.set(n.step,n);return Array.from(t.values())}var ia=z(()=>{YS();jh();ZS();wr();Ve()});function l$(e){if(e.service_access===void 0||e.service_access===null)return"unknown";return e.service_access?"upload":"browse"}async function BM(e,t,n,r,o={}){let s=new URLSearchParams;if(e)s.set("status",e);if(t)s.set("role",t);if(n)s.set("awaiting_approval","1");if(r)s.set("kind",r);if(o.search!==void 0)s.set("q",o.search);if(o.includeDeleted)s.set("include_deleted","true");let i=s.toString()?`?${s.toString()}`:"";return F(`/admin/users${i}`,{},!0,tne)}async function u$(e,t=!1){return F(`/admin/users/by-id/${e}${t?"?include_deleted=true":""}`,{},!0,cne)}async function Rye(e,t){return F(`/admin/users/by-id/${e}`,{method:"PATCH",body:JSON.stringify(t)},!0,lne)}async function $ye(e){return F(`/admin/approve/${e}`,{method:"POST"},!0)}async function Dye(e){return F(`/admin/approve/by-id/${e}`,{method:"POST"},!0)}async function Cye(e){return F(`/admin/revoke/${e}`,{method:"POST"},!0)}async function Aye(e){return F(`/admin/revoke/by-id/${e}`,{method:"POST"},!0)}async function Oye(e){return F(`/admin/users/by-id/${e}/verify`,{method:"POST"},!0)}async function Tye(e,t){return F(`/admin/users/${e}/role`,{method:"POST",body:JSON.stringify({role:t})},!0)}async function Pye(e,t){return F(`/admin/users/${e}/kind`,{method:"POST",body:JSON.stringify({kind:t})},!0)}async function d$(e){return F(`/admin/users/${encodeURIComponent(e)}`,{},!0)}async function Iye(e,t){return F(`/admin/users/${e}/keys`,{method:"POST",body:JSON.stringify({name:t})},!0,kS)}async function Nye(e){return F(`/admin/users/${e}/keys`,{},!0,SS)}async function Fye(e,t){return F(`/admin/users/${e}/keys/${t}`,{method:"DELETE"},!0)}async function Mye(e){return F(`/datasets/${e}/publish`,{method:"POST"},!0)}async function jye(e){return F(`/admin/datasets/${e}/ci`,{},!0)}async function Ll(e){return F(`/admin/datasets/${e}/ci`,{method:"POST"},!0)}async function HM(e){return F(`/admin/datasets/${e}/ci/validate`,{method:"POST"},!0)}async function GM(e){return F(`/admin/datasets/${e}/ci/sync`,{method:"POST"},!0)}async function Lye(e,t){return F(`/admin/datasets/${e}/doi/concept`,{method:"POST",body:JSON.stringify(t)},!0)}async function n_(e){return F(`/admin/datasets/${e}/doi`,{},!0)}async function zM(e,t){return F(`/admin/datasets/${e}/doi/update`,{method:"POST",body:JSON.stringify(t)},!0)}async function qye(e,t){return F(`/admin/datasets/${e}/withdraw`,{method:"POST",body:JSON.stringify({reason:t.reason,dry_run:t.dryRun})},!0)}async function Uye(e,t){return F(`/admin/datasets/${e}/restore`,{method:"POST",body:JSON.stringify({dry_run:t.dryRun})},!0)}async function Bye(e,t){return F(`/admin/datasets/${e}/unpublish`,{method:"POST",body:JSON.stringify({reason:t.reason,dry_run:t.dryRun})},!0)}async function Hye(e){return F(`/admin/datasets/${e}/reset`,{method:"POST"},!0)}async function Gye(e,t=!1){return F(`/admin/datasets/${e}`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({force:t})},!0)}async function zye(e){return F("/admin/datasets/bulk-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dataset_ids:e})},!0)}async function Vye(e){return F("/admin/datasets/import",{method:"POST",body:JSON.stringify(e)},!0)}async function Wye(e){return F("/admin/datasets/exemplar",{method:"POST",body:JSON.stringify(e)},!0)}async function Kye(e){return F(`/admin/datasets/${e}/exemplar/remint-dois`,{method:"POST"},!0)}async function VM(e,t){let n=new URLSearchParams;if(e)n.set("status",e);if(t!==void 0)n.set("blocklisted",t?"1":"0");let r=n.toString();return F(`/admin/imports${r?`?${r}`:""}`,{},!0)}async function Jye(e){return F(`/admin/imports/${e}/rollback`,{method:"POST"},!0)}async function Yye(e){return F(`/admin/imports/${e}/retry`,{method:"POST"},!0)}async function WM(e){return F(`/admin/imports/${e}/verify`,{method:"POST"},!0)}async function Xye(e){return F("/admin/imports/dispatch-cooldown",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dataset_ids:e})},!0)}async function ty(e,t){return F(`/admin/datasets/${e}/reindex`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})},!0)}async function Qye(e,t){return F("/admin/datasets/reindex/bulk",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filter:e,...t??{}})},!0)}async function Zye(e){let t=e?.limit??15;return F(`/admin/datasets/hed-sweep?limit=${encodeURIComponent(String(t))}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function ebe(){return F("/admin/datasets/hed-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function tbe(e){let t=e?.limit??50;return F(`/admin/datasets/recording-stats-sweep?limit=${encodeURIComponent(String(t))}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function nbe(){return F("/admin/datasets/recording-stats-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function rbe(e){let t=e?.limit??15;return F(`/admin/datasets/signal-defaults-sweep?limit=${encodeURIComponent(String(t))}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function obe(){return F("/admin/datasets/signal-defaults-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function sbe(e){let t=e?.limit??15,n=new URLSearchParams({limit:String(t)});if(e?.olderThan!=null)n.set("older-than",String(e.olderThan));if(e?.before!=null)n.set("before",e.before);return F(`/admin/datasets/data-integrity-sweep?${n.toString()}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function ibe(){return F("/admin/datasets/data-integrity-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function abe(e,t){let n=t?.write?"":"?dry_run=1";return F(`/admin/datasets/${e}/availability-report${n}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function cbe(e){let t=e?.limit??30,n=new URLSearchParams({limit:String(t)});if(e?.missingOnly)n.set("missing-only","1");return F(`/admin/datasets/availability-report-sweep?${n.toString()}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function lbe(){return F("/admin/datasets/availability-report-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function ube(e){let t=new URLSearchParams;if(e?.prefix)t.set("prefix",e.prefix);if(e?.visibility)t.set("visibility",e.visibility);if(e?.limit)t.set("limit",String(e.limit));let n=t.toString()?`?${t.toString()}`:"";return F(`/admin/fleet/drift${n}`,{},!0)}async function ny(e,t){return F(`/admin/datasets/${e}/enforce`,{method:"POST",body:JSON.stringify({dry_run:t})},!0)}async function dbe(e){return F("/admin/datasets/enforce/bulk",{method:"POST",body:JSON.stringify({prefix:e.prefix,visibility:e.visibility,limit:e.limit,dry_run:e.dryRun})},!0)}async function fbe(e,t){return F(`/admin/datasets/${e}/review-ruleset`,{method:"POST",body:JSON.stringify({dry_run:t.dryRun,remove:t.remove})},!0)}async function pbe(e){return F("/admin/datasets/review-ruleset/bulk",{method:"POST",body:JSON.stringify({prefix:e.prefix,after:e.after,limit:e.limit,dry_run:e.dryRun,remove:e.remove})},!0)}async function mbe(e,t=!1){return F(`/admin/datasets/${e}/revalidate${t?"?force=true":""}`,{method:"POST"},!0)}async function hbe(e){let t=e?`?user=${encodeURIComponent(e)}`:"";return F(`/admin/email-preferences${t}`,{},!0)}async function gbe(e,t){let n=t?`?user=${encodeURIComponent(t)}`:"";return F(`/admin/email-preferences${n}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)},!0)}async function KM(e){return F("/admin/notify",{method:"POST",body:JSON.stringify(e)},!0)}async function ybe(e){return F(`/admin/notify/${e}`,{},!0)}async function bbe(){return F("/admin/summary/coverage",{},!0)}async function wbe(e,t,n){return F("/admin/manifest/dispatch",{method:"POST",body:JSON.stringify({dataset_id:e,version:t,skip_canary:n?.skipCanary??!1})},!0)}async function JM(e){return F("/admin/doctor/scan",{method:"POST",body:JSON.stringify({...e?.check&&{check:e.check},...e?.datasetId&&{dataset_id:e.datasetId}})},!0)}async function YM(e){return F("/admin/doctor/fix",{method:"POST",body:JSON.stringify({check:e.check,...e.datasetId&&{dataset_id:e.datasetId},...e.dryRun&&{dry_run:!0}})},!0)}async function _be(){return F("/admin/zarr-catalog/publish",{method:"POST"},!0)}async function xbe(e){return F("/admin/neurobagel/regenerate",{method:"POST",body:JSON.stringify(e)},!0)}async function vbe(){return F("/admin/neurobagel/status",{method:"GET"},!0)}async function Ebe(){return F("/admin/neurobagel/verify",{method:"POST",body:"{}"},!0)}async function Sbe(e){let t=new URLSearchParams;if(e?.limit!=null)t.set("limit",String(e.limit));let n=t.toString()?`?${t.toString()}`:"";return F(`/admin/datasets/zarr-fidelity-sweep${n}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function kbe(e){let t=new URLSearchParams;if(e?.execute)t.set("execute","1");if(e?.limit!=null)t.set("limit",String(e.limit));if(e?.after)t.set("after",e.after);let n=t.toString()?`?${t.toString()}`:"";try{return await F(`/admin/datasets/upstream-backfill${n}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}catch(r){let o=r instanceof U&&r.statusCode===502?r.rawBody:void 0;if(o&&typeof o==="object"&&"execute"in o&&"counts"in o)return{...o,ok:!1};throw r}}async function Rbe(e){let t=new URLSearchParams;if(e?.limit!=null)t.set("limit",String(e.limit));if(e?.after)t.set("after",e.after);if(e?.dataset)t.set("dataset",e.dataset);let n=t.toString()?`?${t.toString()}`:"";try{return await F(`/admin/upstream-status${n}`,{method:"GET"},!0)}catch(r){let o=r instanceof U&&r.statusCode===502?r.rawBody:void 0;if(o&&typeof o==="object"&&"rows"in o&&"counts"in o)return{...o,ok:!1};throw r}}async function $be(e){let t=new URLSearchParams;if(e?.limit!=null)t.set("limit",String(e.limit));if(e?.apply)t.set("apply","1");let n=t.toString()?`?${t.toString()}`:"";return F(`/admin/imports/issue-triage${n}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Dbe(e){let t=e?.apply?"?apply=1":"";return F(`/admin/imports/coverage-sweep${t}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Cbe(e){let t=e?.apply?"?apply=1":"";return F(`/admin/imports/weekly-summary${t}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Abe(e){return F("/admin/users/backfill-names",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apply:e?.apply??!1,...e?.limit!=null?{limit:e.limit}:{}})},!0)}async function Obe(e){return F("/admin/users/backfill-usernames",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apply:e?.apply??!1,...e?.limit!=null?{limit:e.limit}:{}})},!0)}async function Tbe(){return F("/admin/users/duplicates",{},!0,Ene)}async function Pbe(e){return F(`/admin/users/${e}/clear-identity-conflict`,{method:"POST"},!0,Sne)}async function Ibe(e){let t=new URLSearchParams;if(e?.limit!=null)t.set("limit",String(e.limit));let n=t.toString()?`?${t.toString()}`:"";return F(`/admin/datasets/anonymity-sweep${n}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Nbe(){return F("/admin/datasets/anonymity-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function r_(e){let t=new URLSearchParams;if(e.verdicts&&e.verdicts.length>0)t.set("verdict",e.verdicts.join(","));if(e.dataset)t.set("dataset",e.dataset);if(e.author)t.set("author",e.author);if(e.needsMe)t.set("needs_me","1");let n=t.toString()?`?${t.toString()}`:"";return F(`/admin/pr-reviews${n}`,{method:"GET"},!0)}async function ry(e,t,n){let r=n?`?head=${encodeURIComponent(n)}`:"";return F(`/admin/pr-reviews/${encodeURIComponent(e)}/${t}${r}`,{method:"GET"},!0)}async function XM(e,t,n={}){let r=n.redo?"?redo=1":"";return F(`/admin/pr-reviews/${encodeURIComponent(e)}/${t}/start${r}`,{method:"POST"},!0)}async function Fbe(e){return F(`/admin/pr-review-authors/${encodeURIComponent(e)}`,{method:"GET"},!0)}async function Mbe(e,t,n){return F(`/admin/pr-review-authors/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(n?{mode:t,reason:n}:{mode:t})},!0)}async function jbe(e){return F(`/admin/pr-review-authors/${encodeURIComponent(e)}`,{method:"DELETE"},!0)}async function Lbe(e,t,n,r){return F(`/admin/pr-reviews/${encodeURIComponent(e)}/${t}/allow`,{method:"POST",body:JSON.stringify({reason:n,...r?{head_sha:r}:{}})},!0)}async function ZM(e){let t=new URLSearchParams;for(let[r,o]of Object.entries(e))if(o!==void 0&&o!=="")t.set(r,String(o));let n=t.toString();return F(`/admin/mail/tickets${n?`?${n}`:""}`,{},!0)}async function e6(e){return F(`/admin/mail/tickets/${e}`,{},!0)}async function qbe(e,t,n){let r={text:t};return F(`/admin/mail/tickets/${e}/reply`,Wd(r,{"Idempotency-Key":n}),!0)}async function Ube(e,t,n){let r={text:t};return F(`/admin/mail/tickets/${e}/note`,Wd(r,{"Idempotency-Key":n}),!0)}async function Bbe(e,t){let n={user_id:t};return F(`/admin/mail/tickets/${e}/assign`,Wd(n),!0)}async function Hbe(e,t){return F(`/admin/mail/tickets/${e}/status`,Wd({status:t}),!0)}async function Gbe(e,t){let n={summary:t};return F(`/admin/mail/tickets/${e}/summary`,QM(n),!0)}async function zbe(e,t){let n=t?{reason:t}:{};return F(`/admin/mail/tickets/${e}/escalate`,Wd(n),!0)}async function Vbe(e,t){return F(`/admin/mail/tickets/${e}/spam`,Wd(t),!0)}async function Wbe(e={}){let t=new URLSearchParams;for(let[r,o]of Object.entries(e))if(o!==void 0&&o!=="")t.set(r,String(o));let n=t.toString();return F(`/admin/mail/blocklist${n?`?${n}`:""}`,{},!0)}async function Kbe(e){return F("/admin/mail/blocklist",Wd(e),!0)}async function Jbe(e){return F(`/admin/mail/blocklist/${e}`,{method:"DELETE"},!0)}async function Ybe(){return F("/admin/mail/queues",{},!0)}async function Xbe(e,t){return F(`/admin/mail/queues/${encodeURIComponent(e)}`,QM(t),!0)}async function Qbe(e){return F(`/admin/mail/availability${e===void 0?"":`/${e}`}`,{},!0)}async function t6(e,t){return F(`/admin/mail/availability${t===void 0?"":`/${t}`}`,QM(e),!0)}async function Zbe(e){return F("/admin/mail/reprocess",Wd({raw_key:e}),!0)}async function e0e(e){return(await F(`/admin/users/by-id/${e}`,{},!0)).user.username}var Wd=(e,t)=>({method:"POST",body:JSON.stringify(e),...t?{headers:t}:{}}),QM=(e)=>({method:"PUT",body:JSON.stringify(e)});var Ec=z(()=>{Y0();Yh();wr();Ve()});async function fo(e,t){return F(`/datasets/${e}/upload-credentials`,{method:"POST",body:JSON.stringify({duration_seconds:t})},!0)}async function n6(e,t){return F(`/datasets/${e}/download-credentials`,{method:"POST",body:JSON.stringify({duration_seconds:t})},!0)}async function n0e(e){return F(`/admin/datasets/${e}/files`,{},!0)}async function r0e(e){let t,n=0,r=[],o=!0;while(o){let s=await F(`/admin/datasets/${e}/s3-lock`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({continuation_token:t})},!0);if(n+=s.locked,s.failed?.length)r.push(...s.failed);if(o=s.hasMore,t=s.continuation_token,o&&!t)throw new U(500,"S3 lock paginated response missing continuation_token; aborting to avoid infinite loop")}return{locked:n,failed:r}}async function o0e(e,t){let n=0,r=[],o=[];for(let s=0;s<t.length;s+=t0e){let i=t.slice(s,s+t0e),a=await F(`/admin/datasets/${e}/s3-lock`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({objects:i})},!0);if(!Array.isArray(a.objects))throw new U(500,"The s3-lock route did not name the objects it locked.");if(n+=a.objects.length,o.push(...a.objects),a.failed?.length)r.push(...a.failed)}return{locked:n,failed:r,objects:o}}var t0e=100;var Sc=z(()=>{wr();Ve()});async function p$(e){return F(`/datasets/${e}/ci/status`,{},!0)}async function s0e(e){return F(`/datasets/${e}/manifest`,{},!0)}async function m$(e,t){return F(`/datasets/${e}/manifest/${t}`,{},!0)}function i0e(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 Kd(e={}){let t=new URLSearchParams;if(e.mine)t.set("mine","true");if(e.search)t.set("search",e.search);if(e.modality)t.set("modality",e.modality);if(e.author)t.set("author",e.author);if(e.task)t.set("task",e.task);if(e.license)t.set("license",e.license);if(e.hasDoi)t.set("has_doi","true");if(e.hasHed)t.set("has_hed","1");if(e.hasZarr)t.set("has_zarr","1");if(e.hasZarrVerified)t.set("has_zarr_verified","1");if(e.dataComplete)t.set("data_complete","1");if(e.recent)t.set("recent",String(e.recent));if(e.sort)t.set("sort",e.sort);if(e.limit!=null)t.set("limit",String(e.limit));if(e.offset!=null)t.set("offset",String(e.offset));if(e.owner)t.set("owner",e.owner);if(e.facets)for(let[o,s]of Object.entries(e.facets))t.set(o,s);if(e.includeUnknown)t.set("include_unknown","1");let n=t.toString()?`?${t.toString()}`:"",r=await F(`/datasets${n}`,{},e.mine?!0:"optional");return r.datasets=r.datasets.map(i0e),r}async function a0e(e){return F(`/datasets/resolve/${e}`,{},"optional")}async function c0e(){return F("/datasets/facets",{signal:AbortSignal.timeout(5000)},"optional",xS)}async function l0e(e,t={}){let n=new URLSearchParams({q:e});if(t.modality)n.set("modality",t.modality);if(t.limit)n.set("limit",String(t.limit));if(t.hasHed)n.set("has_hed","1");if(t.hasZarr)n.set("has_zarr","1");if(t.hasZarrVerified)n.set("has_zarr_verified","1");if(t.author)n.set("author",t.author);if(t.task)n.set("task",t.task);if(t.license)n.set("license",t.license);if(t.hasDoi)n.set("has_doi","true");if(t.dataComplete)n.set("data_complete","1");if(t.recent)n.set("recent",String(t.recent));if(t.facets)for(let[o,s]of Object.entries(t.facets))n.set(o,s);if(t.includeUnknown)n.set("include_unknown","1");return await F(`/datasets/search?${n.toString()}`,{},"optional",hne)}async function ir(e){let t=await F(`/datasets/${e}`,{},"optional");return i0e(t.dataset)}async function kp(e){return F(`/datasets/${e}/versions`,{},!0)}async function u0e(e){try{let t=await kp(e);if(!Array.isArray(t.versions))throw Error(`GET /datasets/${e}/versions answered without a versions list`);return t.versions.length>0}catch(t){if(t instanceof U&&t.statusCode===404&&!Qh(t))return!1;throw t}}async function h$(e){return F("/datasets",{method:"POST",body:JSON.stringify(e)},!0)}async function d0e(e,t){return F(`/datasets/${e}/attestation`,{method:"PUT",body:JSON.stringify(t)},!0)}async function g$(e){return F(`/datasets/${e}/finalize`,{method:"POST"},!0)}async function r6(e){return F(`/datasets/${e}/request-access`,{method:"POST"},!0)}async function f0e(e,t){let n=t?`?status=${t}`:"";return F(`/datasets/${e}/access-requests${n}`,{},!0)}async function p0e(e,t){return F(`/datasets/${e}/access-requests/${t}/approve`,{method:"POST"},!0)}async function m0e(e,t){return F(`/datasets/${e}/access-requests/${t}/deny`,{method:"POST"},!0)}async function h0e(e,t){return F(`/datasets/${e}/invite`,{method:"POST",body:JSON.stringify({username:t})},!0)}async function g0e(e){return F(`/datasets/${e}/collaborators`,{},!0)}async function y0e(e,t){return F(`/admin/datasets/${e}/enrichment`,{method:"POST",body:JSON.stringify(t)},!0)}var f$;var kc=z(()=>{Yh();wr();Ve();f$=/^\d{4}-\d{4}-\d{4}-\d{3}[\dX]$/});function B0e(e,t){return e.filter((n)=>n.visibility==="public").map((n)=>n.dataset_id).filter((n)=>n.startsWith("nm")||n.startsWith("on")).filter((n)=>n!=="nm099999"&&!ql.has(n)).filter((n)=>t.prefix?n.startsWith(t.prefix):!0).sort()}var ql;var _$=z(()=>{ql=new Set(["nm000103","nm000104","nm000105","nm000106","nm000107"])});function mo(e){return e.replace(H0e,G0e)}function G0e(e){if(e===`
113
+ `)}var lye=!1;var OM=z(()=>{We()});function zr(){if(process.env.TEST_API_URL)return process.env.TEST_API_URL;if(xp)return TM;return Yt().apiUrl||TM}async function F(e,t={},n=!1,r){let o=`${zr()}${e}`,s={"Content-Type":"application/json","X-CLI-Version":Gs,...t.headers};if(n){let p=Yt();if(!p.apiKey&&n===!0)throw new U(401,"Not authenticated. Run 'nemar auth login' first.");if(p.apiKey)s.Authorization=`Bearer ${p.apiKey}`}let i=t.method||"GET",a=typeof t.body==="string"?t.body:void 0,c=Date.now(),l;try{l=await fetch(o,{...t,headers:s})}catch(p){if(jl())n$({method:i,url:o,status:null,durationMs:Date.now()-c,requestHeaders:s,requestBody:a,error:p instanceof Error?p.message:String(p)});throw new U(0,`Network error: Could not connect to ${zr()}`,{originalError:p instanceof Error?p.message:String(p)})}let d;try{d=await l.text()}catch(p){if(jl())n$({method:i,url:o,status:l.status,durationMs:Date.now()-c,requestHeaders:s,requestBody:a,error:p instanceof Error?p.message:String(p)});throw new U(0,"Failed to read response body",{httpStatus:l.status,originalError:p instanceof Error?p.message:String(p)})}if(jl())n$({method:i,url:o,status:l.status,durationMs:Date.now()-c,requestHeaders:s,requestBody:a,responseBody:d});let f;try{f=JSON.parse(d)}catch{throw new U(l.status,`Invalid response from server (status ${l.status})`)}if(!l.ok){if(l.status===503&&(f.mode==="read-only"||f.mode==="full")){let H=typeof f.message==="string"?f.message:"NEMAR is in maintenance mode. Please retry shortly.",T=typeof f.eta==="string"?f.eta:null,L=new od(f.mode,H,T,f.details);throw o$(L),L}let p=typeof f.block_reason==="string",m=Array.isArray(f.missing)?f.missing.filter((H)=>typeof H==="string"):void 0,h=typeof f.error==="string"&&(one.includes(f.error)||vne.includes(f.error)),g=typeof f.error==="string"&&(ES.options.includes(f.error)||$ne.includes(f.error)),y=typeof f.error==="string"&&Qte.includes(f.error),b=typeof f.error==="string"&&sne.includes(f.error),x=typeof f.error==="string"&&bne.includes(f.error),v=typeof f.error==="string"&&yne.includes(f.error),S=typeof f.error==="string"&&wne.includes(f.error),A=p||v||S||h||g||y||b||x||m!==void 0&&typeof f.error==="string"&&rne.includes(f.error)?f.message||f.error:f.error||f.message;if(l.status===404&&f.error==="Not Found"&&typeof f.message==="string")A=`${f.message}. This NEMAR backend does not support this command yet.`;let I=new U(l.status,A||"Request failed",f.details,typeof f.step==="string"?f.step:void 0,p?f.block_reason:void 0,m);if(typeof f.error==="string")I.code=f.error;if(typeof f.reason==="string")I.reason=f.reason;throw I.rawBody=f,I}if(r){let p=r.safeParse(f);if(!p.success)throw new U(l.status,`Response for ${e} did not match the expected NEMAR contract`,{issues:p.error.issues});return p.data}return f}var TM="https://nemar-api-dev.sccn-org.workers.dev",xp;var wr=z(()=>{Y0();RS();$I();jh();Fh();Pr();_n();OM();_p();Ve();xp=TM.includes("workers.dev")});async function Kg(e,t={}){return F(`/datasets/${e}/publish/request`,t.anonymous?{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({anonymous:!0})}:{method:"POST"},!0)}async function Jg(e){return F(`/datasets/${e}/publish/status`,{},!0)}async function fye(e){return F(`/datasets/${e}/publish/resend`,{method:"POST"},!0)}async function pye(e){return F(`/datasets/${e}/publish/withdraw`,{method:"POST"},!0)}async function vp(e={}){let{statuses:t,search:n}=typeof e==="string"?{statuses:e?[e]:[]}:e,r=await uye(t,n),o=r;if(t!==void 0&&t.length>1&&r.requests.length===0){let s=[];for(let a of new Set(t))s.push(await uye([a],n));let i=s.flatMap((a)=>a.requests).sort(mye);o={...r,requests:i,count:i.length}}return n?f_t(o,n):o}function mye(e,t){return e.requested_at<t.requested_at?1:e.requested_at>t.requested_at?-1:0}async function uye(e,t){let n=new URLSearchParams;if(e&&e.length>0)n.set("status",e.join(","));if(t)n.set("search",t);let r=n.size>0?`?${n}`:"";return F(`/admin/publish/requests${r}`,{},!0)}function f_t(e,t){let n=e.requests.filter((s)=>Xre(t,[s.dataset_id,s.requested_by_username,s.dataset_name])),r=(s)=>Qre(s.dataset_id,t)?0:1,o=[...n].sort((s,i)=>r(s)-r(i)||mye(s,i));return{...e,requests:o,count:o.length}}async function Yg(e,t,n){return F(`/admin/publish/${e}/deny`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:t,...n!==void 0?{request_id:n}:{}})},!0)}async function s$(e){return F(`/admin/publish/${e}/identifier-screen`,{method:"POST"},!0)}async function i$(e){return F(`/admin/publish/${e}/review`,{},!0)}async function hye(e){return F(`/admin/publish/${e}/review/start`,{method:"POST"},!0)}async function gye(e,t){let n={message:t};return F(`/admin/publish/${e}/comment`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},!0)}function Xg(e){if(!(e instanceof U))return;let t=e.rawBody;if(typeof t!=="object"||t===null||Array.isArray(t))return;let n=t.code;return typeof n==="string"?n:void 0}function p_t(e,t=[]){if(e){let n=Wa.indexOf(e);if(n>=0)return n+1}return Math.min(t.length+1,Wa.length)}function m_t(e){if(!(e instanceof U))return!1;if(e.statusCode===0)return!0;if(e.statusCode===429)return!0;if(e.statusCode>=500&&e.statusCode<600)return!0;if(e.statusCode===403&&/repository has been locked/i.test(e.message))return!0;return!1}function h_t(){let e=process.env.NEMAR_APPROVE_RETRY_DELAY_MS;if(e===void 0||!/^\d+$/.test(e))return XS;let t=Number(e);return Number.isSafeInteger(t)&&t<=XS?t:XS}async function Qg(e,t=!1,n=!1,r=!1,o,s,i,a,c){let d=h_t(),f,p,m=0,h=!1,g,y=t,b=[],x;function v(S,E,A,I){if(!s)return;s({step:S,stepIndex:p_t(S,E),stepTotal:Wa.length,s3LockLocked:A,s3LockTotal:I,s3LockResumed:S==="s3_lock"&&h?!0:void 0})}for(let S=1;S<=5;S++)try{let E,A=!0;do{if(E=await F(`/admin/publish/${e}/approve`,{method:"POST",headers:{"Content-Type":"application/json",...c?.dispatchToken?{[_ne]:c.dispatchToken}:{}},body:JSON.stringify({resume:A?y:!0,sandbox:n,s3_lock_continuation_token:f,s3_lock_total:p,skip_ci_check:r,...i!==void 0?{acknowledge_identifier_screen:i}:{},...a!==void 0?{[Kre]:a}:{},...c?.requestId!==void 0?{request_id:c.requestId}:{}})},!0),A=!1,E.step_results)b.push(...E.step_results);if(E.s3_lock_total!==void 0)p=E.s3_lock_total;if(E.s3_lock_batch_count!==void 0)m+=E.s3_lock_batch_count;let I=E.step??E.step_results?.[E.step_results.length-1]?.step;if(I&&(I!==g||I==="s3_lock"))v(I,E.steps_completed??[],I==="s3_lock"?m:void 0,I==="s3_lock"?p:void 0),g=I;if(E.hasMore&&E.s3_lock_continuation_token!==void 0)f=E.s3_lock_continuation_token;else break}while(E.hasMore);if(b.length>0)E.step_results=dye(b);return E}catch(E){if(x=E,S===5||!m_t(E)){if(E instanceof U&&b.length>0)E.stepResults=dye(b);throw E}let I=E;if(o?.({attempt:S,maxAttempts:5,delayMs:d,step:I.step,error:I.message}),await new Promise((H)=>setTimeout(H,d)),y=!0,f!==void 0)h=!0}throw x}function dye(e){let t=new Map;for(let n of e)t.set(n.step,n);return Array.from(t.values())}var ia=z(()=>{YS();jh();ZS();wr();Ve()});function l$(e){if(e.service_access===void 0||e.service_access===null)return"unknown";return e.service_access?"upload":"browse"}async function BM(e,t,n,r,o={}){let s=new URLSearchParams;if(e)s.set("status",e);if(t)s.set("role",t);if(n)s.set("awaiting_approval","1");if(r)s.set("kind",r);if(o.search!==void 0)s.set("q",o.search);if(o.includeDeleted)s.set("include_deleted","true");let i=s.toString()?`?${s.toString()}`:"";return F(`/admin/users${i}`,{},!0,tne)}async function u$(e,t=!1){return F(`/admin/users/by-id/${e}${t?"?include_deleted=true":""}`,{},!0,cne)}async function Rye(e,t){return F(`/admin/users/by-id/${e}`,{method:"PATCH",body:JSON.stringify(t)},!0,lne)}async function $ye(e){return F(`/admin/approve/${e}`,{method:"POST"},!0)}async function Dye(e){return F(`/admin/approve/by-id/${e}`,{method:"POST"},!0)}async function Cye(e){return F(`/admin/revoke/${e}`,{method:"POST"},!0)}async function Aye(e){return F(`/admin/revoke/by-id/${e}`,{method:"POST"},!0)}async function Oye(e){return F(`/admin/users/by-id/${e}/verify`,{method:"POST"},!0)}async function Tye(e,t){return F(`/admin/users/${e}/role`,{method:"POST",body:JSON.stringify({role:t})},!0)}async function Pye(e,t){return F(`/admin/users/${e}/kind`,{method:"POST",body:JSON.stringify({kind:t})},!0)}async function d$(e){return F(`/admin/users/${encodeURIComponent(e)}`,{},!0)}async function Iye(e,t){return F(`/admin/users/${e}/keys`,{method:"POST",body:JSON.stringify({name:t})},!0,kS)}async function Nye(e){return F(`/admin/users/${e}/keys`,{},!0,SS)}async function Fye(e,t){return F(`/admin/users/${e}/keys/${t}`,{method:"DELETE"},!0)}async function Mye(e){return F(`/datasets/${e}/publish`,{method:"POST"},!0)}async function jye(e){return F(`/admin/datasets/${e}/ci`,{},!0)}async function Ll(e){return F(`/admin/datasets/${e}/ci`,{method:"POST"},!0)}async function HM(e){return F(`/admin/datasets/${e}/ci/validate`,{method:"POST"},!0)}async function GM(e){return F(`/admin/datasets/${e}/ci/sync`,{method:"POST"},!0)}async function Lye(e,t){return F(`/admin/datasets/${e}/doi/concept`,{method:"POST",body:JSON.stringify(t)},!0)}async function n_(e){return F(`/admin/datasets/${e}/doi`,{},!0)}async function zM(e,t){return F(`/admin/datasets/${e}/doi/update`,{method:"POST",body:JSON.stringify(t)},!0)}async function qye(e,t){return F(`/admin/datasets/${e}/withdraw`,{method:"POST",body:JSON.stringify({reason:t.reason,dry_run:t.dryRun})},!0)}async function Uye(e,t){return F(`/admin/datasets/${e}/restore`,{method:"POST",body:JSON.stringify({dry_run:t.dryRun})},!0)}async function Bye(e,t){return F(`/admin/datasets/${e}/unpublish`,{method:"POST",body:JSON.stringify({reason:t.reason,dry_run:t.dryRun})},!0)}async function Hye(e){return F(`/admin/datasets/${e}/reset`,{method:"POST"},!0)}async function Gye(e,t=!1){return F(`/admin/datasets/${e}`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({force:t})},!0)}async function zye(e){return F("/admin/datasets/bulk-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dataset_ids:e})},!0)}async function Vye(e){return F("/admin/datasets/import",{method:"POST",body:JSON.stringify(e)},!0)}async function Wye(e){return F("/admin/datasets/exemplar",{method:"POST",body:JSON.stringify(e)},!0)}async function Kye(e){return F(`/admin/datasets/${e}/exemplar/remint-dois`,{method:"POST"},!0)}async function VM(e,t){let n=new URLSearchParams;if(e)n.set("status",e);if(t!==void 0)n.set("blocklisted",t?"1":"0");let r=n.toString();return F(`/admin/imports${r?`?${r}`:""}`,{},!0)}async function Jye(e){return F(`/admin/imports/${e}/rollback`,{method:"POST"},!0)}async function Yye(e){return F(`/admin/imports/${e}/retry`,{method:"POST"},!0)}async function WM(e){return F(`/admin/imports/${e}/verify`,{method:"POST"},!0)}async function Xye(e){return F("/admin/imports/dispatch-cooldown",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dataset_ids:e})},!0)}async function ty(e,t){return F(`/admin/datasets/${e}/reindex`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})},!0)}async function Qye(e,t){return F("/admin/datasets/reindex/bulk",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filter:e,...t??{}})},!0)}async function Zye(e){let t=e?.limit??15;return F(`/admin/datasets/hed-sweep?limit=${encodeURIComponent(String(t))}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function ebe(){return F("/admin/datasets/hed-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function tbe(e){let t=e?.limit??50;return F(`/admin/datasets/recording-stats-sweep?limit=${encodeURIComponent(String(t))}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function nbe(){return F("/admin/datasets/recording-stats-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function rbe(e){let t=e?.limit??15;return F(`/admin/datasets/signal-defaults-sweep?limit=${encodeURIComponent(String(t))}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function obe(){return F("/admin/datasets/signal-defaults-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function sbe(e){let t=e?.limit??15,n=new URLSearchParams({limit:String(t)});if(e?.olderThan!=null)n.set("older-than",String(e.olderThan));if(e?.before!=null)n.set("before",e.before);return F(`/admin/datasets/data-integrity-sweep?${n.toString()}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function ibe(){return F("/admin/datasets/data-integrity-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function abe(e,t){let n=t?.write?"":"?dry_run=1";return F(`/admin/datasets/${e}/availability-report${n}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function cbe(e){let t=e?.limit??30,n=new URLSearchParams({limit:String(t)});if(e?.missingOnly)n.set("missing-only","1");return F(`/admin/datasets/availability-report-sweep?${n.toString()}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function lbe(){return F("/admin/datasets/availability-report-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function ube(e){let t=new URLSearchParams;if(e?.prefix)t.set("prefix",e.prefix);if(e?.visibility)t.set("visibility",e.visibility);if(e?.limit)t.set("limit",String(e.limit));let n=t.toString()?`?${t.toString()}`:"";return F(`/admin/fleet/drift${n}`,{},!0)}async function ny(e,t){return F(`/admin/datasets/${e}/enforce`,{method:"POST",body:JSON.stringify({dry_run:t})},!0)}async function dbe(e){return F("/admin/datasets/enforce/bulk",{method:"POST",body:JSON.stringify({prefix:e.prefix,visibility:e.visibility,limit:e.limit,dry_run:e.dryRun})},!0)}async function fbe(e,t){return F(`/admin/datasets/${e}/review-ruleset`,{method:"POST",body:JSON.stringify({dry_run:t.dryRun,remove:t.remove})},!0)}async function pbe(e){return F("/admin/datasets/review-ruleset/bulk",{method:"POST",body:JSON.stringify({prefix:e.prefix,after:e.after,limit:e.limit,dry_run:e.dryRun,remove:e.remove})},!0)}async function mbe(e,t=!1){return F(`/admin/datasets/${e}/revalidate${t?"?force=true":""}`,{method:"POST"},!0)}async function hbe(e){let t=e?`?user=${encodeURIComponent(e)}`:"";return F(`/admin/email-preferences${t}`,{},!0)}async function gbe(e,t){let n=t?`?user=${encodeURIComponent(t)}`:"";return F(`/admin/email-preferences${n}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)},!0)}async function KM(e){return F("/admin/notify",{method:"POST",body:JSON.stringify(e)},!0)}async function ybe(e){return F(`/admin/notify/${e}`,{},!0)}async function bbe(){return F("/admin/summary/coverage",{},!0)}async function wbe(e,t,n){return F("/admin/manifest/dispatch",{method:"POST",body:JSON.stringify({dataset_id:e,version:t,skip_canary:n?.skipCanary??!1})},!0)}async function JM(e){return F("/admin/doctor/scan",{method:"POST",body:JSON.stringify({...e?.check&&{check:e.check},...e?.datasetId&&{dataset_id:e.datasetId}})},!0)}async function YM(e){return F("/admin/doctor/fix",{method:"POST",body:JSON.stringify({check:e.check,...e.datasetId&&{dataset_id:e.datasetId},...e.dryRun&&{dry_run:!0}})},!0)}async function _be(){return F("/admin/zarr-catalog/publish",{method:"POST"},!0)}async function xbe(e){return F("/admin/neurobagel/regenerate",{method:"POST",body:JSON.stringify(e)},!0)}async function vbe(){return F("/admin/neurobagel/status",{method:"GET"},!0)}async function Ebe(){return F("/admin/neurobagel/verify",{method:"POST",body:"{}"},!0)}async function Sbe(e){let t=new URLSearchParams;if(e?.limit!=null)t.set("limit",String(e.limit));let n=t.toString()?`?${t.toString()}`:"";return F(`/admin/datasets/zarr-fidelity-sweep${n}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function kbe(e){let t=new URLSearchParams;if(e?.execute)t.set("execute","1");if(e?.limit!=null)t.set("limit",String(e.limit));if(e?.after)t.set("after",e.after);let n=t.toString()?`?${t.toString()}`:"";try{return await F(`/admin/datasets/upstream-backfill${n}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}catch(r){let o=r instanceof U&&r.statusCode===502?r.rawBody:void 0;if(o&&typeof o==="object"&&"execute"in o&&"counts"in o)return{...o,ok:!1};throw r}}async function Rbe(e){let t=new URLSearchParams;if(e?.limit!=null)t.set("limit",String(e.limit));if(e?.after)t.set("after",e.after);if(e?.dataset)t.set("dataset",e.dataset);let n=t.toString()?`?${t.toString()}`:"";try{return await F(`/admin/upstream-status${n}`,{method:"GET"},!0)}catch(r){let o=r instanceof U&&r.statusCode===502?r.rawBody:void 0;if(o&&typeof o==="object"&&"rows"in o&&"counts"in o)return{...o,ok:!1};throw r}}async function $be(e){let t=new URLSearchParams;if(e?.limit!=null)t.set("limit",String(e.limit));if(e?.apply)t.set("apply","1");let n=t.toString()?`?${t.toString()}`:"";return F(`/admin/imports/issue-triage${n}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Dbe(e){let t=e?.apply?"?apply=1":"";return F(`/admin/imports/coverage-sweep${t}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Cbe(e){let t=e?.apply?"?apply=1":"";return F(`/admin/imports/weekly-summary${t}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Abe(e){return F("/admin/users/backfill-names",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apply:e?.apply??!1,...e?.limit!=null?{limit:e.limit}:{}})},!0)}async function Obe(e){return F("/admin/users/backfill-usernames",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apply:e?.apply??!1,...e?.limit!=null?{limit:e.limit}:{}})},!0)}async function Tbe(){return F("/admin/users/duplicates",{},!0,Ene)}async function Pbe(e){return F(`/admin/users/${e}/clear-identity-conflict`,{method:"POST"},!0,Sne)}async function Ibe(e){let t=new URLSearchParams;if(e?.limit!=null)t.set("limit",String(e.limit));let n=t.toString()?`?${t.toString()}`:"";return F(`/admin/datasets/anonymity-sweep${n}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Nbe(){return F("/admin/datasets/anonymity-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function r_(e){let t=new URLSearchParams;if(e.verdicts&&e.verdicts.length>0)t.set("verdict",e.verdicts.join(","));if(e.dataset)t.set("dataset",e.dataset);if(e.author)t.set("author",e.author);if(e.needsMe)t.set("needs_me","1");let n=t.toString()?`?${t.toString()}`:"";return F(`/admin/pr-reviews${n}`,{method:"GET"},!0)}async function ry(e,t,n){let r=n?`?head=${encodeURIComponent(n)}`:"";return F(`/admin/pr-reviews/${encodeURIComponent(e)}/${t}${r}`,{method:"GET"},!0)}async function XM(e,t,n={}){let r=n.redo?"?redo=1":"";return F(`/admin/pr-reviews/${encodeURIComponent(e)}/${t}/start${r}`,{method:"POST"},!0)}async function Fbe(e){return F(`/admin/pr-review-authors/${encodeURIComponent(e)}`,{method:"GET"},!0)}async function Mbe(e,t,n){return F(`/admin/pr-review-authors/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(n?{mode:t,reason:n}:{mode:t})},!0)}async function jbe(e){return F(`/admin/pr-review-authors/${encodeURIComponent(e)}`,{method:"DELETE"},!0)}async function Lbe(e,t,n,r){return F(`/admin/pr-reviews/${encodeURIComponent(e)}/${t}/allow`,{method:"POST",body:JSON.stringify({reason:n,...r?{head_sha:r}:{}})},!0)}async function ZM(e){let t=new URLSearchParams;for(let[r,o]of Object.entries(e))if(o!==void 0&&o!=="")t.set(r,String(o));let n=t.toString();return F(`/admin/mail/tickets${n?`?${n}`:""}`,{},!0)}async function e6(e){return F(`/admin/mail/tickets/${e}`,{},!0)}async function qbe(e,t,n){let r={text:t};return F(`/admin/mail/tickets/${e}/reply`,Wd(r,{"Idempotency-Key":n}),!0)}async function Ube(e,t,n){let r={text:t};return F(`/admin/mail/tickets/${e}/note`,Wd(r,{"Idempotency-Key":n}),!0)}async function Bbe(e,t){let n={user_id:t};return F(`/admin/mail/tickets/${e}/assign`,Wd(n),!0)}async function Hbe(e,t){return F(`/admin/mail/tickets/${e}/status`,Wd({status:t}),!0)}async function Gbe(e,t){let n={summary:t};return F(`/admin/mail/tickets/${e}/summary`,QM(n),!0)}async function zbe(e,t){let n=t?{reason:t}:{};return F(`/admin/mail/tickets/${e}/escalate`,Wd(n),!0)}async function Vbe(e,t){return F(`/admin/mail/tickets/${e}/spam`,Wd(t),!0)}async function Wbe(e={}){let t=new URLSearchParams;for(let[r,o]of Object.entries(e))if(o!==void 0&&o!=="")t.set(r,String(o));let n=t.toString();return F(`/admin/mail/blocklist${n?`?${n}`:""}`,{},!0)}async function Kbe(e){return F("/admin/mail/blocklist",Wd(e),!0)}async function Jbe(e){return F(`/admin/mail/blocklist/${e}`,{method:"DELETE"},!0)}async function Ybe(){return F("/admin/mail/queues",{},!0)}async function Xbe(e,t){return F(`/admin/mail/queues/${encodeURIComponent(e)}`,QM(t),!0)}async function Qbe(e){return F(`/admin/mail/availability${e===void 0?"":`/${e}`}`,{},!0)}async function t6(e,t){return F(`/admin/mail/availability${t===void 0?"":`/${t}`}`,QM(e),!0)}async function Zbe(e){return F("/admin/mail/reprocess",Wd({raw_key:e}),!0)}async function e0e(e){return(await F(`/admin/users/by-id/${e}`,{},!0)).user.username}var Wd=(e,t)=>({method:"POST",body:JSON.stringify(e),...t?{headers:t}:{}}),QM=(e)=>({method:"PUT",body:JSON.stringify(e)});var Ec=z(()=>{Y0();Yh();wr();Ve()});async function fo(e,t){return F(`/datasets/${e}/upload-credentials`,{method:"POST",body:JSON.stringify({duration_seconds:t})},!0)}async function n6(e,t){return F(`/datasets/${e}/download-credentials`,{method:"POST",body:JSON.stringify({duration_seconds:t})},!0)}async function n0e(e){return F(`/admin/datasets/${e}/files`,{},!0)}async function r0e(e){let t,n=0,r=[],o=!0;while(o){let s=await F(`/admin/datasets/${e}/s3-lock`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({continuation_token:t})},!0);if(n+=s.locked,s.failed?.length)r.push(...s.failed);if(o=s.hasMore,t=s.continuation_token,o&&!t)throw new U(500,"S3 lock paginated response missing continuation_token; aborting to avoid infinite loop")}return{locked:n,failed:r}}async function o0e(e,t){let n=0,r=[],o=[];for(let s=0;s<t.length;s+=t0e){let i=t.slice(s,s+t0e),a=await F(`/admin/datasets/${e}/s3-lock`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({objects:i})},!0);if(!Array.isArray(a.objects))throw new U(500,"The s3-lock route did not name the objects it locked.");if(n+=a.objects.length,o.push(...a.objects),a.failed?.length)r.push(...a.failed)}return{locked:n,failed:r,objects:o}}var t0e=100;var Sc=z(()=>{wr();Ve()});async function p$(e){return F(`/datasets/${e}/ci/status`,{},!0)}async function s0e(e){return F(`/datasets/${e}/manifest`,{},!0)}async function m$(e,t){return F(`/datasets/${e}/manifest/${t}`,{},!0)}function i0e(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 Kd(e={}){let t=new URLSearchParams;if(e.mine)t.set("mine","true");if(e.search)t.set("search",e.search);if(e.modality)t.set("modality",e.modality);if(e.author)t.set("author",e.author);if(e.task)t.set("task",e.task);if(e.license)t.set("license",e.license);if(e.hasDoi)t.set("has_doi","true");if(e.hasHed)t.set("has_hed","1");if(e.hasZarr)t.set("has_zarr","1");if(e.hasZarrVerified)t.set("has_zarr_verified","1");if(e.dataComplete)t.set("data_complete","1");if(e.recent)t.set("recent",String(e.recent));if(e.sort)t.set("sort",e.sort);if(e.limit!=null)t.set("limit",String(e.limit));if(e.offset!=null)t.set("offset",String(e.offset));if(e.owner)t.set("owner",e.owner);if(e.facets)for(let[o,s]of Object.entries(e.facets))t.set(o,s);if(e.includeUnknown)t.set("include_unknown","1");let n=t.toString()?`?${t.toString()}`:"",r=await F(`/datasets${n}`,{},e.mine?!0:"optional");return r.datasets=r.datasets.map(i0e),r}async function a0e(e){return F(`/datasets/resolve/${e}`,{},"optional")}async function c0e(){return F("/datasets/facets",{signal:AbortSignal.timeout(5000)},"optional",xS)}async function l0e(e,t={}){let n=new URLSearchParams({q:e});if(t.modality)n.set("modality",t.modality);if(t.limit)n.set("limit",String(t.limit));if(t.hasHed)n.set("has_hed","1");if(t.hasZarr)n.set("has_zarr","1");if(t.hasZarrVerified)n.set("has_zarr_verified","1");if(t.author)n.set("author",t.author);if(t.task)n.set("task",t.task);if(t.license)n.set("license",t.license);if(t.hasDoi)n.set("has_doi","true");if(t.dataComplete)n.set("data_complete","1");if(t.recent)n.set("recent",String(t.recent));if(t.facets)for(let[o,s]of Object.entries(t.facets))n.set(o,s);if(t.includeUnknown)n.set("include_unknown","1");return await F(`/datasets/search?${n.toString()}`,{},"optional",hne)}async function ir(e){let t=await F(`/datasets/${e}`,{},"optional");return i0e(t.dataset)}async function kp(e){return F(`/datasets/${e}/versions`,{},!0)}async function u0e(e){try{let t=await kp(e);if(!Array.isArray(t.versions))throw Error(`GET /datasets/${e}/versions answered without a versions list`);return t.versions.length>0}catch(t){if(t instanceof U&&t.statusCode===404&&!Qh(t))return!1;throw t}}async function h$(e){return F("/datasets",{method:"POST",body:JSON.stringify(e)},!0)}async function d0e(e,t){return F(`/datasets/${e}/attestation`,{method:"PUT",body:JSON.stringify(t)},!0)}async function g$(e){return F(`/datasets/${e}/finalize`,{method:"POST"},!0)}async function r6(e){return F(`/datasets/${e}/request-access`,{method:"POST"},!0)}async function f0e(e,t){let n=t?`?status=${t}`:"";return F(`/datasets/${e}/access-requests${n}`,{},!0)}async function p0e(e,t){return F(`/datasets/${e}/access-requests/${t}/approve`,{method:"POST"},!0)}async function m0e(e,t){return F(`/datasets/${e}/access-requests/${t}/deny`,{method:"POST"},!0)}async function h0e(e,t){return F(`/datasets/${e}/invite`,{method:"POST",body:JSON.stringify({username:t})},!0)}async function g0e(e){return F(`/datasets/${e}/collaborators`,{},!0)}async function y0e(e,t){return F(`/admin/datasets/${e}/enrichment`,{method:"POST",body:JSON.stringify(t)},!0)}var f$;var kc=z(()=>{Yh();wr();Ve();f$=/^\d{4}-\d{4}-\d{4}-\d{3}[\dX]$/});function B0e(e,t){return e.filter((n)=>n.visibility==="public").map((n)=>n.dataset_id).filter((n)=>n.startsWith("nm")||n.startsWith("on")).filter((n)=>n!=="nm099999"&&!ql.has(n)).filter((n)=>t.prefix?n.startsWith(t.prefix):!0).sort()}var ql;var _$=z(()=>{ql=new Set(["nm000103","nm000104","nm000105","nm000106","nm000107"])});function mo(e){return e.replace(H0e,G0e)}function G0e(e){if(e===`
114
114
  `)return"\\n";if(e==="\r")return"\\r";if(e==="\t")return"\\t";let t=e.codePointAt(0)??0;return t<=255?`\\x${t.toString(16).padStart(2,"0")}`:t<=65535?`\\u${t.toString(16).padStart(4,"0")}`:`\\u{${t.toString(16)}}`}function o_(e){return e.replace(H0e,(t)=>t===`
115
115
  `||t==="\t"?t:G0e(t))}function x$(e,t=", "){return e.map(mo).join(t)}var H0e,Rc=(e)=>mo(e)===e;var Rp=z(()=>{H0e=/[\p{Cc}\p{Cf}\u2028\u2029\u034f\u115f\u1160\u3164\uffa0\ufe00-\ufe0f\u{e0100}-\u{e01ef}]/gu});async function $_t(){try{let{exitCode:e,stderr:t}=await O(["ssh","-T","-o","BatchMode=yes","-o","ConnectTimeout=5","git@github.com"]),n=t.includes("successfully authenticated");if(!n)console.warn("SSH test to github.com failed:",{exitCode:e,stderr:t.trim().slice(0,500)});return{works:n,error:n?void 0:t.trim().slice(0,500)}}catch(e){let t=e instanceof Error?e.message:String(e);return console.warn("SSH test exception:",t),{works:!1,error:t}}}async function $p(){try{let{stdout:e,exitCode:t,stderr:n}=await O(["gh","auth","token"],{sensitiveOutput:!0});if(t!==0)return console.warn("gh CLI returned non-zero exit code:",t),console.warn("stderr:",n),{token:null,error:`gh auth token failed: ${n.trim()||"unknown error"}`};if(!e.trim())return console.warn("gh auth token returned empty output"),{token:null,error:"gh CLI returned empty token"};return{token:e.trim()}}catch(e){let t=e instanceof Error?e.message:String(e);if(console.error("Failed to get GitHub token from gh CLI:",t),t.includes("ENOENT")||t.includes("not found"))return{token:null,error:"gh CLI not installed (command not found)"};return{token:null,error:`gh CLI error: ${t}`}}}async function v$(e){try{let{stdout:t,exitCode:n,stderr:r}=await O(["gh","api","user","--jq",".login"]);if(n!==0){if(r.includes("not logged in")||r.includes("auth login"))return{authenticated:!1,error:"gh CLI not authenticated. Run 'gh auth login' to authenticate."};return{authenticated:!1,error:`gh CLI error: ${r.trim()||"unknown error"}`}}let o=t.trim();if(!o)return{authenticated:!1,error:"gh CLI returned empty username"};if(e){let s=o.toLowerCase()===e.toLowerCase();return{authenticated:!0,username:o,matches:s,error:s?void 0:`gh CLI authenticated as '${o}', expected '${e}'`}}return{authenticated:!0,username:o}}catch(t){let n=t instanceof Error?t.message:String(t);if(n.includes("ENOENT")||n.includes("not found"))return{authenticated:!1,error:"gh CLI not installed. Install from https://cli.github.com/"};return{authenticated:!1,error:`Failed to verify gh CLI: ${n}`}}}async function E$(e){if(!/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/.test(e))return{accepted:!1,error:`Invalid repository format: ${e}`};let{stdout:t,exitCode:n,stderr:r}=await O(["gh","api","/user/repository_invitations"]);if(n!==0){if(r.includes("not logged in")||r.includes("auth login"))return{accepted:!1,error:"gh CLI not authenticated. Run 'gh auth login' to authenticate."};if(r.includes("API rate limit")||r.includes("403"))return{accepted:!1,error:"GitHub API rate limit exceeded. Please try again in a few minutes."};if(r.includes("ENOENT")||r.includes("not found"))return{accepted:!1,error:"gh CLI not installed. Install from https://cli.github.com/"};return{accepted:!1,error:`Failed to list invitations: ${r.trim()||"unknown error"}`}}let o=null;try{o=JSON.parse(t||"[]").find((l)=>l.repository.full_name===e)?.id??null}catch(a){let c=a instanceof Error?a.message:String(a);return console.error("Failed to parse GitHub invitations response:",c),console.error(" Raw response (first 500 chars):",(t||"").slice(0,500)),{accepted:!1,error:`Failed to parse GitHub API response: ${c}`}}if(!o){let{exitCode:a}=await O(["gh","api",`/repos/${e}`,"--silent"]);if(a===0)return{accepted:!0,alreadyCollaborator:!0};return{accepted:!1,error:`No pending invitation found for ${e}. You may need to accept it manually via GitHub.`}}let{exitCode:s,stderr:i}=await O(["gh","api","--method","PATCH",`/user/repository_invitations/${o}`]);if(s!==0)return{accepted:!1,error:`Failed to accept invitation: ${i.trim()||"unknown error"}`};return{accepted:!0}}async function $c(e,t,n="origin"){let r=t;if(process.env.GH_TOKEN&&t.startsWith("git@github.com:")){let o=process.env.GH_TOKEN.trim();if(!o||/\s/.test(o))return{success:!1,error:"GH_TOKEN environment variable is set but appears malformed (empty or contains whitespace)"};r=`https://github.com/${t.replace("git@github.com:","")}`,await O(["git","config","credential.https://github.com.helper",`!printf 'username=x-access-token\\npassword=${o}'`],{cwd:e,redact:[o]})}else if(t.startsWith("git@github.com:")){let o=t.replace("git@github.com:",""),s=await $p();if(s.token)r=`https://github.com/${o}`,await O(["git","config","credential.https://github.com.helper",`!printf 'username=x-access-token\\npassword=${s.token}'`],{cwd:e,redact:[s.token]});else{let i=await $_t();if(i.works)r=t;else return{success:!1,error:`GitHub authentication not configured.
116
116
 
@@ -760,7 +760,7 @@ which names the field and never repeats what was typed.
760
760
  Examples:
761
761
  nemar admin oidc clients add --name "Compute portal" --redirect-uri https://portal.example.org/cb \\
762
762
  --scopes openid,profile,orcid --grants authorization_code --sign-in-rule person_proven_orcid \\
763
- --audience https://api.nemar.org
763
+ --audience https://nemar-api-dev.sccn-org.workers.dev
764
764
 
765
765
  Exit codes:
766
766
  0 registered; the secret was printed.
@@ -999,7 +999,7 @@ ${b.message}`,r);if(x)return Zt("message",`The squash message would not carry th
999
999
  `);let{phase:f,code:p}=d;e(`${xx("result",p===void 0?{phase:f}:{phase:f,code:p})}
1000
1000
  `);return}e(`${xx("result",{phase:"failed",code:"runner-failed"})}
1001
1001
  `)};xA={emit(d,f){if(d==="result")o=String(f?.phase??"failed");e(`${xx(d,f)}
1002
- `)},drop(){t++},dropped:()=>t,stored(d,f){s={phase:d,code:d==="refused"||d==="failed"?f:void 0}},time(d,f){i.set(d,f)},quietFields:a},process.on("exit",()=>{if(o===null)c()});let l=()=>{try{t++;let d=o;if(s?d!==s.phase:d===null||d==="planned"||d==="opened"||d==="finished")c()}finally{process.exit(1)}};return process.on("uncaughtException",l),process.on("unhandledRejection",l),xA}function mq(e){return e.some((t)=>t===XCe||t.startsWith(`${XCe}=`))}function yIt(e){let t=e.GITHUB_RUN_ID??"";if(e.GITHUB_SERVER_URL==="https://github.com"&&e.GITHUB_REPOSITORY==="nemarDatasets/.github"&&/^[0-9]{1,20}$/.test(t))return`https://github.com/nemarDatasets/.github/actions/runs/${t}`;return null}function tAe(e,t,n){let r=pq(e);if(r===null)throw Cr("id on the command line");let o=pIt(t);if(o.dispatchId!==r)throw new j("dispatch-mismatch","The dispatch named on the command line is not the one the event delivered.");let s=t.RUNNER_TEMP;return{dispatch:o,runUrl:yIt(t),marker:s?Sf(s,"repull-reported"):null,sink:n}}var bIt="https://api.nemar.org";function nAe(e){let t;try{t=new URL(e)}catch{return!1}if(t.username||t.password||t.search||t.hash||t.pathname!=="/"&&t.pathname!=="")return!1;if(t.protocol==="https:")return t.host===new URL(bIt).host;return t.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(t.hostname)}function hq(e,t){if(!t.some((n)=>n.includes(e.token)))return null;return new j("auto-token-on-argv","The dispatch token is on the command line, where the public log shows it.")}function rAe(e,t){let n=hq(e,t.argv);if(n)return n;let r=t.ownVersion??Gs;if((t.devBuild??xp)||!Ry.test(r)||r!==e.cliVersion)return new j("auto-cli-version","This CLI is not the release the dispatch names: an automatic run uses only that release.");if(t.verbose??(Gg()||jl()||t.argv.includes("--verbose")||t.argv.includes("--debug")))return new j("auto-verbose","Verbose or debug output is on, and it prints what the run reads; an automatic run takes neither.");if(e.mode!==t.mode||e.datasetId!==t.datasetId)return new j("dispatch-mismatch","The command is not the one the dispatch asks for: another kind of run, or another dataset.");if(!t.env.GH_TOKEN?.trim())return new j("auto-no-app-token","GH_TOKEN is not set: an automatic run pushes and opens its pull request with the App token minted for this dataset.");if(EA(t.env,t.nowMs??Date.now())===null)return new j("auto-token-clock",`${oAe} does not say when the App token was minted, so the run cannot keep its pushes inside the token's hour.`);return null}var oAe="NEMAR_REPULL_TOKEN_SINCE";function EA(e,t){let n=e[oAe]?.trim()??"";if(!/^[1-9][0-9]{0,11}$/.test(n))return null;let r=Number(n);return r*1000<=t+300000?r:null}function wIt(e,t){return(e+R_)*1000-t}function vx(e,t,n){let r=(n+jEe+Ij)*1000;if(wIt(e,t)>=r)return null;return new j("auto-token-hour","What is left to do would pass the App token's usable hour, so the run stops before this step; the record, if there is one, stays where it stopped.")}function Ex(e){let t=Zc(e);return Fj({bytes:t.copy_bytes??0,objects:t.copy_items??0})}function pb(e,t){return new j("auto-option",t==="required"?`An automatic run needs ${e}.`:`An automatic run does not take ${e}.`)}function sAe(e){if(!e.executable)throw new j("not-executable","The plan is not executable.");SA(e.body)}function SA(e){let t=Zc(e),n=FEe(e.planner,t);if(n)throw new j(n.code,n.message);if(t.copy_bytes_unknown!==0)throw new j("auto-copy-too-large","An automatic re-pull takes only a plan whose copy size is known for every key.");let{copy_bytes:r,copy_items:o,local_bytes:s,local_uploads:i}=t,a=_It();if(r===void 0||o===void 0||s===void 0||i===void 0||t.local_bytes_unknown!==0||Fj({bytes:r+s,objects:o+i})>a)throw new j("auto-copy-too-long",`An automatic re-pull takes only a plan whose copy, by its known size and count, fits ${Math.floor(a/60)} minutes: the App token that pushes it lasts an hour.`)}function kA(e){return`${e}.planner`}function iAe(e,t,n,r){oIt(Sf(t,"computed"),{mode:448});for(let[s,i]of n)fq(Sf(t,"computed",s),i,{mode:384});fq(Sf(t,"digest"),`${r}
1002
+ `)},drop(){t++},dropped:()=>t,stored(d,f){s={phase:d,code:d==="refused"||d==="failed"?f:void 0}},time(d,f){i.set(d,f)},quietFields:a},process.on("exit",()=>{if(o===null)c()});let l=()=>{try{t++;let d=o;if(s?d!==s.phase:d===null||d==="planned"||d==="opened"||d==="finished")c()}finally{process.exit(1)}};return process.on("uncaughtException",l),process.on("unhandledRejection",l),xA}function mq(e){return e.some((t)=>t===XCe||t.startsWith(`${XCe}=`))}function yIt(e){let t=e.GITHUB_RUN_ID??"";if(e.GITHUB_SERVER_URL==="https://github.com"&&e.GITHUB_REPOSITORY==="nemarDatasets/.github"&&/^[0-9]{1,20}$/.test(t))return`https://github.com/nemarDatasets/.github/actions/runs/${t}`;return null}function tAe(e,t,n){let r=pq(e);if(r===null)throw Cr("id on the command line");let o=pIt(t);if(o.dispatchId!==r)throw new j("dispatch-mismatch","The dispatch named on the command line is not the one the event delivered.");let s=t.RUNNER_TEMP;return{dispatch:o,runUrl:yIt(t),marker:s?Sf(s,"repull-reported"):null,sink:n}}var bIt="https://nemar-api-dev.sccn-org.workers.dev";function nAe(e){let t;try{t=new URL(e)}catch{return!1}if(t.username||t.password||t.search||t.hash||t.pathname!=="/"&&t.pathname!=="")return!1;if(t.protocol==="https:")return t.host===new URL(bIt).host;return t.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(t.hostname)}function hq(e,t){if(!t.some((n)=>n.includes(e.token)))return null;return new j("auto-token-on-argv","The dispatch token is on the command line, where the public log shows it.")}function rAe(e,t){let n=hq(e,t.argv);if(n)return n;let r=t.ownVersion??Gs;if((t.devBuild??xp)||!Ry.test(r)||r!==e.cliVersion)return new j("auto-cli-version","This CLI is not the release the dispatch names: an automatic run uses only that release.");if(t.verbose??(Gg()||jl()||t.argv.includes("--verbose")||t.argv.includes("--debug")))return new j("auto-verbose","Verbose or debug output is on, and it prints what the run reads; an automatic run takes neither.");if(e.mode!==t.mode||e.datasetId!==t.datasetId)return new j("dispatch-mismatch","The command is not the one the dispatch asks for: another kind of run, or another dataset.");if(!t.env.GH_TOKEN?.trim())return new j("auto-no-app-token","GH_TOKEN is not set: an automatic run pushes and opens its pull request with the App token minted for this dataset.");if(EA(t.env,t.nowMs??Date.now())===null)return new j("auto-token-clock",`${oAe} does not say when the App token was minted, so the run cannot keep its pushes inside the token's hour.`);return null}var oAe="NEMAR_REPULL_TOKEN_SINCE";function EA(e,t){let n=e[oAe]?.trim()??"";if(!/^[1-9][0-9]{0,11}$/.test(n))return null;let r=Number(n);return r*1000<=t+300000?r:null}function wIt(e,t){return(e+R_)*1000-t}function vx(e,t,n){let r=(n+jEe+Ij)*1000;if(wIt(e,t)>=r)return null;return new j("auto-token-hour","What is left to do would pass the App token's usable hour, so the run stops before this step; the record, if there is one, stays where it stopped.")}function Ex(e){let t=Zc(e);return Fj({bytes:t.copy_bytes??0,objects:t.copy_items??0})}function pb(e,t){return new j("auto-option",t==="required"?`An automatic run needs ${e}.`:`An automatic run does not take ${e}.`)}function sAe(e){if(!e.executable)throw new j("not-executable","The plan is not executable.");SA(e.body)}function SA(e){let t=Zc(e),n=FEe(e.planner,t);if(n)throw new j(n.code,n.message);if(t.copy_bytes_unknown!==0)throw new j("auto-copy-too-large","An automatic re-pull takes only a plan whose copy size is known for every key.");let{copy_bytes:r,copy_items:o,local_bytes:s,local_uploads:i}=t,a=_It();if(r===void 0||o===void 0||s===void 0||i===void 0||t.local_bytes_unknown!==0||Fj({bytes:r+s,objects:o+i})>a)throw new j("auto-copy-too-long",`An automatic re-pull takes only a plan whose copy, by its known size and count, fits ${Math.floor(a/60)} minutes: the App token that pushes it lasts an hour.`)}function kA(e){return`${e}.planner`}function iAe(e,t,n,r){oIt(Sf(t,"computed"),{mode:448});for(let[s,i]of n)fq(Sf(t,"computed",s),i,{mode:384});fq(Sf(t,"digest"),`${r}
1003
1003
  `,{mode:384});let o=kA(e);aIt(o,{recursive:!0,force:!0}),iIt(t,o)}function aAe(e,t){let n=kA(e),r=Sf(n,"computed"),o=Sf(n,"digest");if(!uq(Sf(n,"upstream.git"))||!uq(r)||!uq(o)||dq(o,"utf8").trim()!==t)throw new j("not-planned","No handoff of this plan's own plan step is beside the plan file; an automatic execute plans nothing itself.");let s=new Map;for(let i of sIt(r))s.set(i,dq(Sf(r,i)));return{workdir:n,computed:s}}function _It(e=process.env){let t=e.NEMAR_REPULL_COPY_BUDGET_SECONDS?.trim()??"",n=/^\d{1,9}$/.test(t)?Number(t):Number.NaN;return Number.isFinite(n)&&n<Nj?n:Nj}async function cAe(e,t,n=fetch){let r=t.GH_TOKEN?.trim();if(!r)return!1;let o;try{o=kn(t)}catch{return!1}try{let s=await n(`${o}/repos/nemarDatasets/${e}`,{redirect:"error",headers:{Authorization:`Bearer ${r}`,Accept:"application/vnd.github+json","User-Agent":"nemar-cli"},signal:AbortSignal.timeout(1e4)});return await s.body?.cancel().catch(()=>{return}),s.status===401}catch{return!1}}function RA(e,t){if(Pj(e))return e;if(t===void 0)return"no-code";if(t==="prepare"&&XRe.includes(e??""))return"scrub-failed";return NEe[t]}var xIt=15000,ZCe=["opened","finished","refused","failed"];async function gq(e,t,n={},r={}){let o={dispatch_id:e.dispatch.dispatchId,dataset_id:e.dispatch.datasetId,phase:t};if(t==="refused"||t==="failed")o.code=RA(n.code);if(t==="opened")o.repull_id=n.repullId;if(e.runUrl)o.workflow_run_url=e.runUrl;let s=r.fetchImpl??fetch,i=r.apiUrl??zr(),a=Math.max(1,r.attempts??3),c={stored:!1,code:"report-unanswered"};for(let l=1;l<=a;l++){let d,f;try{let p=await s(`${i}/webhooks/repull-state`,{method:"POST",redirect:"error",headers:{"Content-Type":"application/json","X-Repull-Token":e.dispatch.token},body:JSON.stringify(o),signal:AbortSignal.timeout(r.timeoutMs??xIt)});d=p.status,f=(await p.json().catch(()=>null))?.code}catch{if(c={stored:!1,code:"report-unanswered"},l<a)await eAe(r.backoffMs??2000);continue}if(d===200){c={stored:!0};break}if(c={stored:!1,code:typeof f==="string"&&Pj(f)?f:"report-unanswered"},d<500)break;if(l<a)await eAe(r.backoffMs??2000)}if(e.sink.emit("report",{phase:t,answer:c.stored?"stored":c.code}),c.stored&&ZCe.includes(t))e.sink.stored(t,o.code);if(c.stored&&ZCe.includes(t)&&e.marker)try{fq(e.marker,`${t}
1004
1004
  `,{mode:384})}catch{}return c}var eAe=(e)=>new Promise((t)=>setTimeout(t,e));ta();wo();wr();Ve();import{existsSync as EFt,readdirSync as SFt,rmdirSync as kFt}from"fs";import{dirname as Ox,join as Ax}from"path";Pr();Lc();Jr();gf();ya();qA();Ty();wo();Ve();import{dirname as LNt,join as qNt}from"path";Pr();function ls(e,t){return new j(e,t)}var Pq=["registered","pr_open","gates_clear"];async function BAe(e,t,n){let r=await rb({token:e.token,base:e.base,datasetId:e.datasetId,state:"all",head:t});if(!r.ok)throw ls("github-unreadable",`GitHub's pull requests of ${t} could not be read whole (${nb(r)}), so whether one merged is not known; nothing was closed.`);let o=new Set(r.pulls.filter((i)=>i.headRef===t).map((i)=>i.number));if(n!==null)o.add(n);let s=[];for(let i of[...o].sort((a,c)=>a-c)){let a=await Ks(e.token,e.datasetId,i,e.base);if(!a.ok)throw ls("github-unreadable",`Pull request #${i} could not be read on GitHub (${a.reason}); nothing was closed.`);s.push({number:i,state:a.value.state,headSha:a.value.headSha})}return s}function UNt(e,t,n,r){return ls("foreign-pull-request-merged",`GitHub says pull request #${t} of ${n} merged, and it is not this re-pull's (it recorded #${r}): that version was released outside the re-pull, which resume does not record. Nothing was closed or ended; read the dataset's history on GitHub (nemarDatasets/${e.datasetId}) to see what merged before this record is ended.`)}function HAe(e,t,n,r){return r!==null&&t!==r?UNt(e,t,n,r):GAe(e,t)}function GAe(e,t,n=!1){return(n?tt:ls)("pull-request-merged",`GitHub says pull request #${t} merged, so this re-pull is not ended: nemar admin repull resume ${e.datasetId} records the merge (a merge minted a DOI, and its release is recorded, not abandoned).`)}async function BNt(e,t){let n=(await is(e,t)).filter((a)=>a.mode==="120000"||a.mode==="100644"||a.mode==="100755"),r=new Map;if(n.length>0){let a=await ne(e,["cat-file","--batch-check"],{stdin:`${n.map((c)=>c.oid).join(`
1005
1005
  `)}
@@ -2599,7 +2599,7 @@ Examples:
2599
2599
  `)}}}jh();Ve();function wPe(e){return e instanceof U&&e.statusCode===422&&e.rawBody?.status==="blocked"&&vS(e.blockReason)}function _Pe(e){let t=e.rawBody?.ci_url;return typeof t==="string"&&/^https:\/\/\S+$/.test(t)?t:void 0}function g3(e){return e==="bids_validation_in_progress"?"Request recorded: BIDS validation is still running.":"Request recorded: BIDS validation has not started yet."}function y3(e,t=!1){let n=`nemar dataset publish request ${e}${t?" --anonymous":""}`;return[" Your request is recorded. NEMAR re-checks it automatically and continues once validation passes.",` If you would rather not wait for that, check validation with: nemar dataset ci ${e}`,` Once it has passed, request again: ${n}`," If it says a request already exists, nothing more is needed."," If validation fails or a submission minimum fails, the request stays blocked and nothing is emailed:",` check nemar dataset ci ${e} or nemar dataset publish status ${e}.`]}Ve();Pr();async function W1(){let e=Yt().sandboxCompleted;if(e!==void 0)return{status:e?"completed":"not_completed"};try{let t=await y$();if(Un("sandboxCompleted",t.sandbox_completed),t.sandbox_dataset_id)Un("sandboxDatasetId",t.sandbox_dataset_id);return t.sandbox_completed?{status:"completed"}:{status:"not_completed"}}catch(t){return{status:"unknown",reason:W(t)}}}We();Di();LL();We();Ro();Ec();Ve();Yp();mC();Rp();Di();$i();bC();BL();mf();Xp();import{existsSync as b3,mkdirSync as Nqt,readFileSync as Fqt,statSync as Mqt,writeFileSync as xPe}from"fs";import{join as jqt,resolve as w3}from"path";function vPe(e,t,n){if(!ha(n,"metadata_write")){if(t)try{let r=w3(e,".nemar"),o=w3(r,"metadata.json");if(!b3(o)){if(!b3(r))Nqt(r,{recursive:!0});xPe(o,JSON.stringify(t,null,2))}let s=w3(e,".bidsignore"),i="";if(b3(s))i=Fqt(s,"utf-8");if(!i.includes(".nemar/")){let a=i?`${i.trimEnd()}
2600
2600
  .nemar/
2601
2601
  `:`.nemar/
2602
- `;xPe(s,a)}console.log(u.dim(" Updated .bidsignore for NEMAR metadata"))}catch(r){console.log(u.yellow(` Warning: Could not update .bidsignore: ${W(r)}`)),console.log(u.dim(" Upload will continue without author enrichment."))}Yl(n,"metadata_write"),Xr(e,n)}else console.log(u.dim(" Metadata write already completed (skipping)"))}var EPe=1073741824;function Lqt(e,t,n=EPe){let r=[],o=0;for(let s of t){let i=e.files[s];if(!i||i.mtimeMs===void 0)continue;r.push({path:s,size:i.size,mtimeMs:i.mtimeMs}),o+=i.size}return o>=n?r:null}function qqt(e,t){return t.filter((n)=>{try{return ho(n.path,Mqt(jqt(e,n.path)).size)}catch{return!0}})}function Uqt(e){let t=0;for(let n of Object.values(e.files))t+=n.size;return t}function Bqt(e){return["Warning: saving dataset changes has produced no stdout or stderr for",`${wC(e)}. git add -A is still running.`,"Wait, or interrupt and rerun the upload; the save step will run again."].join(" ")}async function SPe(e,t,n,r={}){if(!ha(n,"dataset_save")){let o=C({text:"Saving dataset changes...",...r.spinnerStream?{stream:r.spinnerStream}:{}}).start(),s=r.skipMinBytes??EPe,i=[];if(Uqt(n)>=s){let c=r.annexedPaths??null;if(c===null)try{c=await pf(e)}catch(l){console.log(u.dim(` Could not list annexed files (${W(l)}); staging will re-read them`))}if(c!==null)i=qqt(e,Lqt(n,c,s)??[])}let a=await Ul(e,"Initial NEMAR dataset upload",t,{skipContentCheck:i,onInactivityWarning:(c)=>{o=V_(o,Bqt(c))},...r.inactivityWarningAfterMs===void 0?{}:{inactivityWarningAfterMs:r.inactivityWarningAfterMs}});if(!a.success)return Xr(e,n),Fo(o,"Failed to save dataset",a.error),console.log(),console.log(u.yellow("Re-run the same command to resume from this step.")),Le;if(r.verifyRemote){let c;try{c=await JL(e,r.verifyRemote)}catch(l){return Xr(e,n),Fo(o,"Could not confirm the saved files are at the S3 remote",l),console.log(),console.log(u.yellow("Re-run the same command to resume from this step.")),Le}if(c.length>0){Xl(n,"s3_upload"),Xr(e,n);let l=x$(c.slice(0,5)),d=c.length>5?` (and ${c.length-5} more)`:"";return Fo(o,"Saved files are not at the S3 remote",`${c.length} annexed file(s) in the commit are not recorded at the remote: ${l}${d}. The save itself annexed them, after the upload step had run.`),console.log(),console.log(u.yellow("Re-run the same command: it uploads them and saves again.")),Le}}o.succeed("Dataset changes saved"),Yl(n,"dataset_save"),Xr(e,n)}else console.log(u.dim(" Dataset save already completed (skipping)"));return vn()}async function kPe(e,t){if(!ha(t,"github_push")){let n=C("Pushing metadata to GitHub...").start(),r=await _r(e);if(!r.success)return Xr(e,t),Fo(n,"Failed to push to GitHub",r.error),console.log(),console.log(u.yellow("Re-run the same command to resume from this step.")),Le;if(r.warning)n.warn("Metadata pushed to GitHub (with warning)"),console.log(u.yellow(` ${r.warning}`));else n.succeed("Metadata pushed to GitHub");Yl(t,"github_push"),Xr(e,t)}else console.log(u.dim(" GitHub push already completed (skipping)"));return vn()}async function RPe(e,t,n){if(!ha(n,"ci_deploy")){let r=C("Setting up BIDS validation CI...").start(),o="configured";try{await Ll(t),r.succeed("BIDS validation CI configured")}catch(s){if(o="not-configured",s instanceof U&&s.statusCode===403)r.info("CI workflow will be configured by an admin");else{let i=s instanceof Error?s.message:String(s);r.warn(`Could not configure CI: ${i}`),console.log(u.dim(` An admin can add it later with: nemar admin ci add ${t}`))}}return Yl(n,"ci_deploy"),Xr(e,n),o}return console.log(u.dim(" CI deploy already completed (skipping)")),"unknown"}function Hqt(e,t){let n=e.startsWith("xx");if(t==="not-configured"){if(n)return;console.log("BIDS validation is not set up yet."),console.log(` CI is set up when you request publication: ${u.cyan(`nemar dataset publish request ${e}`)}`),console.log();return}if(console.log("BIDS validation runs on GitHub after the upload."),console.log(` Check it with: ${u.cyan(`nemar dataset ci ${e}`)}`),!n)console.log(` Once it has passed, request publication: ${u.cyan(`nemar dataset publish request ${e}`)}`);console.log()}function $Pe(e,t,n="unknown"){z_(e),nRe(e),console.log(),console.log(u.green.bold("Upload complete!")),console.log(),console.log(` Dataset ID: ${u.cyan(t.dataset_id)}`),console.log(` GitHub: ${u.cyan(t.github_url)}`),console.log(),console.log(u.dim("To download this dataset:")),console.log(u.dim(` nemar dataset download ${t.dataset_id}`)),console.log(),Hqt(t.dataset_id,n),console.log(u.yellow("Note: This dataset is private. Only the owner and designated collaborators can")),console.log(u.yellow("download it, and only through the NEMAR CLI (not direct git-annex commands).")),console.log(u.yellow("After publishing, the data will be publicly available for everyone."))}mf();Xp();async function DPe(e,t={}){let n=await hwe(e.absolutePath);if(!n.success)return console.log(u.red(n.error)),console.log(u.yellow("Re-run the same command to retry.")),Le;if(n.cleared>0)console.log(u.yellow(` Cleared ${n.cleared} assume-unchanged flag(s) an earlier, interrupted save left on annexed files`));let r=await cRe(e.absolutePath);if(r.status==="error")return console.log(u.red(r.error)),Le;if(r.status==="warning")console.log(u.yellow(` ${r.warning}`));if(r.status==="restored")console.log(u.yellow(" Put back git-annex's filter process, which an earlier, interrupted upload had left out of this repository's configuration"));let o=await URe(e.absolutePath,e.options,e.dataFiles,e.filesToUpload,e.uploadProgress,e.datasetInfo,{openRemote:t.openRemote,...t.primeMinBytes===void 0?{}:{primeMinBytes:t.primeMinBytes},...t.primeOnSuspended?{primeOnSuspended:t.primeOnSuspended}:{}});if(o.status==="fail")return Le;let{progress:s,annexedPaths:i}=o.value;if(vPe(e.absolutePath,e.coAuthorEnrichment,s),(await(t.saveStep??SPe)(e.absolutePath,e.author,s,{annexedPaths:i,verifyRemote:Gc,...t.skipMinBytes===void 0?{}:{skipMinBytes:t.skipMinBytes},...t.saveInactivityWarningAfterMs===void 0?{}:{inactivityWarningAfterMs:t.saveInactivityWarningAfterMs},...t.saveSpinnerStream===void 0?{}:{spinnerStream:t.saveSpinnerStream}})).status==="fail")return Le;return vn(s)}We();Kl();fm();U_();_n();Gt();import{randomBytes as kUt}from"crypto";import{constants as k3,accessSync as RUt,chmodSync as $Ut,chownSync as DUt,closeSync as C3,copyFileSync as CUt,existsSync as ZPe,fsyncSync as eIe,lstatSync as il,mkdirSync as AUt,mkdtempSync as OUt,openSync as A3,readSync as TUt,readdirSync as PUt,renameSync as IUt,rmSync as O3,rmdirSync as NUt,statSync as tIe,writeSync as FUt}from"fs";import{tmpdir as MUt}from"os";import{dirname as eO,join as Ra}from"path";We();import{lstatSync as yUt,readdirSync as bUt,statSync as UPe}from"fs";import{open as wUt}from"fs/promises";import{join as qPe}from"path";hi();Ro();Kl();var PPe="nemar-identifier-scan/1.0 (+https://docs.nemar.org/policies/takedown/)",Gqt="https://api.nemar.org",zqt="https://data.nemar.org",Vqt="https://nemar.s3.us-east-2.amazonaws.com",Wqt="https://api.github.com";function X1(e,t){if(!Number.isSafeInteger(t)||t<1)throw RangeError(`${e} must be a positive integer, got ${t}`)}async function K1(e,t,n){X1("pool size",t);let r=0,o=Array.from({length:Math.min(t,e.length)},async()=>{while(r<e.length){let a=e[r++];await n(a)}}),i=(await Promise.allSettled(o)).find((a)=>a.status==="rejected");if(i)throw i.reason}function Kqt(e){X1("limit",e);let t=0,n=[];return async(r)=>{if(t>=e)await new Promise((o)=>n.push(o));else t++;try{return await r()}finally{let o=n.shift();if(o)o();else t--}}}class cr 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 Jqt(e,t=Date.now()){let n=e?.trim();if(!n)return;if(/^\d+$/.test(n))return Number(n)*1000;let r=Date.parse(n);return Number.isNaN(r)?void 0:Math.max(0,r-t)}function Yqt(e,t){let n=e>=500||e===429;return new cr(`http-${e}`,{status:e,retryable:n,retryAfterMs:n?Jqt(t):void 0})}class _3 extends Error{constructor(e){super(e);this.name="RunAborted"}}function Xqt(e){X1("abort streak",e.streak);let t=e.now??Date.now,n={tripped:null},r=(o)=>{let s=0,i=0,a=(c)=>{throw n.tripped=new _3(c),n.tripped};return{check(){if(n.tripped)throw n.tripped},ok(){s=0},pausedUntilMs(){return i},observe(c){if(n.tripped)throw n.tripped;if(c.retryAfterMs!==void 0&&c.retryAfterMs>e.retryAfterCapMs)a(`${o} asked to wait ${Math.round(c.retryAfterMs/1000)} s (Retry-After), over the ${Math.round(e.retryAfterCapMs/1000)} s cap (${c.cls})`);if(c.retryAfterMs!==void 0)i=Math.max(i,t()+c.retryAfterMs);if(!c.retryable){s=0;return}if(s++,s>=e.streak)a(`${s} consecutive 429, 5xx, timeout or network failures from ${o} (last ${c.cls})`)}}};return{worker:r("the Worker"),direct:r("direct reads")}}function CPe(e){let t=e instanceof Error?e.name:"";return new cr(t==="TimeoutError"||t==="AbortError"?"timeout":"network",{retryable:!0})}function Qqt(e){if(e instanceof cr)return e.cls;return`error-${e instanceof Error?e.name:"unknown"}`}async function Zqt(e,t={}){let n=t.tries??3,r=t.baseMs??400,o=t.sleep??((s)=>new Promise((i)=>setTimeout(i,s)));X1("tries",n);for(let s=1;;s++)try{return await e()}catch(i){if(!(i instanceof cr&&i.retryable)||s>=n)throw i;let c=i.retryAfterMs??0;if(c>(t.retryAfterCapMs??30000))throw i;await o(Math.max(r*2**(s-1),c))}}async function eUt(e){await e.body?.cancel().catch(()=>{return})}async function tUt(e,t,n={}){let r;try{r=await fetch(e,{headers:{Range:`bytes=0-${t-1}`,"Accept-Encoding":"identity","User-Agent":n.userAgent??PPe},signal:AbortSignal.timeout(n.timeoutMs??30000)})}catch(a){throw CPe(a)}if(r.status!==200&&r.status!==206)throw await eUt(r),Yqt(r.status,r.headers.get("retry-after"));let o=r.body?.getReader();if(!o)throw new cr("no-body");let s=new Uint8Array(t),i=0;try{while(i<t){let{done:a,value:c}=await o.read();if(a||!c)break;let l=Math.min(c.length,t-i);s.set(c.subarray(0,l),i),i+=l}}catch(a){throw CPe(a)}finally{await o.cancel().catch(()=>{return})}if(i<(n.minBytes??0))throw new cr("short-body");return s.subarray(0,i)}var IPe={sideFileBytes:2097152,participantsBytes:16777216};function nUt(e,t){let n=/An error occurred \(([A-Za-z0-9]{1,40})\)/.exec(e)?.[1];if(n)return/^\d+$/.test(n)?`aws/http-${n}`:`aws/error-${n}`;return`aws/exit-${t}`}async function rUt(e,t,n={}){let r;try{let o=Bun.spawn(["aws","s3","cp",`s3://nemar/${e}/version/${t}.json`,"-"],{stdout:"pipe",stderr:"pipe",...n.env?{env:n.env}:{}}),s=!1;r=setTimeout(()=>{s=!0,o.kill("SIGKILL")},n.timeoutMs??600000);let[i,a,c]=await Promise.all([new Response(o.stdout).text(),new Response(o.stderr).text(),o.exited]);if(s)throw new cr("aws/timeout");if(c!==0)throw new cr(nUt(a,c));return i}catch(o){if(o instanceof cr)throw o;throw new cr("aws/unavailable")}finally{clearTimeout(r)}}function oUt(){let e;return async()=>{if(e!==void 0)return e;if(process.env.GITHUB_TOKEN)return e=process.env.GITHUB_TOKEN,e;try{let t=Bun.spawn(["gh","auth","token"],{stdout:"pipe",stderr:"ignore"}),n=(await new Response(t.stdout).text()).trim();e=n===""?null:n}catch{e=null}return e}}var J1=(e)=>e.replace(/\/+$/,"");function NPe(e={}){let t=e.retryAfterCapMs??30000,n=e.awsTimeoutMs??600000;return{api:J1(e.api??process.env.NEMAR_API_BASE??Gqt),data:J1(e.data??process.env.NEMAR_DATA_BASE??zqt),s3Base:J1(e.s3Base??Vqt),githubApi:J1(e.githubApi??Wqt),userAgent:e.userAgent??PPe,fileConcurrency:e.fileConcurrency??24,workerLimit:Kqt(e.workerConcurrency??6),timeoutMs:e.timeoutMs??30000,manifestTimeoutMs:e.manifestTimeoutMs??120000,retryBaseMs:e.retryBaseMs??400,sleep:e.sleep??((r)=>new Promise((o)=>setTimeout(o,r))),now:e.now??Date.now,retryAfterCapMs:t,breakers:Xqt({streak:e.abortStreak??25,retryAfterCapMs:t,now:e.now??Date.now}),limits:{treeHeaderSample:300,scansTables:1,jsonFiles:300,textFiles:300,sideFileBytes:65536,participantsBytes:1048576,...e.limits},readVersionManifest:e.readVersionManifest??((r,o)=>rUt(r,o,{timeoutMs:n,env:e.awsEnv})),githubToken:e.githubToken??oUt(),...e.readEntryHead?{readEntryHead:e.readEntryHead}:{}}}var FPe=(e,t)=>t.startsWith(`${e.data}/`),sUt=(e,t)=>FPe(e,t)||t.startsWith(`${e.api}/`)?e.breakers.worker:e.breakers.direct;async function iUt(e,t,n){let r=sUt(e,t);r.check();let o=r.pausedUntilMs()-e.now();if(o>0)await e.sleep(o),r.check();try{let s=await n();return r.ok(),s}catch(s){if(s instanceof cr)r.observe(s);throw s}}var aUt=(e,t)=>({...t===void 0?{}:{tries:t},baseMs:e.retryBaseMs,sleep:e.sleep,retryAfterCapMs:e.retryAfterCapMs});var APe=(e)=>/sub-([^/_]+)/.exec(e)?.[1]??"?";function OPe(e,t,n){if(t<1)return[];if(e.length<=t)return[...e];let r=new Map;for(let c of e){let l=n(c),d=r.get(l);if(d)d.push(c);else r.set(l,[c])}let o=[...r.entries()].sort(([c],[l])=>c<l?-1:c>l?1:0).map(([,c])=>c);if(o.length>t)return Array.from({length:t},(c,l)=>o[Math.floor((l+0.5)*o.length/t)][0]);let s=o.map((c,l)=>({list:c,index:l})).sort((c,l)=>c.list.length-l.list.length||c.index-l.index),i=t,a=[];return s.forEach(({list:c},l)=>{let d=Math.min(c.length,Math.ceil(i/(s.length-l)));for(let f=0;f<d;f++)a.push(c[Math.floor((f+0.5)*c.length/d)]);i-=d}),a}var cUt=(e)=>e.severity==="identifier"&&tke.has(e.kind),lUt=(e)=>zp.has(e.kind);function MPe(e){return e.headerRead===e.edfCount&&e.incompleteReasons.length===0}function uUt(e){if(e.findings.some(cUt))return"direct-identifiers";if(e.findings.some((t)=>!lUt(t)))return"review";if(!MPe(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 dUt=/\.(edf|bdf)$/i,fUt=(e)=>e.edf===!0||dUt.test(e.path);function pUt(e){return{edf:e.filter(fUt),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/")||!mUt.test(t.path)).filter((t)=>!hUt.test(t.path)),text:e.filter((t)=>gUt.test(t.path)).filter((t)=>t.path.startsWith("sourcedata/")||t.path.startsWith("code/"))}}var mUt=/_(eeg|ieeg|meg|emg|nirs|beh|events|channels|electrodes|coordsystem|scans|physio|stim|photo|T1w|bold)\.(json|tsv)$/,hUt=/(^|\/)(dataset_description|participants|genetic_info)\.json$/,gUt=/\.(py|m|r|txt|md|ya?ml|xml|iml|cfg|ini)$/i;function jPe(e,t,n,r=0){let o=()=>iUt(e,t.url,()=>{let s={minBytes:r,userAgent:e.userAgent,timeoutMs:e.timeoutMs};return e.readEntryHead?e.readEntryHead(t,n,s):tUt(t.url,n,s)});return Zqt(()=>FPe(e,t.url)?e.workerLimit(o):o(),aUt(e))}async function Y1(e,t,n){let r=await jPe(e,t,n),o=t.size===null?r.length>=n:t.size>n;return{text:new TextDecoder("utf-8",{fatal:!1}).decode(r),truncated:o}}function Db(e,t){for(let n of t)e.push(n)}var TPe="edf/superseded-absent";async function LPe(e,t,n,r,o,s={}){let i=r.map((Ie)=>Ie.path),a=o==="clone",c=(Ie,Re,Rn)=>a?[...Ie]:OPe(Ie,Re,Rn),l=[...eC([...i,...s.extraPaths??[]])],d=fke(i),f=Object.values(d.unscreened).reduce((Ie,Re)=>Ie+Re,0),p={},m=(Ie,Re)=>{if(Re instanceof _3)throw Re;let Rn=`${Ie}/${Qqt(Re)}`;p[Rn]=(p[Rn]??0)+1},h=(Ie)=>APe(Ie.path),g=pUt(r),y=new Set(s.supersededEdf??[]),b=[...g.edf,...y],{participants:x,scans:v,json:S,text:E}=g,A=o==="git-tree"?OPe(b,e.limits.treeHeaderSample,h):[...b],I=0,H=0,T=0,L=0,q={},V=new Set,B=new Set,M=new Set,P=new Set,G=new Set,se=new Set;await K1(A,e.fileConcurrency,async(Ie)=>{try{let Re=await jPe(e,Ie,At,At),Rn=cf(Re),{patient:Ab}=QD(Re);if(!Rn.some((us)=>us.kind==="edf-unreadable")){V.add(Ab);let us=Ab.split(/\s+/);if(us.length>=4)M.add(us[0]),G.add(us[2]),P.add(us[3])}if(se.add(APe(Ie.path)),Rn.some((us)=>us.severity==="identifier"))L++,B.add(Ab);Db(l,Rn);for(let us of new Set(Rn.map((Rm)=>Rm.kind)))q[us]=(q[us]??0)+1;I++}catch(Re){if(y.has(Ie)&&Re instanceof cr&&Re.status===404){T++,p[TPe]=(p[TPe]??0)+1;return}H++,m("edf",Re)}});let De=b.length-T,ln=!1,ot=!1;if(x&&x.size!==0)try{let{text:Ie,truncated:Re}=await Y1(e,x,e.limits.participantsBytes),Rn=Ie.indexOf(`
2602
+ `;xPe(s,a)}console.log(u.dim(" Updated .bidsignore for NEMAR metadata"))}catch(r){console.log(u.yellow(` Warning: Could not update .bidsignore: ${W(r)}`)),console.log(u.dim(" Upload will continue without author enrichment."))}Yl(n,"metadata_write"),Xr(e,n)}else console.log(u.dim(" Metadata write already completed (skipping)"))}var EPe=1073741824;function Lqt(e,t,n=EPe){let r=[],o=0;for(let s of t){let i=e.files[s];if(!i||i.mtimeMs===void 0)continue;r.push({path:s,size:i.size,mtimeMs:i.mtimeMs}),o+=i.size}return o>=n?r:null}function qqt(e,t){return t.filter((n)=>{try{return ho(n.path,Mqt(jqt(e,n.path)).size)}catch{return!0}})}function Uqt(e){let t=0;for(let n of Object.values(e.files))t+=n.size;return t}function Bqt(e){return["Warning: saving dataset changes has produced no stdout or stderr for",`${wC(e)}. git add -A is still running.`,"Wait, or interrupt and rerun the upload; the save step will run again."].join(" ")}async function SPe(e,t,n,r={}){if(!ha(n,"dataset_save")){let o=C({text:"Saving dataset changes...",...r.spinnerStream?{stream:r.spinnerStream}:{}}).start(),s=r.skipMinBytes??EPe,i=[];if(Uqt(n)>=s){let c=r.annexedPaths??null;if(c===null)try{c=await pf(e)}catch(l){console.log(u.dim(` Could not list annexed files (${W(l)}); staging will re-read them`))}if(c!==null)i=qqt(e,Lqt(n,c,s)??[])}let a=await Ul(e,"Initial NEMAR dataset upload",t,{skipContentCheck:i,onInactivityWarning:(c)=>{o=V_(o,Bqt(c))},...r.inactivityWarningAfterMs===void 0?{}:{inactivityWarningAfterMs:r.inactivityWarningAfterMs}});if(!a.success)return Xr(e,n),Fo(o,"Failed to save dataset",a.error),console.log(),console.log(u.yellow("Re-run the same command to resume from this step.")),Le;if(r.verifyRemote){let c;try{c=await JL(e,r.verifyRemote)}catch(l){return Xr(e,n),Fo(o,"Could not confirm the saved files are at the S3 remote",l),console.log(),console.log(u.yellow("Re-run the same command to resume from this step.")),Le}if(c.length>0){Xl(n,"s3_upload"),Xr(e,n);let l=x$(c.slice(0,5)),d=c.length>5?` (and ${c.length-5} more)`:"";return Fo(o,"Saved files are not at the S3 remote",`${c.length} annexed file(s) in the commit are not recorded at the remote: ${l}${d}. The save itself annexed them, after the upload step had run.`),console.log(),console.log(u.yellow("Re-run the same command: it uploads them and saves again.")),Le}}o.succeed("Dataset changes saved"),Yl(n,"dataset_save"),Xr(e,n)}else console.log(u.dim(" Dataset save already completed (skipping)"));return vn()}async function kPe(e,t){if(!ha(t,"github_push")){let n=C("Pushing metadata to GitHub...").start(),r=await _r(e);if(!r.success)return Xr(e,t),Fo(n,"Failed to push to GitHub",r.error),console.log(),console.log(u.yellow("Re-run the same command to resume from this step.")),Le;if(r.warning)n.warn("Metadata pushed to GitHub (with warning)"),console.log(u.yellow(` ${r.warning}`));else n.succeed("Metadata pushed to GitHub");Yl(t,"github_push"),Xr(e,t)}else console.log(u.dim(" GitHub push already completed (skipping)"));return vn()}async function RPe(e,t,n){if(!ha(n,"ci_deploy")){let r=C("Setting up BIDS validation CI...").start(),o="configured";try{await Ll(t),r.succeed("BIDS validation CI configured")}catch(s){if(o="not-configured",s instanceof U&&s.statusCode===403)r.info("CI workflow will be configured by an admin");else{let i=s instanceof Error?s.message:String(s);r.warn(`Could not configure CI: ${i}`),console.log(u.dim(` An admin can add it later with: nemar admin ci add ${t}`))}}return Yl(n,"ci_deploy"),Xr(e,n),o}return console.log(u.dim(" CI deploy already completed (skipping)")),"unknown"}function Hqt(e,t){let n=e.startsWith("xx");if(t==="not-configured"){if(n)return;console.log("BIDS validation is not set up yet."),console.log(` CI is set up when you request publication: ${u.cyan(`nemar dataset publish request ${e}`)}`),console.log();return}if(console.log("BIDS validation runs on GitHub after the upload."),console.log(` Check it with: ${u.cyan(`nemar dataset ci ${e}`)}`),!n)console.log(` Once it has passed, request publication: ${u.cyan(`nemar dataset publish request ${e}`)}`);console.log()}function $Pe(e,t,n="unknown"){z_(e),nRe(e),console.log(),console.log(u.green.bold("Upload complete!")),console.log(),console.log(` Dataset ID: ${u.cyan(t.dataset_id)}`),console.log(` GitHub: ${u.cyan(t.github_url)}`),console.log(),console.log(u.dim("To download this dataset:")),console.log(u.dim(` nemar dataset download ${t.dataset_id}`)),console.log(),Hqt(t.dataset_id,n),console.log(u.yellow("Note: This dataset is private. Only the owner and designated collaborators can")),console.log(u.yellow("download it, and only through the NEMAR CLI (not direct git-annex commands).")),console.log(u.yellow("After publishing, the data will be publicly available for everyone."))}mf();Xp();async function DPe(e,t={}){let n=await hwe(e.absolutePath);if(!n.success)return console.log(u.red(n.error)),console.log(u.yellow("Re-run the same command to retry.")),Le;if(n.cleared>0)console.log(u.yellow(` Cleared ${n.cleared} assume-unchanged flag(s) an earlier, interrupted save left on annexed files`));let r=await cRe(e.absolutePath);if(r.status==="error")return console.log(u.red(r.error)),Le;if(r.status==="warning")console.log(u.yellow(` ${r.warning}`));if(r.status==="restored")console.log(u.yellow(" Put back git-annex's filter process, which an earlier, interrupted upload had left out of this repository's configuration"));let o=await URe(e.absolutePath,e.options,e.dataFiles,e.filesToUpload,e.uploadProgress,e.datasetInfo,{openRemote:t.openRemote,...t.primeMinBytes===void 0?{}:{primeMinBytes:t.primeMinBytes},...t.primeOnSuspended?{primeOnSuspended:t.primeOnSuspended}:{}});if(o.status==="fail")return Le;let{progress:s,annexedPaths:i}=o.value;if(vPe(e.absolutePath,e.coAuthorEnrichment,s),(await(t.saveStep??SPe)(e.absolutePath,e.author,s,{annexedPaths:i,verifyRemote:Gc,...t.skipMinBytes===void 0?{}:{skipMinBytes:t.skipMinBytes},...t.saveInactivityWarningAfterMs===void 0?{}:{inactivityWarningAfterMs:t.saveInactivityWarningAfterMs},...t.saveSpinnerStream===void 0?{}:{spinnerStream:t.saveSpinnerStream}})).status==="fail")return Le;return vn(s)}We();Kl();fm();U_();_n();Gt();import{randomBytes as kUt}from"crypto";import{constants as k3,accessSync as RUt,chmodSync as $Ut,chownSync as DUt,closeSync as C3,copyFileSync as CUt,existsSync as ZPe,fsyncSync as eIe,lstatSync as il,mkdirSync as AUt,mkdtempSync as OUt,openSync as A3,readSync as TUt,readdirSync as PUt,renameSync as IUt,rmSync as O3,rmdirSync as NUt,statSync as tIe,writeSync as FUt}from"fs";import{tmpdir as MUt}from"os";import{dirname as eO,join as Ra}from"path";We();import{lstatSync as yUt,readdirSync as bUt,statSync as UPe}from"fs";import{open as wUt}from"fs/promises";import{join as qPe}from"path";hi();Ro();Kl();var PPe="nemar-identifier-scan/1.0 (+https://docs.nemar.org/policies/takedown/)",Gqt="https://nemar-api-dev.sccn-org.workers.dev",zqt="https://data.nemar.org",Vqt="https://nemar.s3.us-east-2.amazonaws.com",Wqt="https://api.github.com";function X1(e,t){if(!Number.isSafeInteger(t)||t<1)throw RangeError(`${e} must be a positive integer, got ${t}`)}async function K1(e,t,n){X1("pool size",t);let r=0,o=Array.from({length:Math.min(t,e.length)},async()=>{while(r<e.length){let a=e[r++];await n(a)}}),i=(await Promise.allSettled(o)).find((a)=>a.status==="rejected");if(i)throw i.reason}function Kqt(e){X1("limit",e);let t=0,n=[];return async(r)=>{if(t>=e)await new Promise((o)=>n.push(o));else t++;try{return await r()}finally{let o=n.shift();if(o)o();else t--}}}class cr 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 Jqt(e,t=Date.now()){let n=e?.trim();if(!n)return;if(/^\d+$/.test(n))return Number(n)*1000;let r=Date.parse(n);return Number.isNaN(r)?void 0:Math.max(0,r-t)}function Yqt(e,t){let n=e>=500||e===429;return new cr(`http-${e}`,{status:e,retryable:n,retryAfterMs:n?Jqt(t):void 0})}class _3 extends Error{constructor(e){super(e);this.name="RunAborted"}}function Xqt(e){X1("abort streak",e.streak);let t=e.now??Date.now,n={tripped:null},r=(o)=>{let s=0,i=0,a=(c)=>{throw n.tripped=new _3(c),n.tripped};return{check(){if(n.tripped)throw n.tripped},ok(){s=0},pausedUntilMs(){return i},observe(c){if(n.tripped)throw n.tripped;if(c.retryAfterMs!==void 0&&c.retryAfterMs>e.retryAfterCapMs)a(`${o} asked to wait ${Math.round(c.retryAfterMs/1000)} s (Retry-After), over the ${Math.round(e.retryAfterCapMs/1000)} s cap (${c.cls})`);if(c.retryAfterMs!==void 0)i=Math.max(i,t()+c.retryAfterMs);if(!c.retryable){s=0;return}if(s++,s>=e.streak)a(`${s} consecutive 429, 5xx, timeout or network failures from ${o} (last ${c.cls})`)}}};return{worker:r("the Worker"),direct:r("direct reads")}}function CPe(e){let t=e instanceof Error?e.name:"";return new cr(t==="TimeoutError"||t==="AbortError"?"timeout":"network",{retryable:!0})}function Qqt(e){if(e instanceof cr)return e.cls;return`error-${e instanceof Error?e.name:"unknown"}`}async function Zqt(e,t={}){let n=t.tries??3,r=t.baseMs??400,o=t.sleep??((s)=>new Promise((i)=>setTimeout(i,s)));X1("tries",n);for(let s=1;;s++)try{return await e()}catch(i){if(!(i instanceof cr&&i.retryable)||s>=n)throw i;let c=i.retryAfterMs??0;if(c>(t.retryAfterCapMs??30000))throw i;await o(Math.max(r*2**(s-1),c))}}async function eUt(e){await e.body?.cancel().catch(()=>{return})}async function tUt(e,t,n={}){let r;try{r=await fetch(e,{headers:{Range:`bytes=0-${t-1}`,"Accept-Encoding":"identity","User-Agent":n.userAgent??PPe},signal:AbortSignal.timeout(n.timeoutMs??30000)})}catch(a){throw CPe(a)}if(r.status!==200&&r.status!==206)throw await eUt(r),Yqt(r.status,r.headers.get("retry-after"));let o=r.body?.getReader();if(!o)throw new cr("no-body");let s=new Uint8Array(t),i=0;try{while(i<t){let{done:a,value:c}=await o.read();if(a||!c)break;let l=Math.min(c.length,t-i);s.set(c.subarray(0,l),i),i+=l}}catch(a){throw CPe(a)}finally{await o.cancel().catch(()=>{return})}if(i<(n.minBytes??0))throw new cr("short-body");return s.subarray(0,i)}var IPe={sideFileBytes:2097152,participantsBytes:16777216};function nUt(e,t){let n=/An error occurred \(([A-Za-z0-9]{1,40})\)/.exec(e)?.[1];if(n)return/^\d+$/.test(n)?`aws/http-${n}`:`aws/error-${n}`;return`aws/exit-${t}`}async function rUt(e,t,n={}){let r;try{let o=Bun.spawn(["aws","s3","cp",`s3://nemar/${e}/version/${t}.json`,"-"],{stdout:"pipe",stderr:"pipe",...n.env?{env:n.env}:{}}),s=!1;r=setTimeout(()=>{s=!0,o.kill("SIGKILL")},n.timeoutMs??600000);let[i,a,c]=await Promise.all([new Response(o.stdout).text(),new Response(o.stderr).text(),o.exited]);if(s)throw new cr("aws/timeout");if(c!==0)throw new cr(nUt(a,c));return i}catch(o){if(o instanceof cr)throw o;throw new cr("aws/unavailable")}finally{clearTimeout(r)}}function oUt(){let e;return async()=>{if(e!==void 0)return e;if(process.env.GITHUB_TOKEN)return e=process.env.GITHUB_TOKEN,e;try{let t=Bun.spawn(["gh","auth","token"],{stdout:"pipe",stderr:"ignore"}),n=(await new Response(t.stdout).text()).trim();e=n===""?null:n}catch{e=null}return e}}var J1=(e)=>e.replace(/\/+$/,"");function NPe(e={}){let t=e.retryAfterCapMs??30000,n=e.awsTimeoutMs??600000;return{api:J1(e.api??process.env.NEMAR_API_BASE??Gqt),data:J1(e.data??process.env.NEMAR_DATA_BASE??zqt),s3Base:J1(e.s3Base??Vqt),githubApi:J1(e.githubApi??Wqt),userAgent:e.userAgent??PPe,fileConcurrency:e.fileConcurrency??24,workerLimit:Kqt(e.workerConcurrency??6),timeoutMs:e.timeoutMs??30000,manifestTimeoutMs:e.manifestTimeoutMs??120000,retryBaseMs:e.retryBaseMs??400,sleep:e.sleep??((r)=>new Promise((o)=>setTimeout(o,r))),now:e.now??Date.now,retryAfterCapMs:t,breakers:Xqt({streak:e.abortStreak??25,retryAfterCapMs:t,now:e.now??Date.now}),limits:{treeHeaderSample:300,scansTables:1,jsonFiles:300,textFiles:300,sideFileBytes:65536,participantsBytes:1048576,...e.limits},readVersionManifest:e.readVersionManifest??((r,o)=>rUt(r,o,{timeoutMs:n,env:e.awsEnv})),githubToken:e.githubToken??oUt(),...e.readEntryHead?{readEntryHead:e.readEntryHead}:{}}}var FPe=(e,t)=>t.startsWith(`${e.data}/`),sUt=(e,t)=>FPe(e,t)||t.startsWith(`${e.api}/`)?e.breakers.worker:e.breakers.direct;async function iUt(e,t,n){let r=sUt(e,t);r.check();let o=r.pausedUntilMs()-e.now();if(o>0)await e.sleep(o),r.check();try{let s=await n();return r.ok(),s}catch(s){if(s instanceof cr)r.observe(s);throw s}}var aUt=(e,t)=>({...t===void 0?{}:{tries:t},baseMs:e.retryBaseMs,sleep:e.sleep,retryAfterCapMs:e.retryAfterCapMs});var APe=(e)=>/sub-([^/_]+)/.exec(e)?.[1]??"?";function OPe(e,t,n){if(t<1)return[];if(e.length<=t)return[...e];let r=new Map;for(let c of e){let l=n(c),d=r.get(l);if(d)d.push(c);else r.set(l,[c])}let o=[...r.entries()].sort(([c],[l])=>c<l?-1:c>l?1:0).map(([,c])=>c);if(o.length>t)return Array.from({length:t},(c,l)=>o[Math.floor((l+0.5)*o.length/t)][0]);let s=o.map((c,l)=>({list:c,index:l})).sort((c,l)=>c.list.length-l.list.length||c.index-l.index),i=t,a=[];return s.forEach(({list:c},l)=>{let d=Math.min(c.length,Math.ceil(i/(s.length-l)));for(let f=0;f<d;f++)a.push(c[Math.floor((f+0.5)*c.length/d)]);i-=d}),a}var cUt=(e)=>e.severity==="identifier"&&tke.has(e.kind),lUt=(e)=>zp.has(e.kind);function MPe(e){return e.headerRead===e.edfCount&&e.incompleteReasons.length===0}function uUt(e){if(e.findings.some(cUt))return"direct-identifiers";if(e.findings.some((t)=>!lUt(t)))return"review";if(!MPe(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 dUt=/\.(edf|bdf)$/i,fUt=(e)=>e.edf===!0||dUt.test(e.path);function pUt(e){return{edf:e.filter(fUt),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/")||!mUt.test(t.path)).filter((t)=>!hUt.test(t.path)),text:e.filter((t)=>gUt.test(t.path)).filter((t)=>t.path.startsWith("sourcedata/")||t.path.startsWith("code/"))}}var mUt=/_(eeg|ieeg|meg|emg|nirs|beh|events|channels|electrodes|coordsystem|scans|physio|stim|photo|T1w|bold)\.(json|tsv)$/,hUt=/(^|\/)(dataset_description|participants|genetic_info)\.json$/,gUt=/\.(py|m|r|txt|md|ya?ml|xml|iml|cfg|ini)$/i;function jPe(e,t,n,r=0){let o=()=>iUt(e,t.url,()=>{let s={minBytes:r,userAgent:e.userAgent,timeoutMs:e.timeoutMs};return e.readEntryHead?e.readEntryHead(t,n,s):tUt(t.url,n,s)});return Zqt(()=>FPe(e,t.url)?e.workerLimit(o):o(),aUt(e))}async function Y1(e,t,n){let r=await jPe(e,t,n),o=t.size===null?r.length>=n:t.size>n;return{text:new TextDecoder("utf-8",{fatal:!1}).decode(r),truncated:o}}function Db(e,t){for(let n of t)e.push(n)}var TPe="edf/superseded-absent";async function LPe(e,t,n,r,o,s={}){let i=r.map((Ie)=>Ie.path),a=o==="clone",c=(Ie,Re,Rn)=>a?[...Ie]:OPe(Ie,Re,Rn),l=[...eC([...i,...s.extraPaths??[]])],d=fke(i),f=Object.values(d.unscreened).reduce((Ie,Re)=>Ie+Re,0),p={},m=(Ie,Re)=>{if(Re instanceof _3)throw Re;let Rn=`${Ie}/${Qqt(Re)}`;p[Rn]=(p[Rn]??0)+1},h=(Ie)=>APe(Ie.path),g=pUt(r),y=new Set(s.supersededEdf??[]),b=[...g.edf,...y],{participants:x,scans:v,json:S,text:E}=g,A=o==="git-tree"?OPe(b,e.limits.treeHeaderSample,h):[...b],I=0,H=0,T=0,L=0,q={},V=new Set,B=new Set,M=new Set,P=new Set,G=new Set,se=new Set;await K1(A,e.fileConcurrency,async(Ie)=>{try{let Re=await jPe(e,Ie,At,At),Rn=cf(Re),{patient:Ab}=QD(Re);if(!Rn.some((us)=>us.kind==="edf-unreadable")){V.add(Ab);let us=Ab.split(/\s+/);if(us.length>=4)M.add(us[0]),G.add(us[2]),P.add(us[3])}if(se.add(APe(Ie.path)),Rn.some((us)=>us.severity==="identifier"))L++,B.add(Ab);Db(l,Rn);for(let us of new Set(Rn.map((Rm)=>Rm.kind)))q[us]=(q[us]??0)+1;I++}catch(Re){if(y.has(Ie)&&Re instanceof cr&&Re.status===404){T++,p[TPe]=(p[TPe]??0)+1;return}H++,m("edf",Re)}});let De=b.length-T,ln=!1,ot=!1;if(x&&x.size!==0)try{let{text:Ie,truncated:Re}=await Y1(e,x,e.limits.participantsBytes),Rn=Ie.indexOf(`
2603
2603
  `);if(Rn<0&&Re)throw new cr("header-truncated");Db(l,cke(Rn<0?Ie:Ie.slice(0,Rn))),Db(l,uke(Ie)),ot=Re}catch(Ie){ln=!0,m("participants",Ie)}let lt=c(v,e.limits.scansTables,h),ae=0;await K1(lt,e.fileConcurrency,async(Ie)=>{if(Ie.size===0){ae++;return}try{let{text:Re}=await Y1(e,Ie,e.limits.sideFileBytes);Db(l,ZD(Re)),ae++}catch(Re){m("scans",Re)}});let Ye=e.limits.sideFileBytes,Pe=(Ie)=>Ie.size!==null&&Ie.size>Ye,re=c(S.filter((Ie)=>!Pe(Ie)),e.limits.jsonFiles,h),st=c(E.filter((Ie)=>!Pe(Ie)),e.limits.textFiles,h),Ge=0,J=0;await K1(re,e.fileConcurrency,async(Ie)=>{if(Ie.size===0){Ge++;return}try{let{text:Re}=await Y1(e,Ie,Ye),Rn;try{Rn=JSON.parse(Re)}catch{throw new cr("json-parse")}Db(l,Gp(Rn)),Ge++}catch(Re){m("json",Re)}}),await K1(st,e.fileConcurrency,async(Ie)=>{if(Ie.size===0){J++;return}try{let{text:Re}=await Y1(e,Ie,Ye);Db(l,dke(Re)),J++}catch(Re){m("text",Re)}});let Y={edf_headers:{candidates:De,oversize:0,selected:A.length-T,scanned:I},scans_tables:{candidates:v.length,oversize:0,selected:lt.length,scanned:ae},json_files:{candidates:S.length,oversize:S.filter(Pe).length,selected:re.length,scanned:Ge},text_files:{candidates:E.length,oversize:E.filter(Pe).length,selected:st.length,scanned:J}},de=new Set,ye=(Ie,Re)=>{if(Re.oversize>0)de.add(`${Ie}-oversize`);if(Re.candidates-Re.oversize>Re.selected)de.add(`${Ie}-sampled`);if(Re.scanned<Re.selected)de.add(`${Ie}-unread`)};if(ye("edf-headers",Y.edf_headers),ye("json",Y.json_files),ye("text",Y.text_files),Y.scans_tables.scanned<Y.scans_tables.selected)de.add("scans-unread");if(ln)de.add("participants-unread");if(ot)de.add("participants-truncated");for(let Ie of s.extraIncompleteReasons??[])de.add(Ie);let ut=[...de].sort(),Tt={findings:l,edfCount:De,headerRead:I,unscreenedCount:f,incompleteReasons:ut},Ar=l.filter((Ie)=>Ie.severity==="identifier"),Is=Object.entries(p).filter(([Ie])=>!Ie.startsWith("edf/")).reduce((Ie,[,Re])=>Ie+Re,0);return{id:t,version:n,scanned_at:new Date().toISOString(),manifest_source:o,status:uUt(Tt),incomplete:!MPe(Tt),incomplete_reasons:ut,files:{total:r.length,edf_bdf:De,header_read:I,header_read_failed:H},sampling:Y,read_failures:p,edf_bdf_files_flagged:L,distinct_patient_field_values:V.size,distinct_subjects_with_edf_bdf:se.size,distinct_patient_code_subfield:M.size,distinct_patient_name_subfield:P.size,distinct_patient_birth_subfield:G.size,distinct_patient_field_values_in_flagged_files:B.size,findings_by_kind:pke(l),edf_bdf_files_by_kind:q,unscreened_formats:d.unscreened,side_reads_failed:Is,finding_fields:[...new Set(Ar.map((Ie)=>`${Ie.kind}:${Ie.field}`))].sort()}}fm();_n();_p();Xp();var Em="--acknowledge-identifier-preflight",_Ut=16,xUt="local:";function E3(e){let t=[],n=new Map,r=0,o=[""];while(o.length>0){let s=o.pop(),i;try{i=bUt(s===""?e:qPe(e,s),{withFileTypes:!0})}catch{r++;continue}i.sort((c,l)=>c.name<l.name?-1:c.name>l.name?1:0);let a=[];for(let c of i){let l=c.name;if(s===""&&(l===".git"||l===".nemar"))continue;let d=s===""?l:`${s}/${l}`;if(c.isDirectory()){a.push(d);continue}if(l===".gitattributes")continue;let f=`${xUt}${t.length}`,p=qPe(e,d),m=null;try{let h=UPe(p);if(h.isFile())m=h.size,n.set(f,p);else if(h.isDirectory()&&!yUt(p).isSymbolicLink()){a.push(d);continue}}catch{}t.push({path:d,size:m,url:f})}for(let c=a.length-1;c>=0;c--)o.push(a[c])}return{entries:t,readable:n,unlisted:r}}function vUt(e,t=new Map){return async(n,r,o)=>{let s=e.get(n.url);if(s===void 0)throw new cr("unreadable-entry");let i=t.get(s),a;try{a=await wUt(s,"r")}catch{throw new cr("unreadable-entry")}try{let c=n.size===null?r:Math.min(r,n.size),l=new Uint8Array(c),d=0;while(d<c){let{bytesRead:f}=await a.read(l,d,c-d,d);if(f===0)break;d+=f}if(d<o.minBytes)throw new cr("short-body");if(i)l.set(i.subarray(0,Math.min(d,i.length)),0);return l.subarray(0,d)}catch(c){if(c instanceof cr)throw c;throw new cr("unreadable-entry")}finally{await a.close().catch(()=>{return})}}}async function BPe(e,t){let n=E3(e),r=NPe({fileConcurrency:_Ut,workerConcurrency:1,limits:{...IPe},readEntryHead:vUt(n.readable,t),githubToken:async()=>null,readVersionManifest:async()=>{throw new cr("unreadable-entry")},sleep:async()=>{return}}),o=await LPe(r,"local",null,n.entries,"clone",{extraIncompleteReasons:n.unlisted>0?["tree-truncated"]:[]}),s={scanned_at:o.scanned_at,status:o.status,incomplete:o.incomplete,incomplete_reasons:o.incomplete_reasons,files:o.files,findings_by_kind:o.findings_by_kind,edf_bdf_files_flagged:o.edf_bdf_files_flagged,unscreened_formats:o.unscreened_formats,read_failures:o.read_failures};return vq(wAe(_Ae(s)))}function Z1(e){if(kf(e.status)!=="acknowledge")return[];let t=new Set([e.status]);if(e.incomplete&&e.status!=="unchecked")t.add("unchecked");let n=Object.values(e.unscreened_formats).reduce((o,s)=>o+s,0),r=e.status==="not-screened"||e.status==="clean-edf-only-others-unscreened";if(n>0&&!r)t.add("not-screened");return[...t].sort()}var HPe=(e,t)=>e.length===t.length&&e.every((n,r)=>n===t[r]);function GPe(e,t){let n=e.split(",").map((o)=>o.trim()).filter((o)=>o!==""),r=IA;if(n.length===0||!n.every((o)=>r.includes(o)))throw new Bo(`Allowed verdicts are ${r.join(", ")}. Direct identifiers cannot be acknowledged.`);return[...t??[],...n]}function EUt(e,t){let n=kf(e.status);if(n==="clear")return{action:"proceed",acknowledgedVia:null};if(n!=="acknowledge")return{action:"refuse"};if(t.acknowledge!==void 0){let r=[...new Set(t.acknowledge)].sort();return HPe(r,Z1(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 SUt={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"},x3=(e)=>`${Em} ${e.join(",")}`;function v3(e){console.log(u.yellow(" This does not stop an upload, but it needs your explicit acknowledgment of:"));for(let t of e)console.log(u.yellow(` ${t}: ${SUt[t]??"not clean"}.`));console.log(u.dim(" Your acknowledgment is recorded with your deposit attestation. NEMAR screens the dataset again when you request publication, and an administrator decides then."))}function zPe(){console.log(),console.log(u.red(" Upload refused: the preflight found direct identifiers (a name, a birth date finer than the year, a record number, an age over 89, or an identifying column or key). Nothing was sent.")),console.log(u.red(" Remove them from the files (for EDF/BDF, the patient and recording fields of the header) and run the upload again.")),console.log(u.dim(` There is no override, and ${Em} does not apply. If this is a false positive, please report it, so the scanner is fixed for every dataset. Terms: ${U1}`))}function VPe(e){if(e instanceof OA)return`report-${e.message}`;let t=e instanceof Error&&/^[A-Za-z]{1,40}$/.test(e.name)?e.name:"unknown",n=e?.code;return typeof n==="string"&&/^E[A-Z0-9]{1,20}$/.test(n)?`${t} ${n}`:t}function WPe(e,t){e.fail("Identifier preflight: DID NOT FINISH"),console.log(u.red(` The preflight could not produce a verdict, so nothing was uploaded (${VPe(t)}).`)),console.log(u.dim(" Please report this: https://github.com/nemarOrg/nemar-cli/issues"))}function Q1(e,t,n=""){let r=Eq(t,null),o=`${r.headline}${n}`;if(r.tone==="ok")e.succeed(o);else if(r.tone==="stop")e.fail(o);else e.warn(o);for(let s of rl({state:t.status,...r},2).slice(1))console.log(s)}function KPe(e,t){try{return vn(xAe({version:AA,scanner:`nemar-cli@${Gs}`,scan:e,acknowledged_via:t}))}catch(n){return console.log(u.red(` The preflight's record did not fit the report contract (${VPe(n)}), so nothing was uploaded.`)),Le}}async function JPe(e,t,n=process.stdin.isTTY===!0,r){let o=C("Screening for identifiers on this machine (nothing is sent)...").start(),s=!1;try{s=UPe(e).isDirectory()}catch{s=!1}if(!s)return o.fail("Identifier preflight: the dataset path is not a directory"),Le;let i=new Map((r?.items??[]).map((p)=>[p.path,p.after])),a;try{a=await BPe(e,i)}catch(p){return WPe(o,p),Le}Q1(o,a);let c=Z1(a),l=EUt(a,{acknowledge:t.acknowledgeIdentifierPreflight,dryRun:t.dryRun,no:t.no,isTty:n}),d;switch(l.action){case"proceed":if(l.acknowledgedVia==="flag")console.log(u.dim(` Acknowledged with ${x3(c)}.`));else if(t.acknowledgeIdentifierPreflight!==void 0)console.log(u.dim(` Nothing to acknowledge; ${Em} was not needed.`));d=l.acknowledgedVia;break;case"preview":return v3(c),console.log(u.yellow(` A real upload stops here until you acknowledge it: answer the prompt, or pass ${x3(c)}.`)),console.log(),vn(null);case"prompt":{v3(c);let p=!1,m=()=>{console.log(u.red(`
2604
2604
  Upload cancelled. Nothing was sent.`)),ue(),process.exit(130)};process.once("SIGINT",m);let h=setInterval(()=>{return},1000);try{({acknowledged:p}=await Ne.prompt([{type:"confirm",name:"acknowledged",message:"Upload anyway?",default:!1}]))}catch{p=!1}finally{clearInterval(h),process.off("SIGINT",m)}if(p!==!0)return console.log(u.red(" Upload cancelled. Nothing was sent.")),ue(),Le;console.log(u.dim(" Acknowledged at the prompt.")),d="prompt";break}case"refuse":return zPe(),ue(),Le;case"stop":if(l.why==="acknowledgment-mismatch")console.log(u.red(` ${Em} must name exactly what was found, which is: ${c.join(",")}. It does not acknowledge this scan. Nothing was sent.`));else v3(c),console.log(u.red(l.why==="declined"?" Declined (--no). Nothing was sent.":` No terminal to ask at: run interactively, or pass ${x3(c)}. --yes does not acknowledge a finding. Nothing was sent.`));return ue(),Le}let f=KPe(a,d);if(f.status==="ok")console.log();return f}async function YPe(e,t){let n=C("Screening again, right before anything is sent...").start(),r;try{r=await BPe(e)}catch(a){return WPe(n,a),Le}let o=kf(r.status);if(o!=="clear"&&o!=="acknowledge")return Q1(n,r),zPe(),ue(),Le;let s=Z1(t.scan),i=Z1(r);if(!HPe(s,i))return Q1(n,r),console.log(u.red(` The files changed since the preflight, and so did what it found (acknowledged: ${s.join(",")||"nothing"}; now: ${i.join(",")}). Nothing was sent. Run the upload again.`)),ue(),Le;if(TA(r.findings_by_kind)!==TA(t.scan.findings_by_kind))Q1(n,r," (screened again)");else n.succeed(`${Eq(r,null).headline} (screened again)`);return KPe(r,t.acknowledged_via)}var jUt=/\.(edf|bdf)$/i,nIe=Ra(".nemar","date-normalization"),LUt=()=>({tracked:0,"nested-repository":0,ignored:0,"tracking-unknown":0,link:0,"not-writable":0,"other-filesystem":0,unverified:0});function qUt(){return{items:[],left:LUt()}}function UUt(e){if(process.env.GIT_DIR||process.env.GIT_WORK_TREE)return!0;for(let t=e;;t=eO(t)){if(ZPe(Ra(t,".git")))return!0;if(eO(t)===t)return!1}}var R3=(e)=>e.normalize("NFC").toLowerCase();async function S3(e,t,n){try{let r=await O(e,{cwd:t,...n===void 0?{}:{stdin:n}});if(!(r.exitCode===0||e.includes("check-ignore")&&r.exitCode===1))return null;return new Set(r.stdout.split("\x00").filter(Boolean).map(R3))}catch{return null}}async function BUt(e,t){let n=`${t.join("\x00")}\x00`;if(UUt(e)){let o=await S3(["git","ls-files","-z"],e),s=await S3(["git","check-ignore","-z","--stdin"],e,n);return o&&s?{tracked:o,ignored:s}:null}let r=null;try{if(r=OUt(Ra(MUt(),"nemar-ignore-")),(await O(["git","init","-q","--bare",r],{cwd:e})).exitCode!==0)return null;let s=await S3(["git",`--git-dir=${r}`,`--work-tree=${e}`,"check-ignore","--no-index","-z","--stdin"],e,n);return s?{tracked:new Set,ignored:s}:null}catch{return null}finally{if(r!==null)try{O3(r,{recursive:!0,force:!0})}catch{}}}function $3(e){let t;try{t=A3(e,"r")}catch{return null}try{let n=new Uint8Array(At),r=0;while(r<At){let o=TUt(t,n,r,At-r,r);if(o===0)break;r+=o}return r===At?n:null}catch{return null}finally{try{C3(t)}catch{}}}var XPe=(e,t)=>e!==null&&e.length===t.length&&e.every((n,r)=>n===t[r]);function QPe(e){try{return RUt(e,k3.W_OK),!0}catch{return!1}}function HUt(e,t,n){let r=t.split("/").slice(0,-1);for(let o=1;o<=r.length;o++){let s=r.slice(0,o).join("/"),i=n.get(s);if(i===void 0){i=ZPe(Ra(e,s,".git"));try{i||=il(Ra(e,s,".git")).isSymbolicLink()}catch{}n.set(s,i)}if(i)return!0}return!1}async function rIe(e){let t=qUt();try{await GUt(e,t)}catch(n){In(`date normalization: planning stopped (${n instanceof Error?n.name:"unknown"})`)}return t}async function GUt(e,t){let n=tIe(e).dev,r=E3(e),o=[];for(let c of r.entries){if(!jUt.test(c.path))continue;let l=r.readable.get(c.url);if(l===void 0)continue;let d=$3(l);if(d===null)continue;try{let f=CL(d);if(f.changed)o.push({path:l,rel:c.path,before:d,after:f.header})}catch(f){if(f instanceof df)continue;t.left.unverified++,In(`date normalization: a header was not planned (${f instanceof Error?f.name:"unknown"})`)}}if(o.length===0)return;let s=await BUt(e,o.map((c)=>c.rel)),i=new Map,a=typeof process.getuid==="function"?process.getuid():null;for(let c of o){if(s===null){t.left["tracking-unknown"]++;continue}if(s.tracked.has(R3(c.rel))){t.left.tracked++;continue}if(HUt(e,c.rel,i)){t.left["nested-repository"]++;continue}if(s.ignored.has(R3(c.rel))){t.left.ignored++;continue}let l;try{l=il(c.path)}catch{continue}if(l.isSymbolicLink()){t.left.link++;continue}if(!l.isFile())continue;if(l.dev!==n){t.left["other-filesystem"]++;continue}if(a!==null&&l.uid!==a||(l.mode&128)===0||!QPe(c.path)||!QPe(eO(c.path))){t.left["not-writable"]++;continue}t.items.push({path:c.path,rel:c.rel,dev:l.dev,ino:l.ino,size:l.size,mtimeMs:l.mtimeMs,mode:l.mode,gid:l.gid,before:c.before,after:c.after})}}var zUt=/^\d+-[0-9a-f]{16}$/;function VUt(e){try{let t=Ra(e,nIe);for(let n of[Ra(e,".nemar"),t])if(!il(n).isDirectory())return;for(let n of PUt(t))if(zUt.test(n))O3(Ra(t,n),{force:!0})}catch{}}function D3(e){for(let t of e)try{NUt(t)}catch{}}function WUt(e,t){let n=[],r=Ra(e,nIe);try{for(let o of[Ra(e,".nemar"),r]){let s;try{s=il(o)}catch{AUt(o),n.push(o),s=il(o)}if(!s.isDirectory()||s.dev!==t)return D3([...n].reverse()),null}return{dir:r,made:n}}catch{return D3([...n].reverse()),null}}function KUt(e){try{let t=A3(e,"r");try{eIe(t)}finally{C3(t)}}catch{}}function JUt(e,t){let n=null;try{let r=(s)=>s.isFile()&&s.dev===e.dev&&s.ino===e.ino&&s.size===e.size&&s.mtimeMs===e.mtimeMs;if(!r(il(e.path))||!XPe($3(e.path),e.before))return null;if(n=Ra(t,`${process.pid}-${kUt(8).toString("hex")}`),CUt(e.path,n,k3.COPYFILE_EXCL|k3.COPYFILE_FICLONE),il(n).gid!==e.gid)DUt(n,-1,e.gid);$Ut(n,e.mode&4095);let o=A3(n,"r+");try{if(FUt(o,e.after,0,At,0)!==At)return null;eIe(o)}finally{C3(o)}if(il(n).size!==e.size||!XPe($3(n),e.after))return null;if(!r(il(e.path)))return null;return IUt(n,e.path),n=null,KUt(eO(e.path)),il(e.path).mtimeMs}catch(r){return In(`date normalization: a header was not set (${r instanceof Error?r.name:"unknown"})`),null}finally{if(n!==null)try{O3(n,{force:!0})}catch{}}}function oIe(e,t){let n={set:0,left:0,mtimes:new Map};if(VUt(e),t.items.length===0)return n;let r=null;try{r=WUt(e,tIe(e).dev)}catch{}if(r===null)return n.left=t.items.length,In("date normalization: no work directory, nothing set"),n;try{for(let o of t.items){let s=JUt(o,r.dir);if(s===null){n.left++;continue}n.set++,n.mtimes.set(o.rel,s)}}finally{D3([r.dir,...[...r.made].reverse().filter((o)=>o!==r.dir)])}if(n.set>0)console.log(u.dim(` ${gAe(n.set)}`));return n}We();hi();Ro();import{existsSync as sv,mkdirSync as m3t,readFileSync as iv,writeFileSync as EIe}from"fs";import{basename as h3t,resolve as Sm}from"path";kc();Ve();Jr();hi();import{existsSync as tO,readFileSync as T3,writeFileSync as iIe}from"fs";import{resolve as nO}from"path";var P3=[{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}],sIe=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 aIe(e){let t=nO(e,"dataset_description.json");if(tO(t))try{let r=JSON.parse(T3(t,"utf-8"));if(typeof r.License==="string"&&r.License.trim())return{spdxId:r.License.trim(),source:"dataset_description"}}catch(r){if(r instanceof SyntaxError)console.warn(` Warning: dataset_description.json has invalid JSON: ${r.message}`);else console.warn(` Warning: Could not read dataset_description.json: ${r instanceof Error?r.message:String(r)}`)}let n=["LICENSE","LICENSE.txt","LICENSE.md","LICENCE","LICENCE.txt"];for(let r of n){let o=nO(e,r);if(tO(o)){try{let s=T3(o,"utf-8").toLowerCase();if(s.includes("cc0")||s.includes("public domain dedication"))return{spdxId:"CC0-1.0",source:"license_file"};if(s.includes("attribution-noncommercial-sharealike"))return{spdxId:"CC-BY-NC-SA-4.0",source:"license_file"};if(s.includes("attribution-noncommercial"))return{spdxId:"CC-BY-NC-4.0",source:"license_file"};if(s.includes("attribution-sharealike"))return{spdxId:"CC-BY-SA-4.0",source:"license_file"};if(s.includes("creativecommons")&&s.includes("attribution"))return{spdxId:"CC-BY-4.0",source:"license_file"};if(s.includes("open database license")||s.includes("odbl"))return{spdxId:"ODbL-1.0",source:"license_file"};if(s.includes("open data commons")&&s.includes("attribution"))return{spdxId:"ODC-By-1.0",source:"license_file"};if(s.includes("public domain dedication and license")||s.includes("pddl"))return{spdxId:"PDDL-1.0",source:"license_file"};if(s.includes("permission is hereby granted, free of charge")||s.includes("mit license"))return{spdxId:"MIT",source:"license_file"}}catch(s){console.warn(` Warning: Could not read ${r}: ${s instanceof Error?s.message:String(s)}`)}return{spdxId:void 0,source:"license_file"}}}return{spdxId:void 0,source:"none"}}async function I3(e){let t=P3.map((o)=>({name:`${o.spdxId.padEnd(22)} ${o.description}`,value:o.spdxId,short:o.spdxId}));t.push({name:"Other (enter SPDX ID manually)",value:"__custom__",short:"Custom"});let n=e?P3.find((o)=>o.spdxId===e)?.spdxId:void 0,{selected:r}=await Ne.prompt([{type:"list",name:"selected",message:"Select a license for this dataset:",choices:t,default:n,pageSize:t.length}]);if(r==="__custom__"){let{customId:o}=await Ne.prompt([{type:"input",name:"customId",message:"Enter SPDX license ID (e.g., MIT, Apache-2.0):",validate:(s)=>{if(!s.trim())return"License ID is required";return!0}}]);return o.trim()}return r}function cIe(e){let t=e.toUpperCase().replace(/\s+/g,"-");if(sIe.has(e))return!0;for(let n of sIe)if(n.toUpperCase()===t)return!0;return!1}function YUt(e){let t=P3.find((n)=>n.spdxId===e);if(t)return`${t.name}
2605
2605
 
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.38-PR2280.9090eea",
4
+ "version": "0.10.38-dev.4682",
5
5
  "description": "CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",
6
6
  "type": "module",
7
7
  "main": "dist/index.js",