nemar-cli 0.10.38-dev.4706 → 0.10.39-PR2296.1810c4a

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,19 +23,19 @@ ${t}`,WM,YM,XM=(e,t,r)=>{let n=r===""?"":`with ${r.trim()}() `,s=BM.bind(null,n,
23
23
  `)}var Vl=!1;var{spawn:ZF}=globalThis.Bun;function zl(e,t=[]){let r=e.replace(eV,'("$1","<redacted>")');for(let n of t)if(n.length>=tV)r=r.split(n).join("<redacted>");return r}function nV(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 mE(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 gE(e,t={}){let r={...process.env,GIT_TERMINAL_PROMPT:"0",...t.env};for(let y of t.unsetEnv??[])delete r[y];let n=ZF({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??rV)};if(u(),t.timeout)o=setTimeout(()=>{s=!0,c(),n.kill()},t.timeout);let d=ac()?[...nV(r),...t.redact??[]]:[];if(ac()){let y=t.cwd?` (cwd=${t.cwd})`:"";qs(Pt.dim(zl(`$ ${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([mE(n.stdout,l),mE(n.stderr,l),m])}finally{if(c(),o)clearTimeout(o)}if(ac()){if(t.sensitiveOutput)qs(Pt.dim("[sensitive subprocess output suppressed]"));else{if(p.trim())qs(Pt.dim(zl(p.trimEnd(),d)));if(f.trim())qs(Pt.yellow(zl(f.trimEnd(),d)))}qs(Pt.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 eV,tV=8,rV=120000;var yE=F(()=>{Fl();eV=/\(\s*"((?:x-amz-)[^"]*|authorization|proxy-authorization)"\s*,\s*"[^"]*"\s*\)/gi});function oV(){if(process.platform==="darwin")return"macos";if(process.platform==="win32")return"windows";return"linux"}function vE(e,t=oV()){return e.installInstructions[t]}function iV(e){let t=e.match(/(\d+\.\d+(?:\.\d+)?)/);return t?t[1]:void 0}function cV(){let e=Number(process.env.TEST_PROBE_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:aV}async function $E(e){try{let{exitCode:t,stdout:r,timedOut:n}=await gE(e.cmd,{timeout:cV()});if(n)return{available:!1,timedOut:!0};if(t!==0)return{available:!1};return{available:!0,version:iV(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 Gl(){let e=Object.entries(_E);return Promise.all(e.map(async([t,r])=>{let{available:n,version:s,timedOut:o}=await $E(r);return{key:t,name:r.name,purpose:r.purpose,required:r.required,available:n,version:s,timedOut:o,installInstruction:vE(r)}}))}async function lB(){let t=(await Gl()).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 dB(e){let r=sV[e].map((i)=>_E[i]).filter(Boolean),n=await Promise.all(r.map(async(i)=>{let a=await $E(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:vE(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 _E,sV,aV=4000;var bE=F(()=>{yE();_E={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)"}}},sV={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 EE;var wE=F(()=>{EE={name:"nemar-cli",packageManager:"bun@1.4.3",version:"0.10.38-dev.4706",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 cc;var Kl=F(()=>{wE();cc=EE.version});import{mkdirSync as lV,readdirSync as dV,unlinkSync as fV,writeFileSync as pV}from"fs";import{join as Hl}from"path";function wB(){Ds=!0}function dc(){return Ds}function EB(e,t=process.env){return e.includes("--debug")||t.NEMAR_DEBUG==="1"}function SB(e){TE=e,mr(`Step: ${e}`)}function xB(){RE=!0}function RB(){return RE}function kB(){if(kE)return;Wl=!0}function TB(){Wl=!1,kE=!0}function OB(){return Wl}function mr(e){if(Ds)process.stderr.write(`[debug] ${e}
26
+ `))}var _E,sV,aV=4000;var bE=F(()=>{yE();_E={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)"}}},sV={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 EE;var wE=F(()=>{EE={name:"nemar-cli",packageManager:"bun@1.4.3",version:"0.10.39-PR2296.1810c4a",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 cc;var Kl=F(()=>{wE();cc=EE.version});import{mkdirSync as lV,readdirSync as dV,unlinkSync as fV,writeFileSync as pV}from"fs";import{join as Hl}from"path";function wB(){Ds=!0}function dc(){return Ds}function EB(e,t=process.env){return e.includes("--debug")||t.NEMAR_DEBUG==="1"}function SB(e){TE=e,mr(`Step: ${e}`)}function xB(){RE=!0}function RB(){return RE}function kB(){if(kE)return;Wl=!0}function TB(){Wl=!1,kE=!0}function OB(){return Wl}function mr(e){if(Ds)process.stderr.write(`[debug] ${e}
27
27
  `)}function yV(e){let t={};for(let[r,n]of Object.entries(e))t[r]=gV.has(r.toLowerCase())?"[REDACTED]":n;return t}function AE(e){let t=e.indexOf("@");if(t<=0)return"***";return`${e[0]}***${e.slice(t)}`}function Bl(e,t,r=0){if(r>vV)return"[REDACTED: depth]";if(Array.isArray(t))return t.map((n)=>Bl(e,n,r+1));if(t&&typeof t==="object"){let n={};for(let[s,o]of Object.entries(t))n[s]=Bl(s,o,r+1);return n}if(typeof t==="string"){if(_V.test(e))return"[REDACTED]";return t.replace(OE,AE)}return t}function Yl(e){return e.replace($V,"Bearer [REDACTED]").replace(bV,"[REDACTED_AWS_KEY]").replace(wV,"$1[REDACTED]").replace(EV,"$1$2=[REDACTED]").replace(OE,AE)}function SV(e){return Yl(e)}function SE(e,t=mV){if(e===void 0)return;let r=e;try{let n=JSON.parse(e);r=JSON.stringify(Bl("",n))}catch{}if(r=Yl(r),Buffer.byteLength(r,"utf8")>t)r=`${Buffer.from(r,"utf8").subarray(0,t).toString("utf8")}... [truncated]`;return r}function fc(e){if(!Ds)return;let t=SV(e.url);try{let r={...e,url:t,requestHeaders:e.requestHeaders?yV(e.requestHeaders):void 0,requestBody:SE(e.requestBody),responseBody:SE(e.responseBody)};lc.push(r),mr(`${e.method} ${t} -> ${e.status??"ERROR"} (${e.durationMs}ms)`)}catch(r){let n=pr(r);lc.push({method:e.method,url:t,status:e.status,durationMs:e.durationMs,note:`redaction failed: ${n}`}),mr(`redaction failed for ${e.method} ${t}: ${n}`)}}async function xV(){let e=[];try{let t=process.versions.bun?`Bun ${process.versions.bun}`:`Node ${process.version}`;e.push(`CLI version: ${cc}`),e.push(`OS/Arch: ${process.platform}/${process.arch}`),e.push(`Runtime: ${t}`)}catch(t){e.push(`(could not read CLI/OS/runtime info: ${pr(t)})`)}e.push(""),e.push("Active account:");try{let t=mn();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: ${pr(t)})`)}e.push(""),e.push("External tools:");try{let t=await Gl();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: ${pr(t)})`)}return e}async function RV(){return(await xV()).join(`
28
28
  `)}async function AB(){if(!Ds||uc!==void 0)return;try{uc=await RV()}catch(e){let t=pr(e);uc=`(could not build environment report: ${t})`,mr(`environment snapshot failed: ${t}`)}}function NE(e){if(xE.has(e))return{flag:e};for(let t of xE){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 kV(e){let t=[];for(let r=0;r<e.length;r++){let n=e[r],s=NE(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 TV(e){let t=[];for(let r=0;r<e.length;r++){let n=e[r],s=NE(n);if(!s){t.push(n);continue}if(!s.kind&&r+1<e.length)r++}return t}function OV(e){let t=[];for(let n of TV(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 AV(e,t){let r=[];if(r.push("NEMAR CLI Debug Log"),r.push(`Generated: ${new Date().toISOString()}`),r.push(`Command: nemar ${Yl(kV(e).join(" "))}`),r.push(""),r.push(uc??"(environment snapshot unavailable)"),r.push(""),r.push("HTTP requests:"),lc.length===0)r.push(" (none)");else lc.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: ${TE??"(none recorded)"}`),r.push(`Exit code: ${t}`),`${r.join(`
29
29
  `)}
30
30
  `}function NV(e,t){let r;try{r=dV(e).filter((s)=>s.startsWith("nemar-")&&s.endsWith(".log"))}catch(s){if(s.code!=="ENOENT")mr(`could not list ${e} for log rotation: ${pr(s)}`);return}r.sort();let n=r.length-t;for(let s=0;s<n;s++)try{fV(Hl(e,r[s]))}catch(o){if(o.code!=="ENOENT")mr(`could not remove old log ${r[s]}: ${pr(o)}`)}}function NB(){return zo}function IB(e,t){if(!Ds)return null;let r=Hl(Jl(),"logs");try{lV(r,{recursive:!0})}catch(i){return zo=pr(i),mr(`could not create log directory ${r}: ${zo}`),null}let s=`nemar-${new Date().toISOString().replace(/[:.]/g,"-")}-${OV(e)}.log`,o=Hl(r,s);try{pV(o,AV(e,t),"utf8")}catch(i){return zo=pr(i),mr(`could not write log file ${o}: ${zo}`),null}return NV(r,hV),o}var hV=10,mV=2048,Ds=!1,RE=!1,Wl=!1,kE=!1,TE,uc,lc,gV,_V,OE,vV=32,$V,bV,wV,EV,xE,zo;var Xl=F(()=>{jl();pc();bE();Kl();lc=[];gV=new Set(["authorization","cookie","set-cookie","x-api-key","x-approval-dispatch-token"]);_V=/^(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,OE=/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g;$V=/Bearer\s+[A-Za-z0-9\-._~+/=]+/gi,bV=/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g,wV=/((?:aws_)?secret_access_key["']?\s*[:=]\s*["']?)[A-Za-z0-9/+=]{20,}/gi,EV=/([?&])(X-Amz-Signature|X-Amz-Security-Token|X-Amz-Credential|Signature|AWSAccessKeyId)=[^&\s"']+/gi;xE=new Set(["-k","--key","--password","--api-key"])});import{chmodSync as IV,copyFileSync as PV,existsSync as Ql,mkdirSync as CV,statSync as jV}from"fs";import{homedir as hc}from"os";import{join as Ms}from"path";function DV(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 Jl(){return process.env.NEMAR_CONFIG_DIR||Ms(hc(),".config","nemar")}function LV(e){if(process.env.NEMAR_CONFIG_DIR)return;let t=Ms(e,"config.json");if(Ql(t))return;let r=[];if(process.platform==="darwin")r.push(Ms(hc(),"Library","Preferences","nemar-nodejs","config.json"));if(process.platform==="win32"){let n=process.env.APPDATA||Ms(hc(),"AppData","Roaming");r.push(Ms(n,"nemar-nodejs","config.json"))}r.push(Ms(hc(),".config","nemar-nodejs","config.json"));for(let n of r)if(Ql(n))try{CV(e,{recursive:!0}),PV(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 xt(){let e=Jl();if(Go&&IE===e)return Go;if(LV(e),Go=new Ha({projectName:"nemar",configFileMode:Zl,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}),IE=e,!PE.has(e))PE.add(e),UV(Go.path),VV(),zV();return Go}function UV(e){if(process.platform==="win32")return;if(!Ql(e))return;try{if((jV(e).mode&511)!==Zl)IV(e,Zl)}catch(t){console.error(`[nemar] could not secure config file permissions for ${e}:`,t)}}function VV(){let e=xt(),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 FV){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 zV(){let e=xt(),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(qV.has(DV(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 xt().get("activeAccount")}function gn(){return xt().get("accounts")||{}}function mn(){let e={apiUrl:Ls},t=Ko();if(!t)return e;return gn()[t]||e}function VB(e,t){let r=xt(),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 zB(e){let t=Ko();if(!t)return;let r=gn();if(r[t])delete r[t][e],xt().set("accounts",r)}function GB(){let e=xt(),t=Ko();if(!t){e.clear();return}let r=gn();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 KB(){xt().clear()}function HB(){return!!mn().apiKey}function BB(){return xt().path}function WB(){let e=gn(),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 YB(e){return e.username?.trim()||e.email}function GV(e){let t=e.trim().toLowerCase();if(!t)return;let r=Object.entries(gn()).filter(([,n])=>n.email&&n.email.toLowerCase()===t).map(([n])=>n);if(r.length>1){mr(`findAccountKeyByEmail: ${r.length} accounts share email ${t}: ${r.join(", ")}`);return}return r[0]}function XB(e,t){let r=xt(),n=gn(),s;if(n[e])s=e;else if(t.email)s=GV(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 JB(e){let t=e.trim();if(!t)return"unchanged";let r=xt(),n=Ko();if(!n||n===t)return"unchanged";let s=gn(),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 QB(e){let t=xt(),r=gn();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",Zl=384,qV,MV,FB,Go=null,IE=null,PE,FV;var pc=F(()=>{Vw();jn();sc();Xl();qV=new Set(["https://api.osc.earth/nemar","https://nemar-api.neuromechanist.workers.dev","https://nemar-api-dev.shirazi-10f.workers.dev"]);MV=ne({field:v(),blocks:Ze(v()).optional(),set_on:Ze(v()).optional()}).passthrough(),FB=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(MV).optional(),orcidVerified:Ue().optional(),role:v().optional(),accountKind:qn.optional(),pendingEmailChange:v().email().optional()});PE=new Set;FV=["apiKey","apiUrl","username","email","githubUsername","sandboxCompleted","sandboxDatasetId","dismissedNoticeIds"]});var KV,HV,r6,BV,n6,WV,CE,s6,o6=8,i6=100,jE,a6,YV,c6;var qE=F(()=>{jn();sc();KV=["given_name","family_name","affiliation","city","country"],HV=["username","github_username","email","orcid"],r6=[...KV,...HV],BV={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()},n6=ne(BV),WV=Ve(["field_not_editable","owner_only_field","edit_own_account","owner_account","system_account","invalid_edit","orcid_already_proven","invalid_search","invalid_user_id"]),CE=WV.options,s6=["exact","name","prefix","substring","fuzzy"],jE=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(),a6=ne({user:jE}).passthrough(),YV=ne({from:v().nullable(),to:v().nullable()}),c6=ne({message:v(),changed:kF(v(),YV),notes:Ze(v()).optional(),old_address_notified:Ue().optional(),user:jE}).passthrough()});var d6=120,f6=64,p6="unnamed machine",XV=25,DE,h6,Us,ME,m6,g6,y6,JV,QV,_6,ed,v6,$6,b6,w6,E6;var LE=F(()=>{jn();DE=Ve(["authorization_pending","slow_down","expired_token","access_denied","invalid_grant"]),h6={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"]),ME=Us.options,m6={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 ${XV} 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."},g6=ne({error:Us,message:v()}).passthrough(),y6=ne({device_code:v(),user_code:v(),verification_uri:v(),verification_uri_complete:v(),expires_in:fe().int(),interval:fe().int()}).passthrough(),JV=Xw("error",[ne({error:Pn("authorization_pending"),message:v()}).passthrough(),ne({error:Pn("slow_down"),message:v()}).passthrough()]),QV=Xw("error",[ne({error:Pn("expired_token"),reason:Us,message:v()}).passthrough(),ne({error:Pn("access_denied"),reason:Us,message:v()}).passthrough(),ne({error:Pn("invalid_grant"),reason:Us,message:v()}).passthrough()]),_6=RF([JV,QV]),ed=ne({id:fe().int(),name:v().nullable(),prefix:v(),created_at:v(),last_used_at:v().nullable(),current:Ue()}).passthrough(),v6=ne({api_key:v(),key:ed,user:ne({username:v().nullable(),email:v(),github_username:v().nullable(),role:v(),sandbox_completed:Ue(),sandbox_dataset_id:v().nullable()}).passthrough()}).passthrough(),$6=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(),b6=ne({ok:Pn(!0),machine_name:v()}).passthrough(),w6=ne({keys:Ze(ed)}).passthrough(),E6=ne({api_key:v(),key:ed}).passthrough()});var ZV,UE,Ho="https://nemar.org/settings",R6,e9,t9,r9,k6,T6;var FE=F(()=>{jn();ZV=Ve(["orcid_in_use","orcid_already_linked","orcid_linked_other","email_in_use","github_in_use","identity_conflict_remains"]),UE=ZV.options,R6={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."},e9=Ve(["orcid","email","github"]),t9=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(),r9=ne({kind:e9,value:v(),canonical_user_id:fe().int(),accounts:Ze(t9)}).passthrough(),k6=ne({groups:Ze(r9),group_count:fe().int(),flagged_count:fe().int()}).passthrough(),T6=ne({ok:Pn(!0),id:fe().int(),cleared:Ue()}).passthrough()});function A6(e){return Bo[e]}function N6(e,t){return e.replace(/\{(\w+)\}/g,(r,n)=>Object.hasOwn(t,n)?t[n]:r)}var Bo;var VE=F(()=>{Bo={"tier.unverified.label":"Email not verified","tier.base.label":"Base access","tier.upload.label":"Upload access","tier.unverified.lede":"Verify your email address to activate your account.","upload_access.section.title":"Upload access","upload_access.section.lede":"A one-time admin grant. Reviewed against export-control and local-jurisdiction rules.","upload_access.state.granted":"Granted","upload_access.state.requested":"Requested","upload_access.state.not_requested":"Not requested","upload_access.invite.title":"Want to contribute a dataset?","upload_access.invite.body":"Browsing, searching and downloading are open to your account already. Uploading, or being added as a collaborator on someone else\u2019s dataset, needs one extra grant: an admin checks your GitHub handle and location against export-control and local-jurisdiction rules, once. Your email address must be verified first.","upload_access.gate.title":"Ask for upload access first","upload_access.gate.body":"Your account can browse, search and download everything public already. Uploading, or being added as a collaborator on someone else\u2019s dataset, needs one extra grant, and your email address must be verified first: an admin checks your GitHub handle and where you\u2019re based against export-control and local-jurisdiction rules. You ask once, and it is answered by email.","upload_access.request.cta":"Request upload access","upload_access.request.form_body":"Tell us what you plan to deposit, or which dataset you want to collaborate on. An admin reviews this alongside your name, username, GitHub handle and location, then grants access once.","upload_access.request.why_label":"What do you intend to upload?","upload_access.request.why_hint":"Describe what you intend to upload in 20-500 characters","upload_access.requested.title":"Your request is with an admin","upload_access.requested.lede":"An admin is reviewing your request.","upload_access.requested.lede_dated":"An admin is reviewing your request from {date}.","upload_access.requested.body.upload":"We\u2019ll email you when there\u2019s a decision, and this page will let you upload as soon as it\u2019s granted.","upload_access.requested.body":"We\u2019ll email you when there\u2019s a decision. Everything else on your account keeps working in the meantime.","upload_access.requested.cta":"See the request","upload_access.granted.body":"You can upload datasets from the upload page. Publishing one is a separate, per-dataset review you start from your dashboard.","upload_access.unverified.body":"Verify your email address first \u2014 the review happens over email.","upload_access.docs_link":"How upload access works","gap.sentence":"{label} is missing: needed {blocks}.","gap.set_on.both":"Set it in {web} or run `{cli}`.","gap.set_on.web":"Set it in {web}.","gap.blocks.verified":"to activate your account","gap.blocks.upload_access":"to request upload access","gap.blocks.publication":"to publish a dataset","gap.blocks.unknown":"to finish setting up your account","gap.blocks.noun.verified":"account activation","gap.blocks.noun.upload_access":"upload access","gap.blocks.noun.publication":"publication","gap.set_on.default_web":"Settings","gap.field.email_verified.label":"A verified email address","gap.field.username.label":"Username","gap.field.given_name.label":"Given name","gap.field.family_name.label":"Family name","gap.field.orcid_verified.label":"Verified ORCID iD","gap.field.github_username.label":"GitHub handle","gap.field.city.label":"City","gap.field.country.label":"Country","gap.field.why.label":"A description of what you intend to upload","gap.field.email_verified.set_on.web":"the verify step on your dashboard","gap.field.email_verified.set_on.cli":"nemar auth resend-verification","gap.field.username.set_on.web":"Settings","gap.field.username.set_on.cli":"nemar auth profile set-username","gap.field.given_name.set_on.web":"Settings","gap.field.given_name.set_on.cli":"nemar auth profile set-name","gap.field.family_name.set_on.web":"Settings","gap.field.family_name.set_on.cli":"nemar auth profile set-name","gap.field.given_name.set_on.web.orcid":"your ORCID record at orcid.org, then sign in again","gap.field.family_name.set_on.web.orcid":"your ORCID record at orcid.org, then sign in again","gap.field.orcid_verified.set_on.web":"Settings","gap.field.orcid_verified.set_on.cli":"nemar auth profile orcid link","gap.field.github_username.set_on.web":"Settings","gap.field.github_username.set_on.cli":"nemar auth profile set-github","gap.field.city.set_on.web":"Settings","gap.field.city.set_on.cli":"nemar auth profile set-location","gap.field.country.set_on.web":"Settings","gap.field.country.set_on.cli":"nemar auth profile set-location","gap.field.why.set_on.web":"the request form in Settings","gap.field.why.set_on.cli":"nemar auth request-upload-access","gaps.title":"What is still missing","gaps.none":"Nothing outstanding \u2014 every field NEMAR needs is filled in.","gaps.nudge.title":"Your profile isn\u2019t finished yet","gaps.nudge.cta":"Complete your profile","gaps.upload.title":"Before you can ask, your account still needs:","gaps.request.title":"Finish these first:","gaps.admin.title":"Still missing","gaps.admin.item":"{label} \u2014 blocks {blocks}","gaps.admin.none":"Nothing missing \u2014 every field the request needs is filled in.","gaps.admin.not_loaded":"Not loaded \u2014 open the user page to see what is still missing.","onboarding.username.auto_assigned.title":"We chose your username from your name","onboarding.username.auto_assigned.body":"Your account needed a username to be listed as a dataset owner, so one was made from your name when you signed in. You can change it once, here, until an admin grants you upload access.","welcome.unverified.title":"Verify your email address","welcome.unverified.body":"Authorizing with ORCID created your NEMAR account and signed you in. One step left: enter the 6-digit code we emailed you. That activates the account \u2014 no admin approval is involved.","welcome.active.title":"Your account is active","welcome.active.body":"Authorizing with ORCID created your NEMAR account and signed you in. There is no separate sign-up step and no approval queue: browse, search, and your dashboard all work right now.","welcome.upload_access.title":"Ask for upload access when you\u2019re ready to contribute","welcome.upload_access.body":"Reading is open to every verified account. Uploading and compute need one extra grant, because an admin has to check your GitHub handle and location against export-control and local-jurisdiction rules first. You ask once, from Settings.","oidc.consent.title":"{client} wants to use your NEMAR account","oidc.consent.acts_as_you":"If you allow it, {client} can act as you on NEMAR in the ways listed below.","oidc.consent.compute_spend":"If you sign in and run compute with this app, it counts against your NEMAR compute allocation.","oidc.consent.scopes_title":"It is asking to:","oidc.consent.scope.openid":"Know which NEMAR account is yours","oidc.consent.scope.profile":"See your name","oidc.consent.scope.email":"See your email address","oidc.consent.scope.orcid":"See your ORCID iD, and whether you proved it by signing in with ORCID","oidc.consent.scope.nemar.account":"See your account type, status and access level","oidc.consent.scope.offline_access":"Keep this access when you are not using it","oidc.consent.scope.compute.read":"See your compute access, balances, usage and jobs","oidc.consent.scope.compute.reserve":"Reserve compute time, report jobs and release reservations for you","oidc.consent.scope.compute.submit":"Submit compute jobs that NEMAR runs for you","oidc.consent.redirect_host":"Either answer sends you to {redirect_host}.","oidc.consent.allow":"Allow","oidc.consent.deny":"Deny","oidc.rule.title":"You can\u2019t sign in to {client} with this account","oidc.rule.account_inactive":"Your NEMAR account is not active.","oidc.rule.account_not_person":"{client} is only for personal accounts, and this account is not one.","oidc.rule.orcid_not_proven":"{client} needs an ORCID iD you proved by signing in to NEMAR with ORCID. Link your ORCID iD in Settings, then try again.","oidc.rule.return":"Return to {client}","oidc.error.title":"This sign-in can\u2019t continue","oidc.error.invalid_client":"The site that sent you here is not one NEMAR signs people in to.","oidc.error.invalid_redirect_uri":"The site that sent you here asked NEMAR to send you to an address it has not registered, so NEMAR will not send you there.","oidc.error.invalid_request":"The sign-in request is incomplete or malformed. Go back to the site you came from and start again.","oidc.error.consent_invalid":"This page has expired. Go back to the site you came from and start again.","oidc.error.unavailable":"NEMAR could not complete this sign-in right now. Try again in a moment.","oidc.error.rate_limited":"Too many sign-in attempts. Try again in a minute.","mail.category.news.label":"News","mail.category.news.description":"New features, data and events.","mail.category.rfcs.label":"Requests for comments","mail.category.rfcs.description":"A new NEMAR request for comments is open for discussion.","mail.category.maintenance.label":"Maintenance","mail.category.maintenance.description":"Planned downtime and changes to the service.","mail.category.recall.label":"Recalls","mail.category.recall.description":"A dataset, release or credential NEMAR distributed has a problem you need to act on.","mail.recall.why":"Recalls cannot be turned off: they tell you to stop using, delete or replace something NEMAR distributed or issued, because continuing to use it can cause harm.","cli.gaps.section.title":"Profile","cli.gaps.unknown":"not checked: run 'nemar auth status --refresh'","cli.gaps.unreported":"not reported by this backend","cli.gap.set_on.cli_only":"Run `{cli}`.","cli.gap.field.sandbox.label":"Sandbox training","cli.gap.blocks.sandbox":"to upload a dataset from the CLI","cli.gap.field.sandbox.set_on.cli":"nemar sandbox","cli.gaps.sandbox_unchecked":"Sandbox training could not be confirmed with the server. Run `nemar sandbox status --refresh`, then `nemar sandbox` if it is still outstanding.","cli.upload.preflight.title":"Upload access is not granted yet","cli.upload.preflight.body":"Browsing, searching and downloading are open to your account already. Uploading, or being added as a collaborator on someone else\u2019s dataset, needs one extra grant: an admin checks your GitHub handle and location against export-control and local-jurisdiction rules, once. Your email address must be verified first.","cli.upload_access.cta":"Ask for it with `nemar auth request-upload-access`.","cli.upload.preflight.unchecked":"Upload access could not be checked ({reason}); continuing.","cli.upload.preflight.gaps_unknown":"Could not determine what is still missing; run `nemar auth profile` for the list.","cli.upload.preflight.dry_run":"Continuing anyway: --dry-run uploads nothing."}});function j6(e){return typeof e==="string"&&n9.includes(e)}function q6(e){return typeof e==="string"&&zE.includes(e)}function D6(e){return Bo[`mail.category.${e}.label`]}function M6(e){return Bo[`mail.category.${e}.description`]}function L6(){return Bo["mail.recall.why"]}function o9(e){return e.replace(/\r\n?/g,`
32
+ [nemar] You can manually copy ${n} to ${t}`)}}function xt(){let e=Jl();if(Go&&IE===e)return Go;if(LV(e),Go=new Ha({projectName:"nemar",configFileMode:Zl,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}),IE=e,!PE.has(e))PE.add(e),UV(Go.path),VV(),zV();return Go}function UV(e){if(process.platform==="win32")return;if(!Ql(e))return;try{if((jV(e).mode&511)!==Zl)IV(e,Zl)}catch(t){console.error(`[nemar] could not secure config file permissions for ${e}:`,t)}}function VV(){let e=xt(),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 FV){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 zV(){let e=xt(),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(qV.has(DV(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 xt().get("activeAccount")}function gn(){return xt().get("accounts")||{}}function mn(){let e={apiUrl:Ls},t=Ko();if(!t)return e;return gn()[t]||e}function VB(e,t){let r=xt(),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 zB(e){let t=Ko();if(!t)return;let r=gn();if(r[t])delete r[t][e],xt().set("accounts",r)}function GB(){let e=xt(),t=Ko();if(!t){e.clear();return}let r=gn();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 KB(){xt().clear()}function HB(){return!!mn().apiKey}function BB(){return xt().path}function WB(){let e=gn(),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 YB(e){return e.username?.trim()||e.email}function GV(e){let t=e.trim().toLowerCase();if(!t)return;let r=Object.entries(gn()).filter(([,n])=>n.email&&n.email.toLowerCase()===t).map(([n])=>n);if(r.length>1){mr(`findAccountKeyByEmail: ${r.length} accounts share email ${t}: ${r.join(", ")}`);return}return r[0]}function XB(e,t){let r=xt(),n=gn(),s;if(n[e])s=e;else if(t.email)s=GV(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 JB(e){let t=e.trim();if(!t)return"unchanged";let r=xt(),n=Ko();if(!n||n===t)return"unchanged";let s=gn(),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 QB(e){let t=xt(),r=gn();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",Zl=384,qV,MV,FB,Go=null,IE=null,PE,FV;var pc=F(()=>{Vw();jn();sc();Xl();qV=new Set(["https://api.osc.earth/nemar","https://nemar-api.neuromechanist.workers.dev","https://nemar-api-dev.shirazi-10f.workers.dev"]);MV=ne({field:v(),blocks:Ze(v()).optional(),set_on:Ze(v()).optional()}).passthrough(),FB=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(MV).optional(),orcidVerified:Ue().optional(),role:v().optional(),accountKind:qn.optional(),pendingEmailChange:v().email().optional()});PE=new Set;FV=["apiKey","apiUrl","username","email","githubUsername","sandboxCompleted","sandboxDatasetId","dismissedNoticeIds"]});var KV,HV,r6,BV,n6,WV,CE,s6,o6=8,i6=100,jE,a6,YV,c6;var qE=F(()=>{jn();sc();KV=["given_name","family_name","affiliation","city","country"],HV=["username","github_username","email","orcid"],r6=[...KV,...HV],BV={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()},n6=ne(BV),WV=Ve(["field_not_editable","owner_only_field","edit_own_account","owner_account","system_account","invalid_edit","orcid_already_proven","invalid_search","invalid_user_id"]),CE=WV.options,s6=["exact","name","prefix","substring","fuzzy"],jE=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(),a6=ne({user:jE}).passthrough(),YV=ne({from:v().nullable(),to:v().nullable()}),c6=ne({message:v(),changed:kF(v(),YV),notes:Ze(v()).optional(),old_address_notified:Ue().optional(),user:jE}).passthrough()});var d6=120,f6=64,p6="unnamed machine",XV=25,DE,h6,Us,ME,m6,g6,y6,JV,QV,_6,ed,v6,$6,b6,w6,E6;var LE=F(()=>{jn();DE=Ve(["authorization_pending","slow_down","expired_token","access_denied","invalid_grant"]),h6={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"]),ME=Us.options,m6={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 ${XV} 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."},g6=ne({error:Us,message:v()}).passthrough(),y6=ne({device_code:v(),user_code:v(),verification_uri:v(),verification_uri_complete:v(),expires_in:fe().int(),interval:fe().int()}).passthrough(),JV=Xw("error",[ne({error:Pn("authorization_pending"),message:v()}).passthrough(),ne({error:Pn("slow_down"),message:v()}).passthrough()]),QV=Xw("error",[ne({error:Pn("expired_token"),reason:Us,message:v()}).passthrough(),ne({error:Pn("access_denied"),reason:Us,message:v()}).passthrough(),ne({error:Pn("invalid_grant"),reason:Us,message:v()}).passthrough()]),_6=RF([JV,QV]),ed=ne({id:fe().int(),name:v().nullable(),prefix:v(),created_at:v(),last_used_at:v().nullable(),current:Ue()}).passthrough(),v6=ne({api_key:v(),key:ed,user:ne({username:v().nullable(),email:v(),github_username:v().nullable(),role:v(),sandbox_completed:Ue(),sandbox_dataset_id:v().nullable()}).passthrough()}).passthrough(),$6=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(),b6=ne({ok:Pn(!0),machine_name:v()}).passthrough(),w6=ne({keys:Ze(ed)}).passthrough(),E6=ne({api_key:v(),key:ed}).passthrough()});var ZV,UE,Ho="https://nemar.org/settings",R6,e9,t9,r9,k6,T6;var FE=F(()=>{jn();ZV=Ve(["orcid_in_use","orcid_already_linked","orcid_linked_other","email_in_use","github_in_use","identity_conflict_remains"]),UE=ZV.options,R6={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."},e9=Ve(["orcid","email","github"]),t9=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(),r9=ne({kind:e9,value:v(),canonical_user_id:fe().int(),accounts:Ze(t9)}).passthrough(),k6=ne({groups:Ze(r9),group_count:fe().int(),flagged_count:fe().int()}).passthrough(),T6=ne({ok:Pn(!0),id:fe().int(),cleared:Ue()}).passthrough()});function A6(e){return Bo[e]}function N6(e,t){return e.replace(/\{(\w+)\}/g,(r,n)=>Object.hasOwn(t,n)?t[n]:r)}var Bo;var VE=F(()=>{Bo={"tier.unverified.label":"Email not verified","tier.base.label":"Base access","tier.upload.label":"Upload access","tier.unverified.lede":"Verify your email address to activate your account.","upload_access.section.title":"Upload access","upload_access.section.lede":"A one-time admin grant. Reviewed against export-control and local-jurisdiction rules.","upload_access.state.granted":"Granted","upload_access.state.requested":"Requested","upload_access.state.not_requested":"Not requested","upload_access.invite.title":"Want to contribute a dataset?","upload_access.invite.body":"Browsing, searching and downloading are open to your account already. Uploading, or being added as a collaborator on someone else\u2019s dataset, needs one extra grant: an admin checks your GitHub handle and location against export-control and local-jurisdiction rules, once. Your email address must be verified first.","upload_access.gate.title":"Ask for upload access first","upload_access.gate.body":"Your account can browse, search and download everything public already. Uploading, or being added as a collaborator on someone else\u2019s dataset, needs one extra grant, and your email address must be verified first: an admin checks your GitHub handle and where you\u2019re based against export-control and local-jurisdiction rules. You ask once, and it is answered by email.","upload_access.request.cta":"Request upload access","upload_access.request.form_body":"Tell us what you plan to deposit, or which dataset you want to collaborate on. An admin reviews this alongside your name, username, GitHub handle and location, then grants access once.","upload_access.request.why_label":"What do you intend to upload?","upload_access.request.why_hint":"Describe what you intend to upload in 20-500 characters","upload_access.requested.title":"Your request is with an admin","upload_access.requested.lede":"An admin is reviewing your request.","upload_access.requested.lede_dated":"An admin is reviewing your request from {date}.","upload_access.requested.body.upload":"We\u2019ll email you when there\u2019s a decision, and this page will let you upload as soon as it\u2019s granted.","upload_access.requested.body":"We\u2019ll email you when there\u2019s a decision. Everything else on your account keeps working in the meantime.","upload_access.requested.cta":"See the request","upload_access.granted.body":"You can upload datasets from the upload page. Publishing one is a separate, per-dataset review you start from your dashboard.","upload_access.unverified.body":"Verify your email address first \u2014 the review happens over email.","upload_access.docs_link":"How upload access works","gap.sentence":"{label} is missing: needed {blocks}.","gap.set_on.both":"Set it in {web} or run `{cli}`.","gap.set_on.web":"Set it in {web}.","gap.blocks.verified":"to activate your account","gap.blocks.upload_access":"to request upload access","gap.blocks.publication":"to publish a dataset","gap.blocks.unknown":"to finish setting up your account","gap.blocks.noun.verified":"account activation","gap.blocks.noun.upload_access":"upload access","gap.blocks.noun.publication":"publication","gap.set_on.default_web":"Settings","gap.field.email_verified.label":"A verified email address","gap.field.username.label":"Username","gap.field.given_name.label":"Given name","gap.field.family_name.label":"Family name","gap.field.orcid_verified.label":"Verified ORCID iD","gap.field.github_username.label":"GitHub handle","gap.field.city.label":"City","gap.field.country.label":"Country","gap.field.why.label":"A description of what you intend to upload","gap.field.email_verified.set_on.web":"the verify step on your dashboard","gap.field.email_verified.set_on.cli":"nemar auth resend-verification","gap.field.username.set_on.web":"Settings","gap.field.username.set_on.cli":"nemar auth profile set-username","gap.field.given_name.set_on.web":"Settings","gap.field.given_name.set_on.cli":"nemar auth profile set-name","gap.field.family_name.set_on.web":"Settings","gap.field.family_name.set_on.cli":"nemar auth profile set-name","gap.field.given_name.set_on.web.orcid":"your ORCID record at orcid.org, then sign in again","gap.field.family_name.set_on.web.orcid":"your ORCID record at orcid.org, then sign in again","gap.field.orcid_verified.set_on.web":"Settings","gap.field.orcid_verified.set_on.cli":"nemar auth profile orcid link","gap.field.github_username.set_on.web":"Settings","gap.field.github_username.set_on.cli":"nemar auth profile set-github","gap.field.city.set_on.web":"Settings","gap.field.city.set_on.cli":"nemar auth profile set-location","gap.field.country.set_on.web":"Settings","gap.field.country.set_on.cli":"nemar auth profile set-location","gap.field.why.set_on.web":"the request form in Settings","gap.field.why.set_on.cli":"nemar auth request-upload-access","gaps.title":"What is still missing","gaps.none":"Nothing outstanding \u2014 every field NEMAR needs is filled in.","gaps.nudge.title":"Your profile isn\u2019t finished yet","gaps.nudge.cta":"Complete your profile","gaps.upload.title":"Before you can ask, your account still needs:","gaps.request.title":"Finish these first:","gaps.admin.title":"Still missing","gaps.admin.item":"{label} \u2014 blocks {blocks}","gaps.admin.none":"Nothing missing \u2014 every field the request needs is filled in.","gaps.admin.not_loaded":"Not loaded \u2014 open the user page to see what is still missing.","onboarding.username.auto_assigned.title":"We chose your username from your name","onboarding.username.auto_assigned.body":"Your account needed a username to be listed as a dataset owner, so one was made from your name when you signed in. You can change it once, here, until an admin grants you upload access.","welcome.unverified.title":"Verify your email address","welcome.unverified.body":"Authorizing with ORCID created your NEMAR account and signed you in. One step left: enter the 6-digit code we emailed you. That activates the account \u2014 no admin approval is involved.","welcome.active.title":"Your account is active","welcome.active.body":"Authorizing with ORCID created your NEMAR account and signed you in. There is no separate sign-up step and no approval queue: browse, search, and your dashboard all work right now.","welcome.upload_access.title":"Ask for upload access when you\u2019re ready to contribute","welcome.upload_access.body":"Reading is open to every verified account. Uploading and compute need one extra grant, because an admin has to check your GitHub handle and location against export-control and local-jurisdiction rules first. You ask once, from Settings.","oidc.consent.title":"{client} wants to use your NEMAR account","oidc.consent.acts_as_you":"If you allow it, {client} can act as you on NEMAR in the ways listed below.","oidc.consent.compute_spend":"If you sign in and run compute with this app, it counts against your NEMAR compute allocation.","oidc.consent.scopes_title":"It is asking to:","oidc.consent.scope.openid":"Know which NEMAR account is yours","oidc.consent.scope.profile":"See your name","oidc.consent.scope.email":"See your email address","oidc.consent.scope.orcid":"See your ORCID iD, and whether you proved it by signing in with ORCID","oidc.consent.scope.nemar.account":"See your account type, status and access level","oidc.consent.scope.offline_access":"Keep this access when you are not using it","oidc.consent.scope.compute.read":"See your compute access, balances, usage and jobs","oidc.consent.scope.compute.reserve":"Reserve compute time, report jobs and release reservations for you","oidc.consent.scope.compute.submit":"Submit compute jobs that NEMAR runs for you","oidc.consent.redirect_host":"Either answer sends you to {redirect_host}.","oidc.consent.allow":"Allow","oidc.consent.deny":"Deny","oidc.rule.title":"You can\u2019t sign in to {client} with this account","oidc.rule.account_inactive":"Your NEMAR account is not active.","oidc.rule.account_not_person":"{client} is only for personal accounts, and this account is not one.","oidc.rule.orcid_not_proven":"{client} needs an ORCID iD you proved by signing in to NEMAR with ORCID. Link your ORCID iD in Settings, then try again.","oidc.rule.return":"Return to {client}","oidc.error.title":"This sign-in can\u2019t continue","oidc.error.invalid_client":"The site that sent you here is not one NEMAR signs people in to.","oidc.error.invalid_redirect_uri":"The site that sent you here asked NEMAR to send you to an address it has not registered, so NEMAR will not send you there.","oidc.error.invalid_request":"The sign-in request is incomplete or malformed. Go back to the site you came from and start again.","oidc.error.consent_invalid":"This page has expired. Go back to the site you came from and start again.","oidc.error.unavailable":"NEMAR could not complete this sign-in right now. Try again in a moment.","oidc.error.rate_limited":"Too many sign-in attempts. Try again in a minute.","mail.category.news.label":"News","mail.category.news.description":"New features, data and events.","mail.category.rfcs.label":"Requests for comments","mail.category.rfcs.description":"A new NEMAR request for comments is open for discussion.","mail.category.maintenance.label":"Maintenance","mail.category.maintenance.description":"Planned downtime and changes to the service.","mail.category.recall.label":"Recalls","mail.category.recall.description":"A dataset, release or credential NEMAR distributed has a problem you need to act on.","mail.recall.why":"Recalls cannot be turned off: they tell you to stop using, delete or replace something NEMAR distributed or issued, because continuing to use it can cause harm.","cli.gaps.section.title":"Profile","cli.gaps.unknown":"not checked: run 'nemar auth status --refresh'","cli.gaps.unreported":"not reported by this backend","cli.gap.set_on.cli_only":"Run `{cli}`.","cli.gap.field.sandbox.label":"Sandbox training","cli.gap.blocks.sandbox":"to upload a dataset from the CLI","cli.gap.field.sandbox.set_on.cli":"nemar sandbox","cli.gaps.sandbox_unchecked":"Sandbox training could not be confirmed with the server. Run `nemar sandbox status --refresh`, then `nemar sandbox` if it is still outstanding.","cli.upload.preflight.title":"Upload access is not granted yet","cli.upload.preflight.body":"Browsing, searching and downloading are open to your account already. Uploading, or being added as a collaborator on someone else\u2019s dataset, needs one extra grant: an admin checks your GitHub handle and location against export-control and local-jurisdiction rules, once. Your email address must be verified first.","cli.upload_access.cta":"Ask for it with `nemar auth request-upload-access`.","cli.upload.preflight.unchecked":"Upload access could not be checked ({reason}); continuing.","cli.upload.preflight.gaps_unknown":"Could not determine what is still missing; run `nemar auth profile` for the list.","cli.upload.preflight.dry_run":"Continuing anyway: --dry-run uploads nothing."}});function j6(e){return typeof e==="string"&&n9.includes(e)}function q6(e){return typeof e==="string"&&zE.includes(e)}function D6(e){return Bo[`mail.category.${e}.label`]}function M6(e){return Bo[`mail.category.${e}.description`]}function L6(){return Bo["mail.recall.why"]}function o9(e){return e.replace(/\r\n?/g,`
33
33
  `).trim().split(/\n{2,}/).map((t)=>t.trim()).filter((t)=>t!=="")}function i9(e){let t=/^(#{1,3})\s+(.+)$/.exec(e);if(!t)return null;return{level:t[1].length,text:t[2]}}function U6(e){let t=new Set(o9(e).map((r)=>i9(r)?.text.trim().toLowerCase()).filter((r)=>Boolean(r)));return s9.filter((r)=>!t.has(r.toLowerCase()))}function F6(e){let t=e.trim(),r=a9.exec(t);if(r)return{kind:"dataset",datasetId:r[1],version:r[2]??null,text:t};if(c9.test(t))return{kind:"github",url:t,text:t};return null}var zE,n9,C6="recall",GE,s9,a9,c9,V6="A recall needs a reference: a dataset id with an optional version (nm000104 or nm000104@v1.2.0), or a nemarOrg or nemarDatasets issue, pull request or security advisory URL.";var KE=F(()=>{VE();zE=["news","rfcs","maintenance"],n9=[...zE,"recall"];GE=["recall_cannot_be_turned_off","admin_alert_not_self_service","unknown_mail_preference","invalid_mail_preference"];s9=["What is affected","What to do"];a9=/^([a-z]{2}\d{6})(?:@v?(\d+\.\d+\.\d+))?$/,c9=/^https:\/\/github\.com\/(?:nemarOrg|nemarDatasets)\/[A-Za-z0-9._-]+\/(?:(?:issues|pull)\/\d{1,9}|security\/advisories\/GHSA(?:-[a-z0-9]{4}){3})$/});function W6(e){return typeof e==="string"&&l9.includes(e)}var u9,K6,H6,B6,l9,d9="ci_check_unavailable",HE,BE,WE,Y6="X-Approval-Dispatch-Token",X6,J6="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 YE=F(()=>{jn();u9=/^\d{4}-\d{4}-\d{4}-\d{3}[\dX]$/,K6=v().regex(u9,"ORCID must be in format 0000-0000-0000-000X"),H6=Ve(["found","no_public_name","lookup_failed"]),B6=Ve(["bids_validation_failed","bids_validation_pending","bids_validation_in_progress","prescreen_failed","min_requirements_failed","owner_name_missing","identifier_screen_findings"]),l9=["bids_validation_pending","bids_validation_in_progress"];HE=[d9],BE=["identifier_screen_pending","identifier_screen_not_clear","identifier_screen_not_applicable"],WE=["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 JE(e){if(XE)return;XE=!0;let t=Pt.yellow("\u2500".repeat(60)),r=Pt.yellow.bold("[MAINTENANCE]"),n=Pt.dim(`mode: ${e.mode}`),s=e.eta?`
34
34
  ${Pt.dim(`eta: ${e.eta}`)}`:"";process.stderr.write(`${t}
35
35
  ${r} ${e.message}
36
36
  ${n}${s}
37
37
  ${t}
38
- `)}var XE=!1;var QE=F(()=>{Fl()});function ZE(){if(process.env.TEST_API_URL)return process.env.TEST_API_URL;if(rd)return td;return mn().apiUrl||td}async function fW(e,t={},r=!1,n){let s=`${ZE()}${e}`,o={"Content-Type":"application/json","X-CLI-Version":cc,...t.headers};if(r){let p=mn();if(!p.apiKey&&r===!0)throw new hr(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(dc())fc({method:i,url:s,status:null,durationMs:Date.now()-c,requestHeaders:o,requestBody:a,error:p instanceof Error?p.message:String(p)});throw new hr(0,`Network error: Could not connect to ${ZE()}`,{originalError:p instanceof Error?p.message:String(p)})}let d;try{d=await u.text()}catch(p){if(dc())fc({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 hr(0,"Failed to read response body",{httpStatus:u.status,originalError:p instanceof Error?p.message:String(p)})}if(dc())fc({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 hr(u.status,`Invalid response from server (status ${u.status})`)}if(!u.ok){if(u.status===503&&(l.mode==="read-only"||l.mode==="full")){let Rt=typeof l.message==="string"?l.message:"NEMAR is in maintenance mode. Please retry shortly.",lt=typeof l.eta==="string"?l.eta:null,jt=new Cl(l.mode,Rt,lt,l.details);throw JE(jt),jt}let p=typeof l.block_reason==="string",f=Array.isArray(l.missing)?l.missing.filter((Rt)=>typeof Rt==="string"):void 0,h=typeof l.error==="string"&&(tE.includes(l.error)||UE.includes(l.error)),m=typeof l.error==="string"&&(DE.options.includes(l.error)||ME.includes(l.error)),y=typeof l.error==="string"&&Qw.includes(l.error),_=typeof l.error==="string"&&CE.includes(l.error),O=typeof l.error==="string"&&BE.includes(l.error),k=typeof l.error==="string"&&HE.includes(l.error),M=typeof l.error==="string"&&WE.includes(l.error),S=typeof l.error==="string"&&GE.includes(l.error),Se=p||S||k||M||h||m||y||_||O||f!==void 0&&typeof l.error==="string"&&eE.includes(l.error)?l.message||l.error:l.error||l.message;if(u.status===404&&l.error==="Not Found"&&typeof l.message==="string")Se=`${l.message}. This NEMAR backend does not support this command yet.`;let pt=new hr(u.status,Se||"Request failed",l.details,typeof l.step==="string"?l.step:void 0,p?l.block_reason:void 0,f);if(typeof l.error==="string")pt.code=l.error;if(typeof l.reason==="string")pt.reason=l.reason;throw pt.rawBody=l,pt}if(n){let p=n.safeParse(l);if(!p.success)throw new hr(u.status,`Response for ${e} did not match the expected NEMAR contract`,{issues:p.error.issues});return p.data}return l}var td="https://nemar-api-dev.sccn-org.workers.dev",rd;var eS=F(()=>{qE();LE();FE();KE();YE();sc();pc();Xl();QE();Kl();jl();rd=td.includes("workers.dev")});pc();import{open as v9,rm as $9}from"fs/promises";eS();var tS="NEMAR_DATA_HOSTS",f9="NEMAR_DATA_HOSTS_ONLY",p9="https://private.nemar.org",h9="https://private-test.nemar.org",m9=/^[a-z]{2,3}[0-9]{6}$/;function rS(e){return m9.test(e)}function g9(e){return e}function nS(e){return e==="127.0.0.1"||e==="localhost"||e==="[::1]"}function sS(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:"&&nS(r.hostname))return r.origin;return null}function oS(e){let t=[],r=[];for(let n of(e??"").split(",")){let s=n.trim();if(s==="")continue;let o=sS(s);if(o===null)r.push(s);else if(!t.includes(o))t.push(o)}return{origins:t,rejected:r}}function iS(e){return e.env??process.env}function y9(e={}){let t=iS(e),r=e.isDevBuild??rd,n=t[f9]==="1"?[]:[r?h9:p9],{origins:s}=oS(t[tS]);return[...n,...s.filter((o)=>!n.includes(o))].map(g9)}function mW(e={}){return oS(iS(e)[tS]).rejected}function mc(e,t={}){let r=sS(e);if(r===null)return null;return y9(t).find((n)=>n===r)??null}function aS(e,t={}){return mc(e,t)!==null}function gW(e,t={}){let r;try{r=new URL(e)}catch{return null}if(r.username!==""||r.password!=="")return null;return mc(r.origin,t)}function cS(e,t){if(e.protocol==="https:")return!0;return e.protocol==="http:"&&nS(e.hostname)&&new URL(t).protocol==="http:"}var _9="NEMAR_DATA_HOST_TIMEOUT_MS";function nd(e,t=process.env){let r=t[_9];if(r===void 0||!/^[0-9]+$/.test(r))return e;let n=Number(r);return n>0&&n<e?n:e}function sd(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 uS=3,dS=60000,b9=262144,fS=255,pS=/^[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 hS(e){return e.length<=fS&&pS.test(e)}function w9(e){if(e.length>fS)return null;let t=pS.exec(e);if(!t||t[2]!==void 0)return null;let r=Number(t[1]);return Number.isSafeInteger(r)?r:null}function E9(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(!rS(t))return{ok:!1,message:"The dataset setting is not a dataset id (two or three letters and six digits)."};let n=mc(e,r);if(n===null)return{ok:!1,message:`The host setting ${Ct(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 Ct(e,t=200){let r=e.replace(/[^\x20-\x7e]/g,"?");return r.length>t?`${r.slice(0,t)}...`:r}function S9(e,t){return new URL(`${e.origin}/o/${encodeURIComponent(e.dataset)}/${encodeURIComponent(t)}`)}function mS(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 gS(e,t,r,n,s,o){if(!aS(e.origin,e.options))return{kind:"failed",message:"The host is not on this CLI's list of data hosts."};let i=S9(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 (${sd(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>=uS)return{kind:"failed",message:`More than ${uS} 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(!cS(p,e.origin))return{kind:"failed",message:"A redirect named an address that is not https."};i=p,a=!0}}async function yS(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 x9(e,t,r,n,s){if(!hS(t))return{ok:!1,message:"The key is not one a data host serves."};let o=w9(t);return yS(nd(dS,e.options?.env),async(i,a)=>{let c=await gS(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:mS(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 ${Ct(l,20)} bytes but its key says ${o}.`};a();let p,f=0,h=0;try{p=await v9(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 gc(`More bytes arrived than the key's ${o}.`);if(await p.write(_),f-h>=b9)h=f,s(f)}if(await p.close(),p=void 0,o!==null&&f!==o)throw new gc(`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 $9(n,{force:!0}).catch(()=>{}),m instanceof gc)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 (${sd(m)}).`}}})}class gc extends Error{constructor(e){super(e);this.name="SizeError"}}async function R9(e,t,r){if(!hS(t))return{state:"unknown",message:"The key is not one a data host serves."};return yS(nd(dS,e.options?.env),async(n)=>{let s=await gS(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:mS(o,!1)}})}class yc extends Error{constructor(e){super(e);this.name="ProtocolAbort"}}async function _S(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 yc("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 yc(p);n.push(p)}},c=async()=>{let d=await a("host"),l=await a("dataset");return E9(d,l,t.options)},u=async(d,l)=>{if(!s||!o){await e.send(`TRANSFER-FAILURE RETRIEVE ${Ct(d)} The remote has not been prepared.`);return}let p=Promise.resolve(),f=await x9(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 ${Ct(d)} ${Ct(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]=lS(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 ${Ct(h.message)}`);break}case"PREPARE":{let h=await c();if(!h.ok){s=null,await e.send(`PREPARE-FAILURE ${Ct(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]=lS(f,2);if(h==="STORE")await e.send(`TRANSFER-FAILURE STORE ${Ct(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 ${Ct(f)} The remote has not been prepared.`);break}let h=await R9(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 ${Ct(f)} ${h.message}`);break}case"REMOVE":await e.send(`REMOVE-FAILURE ${Ct(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 yc)return 1;throw h}}}function lS(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*k9(){let e=new TextDecoder,t="";for await(let r of Bun.stdin.stream()){t+=e.decode(r,{stream:!0});let n=t.indexOf(`
38
+ `)}var XE=!1;var QE=F(()=>{Fl()});function ZE(){if(process.env.TEST_API_URL)return process.env.TEST_API_URL;if(rd)return td;return mn().apiUrl||td}async function fW(e,t={},r=!1,n){let s=`${ZE()}${e}`,o={"Content-Type":"application/json","X-CLI-Version":cc,...t.headers};if(r){let p=mn();if(!p.apiKey&&r===!0)throw new hr(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(dc())fc({method:i,url:s,status:null,durationMs:Date.now()-c,requestHeaders:o,requestBody:a,error:p instanceof Error?p.message:String(p)});throw new hr(0,`Network error: Could not connect to ${ZE()}`,{originalError:p instanceof Error?p.message:String(p)})}let d;try{d=await u.text()}catch(p){if(dc())fc({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 hr(0,"Failed to read response body",{httpStatus:u.status,originalError:p instanceof Error?p.message:String(p)})}if(dc())fc({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 hr(u.status,`Invalid response from server (status ${u.status})`)}if(!u.ok){if(u.status===503&&(l.mode==="read-only"||l.mode==="full")){let Rt=typeof l.message==="string"?l.message:"NEMAR is in maintenance mode. Please retry shortly.",lt=typeof l.eta==="string"?l.eta:null,jt=new Cl(l.mode,Rt,lt,l.details);throw JE(jt),jt}let p=typeof l.block_reason==="string",f=Array.isArray(l.missing)?l.missing.filter((Rt)=>typeof Rt==="string"):void 0,h=typeof l.error==="string"&&(tE.includes(l.error)||UE.includes(l.error)),m=typeof l.error==="string"&&(DE.options.includes(l.error)||ME.includes(l.error)),y=typeof l.error==="string"&&Qw.includes(l.error),_=typeof l.error==="string"&&CE.includes(l.error),O=typeof l.error==="string"&&BE.includes(l.error),k=typeof l.error==="string"&&HE.includes(l.error),M=typeof l.error==="string"&&WE.includes(l.error),S=typeof l.error==="string"&&GE.includes(l.error),Se=p||S||k||M||h||m||y||_||O||f!==void 0&&typeof l.error==="string"&&eE.includes(l.error)?l.message||l.error:l.error||l.message;if(u.status===404&&l.error==="Not Found"&&typeof l.message==="string")Se=`${l.message}. This NEMAR backend does not support this command yet.`;let pt=new hr(u.status,Se||"Request failed",l.details,typeof l.step==="string"?l.step:void 0,p?l.block_reason:void 0,f);if(typeof l.error==="string")pt.code=l.error;if(typeof l.reason==="string")pt.reason=l.reason;throw pt.rawBody=l,pt}if(n){let p=n.safeParse(l);if(!p.success)throw new hr(u.status,`Response for ${e} did not match the expected NEMAR contract`,{issues:p.error.issues});return p.data}return l}var td="https://api.nemar.org",rd;var eS=F(()=>{qE();LE();FE();KE();YE();sc();pc();Xl();QE();Kl();jl();rd=td.includes("workers.dev")});pc();import{open as v9,rm as $9}from"fs/promises";eS();var tS="NEMAR_DATA_HOSTS",f9="NEMAR_DATA_HOSTS_ONLY",p9="https://private.nemar.org",h9="https://private-test.nemar.org",m9=/^[a-z]{2,3}[0-9]{6}$/;function rS(e){return m9.test(e)}function g9(e){return e}function nS(e){return e==="127.0.0.1"||e==="localhost"||e==="[::1]"}function sS(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:"&&nS(r.hostname))return r.origin;return null}function oS(e){let t=[],r=[];for(let n of(e??"").split(",")){let s=n.trim();if(s==="")continue;let o=sS(s);if(o===null)r.push(s);else if(!t.includes(o))t.push(o)}return{origins:t,rejected:r}}function iS(e){return e.env??process.env}function y9(e={}){let t=iS(e),r=e.isDevBuild??rd,n=t[f9]==="1"?[]:[r?h9:p9],{origins:s}=oS(t[tS]);return[...n,...s.filter((o)=>!n.includes(o))].map(g9)}function mW(e={}){return oS(iS(e)[tS]).rejected}function mc(e,t={}){let r=sS(e);if(r===null)return null;return y9(t).find((n)=>n===r)??null}function aS(e,t={}){return mc(e,t)!==null}function gW(e,t={}){let r;try{r=new URL(e)}catch{return null}if(r.username!==""||r.password!=="")return null;return mc(r.origin,t)}function cS(e,t){if(e.protocol==="https:")return!0;return e.protocol==="http:"&&nS(e.hostname)&&new URL(t).protocol==="http:"}var _9="NEMAR_DATA_HOST_TIMEOUT_MS";function nd(e,t=process.env){let r=t[_9];if(r===void 0||!/^[0-9]+$/.test(r))return e;let n=Number(r);return n>0&&n<e?n:e}function sd(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 uS=3,dS=60000,b9=262144,fS=255,pS=/^[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 hS(e){return e.length<=fS&&pS.test(e)}function w9(e){if(e.length>fS)return null;let t=pS.exec(e);if(!t||t[2]!==void 0)return null;let r=Number(t[1]);return Number.isSafeInteger(r)?r:null}function E9(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(!rS(t))return{ok:!1,message:"The dataset setting is not a dataset id (two or three letters and six digits)."};let n=mc(e,r);if(n===null)return{ok:!1,message:`The host setting ${Ct(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 Ct(e,t=200){let r=e.replace(/[^\x20-\x7e]/g,"?");return r.length>t?`${r.slice(0,t)}...`:r}function S9(e,t){return new URL(`${e.origin}/o/${encodeURIComponent(e.dataset)}/${encodeURIComponent(t)}`)}function mS(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 gS(e,t,r,n,s,o){if(!aS(e.origin,e.options))return{kind:"failed",message:"The host is not on this CLI's list of data hosts."};let i=S9(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 (${sd(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>=uS)return{kind:"failed",message:`More than ${uS} 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(!cS(p,e.origin))return{kind:"failed",message:"A redirect named an address that is not https."};i=p,a=!0}}async function yS(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 x9(e,t,r,n,s){if(!hS(t))return{ok:!1,message:"The key is not one a data host serves."};let o=w9(t);return yS(nd(dS,e.options?.env),async(i,a)=>{let c=await gS(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:mS(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 ${Ct(l,20)} bytes but its key says ${o}.`};a();let p,f=0,h=0;try{p=await v9(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 gc(`More bytes arrived than the key's ${o}.`);if(await p.write(_),f-h>=b9)h=f,s(f)}if(await p.close(),p=void 0,o!==null&&f!==o)throw new gc(`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 $9(n,{force:!0}).catch(()=>{}),m instanceof gc)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 (${sd(m)}).`}}})}class gc extends Error{constructor(e){super(e);this.name="SizeError"}}async function R9(e,t,r){if(!hS(t))return{state:"unknown",message:"The key is not one a data host serves."};return yS(nd(dS,e.options?.env),async(n)=>{let s=await gS(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:mS(o,!1)}})}class yc extends Error{constructor(e){super(e);this.name="ProtocolAbort"}}async function _S(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 yc("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 yc(p);n.push(p)}},c=async()=>{let d=await a("host"),l=await a("dataset");return E9(d,l,t.options)},u=async(d,l)=>{if(!s||!o){await e.send(`TRANSFER-FAILURE RETRIEVE ${Ct(d)} The remote has not been prepared.`);return}let p=Promise.resolve(),f=await x9(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 ${Ct(d)} ${Ct(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]=lS(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 ${Ct(h.message)}`);break}case"PREPARE":{let h=await c();if(!h.ok){s=null,await e.send(`PREPARE-FAILURE ${Ct(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]=lS(f,2);if(h==="STORE")await e.send(`TRANSFER-FAILURE STORE ${Ct(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 ${Ct(f)} The remote has not been prepared.`);break}let h=await R9(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 ${Ct(f)} ${h.message}`);break}case"REMOVE":await e.send(`REMOVE-FAILURE ${Ct(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 yc)return 1;throw h}}}function lS(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*k9(){let e=new TextDecoder,t="";for await(let r of Bun.stdin.stream()){t+=e.decode(r,{stream:!0});let n=t.indexOf(`
39
39
  `);while(n>=0)yield t.slice(0,n).replace(/\r$/,""),t=t.slice(n+1),n=t.indexOf(`
40
40
  `)}if(t+=e.decode(),t!=="")yield t}var od=Bun.stdout.writer(),T9=await _S({lines:k9(),send:async(e)=>{od.write(`${e}
41
41
  `),await od.flush()}},{loadApiKey:()=>mn().apiKey||void 0});await od.end();process.exit(T9);
package/dist/index.js CHANGED
@@ -100,18 +100,18 @@ ${t}`,BQe,HQe,GQe=(e,t,n)=>{let r=n===""?"":`with ${n.trim()}() `,o=UQe.bind(nul
100
100
  `)}var CM=!1;var{spawn:Vwt}=globalThis.Bun;function vp(e,t=[]){let n=e.replace(Wwt,'("$1","<redacted>")');for(let r of t)if(r.length>=Kwt)n=n.split(r).join("<redacted>");return n}function i$(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 Jge(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??Jwt)};if(l(),t.timeout)s=setTimeout(()=>{o=!0,c(),r.kill()},t.timeout);let d=Kg()?[...i$(n),...t.redact??[]]:[];if(Kg()){let y=t.cwd?` (cwd=${t.cwd})`:"";Vd(u.dim(vp(`$ ${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([Jge(r.stdout,f),Jge(r.stderr,f),g])}finally{if(c(),s)clearTimeout(s)}if(Kg()){if(t.sensitiveOutput)Vd(u.dim("[sensitive subprocess output suppressed]"));else{if(p.trim())Vd(u.dim(vp(p.trimEnd(),d)));if(m.trim())Vd(u.yellow(vp(m.trimEnd(),d)))}Vd(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 Wwt,Kwt=8,Jwt=120000;var Gt=G(()=>{We();Wwt=/\(\s*"((?:x-amz-)[^"]*|authorization|proxy-authorization)"\s*,\s*"[^"]*"\s*\)/gi});function Xwt(){if(process.platform==="darwin")return"macos";if(process.platform==="win32")return"windows";return"linux"}function Xge(e,t=Xwt()){return e.installInstructions[t]}function Qwt(e){let t=e.match(/(\d+\.\d+(?:\.\d+)?)/);return t?t[1]:void 0}function e_t(){let e=Number(process.env.TEST_PROBE_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:Zwt}async function Qge(e){try{let{exitCode:t,stdout:n,timedOut:r}=await O(e.cmd,{timeout:e_t()});if(r)return{available:!1,timedOut:!0};if(t!==0)return{available:!1};return{available:!0,version:Qwt(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 Qw(){let e=Object.entries(Yge);return Promise.all(e.map(async([t,n])=>{let{available:r,version:o,timedOut:s}=await Qge(n);return{key:t,name:n.name,purpose:n.purpose,required:n.required,available:r,version:o,timedOut:s,installInstruction:Xge(n)}}))}async function Zge(){let t=(await Qw()).filter((n)=>n.required&&!n.available);if(t.length===0)return[];console.warn(`
101
101
  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 Ep(e){let n=Ywt[e].map((i)=>Yge[i]).filter(Boolean),r=await Promise.all(n.map(async(i)=>{let a=await Qge(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:Xge(i.check)}));if(o.length===0)return;let s=[`
102
102
  Missing required tools:`];for(let i of o)s.push(` ${i.tool} not installed`),s.push(` Install: ${i.installInstruction}`);throw Error(s.join(`
103
- `))}var Yge,Ywt,Zwt=4000;var Zw=G(()=>{Gt();Yge={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)"}}},Ywt={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 tye;var eye=G(()=>{tye={name:"nemar-cli",packageManager:"bun@1.4.3",version:"0.10.38-dev.4706",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 Vs;var Sp=G(()=>{eye();Vs=tye.version});import{mkdirSync as n_t,readdirSync as r_t,unlinkSync as o_t,writeFileSync as s_t}from"fs";import{join as AM}from"path";function aye(){Jg=!0}function Ul(){return Jg}function cye(e,t=process.env){return e.includes("--debug")||t.NEMAR_DEBUG==="1"}function t_(e){iye=e,Nn(`Step: ${e}`)}function Yo(){oye=!0}function lye(){return oye}function ue(){if(sye)return;TM=!0}function n_(){TM=!1,sye=!0}function uye(){return TM}function Nn(e){if(Jg)process.stderr.write(`[debug] ${e}
103
+ `))}var Yge,Ywt,Zwt=4000;var Zw=G(()=>{Gt();Yge={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)"}}},Ywt={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 tye;var eye=G(()=>{tye={name:"nemar-cli",packageManager:"bun@1.4.3",version:"0.10.39-PR2296.1810c4a",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 Vs;var Sp=G(()=>{eye();Vs=tye.version});import{mkdirSync as n_t,readdirSync as r_t,unlinkSync as o_t,writeFileSync as s_t}from"fs";import{join as AM}from"path";function aye(){Jg=!0}function Ul(){return Jg}function cye(e,t=process.env){return e.includes("--debug")||t.NEMAR_DEBUG==="1"}function t_(e){iye=e,Nn(`Step: ${e}`)}function Yo(){oye=!0}function lye(){return oye}function ue(){if(sye)return;TM=!0}function n_(){TM=!1,sye=!0}function uye(){return TM}function Nn(e){if(Jg)process.stderr.write(`[debug] ${e}
104
104
  `)}function l_t(e){let t={};for(let[n,r]of Object.entries(e))t[n]=c_t.has(n.toLowerCase())?"[REDACTED]":r;return t}function fye(e){let t=e.indexOf("@");if(t<=0)return"***";return`${e[0]}***${e.slice(t)}`}function OM(e,t,n=0){if(n>d_t)return"[REDACTED: depth]";if(Array.isArray(t))return t.map((r)=>OM(e,r,n+1));if(t&&typeof t==="object"){let r={};for(let[o,s]of Object.entries(t))r[o]=OM(o,s,n+1);return r}if(typeof t==="string"){if(u_t.test(e))return"[REDACTED]";return t.replace(dye,fye)}return t}function PM(e){return e.replace(f_t,"Bearer [REDACTED]").replace(p_t,"[REDACTED_AWS_KEY]").replace(m_t,"$1[REDACTED]").replace(h_t,"$1$2=[REDACTED]").replace(dye,fye)}function g_t(e){return PM(e)}function nye(e,t=a_t){if(e===void 0)return;let n=e;try{let r=JSON.parse(e);n=JSON.stringify(OM("",r))}catch{}if(n=PM(n),Buffer.byteLength(n,"utf8")>t)n=`${Buffer.from(n,"utf8").subarray(0,t).toString("utf8")}... [truncated]`;return n}function l$(e){if(!Jg)return;let t=g_t(e.url);try{let n={...e,url:t,requestHeaders:e.requestHeaders?l_t(e.requestHeaders):void 0,requestBody:nye(e.requestBody),responseBody:nye(e.responseBody)};c$.push(n),Nn(`${e.method} ${t} -> ${e.status??"ERROR"} (${e.durationMs}ms)`)}catch(n){let r=W(n);c$.push({method:e.method,url:t,status:e.status,durationMs:e.durationMs,note:`redaction failed: ${r}`}),Nn(`redaction failed for ${e.method} ${t}: ${r}`)}}async function y_t(){let e=[];try{let t=process.versions.bun?`Bun ${process.versions.bun}`:`Node ${process.version}`;e.push(`CLI version: ${Vs}`),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 Qw();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 IM(){return(await y_t()).join(`
105
105
  `)}async function pye(){if(!Jg||a$!==void 0)return;try{a$=await IM()}catch(e){let t=W(e);a$=`(could not build environment report: ${t})`,Nn(`environment snapshot failed: ${t}`)}}function mye(e){if(rye.has(e))return{flag:e};for(let t of rye){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 b_t(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n],o=mye(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 w_t(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n],o=mye(r);if(!o){t.push(r);continue}if(!o.kind&&n+1<e.length)n++}return t}function __t(e){let t=[];for(let r of w_t(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 x_t(e,t){let n=[];if(n.push("NEMAR CLI Debug Log"),n.push(`Generated: ${new Date().toISOString()}`),n.push(`Command: nemar ${PM(b_t(e).join(" "))}`),n.push(""),n.push(a$??"(environment snapshot unavailable)"),n.push(""),n.push("HTTP requests:"),c$.length===0)n.push(" (none)");else c$.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: ${iye??"(none recorded)"}`),n.push(`Exit code: ${t}`),`${n.join(`
106
106
  `)}
107
107
  `}function v_t(e,t){let n;try{n=r_t(e).filter((o)=>o.startsWith("nemar-")&&o.endsWith(".log"))}catch(o){if(o.code!=="ENOENT")Nn(`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{o_t(AM(e,n[o]))}catch(s){if(s.code!=="ENOENT")Nn(`could not remove old log ${n[o]}: ${W(s)}`)}}function hye(){return e_}function gye(e,t){if(!Jg)return null;let n=AM(sr(),"logs");try{n_t(n,{recursive:!0})}catch(i){return e_=W(i),Nn(`could not create log directory ${n}: ${e_}`),null}let o=`nemar-${new Date().toISOString().replace(/[:.]/g,"-")}-${__t(e)}.log`,s=AM(n,o);try{s_t(s,x_t(e,t),"utf8")}catch(i){return e_=W(i),Nn(`could not write log file ${s}: ${e_}`),null}return v_t(n,i_t),s}var i_t=10,a_t=2048,Jg=!1,oye=!1,TM=!1,sye=!1,iye,a$,c$,c_t,u_t,dye,d_t=32,f_t,p_t,m_t,h_t,rye,e_;var xn=G(()=>{Ve();Ir();Zw();Sp();c$=[];c_t=new Set(["authorization","cookie","set-cookie","x-api-key","x-approval-dispatch-token"]);u_t=/^(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,dye=/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g;f_t=/Bearer\s+[A-Za-z0-9\-._~+/=]+/gi,p_t=/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g,m_t=/((?:aws_)?secret_access_key["']?\s*[:=]\s*["']?)[A-Za-z0-9/+=]{20,}/gi,h_t=/([?&])(X-Amz-Signature|X-Amz-Security-Token|X-Amz-Credential|Signature|AWSAccessKeyId)=[^&\s"']+/gi;rye=new Set(["-k","--key","--password","--api-key"])});import{chmodSync as E_t,copyFileSync as S_t,existsSync as NM,mkdirSync as k_t,statSync as R_t}from"fs";import{homedir as u$}from"os";import{join as Yg}from"path";function D_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||Yg(u$(),".config","nemar")}function A_t(e){if(process.env.NEMAR_CONFIG_DIR)return;let t=Yg(e,"config.json");if(NM(t))return;let n=[];if(process.platform==="darwin")n.push(Yg(u$(),"Library","Preferences","nemar-nodejs","config.json"));if(process.platform==="win32"){let r=process.env.APPDATA||Yg(u$(),"AppData","Roaming");n.push(Yg(r,"nemar-nodejs","config.json"))}n.push(Yg(u$(),".config","nemar-nodejs","config.json"));for(let r of n)if(NM(r))try{k_t(e,{recursive:!0}),S_t(r,t),console.error(`[nemar] Config migrated from ${r} to ${t}
108
108
  [nemar] You can safely remove the old file.`);return}catch(o){console.error(`[nemar] Failed to migrate config from ${r}:`,o,`
109
- [nemar] You can manually copy ${r} to ${t}`)}}function Di(){let e=sr();if(r_&&yye===e)return r_;if(A_t(e),r_=new s$({projectName:"nemar",configFileMode:FM,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}),yye=e,!bye.has(e))bye.add(e),O_t(r_.path),P_t(),I_t();return r_}function O_t(e){if(process.platform==="win32")return;if(!NM(e))return;try{if((R_t(e).mode&511)!==FM)E_t(e,FM)}catch(t){console.error(`[nemar] could not secure config file permissions for ${e}:`,t)}}function P_t(){let e=Di(),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 T_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 I_t(){let e=Di(),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($_t.has(D_t(a)))n[s]={...i,apiUrl:Xg},console.error(`[nemar] migrated stored apiUrl for account "${s}": ${a} -> ${Xg}`),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 o_(){return Di().get("activeAccount")}function Wd(){return Di().get("accounts")||{}}function Yt(){let e={apiUrl:Xg},t=o_();if(!t)return e;return Wd()[t]||e}function Bn(e,t){let n=Di(),r=n.get("activeAccount")||"default",o=n.get("accounts")||{};if(!o[r])o[r]={apiUrl:Xg};o[r][e]=t,n.store={...n.store,accounts:o,activeAccount:r}}function s_(e){let t=o_();if(!t)return;let n=Wd();if(n[t])delete n[t][e],Di().set("accounts",n)}function wye(){let e=Di(),t=o_();if(!t){e.clear();return}let n=Wd();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 _ye(){Di().clear()}function Je(){return!!Yt().apiKey}function MM(){return Di().path}function i_(){let e=Wd(),t=o_();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 xye(e){return e.username?.trim()||e.email}function N_t(e){let t=e.trim().toLowerCase();if(!t)return;let n=Object.entries(Wd()).filter(([,r])=>r.email&&r.email.toLowerCase()===t).map(([r])=>r);if(n.length>1){Nn(`findAccountKeyByEmail: ${n.length} accounts share email ${t}: ${n.join(", ")}`);return}return n[0]}function vye(e,t){let n=Di(),r=Wd(),o;if(r[e])o=e;else if(t.email)o=N_t(t.email);let s=o?r[o]:void 0,i={...s??{apiUrl:Xg},...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 Eye(e){let t=e.trim();if(!t)return"unchanged";let n=Di(),r=o_();if(!r||r===t)return"unchanged";let o=Wd(),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 jM(e){let t=Di(),n=Wd();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 Xg="https://nemar-api-dev.sccn-org.workers.dev",FM=384,$_t,C_t,Wrn,r_=null,yye=null,bye,T_t;var Ir=G(()=>{Wge();fr();qh();xn();$_t=new Set(["https://api.osc.earth/nemar","https://nemar-api.neuromechanist.workers.dev","https://nemar-api-dev.shirazi-10f.workers.dev"]);C_t=N({field:w(),blocks:X(w()).optional(),set_on:X(w()).optional()}).passthrough(),Wrn=N({apiKey:w().optional(),apiUrl:w().url().default(Xg),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(C_t).optional(),orcidVerified:oe().optional(),role:w().optional(),accountKind:op.optional(),pendingEmailChange:w().email().optional()});bye=new Set;T_t=["apiKey","apiUrl","username","email","githubUsername","sandboxCompleted","sandboxDatasetId","dismissedNoticeIds"]});function d$(e){if(Sye)return;Sye=!0;let t=u.yellow("\u2500".repeat(60)),n=u.yellow.bold("[MAINTENANCE]"),r=u.dim(`mode: ${e.mode}`),o=e.eta?`
109
+ [nemar] You can manually copy ${r} to ${t}`)}}function Di(){let e=sr();if(r_&&yye===e)return r_;if(A_t(e),r_=new s$({projectName:"nemar",configFileMode:FM,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}),yye=e,!bye.has(e))bye.add(e),O_t(r_.path),P_t(),I_t();return r_}function O_t(e){if(process.platform==="win32")return;if(!NM(e))return;try{if((R_t(e).mode&511)!==FM)E_t(e,FM)}catch(t){console.error(`[nemar] could not secure config file permissions for ${e}:`,t)}}function P_t(){let e=Di(),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 T_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 I_t(){let e=Di(),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($_t.has(D_t(a)))n[s]={...i,apiUrl:Xg},console.error(`[nemar] migrated stored apiUrl for account "${s}": ${a} -> ${Xg}`),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 o_(){return Di().get("activeAccount")}function Wd(){return Di().get("accounts")||{}}function Yt(){let e={apiUrl:Xg},t=o_();if(!t)return e;return Wd()[t]||e}function Bn(e,t){let n=Di(),r=n.get("activeAccount")||"default",o=n.get("accounts")||{};if(!o[r])o[r]={apiUrl:Xg};o[r][e]=t,n.store={...n.store,accounts:o,activeAccount:r}}function s_(e){let t=o_();if(!t)return;let n=Wd();if(n[t])delete n[t][e],Di().set("accounts",n)}function wye(){let e=Di(),t=o_();if(!t){e.clear();return}let n=Wd();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 _ye(){Di().clear()}function Je(){return!!Yt().apiKey}function MM(){return Di().path}function i_(){let e=Wd(),t=o_();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 xye(e){return e.username?.trim()||e.email}function N_t(e){let t=e.trim().toLowerCase();if(!t)return;let n=Object.entries(Wd()).filter(([,r])=>r.email&&r.email.toLowerCase()===t).map(([r])=>r);if(n.length>1){Nn(`findAccountKeyByEmail: ${n.length} accounts share email ${t}: ${n.join(", ")}`);return}return n[0]}function vye(e,t){let n=Di(),r=Wd(),o;if(r[e])o=e;else if(t.email)o=N_t(t.email);let s=o?r[o]:void 0,i={...s??{apiUrl:Xg},...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 Eye(e){let t=e.trim();if(!t)return"unchanged";let n=Di(),r=o_();if(!r||r===t)return"unchanged";let o=Wd(),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 jM(e){let t=Di(),n=Wd();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 Xg="https://api.nemar.org",FM=384,$_t,C_t,Wrn,r_=null,yye=null,bye,T_t;var Ir=G(()=>{Wge();fr();qh();xn();$_t=new Set(["https://api.osc.earth/nemar","https://nemar-api.neuromechanist.workers.dev","https://nemar-api-dev.shirazi-10f.workers.dev"]);C_t=N({field:w(),blocks:X(w()).optional(),set_on:X(w()).optional()}).passthrough(),Wrn=N({apiKey:w().optional(),apiUrl:w().url().default(Xg),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(C_t).optional(),orcidVerified:oe().optional(),role:w().optional(),accountKind:op.optional(),pendingEmailChange:w().email().optional()});bye=new Set;T_t=["apiKey","apiUrl","username","email","githubUsername","sandboxCompleted","sandboxDatasetId","dismissedNoticeIds"]});function d$(e){if(Sye)return;Sye=!0;let t=u.yellow("\u2500".repeat(60)),n=u.yellow.bold("[MAINTENANCE]"),r=u.dim(`mode: ${e.mode}`),o=e.eta?`
110
110
  ${u.dim(`eta: ${e.eta}`)}`:"";process.stderr.write(`${t}
111
111
  ${n} ${e.message}
112
112
  ${r}${o}
113
113
  ${t}
114
- `)}var Sye=!1;var LM=G(()=>{We()});function Vr(){if(process.env.TEST_API_URL)return process.env.TEST_API_URL;if(kp)return qM;return Yt().apiUrl||qM}async function F(e,t={},n=!1,r){let o=`${Vr()}${e}`,s={"Content-Type":"application/json","X-CLI-Version":Vs,...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(Ul())l$({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 ${Vr()}`,{originalError:p instanceof Error?p.message:String(p)})}let d;try{d=await l.text()}catch(p){if(Ul())l$({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(Ul())l$({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 T=typeof f.message==="string"?f.message:"NEMAR is in maintenance mode. Please retry shortly.",q=typeof f.eta==="string"?f.eta:null,L=new id(f.mode,T,q,f.details);throw d$(L),L}let p=typeof f.block_reason==="string",m=Array.isArray(f.missing)?f.missing.filter((T)=>typeof T==="string"):void 0,h=typeof f.error==="string"&&(pne.includes(f.error)||One.includes(f.error)),g=typeof f.error==="string"&&(AS.options.includes(f.error)||Fne.includes(f.error)),y=typeof f.error==="string"&&ane.includes(f.error),b=typeof f.error==="string"&&mne.includes(f.error),x=typeof f.error==="string"&&$ne.includes(f.error),v=typeof f.error==="string"&&Rne.includes(f.error),S=typeof f.error==="string"&&Dne.includes(f.error),E=typeof f.error==="string"&&Kne.includes(f.error),I=p||E||v||S||h||g||y||b||x||m!==void 0&&typeof f.error==="string"&&fne.includes(f.error)?f.message||f.error:f.error||f.message;if(l.status===404&&f.error==="Not Found"&&typeof f.message==="string")I=`${f.message}. This NEMAR backend does not support this command yet.`;let H=new U(l.status,I||"Request failed",f.details,typeof f.step==="string"?f.step:void 0,p?f.block_reason:void 0,m);if(typeof f.error==="string")H.code=f.error;if(typeof f.reason==="string")H.reason=f.reason;throw H.rawBody=f,H}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 qM="https://nemar-api-dev.sccn-org.workers.dev",kp;var wr=G(()=>{tw();PS();PI();ow();Bh();qh();Ir();xn();LM();Sp();Ve();kp=qM.includes("workers.dev")});async function Qg(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 Zg(e){return F(`/datasets/${e}/publish/status`,{},!0)}async function $ye(e){return F(`/datasets/${e}/publish/resend`,{method:"POST"},!0)}async function Dye(e){return F(`/datasets/${e}/publish/withdraw`,{method:"POST"},!0)}async function Rp(e={}){let{statuses:t,search:n}=typeof e==="string"?{statuses:e?[e]:[]}:e,r=await kye(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 kye([a],n));let i=s.flatMap((a)=>a.requests).sort(Cye);o={...r,requests:i,count:i.length}}return n?F_t(o,n):o}function Cye(e,t){return e.requested_at<t.requested_at?1:e.requested_at>t.requested_at?-1:0}async function kye(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)=>foe(t,[s.dataset_id,s.requested_by_username,s.dataset_name])),r=(s)=>poe(s.dataset_id,t)?0:1,o=[...n].sort((s,i)=>r(s)-r(i)||Cye(s,i));return{...e,requests:o,count:o.length}}async function ey(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 f$(e){return F(`/admin/publish/${e}/identifier-screen`,{method:"POST"},!0)}async function p$(e){return F(`/admin/publish/${e}/review`,{},!0)}async function Aye(e){return F(`/admin/publish/${e}/review/start`,{method:"POST"},!0)}async function Oye(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 ty(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 M_t(e,t=[]){if(e){let n=Ya.indexOf(e);if(n>=0)return n+1}return Math.min(t.length+1,Ya.length)}function j_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 L_t(){let e=process.env.NEMAR_APPROVE_RETRY_DELAY_MS;if(e===void 0||!/^\d+$/.test(e))return ok;let t=Number(e);return Number.isSafeInteger(t)&&t<=ok?t:ok}async function ny(e,t=!1,n=!1,r=!1,o,s,i,a,c){let d=L_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:M_t(S,E),stepTotal:Ya.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?{[Cne]: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?{[loe]: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=Rye(b);return E}catch(E){if(x=E,S===5||!j_t(E)){if(E instanceof U&&b.length>0)E.stepResults=Rye(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 Rye(e){let t=new Map;for(let n of e)t.set(n.step,n);return Array.from(t.values())}var aa=G(()=>{rk();Bh();ik();wr();Ve()});function g$(e){if(e.service_access===void 0||e.service_access===null)return"unknown";return e.service_access?"upload":"browse"}async function YM(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,une)}async function y$(e,t=!1){return F(`/admin/users/by-id/${e}${t?"?include_deleted=true":""}`,{},!0,yne)}async function Uye(e,t){return F(`/admin/users/by-id/${e}`,{method:"PATCH",body:JSON.stringify(t)},!0,bne)}async function Bye(e){return F(`/admin/approve/${e}`,{method:"POST"},!0)}async function Hye(e){return F(`/admin/approve/by-id/${e}`,{method:"POST"},!0)}async function Gye(e){return F(`/admin/revoke/${e}`,{method:"POST"},!0)}async function zye(e){return F(`/admin/revoke/by-id/${e}`,{method:"POST"},!0)}async function Vye(e){return F(`/admin/users/by-id/${e}/verify`,{method:"POST"},!0)}async function Wye(e,t){return F(`/admin/users/${e}/role`,{method:"POST",body:JSON.stringify({role:t})},!0)}async function Kye(e,t){return F(`/admin/users/${e}/kind`,{method:"POST",body:JSON.stringify({kind:t})},!0)}async function b$(e){return F(`/admin/users/${encodeURIComponent(e)}`,{},!0)}async function Jye(e,t){return F(`/admin/users/${e}/keys`,{method:"POST",body:JSON.stringify({name:t})},!0,TS)}async function Yye(e){return F(`/admin/users/${e}/keys`,{},!0,OS)}async function Xye(e,t){return F(`/admin/users/${e}/keys/${t}`,{method:"DELETE"},!0)}async function Qye(e){return F(`/datasets/${e}/publish`,{method:"POST"},!0)}async function Zye(e){return F(`/admin/datasets/${e}/ci`,{},!0)}async function Bl(e){return F(`/admin/datasets/${e}/ci`,{method:"POST"},!0)}async function XM(e){return F(`/admin/datasets/${e}/ci/validate`,{method:"POST"},!0)}async function QM(e){return F(`/admin/datasets/${e}/ci/sync`,{method:"POST"},!0)}async function ebe(e,t){return F(`/admin/datasets/${e}/doi/concept`,{method:"POST",body:JSON.stringify(t)},!0)}async function l_(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 tbe(e,t){return F(`/admin/datasets/${e}/withdraw`,{method:"POST",body:JSON.stringify({reason:t.reason,dry_run:t.dryRun})},!0)}async function nbe(e,t){return F(`/admin/datasets/${e}/restore`,{method:"POST",body:JSON.stringify({dry_run:t.dryRun})},!0)}async function rbe(e,t){return F(`/admin/datasets/${e}/unpublish`,{method:"POST",body:JSON.stringify({reason:t.reason,dry_run:t.dryRun})},!0)}async function obe(e){return F(`/admin/datasets/${e}/reset`,{method:"POST"},!0)}async function sbe(e,t=!1){return F(`/admin/datasets/${e}`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({force:t})},!0)}async function ibe(e){return F("/admin/datasets/bulk-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dataset_ids:e})},!0)}async function abe(e){return F("/admin/datasets/import",{method:"POST",body:JSON.stringify(e)},!0)}async function cbe(e){return F("/admin/datasets/exemplar",{method:"POST",body:JSON.stringify(e)},!0)}async function lbe(e){return F(`/admin/datasets/${e}/exemplar/remint-dois`,{method:"POST"},!0)}async function e6(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 ube(e){return F(`/admin/imports/${e}/rollback`,{method:"POST"},!0)}async function dbe(e){return F(`/admin/imports/${e}/retry`,{method:"POST"},!0)}async function t6(e){return F(`/admin/imports/${e}/verify`,{method:"POST"},!0)}async function fbe(e){return F("/admin/imports/dispatch-cooldown",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dataset_ids:e})},!0)}async function sy(e,t){return F(`/admin/datasets/${e}/reindex`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})},!0)}async function pbe(e,t){return F("/admin/datasets/reindex/bulk",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filter:e,...t??{}})},!0)}async function mbe(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 hbe(){return F("/admin/datasets/hed-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function gbe(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 ybe(){return F("/admin/datasets/recording-stats-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function bbe(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 wbe(){return F("/admin/datasets/signal-defaults-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function _be(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 xbe(){return F("/admin/datasets/data-integrity-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function vbe(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 Ebe(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 Sbe(){return F("/admin/datasets/availability-report-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function kbe(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 iy(e,t){return F(`/admin/datasets/${e}/enforce`,{method:"POST",body:JSON.stringify({dry_run:t})},!0)}async function Rbe(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 $be(e,t){return F(`/admin/datasets/${e}/review-ruleset`,{method:"POST",body:JSON.stringify({dry_run:t.dryRun,remove:t.remove})},!0)}async function Dbe(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 Cbe(e,t=!1){return F(`/admin/datasets/${e}/revalidate${t?"?force=true":""}`,{method:"POST"},!0)}async function Abe(e){let t=e?`?user=${encodeURIComponent(e)}`:"";return F(`/admin/email-preferences${t}`,{},!0)}async function Obe(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 n6(e){return F("/admin/notify",{method:"POST",body:JSON.stringify(e)},!0)}async function Tbe(e){return F(`/admin/notify/${e}`,{},!0)}async function Pbe(){return F("/admin/summary/coverage",{},!0)}async function Ibe(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 r6(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 o6(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 Nbe(){return F("/admin/zarr-catalog/publish",{method:"POST"},!0)}async function Fbe(e){return F("/admin/neurobagel/regenerate",{method:"POST",body:JSON.stringify(e)},!0)}async function Mbe(){return F("/admin/neurobagel/status",{method:"GET"},!0)}async function jbe(){return F("/admin/neurobagel/verify",{method:"POST",body:"{}"},!0)}async function Lbe(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 qbe(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 Ube(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 Bbe(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 Hbe(e){let t=e?.apply?"?apply=1":"";return F(`/admin/imports/coverage-sweep${t}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Gbe(e){let t=e?.apply?"?apply=1":"";return F(`/admin/imports/weekly-summary${t}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function zbe(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 Vbe(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 Wbe(){return F("/admin/users/duplicates",{},!0,Tne)}async function Kbe(e){return F(`/admin/users/${e}/clear-identity-conflict`,{method:"POST"},!0,Pne)}async function Jbe(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 Ybe(){return F("/admin/datasets/anonymity-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function u_(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 ay(e,t,n){let r=n?`?head=${encodeURIComponent(n)}`:"";return F(`/admin/pr-reviews/${encodeURIComponent(e)}/${t}${r}`,{method:"GET"},!0)}async function s6(e,t,n={}){let r=n.redo?"?redo=1":"";return F(`/admin/pr-reviews/${encodeURIComponent(e)}/${t}/start${r}`,{method:"POST"},!0)}async function Xbe(e){return F(`/admin/pr-review-authors/${encodeURIComponent(e)}`,{method:"GET"},!0)}async function Qbe(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 Zbe(e){return F(`/admin/pr-review-authors/${encodeURIComponent(e)}`,{method:"DELETE"},!0)}async function e0e(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 a6(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 c6(e){return F(`/admin/mail/tickets/${e}`,{},!0)}async function t0e(e,t,n){let r={text:t};return F(`/admin/mail/tickets/${e}/reply`,Jd(r,{"Idempotency-Key":n}),!0)}async function n0e(e,t,n){let r={text:t};return F(`/admin/mail/tickets/${e}/note`,Jd(r,{"Idempotency-Key":n}),!0)}async function r0e(e,t){let n={user_id:t};return F(`/admin/mail/tickets/${e}/assign`,Jd(n),!0)}async function o0e(e,t){return F(`/admin/mail/tickets/${e}/status`,Jd({status:t}),!0)}async function s0e(e,t){let n={summary:t};return F(`/admin/mail/tickets/${e}/summary`,i6(n),!0)}async function i0e(e,t){let n=t?{reason:t}:{};return F(`/admin/mail/tickets/${e}/escalate`,Jd(n),!0)}async function a0e(e,t){return F(`/admin/mail/tickets/${e}/spam`,Jd(t),!0)}async function c0e(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 l0e(e){return F("/admin/mail/blocklist",Jd(e),!0)}async function u0e(e){return F(`/admin/mail/blocklist/${e}`,{method:"DELETE"},!0)}async function d0e(){return F("/admin/mail/queues",{},!0)}async function f0e(e,t){return F(`/admin/mail/queues/${encodeURIComponent(e)}`,i6(t),!0)}async function p0e(e){return F(`/admin/mail/availability${e===void 0?"":`/${e}`}`,{},!0)}async function l6(e,t){return F(`/admin/mail/availability${t===void 0?"":`/${t}`}`,i6(e),!0)}async function m0e(e){return F("/admin/mail/reprocess",Jd({raw_key:e}),!0)}async function h0e(e){return(await F(`/admin/users/by-id/${e}`,{},!0)).user.username}var Jd=(e,t)=>({method:"POST",body:JSON.stringify(e),...t?{headers:t}:{}}),i6=(e)=>({method:"PUT",body:JSON.stringify(e)});var Rc=G(()=>{tw();eg();wr();Ve()});async function mo(e,t){return F(`/datasets/${e}/upload-credentials`,{method:"POST",body:JSON.stringify({duration_seconds:t})},!0)}async function u6(e,t){return F(`/datasets/${e}/download-credentials`,{method:"POST",body:JSON.stringify({duration_seconds:t})},!0)}async function y0e(e){return F(`/admin/datasets/${e}/files`,{},!0)}async function b0e(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 w0e(e,t){let n=0,r=[],o=[];for(let s=0;s<t.length;s+=g0e){let i=t.slice(s,s+g0e),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 g0e=100;var $c=G(()=>{wr();Ve()});async function _$(e){return F(`/datasets/${e}/ci/status`,{},!0)}async function _0e(e){return F(`/datasets/${e}/manifest`,{},!0)}async function x$(e,t){return F(`/datasets/${e}/manifest/${t}`,{},!0)}function x0e(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 Yd(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(x0e),r}async function v0e(e){return F(`/datasets/resolve/${e}`,{},"optional")}async function E0e(){return F("/datasets/facets",{signal:AbortSignal.timeout(5000)},"optional",DS)}async function S0e(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",Sne)}async function ir(e){let t=await F(`/datasets/${e}`,{},"optional");return x0e(t.dataset)}async function Cp(e){return F(`/datasets/${e}/versions`,{},!0)}async function k0e(e){try{let t=await Cp(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&&!ng(t))return!1;throw t}}async function v$(e){return F("/datasets",{method:"POST",body:JSON.stringify(e)},!0)}async function R0e(e,t){return F(`/datasets/${e}/attestation`,{method:"PUT",body:JSON.stringify(t)},!0)}async function E$(e){return F(`/datasets/${e}/finalize`,{method:"POST"},!0)}async function d6(e){return F(`/datasets/${e}/request-access`,{method:"POST"},!0)}async function $0e(e,t){let n=t?`?status=${t}`:"";return F(`/datasets/${e}/access-requests${n}`,{},!0)}async function D0e(e,t){return F(`/datasets/${e}/access-requests/${t}/approve`,{method:"POST"},!0)}async function C0e(e,t){return F(`/datasets/${e}/access-requests/${t}/deny`,{method:"POST"},!0)}async function A0e(e,t){return F(`/datasets/${e}/invite`,{method:"POST",body:JSON.stringify({username:t})},!0)}async function O0e(e){return F(`/datasets/${e}/collaborators`,{},!0)}async function T0e(e,t){return F(`/admin/datasets/${e}/enrichment`,{method:"POST",body:JSON.stringify(t)},!0)}var w$;var Dc=G(()=>{eg();wr();Ve();w$=/^\d{4}-\d{4}-\d{4}-\d{3}[\dX]$/});function swe(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"&&!Hl.has(n)).filter((n)=>t.prefix?n.startsWith(t.prefix):!0).sort()}var Hl;var $$=G(()=>{Hl=new Set(["nm000103","nm000104","nm000105","nm000106","nm000107"])});function go(e){return e.replace(iwe,awe)}function awe(e){if(e===`
114
+ `)}var Sye=!1;var LM=G(()=>{We()});function Vr(){if(process.env.TEST_API_URL)return process.env.TEST_API_URL;if(kp)return qM;return Yt().apiUrl||qM}async function F(e,t={},n=!1,r){let o=`${Vr()}${e}`,s={"Content-Type":"application/json","X-CLI-Version":Vs,...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(Ul())l$({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 ${Vr()}`,{originalError:p instanceof Error?p.message:String(p)})}let d;try{d=await l.text()}catch(p){if(Ul())l$({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(Ul())l$({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 T=typeof f.message==="string"?f.message:"NEMAR is in maintenance mode. Please retry shortly.",q=typeof f.eta==="string"?f.eta:null,L=new id(f.mode,T,q,f.details);throw d$(L),L}let p=typeof f.block_reason==="string",m=Array.isArray(f.missing)?f.missing.filter((T)=>typeof T==="string"):void 0,h=typeof f.error==="string"&&(pne.includes(f.error)||One.includes(f.error)),g=typeof f.error==="string"&&(AS.options.includes(f.error)||Fne.includes(f.error)),y=typeof f.error==="string"&&ane.includes(f.error),b=typeof f.error==="string"&&mne.includes(f.error),x=typeof f.error==="string"&&$ne.includes(f.error),v=typeof f.error==="string"&&Rne.includes(f.error),S=typeof f.error==="string"&&Dne.includes(f.error),E=typeof f.error==="string"&&Kne.includes(f.error),I=p||E||v||S||h||g||y||b||x||m!==void 0&&typeof f.error==="string"&&fne.includes(f.error)?f.message||f.error:f.error||f.message;if(l.status===404&&f.error==="Not Found"&&typeof f.message==="string")I=`${f.message}. This NEMAR backend does not support this command yet.`;let H=new U(l.status,I||"Request failed",f.details,typeof f.step==="string"?f.step:void 0,p?f.block_reason:void 0,m);if(typeof f.error==="string")H.code=f.error;if(typeof f.reason==="string")H.reason=f.reason;throw H.rawBody=f,H}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 qM="https://api.nemar.org",kp;var wr=G(()=>{tw();PS();PI();ow();Bh();qh();Ir();xn();LM();Sp();Ve();kp=qM.includes("workers.dev")});async function Qg(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 Zg(e){return F(`/datasets/${e}/publish/status`,{},!0)}async function $ye(e){return F(`/datasets/${e}/publish/resend`,{method:"POST"},!0)}async function Dye(e){return F(`/datasets/${e}/publish/withdraw`,{method:"POST"},!0)}async function Rp(e={}){let{statuses:t,search:n}=typeof e==="string"?{statuses:e?[e]:[]}:e,r=await kye(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 kye([a],n));let i=s.flatMap((a)=>a.requests).sort(Cye);o={...r,requests:i,count:i.length}}return n?F_t(o,n):o}function Cye(e,t){return e.requested_at<t.requested_at?1:e.requested_at>t.requested_at?-1:0}async function kye(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)=>foe(t,[s.dataset_id,s.requested_by_username,s.dataset_name])),r=(s)=>poe(s.dataset_id,t)?0:1,o=[...n].sort((s,i)=>r(s)-r(i)||Cye(s,i));return{...e,requests:o,count:o.length}}async function ey(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 f$(e){return F(`/admin/publish/${e}/identifier-screen`,{method:"POST"},!0)}async function p$(e){return F(`/admin/publish/${e}/review`,{},!0)}async function Aye(e){return F(`/admin/publish/${e}/review/start`,{method:"POST"},!0)}async function Oye(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 ty(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 M_t(e,t=[]){if(e){let n=Ya.indexOf(e);if(n>=0)return n+1}return Math.min(t.length+1,Ya.length)}function j_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 L_t(){let e=process.env.NEMAR_APPROVE_RETRY_DELAY_MS;if(e===void 0||!/^\d+$/.test(e))return ok;let t=Number(e);return Number.isSafeInteger(t)&&t<=ok?t:ok}async function ny(e,t=!1,n=!1,r=!1,o,s,i,a,c){let d=L_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:M_t(S,E),stepTotal:Ya.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?{[Cne]: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?{[loe]: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=Rye(b);return E}catch(E){if(x=E,S===5||!j_t(E)){if(E instanceof U&&b.length>0)E.stepResults=Rye(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 Rye(e){let t=new Map;for(let n of e)t.set(n.step,n);return Array.from(t.values())}var aa=G(()=>{rk();Bh();ik();wr();Ve()});function g$(e){if(e.service_access===void 0||e.service_access===null)return"unknown";return e.service_access?"upload":"browse"}async function YM(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,une)}async function y$(e,t=!1){return F(`/admin/users/by-id/${e}${t?"?include_deleted=true":""}`,{},!0,yne)}async function Uye(e,t){return F(`/admin/users/by-id/${e}`,{method:"PATCH",body:JSON.stringify(t)},!0,bne)}async function Bye(e){return F(`/admin/approve/${e}`,{method:"POST"},!0)}async function Hye(e){return F(`/admin/approve/by-id/${e}`,{method:"POST"},!0)}async function Gye(e){return F(`/admin/revoke/${e}`,{method:"POST"},!0)}async function zye(e){return F(`/admin/revoke/by-id/${e}`,{method:"POST"},!0)}async function Vye(e){return F(`/admin/users/by-id/${e}/verify`,{method:"POST"},!0)}async function Wye(e,t){return F(`/admin/users/${e}/role`,{method:"POST",body:JSON.stringify({role:t})},!0)}async function Kye(e,t){return F(`/admin/users/${e}/kind`,{method:"POST",body:JSON.stringify({kind:t})},!0)}async function b$(e){return F(`/admin/users/${encodeURIComponent(e)}`,{},!0)}async function Jye(e,t){return F(`/admin/users/${e}/keys`,{method:"POST",body:JSON.stringify({name:t})},!0,TS)}async function Yye(e){return F(`/admin/users/${e}/keys`,{},!0,OS)}async function Xye(e,t){return F(`/admin/users/${e}/keys/${t}`,{method:"DELETE"},!0)}async function Qye(e){return F(`/datasets/${e}/publish`,{method:"POST"},!0)}async function Zye(e){return F(`/admin/datasets/${e}/ci`,{},!0)}async function Bl(e){return F(`/admin/datasets/${e}/ci`,{method:"POST"},!0)}async function XM(e){return F(`/admin/datasets/${e}/ci/validate`,{method:"POST"},!0)}async function QM(e){return F(`/admin/datasets/${e}/ci/sync`,{method:"POST"},!0)}async function ebe(e,t){return F(`/admin/datasets/${e}/doi/concept`,{method:"POST",body:JSON.stringify(t)},!0)}async function l_(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 tbe(e,t){return F(`/admin/datasets/${e}/withdraw`,{method:"POST",body:JSON.stringify({reason:t.reason,dry_run:t.dryRun})},!0)}async function nbe(e,t){return F(`/admin/datasets/${e}/restore`,{method:"POST",body:JSON.stringify({dry_run:t.dryRun})},!0)}async function rbe(e,t){return F(`/admin/datasets/${e}/unpublish`,{method:"POST",body:JSON.stringify({reason:t.reason,dry_run:t.dryRun})},!0)}async function obe(e){return F(`/admin/datasets/${e}/reset`,{method:"POST"},!0)}async function sbe(e,t=!1){return F(`/admin/datasets/${e}`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({force:t})},!0)}async function ibe(e){return F("/admin/datasets/bulk-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dataset_ids:e})},!0)}async function abe(e){return F("/admin/datasets/import",{method:"POST",body:JSON.stringify(e)},!0)}async function cbe(e){return F("/admin/datasets/exemplar",{method:"POST",body:JSON.stringify(e)},!0)}async function lbe(e){return F(`/admin/datasets/${e}/exemplar/remint-dois`,{method:"POST"},!0)}async function e6(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 ube(e){return F(`/admin/imports/${e}/rollback`,{method:"POST"},!0)}async function dbe(e){return F(`/admin/imports/${e}/retry`,{method:"POST"},!0)}async function t6(e){return F(`/admin/imports/${e}/verify`,{method:"POST"},!0)}async function fbe(e){return F("/admin/imports/dispatch-cooldown",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dataset_ids:e})},!0)}async function sy(e,t){return F(`/admin/datasets/${e}/reindex`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})},!0)}async function pbe(e,t){return F("/admin/datasets/reindex/bulk",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filter:e,...t??{}})},!0)}async function mbe(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 hbe(){return F("/admin/datasets/hed-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function gbe(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 ybe(){return F("/admin/datasets/recording-stats-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function bbe(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 wbe(){return F("/admin/datasets/signal-defaults-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function _be(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 xbe(){return F("/admin/datasets/data-integrity-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function vbe(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 Ebe(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 Sbe(){return F("/admin/datasets/availability-report-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function kbe(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 iy(e,t){return F(`/admin/datasets/${e}/enforce`,{method:"POST",body:JSON.stringify({dry_run:t})},!0)}async function Rbe(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 $be(e,t){return F(`/admin/datasets/${e}/review-ruleset`,{method:"POST",body:JSON.stringify({dry_run:t.dryRun,remove:t.remove})},!0)}async function Dbe(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 Cbe(e,t=!1){return F(`/admin/datasets/${e}/revalidate${t?"?force=true":""}`,{method:"POST"},!0)}async function Abe(e){let t=e?`?user=${encodeURIComponent(e)}`:"";return F(`/admin/email-preferences${t}`,{},!0)}async function Obe(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 n6(e){return F("/admin/notify",{method:"POST",body:JSON.stringify(e)},!0)}async function Tbe(e){return F(`/admin/notify/${e}`,{},!0)}async function Pbe(){return F("/admin/summary/coverage",{},!0)}async function Ibe(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 r6(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 o6(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 Nbe(){return F("/admin/zarr-catalog/publish",{method:"POST"},!0)}async function Fbe(e){return F("/admin/neurobagel/regenerate",{method:"POST",body:JSON.stringify(e)},!0)}async function Mbe(){return F("/admin/neurobagel/status",{method:"GET"},!0)}async function jbe(){return F("/admin/neurobagel/verify",{method:"POST",body:"{}"},!0)}async function Lbe(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 qbe(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 Ube(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 Bbe(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 Hbe(e){let t=e?.apply?"?apply=1":"";return F(`/admin/imports/coverage-sweep${t}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Gbe(e){let t=e?.apply?"?apply=1":"";return F(`/admin/imports/weekly-summary${t}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function zbe(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 Vbe(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 Wbe(){return F("/admin/users/duplicates",{},!0,Tne)}async function Kbe(e){return F(`/admin/users/${e}/clear-identity-conflict`,{method:"POST"},!0,Pne)}async function Jbe(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 Ybe(){return F("/admin/datasets/anonymity-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function u_(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 ay(e,t,n){let r=n?`?head=${encodeURIComponent(n)}`:"";return F(`/admin/pr-reviews/${encodeURIComponent(e)}/${t}${r}`,{method:"GET"},!0)}async function s6(e,t,n={}){let r=n.redo?"?redo=1":"";return F(`/admin/pr-reviews/${encodeURIComponent(e)}/${t}/start${r}`,{method:"POST"},!0)}async function Xbe(e){return F(`/admin/pr-review-authors/${encodeURIComponent(e)}`,{method:"GET"},!0)}async function Qbe(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 Zbe(e){return F(`/admin/pr-review-authors/${encodeURIComponent(e)}`,{method:"DELETE"},!0)}async function e0e(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 a6(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 c6(e){return F(`/admin/mail/tickets/${e}`,{},!0)}async function t0e(e,t,n){let r={text:t};return F(`/admin/mail/tickets/${e}/reply`,Jd(r,{"Idempotency-Key":n}),!0)}async function n0e(e,t,n){let r={text:t};return F(`/admin/mail/tickets/${e}/note`,Jd(r,{"Idempotency-Key":n}),!0)}async function r0e(e,t){let n={user_id:t};return F(`/admin/mail/tickets/${e}/assign`,Jd(n),!0)}async function o0e(e,t){return F(`/admin/mail/tickets/${e}/status`,Jd({status:t}),!0)}async function s0e(e,t){let n={summary:t};return F(`/admin/mail/tickets/${e}/summary`,i6(n),!0)}async function i0e(e,t){let n=t?{reason:t}:{};return F(`/admin/mail/tickets/${e}/escalate`,Jd(n),!0)}async function a0e(e,t){return F(`/admin/mail/tickets/${e}/spam`,Jd(t),!0)}async function c0e(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 l0e(e){return F("/admin/mail/blocklist",Jd(e),!0)}async function u0e(e){return F(`/admin/mail/blocklist/${e}`,{method:"DELETE"},!0)}async function d0e(){return F("/admin/mail/queues",{},!0)}async function f0e(e,t){return F(`/admin/mail/queues/${encodeURIComponent(e)}`,i6(t),!0)}async function p0e(e){return F(`/admin/mail/availability${e===void 0?"":`/${e}`}`,{},!0)}async function l6(e,t){return F(`/admin/mail/availability${t===void 0?"":`/${t}`}`,i6(e),!0)}async function m0e(e){return F("/admin/mail/reprocess",Jd({raw_key:e}),!0)}async function h0e(e){return(await F(`/admin/users/by-id/${e}`,{},!0)).user.username}var Jd=(e,t)=>({method:"POST",body:JSON.stringify(e),...t?{headers:t}:{}}),i6=(e)=>({method:"PUT",body:JSON.stringify(e)});var Rc=G(()=>{tw();eg();wr();Ve()});async function mo(e,t){return F(`/datasets/${e}/upload-credentials`,{method:"POST",body:JSON.stringify({duration_seconds:t})},!0)}async function u6(e,t){return F(`/datasets/${e}/download-credentials`,{method:"POST",body:JSON.stringify({duration_seconds:t})},!0)}async function y0e(e){return F(`/admin/datasets/${e}/files`,{},!0)}async function b0e(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 w0e(e,t){let n=0,r=[],o=[];for(let s=0;s<t.length;s+=g0e){let i=t.slice(s,s+g0e),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 g0e=100;var $c=G(()=>{wr();Ve()});async function _$(e){return F(`/datasets/${e}/ci/status`,{},!0)}async function _0e(e){return F(`/datasets/${e}/manifest`,{},!0)}async function x$(e,t){return F(`/datasets/${e}/manifest/${t}`,{},!0)}function x0e(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 Yd(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(x0e),r}async function v0e(e){return F(`/datasets/resolve/${e}`,{},"optional")}async function E0e(){return F("/datasets/facets",{signal:AbortSignal.timeout(5000)},"optional",DS)}async function S0e(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",Sne)}async function ir(e){let t=await F(`/datasets/${e}`,{},"optional");return x0e(t.dataset)}async function Cp(e){return F(`/datasets/${e}/versions`,{},!0)}async function k0e(e){try{let t=await Cp(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&&!ng(t))return!1;throw t}}async function v$(e){return F("/datasets",{method:"POST",body:JSON.stringify(e)},!0)}async function R0e(e,t){return F(`/datasets/${e}/attestation`,{method:"PUT",body:JSON.stringify(t)},!0)}async function E$(e){return F(`/datasets/${e}/finalize`,{method:"POST"},!0)}async function d6(e){return F(`/datasets/${e}/request-access`,{method:"POST"},!0)}async function $0e(e,t){let n=t?`?status=${t}`:"";return F(`/datasets/${e}/access-requests${n}`,{},!0)}async function D0e(e,t){return F(`/datasets/${e}/access-requests/${t}/approve`,{method:"POST"},!0)}async function C0e(e,t){return F(`/datasets/${e}/access-requests/${t}/deny`,{method:"POST"},!0)}async function A0e(e,t){return F(`/datasets/${e}/invite`,{method:"POST",body:JSON.stringify({username:t})},!0)}async function O0e(e){return F(`/datasets/${e}/collaborators`,{},!0)}async function T0e(e,t){return F(`/admin/datasets/${e}/enrichment`,{method:"POST",body:JSON.stringify(t)},!0)}var w$;var Dc=G(()=>{eg();wr();Ve();w$=/^\d{4}-\d{4}-\d{4}-\d{3}[\dX]$/});function swe(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"&&!Hl.has(n)).filter((n)=>t.prefix?n.startsWith(t.prefix):!0).sort()}var Hl;var $$=G(()=>{Hl=new Set(["nm000103","nm000104","nm000105","nm000106","nm000107"])});function go(e){return e.replace(iwe,awe)}function awe(e){if(e===`
115
115
  `)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 d_(e){return e.replace(iwe,(t)=>t===`
116
116
  `||t==="\t"?t:awe(t))}function D$(e,t=", "){return e.map(go).join(t)}var iwe,Cc=(e)=>go(e)===e;var Ap=G(()=>{iwe=/[\p{Cc}\p{Cf}\u2028\u2029\u034f\u115f\u1160\u3164\uffa0\ufe00-\ufe0f\u{e0100}-\u{e01ef}]/gu});async function X_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 Op(){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 C$(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 A$(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 Ac(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 Op();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 X_t();if(i.works)r=t;else return{success:!1,error:`GitHub authentication not configured.
117
117
 
@@ -761,7 +761,7 @@ which names the field and never repeats what was typed.
761
761
  Examples:
762
762
  nemar admin oidc clients add --name "Compute portal" --redirect-uri https://portal.example.org/cb \\
763
763
  --scopes openid,profile,orcid --grants authorization_code --sign-in-rule person_proven_orcid \\
764
- --audience https://nemar-api-dev.sccn-org.workers.dev
764
+ --audience https://api.nemar.org
765
765
 
766
766
  Exit codes:
767
767
  0 registered; the secret was printed.
@@ -1000,7 +1000,7 @@ ${b.message}`,r);if(x)return Zt("message",`The squash message would not carry th
1000
1000
  `);let{phase:f,code:p}=d;e(`${Dx("result",p===void 0?{phase:f}:{phase:f,code:p})}
1001
1001
  `);return}e(`${Dx("result",{phase:"failed",code:"runner-failed"})}
1002
1002
  `)};DA={emit(d,f){if(d==="result")o=String(f?.phase??"failed");e(`${Dx(d,f)}
1003
- `)},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),DA}function vq(e){return e.some((t)=>t===mAe||t.startsWith(`${mAe}=`))}function UIt(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 bAe(e,t,n){let r=xq(e);if(r===null)throw Cr("id on the command line");let o=MIt(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:UIt(t),marker:s?Rf(s,"repull-reported"):null,sink:n}}var BIt="https://nemar-api-dev.sccn-org.workers.dev";function wAe(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 Eq(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 _Ae(e,t){let n=Eq(e,t.argv);if(n)return n;let r=t.ownVersion??Vs;if((t.devBuild??kp)||!Ay.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??(Kg()||Ul()||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(AA(t.env,t.nowMs??Date.now())===null)return new j("auto-token-clock",`${xAe} does not say when the App token was minted, so the run cannot keep its pushes inside the token's hour.`);return null}var xAe="NEMAR_REPULL_TOKEN_SINCE";function AA(e,t){let n=e[xAe]?.trim()??"";if(!/^[1-9][0-9]{0,11}$/.test(n))return null;let r=Number(n);return r*1000<=t+300000?r:null}function HIt(e,t){return(e+P_)*1000-t}function Cx(e,t,n){let r=(n+tSe+Bj)*1000;if(HIt(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 Ax(e){let t=nl(e);return Gj({bytes:t.copy_bytes??0,objects:t.copy_items??0})}function yb(e,t){return new j("auto-option",t==="required"?`An automatic run needs ${e}.`:`An automatic run does not take ${e}.`)}function vAe(e){if(!e.executable)throw new j("not-executable","The plan is not executable.");OA(e.body)}function OA(e){let t=nl(e),n=ZEe(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=GIt();if(r===void 0||o===void 0||s===void 0||i===void 0||t.local_bytes_unknown!==0||Gj({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 TA(e){return`${e}.planner`}function EAe(e,t,n,r){DIt(Rf(t,"computed"),{mode:448});for(let[s,i]of n)_q(Rf(t,"computed",s),i,{mode:384});_q(Rf(t,"digest"),`${r}
1003
+ `)},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),DA}function vq(e){return e.some((t)=>t===mAe||t.startsWith(`${mAe}=`))}function UIt(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 bAe(e,t,n){let r=xq(e);if(r===null)throw Cr("id on the command line");let o=MIt(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:UIt(t),marker:s?Rf(s,"repull-reported"):null,sink:n}}var BIt="https://api.nemar.org";function wAe(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 Eq(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 _Ae(e,t){let n=Eq(e,t.argv);if(n)return n;let r=t.ownVersion??Vs;if((t.devBuild??kp)||!Ay.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??(Kg()||Ul()||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(AA(t.env,t.nowMs??Date.now())===null)return new j("auto-token-clock",`${xAe} does not say when the App token was minted, so the run cannot keep its pushes inside the token's hour.`);return null}var xAe="NEMAR_REPULL_TOKEN_SINCE";function AA(e,t){let n=e[xAe]?.trim()??"";if(!/^[1-9][0-9]{0,11}$/.test(n))return null;let r=Number(n);return r*1000<=t+300000?r:null}function HIt(e,t){return(e+P_)*1000-t}function Cx(e,t,n){let r=(n+tSe+Bj)*1000;if(HIt(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 Ax(e){let t=nl(e);return Gj({bytes:t.copy_bytes??0,objects:t.copy_items??0})}function yb(e,t){return new j("auto-option",t==="required"?`An automatic run needs ${e}.`:`An automatic run does not take ${e}.`)}function vAe(e){if(!e.executable)throw new j("not-executable","The plan is not executable.");OA(e.body)}function OA(e){let t=nl(e),n=ZEe(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=GIt();if(r===void 0||o===void 0||s===void 0||i===void 0||t.local_bytes_unknown!==0||Gj({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 TA(e){return`${e}.planner`}function EAe(e,t,n,r){DIt(Rf(t,"computed"),{mode:448});for(let[s,i]of n)_q(Rf(t,"computed",s),i,{mode:384});_q(Rf(t,"digest"),`${r}
1004
1004
  `,{mode:384});let o=TA(e);OIt(o,{recursive:!0,force:!0}),AIt(t,o)}function SAe(e,t){let n=TA(e),r=Rf(n,"computed"),o=Rf(n,"digest");if(!bq(Rf(n,"upstream.git"))||!bq(r)||!bq(o)||wq(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 CIt(r))s.set(i,wq(Rf(r,i)));return{workdir:n,computed:s}}function GIt(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<Hj?n:Hj}async function kAe(e,t,n=fetch){let r=t.GH_TOKEN?.trim();if(!r)return!1;let o;try{o=Rn(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 PA(e,t){if(Uj(e))return e;if(t===void 0)return"no-code";if(t==="prepare"&&m$e.includes(e??""))return"scrub-failed";return QEe[t]}var zIt=15000,gAe=["opened","finished","refused","failed"];async function Sq(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=PA(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??Vr(),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??zIt)});d=p.status,f=(await p.json().catch(()=>null))?.code}catch{if(c={stored:!1,code:"report-unanswered"},l<a)await yAe(r.backoffMs??2000);continue}if(d===200){c={stored:!0};break}if(c={stored:!1,code:typeof f==="string"&&Uj(f)?f:"report-unanswered"},d<500)break;if(l<a)await yAe(r.backoffMs??2000)}if(e.sink.emit("report",{phase:t,answer:c.stored?"stored":c.code}),c.stored&&gAe.includes(t))e.sink.stored(t,o.code);if(c.stored&&gAe.includes(t)&&e.marker)try{_q(e.marker,`${t}
1005
1005
  `,{mode:384})}catch{}return c}var yAe=(e)=>new Promise((t)=>setTimeout(t,e));na();xo();wr();Ve();import{existsSync as WFt,readdirSync as KFt,rmdirSync as JFt}from"fs";import{dirname as jx,join as Mx}from"path";Ir();Bc();Yr();bf();ba();WA();Fy();xo();Ve();import{dirname as lFt,join as uFt}from"path";Ir();function ls(e,t){return new j(e,t)}var Uq=["registered","pr_open","gates_clear"];async function s1e(e,t,n){let r=await ab({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 (${ib(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 Ys(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 dFt(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 i1e(e,t,n,r){return r!==null&&t!==r?dFt(e,t,n,r):a1e(e,t)}function a1e(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 fFt(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(`
1006
1006
  `)}
@@ -2618,7 +2618,7 @@ Examples:
2618
2618
  `)}}}Bh();Ve();function LPe(e){return e instanceof U&&e.statusCode===422&&e.rawBody?.status==="blocked"&&CS(e.blockReason)}function qPe(e){let t=e.rawBody?.ci_url;return typeof t==="string"&&/^https:\/\/\S+$/.test(t)?t:void 0}function k3(e){return e==="bids_validation_in_progress"?"Request recorded: BIDS validation is still running.":"Request recorded: BIDS validation has not started yet."}function R3(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();Ir();async function Z1(){let e=Yt().sandboxCompleted;if(e!==void 0)return{status:e?"completed":"not_completed"};try{let t=await S$();if(Bn("sandboxCompleted",t.sandbox_completed),t.sandbox_dataset_id)Bn("sandboxDatasetId",t.sandbox_dataset_id);return t.sandbox_completed?{status:"completed"}:{status:"not_completed"}}catch(t){return{status:"unknown",reason:W(t)}}}We();Ai();WL();We();$o();Rc();Ve();em();xC();Ap();Ai();Ci();kC();YL();gf();tm();import{existsSync as $3,mkdirSync as fUt,readFileSync as pUt,statSync as mUt,writeFileSync as UPe}from"fs";import{join as hUt,resolve as D3}from"path";function BPe(e,t,n){if(!ga(n,"metadata_write")){if(t)try{let r=D3(e,".nemar"),o=D3(r,"metadata.json");if(!$3(o)){if(!$3(r))fUt(r,{recursive:!0});UPe(o,JSON.stringify(t,null,2))}let s=D3(e,".bidsignore"),i="";if($3(s))i=pUt(s,"utf-8");if(!i.includes(".nemar/")){let a=i?`${i.trimEnd()}
2619
2619
  .nemar/
2620
2620
  `:`.nemar/
2621
- `;UPe(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."))}Zl(n,"metadata_write"),Qr(e,n)}else console.log(u.dim(" Metadata write already completed (skipping)"))}var HPe=1073741824;function gUt(e,t,n=HPe){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 yUt(e,t){return t.filter((n)=>{try{return yo(n.path,mUt(hUt(e,n.path)).size)}catch{return!0}})}function bUt(e){let t=0;for(let n of Object.values(e.files))t+=n.size;return t}function wUt(e){return["Warning: saving dataset changes has produced no stdout or stderr for",`${RC(e)}. git add -A is still running.`,"Wait, or interrupt and rerun the upload; the save step will run again."].join(" ")}async function GPe(e,t,n,r={}){if(!ga(n,"dataset_save")){let o=C({text:"Saving dataset changes...",...r.spinnerStream?{stream:r.spinnerStream}:{}}).start(),s=r.skipMinBytes??HPe,i=[];if(bUt(n)>=s){let c=r.annexedPaths??null;if(c===null)try{c=await hf(e)}catch(l){console.log(u.dim(` Could not list annexed files (${W(l)}); staging will re-read them`))}if(c!==null)i=yUt(e,gUt(n,c,s)??[])}let a=await Gl(e,"Initial NEMAR dataset upload",t,{skipContentCheck:i,onInactivityWarning:(c)=>{o=Z_(o,wUt(c))},...r.inactivityWarningAfterMs===void 0?{}:{inactivityWarningAfterMs:r.inactivityWarningAfterMs}});if(!a.success)return Qr(e,n),Mo(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 r4(e,r.verifyRemote)}catch(l){return Qr(e,n),Mo(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){eu(n,"s3_upload"),Qr(e,n);let l=D$(c.slice(0,5)),d=c.length>5?` (and ${c.length-5} more)`:"";return Mo(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"),Zl(n,"dataset_save"),Qr(e,n)}else console.log(u.dim(" Dataset save already completed (skipping)"));return En()}async function zPe(e,t){if(!ga(t,"github_push")){let n=C("Pushing metadata to GitHub...").start(),r=await _r(e);if(!r.success)return Qr(e,t),Mo(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");Zl(t,"github_push"),Qr(e,t)}else console.log(u.dim(" GitHub push already completed (skipping)"));return En()}async function VPe(e,t,n){if(!ga(n,"ci_deploy")){let r=C("Setting up BIDS validation CI...").start(),o="configured";try{await Bl(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 Zl(n,"ci_deploy"),Qr(e,n),o}return console.log(u.dim(" CI deploy already completed (skipping)")),"unknown"}function _Ut(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 WPe(e,t,n="unknown"){Q_(e),wRe(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(),_Ut(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."))}gf();tm();async function KPe(e,t={}){let n=await Twe(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 kRe(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 o$e(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(BPe(e.absolutePath,e.coAuthorEnrichment,s),(await(t.saveStep??GPe)(e.absolutePath,e.author,s,{annexedPaths:i,verifyRemote:Wc,...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 En(s)}We();Xl();gm();K_();xn();Gt();import{randomBytes as n3t}from"crypto";import{constants as I3,accessSync as r3t,chmodSync as o3t,chownSync as s3t,closeSync as j3,copyFileSync as i3t,existsSync as wIe,fsyncSync as _Ie,lstatSync as ll,mkdirSync as a3t,mkdtempSync as c3t,openSync as L3,readSync as l3t,readdirSync as u3t,renameSync as d3t,rmSync as q3,rmdirSync as f3t,statSync as xIe,writeSync as p3t}from"fs";import{tmpdir as m3t}from"os";import{dirname as iO,join as Da}from"path";We();import{lstatSync as KUt,readdirSync as JUt,statSync as aIe}from"fs";import{open as YUt}from"fs/promises";import{join as iIe}from"path";yi();$o();Xl();var ZPe="nemar-identifier-scan/1.0 (+https://docs.nemar.org/policies/takedown/)",xUt="https://nemar-api-dev.sccn-org.workers.dev",vUt="https://data.nemar.org",EUt="https://nemar.s3.us-east-2.amazonaws.com",SUt="https://api.github.com";function rO(e,t){if(!Number.isSafeInteger(t)||t<1)throw RangeError(`${e} must be a positive integer, got ${t}`)}async function eO(e,t,n){rO("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 kUt(e){rO("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 RUt(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 $Ut(e,t){let n=e>=500||e===429;return new cr(`http-${e}`,{status:e,retryable:n,retryAfterMs:n?RUt(t):void 0})}class C3 extends Error{constructor(e){super(e);this.name="RunAborted"}}function DUt(e){rO("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 C3(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 JPe(e){let t=e instanceof Error?e.name:"";return new cr(t==="TimeoutError"||t==="AbortError"?"timeout":"network",{retryable:!0})}function CUt(e){if(e instanceof cr)return e.cls;return`error-${e instanceof Error?e.name:"unknown"}`}async function AUt(e,t={}){let n=t.tries??3,r=t.baseMs??400,o=t.sleep??((s)=>new Promise((i)=>setTimeout(i,s)));rO("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 OUt(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??ZPe},signal:AbortSignal.timeout(n.timeoutMs??30000)})}catch(a){throw JPe(a)}if(r.status!==200&&r.status!==206)throw await OUt(r),$Ut(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 JPe(a)}finally{await o.cancel().catch(()=>{return})}if(i<(n.minBytes??0))throw new cr("short-body");return s.subarray(0,i)}var eIe={sideFileBytes:2097152,participantsBytes:16777216};function PUt(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 IUt(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(PUt(a,c));return i}catch(o){if(o instanceof cr)throw o;throw new cr("aws/unavailable")}finally{clearTimeout(r)}}function NUt(){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 tO=(e)=>e.replace(/\/+$/,"");function tIe(e={}){let t=e.retryAfterCapMs??30000,n=e.awsTimeoutMs??600000;return{api:tO(e.api??process.env.NEMAR_API_BASE??xUt),data:tO(e.data??process.env.NEMAR_DATA_BASE??vUt),s3Base:tO(e.s3Base??EUt),githubApi:tO(e.githubApi??SUt),userAgent:e.userAgent??ZPe,fileConcurrency:e.fileConcurrency??24,workerLimit:kUt(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:DUt({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)=>IUt(r,o,{timeoutMs:n,env:e.awsEnv})),githubToken:e.githubToken??NUt(),...e.readEntryHead?{readEntryHead:e.readEntryHead}:{}}}var nIe=(e,t)=>t.startsWith(`${e.data}/`),FUt=(e,t)=>nIe(e,t)||t.startsWith(`${e.api}/`)?e.breakers.worker:e.breakers.direct;async function MUt(e,t,n){let r=FUt(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 jUt=(e,t)=>({...t===void 0?{}:{tries:t},baseMs:e.retryBaseMs,sleep:e.sleep,retryAfterCapMs:e.retryAfterCapMs});var YPe=(e)=>/sub-([^/_]+)/.exec(e)?.[1]??"?";function XPe(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 LUt=(e)=>e.severity==="identifier"&&bke.has(e.kind),qUt=(e)=>Jp.has(e.kind);function rIe(e){return e.headerRead===e.edfCount&&e.incompleteReasons.length===0}function UUt(e){if(e.findings.some(LUt))return"direct-identifiers";if(e.findings.some((t)=>!qUt(t)))return"review";if(!rIe(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 BUt=/\.(edf|bdf)$/i,HUt=(e)=>e.edf===!0||BUt.test(e.path);function GUt(e){return{edf:e.filter(HUt),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/")||!zUt.test(t.path)).filter((t)=>!VUt.test(t.path)),text:e.filter((t)=>WUt.test(t.path)).filter((t)=>t.path.startsWith("sourcedata/")||t.path.startsWith("code/"))}}var zUt=/_(eeg|ieeg|meg|emg|nirs|beh|events|channels|electrodes|coordsystem|scans|physio|stim|photo|T1w|bold)\.(json|tsv)$/,VUt=/(^|\/)(dataset_description|participants|genetic_info)\.json$/,WUt=/\.(py|m|r|txt|md|ya?ml|xml|iml|cfg|ini)$/i;function oIe(e,t,n,r=0){let o=()=>MUt(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 AUt(()=>nIe(e,t.url)?e.workerLimit(o):o(),jUt(e))}async function nO(e,t,n){let r=await oIe(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 Pb(e,t){for(let n of t)e.push(n)}var QPe="edf/superseded-absent";async function sIe(e,t,n,r,o,s={}){let i=r.map((Ie)=>Ie.path),a=o==="clone",c=(Ie,Re,$n)=>a?[...Ie]:XPe(Ie,Re,$n),l=[...aC([...i,...s.extraPaths??[]])],d=Cke(i),f=Object.values(d.unscreened).reduce((Ie,Re)=>Ie+Re,0),p={},m=(Ie,Re)=>{if(Re instanceof C3)throw Re;let $n=`${Ie}/${CUt(Re)}`;p[$n]=(p[$n]??0)+1},h=(Ie)=>YPe(Ie.path),g=GUt(r),y=new Set(s.supersededEdf??[]),b=[...g.edf,...y],{participants:x,scans:v,json:S,text:E}=g,A=o==="git-tree"?XPe(b,e.limits.treeHeaderSample,h):[...b],I=0,H=0,T=0,q=0,L={},V=new Set,B=new Set,M=new Set,P=new Set,z=new Set,se=new Set;await eO(A,e.fileConcurrency,async(Ie)=>{try{let Re=await oIe(e,Ie,At,At),$n=uf(Re),{patient:Nb}=sC(Re);if(!$n.some((us)=>us.kind==="edf-unreadable")){V.add(Nb);let us=Nb.split(/\s+/);if(us.length>=4)M.add(us[0]),z.add(us[2]),P.add(us[3])}if(se.add(YPe(Ie.path)),$n.some((us)=>us.severity==="identifier"))q++,B.add(Nb);Pb(l,$n);for(let us of new Set($n.map((Am)=>Am.kind)))L[us]=(L[us]??0)+1;I++}catch(Re){if(y.has(Ie)&&Re instanceof cr&&Re.status===404){T++,p[QPe]=(p[QPe]??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 nO(e,x,e.limits.participantsBytes),$n=Ie.indexOf(`
2621
+ `;UPe(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."))}Zl(n,"metadata_write"),Qr(e,n)}else console.log(u.dim(" Metadata write already completed (skipping)"))}var HPe=1073741824;function gUt(e,t,n=HPe){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 yUt(e,t){return t.filter((n)=>{try{return yo(n.path,mUt(hUt(e,n.path)).size)}catch{return!0}})}function bUt(e){let t=0;for(let n of Object.values(e.files))t+=n.size;return t}function wUt(e){return["Warning: saving dataset changes has produced no stdout or stderr for",`${RC(e)}. git add -A is still running.`,"Wait, or interrupt and rerun the upload; the save step will run again."].join(" ")}async function GPe(e,t,n,r={}){if(!ga(n,"dataset_save")){let o=C({text:"Saving dataset changes...",...r.spinnerStream?{stream:r.spinnerStream}:{}}).start(),s=r.skipMinBytes??HPe,i=[];if(bUt(n)>=s){let c=r.annexedPaths??null;if(c===null)try{c=await hf(e)}catch(l){console.log(u.dim(` Could not list annexed files (${W(l)}); staging will re-read them`))}if(c!==null)i=yUt(e,gUt(n,c,s)??[])}let a=await Gl(e,"Initial NEMAR dataset upload",t,{skipContentCheck:i,onInactivityWarning:(c)=>{o=Z_(o,wUt(c))},...r.inactivityWarningAfterMs===void 0?{}:{inactivityWarningAfterMs:r.inactivityWarningAfterMs}});if(!a.success)return Qr(e,n),Mo(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 r4(e,r.verifyRemote)}catch(l){return Qr(e,n),Mo(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){eu(n,"s3_upload"),Qr(e,n);let l=D$(c.slice(0,5)),d=c.length>5?` (and ${c.length-5} more)`:"";return Mo(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"),Zl(n,"dataset_save"),Qr(e,n)}else console.log(u.dim(" Dataset save already completed (skipping)"));return En()}async function zPe(e,t){if(!ga(t,"github_push")){let n=C("Pushing metadata to GitHub...").start(),r=await _r(e);if(!r.success)return Qr(e,t),Mo(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");Zl(t,"github_push"),Qr(e,t)}else console.log(u.dim(" GitHub push already completed (skipping)"));return En()}async function VPe(e,t,n){if(!ga(n,"ci_deploy")){let r=C("Setting up BIDS validation CI...").start(),o="configured";try{await Bl(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 Zl(n,"ci_deploy"),Qr(e,n),o}return console.log(u.dim(" CI deploy already completed (skipping)")),"unknown"}function _Ut(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 WPe(e,t,n="unknown"){Q_(e),wRe(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(),_Ut(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."))}gf();tm();async function KPe(e,t={}){let n=await Twe(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 kRe(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 o$e(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(BPe(e.absolutePath,e.coAuthorEnrichment,s),(await(t.saveStep??GPe)(e.absolutePath,e.author,s,{annexedPaths:i,verifyRemote:Wc,...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 En(s)}We();Xl();gm();K_();xn();Gt();import{randomBytes as n3t}from"crypto";import{constants as I3,accessSync as r3t,chmodSync as o3t,chownSync as s3t,closeSync as j3,copyFileSync as i3t,existsSync as wIe,fsyncSync as _Ie,lstatSync as ll,mkdirSync as a3t,mkdtempSync as c3t,openSync as L3,readSync as l3t,readdirSync as u3t,renameSync as d3t,rmSync as q3,rmdirSync as f3t,statSync as xIe,writeSync as p3t}from"fs";import{tmpdir as m3t}from"os";import{dirname as iO,join as Da}from"path";We();import{lstatSync as KUt,readdirSync as JUt,statSync as aIe}from"fs";import{open as YUt}from"fs/promises";import{join as iIe}from"path";yi();$o();Xl();var ZPe="nemar-identifier-scan/1.0 (+https://docs.nemar.org/policies/takedown/)",xUt="https://api.nemar.org",vUt="https://data.nemar.org",EUt="https://nemar.s3.us-east-2.amazonaws.com",SUt="https://api.github.com";function rO(e,t){if(!Number.isSafeInteger(t)||t<1)throw RangeError(`${e} must be a positive integer, got ${t}`)}async function eO(e,t,n){rO("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 kUt(e){rO("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 RUt(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 $Ut(e,t){let n=e>=500||e===429;return new cr(`http-${e}`,{status:e,retryable:n,retryAfterMs:n?RUt(t):void 0})}class C3 extends Error{constructor(e){super(e);this.name="RunAborted"}}function DUt(e){rO("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 C3(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 JPe(e){let t=e instanceof Error?e.name:"";return new cr(t==="TimeoutError"||t==="AbortError"?"timeout":"network",{retryable:!0})}function CUt(e){if(e instanceof cr)return e.cls;return`error-${e instanceof Error?e.name:"unknown"}`}async function AUt(e,t={}){let n=t.tries??3,r=t.baseMs??400,o=t.sleep??((s)=>new Promise((i)=>setTimeout(i,s)));rO("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 OUt(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??ZPe},signal:AbortSignal.timeout(n.timeoutMs??30000)})}catch(a){throw JPe(a)}if(r.status!==200&&r.status!==206)throw await OUt(r),$Ut(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 JPe(a)}finally{await o.cancel().catch(()=>{return})}if(i<(n.minBytes??0))throw new cr("short-body");return s.subarray(0,i)}var eIe={sideFileBytes:2097152,participantsBytes:16777216};function PUt(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 IUt(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(PUt(a,c));return i}catch(o){if(o instanceof cr)throw o;throw new cr("aws/unavailable")}finally{clearTimeout(r)}}function NUt(){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 tO=(e)=>e.replace(/\/+$/,"");function tIe(e={}){let t=e.retryAfterCapMs??30000,n=e.awsTimeoutMs??600000;return{api:tO(e.api??process.env.NEMAR_API_BASE??xUt),data:tO(e.data??process.env.NEMAR_DATA_BASE??vUt),s3Base:tO(e.s3Base??EUt),githubApi:tO(e.githubApi??SUt),userAgent:e.userAgent??ZPe,fileConcurrency:e.fileConcurrency??24,workerLimit:kUt(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:DUt({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)=>IUt(r,o,{timeoutMs:n,env:e.awsEnv})),githubToken:e.githubToken??NUt(),...e.readEntryHead?{readEntryHead:e.readEntryHead}:{}}}var nIe=(e,t)=>t.startsWith(`${e.data}/`),FUt=(e,t)=>nIe(e,t)||t.startsWith(`${e.api}/`)?e.breakers.worker:e.breakers.direct;async function MUt(e,t,n){let r=FUt(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 jUt=(e,t)=>({...t===void 0?{}:{tries:t},baseMs:e.retryBaseMs,sleep:e.sleep,retryAfterCapMs:e.retryAfterCapMs});var YPe=(e)=>/sub-([^/_]+)/.exec(e)?.[1]??"?";function XPe(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 LUt=(e)=>e.severity==="identifier"&&bke.has(e.kind),qUt=(e)=>Jp.has(e.kind);function rIe(e){return e.headerRead===e.edfCount&&e.incompleteReasons.length===0}function UUt(e){if(e.findings.some(LUt))return"direct-identifiers";if(e.findings.some((t)=>!qUt(t)))return"review";if(!rIe(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 BUt=/\.(edf|bdf)$/i,HUt=(e)=>e.edf===!0||BUt.test(e.path);function GUt(e){return{edf:e.filter(HUt),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/")||!zUt.test(t.path)).filter((t)=>!VUt.test(t.path)),text:e.filter((t)=>WUt.test(t.path)).filter((t)=>t.path.startsWith("sourcedata/")||t.path.startsWith("code/"))}}var zUt=/_(eeg|ieeg|meg|emg|nirs|beh|events|channels|electrodes|coordsystem|scans|physio|stim|photo|T1w|bold)\.(json|tsv)$/,VUt=/(^|\/)(dataset_description|participants|genetic_info)\.json$/,WUt=/\.(py|m|r|txt|md|ya?ml|xml|iml|cfg|ini)$/i;function oIe(e,t,n,r=0){let o=()=>MUt(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 AUt(()=>nIe(e,t.url)?e.workerLimit(o):o(),jUt(e))}async function nO(e,t,n){let r=await oIe(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 Pb(e,t){for(let n of t)e.push(n)}var QPe="edf/superseded-absent";async function sIe(e,t,n,r,o,s={}){let i=r.map((Ie)=>Ie.path),a=o==="clone",c=(Ie,Re,$n)=>a?[...Ie]:XPe(Ie,Re,$n),l=[...aC([...i,...s.extraPaths??[]])],d=Cke(i),f=Object.values(d.unscreened).reduce((Ie,Re)=>Ie+Re,0),p={},m=(Ie,Re)=>{if(Re instanceof C3)throw Re;let $n=`${Ie}/${CUt(Re)}`;p[$n]=(p[$n]??0)+1},h=(Ie)=>YPe(Ie.path),g=GUt(r),y=new Set(s.supersededEdf??[]),b=[...g.edf,...y],{participants:x,scans:v,json:S,text:E}=g,A=o==="git-tree"?XPe(b,e.limits.treeHeaderSample,h):[...b],I=0,H=0,T=0,q=0,L={},V=new Set,B=new Set,M=new Set,P=new Set,z=new Set,se=new Set;await eO(A,e.fileConcurrency,async(Ie)=>{try{let Re=await oIe(e,Ie,At,At),$n=uf(Re),{patient:Nb}=sC(Re);if(!$n.some((us)=>us.kind==="edf-unreadable")){V.add(Nb);let us=Nb.split(/\s+/);if(us.length>=4)M.add(us[0]),z.add(us[2]),P.add(us[3])}if(se.add(YPe(Ie.path)),$n.some((us)=>us.severity==="identifier"))q++,B.add(Nb);Pb(l,$n);for(let us of new Set($n.map((Am)=>Am.kind)))L[us]=(L[us]??0)+1;I++}catch(Re){if(y.has(Ie)&&Re instanceof cr&&Re.status===404){T++,p[QPe]=(p[QPe]??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 nO(e,x,e.limits.participantsBytes),$n=Ie.indexOf(`
2622
2622
  `);if($n<0&&Re)throw new cr("header-truncated");Pb(l,kke($n<0?Ie:Ie.slice(0,$n))),Pb(l,$ke(Ie)),ot=Re}catch(Ie){ln=!0,m("participants",Ie)}let lt=c(v,e.limits.scansTables,h),ae=0;await eO(lt,e.fileConcurrency,async(Ie)=>{if(Ie.size===0){ae++;return}try{let{text:Re}=await nO(e,Ie,e.limits.sideFileBytes);Pb(l,iC(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 eO(re,e.fileConcurrency,async(Ie)=>{if(Ie.size===0){Ge++;return}try{let{text:Re}=await nO(e,Ie,Ye),$n;try{$n=JSON.parse(Re)}catch{throw new cr("json-parse")}Pb(l,Kp($n)),Ge++}catch(Re){m("json",Re)}}),await eO(st,e.fileConcurrency,async(Ie)=>{if(Ie.size===0){J++;return}try{let{text:Re}=await nO(e,Ie,Ye);Pb(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"),Ns=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:!rIe(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:q,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:z.size,distinct_patient_field_values_in_flagged_files:B.size,findings_by_kind:Ake(l),edf_bdf_files_by_kind:L,unscreened_formats:d.unscreened,side_reads_failed:Ns,finding_fields:[...new Set(Ar.map((Ie)=>`${Ie.kind}:${Ie.field}`))].sort()}}gm();xn();Sp();tm();var $m="--acknowledge-identifier-preflight",XUt=16,QUt="local:";function T3(e){let t=[],n=new Map,r=0,o=[""];while(o.length>0){let s=o.pop(),i;try{i=JUt(s===""?e:iIe(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=`${QUt}${t.length}`,p=iIe(e,d),m=null;try{let h=aIe(p);if(h.isFile())m=h.size,n.set(f,p);else if(h.isDirectory()&&!KUt(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 ZUt(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 YUt(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 cIe(e,t){let n=T3(e),r=tIe({fileConcurrency:XUt,workerConcurrency:1,limits:{...eIe},readEntryHead:ZUt(n.readable,t),githubToken:async()=>null,readVersionManifest:async()=>{throw new cr("unreadable-entry")},sleep:async()=>{return}}),o=await sIe(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 Aq(FAe(MAe(s)))}function sO(e){if($f(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 lIe=(e,t)=>e.length===t.length&&e.every((n,r)=>n===t[r]);function uIe(e,t){let n=e.split(",").map((o)=>o.trim()).filter((o)=>o!==""),r=UA;if(n.length===0||!n.every((o)=>r.includes(o)))throw new jr(`Allowed verdicts are ${r.join(", ")}. Direct identifiers cannot be acknowledged.`);return[...t??[],...n]}function e3t(e,t){let n=$f(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 lIe(r,sO(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 t3t={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"},A3=(e)=>`${$m} ${e.join(",")}`;function O3(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}: ${t3t[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 dIe(){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 ${$m} does not apply. If this is a false positive, please report it, so the scanner is fixed for every dataset. Terms: ${W1}`))}function fIe(e){if(e instanceof jA)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 pIe(e,t){e.fail("Identifier preflight: DID NOT FINISH"),console.log(u.red(` The preflight could not produce a verdict, so nothing was uploaded (${fIe(t)}).`)),console.log(u.dim(" Please report this: https://github.com/nemarOrg/nemar-cli/issues"))}function oO(e,t,n=""){let r=Oq(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 il({state:t.status,...r},2).slice(1))console.log(s)}function mIe(e,t){try{return En(jAe({version:MA,scanner:`nemar-cli@${Vs}`,scan:e,acknowledged_via:t}))}catch(n){return console.log(u.red(` The preflight's record did not fit the report contract (${fIe(n)}), so nothing was uploaded.`)),Le}}async function hIe(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=aIe(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 cIe(e,i)}catch(p){return pIe(o,p),Le}oO(o,a);let c=sO(a),l=e3t(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 ${A3(c)}.`));else if(t.acknowledgeIdentifierPreflight!==void 0)console.log(u.dim(` Nothing to acknowledge; ${$m} was not needed.`));d=l.acknowledgedVia;break;case"preview":return O3(c),console.log(u.yellow(` A real upload stops here until you acknowledge it: answer the prompt, or pass ${A3(c)}.`)),console.log(),En(null);case"prompt":{O3(c);let p=!1,m=()=>{console.log(u.red(`
2623
2623
  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 dIe(),ue(),Le;case"stop":if(l.why==="acknowledgment-mismatch")console.log(u.red(` ${$m} must name exactly what was found, which is: ${c.join(",")}. It does not acknowledge this scan. Nothing was sent.`));else O3(c),console.log(u.red(l.why==="declined"?" Declined (--no). Nothing was sent.":` No terminal to ask at: run interactively, or pass ${A3(c)}. --yes does not acknowledge a finding. Nothing was sent.`));return ue(),Le}let f=mIe(a,d);if(f.status==="ok")console.log();return f}async function gIe(e,t){let n=C("Screening again, right before anything is sent...").start(),r;try{r=await cIe(e)}catch(a){return pIe(n,a),Le}let o=$f(r.status);if(o!=="clear"&&o!=="acknowledge")return oO(n,r),dIe(),ue(),Le;let s=sO(t.scan),i=sO(r);if(!lIe(s,i))return oO(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(LA(r.findings_by_kind)!==LA(t.scan.findings_by_kind))oO(n,r," (screened again)");else n.succeed(`${Oq(r,null).headline} (screened again)`);return mIe(r,t.acknowledged_via)}var h3t=/\.(edf|bdf)$/i,vIe=Da(".nemar","date-normalization"),g3t=()=>({tracked:0,"nested-repository":0,ignored:0,"tracking-unknown":0,link:0,"not-writable":0,"other-filesystem":0,unverified:0});function y3t(){return{items:[],left:g3t()}}function b3t(e){if(process.env.GIT_DIR||process.env.GIT_WORK_TREE)return!0;for(let t=e;;t=iO(t)){if(wIe(Da(t,".git")))return!0;if(iO(t)===t)return!1}}var N3=(e)=>e.normalize("NFC").toLowerCase();async function P3(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(N3))}catch{return null}}async function w3t(e,t){let n=`${t.join("\x00")}\x00`;if(b3t(e)){let o=await P3(["git","ls-files","-z"],e),s=await P3(["git","check-ignore","-z","--stdin"],e,n);return o&&s?{tracked:o,ignored:s}:null}let r=null;try{if(r=c3t(Da(m3t(),"nemar-ignore-")),(await O(["git","init","-q","--bare",r],{cwd:e})).exitCode!==0)return null;let s=await P3(["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{q3(r,{recursive:!0,force:!0})}catch{}}}function F3(e){let t;try{t=L3(e,"r")}catch{return null}try{let n=new Uint8Array(At),r=0;while(r<At){let o=l3t(t,n,r,At-r,r);if(o===0)break;r+=o}return r===At?n:null}catch{return null}finally{try{j3(t)}catch{}}}var yIe=(e,t)=>e!==null&&e.length===t.length&&e.every((n,r)=>n===t[r]);function bIe(e){try{return r3t(e,I3.W_OK),!0}catch{return!1}}function _3t(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=wIe(Da(e,s,".git"));try{i||=ll(Da(e,s,".git")).isSymbolicLink()}catch{}n.set(s,i)}if(i)return!0}return!1}async function EIe(e){let t=y3t();try{await x3t(e,t)}catch(n){Nn(`date normalization: planning stopped (${n instanceof Error?n.name:"unknown"})`)}return t}async function x3t(e,t){let n=xIe(e).dev,r=T3(e),o=[];for(let c of r.entries){if(!h3t.test(c.path))continue;let l=r.readable.get(c.url);if(l===void 0)continue;let d=F3(l);if(d===null)continue;try{let f=ML(d);if(f.changed)o.push({path:l,rel:c.path,before:d,after:f.header})}catch(f){if(f instanceof pf)continue;t.left.unverified++,Nn(`date normalization: a header was not planned (${f instanceof Error?f.name:"unknown"})`)}}if(o.length===0)return;let s=await w3t(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(N3(c.rel))){t.left.tracked++;continue}if(_3t(e,c.rel,i)){t.left["nested-repository"]++;continue}if(s.ignored.has(N3(c.rel))){t.left.ignored++;continue}let l;try{l=ll(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||!bIe(c.path)||!bIe(iO(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 v3t=/^\d+-[0-9a-f]{16}$/;function E3t(e){try{let t=Da(e,vIe);for(let n of[Da(e,".nemar"),t])if(!ll(n).isDirectory())return;for(let n of u3t(t))if(v3t.test(n))q3(Da(t,n),{force:!0})}catch{}}function M3(e){for(let t of e)try{f3t(t)}catch{}}function S3t(e,t){let n=[],r=Da(e,vIe);try{for(let o of[Da(e,".nemar"),r]){let s;try{s=ll(o)}catch{a3t(o),n.push(o),s=ll(o)}if(!s.isDirectory()||s.dev!==t)return M3([...n].reverse()),null}return{dir:r,made:n}}catch{return M3([...n].reverse()),null}}function k3t(e){try{let t=L3(e,"r");try{_Ie(t)}finally{j3(t)}}catch{}}function R3t(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(ll(e.path))||!yIe(F3(e.path),e.before))return null;if(n=Da(t,`${process.pid}-${n3t(8).toString("hex")}`),i3t(e.path,n,I3.COPYFILE_EXCL|I3.COPYFILE_FICLONE),ll(n).gid!==e.gid)s3t(n,-1,e.gid);o3t(n,e.mode&4095);let o=L3(n,"r+");try{if(p3t(o,e.after,0,At,0)!==At)return null;_Ie(o)}finally{j3(o)}if(ll(n).size!==e.size||!yIe(F3(n),e.after))return null;if(!r(ll(e.path)))return null;return d3t(n,e.path),n=null,k3t(iO(e.path)),ll(e.path).mtimeMs}catch(r){return Nn(`date normalization: a header was not set (${r instanceof Error?r.name:"unknown"})`),null}finally{if(n!==null)try{q3(n,{force:!0})}catch{}}}function SIe(e,t){let n={set:0,left:0,mtimes:new Map};if(E3t(e),t.items.length===0)return n;let r=null;try{r=S3t(e,xIe(e).dev)}catch{}if(r===null)return n.left=t.items.length,Nn("date normalization: no work directory, nothing set"),n;try{for(let o of t.items){let s=R3t(o,r.dir);if(s===null){n.left++;continue}n.set++,n.mtimes.set(o.rel,s)}}finally{M3([r.dir,...[...r.made].reverse().filter((o)=>o!==r.dir)])}if(n.set>0)console.log(u.dim(` ${PAe(n.set)}`));return n}We();yi();$o();import{existsSync as fv,mkdirSync as z3t,readFileSync as pv,writeFileSync as HIe}from"fs";import{basename as V3t,resolve as Dm}from"path";Dc();Ve();Yr();yi();import{existsSync as aO,readFileSync as U3,writeFileSync as RIe}from"fs";import{resolve as cO}from"path";var B3=[{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}],kIe=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 $Ie(e){let t=cO(e,"dataset_description.json");if(aO(t))try{let r=JSON.parse(U3(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=cO(e,r);if(aO(o)){try{let s=U3(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 H3(e){let t=B3.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?B3.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 DIe(e){let t=e.toUpperCase().replace(/\s+/g,"-");if(kIe.has(e))return!0;for(let n of kIe)if(n.toUpperCase()===t)return!0;return!1}function $3t(e){let t=B3.find((n)=>n.spdxId===e);if(t)return`${t.name}
2624
2624
 
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-dev.4706",
4
+ "version": "0.10.39-PR2296.1810c4a",
5
5
  "description": "CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",
6
6
  "type": "module",
7
7
  "main": "dist/index.js",