nemar-cli 0.10.24-dev.3968 → 0.10.24-dev.3986

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.
Files changed (2) hide show
  1. package/dist/index.js +2 -2
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -99,7 +99,7 @@ ${t}`,A4e,O4e,T4e=(e,t,r)=>{let n=r===""?"":`with ${r.trim()}() `,i=C4e.bind(nul
99
99
  `)}var QC=!1;var{spawn:met}=globalThis.Bun;function bu(e,t=[]){let r=e.replace(het,'("$1","<redacted>")');for(let n of t)if(n.length>=get)r=r.split(n).join("<redacted>");return r}function c_(e){let t=["AWS_SESSION_TOKEN","AWS_SECRET_ACCESS_KEY","AWS_ACCESS_KEY_ID"],r=new Set;for(let n of[process.env,e??{}])for(let i of t){let o=n[i];if(typeof o==="string"&&o.length>0)r.add(o)}return[...r]}async function gie(e,t){let r=e.getReader(),n=new TextDecoder,i="";while(!0){let{done:o,value:s}=await r.read();if(o)break;if(s.byteLength===0)continue;t(),i+=n.decode(s,{stream:!0})}return i+n.decode()}async function k(e,t={}){let r={...process.env,GIT_TERMINAL_PROMPT:"0",...t.env};for(let b of t.unsetEnv??[])delete r[b];let n=met({cmd:e,cwd:t.cwd,...t.stdin===void 0?{}:{stdin:new TextEncoder().encode(t.stdin)},stdout:"pipe",stderr:"pipe",env:r}),i=!1,o,s,a=performance.now(),c=()=>{if(s!==void 0)clearTimeout(s),s=void 0},u=()=>{if(!t.onInactivityWarning)return;c(),s=setTimeout(()=>{s=void 0;try{t.onInactivityWarning?.(performance.now()-a)}catch{console.error("Could not display subprocess inactivity warning; the child result is unaffected.")}},t.inactivityWarningAfterMs??yet)};if(u(),t.timeout)o=setTimeout(()=>{i=!0,c(),n.kill()},t.timeout);let d=a_()?[...c_(r),...t.redact??[]]:[];if(a_()){let b=t.cwd?` (cwd=${t.cwd})`:"";sl(l.dim(bu(`$ ${e.join(" ")}${b}`,d)))}let f=()=>{a=performance.now(),u()},p,m,h,g=n.exited.then((b)=>(c(),b));try{[p,m,h]=await Promise.all([gie(n.stdout,f),gie(n.stderr,f),g])}finally{if(c(),o)clearTimeout(o)}if(a_()){if(t.sensitiveOutput)sl(l.dim("[sensitive subprocess output suppressed]"));else{if(p.trim())sl(l.dim(bu(p.trimEnd(),d)));if(m.trim())sl(l.yellow(bu(m.trimEnd(),d)))}sl(l.dim(`(exit ${h})`))}if(i)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 het,get=8,yet=120000;var Bt=j(()=>{Me();het=/\(\s*"((?:x-amz-)[^"]*|authorization|proxy-authorization)"\s*,\s*"[^"]*"\s*\)/gi});function wet(){if(process.platform==="darwin")return"macos";if(process.platform==="win32")return"windows";return"linux"}function bie(e,t=wet()){return e.installInstructions[t]}function xet(e){let t=e.match(/(\d+\.\d+(?:\.\d+)?)/);return t?t[1]:void 0}function vet(){let e=Number(process.env.TEST_PROBE_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:_et}async function wie(e){try{let{exitCode:t,stdout:r,timedOut:n}=await k(e.cmd,{timeout:vet()});if(n)return{available:!1,timedOut:!0};if(t!==0)return{available:!1};return{available:!0,version:xet(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 ig(){let e=Object.entries(yie);return Promise.all(e.map(async([t,r])=>{let{available:n,version:i,timedOut:o}=await wie(r);return{key:t,name:r.name,purpose:r.purpose,required:r.required,available:n,version:i,timedOut:o,installInstruction:bie(r)}}))}async function xie(){let t=(await ig()).filter((r)=>r.required&&!r.available);if(t.length===0)return[];console.warn(`
100
100
  Heads up: some tools NEMAR needs for uploading/validating aren't installed yet:`);for(let r of t)console.warn(` - ${r.name} (${r.purpose})`),console.warn(` Install: ${r.installInstruction}`);return console.warn("Run `nemar doctor` anytime to re-check. You can finish signup without them.\n"),t}async function wu(e){let r=bet[e].map((s)=>yie[s]).filter(Boolean),n=await Promise.all(r.map(async(s)=>{let a=await wie(s);return{check:s,available:a.available,timedOut:a.timedOut}}));for(let s of n)if(s.timedOut&&s.check.required)console.warn(`Warning: ${s.check.name} did not respond to a version check in time; continuing anyway.`);let i=n.filter((s)=>!s.available&&!s.timedOut&&s.check.required).map((s)=>({tool:s.check.name,installInstruction:bie(s.check)}));if(i.length===0)return;let o=[`
101
101
  Missing required tools:`];for(let s of i)o.push(` ${s.tool} not installed`),o.push(` Install: ${s.installInstruction}`);throw Error(o.join(`
102
- `))}var yie,bet,_et=4000;var og=j(()=>{Bt();yie={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)"}}},bet={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 vie;var _ie=j(()=>{vie={name:"nemar-cli",packageManager:"bun@1.4.3",version:"0.10.24-dev.3968",description:"CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",type:"module",main:"dist/index.js",bin:{nemar:"dist/index.js"},scripts:{dev:"bun run src/index.ts",build:"bun build src/index.ts --outdir dist --target bun --minify && sed '1s|#!/usr/bin/env node|#!/usr/bin/env bun|' dist/index.js > dist/index.js.tmp && mv dist/index.js.tmp dist/index.js",test:"bun test",lint:"biome check src/","lint:scrub":"biome check scripts/scrub shared/identifier-scrub.ts test/scrub","test:scrub":"bun test --preload ./test/scrub/helpers/temp-dirs-preload.ts --path-ignore-patterns='__run_every_scrub_suite__' test/scrub test/identifier-scan.test.ts test/identifier-scrub.test.ts test/identifier-dates.test.ts test/identifier-fleet.test.ts","migrations:d1-check":"bun run scripts/d1-migration-check.ts","zarr:geometry-check":"bun run backend/scripts/zarr-geometry-conformance.ts","lint:fix":"biome check --fix src/",format:"biome format --write src/",typecheck:"tsc --noEmit && tsc --noEmit -p backend","generate-openapi":"bun run scripts/generate-openapi.ts",prepublishOnly:"bun run build",prepare:"husky",postinstall:"bun scripts/postinstall-check.mjs",deploy:"wrangler deploy",preview:"wrangler dev"},keywords:["nemar","bids","neuroimaging","eeg","emg","datalad","cli"],author:"NEMAR Team",license:"CC-BY-NC-ND-4.0",repository:{type:"git",url:"git+https://github.com/nemarOrg/nemar-cli.git"},bugs:{url:"https://github.com/nemarOrg/nemar-cli/issues"},homepage:"https://docs.nemar.org",engines:{bun:">=1.0.0"},files:["dist","scripts/postinstall-check.mjs","scripts/recover-datasets.json","scripts/withdrawn-datasets.json","README.md","LICENSE"],dependencies:{chalk:"^5.3.0",commander:"^12.1.0",conf:"^13.0.1",inquirer:"^9.2.15",ora:"^8.0.1",semver:"^7.8.5",zod:"^3.23.8"},"lint-staged":{"src/**/*.{ts,tsx}":["biome check --fix"],"backend/src/**/*.{ts,tsx}":["biome check --fix"]},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","lint-staged":"^16.3.2",typescript:"^5.5.4",wrangler:"^4.70.0",yaml:"^2.8.4"}}});var go;var up=j(()=>{_ie();go=vie.version});import{mkdirSync as Det,readdirSync as ket,unlinkSync as $et,writeFileSync as Ret}from"fs";import{join as ZC}from"path";function Rie(){dp=!0}function xu(){return dp}function Cie(e,t=process.env){return e.includes("--debug")||t.NEMAR_DEBUG==="1"}function ag(e){$ie=e,ir(`Step: ${e}`)}function Ds(){Sie=!0}function Aie(){return Sie}function Ee(){if(kie)return;t2=!0}function cg(){t2=!1,kie=!0}function Oie(){return t2}function ir(e){if(dp)process.stderr.write(`[debug] ${e}
102
+ `))}var yie,bet,_et=4000;var og=j(()=>{Bt();yie={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)"}}},bet={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 vie;var _ie=j(()=>{vie={name:"nemar-cli",packageManager:"bun@1.4.3",version:"0.10.24-dev.3986",description:"CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",type:"module",main:"dist/index.js",bin:{nemar:"dist/index.js"},scripts:{dev:"bun run src/index.ts",build:"bun build src/index.ts --outdir dist --target bun --minify && sed '1s|#!/usr/bin/env node|#!/usr/bin/env bun|' dist/index.js > dist/index.js.tmp && mv dist/index.js.tmp dist/index.js",test:"bun test",lint:"biome check src/","lint:scrub":"biome check scripts/scrub shared/identifier-scrub.ts test/scrub","test:scrub":"bun test --preload ./test/scrub/helpers/temp-dirs-preload.ts --path-ignore-patterns='__run_every_scrub_suite__' test/scrub test/identifier-scan.test.ts test/identifier-scrub.test.ts test/identifier-dates.test.ts test/identifier-fleet.test.ts","migrations:d1-check":"bun run scripts/d1-migration-check.ts","zarr:geometry-check":"bun run backend/scripts/zarr-geometry-conformance.ts","lint:fix":"biome check --fix src/",format:"biome format --write src/",typecheck:"tsc --noEmit && tsc --noEmit -p backend","generate-openapi":"bun run scripts/generate-openapi.ts",prepublishOnly:"bun run build",prepare:"husky",postinstall:"bun scripts/postinstall-check.mjs",deploy:"wrangler deploy",preview:"wrangler dev"},keywords:["nemar","bids","neuroimaging","eeg","emg","datalad","cli"],author:"NEMAR Team",license:"CC-BY-NC-ND-4.0",repository:{type:"git",url:"git+https://github.com/nemarOrg/nemar-cli.git"},bugs:{url:"https://github.com/nemarOrg/nemar-cli/issues"},homepage:"https://docs.nemar.org",engines:{bun:">=1.0.0"},files:["dist","scripts/postinstall-check.mjs","scripts/recover-datasets.json","scripts/withdrawn-datasets.json","README.md","LICENSE"],dependencies:{chalk:"^5.3.0",commander:"^12.1.0",conf:"^13.0.1",inquirer:"^9.2.15",ora:"^8.0.1",semver:"^7.8.5",zod:"^3.23.8"},"lint-staged":{"src/**/*.{ts,tsx}":["biome check --fix"],"backend/src/**/*.{ts,tsx}":["biome check --fix"]},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","lint-staged":"^16.3.2",typescript:"^5.5.4",wrangler:"^4.70.0",yaml:"^2.8.4"}}});var go;var up=j(()=>{_ie();go=vie.version});import{mkdirSync as Det,readdirSync as ket,unlinkSync as $et,writeFileSync as Ret}from"fs";import{join as ZC}from"path";function Rie(){dp=!0}function xu(){return dp}function Cie(e,t=process.env){return e.includes("--debug")||t.NEMAR_DEBUG==="1"}function ag(e){$ie=e,ir(`Step: ${e}`)}function Ds(){Sie=!0}function Aie(){return Sie}function Ee(){if(kie)return;t2=!0}function cg(){t2=!1,kie=!0}function Oie(){return t2}function ir(e){if(dp)process.stderr.write(`[debug] ${e}
103
103
  `)}function Tet(e){let t={};for(let[r,n]of Object.entries(e))t[r]=Oet.has(r.toLowerCase())?"[REDACTED]":n;return t}function Pie(e){let t=e.indexOf("@");if(t<=0)return"***";return`${e[0]}***${e.slice(t)}`}function e2(e,t,r=0){if(r>Iet)return"[REDACTED: depth]";if(Array.isArray(t))return t.map((n)=>e2(e,n,r+1));if(t&&typeof t==="object"){let n={};for(let[i,o]of Object.entries(t))n[i]=e2(i,o,r+1);return n}if(typeof t==="string"){if(Pet.test(e))return"[REDACTED]";return t.replace(Tie,Pie)}return t}function r2(e){return e.replace(Net,"Bearer [REDACTED]").replace(Fet,"[REDACTED_AWS_KEY]").replace(jet,"$1[REDACTED]").replace(Met,"$1$2=[REDACTED]").replace(Tie,Pie)}function qet(e){return r2(e)}function Eie(e,t=Aet){if(e===void 0)return;let r=e;try{let n=JSON.parse(e);r=JSON.stringify(e2("",n))}catch{}if(r=r2(r),Buffer.byteLength(r,"utf8")>t)r=`${Buffer.from(r,"utf8").subarray(0,t).toString("utf8")}... [truncated]`;return r}function d_(e){if(!dp)return;let t=qet(e.url);try{let r={...e,url:t,requestHeaders:e.requestHeaders?Tet(e.requestHeaders):void 0,requestBody:Eie(e.requestBody),responseBody:Eie(e.responseBody)};u_.push(r),ir(`${e.method} ${t} -> ${e.status??"ERROR"} (${e.durationMs}ms)`)}catch(r){let n=q(r);u_.push({method:e.method,url:t,status:e.status,durationMs:e.durationMs,note:`redaction failed: ${n}`}),ir(`redaction failed for ${e.method} ${t}: ${n}`)}}async function Let(){let e=[];try{let t=process.versions.bun?`Bun ${process.versions.bun}`:`Node ${process.version}`;e.push(`CLI version: ${go}`),e.push(`OS/Arch: ${process.platform}/${process.arch}`),e.push(`Runtime: ${t}`)}catch(t){e.push(`(could not read CLI/OS/runtime info: ${q(t)})`)}e.push(""),e.push("Active account:");try{let t=Mt();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: ${q(t)})`)}e.push(""),e.push("External tools:");try{let t=await ig();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: ${q(t)})`)}return e}async function n2(){return(await Let()).join(`
104
104
  `)}async function Iie(){if(!dp||l_!==void 0)return;try{l_=await n2()}catch(e){let t=q(e);l_=`(could not build environment report: ${t})`,ir(`environment snapshot failed: ${t}`)}}function Nie(e){if(Die.has(e))return{flag:e};for(let t of Die){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 Bet(e){let t=[];for(let r=0;r<e.length;r++){let n=e[r],i=Nie(n);if(!i){t.push(n);continue}if(i.kind==="long-eq")t.push(`${i.flag}=[REDACTED]`);else if(i.kind==="short-attached")t.push(`${i.flag}[REDACTED]`);else if(t.push(n),r+1<e.length)t.push("[REDACTED]"),r++}return t}function Uet(e){let t=[];for(let r=0;r<e.length;r++){let n=e[r],i=Nie(n);if(!i){t.push(n);continue}if(!i.kind&&r+1<e.length)r++}return t}function zet(e){let t=[];for(let n of Uet(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 Vet(e,t){let r=[];if(r.push("NEMAR CLI Debug Log"),r.push(`Generated: ${new Date().toISOString()}`),r.push(`Command: nemar ${r2(Bet(e).join(" "))}`),r.push(""),r.push(l_??"(environment snapshot unavailable)"),r.push(""),r.push("HTTP requests:"),u_.length===0)r.push(" (none)");else u_.forEach((n,i)=>{if(r.push(` [${i+1}] ${n.method} ${n.url} -> ${n.status??"ERROR"} (${n.durationMs}ms)`),n.error)r.push(` Error: ${n.error}`);if(n.note)r.push(` Note: ${n.note}`);if(n.requestHeaders)r.push(` Request headers: ${JSON.stringify(n.requestHeaders)}`);if(n.requestBody)r.push(` Request body: ${n.requestBody}`);if(n.responseBody)r.push(` Response body: ${n.responseBody}`)});return r.push(""),r.push(`Failing step: ${$ie??"(none recorded)"}`),r.push(`Exit code: ${t}`),`${r.join(`
105
105
  `)}
@@ -240,7 +240,7 @@ ${z.replace(/^/gm," ")}`}let I=" ".repeat(Math.max(0,W-A.length)),L=`${A}${I}
240
240
  `);if(d.push(l.bold("Commands:"),u(_(B)),""),F.length>0){let W=F.map((I)=>I.name()).join(", ");d.push(l.bold("More commands")+l.dim(" (--help-all for details):"),t.wrap(W,r-2,0).replace(/^/gm," "),"")}}else if(C.length>0)d.push(l.bold("Commands:"),u(_([...C].sort(x))),"");return d.join(`
241
241
  `)}};function FI(e){jI(e)}function jI(e){e.configureHelp(Kwe);for(let t of e.commands)jI(t)}function qr(e,t){if(jD)om.call(e,"after",t);else if(!U0.has(e))U0.add(e),om.call(e,"after",NI)}Me();Me();import{existsSync as IE,mkdirSync as xhe,mkdtempSync as TT,readFileSync as _mt,writeFileSync as v0}from"fs";import{tmpdir as PT}from"os";import{join as Pa}from"path";Ai();ln();function vV(e,t){return Math.min(Math.floor(Math.log(e)/Math.log(1024)),t)}function kt(e){if(e===0)return"0 B";let t=["B","KB","MB","GB","TB"],r=vV(e,t.length-1);return`${(e/1024**r).toFixed(r===0?0:1)} ${t[r]}`}function EV(e){if(e===0)return"0 B";let t=["B","KB","MB","GB","TB"],r=vV(e,t.length-1);return`${Number.parseFloat((e/1024**r).toFixed(2))} ${t[r]}`}bh();yf();var nw=50;var $H=["store","node","registration","drift"];function RH(e){let{verification:t,writerMode:r,now:n}=e;if(t===null)return r==="enabled"?{verdict:"unknown",note:"none recorded: the daily verification sweep has not run, which is unknown and not healthy"}:{verdict:"unchecked",note:null};let i=Date.parse(t.at),o=n.getTime()-i;if(Number.isNaN(i)||o>129600000){let s=Number.isNaN(i)?null:Math.floor(o/3600000);return{verdict:"unknown",note:s===null?"the last record has no readable time, so it says nothing about today":`the last record is ${s} hours old, so it says nothing about today`}}return{verdict:t.overall,note:null}}function V1(e){return e==="alarm"?1:e==="unknown"?2:0}var F8e=["store","node","registration","drift"];function j8e(e){return F8e.filter((t)=>e.checkDays[t].unchecked>0)}function H1(e){let t=[];if(e.coverageStatus==="alarm")t.push("coverage is alarming");if(e.coverageStatus==="unknown")t.push("coverage could not be determined");if(e.autoImportEnabled===!1)t.push("auto-import is OFF");if(e.dispatchLost===!0)t.push("dispatches are not landing");if(e.issuesClosed===null)t.push("no daily sweep activity was recorded, so the daily jobs may not be running");let r=e.neurobagel??null,n=[];if(r===null)t.push("no Neurobagel verification run was recorded, so that job may not be running");else{if(n=j8e(r),r.latest.overall==="alarm")t.push("Neurobagel verification is alarming");if(r.latest.overall==="unknown")t.push("Neurobagel verification could not be determined");if(r.days.alarm>0&&r.latest.overall!=="alarm")t.push(`Neurobagel verification alarmed on ${r.days.alarm} day(s) this week`);if(r.days.unknown>0&&r.latest.overall!=="unknown")t.push(`Neurobagel verification could not be determined on ${r.days.unknown} day(s)`);if(r.failedRuns>0)t.push(`the Neurobagel sweep itself failed on ${r.failedRuns} run(s)`);let i=Math.max(0,7-r.runs);if(i>1)t.push(`the daily Neurobagel verification is missing for ${i} of 7 day(s)`)}if(e.neurobagelFindings===null||e.neurobagelFindings===void 0)t.push("Neurobagel findings could not be counted");else if(e.neurobagelFindings>0)t.push(`${e.neurobagelFindings} Neurobagel finding(s) need attention (see the audit log)`);if(e.errors.length>0)t.push(`${e.errors.length} part(s) of this report failed`);return{attention:t.length>0,problems:t,notChecked:n}}Me();var bf=2000,yc=10,bc=500,wc=/^(nm|on|xx)\d{6}$/;Ot();yo();ui();Pr();function P(e){return typeof e==="string"?e.replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu,""):""}function cl(e,t){let r=P(e);return r.length>t?`${r.slice(0,t-1)}\u2026`:r}function pg(e,t=Date.now()){let r=Date.parse(e);if(Number.isNaN(r))return"?";let n=Math.max(0,Math.floor((t-r)/1000));if(n<3600)return`${Math.floor(n/60)}m`;if(n<86400)return`${Math.floor(n/3600)}h`;return`${Math.floor(n/86400)}d`}var p2={owner_name_missing:"Run `nemar admin backfill-names --apply` if the owner's ORCID record publishes their name; an ORCID-linked owner must otherwise make it public on ORCID and sign in again, and an owner with no linked ORCID can now type it into Settings on nemar.org (ADR 0042)."};function di(e){return e?(t)=>console.error(t):(t)=>console.log(t)}function wp(e){if(!(e instanceof M))return!1;if(e.statusCode>=400&&e.statusCode<500)return!0;let t=yp(e);return t!==void 0&&t!=="internal"}function f2(e,t,r,n){if(t)t.fail(e);else r(l.red(e));if(n)r(l.dim(` ${n}`))}function Zie(e,t,r,n,i){if(e instanceof M){let s=(e.blockReason?p2[e.blockReason]:void 0)??n?.[e.statusCode]??(e.statusCode===403?"This command requires admin privileges":void 0);f2(P(e.message),t,i,s);return}f2(r,t,i,`Error details: ${P(q(e))}`)}function gt(e,t,r,n){Zie(e,t,r,n,di(!1))}function Ir(e,t,r,n,i={}){if(Zie(e,t,r,n,di(i.json)),process.exitCode=1,wp(e))Ee();else cg()}function hn(e,t){if(f2(P(e),t.spinner,di(t.json),t.hint),process.exitCode=1,t.answered)Ee();else cg()}function Ss(e,t){if(wc.test(e))return e;return hn(`"${e}" is not a dataset id (like nm000108).`,{json:t,answered:!0}),null}function ltt(e){return/^[a-z]{2}\d{0,6}$/.test(e)}function utt(e){return/^(nm|on|xx)0\d{5}$/.test(e)}function eoe(e,t){if(ltt(e))return e;return hn(`"${e}" is not a dataset id prefix: use two lowercase letters, then up to six digits (like nm or nm0001).`,{json:t,answered:!0}),null}function toe(e,t){if(utt(e))return e;return hn(`"${e}" is not a dataset id (like nm000312). --after takes the last id of the previous page.`,{json:t,answered:!0}),null}function fi(e){if(Ze())return!0;let t=di(e);return t(l.red("Error: Not authenticated")),t(l.dim(" Run 'nemar auth login' first")),process.exitCode=1,Ee(),!1}Me();bh();Me();function xp(e){return(t)=>{try{return e(t)}catch{return String(t)}}}var gn={id:xp(l.cyan),metric:xp(l.magenta),label:xp(l.bold),warn:xp(l.yellow),muted:xp(l.dim),match:xp(l.green)};var dtt=/[\u001b\u009b][\[\]()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-PR-TZcf-ntqry=><~]/g,ftt=/[\n\r\t]+/g,ptt=/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/g;function Nr(e){return e.replace(dtt,"").replace(ftt," ").replace(ptt,"").trim()}var mtt=/(<mark>[\s\S]*?<\/mark>)/g,htt=/^<mark>([\s\S]*)<\/mark>$/,roe=400;function noe(e){if(!e||typeof e!=="string")return null;try{let t=e.length>roe?e.slice(0,roe):e,r=Nr(t);if(!r)return null;return r.split(mtt).filter((n)=>n.length>0).map((n)=>{let i=n.match(htt);return i?gn.match(i[1]):gn.muted(n)}).join("")}catch{return null}}function ioe(e,t){if(!Number.isFinite(t)||t<=0)return e;if(e.length<=t)return e;let r=e.split(","),n=[],i=0;for(let s of r){let a=n.length===0?s.length:i+1+s.length;if(a>t)break;n.push(s),i=a}let o=r.length-n.length;if(n.length===0){let s=r[0],a=Math.max(0,t-1),c=a>0?`${s.slice(0,a)}\u2026`:"\u2026",u=r.length-1;return u>0?`${c} +${u}`:c}return o>0?`${n.join(",")} +${o}`:n.join(",")}function Eu(e){return Nr(e??"")}function m2(e){let t=e.match_kind;return typeof t==="string"&&BV.includes(t)?t:void 0}function h2(e){let t=e.filter((r)=>m2(r)==="exact");return t.length===1?t[0]:null}function g2(e){return e.length>0&&e.every((t)=>m2(t)==="fuzzy")}function y2(e){return e.length===0||e.some((t)=>m2(t)!==void 0)}function ooe(e){if(e.length===0)return{kind:"none"};let t=h2(e);if(t)return{kind:"one",user:t,match:"exact"};let r=g2(e)?"fuzzy":"partial";if(e.length===1)return{kind:"one",user:e[0],match:r};return{kind:"many",users:[...e],match:r}}var b_=[["givenName","given_name"],["familyName","family_name"],["affiliation","affiliation"],["city","city"],["country","country"],["username","username"],["github","github_username"],["email","email"],["orcid","orcid"]];var y_=[{option:"clearAffiliation",valueOption:"affiliation",field:"affiliation"},{option:"clearGithub",valueOption:"github",field:"github_username"}];function ll(e){return`--${e.replace(/[A-Z]/g,(t)=>`-${t.toLowerCase()}`)}`}function soe(e){let t={};for(let[r,n]of b_){let i=e[r];if(typeof i!=="string")continue;if((n==="github_username"?i.trim().replace(/^@/,""):i.trim())===""){let s=y_.find((a)=>a.valueOption===r);return{ok:!1,message:s?`${ll(r)} needs a value. To remove it, say so with ${ll(s.option)}.`:`${ll(r)} needs a value.`}}t[n]=i}for(let{option:r,valueOption:n,field:i}of y_){if(e[r]!==!0)continue;if(i in t)return{ok:!1,message:`Use either ${ll(n)} or ${ll(r)}, not both.`};t[i]=""}return{ok:!0,body:t}}function aoe(e,t){let r=[];for(let[,n]of b_){let i=t[n];if(i===void 0)continue;let o=e[n]??null;if((o??"")===i){if(n==="orcid"&&!e.orcid_verified)r.push({field:n,from:`${i} (unverified)`,to:`${i} (verified, attested)`});continue}r.push({field:n,from:o,to:i})}return r}function pi(e,t="-"){let r=Eu(e);return r!==""?r:t}function mg(e){if(e===null)return l.dim("(none)");if(e==="")return l.dim("(cleared)");return pi(e,l.dim("(blank)"))}function vu(e){if(!e)return"-";let t=new Date(e.includes("T")?e:`${e.replace(" ","T")}Z`);return Number.isNaN(t.getTime())?Eu(e):t.toISOString().replace("T"," ").slice(0,16)}function b2(e){let t=(a)=>l.dim(`${a}:`.padEnd(15)),r=[e.given_name,e.family_name].filter(Boolean).join(" "),n=[e.city,e.country].filter(Boolean).join(", "),i=e.role||"member",o=e.service_access===void 0||e.service_access===null?"unknown":e.service_access?"upload":"browse",s=[];if(s.push(`${l.cyan(pi(e.username??e.email))}${l.dim(` [${Eu(i)}] id ${e.id}`)}${e.username===null?l.dim(" (no username)"):""}`),s.push(` ${t("Name")}${pi(r)}`),s.push(` ${t("Email")}${pi(e.email)} ${e.email_verified?l.green("(verified)"):l.yellow("(unverified)")}`),s.push(` ${t("GitHub")}${e.github_username?`@${pi(e.github_username)}`:"-"}`),s.push(` ${t("ORCID")}${e.orcid?`${pi(e.orcid)} ${e.orcid_verified?l.green("(verified)"):l.yellow("(unverified)")}`:"-"}`),s.push(` ${t("Affiliation")}${pi(e.affiliation)}`),s.push(` ${t("Location")}${pi(n)}`),s.push(` ${t("Status")}${Eu(e.status)}`),s.push(` ${t("Upload access")}${o}${e.service_access&&e.service_access_granted_at?l.dim(` (granted ${vu(e.service_access_granted_at)}${e.service_access_granted_by?` by id ${e.service_access_granted_by}`:""})`):""}`),e.upload_access_requested_at)s.push(` ${t("Asked")}${vu(e.upload_access_requested_at)} (upload access)`);if(s.push(` ${t("Kind")}${Eu(e.account_kind)||"-"}`),s.push(` ${t("Signed up via")}${pi(e.signup_source)}`),s.push(` ${t("Created")}${vu(e.created_at)}`),e.approved_at)s.push(` ${t("Approved")}${vu(e.approved_at)}`);if(e.revoked_at)s.push(` ${t("Revoked")}${vu(e.revoked_at)}`);if(s.push(` ${t("Last changed")}${vu(e.updated_at)}`),s.push(` ${t("Datasets")}${e.dataset_count??"-"}${l.dim(" API keys: ")}${e.active_tokens??"-"}`),s.push(` ${t("Sign-in")}${e.linked_identities&&e.linked_identities.length>0?e.linked_identities.map((a)=>Eu(a)).join(", "):"-"}`),e.description)s.push(` ${t("Description")}${pi(e.description)}`);if(e.identity_conflict)s.push(` ${l.yellow("! Flagged as a duplicate identity: see 'nemar admin duplicates'")}`);if(e.username_auto_assigned)s.push(` ${l.dim("The username was derived from the name, not chosen")}`);if(e.deleted_at)s.push(` ${l.red(`Deleted ${vu(e.deleted_at)} (tombstoned)`)}`);return s}function w2(e){let t=[e.given_name,e.family_name].filter(Boolean).join(" "),r=e.matched_in&&e.matched_in.length>0?l.dim(` matched: ${e.matched_in.map((n)=>Eu(n)).join(", ")}`):"";return` ${String(e.id).padStart(5)} ${l.cyan(pi(e.username,"(no username)"))} ${pi(t,"")} ${l.dim(pi(e.email))}${r}`}ul();ba();fl();Ot();ga();var j2=["critical","warning","maintenance","announcement","tip"];async function Hse(){return N("/notices",{},"optional")}async function Gse(){return N("/admin/notices",{},!0)}async function Wse(e){return N("/admin/notices",{method:"POST",body:JSON.stringify(e)},!0)}async function Kse(e){return N(`/admin/notices/${e}`,{method:"DELETE"},!0)}ui();Ai();async function $e(e,t,r=!1){if(t.no)return"declined";if(t.yes)return"confirmed";if(!process.stdin.isTTY)return console.error("Interactive prompt unavailable; use --yes or --no"),"cancelled";try{let{confirmed:n}=await De.prompt([{type:"confirm",name:"confirmed",message:e,default:r}]);return n?"confirmed":"cancelled"}catch(n){let i=n instanceof Error?n.message:String(n);if(i.includes("closed")||i.includes("TTY")||i.includes("SIGINT")||i.includes("readline"))console.error("Interactive prompt unavailable (non-interactive terminal or interrupted)"),console.error(" Use --yes or --no flags for non-interactive mode");else console.error("Prompt error:",i);return"cancelled"}}async function Yse(e,t,r){if(r.no)return"declined";if(r.yes)return"confirmed";if(!process.stdin.isTTY)return console.error("Interactive prompt unavailable; use --yes or --no"),"cancelled";try{let{input:n}=await De.prompt([{type:"input",name:"input",message:e,validate:(i)=>{if(i!==t)return`Input does not match. Expected: ${t}`;return!0}}]);return n===t?"confirmed":"cancelled"}catch(n){let i=n instanceof Error?n.message:String(n);if(i.includes("closed")||i.includes("TTY")||i.includes("SIGINT")||i.includes("readline"))console.error("Interactive prompt unavailable (non-interactive terminal or interrupted)"),console.error(" Use --yes or --no flags for non-interactive mode");else console.error("Prompt error:",i);return"cancelled"}}var Le="-y, --yes",nt="-n, --no",He="Skip confirmation and proceed",tt="Skip confirmation and decline";Pr();var Jse="__Host-nemar_docs_session";yf();ga();Ot();async function M2(e){return N("/auth/login",{method:"POST",body:JSON.stringify({api_key:e})})}async function Xse(e){return N("/auth/resend-verification",{method:"POST",body:JSON.stringify({email:e})})}async function Qse(e){return N("/auth/request-key-regeneration",{method:"POST",body:JSON.stringify({email:e})})}async function Pn(){return(await N("/users/me",{},!0,NV)).user}async function Zse(e){return N("/sandbox/complete",{method:"POST",body:JSON.stringify({dataset_id:e})},!0)}async function eae(){return N("/sandbox/reset",{method:"POST"},!0)}async function R_(){return N("/sandbox/status",{},!0)}async function tae(e){return N("/users/me/upload-access/request",{method:"POST",body:JSON.stringify({why:e})},!0)}async function rae(e){return N("/auth/email/change/request",{method:"POST",body:JSON.stringify({email:e})},!0)}async function nae(e,t){return N("/auth/email/change/verify",{method:"POST",body:JSON.stringify({email:e,code:t})},!0)}async function q2(e){return N("/auth/profile",{method:"PATCH",body:JSON.stringify(e)},!0)}async function iae(e){return N("/auth/orcid/cli-start",{method:"POST",body:JSON.stringify({mode:e})},!0)}async function oae(){return N("/auth/orcid/unlink",{method:"POST"},!0)}async function sae(e){return N("/auth/device/start",{method:"POST",body:JSON.stringify({machine_name:e})},!1,cH)}function gtt(e){return typeof e==="string"&&Hb.options.includes(e)}function ytt(e){if(typeof e!=="object"||e===null)return;let t=e.message;return typeof t==="string"?t:void 0}async function aae(e,t){try{return{status:"success",data:await N("/auth/device/token",{method:"POST",body:JSON.stringify({device_code:e}),signal:t},!1,uH)}}catch(r){if(r instanceof M&&r.statusCode===400){let n=lH.safeParse(r.rawBody);if(n.success){let i=n.data;if(i.error==="authorization_pending")return{status:"pending"};if(i.error==="slow_down")return{status:"slow_down"};return{status:"terminal",error:i.error,reason:i.reason,message:i.message}}if(gtt(r.code)&&r.code!=="authorization_pending"&&r.code!=="slow_down")return{status:"terminal",error:r.code,reason:void 0,message:ytt(r.rawBody)??sH[r.code]}}throw r}}async function cae(){return N("/auth/keys",{},!0,Gb)}async function lae(e){return N("/auth/keys",{method:"POST",body:JSON.stringify({name:e})},!0,Wb)}async function uae(){return N("/auth/docs/cli-session",{method:"POST"},!0)}async function C_(e){return N(`/auth/keys/${e}`,{method:"DELETE"},!0)}async function dae(e,t){return N(`/auth/keys/${e}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`}},!1)}async function fae(){return N("/auth/profile/username-suggestion",{},!0,jV)}var btt="https://docs.nemar.org";function A_(){return process.env.NEMAR_DOCS_URL||btt}var pae=20000;function wtt(e){let t=e.trim();if(/^https?:\/\//i.test(t)){let n=new URL(t),i=new URL(A_()).hostname;if(n.hostname.toLowerCase()!==i.toLowerCase())throw Error(`Not a ${i} URL: ${e}`);t=n.pathname}if(t=t.replace(/[?#].*$/,""),!t.startsWith("/"))t=`/${t}`;if(t.length>1&&t.endsWith("/"))t=t.slice(0,-1);if(t===""||t==="/")return"/index.md";return t.slice(t.lastIndexOf("/")+1).includes(".")?t:`${t}.md`}function xtt(e,t){if(e===302||e===301||e===307||e===308){if(t?.includes("/auth/docs/authorize"))return"the documentation session was refused (it may have expired mid-run); try again";return`redirected to ${t??"an unknown location"}`}if(e===404)return"not found, or it is a gated page and this account is not an admin";if(e===401)return"the documentation session was rejected; it may have expired, try again";if(e===403)return"this account is no longer an admin, so the documentation session was refused";if(e===503)return"the documentation gate could not reach the API; try again shortly";return`unexpected status ${e}`}async function mae(e){let t=e.map((s)=>{try{return{input:s,path:wtt(s)}}catch(a){return{input:s,error:a.message}}});if(!t.some((s)=>s.path))return t.map((s)=>({path:s.input,ok:!1,error:s.error??"not a usable documentation path"}));let r=await uae();if(typeof r?.session!=="string"||r.session.length===0)throw Error("The API returned no documentation session value.");let n=A_().replace(/\/$/,""),i=`${Jse}=${r.session}`,o=[];for(let s of t){if(!s.path){o.push({path:s.input,ok:!1,error:s.error??"unusable path"});continue}let a=s.path;try{let c=await fetch(`${n}${a}`,{redirect:"manual",signal:AbortSignal.timeout(pae),headers:{Cookie:i,"User-Agent":"nemar-cli"}});if(c.status===200){o.push({path:a,ok:!0,body:await c.text()});continue}o.push({path:a,ok:!1,error:xtt(c.status,c.headers.get("Location"))})}catch(c){let u=c.name;o.push({path:a,ok:!1,error:u==="TimeoutError"?`no response within ${pae/1000}s`:c.message})}}return o}O_();zi();Rs();Bt();var cv=ze(av(),1);function rot(e,t){let r=cv.default.coerce(e),n=cv.default.coerce(t);if(!r||!n)return!1;return cv.default.gte(r,n)}async function Lle(){try{let{stdout:t,exitCode:r,stderr:n}=await k(["git-annex","version"]);if(r!==0)return console.warn("git-annex version returned non-zero exit code:",r),console.warn("stderr:",n),{installed:!1,minVersion:"10.0",error:`Version check failed: ${n.trim()}`};let i=t.match(/version:\s*(\d+\.\d+)/),o=i?i[1]:void 0;if(!o)console.warn("Could not parse git-annex version from output:",t);return{installed:!0,version:o,minVersion:"10.0",compatible:o?rot(o,"10.0"):void 0}}catch(t){let r=t instanceof Error?t.message:String(t);if(r.includes("ENOENT")||r.includes("not found"))return console.info("git-annex not found in PATH"),{installed:!1,minVersion:"10.0"};return console.error("Error checking git-annex installation:",r),{installed:!1,minVersion:"10.0",error:r}}}async function not(){if(process.env.GH_TOKEN)return{accessible:!0,username:"token-auth",useHttps:!0};try{let{stdout:e,stderr:t}=await k(["ssh","-T","-o","BatchMode=yes","-o","StrictHostKeyChecking=accept-new","-o","ConnectTimeout=10","git@github.com"]),r=e+t,n=r.match(/Hi ([^!]+)!/);if(n)return{accessible:!0,username:n[1]};if(r.includes("Permission denied"))return{accessible:!1};return{accessible:r.includes("successfully authenticated")}}catch(e){let t=e instanceof Error?e.message:String(e);if(t.includes("ENOENT")||t.includes("not found"))console.info("SSH command not found");else console.error("Error checking GitHub SSH access:",t);return{accessible:!1}}}function Ble(){let e=process.platform;if(e==="darwin")return"brew install git-annex";if(e==="linux")return"apt install git-annex (Debian/Ubuntu)";return"See https://git-annex.branchable.com/install/"}async function lv(){let[e,t]=await Promise.all([Lle(),not()]),r=[];if(!e.installed)r.push(`git-annex is not installed. Install: ${Ble()}`);else if(e.compatible===!1)r.push(`git-annex version ${e.version} is too old. Required: >= ${e.minVersion}`);if(!t.accessible){if(!(await Su()).token)r.push("GitHub authentication not configured. Run 'gh auth login' to authenticate.")}return{gitAnnex:e,githubSSH:t,allPassed:r.length===0,errors:r}}async function Rg(){let e=await Lle(),t=[];if(!e.installed)t.push(`git-annex is not installed. Install: ${Ble()}`);else if(e.compatible===!1)t.push(`git-annex version ${e.version} is too old. Required: >= ${e.minVersion}`);return{gitAnnex:e,allPassed:t.length===0,errors:t}}Sp();import{readFileSync as iot}from"fs";var oot=/^on\d{6}$/;function sot(e){if(!Array.isArray(e))throw Error("Recover-datasets file must be a JSON array");return e.map((t,r)=>{if(typeof t!=="object"||t===null)throw Error(`Recover-datasets entry ${r} is not an object`);let{dataset_id:n,note:i}=t;if(typeof n!=="string"||!oot.test(n))throw Error(`Recover-datasets entry ${r}: dataset_id "${n}" is not valid`);if(typeof i!=="string"||i.length===0)throw Error(`Recover-datasets entry ${r} (${n}): note is required`);return{dataset_id:n,note:i}})}function hA(e){let t;try{t=JSON.parse(iot(e,"utf-8"))}catch(r){throw Error(`Failed to read/parse recover-datasets file at ${e}: ${r instanceof Error?r.message:String(r)}`)}return sot(t)}function Ule(e,t,r){let n=new Set(t.map((i)=>i.dataset_id));for(let i of e)if(!n.has(i)&&!r.force)return{error:`${i} is not on the checked-in recover-datasets list. Pass --force to override.`};return{targets:e}}function zle(e,t){let r=new Set(e),n=new Map;for(let o of t)if(r.has(o.dataset_id)&&o.source_id)n.set(o.dataset_id,o.source_id);let i=e.filter((o)=>!n.has(o));return{sourceByTarget:n,missingSource:i}}import{readFileSync as aot}from"fs";var Vle=new Set(["upstream_403","no_source","recovered"]),cot=/^(nm|xx|on)\d{6}$/;function lot(e){if(!Array.isArray(e))throw Error("Withdrawn-datasets file must be a JSON array");return e.map((t,r)=>{if(typeof t!=="object"||t===null)throw Error(`Withdrawn-datasets entry ${r} is not an object`);let{dataset_id:n,reason:i,note:o,withdrawn:s,data_available:a,data_keys_missing:c,data_keys_total:u}=t;if(typeof n!=="string"||!cot.test(n))throw Error(`Withdrawn-datasets entry ${r}: dataset_id "${n}" is not valid`);if(typeof i!=="string"||!Vle.has(i))throw Error(`Withdrawn-datasets entry ${r} (${n}): reason "${i}" must be one of ${[...Vle].join(", ")}`);if(typeof o!=="string"||o.length===0)throw Error(`Withdrawn-datasets entry ${r} (${n}): note is required`);if(s!==void 0&&typeof s!=="boolean")throw Error(`Withdrawn-datasets entry ${r} (${n}): withdrawn must be a boolean`);if(a!==void 0&&(typeof a!=="number"||a<0||a>1))throw Error(`Withdrawn-datasets entry ${r} (${n}): data_available must be between 0 and 1`);let d=s??!0;if(i==="recovered"&&d)throw Error(`Withdrawn-datasets entry ${r} (${n}): reason "recovered" means the content came back, so withdrawn must be false`);let f=typeof c==="number",p=typeof u==="number";if(f!==p)throw Error(`Withdrawn-datasets entry ${r} (${n}): data_keys_missing and data_keys_total must be given together`);if(f&&p){if(c<0||u<0)throw Error(`Withdrawn-datasets entry ${r} (${n}): key counts cannot be negative`);if(c>u)throw Error(`Withdrawn-datasets entry ${r} (${n}): ${c} missing of ${u} total is not possible`);if(typeof a==="number"&&u>0){let m=(u-c)/u;if(Math.abs(m-a)>0.001)throw Error(`Withdrawn-datasets entry ${r} (${n}): data_available ${a} disagrees with ${c} missing of ${u} (${m.toFixed(4)})`)}}return{dataset_id:n,reason:i,note:o,withdrawn:d,...typeof a==="number"?{data_available:a}:{},...f?{data_keys_missing:c}:{},...p?{data_keys_total:u}:{}}})}function gA(e){let t;try{t=JSON.parse(aot(e,"utf-8"))}catch(r){throw Error(`Failed to read/parse withdrawn-datasets file at ${e}: ${r instanceof Error?r.message:String(r)}`)}return lot(t)}function Hle(e,t,r){let n=new Map(t.map((o)=>[o.dataset_id,o])),i=[];for(let o of e){let s=n.get(o);if(!s&&!r.force)return{error:`${o} is not on the checked-in withdrawn-datasets list. Pass --force to override.`};if(s?.withdrawn===!1&&!r.force)return{error:`${o} was reinstated (${s.reason}); its entry is a record, not a target. Pass --force to withdraw it again.`};let a=r.reason||s?.reason;if(!a)return{error:`${o}: no --reason given and it has no default entry in the list.`};i.push({datasetId:o,reason:a})}return{targets:i}}function yA(e){return e.filter((t)=>t.withdrawn!==!1)}import{readFileSync as uot}from"fs";var bA=["open","pending","escalated","closed","spam"],Cg=["open","pending","closed","spam"],wA=["fixed","round_robin","pool"];ul();Ot();ui();Pr();Du();function dot(e){let t=e.indexOf("--");return(t===-1?e:e.slice(0,t)).includes("--json")}class jr extends ve{createCommand(e){return new jr(e)}error(e){let t=e.replace(/^error: /,"").trim();if(dot(process.argv))console.error(JSON.stringify({error:t,code:"usage"}));else console.error(`Error: ${_e(t)}`);Ds(),process.exit(Xle)}}var xA=1,Xle=2,fot=3,pot=4;class Wt extends Error{}var Gle={bad_request:"The server rejected the request as malformed; check the arguments and try again.",not_found:"There is no such ticket, or it is not visible to you.",forbidden:"Your account is not permitted to do that (an owner-only action, or an account that is not active).",ineligible_assignee:"That person cannot take it: on a restricted queue everyone named must be an owner, on any other an admin or an owner.",ticket_is_spam:"The ticket is marked spam; reopen it with 'status <id> open' before changing it.",ticket_closed:"The ticket is closed; reopen it with 'status <id> open' before changing it.",already_escalated:"The ticket is already escalated; nothing more to do.",no_escalation_owner:"The queue has no escalation owner; an owner sets one with 'queues set <tag> --escalation <user>'.",escalation_owner_ineligible:"The queue's escalation owner cannot take this ticket; an owner should name another with 'queues set <tag> --escalation <user>'.",restricted_locked:"The ticket is in a restricted queue, which locks this change; ask an owner.",restricted_flag_busy:"The queue still has open tickets, so its restricted flag cannot change: close or move them first.",restriction_mismatch:"The ticket's restricted flag no longer matches its queue, so it cannot be reopened; ask an owner.",reply_in_progress:"A reply with this key is still being sent; wait a moment and retry with the same key.",fallback_not_restrictable:"The '*' fallback queue is never restricted.",reply_not_sent:"Nothing was sent and the key is released; retry with the same key if you still want to reply.",summary_has_address:"The summary contains an email address. Rewrite it without names, addresses, account ids or quoted message text: describe the request and the outcome.",ticket_purged:"The ticket was purged under the retention policy; only its summary remains and nothing can be changed.",reply_delivery_unknown:"The mail provider did not confirm the send, so the reply may or may not have reached the requester. This key will never send it again, so retrying it is pointless: read the thread with 'nemar admin mail show', and ask the requester if needed. Only a new --idempotency-key sends again, and it may deliver a second copy.",inbound_not_configured:"This deployment has no inbound mail bucket, so there is nothing to reprocess.",internal:"The mail routes failed unexpectedly; try again, and report it if it keeps happening."};function Qle(e){let t=e.rawBody;if(t&&typeof t==="object"&&"code"in t&&typeof t.code==="string")return t.code;return}function mot(e){return e!==void 0&&Object.hasOwn(Gle,e)?Gle[e]:void 0}function Zle(e,t="reply"){if(t==="note")return e.statusCode===0||e.statusCode>=500||e.statusCode===408||e.statusCode===429;let r=Qle(e);if(r==="reply_delivery_unknown")return!1;return r==="reply_in_progress"||r==="reply_not_sent"||e.statusCode===0||e.statusCode>=500}function hot(e,t,r){return Zle(e,r)?`Retry with: --idempotency-key ${t} (the same key never ${r==="note"?"stores the note":"sends the reply"} twice)`:void 0}function got(e,t,r="reply"){if(e instanceof Wt)return{message:e.message,code:"usage",exit:Xle,answered:!0};if(e instanceof M){let n=Qle(e),i=n==="not_found"||e.statusCode===404,o=n==="forbidden"||e.statusCode===403,s=mot(n),a=t?hot(e,t,r):void 0,c=[s,a].filter(Boolean).join(" ")||void 0;return{message:e.message,code:n??(e.statusCode===0?"network_error":`http_${e.statusCode}`),exit:i?fot:o?pot:xA,hint:c,retryWithKey:t!==void 0&&Zle(e,r),answered:e.statusCode>=400&&e.statusCode<500}}return{message:q(e),code:"error",exit:xA,answered:!1}}async function Zn(e,t,r,n="reply"){if(!Ze()){Wle(e,{message:"Not authenticated. Run 'nemar auth login' first.",code:"not_authenticated",exit:xA,answered:!0});return}try{await t()}catch(i){Wle(e,got(i,r?.(),n),r?.())}}function Wle(e,t,r){if(e){let n={error:t.message,code:t.code};if(r&&(t.retryWithKey||t.code==="reply_delivery_unknown"))n.idempotency_key=r;console.error(JSON.stringify(n))}else if(console.error(`Error: ${_e(t.message)}`),t.hint)console.error(` ${t.hint}`);if(process.exitCode=t.exit,t.answered)Ee();else cg()}function _e(e){return yg(String(e??"")).replace(/\n/g,"\\n").replace(/\t/g,"\\t")}function ei(e){console.log(JSON.stringify(e,null,2))}function Kle(e,t=" "){return e.split(`
242
242
  `).map((r)=>r===""?r:`${t}${r}`).join(`
243
- `)}function yot(e,t){return e.length>=t?e:e+" ".repeat(t-e.length)}var bot=/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/;class xo{names=new Map;ids=new Map;me;async resolve(e,t,r=!1){if(e==="none"){if(r)return null;throw new Wt(`${t} cannot be 'none' here.`)}if(e==="me")return this.whoAmI();let n=e.startsWith("@");if(!n&&/^\d{1,12}$/.test(e))return Number(e);let i=n?e.slice(1):e;if(!bot.test(i))throw new Wt(`${t}: '${_e(e)}' is not me${r?", none":""}, a user id, a username or @username.`);let o=this.ids.get(i);if(o!==void 0)return o;let{user:s}=await __(i);if(typeof s.id!=="number")throw new M(500,`The user lookup for '${_e(e)}' did not return an id.`);if(this.ids.set(i,s.id),s.username)this.names.set(s.id,Promise.resolve(s.username));return s.id}async whoAmI(){if(this.me===void 0){let e=await Pn();if(this.me=e.id,e.username)this.names.set(e.id,Promise.resolve(e.username))}return this.me}async name(e){if(e===null||e===void 0)return"-";let t=this.names.get(e);if(!t)t=Cse(e).then((r)=>r||`#${e}`,(r)=>{if(r instanceof M&&r.statusCode===404)return`#${e}`;throw r}),this.names.set(e,t);return _e(await t)}async list(e){let t=await Promise.all(e.map((r)=>this.name(r)));return t.length>0?t.join(", "):"-"}}function wot(e,t){return`#${e.id} ${_e(e.ref)} ${_e(e.status)}${e.purged?" (purged)":""} ${_e(e.queue_tag)}${e.restricted?" (restricted)":""} assignee ${t} ${_e(e.subject)}`}async function vA(e,t,r){console.log(`${e}: ${wot(t,await r.name(t.assignee_user_id))}`)}async function xot(e,t){if(e.length===0){console.log("No tickets.");return}let r=[];for(let s of e)r.push([`#${s.id}`,_e(s.ref),s.purged?`${_e(s.status)} (purged)`:_e(s.status),`${_e(s.queue_tag)}${s.restricted?"*":""}`,await t.name(s.assignee_user_id),_e(s.last_message_at),_e(s.requester_email),_e(s.subject)]);let n=["ID","REF","STATUS","QUEUE","ASSIGNEE","LAST MESSAGE","FROM","SUBJECT"],i=n.map((s,a)=>Math.max(s.length,...r.map((c)=>c[a].length))),o=(s)=>s.map((a,c)=>c===s.length-1?a:yot(a,i[c])).join(" ").trimEnd();console.log(o(n));for(let s of r)console.log(o(s));console.log(`
243
+ `)}function yot(e,t){return e.length>=t?e:e+" ".repeat(t-e.length)}var bot=/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/;class xo{names=new Map;ids=new Map;me;async resolve(e,t,r=!1){if(e==="none"){if(r)return null;throw new Wt(`${t} cannot be 'none' here.`)}if(e==="me")return this.whoAmI();let n=e.startsWith("@");if(!n&&/^\d{1,12}$/.test(e))return Number(e);let i=n?e.slice(1):e;if(!bot.test(i))throw new Wt(`${t}: '${_e(e)}' is not me${r?", none":""}, a user id, a username or @username.`);let o=this.ids.get(i);if(o!==void 0)return o;let{user:s}=await __(i);if(typeof s.id!=="number")throw new M(500,`The user lookup for '${_e(e)}' did not return an id.`);if(this.ids.set(i,s.id),s.username)this.names.set(s.id,Promise.resolve(s.username));return s.id}async whoAmI(){if(this.me===void 0){let e=await Pn();if(this.me=e.id,e.username)this.names.set(e.id,Promise.resolve(e.username))}return this.me}async name(e){if(e===null||e===void 0)return"-";let t=this.names.get(e);if(!t)t=Cse(e).then((r)=>r||`#${e}`,(r)=>{if(r instanceof M&&r.statusCode===404)return`#${e}`;throw r}),this.names.set(e,t);return _e(await t)}async list(e){let t=await Promise.all(e.map((r)=>this.name(r)));return t.length>0?t.join(", "):"-"}}function wot(e,t){return`#${e.id} ${_e(e.ref)} ${_e(e.status)}${e.purged?" (purged)":""} ${_e(e.queue_tag)}${e.restricted?" (restricted)":""} assignee ${t} ${_e(e.subject)}`}async function vA(e,t,r){console.log(`${e}: ${wot(t,await r.name(t.assignee_user_id))}`)}async function xot(e,t){if(e.length===0){console.log("No tickets.");return}let r=[];for(let s of e)r.push([s.unread?"new":"",`#${s.id}`,_e(s.ref),s.purged?`${_e(s.status)} (purged)`:_e(s.status),`${_e(s.queue_tag)}${s.restricted?"*":""}`,await t.name(s.assignee_user_id),_e(s.last_message_at),_e(s.requester_email),_e(s.subject)]);let n=["NEW","ID","REF","STATUS","QUEUE","ASSIGNEE","LAST MESSAGE","FROM","SUBJECT"],i=n.map((s,a)=>Math.max(s.length,...r.map((c)=>c[a].length))),o=(s)=>s.map((a,c)=>c===s.length-1?a:yot(a,i[c])).join(" ").trimEnd();console.log(o(n));for(let s of r)console.log(o(s));console.log(`
244
244
  * restricted queue`)}async function _ot(e,t){let r=[],n=e.ticket;r.push(`Ticket #${n.id} ${_e(n.ref)}`),r.push(`Subject: ${_e(n.subject)}`),r.push(`Status: ${_e(n.status)}`),r.push(`Queue: ${_e(n.queue_tag)}${n.restricted?" (restricted)":""}`),r.push(`Assignee: ${await t.name(n.assignee_user_id)}`);let i=n.requester_user_id===null?_e(n.requester_email):`${_e(n.requester_email)} (account ${await t.name(n.requester_user_id)})`;if(r.push(`Requester: ${i}`),r.push(`Tags: ${e.tags.length>0?e.tags.map(_e).join(", "):"-"}`),r.push(`Created: ${_e(n.created_at)}`),r.push(`Updated: ${_e(n.updated_at)}`),e.purged_at)r.push(`Purged on: ${_e(e.purged_at)} (retention: only the summary is kept)`);if(e.summary!==null&&e.summary!==void 0){let a=await t.name(e.summary_author_user_id);r.push(`
245
245
  Summary (by ${a}, ${_e(e.summarized_at??"unknown time")})`),r.push(Kle(yg(e.summary)))}else r.push(`
246
246
  Summary: (none)`);r.push(`
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.24-dev.3968",
4
+ "version": "0.10.24-dev.3986",
5
5
  "description": "CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",
6
6
  "type": "module",
7
7
  "main": "dist/index.js",