nemar-cli 0.10.26-PR1982.d6fa34a → 0.10.26-PR1982.db1ef68

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -99,7 +99,7 @@ ${t}`,TVe,PVe,IVe=(e,t,n)=>{let r=n===""?"":`with ${n.trim()}() `,o=OVe.bind(nul
99
99
  `)}var FI=!1;var{spawn:bft}=globalThis.Bun;function Tf(e,t=[]){let n=e.replace(wft,'("$1","<redacted>")');for(let r of t)if(r.length>=_ft)n=n.split(r).join("<redacted>");return n}function mS(e){let t=["AWS_SESSION_TOKEN","AWS_SECRET_ACCESS_KEY","AWS_ACCESS_KEY_ID"],n=new Set;for(let r of[process.env,e??{}])for(let o of t){let s=r[o];if(typeof s==="string"&&s.length>0)n.add(s)}return[...n]}async function ofe(e,t){let n=e.getReader(),r=new TextDecoder,o="";while(!0){let{done:s,value:i}=await n.read();if(s)break;if(i.byteLength===0)continue;t(),o+=r.decode(i,{stream:!0})}return o+r.decode()}async function R(e,t={}){let n={...process.env,GIT_TERMINAL_PROMPT:"0",...t.env};for(let y of t.unsetEnv??[])delete n[y];let r=bft({cmd:e,cwd:t.cwd,...t.stdin===void 0?{}:{stdin:new TextEncoder().encode(t.stdin)},stdout:"pipe",stderr:"pipe",env:n}),o=!1,s,i,a=performance.now(),c=()=>{if(i!==void 0)clearTimeout(i),i=void 0},l=()=>{if(!t.onInactivityWarning)return;c(),i=setTimeout(()=>{i=void 0;try{t.onInactivityWarning?.(performance.now()-a)}catch{console.error("Could not display subprocess inactivity warning; the child result is unaffected.")}},t.inactivityWarningAfterMs??xft)};if(l(),t.timeout)s=setTimeout(()=>{o=!0,c(),r.kill()},t.timeout);let d=Jh()?[...mS(n),...t.redact??[]]:[];if(Jh()){let y=t.cwd?` (cwd=${t.cwd})`:"";cd(u.dim(Tf(`$ ${e.join(" ")}${y}`,d)))}let f=()=>{a=performance.now(),l()},p,m,h,g=r.exited.then((y)=>(c(),y));try{[p,m,h]=await Promise.all([ofe(r.stdout,f),ofe(r.stderr,f),g])}finally{if(c(),s)clearTimeout(s)}if(Jh()){if(t.sensitiveOutput)cd(u.dim("[sensitive subprocess output suppressed]"));else{if(p.trim())cd(u.dim(Tf(p.trimEnd(),d)));if(m.trim())cd(u.yellow(Tf(m.trimEnd(),d)))}cd(u.dim(`(exit ${h})`))}if(o)return{stdout:p,stderr:m||`Command timed out after ${Math.round(t.timeout/1000)}s`,exitCode:h??1,timedOut:!0};return{stdout:p,stderr:m,exitCode:h,timedOut:!1}}var wft,_ft=8,xft=120000;var qt=V(()=>{He();wft=/\(\s*"((?:x-amz-)[^"]*|authorization|proxy-authorization)"\s*,\s*"[^"]*"\s*\)/gi});function kft(){if(process.platform==="darwin")return"macos";if(process.platform==="win32")return"windows";return"linux"}function ife(e,t=kft()){return e.installInstructions[t]}function Eft(e){let t=e.match(/(\d+\.\d+(?:\.\d+)?)/);return t?t[1]:void 0}function $ft(){let e=Number(process.env.TEST_PROBE_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:Sft}async function afe(e){try{let{exitCode:t,stdout:n,timedOut:r}=await R(e.cmd,{timeout:$ft()});if(r)return{available:!1,timedOut:!0};if(t!==0)return{available:!1};return{available:!0,version:Eft(n)}}catch(t){let n=t instanceof Error?t.message:String(t);if(!n.includes("ENOENT")&&!n.includes("not found"))console.error(` Warning: ${e.name} check failed unexpectedly: ${n}`);return{available:!1}}}async function Db(){let e=Object.entries(sfe);return Promise.all(e.map(async([t,n])=>{let{available:r,version:o,timedOut:s}=await afe(n);return{key:t,name:n.name,purpose:n.purpose,required:n.required,available:r,version:o,timedOut:s,installInstruction:ife(n)}}))}async function cfe(){let t=(await Db()).filter((n)=>n.required&&!n.available);if(t.length===0)return[];console.warn(`
100
100
  Heads up: some tools NEMAR needs for uploading/validating aren't installed yet:`);for(let n of t)console.warn(` - ${n.name} (${n.purpose})`),console.warn(` Install: ${n.installInstruction}`);return console.warn("Run `nemar doctor` anytime to re-check. You can finish signup without them.\n"),t}async function Pf(e){let n=vft[e].map((i)=>sfe[i]).filter(Boolean),r=await Promise.all(n.map(async(i)=>{let a=await afe(i);return{check:i,available:a.available,timedOut:a.timedOut}}));for(let i of r)if(i.timedOut&&i.check.required)console.warn(`Warning: ${i.check.name} did not respond to a version check in time; continuing anyway.`);let o=r.filter((i)=>!i.available&&!i.timedOut&&i.check.required).map((i)=>({tool:i.check.name,installInstruction:ife(i.check)}));if(o.length===0)return;let s=[`
101
101
  Missing required tools:`];for(let i of o)s.push(` ${i.tool} not installed`),s.push(` Install: ${i.installInstruction}`);throw Error(s.join(`
102
- `))}var sfe,vft,Sft=4000;var Rb=V(()=>{qt();sfe={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)"}}},vft={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 ufe;var lfe=V(()=>{ufe={name:"nemar-cli",packageManager:"bun@1.4.3",version:"0.10.26-PR1982.d6fa34a",description:"CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",type:"module",main:"dist/index.js",bin:{nemar:"dist/index.js","git-annex-remote-nemar":"dist/git-annex-remote-nemar.js"},scripts:{dev:"bun run src/index.ts",build:"bun build src/index.ts src/git-annex-remote-nemar.ts --outdir dist --target bun --minify && sed '1s|#!/usr/bin/env node|#!/usr/bin/env bun|' dist/index.js > dist/index.js.tmp && mv dist/index.js.tmp dist/index.js",test:"bun test",lint:"biome check src/","lint:scrub":"biome check scripts/scrub shared/identifier-scrub.ts test/scrub","test:scrub":"bun test --preload ./test/scrub/helpers/temp-dirs-preload.ts --path-ignore-patterns='__run_every_scrub_suite__' test/scrub test/identifier-scan.test.ts test/identifier-scrub.test.ts test/identifier-dates.test.ts test/identifier-fleet.test.ts","migrations:d1-check":"bun run scripts/d1-migration-check.ts","zarr:geometry-check":"bun run backend/scripts/zarr-geometry-conformance.ts","lint:fix":"biome check --fix src/",format:"biome format --write src/",typecheck:"tsc --noEmit && tsc --noEmit -p backend","generate-openapi":"bun run scripts/generate-openapi.ts",prepublishOnly:"bun run build",prepare:"husky",postinstall:"bun scripts/postinstall-check.mjs",deploy:"wrangler deploy",preview:"wrangler dev"},keywords:["nemar","bids","neuroimaging","eeg","emg","datalad","cli"],author:"NEMAR Team",license:"CC-BY-NC-ND-4.0",repository:{type:"git",url:"git+https://github.com/nemarOrg/nemar-cli.git"},bugs:{url:"https://github.com/nemarOrg/nemar-cli/issues"},homepage:"https://docs.nemar.org",engines:{bun:">=1.0.0"},files:["dist","scripts/postinstall-check.mjs","scripts/recover-datasets.json","scripts/withdrawn-datasets.json","README.md","LICENSE"],dependencies:{chalk:"^5.3.0",commander:"^12.1.0",conf:"^13.0.1",inquirer:"^9.2.15",ora:"^8.0.1",semver:"^7.8.5",zod:"^3.23.8"},"lint-staged":{"src/**/*.{ts,tsx}":["biome check --fix"],"backend/src/**/*.{ts,tsx}":["biome check --fix"]},trustedDependencies:["@biomejs/biome"],devDependencies:{"@anthropic-ai/sdk":"^0.132.1","@asteasolutions/zod-to-openapi":"^7.3.4","@biomejs/biome":"1.9.4","@types/bun":"latest","@types/inquirer":"^9.0.7","@types/semver":"^7.8.0",ajv:"^8.20.0","ajv-formats":"^3.0.1",husky:"^9.1.7","lint-staged":"^16.3.2",typescript:"^5.5.4",wrangler:"^4.70.0",yaml:"^2.8.4"}}});var ks;var If=V(()=>{lfe();ks=ufe.version});import{mkdirSync as Rft,readdirSync as Cft,unlinkSync as Aft,writeFileSync as Oft}from"fs";import{join as MI}from"path";function gfe(){Yh=!0}function sl(){return Yh}function yfe(e,t=process.env){return e.includes("--debug")||t.NEMAR_DEBUG==="1"}function Ab(e){hfe=e,Dn(`Step: ${e}`)}function Ao(){pfe=!0}function bfe(){return pfe}function ce(){if(mfe)return;LI=!0}function Ob(){LI=!1,mfe=!0}function wfe(){return LI}function Dn(e){if(Yh)process.stderr.write(`[debug] ${e}
102
+ `))}var sfe,vft,Sft=4000;var Rb=V(()=>{qt();sfe={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)"}}},vft={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 ufe;var lfe=V(()=>{ufe={name:"nemar-cli",packageManager:"bun@1.4.3",version:"0.10.26-PR1982.db1ef68",description:"CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",type:"module",main:"dist/index.js",bin:{nemar:"dist/index.js","git-annex-remote-nemar":"dist/git-annex-remote-nemar.js"},scripts:{dev:"bun run src/index.ts",build:"bun build src/index.ts src/git-annex-remote-nemar.ts --outdir dist --target bun --minify && sed '1s|#!/usr/bin/env node|#!/usr/bin/env bun|' dist/index.js > dist/index.js.tmp && mv dist/index.js.tmp dist/index.js",test:"bun test",lint:"biome check src/","lint:scrub":"biome check scripts/scrub shared/identifier-scrub.ts test/scrub","test:scrub":"bun test --preload ./test/scrub/helpers/temp-dirs-preload.ts --path-ignore-patterns='__run_every_scrub_suite__' test/scrub test/identifier-scan.test.ts test/identifier-scrub.test.ts test/identifier-dates.test.ts test/identifier-fleet.test.ts","migrations:d1-check":"bun run scripts/d1-migration-check.ts","zarr:geometry-check":"bun run backend/scripts/zarr-geometry-conformance.ts","lint:fix":"biome check --fix src/",format:"biome format --write src/",typecheck:"tsc --noEmit && tsc --noEmit -p backend","generate-openapi":"bun run scripts/generate-openapi.ts",prepublishOnly:"bun run build",prepare:"husky",postinstall:"bun scripts/postinstall-check.mjs",deploy:"wrangler deploy",preview:"wrangler dev"},keywords:["nemar","bids","neuroimaging","eeg","emg","datalad","cli"],author:"NEMAR Team",license:"CC-BY-NC-ND-4.0",repository:{type:"git",url:"git+https://github.com/nemarOrg/nemar-cli.git"},bugs:{url:"https://github.com/nemarOrg/nemar-cli/issues"},homepage:"https://docs.nemar.org",engines:{bun:">=1.0.0"},files:["dist","scripts/postinstall-check.mjs","scripts/recover-datasets.json","scripts/withdrawn-datasets.json","README.md","LICENSE"],dependencies:{chalk:"^5.3.0",commander:"^12.1.0",conf:"^13.0.1",inquirer:"^9.2.15",ora:"^8.0.1",semver:"^7.8.5",zod:"^3.23.8"},"lint-staged":{"src/**/*.{ts,tsx}":["biome check --fix"],"backend/src/**/*.{ts,tsx}":["biome check --fix"]},trustedDependencies:["@biomejs/biome"],devDependencies:{"@anthropic-ai/sdk":"^0.132.1","@asteasolutions/zod-to-openapi":"^7.3.4","@biomejs/biome":"1.9.4","@types/bun":"latest","@types/inquirer":"^9.0.7","@types/semver":"^7.8.0",ajv:"^8.20.0","ajv-formats":"^3.0.1",husky:"^9.1.7","lint-staged":"^16.3.2",typescript:"^5.5.4",wrangler:"^4.70.0",yaml:"^2.8.4"}}});var ks;var If=V(()=>{lfe();ks=ufe.version});import{mkdirSync as Rft,readdirSync as Cft,unlinkSync as Aft,writeFileSync as Oft}from"fs";import{join as MI}from"path";function gfe(){Yh=!0}function sl(){return Yh}function yfe(e,t=process.env){return e.includes("--debug")||t.NEMAR_DEBUG==="1"}function Ab(e){hfe=e,Dn(`Step: ${e}`)}function Ao(){pfe=!0}function bfe(){return pfe}function ce(){if(mfe)return;LI=!0}function Ob(){LI=!1,mfe=!0}function wfe(){return LI}function Dn(e){if(Yh)process.stderr.write(`[debug] ${e}
103
103
  `)}function Nft(e){let t={};for(let[n,r]of Object.entries(e))t[n]=Ift.has(n.toLowerCase())?"[REDACTED]":r;return t}function xfe(e){let t=e.indexOf("@");if(t<=0)return"***";return`${e[0]}***${e.slice(t)}`}function jI(e,t,n=0){if(n>Mft)return"[REDACTED: depth]";if(Array.isArray(t))return t.map((r)=>jI(e,r,n+1));if(t&&typeof t==="object"){let r={};for(let[o,s]of Object.entries(t))r[o]=jI(o,s,n+1);return r}if(typeof t==="string"){if(Fft.test(e))return"[REDACTED]";return t.replace(_fe,xfe)}return t}function qI(e){return e.replace(jft,"Bearer [REDACTED]").replace(Lft,"[REDACTED_AWS_KEY]").replace(qft,"$1[REDACTED]").replace(Bft,"$1$2=[REDACTED]").replace(_fe,xfe)}function Uft(e){return qI(e)}function dfe(e,t=Pft){if(e===void 0)return;let n=e;try{let r=JSON.parse(e);n=JSON.stringify(jI("",r))}catch{}if(n=qI(n),Buffer.byteLength(n,"utf8")>t)n=`${Buffer.from(n,"utf8").subarray(0,t).toString("utf8")}... [truncated]`;return n}function yS(e){if(!Yh)return;let t=Uft(e.url);try{let n={...e,url:t,requestHeaders:e.requestHeaders?Nft(e.requestHeaders):void 0,requestBody:dfe(e.requestBody),responseBody:dfe(e.responseBody)};gS.push(n),Dn(`${e.method} ${t} -> ${e.status??"ERROR"} (${e.durationMs}ms)`)}catch(n){let r=G(n);gS.push({method:e.method,url:t,status:e.status,durationMs:e.durationMs,note:`redaction failed: ${r}`}),Dn(`redaction failed for ${e.method} ${t}: ${r}`)}}async function Hft(){let e=[];try{let t=process.versions.bun?`Bun ${process.versions.bun}`:`Node ${process.version}`;e.push(`CLI version: ${ks}`),e.push(`OS/Arch: ${process.platform}/${process.arch}`),e.push(`Runtime: ${t}`)}catch(t){e.push(`(could not read CLI/OS/runtime info: ${G(t)})`)}e.push(""),e.push("Active account:");try{let t=Vt();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: ${G(t)})`)}e.push(""),e.push("External tools:");try{let t=await Db();for(let n of t){let r=n.available?n.version??"installed":n.timedOut?"(timed out)":"not installed";e.push(` ${n.name}: ${r}`)}}catch(t){e.push(` (could not probe external tools: ${G(t)})`)}return e}async function BI(){return(await Hft()).join(`
104
104
  `)}async function vfe(){if(!Yh||hS!==void 0)return;try{hS=await BI()}catch(e){let t=G(e);hS=`(could not build environment report: ${t})`,Dn(`environment snapshot failed: ${t}`)}}function kfe(e){if(ffe.has(e))return{flag:e};for(let t of ffe){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 zft(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n],o=kfe(r);if(!o){t.push(r);continue}if(o.kind==="long-eq")t.push(`${o.flag}=[REDACTED]`);else if(o.kind==="short-attached")t.push(`${o.flag}[REDACTED]`);else if(t.push(r),n+1<e.length)t.push("[REDACTED]"),n++}return t}function Vft(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n],o=kfe(r);if(!o){t.push(r);continue}if(!o.kind&&n+1<e.length)n++}return t}function Gft(e){let t=[];for(let r of Vft(e)){if(r.startsWith("-"))continue;if(t.push(r),t.length===2)break}return(t.length>0?t.join("-"):"nemar").replace(/[^a-zA-Z0-9_-]/g,"_")}function Wft(e,t){let n=[];if(n.push("NEMAR CLI Debug Log"),n.push(`Generated: ${new Date().toISOString()}`),n.push(`Command: nemar ${qI(zft(e).join(" "))}`),n.push(""),n.push(hS??"(environment snapshot unavailable)"),n.push(""),n.push("HTTP requests:"),gS.length===0)n.push(" (none)");else gS.forEach((r,o)=>{if(n.push(` [${o+1}] ${r.method} ${r.url} -> ${r.status??"ERROR"} (${r.durationMs}ms)`),r.error)n.push(` Error: ${r.error}`);if(r.note)n.push(` Note: ${r.note}`);if(r.requestHeaders)n.push(` Request headers: ${JSON.stringify(r.requestHeaders)}`);if(r.requestBody)n.push(` Request body: ${r.requestBody}`);if(r.responseBody)n.push(` Response body: ${r.responseBody}`)});return n.push(""),n.push(`Failing step: ${hfe??"(none recorded)"}`),n.push(`Exit code: ${t}`),`${n.join(`
105
105
  `)}
@@ -227,7 +227,7 @@ ${t}`,d=i&&!c?"Replace stale":"Add",f=s?`Rename ${o} to README.md and ${d.toLowe
227
227
  `)}function Q$t(e,t){let n=Qc(t);return{DOI:`doi:10.18112/openneuro.${e}.v${n}`,URL:`https://openneuro.org/datasets/${e}/versions/${n}`,Version:n}}function Z$t(e,t){if(!Fg(e,t))return!1;let n=e;return["DOI","URL"].every((r)=>{let o=n[r];return typeof o!=="string"||o.trim()===""||Fg({[r]:o},t)})}async function eDt(e,t,n){let r=Mr(e,"dataset_description.json"),o=Vke(e);if(Mg(o,t).source_version!==null)return"already-recorded";let s=o.SourceDatasets,i=Array.isArray(s)?[...s]:s===void 0||s===null?[]:[s],a=Q$t(t,n),c=i.findIndex((g)=>Z$t(g,t)),l,d=c>=0?i[c]:null,f=(g)=>d!==null&&d[g]!==void 0&&d[g]!==null&&d[g]!=="",p=d!==null&&!f("Version")&&(!f("DOI")||typeof d.DOI==="string")&&(!f("URL")||typeof d.URL==="string");if(d!==null&&p)i[c]={...d,...f("DOI")?{}:{DOI:a.DOI},...f("URL")?{}:{URL:a.URL},Version:a.Version},l="completed";else i.push(a),l="appended";let m={...o,SourceDatasets:i};if(Mg(m,t).source_version!==a.Version)return console.log(u.yellow(` Warning: recording upstream ${t} ${n} would not make dataset_description.json read as that tag (an entry for ${t} carries another tag or names another dataset too, or ${n} is not a tag the shared parser reads); left it as it is, so the upstream-moved guard stays inert for this dataset until a person settles it`)),"unreadable";if(d!==null&&!p)console.log(u.yellow(` Warning: left the existing SourceDatasets entry for ${t} as it is (it carries a Version that is not a tag, or a DOI or URL that is not text); recording ${n} beside it`));OR(r,`${JSON.stringify(m,null,2)}
228
228
  `);let h=await R(["git","-c","annex.largefiles=nothing","add","dataset_description.json"],{cwd:e});if(h.exitCode!==0)throw Error(`Failed to stage dataset_description.json: ${h.stderr.trim()}`);return l}function tDt(e,t,n){let r=cy(e,{withFileTypes:!0}).filter((s)=>s.isFile()).map((s)=>s.name),o=TD(r);if(o.kind==="kept")return{kind:"kept",path:o.path};if(o.kind==="renamed")return T$t(Mr(e,o.from),Mr(e,"README.md")),{kind:"renamed",from:"README",to:"README.md"};return OR(Mr(e,"README.md"),Fw(t,n)),{kind:"created",path:"README.md"}}function nDt(e,t){let n=[],r=0;for(let[o,s]of e){let i=j$(s),a=s.startsWith("http")?s:null;if(!i&&!a){r++;continue}n.push({key:o,sourceUrl:a,source:i,destUri:`s3://${Bo}/${t}/objects/${o}`})}return{items:n,skipped:r}}function rDt(e){return`https://github.com/${I$t}/${e}.git`}async function oDt(e,t,n={}){if(n.tag!==void 0&&!Jo(n.tag))throw Error(`Invalid upstream tag ${JSON.stringify(n.tag)}: expected an OpenNeuro snapshot tag such as 1.0.0`);let r=n.repoUrl??rDt(e),o=await W_e(e,n.tag!==void 0?{...n.lookup,attempts:1,timeoutMs:Math.min(n.lookup?.timeoutMs??Bke,Bke)}:n.lookup),s=o.tag,i;if(n.tag!==void 0)i=n.tag;else if(o.tag!==null)i=o.tag;else throw new hl(uD,`${e}: the upstream tag to import could not be resolved (${o.reason}). Nothing was created; the retry engine retries it.`);let a=await po(r,t,{tag:i});if(a.missingTag)throw new hl(uD,`${e}: upstream tag ${i} is not on ${r.replace(/\.git$/,"")} yet. Nothing was created; the retry engine retries it.`);if(!a.success||a.commit===void 0)throw Error(`Failed to clone: ${a.error??"unknown error"}`);return{tag:i,commit:a.commit,latestTag:s}}async function sDt(e,t,n,r=null){if(n.persistStaging)try{await OF(t,Bo,Ki)}catch(o){console.log(u.yellow(` Could not clear s3://${Bo}/${t}/staging/ (${o instanceof Error?o.message:String(o)})`))}Wke(r),D().fail(e.message),process.exit(1)}function Wke(e){if(e===null)return;let t=(n)=>{let r;try{R$t(n,493),r=cy(n,{withFileTypes:!0})}catch{return}for(let o of r)if(o.isDirectory())t(Mr(n,o.name))};try{t(e),Hke(e,{recursive:!0,force:!0})}catch(n){console.log(u.yellow(` Could not remove the work directory ${e} (${n instanceof Error?n.message:String(n)})`))}}async function tj(e,t={}){let n=ej(e),r=t.workDir?null:XM(Mr(QM(),`nemar-import-${n}-`));try{return await iDt(e,n,{...t,workDir:t.workDir??r})}catch(o){if(o instanceof hl)return sDt(o,n,t,r);if(o instanceof AR)Wke(r),D().fail(o.message),process.exit(1);throw o}}async function iDt(e,t,n){let r=n.workDir||XM(Mr(QM(),`nemar-import-${t}-`)),o=Mr(r,t);console.log(u.cyan(`
229
229
  [prepare] ${e} -> ${t}
230
- `)),console.log(u.dim(`Working directory: ${r}`));let s=D("Cloning OpenNeuro dataset...").start(),i;try{i=await oDt(e,o,{tag:n.tag,lookup:n.openNeuroLookup})}catch(Q){if(s.stop(),Q instanceof hl)throw Q;throw new AR(Q instanceof Error?Q.message:String(Q))}if(s.succeed(`Cloned ${e} at upstream tag ${i.tag}`),i.latestTag!==null&&!Sr(i.latestTag,i.tag))console.log(u.yellow(` Warning: importing ${i.tag}, but OpenNeuro's latest is ${i.latestTag}. The copy takes the object currently at each upstream path (only a re-pull's copy pins the object version, ADR 0111 decision 8), so a recording that changed between the two without changing size would be copied with the newer bytes.`));if(!await VS(o,{yes:!0}))console.error(u.red("Cannot proceed with import: branch must be named 'main'.")),process.exit(1);let c=D("Normalizing dataset metadata...").start();try{let Q=await W$t(o,e);if(Q.length>0)c.succeed(`Un-annexed ${Q.length} metadata file(s): ${Q.join(", ")}`);else c.stop()}catch(Q){c.fail(`Failed to normalize annexed metadata: ${Q instanceof Error?Q.message:String(Q)}`),process.exit(1)}let l=0;try{let Q=await CR(o);if(l=Q.length,Q.length>0){let pt=Q.reduce((W,J)=>W+J.size,0),Be=n.skipData?"will stay in the git repo (--skip-data)":"will be moved into the annex and uploaded to S3";console.log(u.yellow(` ${Q.length} file(s) (${(pt/1e6).toFixed(1)} MB) are data under NEMAR policy but plain git blobs upstream; they ${Be}.`));for(let W of Q.slice(0,5))console.log(u.dim(` - ${W.path} (${(W.size/1e6).toFixed(1)} MB)`));if(Q.length>5)console.log(u.dim(` ... and ${Q.length-5} more`))}}catch(Q){console.log(u.dim(` Could not check for un-annexed data: ${Q instanceof Error?Q.message:String(Q)}`))}let d=Vke(o),f=d.Name||e,p=K$t(d);if(console.log(u.dim(` Dataset: ${f}`)),p)console.log(u.dim(` OpenNeuro DOI: ${p}`));let m=D("Creating NEMAR dataset record...").start();try{let Q=await hpe({dataset_id:t,name:f,source:"openneuro",source_id:e});m.succeed(`Created ${Q.dataset_id} (${Q.github_repo})`)}catch(Q){let pt=Q instanceof Error?Q.message:String(Q);if(M$t(pt))m.warn(`Dataset ${t} already exists, continuing...`);else m.fail(`Failed to create dataset: ${pt}`),process.exit(1)}let h=new Map;if(!n.skipData){let Q=D("Mapping annexed files from OpenNeuro S3...").start(),pt=await R(["git","annex","enableremote","s3-PUBLIC"],{cwd:o});if(pt.exitCode!==0)Q.fail(`Failed to enable s3-PUBLIC remote: ${pt.stderr.trim()}`),process.exit(1);let Be=await LF(o);if(h=Be.urlMap,h.size===0){if(Be.fileCount>0)throw Q.fail(`${Be.fileCount} annexed file(s) present but none had a copyable source URL`),Error(`Import aborted: ${t} has ${Be.fileCount} annexed file(s) but git-annex whereis mapped 0 to a copyable source (likely the content's only location is a remote NEMAR can't read). Refusing to publish a dataset with no data. Investigate the upstream annex remotes before retrying.`);Q.warn("No annexed files found, skipping data copy")}else Q.succeed(`Found ${h.size} annexed files`)}await U$(o,(Q,pt)=>{console.log(u.yellow(` Warning: could not mark ${Q} as annex-ignore (${pt}). Future pushes may try to upload to ${Q}; run 'git config remote.${Q}.annex-ignore true' manually.`))});let g=D("Configuring NEMAR remote...").start(),y=await R(["git","remote","remove","origin"],{cwd:o});if(y.exitCode!==0&&!y.stderr.includes("No such remote"))g.fail(`Failed to remove OpenNeuro remote: ${y.stderr.trim()}`),process.exit(1);let b=`git@github.com:nemarDatasets/${t}.git`,_=await nc(o,b,"origin");if(!_.success)g.fail(`Failed to configure remote: ${_.error}`),process.exit(1);g.succeed("Configured NEMAR remote");let x=await rbe(o);if(x.state==="failed")console.log(u.yellow(` Warning: could not fetch or merge ${t}'s existing git-annex state (${x.error}). A retry may register the S3 remote under a new UUID; investigate before re-running finalize.`));let k;try{k=await B$t(o,{sourceId:e,importTag:i.tag,nemarId:t,released:()=>Pme(t)})}catch(Q){if(Q instanceof hl)throw Q;throw new AR(Q instanceof Error?Q.message:String(Q))}let v=k.kind==="hard-reset";if(v)console.log(u.dim(" Re-import: based main on origin/main for an idempotent metadata commit"));else if(k.kind==="retarget")console.log(u.dim(` Re-import of an unreleased dataset: moved from upstream tag ${k.recordedTag} to ${i.tag}, as a fast-forward of origin/main`));if(v&&x.state!=="merged")console.log(u.yellow(" Warning: re-import, but the dataset's git-annex branch could not be fetched; keys a correction marked dead are unknown to this run"));let C=[],T=v;if(!n.skipData)try{C=await CR(o)}catch(Q){console.error(u.red(`Failed to scan for un-annexed data: ${Q instanceof Error?Q.message:String(Q)}`)),console.error(u.dim(" Aborting: continuing would commit data files into the git repo and report success.")),process.exit(1)}let z="",A=[],F=null;if(!n.skipData&&(h.size>0||C.length>0)){let Q=D("Setting up NEMAR S3 remote...").start();F=Gke();let pt=sbe(await obe(o,{bucket:Bo,prefix:`${t}/objects`,region:Ki,originAnnex:x.state,env:bd(F)}));if("refuse"in pt)throw Q.stop(),new hl(l6,pt.refuse);if("warn"in pt)console.log(u.yellow(` ${pt.warn}`));let Be=await Fo(o,{name:"nemar-s3",bucket:Bo,prefix:`${t}/objects`,region:Ki},F);if(!Be.success)Q.fail(`Failed to configure S3 remote: ${Be.error}`),process.exit(1);let W=await _d(o,"nemar-s3");if(!W)Q.fail("Failed to get NEMAR S3 remote UUID"),process.exit(1);if(z=W,Q.succeed("Configured NEMAR S3 remote"),h.size>0){let J=nDt(h,t);if(A=J.items,J.skipped>0)console.log(u.yellow(` Skipped ${J.skipped} keys (no usable source URL)`));console.log(u.dim(` Prepared ${A.length} files for server-side copy`))}}let M,U=D("Applying the identifier scrub and NEMAR annex policy...").start();try{if(C.length>0&&!F)throw Error(`${C.length} file(s) need moving into the annex but no S3 credentials were resolved for ${t}. Refusing to continue: the upload would be attempted with whatever credentials git-annex had cached.`);let Q=await O_e({datasetPath:o,nemarId:t,bucket:Bo,remoteName:"nemar-s3",keyUrlMap:h,upstreamItems:A,unannexedData:C,reimport:T,skipData:n.skipData??!1,maxBytes:n.normalizeMaxBytes,reader:SD(),upload:Rw({credentials:F??"inherit"})}),{scrub:pt,normalized:Be,manifest:W}=Q;A=W.items,M=Q.privacy;let J=pt.counts,le=[J.headers_not_read_skip_data>0?`${J.headers_not_read_skip_data} not read (--skip-data)`:null,J.headers_not_read_no_source>0?`${J.headers_not_read_no_source} with no upstream source`:null,J.headers_not_read_nemar_held>0?`${J.headers_not_read_nemar_held} already NEMAR's (the screen reads them)`:null,J.headers_not_edf>0?`${J.headers_not_edf} not an EDF/BDF header`:null].filter(Boolean);if(console.log(u.dim(` Identifier scrub: ${J.recordings} EDF/BDF recording(s), ${J.headers_read} header(s) read, ${J.headers_scrubbed} scrubbed${le.length>0?` (${le.join(", ")})`:""}; ${J.json_values_blanked} JSON value(s) blanked in ${J.json_files_blanked} file(s), ${J.json_files_unread+J.json_files_annexed} JSON file(s) not read; ${J.images_or_documents_held} image or document path(s) left for review`)),console.log(u.dim(` Acquisition dates set to 1 January: ${J.headers_dates_normalized} header(s), ${J.scans_values_normalized} scans table value(s) in ${J.scans_tables_normalized} table(s); ${J.headers_dates_left} header(s) read keep a date (${J.headers_dates_over_bound} over the --normalize-max-gb bound, ${J.headers_dates_failed} whose download failed, ${J.headers_dates_unproven} unproven); ${J.scans_tables_unread+J.scans_tables_annexed} scans table(s) not read`)),pt.committed)console.log(u.dim(" Committed the privacy correction and its ledger line"));let ne=J.provenance_not_annotated+J.provenance_malformed;if(ne>0)console.log(u.yellow(` Warning: ${ne} provenance file(s) could not be annotated; their checksums still describe the upstream files without saying so`));if(Be.notes.length===0){if(U.stop(),l>0&&C.length===0)console.log(u.dim(` The ${l} file(s) reported above are already annexed on origin/main; nothing to move.`))}else U.succeed(`Applied NEMAR annex policy: ${Be.notes.join("; ")}`);if(Be.carriedOver.length>0)console.log(u.dim(` Carried ${Be.carriedOver.length} key(s) already in this tree into the manifest so finalize verifies them`));if(W.droppedNotInTree>0||W.droppedDead>0)console.log(u.dim(` Copy manifest: ${W.items.length} key(s); dropped ${W.droppedNotInTree} the pushed tree does not name and ${W.droppedDead} the git-annex branch records as dead`));for(let Ue of Be.policy.skipped)console.log(u.yellow(` Warning: left a quoted .gitattributes line alone, so it still governs adds -- ${Ue}`))}catch(Q){U.fail(`Failed to apply the identifier scrub or NEMAR annex policy: ${Q instanceof Error?Q.message:String(Q)}`),process.exit(1)}let B=D("Seeding metadata...").start(),P,O=null;try{if(X$t(o,t,e,d,p),P=tDt(o,e,p),q$t(k))O=await eDt(o,e,i.tag)}catch(Q){B.fail(`Failed to seed metadata: ${Q instanceof Error?Q.message:String(Q)}`),process.exit(1)}let H=[".nemar/metadata.json"];if(P.kind==="renamed")H.push("README","README.md");else if(P.kind==="created")H.push("README.md");let re=await R(["git","add",...H],{cwd:o});if(re.exitCode!==0)B.fail(`Failed to stage metadata: ${re.stderr.trim()}`),process.exit(1);let Ee=await R(["git","commit","-m",`Add NEMAR metadata (imported from OpenNeuro ${e})`],{cwd:o});if(Ee.exitCode!==0&&!Ee.stdout.includes("nothing to commit"))B.fail(`Failed to commit metadata: ${Ee.stderr.trim()}`),process.exit(1);let Qt=P.kind==="renamed"?"renamed README -> README.md":P.kind==="kept"?`kept upstream ${P.path}`:"wrote provenance stub README.md (no upstream README)";B.succeed(`Seeded .nemar/metadata.json (${Qt}${O==="appended"||O==="completed"?`; recorded upstream ${e} ${i.tag} in SourceDatasets`:""})`);let ft=D("Pushing to nemarDatasets...").start(),Ze=await sr(o,"origin");if(!Ze.success)ft.fail(`Failed to push: ${Ze.error}`),process.exit(1);if(Ze.warning)ft.fail(`Pushed main but git-annex branch failed: ${Ze.warning}. Aborting \u2014 published dataset would be uncloneable. Investigate the git-annex push failure and re-run.`),process.exit(1);ft.succeed("Pushed to nemarDatasets");let oe={openneuroId:e,nemarId:t,nemarUuid:z,items:A,privacy:M};if(n.persistStaging)await Q0e(oe,Bo,Ki),console.log(u.dim(` Wrote import manifest to s3://${Bo}/${t}/staging/`));let je=A.filter((Q)=>fl(Q)).length,Ie=A.length-je;return console.log(u.green(`[prepare] done: ${t} (${Ie} files to copy${je>0?`, ${je} already uploaded`:""})`)),oe}async function nj(e,t,n={},r){let o=ej(e),s=r??await AF(o,Bo,Ki),i=`copy ${t.index}/${t.count}`;if(n.skipData||s.items.length===0){console.log(u.dim(`[${i}] no data to copy`));return}let{shardItems:a,localSkipped:c}=Y0e(s.items,t);if(c>0)console.log(u.dim(`[${i}] ${c} key(s) already uploaded by prepare`));if(a.length===0){console.log(u.dim(`[${i}] empty shard`));return}let l=await dl(Bo,`${o}/objects/`,Ki),{toCopy:d,skipped:f}=L$(a,l,q$(a));if(f.length>0)console.log(u.dim(`[${i}] skipped ${f.length} already present`));if(d.length===0){console.log(u.green(`[${i}] nothing to copy (all ${f.length} present)`));return}let p=D(`[${i}] copying ${d.length} files...`).start(),m=await aw(d,Ki,N$t,(h,g)=>{p.text=`[${i}] ${h}/${g}`});if(m.fellBack>0)console.log(u.yellow(` ${m.fellBack} objects needed the curl fallback (check S3 permissions)`));if(m.failed.length>0){p.fail(`[${i}] ${m.failed.length} of ${d.length} files failed`);for(let h of m.failed.slice(0,5))console.error(u.red(` ${h.key}: ${h.error}`));if(m.failed.length>5)console.error(u.red(` ... and ${m.failed.length-5} more`));console.error(u.red("Re-run this shard to resume (already-copied objects are skipped).")),process.exit(1)}p.succeed(`[${i}] copied ${m.copied}, skipped ${f.length}`)}async function rj(e,t={},n){let r=Date.now(),o=ej(e),s=n??await AF(o,Bo,Ki),i=t.workDir||XM(Mr(QM(),`nemar-finalize-${o}-`)),a=Mr(i,`${o}-finalize`);console.log(u.cyan(`
230
+ `)),console.log(u.dim(`Working directory: ${r}`));let s=D("Cloning OpenNeuro dataset...").start(),i;try{i=await oDt(e,o,{tag:n.tag,lookup:n.openNeuroLookup})}catch(Q){if(s.stop(),Q instanceof hl)throw Q;throw new AR(Q instanceof Error?Q.message:String(Q))}if(s.succeed(`Cloned ${e} at upstream tag ${i.tag}`),i.latestTag!==null&&!Sr(i.latestTag,i.tag))console.log(u.yellow(` Warning: importing ${i.tag}, but OpenNeuro's latest is ${i.latestTag}. The copy takes the object currently at each upstream path (a re-pull's copy pins the object version, ADR 0111 decision 8), so a recording that changed between the two without changing size would be copied with the newer bytes.`));if(!await VS(o,{yes:!0}))console.error(u.red("Cannot proceed with import: branch must be named 'main'.")),process.exit(1);let c=D("Normalizing dataset metadata...").start();try{let Q=await W$t(o,e);if(Q.length>0)c.succeed(`Un-annexed ${Q.length} metadata file(s): ${Q.join(", ")}`);else c.stop()}catch(Q){c.fail(`Failed to normalize annexed metadata: ${Q instanceof Error?Q.message:String(Q)}`),process.exit(1)}let l=0;try{let Q=await CR(o);if(l=Q.length,Q.length>0){let pt=Q.reduce((W,J)=>W+J.size,0),Be=n.skipData?"will stay in the git repo (--skip-data)":"will be moved into the annex and uploaded to S3";console.log(u.yellow(` ${Q.length} file(s) (${(pt/1e6).toFixed(1)} MB) are data under NEMAR policy but plain git blobs upstream; they ${Be}.`));for(let W of Q.slice(0,5))console.log(u.dim(` - ${W.path} (${(W.size/1e6).toFixed(1)} MB)`));if(Q.length>5)console.log(u.dim(` ... and ${Q.length-5} more`))}}catch(Q){console.log(u.dim(` Could not check for un-annexed data: ${Q instanceof Error?Q.message:String(Q)}`))}let d=Vke(o),f=d.Name||e,p=K$t(d);if(console.log(u.dim(` Dataset: ${f}`)),p)console.log(u.dim(` OpenNeuro DOI: ${p}`));let m=D("Creating NEMAR dataset record...").start();try{let Q=await hpe({dataset_id:t,name:f,source:"openneuro",source_id:e});m.succeed(`Created ${Q.dataset_id} (${Q.github_repo})`)}catch(Q){let pt=Q instanceof Error?Q.message:String(Q);if(M$t(pt))m.warn(`Dataset ${t} already exists, continuing...`);else m.fail(`Failed to create dataset: ${pt}`),process.exit(1)}let h=new Map;if(!n.skipData){let Q=D("Mapping annexed files from OpenNeuro S3...").start(),pt=await R(["git","annex","enableremote","s3-PUBLIC"],{cwd:o});if(pt.exitCode!==0)Q.fail(`Failed to enable s3-PUBLIC remote: ${pt.stderr.trim()}`),process.exit(1);let Be=await LF(o);if(h=Be.urlMap,h.size===0){if(Be.fileCount>0)throw Q.fail(`${Be.fileCount} annexed file(s) present but none had a copyable source URL`),Error(`Import aborted: ${t} has ${Be.fileCount} annexed file(s) but git-annex whereis mapped 0 to a copyable source (likely the content's only location is a remote NEMAR can't read). Refusing to publish a dataset with no data. Investigate the upstream annex remotes before retrying.`);Q.warn("No annexed files found, skipping data copy")}else Q.succeed(`Found ${h.size} annexed files`)}await U$(o,(Q,pt)=>{console.log(u.yellow(` Warning: could not mark ${Q} as annex-ignore (${pt}). Future pushes may try to upload to ${Q}; run 'git config remote.${Q}.annex-ignore true' manually.`))});let g=D("Configuring NEMAR remote...").start(),y=await R(["git","remote","remove","origin"],{cwd:o});if(y.exitCode!==0&&!y.stderr.includes("No such remote"))g.fail(`Failed to remove OpenNeuro remote: ${y.stderr.trim()}`),process.exit(1);let b=`git@github.com:nemarDatasets/${t}.git`,_=await nc(o,b,"origin");if(!_.success)g.fail(`Failed to configure remote: ${_.error}`),process.exit(1);g.succeed("Configured NEMAR remote");let x=await rbe(o);if(x.state==="failed")console.log(u.yellow(` Warning: could not fetch or merge ${t}'s existing git-annex state (${x.error}). A retry may register the S3 remote under a new UUID; investigate before re-running finalize.`));let k;try{k=await B$t(o,{sourceId:e,importTag:i.tag,nemarId:t,released:()=>Pme(t)})}catch(Q){if(Q instanceof hl)throw Q;throw new AR(Q instanceof Error?Q.message:String(Q))}let v=k.kind==="hard-reset";if(v)console.log(u.dim(" Re-import: based main on origin/main for an idempotent metadata commit"));else if(k.kind==="retarget")console.log(u.dim(` Re-import of an unreleased dataset: moved from upstream tag ${k.recordedTag} to ${i.tag}, as a fast-forward of origin/main`));if(v&&x.state!=="merged")console.log(u.yellow(" Warning: re-import, but the dataset's git-annex branch could not be fetched; keys a correction marked dead are unknown to this run"));let C=[],T=v;if(!n.skipData)try{C=await CR(o)}catch(Q){console.error(u.red(`Failed to scan for un-annexed data: ${Q instanceof Error?Q.message:String(Q)}`)),console.error(u.dim(" Aborting: continuing would commit data files into the git repo and report success.")),process.exit(1)}let z="",A=[],F=null;if(!n.skipData&&(h.size>0||C.length>0)){let Q=D("Setting up NEMAR S3 remote...").start();F=Gke();let pt=sbe(await obe(o,{bucket:Bo,prefix:`${t}/objects`,region:Ki,originAnnex:x.state,env:bd(F)}));if("refuse"in pt)throw Q.stop(),new hl(l6,pt.refuse);if("warn"in pt)console.log(u.yellow(` ${pt.warn}`));let Be=await Fo(o,{name:"nemar-s3",bucket:Bo,prefix:`${t}/objects`,region:Ki},F);if(!Be.success)Q.fail(`Failed to configure S3 remote: ${Be.error}`),process.exit(1);let W=await _d(o,"nemar-s3");if(!W)Q.fail("Failed to get NEMAR S3 remote UUID"),process.exit(1);if(z=W,Q.succeed("Configured NEMAR S3 remote"),h.size>0){let J=nDt(h,t);if(A=J.items,J.skipped>0)console.log(u.yellow(` Skipped ${J.skipped} keys (no usable source URL)`));console.log(u.dim(` Prepared ${A.length} files for server-side copy`))}}let M,U=D("Applying the identifier scrub and NEMAR annex policy...").start();try{if(C.length>0&&!F)throw Error(`${C.length} file(s) need moving into the annex but no S3 credentials were resolved for ${t}. Refusing to continue: the upload would be attempted with whatever credentials git-annex had cached.`);let Q=await O_e({datasetPath:o,nemarId:t,bucket:Bo,remoteName:"nemar-s3",keyUrlMap:h,upstreamItems:A,unannexedData:C,reimport:T,skipData:n.skipData??!1,maxBytes:n.normalizeMaxBytes,reader:SD(),upload:Rw({credentials:F??"inherit"})}),{scrub:pt,normalized:Be,manifest:W}=Q;A=W.items,M=Q.privacy;let J=pt.counts,le=[J.headers_not_read_skip_data>0?`${J.headers_not_read_skip_data} not read (--skip-data)`:null,J.headers_not_read_no_source>0?`${J.headers_not_read_no_source} with no upstream source`:null,J.headers_not_read_nemar_held>0?`${J.headers_not_read_nemar_held} already NEMAR's (the screen reads them)`:null,J.headers_not_edf>0?`${J.headers_not_edf} not an EDF/BDF header`:null].filter(Boolean);if(console.log(u.dim(` Identifier scrub: ${J.recordings} EDF/BDF recording(s), ${J.headers_read} header(s) read, ${J.headers_scrubbed} scrubbed${le.length>0?` (${le.join(", ")})`:""}; ${J.json_values_blanked} JSON value(s) blanked in ${J.json_files_blanked} file(s), ${J.json_files_unread+J.json_files_annexed} JSON file(s) not read; ${J.images_or_documents_held} image or document path(s) left for review`)),console.log(u.dim(` Acquisition dates set to 1 January: ${J.headers_dates_normalized} header(s), ${J.scans_values_normalized} scans table value(s) in ${J.scans_tables_normalized} table(s); ${J.headers_dates_left} header(s) read keep a date (${J.headers_dates_over_bound} over the --normalize-max-gb bound, ${J.headers_dates_failed} whose download failed, ${J.headers_dates_unproven} unproven); ${J.scans_tables_unread+J.scans_tables_annexed} scans table(s) not read`)),pt.committed)console.log(u.dim(" Committed the privacy correction and its ledger line"));let ne=J.provenance_not_annotated+J.provenance_malformed;if(ne>0)console.log(u.yellow(` Warning: ${ne} provenance file(s) could not be annotated; their checksums still describe the upstream files without saying so`));if(Be.notes.length===0){if(U.stop(),l>0&&C.length===0)console.log(u.dim(` The ${l} file(s) reported above are already annexed on origin/main; nothing to move.`))}else U.succeed(`Applied NEMAR annex policy: ${Be.notes.join("; ")}`);if(Be.carriedOver.length>0)console.log(u.dim(` Carried ${Be.carriedOver.length} key(s) already in this tree into the manifest so finalize verifies them`));if(W.droppedNotInTree>0||W.droppedDead>0)console.log(u.dim(` Copy manifest: ${W.items.length} key(s); dropped ${W.droppedNotInTree} the pushed tree does not name and ${W.droppedDead} the git-annex branch records as dead`));for(let Ue of Be.policy.skipped)console.log(u.yellow(` Warning: left a quoted .gitattributes line alone, so it still governs adds -- ${Ue}`))}catch(Q){U.fail(`Failed to apply the identifier scrub or NEMAR annex policy: ${Q instanceof Error?Q.message:String(Q)}`),process.exit(1)}let B=D("Seeding metadata...").start(),P,O=null;try{if(X$t(o,t,e,d,p),P=tDt(o,e,p),q$t(k))O=await eDt(o,e,i.tag)}catch(Q){B.fail(`Failed to seed metadata: ${Q instanceof Error?Q.message:String(Q)}`),process.exit(1)}let H=[".nemar/metadata.json"];if(P.kind==="renamed")H.push("README","README.md");else if(P.kind==="created")H.push("README.md");let re=await R(["git","add",...H],{cwd:o});if(re.exitCode!==0)B.fail(`Failed to stage metadata: ${re.stderr.trim()}`),process.exit(1);let Ee=await R(["git","commit","-m",`Add NEMAR metadata (imported from OpenNeuro ${e})`],{cwd:o});if(Ee.exitCode!==0&&!Ee.stdout.includes("nothing to commit"))B.fail(`Failed to commit metadata: ${Ee.stderr.trim()}`),process.exit(1);let Qt=P.kind==="renamed"?"renamed README -> README.md":P.kind==="kept"?`kept upstream ${P.path}`:"wrote provenance stub README.md (no upstream README)";B.succeed(`Seeded .nemar/metadata.json (${Qt}${O==="appended"||O==="completed"?`; recorded upstream ${e} ${i.tag} in SourceDatasets`:""})`);let ft=D("Pushing to nemarDatasets...").start(),Ze=await sr(o,"origin");if(!Ze.success)ft.fail(`Failed to push: ${Ze.error}`),process.exit(1);if(Ze.warning)ft.fail(`Pushed main but git-annex branch failed: ${Ze.warning}. Aborting \u2014 published dataset would be uncloneable. Investigate the git-annex push failure and re-run.`),process.exit(1);ft.succeed("Pushed to nemarDatasets");let oe={openneuroId:e,nemarId:t,nemarUuid:z,items:A,privacy:M};if(n.persistStaging)await Q0e(oe,Bo,Ki),console.log(u.dim(` Wrote import manifest to s3://${Bo}/${t}/staging/`));let je=A.filter((Q)=>fl(Q)).length,Ie=A.length-je;return console.log(u.green(`[prepare] done: ${t} (${Ie} files to copy${je>0?`, ${je} already uploaded`:""})`)),oe}async function nj(e,t,n={},r){let o=ej(e),s=r??await AF(o,Bo,Ki),i=`copy ${t.index}/${t.count}`;if(n.skipData||s.items.length===0){console.log(u.dim(`[${i}] no data to copy`));return}let{shardItems:a,localSkipped:c}=Y0e(s.items,t);if(c>0)console.log(u.dim(`[${i}] ${c} key(s) already uploaded by prepare`));if(a.length===0){console.log(u.dim(`[${i}] empty shard`));return}let l=await dl(Bo,`${o}/objects/`,Ki),{toCopy:d,skipped:f}=L$(a,l,q$(a));if(f.length>0)console.log(u.dim(`[${i}] skipped ${f.length} already present`));if(d.length===0){console.log(u.green(`[${i}] nothing to copy (all ${f.length} present)`));return}let p=D(`[${i}] copying ${d.length} files...`).start(),m=await aw(d,Ki,N$t,(h,g)=>{p.text=`[${i}] ${h}/${g}`});if(m.fellBack>0)console.log(u.yellow(` ${m.fellBack} objects needed the curl fallback (check S3 permissions)`));if(m.failed.length>0){p.fail(`[${i}] ${m.failed.length} of ${d.length} files failed`);for(let h of m.failed.slice(0,5))console.error(u.red(` ${h.key}: ${h.error}`));if(m.failed.length>5)console.error(u.red(` ... and ${m.failed.length-5} more`));console.error(u.red("Re-run this shard to resume (already-copied objects are skipped).")),process.exit(1)}p.succeed(`[${i}] copied ${m.copied}, skipped ${f.length}`)}async function rj(e,t={},n){let r=Date.now(),o=ej(e),s=n??await AF(o,Bo,Ki),i=t.workDir||XM(Mr(QM(),`nemar-finalize-${o}-`)),a=Mr(i,`${o}-finalize`);console.log(u.cyan(`
231
231
  [finalize] ${e} -> ${o}
232
232
  `));let c=!t.skipData&&s.items.length>0;if(!t.skipData&&s.items.length===0){let A=D("Confirming dataset has no annexed data...").start(),F=await po(`git@github.com:nemarDatasets/${o}.git`,a,{useGitHubToken:!0});if(!F.success)A.fail(`Failed to clone ${o} for the empty-manifest check: ${F.error}`),process.exit(1);let{fileCount:M}=await LF(a);if(M>0)throw A.fail(`${M} annexed file(s) but the import manifest is empty`),Error(`Finalize aborted: ${o} has ${M} annexed file(s) but the import manifest is empty (no data was copied). Refusing to publish a dataset with no data. Re-run prepare + copy; if the data is genuinely unfetchable this should quarantine, not publish.`);A.succeed("Confirmed metadata-only dataset (no annexed data)")}if(c){let A=D("Verifying copied data...").start(),F=await dl(Bo,`${o}/objects/`,Ki),M=xR(s.items,F);if(M.message!==null)A.fail(M.message),process.exit(1);A.succeed(`Verified ${s.items.length} objects present`);let U=D("Re-cloning for git-annex finalize...").start(),B=await po(`git@github.com:nemarDatasets/${o}.git`,a,{useGitHubToken:!0});if(!B.success)U.fail(`Failed to clone ${o}: ${B.error}`),process.exit(1);U.succeed(`Cloned ${o}`);let P=Gke(),O=await Fo(a,{name:"nemar-s3",bucket:Bo,prefix:`${o}/objects`,region:Ki},P);if(!O.success)console.error(u.red(`Failed to enable S3 remote: ${O.error}`)),process.exit(1);let H=await _d(a,"nemar-s3");if(!H)console.error(u.red("Failed to get NEMAR S3 remote UUID on finalize clone")),process.exit(1);if(s.nemarUuid&&H!==s.nemarUuid)console.error(u.red(`nemar-s3 uuid mismatch (prepare=${s.nemarUuid} finalize=${H}). Aborting to avoid registering keys against the wrong remote.`)),process.exit(1);let re=D("Checking every annexed key has an object...").start(),Ee=new Set((await ur(a)).values()),Qt=vR(Ee,F,{bucket:Bo,datasetId:o,manifestItems:s.items.length});if(!Qt.ok)re.fail(Qt.message),process.exit(1);re.succeed(Qt.message);let ft=D("Registering files in git-annex...").start(),Ze=await xke(a,[...Ee],H);if(!Ze.ok)ft.fail(Ze.message),process.exit(1);ft.succeed(Ze.message);let oe=D("Pushing git-annex branch...").start(),je=await sr(a,"origin");if(!je.success)oe.fail(`Failed to push git-annex branch: ${je.error}`),process.exit(1);if(je.warning)oe.fail(`git-annex branch push failed: ${je.warning}. Aborting \u2014 published dataset would be uncloneable.`),process.exit(1);oe.succeed("Pushed git-annex branch")}let l=!1,d=D("Deploying CI workflows...").start();try{await il(o),d.succeed("CI workflows deployed (BIDS validation, LLM enrichment, archive generation)"),l=!0}catch(A){let F=A instanceof Error?A.message:String(A);d.fail(`CI deployment failed: ${F}`),console.log(u.dim(` After fixing the deploy failure, run 'nemar admin ci add ${o}' and 'nemar admin publish request/approve ${o}' to resume.`))}let f=null;if(l){let A=D("Waiting for BIDS validation run to register...").start();if(f=await ZM(o,A),f.kind==="found")A.succeed("BIDS validation run registered; deferring to ci_check at approval");else if(f.kind==="timeout"){let F=t.trustUpstream?"trusting upstream OpenNeuro validation (--trust-upstream)":"no --trust-upstream \u2014 aborting";A.warn(`BIDS validation run did not register within 120s; ${F}`)}else{let F=f.lastError instanceof Error?f.lastError.message:String(f.lastError);A.fail(`All BIDS validation polls failed (last error: ${F})`)}}let p=F$t({ciDeployed:l,poll:f,trustUpstream:t.trustUpstream??!1});if(p.abortReason)console.error(u.red(p.abortReason)),process.exit(1);let m=p.skipCiCheck,h=null;try{h=(await Wn(o)).visibility}catch{}let g=h!==null&&j$t(h)==="skip-already-published",y=5,b=300000,_=D("Requesting publication...").start(),x=!1,k=null;if(g)x=!0,_.succeed(`${o} is already published; skipping publish/request (data re-copy only)`);for(let A=1;!g&&A<=y;A++)try{await Zh(o),x=!0;break}catch(F){let M=F instanceof Error?F.message:String(F);if(M==="Dataset is already published"){g=!0,x=!0,_.succeed(`${o} is already published; skipping publish/request (data re-copy only)`);break}if(F instanceof L&&F.statusCode===409&&M==="A publication request already exists"){k=F.rawBody?.status==="approving"?"approving":"requested",x=!0,_.succeed(`${o} already has an open publication request; using it`);break}if(!M.includes("BIDS validation is currently running"))_.fail(`Failed to request publication: ${M}`),process.exit(1);if(A===y)_.fail(`BIDS validation still in progress after ${y} attempts (~${Math.round(y*b/60000)}min). Re-run 'nemar admin publish request/approve ${o}' once validation completes.`),process.exit(1);_.text=`Waiting for BIDS validation to complete... (attempt ${A}/${y}, next retry in 5min)`,await new Promise((B)=>setTimeout(B,b))}if(x&&!g&&k===null)_.succeed("Publication requested");let v=D("Waiting for the identifier screen...").start(),C;if(g)C={outcome:"already-published"};else if(k==="approving")C={outcome:"unchecked",reason:"approval-in-progress"};else try{C=await Mke({nemarId:o,skipCiCheck:m,privacy:s.privacy,waitMs:t.screenWaitMs??Fke(Date.now()-r),pollMs:t.screenPollMs,onProgress:(A)=>{v.text=A}})}catch(A){let F=A instanceof Error?A.message:String(A);v.fail(`Failed to approve publication: ${F}`),process.exit(1)}let T=jke(o,C);if(C.outcome==="published"||C.outcome==="already-published")v.succeed(T);else v.warn(T);let z=D("Refreshing metadata + LLM enrichment...").start();try{let A=await ig(o),F=A.enrichment?.status==="ok",M=A.sync?.metadata_columns_written===!0;if(F&&M)z.succeed("Refreshed enrichment + metadata columns");else{let U=[];if(!F)U.push(`enrichment ${A.enrichment?.status??"missing"}`);if(!M)U.push("metadata columns not written");z.warn(`Partial reindex: ${U.join(", ")} (run 'nemar admin reindex ${o}' to retry)`)}}catch(A){let F=A instanceof Error?A.message:String(A);z.warn(`Reindex failed (non-fatal): ${F}. Run 'nemar admin reindex ${o}' to retry.`)}if(t.persistStaging)await OF(o,Bo,Ki);return console.log(u.green(`
233
233
  Import complete: ${e} -> ${o} (publication: ${C.outcome})`)),console.log(u.dim(` GitHub: https://github.com/nemarDatasets/${o}`)),console.log(u.dim(` Working dir: ${a}`)),C}async function Kke(e,t={}){let n=await tj(e,t);if(!t.skipData)await nj(e,{index:0,count:1},t,n);await rj(e,t,n)}var I$t="OpenNeuroDatasets",Bo="nemar",Ki="us-east-2",N$t=16,qke,Bke=1e4,AR;var s_=V(()=>{He();ro();xa();tp();K6();Qa();ec();Je();Ni();ep();ii();rc();Fi();ug();qt();cc();Pr();kR();u6();Td();Lke();Vi();Pw();cs();Ad();qke=["anat","beh","dwi","eeg","emg","fmap","func","ieeg","meg","micr","motion","nirs","perf","pet"];AR=class AR extends Error{}});import{existsSync as aDt,mkdirSync as cDt,mkdtempSync as lDt,rmSync as Jke}from"fs";import{tmpdir as uDt}from"os";import{join as Sp}from"path";async function TR(e,t={}){let n=t.workDir??lDt(Sp(uDt(),`nemar-normalize-${e}-`)),r=Sp(n,e);if(aDt(Sp(r,".git")))await fDt(r,e);else{let i=t.originUrl??`git@github.com:nemarDatasets/${e}.git`,a=await po(i,r,{useGitHubToken:!t.originUrl,identity:{name:"NEMAR",email:"nemar-bot@nemar.org"}});if(!a.success)throw Error(`Failed to clone ${e}: ${a.error}`)}await pDt(r,e);let o=await CR(r),s=await mDt(r);return{datasetId:e,datasetPath:r,files:o,bytes:o.reduce((i,a)=>i+a.size,0),attributeFiles:s,pendingKeys:await dDt(r)}}async function dDt(e){if((await R(["git","rev-parse","--verify","--quiet","refs/remotes/origin/main"],{cwd:e})).exitCode!==0)return[];let n=await R(["git","diff","--name-only","origin/main","HEAD"],{cwd:e});if(n.exitCode!==0)return[];let r=new Set;for(let o of n.stdout.split(`
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.26-PR1982.d6fa34a",
4
+ "version": "0.10.26-PR1982.db1ef68",
5
5
  "description": "CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",
6
6
  "type": "module",
7
7
  "main": "dist/index.js",