nemar-cli 0.10.1-PR1328.1794b86 → 0.10.1-PR1328.6df7fdc

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}`,DDe,EDe,SDe=(e,t,r)=>{let n=r===""?"":`with ${r.trim()}() `,i=wDe.bind(nul
99
99
  `)}var Jw=!1;var{spawn:O9e}=globalThis.Bun;async function k(e,t={}){let r={...process.env,GIT_TERMINAL_PROMPT:"0",...t.env};for(let u of t.unsetEnv??[])delete r[u];let n=O9e({cmd:e,cwd:t.cwd,stdout:"pipe",stderr:"pipe",env:r}),i=!1,o;if(t.timeout)o=setTimeout(()=>{i=!0,n.kill()},t.timeout);if(Xw()){let u=t.cwd?` (cwd=${t.cwd})`:"";Zd(l.dim(`$ ${e.join(" ")}${u}`))}let s=await new Response(n.stdout).text(),a=await new Response(n.stderr).text(),c=await n.exited;if(o)clearTimeout(o);if(Xw()){if(s.trim())Zd(l.dim(s.trimEnd()));if(a.trim())Zd(l.yellow(a.trimEnd()));Zd(l.dim(`(exit ${c})`))}if(i)return{stdout:s,stderr:a||`Command timed out after ${Math.round(t.timeout/1000)}s`,exitCode:c??1,timedOut:!0};return{stdout:s,stderr:a,exitCode:c,timedOut:!1}}var or=F(()=>{We()});function F9e(){if(process.platform==="darwin")return"macos";if(process.platform==="win32")return"windows";return"linux"}function wW(e,t=F9e()){return e.installInstructions[t]}function P9e(e){let t=e.match(/(\d+\.\d+(?:\.\d+)?)/);return t?t[1]:void 0}function T9e(){let e=Number(process.env.TEST_PROBE_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:I9e}async function DW(e){try{let{exitCode:t,stdout:r,timedOut:n}=await k(e.cmd,{timeout:T9e()});if(n)return{available:!1,timedOut:!0};if(t!==0)return{available:!1};return{available:!0,version:P9e(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 ef(){let e=Object.entries(vW);return Promise.all(e.map(async([t,r])=>{let{available:n,version:i,timedOut:o}=await DW(r);return{key:t,name:r.name,purpose:r.purpose,required:r.required,available:n,version:i,timedOut:o,installInstruction:wW(r)}}))}async function EW(){let t=(await ef()).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 oa(e){let r=A9e[e].map((s)=>vW[s]).filter(Boolean),n=await Promise.all(r.map(async(s)=>{let a=await DW(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:wW(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 vW,A9e,I9e=4000;var tf=F(()=>{or();vW={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)"}}},A9e={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 $W;var SW=F(()=>{$W={name:"nemar-cli",version:"0.10.1-PR1328.1794b86",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/","migrations:d1-check":"bun run scripts/d1-migration-check.ts","lint:fix":"biome check --fix src/",format:"biome format --write src/",typecheck:"tsc --noEmit && tsc --noEmit -p backend","generate-openapi":"bun run scripts/generate-openapi.ts",prepublishOnly:"bun run build",prepare:"husky",postinstall:"bun scripts/postinstall-check.mjs",deploy:"wrangler deploy",preview:"wrangler dev"},keywords:["nemar","bids","neuroimaging","eeg","emg","datalad","cli"],author:"NEMAR Team",license:"CC-BY-NC-ND-4.0",repository:{type:"git",url:"git+https://github.com/nemarOrg/nemar-cli.git"},bugs:{url:"https://github.com/nemarOrg/nemar-cli/issues"},homepage:"https://docs.nemar.org",engines:{bun:">=1.0.0"},files:["dist","scripts/postinstall-check.mjs","scripts/recover-datasets.json","scripts/withdrawn-datasets.json","README.md","LICENSE"],dependencies:{chalk:"^5.3.0",commander:"^12.1.0",conf:"^13.0.1",inquirer:"^9.2.15",ora:"^8.0.1",semver:"^7.8.5",zod:"^3.23.8"},"lint-staged":{"src/**/*.{ts,tsx}":["biome check --fix"],"backend/src/**/*.{ts,tsx}":["biome check --fix"]},devDependencies:{"@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",bcryptjs:"^3.0.3",husky:"^9.1.7","lint-staged":"^16.3.2",typescript:"^5.5.4",wrangler:"^4.70.0",yaml:"^2.8.4"}}});var oo;var rf=F(()=>{SW();oo=$W.version});import{mkdirSync as q9e,readdirSync as j9e,unlinkSync as M9e,writeFileSync as L9e}from"fs";import{join as Qw}from"path";function AW(){el=!0}function sa(){return el}function FW(e,t=process.env){return e.includes("--debug")||t.NEMAR_DEBUG==="1"}function of(e){OW=e,br(`Step: ${e}`)}function PW(){kW=!0}function IW(){return kW}function br(e){if(el)process.stderr.write(`[debug] ${e}
102
+ `))}var vW,A9e,I9e=4000;var tf=F(()=>{or();vW={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)"}}},A9e={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 $W;var SW=F(()=>{$W={name:"nemar-cli",version:"0.10.1-PR1328.6df7fdc",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/","migrations:d1-check":"bun run scripts/d1-migration-check.ts","lint:fix":"biome check --fix src/",format:"biome format --write src/",typecheck:"tsc --noEmit && tsc --noEmit -p backend","generate-openapi":"bun run scripts/generate-openapi.ts",prepublishOnly:"bun run build",prepare:"husky",postinstall:"bun scripts/postinstall-check.mjs",deploy:"wrangler deploy",preview:"wrangler dev"},keywords:["nemar","bids","neuroimaging","eeg","emg","datalad","cli"],author:"NEMAR Team",license:"CC-BY-NC-ND-4.0",repository:{type:"git",url:"git+https://github.com/nemarOrg/nemar-cli.git"},bugs:{url:"https://github.com/nemarOrg/nemar-cli/issues"},homepage:"https://docs.nemar.org",engines:{bun:">=1.0.0"},files:["dist","scripts/postinstall-check.mjs","scripts/recover-datasets.json","scripts/withdrawn-datasets.json","README.md","LICENSE"],dependencies:{chalk:"^5.3.0",commander:"^12.1.0",conf:"^13.0.1",inquirer:"^9.2.15",ora:"^8.0.1",semver:"^7.8.5",zod:"^3.23.8"},"lint-staged":{"src/**/*.{ts,tsx}":["biome check --fix"],"backend/src/**/*.{ts,tsx}":["biome check --fix"]},devDependencies:{"@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",bcryptjs:"^3.0.3",husky:"^9.1.7","lint-staged":"^16.3.2",typescript:"^5.5.4",wrangler:"^4.70.0",yaml:"^2.8.4"}}});var oo;var rf=F(()=>{SW();oo=$W.version});import{mkdirSync as q9e,readdirSync as j9e,unlinkSync as M9e,writeFileSync as L9e}from"fs";import{join as Qw}from"path";function AW(){el=!0}function sa(){return el}function FW(e,t=process.env){return e.includes("--debug")||t.NEMAR_DEBUG==="1"}function of(e){OW=e,br(`Step: ${e}`)}function PW(){kW=!0}function IW(){return kW}function br(e){if(el)process.stderr.write(`[debug] ${e}
103
103
  `)}function G9e(e){let t={};for(let[r,n]of Object.entries(e))t[r]=V9e.has(r.toLowerCase())?"[REDACTED]":n;return t}function NW(e){let t=e.indexOf("@");if(t<=0)return"***";return`${e[0]}***${e.slice(t)}`}function Zw(e,t,r=0){if(r>H9e)return"[REDACTED: depth]";if(Array.isArray(t))return t.map((n)=>Zw(e,n,r+1));if(t&&typeof t==="object"){let n={};for(let[i,o]of Object.entries(t))n[i]=Zw(i,o,r+1);return n}if(typeof t==="string"){if(z9e.test(e))return"[REDACTED]";return t.replace(TW,NW)}return t}function eD(e){return e.replace(W9e,"Bearer [REDACTED]").replace(K9e,"[REDACTED_AWS_KEY]").replace(Y9e,"$1[REDACTED]").replace(J9e,"$1$2=[REDACTED]").replace(TW,NW)}function X9e(e){return eD(e)}function CW(e,t=U9e){if(e===void 0)return;let r=e;try{let n=JSON.parse(e);r=JSON.stringify(Zw("",n))}catch{}if(r=eD(r),Buffer.byteLength(r,"utf8")>t)r=`${Buffer.from(r,"utf8").subarray(0,t).toString("utf8")}... [truncated]`;return r}function N0(e){if(!el)return;let t=X9e(e.url);try{let r={...e,url:t,requestHeaders:e.requestHeaders?G9e(e.requestHeaders):void 0,requestBody:CW(e.requestBody),responseBody:CW(e.responseBody)};T0.push(r),br(`${e.method} ${t} -> ${e.status??"ERROR"} (${e.durationMs}ms)`)}catch(r){let n=I(r);T0.push({method:e.method,url:t,status:e.status,durationMs:e.durationMs,note:`redaction failed: ${n}`}),br(`redaction failed for ${e.method} ${t}: ${n}`)}}async function Q9e(){let e=[];try{let t=process.versions.bun?`Bun ${process.versions.bun}`:`Node ${process.version}`;e.push(`CLI version: ${oo}`),e.push(`OS/Arch: ${process.platform}/${process.arch}`),e.push(`Runtime: ${t}`)}catch(t){e.push(`(could not read CLI/OS/runtime info: ${I(t)})`)}e.push(""),e.push("Active account:");try{let t=Ze();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: ${I(t)})`)}e.push(""),e.push("External tools:");try{let t=await ef();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: ${I(t)})`)}return e}async function tD(){return(await Q9e()).join(`
104
104
  `)}async function qW(){if(!el||I0!==void 0)return;try{I0=await tD()}catch(e){let t=I(e);I0=`(could not build environment report: ${t})`,br(`environment snapshot failed: ${t}`)}}function jW(e){if(RW.has(e))return{flag:e};for(let t of RW){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 Z9e(e){let t=[];for(let r=0;r<e.length;r++){let n=e[r],i=jW(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 eje(e){let t=[];for(let r=0;r<e.length;r++){let n=e[r],i=jW(n);if(!i){t.push(n);continue}if(!i.kind&&r+1<e.length)r++}return t}function tje(e){let t=[];for(let n of eje(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 rje(e,t){let r=[];if(r.push("NEMAR CLI Debug Log"),r.push(`Generated: ${new Date().toISOString()}`),r.push(`Command: nemar ${eD(Z9e(e).join(" "))}`),r.push(""),r.push(I0??"(environment snapshot unavailable)"),r.push(""),r.push("HTTP requests:"),T0.length===0)r.push(" (none)");else T0.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: ${OW??"(none recorded)"}`),r.push(`Exit code: ${t}`),`${r.join(`
105
105
  `)}
@@ -496,7 +496,7 @@ ${i} finding(s). Preview the remediation with: nemar admin doctor fix <check> --
496
496
  ${l.bold(e)}: ${l.green(`${s.fixed} fixed`)}, ${s.skipped} skipped, ${s.failed>0?l.red(`${s.failed} failed`):"0 failed"}${c}`)}if(s.failed>0)process.exit(1)});async function BUe(e,t,r){let n={fixed:0,skipped:0,failed:0,resolved:0},i=[];for(let[o,s]of e.entries()){let a;try{let c=await t(s,o);if(a=c.results,a.length===0)n.resolved++;else n.fixed+=c.fixed,n.skipped+=c.skipped,n.failed+=c.failed}catch(c){n.failed++,a=[{dataset_id:s,status:"failed",message:I(c)}]}i.push(...a),r?.onDataset?.(s,a)}return{totals:n,results:i}}Ig.command("kinds").description("Check that operational accounts carry their expected account kind (read-only)").action(async()=>{if(!Z())return;let e=Object.entries(K5),t=w(`Checking ${e.length} operational account kind(s)...`).start(),r=[],n=[];try{for(let[i,o]of e)try{let{user:s}=await nK(i);if(s.account_kind!==o)r.push(`${i}: expected '${o}', found '${s.account_kind??"unknown"}'`)}catch(s){if(s instanceof q&&s.statusCode===404)n.push(i);else throw s}if(t.stop(),r.length===0&&n.length===0){console.log(l.green(`All ${e.length} operational account(s) carry their expected kind.`));return}for(let i of r)console.log(` ${l.yellow("kind mismatch")} ${i}`);for(let i of n)console.log(` ${l.yellow("account absent")} ${i}`);console.log(l.yellow(`
497
497
  ${r.length+n.length} finding(s). Fix a mismatch with \`nemar admin kind <username> <kind>\`.`))}catch(i){t.fail("Doctor kinds check failed"),console.error(l.red(I(i))),process.exit(1)}});pe.addCommand(Ig);var D2=new ae("email-preferences").description("Manage email notification preferences");D2.command("show").description("Show email notification preferences").option("--user <username>","(owner only) show another user's preferences").action(async(e)=>{if(!Pe())console.error(l.red("Not authenticated. Run: nemar auth login")),process.exit(1);let t=w("Fetching email preferences...").start();try{let r=await NK(e.user),n=r.username?`${r.username}'s`:"Your";t.succeed(`${n} email notification preferences:`),console.log();let i=[{key:"user_approval",label:"User approval notifications"},{key:"publication_request",label:"Publication request notifications"},{key:"announcements",label:"Announcement emails"}];for(let o of i){let a=r[o.key]?l.green("enabled"):l.dim("disabled");console.log(` ${o.label.padEnd(40)} ${a}`)}console.log(),console.log(l.dim(" Use 'nemar admin email-preferences update' to change settings."))}catch(r){t.fail("Failed to fetch preferences"),console.error(l.red(I(r)))}});D2.command("update").description("Update email notification preferences").option("--user-approval <bool>","Enable/disable user approval notifications").option("--publication-request <bool>","Enable/disable publication request notifications").option("--announcements <bool>","Enable/disable announcement emails").option("--all <bool>","Enable/disable all notifications").option("--user <username>","(owner only) update another user's preferences").action(async(e)=>{if(!Pe())console.error(l.red("Not authenticated. Run: nemar auth login")),process.exit(1);function t(i){if(i===void 0)return;let o=i.toLowerCase();if(o==="true"||o==="1"||o==="on"||o==="yes")return!0;if(o==="false"||o==="0"||o==="off"||o==="no")return!1;console.error(l.red(`Invalid boolean value: "${i}". Use true/false, on/off, yes/no.`)),process.exit(1)}let r={};if(e.all!==void 0){let i=t(e.all);r.user_approval=i,r.publication_request=i,r.announcements=i}else{let i=t(e.userApproval),o=t(e.publicationRequest),s=t(e.announcements);if(i===void 0&&o===void 0&&s===void 0)console.error(l.red("No preferences specified.")),console.log(" --user-approval <bool> User approval notifications"),console.log(" --publication-request <bool> Publication request notifications"),console.log(" --announcements <bool> Announcement emails"),console.log(" --all <bool> All notifications"),process.exit(1);if(i!==void 0)r.user_approval=i;if(o!==void 0)r.publication_request=o;if(s!==void 0)r.announcements=s}let n=w("Updating email preferences...").start();try{let i=await qK(r,e.user),o=i.username?`${i.username}'s`:"Your";n.succeed(`${o} email preferences updated:`),console.log(),console.log(` User approval: ${i.user_approval?l.green("enabled"):l.dim("disabled")}`),console.log(` Publication request: ${i.publication_request?l.green("enabled"):l.dim("disabled")}`),console.log(` Announcements: ${i.announcements?l.green("enabled"):l.dim("disabled")}`)}catch(i){n.fail("Failed to update preferences"),console.error(l.red(I(i)))}});pe.addCommand(D2);var Tg=new ae("notice").description("Manage system notices displayed to CLI users");Tg.command("list").description("List all notices (including expired)").action(async()=>{if(!Pe())console.error(l.red("Not authenticated. Run: nemar auth login")),process.exit(1);let e=w("Fetching notices...").start();try{let{notices:t}=await cY();if(t.length===0){e.succeed("No notices found.");return}e.succeed(`${t.length} notice(s):`),console.log();for(let r of t){let i={critical:l.red.bold,warning:l.yellow,maintenance:l.magenta,announcement:l.green,tip:l.blue,info:l.blue}[r.level]||l.white,o=r.expires_at&&new Date(r.expires_at)<new Date?l.dim(" (expired)"):"";if(console.log(` ${l.dim(`#${r.id}`)} ${i(`[${r.level.toUpperCase()}]`)} ${l.dim(`scope:${r.scope}`)}${o}`),console.log(` ${r.message}`),console.log(` ${l.dim(`Created: ${r.created_at}`)}`),r.expires_at)console.log(` ${l.dim(`Expires: ${r.expires_at}`)}`);console.log()}}catch(t){ze(t,e,"Failed to fetch notices")}});Tg.command("set").description("Create a new system notice").requiredOption("-m, --message <text>","Notice message text").option("-l, --level <level>","Notice level: tip, announcement, maintenance, warning, critical","tip").option("-s, --scope <scope>","Target scope: all, admins, members","all").option("-e, --expires <datetime>","Expiry datetime (ISO 8601)").action(async(e)=>{if(!Pe())console.error(l.red("Not authenticated. Run: nemar auth login")),process.exit(1);if(![...vD,"info"].includes(e.level))console.error(l.red(`Invalid level: ${e.level}. Use ${vD.join(", ")}.`)),process.exit(1);if(!["all","admins","members"].includes(e.scope))console.error(l.red(`Invalid scope: ${e.scope}. Use all, admins, or members.`)),process.exit(1);let t=w("Creating notice...").start();try{let r=await lY({message:e.message,level:e.level,scope:e.scope,expires_at:e.expires});if(t.succeed(`Notice created (ID: ${r.id})`),console.log(` Level: ${r.level}`),console.log(` Scope: ${r.scope}`),console.log(` Message: ${r.message}`),r.expires_at)console.log(` Expires: ${r.expires_at}`)}catch(r){ze(r,t,"Failed to create notice")}});Tg.command("clear <id>").description("Delete a notice by ID").option($e,Ce).option(Ue,Ie).action(async(e,t)=>{if(!Pe())console.error(l.red("Not authenticated. Run: nemar auth login")),process.exit(1);let r=Number.parseInt(e,10);if(Number.isNaN(r))console.error(l.red("Invalid notice ID")),process.exit(1);if(!await Se(`Delete notice #${r}?`,t,!1))return;let i=w("Deleting notice...").start();try{await uY(r),i.succeed(`Notice #${r} deleted`)}catch(o){ze(o,i,"Failed to delete notice")}});pe.addCommand(Tg);pe.command("notify").description("Send an email to a group or a single user").option("--to <group>","Recipient group: all, admins, members").option("--user <username>","Send to a single user by username").requiredOption("--subject <text>","Email subject line").option("--body <text>","Email body (markdown)").option("--body-file <path>","Read email body from file (markdown)").option("--dry-run","Preview recipients without sending").option($e,Ce).option(Ue,Ie).action(async(e)=>{if(!Pe())console.error(l.red("Not authenticated. Run: nemar auth login")),process.exit(1);if(e.to&&e.user)console.error(l.red("--to and --user are mutually exclusive. Provide exactly one.")),process.exit(1);if(!e.to&&!e.user)console.error(l.red("Provide either --to <group> or --user <username>.")),process.exit(1);if(e.to&&!["all","admins","members"].includes(e.to))console.error(l.red(`Invalid group: ${e.to}. Use all, admins, or members.`)),process.exit(1);let t;if(e.bodyFile){if(!kg(e.bodyFile))console.error(l.red(`File not found: ${e.bodyFile}`)),process.exit(1);t=OUe(e.bodyFile,"utf-8")}else if(e.body)t=e.body;else console.error(l.red("Email body required. Use --body or --body-file.")),process.exit(1);let r=e.user?`user:${e.user}`:e.to,n=e.user?{user:e.user,subject:e.subject,body:t}:{to:e.to,subject:e.subject,body:t};if(e.dryRun){let a=w("Checking recipients...").start();try{let c=await gD({...n,dry_run:!0});if("dry_run"in c){a.succeed(`Dry run: ${c.recipient_count} recipient(s) for "${c.recipient_group}"`),console.log();for(let u of c.recipients)console.log(` ${u}`)}}catch(c){ze(c,a,"Failed to check recipients")}return}console.log(l.bold("Email preview:")),console.log(` To: ${l.cyan(r)}`),console.log(` Subject: ${e.subject}`),console.log(` Body: ${t.length>100?`${t.substring(0,100)}...`:t}`),console.log();let i=e.user?`Send this email to ${e.user}?`:"Send this broadcast email?";if(!await Se(i,e,!1))return;let s=w(e.user?`Sending to ${e.user}...`:"Sending broadcast...").start();try{let a=await gD(n);if("broadcast_id"in a)if(a.failure_count>0){s.warn(`Email send: ${a.recipient_count} delivered, ${a.failure_count} failed`);for(let c of a.failed_recipients)console.log(l.red(` Failed: ${c}`))}else{let c=e.user?`Email sent to ${e.user}`:`Broadcast sent to ${a.recipient_count} recipient(s)`;s.succeed(`${c} (ID: ${a.broadcast_id})`)}}catch(a){ze(a,s,"Failed to send email")}});var UUe=1500;function VUe(e){switch(e.kind){case"ok":return l.green(`ok ${e.schema_version}`);case"stale":return l.yellow(`stale ${e.schema_version}`);case"missing":return l.red("missing");case"error":return l.red(`error ${e.status||"?"}: ${e.message}`)}}function GUe(e){return e.kind==="stale"||e.kind==="missing"}function zUe(e){let r=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${r}$`)}var eZ=new ae("summary").description("summary.json coverage across published dataset versions");eZ.command("check").description("Report which (dataset_id, version) pairs have stale or missing summary.json").option("--fix","Dispatch generate-manifest for every stale/missing version").option("--id <id>","Limit to a single dataset_id (exact match)").option("--match <glob>","Limit to dataset_ids matching a glob pattern: `*` matches any run of chars, `?` matches one char. Examples: `on*`, `nm00010?`, `*99999`. Can be combined with --id (id wins if both passed).").option("--only-stale","Print only rows that are not ok (suppresses ok rows)").option("--json","Emit the full report as JSON instead of a table").option($e,Ce).option(Ue,Ie).action(async(e)=>{if(!Z())return;let t=w("Building coverage report...").start(),r;try{r=await jK()}catch(m){ze(m,t,"Failed to fetch coverage report");return}t.succeed(`Coverage: target=schema ${r.target_schema}, versions=${r.totals.versions}`);let n=r.versions,i=null;if(e.id){if(n=n.filter((m)=>m.dataset_id===e.id),i=`dataset_id=${e.id}`,n.length===0){console.log(l.yellow(`No rows for ${i}`));return}}else if(e.match){let m=zUe(e.match);if(n=n.filter((p)=>m.test(p.dataset_id)),i=`--match ${e.match}`,n.length===0){console.log(l.yellow(`No rows match ${i}`));return}console.log(l.dim(`Scoped to ${n.length} version(s) matching ${e.match}`))}if(e.json){console.log(JSON.stringify(i?{...r,versions:n,totals:LQ(n)}:r,null,2));return}let o=e.onlyStale?n.filter((m)=>m.state.kind!=="ok"):n;if(o.length===0)console.log(l.green("All versions at target schema \u2014 no drift."));else{let m=Math.max(...o.map((g)=>g.dataset_id.length),10),p=Math.max(...o.map((g)=>g.version.length),7);for(let g of o)console.log(` ${g.dataset_id.padEnd(m)} ${g.version.padEnd(p)} ${VUe(g.state)}`)}let s=i?LQ(n):r.totals;if(console.log(),console.log(` Total: ${s.versions} ${l.green(`ok=${s.ok}`)} ${l.yellow(`stale=${s.stale}`)} ${l.red(`missing=${s.missing}`)} ${l.red(`error=${s.error}`)}`),!e.fix){if(s.stale+s.missing>0)console.log(l.dim(`
498
498
  Run with --fix to dispatch generate-manifest for the ${s.stale+s.missing} drifted version(s).`));return}let a=n.filter((m)=>GUe(m.state));if(a.length===0){console.log(l.green(`
499
- Nothing to dispatch.`));return}let c=i?` (scoped to ${i})`:"",u=await Se(`Dispatch generate-manifest for ${a.length} version(s)${c}? Each dispatch queues a runner job on nemarDatasets/.github.`,e);if(u!=="confirmed"){console.log(l.dim(u==="declined"?"Skipped":"Cancelled"));return}let d=0,f=0;console.log();for(let[m,p]of a.entries()){let g=`${p.dataset_id}@${p.version}`,y=w(`[${m+1}/${a.length}] dispatching ${g}...`).start();try{await MK(p.dataset_id,p.version),y.succeed(`[${m+1}/${a.length}] dispatched ${g}`),d++}catch(x){y.fail(`[${m+1}/${a.length}] ${g}: ${I(x)}`),f++}if(m<a.length-1)await new Promise((x)=>setTimeout(x,UUe))}if(console.log(),console.log(f===0?l.green(`All ${d} dispatches succeeded.`):l.yellow(`${d} succeeded, ${f} failed.`)),console.log(l.dim("Workflow runs will appear on https://github.com/nemarDatasets/.github/actions. Re-run `nemar admin summary check` once they complete to verify drift cleared.")),f>0)process.exitCode=1});function LQ(e){return{versions:e.length,ok:e.filter((t)=>t.state.kind==="ok").length,stale:e.filter((t)=>t.state.kind==="stale").length,missing:e.filter((t)=>t.state.kind==="missing").length,error:e.filter((t)=>t.state.kind==="error").length}}pe.addCommand(eZ);var tZ=new ae("zarr-catalog").description("Top-level Zarr discovery catalog (zarr-catalog.json)");tZ.command("publish").description("Rebuild and republish zarr-catalog.json to this environment's bucket").action(async()=>{if(!Z())return;let e=w("Publishing zarr-catalog.json...").start();try{let t=await LK();e.succeed(`Published zarr-catalog.json: ${t.count} dataset(s), ${t.bytes} bytes`)}catch(t){ze(t,e,"Failed to publish zarr catalog"),process.exit(1)}});pe.addCommand(tZ);var rZ=new ae("backfill-names").description("Fill missing researcher names from users' public ORCID records (dry run by default)");rZ.option("--apply","Write the names (without this flag, only report what would change)").option("--limit <n>","Users per batch (server clamps to [1,100])","25").option("--json","Output raw JSON instead of the human summary").action(async(e)=>{if(!Z())return;let t=Number.parseInt(e.limit??"25",10)||25,r=e.apply===!0,n=w(r?"Backfilling names from ORCID...":"Checking ORCID for missing names...").start(),i;try{i=await VK({apply:r,limit:t}),n.stop()}catch(o){n.fail("Name backfill failed"),console.error(l.red(I(o))),process.exit(1);return}if(i.lookup_failed>0||(i.write_failed??0)>0||i.remaining===null)process.exitCode=1;if(e.json){console.log(JSON.stringify(i,null,2));return}if(console.log(),!i.apply)console.log(l.yellow("DRY RUN \u2014 nothing was written. Re-run with --apply."));console.log(l.cyan(`scanned=${i.scanned} ${i.apply?"filled":"would_fill"}=${i.apply?i.filled:i.would_fill} no_public_name=${i.no_public_name} lookup_failed=${i.lookup_failed} write_failed=${i.write_failed??0} remaining=${i.remaining??"unknown"}`));for(let o of i.results){let s=o.username??`id ${o.id} <${o.email}>`;if(o.outcome==="filled"||o.outcome==="would_fill"){let a=o.outcome==="filled"?l.green("filled "):l.cyan("would fill");console.log(` ${a} ${s}: ${o.given_name} ${o.family_name} (${o.orcid})`)}else if(o.outcome==="no_public_name")console.log(` ${l.yellow("no name ")} ${s}: ORCID ${o.orcid} does not publish a full name`);else if(o.outcome==="write_failed")console.log(` ${l.red("write ")} ${s}: ${o.error}; retry the batch`);else console.log(` ${l.red("error ")} ${s}: ${o.error}`)}if(i.warning)console.log(l.yellow(` Warning: ${i.warning}`));if(i.no_public_name>0)console.log(),console.log(l.dim("These accounts must make their name public on their ORCID record and sign in again; NEMAR cannot type a name in for an ORCID-linked account, because the record is re-read on every sign-in and would overwrite it. An account with no verified ORCID can set its name in Settings (ADR 0042)."))});pe.addCommand(rZ);function HUe(e){return typeof e==="object"&&e!==null&&Array.isArray(e.errors)}var nZ=new ae("import-issue-triage").description("Close recovered import-failure issues and retire stale cause labels (dry run by default)");nZ.option("--apply","Perform the changes (without this flag, only report what would change)").option("--limit <n>","Issues per batch (server clamps to [1,30])","15").option("--json","Output raw JSON instead of the human summary").action(async(e)=>{if(!Z())return;let t=e.limit??"15",r=Number.parseInt(t,10);if(!Number.isInteger(r)||r<1){console.error(l.red(`Invalid --limit ${JSON.stringify(t)}: expected an integer >= 1.`)),process.exitCode=1;return}let n=e.apply===!0,i=w(n?"Triaging import-failure issues...":"Checking import-failure issues...").start(),o;try{o=await UK({apply:n,limit:r}),i.stop()}catch(s){i.fail("Import-failure issue triage failed"),console.error(l.red(I(s)));let a=s instanceof q?s.details:void 0,c=HUe(a)?a.errors:[];if(e.json)console.log(JSON.stringify(s instanceof q?s.rawBody??{errors:c}:{errors:c},null,2));else for(let u of c)console.error(`${l.red("ERROR".padEnd(15))} #${u.issue} ${u.dataset_id??""} ${u.stage}: ${u.error}`);process.exitCode=1;return}if(o.errors.length>0)process.exitCode=1;if(e.json){console.log(JSON.stringify(o,null,2));return}if(console.log(),!o.applied)console.log(l.yellow("DRY RUN \u2014 nothing was written. Re-run with --apply."));for(let s of o.plan){let a=s.failed?"FAILED ":o.applied?"":"WOULD ",c=`#${s.issueNumber} ${s.datasetId??"(unknown)"}`;if(s.kind==="close"){let u=`${a}CLOSE`.padEnd(15);console.log(`${s.failed?l.red(u):l.green(u)} ${c} ${l.dim(s.reason)}`)}else if(s.kind==="relabel"){let u=`${a}RELABEL`.padEnd(15);console.log(`${s.failed?l.red(u):l.yellow(u)} ${c} ${l.dim(s.reason)}`)}else console.log(`${l.dim("KEEP".padEnd(15))} ${c} ${l.dim(s.reason)}`)}for(let s of o.rollups){let a=o.mode==="per-dataset"?o.applied?"RELEASE":"WOULD RELEASE":"ROLLUP";console.log(`${l.magenta(a.padEnd(15))} #${s.number} ${l.dim(s.title)}`)}for(let s of o.errors)console.log(`${l.red("ERROR".padEnd(15))} #${s.issue} ${s.dataset_id??""} ${s.stage}: ${s.error}`);if(console.log(),console.log(l.cyan(`open=${o.openIssues} mode=${o.mode} examined=${o.examined} attempted=${o.attempted} ${o.applied?"closed":"would_close"}=${o.closed} ${o.applied?"relabelled":"would_relabel"}=${o.relabelled} kept=${o.kept} errors=${o.errors.length} remaining=${o.remaining}`)),o.remaining>0)console.log(l.dim(` ${o.remaining} candidate(s) outside this run's window; the window rotates daily.`));if(o.mode==="rollup")console.log(l.dim(" Rollup mode: new failures with a cause that already has a rollup join it instead of opening their own issue."));if(o.rollupsReleased>0)console.log(l.dim(` ${o.applied?"Released":"Would release"} ${o.rollupsReleased} rollup(s): the backlog has drained, so per-dataset filing resumes.`));if(o.audit_failed)console.log(l.yellow(` Changes were applied but the audit row failed to write: ${o.audit_failed}`));if(!o.applied&&(o.closed>0||o.relabelled>0||o.rollupsReleased>0))console.log(l.dim(" Re-run with --apply to perform these changes."))});pe.addCommand(nZ);var iZ=new ae("backfill-usernames").description("Give username-less accounts a username from their name (dry run by default)");iZ.option("--apply","Write the usernames and send verification messages").option("--limit <n>","Users per batch (server clamps to [1,100])","25").option("--json","Output raw JSON instead of the human summary").action(async(e)=>{if(!Z())return;let t=Number.parseInt(e.limit??"25",10)||25,r=e.apply===!0,n=w(r?"Assigning usernames...":"Checking which accounts need a username...").start(),i;try{i=await GK({apply:r,limit:t}),n.stop()}catch(o){n.fail("Username backfill failed"),console.error(l.red(I(o))),process.exit(1);return}if(i.lookup_failed>0||i.conflict>0||(i.exhausted??0)>0||(i.write_failed??0)>0||(i.verify_failed??0)>0||(i.verify_rate_limited??0)>0||i.remaining===null)process.exitCode=1;if(e.json){console.log(JSON.stringify(i,null,2));return}if(console.log(),!i.apply)console.log(l.yellow("DRY RUN \u2014 nothing was written. Re-run with --apply."));console.log(l.cyan(`scanned=${i.scanned} ${i.apply?"assigned":"would_assign"}=${i.apply?i.assigned:i.would_assign} single_name=${i.single_name} no_name=${i.no_name} lookup_failed=${i.lookup_failed} conflict=${i.conflict} exhausted=${i.exhausted??0} write_failed=${i.write_failed??0} verify_sent=${i.verify_sent} verify_failed=${i.verify_failed??0} verify_rate_limited=${i.verify_rate_limited??0} remaining=${i.remaining??"unknown"}`));for(let o of i.results){let s=`id ${o.id} <${o.email}>`,a=[o.given_name,o.family_name].filter(Boolean).join(" ");if(o.outcome==="assigned"||o.outcome==="would_assign"){let c=o.outcome==="assigned"?l.green("assigned "):l.cyan("would give"),u=o.outcome==="assigned"?` [verify: ${o.verify}]`:"";console.log(` ${c} ${s}: ${l.cyan(o.username??"?")} (${a})${u}`)}else if(o.outcome==="single_name")console.log(` ${l.yellow("one name ")} ${s}: only "${a}" on record; pick a username by hand`);else if(o.outcome==="no_name")console.log(` ${l.yellow("no name ")} ${s}: run 'nemar admin backfill-names --apply' first`);else if(o.outcome==="conflict")console.log(` ${l.yellow("conflict ")} ${s}: ${o.error}`);else if(o.outcome==="exhausted")console.log(` ${l.yellow("exhausted ")} ${s}: ${o.error}; pick a username by hand`);else if(o.outcome==="write_failed")console.log(` ${l.red("write ")} ${s}: ${o.error}; retry the batch`);else console.log(` ${l.red("error ")} ${s}: ${o.error}`)}for(let o of i.verify_retries??[]){let s=o.verify==="sent"?l.green("re-sent "):o.verify==="not_attempted"?l.cyan("would send"):l.yellow(`verify ${o.verify}`);console.log(` ${s} id ${o.id} <${o.email}>`)}if(i.warning)console.log(l.yellow(` Warning: ${i.warning}`));if(i.single_name>0||i.no_name>0)console.log(),console.log(l.dim("Accounts with one name or none are listed, never guessed at: a username derived from an email address is a handle the person never chose."))});pe.addCommand(iZ);var oZ=new ae("duplicates").description("Report live accounts sharing an ORCID iD, email, or GitHub handle");function WUe(e){let t=e.username??l.dim("(no username)"),r=[];if(e.canonical)r.push(l.green("canonical"));if(e.identity_conflict===1)r.push(l.yellow("flagged"));if(e.has_oauth_identity)r.push(l.dim("orcid-login"));let n=r.length>0?` [${r.join(", ")}]`:"",i=`created ${e.created_at} datasets=${e.dataset_count}`;console.log(` id ${String(e.id).padEnd(5)} ${t} <${e.email}> ${i}${n}`)}oZ.option("--json","Output raw JSON instead of the human report").option("--clear <id>","Clear one account's identity-conflict flag (refuses while the collision remains)").action(async(e)=>{if(!Z())return;if(e.clear!==void 0){let n=Number.parseInt(e.clear,10);if(!Number.isInteger(n)||n<=0){console.error(l.red(`Invalid user id: ${e.clear}`)),process.exit(1);return}let i=w(`Clearing identity-conflict flag on user ${n}...`).start();try{let o=await HK(n);if(i.stop(),e.json){console.log(JSON.stringify(o,null,2));return}console.log(o.cleared?l.green(`Cleared the identity-conflict flag on user ${n}.`):l.dim(`User ${n} was not flagged; nothing to clear.`))}catch(o){i.fail(o instanceof q&&o.statusCode===409?"Still colliding; flag not cleared":"Failed to clear the identity-conflict flag"),console.error(l.red(I(o))),process.exit(1)}return}let t=w("Checking for duplicate accounts...").start(),r;try{r=await zK(),t.stop()}catch(n){t.fail("Duplicate report failed"),console.error(l.red(I(n))),process.exit(1);return}if(e.json){console.log(JSON.stringify(r,null,2));return}if(console.log(),r.groups.length===0){if(console.log(l.green("No duplicate accounts.")),r.flagged_count>0)console.log(l.yellow(`${r.flagged_count} account(s) still carry an identity-conflict flag with no remaining collision.`)),console.log(l.dim(" Clear each with 'nemar admin duplicates --clear <id>'."));return}console.log(l.cyan(`${r.group_count} duplicate group(s); ${r.flagged_count} account(s) flagged`));for(let n of r.groups){console.log(),console.log(` ${l.bold(n.kind)} ${n.value}`);for(let i of n.accounts)WUe(i)}console.log(),console.log(l.dim("The fix is self-service on the surviving account: change its email or GitHub username, or unlink/re-link its ORCID iD, in Settings on nemar.org. Merging two accounts is manual.")),process.exitCode=1});pe.addCommand(oZ);We();li();Rn();Sc();Cc();Wu();We();Sc();Cc();var KUe=Dt["cli.gaps.section.title"];function sZ(e){if(e.gaps===void 0)return[e.unknownReason??Dt["cli.gaps.unknown"]];let t=Xm(e.gaps,{orcidVerified:e.orcidVerified}).map(vq);if(e.sandboxCompleted===!1)t.push(Qm());return t.length>0?t:[Dt["gaps.none"]]}function YUe(e){let t=sZ(e);return t.length===1&&t[0]===Dt["gaps.none"]}function Ff(e){let t=e.gaps===void 0||YUe(e);console.log(),console.log(l.bold(KUe));for(let r of sZ(e))console.log(` ${t?l.dim(r):l.yellow(r)}`)}function Ng(e,t,r={}){let n=r.indent??" ";console.log(),console.log(`${n}${e}`);for(let i of t)console.log(`${n} ${l.yellow(i.label)} ${bv(i)}`)}Rc();us();Ct();async function E2(e){return O("/auth/login",{method:"POST",body:JSON.stringify({api_key:e})})}async function aZ(e){return O("/auth/resend-verification",{method:"POST",body:JSON.stringify({email:e})})}async function cZ(e,t){return O("/auth/retrieve-key",{method:"POST",body:JSON.stringify({email:e,password:t})})}async function lZ(e){return O("/auth/request-key-regeneration",{method:"POST",body:JSON.stringify({email:e})})}async function Hn(){return(await O("/users/me",{},!0,X5)).user}async function uZ(e){return O("/sandbox/complete",{method:"POST",body:JSON.stringify({dataset_id:e})},!0)}async function dZ(){return O("/sandbox/reset",{method:"POST"},!0)}async function qg(){return O("/sandbox/status",{},!0)}async function fZ(e){return O("/users/me/upload-access/request",{method:"POST",body:JSON.stringify({why:e})},!0)}async function pZ(e){return O("/auth/email/change/request",{method:"POST",body:JSON.stringify({email:e})},!0)}async function mZ(e,t){return O("/auth/email/change/verify",{method:"POST",body:JSON.stringify({email:e,code:t})},!0)}async function S2(e){return O("/auth/profile",{method:"PATCH",body:JSON.stringify(e)},!0)}async function hZ(e){return O("/auth/orcid/cli-start",{method:"POST",body:JSON.stringify({mode:e})},!0)}async function gZ(){return O("/auth/orcid/unlink",{method:"POST"},!0)}async function yZ(e){return O("/auth/device/start",{method:"POST",body:JSON.stringify({machine_name:e})},!1,mq)}function JUe(e){return typeof e==="string"&&Hm.options.includes(e)}function XUe(e){if(typeof e!=="object"||e===null)return;let t=e.message;return typeof t==="string"?t:void 0}async function xZ(e,t){try{return{status:"success",data:await O("/auth/device/token",{method:"POST",body:JSON.stringify({device_code:e}),signal:t},!1,gq)}}catch(r){if(r instanceof q&&r.statusCode===400){let n=hq.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(JUe(r.code)&&r.code!=="authorization_pending"&&r.code!=="slow_down")return{status:"terminal",error:r.code,reason:void 0,message:XUe(r.rawBody)??fq[r.code]}}throw r}}async function bZ(){return O("/auth/keys",{},!0,Wm)}async function _Z(e){return O("/auth/keys",{method:"POST",body:JSON.stringify({name:e})},!0,Km)}async function jg(e){return O(`/auth/keys/${e}`,{method:"DELETE"},!0)}async function vZ(e,t){return O(`/auth/keys/${e}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`}},!1)}async function wZ(){return O("/auth/profile/username-suggestion",{},!0,Z5)}Ct();so();import{spawn as QUe}from"child_process";function ZUe(e,t){if(e==="darwin")return{command:"open",args:[t]};if(e==="win32")return{command:"cmd",args:["/c","start","",t]};if(e==="linux")return{command:"xdg-open",args:[t]};return null}function Mg(e){if(process.env.NEMAR_NO_BROWSER==="1")return!1;let t=ZUe(process.platform,e);if(!t)return!1;try{let r=QUe(t.command,t.args,{stdio:"ignore",detached:!0});return r.on("error",(n)=>{br(`openInBrowser: ${t.command} failed: ${n instanceof Error?n.message:n}`)}),r.unref(),!0}catch(r){return br(`openInBrowser: could not spawn ${t.command}: ${r instanceof Error?r.message:r}`),!1}}gl();Ei();so();We();Ym();import{hostname as eVe}from"os";Ct();so();function tVe(e){let t=e.replace(/[\x00-\x1f\x7f]/g,"").replace(/\s+/g," ").trim();return t?t.slice(0,dq):gv}function rVe(){try{return tVe(eVe())}catch{return gv}}function nVe(e,t,r=hv){return e+(t+r)*1000}function SZ(e){switch(e.kind){case"cancelled":return{lines:["Sign-in canceled. Run `nemar auth login` to try again."],exitCode:130};case"denied":case"expired":case"invalid":return{lines:[e.message],exitCode:1};case"unreachable":return{lines:[`NEMAR could not be reached: ${e.detail}`,"Run `nemar auth login` again once you're back online."],exitCode:1};case"server_error":return{lines:[`NEMAR keeps answering with an error (${e.detail}). Try again in a few minutes; if it keeps happening, run \`nemar auth login --debug\` and report the log.`],exitCode:1};case"start_failed":return{lines:[`Could not start sign-in: ${e.detail}`],exitCode:1}}}var iVe=15000,DZ=1000,oVe=5000,EZ=3;function sVe(e){if(e instanceof q&&e.statusCode!==0)return`HTTP ${e.statusCode}`;return I(e)}function aVe(e){if(typeof AbortSignal.any==="function")return AbortSignal.any(e);let t=new AbortController;for(let r of e){if(r.aborted){t.abort();break}r.addEventListener("abort",()=>t.abort(),{once:!0})}return t.signal}function cVe(e,t){return new Promise((r)=>{if(t.aborted){r();return}let n=setTimeout(()=>{t.removeEventListener("abort",i),r()},e);function i(){clearTimeout(n),r()}t.addEventListener("abort",i,{once:!0})})}async function lVe(e,t={}){let r=Date.now(),n=nVe(r,e.expires_in,t.graceSeconds??hv),i=Math.max(e.interval*1000,DZ),o=new AbortController,s=()=>o.abort();process.on("SIGINT",s);let a=0;try{while(!0){if(o.signal.aborted)return{kind:"cancelled"};if(Date.now()>=n)return{kind:"unreachable",detail:"gave up waiting to reach NEMAR"};if(await cVe(i,o.signal),o.signal.aborted)return{kind:"cancelled"};let c=aVe([o.signal,AbortSignal.timeout(iVe)]),u;try{u=await xZ(e.device_code,c),a=0}catch(d){if(o.signal.aborted)return{kind:"cancelled"};if(d instanceof q&&d.statusCode===0){console.log(l.dim(" NEMAR is unreachable; retrying...")),a=0;continue}let f=sVe(d);if(a+=1,br(`poll error ${a}/${EZ}: ${f} -- ${I(d)}`),console.log(l.dim(` NEMAR answered with an error (${f}); retrying...`)),a>=EZ)return{kind:"server_error",detail:f};continue}if(u.status==="pending")continue;if(u.status==="slow_down"){i=Math.max(i+oVe,e.interval*1000,DZ);continue}if(u.status==="success")return{...u.data,kind:"success"};if(u.error==="expired_token")return{kind:"expired",message:u.message};if(u.error==="access_denied")return{kind:"denied",message:u.message};return{kind:"invalid",message:u.message}}}finally{process.off("SIGINT",s)}}async function $2(e={}){let t;try{t=await yZ(rVe())}catch(r){return{kind:"start_failed",detail:I(r)}}if(console.log(` ${t.verification_uri_complete}`),console.log(` Code: ${l.cyan(t.user_code)}`),console.log(l.dim(" (if the page asks for it)")),console.log(),e.open!==!1&&Mg(t.verification_uri_complete))console.log(l.dim(" (trying to open your browser; use the link above if it doesn't)")),console.log();return lVe(t)}tf();import{appendFileSync as uVe,existsSync as xs,mkdirSync as $Z,readFileSync as Bg,writeFileSync as dVe}from"fs";import{homedir as fVe}from"os";import{join as Lg}from"path";var{spawn:CZ}=globalThis.Bun;function da(){let e=Lg(fVe(),".ssh");return{sshDir:e,privateKey:Lg(e,"nemar_ed25519"),publicKey:Lg(e,"nemar_ed25519.pub"),configFile:Lg(e,"config")}}function RZ(){let e=da();return xs(e.privateKey)&&xs(e.publicKey)}async function kZ(e){let t=da();if(!xs(t.sshDir))try{$Z(t.sshDir,{mode:448})}catch(r){return{success:!1,error:`Cannot create ~/.ssh directory: ${r.message}`}}if(xs(t.privateKey))try{return{success:!0,publicKey:Bg(t.publicKey,"utf-8").trim()}}catch(r){return{success:!1,error:`NEMAR SSH key exists but cannot read public key: ${r.message}`}}try{let r=CZ({cmd:["ssh-keygen","-t","ed25519","-f",t.privateKey,"-N","","-C",`nemar-cli-${e}`],stdout:"pipe",stderr:"pipe"}),n=await new Response(r.stderr).text();if(await r.exited!==0)return{success:!1,error:`ssh-keygen failed: ${n}`};return{success:!0,publicKey:Bg(t.publicKey,"utf-8").trim()}}catch(r){return{success:!1,error:`Failed to generate SSH key: ${r.message}`}}}function OZ(){let e=da();if(!xs(e.publicKey))return null;try{return Bg(e.publicKey,"utf-8").trim()}catch{return null}}function pVe(){let e=da();if(!xs(e.configFile))return!1;try{let t=Bg(e.configFile,"utf-8");return t.includes("IdentityFile ~/.ssh/nemar_ed25519")||t.includes(`IdentityFile ${e.privateKey}`)}catch{return!1}}function AZ(){let e=da();if(!xs(e.sshDir))try{$Z(e.sshDir,{mode:448})}catch(r){return{success:!1,error:`Cannot create ~/.ssh directory: ${r.message}`}}if(pVe())return{success:!0};let t=`
499
+ Nothing to dispatch.`));return}let c=i?` (scoped to ${i})`:"",u=await Se(`Dispatch generate-manifest for ${a.length} version(s)${c}? Each dispatch queues a runner job on nemarDatasets/.github.`,e);if(u!=="confirmed"){console.log(l.dim(u==="declined"?"Skipped":"Cancelled"));return}let d=0,f=0;console.log();for(let[m,p]of a.entries()){let g=`${p.dataset_id}@${p.version}`,y=w(`[${m+1}/${a.length}] dispatching ${g}...`).start();try{await MK(p.dataset_id,p.version),y.succeed(`[${m+1}/${a.length}] dispatched ${g}`),d++}catch(x){y.fail(`[${m+1}/${a.length}] ${g}: ${I(x)}`),f++}if(m<a.length-1)await new Promise((x)=>setTimeout(x,UUe))}if(console.log(),console.log(f===0?l.green(`All ${d} dispatches succeeded.`):l.yellow(`${d} succeeded, ${f} failed.`)),console.log(l.dim("Workflow runs will appear on https://github.com/nemarDatasets/.github/actions. Re-run `nemar admin summary check` once they complete to verify drift cleared.")),f>0)process.exitCode=1});function LQ(e){return{versions:e.length,ok:e.filter((t)=>t.state.kind==="ok").length,stale:e.filter((t)=>t.state.kind==="stale").length,missing:e.filter((t)=>t.state.kind==="missing").length,error:e.filter((t)=>t.state.kind==="error").length}}pe.addCommand(eZ);var tZ=new ae("zarr-catalog").description("Top-level Zarr discovery catalog (zarr-catalog.json)");tZ.command("publish").description("Rebuild and republish zarr-catalog.json to this environment's bucket").action(async()=>{if(!Z())return;let e=w("Publishing zarr-catalog.json...").start();try{let t=await LK();e.succeed(`Published zarr-catalog.json: ${t.count} dataset(s), ${t.bytes} bytes`)}catch(t){ze(t,e,"Failed to publish zarr catalog"),process.exit(1)}});pe.addCommand(tZ);var rZ=new ae("backfill-names").description("Fill missing researcher names from users' public ORCID records (dry run by default)");rZ.option("--apply","Write the names (without this flag, only report what would change)").option("--limit <n>","Users per batch (server clamps to [1,100])","25").option("--json","Output raw JSON instead of the human summary").action(async(e)=>{if(!Z())return;let t=Number.parseInt(e.limit??"25",10)||25,r=e.apply===!0,n=w(r?"Backfilling names from ORCID...":"Checking ORCID for missing names...").start(),i;try{i=await VK({apply:r,limit:t}),n.stop()}catch(o){n.fail("Name backfill failed"),console.error(l.red(I(o))),process.exit(1);return}if(i.lookup_failed>0||(i.write_failed??0)>0||i.remaining===null)process.exitCode=1;if(e.json){console.log(JSON.stringify(i,null,2));return}if(console.log(),!i.apply)console.log(l.yellow("DRY RUN \u2014 nothing was written. Re-run with --apply."));console.log(l.cyan(`scanned=${i.scanned} ${i.apply?"filled":"would_fill"}=${i.apply?i.filled:i.would_fill} no_public_name=${i.no_public_name} lookup_failed=${i.lookup_failed} write_failed=${i.write_failed??0} remaining=${i.remaining??"unknown"}`));for(let o of i.results){let s=o.username??`id ${o.id} <${o.email}>`;if(o.outcome==="filled"||o.outcome==="would_fill"){let a=o.outcome==="filled"?l.green("filled "):l.cyan("would fill");console.log(` ${a} ${s}: ${o.given_name} ${o.family_name} (${o.orcid})`)}else if(o.outcome==="no_public_name")console.log(` ${l.yellow("no name ")} ${s}: ORCID ${o.orcid} does not publish a full name`);else if(o.outcome==="write_failed")console.log(` ${l.red("write ")} ${s}: ${o.error}; retry the batch`);else console.log(` ${l.red("error ")} ${s}: ${o.error}`)}if(i.warning)console.log(l.yellow(` Warning: ${i.warning}`));if(i.no_public_name>0)console.log(),console.log(l.dim("These accounts must make their name public on their ORCID record and sign in again; NEMAR cannot type a name in for an ORCID-linked account, because the record is re-read on every sign-in and would overwrite it. An account with no verified ORCID can set its name in Settings (ADR 0042)."))});pe.addCommand(rZ);function HUe(e){return typeof e==="object"&&e!==null&&Array.isArray(e.errors)}var nZ=new ae("import-issue-triage").description("Close recovered import-failure issues and retire stale cause labels (dry run by default)");nZ.option("--apply","Perform the changes (without this flag, only report what would change)").option("--limit <n>","Issues per batch (server clamps to [1,30])","15").option("--json","Output raw JSON instead of the human summary").action(async(e)=>{if(!Z())return;let t=e.limit??"15",r=t.trim()===""?Number.NaN:Number(t);if(!Number.isInteger(r)||r<1){console.error(l.red(`Invalid --limit ${JSON.stringify(t)}: expected an integer >= 1.`)),process.exitCode=1;return}let n=e.apply===!0,i=w(n?"Triaging import-failure issues...":"Checking import-failure issues...").start(),o;try{o=await UK({apply:n,limit:r}),i.stop()}catch(s){i.fail("Import-failure issue triage failed"),console.error(l.red(I(s)));let a=s instanceof q?s.details:void 0,c=HUe(a)?a.errors:[];if(e.json)console.log(JSON.stringify(s instanceof q?s.rawBody??{errors:c}:{errors:c},null,2));else for(let u of c)console.error(`${l.red("ERROR".padEnd(15))} #${u.issue} ${u.dataset_id??""} ${u.stage}: ${u.error}`);process.exitCode=1;return}if(o.errors.length>0)process.exitCode=1;if(e.json){console.log(JSON.stringify(o,null,2));return}if(console.log(),!o.applied)console.log(l.yellow("DRY RUN \u2014 nothing was written. Re-run with --apply."));for(let s of o.plan){let a=s.failed?"FAILED ":o.applied?"":"WOULD ",c=`#${s.issueNumber} ${s.datasetId??"(unknown)"}`;if(s.kind==="close"){let u=`${a}CLOSE`.padEnd(15);console.log(`${s.failed?l.red(u):l.green(u)} ${c} ${l.dim(s.reason)}`)}else if(s.kind==="relabel"){let u=`${a}RELABEL`.padEnd(15);console.log(`${s.failed?l.red(u):l.yellow(u)} ${c} ${l.dim(s.reason)}`)}else console.log(`${l.dim("KEEP".padEnd(15))} ${c} ${l.dim(s.reason)}`)}for(let s of o.rollups){let c=(s.outcome==="failed"?"FAILED RELEASE":s.outcome==="released"?"RELEASE":o.mode==="per-dataset"?"WOULD RELEASE":"ROLLUP").padEnd(15);console.log(`${s.outcome==="failed"?l.red(c):l.magenta(c)} #${s.number} ${l.dim(s.title)}`)}for(let s of o.errors)console.log(`${l.red("ERROR".padEnd(15))} #${s.issue} ${s.dataset_id??""} ${s.stage}: ${s.error}`);if(console.log(),console.log(l.cyan(`open=${o.openIssues} mode=${o.mode} examined=${o.examined} attempted=${o.attempted} ${o.applied?"closed":"would_close"}=${o.closed} ${o.applied?"relabelled":"would_relabel"}=${o.relabelled} kept=${o.kept} errors=${o.errors.length} remaining=${o.remaining}`)),o.remaining>0)console.log(l.dim(` ${o.remaining} candidate(s) outside this run's window; the window rotates daily.`));if(o.mode==="rollup")console.log(l.dim(" Rollup mode: new failures with a cause that already has a rollup join it instead of opening their own issue."));if(o.rollupsReleased>0)console.log(l.dim(` ${o.applied?"Released":"Would release"} ${o.rollupsReleased} rollup(s): the backlog has drained, so per-dataset filing resumes.`));if(o.audit_failed)console.log(l.yellow(` Changes were applied but the audit row failed to write: ${o.audit_failed}`));if(!o.applied&&(o.closed>0||o.relabelled>0||o.rollupsReleased>0))console.log(l.dim(" Re-run with --apply to perform these changes."))});pe.addCommand(nZ);var iZ=new ae("backfill-usernames").description("Give username-less accounts a username from their name (dry run by default)");iZ.option("--apply","Write the usernames and send verification messages").option("--limit <n>","Users per batch (server clamps to [1,100])","25").option("--json","Output raw JSON instead of the human summary").action(async(e)=>{if(!Z())return;let t=Number.parseInt(e.limit??"25",10)||25,r=e.apply===!0,n=w(r?"Assigning usernames...":"Checking which accounts need a username...").start(),i;try{i=await GK({apply:r,limit:t}),n.stop()}catch(o){n.fail("Username backfill failed"),console.error(l.red(I(o))),process.exit(1);return}if(i.lookup_failed>0||i.conflict>0||(i.exhausted??0)>0||(i.write_failed??0)>0||(i.verify_failed??0)>0||(i.verify_rate_limited??0)>0||i.remaining===null)process.exitCode=1;if(e.json){console.log(JSON.stringify(i,null,2));return}if(console.log(),!i.apply)console.log(l.yellow("DRY RUN \u2014 nothing was written. Re-run with --apply."));console.log(l.cyan(`scanned=${i.scanned} ${i.apply?"assigned":"would_assign"}=${i.apply?i.assigned:i.would_assign} single_name=${i.single_name} no_name=${i.no_name} lookup_failed=${i.lookup_failed} conflict=${i.conflict} exhausted=${i.exhausted??0} write_failed=${i.write_failed??0} verify_sent=${i.verify_sent} verify_failed=${i.verify_failed??0} verify_rate_limited=${i.verify_rate_limited??0} remaining=${i.remaining??"unknown"}`));for(let o of i.results){let s=`id ${o.id} <${o.email}>`,a=[o.given_name,o.family_name].filter(Boolean).join(" ");if(o.outcome==="assigned"||o.outcome==="would_assign"){let c=o.outcome==="assigned"?l.green("assigned "):l.cyan("would give"),u=o.outcome==="assigned"?` [verify: ${o.verify}]`:"";console.log(` ${c} ${s}: ${l.cyan(o.username??"?")} (${a})${u}`)}else if(o.outcome==="single_name")console.log(` ${l.yellow("one name ")} ${s}: only "${a}" on record; pick a username by hand`);else if(o.outcome==="no_name")console.log(` ${l.yellow("no name ")} ${s}: run 'nemar admin backfill-names --apply' first`);else if(o.outcome==="conflict")console.log(` ${l.yellow("conflict ")} ${s}: ${o.error}`);else if(o.outcome==="exhausted")console.log(` ${l.yellow("exhausted ")} ${s}: ${o.error}; pick a username by hand`);else if(o.outcome==="write_failed")console.log(` ${l.red("write ")} ${s}: ${o.error}; retry the batch`);else console.log(` ${l.red("error ")} ${s}: ${o.error}`)}for(let o of i.verify_retries??[]){let s=o.verify==="sent"?l.green("re-sent "):o.verify==="not_attempted"?l.cyan("would send"):l.yellow(`verify ${o.verify}`);console.log(` ${s} id ${o.id} <${o.email}>`)}if(i.warning)console.log(l.yellow(` Warning: ${i.warning}`));if(i.single_name>0||i.no_name>0)console.log(),console.log(l.dim("Accounts with one name or none are listed, never guessed at: a username derived from an email address is a handle the person never chose."))});pe.addCommand(iZ);var oZ=new ae("duplicates").description("Report live accounts sharing an ORCID iD, email, or GitHub handle");function WUe(e){let t=e.username??l.dim("(no username)"),r=[];if(e.canonical)r.push(l.green("canonical"));if(e.identity_conflict===1)r.push(l.yellow("flagged"));if(e.has_oauth_identity)r.push(l.dim("orcid-login"));let n=r.length>0?` [${r.join(", ")}]`:"",i=`created ${e.created_at} datasets=${e.dataset_count}`;console.log(` id ${String(e.id).padEnd(5)} ${t} <${e.email}> ${i}${n}`)}oZ.option("--json","Output raw JSON instead of the human report").option("--clear <id>","Clear one account's identity-conflict flag (refuses while the collision remains)").action(async(e)=>{if(!Z())return;if(e.clear!==void 0){let n=Number.parseInt(e.clear,10);if(!Number.isInteger(n)||n<=0){console.error(l.red(`Invalid user id: ${e.clear}`)),process.exit(1);return}let i=w(`Clearing identity-conflict flag on user ${n}...`).start();try{let o=await HK(n);if(i.stop(),e.json){console.log(JSON.stringify(o,null,2));return}console.log(o.cleared?l.green(`Cleared the identity-conflict flag on user ${n}.`):l.dim(`User ${n} was not flagged; nothing to clear.`))}catch(o){i.fail(o instanceof q&&o.statusCode===409?"Still colliding; flag not cleared":"Failed to clear the identity-conflict flag"),console.error(l.red(I(o))),process.exit(1)}return}let t=w("Checking for duplicate accounts...").start(),r;try{r=await zK(),t.stop()}catch(n){t.fail("Duplicate report failed"),console.error(l.red(I(n))),process.exit(1);return}if(e.json){console.log(JSON.stringify(r,null,2));return}if(console.log(),r.groups.length===0){if(console.log(l.green("No duplicate accounts.")),r.flagged_count>0)console.log(l.yellow(`${r.flagged_count} account(s) still carry an identity-conflict flag with no remaining collision.`)),console.log(l.dim(" Clear each with 'nemar admin duplicates --clear <id>'."));return}console.log(l.cyan(`${r.group_count} duplicate group(s); ${r.flagged_count} account(s) flagged`));for(let n of r.groups){console.log(),console.log(` ${l.bold(n.kind)} ${n.value}`);for(let i of n.accounts)WUe(i)}console.log(),console.log(l.dim("The fix is self-service on the surviving account: change its email or GitHub username, or unlink/re-link its ORCID iD, in Settings on nemar.org. Merging two accounts is manual.")),process.exitCode=1});pe.addCommand(oZ);We();li();Rn();Sc();Cc();Wu();We();Sc();Cc();var KUe=Dt["cli.gaps.section.title"];function sZ(e){if(e.gaps===void 0)return[e.unknownReason??Dt["cli.gaps.unknown"]];let t=Xm(e.gaps,{orcidVerified:e.orcidVerified}).map(vq);if(e.sandboxCompleted===!1)t.push(Qm());return t.length>0?t:[Dt["gaps.none"]]}function YUe(e){let t=sZ(e);return t.length===1&&t[0]===Dt["gaps.none"]}function Ff(e){let t=e.gaps===void 0||YUe(e);console.log(),console.log(l.bold(KUe));for(let r of sZ(e))console.log(` ${t?l.dim(r):l.yellow(r)}`)}function Ng(e,t,r={}){let n=r.indent??" ";console.log(),console.log(`${n}${e}`);for(let i of t)console.log(`${n} ${l.yellow(i.label)} ${bv(i)}`)}Rc();us();Ct();async function E2(e){return O("/auth/login",{method:"POST",body:JSON.stringify({api_key:e})})}async function aZ(e){return O("/auth/resend-verification",{method:"POST",body:JSON.stringify({email:e})})}async function cZ(e,t){return O("/auth/retrieve-key",{method:"POST",body:JSON.stringify({email:e,password:t})})}async function lZ(e){return O("/auth/request-key-regeneration",{method:"POST",body:JSON.stringify({email:e})})}async function Hn(){return(await O("/users/me",{},!0,X5)).user}async function uZ(e){return O("/sandbox/complete",{method:"POST",body:JSON.stringify({dataset_id:e})},!0)}async function dZ(){return O("/sandbox/reset",{method:"POST"},!0)}async function qg(){return O("/sandbox/status",{},!0)}async function fZ(e){return O("/users/me/upload-access/request",{method:"POST",body:JSON.stringify({why:e})},!0)}async function pZ(e){return O("/auth/email/change/request",{method:"POST",body:JSON.stringify({email:e})},!0)}async function mZ(e,t){return O("/auth/email/change/verify",{method:"POST",body:JSON.stringify({email:e,code:t})},!0)}async function S2(e){return O("/auth/profile",{method:"PATCH",body:JSON.stringify(e)},!0)}async function hZ(e){return O("/auth/orcid/cli-start",{method:"POST",body:JSON.stringify({mode:e})},!0)}async function gZ(){return O("/auth/orcid/unlink",{method:"POST"},!0)}async function yZ(e){return O("/auth/device/start",{method:"POST",body:JSON.stringify({machine_name:e})},!1,mq)}function JUe(e){return typeof e==="string"&&Hm.options.includes(e)}function XUe(e){if(typeof e!=="object"||e===null)return;let t=e.message;return typeof t==="string"?t:void 0}async function xZ(e,t){try{return{status:"success",data:await O("/auth/device/token",{method:"POST",body:JSON.stringify({device_code:e}),signal:t},!1,gq)}}catch(r){if(r instanceof q&&r.statusCode===400){let n=hq.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(JUe(r.code)&&r.code!=="authorization_pending"&&r.code!=="slow_down")return{status:"terminal",error:r.code,reason:void 0,message:XUe(r.rawBody)??fq[r.code]}}throw r}}async function bZ(){return O("/auth/keys",{},!0,Wm)}async function _Z(e){return O("/auth/keys",{method:"POST",body:JSON.stringify({name:e})},!0,Km)}async function jg(e){return O(`/auth/keys/${e}`,{method:"DELETE"},!0)}async function vZ(e,t){return O(`/auth/keys/${e}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`}},!1)}async function wZ(){return O("/auth/profile/username-suggestion",{},!0,Z5)}Ct();so();import{spawn as QUe}from"child_process";function ZUe(e,t){if(e==="darwin")return{command:"open",args:[t]};if(e==="win32")return{command:"cmd",args:["/c","start","",t]};if(e==="linux")return{command:"xdg-open",args:[t]};return null}function Mg(e){if(process.env.NEMAR_NO_BROWSER==="1")return!1;let t=ZUe(process.platform,e);if(!t)return!1;try{let r=QUe(t.command,t.args,{stdio:"ignore",detached:!0});return r.on("error",(n)=>{br(`openInBrowser: ${t.command} failed: ${n instanceof Error?n.message:n}`)}),r.unref(),!0}catch(r){return br(`openInBrowser: could not spawn ${t.command}: ${r instanceof Error?r.message:r}`),!1}}gl();Ei();so();We();Ym();import{hostname as eVe}from"os";Ct();so();function tVe(e){let t=e.replace(/[\x00-\x1f\x7f]/g,"").replace(/\s+/g," ").trim();return t?t.slice(0,dq):gv}function rVe(){try{return tVe(eVe())}catch{return gv}}function nVe(e,t,r=hv){return e+(t+r)*1000}function SZ(e){switch(e.kind){case"cancelled":return{lines:["Sign-in canceled. Run `nemar auth login` to try again."],exitCode:130};case"denied":case"expired":case"invalid":return{lines:[e.message],exitCode:1};case"unreachable":return{lines:[`NEMAR could not be reached: ${e.detail}`,"Run `nemar auth login` again once you're back online."],exitCode:1};case"server_error":return{lines:[`NEMAR keeps answering with an error (${e.detail}). Try again in a few minutes; if it keeps happening, run \`nemar auth login --debug\` and report the log.`],exitCode:1};case"start_failed":return{lines:[`Could not start sign-in: ${e.detail}`],exitCode:1}}}var iVe=15000,DZ=1000,oVe=5000,EZ=3;function sVe(e){if(e instanceof q&&e.statusCode!==0)return`HTTP ${e.statusCode}`;return I(e)}function aVe(e){if(typeof AbortSignal.any==="function")return AbortSignal.any(e);let t=new AbortController;for(let r of e){if(r.aborted){t.abort();break}r.addEventListener("abort",()=>t.abort(),{once:!0})}return t.signal}function cVe(e,t){return new Promise((r)=>{if(t.aborted){r();return}let n=setTimeout(()=>{t.removeEventListener("abort",i),r()},e);function i(){clearTimeout(n),r()}t.addEventListener("abort",i,{once:!0})})}async function lVe(e,t={}){let r=Date.now(),n=nVe(r,e.expires_in,t.graceSeconds??hv),i=Math.max(e.interval*1000,DZ),o=new AbortController,s=()=>o.abort();process.on("SIGINT",s);let a=0;try{while(!0){if(o.signal.aborted)return{kind:"cancelled"};if(Date.now()>=n)return{kind:"unreachable",detail:"gave up waiting to reach NEMAR"};if(await cVe(i,o.signal),o.signal.aborted)return{kind:"cancelled"};let c=aVe([o.signal,AbortSignal.timeout(iVe)]),u;try{u=await xZ(e.device_code,c),a=0}catch(d){if(o.signal.aborted)return{kind:"cancelled"};if(d instanceof q&&d.statusCode===0){console.log(l.dim(" NEMAR is unreachable; retrying...")),a=0;continue}let f=sVe(d);if(a+=1,br(`poll error ${a}/${EZ}: ${f} -- ${I(d)}`),console.log(l.dim(` NEMAR answered with an error (${f}); retrying...`)),a>=EZ)return{kind:"server_error",detail:f};continue}if(u.status==="pending")continue;if(u.status==="slow_down"){i=Math.max(i+oVe,e.interval*1000,DZ);continue}if(u.status==="success")return{...u.data,kind:"success"};if(u.error==="expired_token")return{kind:"expired",message:u.message};if(u.error==="access_denied")return{kind:"denied",message:u.message};return{kind:"invalid",message:u.message}}}finally{process.off("SIGINT",s)}}async function $2(e={}){let t;try{t=await yZ(rVe())}catch(r){return{kind:"start_failed",detail:I(r)}}if(console.log(` ${t.verification_uri_complete}`),console.log(` Code: ${l.cyan(t.user_code)}`),console.log(l.dim(" (if the page asks for it)")),console.log(),e.open!==!1&&Mg(t.verification_uri_complete))console.log(l.dim(" (trying to open your browser; use the link above if it doesn't)")),console.log();return lVe(t)}tf();import{appendFileSync as uVe,existsSync as xs,mkdirSync as $Z,readFileSync as Bg,writeFileSync as dVe}from"fs";import{homedir as fVe}from"os";import{join as Lg}from"path";var{spawn:CZ}=globalThis.Bun;function da(){let e=Lg(fVe(),".ssh");return{sshDir:e,privateKey:Lg(e,"nemar_ed25519"),publicKey:Lg(e,"nemar_ed25519.pub"),configFile:Lg(e,"config")}}function RZ(){let e=da();return xs(e.privateKey)&&xs(e.publicKey)}async function kZ(e){let t=da();if(!xs(t.sshDir))try{$Z(t.sshDir,{mode:448})}catch(r){return{success:!1,error:`Cannot create ~/.ssh directory: ${r.message}`}}if(xs(t.privateKey))try{return{success:!0,publicKey:Bg(t.publicKey,"utf-8").trim()}}catch(r){return{success:!1,error:`NEMAR SSH key exists but cannot read public key: ${r.message}`}}try{let r=CZ({cmd:["ssh-keygen","-t","ed25519","-f",t.privateKey,"-N","","-C",`nemar-cli-${e}`],stdout:"pipe",stderr:"pipe"}),n=await new Response(r.stderr).text();if(await r.exited!==0)return{success:!1,error:`ssh-keygen failed: ${n}`};return{success:!0,publicKey:Bg(t.publicKey,"utf-8").trim()}}catch(r){return{success:!1,error:`Failed to generate SSH key: ${r.message}`}}}function OZ(){let e=da();if(!xs(e.publicKey))return null;try{return Bg(e.publicKey,"utf-8").trim()}catch{return null}}function pVe(){let e=da();if(!xs(e.configFile))return!1;try{let t=Bg(e.configFile,"utf-8");return t.includes("IdentityFile ~/.ssh/nemar_ed25519")||t.includes(`IdentityFile ${e.privateKey}`)}catch{return!1}}function AZ(){let e=da();if(!xs(e.sshDir))try{$Z(e.sshDir,{mode:448})}catch(r){return{success:!1,error:`Cannot create ~/.ssh directory: ${r.message}`}}if(pVe())return{success:!0};let t=`
500
500
  # NEMAR CLI SSH key (auto-generated)
501
501
  Host github.com
502
502
  AddKeysToAgent yes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nemar-cli",
3
- "version": "0.10.1-PR1328.1794b86",
3
+ "version": "0.10.1-PR1328.6df7fdc",
4
4
  "description": "CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",