nemar-cli 0.10.26-PR1981.fad0a64 → 0.10.26-PR1982.a8dac72
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/git-annex-remote-nemar.js +1 -1
- package/dist/index.js +69 -69
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -13,17 +13,17 @@ var JCe=Object.create;var{getPrototypeOf:YCe,defineProperty:z_,getOwnPropertyNam
|
|
|
13
13
|
`)return"";return(g>0?l:"")+h.trimEnd()}).join(`
|
|
14
14
|
`)}}RAe.Help=tq});var hC=w(function(PAe){var{InvalidArgumentError:AAe}=Dy();class nq{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;let n=TAe(e);if(this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long)this.negate=this.long.startsWith("--no-");this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}preset(e){return this.presetArg=e,this}conflicts(e){return this.conflictsWith=this.conflictsWith.concat(e),this}implies(e){let t=e;if(typeof e==="string")t={[e]:!0};return this.implied=Object.assign(this.implied||{},t),this}env(e){return this.envVar=e,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,t){if(t===this.defaultValue||!Array.isArray(t))return[e];return t.concat(e)}choices(e){return this.argChoices=e.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new AAe(`Allowed choices are ${this.argChoices.join(", ")}.`);if(this.variadic)return this._concatValue(t,n);return t},this}name(){if(this.long)return this.long.replace(/^--/,"");return this.short.replace(/^-/,"")}attributeName(){return OAe(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class rq{constructor(e){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,e.forEach((t)=>{if(t.negate)this.negativeOptions.set(t.attributeName(),t);else this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,n)=>{if(this.positiveOptions.has(n))this.dualOptions.add(n)})}valueFromOption(e,t){let n=t.attributeName();if(!this.dualOptions.has(n))return!0;let r=this.negativeOptions.get(n).presetArg,o=r!==void 0?r:!1;return t.negate===(o===e)}}function OAe(e){return e.split("-").reduce((t,n)=>t+n[0].toUpperCase()+n.slice(1))}function TAe(e){let t,n,r=e.split(/[ |,]+/);if(r.length>1&&!/^[[<]/.test(r[1]))t=r.shift();if(n=r.shift(),!t&&/^-[^-]$/.test(n))t=n,n=void 0;return{shortFlag:t,longFlag:n}}PAe.Option=nq;PAe.DualOptions=rq});var oq=w(function(jAe){function FAe(e,t){if(Math.abs(e.length-t.length)>3)return Math.max(e.length,t.length);let n=[];for(let r=0;r<=e.length;r++)n[r]=[r];for(let r=0;r<=t.length;r++)n[0][r]=r;for(let r=1;r<=t.length;r++)for(let o=1;o<=e.length;o++){let s=1;if(e[o-1]===t[r-1])s=0;else s=1;if(n[o][r]=Math.min(n[o-1][r]+1,n[o][r-1]+1,n[o-1][r-1]+s),o>1&&r>1&&e[o-1]===t[r-2]&&e[o-2]===t[r-1])n[o][r]=Math.min(n[o][r],n[o-2][r-2]+1)}return n[e.length][t.length]}function MAe(e,t){if(!t||t.length===0)return"";t=Array.from(new Set(t));let n=e.startsWith("--");if(n)e=e.slice(2),t=t.map((i)=>i.slice(2));let r=[],o=3,s=0.4;if(t.forEach((i)=>{if(i.length<=1)return;let a=FAe(e,i),c=Math.max(e.length,i.length);if((c-a)/c>s){if(a<o)o=a,r=[i];else if(a===o)r.push(i)}}),r.sort((i,a)=>i.localeCompare(a)),n)r=r.map((i)=>`--${i}`);if(r.length>1)return`
|
|
15
15
|
(Did you mean one of ${r.join(", ")}?)`;if(r.length===1)return`
|
|
16
|
-
(Did you mean ${r[0]}?)`;return""}jAe.suggestSimilar=MAe});var cq=w(function(VAe){var qAe=Nt("events").EventEmitter,Up=Nt("child_process"),xr=Nt("path"),Hp=Nt("fs"),
|
|
16
|
+
(Did you mean ${r[0]}?)`;return""}jAe.suggestSimilar=MAe});var cq=w(function(VAe){var qAe=Nt("events").EventEmitter,Up=Nt("child_process"),xr=Nt("path"),Hp=Nt("fs"),Qe=Nt("process"),{Argument:BAe,humanReadableArgName:UAe}=W_(),{CommanderError:gC}=Dy(),{Help:HAe}=mC(),{Option:sq,DualOptions:zAe}=hC(),{suggestSimilar:iq}=oq();class yC extends qAe{constructor(e){super();this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._outputConfiguration={writeOut:(t)=>Qe.stdout.write(t),writeErr:(t)=>Qe.stderr.write(t),getOutHelpWidth:()=>Qe.stdout.isTTY?Qe.stdout.columns:void 0,getErrHelpWidth:()=>Qe.stderr.isTTY?Qe.stderr.columns:void 0,outputError:(t,n)=>n(t)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._helpOption=e._helpOption,this._helpCommand=e._helpCommand,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let t=this;t;t=t.parent)e.push(t);return e}command(e,t,n){let r=t,o=n;if(typeof r==="object"&&r!==null)o=r,r=null;o=o||{};let[,s,i]=e.match(/([^ ]+) *(.*)/),a=this.createCommand(s);if(r)a.description(r),a._executableHandler=!0;if(o.isDefault)this._defaultCommandName=a._name;if(a._hidden=!!(o.noHelp||o.hidden),a._executableFile=o.executableFile||null,i)a.arguments(i);if(this._registerCommand(a),a.parent=this,a.copyInheritedSettings(this),r)return this;return a}createCommand(e){return new yC(e)}createHelp(){return Object.assign(new HAe,this.configureHelp())}configureHelp(e){if(e===void 0)return this._helpConfiguration;return this._helpConfiguration=e,this}configureOutput(e){if(e===void 0)return this._outputConfiguration;return Object.assign(this._outputConfiguration,e),this}showHelpAfterError(e=!0){if(typeof e!=="string")e=!!e;return this._showHelpAfterError=e,this}showSuggestionAfterError(e=!0){return this._showSuggestionAfterError=!!e,this}addCommand(e,t){if(!e._name)throw Error(`Command passed to .addCommand() must have a name
|
|
17
17
|
- specify the name in Command constructor or using .name()`);if(t=t||{},t.isDefault)this._defaultCommandName=e._name;if(t.noHelp||t.hidden)e._hidden=!0;return this._registerCommand(e),e.parent=this,e._checkForBrokenPassThrough(),this}createArgument(e,t){return new BAe(e,t)}argument(e,t,n,r){let o=this.createArgument(e,t);if(typeof n==="function")o.default(r).argParser(n);else o.default(n);return this.addArgument(o),this}arguments(e){return e.trim().split(/ +/).forEach((t)=>{this.argument(t)}),this}addArgument(e){let t=this.registeredArguments.slice(-1)[0];if(t&&t.variadic)throw Error(`only the last argument can be variadic '${t.name()}'`);if(e.required&&e.defaultValue!==void 0&&e.parseArg===void 0)throw Error(`a default value for a required argument is never used: '${e.name()}'`);return this.registeredArguments.push(e),this}helpCommand(e,t){if(typeof e==="boolean")return this._addImplicitHelpCommand=e,this;e=e??"help [command]";let[,n,r]=e.match(/([^ ]+) *(.*)/),o=t??"display help for command",s=this.createCommand(n);if(s.helpOption(!1),r)s.arguments(r);if(o)s.description(o);return this._addImplicitHelpCommand=!0,this._helpCommand=s,this}addHelpCommand(e,t){if(typeof e!=="object")return this.helpCommand(e,t),this;return this._addImplicitHelpCommand=!0,this._helpCommand=e,this}_getHelpCommand(){if(this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))){if(this._helpCommand===void 0)this.helpCommand(void 0,void 0);return this._helpCommand}return null}hook(e,t){let n=["preSubcommand","preAction","postAction"];if(!n.includes(e))throw Error(`Unexpected value for event passed to hook : '${e}'.
|
|
18
|
-
Expecting one of '${n.join("', '")}'`);if(this._lifeCycleHooks[e])this._lifeCycleHooks[e].push(t);else this._lifeCycleHooks[e]=[t];return this}exitOverride(e){if(e)this._exitCallback=e;else this._exitCallback=(t)=>{if(t.code!=="commander.executeSubCommandAsync")throw t};return this}_exit(e,t,n){if(this._exitCallback)this._exitCallback(new gC(e,t,n));
|
|
19
|
-
- already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=(r)=>[r.name()].concat(r.aliases()),n=t(e).find((r)=>this._findCommand(r));if(n){let r=t(this._findCommand(n)).join("|"),o=t(e).join("|");throw Error(`cannot add command '${o}' as already have command '${r}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();if(e.negate){let o=e.long.replace(/^--no-/,"--");if(!this._findOption(o))this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else if(e.defaultValue!==void 0)this.setOptionValueWithSource(n,e.defaultValue,"default");let r=(o,s,i)=>{if(o==null&&e.presetArg!==void 0)o=e.presetArg;let a=this.getOptionValue(n);if(o!==null&&e.parseArg)o=this._callParseArg(e,o,a,s);else if(o!==null&&e.variadic)o=e._concatValue(o,a);if(o==null)if(e.negate)o=!1;else if(e.isBoolean()||e.optional)o=!0;else o="";this.setOptionValueWithSource(n,o,i)};if(this.on("option:"+t,(o)=>{let s=`error: option '${e.flags}' argument '${o}' is invalid.`;r(o,s,"cli")}),e.envVar)this.on("optionEnv:"+t,(o)=>{let s=`error: option '${e.flags}' value '${o}' from env '${e.envVar}' is invalid.`;r(o,s,"env")});return this}_optionEx(e,t,n,r,o){if(typeof t==="object"&&t instanceof sq)throw Error("To add an Option object use addOption() instead of option() or requiredOption()");let s=this.createOption(t,n);if(s.makeOptionMandatory(!!e.mandatory),typeof r==="function")s.default(o).argParser(r);else if(r instanceof RegExp){let i=r;r=(a,c)=>{let l=i.exec(a);return l?l[0]:c},s.default(o).argParser(r)}else s.default(r);return this.addOption(s)}option(e,t,n,r){return this._optionEx({},e,t,n,r)}requiredOption(e,t,n,r){return this._optionEx({mandatory:!0},e,t,n,r)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){if(this._storeOptionsAsProperties)return this[e];return this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,n){if(this._storeOptionsAsProperties)this[e]=t;else this._optionValues[e]=t;return this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach((n)=>{if(n.getOptionValueSource(e)!==void 0)t=n.getOptionValueSource(e)}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){if(
|
|
18
|
+
Expecting one of '${n.join("', '")}'`);if(this._lifeCycleHooks[e])this._lifeCycleHooks[e].push(t);else this._lifeCycleHooks[e]=[t];return this}exitOverride(e){if(e)this._exitCallback=e;else this._exitCallback=(t)=>{if(t.code!=="commander.executeSubCommandAsync")throw t};return this}_exit(e,t,n){if(this._exitCallback)this._exitCallback(new gC(e,t,n));Qe.exit(e)}action(e){let t=(n)=>{let r=this.registeredArguments.length,o=n.slice(0,r);if(this._storeOptionsAsProperties)o[r]=this;else o[r]=this.opts();return o.push(this),e.apply(this,o)};return this._actionHandler=t,this}createOption(e,t){return new sq(e,t)}_callParseArg(e,t,n,r){try{return e.parseArg(t,n)}catch(o){if(o.code==="commander.invalidArgument"){let s=`${r} ${o.message}`;this.error(s,{exitCode:o.exitCode,code:o.code})}throw o}}_registerOption(e){let t=e.short&&this._findOption(e.short)||e.long&&this._findOption(e.long);if(t){let n=e.long&&this._findOption(e.long)?e.long:e.short;throw Error(`Cannot add option '${e.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}'
|
|
19
|
+
- already used by option '${t.flags}'`)}this.options.push(e)}_registerCommand(e){let t=(r)=>[r.name()].concat(r.aliases()),n=t(e).find((r)=>this._findCommand(r));if(n){let r=t(this._findCommand(n)).join("|"),o=t(e).join("|");throw Error(`cannot add command '${o}' as already have command '${r}'`)}this.commands.push(e)}addOption(e){this._registerOption(e);let t=e.name(),n=e.attributeName();if(e.negate){let o=e.long.replace(/^--no-/,"--");if(!this._findOption(o))this.setOptionValueWithSource(n,e.defaultValue===void 0?!0:e.defaultValue,"default")}else if(e.defaultValue!==void 0)this.setOptionValueWithSource(n,e.defaultValue,"default");let r=(o,s,i)=>{if(o==null&&e.presetArg!==void 0)o=e.presetArg;let a=this.getOptionValue(n);if(o!==null&&e.parseArg)o=this._callParseArg(e,o,a,s);else if(o!==null&&e.variadic)o=e._concatValue(o,a);if(o==null)if(e.negate)o=!1;else if(e.isBoolean()||e.optional)o=!0;else o="";this.setOptionValueWithSource(n,o,i)};if(this.on("option:"+t,(o)=>{let s=`error: option '${e.flags}' argument '${o}' is invalid.`;r(o,s,"cli")}),e.envVar)this.on("optionEnv:"+t,(o)=>{let s=`error: option '${e.flags}' value '${o}' from env '${e.envVar}' is invalid.`;r(o,s,"env")});return this}_optionEx(e,t,n,r,o){if(typeof t==="object"&&t instanceof sq)throw Error("To add an Option object use addOption() instead of option() or requiredOption()");let s=this.createOption(t,n);if(s.makeOptionMandatory(!!e.mandatory),typeof r==="function")s.default(o).argParser(r);else if(r instanceof RegExp){let i=r;r=(a,c)=>{let l=i.exec(a);return l?l[0]:c},s.default(o).argParser(r)}else s.default(r);return this.addOption(s)}option(e,t,n,r){return this._optionEx({},e,t,n,r)}requiredOption(e,t,n,r){return this._optionEx({mandatory:!0},e,t,n,r)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){return this._passThroughOptions=!!e,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(e=!0){if(this.options.length)throw Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!e,this}getOptionValue(e){if(this._storeOptionsAsProperties)return this[e];return this._optionValues[e]}setOptionValue(e,t){return this.setOptionValueWithSource(e,t,void 0)}setOptionValueWithSource(e,t,n){if(this._storeOptionsAsProperties)this[e]=t;else this._optionValues[e]=t;return this._optionValueSources[e]=n,this}getOptionValueSource(e){return this._optionValueSources[e]}getOptionValueSourceWithGlobals(e){let t;return this._getCommandAndAncestors().forEach((n)=>{if(n.getOptionValueSource(e)!==void 0)t=n.getOptionValueSource(e)}),t}_prepareUserArgs(e,t){if(e!==void 0&&!Array.isArray(e))throw Error("first parameter to parse must be array or undefined");if(t=t||{},e===void 0&&t.from===void 0){if(Qe.versions?.electron)t.from="electron";let r=Qe.execArgv??[];if(r.includes("-e")||r.includes("--eval")||r.includes("-p")||r.includes("--print"))t.from="eval"}if(e===void 0)e=Qe.argv;this.rawArgs=e.slice();let n;switch(t.from){case void 0:case"node":this._scriptPath=e[1],n=e.slice(2);break;case"electron":if(Qe.defaultApp)this._scriptPath=e[1],n=e.slice(2);else n=e.slice(1);break;case"user":n=e.slice(0);break;case"eval":n=e.slice(1);break;default:throw Error(`unexpected parse option { from: '${t.from}' }`)}if(!this._name&&this._scriptPath)this.nameFromFilename(this._scriptPath);return this._name=this._name||"program",n}parse(e,t){let n=this._prepareUserArgs(e,t);return this._parseCommand([],n),this}async parseAsync(e,t){let n=this._prepareUserArgs(e,t);return await this._parseCommand([],n),this}_executeSubCommand(e,t){t=t.slice();let n=!1,r=[".js",".ts",".tsx",".mjs",".cjs"];function o(l,d){let f=xr.resolve(l,d);if(Hp.existsSync(f))return f;if(r.includes(xr.extname(d)))return;let p=r.find((m)=>Hp.existsSync(`${f}${m}`));if(p)return`${f}${p}`;return}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=e._executableFile||`${this._name}-${e._name}`,i=this._executableDir||"";if(this._scriptPath){let l;try{l=Hp.realpathSync(this._scriptPath)}catch(d){l=this._scriptPath}i=xr.resolve(xr.dirname(l),i)}if(i){let l=o(i,s);if(!l&&!e._executableFile&&this._scriptPath){let d=xr.basename(this._scriptPath,xr.extname(this._scriptPath));if(d!==this._name)l=o(i,`${d}-${e._name}`)}s=l||s}n=r.includes(xr.extname(s));let a;if(Qe.platform!=="win32")if(n)t.unshift(s),t=aq(Qe.execArgv).concat(t),a=Up.spawn(Qe.argv[0],t,{stdio:"inherit"});else a=Up.spawn(s,t,{stdio:"inherit"});else t.unshift(s),t=aq(Qe.execArgv).concat(t),a=Up.spawn(Qe.execPath,t,{stdio:"inherit"});if(!a.killed)["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach((d)=>{Qe.on(d,()=>{if(a.killed===!1&&a.exitCode===null)a.kill(d)})});let c=this._exitCallback;a.on("close",(l)=>{if(l=l??1,!c)Qe.exit(l);else c(new gC(l,"commander.executeSubCommandAsync","(close)"))}),a.on("error",(l)=>{if(l.code==="ENOENT"){let d=i?`searched for local subcommand relative to directory '${i}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",f=`'${s}' does not exist
|
|
20
20
|
- if '${e._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
21
21
|
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
22
|
-
- ${d}`;throw Error(f)}else if(l.code==="EACCES")throw Error(`'${s}' not executable`);if(!c)
|
|
22
|
+
- ${d}`;throw Error(f)}else if(l.code==="EACCES")throw Error(`'${s}' not executable`);if(!c)Qe.exit(1);else{let d=new gC(1,"commander.executeSubCommandAsync","(error)");d.nestedError=l,c(d)}}),this.runningCommand=a}_dispatchSubcommand(e,t,n){let r=this._findCommand(e);if(!r)this.help({error:!0});let o;return o=this._chainOrCallSubCommandHook(o,r,"preSubcommand"),o=this._chainOrCall(o,()=>{if(r._executableHandler)this._executeSubCommand(r,t.concat(n));else return r._parseCommand(t,n)}),o}_dispatchHelpCommand(e){if(!e)this.help();let t=this._findCommand(e);if(t&&!t._executableHandler)t.help();return this._dispatchSubcommand(e,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){if(this.registeredArguments.forEach((e,t)=>{if(e.required&&this.args[t]==null)this.missingArgument(e.name())}),this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)return;if(this.args.length>this.registeredArguments.length)this._excessArguments(this.args)}_processArguments(){let e=(n,r,o)=>{let s=r;if(r!==null&&n.parseArg){let i=`error: command-argument value '${r}' is invalid for argument '${n.name()}'.`;s=this._callParseArg(n,r,o,i)}return s};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,r)=>{let o=n.defaultValue;if(n.variadic){if(r<this.args.length){if(o=this.args.slice(r),n.parseArg)o=o.reduce((s,i)=>e(n,i,s),n.defaultValue)}else if(o===void 0)o=[]}else if(r<this.args.length){if(o=this.args[r],n.parseArg)o=e(n,o,n.defaultValue)}t[r]=o}),this.processedArgs=t}_chainOrCall(e,t){if(e&&e.then&&typeof e.then==="function")return e.then(()=>t());return t()}_chainOrCallHooks(e,t){let n=e,r=[];if(this._getCommandAndAncestors().reverse().filter((o)=>o._lifeCycleHooks[t]!==void 0).forEach((o)=>{o._lifeCycleHooks[t].forEach((s)=>{r.push({hookedCommand:o,callback:s})})}),t==="postAction")r.reverse();return r.forEach((o)=>{n=this._chainOrCall(n,()=>o.callback(o.hookedCommand,this))}),n}_chainOrCallSubCommandHook(e,t,n){let r=e;if(this._lifeCycleHooks[n]!==void 0)this._lifeCycleHooks[n].forEach((o)=>{r=this._chainOrCall(r,()=>o(this,t))});return r}_parseCommand(e,t){let n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),e=e.concat(n.operands),t=n.unknown,this.args=e.concat(t),e&&this._findCommand(e[0]))return this._dispatchSubcommand(e[0],e.slice(1),t);if(this._getHelpCommand()&&e[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(e[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,e,t);if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName)this.help({error:!0});this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=()=>{if(n.unknown.length>0)this.unknownOption(n.unknown[0])},o=`command:${this.name()}`;if(this._actionHandler){r(),this._processArguments();let s;if(s=this._chainOrCallHooks(s,"preAction"),s=this._chainOrCall(s,()=>this._actionHandler(this.processedArgs)),this.parent)s=this._chainOrCall(s,()=>{this.parent.emit(o,e,t)});return s=this._chainOrCallHooks(s,"postAction"),s}if(this.parent&&this.parent.listenerCount(o))r(),this._processArguments(),this.parent.emit(o,e,t);else if(e.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",e,t);if(this.listenerCount("command:*"))this.emit("command:*",e,t);else if(this.commands.length)this.unknownCommand();else r(),this._processArguments()}else if(this.commands.length)r(),this.help({error:!0});else r(),this._processArguments()}_findCommand(e){if(!e)return;return this.commands.find((t)=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find((t)=>t.is(e))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach((e)=>{e.options.forEach((t)=>{if(t.mandatory&&e.getOptionValue(t.attributeName())===void 0)e.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let e=this.options.filter((n)=>{let r=n.attributeName();if(this.getOptionValue(r)===void 0)return!1;return this.getOptionValueSource(r)!=="default"});e.filter((n)=>n.conflictsWith.length>0).forEach((n)=>{let r=e.find((o)=>n.conflictsWith.includes(o.attributeName()));if(r)this._conflictingOption(n,r)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach((e)=>{e._checkForConflictingLocalOptions()})}parseOptions(e){let t=[],n=[],r=t,o=e.slice();function s(a){return a.length>1&&a[0]==="-"}let i=null;while(o.length){let a=o.shift();if(a==="--"){if(r===n)r.push(a);r.push(...o);break}if(i&&!s(a)){this.emit(`option:${i.name()}`,a);continue}if(i=null,s(a)){let c=this._findOption(a);if(c){if(c.required){let l=o.shift();if(l===void 0)this.optionMissingArgument(c);this.emit(`option:${c.name()}`,l)}else if(c.optional){let l=null;if(o.length>0&&!s(o[0]))l=o.shift();this.emit(`option:${c.name()}`,l)}else this.emit(`option:${c.name()}`);i=c.variadic?c:null;continue}}if(a.length>2&&a[0]==="-"&&a[1]!=="-"){let c=this._findOption(`-${a[1]}`);if(c){if(c.required||c.optional&&this._combineFlagAndOptionalValue)this.emit(`option:${c.name()}`,a.slice(2));else this.emit(`option:${c.name()}`),o.unshift(`-${a.slice(2)}`);continue}}if(/^--[^=]+=/.test(a)){let c=a.indexOf("="),l=this._findOption(a.slice(0,c));if(l&&(l.required||l.optional)){this.emit(`option:${l.name()}`,a.slice(c+1));continue}}if(s(a))r=n;if((this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(a)){if(t.push(a),o.length>0)n.push(...o);break}else if(this._getHelpCommand()&&a===this._getHelpCommand().name()){if(t.push(a),o.length>0)t.push(...o);break}else if(this._defaultCommandName){if(n.push(a),o.length>0)n.push(...o);break}}if(this._passThroughOptions){if(r.push(a),o.length>0)r.push(...o);break}r.push(a)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let e={},t=this.options.length;for(let n=0;n<t;n++){let r=this.options[n].attributeName();e[r]=r===this._versionOptionName?this._version:this[r]}return e}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((e,t)=>Object.assign(e,t.opts()),{})}error(e,t){if(this._outputConfiguration.outputError(`${e}
|
|
23
23
|
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError==="string")this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
24
24
|
`);else if(this._showHelpAfterError)this._outputConfiguration.writeErr(`
|
|
25
|
-
`),this.outputHelp({error:!0});let n=t||{},r=n.exitCode||1,o=n.code||"commander.error";this._exit(r,o,e)}_parseOptionsEnv(){this.options.forEach((e)=>{if(e.envVar&&e.envVar in
|
|
26
|
-
`),this._exit(0,"commander.version",e)}),this}description(e,t){if(e===void 0&&t===void 0)return this._description;if(this._description=e,t)this._argsDescription=t;return this}summary(e){if(e===void 0)return this._summary;return this._summary=e,this}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)t=this.commands[this.commands.length-1];if(e===t._name)throw Error("Command alias can't be the same as its name");let n=this.parent?._findCommand(e);if(n){let r=[n.name()].concat(n.aliases()).join("|");throw Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${r}'`)}return t._aliases.push(e),this}aliases(e){if(e===void 0)return this._aliases;return e.forEach((t)=>this.alias(t)),this}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map((n)=>UAe(n));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){if(e===void 0)return this._name;return this._name=e,this}nameFromFilename(e){return this._name=xr.basename(e,xr.extname(e)),this}executableDir(e){if(e===void 0)return this._executableDir;return this._executableDir=e,this}helpInformation(e){let t=this.createHelp();if(t.helpWidth===void 0)t.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth();return t.formatHelp(this,t)}_getHelpContext(e){e=e||{};let t={error:!!e.error},n;if(t.error)n=(r)=>this._outputConfiguration.writeErr(r);else n=(r)=>this._outputConfiguration.writeOut(r);return t.write=e.write||n,t.command=this,t}outputHelp(e){let t;if(typeof e==="function")t=e,e=void 0;let n=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach((o)=>o.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let r=this.helpInformation(n);if(t){if(r=t(r),typeof r!=="string"&&!Buffer.isBuffer(r))throw Error("outputHelp callback must return a string or a Buffer")}if(n.write(r),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",n),this._getCommandAndAncestors().forEach((o)=>o.emit("afterAllHelp",n))}helpOption(e,t){if(typeof e==="boolean"){if(e)this._helpOption=this._helpOption??void 0;else this._helpOption=null;return this}return e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),this}_getHelpOption(){if(this._helpOption===void 0)this.helpOption(void 0,void 0);return this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let t=
|
|
25
|
+
`),this.outputHelp({error:!0});let n=t||{},r=n.exitCode||1,o=n.code||"commander.error";this._exit(r,o,e)}_parseOptionsEnv(){this.options.forEach((e)=>{if(e.envVar&&e.envVar in Qe.env){let t=e.attributeName();if(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))if(e.required||e.optional)this.emit(`optionEnv:${e.name()}`,Qe.env[e.envVar]);else this.emit(`optionEnv:${e.name()}`)}})}_parseOptionsImplied(){let e=new zAe(this.options),t=(n)=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter((n)=>n.implied!==void 0&&t(n.attributeName())&&e.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach((n)=>{Object.keys(n.implied).filter((r)=>!t(r)).forEach((r)=>{this.setOptionValueWithSource(r,n.implied[r],"implied")})})}missingArgument(e){let t=`error: missing required argument '${e}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(e){let t=`error: option '${e.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(e){let t=`error: required option '${e.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(e,t){let n=(s)=>{let i=s.attributeName(),a=this.getOptionValue(i),c=this.options.find((d)=>d.negate&&i===d.attributeName()),l=this.options.find((d)=>!d.negate&&i===d.attributeName());if(c&&(c.presetArg===void 0&&a===!1||c.presetArg!==void 0&&a===c.presetArg))return c;return l||s},r=(s)=>{let i=n(s),a=i.attributeName();if(this.getOptionValueSource(a)==="env")return`environment variable '${i.envVar}'`;return`option '${i.flags}'`},o=`error: ${r(e)} cannot be used with ${r(t)}`;this.error(o,{code:"commander.conflictingOption"})}unknownOption(e){if(this._allowUnknownOption)return;let t="";if(e.startsWith("--")&&this._showSuggestionAfterError){let r=[],o=this;do{let s=o.createHelp().visibleOptions(o).filter((i)=>i.long).map((i)=>i.long);r=r.concat(s),o=o.parent}while(o&&!o._enablePositionalOptions);t=iq(e,r)}let n=`error: unknown option '${e}'${t}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(e){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,n=t===1?"":"s",o=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${n} but got ${e.length}.`;this.error(o,{code:"commander.excessArguments"})}unknownCommand(){let e=this.args[0],t="";if(this._showSuggestionAfterError){let r=[];this.createHelp().visibleCommands(this).forEach((o)=>{if(r.push(o.name()),o.alias())r.push(o.alias())}),t=iq(e,r)}let n=`error: unknown command '${e}'${t}`;this.error(n,{code:"commander.unknownCommand"})}version(e,t,n){if(e===void 0)return this._version;this._version=e,t=t||"-V, --version",n=n||"output the version number";let r=this.createOption(t,n);return this._versionOptionName=r.attributeName(),this._registerOption(r),this.on("option:"+r.name(),()=>{this._outputConfiguration.writeOut(`${e}
|
|
26
|
+
`),this._exit(0,"commander.version",e)}),this}description(e,t){if(e===void 0&&t===void 0)return this._description;if(this._description=e,t)this._argsDescription=t;return this}summary(e){if(e===void 0)return this._summary;return this._summary=e,this}alias(e){if(e===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler)t=this.commands[this.commands.length-1];if(e===t._name)throw Error("Command alias can't be the same as its name");let n=this.parent?._findCommand(e);if(n){let r=[n.name()].concat(n.aliases()).join("|");throw Error(`cannot add alias '${e}' to command '${this.name()}' as already have command '${r}'`)}return t._aliases.push(e),this}aliases(e){if(e===void 0)return this._aliases;return e.forEach((t)=>this.alias(t)),this}usage(e){if(e===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map((n)=>UAe(n));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=e,this}name(e){if(e===void 0)return this._name;return this._name=e,this}nameFromFilename(e){return this._name=xr.basename(e,xr.extname(e)),this}executableDir(e){if(e===void 0)return this._executableDir;return this._executableDir=e,this}helpInformation(e){let t=this.createHelp();if(t.helpWidth===void 0)t.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth();return t.formatHelp(this,t)}_getHelpContext(e){e=e||{};let t={error:!!e.error},n;if(t.error)n=(r)=>this._outputConfiguration.writeErr(r);else n=(r)=>this._outputConfiguration.writeOut(r);return t.write=e.write||n,t.command=this,t}outputHelp(e){let t;if(typeof e==="function")t=e,e=void 0;let n=this._getHelpContext(e);this._getCommandAndAncestors().reverse().forEach((o)=>o.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let r=this.helpInformation(n);if(t){if(r=t(r),typeof r!=="string"&&!Buffer.isBuffer(r))throw Error("outputHelp callback must return a string or a Buffer")}if(n.write(r),this._getHelpOption()?.long)this.emit(this._getHelpOption().long);this.emit("afterHelp",n),this._getCommandAndAncestors().forEach((o)=>o.emit("afterAllHelp",n))}helpOption(e,t){if(typeof e==="boolean"){if(e)this._helpOption=this._helpOption??void 0;else this._helpOption=null;return this}return e=e??"-h, --help",t=t??"display help for command",this._helpOption=this.createOption(e,t),this}_getHelpOption(){if(this._helpOption===void 0)this.helpOption(void 0,void 0);return this._helpOption}addHelpOption(e){return this._helpOption=e,this}help(e){this.outputHelp(e);let t=Qe.exitCode||0;if(t===0&&e&&typeof e!=="function"&&e.error)t=1;this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){let n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw Error(`Unexpected value for position to addHelpText.
|
|
27
27
|
Expecting one of '${n.join("', '")}'`);let r=`${e}Help`;return this.on(r,(o)=>{let s;if(typeof t==="function")s=t({error:o.error,command:o.command});else s=t;if(s)o.write(`${s}
|
|
28
28
|
`)}),this}_outputHelpIfRequested(e){let t=this._getHelpOption();if(t&&e.find((r)=>t.is(r)))this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)")}}function aq(e){return e.map((t)=>{if(!t.startsWith("--inspect"))return t;let n,r="127.0.0.1",o="9229",s;if((s=t.match(/^(--inspect(-brk)?)$/))!==null)n=s[1];else if((s=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null)if(n=s[1],/^\d+$/.test(s[3]))o=s[3];else r=s[3];else if((s=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null)n=s[1],r=s[3],o=s[4];if(n&&o!=="0")return`${n}=${r}:${parseInt(o)+1}`;return t})}VAe.Command=yC});var gs={};L3(gs,{default:()=>Cq},{default:(DNt)=>Cq=DNt});var Et,Cq,Kt="\x1B[",Cy="\x1B]",Vp="\x07",J_=";",Dq;var Ay=V(()=>{Et=gs;Cq=Et;Dq=process.env.TERM_PROGRAM==="Apple_Terminal";Et.cursorTo=(e,t)=>{if(typeof e!=="number")throw TypeError("The `x` argument is required");if(typeof t!=="number")return Kt+(e+1)+"G";return Kt+(t+1)+";"+(e+1)+"H"};Et.cursorMove=(e,t)=>{if(typeof e!=="number")throw TypeError("The `x` argument is required");let n="";if(e<0)n+=Kt+-e+"D";else if(e>0)n+=Kt+e+"C";if(t<0)n+=Kt+-t+"A";else if(t>0)n+=Kt+t+"B";return n};Et.cursorUp=(e=1)=>Kt+e+"A";Et.cursorDown=(e=1)=>Kt+e+"B";Et.cursorForward=(e=1)=>Kt+e+"C";Et.cursorBackward=(e=1)=>Kt+e+"D";Et.cursorLeft=Kt+"G";Et.cursorSavePosition=Dq?"\x1B7":Kt+"s";Et.cursorRestorePosition=Dq?"\x1B8":Kt+"u";Et.cursorGetPosition=Kt+"6n";Et.cursorNextLine=Kt+"E";Et.cursorPrevLine=Kt+"F";Et.cursorHide=Kt+"?25l";Et.cursorShow=Kt+"?25h";Et.eraseLines=(e)=>{let t="";for(let n=0;n<e;n++)t+=Et.eraseLine+(n<e-1?Et.cursorUp():"");if(e)t+=Et.cursorLeft;return t};Et.eraseEndLine=Kt+"K";Et.eraseStartLine=Kt+"1K";Et.eraseLine=Kt+"2K";Et.eraseDown=Kt+"J";Et.eraseUp=Kt+"1J";Et.eraseScreen=Kt+"2J";Et.scrollUp=Kt+"S";Et.scrollDown=Kt+"T";Et.clearScreen="\x1Bc";Et.clearTerminal=process.platform==="win32"?`${Et.eraseScreen}${Kt}0f`:`${Et.eraseScreen}${Kt}3J${Kt}H`;Et.beep=Vp;Et.link=(e,t)=>[Cy,"8",J_,J_,t,Vp,e,Cy,"8",J_,J_,Vp].join("");Et.image=(e,t={})=>{let n=`${Cy}1337;File=inline=1`;if(t.width)n+=`;width=${t.width}`;if(t.height)n+=`;height=${t.height}`;if(t.preserveAspectRatio===!1)n+=";preserveAspectRatio=0";return n+":"+e.toString("base64")+Vp};Et.iTerm={setCwd:(e=process.cwd())=>`${Cy}50;CurrentDir=${e}${Vp}`,annotation:(e,t={})=>{let n=`${Cy}1337;`,r=typeof t.x<"u",o=typeof t.y<"u";if((r||o)&&!(r&&o&&typeof t.length<"u"))throw Error("`x`, `y` and `length` must be defined when `x` or `y` is defined");if(e=e.replace(/\|/g,""),n+=t.isHidden?"AddHiddenAnnotation=":"AddAnnotation=",t.length>0)n+=(r?[e,t.length,t.x,t.y]:[t.length,e]).join("|");else n+=e;return n+Vp}}});var js=w(function(RNt,Aq){var XAe=Nt("tty"),QAe=XAe?.WriteStream?.prototype?.hasColors?.()??!1,mt=(e,t)=>{if(!QAe)return(o)=>o;let n=`\x1B[${e}m`,r=`\x1B[${t}m`;return(o)=>{let s=o+"",i=s.indexOf(r);if(i===-1)return n+s+r;let a=n,c=0,d=(t===22?r:"")+n;while(i!==-1)a+=s.slice(c,i)+d,c=i+r.length,i=s.indexOf(r,c);return a+=s.slice(c)+r,a}},st={};st.reset=mt(0,0);st.bold=mt(1,22);st.dim=mt(2,22);st.italic=mt(3,23);st.underline=mt(4,24);st.overline=mt(53,55);st.inverse=mt(7,27);st.hidden=mt(8,28);st.strikethrough=mt(9,29);st.black=mt(30,39);st.red=mt(31,39);st.green=mt(32,39);st.yellow=mt(33,39);st.blue=mt(34,39);st.magenta=mt(35,39);st.cyan=mt(36,39);st.white=mt(37,39);st.gray=mt(90,39);st.bgBlack=mt(40,49);st.bgRed=mt(41,49);st.bgGreen=mt(42,49);st.bgYellow=mt(43,49);st.bgBlue=mt(44,49);st.bgMagenta=mt(45,49);st.bgCyan=mt(46,49);st.bgWhite=mt(47,49);st.bgGray=mt(100,49);st.redBright=mt(91,39);st.greenBright=mt(92,39);st.yellowBright=mt(93,39);st.blueBright=mt(94,39);st.magentaBright=mt(95,39);st.cyanBright=mt(96,39);st.whiteBright=mt(97,39);st.bgRedBright=mt(101,49);st.bgGreenBright=mt(102,49);st.bgYellowBright=mt(103,49);st.bgBlueBright=mt(104,49);st.bgMagentaBright=mt(105,49);st.bgCyanBright=mt(106,49);st.bgWhiteBright=mt(107,49);Aq.exports=st});import na from"process";function ZAe(){if(na.platform!=="win32")return na.env.TERM!=="linux";return Boolean(na.env.WT_SESSION)||Boolean(na.env.TERMINUS_SUBLIME)||na.env.ConEmuTask==="{cmd::Cmder}"||na.env.TERM_PROGRAM==="Terminus-Sublime"||na.env.TERM_PROGRAM==="vscode"||na.env.TERM==="xterm-256color"||na.env.TERM==="alacritty"||na.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var Oq,Tq,e2e,t2e,n2e,r2e,o2e,ql,ANt;var Y_=V(()=>{Oq={circleQuestionMark:"(?)",questionMarkPrefix:"(?)",square:"\u2588",squareDarkShade:"\u2593",squareMediumShade:"\u2592",squareLightShade:"\u2591",squareTop:"\u2580",squareBottom:"\u2584",squareLeft:"\u258C",squareRight:"\u2590",squareCenter:"\u25A0",bullet:"\u25CF",dot:"\u2024",ellipsis:"\u2026",pointerSmall:"\u203A",triangleUp:"\u25B2",triangleUpSmall:"\u25B4",triangleDown:"\u25BC",triangleDownSmall:"\u25BE",triangleLeftSmall:"\u25C2",triangleRightSmall:"\u25B8",home:"\u2302",heart:"\u2665",musicNote:"\u266A",musicNoteBeamed:"\u266B",arrowUp:"\u2191",arrowDown:"\u2193",arrowLeft:"\u2190",arrowRight:"\u2192",arrowLeftRight:"\u2194",arrowUpDown:"\u2195",almostEqual:"\u2248",notEqual:"\u2260",lessOrEqual:"\u2264",greaterOrEqual:"\u2265",identical:"\u2261",infinity:"\u221E",subscriptZero:"\u2080",subscriptOne:"\u2081",subscriptTwo:"\u2082",subscriptThree:"\u2083",subscriptFour:"\u2084",subscriptFive:"\u2085",subscriptSix:"\u2086",subscriptSeven:"\u2087",subscriptEight:"\u2088",subscriptNine:"\u2089",oneHalf:"\xBD",oneThird:"\u2153",oneQuarter:"\xBC",oneFifth:"\u2155",oneSixth:"\u2159",oneEighth:"\u215B",twoThirds:"\u2154",twoFifths:"\u2156",threeQuarters:"\xBE",threeFifths:"\u2157",threeEighths:"\u215C",fourFifths:"\u2158",fiveSixths:"\u215A",fiveEighths:"\u215D",sevenEighths:"\u215E",line:"\u2500",lineBold:"\u2501",lineDouble:"\u2550",lineDashed0:"\u2504",lineDashed1:"\u2505",lineDashed2:"\u2508",lineDashed3:"\u2509",lineDashed4:"\u254C",lineDashed5:"\u254D",lineDashed6:"\u2574",lineDashed7:"\u2576",lineDashed8:"\u2578",lineDashed9:"\u257A",lineDashed10:"\u257C",lineDashed11:"\u257E",lineDashed12:"\u2212",lineDashed13:"\u2013",lineDashed14:"\u2010",lineDashed15:"\u2043",lineVertical:"\u2502",lineVerticalBold:"\u2503",lineVerticalDouble:"\u2551",lineVerticalDashed0:"\u2506",lineVerticalDashed1:"\u2507",lineVerticalDashed2:"\u250A",lineVerticalDashed3:"\u250B",lineVerticalDashed4:"\u254E",lineVerticalDashed5:"\u254F",lineVerticalDashed6:"\u2575",lineVerticalDashed7:"\u2577",lineVerticalDashed8:"\u2579",lineVerticalDashed9:"\u257B",lineVerticalDashed10:"\u257D",lineVerticalDashed11:"\u257F",lineDownLeft:"\u2510",lineDownLeftArc:"\u256E",lineDownBoldLeftBold:"\u2513",lineDownBoldLeft:"\u2512",lineDownLeftBold:"\u2511",lineDownDoubleLeftDouble:"\u2557",lineDownDoubleLeft:"\u2556",lineDownLeftDouble:"\u2555",lineDownRight:"\u250C",lineDownRightArc:"\u256D",lineDownBoldRightBold:"\u250F",lineDownBoldRight:"\u250E",lineDownRightBold:"\u250D",lineDownDoubleRightDouble:"\u2554",lineDownDoubleRight:"\u2553",lineDownRightDouble:"\u2552",lineUpLeft:"\u2518",lineUpLeftArc:"\u256F",lineUpBoldLeftBold:"\u251B",lineUpBoldLeft:"\u251A",lineUpLeftBold:"\u2519",lineUpDoubleLeftDouble:"\u255D",lineUpDoubleLeft:"\u255C",lineUpLeftDouble:"\u255B",lineUpRight:"\u2514",lineUpRightArc:"\u2570",lineUpBoldRightBold:"\u2517",lineUpBoldRight:"\u2516",lineUpRightBold:"\u2515",lineUpDoubleRightDouble:"\u255A",lineUpDoubleRight:"\u2559",lineUpRightDouble:"\u2558",lineUpDownLeft:"\u2524",lineUpBoldDownBoldLeftBold:"\u252B",lineUpBoldDownBoldLeft:"\u2528",lineUpDownLeftBold:"\u2525",lineUpBoldDownLeftBold:"\u2529",lineUpDownBoldLeftBold:"\u252A",lineUpDownBoldLeft:"\u2527",lineUpBoldDownLeft:"\u2526",lineUpDoubleDownDoubleLeftDouble:"\u2563",lineUpDoubleDownDoubleLeft:"\u2562",lineUpDownLeftDouble:"\u2561",lineUpDownRight:"\u251C",lineUpBoldDownBoldRightBold:"\u2523",lineUpBoldDownBoldRight:"\u2520",lineUpDownRightBold:"\u251D",lineUpBoldDownRightBold:"\u2521",lineUpDownBoldRightBold:"\u2522",lineUpDownBoldRight:"\u251F",lineUpBoldDownRight:"\u251E",lineUpDoubleDownDoubleRightDouble:"\u2560",lineUpDoubleDownDoubleRight:"\u255F",lineUpDownRightDouble:"\u255E",lineDownLeftRight:"\u252C",lineDownBoldLeftBoldRightBold:"\u2533",lineDownLeftBoldRightBold:"\u252F",lineDownBoldLeftRight:"\u2530",lineDownBoldLeftBoldRight:"\u2531",lineDownBoldLeftRightBold:"\u2532",lineDownLeftRightBold:"\u252E",lineDownLeftBoldRight:"\u252D",lineDownDoubleLeftDoubleRightDouble:"\u2566",lineDownDoubleLeftRight:"\u2565",lineDownLeftDoubleRightDouble:"\u2564",lineUpLeftRight:"\u2534",lineUpBoldLeftBoldRightBold:"\u253B",lineUpLeftBoldRightBold:"\u2537",lineUpBoldLeftRight:"\u2538",lineUpBoldLeftBoldRight:"\u2539",lineUpBoldLeftRightBold:"\u253A",lineUpLeftRightBold:"\u2536",lineUpLeftBoldRight:"\u2535",lineUpDoubleLeftDoubleRightDouble:"\u2569",lineUpDoubleLeftRight:"\u2568",lineUpLeftDoubleRightDouble:"\u2567",lineUpDownLeftRight:"\u253C",lineUpBoldDownBoldLeftBoldRightBold:"\u254B",lineUpDownBoldLeftBoldRightBold:"\u2548",lineUpBoldDownLeftBoldRightBold:"\u2547",lineUpBoldDownBoldLeftRightBold:"\u254A",lineUpBoldDownBoldLeftBoldRight:"\u2549",lineUpBoldDownLeftRight:"\u2540",lineUpDownBoldLeftRight:"\u2541",lineUpDownLeftBoldRight:"\u253D",lineUpDownLeftRightBold:"\u253E",lineUpBoldDownBoldLeftRight:"\u2542",lineUpDownLeftBoldRightBold:"\u253F",lineUpBoldDownLeftBoldRight:"\u2543",lineUpBoldDownLeftRightBold:"\u2544",lineUpDownBoldLeftBoldRight:"\u2545",lineUpDownBoldLeftRightBold:"\u2546",lineUpDoubleDownDoubleLeftDoubleRightDouble:"\u256C",lineUpDoubleDownDoubleLeftRight:"\u256B",lineUpDownLeftDoubleRightDouble:"\u256A",lineCross:"\u2573",lineBackslash:"\u2572",lineSlash:"\u2571"},Tq={tick:"\u2714",info:"\u2139",warning:"\u26A0",cross:"\u2718",squareSmall:"\u25FB",squareSmallFilled:"\u25FC",circle:"\u25EF",circleFilled:"\u25C9",circleDotted:"\u25CC",circleDouble:"\u25CE",circleCircle:"\u24DE",circleCross:"\u24E7",circlePipe:"\u24BE",radioOn:"\u25C9",radioOff:"\u25EF",checkboxOn:"\u2612",checkboxOff:"\u2610",checkboxCircleOn:"\u24E7",checkboxCircleOff:"\u24BE",pointer:"\u276F",triangleUpOutline:"\u25B3",triangleLeft:"\u25C0",triangleRight:"\u25B6",lozenge:"\u25C6",lozengeOutline:"\u25C7",hamburger:"\u2630",smiley:"\u32E1",mustache:"\u0DF4",star:"\u2605",play:"\u25B6",nodejs:"\u2B22",oneSeventh:"\u2150",oneNinth:"\u2151",oneTenth:"\u2152"},e2e={tick:"\u221A",info:"i",warning:"\u203C",cross:"\xD7",squareSmall:"\u25A1",squareSmallFilled:"\u25A0",circle:"( )",circleFilled:"(*)",circleDotted:"( )",circleDouble:"( )",circleCircle:"(\u25CB)",circleCross:"(\xD7)",circlePipe:"(\u2502)",radioOn:"(*)",radioOff:"( )",checkboxOn:"[\xD7]",checkboxOff:"[ ]",checkboxCircleOn:"(\xD7)",checkboxCircleOff:"( )",pointer:">",triangleUpOutline:"\u2206",triangleLeft:"\u25C4",triangleRight:"\u25BA",lozenge:"\u2666",lozengeOutline:"\u25CA",hamburger:"\u2261",smiley:"\u263A",mustache:"\u250C\u2500\u2510",star:"\u2736",play:"\u25BA",nodejs:"\u2666",oneSeventh:"1/7",oneNinth:"1/9",oneTenth:"1/10"},t2e={...Oq,...Tq},n2e={...Oq,...e2e},r2e=ZAe(),o2e=r2e?t2e:n2e,ql=o2e,ANt=Object.entries(Tq)});var Oy=w(function(TNt,Nq){function Pq(e){return!!e&&(typeof e==="object"||typeof e==="function")&&typeof e.then==="function"}var Iq=Nq.exports=function(e,t,n="async"){if(typeof t==="string")n=t,t=void 0;return t=t||function(){},function(){var r=arguments,o=this,s=new Promise(function(i,a){var c=!1;let l=function(_){if(c)console.warn("Run-async promise already resolved.");c=!0,i(_)};var d=!1;let f=function(_){if(d)console.warn("Run-async promise already rejected.");d=!0,a(_)};var p=!1,m=!1,h=!1,g=function(){if(h)return console.warn("Run-async async() called outside a valid run-async context, callback will be ignored."),function(){};if(m)console.warn(`Run-async wrapped function (async) returned a promise.
|
|
29
29
|
Calls to async() callback can have unexpected results.`);return p=!0,function(_,x){if(_)f(_);else l(x)}},y;if(o&&n&&Proxy)y=new Proxy(o,{get(_,x){if(x===n){if(x in _)console.warn(`${n} property is been shadowed by run-sync`);return g}return Reflect.get(...arguments)}});else y={[n]:g};var b=e.apply(y,Array.prototype.slice.call(r));if(p){if(Pq(b))console.warn("Run-async wrapped function (sync) returned a promise but async() callback must be executed to resolve.")}else if(Pq(b))m=!0,b.then(l,f);else l(b);h=!0});return s.then(t.bind(null,null),t),s}};Iq.cb=function(e,t){return Iq(function(){var n=Array.prototype.slice.call(arguments);if(n.length===e.length-1)n.push(this.async());return e.apply(this,n)},t)}});var Jt=w(function(Fq){Object.defineProperty(Fq,"__esModule",{value:!0});Fq.isFunction=void 0;function s2e(e){return typeof e==="function"}Fq.isFunction=s2e});var Bl=w(function(jq){Object.defineProperty(jq,"__esModule",{value:!0});jq.createErrorClass=void 0;function i2e(e){var t=function(r){Error.call(r),r.stack=Error().stack},n=e(t);return n.prototype=Object.create(Error.prototype),n.prototype.constructor=n,n}jq.createErrorClass=i2e});var vC=w(function(qq){Object.defineProperty(qq,"__esModule",{value:!0});qq.UnsubscriptionError=void 0;var a2e=Bl();qq.UnsubscriptionError=a2e.createErrorClass(function(e){return function(n){e(this),this.message=n?n.length+` errors occurred during unsubscription:
|
|
@@ -81,7 +81,7 @@ ${gs.cursorShow}`)}releaseCursor(){if(this.extraLinesUnderPrompt>0)L2(this.rl,th
|
|
|
81
81
|
${t}`,TVe,PVe,IVe=(e,t,n)=>{let r=n===""?"":`with ${n.trim()}() `,o=OVe.bind(null,r,t.toString());Object.defineProperty(o,"name",PVe);let{writable:s,enumerable:i,configurable:a}=TVe;Object.defineProperty(e,"toString",{value:o,writable:s,enumerable:i,configurable:a})};var qO=V(()=>{TVe=Object.getOwnPropertyDescriptor(Function.prototype,"toString"),PVe=Object.getOwnPropertyDescriptor(Function.prototype.toString,"name")});var Tv,FX=(e,t={})=>{if(typeof e!=="function")throw TypeError("Expected a function");let n,r=0,o=e.displayName||e.name||"<anonymous>",s=function(...i){if(Tv.set(s,++r),r===1)n=e.apply(this,i),e=void 0;else if(t.throw===!0)throw Error(`Function \`${o}\` can only be called once`);return n};return v0(s,e),Tv.set(s,r),s},MX;var jX=V(()=>{qO();Tv=new WeakMap;FX.callCount=(e)=>{if(!Tv.has(e))throw Error(`The given function \`${e.name}\` is not wrapped by the \`onetime\` package`);return Tv.get(e)};MX=FX});var mf;var LX=V(()=>{mf=[];mf.push("SIGHUP","SIGINT","SIGTERM");if(process.platform!=="win32")mf.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");if(process.platform==="linux")mf.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT")});class qX{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(UO[BO])return UO[BO];NVe(UO,BO,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(e,t){this.listeners[e].push(t)}removeListener(e,t){let n=this.listeners[e],r=n.indexOf(t);if(r===-1)return;if(r===0&&n.length===1)n.length=0;else n.splice(r,1)}emit(e,t,n){if(this.emitted[e])return!1;this.emitted[e]=!0;let r=!1;for(let o of this.listeners[e])r=o(t,n)===!0||r;if(e==="exit")r=this.emit("afterExit",t,n)||r;return r}}class zO{}var Pv=(e)=>!!e&&typeof e==="object"&&typeof e.removeListener==="function"&&typeof e.emit==="function"&&typeof e.reallyExit==="function"&&typeof e.listeners==="function"&&typeof e.kill==="function"&&typeof e.pid==="number"&&typeof e.on==="function",BO,UO,NVe,FVe=(e)=>({onExit(t,n){return e.onExit(t,n)},load(){return e.load()},unload(){return e.unload()}}),BX,UX,HO,HX,t4t,n4t;var zX=V(()=>{LX();BO=Symbol.for("signal-exit emitter"),UO=globalThis,NVe=Object.defineProperty.bind(Object);BX=class BX extends zO{onExit(){return()=>{}}load(){}unload(){}};UX=class UX extends zO{#n=HO.platform==="win32"?"SIGINT":"SIGHUP";#t=new qX;#e;#o;#f;#r={};#i=!1;constructor(e){super();this.#e=e,this.#r={};for(let t of mf)this.#r[t]=()=>{let n=this.#e.listeners(t),{count:r}=this.#t,o=e;if(typeof o.__signal_exit_emitter__==="object"&&typeof o.__signal_exit_emitter__.count==="number")r+=o.__signal_exit_emitter__.count;if(n.length===r){this.unload();let s=this.#t.emit("exit",null,t),i=t==="SIGHUP"?this.#n:t;if(!s)e.kill(e.pid,i)}};this.#f=e.reallyExit,this.#o=e.emit}onExit(e,t){if(!Pv(this.#e))return()=>{};if(this.#i===!1)this.load();let n=t?.alwaysLast?"afterExit":"exit";return this.#t.on(n,e),()=>{if(this.#t.removeListener(n,e),this.#t.listeners.exit.length===0&&this.#t.listeners.afterExit.length===0)this.unload()}}load(){if(this.#i)return;this.#i=!0,this.#t.count+=1;for(let e of mf)try{let t=this.#r[e];if(t)this.#e.on(e,t)}catch(t){}this.#e.emit=(e,...t)=>this.#p(e,...t),this.#e.reallyExit=(e)=>this.#s(e)}unload(){if(!this.#i)return;this.#i=!1,mf.forEach((e)=>{let t=this.#r[e];if(!t)throw Error("Listener not defined for signal: "+e);try{this.#e.removeListener(e,t)}catch(n){}}),this.#e.emit=this.#o,this.#e.reallyExit=this.#f,this.#t.count-=1}#s(e){if(!Pv(this.#e))return 0;return this.#e.exitCode=e||0,this.#t.emit("exit",this.#e.exitCode,null),this.#f.call(this.#e,this.#e.exitCode)}#p(e,...t){let n=this.#o;if(e==="exit"&&Pv(this.#e)){if(typeof t[0]==="number")this.#e.exitCode=t[0];let r=n.call(this.#e,e,...t);return this.#t.emit("exit",this.#e.exitCode,null),r}else return n.call(this.#e,e,...t)}};HO=globalThis.process,{onExit:HX,load:t4t,unload:n4t}=FVe(Pv(HO)?new UX(HO):new BX)});import Iv from"process";var VX,MVe,GX;var WX=V(()=>{jX();zX();VX=Iv.stderr.isTTY?Iv.stderr:Iv.stdout.isTTY?Iv.stdout:void 0,MVe=VX?MX(()=>{HX(()=>{VX.write("\x1B[?25h")},{alwaysLast:!0})}):()=>{},GX=MVe});import KX from"process";var Nv=!1,Um,VO;var JX=V(()=>{WX();Um={};Um.show=(e=KX.stderr)=>{if(!e.isTTY)return;Nv=!1,e.write("\x1B[?25h")};Um.hide=(e=KX.stderr)=>{if(!e.isTTY)return;GX(),Nv=!0,e.write("\x1B[?25l")};Um.toggle=(e,t)=>{if(e!==void 0)Nv=e;if(Nv)Um.show(t);else Um.hide(t)};VO=Um});import Ci from"process";function GO(){if(Ci.platform!=="win32")return Ci.env.TERM!=="linux";return Boolean(Ci.env.CI)||Boolean(Ci.env.WT_SESSION)||Boolean(Ci.env.TERMINUS_SUBLIME)||Ci.env.ConEmuTask==="{cmd::Cmder}"||Ci.env.TERM_PROGRAM==="Terminus-Sublime"||Ci.env.TERM_PROGRAM==="vscode"||Ci.env.TERM==="xterm-256color"||Ci.env.TERM==="alacritty"||Ci.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var YX=()=>{};var jVe,LVe,qVe,k0;var XX=V(()=>{He();YX();jVe={info:u.blue("\u2139"),success:u.green("\u2714"),warning:u.yellow("\u26A0"),error:u.red("\u2716")},LVe={info:u.blue("i"),success:u.green("\u221A"),warning:u.yellow("\u203C"),error:u.red("\xD7")},qVe=GO()?jVe:LVe,k0=qVe});function WO({onlyFirst:e=!1}={}){return new RegExp("(?:\\u001B\\][\\s\\S]*?(?:\\u0007|\\u001B\\u005C|\\u009C))|[\\u001B\\u009B][[\\]()#;?]*(?:\\d{1,4}(?:[;:]\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]",e?void 0:"g")}function E0(e){if(typeof e!=="string")throw TypeError(`Expected a \`string\`, got \`${typeof e}\``);return e.replace(BVe,"")}var BVe;var KO=V(()=>{BVe=WO()});function QX(e){return e===161||e===164||e===167||e===168||e===170||e===173||e===174||e>=176&&e<=180||e>=182&&e<=186||e>=188&&e<=191||e===198||e===208||e===215||e===216||e>=222&&e<=225||e===230||e>=232&&e<=234||e===236||e===237||e===240||e===242||e===243||e>=247&&e<=250||e===252||e===254||e===257||e===273||e===275||e===283||e===294||e===295||e===299||e>=305&&e<=307||e===312||e>=319&&e<=322||e===324||e>=328&&e<=331||e===333||e===338||e===339||e===358||e===359||e===363||e===462||e===464||e===466||e===468||e===470||e===472||e===474||e===476||e===593||e===609||e===708||e===711||e>=713&&e<=715||e===717||e===720||e>=728&&e<=731||e===733||e===735||e>=768&&e<=879||e>=913&&e<=929||e>=931&&e<=937||e>=945&&e<=961||e>=963&&e<=969||e===1025||e>=1040&&e<=1103||e===1105||e===8208||e>=8211&&e<=8214||e===8216||e===8217||e===8220||e===8221||e>=8224&&e<=8226||e>=8228&&e<=8231||e===8240||e===8242||e===8243||e===8245||e===8251||e===8254||e===8308||e===8319||e>=8321&&e<=8324||e===8364||e===8451||e===8453||e===8457||e===8467||e===8470||e===8481||e===8482||e===8486||e===8491||e===8531||e===8532||e>=8539&&e<=8542||e>=8544&&e<=8555||e>=8560&&e<=8569||e===8585||e>=8592&&e<=8601||e===8632||e===8633||e===8658||e===8660||e===8679||e===8704||e===8706||e===8707||e===8711||e===8712||e===8715||e===8719||e===8721||e===8725||e===8730||e>=8733&&e<=8736||e===8739||e===8741||e>=8743&&e<=8748||e===8750||e>=8756&&e<=8759||e===8764||e===8765||e===8776||e===8780||e===8786||e===8800||e===8801||e>=8804&&e<=8807||e===8810||e===8811||e===8814||e===8815||e===8834||e===8835||e===8838||e===8839||e===8853||e===8857||e===8869||e===8895||e===8978||e>=9312&&e<=9449||e>=9451&&e<=9547||e>=9552&&e<=9587||e>=9600&&e<=9615||e>=9618&&e<=9621||e===9632||e===9633||e>=9635&&e<=9641||e===9650||e===9651||e===9654||e===9655||e===9660||e===9661||e===9664||e===9665||e>=9670&&e<=9672||e===9675||e>=9678&&e<=9681||e>=9698&&e<=9701||e===9711||e===9733||e===9734||e===9737||e===9742||e===9743||e===9756||e===9758||e===9792||e===9794||e===9824||e===9825||e>=9827&&e<=9829||e>=9831&&e<=9834||e===9836||e===9837||e===9839||e===9886||e===9887||e===9919||e>=9926&&e<=9933||e>=9935&&e<=9939||e>=9941&&e<=9953||e===9955||e===9960||e===9961||e>=9963&&e<=9969||e===9972||e>=9974&&e<=9977||e===9979||e===9980||e===9982||e===9983||e===10045||e>=10102&&e<=10111||e>=11094&&e<=11097||e>=12872&&e<=12879||e>=57344&&e<=63743||e>=65024&&e<=65039||e===65533||e>=127232&&e<=127242||e>=127248&&e<=127277||e>=127280&&e<=127337||e>=127344&&e<=127373||e===127375||e===127376||e>=127387&&e<=127404||e>=917760&&e<=917999||e>=983040&&e<=1048573||e>=1048576&&e<=1114109}function ZX(e){return e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510}function eQ(e){return e>=4352&&e<=4447||e===8986||e===8987||e===9001||e===9002||e>=9193&&e<=9196||e===9200||e===9203||e===9725||e===9726||e===9748||e===9749||e>=9776&&e<=9783||e>=9800&&e<=9811||e===9855||e>=9866&&e<=9871||e===9875||e===9889||e===9898||e===9899||e===9917||e===9918||e===9924||e===9925||e===9934||e===9940||e===9962||e===9970||e===9971||e===9973||e===9978||e===9981||e===9989||e===9994||e===9995||e===10024||e===10060||e===10062||e>=10067&&e<=10069||e===10071||e>=10133&&e<=10135||e===10160||e===10175||e===11035||e===11036||e===11088||e===11093||e>=11904&&e<=11929||e>=11931&&e<=12019||e>=12032&&e<=12245||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12353&&e<=12438||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12773||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=42124||e>=42128&&e<=42182||e>=43360&&e<=43388||e>=44032&&e<=55203||e>=63744&&e<=64255||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=94176&&e<=94180||e>=94192&&e<=94198||e>=94208&&e<=101589||e>=101631&&e<=101662||e>=101760&&e<=101874||e>=110576&&e<=110579||e>=110581&&e<=110587||e===110589||e===110590||e>=110592&&e<=110882||e===110898||e>=110928&&e<=110930||e===110933||e>=110948&&e<=110951||e>=110960&&e<=111355||e>=119552&&e<=119638||e>=119648&&e<=119670||e===126980||e===127183||e===127374||e>=127377&&e<=127386||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e===127568||e===127569||e>=127584&&e<=127589||e>=127744&&e<=127776||e>=127789&&e<=127797||e>=127799&&e<=127868||e>=127870&&e<=127891||e>=127904&&e<=127946||e>=127951&&e<=127955||e>=127968&&e<=127984||e===127988||e>=127992&&e<=128062||e===128064||e>=128066&&e<=128252||e>=128255&&e<=128317||e>=128331&&e<=128334||e>=128336&&e<=128359||e===128378||e===128405||e===128406||e===128420||e>=128507&&e<=128591||e>=128640&&e<=128709||e===128716||e>=128720&&e<=128722||e>=128725&&e<=128728||e>=128732&&e<=128735||e===128747||e===128748||e>=128756&&e<=128764||e>=128992&&e<=129003||e===129008||e>=129292&&e<=129338||e>=129340&&e<=129349||e>=129351&&e<=129535||e>=129648&&e<=129660||e>=129664&&e<=129674||e>=129678&&e<=129734||e===129736||e>=129741&&e<=129756||e>=129759&&e<=129770||e>=129775&&e<=129784||e>=131072&&e<=196605||e>=196608&&e<=262141}var tQ=()=>{};function UVe(e){if(!Number.isSafeInteger(e))throw TypeError(`Expected a code point, got \`${typeof e}\`.`)}function nQ(e,{ambiguousAsWide:t=!1}={}){if(UVe(e),ZX(e)||eQ(e)||t&&QX(e))return 2;return 1}var rQ=V(()=>{tQ()});var oQ=()=>/[#*0-9]\uFE0F?\u20E3|[\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23ED-\u23EF\u23F1\u23F2\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB\u25FC\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692\u2694-\u2697\u2699\u269B\u269C\u26A0\u26A7\u26AA\u26B0\u26B1\u26BD\u26BE\u26C4\u26C8\u26CF\u26D1\u26E9\u26F0-\u26F5\u26F7\u26F8\u26FA\u2702\u2708\u2709\u270F\u2712\u2714\u2716\u271D\u2721\u2733\u2734\u2744\u2747\u2757\u2763\u27A1\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B55\u3030\u303D\u3297\u3299]\uFE0F?|[\u261D\u270C\u270D](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\u270A\u270B](?:\uD83C[\uDFFB-\uDFFF])?|[\u23E9-\u23EC\u23F0\u23F3\u25FD\u2693\u26A1\u26AB\u26C5\u26CE\u26D4\u26EA\u26FD\u2705\u2728\u274C\u274E\u2753-\u2755\u2795-\u2797\u27B0\u27BF\u2B50]|\u26D3\uFE0F?(?:\u200D\uD83D\uDCA5)?|\u26F9(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\u2764\uFE0F?(?:\u200D(?:\uD83D\uDD25|\uD83E\uDE79))?|\uD83C(?:[\uDC04\uDD70\uDD71\uDD7E\uDD7F\uDE02\uDE37\uDF21\uDF24-\uDF2C\uDF36\uDF7D\uDF96\uDF97\uDF99-\uDF9B\uDF9E\uDF9F\uDFCD\uDFCE\uDFD4-\uDFDF\uDFF5\uDFF7]\uFE0F?|[\uDF85\uDFC2\uDFC7](?:\uD83C[\uDFFB-\uDFFF])?|[\uDFC4\uDFCA](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDFCB\uDFCC](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDCCF\uDD8E\uDD91-\uDD9A\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF43\uDF45-\uDF4A\uDF4C-\uDF7C\uDF7E-\uDF84\uDF86-\uDF93\uDFA0-\uDFC1\uDFC5\uDFC6\uDFC8\uDFC9\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF8-\uDFFF]|\uDDE6\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF]|\uDDE7\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF]|\uDDE8\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF7\uDDFA-\uDDFF]|\uDDE9\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF]|\uDDEA\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA]|\uDDEB\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7]|\uDDEC\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE]|\uDDED\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA]|\uDDEE\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9]|\uDDEF\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5]|\uDDF0\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF]|\uDDF1\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE]|\uDDF2\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF]|\uDDF3\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF]|\uDDF4\uD83C\uDDF2|\uDDF5\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE]|\uDDF6\uD83C\uDDE6|\uDDF7\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC]|\uDDF8\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF]|\uDDF9\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF]|\uDDFA\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF]|\uDDFB\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA]|\uDDFC\uD83C[\uDDEB\uDDF8]|\uDDFD\uD83C\uDDF0|\uDDFE\uD83C[\uDDEA\uDDF9]|\uDDFF\uD83C[\uDDE6\uDDF2\uDDFC]|\uDF44(?:\u200D\uD83D\uDFEB)?|\uDF4B(?:\u200D\uD83D\uDFE9)?|\uDFC3(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDFF3\uFE0F?(?:\u200D(?:\u26A7\uFE0F?|\uD83C\uDF08))?|\uDFF4(?:\u200D\u2620\uFE0F?|\uDB40\uDC67\uDB40\uDC62\uDB40(?:\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDC73\uDB40\uDC63\uDB40\uDC74|\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F)?)|\uD83D(?:[\uDC3F\uDCFD\uDD49\uDD4A\uDD6F\uDD70\uDD73\uDD76-\uDD79\uDD87\uDD8A-\uDD8D\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA\uDECB\uDECD-\uDECF\uDEE0-\uDEE5\uDEE9\uDEF0\uDEF3]\uFE0F?|[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDC8F\uDC91\uDCAA\uDD7A\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC](?:\uD83C[\uDFFB-\uDFFF])?|[\uDC6E-\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4\uDEB5](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD74\uDD90](?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?|[\uDC00-\uDC07\uDC09-\uDC14\uDC16-\uDC25\uDC27-\uDC3A\uDC3C-\uDC3E\uDC40\uDC44\uDC45\uDC51-\uDC65\uDC6A\uDC79-\uDC7B\uDC7D-\uDC80\uDC84\uDC88-\uDC8E\uDC90\uDC92-\uDCA9\uDCAB-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDDA4\uDDFB-\uDE2D\uDE2F-\uDE34\uDE37-\uDE41\uDE43\uDE44\uDE48-\uDE4A\uDE80-\uDEA2\uDEA4-\uDEB3\uDEB7-\uDEBF\uDEC1-\uDEC5\uDED0-\uDED2\uDED5-\uDED8\uDEDC-\uDEDF\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB\uDFF0]|\uDC08(?:\u200D\u2B1B)?|\uDC15(?:\u200D\uD83E\uDDBA)?|\uDC26(?:\u200D(?:\u2B1B|\uD83D\uDD25))?|\uDC3B(?:\u200D\u2744\uFE0F?)?|\uDC41\uFE0F?(?:\u200D\uD83D\uDDE8\uFE0F?)?|\uDC68(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDC68\uDC69]\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?)|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFC-\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFD-\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFD\uDFFF]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?\uDC68\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDD1D\uDEEF]\u200D\uD83D\uDC68\uD83C[\uDFFB-\uDFFE]|[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3])))?))?|\uDC69(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:\uDC8B\u200D\uD83D)?[\uDC68\uDC69]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?|\uDC69\u200D\uD83D(?:\uDC66(?:\u200D\uD83D\uDC66)?|\uDC67(?:\u200D\uD83D[\uDC66\uDC67])?))|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFC-\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFD-\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFD\uDFFF]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D\uD83D(?:[\uDC68\uDC69]|\uDC8B\u200D\uD83D[\uDC68\uDC69])\uD83C[\uDFFB-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3]|\uDD1D\u200D\uD83D[\uDC68\uDC69]\uD83C[\uDFFB-\uDFFE]|\uDEEF\u200D\uD83D\uDC69\uD83C[\uDFFB-\uDFFE])))?))?|\uDD75(?:\uD83C[\uDFFB-\uDFFF]|\uFE0F)?(?:\u200D[\u2640\u2642]\uFE0F?)?|\uDE2E(?:\u200D\uD83D\uDCA8)?|\uDE35(?:\u200D\uD83D\uDCAB)?|\uDE36(?:\u200D\uD83C\uDF2B\uFE0F?)?|\uDE42(?:\u200D[\u2194\u2195]\uFE0F?)?|\uDEB6(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?)|\uD83E(?:[\uDD0C\uDD0F\uDD18-\uDD1F\uDD30-\uDD34\uDD36\uDD77\uDDB5\uDDB6\uDDBB\uDDD2\uDDD3\uDDD5\uDEC3-\uDEC5\uDEF0\uDEF2-\uDEF8](?:\uD83C[\uDFFB-\uDFFF])?|[\uDD26\uDD35\uDD37-\uDD39\uDD3C-\uDD3E\uDDB8\uDDB9\uDDCD\uDDCF\uDDD4\uDDD6-\uDDDD](?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDDDE\uDDDF](?:\u200D[\u2640\u2642]\uFE0F?)?|[\uDD0D\uDD0E\uDD10-\uDD17\uDD20-\uDD25\uDD27-\uDD2F\uDD3A\uDD3F-\uDD45\uDD47-\uDD76\uDD78-\uDDB4\uDDB7\uDDBA\uDDBC-\uDDCC\uDDD0\uDDE0-\uDDFF\uDE70-\uDE7C\uDE80-\uDE8A\uDE8E-\uDEC2\uDEC6\uDEC8\uDECD-\uDEDC\uDEDF-\uDEEA\uDEEF]|\uDDCE(?:\uD83C[\uDFFB-\uDFFF])?(?:\u200D(?:[\u2640\u2642]\uFE0F?(?:\u200D\u27A1\uFE0F?)?|\u27A1\uFE0F?))?|\uDDD1(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1|\uDDD1\u200D\uD83E\uDDD2(?:\u200D\uD83E\uDDD2)?|\uDDD2(?:\u200D\uD83E\uDDD2)?))|\uD83C(?:\uDFFB(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFC-\uDFFF])))?|\uDFFC(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFD-\uDFFF])))?|\uDFFD(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])))?|\uDFFE(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFD\uDFFF])))?|\uDFFF(?:\u200D(?:[\u2695\u2696\u2708]\uFE0F?|\u2764\uFE0F?\u200D(?:\uD83D\uDC8B\u200D)?\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE]|\uD83C[\uDF3E\uDF73\uDF7C\uDF84\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D(?:[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uDC30\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE])|\uD83E(?:[\uDDAF\uDDBC\uDDBD](?:\u200D\u27A1\uFE0F?)?|[\uDDB0-\uDDB3\uDE70]|\uDD1D\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFF]|\uDEEF\u200D\uD83E\uDDD1\uD83C[\uDFFB-\uDFFE])))?))?|\uDEF1(?:\uD83C(?:\uDFFB(?:\u200D\uD83E\uDEF2\uD83C[\uDFFC-\uDFFF])?|\uDFFC(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFD-\uDFFF])?|\uDFFD(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])?|\uDFFE(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFD\uDFFF])?|\uDFFF(?:\u200D\uD83E\uDEF2\uD83C[\uDFFB-\uDFFE])?))?)/g;function JO(e,t={}){if(typeof e!=="string"||e.length===0)return 0;let{ambiguousIsNarrow:n=!0,countAnsiEscapeCodes:r=!1}=t;if(!r)e=E0(e);if(e.length===0)return 0;let o=0,s={ambiguousAsWide:!n};for(let{segment:i}of HVe.segment(e)){let a=i.codePointAt(0);if(a<=31||a>=127&&a<=159)continue;if(a>=8203&&a<=8207||a===65279)continue;if(a>=768&&a<=879||a>=6832&&a<=6911||a>=7616&&a<=7679||a>=8400&&a<=8447||a>=65056&&a<=65071)continue;if(a>=55296&&a<=57343)continue;if(a>=65024&&a<=65039)continue;if(zVe.test(i))continue;if(oQ().test(i)){o+=2;continue}o+=nQ(a,s)}return o}var HVe,zVe;var sQ=V(()=>{KO();rQ();HVe=new Intl.Segmenter,zVe=/^\p{Default_Ignorable_Code_Point}$/u});function YO({stream:e=process.stdout}={}){return Boolean(e&&e.isTTY&&process.env.TERM!=="dumb"&&!("CI"in process.env))}import iQ from"process";function XO(){let{env:e}=iQ,{TERM:t,TERM_PROGRAM:n}=e;if(iQ.platform!=="win32")return t!=="linux";return Boolean(e.WT_SESSION)||Boolean(e.TERMINUS_SUBLIME)||e.ConEmuTask==="{cmd::Cmder}"||n==="Terminus-Sublime"||n==="vscode"||t==="xterm-256color"||t==="alacritty"||t==="rxvt-unicode"||t==="rxvt-unicode-256color"||e.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var aQ=()=>{};import ga from"process";class cQ{#n=0;start(){if(this.#n++,this.#n===1)this.#t()}stop(){if(this.#n<=0)throw Error("`stop` called more times than `start`");if(this.#n--,this.#n===0)this.#e()}#t(){if(ga.platform==="win32"||!ga.stdin.isTTY)return;ga.stdin.setRawMode(!0),ga.stdin.on("data",this.#o),ga.stdin.resume()}#e(){if(!ga.stdin.isTTY)return;ga.stdin.off("data",this.#o),ga.stdin.pause(),ga.stdin.setRawMode(!1)}#o(e){if(e[0]===VVe)ga.emit("SIGINT")}}var VVe=3,GVe,QO;var lQ=V(()=>{GVe=new cQ,QO=GVe});import Fv from"process";class uQ{#n=0;#t=!1;#e=0;#o=-1;#f=0;#r;#i;#s;#p;#h;#l;#u;#d;#g;#a;#c;color;constructor(e){if(typeof e==="string")e={text:e};if(this.#r={color:"cyan",stream:Fv.stderr,discardStdin:!0,hideCursor:!0,...e},this.color=this.#r.color,this.spinner=this.#r.spinner,this.#h=this.#r.interval,this.#s=this.#r.stream,this.#l=typeof this.#r.isEnabled==="boolean"?this.#r.isEnabled:YO({stream:this.#s}),this.#u=typeof this.#r.isSilent==="boolean"?this.#r.isSilent:!1,this.text=this.#r.text,this.prefixText=this.#r.prefixText,this.suffixText=this.#r.suffixText,this.indent=this.#r.indent,Fv.env.NODE_ENV==="test")this._stream=this.#s,this._isEnabled=this.#l,Object.defineProperty(this,"_linesToClear",{get(){return this.#n},set(t){this.#n=t}}),Object.defineProperty(this,"_frameIndex",{get(){return this.#o}}),Object.defineProperty(this,"_lineCount",{get(){return this.#e}})}get indent(){return this.#d}set indent(e=0){if(!(e>=0&&Number.isInteger(e)))throw Error("The `indent` option must be an integer from 0 and up");this.#d=e,this.#m()}get interval(){return this.#h??this.#i.interval??100}get spinner(){return this.#i}set spinner(e){if(this.#o=-1,this.#h=void 0,typeof e==="object"){if(e.frames===void 0)throw Error("The given spinner must have a `frames` property");this.#i=e}else if(!XO())this.#i=S0.default.line;else if(e===void 0)this.#i=S0.default.dots;else if(e!=="default"&&S0.default[e])this.#i=S0.default[e];else throw Error(`There is no built-in spinner named '${e}'. See https://github.com/sindresorhus/cli-spinners/blob/main/spinners.json for a full list.`)}get text(){return this.#g}set text(e=""){this.#g=e,this.#m()}get prefixText(){return this.#a}set prefixText(e=""){this.#a=e,this.#m()}get suffixText(){return this.#c}set suffixText(e=""){this.#c=e,this.#m()}get isSpinning(){return this.#p!==void 0}#y(e=this.#a,t=" "){if(typeof e==="string"&&e!=="")return e+t;if(typeof e==="function")return e()+t;return""}#b(e=this.#c,t=" "){if(typeof e==="string"&&e!=="")return t+e;if(typeof e==="function")return t+e();return""}#m(){let e=this.#s.columns??80,t=this.#y(this.#a,"-"),n=this.#b(this.#c,"-"),r=" ".repeat(this.#d)+t+"--"+this.#g+"--"+n;this.#e=0;for(let o of E0(r).split(`
|
|
82
82
|
`))this.#e+=Math.max(1,Math.ceil(JO(o,{countAnsiEscapeCodes:!0})/e))}get isEnabled(){return this.#l&&!this.#u}set isEnabled(e){if(typeof e!=="boolean")throw TypeError("The `isEnabled` option must be a boolean");this.#l=e}get isSilent(){return this.#u}set isSilent(e){if(typeof e!=="boolean")throw TypeError("The `isSilent` option must be a boolean");this.#u=e}frame(){let e=Date.now();if(this.#o===-1||e-this.#f>=this.interval)this.#o=++this.#o%this.#i.frames.length,this.#f=e;let{frames:t}=this.#i,n=t[this.#o];if(this.color)n=u[this.color](n);let r=typeof this.#a==="string"&&this.#a!==""?this.#a+" ":"",o=typeof this.text==="string"?" "+this.text:"",s=typeof this.#c==="string"&&this.#c!==""?" "+this.#c:"";return r+n+o+s}clear(){if(!this.#l||!this.#s.isTTY)return this;this.#s.cursorTo(0);for(let e=0;e<this.#n;e++){if(e>0)this.#s.moveCursor(0,-1);this.#s.clearLine(1)}if(this.#d||this.lastIndent!==this.#d)this.#s.cursorTo(this.#d);return this.lastIndent=this.#d,this.#n=0,this}render(){if(this.#u)return this;return this.clear(),this.#s.write(this.frame()),this.#n=this.#e,this}start(e){if(e)this.text=e;if(this.#u)return this;if(!this.#l){if(this.text)this.#s.write(`- ${this.text}
|
|
83
83
|
`);return this}if(this.isSpinning)return this;if(this.#r.hideCursor)VO.hide(this.#s);if(this.#r.discardStdin&&Fv.stdin.isTTY)this.#t=!0,QO.start();return this.render(),this.#p=setInterval(this.render.bind(this),this.interval),this}stop(){if(!this.#l)return this;if(clearInterval(this.#p),this.#p=void 0,this.#o=0,this.clear(),this.#r.hideCursor)VO.show(this.#s);if(this.#r.discardStdin&&Fv.stdin.isTTY&&this.#t)QO.stop(),this.#t=!1;return this}succeed(e){return this.stopAndPersist({symbol:k0.success,text:e})}fail(e){return this.stopAndPersist({symbol:k0.error,text:e})}warn(e){return this.stopAndPersist({symbol:k0.warning,text:e})}info(e){return this.stopAndPersist({symbol:k0.info,text:e})}stopAndPersist(e={}){if(this.#u)return this;let t=e.prefixText??this.#a,n=this.#y(t," "),r=e.symbol??" ",o=e.text??this.text,i=typeof o==="string"?(r?" ":"")+o:"",a=e.suffixText??this.#c,c=this.#b(a," "),l=n+r+i+c+`
|
|
84
|
-
`;return this.stop(),this.#s.write(l),this}}function D(e){return new uQ(e)}var S0,WVe;var ro=V(()=>{He();JX();XX();KO();sQ();aQ();lQ();S0=et(Ox(),1),WVe=et(Ox(),1)});var kt,pQ,fe,Vc=(e)=>{switch(typeof e){case"undefined":return fe.undefined;case"string":return fe.string;case"number":return Number.isNaN(e)?fe.nan:fe.number;case"boolean":return fe.boolean;case"function":return fe.function;case"bigint":return fe.bigint;case"symbol":return fe.symbol;case"object":if(Array.isArray(e))return fe.array;if(e===null)return fe.null;if(e.then&&typeof e.then==="function"&&e.catch&&typeof e.catch==="function")return fe.promise;if(typeof Map<"u"&&e instanceof Map)return fe.map;if(typeof Set<"u"&&e instanceof Set)return fe.set;if(typeof Date<"u"&&e instanceof Date)return fe.date;return fe.object;default:return fe.unknown}};var $0=V(()=>{(function(e){e.assertEqual=(o)=>{};function t(o){}e.assertIs=t;function n(o){throw Error()}e.assertNever=n,e.arrayToEnum=(o)=>{let s={};for(let i of o)s[i]=i;return s},e.getValidEnumValues=(o)=>{let s=e.objectKeys(o).filter((a)=>typeof o[o[a]]!=="number"),i={};for(let a of s)i[a]=o[a];return e.objectValues(i)},e.objectValues=(o)=>e.objectKeys(o).map(function(s){return o[s]}),e.objectKeys=typeof Object.keys==="function"?(o)=>Object.keys(o):(o)=>{let s=[];for(let i in o)if(Object.prototype.hasOwnProperty.call(o,i))s.push(i);return s},e.find=(o,s)=>{for(let i of o)if(s(i))return i;return},e.isInteger=typeof Number.isInteger==="function"?(o)=>Number.isInteger(o):(o)=>typeof o==="number"&&Number.isFinite(o)&&Math.floor(o)===o;function r(o,s=" | "){return o.map((i)=>typeof i==="string"?`'${i}'`:i).join(s)}e.joinValues=r,e.jsonStringifyReplacer=(o,s)=>{if(typeof s==="bigint")return s.toString();return s}})(kt||(kt={}));(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(pQ||(pQ={}));fe=kt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"])});var Z,xs;var Mv=V(()=>{$0();Z=kt.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);xs=class xs extends Error{get errors(){return this.issues}constructor(e){super();this.issues=[],this.addIssue=(n)=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let t=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,t);else this.__proto__=t;this.name="ZodError",this.issues=e}format(e){let t=e||function(o){return o.message},n={_errors:[]},r=(o)=>{for(let s of o.issues)if(s.code==="invalid_union")s.unionErrors.map(r);else if(s.code==="invalid_return_type")r(s.returnTypeError);else if(s.code==="invalid_arguments")r(s.argumentsError);else if(s.path.length===0)n._errors.push(t(s));else{let i=n,a=0;while(a<s.path.length){let c=s.path[a];if(a!==s.path.length-1)i[c]=i[c]||{_errors:[]};else i[c]=i[c]||{_errors:[]},i[c]._errors.push(t(s));i=i[c],a++}}};return r(this),n}static assert(e){if(!(e instanceof xs))throw Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,kt.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=(t)=>t.message){let t={},n=[];for(let r of this.issues)if(r.path.length>0){let o=r.path[0];t[o]=t[o]||[],t[o].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};xs.create=(e)=>new xs(e)});var KVe=(e,t)=>{let n;switch(e.code){case Z.invalid_type:if(e.received===fe.undefined)n="Required";else n=`Expected ${e.expected}, received ${e.received}`;break;case Z.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,kt.jsonStringifyReplacer)}`;break;case Z.unrecognized_keys:n=`Unrecognized key(s) in object: ${kt.joinValues(e.keys,", ")}`;break;case Z.invalid_union:n="Invalid input";break;case Z.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${kt.joinValues(e.options)}`;break;case Z.invalid_enum_value:n=`Invalid enum value. Expected ${kt.joinValues(e.options)}, received '${e.received}'`;break;case Z.invalid_arguments:n="Invalid function arguments";break;case Z.invalid_return_type:n="Invalid function return type";break;case Z.invalid_date:n="Invalid date";break;case Z.invalid_string:if(typeof e.validation==="object")if("includes"in e.validation){if(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==="number")n=`${n} at one or more positions greater than or equal to ${e.validation.position}`}else if("startsWith"in e.validation)n=`Invalid input: must start with "${e.validation.startsWith}"`;else if("endsWith"in e.validation)n=`Invalid input: must end with "${e.validation.endsWith}"`;else kt.assertNever(e.validation);else if(e.validation!=="regex")n=`Invalid ${e.validation}`;else n="Invalid";break;case Z.too_small:if(e.type==="array")n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`;else if(e.type==="string")n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`;else if(e.type==="number")n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`;else if(e.type==="bigint")n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`;else if(e.type==="date")n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`;else n="Invalid input";break;case Z.too_big:if(e.type==="array")n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`;else if(e.type==="string")n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`;else if(e.type==="number")n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`;else if(e.type==="bigint")n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`;else if(e.type==="date")n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`;else n="Invalid input";break;case Z.custom:n="Invalid input";break;case Z.invalid_intersection_types:n="Intersection results could not be merged";break;case Z.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case Z.not_finite:n="Number must be finite";break;default:n=t.defaultError,kt.assertNever(e)}return{message:n}},bu;var ZO=V(()=>{Mv();$0();bu=KVe});function D0(){return JVe}var JVe;var jv=V(()=>{ZO();JVe=bu});function ae(e,t){let n=D0(),r=Lv({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===bu?void 0:bu].filter((o)=>!!o)});e.common.issues.push(r)}class oo{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(e,t){let n=[];for(let r of t){if(r.status==="aborted")return Le;if(r.status==="dirty")e.dirty();n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){let n=[];for(let r of t){let o=await r.key,s=await r.value;n.push({key:o,value:s})}return oo.mergeObjectSync(e,n)}static mergeObjectSync(e,t){let n={};for(let r of t){let{key:o,value:s}=r;if(o.status==="aborted")return Le;if(s.status==="aborted")return Le;if(o.status==="dirty")e.dirty();if(s.status==="dirty")e.dirty();if(o.value!=="__proto__"&&(typeof s.value<"u"||r.alwaysSet))n[o.value]=s.value}return{status:e.value,value:n}}}var Lv=(e)=>{let{data:t,path:n,errorMaps:r,issueData:o}=e,s=[...n,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",c=r.filter((l)=>!!l).slice().reverse();for(let l of c)a=l(i,{data:t,defaultError:a}).message;return{...o,path:s,message:a}},Le,Hm=(e)=>({status:"dirty",value:e}),Eo=(e)=>({status:"valid",value:e}),eT=(e)=>e.status==="aborted",tT=(e)=>e.status==="dirty",hf=(e)=>e.status==="valid",R0=(e)=>typeof Promise<"u"&&e instanceof Promise;var nT=V(()=>{jv();ZO();Le=Object.freeze({status:"aborted"})});var mQ=()=>{};var $e;var hQ=V(()=>{(function(e){e.errToObj=(t)=>typeof t==="string"?{message:t}:t||{},e.toString=(t)=>typeof t==="string"?t:t?.message})($e||($e={}))});class Ai{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}function at(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:o}=e;if(t&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(t)return{errorMap:t,description:o};return{errorMap:(i,a)=>{let{message:c}=e;if(i.code==="invalid_enum_value")return{message:c??a.defaultError};if(typeof a.data>"u")return{message:c??r??a.defaultError};if(i.code!=="invalid_type")return{message:a.defaultError};return{message:c??n??a.defaultError}},description:o}}class wt{get description(){return this._def.description}_getType(e){return Vc(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Vc(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new oo,ctx:{common:e.parent.common,data:e.data,parsedType:Vc(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(R0(t))throw Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Vc(e)},r=this._parseSync({data:e,path:n.path,parent:n});return gQ(n,r)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Vc(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return hf(n)?{value:n.value}:{issues:t.common.issues}}catch(n){if(n?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then((n)=>hf(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Vc(e)},r=this._parse({data:e,path:n.path,parent:n}),o=await(R0(r)?r:Promise.resolve(r));return gQ(n,o)}refine(e,t){let n=(r)=>{if(typeof t==="string"||typeof t>"u")return{message:t};else if(typeof t==="function")return t(r);else return t};return this._refinement((r,o)=>{let s=e(r),i=()=>o.addIssue({code:Z.custom,...n(r)});if(typeof Promise<"u"&&s instanceof Promise)return s.then((a)=>{if(!a)return i(),!1;else return!0});if(!s)return i(),!1;else return!0})}refinement(e,t){return this._refinement((n,r)=>{if(!e(n))return r.addIssue(typeof t==="function"?t(n,r):t),!1;else return!0})}_refinement(e){return new wa({schema:this,typeName:qe.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(t)=>this["~validate"](t)}}optional(){return ba.create(this,this._def)}nullable(){return wu.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ya.create(this)}promise(){return Km.create(this,this._def)}or(e){return P0.create([this,e],this._def)}and(e){return I0.create(this,e,this._def)}transform(e){return new wa({...at(this._def),schema:this,typeName:qe.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e==="function"?e:()=>e;return new j0({...at(this._def),innerType:this,defaultValue:t,typeName:qe.ZodDefault})}brand(){return new iT({typeName:qe.ZodBranded,type:this,...at(this._def)})}catch(e){let t=typeof e==="function"?e:()=>e;return new L0({...at(this._def),innerType:this,catchValue:t,typeName:qe.ZodCatch})}describe(e){return new this.constructor({...this._def,description:e})}pipe(e){return Wv.create(this,e)}readonly(){return q0.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}function bQ(e){let t="[0-5]\\d";if(e.precision)t=`${t}\\.\\d{${e.precision}}`;else if(e.precision==null)t=`${t}(\\.\\d+)?`;let n=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function fGe(e){return new RegExp(`^${bQ(e)}$`)}function pGe(e){let t=`${yQ}T${bQ(e)}`,n=[];if(n.push(e.local?"Z?":"Z"),e.offset)n.push("([+-]\\d{2}:?\\d{2})");return t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function mGe(e,t){if((t==="v4"||!t)&&sGe.test(e))return!0;if((t==="v6"||!t)&&aGe.test(e))return!0;return!1}function hGe(e,t){if(!tGe.test(e))return!1;try{let[n]=e.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),o=JSON.parse(atob(r));if(typeof o!=="object"||o===null)return!1;if("typ"in o&&o?.typ!=="JWT")return!1;if(!o.alg)return!1;if(t&&o.alg!==t)return!1;return!0}catch{return!1}}function gGe(e,t){if((t==="v4"||!t)&&iGe.test(e))return!0;if((t==="v6"||!t)&&cGe.test(e))return!0;return!1}function yGe(e,t){let n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,s=Number.parseInt(e.toFixed(o).replace(".","")),i=Number.parseInt(t.toFixed(o).replace(".",""));return s%i/10**o}function zm(e){if(e instanceof In){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=ba.create(zm(r))}return new In({...e._def,shape:()=>t})}else if(e instanceof ya)return new ya({...e._def,type:zm(e.element)});else if(e instanceof ba)return ba.create(zm(e.unwrap()));else if(e instanceof wu)return wu.create(zm(e.unwrap()));else if(e instanceof Jc)return Jc.create(e.items.map((t)=>zm(t)));else return e}function oT(e,t){let n=Vc(e),r=Vc(t);if(e===t)return{valid:!0,data:e};else if(n===fe.object&&r===fe.object){let o=kt.objectKeys(t),s=kt.objectKeys(e).filter((a)=>o.indexOf(a)!==-1),i={...e,...t};for(let a of s){let c=oT(e[a],t[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(n===fe.array&&r===fe.array){if(e.length!==t.length)return{valid:!1};let o=[];for(let s=0;s<e.length;s++){let i=e[s],a=t[s],c=oT(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else if(n===fe.date&&r===fe.date&&+e===+t)return{valid:!0,data:e};else return{valid:!1}}function wQ(e,t){return new yf({values:e,typeName:qe.ZodEnum,...at(t)})}var gQ=(e,t)=>{if(hf(t))return{success:!0,data:t.value};else{if(!e.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new xs(e.common.issues);return this._error=n,this._error}}}},YVe,XVe,QVe,ZVe,eGe,tGe,nGe,rGe,oGe="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",rT,sGe,iGe,aGe,cGe,lGe,uGe,yQ="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",dGe,Wc,Vm,Gm,qv,A0,Bv,O0,T0,Uv,gf,Kc,Hv,ya,In,P0,Gc=(e)=>{if(e instanceof N0)return Gc(e.schema);else if(e instanceof wa)return Gc(e.innerType());else if(e instanceof F0)return[e.value];else if(e instanceof yf)return e.options;else if(e instanceof M0)return kt.objectValues(e.enum);else if(e instanceof j0)return Gc(e._def.innerType);else if(e instanceof O0)return[void 0];else if(e instanceof T0)return[null];else if(e instanceof ba)return[void 0,...Gc(e.unwrap())];else if(e instanceof wu)return[null,...Gc(e.unwrap())];else if(e instanceof iT)return Gc(e.unwrap());else if(e instanceof q0)return Gc(e.unwrap());else if(e instanceof L0)return Gc(e._def.innerType);else return[]},sT,I0,Jc,zv,Vv,Wm,C0,N0,F0,yf,M0,Km,wa,ba,wu,j0,L0,Gv,a8t,iT,Wv,q0,c8t,qe,S,j,l8t,u8t,Qe,d8t,f8t,p8t,m8t,h8t,_u,g8t,y8t,he,ee,b8t,Jm,aT,w8t,_8t,Ks,x8t,v8t,k8t,E8t,$t,Ft,S8t,$8t,D8t,R8t,C8t,A8t,O8t;var _Q=V(()=>{Mv();jv();hQ();nT();$0();YVe=/^c[^\s-]{8,}$/i,XVe=/^[0-9a-z]+$/,QVe=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ZVe=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,eGe=/^[a-z0-9_-]{21}$/i,tGe=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,nGe=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,rGe=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,sGe=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,iGe=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,aGe=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,cGe=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,lGe=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,uGe=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dGe=new RegExp(`^${yQ}$`);Wc=class Wc extends wt{_parse(e){if(this._def.coerce)e.data=String(e.data);if(this._getType(e)!==fe.string){let o=this._getOrReturnCtx(e);return ae(o,{code:Z.invalid_type,expected:fe.string,received:o.parsedType}),Le}let n=new oo,r=void 0;for(let o of this._def.checks)if(o.kind==="min"){if(e.data.length<o.value)r=this._getOrReturnCtx(e,r),ae(r,{code:Z.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty()}else if(o.kind==="max"){if(e.data.length>o.value)r=this._getOrReturnCtx(e,r),ae(r,{code:Z.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty()}else if(o.kind==="length"){let s=e.data.length>o.value,i=e.data.length<o.value;if(s||i){if(r=this._getOrReturnCtx(e,r),s)ae(r,{code:Z.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message});else if(i)ae(r,{code:Z.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message});n.dirty()}}else if(o.kind==="email"){if(!rGe.test(e.data))r=this._getOrReturnCtx(e,r),ae(r,{validation:"email",code:Z.invalid_string,message:o.message}),n.dirty()}else if(o.kind==="emoji"){if(!rT)rT=new RegExp(oGe,"u");if(!rT.test(e.data))r=this._getOrReturnCtx(e,r),ae(r,{validation:"emoji",code:Z.invalid_string,message:o.message}),n.dirty()}else if(o.kind==="uuid"){if(!ZVe.test(e.data))r=this._getOrReturnCtx(e,r),ae(r,{validation:"uuid",code:Z.invalid_string,message:o.message}),n.dirty()}else if(o.kind==="nanoid"){if(!eGe.test(e.data))r=this._getOrReturnCtx(e,r),ae(r,{validation:"nanoid",code:Z.invalid_string,message:o.message}),n.dirty()}else if(o.kind==="cuid"){if(!YVe.test(e.data))r=this._getOrReturnCtx(e,r),ae(r,{validation:"cuid",code:Z.invalid_string,message:o.message}),n.dirty()}else if(o.kind==="cuid2"){if(!XVe.test(e.data))r=this._getOrReturnCtx(e,r),ae(r,{validation:"cuid2",code:Z.invalid_string,message:o.message}),n.dirty()}else if(o.kind==="ulid"){if(!QVe.test(e.data))r=this._getOrReturnCtx(e,r),ae(r,{validation:"ulid",code:Z.invalid_string,message:o.message}),n.dirty()}else if(o.kind==="url")try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),ae(r,{validation:"url",code:Z.invalid_string,message:o.message}),n.dirty()}else if(o.kind==="regex"){if(o.regex.lastIndex=0,!o.regex.test(e.data))r=this._getOrReturnCtx(e,r),ae(r,{validation:"regex",code:Z.invalid_string,message:o.message}),n.dirty()}else if(o.kind==="trim")e.data=e.data.trim();else if(o.kind==="includes"){if(!e.data.includes(o.value,o.position))r=this._getOrReturnCtx(e,r),ae(r,{code:Z.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()}else if(o.kind==="toLowerCase")e.data=e.data.toLowerCase();else if(o.kind==="toUpperCase")e.data=e.data.toUpperCase();else if(o.kind==="startsWith"){if(!e.data.startsWith(o.value))r=this._getOrReturnCtx(e,r),ae(r,{code:Z.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()}else if(o.kind==="endsWith"){if(!e.data.endsWith(o.value))r=this._getOrReturnCtx(e,r),ae(r,{code:Z.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()}else if(o.kind==="datetime"){if(!pGe(o).test(e.data))r=this._getOrReturnCtx(e,r),ae(r,{code:Z.invalid_string,validation:"datetime",message:o.message}),n.dirty()}else if(o.kind==="date"){if(!dGe.test(e.data))r=this._getOrReturnCtx(e,r),ae(r,{code:Z.invalid_string,validation:"date",message:o.message}),n.dirty()}else if(o.kind==="time"){if(!fGe(o).test(e.data))r=this._getOrReturnCtx(e,r),ae(r,{code:Z.invalid_string,validation:"time",message:o.message}),n.dirty()}else if(o.kind==="duration"){if(!nGe.test(e.data))r=this._getOrReturnCtx(e,r),ae(r,{validation:"duration",code:Z.invalid_string,message:o.message}),n.dirty()}else if(o.kind==="ip"){if(!mGe(e.data,o.version))r=this._getOrReturnCtx(e,r),ae(r,{validation:"ip",code:Z.invalid_string,message:o.message}),n.dirty()}else if(o.kind==="jwt"){if(!hGe(e.data,o.alg))r=this._getOrReturnCtx(e,r),ae(r,{validation:"jwt",code:Z.invalid_string,message:o.message}),n.dirty()}else if(o.kind==="cidr"){if(!gGe(e.data,o.version))r=this._getOrReturnCtx(e,r),ae(r,{validation:"cidr",code:Z.invalid_string,message:o.message}),n.dirty()}else if(o.kind==="base64"){if(!lGe.test(e.data))r=this._getOrReturnCtx(e,r),ae(r,{validation:"base64",code:Z.invalid_string,message:o.message}),n.dirty()}else if(o.kind==="base64url"){if(!uGe.test(e.data))r=this._getOrReturnCtx(e,r),ae(r,{validation:"base64url",code:Z.invalid_string,message:o.message}),n.dirty()}else kt.assertNever(o);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement((r)=>e.test(r),{validation:t,code:Z.invalid_string,...$e.errToObj(n)})}_addCheck(e){return new Wc({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...$e.errToObj(e)})}url(e){return this._addCheck({kind:"url",...$e.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...$e.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...$e.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...$e.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...$e.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...$e.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...$e.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...$e.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...$e.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...$e.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...$e.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...$e.errToObj(e)})}datetime(e){if(typeof e==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e});return this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...$e.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){if(typeof e==="string")return this._addCheck({kind:"time",precision:null,message:e});return this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...$e.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...$e.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...$e.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...$e.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...$e.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...$e.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...$e.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...$e.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...$e.errToObj(t)})}nonempty(e){return this.min(1,$e.errToObj(e))}trim(){return new Wc({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Wc({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Wc({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((e)=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find((e)=>e.kind==="date")}get isTime(){return!!this._def.checks.find((e)=>e.kind==="time")}get isDuration(){return!!this._def.checks.find((e)=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find((e)=>e.kind==="email")}get isURL(){return!!this._def.checks.find((e)=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find((e)=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find((e)=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((e)=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((e)=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((e)=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find((e)=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find((e)=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find((e)=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find((e)=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find((e)=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxLength(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}};Wc.create=(e)=>new Wc({checks:[],typeName:qe.ZodString,coerce:e?.coerce??!1,...at(e)});Vm=class Vm extends wt{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce)e.data=Number(e.data);if(this._getType(e)!==fe.number){let o=this._getOrReturnCtx(e);return ae(o,{code:Z.invalid_type,expected:fe.number,received:o.parsedType}),Le}let n=void 0,r=new oo;for(let o of this._def.checks)if(o.kind==="int"){if(!kt.isInteger(e.data))n=this._getOrReturnCtx(e,n),ae(n,{code:Z.invalid_type,expected:"integer",received:"float",message:o.message}),r.dirty()}else if(o.kind==="min"){if(o.inclusive?e.data<o.value:e.data<=o.value)n=this._getOrReturnCtx(e,n),ae(n,{code:Z.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),r.dirty()}else if(o.kind==="max"){if(o.inclusive?e.data>o.value:e.data>=o.value)n=this._getOrReturnCtx(e,n),ae(n,{code:Z.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),r.dirty()}else if(o.kind==="multipleOf"){if(yGe(e.data,o.value)!==0)n=this._getOrReturnCtx(e,n),ae(n,{code:Z.not_multiple_of,multipleOf:o.value,message:o.message}),r.dirty()}else if(o.kind==="finite"){if(!Number.isFinite(e.data))n=this._getOrReturnCtx(e,n),ae(n,{code:Z.not_finite,message:o.message}),r.dirty()}else kt.assertNever(o);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,$e.toString(t))}gt(e,t){return this.setLimit("min",e,!1,$e.toString(t))}lte(e,t){return this.setLimit("max",e,!0,$e.toString(t))}lt(e,t){return this.setLimit("max",e,!1,$e.toString(t))}setLimit(e,t,n,r){return new Vm({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:$e.toString(r)}]})}_addCheck(e){return new Vm({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:$e.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:$e.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:$e.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:$e.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:$e.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:$e.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:$e.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:$e.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:$e.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxValue(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}get isInt(){return!!this._def.checks.find((e)=>e.kind==="int"||e.kind==="multipleOf"&&kt.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;else if(n.kind==="min"){if(t===null||n.value>t)t=n.value}else if(n.kind==="max"){if(e===null||n.value<e)e=n.value}return Number.isFinite(t)&&Number.isFinite(e)}};Vm.create=(e)=>new Vm({checks:[],typeName:qe.ZodNumber,coerce:e?.coerce||!1,...at(e)});Gm=class Gm extends wt{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==fe.bigint)return this._getInvalidInput(e);let n=void 0,r=new oo;for(let o of this._def.checks)if(o.kind==="min"){if(o.inclusive?e.data<o.value:e.data<=o.value)n=this._getOrReturnCtx(e,n),ae(n,{code:Z.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),r.dirty()}else if(o.kind==="max"){if(o.inclusive?e.data>o.value:e.data>=o.value)n=this._getOrReturnCtx(e,n),ae(n,{code:Z.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),r.dirty()}else if(o.kind==="multipleOf"){if(e.data%o.value!==BigInt(0))n=this._getOrReturnCtx(e,n),ae(n,{code:Z.not_multiple_of,multipleOf:o.value,message:o.message}),r.dirty()}else kt.assertNever(o);return{status:r.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return ae(t,{code:Z.invalid_type,expected:fe.bigint,received:t.parsedType}),Le}gte(e,t){return this.setLimit("min",e,!0,$e.toString(t))}gt(e,t){return this.setLimit("min",e,!1,$e.toString(t))}lte(e,t){return this.setLimit("max",e,!0,$e.toString(t))}lt(e,t){return this.setLimit("max",e,!1,$e.toString(t))}setLimit(e,t,n,r){return new Gm({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:$e.toString(r)}]})}_addCheck(e){return new Gm({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:$e.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:$e.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:$e.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:$e.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:$e.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxValue(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}};Gm.create=(e)=>new Gm({checks:[],typeName:qe.ZodBigInt,coerce:e?.coerce??!1,...at(e)});qv=class qv extends wt{_parse(e){if(this._def.coerce)e.data=Boolean(e.data);if(this._getType(e)!==fe.boolean){let n=this._getOrReturnCtx(e);return ae(n,{code:Z.invalid_type,expected:fe.boolean,received:n.parsedType}),Le}return Eo(e.data)}};qv.create=(e)=>new qv({typeName:qe.ZodBoolean,coerce:e?.coerce||!1,...at(e)});A0=class A0 extends wt{_parse(e){if(this._def.coerce)e.data=new Date(e.data);if(this._getType(e)!==fe.date){let o=this._getOrReturnCtx(e);return ae(o,{code:Z.invalid_type,expected:fe.date,received:o.parsedType}),Le}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return ae(o,{code:Z.invalid_date}),Le}let n=new oo,r=void 0;for(let o of this._def.checks)if(o.kind==="min"){if(e.data.getTime()<o.value)r=this._getOrReturnCtx(e,r),ae(r,{code:Z.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()}else if(o.kind==="max"){if(e.data.getTime()>o.value)r=this._getOrReturnCtx(e,r),ae(r,{code:Z.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()}else kt.assertNever(o);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new A0({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:$e.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:$e.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e!=null?new Date(e):null}};A0.create=(e)=>new A0({checks:[],coerce:e?.coerce||!1,typeName:qe.ZodDate,...at(e)});Bv=class Bv extends wt{_parse(e){if(this._getType(e)!==fe.symbol){let n=this._getOrReturnCtx(e);return ae(n,{code:Z.invalid_type,expected:fe.symbol,received:n.parsedType}),Le}return Eo(e.data)}};Bv.create=(e)=>new Bv({typeName:qe.ZodSymbol,...at(e)});O0=class O0 extends wt{_parse(e){if(this._getType(e)!==fe.undefined){let n=this._getOrReturnCtx(e);return ae(n,{code:Z.invalid_type,expected:fe.undefined,received:n.parsedType}),Le}return Eo(e.data)}};O0.create=(e)=>new O0({typeName:qe.ZodUndefined,...at(e)});T0=class T0 extends wt{_parse(e){if(this._getType(e)!==fe.null){let n=this._getOrReturnCtx(e);return ae(n,{code:Z.invalid_type,expected:fe.null,received:n.parsedType}),Le}return Eo(e.data)}};T0.create=(e)=>new T0({typeName:qe.ZodNull,...at(e)});Uv=class Uv extends wt{constructor(){super(...arguments);this._any=!0}_parse(e){return Eo(e.data)}};Uv.create=(e)=>new Uv({typeName:qe.ZodAny,...at(e)});gf=class gf extends wt{constructor(){super(...arguments);this._unknown=!0}_parse(e){return Eo(e.data)}};gf.create=(e)=>new gf({typeName:qe.ZodUnknown,...at(e)});Kc=class Kc extends wt{_parse(e){let t=this._getOrReturnCtx(e);return ae(t,{code:Z.invalid_type,expected:fe.never,received:t.parsedType}),Le}};Kc.create=(e)=>new Kc({typeName:qe.ZodNever,...at(e)});Hv=class Hv extends wt{_parse(e){if(this._getType(e)!==fe.undefined){let n=this._getOrReturnCtx(e);return ae(n,{code:Z.invalid_type,expected:fe.void,received:n.parsedType}),Le}return Eo(e.data)}};Hv.create=(e)=>new Hv({typeName:qe.ZodVoid,...at(e)});ya=class ya extends wt{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==fe.array)return ae(t,{code:Z.invalid_type,expected:fe.array,received:t.parsedType}),Le;if(r.exactLength!==null){let s=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;if(s||i)ae(t,{code:s?Z.too_big:Z.too_small,minimum:i?r.exactLength.value:void 0,maximum:s?r.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty()}if(r.minLength!==null){if(t.data.length<r.minLength.value)ae(t,{code:Z.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()}if(r.maxLength!==null){if(t.data.length>r.maxLength.value)ae(t,{code:Z.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()}if(t.common.async)return Promise.all([...t.data].map((s,i)=>r.type._parseAsync(new Ai(t,s,t.path,i)))).then((s)=>oo.mergeArray(n,s));let o=[...t.data].map((s,i)=>r.type._parseSync(new Ai(t,s,t.path,i)));return oo.mergeArray(n,o)}get element(){return this._def.type}min(e,t){return new ya({...this._def,minLength:{value:e,message:$e.toString(t)}})}max(e,t){return new ya({...this._def,maxLength:{value:e,message:$e.toString(t)}})}length(e,t){return new ya({...this._def,exactLength:{value:e,message:$e.toString(t)}})}nonempty(e){return this.min(1,e)}};ya.create=(e,t)=>new ya({type:e,minLength:null,maxLength:null,exactLength:null,typeName:qe.ZodArray,...at(t)});In=class In extends wt{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=kt.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==fe.object){let c=this._getOrReturnCtx(e);return ae(c,{code:Z.invalid_type,expected:fe.object,received:c.parsedType}),Le}let{status:n,ctx:r}=this._processInputParams(e),{shape:o,keys:s}=this._getCached(),i=[];if(!(this._def.catchall instanceof Kc&&this._def.unknownKeys==="strip")){for(let c in r.data)if(!s.includes(c))i.push(c)}let a=[];for(let c of s){let l=o[c],d=r.data[c];a.push({key:{status:"valid",value:c},value:l._parse(new Ai(r,d,r.path,c)),alwaysSet:c in r.data})}if(this._def.catchall instanceof Kc){let c=this._def.unknownKeys;if(c==="passthrough")for(let l of i)a.push({key:{status:"valid",value:l},value:{status:"valid",value:r.data[l]}});else if(c==="strict"){if(i.length>0)ae(r,{code:Z.unrecognized_keys,keys:i}),n.dirty()}else if(c==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let l of i){let d=r.data[l];a.push({key:{status:"valid",value:l},value:c._parse(new Ai(r,d,r.path,l)),alwaysSet:l in r.data})}}if(r.common.async)return Promise.resolve().then(async()=>{let c=[];for(let l of a){let d=await l.key,f=await l.value;c.push({key:d,value:f,alwaysSet:l.alwaysSet})}return c}).then((c)=>oo.mergeObjectSync(n,c));else return oo.mergeObjectSync(n,a)}get shape(){return this._def.shape()}strict(e){return $e.errToObj,new In({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{let r=this._def.errorMap?.(t,n).message??n.defaultError;if(t.code==="unrecognized_keys")return{message:$e.errToObj(e).message??r};return{message:r}}}:{}})}strip(){return new In({...this._def,unknownKeys:"strip"})}passthrough(){return new In({...this._def,unknownKeys:"passthrough"})}extend(e){return new In({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new In({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:qe.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new In({...this._def,catchall:e})}pick(e){let t={};for(let n of kt.objectKeys(e))if(e[n]&&this.shape[n])t[n]=this.shape[n];return new In({...this._def,shape:()=>t})}omit(e){let t={};for(let n of kt.objectKeys(this.shape))if(!e[n])t[n]=this.shape[n];return new In({...this._def,shape:()=>t})}deepPartial(){return zm(this)}partial(e){let t={};for(let n of kt.objectKeys(this.shape)){let r=this.shape[n];if(e&&!e[n])t[n]=r;else t[n]=r.optional()}return new In({...this._def,shape:()=>t})}required(e){let t={};for(let n of kt.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let o=this.shape[n];while(o instanceof ba)o=o._def.innerType;t[n]=o}return new In({...this._def,shape:()=>t})}keyof(){return wQ(kt.objectKeys(this.shape))}};In.create=(e,t)=>new In({shape:()=>e,unknownKeys:"strip",catchall:Kc.create(),typeName:qe.ZodObject,...at(t)});In.strictCreate=(e,t)=>new In({shape:()=>e,unknownKeys:"strict",catchall:Kc.create(),typeName:qe.ZodObject,...at(t)});In.lazycreate=(e,t)=>new In({shape:e,unknownKeys:"strip",catchall:Kc.create(),typeName:qe.ZodObject,...at(t)});P0=class P0 extends wt{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(o){for(let i of o)if(i.result.status==="valid")return i.result;for(let i of o)if(i.result.status==="dirty")return t.common.issues.push(...i.ctx.common.issues),i.result;let s=o.map((i)=>new xs(i.ctx.common.issues));return ae(t,{code:Z.invalid_union,unionErrors:s}),Le}if(t.common.async)return Promise.all(n.map(async(o)=>{let s={...t,common:{...t.common,issues:[]},parent:null};return{result:await o._parseAsync({data:t.data,path:t.path,parent:s}),ctx:s}})).then(r);else{let o=void 0,s=[];for(let a of n){let c={...t,common:{...t.common,issues:[]},parent:null},l=a._parseSync({data:t.data,path:t.path,parent:c});if(l.status==="valid")return l;else if(l.status==="dirty"&&!o)o={result:l,ctx:c};if(c.common.issues.length)s.push(c.common.issues)}if(o)return t.common.issues.push(...o.ctx.common.issues),o.result;let i=s.map((a)=>new xs(a));return ae(t,{code:Z.invalid_union,unionErrors:i}),Le}}get options(){return this._def.options}};P0.create=(e,t)=>new P0({options:e,typeName:qe.ZodUnion,...at(t)});sT=class sT extends wt{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==fe.object)return ae(t,{code:Z.invalid_type,expected:fe.object,received:t.parsedType}),Le;let n=this.discriminator,r=t.data[n],o=this.optionsMap.get(r);if(!o)return ae(t,{code:Z.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),Le;if(t.common.async)return o._parseAsync({data:t.data,path:t.path,parent:t});else return o._parseSync({data:t.data,path:t.path,parent:t})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let r=new Map;for(let o of t){let s=Gc(o.shape[e]);if(!s.length)throw Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let i of s){if(r.has(i))throw Error(`Discriminator property ${String(e)} has duplicate value ${String(i)}`);r.set(i,o)}}return new sT({typeName:qe.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:r,...at(n)})}};I0=class I0 extends wt{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(o,s)=>{if(eT(o)||eT(s))return Le;let i=oT(o.value,s.value);if(!i.valid)return ae(n,{code:Z.invalid_intersection_types}),Le;if(tT(o)||tT(s))t.dirty();return{status:t.value,value:i.data}};if(n.common.async)return Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([o,s])=>r(o,s));else return r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};I0.create=(e,t,n)=>new I0({left:e,right:t,typeName:qe.ZodIntersection,...at(n)});Jc=class Jc extends wt{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==fe.array)return ae(n,{code:Z.invalid_type,expected:fe.array,received:n.parsedType}),Le;if(n.data.length<this._def.items.length)return ae(n,{code:Z.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Le;if(!this._def.rest&&n.data.length>this._def.items.length)ae(n,{code:Z.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty();let o=[...n.data].map((s,i)=>{let a=this._def.items[i]||this._def.rest;if(!a)return null;return a._parse(new Ai(n,s,n.path,i))}).filter((s)=>!!s);if(n.common.async)return Promise.all(o).then((s)=>oo.mergeArray(t,s));else return oo.mergeArray(t,o)}get items(){return this._def.items}rest(e){return new Jc({...this._def,rest:e})}};Jc.create=(e,t)=>{if(!Array.isArray(e))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new Jc({items:e,typeName:qe.ZodTuple,rest:null,...at(t)})};zv=class zv extends wt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==fe.object)return ae(n,{code:Z.invalid_type,expected:fe.object,received:n.parsedType}),Le;let r=[],o=this._def.keyType,s=this._def.valueType;for(let i in n.data)r.push({key:o._parse(new Ai(n,i,n.path,i)),value:s._parse(new Ai(n,n.data[i],n.path,i)),alwaysSet:i in n.data});if(n.common.async)return oo.mergeObjectAsync(t,r);else return oo.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(e,t,n){if(t instanceof wt)return new zv({keyType:e,valueType:t,typeName:qe.ZodRecord,...at(n)});return new zv({keyType:Wc.create(),valueType:e,typeName:qe.ZodRecord,...at(t)})}};Vv=class Vv extends wt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==fe.map)return ae(n,{code:Z.invalid_type,expected:fe.map,received:n.parsedType}),Le;let r=this._def.keyType,o=this._def.valueType,s=[...n.data.entries()].map(([i,a],c)=>({key:r._parse(new Ai(n,i,n.path,[c,"key"])),value:o._parse(new Ai(n,a,n.path,[c,"value"]))}));if(n.common.async){let i=new Map;return Promise.resolve().then(async()=>{for(let a of s){let c=await a.key,l=await a.value;if(c.status==="aborted"||l.status==="aborted")return Le;if(c.status==="dirty"||l.status==="dirty")t.dirty();i.set(c.value,l.value)}return{status:t.value,value:i}})}else{let i=new Map;for(let a of s){let{key:c,value:l}=a;if(c.status==="aborted"||l.status==="aborted")return Le;if(c.status==="dirty"||l.status==="dirty")t.dirty();i.set(c.value,l.value)}return{status:t.value,value:i}}}};Vv.create=(e,t,n)=>new Vv({valueType:t,keyType:e,typeName:qe.ZodMap,...at(n)});Wm=class Wm extends wt{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==fe.set)return ae(n,{code:Z.invalid_type,expected:fe.set,received:n.parsedType}),Le;let r=this._def;if(r.minSize!==null){if(n.data.size<r.minSize.value)ae(n,{code:Z.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()}if(r.maxSize!==null){if(n.data.size>r.maxSize.value)ae(n,{code:Z.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty()}let o=this._def.valueType;function s(a){let c=new Set;for(let l of a){if(l.status==="aborted")return Le;if(l.status==="dirty")t.dirty();c.add(l.value)}return{status:t.value,value:c}}let i=[...n.data.values()].map((a,c)=>o._parse(new Ai(n,a,n.path,c)));if(n.common.async)return Promise.all(i).then((a)=>s(a));else return s(i)}min(e,t){return new Wm({...this._def,minSize:{value:e,message:$e.toString(t)}})}max(e,t){return new Wm({...this._def,maxSize:{value:e,message:$e.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};Wm.create=(e,t)=>new Wm({valueType:e,minSize:null,maxSize:null,typeName:qe.ZodSet,...at(t)});C0=class C0 extends wt{constructor(){super(...arguments);this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==fe.function)return ae(t,{code:Z.invalid_type,expected:fe.function,received:t.parsedType}),Le;function n(i,a){return Lv({data:i,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,D0(),bu].filter((c)=>!!c),issueData:{code:Z.invalid_arguments,argumentsError:a}})}function r(i,a){return Lv({data:i,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,D0(),bu].filter((c)=>!!c),issueData:{code:Z.invalid_return_type,returnTypeError:a}})}let o={errorMap:t.common.contextualErrorMap},s=t.data;if(this._def.returns instanceof Km){let i=this;return Eo(async function(...a){let c=new xs([]),l=await i._def.args.parseAsync(a,o).catch((p)=>{throw c.addIssue(n(a,p)),c}),d=await Reflect.apply(s,this,l);return await i._def.returns._def.type.parseAsync(d,o).catch((p)=>{throw c.addIssue(r(d,p)),c})})}else{let i=this;return Eo(function(...a){let c=i._def.args.safeParse(a,o);if(!c.success)throw new xs([n(a,c.error)]);let l=Reflect.apply(s,this,c.data),d=i._def.returns.safeParse(l,o);if(!d.success)throw new xs([r(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new C0({...this._def,args:Jc.create(e).rest(gf.create())})}returns(e){return new C0({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new C0({args:e?e:Jc.create([]).rest(gf.create()),returns:t||gf.create(),typeName:qe.ZodFunction,...at(n)})}};N0=class N0 extends wt{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};N0.create=(e,t)=>new N0({getter:e,typeName:qe.ZodLazy,...at(t)});F0=class F0 extends wt{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return ae(t,{received:t.data,code:Z.invalid_literal,expected:this._def.value}),Le}return{status:"valid",value:e.data}}get value(){return this._def.value}};F0.create=(e,t)=>new F0({value:e,typeName:qe.ZodLiteral,...at(t)});yf=class yf extends wt{_parse(e){if(typeof e.data!=="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return ae(t,{expected:kt.joinValues(n),received:t.parsedType,code:Z.invalid_type}),Le}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return ae(t,{received:t.data,code:Z.invalid_enum_value,options:n}),Le}return Eo(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return yf.create(e,{...this._def,...t})}exclude(e,t=this._def){return yf.create(this.options.filter((n)=>!e.includes(n)),{...this._def,...t})}};yf.create=wQ;M0=class M0 extends wt{_parse(e){let t=kt.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==fe.string&&n.parsedType!==fe.number){let r=kt.objectValues(t);return ae(n,{expected:kt.joinValues(r),received:n.parsedType,code:Z.invalid_type}),Le}if(!this._cache)this._cache=new Set(kt.getValidEnumValues(this._def.values));if(!this._cache.has(e.data)){let r=kt.objectValues(t);return ae(n,{received:n.data,code:Z.invalid_enum_value,options:r}),Le}return Eo(e.data)}get enum(){return this._def.values}};M0.create=(e,t)=>new M0({values:e,typeName:qe.ZodNativeEnum,...at(t)});Km=class Km extends wt{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==fe.promise&&t.common.async===!1)return ae(t,{code:Z.invalid_type,expected:fe.promise,received:t.parsedType}),Le;let n=t.parsedType===fe.promise?t.data:Promise.resolve(t.data);return Eo(n.then((r)=>this._def.type.parseAsync(r,{path:t.path,errorMap:t.common.contextualErrorMap})))}};Km.create=(e,t)=>new Km({type:e,typeName:qe.ZodPromise,...at(t)});wa=class wa extends wt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===qe.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,o={addIssue:(s)=>{if(ae(n,s),s.fatal)t.abort();else t.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),r.type==="preprocess"){let s=r.transform(n.data,o);if(n.common.async)return Promise.resolve(s).then(async(i)=>{if(t.value==="aborted")return Le;let a=await this._def.schema._parseAsync({data:i,path:n.path,parent:n});if(a.status==="aborted")return Le;if(a.status==="dirty")return Hm(a.value);if(t.value==="dirty")return Hm(a.value);return a});else{if(t.value==="aborted")return Le;let i=this._def.schema._parseSync({data:s,path:n.path,parent:n});if(i.status==="aborted")return Le;if(i.status==="dirty")return Hm(i.value);if(t.value==="dirty")return Hm(i.value);return i}}if(r.type==="refinement"){let s=(i)=>{let a=r.refinement(i,o);if(n.common.async)return Promise.resolve(a);if(a instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return i};if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(i.status==="aborted")return Le;if(i.status==="dirty")t.dirty();return s(i.value),{status:t.value,value:i.value}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then((i)=>{if(i.status==="aborted")return Le;if(i.status==="dirty")t.dirty();return s(i.value).then(()=>({status:t.value,value:i.value}))})}if(r.type==="transform")if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!hf(s))return Le;let i=r.transform(s.value,o);if(i instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:i}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then((s)=>{if(!hf(s))return Le;return Promise.resolve(r.transform(s.value,o)).then((i)=>({status:t.value,value:i}))});kt.assertNever(r)}};wa.create=(e,t,n)=>new wa({schema:e,typeName:qe.ZodEffects,effect:t,...at(n)});wa.createWithPreprocess=(e,t,n)=>new wa({schema:t,effect:{type:"preprocess",transform:e},typeName:qe.ZodEffects,...at(n)});ba=class ba extends wt{_parse(e){if(this._getType(e)===fe.undefined)return Eo(void 0);return this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ba.create=(e,t)=>new ba({innerType:e,typeName:qe.ZodOptional,...at(t)});wu=class wu extends wt{_parse(e){if(this._getType(e)===fe.null)return Eo(null);return this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};wu.create=(e,t)=>new wu({innerType:e,typeName:qe.ZodNullable,...at(t)});j0=class j0 extends wt{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;if(t.parsedType===fe.undefined)n=this._def.defaultValue();return this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};j0.create=(e,t)=>new j0({innerType:e,typeName:qe.ZodDefault,defaultValue:typeof t.default==="function"?t.default:()=>t.default,...at(t)});L0=class L0 extends wt{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});if(R0(r))return r.then((o)=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new xs(n.common.issues)},input:n.data})}));else return{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new xs(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};L0.create=(e,t)=>new L0({innerType:e,typeName:qe.ZodCatch,catchValue:typeof t.catch==="function"?t.catch:()=>t.catch,...at(t)});Gv=class Gv extends wt{_parse(e){if(this._getType(e)!==fe.nan){let n=this._getOrReturnCtx(e);return ae(n,{code:Z.invalid_type,expected:fe.nan,received:n.parsedType}),Le}return{status:"valid",value:e.data}}};Gv.create=(e)=>new Gv({typeName:qe.ZodNaN,...at(e)});a8t=Symbol("zod_brand");iT=class iT extends wt{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}};Wv=class Wv extends wt{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});if(o.status==="aborted")return Le;if(o.status==="dirty")return t.dirty(),Hm(o.value);else return this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();else{let r=this._def.in._parseSync({data:n.data,path:n.path,parent:n});if(r.status==="aborted")return Le;if(r.status==="dirty")return t.dirty(),{status:"dirty",value:r.value};else return this._def.out._parseSync({data:r.value,path:n.path,parent:n})}}static create(e,t){return new Wv({in:e,out:t,typeName:qe.ZodPipeline})}};q0=class q0 extends wt{_parse(e){let t=this._def.innerType._parse(e),n=(r)=>{if(hf(r))r.value=Object.freeze(r.value);return r};return R0(t)?t.then((r)=>n(r)):n(t)}unwrap(){return this._def.innerType}};q0.create=(e,t)=>new q0({innerType:e,typeName:qe.ZodReadonly,...at(t)});c8t={object:In.lazycreate};(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(qe||(qe={}));S=Wc.create,j=Vm.create,l8t=Gv.create,u8t=Gm.create,Qe=qv.create,d8t=A0.create,f8t=Bv.create,p8t=O0.create,m8t=T0.create,h8t=Uv.create,_u=gf.create,g8t=Kc.create,y8t=Hv.create,he=ya.create,ee=In.create,b8t=In.strictCreate,Jm=P0.create,aT=sT.create,w8t=I0.create,_8t=Jc.create,Ks=zv.create,x8t=Vv.create,v8t=Wm.create,k8t=C0.create,E8t=N0.create,$t=F0.create,Ft=yf.create,S8t=M0.create,$8t=Km.create,D8t=wa.create,R8t=ba.create,C8t=wu.create,A8t=wa.createWithPreprocess,O8t=Wv.create});var cT=V(()=>{jv();nT();mQ();$0();_Q();Mv()});var Ko=V(()=>{cT();cT()});function lT(e){return Kv.includes(e)}var bGe,bf,Kv,xQ,wGe,vQ,_Ge,kQ,xGe,vGe,EQ,kGe,SQ,U8t,H8t,$Q,EGe,DQ,SGe,RQ,uT=20,dT=500,$Ge,z8t;var Ym=V(()=>{Ko();bGe=Ft(["pending","verified","approved","revoked"]),bf=Ft(["person","service","test"]),Kv=bf.options;xQ={nemarOwner:"service",nemarAdmin:"service","test-admin":"service","test-owner":"service","cool-vibers":"test","test-user":"test","test-pending":"test","test-verified":"test","test-revoked":"test"},wGe=Ft(["same_kind","orcid_linked","own_account","kind_changed_concurrently"]),vQ=wGe.options,_Ge=Ft(["active","pending","revoked"]),kQ=ee({field:S(),blocks:he(S()).optional(),set_on:he(S()).optional()}).passthrough(),xGe=ee({id:j().int(),username:S().nullable(),email:S(),github_username:S().nullable(),role:S(),orcid:S().nullable().optional(),created_at:S().optional(),approved_at:S().nullable().optional(),dataset_count:j().int().optional(),sandbox_completed:Qe().optional(),sandbox_completed_at:S().nullable().optional(),sandbox_dataset_id:S().nullable().optional(),service_access:Qe().optional(),status:bGe.optional(),email_verified:Qe().optional(),orcid_verified:Qe().optional(),given_name:S().nullable().optional(),family_name:S().nullable().optional(),profile_gaps:he(kQ).optional(),username_auto_assigned:Qe().optional(),account_kind:bf.optional()}).passthrough(),vGe=ee({prefix:S(),created_at:S(),last_used_at:S().nullable()}).passthrough().nullable(),EQ=ee({user:xGe,token:vGe.optional()}).passthrough(),kGe=ee({id:j().int(),username:S().nullable(),email:S(),github_username:S().nullable(),status:S(),email_verified:j().int().nullable().optional(),role:S().nullable(),created_at:S(),approved_at:S().nullable().optional(),revoked_at:S().nullable().optional(),signup_source:S().nullable().optional(),service_access:j().int().nullable().optional(),service_access_granted_at:S().nullable().optional(),given_name:S().nullable().optional(),family_name:S().nullable().optional(),orcid:S().nullable().optional(),upload_access_requested_at:S().nullable().optional(),account_kind:bf.optional(),matched_in:he(S()).optional(),match_kind:S().optional()}).passthrough(),SQ=ee({users:he(kGe),count:j().int()}).passthrough(),U8t=Ft(["assigned","would_assign","single_name","no_name","lookup_failed","conflict","exhausted","write_failed"]),H8t=Ft(["sent","already_verified","skipped_fence","rate_limited","failed","not_attempted"]),$Q=ee({suggestion:S().nullable(),based_on:Ft(["name","unavailable","exhausted"])}).passthrough(),EGe=Ft(["why_required","email_not_verified","profile_incomplete","github_username_unverified","github_unavailable","already_approved"]),DQ=EGe.options,SGe=Ft(["invalid_github_username","city_required","country_required","empty_patch","username_too_short","username_too_long","username_charset","given_name_required","family_name_required","username_taken","username_locked","name_is_orcid_canonical","account_revoked","github_unavailable","same_email","code_expired","code_incorrect","orcid_already_have","orcid_unavailable"]),RQ=SGe.options,$Ge=ee({id:j().int(),email:S(),username:S().nullable(),role:S(),status:_Ge,email_verified:Qe(),given_name:S().nullable(),family_name:S().nullable(),orcid:S().nullable(),orcid_verified:Qe(),github_username:S().nullable(),city:S().nullable(),country:S().nullable(),affiliation:S().nullable(),service_access:Qe(),service_access_granted_at:S().nullable(),upload_access_requested_at:S().nullable(),profile_gaps:he(kQ),username_auto_assigned:Qe()}).passthrough(),z8t=ee({user:$Ge.nullable()}).passthrough()});var fT,pT,K8t,DGe,J8t,RGe,CQ,AQ,mT=8,hT=100,OQ,TQ,CGe,PQ;var B0=V(()=>{Ko();Ym();fT=["given_name","family_name","affiliation","city","country"],pT=["username","github_username","email","orcid"],K8t=[...fT,...pT],DGe={given_name:S().max(200).optional(),family_name:S().max(200).optional(),affiliation:S().max(500).optional(),city:S().max(200).optional(),country:S().max(200).optional(),username:S().max(100).optional(),github_username:S().max(100).optional(),email:S().max(320).optional(),orcid:S().max(40).optional()},J8t=ee(DGe),RGe=Ft(["field_not_editable","owner_only_field","edit_own_account","owner_account","system_account","invalid_edit","orcid_already_proven","invalid_search","invalid_user_id"]),CQ=RGe.options,AQ=["exact","name","prefix","substring","fuzzy"],OQ=ee({id:j().int(),username:S().nullable(),email:S(),github_username:S().nullable(),status:S(),role:S().nullable(),account_kind:bf.optional(),email_verified:j().int().nullable().optional(),orcid:S().nullable().optional(),orcid_verified:j().int().nullable().optional(),given_name:S().nullable().optional(),family_name:S().nullable().optional(),affiliation:S().nullable().optional(),city:S().nullable().optional(),country:S().nullable().optional(),description:S().nullable().optional(),signup_source:S().nullable().optional(),created_at:S(),updated_at:S().nullable().optional(),approved_at:S().nullable().optional(),revoked_at:S().nullable().optional(),deleted_at:S().nullable().optional(),service_access:j().int().nullable().optional(),service_access_granted_at:S().nullable().optional(),service_access_granted_by:j().int().nullable().optional(),upload_access_requested_at:S().nullable().optional(),upload_access_notified_at:S().nullable().optional(),identity_conflict:j().int().nullable().optional(),username_auto_assigned:j().int().nullable().optional(),sandbox_completed:j().int().nullable().optional(),sandbox_completed_at:S().nullable().optional(),sandbox_dataset_id:S().nullable().optional(),aws_iam_username:S().nullable().optional(),dataset_count:j().int().optional(),active_tokens:j().int().optional(),linked_identities:he(S()).optional()}).passthrough(),TQ=ee({user:OQ}).passthrough(),CGe=ee({from:S().nullable(),to:S().nullable()}),PQ=ee({message:S(),changed:Ks(S(),CGe),notes:he(S()).optional(),old_address_notified:Qe().optional(),user:OQ}).passthrough()});function TGe(e){return e.startsWith("v")?e:`v${e}`}var AGe,OGe,IQ,Q8t;var gT=V(()=>{Ko();AGe=/^v?\d+\.\d+\.\d+(?:-(?:rc|alpha|beta)\d*)?$/,OGe=/^v\d+\.\d+\.\d+(?:-(?:rc|alpha|beta)\d*)?$/;IQ=S().regex(AGe,"must be a semver version, optionally v-prefixed").transform(TGe),Q8t=S().regex(OGe,"must be the canonical v-prefixed tag (vX.Y.Z)")});function FQ(e,t){if(e.zarr_index_url!=null&&e.zarr_status!=="ready")t.addIssue({code:Z.custom,message:"zarr_index_url must be null/absent unless zarr_status is 'ready'",path:["zarr_index_url"]})}function MQ(e,t){if(e.zarr_verified_at!=null&&e.zarr_verify_status==null)t.addIssue({code:Z.custom,message:"zarr_verified_at must be null/absent unless zarr_verify_status is non-null",path:["zarr_verified_at"]})}var PGe="0.4.1",yT,Xm,NQ,IGe,NGe,FGe,jQ,nBt,LQ,rBt,Yc,MGe,Jv,oBt,jGe,LGe,sBt;var bT=V(()=>{Ko();gT();yT=Ft(["openneuro","nemar","gin","other"]),Xm=Jm([$t(0),$t(1)]).nullable(),NQ=ee({dataset_id:S(),id:S().optional(),name:S(),description:S().nullable().optional(),status:S(),visibility:S(),anonymous:j().int().nullable().optional(),concept_doi:S().nullable().optional(),doi:S().nullable().optional(),created_at:S(),updated_at:S().optional(),first_published_at:S().nullable().optional(),owner_username:S().nullable().optional(),source:S().nullable().optional(),modalities:S().optional(),participants:j().int().nonnegative(),tasks:S().optional(),authors:S().optional(),license:S().optional(),file_size:j().nonnegative(),file_size_formatted:S().optional(),total_files:j().nonnegative().nullable().optional(),num_citations:j().int().nonnegative().optional(),n_channels:j().int().nullable().optional(),electrode_system:S().nullable().optional(),has_hed:Xm.optional(),hed_version:S().nullable().optional(),data_complete:Xm.optional(),bytes_present:j().nonnegative().nullable().optional(),latest_version:IQ.nullable().optional(),latest_version_at:S().nullable().optional(),subject_count:j().int().nullable().optional(),file_size_bytes:j().nullable().optional(),sessions_count:j().int().nullable().optional(),age_min:j().nullable().optional(),age_max:j().nullable().optional(),bids_version:S().nullable().optional(),zarr_status:Ft(["pending","ready","failed"]).nullable().optional(),zarr_store_count:j().int().nullable().optional(),zarr_converted_at:S().nullable().optional(),zarr_source_commit:S().nullable().optional(),zarr_errors:j().int().nullable().optional(),zarr_failure_count:j().int().nullable().optional(),zarr_deterministic:Xm.optional(),zarr_failed_at:S().nullable().optional(),zarr_index_url:S().nullable().optional(),zarr_verify_status:Ft(["verified","failed","unverifiable"]).nullable().optional(),zarr_verified_at:S().nullable().optional(),zarr_requeue_at:S().nullable().optional(),anonymity_status:Ft(["verified","findings","unverifiable"]).nullable().optional(),anonymity_checked_at:S().nullable().optional(),anonymity_findings:S().nullable().optional(),anonymity_unchecked:S().nullable().optional(),total_recording_duration:j().nullable().optional(),recording_duration_min:j().nullable().optional(),recording_duration_max:j().nullable().optional(),recording_count:j().int().nullable().optional(),recordings_unavailable:j().int().nullable().optional(),channel_count_min:j().int().nullable().optional(),channel_count_max:j().int().nullable().optional(),sampling_frequency:j().nullable().optional(),power_line_frequency:j().nullable().optional(),eeg_reference:S().nullable().optional(),placement_scheme:S().nullable().optional()}).passthrough();IGe=NQ.superRefine((e,t)=>{FQ(e,t),MQ(e,t)}),NGe=NQ.extend({file_size:j().nonnegative().nullable(),file_size_formatted:S().nullable().optional(),modalities:S().nullable().optional(),tasks:S().nullable().optional(),authors:S().nullable().optional(),license:S().nullable().optional(),owner_github:S().nullable().optional(),attestation_deposit_type:Ft(["owner","redistribution"]).nullable().optional(),attestation_key_status:Ft(["destroyed","retained"]).nullable().optional(),attestation_deidentified:Xm.optional(),attestation_no_duplicate:Xm.optional(),attestation_upstream_source:S().nullable().optional(),attestation_accepted_at:S().nullable().optional(),zarr_data_failures:ee({count:j().int().nonnegative(),detail_ref:S(),compacted_by:S().optional(),pending:j().int().nonnegative().optional(),discovered:j().int().nonnegative().optional(),events_upload_failed:$t(!0).optional(),manifest_upload_failed:$t(!0).optional()}).passthrough().nullable().optional()}).passthrough().superRefine((e,t)=>{FQ(e,t),MQ(e,t)}),FGe=ee({id:S(),name:S(),modalities:S().nullable().optional(),participants:j().int().nullable().optional(),doi:S().nullable().optional(),tasks:S().nullable().optional(),authors:S().nullable().optional(),has_hed:Xm.optional(),score:j().optional(),snippet:S().optional()}).passthrough(),jQ=Ks(S(),j().int().nonnegative()),nBt=ee({datasets:he(IGe),count:j().int().nonnegative(),total_count:j().int().nonnegative().optional(),limit:j().int().optional(),offset:j().int().optional(),excluded_unknown:j().int().nonnegative().optional(),excluded_unknown_by_facet:jQ.optional()}).passthrough(),LQ=ee({results:he(FGe),count:j().int().nonnegative(),returned:j().int().nonnegative().optional(),offset:j().int().nonnegative().optional(),limit:j().int().optional(),candidate_ceiling:j().int().optional(),truncated:Qe().optional(),method:Ft(["exact_id","text","text_fallback","semantic","unavailable"]).optional(),min_score:j().optional(),warning:S().optional(),excluded_unknown:j().int().nonnegative().optional(),excluded_unknown_by_facet:jQ.optional()}).passthrough(),rBt=ee({dataset:NGe}).passthrough(),Yc=ee({value:S(),count:j().int().nonnegative()}),MGe=ee({values:he(Yc),distinct_total:j().int().nonnegative(),truncated:Qe()}),Jv=ee({"electrode-system":he(Yc).optional(),source:he(Yc).optional(),zarr:he(Yc).optional(),powerline:he(Yc).optional(),"bids-version":he(Yc).optional(),"hed-version":he(Yc).optional(),license:he(Yc).optional(),modality:he(Yc).optional(),task:MGe.optional(),warning:S().optional()}).passthrough(),oBt=ee({schema_version:$t(PGe),doc_type:$t("dataset"),dataset_id:S().regex(/^[a-z]{2}\d+$/,"neuroschema dataset_id pattern"),name:S(),source:yT,recording_modality:he(S()).min(1),description:S().nullable().optional(),bids_version:S().nullable().optional(),license:S().nullable().optional()}).passthrough(),jGe=ee({tasks:Ks(ee({runs:he(S())}).passthrough())}).passthrough(),LGe=ee({sessions:he(S()),modalities:Ks(jGe),session_modalities:Ks(he(S())).optional()}).passthrough(),sBt=ee({version:S(),subjects:Ks(LGe)}).passthrough()});function Yv(e){return typeof e==="string"&&qQ.includes(e)}var qGe,cBt,lBt,uBt,qQ,BGe="ci_check_unavailable",BQ,UQ,HQ,zQ="X-Approval-Dispatch-Token",dBt;var U0=V(()=>{Ko();qGe=/^\d{4}-\d{4}-\d{4}-\d{3}[\dX]$/,cBt=S().regex(qGe,"ORCID must be in format 0000-0000-0000-000X"),lBt=Ft(["found","no_public_name","lookup_failed"]),uBt=Ft(["bids_validation_failed","bids_validation_pending","bids_validation_in_progress","prescreen_failed","min_requirements_failed","owner_name_missing","identifier_screen_findings"]),qQ=["bids_validation_pending","bids_validation_in_progress"];BQ=[BGe],UQ=["identifier_screen_pending","identifier_screen_not_clear","identifier_screen_not_applicable"],HQ=["publication_review_not_clear","request_blocked","request_changed","request_mismatch","dispatch_superseded","dispatch_expired","decision_with_dispatch_token","approval_in_flight","deny_after_publishing","invalid_dataset_id","approval_closed_during_run"],dBt=Ft(["filled","would_fill","no_public_name","lookup_failed","write_failed"])});var UGe,VQ,H0="https://nemar.org/settings",mBt,HGe,zGe,VGe,GQ,WQ;var wT=V(()=>{Ko();UGe=Ft(["orcid_in_use","orcid_already_linked","orcid_linked_other","email_in_use","github_in_use","identity_conflict_remains"]),VQ=UGe.options,mBt={orcid_in_use:`That ORCID iD already belongs to a NEMAR account. Sign in to that account instead; if you want the iD on a different account, unlink it there first (Settings, ${H0}).`,orcid_already_linked:`That ORCID iD already belongs to a NEMAR account. Sign in to that account instead; if you want the iD on a different account, unlink it there first (Settings, ${H0}).`,orcid_linked_other:`That ORCID iD is linked to a different NEMAR account. Unlink it there first (Settings, ${H0}), then link it here.`,email_in_use:`That email address already belongs to a NEMAR account. Sign in to that account instead, or change its address first (Settings, ${H0}).`,github_in_use:`That GitHub account is already linked to a NEMAR account. Sign in to that account instead, or change its GitHub username first (Settings, ${H0}).`,identity_conflict_remains:"The collision that flagged this account is still there. Resolve it on the other account first (change its email or GitHub username, or unlink its ORCID iD), or delete that account, then clear the flag."},HGe=Ft(["orcid","email","github"]),zGe=ee({id:j().int(),username:S().nullable(),email:S(),created_at:S(),has_oauth_identity:Qe(),dataset_count:j().int(),identity_conflict:j().int(),canonical:Qe()}).passthrough(),VGe=ee({kind:HGe,value:S(),canonical_user_id:j().int(),accounts:he(zGe)}).passthrough(),GQ=ee({groups:he(VGe),group_count:j().int(),flagged_count:j().int()}).passthrough(),WQ=ee({ok:$t(!0),id:j().int(),cleared:Qe()}).passthrough()});var _T=120,KQ=64,xT="unnamed machine",GGe=25,Xv,JQ,Qm,YQ,yBt,bBt,XQ,WGe,KGe,QQ,vT,ZQ,wBt,_Bt,Qv,Zv;var ek=V(()=>{Ko();Xv=Ft(["authorization_pending","slow_down","expired_token","access_denied","invalid_grant"]),JQ={authorization_pending:"Waiting for you to authorize this machine in the browser.",slow_down:"Polling too quickly; the CLI will slow down automatically.",expired_token:"The code expired. Run `nemar auth login` again for a new one.",access_denied:"This sign-in was declined in the browser. Run `nemar auth login` again if that was a mistake.",invalid_grant:"That code is no longer valid. Run `nemar auth login` again for a new one."},Qm=Ft(["device_code_unknown","device_code_expired","device_code_used","device_code_denied","account_pending","account_revoked","identity_conflict","service_account","person_account","too_many_keys","key_not_found"]),YQ=Qm.options,yBt={device_code_unknown:"That code was not found. Check the code shown in your terminal, or run `nemar auth login` again for a new one.",device_code_expired:"The code expired. Run `nemar auth login` again for a new one.",device_code_used:"That code has already been used. Run `nemar auth login` again for a new one.",device_code_denied:"This sign-in was declined in the browser. Run `nemar auth login` again if that was a mistake.",account_pending:"Verify your email address first. Check your inbox for the NEMAR verification code, then authorize again.",account_revoked:"Your NEMAR account access has been revoked. Contact the NEMAR team if you think this is a mistake.",identity_conflict:"This account shares an identifier with another NEMAR account and cannot sign in until that is resolved. Fix it in Settings on nemar.org or contact the NEMAR team.",service_account:"This is a service or test account, and it cannot sign in this way. Ask an owner to create a key for it with `nemar admin keys create`.",person_account:"This account belongs to a person. A person creates their own keys with `nemar auth login` or in Settings on nemar.org.",too_many_keys:`This account already has ${GGe} active keys. Revoke one in Settings on nemar.org or with \`nemar auth keys\`, then try again.`,key_not_found:"That key was not found on this account, or it is already revoked. Run `nemar auth keys` to see the active ones."},bBt=ee({error:Qm,message:S()}).passthrough(),XQ=ee({device_code:S(),user_code:S(),verification_uri:S(),verification_uri_complete:S(),expires_in:j().int(),interval:j().int()}).passthrough(),WGe=aT("error",[ee({error:$t("authorization_pending"),message:S()}).passthrough(),ee({error:$t("slow_down"),message:S()}).passthrough()]),KGe=aT("error",[ee({error:$t("expired_token"),reason:Qm,message:S()}).passthrough(),ee({error:$t("access_denied"),reason:Qm,message:S()}).passthrough(),ee({error:$t("invalid_grant"),reason:Qm,message:S()}).passthrough()]),QQ=Jm([WGe,KGe]),vT=ee({id:j().int(),name:S().nullable(),prefix:S(),created_at:S(),last_used_at:S().nullable(),current:Qe()}).passthrough(),ZQ=ee({api_key:S(),key:vT,user:ee({username:S().nullable(),email:S(),github_username:S().nullable(),role:S(),sandbox_completed:Qe(),sandbox_dataset_id:S().nullable()}).passthrough()}).passthrough(),wBt=ee({user_code:S(),machine_name:S(),requested_at:S(),expires_in:j().int(),account:ee({username:S().nullable(),email_masked:S()}).passthrough(),refusal:ee({code:Qm,message:S()}).passthrough().nullable()}).passthrough(),_Bt=ee({ok:$t(!0),machine_name:S()}).passthrough(),Qv=ee({keys:he(vT)}).passthrough(),Zv=ee({api_key:S(),key:vT}).passthrough()});function nr(e){return Nn[e]}function Xc(e,t){return e.replace(/\{(\w+)\}/g,(n,r)=>Object.hasOwn(t,r)?t[r]:n)}var Nn;var Zm=V(()=>{Nn={"tier.unverified.label":"Email not verified","tier.base.label":"Base access","tier.upload.label":"Upload access","tier.unverified.lede":"Verify your email address to activate your account.","upload_access.section.title":"Upload access","upload_access.section.lede":"A one-time admin grant. Reviewed against export-control and local-jurisdiction rules.","upload_access.state.granted":"Granted","upload_access.state.requested":"Requested","upload_access.state.not_requested":"Not requested","upload_access.invite.title":"Want to contribute a dataset?","upload_access.invite.body":"Browsing, searching and downloading are open to your account already. Uploading, or being added as a collaborator on someone else\u2019s dataset, needs one extra grant: an admin checks your GitHub handle and location against export-control and local-jurisdiction rules, once. Your email address must be verified first.","upload_access.gate.title":"Ask for upload access first","upload_access.gate.body":"Your account can browse, search and download everything public already. Uploading, or being added as a collaborator on someone else\u2019s dataset, needs one extra grant, and your email address must be verified first: an admin checks your GitHub handle and where you\u2019re based against export-control and local-jurisdiction rules. You ask once, and it is answered by email.","upload_access.request.cta":"Request upload access","upload_access.request.form_body":"Tell us what you plan to deposit, or which dataset you want to collaborate on. An admin reviews this alongside your name, username, GitHub handle and location, then grants access once.","upload_access.request.why_label":"What do you intend to upload?","upload_access.request.why_hint":"Describe what you intend to upload in 20-500 characters","upload_access.requested.title":"Your request is with an admin","upload_access.requested.lede":"An admin is reviewing your request.","upload_access.requested.lede_dated":"An admin is reviewing your request from {date}.","upload_access.requested.body.upload":"We\u2019ll email you when there\u2019s a decision, and this page will let you upload as soon as it\u2019s granted.","upload_access.requested.body":"We\u2019ll email you when there\u2019s a decision. Everything else on your account keeps working in the meantime.","upload_access.requested.cta":"See the request","upload_access.granted.body":"You can upload datasets from the upload page. Publishing one is a separate, per-dataset review you start from your dashboard.","upload_access.unverified.body":"Verify your email address first \u2014 the review happens over email.","upload_access.docs_link":"How upload access works","gap.sentence":"{label} is missing: needed {blocks}.","gap.set_on.both":"Set it in {web} or run `{cli}`.","gap.set_on.web":"Set it in {web}.","gap.blocks.verified":"to activate your account","gap.blocks.upload_access":"to request upload access","gap.blocks.publication":"to publish a dataset","gap.blocks.unknown":"to finish setting up your account","gap.blocks.noun.verified":"account activation","gap.blocks.noun.upload_access":"upload access","gap.blocks.noun.publication":"publication","gap.set_on.default_web":"Settings","gap.field.email_verified.label":"A verified email address","gap.field.username.label":"Username","gap.field.given_name.label":"Given name","gap.field.family_name.label":"Family name","gap.field.orcid_verified.label":"Verified ORCID iD","gap.field.github_username.label":"GitHub handle","gap.field.city.label":"City","gap.field.country.label":"Country","gap.field.why.label":"A description of what you intend to upload","gap.field.email_verified.set_on.web":"the verify step on your dashboard","gap.field.email_verified.set_on.cli":"nemar auth resend-verification","gap.field.username.set_on.web":"Settings","gap.field.username.set_on.cli":"nemar auth profile set-username","gap.field.given_name.set_on.web":"Settings","gap.field.given_name.set_on.cli":"nemar auth profile set-name","gap.field.family_name.set_on.web":"Settings","gap.field.family_name.set_on.cli":"nemar auth profile set-name","gap.field.given_name.set_on.web.orcid":"your ORCID record at orcid.org, then sign in again","gap.field.family_name.set_on.web.orcid":"your ORCID record at orcid.org, then sign in again","gap.field.orcid_verified.set_on.web":"Settings","gap.field.orcid_verified.set_on.cli":"nemar auth profile orcid link","gap.field.github_username.set_on.web":"Settings","gap.field.github_username.set_on.cli":"nemar auth profile set-github","gap.field.city.set_on.web":"Settings","gap.field.city.set_on.cli":"nemar auth profile set-location","gap.field.country.set_on.web":"Settings","gap.field.country.set_on.cli":"nemar auth profile set-location","gap.field.why.set_on.web":"the request form in Settings","gap.field.why.set_on.cli":"nemar auth request-upload-access","gaps.title":"What is still missing","gaps.none":"Nothing outstanding \u2014 every field NEMAR needs is filled in.","gaps.nudge.title":"Your profile isn\u2019t finished yet","gaps.nudge.cta":"Complete your profile","gaps.upload.title":"Before you can ask, your account still needs:","gaps.request.title":"Finish these first:","gaps.admin.title":"Still missing","gaps.admin.item":"{label} \u2014 blocks {blocks}","gaps.admin.none":"Nothing missing \u2014 every field the request needs is filled in.","gaps.admin.not_loaded":"Not loaded \u2014 open the user page to see what is still missing.","onboarding.username.auto_assigned.title":"We chose your username from your name","onboarding.username.auto_assigned.body":"Your account needed a username to be listed as a dataset owner, so one was made from your name when you signed in. You can change it once, here, until an admin grants you upload access.","welcome.unverified.title":"Verify your email address","welcome.unverified.body":"Authorizing with ORCID created your NEMAR account and signed you in. One step left: enter the 6-digit code we emailed you. That activates the account \u2014 no admin approval is involved.","welcome.active.title":"Your account is active","welcome.active.body":"Authorizing with ORCID created your NEMAR account and signed you in. There is no separate sign-up step and no approval queue: browse, search, and your dashboard all work right now.","welcome.upload_access.title":"Ask for upload access when you\u2019re ready to contribute","welcome.upload_access.body":"Reading is open to every verified account. Uploading and compute need one extra grant, because an admin has to check your GitHub handle and location against export-control and local-jurisdiction rules first. You ask once, from Settings.","cli.gaps.section.title":"Profile","cli.gaps.unknown":"not checked: run 'nemar auth status --refresh'","cli.gaps.unreported":"not reported by this backend","cli.gap.set_on.cli_only":"Run `{cli}`.","cli.gap.field.sandbox.label":"Sandbox training","cli.gap.blocks.sandbox":"to upload a dataset from the CLI","cli.gap.field.sandbox.set_on.cli":"nemar sandbox","cli.gaps.sandbox_unchecked":"Sandbox training could not be confirmed with the server. Run `nemar sandbox status --refresh`, then `nemar sandbox` if it is still outstanding.","cli.upload.preflight.title":"Upload access is not granted yet","cli.upload.preflight.body":"Browsing, searching and downloading are open to your account already. Uploading, or being added as a collaborator on someone else\u2019s dataset, needs one extra grant: an admin checks your GitHub handle and location against export-control and local-jurisdiction rules, once. Your email address must be verified first.","cli.upload_access.cta":"Ask for it with `nemar auth request-upload-access`.","cli.upload.preflight.unchecked":"Upload access could not be checked ({reason}); continuing.","cli.upload.preflight.gaps_unknown":"Could not determine what is still missing; run `nemar auth profile` for the list.","cli.upload.preflight.dry_run":"Continuing anyway: --dry-run uploads nothing."}});function YGe(e){return e==="verified"||e==="upload_access"||e==="publication"}function eh(e){return(e??"").trim().length===0}function XGe(e){return e==="service"||e==="test"}function nZ(e,t={}){let n=t.orcidVerified===!0,r=Object.hasOwn(tk,e)?tk[e]:void 0;if(!r)return{field:e,label:e,blocks:t.blocks??[],setOnWeb:Nn["gap.set_on.default_web"],setOnCli:null,known:!1};let o=n&&r.orcidWebKey!==void 0;return{field:e,blocks:t.blocks??r.blocks,label:Nn[r.labelKey],setOnWeb:Nn[o?r.orcidWebKey:r.webKey],setOnCli:o||r.cliKey===null?null:Nn[r.cliKey],known:!0}}function eZ(e){let t=kT.indexOf(e);return t===-1?kT.length:t}function rZ(e,t={}){return e.map((n)=>nZ(n,{orcidVerified:t.orcidVerified}))}function nk(e,t={}){return e.filter((n)=>!!n&&typeof n.field==="string").map((n)=>{let r=Array.isArray(n.blocks)?n.blocks.filter(YGe):[];return nZ(n.field,{orcidVerified:t.orcidVerified,blocks:r.length>0?r:void 0})}).sort((n,r)=>eZ(n.field)-eZ(r.field))}function ET(e){let t=e.blocks[0],n=t?Nn[JGe[t]]:Nn["gap.blocks.unknown"],r=Xc(Nn["gap.sentence"],{label:"",blocks:n}).trimStart(),o=e.setOnCli?Xc(Nn["gap.set_on.both"],{web:e.setOnWeb,cli:e.setOnCli}):Xc(Nn["gap.set_on.web"],{web:e.setOnWeb});return`${r} ${o}`}function oZ(e){return`${e.label} ${ET(e)}`}function rk(){let e=Xc(Nn["gap.sentence"],{label:tZ.label,blocks:Nn["cli.gap.blocks.sandbox"]}),t=Xc(Nn["cli.gap.set_on.cli_only"],{cli:tZ.command});return`${e} ${t}`}function sZ(){return Nn["cli.gaps.sandbox_unchecked"]}var tk,kT,EBt,JGe,tZ;var th=V(()=>{Zm();tk={email_verified:{blocks:["verified","upload_access"],labelKey:"gap.field.email_verified.label",webKey:"gap.field.email_verified.set_on.web",cliKey:"gap.field.email_verified.set_on.cli",isMissing:(e)=>e.status==="pending"||e.email_verified===!1},username:{blocks:["upload_access"],labelKey:"gap.field.username.label",webKey:"gap.field.username.set_on.web",cliKey:"gap.field.username.set_on.cli",isMissing:(e)=>e.username!==void 0&&eh(e.username)},given_name:{blocks:["upload_access","publication"],labelKey:"gap.field.given_name.label",webKey:"gap.field.given_name.set_on.web",cliKey:"gap.field.given_name.set_on.cli",orcidWebKey:"gap.field.given_name.set_on.web.orcid",isMissing:(e)=>eh(e.given_name)},family_name:{blocks:["upload_access","publication"],labelKey:"gap.field.family_name.label",webKey:"gap.field.family_name.set_on.web",cliKey:"gap.field.family_name.set_on.cli",orcidWebKey:"gap.field.family_name.set_on.web.orcid",isMissing:(e)=>eh(e.family_name)},orcid_verified:{blocks:["upload_access"],labelKey:"gap.field.orcid_verified.label",webKey:"gap.field.orcid_verified.set_on.web",cliKey:"gap.field.orcid_verified.set_on.cli",isMissing:(e)=>e.orcid_verified!==!0&&!XGe(e.account_kind)},github_username:{blocks:["upload_access","publication"],labelKey:"gap.field.github_username.label",webKey:"gap.field.github_username.set_on.web",cliKey:"gap.field.github_username.set_on.cli",isMissing:(e)=>eh(e.github_username)},city:{blocks:["upload_access"],labelKey:"gap.field.city.label",webKey:"gap.field.city.set_on.web",cliKey:"gap.field.city.set_on.cli",isMissing:(e)=>eh(e.city)},country:{blocks:["upload_access"],labelKey:"gap.field.country.label",webKey:"gap.field.country.set_on.web",cliKey:"gap.field.country.set_on.cli",isMissing:(e)=>eh(e.country)},why:{blocks:["upload_access"],labelKey:"gap.field.why.label",webKey:"gap.field.why.set_on.web",cliKey:"gap.field.why.set_on.cli",isMissing:null}},kT=Object.keys(tk),EBt=kT.filter((e)=>tk[e].isMissing!==null),JGe={verified:"gap.blocks.verified",upload_access:"gap.blocks.upload_access",publication:"gap.blocks.publication"};tZ={field:"sandbox",label:Nn["cli.gap.field.sandbox.label"],command:Nn["cli.gap.field.sandbox.set_on.cli"]}});function ak(e,t){let n=e.sss!==void 0;if(e.derived!==n)t.addIssue({code:Z.custom,path:["sss"],message:e.derived?"derived is true but sss is absent (ADR 0028: the two travel together)":"sss is present but derived is false (ADR 0028: the two travel together)"})}var So,ok,iZ,sk,QGe,ik,ZGe,eWe,tWe,nWe,rWe,DBt,oWe,RBt,sWe,CBt;var ST=V(()=>{Ko();So=/^[a-z]{2}[0-9]{6}$/,ok=/^[0-9a-f]{40}$/,iZ=ee({name:S(),modality:S().nullable().optional(),rate:j().nullable().optional(),n_channels:j().int().nonnegative().nullable().optional(),n_samples:j().int().nonnegative().nullable().optional(),duration_s:j().nonnegative().nullable().optional(),source_rate_hz:j().nullable().optional(),n_view_levels:j().int().nonnegative().optional(),view_chunk_columns:j().int().positive().optional(),chunk_samples:j().int().positive().optional(),shard_samples:j().int().positive().optional()}).passthrough(),sk=ee({converted:j().int().nonnegative().optional(),relabelled:j().int().nonnegative().optional(),kept_importer_unit:j().int().nonnegative().optional(),units_column_present:Qe().optional(),sidecar:S().optional(),sidecar_supplied:Qe().optional(),unmatched_channels:j().int().nonnegative().optional(),unmatched_case_only:j().int().positive().optional(),matched_case_only:j().int().positive().optional(),matched_case_only_examples:he(S()).max(5).optional(),unmatched_raw_label:j().int().positive().optional(),unmatched_examples:he(S()).max(5).optional()}).passthrough(),QGe=ee({channels_tsv:j().int().positive(),in_file:j().int().nonnegative(),in_store:j().int().nonnegative()}).passthrough(),ik=ee({applied:Qe().optional(),method:S().optional(),calibration:S().optional(),cross_talk:S().optional(),mne_version:S().optional()}).passthrough();ZGe=ee({path:S(),zarr:S().regex(/\.zarr$/,"must end in .zarr"),updated_utc:S().optional(),source_tree:$t("raw"),derived:Qe(),modalities:he(S()).optional(),groups:he(iZ).optional(),power_line_frequency:j().nullable().optional(),event_description_count:j().int().nonnegative().optional(),n_events:j().int().nonnegative().optional(),trial_types:Ks(S(),j().int().nonnegative()).optional(),units_report:sk.optional(),channels_tsv_read_error:Qe().optional(),channels_tsv_count_mismatch:QGe.optional(),split_members:he(S()).optional(),sss:ik.optional()}).passthrough().superRefine(ak),eWe=ee({path:S(),zarr:S().regex(/\.zarr$/,"must end in .zarr").optional(),code:S(),reason:S(),detail:S().nullable().optional(),attempts:j().int().nonnegative().optional()}).passthrough(),tWe=Ft(["infra_failure","memory_budget","not_attempted"]),nWe=ee({path:S(),zarr:S().regex(/\.zarr$/,"must end in .zarr"),reason:tWe,attempts:j().int().nonnegative(),last_error:S().nullable().optional(),last_attempt_utc:S().nullable().optional()}).passthrough(),rWe=ee({level0:$t("<zarr>/<group>/0"),view:$t("<zarr>/<group>/view/<L>"),view_levels:$t("1..n_view_levels from the group attrs"),scale_offset:$t("level-0 array attrs scale[] and offset[]; physical = digital * scale + offset"),events:$t("<data_base>events.parquet").optional()}).passthrough(),DBt=ee({format:$t("nemar-zarr-index"),format_version:$t(3),dataset_id:S().regex(So,"NEMAR dataset id (nm/on/xx band)"),contract_base:S().regex(/^https:\/\//,"must be https"),data_base:S().regex(/^https:\/\//,"must be https"),data_base_kind:$t("s3-public"),s3_uri:S().regex(/^s3:\/\//,"must be an s3:// URI"),s3_region:S().min(1),s3_anonymous:Qe(),source_commit:S().regex(ok,"must be a full 40-hex SHA"),engine_version:S().min(1),biosigio_version:S().nullable().optional(),updated_utc:S(),discovered_count:j().int().nonnegative(),store_count:j().int().nonnegative(),n_recordings:j().int().nonnegative(),errors:j().int().nonnegative(),failure_count:j().int().nonnegative(),pending_count:j().int().nonnegative(),stores:he(ZGe),failures:he(eWe),pending:he(nWe),doi:S().nullable().optional(),license:S().nullable().optional(),citation:S().nullable().optional(),hed_version:S().nullable().optional(),events_parquet:S().regex(/^https:\/\//,"must be https").optional(),events_row_count:j().int().nonnegative().optional(),layout:rWe}).passthrough(),oWe=ee({name:S(),configuration:Ks(S(),_u()).optional()}).passthrough(),RBt=ee({zarr_format:$t(3),node_type:$t("array"),shape:he(j().int().nonnegative()),data_type:S(),chunk_grid:ee({name:S(),configuration:Ks(S(),_u()).optional()}).passthrough(),codecs:he(oWe),fill_value:_u().optional(),attributes:Ks(S(),_u()).optional(),dimension_names:he(S().nullable()).optional()}).passthrough(),sWe=ee({path:S(),zarr:S().regex(/\.zarr$/,"must end in .zarr"),groups:he(iZ).optional(),modalities:he(S()).optional()}).passthrough(),CBt=ee({format:$t("nemar-zarr-index"),format_version:j().int(),dataset_id:S().regex(So,"NEMAR dataset id (nm/on/xx band)"),source_commit:S(),stores:he(sWe)}).passthrough()});function aZ(e){let t=e.unit?` (${e.unit})`:"";switch(e.valueKind){case"enum":return`${e.label} -- comma-separated, one or more of: ${(e.enumValues??[]).join(", ")}`;case"number":return`${e.label}${t} -- range (e.g. 10..50, 10.., ..50, or 10)`;case"bytes":return`${e.label}${t} -- range with optional units (e.g. 10gb..2tb, 500mb.., ..1gb; bare = bytes)`;case"duration":return`${e.label}${t} -- range with optional units (e.g. 30m..2h, 100h.., ..90s; bare = seconds)`;case"text":return`${e.label} -- substring match`;case"version":return`${e.label} -- exact or prefix match`}}var iWe,aWe,cWe,lWe,_a,TBt;var ck=V(()=>{bT();iWe=["10-05","10-10","10-20","biosemi","egi-geodesic","other"],aWe=["50","60"],cWe=["ready","pending","failed"],lWe=yT.options,_a=[{key:"subjects",flag:"--subjects",queryParam:"subjects",valueKind:"number",label:"Subject count",unit:"subjects"},{key:"channels",flag:"--channels",queryParam:"channels",valueKind:"number",label:"Channel count",unit:"channels"},{key:"sessions",flag:"--sessions",queryParam:"sessions",valueKind:"number",label:"Session count",unit:"sessions"},{key:"size",flag:"--size",queryParam:"size",valueKind:"bytes",label:"Dataset size"},{key:"files",flag:"--files",queryParam:"files",valueKind:"number",label:"File count",unit:"files"},{key:"citations",flag:"--citations",queryParam:"citations",valueKind:"number",label:"Citation count",unit:"citations"},{key:"duration",flag:"--duration",queryParam:"duration",valueKind:"duration",label:"Total recording duration"},{key:"recording-length",flag:"--recording-length",queryParam:"recording_length",valueKind:"duration",label:"Per-recording duration"},{key:"recordings",flag:"--recordings",queryParam:"recordings",valueKind:"number",label:"Recording count",unit:"recordings"},{key:"unavailable",flag:"--unavailable",queryParam:"unavailable",valueKind:"number",label:"Unavailable recording count",unit:"recordings"},{key:"age",flag:"--age",queryParam:"age",valueKind:"number",label:"Participant age",unit:"years"},{key:"rate",flag:"--rate",queryParam:"rate",valueKind:"number",label:"Sampling rate",unit:"Hz"},{key:"powerline",flag:"--powerline",queryParam:"powerline",valueKind:"enum",label:"Power line frequency",enumValues:aWe},{key:"reference",flag:"--reference",queryParam:"reference",valueKind:"text",label:"EEG reference"},{key:"placement",flag:"--placement",queryParam:"placement",valueKind:"text",label:"Electrode placement scheme"},{key:"electrode-system",flag:"--electrode-system",queryParam:"electrode_system",valueKind:"enum",label:"Electrode system",enumValues:iWe},{key:"source",flag:"--source",queryParam:"source",valueKind:"enum",label:"Source archive",enumValues:lWe},{key:"zarr",flag:"--zarr",queryParam:"zarr",valueKind:"enum",label:"Zarr conversion status",enumValues:cWe},{key:"bids-version",flag:"--bids-version",queryParam:"bids_version",valueKind:"version",label:"BIDS version"},{key:"hed-version",flag:"--hed-version",queryParam:"hed_version",valueKind:"version",label:"HED version"}],TBt=new Map(_a.map((e)=>[e.key,e]))});var uWe,MBt,dWe,fZ,z0,cZ,fWe,pZ,pWe=20,mWe=100,hWe,mZ,gWe,jBt,LBt,yWe,qBt,BBt,bWe,wWe,_We,UBt,xWe=50,vWe=500,HBt,kWe,EWe,zBt,SWe=1000,$We=5000,lZ=8,DWe=100,RWe=32,uZ,VBt,CWe,AWe,OWe,GBt,TWe=800,PWe=4000,WBt,KBt,$T=60,DT=64,dZ,IWe=86400,NWe=4096,JBt,FWe,MWe,YBt;var hZ=V(()=>{Ko();ck();ST();uWe=ee({dataset_id:S().regex(So),name:S(),doi:S().nullable().optional(),license:S().nullable().optional(),modalities:he(S()).optional(),tasks:he(S()).optional(),subject_count:j().int().nonnegative().nullable().optional(),has_hed:Jm([$t(0),$t(1)]).nullable().optional(),hed_version:S().nullable().optional(),store_count:j().int().nonnegative().nullable().optional(),recording_count:j().int().nonnegative().nullable().optional(),recordings_unavailable:j().int().nonnegative().nullable().optional(),total_recording_duration:j().nullable().optional(),zarr_converted_at:S().nullable().optional(),zarr_source_commit:S().nullable().optional(),zarr_errors:j().int().nonnegative().nullable().optional(),zarr_verify_status:Ft(["verified","failed","unverifiable"]).nullable().optional(),zarr_verified_at:S().nullable().optional(),index_url:S().nullable().optional()}).passthrough(),MBt=ee({format:$t("nemar-zarr-catalog"),format_version:j().int(),generated_utc:S(),contract_base:S(),count:j().int().nonnegative(),datasets:he(uWe)}).passthrough(),dWe=["verified","failed","unverifiable"],fZ=Ft(dWe).nullable(),z0=ee({dataset_id:S().regex(So),doi:S().nullable(),license:S().nullable(),citation:S().nullable(),source_commit:S().regex(ok),index_etag:S().nullable(),engine_version:S(),source_tree:$t("raw"),derived:Qe(),sss:ik.optional(),lossy:Qe(),dtype:S().nullable(),effective_rate_hz:j().nullable(),source_rate_hz:j().nullable(),units_report:sk.nullable().optional(),zarr_verify_status:fZ,note:S().nullable().optional()}).passthrough().superRefine(ak),cZ=ee({start:j().int().nonnegative(),end:j().int().nonnegative()}).passthrough().refine((e)=>e.end>=e.start,{message:"end must be >= start",path:["end"]}),fWe=ee({python_zarr:S(),zarrita:S(),python_browser:S()}).passthrough(),pZ=ee({contract_base:S(),data_base:S(),s3_uri:S(),s3_region:S(),s3_anonymous:Qe(),zarr:S(),group:S(),level:Jm([$t("0"),j().int().positive()]),array_path:S(),dtype:S().nullable(),codecs:he(_u()).optional(),chunk_samples:j().int().positive().nullable(),shard_samples:j().int().positive().nullable(),n_channels:j().int().nonnegative().nullable(),sample_slice:cZ.optional(),channel_slice:cZ.optional(),scale_offset:S(),how_to:fWe}).passthrough(),hWe=Object.fromEntries(_a.map((e)=>[e.queryParam,S().optional()])),mZ={modality:S().optional(),task:S().optional(),has_hed:Qe().optional(),has_zarr:Qe().optional(),author:S().optional(),has_doi:Qe().optional(),has_zarr_verified:Qe().optional(),data_complete:Qe().optional(),recent:j().int().positive().optional(),license:S().optional()},gWe=Object.keys(mZ),jBt=[...gWe,..._a.map((e)=>e.queryParam)],LBt=ee({query:S().optional(),...mZ,include_unknown:Qe().optional(),...hWe,limit:j().int().positive().max(mWe).default(pWe)}).passthrough(),yWe=ee({dataset_id:S().regex(So),name:S(),doi:S().nullable().optional(),license:S().nullable().optional(),modalities:he(S()).optional(),tasks:he(S()).optional(),subject_count:j().int().nullable().optional(),has_hed:Qe().nullable().optional(),has_zarr:Qe()}).passthrough(),qBt=ee({results:he(yWe),count:j().int().nonnegative(),limit:j().int(),note:S().nullable().optional(),truncated:Qe().optional()}).passthrough(),BBt=ee({dataset_id:S().regex(So)}).passthrough(),bWe=["list_recordings","get_events","render_overview","read_window"],wWe=ee({next_cheapest_tool:Ft(bWe),reason:S()}).passthrough(),_We=["pending","ready","failed"],UBt=ee({dataset_id:S().regex(So),name:S(),doi:S().nullable(),license:S().nullable(),citation:S().nullable(),modalities:he(S()).optional(),tasks:he(S()).optional(),subject_count:j().int().nullable().optional(),has_hed:Qe().nullable().optional(),hed_version:S().nullable().optional(),recording_count:j().int().nullable().optional(),total_recording_duration_s:j().nullable().optional(),zarr_status:Ft(_We).nullable().optional(),zarr_verify_status:fZ.optional(),zarr_source_commit:S().nullable().optional(),zarr_store_count:j().int().nullable().optional(),cost_hint:wWe}).passthrough(),HBt=ee({dataset_id:S().regex(So),modality:S().optional(),min_duration_s:j().nonnegative().optional(),include_derived:Qe().default(!1),limit:j().int().positive().max(vWe).default(xWe),offset:j().int().nonnegative().default(0)}).passthrough(),kWe=ee({name:S(),modality:S().nullable().optional(),rate:j().nullable().optional(),n_channels:j().int().nullable().optional(),duration_s:j().nullable().optional(),n_view_levels:j().int().nonnegative().nullable().optional(),n_samples:j().int().nonnegative().nullable().optional(),view_chunk_columns:j().int().positive().nullable().optional()}).passthrough(),EWe=ee({path:S(),zarr:S(),source_tree:$t("raw"),derived:Qe(),groups:he(kWe).optional(),n_events:j().int().nonnegative().optional(),sss:ik.optional(),units_report:sk.optional()}).passthrough().superRefine(ak),zBt=ee({dataset_id:S().regex(So),source_commit:S().regex(ok).nullable(),recordings:he(EWe),total_count:j().int().nonnegative(),excluded_derived_count:j().int().nonnegative(),limit:j().int(),offset:j().int(),index_format_version:j().int(),discovered_count:j().int().nonnegative().nullable(),failure_count:j().int().nonnegative().nullable(),pending_count:j().int().nonnegative().nullable(),excluded_legacy_non_raw_count:j().int().nonnegative(),note:S().nullable().optional(),envelope:z0.optional()}).passthrough(),uZ=S().min(1).max(64),VBt=ee({dataset_id:S().regex(So),recording:S(),group:S().optional(),limit:j().int().positive().max($We).default(SWe),offset:j().int().nonnegative().default(0),where:Ks(uZ,he(Jm([S(),j()])).min(1).max(DWe)).refine((e)=>{let t=Object.keys(e).length;return t>=1&&t<=lZ},{message:`where names 1 to ${lZ} columns`}).optional(),columns:he(uZ).min(1).max(RWe).optional()}).passthrough(),CWe=ee({store_path:S(),group_name:S(),onset_s:j(),duration_s:j().nullable().optional(),sample_index:j().int().nonnegative(),trial_type:S().nullable().optional(),value:Jm([S(),j()]).nullable().optional(),hed:S().nullable().optional()}).passthrough(),AWe=CWe.partial().required({onset_s:!0,sample_index:!0}),OWe=ee({name:S(),distinct_count:j().int().nonnegative(),null_count:j().int().nonnegative(),values:he(ee({value:S(),count:j().int().positive()}).passthrough()).nullable()}).passthrough(),GBt=ee({dataset_id:S().regex(So),recording:S(),events:he(AWe),source:Ft(["events_parquet","events_tsv_fallback"]),estimated:Qe(),total_count:j().int().nonnegative(),limit:j().int(),offset:j().int(),truncated:Qe(),note:S().nullable().optional(),columns_summary:he(OWe).optional(),envelope:z0.optional()}).passthrough(),WBt=ee({dataset_id:S().regex(So),recording:S(),group:S().optional(),width_px:j().int().positive().max(PWe).default(TWe)}).passthrough(),KBt=ee({dataset_id:S().regex(So),recording:S(),group:S(),level:j().int().positive(),width_px:j().int().positive(),height_px:j().int().positive(),mime_type:$t("image/png"),columns_read:j().int().nonnegative(),chunks_read:j().int().nonnegative(),bytes_read:j().int().nonnegative(),envelope:z0.optional()}).passthrough(),dZ=$T*DT,JBt=ee({dataset_id:S().regex(So),recording:S(),group:S().optional(),start_s:j().nonnegative().default(0),duration_s:j().positive().max(IWe).default(10),channels:he(j().int().nonnegative()).max(NWe).optional(),taste:Qe().default(!1)}).passthrough().superRefine((e,t)=>{if(!e.taste)return;if(!e.channels||e.channels.length===0){t.addIssue({code:Z.custom,message:"taste requires channels: name the channel indices you want (list_recordings reports each group's n_channels), or omit taste for a recipe",path:["channels"]});return}if(e.duration_s>$T)t.addIssue({code:Z.custom,message:`taste duration_s (${e.duration_s}) exceeds the ${$T} s cap; omit taste for a recipe instead`,path:["duration_s"]});if(e.channels.length>DT)t.addIssue({code:Z.custom,message:`taste channels (${e.channels.length}) exceeds the ${DT}-channel cap; omit taste for a recipe instead`,path:["channels"]});let n=e.duration_s*e.channels.length;if(n>dZ)t.addIssue({code:Z.custom,message:`taste exceeds the cap of ${dZ} channel-seconds (duration_s x channels = ${n}); omit taste for a recipe instead`,path:["duration_s"]})}),FWe=ee({mode:$t("recipe"),recipe:pZ,envelope:z0}).passthrough(),MWe=ee({mode:$t("taste"),start_s:j(),duration_s:j(),channels:he(j().int()),sample_rate_hz:j(),values:he(he(j())),recipe:pZ,chunks_read:j().int().nonnegative(),bytes_read:j().int().nonnegative(),filled_ranges:he(ee({start_sample:j().int().nonnegative(),end_sample:j().int().nonnegative(),start_s:j(),end_s:j()}).passthrough()),note:S().nullable().optional(),envelope:z0}).passthrough(),YBt=aT("mode",[FWe,MWe])});var nh=V(()=>{gT();Ym();bT();U0();wT();ek();Zm();th();ST();hZ()});function Jo(e){return typeof e==="string"&&qWe.test(e)&&!e.includes("..")}function Qc(e){return/^v\d/.test(e)?e.slice(1):e}function Sr(e,t){return Qc(e)===Qc(t)}var qWe;var xa=V(()=>{qWe=/^[0-9A-Za-z][0-9A-Za-z._-]{0,63}$/});function G(e){if(e instanceof Error)return e.message;return String(e)}function uk(e){if(!(e instanceof L)||e.statusCode!==404)return!1;let t=e.rawBody;return typeof t==="object"&&t!==null&&t.error==="Not Found"&&typeof t.message==="string"}var L,vu;var Ke=V(()=>{L=class L extends Error{statusCode;details;step;blockReason;missing;code;reason;rawBody;constructor(e,t,n,r,o,s){super(t);this.statusCode=e;this.details=n;this.step=r;this.blockReason=o;this.missing=s;this.name="ApiError"}};vu=class vu extends L{mode;eta;constructor(e,t,n,r){super(503,t,r);this.mode=e;this.eta=n;this.name="MaintenanceError"}}});var BWe,UWe,HWe,g5t,bZ="override_publication_review",wZ="publication_review_not_clear",AT=2000;var dk=V(()=>{BWe=["dispatched","redispatched","dispatch_claimed"],UWe=["review_disabled","not_applicable","not_owned_here","request_not_requested","screen_not_ready","running","has_result","platform_limit"],HWe=["dispatch_failed","dispatch_unconfigured"],g5t=[...BWe,...UWe,...HWe]});var fk=1e4;function pk(e){return e?VWe:va}var va,w5t,zWe,VWe,OT;var mk=V(()=>{va=["ci_check","enrichment_check","s3_public_read","repo_public","tag_protect","doi_create","update_metadata","update_readme","create_tag","create_release","upload_to_zenodo","publish_doi","version_doi","s3_lock","sync_nemar","notify_user"],w5t=va.slice(0,va.indexOf("s3_public_read")),zWe=["update_metadata","update_readme","upload_to_zenodo","publish_doi"],VWe=va.filter((e)=>!zWe.includes(e));OT={ci_check:"Check CI",enrichment_check:"Enrichment check",s3_public_read:"S3 public read",repo_public:"Make catalog row public",tag_protect:"Tag protection",doi_create:"Create DOI",update_metadata:"Update metadata",update_readme:"Update README",create_tag:"Create version tag",create_release:"Create GitHub release",upload_to_zenodo:"Upload to Zenodo (no-op)",publish_doi:"Publish DOI (irreversible)",version_doi:"Version DOI + manifest",s3_lock:"S3 Object Lock",sync_nemar:"Sync NEMAR (no-op)",notify_user:"Notify user"}});function GWe(e){return`%${e.replace(/[\\%_]/g,"\\$&")}%`}function WWe(e){return new TextEncoder().encode(GWe(e)).length}function _Z(e){if(WWe(e)<=50)return null;return["search is too long: its match pattern may be at most 50 bytes,","which is about 48 plain characters (each of _ % \\ counts twice and a non-ASCII","character counts by its UTF-8 length)"].join(" ")}function hk(e){return e.replace(/[A-Z]/g,(t)=>t.toLowerCase())}function xZ(e,t){if(e==="")return!0;let n=hk(e);return t.some((r)=>typeof r==="string"&&hk(r).includes(n))}function vZ(e,t){return hk(e)===hk(t)}function gk(e){let t=[],n="",r="start",o=!1;for(let s of e)switch(s){case"\\":{if(r==="index")throw Error("Invalid character in an index");if(r==="indexEnd")throw Error("Invalid character after an index");if(o)n+=s;r="property",o=!o;break}case".":{if(r==="index")throw Error("Invalid character in an index");if(r==="indexEnd"){r="property";break}if(o){o=!1,n+=s;break}if(TT.has(n))return[];t.push(n),n="",r="property";break}case"[":{if(r==="index")throw Error("Invalid character in an index");if(r==="indexEnd"){r="index";break}if(o){o=!1,n+=s;break}if(r==="property"){if(TT.has(n))return[];t.push(n),n=""}r="index";break}case"]":{if(r==="index"){t.push(Number.parseInt(n,10)),n="",r="indexEnd";break}if(r==="indexEnd")throw Error("Invalid character after an index")}default:{if(r==="index"&&!KWe.has(s))throw Error("Invalid character in an index");if(r==="indexEnd")throw Error("Invalid character after an index");if(r==="start")r="property";if(o)o=!1,n+="\\";n+=s}}if(o)n+="\\";switch(r){case"property":{if(TT.has(n))return[];t.push(n);break}case"index":throw Error("Index was not closed");case"start":{t.push("");break}}return t}function PT(e,t){if(typeof t!=="number"&&Array.isArray(e)){let n=Number.parseInt(t,10);return Number.isInteger(n)&&e[n]===e[t]}return!1}function kZ(e,t){if(PT(e,t))throw Error("Cannot use string index")}function EZ(e,t,n){if(!wf(e)||typeof t!=="string")return n===void 0?e:n;let r=gk(t);if(r.length===0)return n;for(let o=0;o<r.length;o++){let s=r[o];if(PT(e,s))e=o===r.length-1?void 0:null;else e=e[s];if(e===void 0||e===null){if(o!==r.length-1)return n;break}}return e===void 0?n:e}function IT(e,t,n){if(!wf(e)||typeof t!=="string")return e;let r=e,o=gk(t);for(let s=0;s<o.length;s++){let i=o[s];if(kZ(e,i),s===o.length-1)e[i]=n;else if(!wf(e[i]))e[i]=typeof o[s+1]==="number"?[]:{};e=e[i]}return r}function SZ(e,t){if(!wf(e)||typeof t!=="string")return!1;let n=gk(t);for(let r=0;r<n.length;r++){let o=n[r];if(kZ(e,o),r===n.length-1)return delete e[o],!0;if(e=e[o],!wf(e))return!1}}function $Z(e,t){if(!wf(e)||typeof t!=="string")return!1;let n=gk(t);if(n.length===0)return!1;for(let r of n){if(!wf(e)||!(r in e)||PT(e,r))return!1;e=e[r]}return!0}var wf=(e)=>{let t=typeof e;return e!==null&&(t==="object"||t==="function")},TT,KWe;var DZ=V(()=>{TT=new Set(["__proto__","prototype","constructor"]),KWe=new Set("0123456789")});import $n from"path";import RZ from"os";import NT from"process";function MT(e,{suffix:t="nodejs"}={}){if(typeof e!=="string")throw TypeError(`Expected a string, got ${typeof e}`);if(t)e+=`-${t}`;if(NT.platform==="darwin")return JWe(e);if(NT.platform==="win32")return YWe(e);return XWe(e)}var ku,FT,oh,JWe=(e)=>{let t=$n.join(ku,"Library");return{data:$n.join(t,"Application Support",e),config:$n.join(t,"Preferences",e),cache:$n.join(t,"Caches",e),log:$n.join(t,"Logs",e),temp:$n.join(FT,e)}},YWe=(e)=>{let t=oh.APPDATA||$n.join(ku,"AppData","Roaming"),n=oh.LOCALAPPDATA||$n.join(ku,"AppData","Local");return{data:$n.join(n,e,"Data"),config:$n.join(t,e,"Config"),cache:$n.join(n,e,"Cache"),log:$n.join(n,e,"Log"),temp:$n.join(FT,e)}},XWe=(e)=>{let t=$n.basename(ku);return{data:$n.join(oh.XDG_DATA_HOME||$n.join(ku,".local","share"),e),config:$n.join(oh.XDG_CONFIG_HOME||$n.join(ku,".config"),e),cache:$n.join(oh.XDG_CACHE_HOME||$n.join(ku,".cache"),e),log:$n.join(oh.XDG_STATE_HOME||$n.join(ku,".local","state"),e),temp:$n.join(FT,t,e)}};var CZ=V(()=>{ku=RZ.homedir(),FT=RZ.tmpdir(),{env:oh}=NT});var QWe=(e,t)=>{let{onError:n}=t;return function(...o){return e.apply(void 0,o).catch(n)}},ka;var AZ=V(()=>{ka=QWe});var ZWe=(e,t)=>{let{onError:n}=t;return function(...o){try{return e.apply(void 0,o)}catch(s){return n(s)}}},Oi;var OZ=V(()=>{Oi=ZWe});var TZ=250;var PZ=()=>{};var eKe=(e,t)=>{let{isRetriable:n}=t;return function(o){let{timeout:s}=o,i=o.interval??TZ,a=Date.now()+s;return function c(...l){return e.apply(void 0,l).catch((d)=>{if(!n(d))throw d;if(Date.now()>=a)throw d;let f=Math.round(i*Math.random());if(f>0)return new Promise((m)=>setTimeout(m,f)).then(()=>c.apply(void 0,l));else return c.apply(void 0,l)})}}},Ea;var IZ=V(()=>{PZ();Ea=eKe});var tKe=(e,t)=>{let{isRetriable:n}=t;return function(o){let{timeout:s}=o,i=Date.now()+s;return function(...c){while(!0)try{return e.apply(void 0,c)}catch(l){if(!n(l))throw l;if(Date.now()>=i)throw l;continue}}}},Sa;var NZ=V(()=>{Sa=tKe});var jT=V(()=>{AZ();OZ();IZ();NZ()});var V0,LT;var FZ=V(()=>{qT();V0={isChangeErrorOk:(e)=>{if(!V0.isNodeError(e))return!1;let{code:t}=e;if(t==="ENOSYS")return!0;if(!MZ&&(t==="EINVAL"||t==="EPERM"))return!0;return!1},isNodeError:(e)=>e instanceof Error,isRetriableError:(e)=>{if(!V0.isNodeError(e))return!1;let{code:t}=e;if(t==="EMFILE"||t==="ENFILE"||t==="EAGAIN"||t==="EBUSY"||t==="EACCESS"||t==="EACCES"||t==="EACCS"||t==="EPERM")return!0;return!1},onChangeError:(e)=>{if(!V0.isNodeError(e))throw e;if(V0.isChangeErrorOk(e))return;throw e}},LT=V0});import jZ from"process";var G0,Qo,MZ,Vr;var qT=V(()=>{FZ();G0={onError:LT.onChangeError},Qo={onError:()=>{return}},MZ=jZ.getuid?!jZ.getuid():!1,Vr={isRetriable:LT.isRetriableError}});import Ot from"fs";import{promisify as so}from"util";var nKe,$r;var BT=V(()=>{jT();jT();qT();nKe={attempt:{chmod:ka(so(Ot.chmod),G0),chown:ka(so(Ot.chown),G0),close:ka(so(Ot.close),Qo),fsync:ka(so(Ot.fsync),Qo),mkdir:ka(so(Ot.mkdir),Qo),realpath:ka(so(Ot.realpath),Qo),stat:ka(so(Ot.stat),Qo),unlink:ka(so(Ot.unlink),Qo),chmodSync:Oi(Ot.chmodSync,G0),chownSync:Oi(Ot.chownSync,G0),closeSync:Oi(Ot.closeSync,Qo),existsSync:Oi(Ot.existsSync,Qo),fsyncSync:Oi(Ot.fsync,Qo),mkdirSync:Oi(Ot.mkdirSync,Qo),realpathSync:Oi(Ot.realpathSync,Qo),statSync:Oi(Ot.statSync,Qo),unlinkSync:Oi(Ot.unlinkSync,Qo)},retry:{close:Ea(so(Ot.close),Vr),fsync:Ea(so(Ot.fsync),Vr),open:Ea(so(Ot.open),Vr),readFile:Ea(so(Ot.readFile),Vr),rename:Ea(so(Ot.rename),Vr),stat:Ea(so(Ot.stat),Vr),write:Ea(so(Ot.write),Vr),writeFile:Ea(so(Ot.writeFile),Vr),closeSync:Sa(Ot.closeSync,Vr),fsyncSync:Sa(Ot.fsyncSync,Vr),openSync:Sa(Ot.openSync,Vr),readFileSync:Sa(Ot.readFileSync,Vr),renameSync:Sa(Ot.renameSync,Vr),statSync:Sa(Ot.statSync,Vr),writeSync:Sa(Ot.writeSync,Vr),writeFileSync:Sa(Ot.writeFileSync,Vr)}},$r=nKe});import _f from"process";var LZ="utf8",UT=438,qZ=511,BZ,UZ,HZ,zZ=1000,VZ,Y5t,HT=128;var zT=V(()=>{BZ={},UZ=_f.geteuid?_f.geteuid():-1,HZ=_f.getegid?_f.getegid():-1,VZ=!!_f.getuid,Y5t=_f.getuid?!_f.getuid():!1});var GZ=(e)=>e instanceof Error&&("code"in e),VT=(e)=>typeof e==="string",yk=(e)=>e===void 0;var WZ=()=>{};var KZ=()=>{};import JZ from"process";var YZ,bk;var GT=V(()=>{YZ=JZ.platform==="linux",bk=JZ.platform==="win32"});var WT,XZ;var QZ=V(()=>{GT();WT=["SIGHUP","SIGINT","SIGTERM"];if(!bk)WT.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");if(YZ)WT.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");XZ=WT});import sh from"process";class ZZ{constructor(){this.callbacks=new Set,this.exited=!1,this.exit=(e)=>{if(this.exited)return;this.exited=!0;for(let t of this.callbacks)t();if(e)if(bk&&(e!=="SIGINT"&&e!=="SIGTERM"&&e!=="SIGKILL"))sh.kill(sh.pid,"SIGTERM");else sh.kill(sh.pid,e)},this.hook=()=>{sh.once("exit",()=>this.exit());for(let e of XZ)try{sh.once(e,()=>this.exit(e))}catch{}},this.register=(e)=>(this.callbacks.add(e),()=>{this.callbacks.delete(e)}),this.hook()}}var eee;var tee=V(()=>{GT();QZ();eee=new ZZ});var rKe,nee;var ree=V(()=>{tee();rKe=eee.register,nee=rKe});import oKe from"path";var vs,W0;var oee=V(()=>{BT();ree();zT();vs={store:{},create:(e)=>{let t=`000000${Math.floor(Math.random()*16777215).toString(16)}`.slice(-6),n=Date.now().toString().slice(-10),r="tmp-",o=`.tmp-${n}${t}`;return`${e}${o}`},get:(e,t,n=!0)=>{let r=vs.truncate(t(e));if(r in vs.store)return vs.get(e,t,n);return vs.store[r]=n,[r,()=>delete vs.store[r]]},purge:(e)=>{if(!vs.store[e])return;delete vs.store[e],$r.attempt.unlink(e)},purgeSync:(e)=>{if(!vs.store[e])return;delete vs.store[e],$r.attempt.unlinkSync(e)},purgeSyncAll:()=>{for(let e in vs.store)vs.purgeSync(e)},truncate:(e)=>{let t=oKe.basename(e);if(t.length<=HT)return e;let n=/^(\.?)(.*?)((?:\.[^.]+)?(?:\.tmp-\d{10}[a-f0-9]{6})?)$/.exec(t);if(!n)return e;let r=t.length-HT;return`${e.slice(0,-t.length)}${n[1]}${n[2].slice(0,-r)}${n[3]}`}};nee(vs.purgeSyncAll);W0=vs});import sKe from"path";function KT(e,t,n=BZ){if(VT(n))return KT(e,t,{encoding:n});let o={timeout:n.timeout??zZ},s=null,i=null,a=null;try{let c=$r.attempt.realpathSync(e),l=!!c;e=c||e,[i,s]=W0.get(e,n.tmpCreate||W0.create,n.tmpPurge!==!1);let d=VZ&&yk(n.chown),f=yk(n.mode);if(l&&(d||f)){let p=$r.attempt.statSync(e);if(p){if(n={...n},d)n.chown={uid:p.uid,gid:p.gid};if(f)n.mode=p.mode}}if(!l){let p=sKe.dirname(e);$r.attempt.mkdirSync(p,{mode:qZ,recursive:!0})}if(a=$r.retry.openSync(o)(i,"w",n.mode||UT),n.tmpCreated)n.tmpCreated(i);if(VT(t))$r.retry.writeSync(o)(a,t,0,n.encoding||LZ);else if(!yk(t))$r.retry.writeSync(o)(a,t,0,t.length,0);if(n.fsync!==!1)if(n.fsyncWait!==!1)$r.retry.fsyncSync(o)(a);else $r.attempt.fsync(a);if($r.retry.closeSync(o)(a),a=null,n.chown&&(n.chown.uid!==UZ||n.chown.gid!==HZ))$r.attempt.chownSync(i,n.chown.uid,n.chown.gid);if(n.mode&&n.mode!==UT)$r.attempt.chmodSync(i,n.mode);try{$r.retry.renameSync(o)(i,e)}catch(p){if(!GZ(p))throw p;if(p.code!=="ENAMETOOLONG")throw p;$r.retry.renameSync(o)(i,W0.truncate(e))}s(),i=null}finally{if(a)$r.attempt.closeSync(a);if(i)W0.purge(i)}}var see=V(()=>{BT();zT();WZ();KZ();oee()});var J0=w(function(cee){Object.defineProperty(cee,"__esModule",{value:!0});cee.regexpCode=cee.getEsmExportName=cee.getProperty=cee.safeStringify=cee.stringify=cee.strConcat=cee.addCodeArg=cee.str=cee._=cee.nil=cee._Code=cee.Name=cee.IDENTIFIER=cee._CodeOrName=void 0;class wk{}cee._CodeOrName=wk;cee.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class ih extends wk{constructor(e){super();if(!cee.IDENTIFIER.test(e))throw Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}cee.Name=ih;class Ti extends wk{constructor(e){super();this._items=typeof e==="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((t,n)=>`${t}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((t,n)=>{if(n instanceof ih)t[n.str]=(t[n.str]||0)+1;return t},{})}}cee._Code=Ti;cee.nil=new Ti("");function iee(e,...t){let n=[e[0]],r=0;while(r<t.length)YT(n,t[r]),n.push(e[++r]);return new Ti(n)}cee._=iee;var JT=new Ti("+");function aee(e,...t){let n=[K0(e[0])],r=0;while(r<t.length)n.push(JT),YT(n,t[r]),n.push(JT,K0(e[++r]));return iKe(n),new Ti(n)}cee.str=aee;function YT(e,t){if(t instanceof Ti)e.push(...t._items);else if(t instanceof ih)e.push(t);else e.push(lKe(t))}cee.addCodeArg=YT;function iKe(e){let t=1;while(t<e.length-1){if(e[t]===JT){let n=aKe(e[t-1],e[t+1]);if(n!==void 0){e.splice(t-1,3,n);continue}e[t++]="+"}t++}}function aKe(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string"){if(t instanceof ih||e[e.length-1]!=='"')return;if(typeof t!="string")return`${e.slice(0,-1)}${t}"`;if(t[0]==='"')return e.slice(0,-1)+t.slice(1);return}if(typeof t=="string"&&t[0]==='"'&&!(e instanceof ih))return`"${e}${t.slice(1)}`;return}function cKe(e,t){return t.emptyStr()?e:e.emptyStr()?t:aee`${e}${t}`}cee.strConcat=cKe;function lKe(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:K0(Array.isArray(e)?e.join(","):e)}function uKe(e){return new Ti(K0(e))}cee.stringify=uKe;function K0(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}cee.safeStringify=K0;function dKe(e){return typeof e=="string"&&cee.IDENTIFIER.test(e)?new Ti(`.${e}`):iee`[${e}]`}cee.getProperty=dKe;function fKe(e){if(typeof e=="string"&&cee.IDENTIFIER.test(e))return new Ti(`${e}`);throw Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}cee.getEsmExportName=fKe;function pKe(e){return new Ti(e.toString())}cee.regexpCode=pKe});var eP=w(function(fee){Object.defineProperty(fee,"__esModule",{value:!0});fee.ValueScope=fee.ValueScopeName=fee.Scope=fee.varKinds=fee.UsedValueState=void 0;var en=J0();class uee extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`);this.value=e.value}}var xk;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(xk||(fee.UsedValueState=xk={}));fee.varKinds={const:new en.Name("const"),let:new en.Name("let"),var:new en.Name("var")};class QT{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof en.Name?e:this.name(e)}name(e){return new en.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){var t,n;if(((n=(t=this._parent)===null||t===void 0?void 0:t._prefixes)===null||n===void 0?void 0:n.has(e))||this._prefixes&&!this._prefixes.has(e))throw Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}}fee.Scope=QT;class ZT extends en.Name{constructor(e,t){super(t);this.prefix=e}setValue(e,{property:t,itemIndex:n}){this.value=e,this.scopePath=en._`.${new en.Name(t)}[${n}]`}}fee.ValueScopeName=ZT;var $Ke=en._`\n`;class dee extends QT{constructor(e){super(e);this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?$Ke:en.nil}}get(){return this._scope}name(e){return new ZT(e,this._newName(e))}value(e,t){var n;if(t.ref===void 0)throw Error("CodeGen: ref must be passed in value");let r=this.toName(e),{prefix:o}=r,s=(n=t.key)!==null&&n!==void 0?n:t.ref,i=this._values[o];if(i){let l=i.get(s);if(l)return l}else i=this._values[o]=new Map;i.set(s,r);let a=this._scope[o]||(this._scope[o]=[]),c=a.length;return a[c]=t.ref,r.setValue(t,{property:o,itemIndex:c}),r}getValue(e,t){let n=this._values[e];if(!n)return;return n.get(t)}scopeRefs(e,t=this._values){return this._reduceValues(t,(n)=>{if(n.scopePath===void 0)throw Error(`CodeGen: name "${n}" has no value`);return en._`${e}${n.scopePath}`})}scopeCode(e=this._values,t,n){return this._reduceValues(e,(r)=>{if(r.value===void 0)throw Error(`CodeGen: name "${r}" has no value`);return r.value.code},t,n)}_reduceValues(e,t,n={},r){let o=en.nil;for(let s in e){let i=e[s];if(!i)continue;let a=n[s]=n[s]||new Map;i.forEach((c)=>{if(a.has(c))return;a.set(c,xk.Started);let l=t(c);if(l){let d=this.opts.es5?fee.varKinds.var:fee.varKinds.const;o=en._`${o}${d} ${c} = ${l};${this.opts._n}`}else if(l=r===null||r===void 0?void 0:r(c))o=en._`${o}${l}${this.opts._n}`;else throw new uee(c);a.set(c,xk.Completed)})}return o}}fee.ValueScope=dee});var ct=w(function(Zo){Object.defineProperty(Zo,"__esModule",{value:!0});Zo.or=Zo.and=Zo.not=Zo.CodeGen=Zo.operators=Zo.varKinds=Zo.ValueScopeName=Zo.ValueScope=Zo.Scope=Zo.Name=Zo.regexpCode=Zo.stringify=Zo.getProperty=Zo.nil=Zo.strConcat=Zo.str=Zo._=void 0;var pe=J0(),Fn=eP(),Eu=J0();Object.defineProperty(Zo,"_",{enumerable:!0,get:function(){return Eu._}});Object.defineProperty(Zo,"str",{enumerable:!0,get:function(){return Eu.str}});Object.defineProperty(Zo,"strConcat",{enumerable:!0,get:function(){return Eu.strConcat}});Object.defineProperty(Zo,"nil",{enumerable:!0,get:function(){return Eu.nil}});Object.defineProperty(Zo,"getProperty",{enumerable:!0,get:function(){return Eu.getProperty}});Object.defineProperty(Zo,"stringify",{enumerable:!0,get:function(){return Eu.stringify}});Object.defineProperty(Zo,"regexpCode",{enumerable:!0,get:function(){return Eu.regexpCode}});Object.defineProperty(Zo,"Name",{enumerable:!0,get:function(){return Eu.Name}});var Dk=eP();Object.defineProperty(Zo,"Scope",{enumerable:!0,get:function(){return Dk.Scope}});Object.defineProperty(Zo,"ValueScope",{enumerable:!0,get:function(){return Dk.ValueScope}});Object.defineProperty(Zo,"ValueScopeName",{enumerable:!0,get:function(){return Dk.ValueScopeName}});Object.defineProperty(Zo,"varKinds",{enumerable:!0,get:function(){return Dk.varKinds}});Zo.operators={GT:new pe._Code(">"),GTE:new pe._Code(">="),LT:new pe._Code("<"),LTE:new pe._Code("<="),EQ:new pe._Code("==="),NEQ:new pe._Code("!=="),NOT:new pe._Code("!"),OR:new pe._Code("||"),AND:new pe._Code("&&"),ADD:new pe._Code("+")};class Su{optimizeNodes(){return this}optimizeNames(e,t){return this}}class mee extends Su{constructor(e,t,n){super();this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let n=e?Fn.varKinds.var:this.varKind,r=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${r};`+t}optimizeNames(e,t){if(!e[this.name.str])return;if(this.rhs)this.rhs=ch(this.rhs,e,t);return this}get names(){return this.rhs instanceof pe._CodeOrName?this.rhs.names:{}}}class rP extends Su{constructor(e,t,n){super();this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,t){if(this.lhs instanceof pe.Name&&!e[this.lhs.str]&&!this.sideEffects)return;return this.rhs=ch(this.rhs,e,t),this}get names(){let e=this.lhs instanceof pe.Name?{}:{...this.lhs.names};return $k(e,this.rhs)}}class hee extends rP{constructor(e,t,n,r){super(e,n,r);this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}}class gee extends Su{constructor(e){super();this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}}class yee extends Su{constructor(e){super();this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}}class bee extends Su{constructor(e){super();this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}}class wee extends Su{constructor(e){super();this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=ch(this.code,e,t),this}get names(){return this.code instanceof pe._CodeOrName?this.code.names:{}}}class Rk extends Su{constructor(e=[]){super();this.nodes=e}render(e){return this.nodes.reduce((t,n)=>t+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,t=e.length;while(t--){let n=e[t].optimizeNodes();if(Array.isArray(n))e.splice(t,1,...n);else if(n)e[t]=n;else e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:n}=this,r=n.length;while(r--){let o=n[r];if(o.optimizeNames(e,t))continue;AKe(e,o.names),n.splice(r,1)}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>xf(e,t.names),{})}}class $u extends Rk{render(e){return"{"+e._n+super.render(e)+"}"+e._n}}class _ee extends Rk{}class Y0 extends $u{}Y0.kind="else";class Zc extends $u{constructor(e,t){super(t);this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);if(this.else)t+="else "+this.else.render(e);return t}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let t=this.else;if(t){let n=t.optimizeNodes();t=this.else=Array.isArray(n)?new Y0(n):n}if(t){if(e===!1)return t instanceof Zc?t:t.nodes;if(this.nodes.length)return this;return new Zc(See(e),t instanceof Zc?[t]:t.nodes)}if(e===!1||!this.nodes.length)return;return this}optimizeNames(e,t){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,t),!(super.optimizeNames(e,t)||this.else))return;return this.condition=ch(this.condition,e,t),this}get names(){let e=super.names;if($k(e,this.condition),this.else)xf(e,this.else.names);return e}}Zc.kind="if";class ah extends $u{}ah.kind="for";class xee extends ah{constructor(e){super();this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(!super.optimizeNames(e,t))return;return this.iteration=ch(this.iteration,e,t),this}get names(){return xf(super.names,this.iteration.names)}}class vee extends ah{constructor(e,t,n,r){super();this.varKind=e,this.name=t,this.from=n,this.to=r}render(e){let t=e.es5?Fn.varKinds.var:this.varKind,{name:n,from:r,to:o}=this;return`for(${t} ${n}=${r}; ${n}<${o}; ${n}++)`+super.render(e)}get names(){let e=$k(super.names,this.from);return $k(e,this.to)}}class tP extends ah{constructor(e,t,n,r){super();this.loop=e,this.varKind=t,this.name=n,this.iterable=r}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(!super.optimizeNames(e,t))return;return this.iterable=ch(this.iterable,e,t),this}get names(){return xf(super.names,this.iterable.names)}}class vk extends $u{constructor(e,t,n){super();this.name=e,this.args=t,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}}vk.kind="func";class kk extends Rk{render(e){return"return "+super.render(e)}}kk.kind="return";class kee extends $u{render(e){let t="try"+super.render(e);if(this.catch)t+=this.catch.render(e);if(this.finally)t+=this.finally.render(e);return t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(t=this.finally)===null||t===void 0||t.optimizeNodes(),this}optimizeNames(e,t){var n,r;return super.optimizeNames(e,t),(n=this.catch)===null||n===void 0||n.optimizeNames(e,t),(r=this.finally)===null||r===void 0||r.optimizeNames(e,t),this}get names(){let e=super.names;if(this.catch)xf(e,this.catch.names);if(this.finally)xf(e,this.finally.names);return e}}class Ek extends $u{constructor(e){super();this.error=e}render(e){return`catch(${this.error})`+super.render(e)}}Ek.kind="catch";class Sk extends $u{render(e){return"finally"+super.render(e)}}Sk.kind="finally";class Eee{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
|
|
84
|
+
`;return this.stop(),this.#s.write(l),this}}function D(e){return new uQ(e)}var S0,WVe;var ro=V(()=>{He();JX();XX();KO();sQ();aQ();lQ();S0=et(Ox(),1),WVe=et(Ox(),1)});var kt,pQ,fe,Vc=(e)=>{switch(typeof e){case"undefined":return fe.undefined;case"string":return fe.string;case"number":return Number.isNaN(e)?fe.nan:fe.number;case"boolean":return fe.boolean;case"function":return fe.function;case"bigint":return fe.bigint;case"symbol":return fe.symbol;case"object":if(Array.isArray(e))return fe.array;if(e===null)return fe.null;if(e.then&&typeof e.then==="function"&&e.catch&&typeof e.catch==="function")return fe.promise;if(typeof Map<"u"&&e instanceof Map)return fe.map;if(typeof Set<"u"&&e instanceof Set)return fe.set;if(typeof Date<"u"&&e instanceof Date)return fe.date;return fe.object;default:return fe.unknown}};var $0=V(()=>{(function(e){e.assertEqual=(o)=>{};function t(o){}e.assertIs=t;function n(o){throw Error()}e.assertNever=n,e.arrayToEnum=(o)=>{let s={};for(let i of o)s[i]=i;return s},e.getValidEnumValues=(o)=>{let s=e.objectKeys(o).filter((a)=>typeof o[o[a]]!=="number"),i={};for(let a of s)i[a]=o[a];return e.objectValues(i)},e.objectValues=(o)=>e.objectKeys(o).map(function(s){return o[s]}),e.objectKeys=typeof Object.keys==="function"?(o)=>Object.keys(o):(o)=>{let s=[];for(let i in o)if(Object.prototype.hasOwnProperty.call(o,i))s.push(i);return s},e.find=(o,s)=>{for(let i of o)if(s(i))return i;return},e.isInteger=typeof Number.isInteger==="function"?(o)=>Number.isInteger(o):(o)=>typeof o==="number"&&Number.isFinite(o)&&Math.floor(o)===o;function r(o,s=" | "){return o.map((i)=>typeof i==="string"?`'${i}'`:i).join(s)}e.joinValues=r,e.jsonStringifyReplacer=(o,s)=>{if(typeof s==="bigint")return s.toString();return s}})(kt||(kt={}));(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(pQ||(pQ={}));fe=kt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"])});var Z,xs;var Mv=V(()=>{$0();Z=kt.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);xs=class xs extends Error{get errors(){return this.issues}constructor(e){super();this.issues=[],this.addIssue=(n)=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let t=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,t);else this.__proto__=t;this.name="ZodError",this.issues=e}format(e){let t=e||function(o){return o.message},n={_errors:[]},r=(o)=>{for(let s of o.issues)if(s.code==="invalid_union")s.unionErrors.map(r);else if(s.code==="invalid_return_type")r(s.returnTypeError);else if(s.code==="invalid_arguments")r(s.argumentsError);else if(s.path.length===0)n._errors.push(t(s));else{let i=n,a=0;while(a<s.path.length){let c=s.path[a];if(a!==s.path.length-1)i[c]=i[c]||{_errors:[]};else i[c]=i[c]||{_errors:[]},i[c]._errors.push(t(s));i=i[c],a++}}};return r(this),n}static assert(e){if(!(e instanceof xs))throw Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,kt.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=(t)=>t.message){let t={},n=[];for(let r of this.issues)if(r.path.length>0){let o=r.path[0];t[o]=t[o]||[],t[o].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};xs.create=(e)=>new xs(e)});var KVe=(e,t)=>{let n;switch(e.code){case Z.invalid_type:if(e.received===fe.undefined)n="Required";else n=`Expected ${e.expected}, received ${e.received}`;break;case Z.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,kt.jsonStringifyReplacer)}`;break;case Z.unrecognized_keys:n=`Unrecognized key(s) in object: ${kt.joinValues(e.keys,", ")}`;break;case Z.invalid_union:n="Invalid input";break;case Z.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${kt.joinValues(e.options)}`;break;case Z.invalid_enum_value:n=`Invalid enum value. Expected ${kt.joinValues(e.options)}, received '${e.received}'`;break;case Z.invalid_arguments:n="Invalid function arguments";break;case Z.invalid_return_type:n="Invalid function return type";break;case Z.invalid_date:n="Invalid date";break;case Z.invalid_string:if(typeof e.validation==="object")if("includes"in e.validation){if(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==="number")n=`${n} at one or more positions greater than or equal to ${e.validation.position}`}else if("startsWith"in e.validation)n=`Invalid input: must start with "${e.validation.startsWith}"`;else if("endsWith"in e.validation)n=`Invalid input: must end with "${e.validation.endsWith}"`;else kt.assertNever(e.validation);else if(e.validation!=="regex")n=`Invalid ${e.validation}`;else n="Invalid";break;case Z.too_small:if(e.type==="array")n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`;else if(e.type==="string")n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`;else if(e.type==="number")n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`;else if(e.type==="bigint")n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`;else if(e.type==="date")n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`;else n="Invalid input";break;case Z.too_big:if(e.type==="array")n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`;else if(e.type==="string")n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`;else if(e.type==="number")n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`;else if(e.type==="bigint")n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`;else if(e.type==="date")n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`;else n="Invalid input";break;case Z.custom:n="Invalid input";break;case Z.invalid_intersection_types:n="Intersection results could not be merged";break;case Z.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case Z.not_finite:n="Number must be finite";break;default:n=t.defaultError,kt.assertNever(e)}return{message:n}},bu;var ZO=V(()=>{Mv();$0();bu=KVe});function D0(){return JVe}var JVe;var jv=V(()=>{ZO();JVe=bu});function ae(e,t){let n=D0(),r=Lv({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===bu?void 0:bu].filter((o)=>!!o)});e.common.issues.push(r)}class oo{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(e,t){let n=[];for(let r of t){if(r.status==="aborted")return Le;if(r.status==="dirty")e.dirty();n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){let n=[];for(let r of t){let o=await r.key,s=await r.value;n.push({key:o,value:s})}return oo.mergeObjectSync(e,n)}static mergeObjectSync(e,t){let n={};for(let r of t){let{key:o,value:s}=r;if(o.status==="aborted")return Le;if(s.status==="aborted")return Le;if(o.status==="dirty")e.dirty();if(s.status==="dirty")e.dirty();if(o.value!=="__proto__"&&(typeof s.value<"u"||r.alwaysSet))n[o.value]=s.value}return{status:e.value,value:n}}}var Lv=(e)=>{let{data:t,path:n,errorMaps:r,issueData:o}=e,s=[...n,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",c=r.filter((l)=>!!l).slice().reverse();for(let l of c)a=l(i,{data:t,defaultError:a}).message;return{...o,path:s,message:a}},Le,Hm=(e)=>({status:"dirty",value:e}),Eo=(e)=>({status:"valid",value:e}),eT=(e)=>e.status==="aborted",tT=(e)=>e.status==="dirty",hf=(e)=>e.status==="valid",R0=(e)=>typeof Promise<"u"&&e instanceof Promise;var nT=V(()=>{jv();ZO();Le=Object.freeze({status:"aborted"})});var mQ=()=>{};var $e;var hQ=V(()=>{(function(e){e.errToObj=(t)=>typeof t==="string"?{message:t}:t||{},e.toString=(t)=>typeof t==="string"?t:t?.message})($e||($e={}))});class Ai{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}function at(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:o}=e;if(t&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(t)return{errorMap:t,description:o};return{errorMap:(i,a)=>{let{message:c}=e;if(i.code==="invalid_enum_value")return{message:c??a.defaultError};if(typeof a.data>"u")return{message:c??r??a.defaultError};if(i.code!=="invalid_type")return{message:a.defaultError};return{message:c??n??a.defaultError}},description:o}}class wt{get description(){return this._def.description}_getType(e){return Vc(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Vc(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new oo,ctx:{common:e.parent.common,data:e.data,parsedType:Vc(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(R0(t))throw Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Vc(e)},r=this._parseSync({data:e,path:n.path,parent:n});return gQ(n,r)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Vc(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return hf(n)?{value:n.value}:{issues:t.common.issues}}catch(n){if(n?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then((n)=>hf(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Vc(e)},r=this._parse({data:e,path:n.path,parent:n}),o=await(R0(r)?r:Promise.resolve(r));return gQ(n,o)}refine(e,t){let n=(r)=>{if(typeof t==="string"||typeof t>"u")return{message:t};else if(typeof t==="function")return t(r);else return t};return this._refinement((r,o)=>{let s=e(r),i=()=>o.addIssue({code:Z.custom,...n(r)});if(typeof Promise<"u"&&s instanceof Promise)return s.then((a)=>{if(!a)return i(),!1;else return!0});if(!s)return i(),!1;else return!0})}refinement(e,t){return this._refinement((n,r)=>{if(!e(n))return r.addIssue(typeof t==="function"?t(n,r):t),!1;else return!0})}_refinement(e){return new wa({schema:this,typeName:qe.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(t)=>this["~validate"](t)}}optional(){return ba.create(this,this._def)}nullable(){return wu.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ya.create(this)}promise(){return Km.create(this,this._def)}or(e){return P0.create([this,e],this._def)}and(e){return I0.create(this,e,this._def)}transform(e){return new wa({...at(this._def),schema:this,typeName:qe.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e==="function"?e:()=>e;return new j0({...at(this._def),innerType:this,defaultValue:t,typeName:qe.ZodDefault})}brand(){return new iT({typeName:qe.ZodBranded,type:this,...at(this._def)})}catch(e){let t=typeof e==="function"?e:()=>e;return new L0({...at(this._def),innerType:this,catchValue:t,typeName:qe.ZodCatch})}describe(e){return new this.constructor({...this._def,description:e})}pipe(e){return Wv.create(this,e)}readonly(){return q0.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}function bQ(e){let t="[0-5]\\d";if(e.precision)t=`${t}\\.\\d{${e.precision}}`;else if(e.precision==null)t=`${t}(\\.\\d+)?`;let n=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function fGe(e){return new RegExp(`^${bQ(e)}$`)}function pGe(e){let t=`${yQ}T${bQ(e)}`,n=[];if(n.push(e.local?"Z?":"Z"),e.offset)n.push("([+-]\\d{2}:?\\d{2})");return t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function mGe(e,t){if((t==="v4"||!t)&&sGe.test(e))return!0;if((t==="v6"||!t)&&aGe.test(e))return!0;return!1}function hGe(e,t){if(!tGe.test(e))return!1;try{let[n]=e.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),o=JSON.parse(atob(r));if(typeof o!=="object"||o===null)return!1;if("typ"in o&&o?.typ!=="JWT")return!1;if(!o.alg)return!1;if(t&&o.alg!==t)return!1;return!0}catch{return!1}}function gGe(e,t){if((t==="v4"||!t)&&iGe.test(e))return!0;if((t==="v6"||!t)&&cGe.test(e))return!0;return!1}function yGe(e,t){let n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,s=Number.parseInt(e.toFixed(o).replace(".","")),i=Number.parseInt(t.toFixed(o).replace(".",""));return s%i/10**o}function zm(e){if(e instanceof In){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=ba.create(zm(r))}return new In({...e._def,shape:()=>t})}else if(e instanceof ya)return new ya({...e._def,type:zm(e.element)});else if(e instanceof ba)return ba.create(zm(e.unwrap()));else if(e instanceof wu)return wu.create(zm(e.unwrap()));else if(e instanceof Jc)return Jc.create(e.items.map((t)=>zm(t)));else return e}function oT(e,t){let n=Vc(e),r=Vc(t);if(e===t)return{valid:!0,data:e};else if(n===fe.object&&r===fe.object){let o=kt.objectKeys(t),s=kt.objectKeys(e).filter((a)=>o.indexOf(a)!==-1),i={...e,...t};for(let a of s){let c=oT(e[a],t[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(n===fe.array&&r===fe.array){if(e.length!==t.length)return{valid:!1};let o=[];for(let s=0;s<e.length;s++){let i=e[s],a=t[s],c=oT(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else if(n===fe.date&&r===fe.date&&+e===+t)return{valid:!0,data:e};else return{valid:!1}}function wQ(e,t){return new yf({values:e,typeName:qe.ZodEnum,...at(t)})}var gQ=(e,t)=>{if(hf(t))return{success:!0,data:t.value};else{if(!e.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new xs(e.common.issues);return this._error=n,this._error}}}},YVe,XVe,QVe,ZVe,eGe,tGe,nGe,rGe,oGe="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",rT,sGe,iGe,aGe,cGe,lGe,uGe,yQ="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",dGe,Wc,Vm,Gm,qv,A0,Bv,O0,T0,Uv,gf,Kc,Hv,ya,In,P0,Gc=(e)=>{if(e instanceof N0)return Gc(e.schema);else if(e instanceof wa)return Gc(e.innerType());else if(e instanceof F0)return[e.value];else if(e instanceof yf)return e.options;else if(e instanceof M0)return kt.objectValues(e.enum);else if(e instanceof j0)return Gc(e._def.innerType);else if(e instanceof O0)return[void 0];else if(e instanceof T0)return[null];else if(e instanceof ba)return[void 0,...Gc(e.unwrap())];else if(e instanceof wu)return[null,...Gc(e.unwrap())];else if(e instanceof iT)return Gc(e.unwrap());else if(e instanceof q0)return Gc(e.unwrap());else if(e instanceof L0)return Gc(e._def.innerType);else return[]},sT,I0,Jc,zv,Vv,Wm,C0,N0,F0,yf,M0,Km,wa,ba,wu,j0,L0,Gv,a8t,iT,Wv,q0,c8t,qe,S,j,l8t,u8t,Ke,d8t,f8t,p8t,m8t,h8t,_u,g8t,y8t,he,ee,b8t,Jm,aT,w8t,_8t,Ks,x8t,v8t,k8t,E8t,$t,Ft,S8t,$8t,D8t,R8t,C8t,A8t,O8t;var _Q=V(()=>{Mv();jv();hQ();nT();$0();YVe=/^c[^\s-]{8,}$/i,XVe=/^[0-9a-z]+$/,QVe=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ZVe=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,eGe=/^[a-z0-9_-]{21}$/i,tGe=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,nGe=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,rGe=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,sGe=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,iGe=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,aGe=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,cGe=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,lGe=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,uGe=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,dGe=new RegExp(`^${yQ}$`);Wc=class Wc extends wt{_parse(e){if(this._def.coerce)e.data=String(e.data);if(this._getType(e)!==fe.string){let o=this._getOrReturnCtx(e);return ae(o,{code:Z.invalid_type,expected:fe.string,received:o.parsedType}),Le}let n=new oo,r=void 0;for(let o of this._def.checks)if(o.kind==="min"){if(e.data.length<o.value)r=this._getOrReturnCtx(e,r),ae(r,{code:Z.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty()}else if(o.kind==="max"){if(e.data.length>o.value)r=this._getOrReturnCtx(e,r),ae(r,{code:Z.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty()}else if(o.kind==="length"){let s=e.data.length>o.value,i=e.data.length<o.value;if(s||i){if(r=this._getOrReturnCtx(e,r),s)ae(r,{code:Z.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message});else if(i)ae(r,{code:Z.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message});n.dirty()}}else if(o.kind==="email"){if(!rGe.test(e.data))r=this._getOrReturnCtx(e,r),ae(r,{validation:"email",code:Z.invalid_string,message:o.message}),n.dirty()}else if(o.kind==="emoji"){if(!rT)rT=new RegExp(oGe,"u");if(!rT.test(e.data))r=this._getOrReturnCtx(e,r),ae(r,{validation:"emoji",code:Z.invalid_string,message:o.message}),n.dirty()}else if(o.kind==="uuid"){if(!ZVe.test(e.data))r=this._getOrReturnCtx(e,r),ae(r,{validation:"uuid",code:Z.invalid_string,message:o.message}),n.dirty()}else if(o.kind==="nanoid"){if(!eGe.test(e.data))r=this._getOrReturnCtx(e,r),ae(r,{validation:"nanoid",code:Z.invalid_string,message:o.message}),n.dirty()}else if(o.kind==="cuid"){if(!YVe.test(e.data))r=this._getOrReturnCtx(e,r),ae(r,{validation:"cuid",code:Z.invalid_string,message:o.message}),n.dirty()}else if(o.kind==="cuid2"){if(!XVe.test(e.data))r=this._getOrReturnCtx(e,r),ae(r,{validation:"cuid2",code:Z.invalid_string,message:o.message}),n.dirty()}else if(o.kind==="ulid"){if(!QVe.test(e.data))r=this._getOrReturnCtx(e,r),ae(r,{validation:"ulid",code:Z.invalid_string,message:o.message}),n.dirty()}else if(o.kind==="url")try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),ae(r,{validation:"url",code:Z.invalid_string,message:o.message}),n.dirty()}else if(o.kind==="regex"){if(o.regex.lastIndex=0,!o.regex.test(e.data))r=this._getOrReturnCtx(e,r),ae(r,{validation:"regex",code:Z.invalid_string,message:o.message}),n.dirty()}else if(o.kind==="trim")e.data=e.data.trim();else if(o.kind==="includes"){if(!e.data.includes(o.value,o.position))r=this._getOrReturnCtx(e,r),ae(r,{code:Z.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.dirty()}else if(o.kind==="toLowerCase")e.data=e.data.toLowerCase();else if(o.kind==="toUpperCase")e.data=e.data.toUpperCase();else if(o.kind==="startsWith"){if(!e.data.startsWith(o.value))r=this._getOrReturnCtx(e,r),ae(r,{code:Z.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()}else if(o.kind==="endsWith"){if(!e.data.endsWith(o.value))r=this._getOrReturnCtx(e,r),ae(r,{code:Z.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()}else if(o.kind==="datetime"){if(!pGe(o).test(e.data))r=this._getOrReturnCtx(e,r),ae(r,{code:Z.invalid_string,validation:"datetime",message:o.message}),n.dirty()}else if(o.kind==="date"){if(!dGe.test(e.data))r=this._getOrReturnCtx(e,r),ae(r,{code:Z.invalid_string,validation:"date",message:o.message}),n.dirty()}else if(o.kind==="time"){if(!fGe(o).test(e.data))r=this._getOrReturnCtx(e,r),ae(r,{code:Z.invalid_string,validation:"time",message:o.message}),n.dirty()}else if(o.kind==="duration"){if(!nGe.test(e.data))r=this._getOrReturnCtx(e,r),ae(r,{validation:"duration",code:Z.invalid_string,message:o.message}),n.dirty()}else if(o.kind==="ip"){if(!mGe(e.data,o.version))r=this._getOrReturnCtx(e,r),ae(r,{validation:"ip",code:Z.invalid_string,message:o.message}),n.dirty()}else if(o.kind==="jwt"){if(!hGe(e.data,o.alg))r=this._getOrReturnCtx(e,r),ae(r,{validation:"jwt",code:Z.invalid_string,message:o.message}),n.dirty()}else if(o.kind==="cidr"){if(!gGe(e.data,o.version))r=this._getOrReturnCtx(e,r),ae(r,{validation:"cidr",code:Z.invalid_string,message:o.message}),n.dirty()}else if(o.kind==="base64"){if(!lGe.test(e.data))r=this._getOrReturnCtx(e,r),ae(r,{validation:"base64",code:Z.invalid_string,message:o.message}),n.dirty()}else if(o.kind==="base64url"){if(!uGe.test(e.data))r=this._getOrReturnCtx(e,r),ae(r,{validation:"base64url",code:Z.invalid_string,message:o.message}),n.dirty()}else kt.assertNever(o);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement((r)=>e.test(r),{validation:t,code:Z.invalid_string,...$e.errToObj(n)})}_addCheck(e){return new Wc({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...$e.errToObj(e)})}url(e){return this._addCheck({kind:"url",...$e.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...$e.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...$e.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...$e.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...$e.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...$e.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...$e.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...$e.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...$e.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...$e.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...$e.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...$e.errToObj(e)})}datetime(e){if(typeof e==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e});return this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...$e.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){if(typeof e==="string")return this._addCheck({kind:"time",precision:null,message:e});return this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...$e.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...$e.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...$e.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...$e.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...$e.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...$e.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...$e.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...$e.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...$e.errToObj(t)})}nonempty(e){return this.min(1,$e.errToObj(e))}trim(){return new Wc({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new Wc({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new Wc({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((e)=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find((e)=>e.kind==="date")}get isTime(){return!!this._def.checks.find((e)=>e.kind==="time")}get isDuration(){return!!this._def.checks.find((e)=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find((e)=>e.kind==="email")}get isURL(){return!!this._def.checks.find((e)=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find((e)=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find((e)=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((e)=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((e)=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((e)=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find((e)=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find((e)=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find((e)=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find((e)=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find((e)=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxLength(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}};Wc.create=(e)=>new Wc({checks:[],typeName:qe.ZodString,coerce:e?.coerce??!1,...at(e)});Vm=class Vm extends wt{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce)e.data=Number(e.data);if(this._getType(e)!==fe.number){let o=this._getOrReturnCtx(e);return ae(o,{code:Z.invalid_type,expected:fe.number,received:o.parsedType}),Le}let n=void 0,r=new oo;for(let o of this._def.checks)if(o.kind==="int"){if(!kt.isInteger(e.data))n=this._getOrReturnCtx(e,n),ae(n,{code:Z.invalid_type,expected:"integer",received:"float",message:o.message}),r.dirty()}else if(o.kind==="min"){if(o.inclusive?e.data<o.value:e.data<=o.value)n=this._getOrReturnCtx(e,n),ae(n,{code:Z.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),r.dirty()}else if(o.kind==="max"){if(o.inclusive?e.data>o.value:e.data>=o.value)n=this._getOrReturnCtx(e,n),ae(n,{code:Z.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),r.dirty()}else if(o.kind==="multipleOf"){if(yGe(e.data,o.value)!==0)n=this._getOrReturnCtx(e,n),ae(n,{code:Z.not_multiple_of,multipleOf:o.value,message:o.message}),r.dirty()}else if(o.kind==="finite"){if(!Number.isFinite(e.data))n=this._getOrReturnCtx(e,n),ae(n,{code:Z.not_finite,message:o.message}),r.dirty()}else kt.assertNever(o);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,$e.toString(t))}gt(e,t){return this.setLimit("min",e,!1,$e.toString(t))}lte(e,t){return this.setLimit("max",e,!0,$e.toString(t))}lt(e,t){return this.setLimit("max",e,!1,$e.toString(t))}setLimit(e,t,n,r){return new Vm({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:$e.toString(r)}]})}_addCheck(e){return new Vm({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:$e.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:$e.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:$e.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:$e.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:$e.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:$e.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:$e.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:$e.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:$e.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxValue(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}get isInt(){return!!this._def.checks.find((e)=>e.kind==="int"||e.kind==="multipleOf"&&kt.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;else if(n.kind==="min"){if(t===null||n.value>t)t=n.value}else if(n.kind==="max"){if(e===null||n.value<e)e=n.value}return Number.isFinite(t)&&Number.isFinite(e)}};Vm.create=(e)=>new Vm({checks:[],typeName:qe.ZodNumber,coerce:e?.coerce||!1,...at(e)});Gm=class Gm extends wt{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==fe.bigint)return this._getInvalidInput(e);let n=void 0,r=new oo;for(let o of this._def.checks)if(o.kind==="min"){if(o.inclusive?e.data<o.value:e.data<=o.value)n=this._getOrReturnCtx(e,n),ae(n,{code:Z.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),r.dirty()}else if(o.kind==="max"){if(o.inclusive?e.data>o.value:e.data>=o.value)n=this._getOrReturnCtx(e,n),ae(n,{code:Z.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),r.dirty()}else if(o.kind==="multipleOf"){if(e.data%o.value!==BigInt(0))n=this._getOrReturnCtx(e,n),ae(n,{code:Z.not_multiple_of,multipleOf:o.value,message:o.message}),r.dirty()}else kt.assertNever(o);return{status:r.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return ae(t,{code:Z.invalid_type,expected:fe.bigint,received:t.parsedType}),Le}gte(e,t){return this.setLimit("min",e,!0,$e.toString(t))}gt(e,t){return this.setLimit("min",e,!1,$e.toString(t))}lte(e,t){return this.setLimit("max",e,!0,$e.toString(t))}lt(e,t){return this.setLimit("max",e,!1,$e.toString(t))}setLimit(e,t,n,r){return new Gm({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:$e.toString(r)}]})}_addCheck(e){return new Gm({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:$e.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:$e.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:$e.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:$e.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:$e.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e}get maxValue(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e}};Gm.create=(e)=>new Gm({checks:[],typeName:qe.ZodBigInt,coerce:e?.coerce??!1,...at(e)});qv=class qv extends wt{_parse(e){if(this._def.coerce)e.data=Boolean(e.data);if(this._getType(e)!==fe.boolean){let n=this._getOrReturnCtx(e);return ae(n,{code:Z.invalid_type,expected:fe.boolean,received:n.parsedType}),Le}return Eo(e.data)}};qv.create=(e)=>new qv({typeName:qe.ZodBoolean,coerce:e?.coerce||!1,...at(e)});A0=class A0 extends wt{_parse(e){if(this._def.coerce)e.data=new Date(e.data);if(this._getType(e)!==fe.date){let o=this._getOrReturnCtx(e);return ae(o,{code:Z.invalid_type,expected:fe.date,received:o.parsedType}),Le}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return ae(o,{code:Z.invalid_date}),Le}let n=new oo,r=void 0;for(let o of this._def.checks)if(o.kind==="min"){if(e.data.getTime()<o.value)r=this._getOrReturnCtx(e,r),ae(r,{code:Z.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()}else if(o.kind==="max"){if(e.data.getTime()>o.value)r=this._getOrReturnCtx(e,r),ae(r,{code:Z.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()}else kt.assertNever(o);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new A0({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:$e.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:$e.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)if(t.kind==="min"){if(e===null||t.value>e)e=t.value}return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)if(t.kind==="max"){if(e===null||t.value<e)e=t.value}return e!=null?new Date(e):null}};A0.create=(e)=>new A0({checks:[],coerce:e?.coerce||!1,typeName:qe.ZodDate,...at(e)});Bv=class Bv extends wt{_parse(e){if(this._getType(e)!==fe.symbol){let n=this._getOrReturnCtx(e);return ae(n,{code:Z.invalid_type,expected:fe.symbol,received:n.parsedType}),Le}return Eo(e.data)}};Bv.create=(e)=>new Bv({typeName:qe.ZodSymbol,...at(e)});O0=class O0 extends wt{_parse(e){if(this._getType(e)!==fe.undefined){let n=this._getOrReturnCtx(e);return ae(n,{code:Z.invalid_type,expected:fe.undefined,received:n.parsedType}),Le}return Eo(e.data)}};O0.create=(e)=>new O0({typeName:qe.ZodUndefined,...at(e)});T0=class T0 extends wt{_parse(e){if(this._getType(e)!==fe.null){let n=this._getOrReturnCtx(e);return ae(n,{code:Z.invalid_type,expected:fe.null,received:n.parsedType}),Le}return Eo(e.data)}};T0.create=(e)=>new T0({typeName:qe.ZodNull,...at(e)});Uv=class Uv extends wt{constructor(){super(...arguments);this._any=!0}_parse(e){return Eo(e.data)}};Uv.create=(e)=>new Uv({typeName:qe.ZodAny,...at(e)});gf=class gf extends wt{constructor(){super(...arguments);this._unknown=!0}_parse(e){return Eo(e.data)}};gf.create=(e)=>new gf({typeName:qe.ZodUnknown,...at(e)});Kc=class Kc extends wt{_parse(e){let t=this._getOrReturnCtx(e);return ae(t,{code:Z.invalid_type,expected:fe.never,received:t.parsedType}),Le}};Kc.create=(e)=>new Kc({typeName:qe.ZodNever,...at(e)});Hv=class Hv extends wt{_parse(e){if(this._getType(e)!==fe.undefined){let n=this._getOrReturnCtx(e);return ae(n,{code:Z.invalid_type,expected:fe.void,received:n.parsedType}),Le}return Eo(e.data)}};Hv.create=(e)=>new Hv({typeName:qe.ZodVoid,...at(e)});ya=class ya extends wt{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==fe.array)return ae(t,{code:Z.invalid_type,expected:fe.array,received:t.parsedType}),Le;if(r.exactLength!==null){let s=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;if(s||i)ae(t,{code:s?Z.too_big:Z.too_small,minimum:i?r.exactLength.value:void 0,maximum:s?r.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty()}if(r.minLength!==null){if(t.data.length<r.minLength.value)ae(t,{code:Z.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()}if(r.maxLength!==null){if(t.data.length>r.maxLength.value)ae(t,{code:Z.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()}if(t.common.async)return Promise.all([...t.data].map((s,i)=>r.type._parseAsync(new Ai(t,s,t.path,i)))).then((s)=>oo.mergeArray(n,s));let o=[...t.data].map((s,i)=>r.type._parseSync(new Ai(t,s,t.path,i)));return oo.mergeArray(n,o)}get element(){return this._def.type}min(e,t){return new ya({...this._def,minLength:{value:e,message:$e.toString(t)}})}max(e,t){return new ya({...this._def,maxLength:{value:e,message:$e.toString(t)}})}length(e,t){return new ya({...this._def,exactLength:{value:e,message:$e.toString(t)}})}nonempty(e){return this.min(1,e)}};ya.create=(e,t)=>new ya({type:e,minLength:null,maxLength:null,exactLength:null,typeName:qe.ZodArray,...at(t)});In=class In extends wt{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=kt.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==fe.object){let c=this._getOrReturnCtx(e);return ae(c,{code:Z.invalid_type,expected:fe.object,received:c.parsedType}),Le}let{status:n,ctx:r}=this._processInputParams(e),{shape:o,keys:s}=this._getCached(),i=[];if(!(this._def.catchall instanceof Kc&&this._def.unknownKeys==="strip")){for(let c in r.data)if(!s.includes(c))i.push(c)}let a=[];for(let c of s){let l=o[c],d=r.data[c];a.push({key:{status:"valid",value:c},value:l._parse(new Ai(r,d,r.path,c)),alwaysSet:c in r.data})}if(this._def.catchall instanceof Kc){let c=this._def.unknownKeys;if(c==="passthrough")for(let l of i)a.push({key:{status:"valid",value:l},value:{status:"valid",value:r.data[l]}});else if(c==="strict"){if(i.length>0)ae(r,{code:Z.unrecognized_keys,keys:i}),n.dirty()}else if(c==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let l of i){let d=r.data[l];a.push({key:{status:"valid",value:l},value:c._parse(new Ai(r,d,r.path,l)),alwaysSet:l in r.data})}}if(r.common.async)return Promise.resolve().then(async()=>{let c=[];for(let l of a){let d=await l.key,f=await l.value;c.push({key:d,value:f,alwaysSet:l.alwaysSet})}return c}).then((c)=>oo.mergeObjectSync(n,c));else return oo.mergeObjectSync(n,a)}get shape(){return this._def.shape()}strict(e){return $e.errToObj,new In({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{let r=this._def.errorMap?.(t,n).message??n.defaultError;if(t.code==="unrecognized_keys")return{message:$e.errToObj(e).message??r};return{message:r}}}:{}})}strip(){return new In({...this._def,unknownKeys:"strip"})}passthrough(){return new In({...this._def,unknownKeys:"passthrough"})}extend(e){return new In({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new In({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:qe.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new In({...this._def,catchall:e})}pick(e){let t={};for(let n of kt.objectKeys(e))if(e[n]&&this.shape[n])t[n]=this.shape[n];return new In({...this._def,shape:()=>t})}omit(e){let t={};for(let n of kt.objectKeys(this.shape))if(!e[n])t[n]=this.shape[n];return new In({...this._def,shape:()=>t})}deepPartial(){return zm(this)}partial(e){let t={};for(let n of kt.objectKeys(this.shape)){let r=this.shape[n];if(e&&!e[n])t[n]=r;else t[n]=r.optional()}return new In({...this._def,shape:()=>t})}required(e){let t={};for(let n of kt.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let o=this.shape[n];while(o instanceof ba)o=o._def.innerType;t[n]=o}return new In({...this._def,shape:()=>t})}keyof(){return wQ(kt.objectKeys(this.shape))}};In.create=(e,t)=>new In({shape:()=>e,unknownKeys:"strip",catchall:Kc.create(),typeName:qe.ZodObject,...at(t)});In.strictCreate=(e,t)=>new In({shape:()=>e,unknownKeys:"strict",catchall:Kc.create(),typeName:qe.ZodObject,...at(t)});In.lazycreate=(e,t)=>new In({shape:e,unknownKeys:"strip",catchall:Kc.create(),typeName:qe.ZodObject,...at(t)});P0=class P0 extends wt{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(o){for(let i of o)if(i.result.status==="valid")return i.result;for(let i of o)if(i.result.status==="dirty")return t.common.issues.push(...i.ctx.common.issues),i.result;let s=o.map((i)=>new xs(i.ctx.common.issues));return ae(t,{code:Z.invalid_union,unionErrors:s}),Le}if(t.common.async)return Promise.all(n.map(async(o)=>{let s={...t,common:{...t.common,issues:[]},parent:null};return{result:await o._parseAsync({data:t.data,path:t.path,parent:s}),ctx:s}})).then(r);else{let o=void 0,s=[];for(let a of n){let c={...t,common:{...t.common,issues:[]},parent:null},l=a._parseSync({data:t.data,path:t.path,parent:c});if(l.status==="valid")return l;else if(l.status==="dirty"&&!o)o={result:l,ctx:c};if(c.common.issues.length)s.push(c.common.issues)}if(o)return t.common.issues.push(...o.ctx.common.issues),o.result;let i=s.map((a)=>new xs(a));return ae(t,{code:Z.invalid_union,unionErrors:i}),Le}}get options(){return this._def.options}};P0.create=(e,t)=>new P0({options:e,typeName:qe.ZodUnion,...at(t)});sT=class sT extends wt{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==fe.object)return ae(t,{code:Z.invalid_type,expected:fe.object,received:t.parsedType}),Le;let n=this.discriminator,r=t.data[n],o=this.optionsMap.get(r);if(!o)return ae(t,{code:Z.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),Le;if(t.common.async)return o._parseAsync({data:t.data,path:t.path,parent:t});else return o._parseSync({data:t.data,path:t.path,parent:t})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let r=new Map;for(let o of t){let s=Gc(o.shape[e]);if(!s.length)throw Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let i of s){if(r.has(i))throw Error(`Discriminator property ${String(e)} has duplicate value ${String(i)}`);r.set(i,o)}}return new sT({typeName:qe.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:r,...at(n)})}};I0=class I0 extends wt{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(o,s)=>{if(eT(o)||eT(s))return Le;let i=oT(o.value,s.value);if(!i.valid)return ae(n,{code:Z.invalid_intersection_types}),Le;if(tT(o)||tT(s))t.dirty();return{status:t.value,value:i.data}};if(n.common.async)return Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([o,s])=>r(o,s));else return r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};I0.create=(e,t,n)=>new I0({left:e,right:t,typeName:qe.ZodIntersection,...at(n)});Jc=class Jc extends wt{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==fe.array)return ae(n,{code:Z.invalid_type,expected:fe.array,received:n.parsedType}),Le;if(n.data.length<this._def.items.length)return ae(n,{code:Z.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Le;if(!this._def.rest&&n.data.length>this._def.items.length)ae(n,{code:Z.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty();let o=[...n.data].map((s,i)=>{let a=this._def.items[i]||this._def.rest;if(!a)return null;return a._parse(new Ai(n,s,n.path,i))}).filter((s)=>!!s);if(n.common.async)return Promise.all(o).then((s)=>oo.mergeArray(t,s));else return oo.mergeArray(t,o)}get items(){return this._def.items}rest(e){return new Jc({...this._def,rest:e})}};Jc.create=(e,t)=>{if(!Array.isArray(e))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new Jc({items:e,typeName:qe.ZodTuple,rest:null,...at(t)})};zv=class zv extends wt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==fe.object)return ae(n,{code:Z.invalid_type,expected:fe.object,received:n.parsedType}),Le;let r=[],o=this._def.keyType,s=this._def.valueType;for(let i in n.data)r.push({key:o._parse(new Ai(n,i,n.path,i)),value:s._parse(new Ai(n,n.data[i],n.path,i)),alwaysSet:i in n.data});if(n.common.async)return oo.mergeObjectAsync(t,r);else return oo.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(e,t,n){if(t instanceof wt)return new zv({keyType:e,valueType:t,typeName:qe.ZodRecord,...at(n)});return new zv({keyType:Wc.create(),valueType:e,typeName:qe.ZodRecord,...at(t)})}};Vv=class Vv extends wt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==fe.map)return ae(n,{code:Z.invalid_type,expected:fe.map,received:n.parsedType}),Le;let r=this._def.keyType,o=this._def.valueType,s=[...n.data.entries()].map(([i,a],c)=>({key:r._parse(new Ai(n,i,n.path,[c,"key"])),value:o._parse(new Ai(n,a,n.path,[c,"value"]))}));if(n.common.async){let i=new Map;return Promise.resolve().then(async()=>{for(let a of s){let c=await a.key,l=await a.value;if(c.status==="aborted"||l.status==="aborted")return Le;if(c.status==="dirty"||l.status==="dirty")t.dirty();i.set(c.value,l.value)}return{status:t.value,value:i}})}else{let i=new Map;for(let a of s){let{key:c,value:l}=a;if(c.status==="aborted"||l.status==="aborted")return Le;if(c.status==="dirty"||l.status==="dirty")t.dirty();i.set(c.value,l.value)}return{status:t.value,value:i}}}};Vv.create=(e,t,n)=>new Vv({valueType:t,keyType:e,typeName:qe.ZodMap,...at(n)});Wm=class Wm extends wt{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==fe.set)return ae(n,{code:Z.invalid_type,expected:fe.set,received:n.parsedType}),Le;let r=this._def;if(r.minSize!==null){if(n.data.size<r.minSize.value)ae(n,{code:Z.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()}if(r.maxSize!==null){if(n.data.size>r.maxSize.value)ae(n,{code:Z.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty()}let o=this._def.valueType;function s(a){let c=new Set;for(let l of a){if(l.status==="aborted")return Le;if(l.status==="dirty")t.dirty();c.add(l.value)}return{status:t.value,value:c}}let i=[...n.data.values()].map((a,c)=>o._parse(new Ai(n,a,n.path,c)));if(n.common.async)return Promise.all(i).then((a)=>s(a));else return s(i)}min(e,t){return new Wm({...this._def,minSize:{value:e,message:$e.toString(t)}})}max(e,t){return new Wm({...this._def,maxSize:{value:e,message:$e.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};Wm.create=(e,t)=>new Wm({valueType:e,minSize:null,maxSize:null,typeName:qe.ZodSet,...at(t)});C0=class C0 extends wt{constructor(){super(...arguments);this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==fe.function)return ae(t,{code:Z.invalid_type,expected:fe.function,received:t.parsedType}),Le;function n(i,a){return Lv({data:i,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,D0(),bu].filter((c)=>!!c),issueData:{code:Z.invalid_arguments,argumentsError:a}})}function r(i,a){return Lv({data:i,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,D0(),bu].filter((c)=>!!c),issueData:{code:Z.invalid_return_type,returnTypeError:a}})}let o={errorMap:t.common.contextualErrorMap},s=t.data;if(this._def.returns instanceof Km){let i=this;return Eo(async function(...a){let c=new xs([]),l=await i._def.args.parseAsync(a,o).catch((p)=>{throw c.addIssue(n(a,p)),c}),d=await Reflect.apply(s,this,l);return await i._def.returns._def.type.parseAsync(d,o).catch((p)=>{throw c.addIssue(r(d,p)),c})})}else{let i=this;return Eo(function(...a){let c=i._def.args.safeParse(a,o);if(!c.success)throw new xs([n(a,c.error)]);let l=Reflect.apply(s,this,c.data),d=i._def.returns.safeParse(l,o);if(!d.success)throw new xs([r(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new C0({...this._def,args:Jc.create(e).rest(gf.create())})}returns(e){return new C0({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new C0({args:e?e:Jc.create([]).rest(gf.create()),returns:t||gf.create(),typeName:qe.ZodFunction,...at(n)})}};N0=class N0 extends wt{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};N0.create=(e,t)=>new N0({getter:e,typeName:qe.ZodLazy,...at(t)});F0=class F0 extends wt{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return ae(t,{received:t.data,code:Z.invalid_literal,expected:this._def.value}),Le}return{status:"valid",value:e.data}}get value(){return this._def.value}};F0.create=(e,t)=>new F0({value:e,typeName:qe.ZodLiteral,...at(t)});yf=class yf extends wt{_parse(e){if(typeof e.data!=="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return ae(t,{expected:kt.joinValues(n),received:t.parsedType,code:Z.invalid_type}),Le}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return ae(t,{received:t.data,code:Z.invalid_enum_value,options:n}),Le}return Eo(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return yf.create(e,{...this._def,...t})}exclude(e,t=this._def){return yf.create(this.options.filter((n)=>!e.includes(n)),{...this._def,...t})}};yf.create=wQ;M0=class M0 extends wt{_parse(e){let t=kt.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==fe.string&&n.parsedType!==fe.number){let r=kt.objectValues(t);return ae(n,{expected:kt.joinValues(r),received:n.parsedType,code:Z.invalid_type}),Le}if(!this._cache)this._cache=new Set(kt.getValidEnumValues(this._def.values));if(!this._cache.has(e.data)){let r=kt.objectValues(t);return ae(n,{received:n.data,code:Z.invalid_enum_value,options:r}),Le}return Eo(e.data)}get enum(){return this._def.values}};M0.create=(e,t)=>new M0({values:e,typeName:qe.ZodNativeEnum,...at(t)});Km=class Km extends wt{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==fe.promise&&t.common.async===!1)return ae(t,{code:Z.invalid_type,expected:fe.promise,received:t.parsedType}),Le;let n=t.parsedType===fe.promise?t.data:Promise.resolve(t.data);return Eo(n.then((r)=>this._def.type.parseAsync(r,{path:t.path,errorMap:t.common.contextualErrorMap})))}};Km.create=(e,t)=>new Km({type:e,typeName:qe.ZodPromise,...at(t)});wa=class wa extends wt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===qe.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,o={addIssue:(s)=>{if(ae(n,s),s.fatal)t.abort();else t.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),r.type==="preprocess"){let s=r.transform(n.data,o);if(n.common.async)return Promise.resolve(s).then(async(i)=>{if(t.value==="aborted")return Le;let a=await this._def.schema._parseAsync({data:i,path:n.path,parent:n});if(a.status==="aborted")return Le;if(a.status==="dirty")return Hm(a.value);if(t.value==="dirty")return Hm(a.value);return a});else{if(t.value==="aborted")return Le;let i=this._def.schema._parseSync({data:s,path:n.path,parent:n});if(i.status==="aborted")return Le;if(i.status==="dirty")return Hm(i.value);if(t.value==="dirty")return Hm(i.value);return i}}if(r.type==="refinement"){let s=(i)=>{let a=r.refinement(i,o);if(n.common.async)return Promise.resolve(a);if(a instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return i};if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(i.status==="aborted")return Le;if(i.status==="dirty")t.dirty();return s(i.value),{status:t.value,value:i.value}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then((i)=>{if(i.status==="aborted")return Le;if(i.status==="dirty")t.dirty();return s(i.value).then(()=>({status:t.value,value:i.value}))})}if(r.type==="transform")if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!hf(s))return Le;let i=r.transform(s.value,o);if(i instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:i}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then((s)=>{if(!hf(s))return Le;return Promise.resolve(r.transform(s.value,o)).then((i)=>({status:t.value,value:i}))});kt.assertNever(r)}};wa.create=(e,t,n)=>new wa({schema:e,typeName:qe.ZodEffects,effect:t,...at(n)});wa.createWithPreprocess=(e,t,n)=>new wa({schema:t,effect:{type:"preprocess",transform:e},typeName:qe.ZodEffects,...at(n)});ba=class ba extends wt{_parse(e){if(this._getType(e)===fe.undefined)return Eo(void 0);return this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ba.create=(e,t)=>new ba({innerType:e,typeName:qe.ZodOptional,...at(t)});wu=class wu extends wt{_parse(e){if(this._getType(e)===fe.null)return Eo(null);return this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};wu.create=(e,t)=>new wu({innerType:e,typeName:qe.ZodNullable,...at(t)});j0=class j0 extends wt{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;if(t.parsedType===fe.undefined)n=this._def.defaultValue();return this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};j0.create=(e,t)=>new j0({innerType:e,typeName:qe.ZodDefault,defaultValue:typeof t.default==="function"?t.default:()=>t.default,...at(t)});L0=class L0 extends wt{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});if(R0(r))return r.then((o)=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new xs(n.common.issues)},input:n.data})}));else return{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new xs(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};L0.create=(e,t)=>new L0({innerType:e,typeName:qe.ZodCatch,catchValue:typeof t.catch==="function"?t.catch:()=>t.catch,...at(t)});Gv=class Gv extends wt{_parse(e){if(this._getType(e)!==fe.nan){let n=this._getOrReturnCtx(e);return ae(n,{code:Z.invalid_type,expected:fe.nan,received:n.parsedType}),Le}return{status:"valid",value:e.data}}};Gv.create=(e)=>new Gv({typeName:qe.ZodNaN,...at(e)});a8t=Symbol("zod_brand");iT=class iT extends wt{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}};Wv=class Wv extends wt{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});if(o.status==="aborted")return Le;if(o.status==="dirty")return t.dirty(),Hm(o.value);else return this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();else{let r=this._def.in._parseSync({data:n.data,path:n.path,parent:n});if(r.status==="aborted")return Le;if(r.status==="dirty")return t.dirty(),{status:"dirty",value:r.value};else return this._def.out._parseSync({data:r.value,path:n.path,parent:n})}}static create(e,t){return new Wv({in:e,out:t,typeName:qe.ZodPipeline})}};q0=class q0 extends wt{_parse(e){let t=this._def.innerType._parse(e),n=(r)=>{if(hf(r))r.value=Object.freeze(r.value);return r};return R0(t)?t.then((r)=>n(r)):n(t)}unwrap(){return this._def.innerType}};q0.create=(e,t)=>new q0({innerType:e,typeName:qe.ZodReadonly,...at(t)});c8t={object:In.lazycreate};(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(qe||(qe={}));S=Wc.create,j=Vm.create,l8t=Gv.create,u8t=Gm.create,Ke=qv.create,d8t=A0.create,f8t=Bv.create,p8t=O0.create,m8t=T0.create,h8t=Uv.create,_u=gf.create,g8t=Kc.create,y8t=Hv.create,he=ya.create,ee=In.create,b8t=In.strictCreate,Jm=P0.create,aT=sT.create,w8t=I0.create,_8t=Jc.create,Ks=zv.create,x8t=Vv.create,v8t=Wm.create,k8t=C0.create,E8t=N0.create,$t=F0.create,Ft=yf.create,S8t=M0.create,$8t=Km.create,D8t=wa.create,R8t=ba.create,C8t=wu.create,A8t=wa.createWithPreprocess,O8t=Wv.create});var cT=V(()=>{jv();nT();mQ();$0();_Q();Mv()});var Ko=V(()=>{cT();cT()});function lT(e){return Kv.includes(e)}var bGe,bf,Kv,xQ,wGe,vQ,_Ge,kQ,xGe,vGe,EQ,kGe,SQ,U8t,H8t,$Q,EGe,DQ,SGe,RQ,uT=20,dT=500,$Ge,z8t;var Ym=V(()=>{Ko();bGe=Ft(["pending","verified","approved","revoked"]),bf=Ft(["person","service","test"]),Kv=bf.options;xQ={nemarOwner:"service",nemarAdmin:"service","test-admin":"service","test-owner":"service","cool-vibers":"test","test-user":"test","test-pending":"test","test-verified":"test","test-revoked":"test"},wGe=Ft(["same_kind","orcid_linked","own_account","kind_changed_concurrently"]),vQ=wGe.options,_Ge=Ft(["active","pending","revoked"]),kQ=ee({field:S(),blocks:he(S()).optional(),set_on:he(S()).optional()}).passthrough(),xGe=ee({id:j().int(),username:S().nullable(),email:S(),github_username:S().nullable(),role:S(),orcid:S().nullable().optional(),created_at:S().optional(),approved_at:S().nullable().optional(),dataset_count:j().int().optional(),sandbox_completed:Ke().optional(),sandbox_completed_at:S().nullable().optional(),sandbox_dataset_id:S().nullable().optional(),service_access:Ke().optional(),status:bGe.optional(),email_verified:Ke().optional(),orcid_verified:Ke().optional(),given_name:S().nullable().optional(),family_name:S().nullable().optional(),profile_gaps:he(kQ).optional(),username_auto_assigned:Ke().optional(),account_kind:bf.optional()}).passthrough(),vGe=ee({prefix:S(),created_at:S(),last_used_at:S().nullable()}).passthrough().nullable(),EQ=ee({user:xGe,token:vGe.optional()}).passthrough(),kGe=ee({id:j().int(),username:S().nullable(),email:S(),github_username:S().nullable(),status:S(),email_verified:j().int().nullable().optional(),role:S().nullable(),created_at:S(),approved_at:S().nullable().optional(),revoked_at:S().nullable().optional(),signup_source:S().nullable().optional(),service_access:j().int().nullable().optional(),service_access_granted_at:S().nullable().optional(),given_name:S().nullable().optional(),family_name:S().nullable().optional(),orcid:S().nullable().optional(),upload_access_requested_at:S().nullable().optional(),account_kind:bf.optional(),matched_in:he(S()).optional(),match_kind:S().optional()}).passthrough(),SQ=ee({users:he(kGe),count:j().int()}).passthrough(),U8t=Ft(["assigned","would_assign","single_name","no_name","lookup_failed","conflict","exhausted","write_failed"]),H8t=Ft(["sent","already_verified","skipped_fence","rate_limited","failed","not_attempted"]),$Q=ee({suggestion:S().nullable(),based_on:Ft(["name","unavailable","exhausted"])}).passthrough(),EGe=Ft(["why_required","email_not_verified","profile_incomplete","github_username_unverified","github_unavailable","already_approved"]),DQ=EGe.options,SGe=Ft(["invalid_github_username","city_required","country_required","empty_patch","username_too_short","username_too_long","username_charset","given_name_required","family_name_required","username_taken","username_locked","name_is_orcid_canonical","account_revoked","github_unavailable","same_email","code_expired","code_incorrect","orcid_already_have","orcid_unavailable"]),RQ=SGe.options,$Ge=ee({id:j().int(),email:S(),username:S().nullable(),role:S(),status:_Ge,email_verified:Ke(),given_name:S().nullable(),family_name:S().nullable(),orcid:S().nullable(),orcid_verified:Ke(),github_username:S().nullable(),city:S().nullable(),country:S().nullable(),affiliation:S().nullable(),service_access:Ke(),service_access_granted_at:S().nullable(),upload_access_requested_at:S().nullable(),profile_gaps:he(kQ),username_auto_assigned:Ke()}).passthrough(),z8t=ee({user:$Ge.nullable()}).passthrough()});var fT,pT,K8t,DGe,J8t,RGe,CQ,AQ,mT=8,hT=100,OQ,TQ,CGe,PQ;var B0=V(()=>{Ko();Ym();fT=["given_name","family_name","affiliation","city","country"],pT=["username","github_username","email","orcid"],K8t=[...fT,...pT],DGe={given_name:S().max(200).optional(),family_name:S().max(200).optional(),affiliation:S().max(500).optional(),city:S().max(200).optional(),country:S().max(200).optional(),username:S().max(100).optional(),github_username:S().max(100).optional(),email:S().max(320).optional(),orcid:S().max(40).optional()},J8t=ee(DGe),RGe=Ft(["field_not_editable","owner_only_field","edit_own_account","owner_account","system_account","invalid_edit","orcid_already_proven","invalid_search","invalid_user_id"]),CQ=RGe.options,AQ=["exact","name","prefix","substring","fuzzy"],OQ=ee({id:j().int(),username:S().nullable(),email:S(),github_username:S().nullable(),status:S(),role:S().nullable(),account_kind:bf.optional(),email_verified:j().int().nullable().optional(),orcid:S().nullable().optional(),orcid_verified:j().int().nullable().optional(),given_name:S().nullable().optional(),family_name:S().nullable().optional(),affiliation:S().nullable().optional(),city:S().nullable().optional(),country:S().nullable().optional(),description:S().nullable().optional(),signup_source:S().nullable().optional(),created_at:S(),updated_at:S().nullable().optional(),approved_at:S().nullable().optional(),revoked_at:S().nullable().optional(),deleted_at:S().nullable().optional(),service_access:j().int().nullable().optional(),service_access_granted_at:S().nullable().optional(),service_access_granted_by:j().int().nullable().optional(),upload_access_requested_at:S().nullable().optional(),upload_access_notified_at:S().nullable().optional(),identity_conflict:j().int().nullable().optional(),username_auto_assigned:j().int().nullable().optional(),sandbox_completed:j().int().nullable().optional(),sandbox_completed_at:S().nullable().optional(),sandbox_dataset_id:S().nullable().optional(),aws_iam_username:S().nullable().optional(),dataset_count:j().int().optional(),active_tokens:j().int().optional(),linked_identities:he(S()).optional()}).passthrough(),TQ=ee({user:OQ}).passthrough(),CGe=ee({from:S().nullable(),to:S().nullable()}),PQ=ee({message:S(),changed:Ks(S(),CGe),notes:he(S()).optional(),old_address_notified:Ke().optional(),user:OQ}).passthrough()});function TGe(e){return e.startsWith("v")?e:`v${e}`}var AGe,OGe,IQ,Q8t;var gT=V(()=>{Ko();AGe=/^v?\d+\.\d+\.\d+(?:-(?:rc|alpha|beta)\d*)?$/,OGe=/^v\d+\.\d+\.\d+(?:-(?:rc|alpha|beta)\d*)?$/;IQ=S().regex(AGe,"must be a semver version, optionally v-prefixed").transform(TGe),Q8t=S().regex(OGe,"must be the canonical v-prefixed tag (vX.Y.Z)")});function FQ(e,t){if(e.zarr_index_url!=null&&e.zarr_status!=="ready")t.addIssue({code:Z.custom,message:"zarr_index_url must be null/absent unless zarr_status is 'ready'",path:["zarr_index_url"]})}function MQ(e,t){if(e.zarr_verified_at!=null&&e.zarr_verify_status==null)t.addIssue({code:Z.custom,message:"zarr_verified_at must be null/absent unless zarr_verify_status is non-null",path:["zarr_verified_at"]})}var PGe="0.4.1",yT,Xm,NQ,IGe,NGe,FGe,jQ,nBt,LQ,rBt,Yc,MGe,Jv,oBt,jGe,LGe,sBt;var bT=V(()=>{Ko();gT();yT=Ft(["openneuro","nemar","gin","other"]),Xm=Jm([$t(0),$t(1)]).nullable(),NQ=ee({dataset_id:S(),id:S().optional(),name:S(),description:S().nullable().optional(),status:S(),visibility:S(),anonymous:j().int().nullable().optional(),concept_doi:S().nullable().optional(),doi:S().nullable().optional(),created_at:S(),updated_at:S().optional(),first_published_at:S().nullable().optional(),owner_username:S().nullable().optional(),source:S().nullable().optional(),modalities:S().optional(),participants:j().int().nonnegative(),tasks:S().optional(),authors:S().optional(),license:S().optional(),file_size:j().nonnegative(),file_size_formatted:S().optional(),total_files:j().nonnegative().nullable().optional(),num_citations:j().int().nonnegative().optional(),n_channels:j().int().nullable().optional(),electrode_system:S().nullable().optional(),has_hed:Xm.optional(),hed_version:S().nullable().optional(),data_complete:Xm.optional(),bytes_present:j().nonnegative().nullable().optional(),latest_version:IQ.nullable().optional(),latest_version_at:S().nullable().optional(),subject_count:j().int().nullable().optional(),file_size_bytes:j().nullable().optional(),sessions_count:j().int().nullable().optional(),age_min:j().nullable().optional(),age_max:j().nullable().optional(),bids_version:S().nullable().optional(),zarr_status:Ft(["pending","ready","failed"]).nullable().optional(),zarr_store_count:j().int().nullable().optional(),zarr_converted_at:S().nullable().optional(),zarr_source_commit:S().nullable().optional(),zarr_errors:j().int().nullable().optional(),zarr_failure_count:j().int().nullable().optional(),zarr_deterministic:Xm.optional(),zarr_failed_at:S().nullable().optional(),zarr_index_url:S().nullable().optional(),zarr_verify_status:Ft(["verified","failed","unverifiable"]).nullable().optional(),zarr_verified_at:S().nullable().optional(),zarr_requeue_at:S().nullable().optional(),anonymity_status:Ft(["verified","findings","unverifiable"]).nullable().optional(),anonymity_checked_at:S().nullable().optional(),anonymity_findings:S().nullable().optional(),anonymity_unchecked:S().nullable().optional(),total_recording_duration:j().nullable().optional(),recording_duration_min:j().nullable().optional(),recording_duration_max:j().nullable().optional(),recording_count:j().int().nullable().optional(),recordings_unavailable:j().int().nullable().optional(),channel_count_min:j().int().nullable().optional(),channel_count_max:j().int().nullable().optional(),sampling_frequency:j().nullable().optional(),power_line_frequency:j().nullable().optional(),eeg_reference:S().nullable().optional(),placement_scheme:S().nullable().optional()}).passthrough();IGe=NQ.superRefine((e,t)=>{FQ(e,t),MQ(e,t)}),NGe=NQ.extend({file_size:j().nonnegative().nullable(),file_size_formatted:S().nullable().optional(),modalities:S().nullable().optional(),tasks:S().nullable().optional(),authors:S().nullable().optional(),license:S().nullable().optional(),owner_github:S().nullable().optional(),attestation_deposit_type:Ft(["owner","redistribution"]).nullable().optional(),attestation_key_status:Ft(["destroyed","retained"]).nullable().optional(),attestation_deidentified:Xm.optional(),attestation_no_duplicate:Xm.optional(),attestation_upstream_source:S().nullable().optional(),attestation_accepted_at:S().nullable().optional(),zarr_data_failures:ee({count:j().int().nonnegative(),detail_ref:S(),compacted_by:S().optional(),pending:j().int().nonnegative().optional(),discovered:j().int().nonnegative().optional(),events_upload_failed:$t(!0).optional(),manifest_upload_failed:$t(!0).optional()}).passthrough().nullable().optional()}).passthrough().superRefine((e,t)=>{FQ(e,t),MQ(e,t)}),FGe=ee({id:S(),name:S(),modalities:S().nullable().optional(),participants:j().int().nullable().optional(),doi:S().nullable().optional(),tasks:S().nullable().optional(),authors:S().nullable().optional(),has_hed:Xm.optional(),score:j().optional(),snippet:S().optional()}).passthrough(),jQ=Ks(S(),j().int().nonnegative()),nBt=ee({datasets:he(IGe),count:j().int().nonnegative(),total_count:j().int().nonnegative().optional(),limit:j().int().optional(),offset:j().int().optional(),excluded_unknown:j().int().nonnegative().optional(),excluded_unknown_by_facet:jQ.optional()}).passthrough(),LQ=ee({results:he(FGe),count:j().int().nonnegative(),returned:j().int().nonnegative().optional(),offset:j().int().nonnegative().optional(),limit:j().int().optional(),candidate_ceiling:j().int().optional(),truncated:Ke().optional(),method:Ft(["exact_id","text","text_fallback","semantic","unavailable"]).optional(),min_score:j().optional(),warning:S().optional(),excluded_unknown:j().int().nonnegative().optional(),excluded_unknown_by_facet:jQ.optional()}).passthrough(),rBt=ee({dataset:NGe}).passthrough(),Yc=ee({value:S(),count:j().int().nonnegative()}),MGe=ee({values:he(Yc),distinct_total:j().int().nonnegative(),truncated:Ke()}),Jv=ee({"electrode-system":he(Yc).optional(),source:he(Yc).optional(),zarr:he(Yc).optional(),powerline:he(Yc).optional(),"bids-version":he(Yc).optional(),"hed-version":he(Yc).optional(),license:he(Yc).optional(),modality:he(Yc).optional(),task:MGe.optional(),warning:S().optional()}).passthrough(),oBt=ee({schema_version:$t(PGe),doc_type:$t("dataset"),dataset_id:S().regex(/^[a-z]{2}\d+$/,"neuroschema dataset_id pattern"),name:S(),source:yT,recording_modality:he(S()).min(1),description:S().nullable().optional(),bids_version:S().nullable().optional(),license:S().nullable().optional()}).passthrough(),jGe=ee({tasks:Ks(ee({runs:he(S())}).passthrough())}).passthrough(),LGe=ee({sessions:he(S()),modalities:Ks(jGe),session_modalities:Ks(he(S())).optional()}).passthrough(),sBt=ee({version:S(),subjects:Ks(LGe)}).passthrough()});function Yv(e){return typeof e==="string"&&qQ.includes(e)}var qGe,cBt,lBt,uBt,qQ,BGe="ci_check_unavailable",BQ,UQ,HQ,zQ="X-Approval-Dispatch-Token",dBt;var U0=V(()=>{Ko();qGe=/^\d{4}-\d{4}-\d{4}-\d{3}[\dX]$/,cBt=S().regex(qGe,"ORCID must be in format 0000-0000-0000-000X"),lBt=Ft(["found","no_public_name","lookup_failed"]),uBt=Ft(["bids_validation_failed","bids_validation_pending","bids_validation_in_progress","prescreen_failed","min_requirements_failed","owner_name_missing","identifier_screen_findings"]),qQ=["bids_validation_pending","bids_validation_in_progress"];BQ=[BGe],UQ=["identifier_screen_pending","identifier_screen_not_clear","identifier_screen_not_applicable"],HQ=["publication_review_not_clear","request_blocked","request_changed","request_mismatch","dispatch_superseded","dispatch_expired","decision_with_dispatch_token","approval_in_flight","deny_after_publishing","invalid_dataset_id","approval_closed_during_run"],dBt=Ft(["filled","would_fill","no_public_name","lookup_failed","write_failed"])});var UGe,VQ,H0="https://nemar.org/settings",mBt,HGe,zGe,VGe,GQ,WQ;var wT=V(()=>{Ko();UGe=Ft(["orcid_in_use","orcid_already_linked","orcid_linked_other","email_in_use","github_in_use","identity_conflict_remains"]),VQ=UGe.options,mBt={orcid_in_use:`That ORCID iD already belongs to a NEMAR account. Sign in to that account instead; if you want the iD on a different account, unlink it there first (Settings, ${H0}).`,orcid_already_linked:`That ORCID iD already belongs to a NEMAR account. Sign in to that account instead; if you want the iD on a different account, unlink it there first (Settings, ${H0}).`,orcid_linked_other:`That ORCID iD is linked to a different NEMAR account. Unlink it there first (Settings, ${H0}), then link it here.`,email_in_use:`That email address already belongs to a NEMAR account. Sign in to that account instead, or change its address first (Settings, ${H0}).`,github_in_use:`That GitHub account is already linked to a NEMAR account. Sign in to that account instead, or change its GitHub username first (Settings, ${H0}).`,identity_conflict_remains:"The collision that flagged this account is still there. Resolve it on the other account first (change its email or GitHub username, or unlink its ORCID iD), or delete that account, then clear the flag."},HGe=Ft(["orcid","email","github"]),zGe=ee({id:j().int(),username:S().nullable(),email:S(),created_at:S(),has_oauth_identity:Ke(),dataset_count:j().int(),identity_conflict:j().int(),canonical:Ke()}).passthrough(),VGe=ee({kind:HGe,value:S(),canonical_user_id:j().int(),accounts:he(zGe)}).passthrough(),GQ=ee({groups:he(VGe),group_count:j().int(),flagged_count:j().int()}).passthrough(),WQ=ee({ok:$t(!0),id:j().int(),cleared:Ke()}).passthrough()});var _T=120,KQ=64,xT="unnamed machine",GGe=25,Xv,JQ,Qm,YQ,yBt,bBt,XQ,WGe,KGe,QQ,vT,ZQ,wBt,_Bt,Qv,Zv;var ek=V(()=>{Ko();Xv=Ft(["authorization_pending","slow_down","expired_token","access_denied","invalid_grant"]),JQ={authorization_pending:"Waiting for you to authorize this machine in the browser.",slow_down:"Polling too quickly; the CLI will slow down automatically.",expired_token:"The code expired. Run `nemar auth login` again for a new one.",access_denied:"This sign-in was declined in the browser. Run `nemar auth login` again if that was a mistake.",invalid_grant:"That code is no longer valid. Run `nemar auth login` again for a new one."},Qm=Ft(["device_code_unknown","device_code_expired","device_code_used","device_code_denied","account_pending","account_revoked","identity_conflict","service_account","person_account","too_many_keys","key_not_found"]),YQ=Qm.options,yBt={device_code_unknown:"That code was not found. Check the code shown in your terminal, or run `nemar auth login` again for a new one.",device_code_expired:"The code expired. Run `nemar auth login` again for a new one.",device_code_used:"That code has already been used. Run `nemar auth login` again for a new one.",device_code_denied:"This sign-in was declined in the browser. Run `nemar auth login` again if that was a mistake.",account_pending:"Verify your email address first. Check your inbox for the NEMAR verification code, then authorize again.",account_revoked:"Your NEMAR account access has been revoked. Contact the NEMAR team if you think this is a mistake.",identity_conflict:"This account shares an identifier with another NEMAR account and cannot sign in until that is resolved. Fix it in Settings on nemar.org or contact the NEMAR team.",service_account:"This is a service or test account, and it cannot sign in this way. Ask an owner to create a key for it with `nemar admin keys create`.",person_account:"This account belongs to a person. A person creates their own keys with `nemar auth login` or in Settings on nemar.org.",too_many_keys:`This account already has ${GGe} active keys. Revoke one in Settings on nemar.org or with \`nemar auth keys\`, then try again.`,key_not_found:"That key was not found on this account, or it is already revoked. Run `nemar auth keys` to see the active ones."},bBt=ee({error:Qm,message:S()}).passthrough(),XQ=ee({device_code:S(),user_code:S(),verification_uri:S(),verification_uri_complete:S(),expires_in:j().int(),interval:j().int()}).passthrough(),WGe=aT("error",[ee({error:$t("authorization_pending"),message:S()}).passthrough(),ee({error:$t("slow_down"),message:S()}).passthrough()]),KGe=aT("error",[ee({error:$t("expired_token"),reason:Qm,message:S()}).passthrough(),ee({error:$t("access_denied"),reason:Qm,message:S()}).passthrough(),ee({error:$t("invalid_grant"),reason:Qm,message:S()}).passthrough()]),QQ=Jm([WGe,KGe]),vT=ee({id:j().int(),name:S().nullable(),prefix:S(),created_at:S(),last_used_at:S().nullable(),current:Ke()}).passthrough(),ZQ=ee({api_key:S(),key:vT,user:ee({username:S().nullable(),email:S(),github_username:S().nullable(),role:S(),sandbox_completed:Ke(),sandbox_dataset_id:S().nullable()}).passthrough()}).passthrough(),wBt=ee({user_code:S(),machine_name:S(),requested_at:S(),expires_in:j().int(),account:ee({username:S().nullable(),email_masked:S()}).passthrough(),refusal:ee({code:Qm,message:S()}).passthrough().nullable()}).passthrough(),_Bt=ee({ok:$t(!0),machine_name:S()}).passthrough(),Qv=ee({keys:he(vT)}).passthrough(),Zv=ee({api_key:S(),key:vT}).passthrough()});function nr(e){return Nn[e]}function Xc(e,t){return e.replace(/\{(\w+)\}/g,(n,r)=>Object.hasOwn(t,r)?t[r]:n)}var Nn;var Zm=V(()=>{Nn={"tier.unverified.label":"Email not verified","tier.base.label":"Base access","tier.upload.label":"Upload access","tier.unverified.lede":"Verify your email address to activate your account.","upload_access.section.title":"Upload access","upload_access.section.lede":"A one-time admin grant. Reviewed against export-control and local-jurisdiction rules.","upload_access.state.granted":"Granted","upload_access.state.requested":"Requested","upload_access.state.not_requested":"Not requested","upload_access.invite.title":"Want to contribute a dataset?","upload_access.invite.body":"Browsing, searching and downloading are open to your account already. Uploading, or being added as a collaborator on someone else\u2019s dataset, needs one extra grant: an admin checks your GitHub handle and location against export-control and local-jurisdiction rules, once. Your email address must be verified first.","upload_access.gate.title":"Ask for upload access first","upload_access.gate.body":"Your account can browse, search and download everything public already. Uploading, or being added as a collaborator on someone else\u2019s dataset, needs one extra grant, and your email address must be verified first: an admin checks your GitHub handle and where you\u2019re based against export-control and local-jurisdiction rules. You ask once, and it is answered by email.","upload_access.request.cta":"Request upload access","upload_access.request.form_body":"Tell us what you plan to deposit, or which dataset you want to collaborate on. An admin reviews this alongside your name, username, GitHub handle and location, then grants access once.","upload_access.request.why_label":"What do you intend to upload?","upload_access.request.why_hint":"Describe what you intend to upload in 20-500 characters","upload_access.requested.title":"Your request is with an admin","upload_access.requested.lede":"An admin is reviewing your request.","upload_access.requested.lede_dated":"An admin is reviewing your request from {date}.","upload_access.requested.body.upload":"We\u2019ll email you when there\u2019s a decision, and this page will let you upload as soon as it\u2019s granted.","upload_access.requested.body":"We\u2019ll email you when there\u2019s a decision. Everything else on your account keeps working in the meantime.","upload_access.requested.cta":"See the request","upload_access.granted.body":"You can upload datasets from the upload page. Publishing one is a separate, per-dataset review you start from your dashboard.","upload_access.unverified.body":"Verify your email address first \u2014 the review happens over email.","upload_access.docs_link":"How upload access works","gap.sentence":"{label} is missing: needed {blocks}.","gap.set_on.both":"Set it in {web} or run `{cli}`.","gap.set_on.web":"Set it in {web}.","gap.blocks.verified":"to activate your account","gap.blocks.upload_access":"to request upload access","gap.blocks.publication":"to publish a dataset","gap.blocks.unknown":"to finish setting up your account","gap.blocks.noun.verified":"account activation","gap.blocks.noun.upload_access":"upload access","gap.blocks.noun.publication":"publication","gap.set_on.default_web":"Settings","gap.field.email_verified.label":"A verified email address","gap.field.username.label":"Username","gap.field.given_name.label":"Given name","gap.field.family_name.label":"Family name","gap.field.orcid_verified.label":"Verified ORCID iD","gap.field.github_username.label":"GitHub handle","gap.field.city.label":"City","gap.field.country.label":"Country","gap.field.why.label":"A description of what you intend to upload","gap.field.email_verified.set_on.web":"the verify step on your dashboard","gap.field.email_verified.set_on.cli":"nemar auth resend-verification","gap.field.username.set_on.web":"Settings","gap.field.username.set_on.cli":"nemar auth profile set-username","gap.field.given_name.set_on.web":"Settings","gap.field.given_name.set_on.cli":"nemar auth profile set-name","gap.field.family_name.set_on.web":"Settings","gap.field.family_name.set_on.cli":"nemar auth profile set-name","gap.field.given_name.set_on.web.orcid":"your ORCID record at orcid.org, then sign in again","gap.field.family_name.set_on.web.orcid":"your ORCID record at orcid.org, then sign in again","gap.field.orcid_verified.set_on.web":"Settings","gap.field.orcid_verified.set_on.cli":"nemar auth profile orcid link","gap.field.github_username.set_on.web":"Settings","gap.field.github_username.set_on.cli":"nemar auth profile set-github","gap.field.city.set_on.web":"Settings","gap.field.city.set_on.cli":"nemar auth profile set-location","gap.field.country.set_on.web":"Settings","gap.field.country.set_on.cli":"nemar auth profile set-location","gap.field.why.set_on.web":"the request form in Settings","gap.field.why.set_on.cli":"nemar auth request-upload-access","gaps.title":"What is still missing","gaps.none":"Nothing outstanding \u2014 every field NEMAR needs is filled in.","gaps.nudge.title":"Your profile isn\u2019t finished yet","gaps.nudge.cta":"Complete your profile","gaps.upload.title":"Before you can ask, your account still needs:","gaps.request.title":"Finish these first:","gaps.admin.title":"Still missing","gaps.admin.item":"{label} \u2014 blocks {blocks}","gaps.admin.none":"Nothing missing \u2014 every field the request needs is filled in.","gaps.admin.not_loaded":"Not loaded \u2014 open the user page to see what is still missing.","onboarding.username.auto_assigned.title":"We chose your username from your name","onboarding.username.auto_assigned.body":"Your account needed a username to be listed as a dataset owner, so one was made from your name when you signed in. You can change it once, here, until an admin grants you upload access.","welcome.unverified.title":"Verify your email address","welcome.unverified.body":"Authorizing with ORCID created your NEMAR account and signed you in. One step left: enter the 6-digit code we emailed you. That activates the account \u2014 no admin approval is involved.","welcome.active.title":"Your account is active","welcome.active.body":"Authorizing with ORCID created your NEMAR account and signed you in. There is no separate sign-up step and no approval queue: browse, search, and your dashboard all work right now.","welcome.upload_access.title":"Ask for upload access when you\u2019re ready to contribute","welcome.upload_access.body":"Reading is open to every verified account. Uploading and compute need one extra grant, because an admin has to check your GitHub handle and location against export-control and local-jurisdiction rules first. You ask once, from Settings.","cli.gaps.section.title":"Profile","cli.gaps.unknown":"not checked: run 'nemar auth status --refresh'","cli.gaps.unreported":"not reported by this backend","cli.gap.set_on.cli_only":"Run `{cli}`.","cli.gap.field.sandbox.label":"Sandbox training","cli.gap.blocks.sandbox":"to upload a dataset from the CLI","cli.gap.field.sandbox.set_on.cli":"nemar sandbox","cli.gaps.sandbox_unchecked":"Sandbox training could not be confirmed with the server. Run `nemar sandbox status --refresh`, then `nemar sandbox` if it is still outstanding.","cli.upload.preflight.title":"Upload access is not granted yet","cli.upload.preflight.body":"Browsing, searching and downloading are open to your account already. Uploading, or being added as a collaborator on someone else\u2019s dataset, needs one extra grant: an admin checks your GitHub handle and location against export-control and local-jurisdiction rules, once. Your email address must be verified first.","cli.upload_access.cta":"Ask for it with `nemar auth request-upload-access`.","cli.upload.preflight.unchecked":"Upload access could not be checked ({reason}); continuing.","cli.upload.preflight.gaps_unknown":"Could not determine what is still missing; run `nemar auth profile` for the list.","cli.upload.preflight.dry_run":"Continuing anyway: --dry-run uploads nothing."}});function YGe(e){return e==="verified"||e==="upload_access"||e==="publication"}function eh(e){return(e??"").trim().length===0}function XGe(e){return e==="service"||e==="test"}function nZ(e,t={}){let n=t.orcidVerified===!0,r=Object.hasOwn(tk,e)?tk[e]:void 0;if(!r)return{field:e,label:e,blocks:t.blocks??[],setOnWeb:Nn["gap.set_on.default_web"],setOnCli:null,known:!1};let o=n&&r.orcidWebKey!==void 0;return{field:e,blocks:t.blocks??r.blocks,label:Nn[r.labelKey],setOnWeb:Nn[o?r.orcidWebKey:r.webKey],setOnCli:o||r.cliKey===null?null:Nn[r.cliKey],known:!0}}function eZ(e){let t=kT.indexOf(e);return t===-1?kT.length:t}function rZ(e,t={}){return e.map((n)=>nZ(n,{orcidVerified:t.orcidVerified}))}function nk(e,t={}){return e.filter((n)=>!!n&&typeof n.field==="string").map((n)=>{let r=Array.isArray(n.blocks)?n.blocks.filter(YGe):[];return nZ(n.field,{orcidVerified:t.orcidVerified,blocks:r.length>0?r:void 0})}).sort((n,r)=>eZ(n.field)-eZ(r.field))}function ET(e){let t=e.blocks[0],n=t?Nn[JGe[t]]:Nn["gap.blocks.unknown"],r=Xc(Nn["gap.sentence"],{label:"",blocks:n}).trimStart(),o=e.setOnCli?Xc(Nn["gap.set_on.both"],{web:e.setOnWeb,cli:e.setOnCli}):Xc(Nn["gap.set_on.web"],{web:e.setOnWeb});return`${r} ${o}`}function oZ(e){return`${e.label} ${ET(e)}`}function rk(){let e=Xc(Nn["gap.sentence"],{label:tZ.label,blocks:Nn["cli.gap.blocks.sandbox"]}),t=Xc(Nn["cli.gap.set_on.cli_only"],{cli:tZ.command});return`${e} ${t}`}function sZ(){return Nn["cli.gaps.sandbox_unchecked"]}var tk,kT,EBt,JGe,tZ;var th=V(()=>{Zm();tk={email_verified:{blocks:["verified","upload_access"],labelKey:"gap.field.email_verified.label",webKey:"gap.field.email_verified.set_on.web",cliKey:"gap.field.email_verified.set_on.cli",isMissing:(e)=>e.status==="pending"||e.email_verified===!1},username:{blocks:["upload_access"],labelKey:"gap.field.username.label",webKey:"gap.field.username.set_on.web",cliKey:"gap.field.username.set_on.cli",isMissing:(e)=>e.username!==void 0&&eh(e.username)},given_name:{blocks:["upload_access","publication"],labelKey:"gap.field.given_name.label",webKey:"gap.field.given_name.set_on.web",cliKey:"gap.field.given_name.set_on.cli",orcidWebKey:"gap.field.given_name.set_on.web.orcid",isMissing:(e)=>eh(e.given_name)},family_name:{blocks:["upload_access","publication"],labelKey:"gap.field.family_name.label",webKey:"gap.field.family_name.set_on.web",cliKey:"gap.field.family_name.set_on.cli",orcidWebKey:"gap.field.family_name.set_on.web.orcid",isMissing:(e)=>eh(e.family_name)},orcid_verified:{blocks:["upload_access"],labelKey:"gap.field.orcid_verified.label",webKey:"gap.field.orcid_verified.set_on.web",cliKey:"gap.field.orcid_verified.set_on.cli",isMissing:(e)=>e.orcid_verified!==!0&&!XGe(e.account_kind)},github_username:{blocks:["upload_access","publication"],labelKey:"gap.field.github_username.label",webKey:"gap.field.github_username.set_on.web",cliKey:"gap.field.github_username.set_on.cli",isMissing:(e)=>eh(e.github_username)},city:{blocks:["upload_access"],labelKey:"gap.field.city.label",webKey:"gap.field.city.set_on.web",cliKey:"gap.field.city.set_on.cli",isMissing:(e)=>eh(e.city)},country:{blocks:["upload_access"],labelKey:"gap.field.country.label",webKey:"gap.field.country.set_on.web",cliKey:"gap.field.country.set_on.cli",isMissing:(e)=>eh(e.country)},why:{blocks:["upload_access"],labelKey:"gap.field.why.label",webKey:"gap.field.why.set_on.web",cliKey:"gap.field.why.set_on.cli",isMissing:null}},kT=Object.keys(tk),EBt=kT.filter((e)=>tk[e].isMissing!==null),JGe={verified:"gap.blocks.verified",upload_access:"gap.blocks.upload_access",publication:"gap.blocks.publication"};tZ={field:"sandbox",label:Nn["cli.gap.field.sandbox.label"],command:Nn["cli.gap.field.sandbox.set_on.cli"]}});function ak(e,t){let n=e.sss!==void 0;if(e.derived!==n)t.addIssue({code:Z.custom,path:["sss"],message:e.derived?"derived is true but sss is absent (ADR 0028: the two travel together)":"sss is present but derived is false (ADR 0028: the two travel together)"})}var So,ok,iZ,sk,QGe,ik,ZGe,eWe,tWe,nWe,rWe,DBt,oWe,RBt,sWe,CBt;var ST=V(()=>{Ko();So=/^[a-z]{2}[0-9]{6}$/,ok=/^[0-9a-f]{40}$/,iZ=ee({name:S(),modality:S().nullable().optional(),rate:j().nullable().optional(),n_channels:j().int().nonnegative().nullable().optional(),n_samples:j().int().nonnegative().nullable().optional(),duration_s:j().nonnegative().nullable().optional(),source_rate_hz:j().nullable().optional(),n_view_levels:j().int().nonnegative().optional(),view_chunk_columns:j().int().positive().optional(),chunk_samples:j().int().positive().optional(),shard_samples:j().int().positive().optional()}).passthrough(),sk=ee({converted:j().int().nonnegative().optional(),relabelled:j().int().nonnegative().optional(),kept_importer_unit:j().int().nonnegative().optional(),units_column_present:Ke().optional(),sidecar:S().optional(),sidecar_supplied:Ke().optional(),unmatched_channels:j().int().nonnegative().optional(),unmatched_case_only:j().int().positive().optional(),matched_case_only:j().int().positive().optional(),matched_case_only_examples:he(S()).max(5).optional(),unmatched_raw_label:j().int().positive().optional(),unmatched_examples:he(S()).max(5).optional()}).passthrough(),QGe=ee({channels_tsv:j().int().positive(),in_file:j().int().nonnegative(),in_store:j().int().nonnegative()}).passthrough(),ik=ee({applied:Ke().optional(),method:S().optional(),calibration:S().optional(),cross_talk:S().optional(),mne_version:S().optional()}).passthrough();ZGe=ee({path:S(),zarr:S().regex(/\.zarr$/,"must end in .zarr"),updated_utc:S().optional(),source_tree:$t("raw"),derived:Ke(),modalities:he(S()).optional(),groups:he(iZ).optional(),power_line_frequency:j().nullable().optional(),event_description_count:j().int().nonnegative().optional(),n_events:j().int().nonnegative().optional(),trial_types:Ks(S(),j().int().nonnegative()).optional(),units_report:sk.optional(),channels_tsv_read_error:Ke().optional(),channels_tsv_count_mismatch:QGe.optional(),split_members:he(S()).optional(),sss:ik.optional()}).passthrough().superRefine(ak),eWe=ee({path:S(),zarr:S().regex(/\.zarr$/,"must end in .zarr").optional(),code:S(),reason:S(),detail:S().nullable().optional(),attempts:j().int().nonnegative().optional()}).passthrough(),tWe=Ft(["infra_failure","memory_budget","not_attempted"]),nWe=ee({path:S(),zarr:S().regex(/\.zarr$/,"must end in .zarr"),reason:tWe,attempts:j().int().nonnegative(),last_error:S().nullable().optional(),last_attempt_utc:S().nullable().optional()}).passthrough(),rWe=ee({level0:$t("<zarr>/<group>/0"),view:$t("<zarr>/<group>/view/<L>"),view_levels:$t("1..n_view_levels from the group attrs"),scale_offset:$t("level-0 array attrs scale[] and offset[]; physical = digital * scale + offset"),events:$t("<data_base>events.parquet").optional()}).passthrough(),DBt=ee({format:$t("nemar-zarr-index"),format_version:$t(3),dataset_id:S().regex(So,"NEMAR dataset id (nm/on/xx band)"),contract_base:S().regex(/^https:\/\//,"must be https"),data_base:S().regex(/^https:\/\//,"must be https"),data_base_kind:$t("s3-public"),s3_uri:S().regex(/^s3:\/\//,"must be an s3:// URI"),s3_region:S().min(1),s3_anonymous:Ke(),source_commit:S().regex(ok,"must be a full 40-hex SHA"),engine_version:S().min(1),biosigio_version:S().nullable().optional(),updated_utc:S(),discovered_count:j().int().nonnegative(),store_count:j().int().nonnegative(),n_recordings:j().int().nonnegative(),errors:j().int().nonnegative(),failure_count:j().int().nonnegative(),pending_count:j().int().nonnegative(),stores:he(ZGe),failures:he(eWe),pending:he(nWe),doi:S().nullable().optional(),license:S().nullable().optional(),citation:S().nullable().optional(),hed_version:S().nullable().optional(),events_parquet:S().regex(/^https:\/\//,"must be https").optional(),events_row_count:j().int().nonnegative().optional(),layout:rWe}).passthrough(),oWe=ee({name:S(),configuration:Ks(S(),_u()).optional()}).passthrough(),RBt=ee({zarr_format:$t(3),node_type:$t("array"),shape:he(j().int().nonnegative()),data_type:S(),chunk_grid:ee({name:S(),configuration:Ks(S(),_u()).optional()}).passthrough(),codecs:he(oWe),fill_value:_u().optional(),attributes:Ks(S(),_u()).optional(),dimension_names:he(S().nullable()).optional()}).passthrough(),sWe=ee({path:S(),zarr:S().regex(/\.zarr$/,"must end in .zarr"),groups:he(iZ).optional(),modalities:he(S()).optional()}).passthrough(),CBt=ee({format:$t("nemar-zarr-index"),format_version:j().int(),dataset_id:S().regex(So,"NEMAR dataset id (nm/on/xx band)"),source_commit:S(),stores:he(sWe)}).passthrough()});function aZ(e){let t=e.unit?` (${e.unit})`:"";switch(e.valueKind){case"enum":return`${e.label} -- comma-separated, one or more of: ${(e.enumValues??[]).join(", ")}`;case"number":return`${e.label}${t} -- range (e.g. 10..50, 10.., ..50, or 10)`;case"bytes":return`${e.label}${t} -- range with optional units (e.g. 10gb..2tb, 500mb.., ..1gb; bare = bytes)`;case"duration":return`${e.label}${t} -- range with optional units (e.g. 30m..2h, 100h.., ..90s; bare = seconds)`;case"text":return`${e.label} -- substring match`;case"version":return`${e.label} -- exact or prefix match`}}var iWe,aWe,cWe,lWe,_a,TBt;var ck=V(()=>{bT();iWe=["10-05","10-10","10-20","biosemi","egi-geodesic","other"],aWe=["50","60"],cWe=["ready","pending","failed"],lWe=yT.options,_a=[{key:"subjects",flag:"--subjects",queryParam:"subjects",valueKind:"number",label:"Subject count",unit:"subjects"},{key:"channels",flag:"--channels",queryParam:"channels",valueKind:"number",label:"Channel count",unit:"channels"},{key:"sessions",flag:"--sessions",queryParam:"sessions",valueKind:"number",label:"Session count",unit:"sessions"},{key:"size",flag:"--size",queryParam:"size",valueKind:"bytes",label:"Dataset size"},{key:"files",flag:"--files",queryParam:"files",valueKind:"number",label:"File count",unit:"files"},{key:"citations",flag:"--citations",queryParam:"citations",valueKind:"number",label:"Citation count",unit:"citations"},{key:"duration",flag:"--duration",queryParam:"duration",valueKind:"duration",label:"Total recording duration"},{key:"recording-length",flag:"--recording-length",queryParam:"recording_length",valueKind:"duration",label:"Per-recording duration"},{key:"recordings",flag:"--recordings",queryParam:"recordings",valueKind:"number",label:"Recording count",unit:"recordings"},{key:"unavailable",flag:"--unavailable",queryParam:"unavailable",valueKind:"number",label:"Unavailable recording count",unit:"recordings"},{key:"age",flag:"--age",queryParam:"age",valueKind:"number",label:"Participant age",unit:"years"},{key:"rate",flag:"--rate",queryParam:"rate",valueKind:"number",label:"Sampling rate",unit:"Hz"},{key:"powerline",flag:"--powerline",queryParam:"powerline",valueKind:"enum",label:"Power line frequency",enumValues:aWe},{key:"reference",flag:"--reference",queryParam:"reference",valueKind:"text",label:"EEG reference"},{key:"placement",flag:"--placement",queryParam:"placement",valueKind:"text",label:"Electrode placement scheme"},{key:"electrode-system",flag:"--electrode-system",queryParam:"electrode_system",valueKind:"enum",label:"Electrode system",enumValues:iWe},{key:"source",flag:"--source",queryParam:"source",valueKind:"enum",label:"Source archive",enumValues:lWe},{key:"zarr",flag:"--zarr",queryParam:"zarr",valueKind:"enum",label:"Zarr conversion status",enumValues:cWe},{key:"bids-version",flag:"--bids-version",queryParam:"bids_version",valueKind:"version",label:"BIDS version"},{key:"hed-version",flag:"--hed-version",queryParam:"hed_version",valueKind:"version",label:"HED version"}],TBt=new Map(_a.map((e)=>[e.key,e]))});var uWe,MBt,dWe,fZ,z0,cZ,fWe,pZ,pWe=20,mWe=100,hWe,mZ,gWe,jBt,LBt,yWe,qBt,BBt,bWe,wWe,_We,UBt,xWe=50,vWe=500,HBt,kWe,EWe,zBt,SWe=1000,$We=5000,lZ=8,DWe=100,RWe=32,uZ,VBt,CWe,AWe,OWe,GBt,TWe=800,PWe=4000,WBt,KBt,$T=60,DT=64,dZ,IWe=86400,NWe=4096,JBt,FWe,MWe,YBt;var hZ=V(()=>{Ko();ck();ST();uWe=ee({dataset_id:S().regex(So),name:S(),doi:S().nullable().optional(),license:S().nullable().optional(),modalities:he(S()).optional(),tasks:he(S()).optional(),subject_count:j().int().nonnegative().nullable().optional(),has_hed:Jm([$t(0),$t(1)]).nullable().optional(),hed_version:S().nullable().optional(),store_count:j().int().nonnegative().nullable().optional(),recording_count:j().int().nonnegative().nullable().optional(),recordings_unavailable:j().int().nonnegative().nullable().optional(),total_recording_duration:j().nullable().optional(),zarr_converted_at:S().nullable().optional(),zarr_source_commit:S().nullable().optional(),zarr_errors:j().int().nonnegative().nullable().optional(),zarr_verify_status:Ft(["verified","failed","unverifiable"]).nullable().optional(),zarr_verified_at:S().nullable().optional(),index_url:S().nullable().optional()}).passthrough(),MBt=ee({format:$t("nemar-zarr-catalog"),format_version:j().int(),generated_utc:S(),contract_base:S(),count:j().int().nonnegative(),datasets:he(uWe)}).passthrough(),dWe=["verified","failed","unverifiable"],fZ=Ft(dWe).nullable(),z0=ee({dataset_id:S().regex(So),doi:S().nullable(),license:S().nullable(),citation:S().nullable(),source_commit:S().regex(ok),index_etag:S().nullable(),engine_version:S(),source_tree:$t("raw"),derived:Ke(),sss:ik.optional(),lossy:Ke(),dtype:S().nullable(),effective_rate_hz:j().nullable(),source_rate_hz:j().nullable(),units_report:sk.nullable().optional(),zarr_verify_status:fZ,note:S().nullable().optional()}).passthrough().superRefine(ak),cZ=ee({start:j().int().nonnegative(),end:j().int().nonnegative()}).passthrough().refine((e)=>e.end>=e.start,{message:"end must be >= start",path:["end"]}),fWe=ee({python_zarr:S(),zarrita:S(),python_browser:S()}).passthrough(),pZ=ee({contract_base:S(),data_base:S(),s3_uri:S(),s3_region:S(),s3_anonymous:Ke(),zarr:S(),group:S(),level:Jm([$t("0"),j().int().positive()]),array_path:S(),dtype:S().nullable(),codecs:he(_u()).optional(),chunk_samples:j().int().positive().nullable(),shard_samples:j().int().positive().nullable(),n_channels:j().int().nonnegative().nullable(),sample_slice:cZ.optional(),channel_slice:cZ.optional(),scale_offset:S(),how_to:fWe}).passthrough(),hWe=Object.fromEntries(_a.map((e)=>[e.queryParam,S().optional()])),mZ={modality:S().optional(),task:S().optional(),has_hed:Ke().optional(),has_zarr:Ke().optional(),author:S().optional(),has_doi:Ke().optional(),has_zarr_verified:Ke().optional(),data_complete:Ke().optional(),recent:j().int().positive().optional(),license:S().optional()},gWe=Object.keys(mZ),jBt=[...gWe,..._a.map((e)=>e.queryParam)],LBt=ee({query:S().optional(),...mZ,include_unknown:Ke().optional(),...hWe,limit:j().int().positive().max(mWe).default(pWe)}).passthrough(),yWe=ee({dataset_id:S().regex(So),name:S(),doi:S().nullable().optional(),license:S().nullable().optional(),modalities:he(S()).optional(),tasks:he(S()).optional(),subject_count:j().int().nullable().optional(),has_hed:Ke().nullable().optional(),has_zarr:Ke()}).passthrough(),qBt=ee({results:he(yWe),count:j().int().nonnegative(),limit:j().int(),note:S().nullable().optional(),truncated:Ke().optional()}).passthrough(),BBt=ee({dataset_id:S().regex(So)}).passthrough(),bWe=["list_recordings","get_events","render_overview","read_window"],wWe=ee({next_cheapest_tool:Ft(bWe),reason:S()}).passthrough(),_We=["pending","ready","failed"],UBt=ee({dataset_id:S().regex(So),name:S(),doi:S().nullable(),license:S().nullable(),citation:S().nullable(),modalities:he(S()).optional(),tasks:he(S()).optional(),subject_count:j().int().nullable().optional(),has_hed:Ke().nullable().optional(),hed_version:S().nullable().optional(),recording_count:j().int().nullable().optional(),total_recording_duration_s:j().nullable().optional(),zarr_status:Ft(_We).nullable().optional(),zarr_verify_status:fZ.optional(),zarr_source_commit:S().nullable().optional(),zarr_store_count:j().int().nullable().optional(),cost_hint:wWe}).passthrough(),HBt=ee({dataset_id:S().regex(So),modality:S().optional(),min_duration_s:j().nonnegative().optional(),include_derived:Ke().default(!1),limit:j().int().positive().max(vWe).default(xWe),offset:j().int().nonnegative().default(0)}).passthrough(),kWe=ee({name:S(),modality:S().nullable().optional(),rate:j().nullable().optional(),n_channels:j().int().nullable().optional(),duration_s:j().nullable().optional(),n_view_levels:j().int().nonnegative().nullable().optional(),n_samples:j().int().nonnegative().nullable().optional(),view_chunk_columns:j().int().positive().nullable().optional()}).passthrough(),EWe=ee({path:S(),zarr:S(),source_tree:$t("raw"),derived:Ke(),groups:he(kWe).optional(),n_events:j().int().nonnegative().optional(),sss:ik.optional(),units_report:sk.optional()}).passthrough().superRefine(ak),zBt=ee({dataset_id:S().regex(So),source_commit:S().regex(ok).nullable(),recordings:he(EWe),total_count:j().int().nonnegative(),excluded_derived_count:j().int().nonnegative(),limit:j().int(),offset:j().int(),index_format_version:j().int(),discovered_count:j().int().nonnegative().nullable(),failure_count:j().int().nonnegative().nullable(),pending_count:j().int().nonnegative().nullable(),excluded_legacy_non_raw_count:j().int().nonnegative(),note:S().nullable().optional(),envelope:z0.optional()}).passthrough(),uZ=S().min(1).max(64),VBt=ee({dataset_id:S().regex(So),recording:S(),group:S().optional(),limit:j().int().positive().max($We).default(SWe),offset:j().int().nonnegative().default(0),where:Ks(uZ,he(Jm([S(),j()])).min(1).max(DWe)).refine((e)=>{let t=Object.keys(e).length;return t>=1&&t<=lZ},{message:`where names 1 to ${lZ} columns`}).optional(),columns:he(uZ).min(1).max(RWe).optional()}).passthrough(),CWe=ee({store_path:S(),group_name:S(),onset_s:j(),duration_s:j().nullable().optional(),sample_index:j().int().nonnegative(),trial_type:S().nullable().optional(),value:Jm([S(),j()]).nullable().optional(),hed:S().nullable().optional()}).passthrough(),AWe=CWe.partial().required({onset_s:!0,sample_index:!0}),OWe=ee({name:S(),distinct_count:j().int().nonnegative(),null_count:j().int().nonnegative(),values:he(ee({value:S(),count:j().int().positive()}).passthrough()).nullable()}).passthrough(),GBt=ee({dataset_id:S().regex(So),recording:S(),events:he(AWe),source:Ft(["events_parquet","events_tsv_fallback"]),estimated:Ke(),total_count:j().int().nonnegative(),limit:j().int(),offset:j().int(),truncated:Ke(),note:S().nullable().optional(),columns_summary:he(OWe).optional(),envelope:z0.optional()}).passthrough(),WBt=ee({dataset_id:S().regex(So),recording:S(),group:S().optional(),width_px:j().int().positive().max(PWe).default(TWe)}).passthrough(),KBt=ee({dataset_id:S().regex(So),recording:S(),group:S(),level:j().int().positive(),width_px:j().int().positive(),height_px:j().int().positive(),mime_type:$t("image/png"),columns_read:j().int().nonnegative(),chunks_read:j().int().nonnegative(),bytes_read:j().int().nonnegative(),envelope:z0.optional()}).passthrough(),dZ=$T*DT,JBt=ee({dataset_id:S().regex(So),recording:S(),group:S().optional(),start_s:j().nonnegative().default(0),duration_s:j().positive().max(IWe).default(10),channels:he(j().int().nonnegative()).max(NWe).optional(),taste:Ke().default(!1)}).passthrough().superRefine((e,t)=>{if(!e.taste)return;if(!e.channels||e.channels.length===0){t.addIssue({code:Z.custom,message:"taste requires channels: name the channel indices you want (list_recordings reports each group's n_channels), or omit taste for a recipe",path:["channels"]});return}if(e.duration_s>$T)t.addIssue({code:Z.custom,message:`taste duration_s (${e.duration_s}) exceeds the ${$T} s cap; omit taste for a recipe instead`,path:["duration_s"]});if(e.channels.length>DT)t.addIssue({code:Z.custom,message:`taste channels (${e.channels.length}) exceeds the ${DT}-channel cap; omit taste for a recipe instead`,path:["channels"]});let n=e.duration_s*e.channels.length;if(n>dZ)t.addIssue({code:Z.custom,message:`taste exceeds the cap of ${dZ} channel-seconds (duration_s x channels = ${n}); omit taste for a recipe instead`,path:["duration_s"]})}),FWe=ee({mode:$t("recipe"),recipe:pZ,envelope:z0}).passthrough(),MWe=ee({mode:$t("taste"),start_s:j(),duration_s:j(),channels:he(j().int()),sample_rate_hz:j(),values:he(he(j())),recipe:pZ,chunks_read:j().int().nonnegative(),bytes_read:j().int().nonnegative(),filled_ranges:he(ee({start_sample:j().int().nonnegative(),end_sample:j().int().nonnegative(),start_s:j(),end_s:j()}).passthrough()),note:S().nullable().optional(),envelope:z0}).passthrough(),YBt=aT("mode",[FWe,MWe])});var nh=V(()=>{gT();Ym();bT();U0();wT();ek();Zm();th();ST();hZ()});function Jo(e){return typeof e==="string"&&qWe.test(e)&&!e.includes("..")}function Qc(e){return/^v\d/.test(e)?e.slice(1):e}function Sr(e,t){return Qc(e)===Qc(t)}var qWe;var xa=V(()=>{qWe=/^[0-9A-Za-z][0-9A-Za-z._-]{0,63}$/});function G(e){if(e instanceof Error)return e.message;return String(e)}function uk(e){if(!(e instanceof L)||e.statusCode!==404)return!1;let t=e.rawBody;return typeof t==="object"&&t!==null&&t.error==="Not Found"&&typeof t.message==="string"}var L,vu;var Je=V(()=>{L=class L extends Error{statusCode;details;step;blockReason;missing;code;reason;rawBody;constructor(e,t,n,r,o,s){super(t);this.statusCode=e;this.details=n;this.step=r;this.blockReason=o;this.missing=s;this.name="ApiError"}};vu=class vu extends L{mode;eta;constructor(e,t,n,r){super(503,t,r);this.mode=e;this.eta=n;this.name="MaintenanceError"}}});var BWe,UWe,HWe,g5t,bZ="override_publication_review",wZ="publication_review_not_clear",AT=2000;var dk=V(()=>{BWe=["dispatched","redispatched","dispatch_claimed"],UWe=["review_disabled","not_applicable","not_owned_here","request_not_requested","screen_not_ready","running","has_result","platform_limit"],HWe=["dispatch_failed","dispatch_unconfigured"],g5t=[...BWe,...UWe,...HWe]});var fk=1e4;function pk(e){return e?VWe:va}var va,w5t,zWe,VWe,OT;var mk=V(()=>{va=["ci_check","enrichment_check","s3_public_read","repo_public","tag_protect","doi_create","update_metadata","update_readme","create_tag","create_release","upload_to_zenodo","publish_doi","version_doi","s3_lock","sync_nemar","notify_user"],w5t=va.slice(0,va.indexOf("s3_public_read")),zWe=["update_metadata","update_readme","upload_to_zenodo","publish_doi"],VWe=va.filter((e)=>!zWe.includes(e));OT={ci_check:"Check CI",enrichment_check:"Enrichment check",s3_public_read:"S3 public read",repo_public:"Make catalog row public",tag_protect:"Tag protection",doi_create:"Create DOI",update_metadata:"Update metadata",update_readme:"Update README",create_tag:"Create version tag",create_release:"Create GitHub release",upload_to_zenodo:"Upload to Zenodo (no-op)",publish_doi:"Publish DOI (irreversible)",version_doi:"Version DOI + manifest",s3_lock:"S3 Object Lock",sync_nemar:"Sync NEMAR (no-op)",notify_user:"Notify user"}});function GWe(e){return`%${e.replace(/[\\%_]/g,"\\$&")}%`}function WWe(e){return new TextEncoder().encode(GWe(e)).length}function _Z(e){if(WWe(e)<=50)return null;return["search is too long: its match pattern may be at most 50 bytes,","which is about 48 plain characters (each of _ % \\ counts twice and a non-ASCII","character counts by its UTF-8 length)"].join(" ")}function hk(e){return e.replace(/[A-Z]/g,(t)=>t.toLowerCase())}function xZ(e,t){if(e==="")return!0;let n=hk(e);return t.some((r)=>typeof r==="string"&&hk(r).includes(n))}function vZ(e,t){return hk(e)===hk(t)}function gk(e){let t=[],n="",r="start",o=!1;for(let s of e)switch(s){case"\\":{if(r==="index")throw Error("Invalid character in an index");if(r==="indexEnd")throw Error("Invalid character after an index");if(o)n+=s;r="property",o=!o;break}case".":{if(r==="index")throw Error("Invalid character in an index");if(r==="indexEnd"){r="property";break}if(o){o=!1,n+=s;break}if(TT.has(n))return[];t.push(n),n="",r="property";break}case"[":{if(r==="index")throw Error("Invalid character in an index");if(r==="indexEnd"){r="index";break}if(o){o=!1,n+=s;break}if(r==="property"){if(TT.has(n))return[];t.push(n),n=""}r="index";break}case"]":{if(r==="index"){t.push(Number.parseInt(n,10)),n="",r="indexEnd";break}if(r==="indexEnd")throw Error("Invalid character after an index")}default:{if(r==="index"&&!KWe.has(s))throw Error("Invalid character in an index");if(r==="indexEnd")throw Error("Invalid character after an index");if(r==="start")r="property";if(o)o=!1,n+="\\";n+=s}}if(o)n+="\\";switch(r){case"property":{if(TT.has(n))return[];t.push(n);break}case"index":throw Error("Index was not closed");case"start":{t.push("");break}}return t}function PT(e,t){if(typeof t!=="number"&&Array.isArray(e)){let n=Number.parseInt(t,10);return Number.isInteger(n)&&e[n]===e[t]}return!1}function kZ(e,t){if(PT(e,t))throw Error("Cannot use string index")}function EZ(e,t,n){if(!wf(e)||typeof t!=="string")return n===void 0?e:n;let r=gk(t);if(r.length===0)return n;for(let o=0;o<r.length;o++){let s=r[o];if(PT(e,s))e=o===r.length-1?void 0:null;else e=e[s];if(e===void 0||e===null){if(o!==r.length-1)return n;break}}return e===void 0?n:e}function IT(e,t,n){if(!wf(e)||typeof t!=="string")return e;let r=e,o=gk(t);for(let s=0;s<o.length;s++){let i=o[s];if(kZ(e,i),s===o.length-1)e[i]=n;else if(!wf(e[i]))e[i]=typeof o[s+1]==="number"?[]:{};e=e[i]}return r}function SZ(e,t){if(!wf(e)||typeof t!=="string")return!1;let n=gk(t);for(let r=0;r<n.length;r++){let o=n[r];if(kZ(e,o),r===n.length-1)return delete e[o],!0;if(e=e[o],!wf(e))return!1}}function $Z(e,t){if(!wf(e)||typeof t!=="string")return!1;let n=gk(t);if(n.length===0)return!1;for(let r of n){if(!wf(e)||!(r in e)||PT(e,r))return!1;e=e[r]}return!0}var wf=(e)=>{let t=typeof e;return e!==null&&(t==="object"||t==="function")},TT,KWe;var DZ=V(()=>{TT=new Set(["__proto__","prototype","constructor"]),KWe=new Set("0123456789")});import $n from"path";import RZ from"os";import NT from"process";function MT(e,{suffix:t="nodejs"}={}){if(typeof e!=="string")throw TypeError(`Expected a string, got ${typeof e}`);if(t)e+=`-${t}`;if(NT.platform==="darwin")return JWe(e);if(NT.platform==="win32")return YWe(e);return XWe(e)}var ku,FT,oh,JWe=(e)=>{let t=$n.join(ku,"Library");return{data:$n.join(t,"Application Support",e),config:$n.join(t,"Preferences",e),cache:$n.join(t,"Caches",e),log:$n.join(t,"Logs",e),temp:$n.join(FT,e)}},YWe=(e)=>{let t=oh.APPDATA||$n.join(ku,"AppData","Roaming"),n=oh.LOCALAPPDATA||$n.join(ku,"AppData","Local");return{data:$n.join(n,e,"Data"),config:$n.join(t,e,"Config"),cache:$n.join(n,e,"Cache"),log:$n.join(n,e,"Log"),temp:$n.join(FT,e)}},XWe=(e)=>{let t=$n.basename(ku);return{data:$n.join(oh.XDG_DATA_HOME||$n.join(ku,".local","share"),e),config:$n.join(oh.XDG_CONFIG_HOME||$n.join(ku,".config"),e),cache:$n.join(oh.XDG_CACHE_HOME||$n.join(ku,".cache"),e),log:$n.join(oh.XDG_STATE_HOME||$n.join(ku,".local","state"),e),temp:$n.join(FT,t,e)}};var CZ=V(()=>{ku=RZ.homedir(),FT=RZ.tmpdir(),{env:oh}=NT});var QWe=(e,t)=>{let{onError:n}=t;return function(...o){return e.apply(void 0,o).catch(n)}},ka;var AZ=V(()=>{ka=QWe});var ZWe=(e,t)=>{let{onError:n}=t;return function(...o){try{return e.apply(void 0,o)}catch(s){return n(s)}}},Oi;var OZ=V(()=>{Oi=ZWe});var TZ=250;var PZ=()=>{};var eKe=(e,t)=>{let{isRetriable:n}=t;return function(o){let{timeout:s}=o,i=o.interval??TZ,a=Date.now()+s;return function c(...l){return e.apply(void 0,l).catch((d)=>{if(!n(d))throw d;if(Date.now()>=a)throw d;let f=Math.round(i*Math.random());if(f>0)return new Promise((m)=>setTimeout(m,f)).then(()=>c.apply(void 0,l));else return c.apply(void 0,l)})}}},Ea;var IZ=V(()=>{PZ();Ea=eKe});var tKe=(e,t)=>{let{isRetriable:n}=t;return function(o){let{timeout:s}=o,i=Date.now()+s;return function(...c){while(!0)try{return e.apply(void 0,c)}catch(l){if(!n(l))throw l;if(Date.now()>=i)throw l;continue}}}},Sa;var NZ=V(()=>{Sa=tKe});var jT=V(()=>{AZ();OZ();IZ();NZ()});var V0,LT;var FZ=V(()=>{qT();V0={isChangeErrorOk:(e)=>{if(!V0.isNodeError(e))return!1;let{code:t}=e;if(t==="ENOSYS")return!0;if(!MZ&&(t==="EINVAL"||t==="EPERM"))return!0;return!1},isNodeError:(e)=>e instanceof Error,isRetriableError:(e)=>{if(!V0.isNodeError(e))return!1;let{code:t}=e;if(t==="EMFILE"||t==="ENFILE"||t==="EAGAIN"||t==="EBUSY"||t==="EACCESS"||t==="EACCES"||t==="EACCS"||t==="EPERM")return!0;return!1},onChangeError:(e)=>{if(!V0.isNodeError(e))throw e;if(V0.isChangeErrorOk(e))return;throw e}},LT=V0});import jZ from"process";var G0,Qo,MZ,Vr;var qT=V(()=>{FZ();G0={onError:LT.onChangeError},Qo={onError:()=>{return}},MZ=jZ.getuid?!jZ.getuid():!1,Vr={isRetriable:LT.isRetriableError}});import Ot from"fs";import{promisify as so}from"util";var nKe,$r;var BT=V(()=>{jT();jT();qT();nKe={attempt:{chmod:ka(so(Ot.chmod),G0),chown:ka(so(Ot.chown),G0),close:ka(so(Ot.close),Qo),fsync:ka(so(Ot.fsync),Qo),mkdir:ka(so(Ot.mkdir),Qo),realpath:ka(so(Ot.realpath),Qo),stat:ka(so(Ot.stat),Qo),unlink:ka(so(Ot.unlink),Qo),chmodSync:Oi(Ot.chmodSync,G0),chownSync:Oi(Ot.chownSync,G0),closeSync:Oi(Ot.closeSync,Qo),existsSync:Oi(Ot.existsSync,Qo),fsyncSync:Oi(Ot.fsync,Qo),mkdirSync:Oi(Ot.mkdirSync,Qo),realpathSync:Oi(Ot.realpathSync,Qo),statSync:Oi(Ot.statSync,Qo),unlinkSync:Oi(Ot.unlinkSync,Qo)},retry:{close:Ea(so(Ot.close),Vr),fsync:Ea(so(Ot.fsync),Vr),open:Ea(so(Ot.open),Vr),readFile:Ea(so(Ot.readFile),Vr),rename:Ea(so(Ot.rename),Vr),stat:Ea(so(Ot.stat),Vr),write:Ea(so(Ot.write),Vr),writeFile:Ea(so(Ot.writeFile),Vr),closeSync:Sa(Ot.closeSync,Vr),fsyncSync:Sa(Ot.fsyncSync,Vr),openSync:Sa(Ot.openSync,Vr),readFileSync:Sa(Ot.readFileSync,Vr),renameSync:Sa(Ot.renameSync,Vr),statSync:Sa(Ot.statSync,Vr),writeSync:Sa(Ot.writeSync,Vr),writeFileSync:Sa(Ot.writeFileSync,Vr)}},$r=nKe});import _f from"process";var LZ="utf8",UT=438,qZ=511,BZ,UZ,HZ,zZ=1000,VZ,Y5t,HT=128;var zT=V(()=>{BZ={},UZ=_f.geteuid?_f.geteuid():-1,HZ=_f.getegid?_f.getegid():-1,VZ=!!_f.getuid,Y5t=_f.getuid?!_f.getuid():!1});var GZ=(e)=>e instanceof Error&&("code"in e),VT=(e)=>typeof e==="string",yk=(e)=>e===void 0;var WZ=()=>{};var KZ=()=>{};import JZ from"process";var YZ,bk;var GT=V(()=>{YZ=JZ.platform==="linux",bk=JZ.platform==="win32"});var WT,XZ;var QZ=V(()=>{GT();WT=["SIGHUP","SIGINT","SIGTERM"];if(!bk)WT.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");if(YZ)WT.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");XZ=WT});import sh from"process";class ZZ{constructor(){this.callbacks=new Set,this.exited=!1,this.exit=(e)=>{if(this.exited)return;this.exited=!0;for(let t of this.callbacks)t();if(e)if(bk&&(e!=="SIGINT"&&e!=="SIGTERM"&&e!=="SIGKILL"))sh.kill(sh.pid,"SIGTERM");else sh.kill(sh.pid,e)},this.hook=()=>{sh.once("exit",()=>this.exit());for(let e of XZ)try{sh.once(e,()=>this.exit(e))}catch{}},this.register=(e)=>(this.callbacks.add(e),()=>{this.callbacks.delete(e)}),this.hook()}}var eee;var tee=V(()=>{GT();QZ();eee=new ZZ});var rKe,nee;var ree=V(()=>{tee();rKe=eee.register,nee=rKe});import oKe from"path";var vs,W0;var oee=V(()=>{BT();ree();zT();vs={store:{},create:(e)=>{let t=`000000${Math.floor(Math.random()*16777215).toString(16)}`.slice(-6),n=Date.now().toString().slice(-10),r="tmp-",o=`.tmp-${n}${t}`;return`${e}${o}`},get:(e,t,n=!0)=>{let r=vs.truncate(t(e));if(r in vs.store)return vs.get(e,t,n);return vs.store[r]=n,[r,()=>delete vs.store[r]]},purge:(e)=>{if(!vs.store[e])return;delete vs.store[e],$r.attempt.unlink(e)},purgeSync:(e)=>{if(!vs.store[e])return;delete vs.store[e],$r.attempt.unlinkSync(e)},purgeSyncAll:()=>{for(let e in vs.store)vs.purgeSync(e)},truncate:(e)=>{let t=oKe.basename(e);if(t.length<=HT)return e;let n=/^(\.?)(.*?)((?:\.[^.]+)?(?:\.tmp-\d{10}[a-f0-9]{6})?)$/.exec(t);if(!n)return e;let r=t.length-HT;return`${e.slice(0,-t.length)}${n[1]}${n[2].slice(0,-r)}${n[3]}`}};nee(vs.purgeSyncAll);W0=vs});import sKe from"path";function KT(e,t,n=BZ){if(VT(n))return KT(e,t,{encoding:n});let o={timeout:n.timeout??zZ},s=null,i=null,a=null;try{let c=$r.attempt.realpathSync(e),l=!!c;e=c||e,[i,s]=W0.get(e,n.tmpCreate||W0.create,n.tmpPurge!==!1);let d=VZ&&yk(n.chown),f=yk(n.mode);if(l&&(d||f)){let p=$r.attempt.statSync(e);if(p){if(n={...n},d)n.chown={uid:p.uid,gid:p.gid};if(f)n.mode=p.mode}}if(!l){let p=sKe.dirname(e);$r.attempt.mkdirSync(p,{mode:qZ,recursive:!0})}if(a=$r.retry.openSync(o)(i,"w",n.mode||UT),n.tmpCreated)n.tmpCreated(i);if(VT(t))$r.retry.writeSync(o)(a,t,0,n.encoding||LZ);else if(!yk(t))$r.retry.writeSync(o)(a,t,0,t.length,0);if(n.fsync!==!1)if(n.fsyncWait!==!1)$r.retry.fsyncSync(o)(a);else $r.attempt.fsync(a);if($r.retry.closeSync(o)(a),a=null,n.chown&&(n.chown.uid!==UZ||n.chown.gid!==HZ))$r.attempt.chownSync(i,n.chown.uid,n.chown.gid);if(n.mode&&n.mode!==UT)$r.attempt.chmodSync(i,n.mode);try{$r.retry.renameSync(o)(i,e)}catch(p){if(!GZ(p))throw p;if(p.code!=="ENAMETOOLONG")throw p;$r.retry.renameSync(o)(i,W0.truncate(e))}s(),i=null}finally{if(a)$r.attempt.closeSync(a);if(i)W0.purge(i)}}var see=V(()=>{BT();zT();WZ();KZ();oee()});var J0=w(function(cee){Object.defineProperty(cee,"__esModule",{value:!0});cee.regexpCode=cee.getEsmExportName=cee.getProperty=cee.safeStringify=cee.stringify=cee.strConcat=cee.addCodeArg=cee.str=cee._=cee.nil=cee._Code=cee.Name=cee.IDENTIFIER=cee._CodeOrName=void 0;class wk{}cee._CodeOrName=wk;cee.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class ih extends wk{constructor(e){super();if(!cee.IDENTIFIER.test(e))throw Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}cee.Name=ih;class Ti extends wk{constructor(e){super();this._items=typeof e==="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((t,n)=>`${t}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((t,n)=>{if(n instanceof ih)t[n.str]=(t[n.str]||0)+1;return t},{})}}cee._Code=Ti;cee.nil=new Ti("");function iee(e,...t){let n=[e[0]],r=0;while(r<t.length)YT(n,t[r]),n.push(e[++r]);return new Ti(n)}cee._=iee;var JT=new Ti("+");function aee(e,...t){let n=[K0(e[0])],r=0;while(r<t.length)n.push(JT),YT(n,t[r]),n.push(JT,K0(e[++r]));return iKe(n),new Ti(n)}cee.str=aee;function YT(e,t){if(t instanceof Ti)e.push(...t._items);else if(t instanceof ih)e.push(t);else e.push(lKe(t))}cee.addCodeArg=YT;function iKe(e){let t=1;while(t<e.length-1){if(e[t]===JT){let n=aKe(e[t-1],e[t+1]);if(n!==void 0){e.splice(t-1,3,n);continue}e[t++]="+"}t++}}function aKe(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string"){if(t instanceof ih||e[e.length-1]!=='"')return;if(typeof t!="string")return`${e.slice(0,-1)}${t}"`;if(t[0]==='"')return e.slice(0,-1)+t.slice(1);return}if(typeof t=="string"&&t[0]==='"'&&!(e instanceof ih))return`"${e}${t.slice(1)}`;return}function cKe(e,t){return t.emptyStr()?e:e.emptyStr()?t:aee`${e}${t}`}cee.strConcat=cKe;function lKe(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:K0(Array.isArray(e)?e.join(","):e)}function uKe(e){return new Ti(K0(e))}cee.stringify=uKe;function K0(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}cee.safeStringify=K0;function dKe(e){return typeof e=="string"&&cee.IDENTIFIER.test(e)?new Ti(`.${e}`):iee`[${e}]`}cee.getProperty=dKe;function fKe(e){if(typeof e=="string"&&cee.IDENTIFIER.test(e))return new Ti(`${e}`);throw Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}cee.getEsmExportName=fKe;function pKe(e){return new Ti(e.toString())}cee.regexpCode=pKe});var eP=w(function(fee){Object.defineProperty(fee,"__esModule",{value:!0});fee.ValueScope=fee.ValueScopeName=fee.Scope=fee.varKinds=fee.UsedValueState=void 0;var en=J0();class uee extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`);this.value=e.value}}var xk;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(xk||(fee.UsedValueState=xk={}));fee.varKinds={const:new en.Name("const"),let:new en.Name("let"),var:new en.Name("var")};class QT{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof en.Name?e:this.name(e)}name(e){return new en.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){var t,n;if(((n=(t=this._parent)===null||t===void 0?void 0:t._prefixes)===null||n===void 0?void 0:n.has(e))||this._prefixes&&!this._prefixes.has(e))throw Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}}fee.Scope=QT;class ZT extends en.Name{constructor(e,t){super(t);this.prefix=e}setValue(e,{property:t,itemIndex:n}){this.value=e,this.scopePath=en._`.${new en.Name(t)}[${n}]`}}fee.ValueScopeName=ZT;var $Ke=en._`\n`;class dee extends QT{constructor(e){super(e);this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?$Ke:en.nil}}get(){return this._scope}name(e){return new ZT(e,this._newName(e))}value(e,t){var n;if(t.ref===void 0)throw Error("CodeGen: ref must be passed in value");let r=this.toName(e),{prefix:o}=r,s=(n=t.key)!==null&&n!==void 0?n:t.ref,i=this._values[o];if(i){let l=i.get(s);if(l)return l}else i=this._values[o]=new Map;i.set(s,r);let a=this._scope[o]||(this._scope[o]=[]),c=a.length;return a[c]=t.ref,r.setValue(t,{property:o,itemIndex:c}),r}getValue(e,t){let n=this._values[e];if(!n)return;return n.get(t)}scopeRefs(e,t=this._values){return this._reduceValues(t,(n)=>{if(n.scopePath===void 0)throw Error(`CodeGen: name "${n}" has no value`);return en._`${e}${n.scopePath}`})}scopeCode(e=this._values,t,n){return this._reduceValues(e,(r)=>{if(r.value===void 0)throw Error(`CodeGen: name "${r}" has no value`);return r.value.code},t,n)}_reduceValues(e,t,n={},r){let o=en.nil;for(let s in e){let i=e[s];if(!i)continue;let a=n[s]=n[s]||new Map;i.forEach((c)=>{if(a.has(c))return;a.set(c,xk.Started);let l=t(c);if(l){let d=this.opts.es5?fee.varKinds.var:fee.varKinds.const;o=en._`${o}${d} ${c} = ${l};${this.opts._n}`}else if(l=r===null||r===void 0?void 0:r(c))o=en._`${o}${l}${this.opts._n}`;else throw new uee(c);a.set(c,xk.Completed)})}return o}}fee.ValueScope=dee});var ct=w(function(Zo){Object.defineProperty(Zo,"__esModule",{value:!0});Zo.or=Zo.and=Zo.not=Zo.CodeGen=Zo.operators=Zo.varKinds=Zo.ValueScopeName=Zo.ValueScope=Zo.Scope=Zo.Name=Zo.regexpCode=Zo.stringify=Zo.getProperty=Zo.nil=Zo.strConcat=Zo.str=Zo._=void 0;var pe=J0(),Fn=eP(),Eu=J0();Object.defineProperty(Zo,"_",{enumerable:!0,get:function(){return Eu._}});Object.defineProperty(Zo,"str",{enumerable:!0,get:function(){return Eu.str}});Object.defineProperty(Zo,"strConcat",{enumerable:!0,get:function(){return Eu.strConcat}});Object.defineProperty(Zo,"nil",{enumerable:!0,get:function(){return Eu.nil}});Object.defineProperty(Zo,"getProperty",{enumerable:!0,get:function(){return Eu.getProperty}});Object.defineProperty(Zo,"stringify",{enumerable:!0,get:function(){return Eu.stringify}});Object.defineProperty(Zo,"regexpCode",{enumerable:!0,get:function(){return Eu.regexpCode}});Object.defineProperty(Zo,"Name",{enumerable:!0,get:function(){return Eu.Name}});var Dk=eP();Object.defineProperty(Zo,"Scope",{enumerable:!0,get:function(){return Dk.Scope}});Object.defineProperty(Zo,"ValueScope",{enumerable:!0,get:function(){return Dk.ValueScope}});Object.defineProperty(Zo,"ValueScopeName",{enumerable:!0,get:function(){return Dk.ValueScopeName}});Object.defineProperty(Zo,"varKinds",{enumerable:!0,get:function(){return Dk.varKinds}});Zo.operators={GT:new pe._Code(">"),GTE:new pe._Code(">="),LT:new pe._Code("<"),LTE:new pe._Code("<="),EQ:new pe._Code("==="),NEQ:new pe._Code("!=="),NOT:new pe._Code("!"),OR:new pe._Code("||"),AND:new pe._Code("&&"),ADD:new pe._Code("+")};class Su{optimizeNodes(){return this}optimizeNames(e,t){return this}}class mee extends Su{constructor(e,t,n){super();this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let n=e?Fn.varKinds.var:this.varKind,r=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${r};`+t}optimizeNames(e,t){if(!e[this.name.str])return;if(this.rhs)this.rhs=ch(this.rhs,e,t);return this}get names(){return this.rhs instanceof pe._CodeOrName?this.rhs.names:{}}}class rP extends Su{constructor(e,t,n){super();this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,t){if(this.lhs instanceof pe.Name&&!e[this.lhs.str]&&!this.sideEffects)return;return this.rhs=ch(this.rhs,e,t),this}get names(){let e=this.lhs instanceof pe.Name?{}:{...this.lhs.names};return $k(e,this.rhs)}}class hee extends rP{constructor(e,t,n,r){super(e,n,r);this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}}class gee extends Su{constructor(e){super();this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}}class yee extends Su{constructor(e){super();this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}}class bee extends Su{constructor(e){super();this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}}class wee extends Su{constructor(e){super();this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=ch(this.code,e,t),this}get names(){return this.code instanceof pe._CodeOrName?this.code.names:{}}}class Rk extends Su{constructor(e=[]){super();this.nodes=e}render(e){return this.nodes.reduce((t,n)=>t+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,t=e.length;while(t--){let n=e[t].optimizeNodes();if(Array.isArray(n))e.splice(t,1,...n);else if(n)e[t]=n;else e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:n}=this,r=n.length;while(r--){let o=n[r];if(o.optimizeNames(e,t))continue;AKe(e,o.names),n.splice(r,1)}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>xf(e,t.names),{})}}class $u extends Rk{render(e){return"{"+e._n+super.render(e)+"}"+e._n}}class _ee extends Rk{}class Y0 extends $u{}Y0.kind="else";class Zc extends $u{constructor(e,t){super(t);this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);if(this.else)t+="else "+this.else.render(e);return t}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let t=this.else;if(t){let n=t.optimizeNodes();t=this.else=Array.isArray(n)?new Y0(n):n}if(t){if(e===!1)return t instanceof Zc?t:t.nodes;if(this.nodes.length)return this;return new Zc(See(e),t instanceof Zc?[t]:t.nodes)}if(e===!1||!this.nodes.length)return;return this}optimizeNames(e,t){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,t),!(super.optimizeNames(e,t)||this.else))return;return this.condition=ch(this.condition,e,t),this}get names(){let e=super.names;if($k(e,this.condition),this.else)xf(e,this.else.names);return e}}Zc.kind="if";class ah extends $u{}ah.kind="for";class xee extends ah{constructor(e){super();this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(!super.optimizeNames(e,t))return;return this.iteration=ch(this.iteration,e,t),this}get names(){return xf(super.names,this.iteration.names)}}class vee extends ah{constructor(e,t,n,r){super();this.varKind=e,this.name=t,this.from=n,this.to=r}render(e){let t=e.es5?Fn.varKinds.var:this.varKind,{name:n,from:r,to:o}=this;return`for(${t} ${n}=${r}; ${n}<${o}; ${n}++)`+super.render(e)}get names(){let e=$k(super.names,this.from);return $k(e,this.to)}}class tP extends ah{constructor(e,t,n,r){super();this.loop=e,this.varKind=t,this.name=n,this.iterable=r}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(!super.optimizeNames(e,t))return;return this.iterable=ch(this.iterable,e,t),this}get names(){return xf(super.names,this.iterable.names)}}class vk extends $u{constructor(e,t,n){super();this.name=e,this.args=t,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}}vk.kind="func";class kk extends Rk{render(e){return"return "+super.render(e)}}kk.kind="return";class kee extends $u{render(e){let t="try"+super.render(e);if(this.catch)t+=this.catch.render(e);if(this.finally)t+=this.finally.render(e);return t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(t=this.finally)===null||t===void 0||t.optimizeNodes(),this}optimizeNames(e,t){var n,r;return super.optimizeNames(e,t),(n=this.catch)===null||n===void 0||n.optimizeNames(e,t),(r=this.finally)===null||r===void 0||r.optimizeNames(e,t),this}get names(){let e=super.names;if(this.catch)xf(e,this.catch.names);if(this.finally)xf(e,this.finally.names);return e}}class Ek extends $u{constructor(e){super();this.error=e}render(e){return`catch(${this.error})`+super.render(e)}}Ek.kind="catch";class Sk extends $u{render(e){return"finally"+super.render(e)}}Sk.kind="finally";class Eee{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
|
|
85
85
|
`:""},this._extScope=e,this._scope=new Fn.Scope({parent:e}),this._nodes=[new _ee]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let n=this._extScope.value(e,t);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,n,r){let o=this._scope.toName(t);if(n!==void 0&&r)this._constants[o.str]=n;return this._leafNode(new mee(e,o,n)),o}const(e,t,n){return this._def(Fn.varKinds.const,e,t,n)}let(e,t,n){return this._def(Fn.varKinds.let,e,t,n)}var(e,t,n){return this._def(Fn.varKinds.var,e,t,n)}assign(e,t,n){return this._leafNode(new rP(e,t,n))}add(e,t){return this._leafNode(new hee(e,Zo.operators.ADD,t))}code(e){if(typeof e=="function")e();else if(e!==pe.nil)this._leafNode(new wee(e));return this}object(...e){let t=["{"];for(let[n,r]of e){if(t.length>1)t.push(",");if(t.push(n),n!==r||this.opts.es5)t.push(":"),pe.addCodeArg(t,r)}return t.push("}"),new pe._Code(t)}if(e,t,n){if(this._blockNode(new Zc(e)),t&&n)this.code(t).else().code(n).endIf();else if(t)this.code(t).endIf();else if(n)throw Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Zc(e))}else(){return this._elseNode(new Y0)}endIf(){return this._endBlockNode(Zc,Y0)}_for(e,t){if(this._blockNode(e),t)this.code(t).endFor();return this}for(e,t){return this._for(new xee(e),t)}forRange(e,t,n,r,o=this.opts.es5?Fn.varKinds.var:Fn.varKinds.let){let s=this._scope.toName(e);return this._for(new vee(o,s,t,n),()=>r(s))}forOf(e,t,n,r=Fn.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let s=t instanceof pe.Name?t:this.var("_arr",t);return this.forRange("_i",0,pe._`${s}.length`,(i)=>{this.var(o,pe._`${s}[${i}]`),n(o)})}return this._for(new tP("of",r,o,t),()=>n(o))}forIn(e,t,n,r=this.opts.es5?Fn.varKinds.var:Fn.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,pe._`Object.keys(${t})`,n);let o=this._scope.toName(e);return this._for(new tP("in",r,o,t),()=>n(o))}endFor(){return this._endBlockNode(ah)}label(e){return this._leafNode(new gee(e))}break(e){return this._leafNode(new yee(e))}return(e){let t=new kk;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(kk)}try(e,t,n){if(!t&&!n)throw Error('CodeGen: "try" without "catch" and "finally"');let r=new kee;if(this._blockNode(r),this.code(e),t){let o=this.name("e");this._currNode=r.catch=new Ek(o),t(o)}if(n)this._currNode=r.finally=new Sk,this.code(n);return this._endBlockNode(Ek,Sk)}throw(e){return this._leafNode(new bee(e))}block(e,t){if(this._blockStarts.push(this._nodes.length),e)this.code(e).endBlock(t);return this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw Error("CodeGen: not in self-balancing block");let n=this._nodes.length-t;if(n<0||e!==void 0&&n!==e)throw Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=t,this}func(e,t=pe.nil,n,r){if(this._blockNode(new vk(e,t,n)),r)this.code(r).endFunc();return this}endFunc(){return this._endBlockNode(vk)}optimize(e=1){while(e-- >0)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){let n=this._currNode;if(n instanceof e||t&&n instanceof t)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof Zc))throw Error('CodeGen: "else" without "if"');return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}}Zo.CodeGen=Eee;function xf(e,t){for(let n in t)e[n]=(e[n]||0)+(t[n]||0);return e}function $k(e,t){return t instanceof pe._CodeOrName?xf(e,t.names):e}function ch(e,t,n){if(e instanceof pe.Name)return r(e);if(!o(e))return e;return new pe._Code(e._items.reduce((s,i)=>{if(i instanceof pe.Name)i=r(i);if(i instanceof pe._Code)s.push(...i._items);else s.push(i);return s},[]));function r(s){let i=n[s.str];if(i===void 0||t[s.str]!==1)return s;return delete t[s.str],i}function o(s){return s instanceof pe._Code&&s._items.some((i)=>i instanceof pe.Name&&t[i.str]===1&&n[i.str]!==void 0)}}function AKe(e,t){for(let n in t)e[n]=(e[n]||0)-(t[n]||0)}function See(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:pe._`!${nP(e)}`}Zo.not=See;var OKe=$ee(Zo.operators.AND);function TKe(...e){return e.reduce(OKe)}Zo.and=TKe;var PKe=$ee(Zo.operators.OR);function IKe(...e){return e.reduce(PKe)}Zo.or=IKe;function $ee(e){return(t,n)=>t===pe.nil?n:n===pe.nil?t:pe._`${nP(t)} ${e} ${nP(n)}`}function nP(e){return e instanceof pe.Name?e:pe._`(${e})`}});var xt=w(function(Fee){Object.defineProperty(Fee,"__esModule",{value:!0});Fee.checkStrictMode=Fee.getErrorPath=Fee.Type=Fee.useFunc=Fee.setEvaluated=Fee.evaluatedPropsToName=Fee.mergeEvaluated=Fee.eachItem=Fee.unescapeJsonPointer=Fee.escapeJsonPointer=Fee.escapeFragment=Fee.unescapeFragment=Fee.schemaRefOrVal=Fee.schemaHasRulesButRef=Fee.schemaHasRules=Fee.checkUnknownRules=Fee.alwaysValidSchema=Fee.toHash=void 0;var Te=ct(),Aee=J0();function jKe(e){let t={};for(let n of e)t[n]=!0;return t}Fee.toHash=jKe;function LKe(e,t){if(typeof t=="boolean")return t;if(Object.keys(t).length===0)return!0;return Oee(e,t),!Tee(t,e.self.RULES.all)}Fee.alwaysValidSchema=LKe;function Oee(e,t=e.schema){let{opts:n,self:r}=e;if(!n.strictSchema)return;if(typeof t==="boolean")return;let o=r.RULES.keywords;for(let s in t)if(!o[s])Nee(e,`unknown keyword: "${s}"`)}Fee.checkUnknownRules=Oee;function Tee(e,t){if(typeof e=="boolean")return!e;for(let n in e)if(t[n])return!0;return!1}Fee.schemaHasRules=Tee;function qKe(e,t){if(typeof e=="boolean")return!e;for(let n in e)if(n!=="$ref"&&t.all[n])return!0;return!1}Fee.schemaHasRulesButRef=qKe;function BKe({topSchemaRef:e,schemaPath:t},n,r,o){if(!o){if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="string")return Te._`${n}`}return Te._`${e}${t}${Te.getProperty(r)}`}Fee.schemaRefOrVal=BKe;function UKe(e){return Pee(decodeURIComponent(e))}Fee.unescapeFragment=UKe;function HKe(e){return encodeURIComponent(sP(e))}Fee.escapeFragment=HKe;function sP(e){if(typeof e=="number")return`${e}`;return e.replace(/~/g,"~0").replace(/\//g,"~1")}Fee.escapeJsonPointer=sP;function Pee(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}Fee.unescapeJsonPointer=Pee;function zKe(e,t){if(Array.isArray(e))for(let n of e)t(n);else t(e)}Fee.eachItem=zKe;function Ree({mergeNames:e,mergeToName:t,mergeValues:n,resultToName:r}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof Te.Name?(s instanceof Te.Name?e(o,s,i):t(o,s,i),i):s instanceof Te.Name?(t(o,i,s),s):n(s,i);return a===Te.Name&&!(c instanceof Te.Name)?r(o,c):c}}Fee.mergeEvaluated={props:Ree({mergeNames:(e,t,n)=>e.if(Te._`${n} !== true && ${t} !== undefined`,()=>{e.if(Te._`${t} === true`,()=>e.assign(n,!0),()=>e.assign(n,Te._`${n} || {}`).code(Te._`Object.assign(${n}, ${t})`))}),mergeToName:(e,t,n)=>e.if(Te._`${n} !== true`,()=>{if(t===!0)e.assign(n,!0);else e.assign(n,Te._`${n} || {}`),iP(e,n,t)}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:Iee}),items:Ree({mergeNames:(e,t,n)=>e.if(Te._`${n} !== true && ${t} !== undefined`,()=>e.assign(n,Te._`${t} === true ? true : ${n} > ${t} ? ${n} : ${t}`)),mergeToName:(e,t,n)=>e.if(Te._`${n} !== true`,()=>e.assign(n,t===!0?!0:Te._`${n} > ${t} ? ${n} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function Iee(e,t){if(t===!0)return e.var("props",!0);let n=e.var("props",Te._`{}`);if(t!==void 0)iP(e,n,t);return n}Fee.evaluatedPropsToName=Iee;function iP(e,t,n){Object.keys(n).forEach((r)=>e.assign(Te._`${t}${Te.getProperty(r)}`,!0))}Fee.setEvaluated=iP;var Cee={};function VKe(e,t){return e.scopeValue("func",{ref:t,code:Cee[t.code]||(Cee[t.code]=new Aee._Code(t.code))})}Fee.useFunc=VKe;var oP;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(oP||(Fee.Type=oP={}));function GKe(e,t,n){if(e instanceof Te.Name){let r=t===oP.Num;return n?r?Te._`"[" + ${e} + "]"`:Te._`"['" + ${e} + "']"`:r?Te._`"/" + ${e}`:Te._`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?Te.getProperty(e).toString():"/"+sP(e)}Fee.getErrorPath=GKe;function Nee(e,t,n=e.opts.strictSchema){if(!n)return;if(t=`strict mode: ${t}`,n===!0)throw Error(t);e.self.logger.warn(t)}Fee.checkStrictMode=Nee});var Js=w(function(jee){Object.defineProperty(jee,"__esModule",{value:!0});var Mt=ct(),uJe={data:new Mt.Name("data"),valCxt:new Mt.Name("valCxt"),instancePath:new Mt.Name("instancePath"),parentData:new Mt.Name("parentData"),parentDataProperty:new Mt.Name("parentDataProperty"),rootData:new Mt.Name("rootData"),dynamicAnchors:new Mt.Name("dynamicAnchors"),vErrors:new Mt.Name("vErrors"),errors:new Mt.Name("errors"),this:new Mt.Name("this"),self:new Mt.Name("self"),scope:new Mt.Name("scope"),json:new Mt.Name("json"),jsonPos:new Mt.Name("jsonPos"),jsonLen:new Mt.Name("jsonLen"),jsonPart:new Mt.Name("jsonPart")};jee.default=uJe});var X0=w(function(Uee){Object.defineProperty(Uee,"__esModule",{value:!0});Uee.extendErrors=Uee.resetErrorsCount=Uee.reportExtraError=Uee.reportError=Uee.keyword$DataError=Uee.keywordError=void 0;var ge=ct(),Du=xt(),$o=Js();Uee.keywordError={message:({keyword:e})=>ge.str`must pass "${e}" keyword validation`};Uee.keyword$DataError={message:({keyword:e,schemaType:t})=>t?ge.str`"${e}" keyword must be ${t} ($data)`:ge.str`"${e}" keyword is invalid ($data)`};function fJe(e,t=Uee.keywordError,n,r){let{it:o}=e,{gen:s,compositeRule:i,allErrors:a}=o,c=Bee(e,t,n);if(r!==null&&r!==void 0?r:i||a)Lee(s,c);else qee(o,ge._`[${c}]`)}Uee.reportError=fJe;function pJe(e,t=Uee.keywordError,n){let{it:r}=e,{gen:o,compositeRule:s,allErrors:i}=r,a=Bee(e,t,n);if(Lee(o,a),!(s||i))qee(r,$o.default.vErrors)}Uee.reportExtraError=pJe;function mJe(e,t){e.assign($o.default.errors,t),e.if(ge._`${$o.default.vErrors} !== null`,()=>e.if(t,()=>e.assign(ge._`${$o.default.vErrors}.length`,t),()=>e.assign($o.default.vErrors,null)))}Uee.resetErrorsCount=mJe;function hJe({gen:e,keyword:t,schemaValue:n,data:r,errsCount:o,it:s}){if(o===void 0)throw Error("ajv implementation error");let i=e.name("err");e.forRange("i",o,$o.default.errors,(a)=>{if(e.const(i,ge._`${$o.default.vErrors}[${a}]`),e.if(ge._`${i}.instancePath === undefined`,()=>e.assign(ge._`${i}.instancePath`,ge.strConcat($o.default.instancePath,s.errorPath))),e.assign(ge._`${i}.schemaPath`,ge.str`${s.errSchemaPath}/${t}`),s.opts.verbose)e.assign(ge._`${i}.schema`,n),e.assign(ge._`${i}.data`,r)})}Uee.extendErrors=hJe;function Lee(e,t){let n=e.const("err",t);e.if(ge._`${$o.default.vErrors} === null`,()=>e.assign($o.default.vErrors,ge._`[${n}]`),ge._`${$o.default.vErrors}.push(${n})`),e.code(ge._`${$o.default.errors}++`)}function qee(e,t){let{gen:n,validateName:r,schemaEnv:o}=e;if(o.$async)n.throw(ge._`new ${e.ValidationError}(${t})`);else n.assign(ge._`${r}.errors`,t),n.return(!1)}var vf={keyword:new ge.Name("keyword"),schemaPath:new ge.Name("schemaPath"),params:new ge.Name("params"),propertyName:new ge.Name("propertyName"),message:new ge.Name("message"),schema:new ge.Name("schema"),parentSchema:new ge.Name("parentSchema")};function Bee(e,t,n){let{createErrors:r}=e.it;if(r===!1)return ge._`{}`;return gJe(e,t,n)}function gJe(e,t,n={}){let{gen:r,it:o}=e,s=[yJe(o,n),bJe(e,n)];return wJe(e,t,s),r.object(...s)}function yJe({errorPath:e},{instancePath:t}){let n=t?ge.str`${e}${Du.getErrorPath(t,Du.Type.Str)}`:e;return[$o.default.instancePath,ge.strConcat($o.default.instancePath,n)]}function bJe({keyword:e,it:{errSchemaPath:t}},{schemaPath:n,parentSchema:r}){let o=r?t:ge.str`${t}/${e}`;if(n)o=ge.str`${o}${Du.getErrorPath(n,Du.Type.Str)}`;return[vf.schemaPath,o]}function wJe(e,{params:t,message:n},r){let{keyword:o,data:s,schemaValue:i,it:a}=e,{opts:c,propertyName:l,topSchemaRef:d,schemaPath:f}=a;if(r.push([vf.keyword,o],[vf.params,typeof t=="function"?t(e):t||ge._`{}`]),c.messages)r.push([vf.message,typeof n=="function"?n(e):n]);if(c.verbose)r.push([vf.schema,i],[vf.parentSchema,ge._`${d}${f}`],[$o.default.data,s]);if(l)r.push([vf.propertyName,l])}});var Jee=w(function(Wee){Object.defineProperty(Wee,"__esModule",{value:!0});Wee.boolOrEmptySchema=Wee.topBoolOrEmptySchema=void 0;var zee=X0(),Vee=ct(),EJe=Js(),SJe={message:"boolean schema is false"};function $Je(e){let{gen:t,schema:n,validateName:r}=e;if(n===!1)Gee(e,!1);else if(typeof n=="object"&&n.$async===!0)t.return(EJe.default.data);else t.assign(Vee._`${r}.errors`,null),t.return(!0)}Wee.topBoolOrEmptySchema=$Je;function DJe(e,t){let{gen:n,schema:r}=e;if(r===!1)n.var(t,!1),Gee(e);else n.var(t,!0)}Wee.boolOrEmptySchema=DJe;function Gee(e,t){let{gen:n,data:r}=e;zee.reportError({gen:n,keyword:"false schema",data:r,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e},SJe,void 0,t)}});var cP=w(function(Yee){Object.defineProperty(Yee,"__esModule",{value:!0});Yee.getRules=Yee.isJSONType=void 0;var CJe=["string","number","integer","boolean","null","object","array"],AJe=new Set(CJe);function OJe(e){return typeof e=="string"&&AJe.has(e)}Yee.isJSONType=OJe;function TJe(){let e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}Yee.getRules=TJe});var lP=w(function(ete){Object.defineProperty(ete,"__esModule",{value:!0});ete.shouldUseRule=ete.shouldUseGroup=ete.schemaHasRulesForType=void 0;function IJe({schema:e,self:t},n){let r=t.RULES.types[n];return r&&r!==!0&&Qee(e,r)}ete.schemaHasRulesForType=IJe;function Qee(e,t){return t.rules.some((n)=>Zee(e,n))}ete.shouldUseGroup=Qee;function Zee(e,t){var n;return e[t.keyword]!==void 0||((n=t.definition.implements)===null||n===void 0?void 0:n.some((r)=>e[r]!==void 0))}ete.shouldUseRule=Zee});var Q0=w(function(ate){Object.defineProperty(ate,"__esModule",{value:!0});ate.reportTypeError=ate.checkDataTypes=ate.checkDataType=ate.coerceAndCheckDataType=ate.getJSONTypes=ate.getSchemaTypes=ate.DataType=void 0;var nte=cP(),rte=lP(),ote=X0(),se=ct(),Ak=xt(),lh;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(lh||(ate.DataType=lh={}));function MJe(e){let t=ste(e.type);if(t.includes("null")){if(e.nullable===!1)throw Error("type: null contradicts nullable: false")}else{if(!t.length&&e.nullable!==void 0)throw Error('"nullable" cannot be used without "type"');if(e.nullable===!0)t.push("null")}return t}ate.getSchemaTypes=MJe;function ste(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(nte.isJSONType))return t;throw Error("type must be JSONType or JSONType[]: "+t.join(","))}ate.getJSONTypes=ste;function jJe(e,t){let{gen:n,data:r,opts:o}=e,s=LJe(t,o.coerceTypes),i=t.length>0&&!(s.length===0&&t.length===1&&rte.schemaHasRulesForType(e,t[0]));if(i){let a=dP(t,r,o.strictNumbers,lh.Wrong);n.if(a,()=>{if(s.length)qJe(e,t,s);else fP(e)})}return i}ate.coerceAndCheckDataType=jJe;var ite=new Set(["string","number","integer","boolean","null"]);function LJe(e,t){return t?e.filter((n)=>ite.has(n)||t==="array"&&n==="array"):[]}function qJe(e,t,n){let{gen:r,data:o,opts:s}=e,i=r.let("dataType",se._`typeof ${o}`),a=r.let("coerced",se._`undefined`);if(s.coerceTypes==="array")r.if(se._`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>r.assign(o,se._`${o}[0]`).assign(i,se._`typeof ${o}`).if(dP(t,o,s.strictNumbers),()=>r.assign(a,o)));r.if(se._`${a} !== undefined`);for(let l of n)if(ite.has(l)||l==="array"&&s.coerceTypes==="array")c(l);r.else(),fP(e),r.endIf(),r.if(se._`${a} !== undefined`,()=>{r.assign(o,a),BJe(e,a)});function c(l){switch(l){case"string":r.elseIf(se._`${i} == "number" || ${i} == "boolean"`).assign(a,se._`"" + ${o}`).elseIf(se._`${o} === null`).assign(a,se._`""`);return;case"number":r.elseIf(se._`${i} == "boolean" || ${o} === null
|
|
86
86
|
|| (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,se._`+${o}`);return;case"integer":r.elseIf(se._`${i} === "boolean" || ${o} === null
|
|
87
87
|
|| (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,se._`+${o}`);return;case"boolean":r.elseIf(se._`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf(se._`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":r.elseIf(se._`${o} === "" || ${o} === 0 || ${o} === false`),r.assign(a,null);return;case"array":r.elseIf(se._`${i} === "string" || ${i} === "number"
|
|
@@ -99,18 +99,18 @@ ${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-
|
|
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.a8dac72",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
|
`)}
|
|
106
|
-
`}function Kft(e,t){let n;try{n=Cft(e).filter((o)=>o.startsWith("nemar-")&&o.endsWith(".log"))}catch(o){if(o.code!=="ENOENT")Dn(`could not list ${e} for log rotation: ${G(o)}`);return}n.sort();let r=n.length-t;for(let o=0;o<r;o++)try{Aft(MI(e,n[o]))}catch(s){if(s.code!=="ENOENT")Dn(`could not remove old log ${n[o]}: ${G(s)}`)}}function Efe(){return Cb}function Sfe(e,t){if(!Yh)return null;let n=MI(Vn(),"logs");try{Rft(n,{recursive:!0})}catch(i){return Cb=G(i),Dn(`could not create log directory ${n}: ${Cb}`),null}let o=`nemar-${new Date().toISOString().replace(/[:.]/g,"-")}-${Gft(e)}.log`,s=MI(n,o);try{Oft(s,Wft(e,t),"utf8")}catch(i){return Cb=G(i),Dn(`could not write log file ${s}: ${Cb}`),null}return Kft(n,Tft),s}var Tft=10,Pft=2048,Yh=!1,pfe=!1,LI=!1,mfe=!1,hfe,hS,gS,Ift,Fft,_fe,Mft=32,jft,Lft,qft,Bft,ffe,Cb;var dn=V(()=>{
|
|
106
|
+
`}function Kft(e,t){let n;try{n=Cft(e).filter((o)=>o.startsWith("nemar-")&&o.endsWith(".log"))}catch(o){if(o.code!=="ENOENT")Dn(`could not list ${e} for log rotation: ${G(o)}`);return}n.sort();let r=n.length-t;for(let o=0;o<r;o++)try{Aft(MI(e,n[o]))}catch(s){if(s.code!=="ENOENT")Dn(`could not remove old log ${n[o]}: ${G(s)}`)}}function Efe(){return Cb}function Sfe(e,t){if(!Yh)return null;let n=MI(Vn(),"logs");try{Rft(n,{recursive:!0})}catch(i){return Cb=G(i),Dn(`could not create log directory ${n}: ${Cb}`),null}let o=`nemar-${new Date().toISOString().replace(/[:.]/g,"-")}-${Gft(e)}.log`,s=MI(n,o);try{Oft(s,Wft(e,t),"utf8")}catch(i){return Cb=G(i),Dn(`could not write log file ${s}: ${Cb}`),null}return Kft(n,Tft),s}var Tft=10,Pft=2048,Yh=!1,pfe=!1,LI=!1,mfe=!1,hfe,hS,gS,Ift,Fft,_fe,Mft=32,jft,Lft,qft,Bft,ffe,Cb;var dn=V(()=>{Je();gr();Rb();If();gS=[];Ift=new Set(["authorization","cookie","set-cookie","x-api-key","x-approval-dispatch-token"]);Fft=/^(api[_-]?key|apikey|password|token|secret|access[_-]?key(_id)?|secret[_-]?access[_-]?key|session|session[_-]?token|authorization|ssh[_-]?key|private[_-]?key|device[_-]?code|dispatch[_-]?token)$/i,_fe=/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g;jft=/Bearer\s+[A-Za-z0-9\-._~+/=]+/gi,Lft=/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g,qft=/((?:aws_)?secret_access_key["']?\s*[:=]\s*["']?)[A-Za-z0-9/+=]{20,}/gi,Bft=/([?&])(X-Amz-Signature|X-Amz-Security-Token|X-Amz-Credential|Signature|AWSAccessKeyId)=[^&\s"']+/gi;ffe=new Set(["-k","--key","--password","--api-key"])});import{chmodSync as Jft,copyFileSync as Yft,existsSync as UI,mkdirSync as Xft,statSync as Qft}from"fs";import{homedir as bS}from"os";import{join as Xh}from"path";function ept(e){let t=e.trim().replace(/\/+$/,"");try{let n=new URL(t);return n.protocol=n.protocol.toLowerCase(),n.host=n.host.toLowerCase(),n.toString().replace(/\/+$/,"")}catch{return console.error(`[nemar] could not parse stored apiUrl ${JSON.stringify(e)}; leaving as-is`),t}}function Vn(){return process.env.NEMAR_CONFIG_DIR||Xh(bS(),".config","nemar")}function npt(e){if(process.env.NEMAR_CONFIG_DIR)return;let t=Xh(e,"config.json");if(UI(t))return;let n=[];if(process.platform==="darwin")n.push(Xh(bS(),"Library","Preferences","nemar-nodejs","config.json"));if(process.platform==="win32"){let r=process.env.APPDATA||Xh(bS(),"AppData","Roaming");n.push(Xh(r,"nemar-nodejs","config.json"))}n.push(Xh(bS(),".config","nemar-nodejs","config.json"));for(let r of n)if(UI(r))try{Xft(e,{recursive:!0}),Yft(r,t),console.error(`[nemar] Config migrated from ${r} to ${t}
|
|
107
107
|
[nemar] You can safely remove the old file.`);return}catch(o){console.error(`[nemar] Failed to migrate config from ${r}:`,o,`
|
|
108
|
-
[nemar] You can manually copy ${r} to ${t}`)}}function si(){let e=Vn();if(Tb&&$fe===e)return Tb;if(npt(e),Tb=new pS({projectName:"nemar",configFileMode:HI,schema:{activeAccount:{type:"string"},accounts:{type:"object"},apiKey:{type:"string"},apiUrl:{type:"string"},username:{type:"string"},email:{type:"string"},githubUsername:{type:"string"},sandboxCompleted:{type:"boolean"},sandboxDatasetId:{type:"string"}},cwd:e}),$fe=e,!Dfe.has(e))Dfe.add(e),rpt(Tb.path),spt(),ipt();return Tb}function rpt(e){if(process.platform==="win32")return;if(!UI(e))return;try{if((Qft(e).mode&511)!==HI)Jft(e,HI)}catch(t){console.error(`[nemar] could not secure config file permissions for ${e}:`,t)}}function spt(){let e=si(),t=e.get("accounts");if(t&&Object.keys(t).length>0)return;let n=e.get("apiKey"),r=e.get("username");if(!n&&!r)return;try{let o=r||"default",s={};for(let i of opt){let a=e.get(i);if(a!==void 0)s[i]=a}e.store={activeAccount:o,accounts:{[o]:s}}}catch(o){console.error("Config migration failed (legacy config preserved):",o)}}function ipt(){let e=si(),t=e.store,n=t.accounts,r=!1;if(n)for(let[s,i]of Object.entries(n)){let a=i?.apiUrl;if(!a)continue;if(Zft.has(ept(a)))n[s]={...i,apiUrl:Qh},console.error(`[nemar] migrated stored apiUrl for account "${s}": ${a} -> ${Qh}`),r=!0}let o=t.apiUrl;if(n&&Object.keys(n).length>0&&o!==void 0){let{apiUrl:s,...i}=t;try{e.store=i,console.error(`[nemar] removed stale top-level apiUrl from config (was: ${o})`),r=!1}catch(a){console.error("API URL cleanup failed (config file unchanged):",a)}}if(r)try{e.store={...e.store,accounts:n}}catch(s){console.error("API URL migration failed (config file unchanged):",s)}}function Pb(){return si().get("activeAccount")}function ld(){return si().get("accounts")||{}}function Vt(){let e={apiUrl:Qh},t=Pb();if(!t)return e;return ld()[t]||e}function Rn(e,t){let n=si(),r=n.get("activeAccount")||"default",o=n.get("accounts")||{};if(!o[r])o[r]={apiUrl:Qh};o[r][e]=t,n.store={...n.store,accounts:o,activeAccount:r}}function Ib(e){let t=Pb();if(!t)return;let n=ld();if(n[t])delete n[t][e],si().set("accounts",n)}function Rfe(){let e=si(),t=Pb();if(!t){e.clear();return}let n=ld();delete n[t];let r=Object.keys(n);if(r.length>0)e.store={...e.store,accounts:n,activeAccount:r[0]};else e.clear()}function Cfe(){si().clear()}function ze(){return!!Vt().apiKey}function zI(){return si().path}function Nb(){let e=ld(),t=Pb();return Object.entries(e).map(([n,r])=>({key:n,username:r.username,email:r.email,githubUsername:r.githubUsername,active:n===t,keySource:r.keySource}))}function Afe(e){return e.username?.trim()||e.email}function apt(e){let t=e.trim().toLowerCase();if(!t)return;let n=Object.entries(ld()).filter(([,r])=>r.email&&r.email.toLowerCase()===t).map(([r])=>r);if(n.length>1){Dn(`findAccountKeyByEmail: ${n.length} accounts share email ${t}: ${n.join(", ")}`);return}return n[0]}function Ofe(e,t){let n=si(),r=ld(),o;if(r[e])o=e;else if(t.email)o=apt(t.email);let s=o?r[o]:void 0,i={...s??{apiUrl:Qh},...t};if(o&&o!==e)delete r[o];return r[e]=i,n.store={...n.store,accounts:r,activeAccount:e},{key:e,previous:s}}function Tfe(e){let t=e.trim();if(!t)return"unchanged";let n=si(),r=Pb();if(!r||r===t)return"unchanged";let o=ld(),s=o[r];if(!s)return"unchanged";if(o[t])return"key_taken";return delete o[r],o[t]={...s,username:t},n.store={...n.store,accounts:o,activeAccount:t},"renamed"}function VI(e){let t=si(),n=ld();if(n[e])return t.store={...t.store,activeAccount:e},n[e];for(let[r,o]of Object.entries(n))if(o.githubUsername===e)return t.store={...t.store,activeAccount:r},o;return null}var Qh="https://api.nemar.org",HI=384,Zft,tpt,zVt,Tb=null,$fe=null,Dfe,opt;var gr=V(()=>{nfe();Ko();Ym();dn();Zft=new Set(["https://api.osc.earth/nemar","https://nemar-api.neuromechanist.workers.dev","https://nemar-api-dev.shirazi-10f.workers.dev"]);tpt=ee({field:S(),blocks:he(S()).optional(),set_on:he(S()).optional()}).passthrough(),zVt=ee({apiKey:S().optional(),apiUrl:S().url().default(Qh),username:S().optional(),email:S().email().optional(),githubUsername:S().optional(),sandboxCompleted:
|
|
108
|
+
[nemar] You can manually copy ${r} to ${t}`)}}function si(){let e=Vn();if(Tb&&$fe===e)return Tb;if(npt(e),Tb=new pS({projectName:"nemar",configFileMode:HI,schema:{activeAccount:{type:"string"},accounts:{type:"object"},apiKey:{type:"string"},apiUrl:{type:"string"},username:{type:"string"},email:{type:"string"},githubUsername:{type:"string"},sandboxCompleted:{type:"boolean"},sandboxDatasetId:{type:"string"}},cwd:e}),$fe=e,!Dfe.has(e))Dfe.add(e),rpt(Tb.path),spt(),ipt();return Tb}function rpt(e){if(process.platform==="win32")return;if(!UI(e))return;try{if((Qft(e).mode&511)!==HI)Jft(e,HI)}catch(t){console.error(`[nemar] could not secure config file permissions for ${e}:`,t)}}function spt(){let e=si(),t=e.get("accounts");if(t&&Object.keys(t).length>0)return;let n=e.get("apiKey"),r=e.get("username");if(!n&&!r)return;try{let o=r||"default",s={};for(let i of opt){let a=e.get(i);if(a!==void 0)s[i]=a}e.store={activeAccount:o,accounts:{[o]:s}}}catch(o){console.error("Config migration failed (legacy config preserved):",o)}}function ipt(){let e=si(),t=e.store,n=t.accounts,r=!1;if(n)for(let[s,i]of Object.entries(n)){let a=i?.apiUrl;if(!a)continue;if(Zft.has(ept(a)))n[s]={...i,apiUrl:Qh},console.error(`[nemar] migrated stored apiUrl for account "${s}": ${a} -> ${Qh}`),r=!0}let o=t.apiUrl;if(n&&Object.keys(n).length>0&&o!==void 0){let{apiUrl:s,...i}=t;try{e.store=i,console.error(`[nemar] removed stale top-level apiUrl from config (was: ${o})`),r=!1}catch(a){console.error("API URL cleanup failed (config file unchanged):",a)}}if(r)try{e.store={...e.store,accounts:n}}catch(s){console.error("API URL migration failed (config file unchanged):",s)}}function Pb(){return si().get("activeAccount")}function ld(){return si().get("accounts")||{}}function Vt(){let e={apiUrl:Qh},t=Pb();if(!t)return e;return ld()[t]||e}function Rn(e,t){let n=si(),r=n.get("activeAccount")||"default",o=n.get("accounts")||{};if(!o[r])o[r]={apiUrl:Qh};o[r][e]=t,n.store={...n.store,accounts:o,activeAccount:r}}function Ib(e){let t=Pb();if(!t)return;let n=ld();if(n[t])delete n[t][e],si().set("accounts",n)}function Rfe(){let e=si(),t=Pb();if(!t){e.clear();return}let n=ld();delete n[t];let r=Object.keys(n);if(r.length>0)e.store={...e.store,accounts:n,activeAccount:r[0]};else e.clear()}function Cfe(){si().clear()}function ze(){return!!Vt().apiKey}function zI(){return si().path}function Nb(){let e=ld(),t=Pb();return Object.entries(e).map(([n,r])=>({key:n,username:r.username,email:r.email,githubUsername:r.githubUsername,active:n===t,keySource:r.keySource}))}function Afe(e){return e.username?.trim()||e.email}function apt(e){let t=e.trim().toLowerCase();if(!t)return;let n=Object.entries(ld()).filter(([,r])=>r.email&&r.email.toLowerCase()===t).map(([r])=>r);if(n.length>1){Dn(`findAccountKeyByEmail: ${n.length} accounts share email ${t}: ${n.join(", ")}`);return}return n[0]}function Ofe(e,t){let n=si(),r=ld(),o;if(r[e])o=e;else if(t.email)o=apt(t.email);let s=o?r[o]:void 0,i={...s??{apiUrl:Qh},...t};if(o&&o!==e)delete r[o];return r[e]=i,n.store={...n.store,accounts:r,activeAccount:e},{key:e,previous:s}}function Tfe(e){let t=e.trim();if(!t)return"unchanged";let n=si(),r=Pb();if(!r||r===t)return"unchanged";let o=ld(),s=o[r];if(!s)return"unchanged";if(o[t])return"key_taken";return delete o[r],o[t]={...s,username:t},n.store={...n.store,accounts:o,activeAccount:t},"renamed"}function VI(e){let t=si(),n=ld();if(n[e])return t.store={...t.store,activeAccount:e},n[e];for(let[r,o]of Object.entries(n))if(o.githubUsername===e)return t.store={...t.store,activeAccount:r},o;return null}var Qh="https://api.nemar.org",HI=384,Zft,tpt,zVt,Tb=null,$fe=null,Dfe,opt;var gr=V(()=>{nfe();Ko();Ym();dn();Zft=new Set(["https://api.osc.earth/nemar","https://nemar-api.neuromechanist.workers.dev","https://nemar-api-dev.shirazi-10f.workers.dev"]);tpt=ee({field:S(),blocks:he(S()).optional(),set_on:he(S()).optional()}).passthrough(),zVt=ee({apiKey:S().optional(),apiUrl:S().url().default(Qh),username:S().optional(),email:S().email().optional(),githubUsername:S().optional(),sandboxCompleted:Ke().optional(),sandboxDatasetId:S().optional(),dismissedNoticeIds:he(j()).optional(),serviceAccess:Ke().optional(),profileGaps:he(tpt).optional(),orcidVerified:Ke().optional(),role:S().optional(),accountKind:bf.optional(),pendingEmailChange:S().email().optional()});Dfe=new Set;opt=["apiKey","apiUrl","username","email","githubUsername","sandboxCompleted","sandboxDatasetId","dismissedNoticeIds"]});function wS(e){if(Pfe)return;Pfe=!0;let t=u.yellow("\u2500".repeat(60)),n=u.yellow.bold("[MAINTENANCE]"),r=u.dim(`mode: ${e.mode}`),o=e.eta?`
|
|
109
109
|
${u.dim(`eta: ${e.eta}`)}`:"";process.stderr.write(`${t}
|
|
110
110
|
${n} ${e.message}
|
|
111
111
|
${r}${o}
|
|
112
112
|
${t}
|
|
113
|
-
`)}var Pfe=!1;var GI=V(()=>{He()});function Cr(){if(process.env.TEST_API_URL)return process.env.TEST_API_URL;if(Nf)return WI;return Vt().apiUrl||WI}async function q(e,t={},n=!1,r){let o=`${Cr()}${e}`,s={"Content-Type":"application/json","X-CLI-Version":ks,...t.headers};if(n){let p=Vt();if(!p.apiKey&&n===!0)throw new L(401,"Not authenticated. Run 'nemar auth login' first.");if(p.apiKey)s.Authorization=`Bearer ${p.apiKey}`}let i=t.method||"GET",a=typeof t.body==="string"?t.body:void 0,c=Date.now(),l;try{l=await fetch(o,{...t,headers:s})}catch(p){if(sl())yS({method:i,url:o,status:null,durationMs:Date.now()-c,requestHeaders:s,requestBody:a,error:p instanceof Error?p.message:String(p)});throw new L(0,`Network error: Could not connect to ${Cr()}`,{originalError:p instanceof Error?p.message:String(p)})}let d;try{d=await l.text()}catch(p){if(sl())yS({method:i,url:o,status:l.status,durationMs:Date.now()-c,requestHeaders:s,requestBody:a,error:p instanceof Error?p.message:String(p)});throw new L(0,"Failed to read response body",{httpStatus:l.status,originalError:p instanceof Error?p.message:String(p)})}if(sl())yS({method:i,url:o,status:l.status,durationMs:Date.now()-c,requestHeaders:s,requestBody:a,responseBody:d});let f;try{f=JSON.parse(d)}catch{throw new L(l.status,`Invalid response from server (status ${l.status})`)}if(!l.ok){if(l.status===503&&(f.mode==="read-only"||f.mode==="full")){let z=typeof f.message==="string"?f.message:"NEMAR is in maintenance mode. Please retry shortly.",A=typeof f.eta==="string"?f.eta:null,F=new vu(f.mode,z,A,f.details);throw wS(F),F}let p=typeof f.block_reason==="string",m=Array.isArray(f.missing)?f.missing.filter((z)=>typeof z==="string"):void 0,h=typeof f.error==="string"&&(RQ.includes(f.error)||VQ.includes(f.error)),g=typeof f.error==="string"&&(Xv.options.includes(f.error)||YQ.includes(f.error)),y=typeof f.error==="string"&&vQ.includes(f.error),b=typeof f.error==="string"&&CQ.includes(f.error),_=typeof f.error==="string"&&UQ.includes(f.error),x=typeof f.error==="string"&&BQ.includes(f.error),k=typeof f.error==="string"&&HQ.includes(f.error),C=p||x||k||h||g||y||b||_||m!==void 0&&typeof f.error==="string"&&DQ.includes(f.error)?f.message||f.error:f.error||f.message;if(l.status===404&&f.error==="Not Found"&&typeof f.message==="string")C=`${f.message}. This NEMAR backend does not support this command yet.`;let T=new L(l.status,C||"Request failed",f.details,typeof f.step==="string"?f.step:void 0,p?f.block_reason:void 0,m);if(typeof f.error==="string")T.code=f.error;if(typeof f.reason==="string")T.reason=f.reason;throw T.rawBody=f,T}if(r){let p=r.safeParse(f);if(!p.success)throw new L(l.status,`Response for ${e} did not match the expected NEMAR contract`,{issues:p.error.issues});return p.data}return f}var WI="https://api.nemar.org",Nf;var lo=V(()=>{B0();ek();wT();U0();Ym();gr();dn();GI();If();Ke();Nf=WI.includes("workers.dev")});async function Zh(e,t={}){return q(`/datasets/${e}/publish/request`,t.anonymous?{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({anonymous:!0})}:{method:"POST"},!0)}async function eg(e){return q(`/datasets/${e}/publish/status`,{},!0)}async function Ffe(e){return q(`/datasets/${e}/publish/resend`,{method:"POST"},!0)}async function Mfe(e){return q(`/datasets/${e}/publish/withdraw`,{method:"POST"},!0)}async function Ff(e={}){let{statuses:t,search:n}=typeof e==="string"?{statuses:e?[e]:[]}:e,r=await Ife(t,n),o=r;if(t!==void 0&&t.length>1&&r.requests.length===0){let s=[];for(let a of new Set(t))s.push(await Ife([a],n));let i=s.flatMap((a)=>a.requests).sort(jfe);o={...r,requests:i,count:i.length}}return n?cpt(o,n):o}function jfe(e,t){return e.requested_at<t.requested_at?1:e.requested_at>t.requested_at?-1:0}async function Ife(e,t){let n=new URLSearchParams;if(e&&e.length>0)n.set("status",e.join(","));if(t)n.set("search",t);let r=n.size>0?`?${n}`:"";return q(`/admin/publish/requests${r}`,{},!0)}function cpt(e,t){let n=e.requests.filter((s)=>xZ(t,[s.dataset_id,s.requested_by_username,s.dataset_name])),r=(s)=>vZ(s.dataset_id,t)?0:1,o=[...n].sort((s,i)=>r(s)-r(i)||jfe(s,i));return{...e,requests:o,count:o.length}}async function tg(e,t,n){return q(`/admin/publish/${e}/deny`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:t,...n!==void 0?{request_id:n}:{}})},!0)}async function _S(e){return q(`/admin/publish/${e}/identifier-screen`,{method:"POST"},!0)}async function xS(e){return q(`/admin/publish/${e}/review`,{},!0)}async function Lfe(e){return q(`/admin/publish/${e}/review/start`,{method:"POST"},!0)}async function qfe(e,t){let n={message:t};return q(`/admin/publish/${e}/comment`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},!0)}function ng(e){if(!(e instanceof L))return;let t=e.rawBody;if(typeof t!=="object"||t===null||Array.isArray(t))return;let n=t.code;return typeof n==="string"?n:void 0}function lpt(e,t=[]){if(e){let n=va.indexOf(e);if(n>=0)return n+1}return Math.min(t.length+1,va.length)}function upt(e){if(!(e instanceof L))return!1;if(e.statusCode===0)return!0;if(e.statusCode===429)return!0;if(e.statusCode>=500&&e.statusCode<600)return!0;if(e.statusCode===403&&/repository has been locked/i.test(e.message))return!0;return!1}function dpt(){let e=process.env.NEMAR_APPROVE_RETRY_DELAY_MS;if(e===void 0||!/^\d+$/.test(e))return fk;let t=Number(e);return Number.isSafeInteger(t)&&t<=fk?t:fk}async function rg(e,t=!1,n=!1,r=!1,o,s,i,a,c){let d=dpt(),f,p,m=0,h=!1,g,y=t,b=[],_;function x(k,v,C,T){if(!s)return;s({step:k,stepIndex:lpt(k,v),stepTotal:va.length,s3LockLocked:C,s3LockTotal:T,s3LockResumed:k==="s3_lock"&&h?!0:void 0})}for(let k=1;k<=5;k++)try{let v,C=!0;do{if(v=await q(`/admin/publish/${e}/approve`,{method:"POST",headers:{"Content-Type":"application/json",...c?.dispatchToken?{[zQ]:c.dispatchToken}:{}},body:JSON.stringify({resume:C?y:!0,sandbox:n,s3_lock_continuation_token:f,s3_lock_total:p,skip_ci_check:r,...i!==void 0?{acknowledge_identifier_screen:i}:{},...a!==void 0?{[bZ]:a}:{},...c?.requestId!==void 0?{request_id:c.requestId}:{}})},!0),C=!1,v.step_results)b.push(...v.step_results);if(v.s3_lock_total!==void 0)p=v.s3_lock_total;if(v.s3_lock_batch_count!==void 0)m+=v.s3_lock_batch_count;let T=v.step??v.step_results?.[v.step_results.length-1]?.step;if(T&&(T!==g||T==="s3_lock"))x(T,v.steps_completed??[],T==="s3_lock"?m:void 0,T==="s3_lock"?p:void 0),g=T;if(v.hasMore&&v.s3_lock_continuation_token!==void 0)f=v.s3_lock_continuation_token;else break}while(v.hasMore);if(b.length>0)v.step_results=Nfe(b);return v}catch(v){if(_=v,k===5||!upt(v)){if(v instanceof L&&b.length>0)v.stepResults=Nfe(b);throw v}let T=v;if(o?.({attempt:k,maxAttempts:5,delayMs:d,step:T.step,error:T.message}),await new Promise((z)=>setTimeout(z,d)),y=!0,f!==void 0)h=!0}throw _}function Nfe(e){let t=new Map;for(let n of e)t.set(n.step,n);return Array.from(t.values())}var Ni=V(()=>{dk();U0();mk();lo();Ke()});function ES(e){if(e.service_access===void 0||e.service_access===null)return"unknown";return e.service_access?"upload":"browse"}async function nN(e,t,n,r,o={}){let s=new URLSearchParams;if(e)s.set("status",e);if(t)s.set("role",t);if(n)s.set("awaiting_approval","1");if(r)s.set("kind",r);if(o.search!==void 0)s.set("q",o.search);if(o.includeDeleted)s.set("include_deleted","true");let i=s.toString()?`?${s.toString()}`:"";return q(`/admin/users${i}`,{},!0,SQ)}async function SS(e,t=!1){return q(`/admin/users/by-id/${e}${t?"?include_deleted=true":""}`,{},!0,TQ)}async function Yfe(e,t){return q(`/admin/users/by-id/${e}`,{method:"PATCH",body:JSON.stringify(t)},!0,PQ)}async function Xfe(e){return q(`/admin/approve/${e}`,{method:"POST"},!0)}async function Qfe(e){return q(`/admin/approve/by-id/${e}`,{method:"POST"},!0)}async function Zfe(e){return q(`/admin/revoke/${e}`,{method:"POST"},!0)}async function epe(e){return q(`/admin/revoke/by-id/${e}`,{method:"POST"},!0)}async function tpe(e){return q(`/admin/users/by-id/${e}/verify`,{method:"POST"},!0)}async function npe(e,t){return q(`/admin/users/${e}/role`,{method:"POST",body:JSON.stringify({role:t})},!0)}async function rpe(e,t){return q(`/admin/users/${e}/kind`,{method:"POST",body:JSON.stringify({kind:t})},!0)}async function $S(e){return q(`/admin/users/${encodeURIComponent(e)}`,{},!0)}async function ope(e,t){return q(`/admin/users/${e}/keys`,{method:"POST",body:JSON.stringify({name:t})},!0,Zv)}async function spe(e){return q(`/admin/users/${e}/keys`,{},!0,Qv)}async function ipe(e,t){return q(`/admin/users/${e}/keys/${t}`,{method:"DELETE"},!0)}async function rN(e,t){return q(`/admin/datasets/${e}/visibility`,{method:"PATCH",body:JSON.stringify({visibility:t})},!0)}async function ape(e){return q(`/datasets/${e}/publish`,{method:"POST"},!0)}async function cpe(e){return q(`/admin/datasets/${e}/ci`,{},!0)}async function il(e){return q(`/admin/datasets/${e}/ci`,{method:"POST"},!0)}async function oN(e){return q(`/admin/datasets/${e}/ci/validate`,{method:"POST"},!0)}async function sN(e){return q(`/admin/datasets/${e}/ci/sync`,{method:"POST"},!0)}async function lpe(e,t){return q(`/admin/datasets/${e}/doi/concept`,{method:"POST",body:JSON.stringify(t)},!0)}async function jb(e){return q(`/admin/datasets/${e}/doi`,{},!0)}async function iN(e,t){return q(`/admin/datasets/${e}/doi/update`,{method:"POST",body:JSON.stringify(t)},!0)}async function upe(e,t){return q(`/admin/datasets/${e}/withdraw`,{method:"POST",body:JSON.stringify({reason:t.reason,dry_run:t.dryRun})},!0)}async function dpe(e,t){return q(`/admin/datasets/${e}/restore`,{method:"POST",body:JSON.stringify({dry_run:t.dryRun})},!0)}async function fpe(e){return q(`/admin/datasets/${e}/reset`,{method:"POST"},!0)}async function ppe(e,t=!1){return q(`/admin/datasets/${e}`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({force:t})},!0)}async function mpe(e){return q("/admin/datasets/bulk-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dataset_ids:e})},!0)}async function hpe(e){return q("/admin/datasets/import",{method:"POST",body:JSON.stringify(e)},!0)}async function gpe(e){return q("/admin/datasets/exemplar",{method:"POST",body:JSON.stringify(e)},!0)}async function ype(e){return q(`/admin/datasets/${e}/exemplar/remint-dois`,{method:"POST"},!0)}async function aN(e,t){let n=new URLSearchParams;if(e)n.set("status",e);if(t!==void 0)n.set("blocklisted",t?"1":"0");let r=n.toString();return q(`/admin/imports${r?`?${r}`:""}`,{},!0)}async function bpe(e){return q(`/admin/imports/${e}/rollback`,{method:"POST"},!0)}async function wpe(e){return q(`/admin/imports/${e}/retry`,{method:"POST"},!0)}async function cN(e){return q(`/admin/imports/${e}/verify`,{method:"POST"},!0)}async function _pe(e){return q("/admin/imports/dispatch-cooldown",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dataset_ids:e})},!0)}async function ig(e,t){return q(`/admin/datasets/${e}/reindex`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})},!0)}async function xpe(e,t){return q("/admin/datasets/reindex/bulk",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filter:e,...t??{}})},!0)}async function vpe(e){let t=e?.limit??15;return q(`/admin/datasets/hed-sweep?limit=${encodeURIComponent(String(t))}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function kpe(){return q("/admin/datasets/hed-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Epe(e){let t=e?.limit??50;return q(`/admin/datasets/recording-stats-sweep?limit=${encodeURIComponent(String(t))}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Spe(){return q("/admin/datasets/recording-stats-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function $pe(e){let t=e?.limit??15;return q(`/admin/datasets/signal-defaults-sweep?limit=${encodeURIComponent(String(t))}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Dpe(){return q("/admin/datasets/signal-defaults-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Rpe(e){let t=e?.limit??15,n=new URLSearchParams({limit:String(t)});if(e?.olderThan!=null)n.set("older-than",String(e.olderThan));if(e?.before!=null)n.set("before",e.before);return q(`/admin/datasets/data-integrity-sweep?${n.toString()}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Cpe(){return q("/admin/datasets/data-integrity-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Ape(e,t){let n=t?.write?"":"?dry_run=1";return q(`/admin/datasets/${e}/availability-report${n}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Ope(e){let t=e?.limit??30,n=new URLSearchParams({limit:String(t)});if(e?.missingOnly)n.set("missing-only","1");return q(`/admin/datasets/availability-report-sweep?${n.toString()}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Tpe(){return q("/admin/datasets/availability-report-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Ppe(e){let t=new URLSearchParams;if(e?.prefix)t.set("prefix",e.prefix);if(e?.visibility)t.set("visibility",e.visibility);if(e?.limit)t.set("limit",String(e.limit));let n=t.toString()?`?${t.toString()}`:"";return q(`/admin/fleet/drift${n}`,{},!0)}async function ag(e,t){return q(`/admin/datasets/${e}/enforce`,{method:"POST",body:JSON.stringify({dry_run:t})},!0)}async function Ipe(e){return q("/admin/datasets/enforce/bulk",{method:"POST",body:JSON.stringify({prefix:e.prefix,visibility:e.visibility,limit:e.limit,dry_run:e.dryRun})},!0)}async function Npe(e,t){return q(`/admin/datasets/${e}/review-ruleset`,{method:"POST",body:JSON.stringify({dry_run:t.dryRun,remove:t.remove})},!0)}async function Fpe(e){return q("/admin/datasets/review-ruleset/bulk",{method:"POST",body:JSON.stringify({prefix:e.prefix,after:e.after,limit:e.limit,dry_run:e.dryRun,remove:e.remove})},!0)}async function Mpe(e,t=!1){return q(`/admin/datasets/${e}/revalidate${t?"?force=true":""}`,{method:"POST"},!0)}async function jpe(e){let t=e?`?user=${encodeURIComponent(e)}`:"";return q(`/admin/email-preferences${t}`,{},!0)}async function Lpe(e,t){let n=t?`?user=${encodeURIComponent(t)}`:"";return q(`/admin/email-preferences${n}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)},!0)}async function lN(e){return q("/admin/notify",{method:"POST",body:JSON.stringify(e)},!0)}async function qpe(e){return q(`/admin/notify/${e}`,{},!0)}async function Bpe(){return q("/admin/summary/coverage",{},!0)}async function Upe(e,t,n){return q("/admin/manifest/dispatch",{method:"POST",body:JSON.stringify({dataset_id:e,version:t,skip_canary:n?.skipCanary??!1})},!0)}async function uN(e){return q("/admin/doctor/scan",{method:"POST",body:JSON.stringify({...e?.check&&{check:e.check},...e?.datasetId&&{dataset_id:e.datasetId}})},!0)}async function dN(e){return q("/admin/doctor/fix",{method:"POST",body:JSON.stringify({check:e.check,...e.datasetId&&{dataset_id:e.datasetId},...e.dryRun&&{dry_run:!0}})},!0)}async function Hpe(){return q("/admin/zarr-catalog/publish",{method:"POST"},!0)}async function zpe(e){return q("/admin/neurobagel/regenerate",{method:"POST",body:JSON.stringify(e)},!0)}async function Vpe(){return q("/admin/neurobagel/status",{method:"GET"},!0)}async function Gpe(){return q("/admin/neurobagel/verify",{method:"POST",body:"{}"},!0)}async function Wpe(e){let t=new URLSearchParams;if(e?.limit!=null)t.set("limit",String(e.limit));let n=t.toString()?`?${t.toString()}`:"";return q(`/admin/datasets/zarr-fidelity-sweep${n}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Kpe(e){let t=new URLSearchParams;if(e?.execute)t.set("execute","1");if(e?.limit!=null)t.set("limit",String(e.limit));if(e?.after)t.set("after",e.after);let n=t.toString()?`?${t.toString()}`:"";try{return await q(`/admin/datasets/upstream-backfill${n}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}catch(r){let o=r instanceof L&&r.statusCode===502?r.rawBody:void 0;if(o&&typeof o==="object"&&"execute"in o&&"counts"in o)return{...o,ok:!1};throw r}}async function Jpe(e){let t=new URLSearchParams;if(e?.limit!=null)t.set("limit",String(e.limit));if(e?.after)t.set("after",e.after);if(e?.dataset)t.set("dataset",e.dataset);let n=t.toString()?`?${t.toString()}`:"";try{return await q(`/admin/upstream-status${n}`,{method:"GET"},!0)}catch(r){let o=r instanceof L&&r.statusCode===502?r.rawBody:void 0;if(o&&typeof o==="object"&&"rows"in o&&"counts"in o)return{...o,ok:!1};throw r}}async function Ype(e){let t=new URLSearchParams;if(e?.limit!=null)t.set("limit",String(e.limit));if(e?.apply)t.set("apply","1");let n=t.toString()?`?${t.toString()}`:"";return q(`/admin/imports/issue-triage${n}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Xpe(e){let t=e?.apply?"?apply=1":"";return q(`/admin/imports/coverage-sweep${t}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Qpe(e){let t=e?.apply?"?apply=1":"";return q(`/admin/imports/weekly-summary${t}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Zpe(e){return q("/admin/users/backfill-names",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apply:e?.apply??!1,...e?.limit!=null?{limit:e.limit}:{}})},!0)}async function eme(e){return q("/admin/users/backfill-usernames",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apply:e?.apply??!1,...e?.limit!=null?{limit:e.limit}:{}})},!0)}async function tme(){return q("/admin/users/duplicates",{},!0,GQ)}async function nme(e){return q(`/admin/users/${e}/clear-identity-conflict`,{method:"POST"},!0,WQ)}async function rme(e){let t=new URLSearchParams;if(e?.limit!=null)t.set("limit",String(e.limit));let n=t.toString()?`?${t.toString()}`:"";return q(`/admin/datasets/anonymity-sweep${n}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function ome(){return q("/admin/datasets/anonymity-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Lb(e){let t=new URLSearchParams;if(e.verdicts&&e.verdicts.length>0)t.set("verdict",e.verdicts.join(","));if(e.dataset)t.set("dataset",e.dataset);if(e.author)t.set("author",e.author);if(e.needsMe)t.set("needs_me","1");let n=t.toString()?`?${t.toString()}`:"";return q(`/admin/pr-reviews${n}`,{method:"GET"},!0)}async function cg(e,t,n){let r=n?`?head=${encodeURIComponent(n)}`:"";return q(`/admin/pr-reviews/${encodeURIComponent(e)}/${t}${r}`,{method:"GET"},!0)}async function fN(e,t,n={}){let r=n.redo?"?redo=1":"";return q(`/admin/pr-reviews/${encodeURIComponent(e)}/${t}/start${r}`,{method:"POST"},!0)}async function sme(e){return q(`/admin/pr-review-authors/${encodeURIComponent(e)}`,{method:"GET"},!0)}async function ime(e,t,n){return q(`/admin/pr-review-authors/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(n?{mode:t,reason:n}:{mode:t})},!0)}async function ame(e){return q(`/admin/pr-review-authors/${encodeURIComponent(e)}`,{method:"DELETE"},!0)}async function cme(e,t,n,r){return q(`/admin/pr-reviews/${encodeURIComponent(e)}/${t}/allow`,{method:"POST",body:JSON.stringify({reason:n,...r?{head_sha:r}:{}})},!0)}async function mN(e){let t=new URLSearchParams;for(let[r,o]of Object.entries(e))if(o!==void 0&&o!=="")t.set(r,String(o));let n=t.toString();return q(`/admin/mail/tickets${n?`?${n}`:""}`,{},!0)}async function hN(e){return q(`/admin/mail/tickets/${e}`,{},!0)}async function lme(e,t,n){let r={text:t};return q(`/admin/mail/tickets/${e}/reply`,dd(r,{"Idempotency-Key":n}),!0)}async function ume(e,t,n){let r={text:t};return q(`/admin/mail/tickets/${e}/note`,dd(r,{"Idempotency-Key":n}),!0)}async function dme(e,t){let n={user_id:t};return q(`/admin/mail/tickets/${e}/assign`,dd(n),!0)}async function fme(e,t){return q(`/admin/mail/tickets/${e}/status`,dd({status:t}),!0)}async function pme(e,t){let n={summary:t};return q(`/admin/mail/tickets/${e}/summary`,pN(n),!0)}async function mme(e,t){let n=t?{reason:t}:{};return q(`/admin/mail/tickets/${e}/escalate`,dd(n),!0)}async function hme(e,t){return q(`/admin/mail/tickets/${e}/spam`,dd(t),!0)}async function gme(e={}){let t=new URLSearchParams;for(let[r,o]of Object.entries(e))if(o!==void 0&&o!=="")t.set(r,String(o));let n=t.toString();return q(`/admin/mail/blocklist${n?`?${n}`:""}`,{},!0)}async function yme(e){return q("/admin/mail/blocklist",dd(e),!0)}async function bme(e){return q(`/admin/mail/blocklist/${e}`,{method:"DELETE"},!0)}async function wme(){return q("/admin/mail/queues",{},!0)}async function _me(e,t){return q(`/admin/mail/queues/${encodeURIComponent(e)}`,pN(t),!0)}async function xme(e){return q(`/admin/mail/availability${e===void 0?"":`/${e}`}`,{},!0)}async function gN(e,t){return q(`/admin/mail/availability${t===void 0?"":`/${t}`}`,pN(e),!0)}async function vme(e){return q("/admin/mail/reprocess",dd({raw_key:e}),!0)}async function kme(e){return(await q(`/admin/users/by-id/${e}`,{},!0)).user.username}var dd=(e,t)=>({method:"POST",body:JSON.stringify(e),...t?{headers:t}:{}}),pN=(e)=>({method:"PUT",body:JSON.stringify(e)});var Qa=V(()=>{B0();nh();lo();Ke()});async function Gr(e,t){return q(`/datasets/${e}/upload-credentials`,{method:"POST",body:JSON.stringify({duration_seconds:t})},!0)}async function yN(e,t){return q(`/datasets/${e}/download-credentials`,{method:"POST",body:JSON.stringify({duration_seconds:t})},!0)}async function Sme(e){return q(`/admin/datasets/${e}/files`,{},!0)}async function $me(e){let t,n=0,r=[],o=!0;while(o){let s=await q(`/admin/datasets/${e}/s3-lock`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({continuation_token:t})},!0);if(n+=s.locked,s.failed?.length)r.push(...s.failed);if(o=s.hasMore,t=s.continuation_token,o&&!t)throw new L(500,"S3 lock paginated response missing continuation_token; aborting to avoid infinite loop")}return{locked:n,failed:r}}async function Dme(e,t){let n=0,r=[],o=[];for(let s=0;s<t.length;s+=Eme){let i=t.slice(s,s+Eme),a=await q(`/admin/datasets/${e}/s3-lock`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({objects:i})},!0);if(!Array.isArray(a.objects))throw new L(500,"The s3-lock route did not name the objects it locked.");if(n+=a.objects.length,o.push(...a.objects),a.failed?.length)r.push(...a.failed)}return{locked:n,failed:r,objects:o}}var Eme=100;var Za=V(()=>{lo();Ke()});async function RS(e){return q(`/datasets/${e}/ci/status`,{},!0)}async function Rme(e){return q(`/datasets/${e}/manifest`,{},!0)}async function CS(e,t){return q(`/datasets/${e}/manifest/${t}`,{},!0)}function Cme(e){let t=e;if(!t.status)t.status="active";else if(!["active","archived","deleted"].includes(t.status))throw Error(`Invalid dataset status: ${t.status}`);if(!t.visibility)t.visibility="private";else if(!["public","private"].includes(t.visibility))throw Error(`Invalid dataset visibility: ${t.visibility}`);return t}async function fd(e={}){let t=new URLSearchParams;if(e.mine)t.set("mine","true");if(e.search)t.set("search",e.search);if(e.modality)t.set("modality",e.modality);if(e.author)t.set("author",e.author);if(e.task)t.set("task",e.task);if(e.license)t.set("license",e.license);if(e.hasDoi)t.set("has_doi","true");if(e.hasHed)t.set("has_hed","1");if(e.hasZarr)t.set("has_zarr","1");if(e.hasZarrVerified)t.set("has_zarr_verified","1");if(e.dataComplete)t.set("data_complete","1");if(e.recent)t.set("recent",String(e.recent));if(e.sort)t.set("sort",e.sort);if(e.limit!=null)t.set("limit",String(e.limit));if(e.offset!=null)t.set("offset",String(e.offset));if(e.owner)t.set("owner",e.owner);if(e.facets)for(let[o,s]of Object.entries(e.facets))t.set(o,s);if(e.includeUnknown)t.set("include_unknown","1");let n=t.toString()?`?${t.toString()}`:"",r=await q(`/datasets${n}`,{},e.mine?!0:"optional");return r.datasets=r.datasets.map(Cme),r}async function Ame(e){return q(`/datasets/resolve/${e}`,{},"optional")}async function Ome(){return q("/datasets/facets",{signal:AbortSignal.timeout(5000)},"optional",Jv)}async function Tme(e,t={}){let n=new URLSearchParams({q:e});if(t.modality)n.set("modality",t.modality);if(t.limit)n.set("limit",String(t.limit));if(t.hasHed)n.set("has_hed","1");if(t.hasZarr)n.set("has_zarr","1");if(t.hasZarrVerified)n.set("has_zarr_verified","1");if(t.author)n.set("author",t.author);if(t.task)n.set("task",t.task);if(t.license)n.set("license",t.license);if(t.hasDoi)n.set("has_doi","true");if(t.dataComplete)n.set("data_complete","1");if(t.recent)n.set("recent",String(t.recent));if(t.facets)for(let[o,s]of Object.entries(t.facets))n.set(o,s);if(t.includeUnknown)n.set("include_unknown","1");return await q(`/datasets/search?${n.toString()}`,{},"optional",LQ)}async function Wn(e){let t=await q(`/datasets/${e}`,{},"optional");return Cme(t.dataset)}async function Lf(e){return q(`/datasets/${e}/versions`,{},!0)}async function Pme(e){try{let t=await Lf(e);if(!Array.isArray(t.versions))throw Error(`GET /datasets/${e}/versions answered without a versions list`);return t.versions.length>0}catch(t){if(t instanceof L&&t.statusCode===404&&!uk(t))return!1;throw t}}async function AS(e){return q("/datasets",{method:"POST",body:JSON.stringify(e)},!0)}async function Ime(e,t){return q(`/datasets/${e}/attestation`,{method:"PUT",body:JSON.stringify(t)},!0)}async function OS(e){return q(`/datasets/${e}/finalize`,{method:"POST"},!0)}async function bN(e){return q(`/datasets/${e}/request-access`,{method:"POST"},!0)}async function Nme(e,t){let n=t?`?status=${t}`:"";return q(`/datasets/${e}/access-requests${n}`,{},!0)}async function Fme(e,t){return q(`/datasets/${e}/access-requests/${t}/approve`,{method:"POST"},!0)}async function Mme(e,t){return q(`/datasets/${e}/access-requests/${t}/deny`,{method:"POST"},!0)}async function jme(e,t){return q(`/datasets/${e}/invite`,{method:"POST",body:JSON.stringify({username:t})},!0)}async function Lme(e){return q(`/datasets/${e}/collaborators`,{},!0)}async function qme(e,t){return q(`/admin/datasets/${e}/enrichment`,{method:"POST",body:JSON.stringify(t)},!0)}var DS;var ec=V(()=>{nh();lo();Ke();DS=/^\d{4}-\d{4}-\d{4}-\d{3}[\dX]$/});function dhe(e,t){return e.filter((n)=>n.visibility==="public").map((n)=>n.dataset_id).filter((n)=>n.startsWith("nm")||n.startsWith("on")).filter((n)=>n!=="nm099999"&&!al.has(n)).filter((n)=>t.prefix?n.startsWith(t.prefix):!0).sort()}var al;var NS=V(()=>{al=new Set(["nm000103","nm000104","nm000105","nm000106","nm000107"])});function Kr(e){return e.replace(fhe,phe)}function phe(e){if(e===`
|
|
113
|
+
`)}var Pfe=!1;var GI=V(()=>{He()});function Cr(){if(process.env.TEST_API_URL)return process.env.TEST_API_URL;if(Nf)return WI;return Vt().apiUrl||WI}async function q(e,t={},n=!1,r){let o=`${Cr()}${e}`,s={"Content-Type":"application/json","X-CLI-Version":ks,...t.headers};if(n){let p=Vt();if(!p.apiKey&&n===!0)throw new L(401,"Not authenticated. Run 'nemar auth login' first.");if(p.apiKey)s.Authorization=`Bearer ${p.apiKey}`}let i=t.method||"GET",a=typeof t.body==="string"?t.body:void 0,c=Date.now(),l;try{l=await fetch(o,{...t,headers:s})}catch(p){if(sl())yS({method:i,url:o,status:null,durationMs:Date.now()-c,requestHeaders:s,requestBody:a,error:p instanceof Error?p.message:String(p)});throw new L(0,`Network error: Could not connect to ${Cr()}`,{originalError:p instanceof Error?p.message:String(p)})}let d;try{d=await l.text()}catch(p){if(sl())yS({method:i,url:o,status:l.status,durationMs:Date.now()-c,requestHeaders:s,requestBody:a,error:p instanceof Error?p.message:String(p)});throw new L(0,"Failed to read response body",{httpStatus:l.status,originalError:p instanceof Error?p.message:String(p)})}if(sl())yS({method:i,url:o,status:l.status,durationMs:Date.now()-c,requestHeaders:s,requestBody:a,responseBody:d});let f;try{f=JSON.parse(d)}catch{throw new L(l.status,`Invalid response from server (status ${l.status})`)}if(!l.ok){if(l.status===503&&(f.mode==="read-only"||f.mode==="full")){let z=typeof f.message==="string"?f.message:"NEMAR is in maintenance mode. Please retry shortly.",A=typeof f.eta==="string"?f.eta:null,F=new vu(f.mode,z,A,f.details);throw wS(F),F}let p=typeof f.block_reason==="string",m=Array.isArray(f.missing)?f.missing.filter((z)=>typeof z==="string"):void 0,h=typeof f.error==="string"&&(RQ.includes(f.error)||VQ.includes(f.error)),g=typeof f.error==="string"&&(Xv.options.includes(f.error)||YQ.includes(f.error)),y=typeof f.error==="string"&&vQ.includes(f.error),b=typeof f.error==="string"&&CQ.includes(f.error),_=typeof f.error==="string"&&UQ.includes(f.error),x=typeof f.error==="string"&&BQ.includes(f.error),k=typeof f.error==="string"&&HQ.includes(f.error),C=p||x||k||h||g||y||b||_||m!==void 0&&typeof f.error==="string"&&DQ.includes(f.error)?f.message||f.error:f.error||f.message;if(l.status===404&&f.error==="Not Found"&&typeof f.message==="string")C=`${f.message}. This NEMAR backend does not support this command yet.`;let T=new L(l.status,C||"Request failed",f.details,typeof f.step==="string"?f.step:void 0,p?f.block_reason:void 0,m);if(typeof f.error==="string")T.code=f.error;if(typeof f.reason==="string")T.reason=f.reason;throw T.rawBody=f,T}if(r){let p=r.safeParse(f);if(!p.success)throw new L(l.status,`Response for ${e} did not match the expected NEMAR contract`,{issues:p.error.issues});return p.data}return f}var WI="https://api.nemar.org",Nf;var lo=V(()=>{B0();ek();wT();U0();Ym();gr();dn();GI();If();Je();Nf=WI.includes("workers.dev")});async function Zh(e,t={}){return q(`/datasets/${e}/publish/request`,t.anonymous?{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({anonymous:!0})}:{method:"POST"},!0)}async function eg(e){return q(`/datasets/${e}/publish/status`,{},!0)}async function Ffe(e){return q(`/datasets/${e}/publish/resend`,{method:"POST"},!0)}async function Mfe(e){return q(`/datasets/${e}/publish/withdraw`,{method:"POST"},!0)}async function Ff(e={}){let{statuses:t,search:n}=typeof e==="string"?{statuses:e?[e]:[]}:e,r=await Ife(t,n),o=r;if(t!==void 0&&t.length>1&&r.requests.length===0){let s=[];for(let a of new Set(t))s.push(await Ife([a],n));let i=s.flatMap((a)=>a.requests).sort(jfe);o={...r,requests:i,count:i.length}}return n?cpt(o,n):o}function jfe(e,t){return e.requested_at<t.requested_at?1:e.requested_at>t.requested_at?-1:0}async function Ife(e,t){let n=new URLSearchParams;if(e&&e.length>0)n.set("status",e.join(","));if(t)n.set("search",t);let r=n.size>0?`?${n}`:"";return q(`/admin/publish/requests${r}`,{},!0)}function cpt(e,t){let n=e.requests.filter((s)=>xZ(t,[s.dataset_id,s.requested_by_username,s.dataset_name])),r=(s)=>vZ(s.dataset_id,t)?0:1,o=[...n].sort((s,i)=>r(s)-r(i)||jfe(s,i));return{...e,requests:o,count:o.length}}async function tg(e,t,n){return q(`/admin/publish/${e}/deny`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:t,...n!==void 0?{request_id:n}:{}})},!0)}async function _S(e){return q(`/admin/publish/${e}/identifier-screen`,{method:"POST"},!0)}async function xS(e){return q(`/admin/publish/${e}/review`,{},!0)}async function Lfe(e){return q(`/admin/publish/${e}/review/start`,{method:"POST"},!0)}async function qfe(e,t){let n={message:t};return q(`/admin/publish/${e}/comment`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},!0)}function ng(e){if(!(e instanceof L))return;let t=e.rawBody;if(typeof t!=="object"||t===null||Array.isArray(t))return;let n=t.code;return typeof n==="string"?n:void 0}function lpt(e,t=[]){if(e){let n=va.indexOf(e);if(n>=0)return n+1}return Math.min(t.length+1,va.length)}function upt(e){if(!(e instanceof L))return!1;if(e.statusCode===0)return!0;if(e.statusCode===429)return!0;if(e.statusCode>=500&&e.statusCode<600)return!0;if(e.statusCode===403&&/repository has been locked/i.test(e.message))return!0;return!1}function dpt(){let e=process.env.NEMAR_APPROVE_RETRY_DELAY_MS;if(e===void 0||!/^\d+$/.test(e))return fk;let t=Number(e);return Number.isSafeInteger(t)&&t<=fk?t:fk}async function rg(e,t=!1,n=!1,r=!1,o,s,i,a,c){let d=dpt(),f,p,m=0,h=!1,g,y=t,b=[],_;function x(k,v,C,T){if(!s)return;s({step:k,stepIndex:lpt(k,v),stepTotal:va.length,s3LockLocked:C,s3LockTotal:T,s3LockResumed:k==="s3_lock"&&h?!0:void 0})}for(let k=1;k<=5;k++)try{let v,C=!0;do{if(v=await q(`/admin/publish/${e}/approve`,{method:"POST",headers:{"Content-Type":"application/json",...c?.dispatchToken?{[zQ]:c.dispatchToken}:{}},body:JSON.stringify({resume:C?y:!0,sandbox:n,s3_lock_continuation_token:f,s3_lock_total:p,skip_ci_check:r,...i!==void 0?{acknowledge_identifier_screen:i}:{},...a!==void 0?{[bZ]:a}:{},...c?.requestId!==void 0?{request_id:c.requestId}:{}})},!0),C=!1,v.step_results)b.push(...v.step_results);if(v.s3_lock_total!==void 0)p=v.s3_lock_total;if(v.s3_lock_batch_count!==void 0)m+=v.s3_lock_batch_count;let T=v.step??v.step_results?.[v.step_results.length-1]?.step;if(T&&(T!==g||T==="s3_lock"))x(T,v.steps_completed??[],T==="s3_lock"?m:void 0,T==="s3_lock"?p:void 0),g=T;if(v.hasMore&&v.s3_lock_continuation_token!==void 0)f=v.s3_lock_continuation_token;else break}while(v.hasMore);if(b.length>0)v.step_results=Nfe(b);return v}catch(v){if(_=v,k===5||!upt(v)){if(v instanceof L&&b.length>0)v.stepResults=Nfe(b);throw v}let T=v;if(o?.({attempt:k,maxAttempts:5,delayMs:d,step:T.step,error:T.message}),await new Promise((z)=>setTimeout(z,d)),y=!0,f!==void 0)h=!0}throw _}function Nfe(e){let t=new Map;for(let n of e)t.set(n.step,n);return Array.from(t.values())}var Ni=V(()=>{dk();U0();mk();lo();Je()});function ES(e){if(e.service_access===void 0||e.service_access===null)return"unknown";return e.service_access?"upload":"browse"}async function nN(e,t,n,r,o={}){let s=new URLSearchParams;if(e)s.set("status",e);if(t)s.set("role",t);if(n)s.set("awaiting_approval","1");if(r)s.set("kind",r);if(o.search!==void 0)s.set("q",o.search);if(o.includeDeleted)s.set("include_deleted","true");let i=s.toString()?`?${s.toString()}`:"";return q(`/admin/users${i}`,{},!0,SQ)}async function SS(e,t=!1){return q(`/admin/users/by-id/${e}${t?"?include_deleted=true":""}`,{},!0,TQ)}async function Yfe(e,t){return q(`/admin/users/by-id/${e}`,{method:"PATCH",body:JSON.stringify(t)},!0,PQ)}async function Xfe(e){return q(`/admin/approve/${e}`,{method:"POST"},!0)}async function Qfe(e){return q(`/admin/approve/by-id/${e}`,{method:"POST"},!0)}async function Zfe(e){return q(`/admin/revoke/${e}`,{method:"POST"},!0)}async function epe(e){return q(`/admin/revoke/by-id/${e}`,{method:"POST"},!0)}async function tpe(e){return q(`/admin/users/by-id/${e}/verify`,{method:"POST"},!0)}async function npe(e,t){return q(`/admin/users/${e}/role`,{method:"POST",body:JSON.stringify({role:t})},!0)}async function rpe(e,t){return q(`/admin/users/${e}/kind`,{method:"POST",body:JSON.stringify({kind:t})},!0)}async function $S(e){return q(`/admin/users/${encodeURIComponent(e)}`,{},!0)}async function ope(e,t){return q(`/admin/users/${e}/keys`,{method:"POST",body:JSON.stringify({name:t})},!0,Zv)}async function spe(e){return q(`/admin/users/${e}/keys`,{},!0,Qv)}async function ipe(e,t){return q(`/admin/users/${e}/keys/${t}`,{method:"DELETE"},!0)}async function rN(e,t){return q(`/admin/datasets/${e}/visibility`,{method:"PATCH",body:JSON.stringify({visibility:t})},!0)}async function ape(e){return q(`/datasets/${e}/publish`,{method:"POST"},!0)}async function cpe(e){return q(`/admin/datasets/${e}/ci`,{},!0)}async function il(e){return q(`/admin/datasets/${e}/ci`,{method:"POST"},!0)}async function oN(e){return q(`/admin/datasets/${e}/ci/validate`,{method:"POST"},!0)}async function sN(e){return q(`/admin/datasets/${e}/ci/sync`,{method:"POST"},!0)}async function lpe(e,t){return q(`/admin/datasets/${e}/doi/concept`,{method:"POST",body:JSON.stringify(t)},!0)}async function jb(e){return q(`/admin/datasets/${e}/doi`,{},!0)}async function iN(e,t){return q(`/admin/datasets/${e}/doi/update`,{method:"POST",body:JSON.stringify(t)},!0)}async function upe(e,t){return q(`/admin/datasets/${e}/withdraw`,{method:"POST",body:JSON.stringify({reason:t.reason,dry_run:t.dryRun})},!0)}async function dpe(e,t){return q(`/admin/datasets/${e}/restore`,{method:"POST",body:JSON.stringify({dry_run:t.dryRun})},!0)}async function fpe(e){return q(`/admin/datasets/${e}/reset`,{method:"POST"},!0)}async function ppe(e,t=!1){return q(`/admin/datasets/${e}`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({force:t})},!0)}async function mpe(e){return q("/admin/datasets/bulk-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dataset_ids:e})},!0)}async function hpe(e){return q("/admin/datasets/import",{method:"POST",body:JSON.stringify(e)},!0)}async function gpe(e){return q("/admin/datasets/exemplar",{method:"POST",body:JSON.stringify(e)},!0)}async function ype(e){return q(`/admin/datasets/${e}/exemplar/remint-dois`,{method:"POST"},!0)}async function aN(e,t){let n=new URLSearchParams;if(e)n.set("status",e);if(t!==void 0)n.set("blocklisted",t?"1":"0");let r=n.toString();return q(`/admin/imports${r?`?${r}`:""}`,{},!0)}async function bpe(e){return q(`/admin/imports/${e}/rollback`,{method:"POST"},!0)}async function wpe(e){return q(`/admin/imports/${e}/retry`,{method:"POST"},!0)}async function cN(e){return q(`/admin/imports/${e}/verify`,{method:"POST"},!0)}async function _pe(e){return q("/admin/imports/dispatch-cooldown",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dataset_ids:e})},!0)}async function ig(e,t){return q(`/admin/datasets/${e}/reindex`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})},!0)}async function xpe(e,t){return q("/admin/datasets/reindex/bulk",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filter:e,...t??{}})},!0)}async function vpe(e){let t=e?.limit??15;return q(`/admin/datasets/hed-sweep?limit=${encodeURIComponent(String(t))}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function kpe(){return q("/admin/datasets/hed-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Epe(e){let t=e?.limit??50;return q(`/admin/datasets/recording-stats-sweep?limit=${encodeURIComponent(String(t))}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Spe(){return q("/admin/datasets/recording-stats-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function $pe(e){let t=e?.limit??15;return q(`/admin/datasets/signal-defaults-sweep?limit=${encodeURIComponent(String(t))}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Dpe(){return q("/admin/datasets/signal-defaults-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Rpe(e){let t=e?.limit??15,n=new URLSearchParams({limit:String(t)});if(e?.olderThan!=null)n.set("older-than",String(e.olderThan));if(e?.before!=null)n.set("before",e.before);return q(`/admin/datasets/data-integrity-sweep?${n.toString()}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Cpe(){return q("/admin/datasets/data-integrity-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Ape(e,t){let n=t?.write?"":"?dry_run=1";return q(`/admin/datasets/${e}/availability-report${n}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Ope(e){let t=e?.limit??30,n=new URLSearchParams({limit:String(t)});if(e?.missingOnly)n.set("missing-only","1");return q(`/admin/datasets/availability-report-sweep?${n.toString()}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Tpe(){return q("/admin/datasets/availability-report-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Ppe(e){let t=new URLSearchParams;if(e?.prefix)t.set("prefix",e.prefix);if(e?.visibility)t.set("visibility",e.visibility);if(e?.limit)t.set("limit",String(e.limit));let n=t.toString()?`?${t.toString()}`:"";return q(`/admin/fleet/drift${n}`,{},!0)}async function ag(e,t){return q(`/admin/datasets/${e}/enforce`,{method:"POST",body:JSON.stringify({dry_run:t})},!0)}async function Ipe(e){return q("/admin/datasets/enforce/bulk",{method:"POST",body:JSON.stringify({prefix:e.prefix,visibility:e.visibility,limit:e.limit,dry_run:e.dryRun})},!0)}async function Npe(e,t){return q(`/admin/datasets/${e}/review-ruleset`,{method:"POST",body:JSON.stringify({dry_run:t.dryRun,remove:t.remove})},!0)}async function Fpe(e){return q("/admin/datasets/review-ruleset/bulk",{method:"POST",body:JSON.stringify({prefix:e.prefix,after:e.after,limit:e.limit,dry_run:e.dryRun,remove:e.remove})},!0)}async function Mpe(e,t=!1){return q(`/admin/datasets/${e}/revalidate${t?"?force=true":""}`,{method:"POST"},!0)}async function jpe(e){let t=e?`?user=${encodeURIComponent(e)}`:"";return q(`/admin/email-preferences${t}`,{},!0)}async function Lpe(e,t){let n=t?`?user=${encodeURIComponent(t)}`:"";return q(`/admin/email-preferences${n}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)},!0)}async function lN(e){return q("/admin/notify",{method:"POST",body:JSON.stringify(e)},!0)}async function qpe(e){return q(`/admin/notify/${e}`,{},!0)}async function Bpe(){return q("/admin/summary/coverage",{},!0)}async function Upe(e,t,n){return q("/admin/manifest/dispatch",{method:"POST",body:JSON.stringify({dataset_id:e,version:t,skip_canary:n?.skipCanary??!1})},!0)}async function uN(e){return q("/admin/doctor/scan",{method:"POST",body:JSON.stringify({...e?.check&&{check:e.check},...e?.datasetId&&{dataset_id:e.datasetId}})},!0)}async function dN(e){return q("/admin/doctor/fix",{method:"POST",body:JSON.stringify({check:e.check,...e.datasetId&&{dataset_id:e.datasetId},...e.dryRun&&{dry_run:!0}})},!0)}async function Hpe(){return q("/admin/zarr-catalog/publish",{method:"POST"},!0)}async function zpe(e){return q("/admin/neurobagel/regenerate",{method:"POST",body:JSON.stringify(e)},!0)}async function Vpe(){return q("/admin/neurobagel/status",{method:"GET"},!0)}async function Gpe(){return q("/admin/neurobagel/verify",{method:"POST",body:"{}"},!0)}async function Wpe(e){let t=new URLSearchParams;if(e?.limit!=null)t.set("limit",String(e.limit));let n=t.toString()?`?${t.toString()}`:"";return q(`/admin/datasets/zarr-fidelity-sweep${n}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Kpe(e){let t=new URLSearchParams;if(e?.execute)t.set("execute","1");if(e?.limit!=null)t.set("limit",String(e.limit));if(e?.after)t.set("after",e.after);let n=t.toString()?`?${t.toString()}`:"";try{return await q(`/admin/datasets/upstream-backfill${n}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}catch(r){let o=r instanceof L&&r.statusCode===502?r.rawBody:void 0;if(o&&typeof o==="object"&&"execute"in o&&"counts"in o)return{...o,ok:!1};throw r}}async function Jpe(e){let t=new URLSearchParams;if(e?.limit!=null)t.set("limit",String(e.limit));if(e?.after)t.set("after",e.after);if(e?.dataset)t.set("dataset",e.dataset);let n=t.toString()?`?${t.toString()}`:"";try{return await q(`/admin/upstream-status${n}`,{method:"GET"},!0)}catch(r){let o=r instanceof L&&r.statusCode===502?r.rawBody:void 0;if(o&&typeof o==="object"&&"rows"in o&&"counts"in o)return{...o,ok:!1};throw r}}async function Ype(e){let t=new URLSearchParams;if(e?.limit!=null)t.set("limit",String(e.limit));if(e?.apply)t.set("apply","1");let n=t.toString()?`?${t.toString()}`:"";return q(`/admin/imports/issue-triage${n}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Xpe(e){let t=e?.apply?"?apply=1":"";return q(`/admin/imports/coverage-sweep${t}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Qpe(e){let t=e?.apply?"?apply=1":"";return q(`/admin/imports/weekly-summary${t}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Zpe(e){return q("/admin/users/backfill-names",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apply:e?.apply??!1,...e?.limit!=null?{limit:e.limit}:{}})},!0)}async function eme(e){return q("/admin/users/backfill-usernames",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apply:e?.apply??!1,...e?.limit!=null?{limit:e.limit}:{}})},!0)}async function tme(){return q("/admin/users/duplicates",{},!0,GQ)}async function nme(e){return q(`/admin/users/${e}/clear-identity-conflict`,{method:"POST"},!0,WQ)}async function rme(e){let t=new URLSearchParams;if(e?.limit!=null)t.set("limit",String(e.limit));let n=t.toString()?`?${t.toString()}`:"";return q(`/admin/datasets/anonymity-sweep${n}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function ome(){return q("/admin/datasets/anonymity-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function Lb(e){let t=new URLSearchParams;if(e.verdicts&&e.verdicts.length>0)t.set("verdict",e.verdicts.join(","));if(e.dataset)t.set("dataset",e.dataset);if(e.author)t.set("author",e.author);if(e.needsMe)t.set("needs_me","1");let n=t.toString()?`?${t.toString()}`:"";return q(`/admin/pr-reviews${n}`,{method:"GET"},!0)}async function cg(e,t,n){let r=n?`?head=${encodeURIComponent(n)}`:"";return q(`/admin/pr-reviews/${encodeURIComponent(e)}/${t}${r}`,{method:"GET"},!0)}async function fN(e,t,n={}){let r=n.redo?"?redo=1":"";return q(`/admin/pr-reviews/${encodeURIComponent(e)}/${t}/start${r}`,{method:"POST"},!0)}async function sme(e){return q(`/admin/pr-review-authors/${encodeURIComponent(e)}`,{method:"GET"},!0)}async function ime(e,t,n){return q(`/admin/pr-review-authors/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(n?{mode:t,reason:n}:{mode:t})},!0)}async function ame(e){return q(`/admin/pr-review-authors/${encodeURIComponent(e)}`,{method:"DELETE"},!0)}async function cme(e,t,n,r){return q(`/admin/pr-reviews/${encodeURIComponent(e)}/${t}/allow`,{method:"POST",body:JSON.stringify({reason:n,...r?{head_sha:r}:{}})},!0)}async function mN(e){let t=new URLSearchParams;for(let[r,o]of Object.entries(e))if(o!==void 0&&o!=="")t.set(r,String(o));let n=t.toString();return q(`/admin/mail/tickets${n?`?${n}`:""}`,{},!0)}async function hN(e){return q(`/admin/mail/tickets/${e}`,{},!0)}async function lme(e,t,n){let r={text:t};return q(`/admin/mail/tickets/${e}/reply`,dd(r,{"Idempotency-Key":n}),!0)}async function ume(e,t,n){let r={text:t};return q(`/admin/mail/tickets/${e}/note`,dd(r,{"Idempotency-Key":n}),!0)}async function dme(e,t){let n={user_id:t};return q(`/admin/mail/tickets/${e}/assign`,dd(n),!0)}async function fme(e,t){return q(`/admin/mail/tickets/${e}/status`,dd({status:t}),!0)}async function pme(e,t){let n={summary:t};return q(`/admin/mail/tickets/${e}/summary`,pN(n),!0)}async function mme(e,t){let n=t?{reason:t}:{};return q(`/admin/mail/tickets/${e}/escalate`,dd(n),!0)}async function hme(e,t){return q(`/admin/mail/tickets/${e}/spam`,dd(t),!0)}async function gme(e={}){let t=new URLSearchParams;for(let[r,o]of Object.entries(e))if(o!==void 0&&o!=="")t.set(r,String(o));let n=t.toString();return q(`/admin/mail/blocklist${n?`?${n}`:""}`,{},!0)}async function yme(e){return q("/admin/mail/blocklist",dd(e),!0)}async function bme(e){return q(`/admin/mail/blocklist/${e}`,{method:"DELETE"},!0)}async function wme(){return q("/admin/mail/queues",{},!0)}async function _me(e,t){return q(`/admin/mail/queues/${encodeURIComponent(e)}`,pN(t),!0)}async function xme(e){return q(`/admin/mail/availability${e===void 0?"":`/${e}`}`,{},!0)}async function gN(e,t){return q(`/admin/mail/availability${t===void 0?"":`/${t}`}`,pN(e),!0)}async function vme(e){return q("/admin/mail/reprocess",dd({raw_key:e}),!0)}async function kme(e){return(await q(`/admin/users/by-id/${e}`,{},!0)).user.username}var dd=(e,t)=>({method:"POST",body:JSON.stringify(e),...t?{headers:t}:{}}),pN=(e)=>({method:"PUT",body:JSON.stringify(e)});var Qa=V(()=>{B0();nh();lo();Je()});async function Gr(e,t){return q(`/datasets/${e}/upload-credentials`,{method:"POST",body:JSON.stringify({duration_seconds:t})},!0)}async function yN(e,t){return q(`/datasets/${e}/download-credentials`,{method:"POST",body:JSON.stringify({duration_seconds:t})},!0)}async function Sme(e){return q(`/admin/datasets/${e}/files`,{},!0)}async function $me(e){let t,n=0,r=[],o=!0;while(o){let s=await q(`/admin/datasets/${e}/s3-lock`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({continuation_token:t})},!0);if(n+=s.locked,s.failed?.length)r.push(...s.failed);if(o=s.hasMore,t=s.continuation_token,o&&!t)throw new L(500,"S3 lock paginated response missing continuation_token; aborting to avoid infinite loop")}return{locked:n,failed:r}}async function Dme(e,t){let n=0,r=[],o=[];for(let s=0;s<t.length;s+=Eme){let i=t.slice(s,s+Eme),a=await q(`/admin/datasets/${e}/s3-lock`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({objects:i})},!0);if(!Array.isArray(a.objects))throw new L(500,"The s3-lock route did not name the objects it locked.");if(n+=a.objects.length,o.push(...a.objects),a.failed?.length)r.push(...a.failed)}return{locked:n,failed:r,objects:o}}var Eme=100;var Za=V(()=>{lo();Je()});async function RS(e){return q(`/datasets/${e}/ci/status`,{},!0)}async function Rme(e){return q(`/datasets/${e}/manifest`,{},!0)}async function CS(e,t){return q(`/datasets/${e}/manifest/${t}`,{},!0)}function Cme(e){let t=e;if(!t.status)t.status="active";else if(!["active","archived","deleted"].includes(t.status))throw Error(`Invalid dataset status: ${t.status}`);if(!t.visibility)t.visibility="private";else if(!["public","private"].includes(t.visibility))throw Error(`Invalid dataset visibility: ${t.visibility}`);return t}async function fd(e={}){let t=new URLSearchParams;if(e.mine)t.set("mine","true");if(e.search)t.set("search",e.search);if(e.modality)t.set("modality",e.modality);if(e.author)t.set("author",e.author);if(e.task)t.set("task",e.task);if(e.license)t.set("license",e.license);if(e.hasDoi)t.set("has_doi","true");if(e.hasHed)t.set("has_hed","1");if(e.hasZarr)t.set("has_zarr","1");if(e.hasZarrVerified)t.set("has_zarr_verified","1");if(e.dataComplete)t.set("data_complete","1");if(e.recent)t.set("recent",String(e.recent));if(e.sort)t.set("sort",e.sort);if(e.limit!=null)t.set("limit",String(e.limit));if(e.offset!=null)t.set("offset",String(e.offset));if(e.owner)t.set("owner",e.owner);if(e.facets)for(let[o,s]of Object.entries(e.facets))t.set(o,s);if(e.includeUnknown)t.set("include_unknown","1");let n=t.toString()?`?${t.toString()}`:"",r=await q(`/datasets${n}`,{},e.mine?!0:"optional");return r.datasets=r.datasets.map(Cme),r}async function Ame(e){return q(`/datasets/resolve/${e}`,{},"optional")}async function Ome(){return q("/datasets/facets",{signal:AbortSignal.timeout(5000)},"optional",Jv)}async function Tme(e,t={}){let n=new URLSearchParams({q:e});if(t.modality)n.set("modality",t.modality);if(t.limit)n.set("limit",String(t.limit));if(t.hasHed)n.set("has_hed","1");if(t.hasZarr)n.set("has_zarr","1");if(t.hasZarrVerified)n.set("has_zarr_verified","1");if(t.author)n.set("author",t.author);if(t.task)n.set("task",t.task);if(t.license)n.set("license",t.license);if(t.hasDoi)n.set("has_doi","true");if(t.dataComplete)n.set("data_complete","1");if(t.recent)n.set("recent",String(t.recent));if(t.facets)for(let[o,s]of Object.entries(t.facets))n.set(o,s);if(t.includeUnknown)n.set("include_unknown","1");return await q(`/datasets/search?${n.toString()}`,{},"optional",LQ)}async function Wn(e){let t=await q(`/datasets/${e}`,{},"optional");return Cme(t.dataset)}async function Lf(e){return q(`/datasets/${e}/versions`,{},!0)}async function Pme(e){try{let t=await Lf(e);if(!Array.isArray(t.versions))throw Error(`GET /datasets/${e}/versions answered without a versions list`);return t.versions.length>0}catch(t){if(t instanceof L&&t.statusCode===404&&!uk(t))return!1;throw t}}async function AS(e){return q("/datasets",{method:"POST",body:JSON.stringify(e)},!0)}async function Ime(e,t){return q(`/datasets/${e}/attestation`,{method:"PUT",body:JSON.stringify(t)},!0)}async function OS(e){return q(`/datasets/${e}/finalize`,{method:"POST"},!0)}async function bN(e){return q(`/datasets/${e}/request-access`,{method:"POST"},!0)}async function Nme(e,t){let n=t?`?status=${t}`:"";return q(`/datasets/${e}/access-requests${n}`,{},!0)}async function Fme(e,t){return q(`/datasets/${e}/access-requests/${t}/approve`,{method:"POST"},!0)}async function Mme(e,t){return q(`/datasets/${e}/access-requests/${t}/deny`,{method:"POST"},!0)}async function jme(e,t){return q(`/datasets/${e}/invite`,{method:"POST",body:JSON.stringify({username:t})},!0)}async function Lme(e){return q(`/datasets/${e}/collaborators`,{},!0)}async function qme(e,t){return q(`/admin/datasets/${e}/enrichment`,{method:"POST",body:JSON.stringify(t)},!0)}var DS;var ec=V(()=>{nh();lo();Je();DS=/^\d{4}-\d{4}-\d{4}-\d{3}[\dX]$/});function dhe(e,t){return e.filter((n)=>n.visibility==="public").map((n)=>n.dataset_id).filter((n)=>n.startsWith("nm")||n.startsWith("on")).filter((n)=>n!=="nm099999"&&!al.has(n)).filter((n)=>t.prefix?n.startsWith(t.prefix):!0).sort()}var al;var NS=V(()=>{al=new Set(["nm000103","nm000104","nm000105","nm000106","nm000107"])});function Kr(e){return e.replace(fhe,phe)}function phe(e){if(e===`
|
|
114
114
|
`)return"\\n";if(e==="\r")return"\\r";if(e==="\t")return"\\t";let t=e.codePointAt(0)??0;return t<=255?`\\x${t.toString(16).padStart(2,"0")}`:t<=65535?`\\u${t.toString(16).padStart(4,"0")}`:`\\u{${t.toString(16)}}`}function qb(e){return e.replace(fhe,(t)=>t===`
|
|
115
115
|
`||t==="\t"?t:phe(t))}function FS(e,t=", "){return e.map(Kr).join(t)}var fhe,tc=(e)=>Kr(e)===e;var qf=V(()=>{fhe=/[\p{Cc}\p{Cf}\u2028\u2029\u034f\u115f\u1160\u3164\uffa0\ufe00-\ufe0f\u{e0100}-\u{e01ef}]/gu});async function Ept(){try{let{exitCode:e,stderr:t}=await R(["ssh","-T","-o","BatchMode=yes","-o","ConnectTimeout=5","git@github.com"]),n=t.includes("successfully authenticated");if(!n)console.warn("SSH test to github.com failed:",{exitCode:e,stderr:t.trim().slice(0,500)});return{works:n,error:n?void 0:t.trim().slice(0,500)}}catch(e){let t=e instanceof Error?e.message:String(e);return console.warn("SSH test exception:",t),{works:!1,error:t}}}async function Bf(){try{let{stdout:e,exitCode:t,stderr:n}=await R(["gh","auth","token"],{sensitiveOutput:!0});if(t!==0)return console.warn("gh CLI returned non-zero exit code:",t),console.warn("stderr:",n),{token:null,error:`gh auth token failed: ${n.trim()||"unknown error"}`};if(!e.trim())return console.warn("gh auth token returned empty output"),{token:null,error:"gh CLI returned empty token"};return{token:e.trim()}}catch(e){let t=e instanceof Error?e.message:String(e);if(console.error("Failed to get GitHub token from gh CLI:",t),t.includes("ENOENT")||t.includes("not found"))return{token:null,error:"gh CLI not installed (command not found)"};return{token:null,error:`gh CLI error: ${t}`}}}async function MS(e){try{let{stdout:t,exitCode:n,stderr:r}=await R(["gh","api","user","--jq",".login"]);if(n!==0){if(r.includes("not logged in")||r.includes("auth login"))return{authenticated:!1,error:"gh CLI not authenticated. Run 'gh auth login' to authenticate."};return{authenticated:!1,error:`gh CLI error: ${r.trim()||"unknown error"}`}}let o=t.trim();if(!o)return{authenticated:!1,error:"gh CLI returned empty username"};if(e){let s=o.toLowerCase()===e.toLowerCase();return{authenticated:!0,username:o,matches:s,error:s?void 0:`gh CLI authenticated as '${o}', expected '${e}'`}}return{authenticated:!0,username:o}}catch(t){let n=t instanceof Error?t.message:String(t);if(n.includes("ENOENT")||n.includes("not found"))return{authenticated:!1,error:"gh CLI not installed. Install from https://cli.github.com/"};return{authenticated:!1,error:`Failed to verify gh CLI: ${n}`}}}async function jS(e){if(!/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/.test(e))return{accepted:!1,error:`Invalid repository format: ${e}`};let{stdout:t,exitCode:n,stderr:r}=await R(["gh","api","/user/repository_invitations"]);if(n!==0){if(r.includes("not logged in")||r.includes("auth login"))return{accepted:!1,error:"gh CLI not authenticated. Run 'gh auth login' to authenticate."};if(r.includes("API rate limit")||r.includes("403"))return{accepted:!1,error:"GitHub API rate limit exceeded. Please try again in a few minutes."};if(r.includes("ENOENT")||r.includes("not found"))return{accepted:!1,error:"gh CLI not installed. Install from https://cli.github.com/"};return{accepted:!1,error:`Failed to list invitations: ${r.trim()||"unknown error"}`}}let o=null;try{o=JSON.parse(t||"[]").find((l)=>l.repository.full_name===e)?.id??null}catch(a){let c=a instanceof Error?a.message:String(a);return console.error("Failed to parse GitHub invitations response:",c),console.error(" Raw response (first 500 chars):",(t||"").slice(0,500)),{accepted:!1,error:`Failed to parse GitHub API response: ${c}`}}if(!o){let{exitCode:a}=await R(["gh","api",`/repos/${e}`,"--silent"]);if(a===0)return{accepted:!0,alreadyCollaborator:!0};return{accepted:!1,error:`No pending invitation found for ${e}. You may need to accept it manually via GitHub.`}}let{exitCode:s,stderr:i}=await R(["gh","api","--method","PATCH",`/user/repository_invitations/${o}`]);if(s!==0)return{accepted:!1,error:`Failed to accept invitation: ${i.trim()||"unknown error"}`};return{accepted:!0}}async function nc(e,t,n="origin"){let r=t;if(process.env.GH_TOKEN&&t.startsWith("git@github.com:")){let o=process.env.GH_TOKEN.trim();if(!o||/\s/.test(o))return{success:!1,error:"GH_TOKEN environment variable is set but appears malformed (empty or contains whitespace)"};r=`https://github.com/${t.replace("git@github.com:","")}`,await R(["git","config","credential.https://github.com.helper",`!printf 'username=x-access-token\\npassword=${o}'`],{cwd:e,redact:[o]})}else if(t.startsWith("git@github.com:")){let o=t.replace("git@github.com:",""),s=await Bf();if(s.token)r=`https://github.com/${o}`,await R(["git","config","credential.https://github.com.helper",`!printf 'username=x-access-token\\npassword=${s.token}'`],{cwd:e,redact:[s.token]});else{let i=await Ept();if(i.works)r=t;else return{success:!1,error:`GitHub authentication not configured.
|
|
116
116
|
|
|
@@ -189,12 +189,12 @@ Privacy correction ${e}: ${r}. The checksums in the provenance file describe the
|
|
|
189
189
|
`)){if(!d.endsWith(".log.rmet"))continue;let f=d.slice(d.lastIndexOf("/")+1,-9);if(i.has(f))a.push([f,d])}let c=await a_t(e,n,a.map(([,d])=>d)),l=new Map;for(let[d,f]of a){let p=c.get(f);if(!p)continue;let m=rD(p,o);if(m.length>0)l.set(d,m)}return l}async function l_t(e,t,n=lw,r="git-annex"){let{stdout:o,stderr:s,exitCode:i}=await R(["git","show",`${r}:remote.log`],{cwd:e});if(i!==0&&!_we(s))throw Error(`could not read ${r}:remote.log to find ${n}'s object prefix: ${s.trim()||`exit ${i}`}`);for(let a of np(o).values())if(a.name===n&&a.fileprefix)return a.fileprefix;return`${t}/objects/`}function sD(e,t,n){let r=(d)=>n.filter(d).reduce((f,p)=>f+p.size,0),o=n.filter((d)=>d.action==="recovered").length,s=n.filter((d)=>d.action==="unrecoverable").length,i=n.filter((d)=>d.action==="failed").length,a=n.filter((d)=>d.action==="would-recover").length,c=t.length-n.length,l;if(t.length===0)l="nothing-missing";else if(i>0)l="failed";else if(a>0)l="would-recover";else if(o>0)l=s>0||c>0?"partial":"recovered";else l="unrecoverable";return{datasetId:e,action:l,measured:!0,missing:t.length,missingBytes:t.reduce((d,f)=>d+f.size,0),recovered:o,recoveredBytes:r((d)=>d.action==="recovered"),unrecoverable:s,unrecoverableBytes:r((d)=>d.action==="unrecoverable"),failed:i,keys:n}}async function u_t(e,t,n){let r={...sD(e,[],[]),measured:!1,action:"failed"};if(!s_t.test(e))return{...r,error:`"${e}" is not a dataset id, and it would become a directory this deletes`};let o=o_t(n.workRoot,e);i6(o,{recursive:!0,force:!0});let s=n.originUrl??`https://github.com/nemarDatasets/${e}.git`,i=await BF(s,o,{partial:!1,description:"fleet-content-recovery"});if(i)return i6(o,{recursive:!0,force:!0}),{...r,error:i};try{let a=await i_t(o),c=await t(e),l=[...a.keys()].filter((b)=>!cr(b,c));if(l.length===0)return sD(e,[],[]);let d=await c_t(o,l),f;if(e.startsWith("on")){let b=`ds${e.slice(2)}/`;f={bucket:rp,prefix:b,index:await mwe({bucket:rp,prefix:b})}}let p=l.map((b)=>gwe({key:b,paths:a.get(b)??[],pins:d.get(b)??[],upstream:f})).sort((b,_)=>b.size-_.size),m=n.limit?p.slice(0,n.limit):p,h=await l_t(o,e,n.remoteName),g=0,y=await uw(m,n.concurrency??8,async(b)=>{let _=await wwe({entry:b,destBucket:"nemar",destKey:`${h}${b.key}`,apply:n.apply===!0,env:n.env});return n.onKey?.(_,++g,m.length),_});return sD(e,p,y)}catch(a){return{...r,error:a instanceof Error?a.message:String(a)}}finally{i6(o,{recursive:!0,force:!0})}}async function xwe(e,t,n){let r=[...new Set(e)],o=[],s=0;for(let l of r){let d;try{d=await u_t(l,t,n)}catch(f){d={...sD(l,[],[]),measured:!1,action:"failed",error:f instanceof Error?f.message:String(f)}}o.push(d),n.onDataset?.(d,++s,r.length)}let i={"nothing-missing":0,recovered:0,"would-recover":0,partial:0,unrecoverable:0,failed:0},a=0,c=0;for(let l of o)i[l.action]++,a+=l.recovered,c+=l.recoveredBytes;return{outcomes:o,tally:i,recoveredKeys:a,recoveredBytes:c}}var s_t,rp="openneuro.org";var iD=V(()=>{oD();lc();qt();Pr();cs();s_t=/^[a-z]{2}[0-9]{6}$/});function f_t(e){return e.field.startsWith("patient")&&Dwe.has(e.kind)||e.field.startsWith("recording")&&Rwe.has(e.kind)}function vwe(e,t,n){let r=t.end-t.start;e.fill(32,t.start,t.end);for(let o=0;o<Math.min(n.length,r);o++)e[t.start+o]=n.charCodeAt(o)}function p_t(e){let t=/^startdate\s+(\d{2}-[A-Za-z]{3}-\d{4})(?=\s|$)/i.exec(e);return`Startdate ${t?t[1].toUpperCase():"X"} X X X`}function m_t(e){if(e.length<vt)throw new Dd("header-too-short");if(!vd(e))throw new Dd("not-edf");let t=e.slice(0,vt),n=kd(t),r=[];if(n.some((o)=>o.field.startsWith("patient")&&Dwe.has(o.kind)))vwe(t,Swe,d_t),r.push("patient");if(n.some((o)=>o.field.startsWith("recording")&&Rwe.has(o.kind))){let{recording:o}=K$(t);vwe(t,$we,p_t(o)),r.push("recording")}return{header:t,changed:r.length>0,fields:r}}function h_t(e,t){let n=[];if(e.length<vt||t.length<vt)return{ok:!1,reasons:["header-too-short"]};let r=(s,i)=>{for(let a=s;a<i;a++)if(e[a]!==t[a])return!1;return!0};if(!r(0,Swe.start))n.push("bytes-before-patient-changed");if(!r($we.end,vt))n.push("bytes-after-recording-changed");if(vd(e)!==vd(t))n.push("file-family-changed");if(kd(t).filter(f_t).length>0)n.push("identifying-content-remains");return{ok:n.length===0,reasons:n}}function w_t(e){let t=GF(e);if(!t)return null;let n=new Set;if(t.startdate)for(let r of g_t)n.add(r);if(t.recording)for(let r of b_t)n.add(t.recording.start+r);return n}function a6(e){if(e.length<vt)throw new Dd("header-too-short");let t=e.subarray(0,vt),n=GF(t);if(!n)throw new Dd("not-edf");let r=t.slice(),o={header:r,changed:!1,fields:[]},s=n.recording;if(s){let a=String.fromCharCode(...r.subarray(s.start,s.end));if(!s.wholeSlot||!y_t.test(a))return o}let i=[];if(s){r[s.start]=48,r[s.start+1]=49;for(let a=0;a<3;a++){let c=r[s.start+3+a],l="JAN".charCodeAt(a);r[s.start+3+a]=c>=97&&c<=122?l|32:l}i.push("recording.startdate")}if(n.startdate)r[168]=48,r[169]=49,r[171]=48,r[172]=49,i.push("startdate");if(i.length===0)return o;if(!Cwe(t,r).ok)throw new aD;return{header:r,changed:!0,fields:i}}function Cwe(e,t){if(e.length<vt||t.length<vt)return{ok:!1,reasons:["header-too-short"]};let n=w_t(e);if(!n)return{ok:!1,reasons:["not-edf"]};let r=[];for(let i=0;i<vt;i++)if(e[i]!==t[i]&&!n.has(i)){r.push("bytes-outside-dates-changed");break}if(vd(e)!==vd(t))r.push("file-family-changed");let o=kd(t.subarray(0,vt));if(o.some((i)=>kwe.has(i.kind)))r.push("acquisition-date-remains");let s=(i)=>i.filter((a)=>!kwe.has(a.kind)).map((a)=>`${a.kind}\x00${a.severity}\x00${a.field}\x00${a.shape}`).sort().join(`
|
|
190
190
|
`);if(s(o)!==s(kd(e.subarray(0,vt))))r.push("other-findings-changed");return{ok:r.length===0,reasons:r}}function cD(e,t){let n;try{n=m_t(e)}catch(a){if(a instanceof Dd)return{ok:!1,reason:"not-edf"};throw a}if(n.changed&&!h_t(e,n.header).ok)return{ok:!1,reason:"scrub-unverified"};let r=n.header,o=!1,s=!1;if(t)try{let a=a6(n.header);if(a.changed&&Cwe(n.header,a.header).ok)r=a.header,o=!0;else if(a.changed)s=!0}catch{s=!0}let i=kd(r).some((a)=>Qf.has(a.kind));return{ok:!0,header:r,change:{scrub:n.changed,dates:o,datesLeft:i,datesUnproven:s}}}function lD(e){let t=e.length>=3&&e[0]===239&&e[1]===187&&e[2]===191,n;try{n=new TextDecoder("utf-8",{fatal:!0}).decode(e)}catch{return{status:"unreadable",values:0}}let r=n.split(""),o=new Set,s=0;for(let d of JF(n)){if(KF(d.value).length===0)continue;let f=d.index+(d.value.length-d.value.trimStart().length);for(let[p,m]of[[5,"0"],[6,"1"],[8,"0"],[9,"1"]])r[f+p]=m,o.add(f+p);s++}if(s===0)return{status:"clean",values:0};let i=r.join(""),a=i.length===n.length;for(let d=0;a&&d<i.length;d++)if(i[d]!==n[d]&&!(o.has(d)&&/\d/.test(n[d])))a=!1;if(!a||J$(i).length!==0)throw new aD;let c=new TextEncoder().encode(i),l=t?new Uint8Array([239,187,191,...c]):c;if(l.length!==e.length)throw new aD;return{status:"normalized",bytes:l,values:s}}function __t(e){return Xf({[e]:"x"}).some((t)=>t.severity==="identifier")}function x_t(e,t){let n=(a)=>{let c=a;while(c<e.length&&`
|
|
191
191
|
\r`.includes(e[c]))c++;return c},r=(a)=>{let c=a+1;while(e[c]!=='"'){if(c>=e.length)throw Error("string");c+=e[c]==="\\"?2:1}return c+1},o=(a)=>{let c=e[a];if(c==="{"){let l=n(a+1);if(e[l]==="}")return l+1;for(;;){if(e[l]!=='"')throw Error("key");let d=r(l),f=JSON.parse(e.slice(l,d));if(l=n(d),e[l]!==":")throw Error("colon");let p=n(l+1),m=s(p);if(!t({key:f,start:p,end:m}))o(p);if(l=n(m),e[l]===","){l=n(l+1);continue}if(e[l]!=="}")throw Error("object");return l+1}}if(c==="["){let l=n(a+1);if(e[l]==="]")return l+1;for(;;){if(l=n(o(l)),e[l]===","){l=n(l+1);continue}if(e[l]!=="]")throw Error("array");return l+1}}return s(a)},s=(a)=>{let c=e[a];if(c==='"')return r(a);if(c==="{"||c==="["){let d=0,f=a;while(f<e.length){let p=e[f];if(p==='"'){f=r(f);continue}if(p==="{"||p==="[")d++;else if(p==="}"||p==="]"){if(d--,d===0)return f+1}f++}throw Error("unterminated")}let l=a;while(l<e.length&&!`,]}
|
|
192
|
-
\r`.includes(e[l]))l++;if(l===a)throw Error("scalar");return l};if(n(o(n(0)))!==e.length)throw Error("trailing")}function Ewe(e){let t=[];return x_t(e,(n)=>{if(!__t(n.key))return!1;if(!gw(JSON.parse(e.slice(n.start,n.end))))return!1;return t.push(n),!0}),t}function jg(e){let t=e.length>=3&&e[0]===239&&e[1]===187&&e[2]===191,n,r;try{n=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(t?e.subarray(3):e),JSON.parse(n),r=Ewe(n)}catch{return{status:"unreadable",blanked:0}}if(r.length===0)return{status:"clean",blanked:0};let o=n;for(let c of[...r].sort((l,d)=>d.start-l.start))o=`${o.slice(0,c.start)}""${o.slice(c.end)}`;let s;try{let c=JSON.parse(o);s=Ewe(o).length+Xf(c).filter((l)=>l.severity==="identifier").length}catch{throw new op}if(s!==0)throw new op;let i=new TextEncoder().encode(o);return{status:"blanked",bytes:t?new Uint8Array([239,187,191,...i]):i,blanked:r.length}}var Swe,$we,d_t="X X X X",Dd,Dwe,Rwe,kwe,g_t,y_t,b_t,aD,op;var _w=V(()=>{ml();Swe={start:8,end:88},$we={start:88,end:168};Dd=class Dd extends Error{reason;constructor(e){super(`scrub refused: ${e}`);this.reason=e;this.name="ScrubRefused"}};Dwe=new Set(["edf-patient-name","edf-patient-code","edf-patient-recordnumber","edf-patient-freetext","edf-patient-birthdate","edf-patient-nonascii","edf-patient-age"]),Rwe=new Set(["edf-recording-freetext","edf-recording-technician","edf-recording-nonascii","edf-patient-birthdate"]);kwe=new Set(["edf-startdate","edf-recording-startdate"]),g_t=[168,169,171,172],y_t=/^\d{2}-[A-Za-z]{3}-\d{4}$/,b_t=[0,1,3,4,5];aD=class aD extends Error{constructor(){super("date normalization unverified");this.name="DateNormalizationUnverified"}};op=class op extends Error{constructor(){super("json blank unverified");this.name="JsonBlankUnverified"}}});var uD="[openneuro-mirror-lag]",c6="[openneuro-upstream-moved]",l6="[nemar-annex-uuid-conflict]";var dD="[openneuro-upstream-inaccessible]",Awe="[nemar-identifier-scrub]",hl;var u6=V(()=>{hl=class hl extends Error{marker;constructor(e,t){super(`${e} ${t}`);this.marker=e;this.name="ImportRefused"}}});function Ir(){if(!ze())console.log(u.red("Error: Not authenticated")),console.log("Run 'nemar auth login' first"),process.exit(1)}function go(e,t,n){e.fail(t),console.log(u.red(` ${G(n)}`)),Ab(t)}function d6(e){let{filesDownloaded:t,filesUnavailable:n,unavailablePaths:r}=e;console.log(u.yellow(`Downloaded ${t} file(s); ${n} file(s) are not available from the archive.`));for(let s of r)console.log(u.dim(` ${s}`));let o=r.length;if(n>o&&o>0)console.log(u.dim(` ... and ${n-o} more`));console.log(u.dim(" This is not a problem with your connection or credentials.")),console.log(u.dim(" Per-file detail, including why each file is missing:")),console.log(u.dim(" .nemar/availability-report.json"))}function f6(e=0){let t=e>0?` ${e} of the fetched file(s) declare no size in their key and could be verified by neither hash nor size.`:"";console.error(u.yellow(`Note: --no-verify skipped checksum verification. Sizes were still checked; file contents were not.${t}`))}function xw(e){for(let t of e)console.error(u.red(` ${t}`))}var sp=V(()=>{He();
|
|
192
|
+
\r`.includes(e[l]))l++;if(l===a)throw Error("scalar");return l};if(n(o(n(0)))!==e.length)throw Error("trailing")}function Ewe(e){let t=[];return x_t(e,(n)=>{if(!__t(n.key))return!1;if(!gw(JSON.parse(e.slice(n.start,n.end))))return!1;return t.push(n),!0}),t}function jg(e){let t=e.length>=3&&e[0]===239&&e[1]===187&&e[2]===191,n,r;try{n=new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(t?e.subarray(3):e),JSON.parse(n),r=Ewe(n)}catch{return{status:"unreadable",blanked:0}}if(r.length===0)return{status:"clean",blanked:0};let o=n;for(let c of[...r].sort((l,d)=>d.start-l.start))o=`${o.slice(0,c.start)}""${o.slice(c.end)}`;let s;try{let c=JSON.parse(o);s=Ewe(o).length+Xf(c).filter((l)=>l.severity==="identifier").length}catch{throw new op}if(s!==0)throw new op;let i=new TextEncoder().encode(o);return{status:"blanked",bytes:t?new Uint8Array([239,187,191,...i]):i,blanked:r.length}}var Swe,$we,d_t="X X X X",Dd,Dwe,Rwe,kwe,g_t,y_t,b_t,aD,op;var _w=V(()=>{ml();Swe={start:8,end:88},$we={start:88,end:168};Dd=class Dd extends Error{reason;constructor(e){super(`scrub refused: ${e}`);this.reason=e;this.name="ScrubRefused"}};Dwe=new Set(["edf-patient-name","edf-patient-code","edf-patient-recordnumber","edf-patient-freetext","edf-patient-birthdate","edf-patient-nonascii","edf-patient-age"]),Rwe=new Set(["edf-recording-freetext","edf-recording-technician","edf-recording-nonascii","edf-patient-birthdate"]);kwe=new Set(["edf-startdate","edf-recording-startdate"]),g_t=[168,169,171,172],y_t=/^\d{2}-[A-Za-z]{3}-\d{4}$/,b_t=[0,1,3,4,5];aD=class aD extends Error{constructor(){super("date normalization unverified");this.name="DateNormalizationUnverified"}};op=class op extends Error{constructor(){super("json blank unverified");this.name="JsonBlankUnverified"}}});var uD="[openneuro-mirror-lag]",c6="[openneuro-upstream-moved]",l6="[nemar-annex-uuid-conflict]";var dD="[openneuro-upstream-inaccessible]",Awe="[nemar-identifier-scrub]",hl;var u6=V(()=>{hl=class hl extends Error{marker;constructor(e,t){super(`${e} ${t}`);this.marker=e;this.name="ImportRefused"}}});function Ir(){if(!ze())console.log(u.red("Error: Not authenticated")),console.log("Run 'nemar auth login' first"),process.exit(1)}function go(e,t,n){e.fail(t),console.log(u.red(` ${G(n)}`)),Ab(t)}function d6(e){let{filesDownloaded:t,filesUnavailable:n,unavailablePaths:r}=e;console.log(u.yellow(`Downloaded ${t} file(s); ${n} file(s) are not available from the archive.`));for(let s of r)console.log(u.dim(` ${s}`));let o=r.length;if(n>o&&o>0)console.log(u.dim(` ... and ${n-o} more`));console.log(u.dim(" This is not a problem with your connection or credentials.")),console.log(u.dim(" Per-file detail, including why each file is missing:")),console.log(u.dim(" .nemar/availability-report.json"))}function f6(e=0){let t=e>0?` ${e} of the fetched file(s) declare no size in their key and could be verified by neither hash nor size.`:"";console.error(u.yellow(`Note: --no-verify skipped checksum verification. Sizes were still checked; file contents were not.${t}`))}function xw(e){for(let t of e)console.error(u.red(` ${t}`))}var sp=V(()=>{He();Je();gr();dn()});import{existsSync as Owe,mkdirSync as v_t,readFileSync as k_t,writeFileSync as E_t}from"fs";import{join as Twe}from"path";function p6(e){return Twe(e,S_t)}function Pwe(e){return Twe(p6(e),$_t)}function D_t(e){if(!e||typeof e!=="object")return!1;let t=e;return typeof t.dataset_id==="string"&&t.dataset_id.length>0&&typeof t.github_url==="string"&&typeof t.ssh_url==="string"&&typeof t.s3_prefix==="string"&&typeof t.s3_config==="object"&&t.s3_config!==null&&typeof t.created_at==="string"}function m6(e){let t=Pwe(e);if(!Owe(t))return null;try{let n=k_t(t,"utf-8"),r=JSON.parse(n);if(!D_t(r))return console.error(`Warning: Local config at ${t} is invalid or corrupted`),console.error(` Delete it to start fresh: rm -rf ${p6(e)}`),null;return r}catch(n){let r=n instanceof Error?n.message:String(n);return console.error(`Warning: Could not read local config at ${t}`),console.error(` Error: ${r}`),null}}function h6(e,t){let n=p6(e),r=Pwe(e);try{if(!Owe(n))v_t(n,{recursive:!0});return E_t(r,JSON.stringify(t,null,2)),!0}catch(o){let s=o instanceof Error?o.message:String(o);return console.error(`Warning: Could not save local config to ${r}`),console.error(` Error: ${s}`),console.error(" Resume capability will not be available for this dataset."),!1}}function Iwe(e){let t=m6(e);if(!t)return!1;return t.last_upload_at=new Date().toISOString(),h6(e,t)}var S_t=".nemar",$_t="config.json";var fD=()=>{};import{spawnSync as R_t}from"child_process";async function Rs(e,t,n){let r=n==="local"?["git","config","--local","--null","--get-all",t]:["git","config","--null","--get-all",t];try{let o=await R(r,{cwd:e});if(o.exitCode===1&&o.stderr.trim()==="")return{values:[]};if(o.exitCode!==0)return{error:o.stderr.trim()||`git config exited ${o.exitCode}`};return{values:o.stdout.split("\x00").slice(0,-1)}}catch(o){return{error:o instanceof Error?o.message:String(o)}}}async function Lg(e,t){try{let n=await R(["git","config","--local",...t],{cwd:e});if(n.exitCode===0)return;if(t[0]==="--unset-all"&&n.exitCode===jwe)return;return n.stderr.trim()||`git config exited ${n.exitCode}`}catch(n){return n instanceof Error?n.message:String(n)}}async function hD(e,t){let n=(c,l=!1)=>({error:c,filterOff:l}),r=await Rs(e,fr,"local");if("error"in r)return n(r.error);if(r.values.includes(""))return n(Lwe,!0);if(r.values.length===0){let c=await Lg(e,[fr,t]);if(c)return n(c)}let o=await Lg(e,["--unset-all",pi]);if(o)return n(o);let s=await Rs(e,fr,"local");if("error"in s)return n(s.error);let i=r.values.length===0?[t]:r.values;if(JSON.stringify(s.values)!==JSON.stringify(i))return n(`${fr} reads back as ${JSON.stringify(s.values)}, not ${JSON.stringify(i)}`);let a=await Rs(e,pi,"local");if("error"in a)return n(a.error);if(a.values.length>0)return n(`${pi} is still set`);return}function mD(e){return`'${e.replace(/'/g,"'\\''")}'`}function P_t(e,t){if(!tc(e)||!tc(t))return"Run the upload again, which puts it back first.";return`Run the upload again, which puts it back first, or by hand: git -C ${mD(e)} config ${fr} ${mD(t)} && git -C ${mD(e)} config --unset-all ${pi}`}function vw(e,t,n,r){let o=r==="per-file"?"Until it is back, git uses git-annex's per-file filters (no other filter process was set when it was taken out), which store files the same way but start one git-annex process per file.":"Until it is back, git may not run git-annex's filter at all, so do not run git add or git commit in this repository before it is restored.";return`Could not put git-annex's filter process back into ${Kr(e)}'s configuration (${Kr(n)}). ${o} ${P_t(e,t)}`}async function Nwe(e){let t=await Rs(e,fr,"all");if(!("values"in t)||t.values.length>0)return"unchecked";let n=await Rs(e,"filter.annex.clean","all");if(!("values"in n))return"unchecked";let r=n.values[n.values.length-1];return r!==void 0&&g6(r)?"per-file":"unchecked"}async function qwe(e){let t=await Rs(e,pi,"local");if("error"in t)return{status:"error",error:`Could not check whether an earlier upload left git-annex's filter process out of the configuration (${Kr(t.error)}). Run the upload again; if git keeps failing, the repository needs attention.`};if(t.values.length===0)return{status:"unchanged"};let n=t.values[t.values.length-1],r=await Rs(e,fr,"local");if("error"in r)return{status:"error",error:vw(e,n,r.error,await Nwe(e))};if(r.values.includes(""))return{status:"error",error:vw(e,n,Lwe,"unchecked")};if(r.values.length>0){let s=await Lg(e,["--unset-all",pi]);if(s)return{status:"warning",warning:Bwe(e,s)};return{status:"unchanged"}}let o=await hD(e,n);if(o)o=await hD(e,n);if(o){let s=o.filterOff?"unchecked":await Nwe(e);return{status:"error",error:vw(e,n,o.error,s)}}return{status:"restored"}}function Bwe(e,t){let n=tc(e)?` Remove it with: git -C ${mD(e)} config --unset-all ${pi}`:"";return`Could not remove a leftover ${pi} setting (${Kr(t)}). git-annex's filter process itself is set, so nothing is out of the configuration; git-annex's next restage removes the setting too.${n}`}function Fwe(e,t){let n=(i)=>R_t("git",["config","--local",...i],{cwd:e,stdio:["ignore","pipe","pipe"],timeout:C_t}),r=n(["--null","--get-all",fr]);if(r.error)return r.error.message;if(!(r.status===0?(r.stdout?.toString()??"").split("\x00").slice(0,-1):[]).some((i)=>i!=="")){let i=n(["--replace-all",fr,t]);if(i.error)return i.error.message;if(i.status!==0)return i.stderr?.toString().trim()||`git config exited ${i.status}`}let s=n(["--unset-all",pi]);if(s.error)return s.error.message;if(s.status!==0&&s.status!==jwe)return s.stderr?.toString().trim()||`git config exited ${s.status}`;return}function I_t(e,t,n){function r(){for(let s of Ub)process.removeListener(s,o)}function o(s){let i=Date.now()+A_t,a=Fwe(e,t);while(a&&Date.now()<i)JS(O_t),a=Fwe(e,t);if(NN(),a)FN(`
|
|
193
193
|
${vw(e,t,a,n())}
|
|
194
194
|
`);r(),process.kill(process.pid,s)}for(let s of Ub)process.on(s,o);return r}async function N_t(e,t){let n=[];try{for(let r of fo(t)){let o=await R(["git","--literal-pathspecs","ls-files","-z","--",...r],{cwd:e});if(o.exitCode!==0)return{error:o.stderr.trim()||"git ls-files failed"};n.push(...o.stdout.split("\x00").filter(Boolean))}}catch(r){return{error:r instanceof Error?r.message:String(r)}}return{paths:n}}function g6(e){return/\bgit-annex\b.*\bsmudge\b.*--clean\b/.test(e)}async function F_t(e,t,n,r){if(t!==void 0){let a=await Lg(e,["--unset-all",fr]);if(a)return`could not unset ${fr}: ${a}`}r?.(n);let o=await Rs(e,fr,"all");if("error"in o)return`could not check ${fr}: ${o.error}`;if(o.values.length>0)return`a filter process is set once this repository's value is out (${fr} came back, or is set in another scope)`;let s=await Rs(e,"filter.annex.clean","all");if("error"in s)return`could not check filter.annex.clean: ${s.error}`;let i=s.values[s.values.length-1];if(i===void 0||!g6(i))return"filter.annex.clean is no longer git-annex's clean filter";return}async function Uwe(e,t,n={}){if(t.length===0)return{status:"primed",primed:0};let r=await N_t(e,t);if("error"in r)return{status:"skipped",reason:`could not read the index: ${r.error}`};if(r.paths.length===0)return{status:"primed",primed:0};let o=await Rs(e,"filter.annex.clean","all");if("error"in o)return{status:"error",error:pD(o.error)};let s=o.values[o.values.length-1];if(s===void 0||!g6(s))return{status:"skipped",reason:"filter.annex.clean is not git-annex's clean filter"};let i=await Rs(e,fr,"local");if("error"in i)return{status:"error",error:pD(i.error)};let a=await Rs(e,fr,"all");if("error"in a)return{status:"error",error:pD(a.error)};if(i.values.length>1||a.values.length>i.values.length||a.values.some((m)=>m===""))return{status:"skipped",reason:`${fr} is set outside this repository's configuration, more than once, or empty`};let c=i.values[0],l="unchecked",d=c===void 0?()=>{}:I_t(e,c,()=>l),f=0,p=()=>f>0?{primed:f}:{};try{let m=fo(r.paths,n.chunkPaths??T_t);for(let[h,g]of m.entries()){if(c!==void 0){if(h>0){let k=await Rs(e,fr,"local");if("error"in k)return{status:"error",error:pD(k.error)};if(k.values.length!==1||k.values[0]!==c)return{status:"skipped",reason:`${fr} changed while the priming ran`,...p()}}let x=await Lg(e,[pi,c]);if(x){let k=await Lg(e,["--unset-all",pi]),v=k?` ${Bwe(e,k)}`:"";return{status:"skipped",reason:`could not record ${pi}: ${x}.${v}`,...p()}}}l="unchecked";let y,b,_;try{if(y=await F_t(e,c,h,n.onSuspended),!y){l="per-file";let x=await R(["git","--literal-pathspecs","add","--refresh","--",...g],{cwd:e});if(x.exitCode!==0)b=x.stderr.trim()||`git add --refresh exited ${x.exitCode}`}}finally{if(c!==void 0){if(_=await hD(e,c),_)_=await hD(e,c)}}if(_&&c!==void 0)return{status:"error",error:vw(e,c,_.error,_.filterOff?"unchecked":l)};if(y)return{status:"skipped",reason:y,...p()};if(b)return{status:"skipped",reason:`git add --refresh failed: ${b}`,...p()};f+=g.length,n.onProgress?.(f,r.paths.length)}}finally{d()}return{status:"primed",primed:f}}function pD(e){return`Could not read the repository's git-annex filter configuration (${Kr(e)}). Run the upload again; if git keeps failing, the repository needs attention.`}var fr="filter.annex.process",pi="filter.annex.process-temp-disabled",Mwe=1073741824,C_t=5000,A_t=2500,O_t=100,T_t=100,jwe=5,Lwe;var y6=V(()=>{qf();ii();ji();qt();Lwe=`${fr} is empty in this repository's configuration, which turns git-annex's filter off`});import{createHash as M_t}from"crypto";import{existsSync as b6,mkdirSync as j_t,readFileSync as L_t,unlinkSync as q_t,writeFileSync as B_t}from"fs";import{join as Hwe}from"path";function Vwe(e,t){let n=[...e].sort(([o,s],[i,a])=>{if(o!==i)return o<i?-1:1;if(s===a)return 0;return s<a?-1:1}),r=M_t("sha256");r.update(t).update("\x00");for(let[o,s]of n)r.update(o).update("\x00").update(s).update("\x00");return r.digest("hex")}function Gwe(e,t,n,r=Date.now()){let o=e.remote_checked_at;if(typeof o!=="string")return!1;if(e.remote_checked_count!==t)return!1;if(e.remote_checked_fingerprint!==n)return!1;let s=Date.parse(o);if(Number.isNaN(s))return!1;return s<=r&&r-s<zwe}function Wwe(e,t,n,r=Date.now()){e.remote_checked_at=new Date(r).toISOString(),e.remote_checked_count=t,e.remote_checked_fingerprint=n}function w6(e){return Hwe(e,Kwe,U_t)}function Jwe(e,t,n){let r=new Date().toISOString(),o={dataset_id:t,started_at:r,updated_at:r,files:{},completed_steps:[]};for(let s of n)o.files[s.path]={status:"pending",size:s.size,mtimeMs:s.mtimeMs,updated_at:r};return Nr(e,o),o}function Ywe(e){let t=w6(e);if(!b6(t))return null;try{let n=L_t(t,"utf-8"),r=JSON.parse(n);if(!W_t(r))return console.warn(`Warning: Upload progress file is invalid or corrupted (${t})`),console.warn(" Use --restart to clear progress and start fresh."),null;return r}catch(n){let r=n instanceof Error?n.message:String(n);return console.warn(`Warning: Could not read upload progress (${t}): ${r}`),console.warn(" Use --restart to clear progress and start fresh."),null}}function Nr(e,t){let n=Hwe(e,Kwe),r=w6(e);try{if(!b6(n))j_t(n,{recursive:!0});return t.updated_at=new Date().toISOString(),B_t(r,JSON.stringify(t,null,2)),!0}catch(o){let s=o instanceof Error?o.message:String(o);return console.warn(`Warning: Could not save upload progress (${r}): ${s}`),console.warn(" If the upload is interrupted, resume may not work correctly."),!1}}function Xwe(e,t,n){let r=e.files[t];if(r){if(r.status="uploaded",r.updated_at=new Date().toISOString(),r.error=void 0,n)r.size=n.size,r.mtimeMs=n.mtimeMs}}function gl(e,t){if(!e.completed_steps.includes(t))e.completed_steps.push(t)}function Hi(e,t){return e.completed_steps.includes(t)}function yl(e,t){e.completed_steps=e.completed_steps.filter((n)=>n!==t)}function Qwe(e,t){return t.some((n)=>Zwe(e.files[n.path],n))}function Zwe(e,t){if(!e)return!0;if(e.size!==t.size)return!0;if(t.mtimeMs!==void 0&&e.mtimeMs!==t.mtimeMs)return!0;return!1}function e_e(e,t){return t.filter((n)=>{let r=e.files[n.path];return!r||r.status!=="uploaded"||Zwe(r,n)})}function Ew(e){let t=w6(e);try{if(b6(t))q_t(t);return!0}catch(n){let r=n instanceof Error?n.message:String(n);return console.warn(`Warning: Could not clear upload progress (${t}): ${r}`),!1}}function t_e(e){let t=Object.values(e.files),n=0,r=0,o=0;for(let s of t)switch(s.status){case"uploaded":n++;break;case"failed":r++;break;case"pending":o++;break}return{total:t.length,uploaded:n,failed:r,pending:o,completedSteps:e.completed_steps}}function W_t(e){return G_t.safeParse(e).success}var zwe=21600000,kw,Kwe=".nemar",U_t="upload-progress.json",H_t,z_t,V_t,G_t;var gD=V(()=>{Ko();kw=`${zwe/3600000} hours`;H_t=Ft(["pending","uploaded","failed"]),z_t=Ft(["tracking","s3_upload","url_registration","metadata_write","dataset_save","github_push","ci_deploy"]),V_t=ee({status:H_t,size:j().nonnegative(),mtimeMs:j().nonnegative().optional(),updated_at:S()}),G_t=ee({dataset_id:S().min(1),started_at:S(),updated_at:S(),files:Ks(S(),V_t),completed_steps:he(z_t),remote_checked_at:_u().optional(),remote_checked_count:_u().optional(),remote_checked_fingerprint:_u().optional()})});function yD(e){if(e<1000)return`about ${Math.max(1,Math.round(e))} ms`;let t=Math.round(e/60000);if(t>0)return`about ${t} minute${t===1?"":"s"}`;let n=Math.round(e/1000);return`about ${n} second${n===1?"":"s"}`}function Sw(e,t){let n=e.text;if(e.info(u.yellow(t)),e.isEnabled)e.start(n);return e}var _6=V(()=>{He()});function v6(e,t,n=Date.now()){let r=t?Date.parse(t):Number.NaN,o=Number.isFinite(r)?r:n+3300000;return{credentials:e,expiresAtMs:o}}function k6(e,t,n={}){let r=n.maxFiles??200,o=n.maxBytes??53687091200,s=[],i=[],a=0;for(let c of e){let l=t.get(c);if(l===void 0){if(i.length>0)s.push(i),i=[],a=0;s.push([c]);continue}if(i.length>0&&(i.length>=r||a+l>o))s.push(i),i=[],a=0;i.push(c),a+=l}if(i.length>0)s.push(i);return s}function E6(e){if(!e)return!1;return/ExpiredToken|RequestExpired|token (has|is) expired|security token included in the request is (expired|invalid)|InvalidToken|InvalidAccessKeyId/i.test(e)}var n_e=1200000,r_e=48,x6=2;function fn(e){return{status:"ok",value:e}}var Ne,o_e;var ip=V(()=>{Ne={status:"fail"},o_e={status:"stop"}});import{existsSync as K_t,readFileSync as J_t,writeFileSync as Y_t}from"fs";import{resolve as X_t}from"path";function a_e(e){return["Warning: local git-annex tracking has produced no stdout or stderr for",`${yD(e)}. git-annex is still running and may be reading a large file.`,"Wait, or interrupt and rerun the upload; earlier completed batches remain resumable."].join(" ")}function Q_t(e,t){if(!e)return console.log(u.yellow(` ${t}`)),null;return Sw(e,t)}async function s_e(e,t,n,r,o={}){let s=t.filter((c)=>c.size>=n).map((c)=>c.path);if(s.length===0)return!0;let i=D({text:r==="before"?"Checking large data files an earlier run left in the index...":`Recording index stat data for ${zi(s.length)} of ${S6(n)} or more...`,...o.stream?{stream:o.stream}:{}}).start(),a=await Uwe(e,s,{...o.onSuspended?{onSuspended:o.onSuspended}:{},...o.chunkPaths===void 0?{}:{chunkPaths:o.chunkPaths},onProgress:(c,l)=>{i.text=`Recording index stat data for large data files (${c.toLocaleString("en-US")} of ${l.toLocaleString("en-US")})...`}});if(a.status==="error")return i.fail(a.error),!1;if(a.status==="skipped")return i.warn(Z_t(a.reason,a.primed)),!0;if(a.primed===0)return i.stop(),!0;return i.succeed(r==="before"?`Checked ${zi(a.primed)} of ${S6(n)} or more that an earlier run left in the index; the add need not re-read the unchanged ones`:`Checked ${zi(a.primed)} of ${S6(n)} or more against the index; git need not re-read the unchanged ones`),!0}function Z_t(e,t){return`${t&&t>0?`Index stat data was recorded for ${zi(t)} before it stopped; the other large data files`:"Large data files"} will be re-read by git through git-annex filter-process (${e})`}function S6(e){let t=["bytes","KiB","MiB","GiB","TiB"],n=e,r=0;while(n>=1024&&Number.isInteger(n/1024)&&r<t.length-1)n/=1024,r+=1;return`${n.toLocaleString("en-US")} ${t[r]}`}function ext(e){let t=e?.match(/github\.com\/([a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+)/);return t?t[1].replace(/\.git$/,""):null}function txt(e){try{let t=X_t(e,".gitignore"),n="";if(K_t(t))n=J_t(t,"utf-8");if(!n.includes(".nemar/")){let r=n?`${n.trimEnd()}
|
|
195
195
|
.nemar/
|
|
196
196
|
`:`.nemar/
|
|
197
|
-
`;Y_t(t,r)}}catch(t){console.log(u.yellow(` Warning: Could not update .gitignore: ${G(t)}`))}}function bD(e,t){if(e===void 0)return!1;if("identifier_preflight_recorded"in t&&t.identifier_preflight_recorded===!0)return!1;let n;if("error"in t)n=`the request failed: ${G(t.error)}`;else if(t.identifier_preflight_refused)n=`the server refused it (${t.identifier_preflight_refused})`;else if(t.identifier_preflight_recorded===!1)n="the server could not store it; running the upload again records it";else n="this NEMAR server does not record it";return console.log(u.yellow(` Warning: the identifier preflight was not recorded with your attestation (${n}).`)),console.log(u.dim(" The upload continues; NEMAR screens the dataset again before publication.")),!0}async function c_e(e,t,n,r,o,s,i){let a,c=o!==null,l;if(c){l=D(`Resuming upload for ${o.dataset_id}...`).start();try{await Wn(o.dataset_id),a={dataset_id:o.dataset_id,ssh_url:o.ssh_url,s3_prefix:o.s3_prefix,github_url:o.github_url,upload_urls:{},s3_config:o.s3_config},l.succeed(`Resuming upload: ${a.dataset_id}`)}catch(d){if(go(l,"Failed to resume upload",d),d instanceof L&&d.statusCode===404)console.log(u.yellow(" The dataset may have been deleted. Try uploading as a new dataset.")),console.log(u.dim(` Remove ${e}/.nemar to start fresh.`));return Ne}if(s)try{let d=await Ime(a.dataset_id,{attestation:s,identifier_preflight:i});bD(i,d)}catch(d){console.log(u.yellow(` Warning: the deposit attestation could not be recorded on resume: ${G(d)}`)),bD(i,{error:d})}else bD(i,{identifier_preflight_recorded:!1,identifier_preflight_refused:"preflight-without-attestation"})}else{l=D("Creating dataset in NEMAR...").start();try{let d=await AS({name:n,description:t.description,files:r.map((p)=>({path:p.path,size:p.size,type:p.type})),attestation:s,identifier_preflight:i,dataset_id:t.datasetId});a={dataset_id:d.dataset.dataset_id,ssh_url:d.dataset.ssh_url,s3_prefix:d.dataset.s3_prefix,github_url:d.dataset.github_url,upload_urls:d.upload_urls||{},s3_config:d.s3_config};let f={dataset_id:a.dataset_id,github_url:a.github_url,ssh_url:a.ssh_url,s3_prefix:a.s3_prefix,s3_config:a.s3_config,created_at:new Date().toISOString()};if(h6(e,f),l.succeed(d.resumed?`Resumed existing dataset: ${a.dataset_id}`:`Dataset created: ${a.dataset_id}`),bD(i,d),!d.resumed)await new Promise((p)=>setTimeout(p,1e4))}catch(d){return go(l,"Failed to create dataset",d),Ne}}return fn(a)}async function l_e(e){let t=D("Accepting GitHub repository invitation...").start(),n=ext(e.github_url);if(!n)return t.fail("Invalid GitHub repository URL from backend"),console.log(u.red(` Received: ${e.github_url||"(empty)"}`)),console.log(u.red(" Expected format: https://github.com/owner/repo")),console.log(),console.log("This may indicate a backend issue. Please contact support."),Ne;let r=await jS(n);if(r.accepted)if(r.alreadyCollaborator)t.succeed("Already a collaborator on this repository");else t.succeed("GitHub invitation accepted");else t.warn("Could not auto-accept invitation"),console.log(u.yellow(` ${r.error}`)),console.log(),console.log("You may need to accept the invitation manually:"),console.log(u.cyan(` https://github.com/${n}/invitations`)),console.log();return fn()}async function u_e(e,t){let n=D("Initializing git-annex dataset...").start();if(!await Mi(e)){let c=await lg(e,{author:t});if(!c.success)return go(n,"Failed to initialize git-annex dataset",c.error),Ne}let o=await _he(e);if(!o.success)return go(n,"Failed to initialize git-annex",o.error),Ne;let s=await whe(e);if(!s.success)return go(n,"Failed to set a non-identifying git-annex description",s.error),Ne;let i=await pd(e);if(!i.success)n.warn("Could not configure largefiles pattern"),console.log(u.dim(` ${i.error}`));if(n.succeed("git-annex dataset initialized"),s.changed)console.log(u.dim(" Replaced the repository's user@host:/path annex description (#1399)"));let a=await sc(e);if(a?.startsWith("adjusted/"))console.log(u.dim(` Note: Your local branch is "${a}".`)),console.log(u.dim(" This is normal; it keeps files unlocked so you can work with them directly.")),console.log(u.dim(' Pushes will go to the "main" branch on GitHub automatically.'));return txt(e),fn()}async function d_e(e,t,n){let r=D("Configuring GitHub remote...").start(),o=await nc(e,t.ssh_url);if(!o.success)return go(r,"Failed to configure GitHub remote",o.error),Ne;if(r.succeed("GitHub remote configured"),!await VS(e,{yes:n.yes}))return Ne;return fn()}function xD(e,t,n){let r=t.trim();return r?`${r} (${e} exited ${n})`:`${e} failed (exit status ${n})`}async function cp(e){let{stdout:t,stderr:n,exitCode:r}=await R(["git","ls-files","-z"],{cwd:e});if(r!==0)throw Error(xD("git ls-files",n,r));return new Set(t.split("\x00").filter(Boolean))}async function Cd(e,t){let n=t?["git","annex","find","--in",t,"--print0"]:["git","annex","find","--include","*","--print0"],{stdout:r,stderr:o,exitCode:s}=await R(n,{cwd:e});if(s!==0)throw Error(xD("git annex find",o,s));return new Set(r.split("\x00").filter(Boolean))}async function ap(e,t,n){let r=n?["git","--literal-pathspecs","annex","find","--not","--in",t,"--print0","--",...n]:["git","annex","find","--not","--in",t,"--print0"],{stdout:o,stderr:s,exitCode:i}=await R(r,{cwd:e});if(i!==0)throw Error(xD("git annex find",s,i));return new Set(o.split("\x00").filter(Boolean))}function nxt(e,t,n){let r=[...e],o=new Set(e.map((s)=>s.path));for(let s of t)if(!n.has(s.path)&&!o.has(s.path))r.push(s),o.add(s.path);return r}async function f_e(e,t,n={}){let r=t.filter($N),o=t.filter((a)=>!$N(a)),s={annexJobs:n.annexJobs??qg,...n.onInactivityWarning?{onInactivityWarning:n.onInactivityWarning}:{}},i=await oc(e,o,{},s);if(!i.success||r.length===0)return i;return oc(e,r,{},{forceLarge:!0,...s})}function rxt(e,t){let n=e.filter((r)=>(r.type??"data")==="data"&&!t.has(r.path));return{blocking:n.filter((r)=>r.size>SN),small:n.filter((r)=>r.size<=SN)}}function zi(e){return`${e} data ${e===1?"file":"files"}`}function $6(e){return e==="partial"?"git-annex gave no result for some of them":"git-annex's output was not recognized"}function oxt(e,t,n,r={}){if(e===0)return"No annexed data files, so nothing was copied to S3";let o=r.resent??0,s=r.recordedNoLocal??0,i=r.sent??n,a=r.recordedCheckSkipped===!0,c=r.output??"understood",l=r.recordedOutput??"understood",d=Math.max(0,e-t);if(t===0&&o===0){if(a)return`All ${e} data files are recorded at the S3 remote; not checked again, because these files and their annex keys passed a check at this destination within the last ${kw}`;if(l!=="understood")return`All ${e} data files are recorded at the S3 remote (${$6(l)}, so what its check found is unknown)`;let p;if(s===0)p=e===1?"git-annex checked it":"git-annex checked each one";else if(s>=e)p=e===1?"it has no local content, so it was checked with git-annex fsck":"none has local content, so git-annex fsck checked them";else p=`${e-s} checked by git-annex copy, ${s} without local content checked with git-annex fsck`;return e===1?`The 1 data file is already at the S3 remote (${p}; nothing to copy)`:`All ${e} data files are already at the S3 remote (${p}; nothing to copy)`}let f=[];if(t>0){let p=zi(t),m=c!=="understood"?`${$6(c)}, so how many it transferred is unknown; the location log is what shows them recorded`:n<t?`git-annex confirmed ${n} of ${t}; the rest are recorded in the location log`:n>t?`git-annex reported ${n} successful copies for ${t} files`:i<t?`git-annex reported transferring ${i}`:"";f.push(m?`${p} not yet recorded at the S3 remote ${Rd(t)} copied (${m})`:`Uploaded ${p} to S3`)}else f.push("Sent no new files to S3");if(d>0)if(a)f.push(`${d} already recorded at the remote ${Rd(d)} not checked again, because these files and their annex keys passed a check at this destination within the last ${kw}`);else if(l!=="understood")f.push(`${d} ${Rd(d)} already recorded at the remote (${$6(l)}, so what its check found is unknown)`);else{let p=Math.max(0,d-s-o);if(p>0)f.push(`${p} ${Rd(p)} already at the remote`);if(s>0)f.push(`${s} recorded ${s===1?"file":"files"} with no local content ${Rd(s)} checked with git-annex fsck`);if(o>0){let m=Rd(o);f.push(`${o} ${m} recorded but missing at the remote and ${m} sent again`)}}return f.push("all recorded at the remote"),f.join("; ")}function p_e(e){return e.lease?.credentials??e.credentials}function m_e(e){return Boolean(e.lease&&e.renewLease&&e.lease.expiresAtMs-Date.now()<n_e+e.longestBatchMs)}function h_e(e,t){e.longestBatchMs=Math.max(e.longestBatchMs,t)}async function _D(e,t,n){if(!e.renewLease)return"Upload credentials cannot be renewed in this remote";if(e.refreshes>=r_e)return`Upload credentials were renewed ${e.refreshes} times and the ${n} is still not done; re-run the command to continue`;try{e.lease=await e.renewLease()}catch(r){return`Could not renew upload credentials (${t}): ${G(r)}`}return e.refreshes++,e.onCredentialsRenewed?.(e.refreshes,t),null}function sxt(e){return[e.error,..."absent"in e?e.absent.flatMap((n)=>n.errors):[]].find(E6)}function ixt(e,t,n){let r=[],o=[],s=()=>{if(o.length===0)return;r.push(...k6(o,t,{maxFiles:n??HS})),o=[]};for(let i of e)if(t.has(i))o.push(i);else s(),r.push([i]);return s(),r}async function g_e(e){let t=0,n=!1,r=new Set,o=!0;for(;;){if(!n&&m_e(e.session)){let m=await _D(e.session,"close to expiry","recorded-file verification");if(m)return{success:!1,error:m}}n=!1;let s=Date.now(),i=await e.run(p_e(e.session));h_e(e.session,Date.now()-s);let a=r.size;if("sentPaths"in i){for(let m of i.sentPaths)r.add(m);if(i.output!=="understood"||i.filesSent!==i.sentPaths.length)o=!1}let c=r.size>a,l=sxt(i),d=Boolean(e.session.lease&&e.session.lease.expiresAtMs<=Date.now()&&(i.error!==void 0||("absent"in i)&&i.absent.length>0)),f=l??(d?"The credential lease expired while the recorded-file check was running":void 0);if(!f){if(!i.success)return{success:!1,error:i.error??`Failed to run the recorded-file ${e.operation}`};if("sentPaths"in i)return{success:!0,outcome:{...i,filesSent:o?r.size:i.filesSent,sentPaths:[...r],output:o?i.output:vD(i.output,"unrecognized")}};return{success:!0,outcome:i}}if(!e.session.lease||!e.session.renewLease)return{success:!1,error:i.error??`Expired upload credentials interrupted the recorded-file ${e.operation}: ${f}`};if(c)t=0;else t++;if(t>=x6)return{success:!1,error:`Recorded-file ${e.operation} keeps failing with expired credentials: ${f}`};let p=await _D(e.session,l?"expired during recorded-file verification":"lease expired during recorded-file verification","recorded-file verification");if(p)return{success:!1,error:p};n=!0}}function vD(e,t){return e==="unrecognized"||t==="unrecognized"?"unrecognized":e==="partial"||t==="partial"?"partial":"understood"}async function axt(e){let t=0,n="understood";for(let r of ixt(e.paths,e.sizes,e.batchMaxFiles))for(let o of fo(r)){let s=await g_e({session:e.credentialSession,operation:"copy check",run:(i)=>cw(e.absolutePath,e.remote,o,e.jobs,i)});if(!s.success)return s;t+=s.outcome.filesSent,n=vD(n,s.outcome.output)}return{success:!0,filesSent:t,output:n}}async function cxt(e){let t=0,n=[],r=[],o="understood";for(let s of fo(e.paths)){let i=await g_e({session:e.credentialSession,operation:"presence check",run:(a)=>ybe(e.absolutePath,e.remote,s,e.jobs,a)});if(!i.success)return{success:!1,error:i.error,present:t,absent:n,unanswered:r,output:o};t+=i.outcome.present,n=n.concat(i.outcome.absent),r=r.concat(i.outcome.unanswered),o=vD(o,i.outcome.output)}return{success:!0,present:t,absent:n,unanswered:r,output:o}}async function lxt(e){let t=0,n=0,r=new Set,o="understood",s=(i)=>({success:!1,error:i,filesCopied:t,filesSent:n,output:o});for(let i of e.batches){let a=0,c=!1;for(;;){let l;try{l=await ap(e.absolutePath,e.remote,i)}catch(b){return s(`Could not read the annex location log before copying: ${G(b)}`)}let d=i.filter((b)=>l.has(b));if(d.length===0)break;if(c)c=!1;else if(m_e(e.credentialSession)){let b=await _D(e.credentialSession,"close to expiry","copy");if(b)return s(b)}let f=Date.now(),p=await cw(e.absolutePath,e.remote,d,e.jobs,p_e(e.credentialSession));h_e(e.credentialSession,Date.now()-f);let m;try{m=await ap(e.absolutePath,e.remote,i)}catch(b){return s(`Could not read the annex location log after copying: ${G(b)}`)}let h=d.filter((b)=>m.has(b)),g=d.length-h.length;t+=g;for(let b of p.sentPaths)r.add(b);if(n=r.size,o=vD(o,p.output),h.length===0)break;if(p.success)break;if(!E6(p.error))return s(p.error??"Failed to copy pending files to the remote");if(!e.credentialSession.lease||!e.credentialSession.renewLease)return s(p.error??"Expired upload credentials cannot be renewed in this remote");if(a=g>0?0:a+1,a>=x6)return s(`Copy keeps failing with expired credentials and the pending location-log set did not shrink: ${p.error??"expired credentials"}`);let y=await _D(e.credentialSession,"expired during copy","copy");if(y)return s(y);c=!0}}return{success:!0,filesCopied:t,filesSent:n,output:o}}async function i_e(e){let{absolutePath:t,remote:n,addTargets:r}=e,o,s;try{o=await Cd(t),s=[...await ap(t,n)].sort()}catch(U){return{status:"unreadable",error:G(U)}}let i=null;if(o.size>0&&e.remoteIdentity)try{i=await ur(t)}catch{}let a=(U)=>{if(!i)return null;let B=[];for(let P of U){let O=i.get(P);if(O===void 0)return null;B.push([P,O])}if(!e.remoteIdentity)return null;return Vwe(B,e.remoteIdentity)},c=a(o),l=rxt(r,o);if(l.blocking.length>0)return{status:"blocked",blocking:l.blocking.map((U)=>({path:U.path,size:U.size}))};let d={inGit:[],leftOut:[]};if(l.small.length>0){let U;try{U=await cp(t)}catch(B){return{status:"unreadable",error:G(B)}}for(let B of l.small)(U.has(B.path)?d.inGit:d.leftOut).push(B.path);d.inGit.sort(),d.leftOut.sort()}let f=new Set(s),p=[...o].filter((U)=>!f.has(U)).sort(),m=a(p),h=p.length>0&&c!==null&&m!==null&&e.skipRecordedCheck?.(p.length,m)===!0,g=p,y=[];if(p.length>0&&!h)try{let U=await ap(t,"here");y=p.filter((B)=>U.has(B)),g=p.filter((B)=>!U.has(B))}catch(U){return{status:"unreadable",error:G(U)}}let b=new Map(e.dataFiles.map((U)=>[U.path,U.size])),_=k6(s,b,{maxFiles:e.batchMaxFiles,maxBytes:e.batchMaxBytes});await e.onPlan?.({total:o.size,pending:s.length,copyBatchCount:_.length,recorded:p.length,recordedNoLocal:y.length,recordedCheckSkipped:h,smallNotAnnexed:d});let x={credentials:e.credentials,lease:e.lease,renewLease:e.renewLease,refreshes:0,longestBatchMs:0,onCredentialsRenewed:e.onCredentialsRenewed},k=await lxt({absolutePath:t,remote:n,batches:_,jobs:e.jobs,credentialSession:x});if(!k.success)return{status:"copy_failed",error:k.error??"Failed to copy to remote"};let v=0,C="understood",T=[],z=[];if(!h){let U=await axt({absolutePath:t,remote:n,paths:g,sizes:b,jobs:e.jobs,batchMaxFiles:e.batchMaxFiles,credentialSession:x});if(!U.success)return{status:"copy_failed",error:U.error??"Failed to check the remote"};if(v=U.filesSent,C=U.output,y.length>0){let B=await cxt({absolutePath:t,remote:n,paths:y,jobs:e.jobs,credentialSession:x});if(!B.success)return{status:"copy_failed",error:B.error??"Failed to check the remote"};if(T=B.absent,z=B.unanswered,B.output!=="understood"&&C==="understood")C=B.output}}let A;try{A=[...await ap(t,n)].sort()}catch(U){return{status:"unverifiable",error:G(U)}}let F=new Set(A),M=[...T.filter((U)=>!F.has(U.file)).map((U)=>({file:U.file,why:U.errors[0]??"no reason given"})),...z.map((U)=>({file:U,why:"git-annex gave no result for it"}))];if(M.length>0){let U=M[0];return{status:"unverifiable",error:`git-annex could not confirm that ${M.length} recorded ${M.length===1?"file":"files"} with no local content ${M.length===1?"is":"are"} at the remote (${Kr(U.file)}: ${U.why})`}}if(A.length>0){let U=o.size+A.filter((O)=>!o.has(O)).length,B=[],P=!0;try{let O=await ap(t,"here");B=A.filter((H)=>O.has(H))}catch{P=!1;let O=new Set([...y,...T.map((H)=>H.file)]);B=A.filter((H)=>O.has(H))}return{status:"incomplete",missing:A,total:U,notLocal:B,notLocalKnown:P,lostAtRemote:T.map((O)=>O.file).sort()}}return{status:"ok",total:o.size,attempted:s.length,confirmed:k.filesCopied,sent:k.filesSent,resent:v,recordedNoLocal:y.length,recordedCheckSkipped:h,output:k.output,recordedOutput:C,remoteConfirmed:!h&&k.output==="understood"&&C==="understood",recordedCheckFingerprint:c,annexedPaths:o,smallNotAnnexed:d}}async function uxt(e,t,n){yl(t,"tracking");let r=Nr(e,t),o=n,s=null,i=[];try{let a=await cp(e);o=n.filter((c)=>a.has(c)),await zS(e,o),s=o.length}catch(a){i.push(G(a))}if(!r)i.push("the upload progress could not be saved, so the next run may skip the tracking step; if it does, run the upload with --restart");return{unstaged:s,staged:o,...i.length>0?{error:i.join("; ")}:{}}}function wD(e,t=5){let n=e.slice(0,t).map((r)=>` - ${Kr(r)}`);if(e.length>t)n.push(` ... and ${e.length-t} more`);return n}function y_e(e){return`'${e.replace(/'/g,"'\\''")}'`}function fxt(e,t){let n=e.map((o)=>o.path),r=[`${zi(e.length)} over ${BS()} ${e.length===1?"was":"were"} not added to git-annex and would be committed to git instead of uploaded to S3:`,...wD(n)];if(t.unstaged!==null){if(r.push(t.unstaged>0?` ${t.unstaged} of them ${Rd(t.unstaged)} unstaged so the next run can annex them; the files themselves are untouched.`:" None of them was staged, so nothing needed unstaging."),t.error)r.push(` But: ${t.error}.`)}else if(r.push(` Could not finish making the next run able to annex them: ${t.error}.`),t.staged.length===0)r.push(" None of them is staged, so fixing the cause is all that is left.");else if(t.staged.length>dxt)r.push(` ${t.staged.length} paths are involved; the next run tries again, unstaging them.`);else if(!t.staged.every(tc))r.push(" A name has a character that cannot go in a command; the next run tries again, unstaging them.");else r.push(" The next run tries again; to do it now, run this in the dataset directory:",` git --literal-pathspecs rm --cached --quiet --ignore-unmatch -- ${t.staged.map(y_e).join(" ")}`);return r.push(" Find out why git-annex declined them, fix that, then re-run `nemar dataset upload`:"," - a .gitattributes `annex.largefiles` setting overrides NEMAR's annex policy"," - a .gitignore pattern matches the file: git-annex skips an ignored file without saying so, while the upload plan lists every file on disk"),r}async function b_e(e,t){let{stdout:n,stderr:r,exitCode:o}=await R(["git","config","--get",`remote.${t}.annex-uuid`],{cwd:e});if(o===1)return!1;if(o!==0)throw Error(xD("git config",r,o));return n.trim().length>0}async function D6(e,t){return[...await b_e(e,t)?await ap(e,t):await Cd(e)].sort()}function pxt(e,t){return async()=>{let n=D("Requesting upload credentials...").start(),r;try{r=await Gr(t.dataset_id),n.succeed("Upload credentials received (2h expiry)")}catch(a){return n.fail(`Could not get upload credentials: ${G(a)}`),console.log(u.red(" Upload credentials are required for S3 access.")),console.log(u.dim(" Re-run the command to retry.")),Ne}n=D("Configuring S3 remote...").start();let o={name:mc,bucket:r.s3.bucket,prefix:`${t.dataset_id}/objects`,region:r.s3.region,publicUrl:t.s3_config.public_url},s=await Fo(e,o,lr(r.credentials));if(!s.success)return n.fail(`Failed to configure S3 remote: ${s.error}`),console.log(u.dim(" Re-run the command to retry.")),Ne;n.succeed("S3 remote configured");let i=v6(lr(r.credentials),r.credentials.expiration);return fn({credentials:i.credentials,lease:i,renewLease:async()=>{let a=await Gr(t.dataset_id);return v6(lr(a.credentials),a.credentials.expiration)},remoteIdentity:JSON.stringify([mc,PF(o)])})}}function gxt(e){if(e<60)return"under a minute";let t=Math.round(e/60);if(t<60)return`about ${t} ${t===1?"minute":"minutes"}`;let n=Math.floor(t/60),r=t%60,o=`${n} ${n===1?"hour":"hours"}`;return r===0?`about ${o}`:`about ${o} ${r} ${r===1?"minute":"minutes"}`}function yxt(e,t){let n=[];if(e.recorded===0)return n;if(e.recordedCheckSkipped)return n.push(` These ${e.recorded} recorded files and their annex keys passed a check at this destination within the last ${kw}; the remote is not asked about them again.`),n;if(e.recordedNoLocal>0)n.push(` ${zi(e.recordedNoLocal)} recorded at the S3 remote ${e.recordedNoLocal===1?"has":"have"} no content in this repository, so the remote is asked about ${e.recordedNoLocal===1?"it":"them"} with git-annex fsck.`);if(e.recorded>mxt){let r=Math.ceil(e.recorded*hxt/Math.max(1,t));n.push(` The remote is asked about each of the ${e.recorded.toLocaleString("en-US")} files already recorded there, one request each: ${gxt(r)} with ${t} parallel ${t===1?"job":"jobs"} (50 to 100 ms a request; --jobs changes it). A run that gets through it, with git-annex's answers understood, lets a re-run within ${kw} skip it.`)}return n}async function bxt(e){let{absolutePath:t,progress:n,addTargets:r}=e,o=null,s=(p)=>{if(o)o.fail(p);else console.log(u.red(p))};await Xr(t);let i,a=null,c=0;try{let p=await e.openRemote();if(p.status==="fail")return Ne;let m={absolutePath:t,remote:mc,remoteIdentity:p.value.remoteIdentity,addTargets:r,dataFiles:e.dataFiles,jobs:e.jobs,credentials:p.value.credentials,lease:p.value.lease,renewLease:p.value.renewLease,batchMaxFiles:e.copyBatchMaxFiles,onCredentialsRenewed:(h,g)=>{let y=`Renewed upload credentials (${g}; renewal ${h})`;if(o)o.info(y),o=D("Uploading data files to S3...").start();else console.log(u.dim(` ${y}`))},skipRecordedCheck:(h,g)=>Gwe(n,h,g),onPlan:(h)=>{let{inGit:g,leftOut:y}=h.smallNotAnnexed;if(g.length>0){console.log(u.dim(` ${g.length} small data file(s) (<= ${BS()}) were stored in git rather than the annex:`));for(let _ of wD(g,3))console.log(u.dim(_))}if(y.length>0){console.log(u.yellow(` Warning: ${y.length} small data file(s) (<= ${BS()}) are in neither git nor the annex and will NOT be uploaded; a .gitignore pattern probably matches them:`));for(let _ of wD(y,3))console.log(u.yellow(_))}for(let _ of yxt(h,e.jobs))console.log(u.dim(_));let b=h.recordedCheckSkipped?0:h.recorded;if(h.pending>0)o=D(`Uploading ${zi(h.pending)} in ${h.copyBatchCount.toLocaleString()} ${h.copyBatchCount===1?"copy batch":"copy batches"} to S3${b>0?` (then checking the S3 remote for ${zi(b)} already recorded)`:""}...`).start();else if(b>0)o=D(`Checking the S3 remote for ${zi(b)}...`).start()}};i=await i_e(m);while(i.status==="blocked"){let h=i.blocking.map((y)=>y.path);if(a=await uxt(t,n,h),c>0||a.unstaged===null)break;let g=await f_e(t,h,{annexJobs:e.annexJobs,onInactivityWarning:(y)=>{o=Q_t(o,a_e(y))}});if(!g.success){if(console.log(u.red(`Failed to track data files: ${g.error}`)),a.error)console.log(u.yellow(`The recovery before it also reported: ${a.error}`));return console.log(u.yellow("Re-run the same command to resume tracking.")),Ne}c=h.length,i=await i_e(m)}}finally{await Xr(t)}let l=i.status==="ok"||i.status==="copy_failed"||i.status==="incomplete"||i.status==="unverifiable";if(c>0&&l)gl(n,"tracking"),Nr(t,n),console.log(u.dim(` ${zi(c)} git-annex had declined ${Rd(c)} unstaged and added again; ${c===1?"it is":"they are"} annexed now.`));switch(i.status){case"unreadable":return console.log(u.red(`Could not read the annex location log: ${i.error}`)),console.log(u.yellow("Re-run the same command to retry.")),Ne;case"blocked":{let p=a??{unstaged:null,staged:[],error:"no recovery ran"};for(let m of fxt(i.blocking,p))console.log(m.startsWith(" ")?u.yellow(m):u.red(m));return Ne}case"copy_failed":return s(`S3 upload failed: ${i.error}`),console.log(u.yellow("Re-run the same command to resume uploading.")),Ne;case"unverifiable":return s(`Could not confirm the S3 upload is recorded: ${i.error}`),console.log(u.yellow("Re-run the same command to retry.")),Ne;case"incomplete":{s(`S3 upload incomplete: ${i.missing.length} of ${i.total} annexed data files are not recorded at the S3 remote`);for(let h of wD(i.missing))console.log(u.red(h));let p=i.lostAtRemote.length;if(p>0)console.log(u.red(`git-annex reports that the S3 remote no longer holds ${p} of them: fsck did not find ${p===1?"it":"them"} there and struck ${p===1?"it":"them"} from the location log.`)),console.log(u.yellow(`If the remote could not be read, rather than having lost the objects, \`git annex fsck --fast --from ${mc}\` puts back the keys that were struck only for that reason.`));let m=i.notLocal.length;if(m>0){let h=i.notLocal[0],y=m===1&&i.notLocalKnown&&tc(h)?`git annex get -- ${y_e(h)}`:`git annex get --not --in ${mc}`,_=`${i.notLocalKnown?"":"At least "}${m} of them ${m===1?"has":"have"} no content in this repository, so ${m===1?"it cannot":"they cannot"} be uploaded from here.`;console.log(u.yellow(`${_} ${p>0?"Get the content from another copy of the dataset":`Fetch ${m===1?"it":"them"}`} with \`${y}\`, then re-run.`))}else if(!i.notLocalKnown)console.log(u.yellow(`Which of them have no content in this repository could not be read. If re-running does not help, fetch the missing content with \`git annex get --not --in ${mc}\`, then re-run.`));else console.log(u.yellow("Re-run the same command to resume uploading."));return Ne}case"ok":break}for(let p of r)Xwe(n,p.path,{size:p.size,mtimeMs:p.mtimeMs});if(i.remoteConfirmed&&i.recordedCheckFingerprint!==null)Wwe(n,i.total,i.recordedCheckFingerprint);Nr(t,n);let d=oxt(i.total,i.attempted,i.confirmed,{sent:i.sent,resent:i.resent,recordedNoLocal:i.recordedNoLocal,recordedCheckSkipped:i.recordedCheckSkipped,output:i.output,recordedOutput:i.recordedOutput}),f=i.output!=="understood"||i.recordedOutput!=="understood";if(o)if(f)o.warn(d);else o.succeed(d);else console.log(f?u.yellow(d):d);return fn({annexedPaths:i.annexedPaths})}async function w_e(e,t,n,r,o,s,i={}){let a=o,c,l=null;if(!a)a=Jwe(e,s.dataset_id,n);else{if(Hi(a,"tracking")&&Qwe(a,n))yl(a,"tracking"),console.log(u.dim(" Data files changed since the last run; re-running git-annex add"));for(let x of n)if(!a.files[x.path])a.files[x.path]={status:"pending",size:x.size,mtimeMs:x.mtimeMs,updated_at:new Date().toISOString()};Nr(e,a)}let d;try{d=await cp(e)}catch(x){return console.log(u.red(`Failed to read the git index: ${G(x)}`)),console.log(u.dim(" Re-run the command to retry.")),Ne}let f=nxt(r,n,d),p=t.annexJobs===void 0?qg:Number(t.annexJobs),m,h;try{h=await b_e(e,mc),m=await D6(e,mc)}catch(x){return console.log(u.red(`Could not read the annex location log: ${G(x)}`)),console.log(u.yellow("Re-run the same command to retry.")),Ne}let g=f.length>0||m.length>0,y=f.length-r.length,b=y>0&&Hi(a,"tracking"),_=g&&Hi(a,"s3_upload");if(b)yl(a,"tracking");if(_)yl(a,"s3_upload"),yl(a,"dataset_save"),yl(a,"github_push");if(b||_)Nr(e,a);if(b)console.log(u.yellow(` ${y} data files are missing from git despite recorded progress; re-tracking them`));if(_)console.log(u.yellow(f.length>0?` ${f.length} data file(s) still need upload despite a completed s3_upload step; resuming`:h?` ${m.length} annexed data file(s) are not recorded at the S3 remote despite a completed s3_upload step; resuming`:" The S3 remote is not set up in this repository, so nothing can be recorded there despite a completed s3_upload step; resuming and checking every annexed data file against it"));if(!Hi(a,"s3_upload")){if(g){if(f.length>0&&!Hi(a,"tracking")){let k=i.primeMinBytes??Mwe,v={...i.primeChunkPaths===void 0?{}:{chunkPaths:i.primeChunkPaths},...i.primeSpinnerStream?{stream:i.primeSpinnerStream}:{}};if(!await s_e(e,f,k,"before",v))return Ne;c=D(`Tracking ${f.length} data files with git-annex...`).start();let C=await f_e(e,f.map((T)=>T.path),{annexJobs:p,onInactivityWarning:(T)=>{c=Sw(c,a_e(T))}});if(!C.success)return c.fail(`Failed to track data files: ${C.error}`),console.log(u.yellow("Re-run the same command to resume tracking.")),Ne;if(c.succeed("Data files tracked by git-annex"),gl(a,"tracking"),Nr(e,a),!await s_e(e,f,k,"after",{...v,...i.primeOnSuspended?{onSuspended:i.primeOnSuspended}:{}}))return Ne}else if(f.length>0)console.log(u.dim(" Data files already tracked by git-annex (skipping)"));let x=await bxt({absolutePath:e,progress:a,addTargets:f,dataFiles:n,jobs:Number.parseInt(t.jobs,10),annexJobs:p,openRemote:i.openRemote??pxt(e,s)});if(x.status==="fail")return Ne;l=x.value.annexedPaths}else console.log(u.dim("No data files to upload to S3"));gl(a,"s3_upload"),Nr(e,a)}else console.log(u.dim(" S3 upload already completed (skipping)"));return fn({progress:a,annexedPaths:l})}var qg=4,Rd=(e)=>e===1?"was":"were",dxt=50,mc="nemar-s3",mxt=5000,hxt=0.075;var Ad=V(()=>{He();ro();Za();ec();Ke();sp();fD();qf();rc();y6();ji();Fi();ug();qt();cc();Pr();gD();_6();ip()});import{existsSync as wxt,readFileSync as _xt,writeFileSync as xxt}from"fs";import{join as vxt}from"path";function kxt(e){return e.startsWith("ASIA")}function Ext(e){if(e==="inherit")return;if(kxt(e.accessKeyId)&&!e.sessionToken)throw Error(`Refusing to transfer with temporary AWS credentials that carry no session token: S3 rejects every such request with a bare 403. Pass the session token the credential response returned, or say "inherit" to use the environment's own credentials.`);return e}function $xt(e){return(e.split("/").pop()??e).startsWith(".git")}function Od(e){let t=e.endsWith(`
|
|
197
|
+
`;Y_t(t,r)}}catch(t){console.log(u.yellow(` Warning: Could not update .gitignore: ${G(t)}`))}}function bD(e,t){if(e===void 0)return!1;if("identifier_preflight_recorded"in t&&t.identifier_preflight_recorded===!0)return!1;let n;if("error"in t)n=`the request failed: ${G(t.error)}`;else if(t.identifier_preflight_refused)n=`the server refused it (${t.identifier_preflight_refused})`;else if(t.identifier_preflight_recorded===!1)n="the server could not store it; running the upload again records it";else n="this NEMAR server does not record it";return console.log(u.yellow(` Warning: the identifier preflight was not recorded with your attestation (${n}).`)),console.log(u.dim(" The upload continues; NEMAR screens the dataset again before publication.")),!0}async function c_e(e,t,n,r,o,s,i){let a,c=o!==null,l;if(c){l=D(`Resuming upload for ${o.dataset_id}...`).start();try{await Wn(o.dataset_id),a={dataset_id:o.dataset_id,ssh_url:o.ssh_url,s3_prefix:o.s3_prefix,github_url:o.github_url,upload_urls:{},s3_config:o.s3_config},l.succeed(`Resuming upload: ${a.dataset_id}`)}catch(d){if(go(l,"Failed to resume upload",d),d instanceof L&&d.statusCode===404)console.log(u.yellow(" The dataset may have been deleted. Try uploading as a new dataset.")),console.log(u.dim(` Remove ${e}/.nemar to start fresh.`));return Ne}if(s)try{let d=await Ime(a.dataset_id,{attestation:s,identifier_preflight:i});bD(i,d)}catch(d){console.log(u.yellow(` Warning: the deposit attestation could not be recorded on resume: ${G(d)}`)),bD(i,{error:d})}else bD(i,{identifier_preflight_recorded:!1,identifier_preflight_refused:"preflight-without-attestation"})}else{l=D("Creating dataset in NEMAR...").start();try{let d=await AS({name:n,description:t.description,files:r.map((p)=>({path:p.path,size:p.size,type:p.type})),attestation:s,identifier_preflight:i,dataset_id:t.datasetId});a={dataset_id:d.dataset.dataset_id,ssh_url:d.dataset.ssh_url,s3_prefix:d.dataset.s3_prefix,github_url:d.dataset.github_url,upload_urls:d.upload_urls||{},s3_config:d.s3_config};let f={dataset_id:a.dataset_id,github_url:a.github_url,ssh_url:a.ssh_url,s3_prefix:a.s3_prefix,s3_config:a.s3_config,created_at:new Date().toISOString()};if(h6(e,f),l.succeed(d.resumed?`Resumed existing dataset: ${a.dataset_id}`:`Dataset created: ${a.dataset_id}`),bD(i,d),!d.resumed)await new Promise((p)=>setTimeout(p,1e4))}catch(d){return go(l,"Failed to create dataset",d),Ne}}return fn(a)}async function l_e(e){let t=D("Accepting GitHub repository invitation...").start(),n=ext(e.github_url);if(!n)return t.fail("Invalid GitHub repository URL from backend"),console.log(u.red(` Received: ${e.github_url||"(empty)"}`)),console.log(u.red(" Expected format: https://github.com/owner/repo")),console.log(),console.log("This may indicate a backend issue. Please contact support."),Ne;let r=await jS(n);if(r.accepted)if(r.alreadyCollaborator)t.succeed("Already a collaborator on this repository");else t.succeed("GitHub invitation accepted");else t.warn("Could not auto-accept invitation"),console.log(u.yellow(` ${r.error}`)),console.log(),console.log("You may need to accept the invitation manually:"),console.log(u.cyan(` https://github.com/${n}/invitations`)),console.log();return fn()}async function u_e(e,t){let n=D("Initializing git-annex dataset...").start();if(!await Mi(e)){let c=await lg(e,{author:t});if(!c.success)return go(n,"Failed to initialize git-annex dataset",c.error),Ne}let o=await _he(e);if(!o.success)return go(n,"Failed to initialize git-annex",o.error),Ne;let s=await whe(e);if(!s.success)return go(n,"Failed to set a non-identifying git-annex description",s.error),Ne;let i=await pd(e);if(!i.success)n.warn("Could not configure largefiles pattern"),console.log(u.dim(` ${i.error}`));if(n.succeed("git-annex dataset initialized"),s.changed)console.log(u.dim(" Replaced the repository's user@host:/path annex description (#1399)"));let a=await sc(e);if(a?.startsWith("adjusted/"))console.log(u.dim(` Note: Your local branch is "${a}".`)),console.log(u.dim(" This is normal; it keeps files unlocked so you can work with them directly.")),console.log(u.dim(' Pushes will go to the "main" branch on GitHub automatically.'));return txt(e),fn()}async function d_e(e,t,n){let r=D("Configuring GitHub remote...").start(),o=await nc(e,t.ssh_url);if(!o.success)return go(r,"Failed to configure GitHub remote",o.error),Ne;if(r.succeed("GitHub remote configured"),!await VS(e,{yes:n.yes}))return Ne;return fn()}function xD(e,t,n){let r=t.trim();return r?`${r} (${e} exited ${n})`:`${e} failed (exit status ${n})`}async function cp(e){let{stdout:t,stderr:n,exitCode:r}=await R(["git","ls-files","-z"],{cwd:e});if(r!==0)throw Error(xD("git ls-files",n,r));return new Set(t.split("\x00").filter(Boolean))}async function Cd(e,t){let n=t?["git","annex","find","--in",t,"--print0"]:["git","annex","find","--include","*","--print0"],{stdout:r,stderr:o,exitCode:s}=await R(n,{cwd:e});if(s!==0)throw Error(xD("git annex find",o,s));return new Set(r.split("\x00").filter(Boolean))}async function ap(e,t,n){let r=n?["git","--literal-pathspecs","annex","find","--not","--in",t,"--print0","--",...n]:["git","annex","find","--not","--in",t,"--print0"],{stdout:o,stderr:s,exitCode:i}=await R(r,{cwd:e});if(i!==0)throw Error(xD("git annex find",s,i));return new Set(o.split("\x00").filter(Boolean))}function nxt(e,t,n){let r=[...e],o=new Set(e.map((s)=>s.path));for(let s of t)if(!n.has(s.path)&&!o.has(s.path))r.push(s),o.add(s.path);return r}async function f_e(e,t,n={}){let r=t.filter($N),o=t.filter((a)=>!$N(a)),s={annexJobs:n.annexJobs??qg,...n.onInactivityWarning?{onInactivityWarning:n.onInactivityWarning}:{}},i=await oc(e,o,{},s);if(!i.success||r.length===0)return i;return oc(e,r,{},{forceLarge:!0,...s})}function rxt(e,t){let n=e.filter((r)=>(r.type??"data")==="data"&&!t.has(r.path));return{blocking:n.filter((r)=>r.size>SN),small:n.filter((r)=>r.size<=SN)}}function zi(e){return`${e} data ${e===1?"file":"files"}`}function $6(e){return e==="partial"?"git-annex gave no result for some of them":"git-annex's output was not recognized"}function oxt(e,t,n,r={}){if(e===0)return"No annexed data files, so nothing was copied to S3";let o=r.resent??0,s=r.recordedNoLocal??0,i=r.sent??n,a=r.recordedCheckSkipped===!0,c=r.output??"understood",l=r.recordedOutput??"understood",d=Math.max(0,e-t);if(t===0&&o===0){if(a)return`All ${e} data files are recorded at the S3 remote; not checked again, because these files and their annex keys passed a check at this destination within the last ${kw}`;if(l!=="understood")return`All ${e} data files are recorded at the S3 remote (${$6(l)}, so what its check found is unknown)`;let p;if(s===0)p=e===1?"git-annex checked it":"git-annex checked each one";else if(s>=e)p=e===1?"it has no local content, so it was checked with git-annex fsck":"none has local content, so git-annex fsck checked them";else p=`${e-s} checked by git-annex copy, ${s} without local content checked with git-annex fsck`;return e===1?`The 1 data file is already at the S3 remote (${p}; nothing to copy)`:`All ${e} data files are already at the S3 remote (${p}; nothing to copy)`}let f=[];if(t>0){let p=zi(t),m=c!=="understood"?`${$6(c)}, so how many it transferred is unknown; the location log is what shows them recorded`:n<t?`git-annex confirmed ${n} of ${t}; the rest are recorded in the location log`:n>t?`git-annex reported ${n} successful copies for ${t} files`:i<t?`git-annex reported transferring ${i}`:"";f.push(m?`${p} not yet recorded at the S3 remote ${Rd(t)} copied (${m})`:`Uploaded ${p} to S3`)}else f.push("Sent no new files to S3");if(d>0)if(a)f.push(`${d} already recorded at the remote ${Rd(d)} not checked again, because these files and their annex keys passed a check at this destination within the last ${kw}`);else if(l!=="understood")f.push(`${d} ${Rd(d)} already recorded at the remote (${$6(l)}, so what its check found is unknown)`);else{let p=Math.max(0,d-s-o);if(p>0)f.push(`${p} ${Rd(p)} already at the remote`);if(s>0)f.push(`${s} recorded ${s===1?"file":"files"} with no local content ${Rd(s)} checked with git-annex fsck`);if(o>0){let m=Rd(o);f.push(`${o} ${m} recorded but missing at the remote and ${m} sent again`)}}return f.push("all recorded at the remote"),f.join("; ")}function p_e(e){return e.lease?.credentials??e.credentials}function m_e(e){return Boolean(e.lease&&e.renewLease&&e.lease.expiresAtMs-Date.now()<n_e+e.longestBatchMs)}function h_e(e,t){e.longestBatchMs=Math.max(e.longestBatchMs,t)}async function _D(e,t,n){if(!e.renewLease)return"Upload credentials cannot be renewed in this remote";if(e.refreshes>=r_e)return`Upload credentials were renewed ${e.refreshes} times and the ${n} is still not done; re-run the command to continue`;try{e.lease=await e.renewLease()}catch(r){return`Could not renew upload credentials (${t}): ${G(r)}`}return e.refreshes++,e.onCredentialsRenewed?.(e.refreshes,t),null}function sxt(e){return[e.error,..."absent"in e?e.absent.flatMap((n)=>n.errors):[]].find(E6)}function ixt(e,t,n){let r=[],o=[],s=()=>{if(o.length===0)return;r.push(...k6(o,t,{maxFiles:n??HS})),o=[]};for(let i of e)if(t.has(i))o.push(i);else s(),r.push([i]);return s(),r}async function g_e(e){let t=0,n=!1,r=new Set,o=!0;for(;;){if(!n&&m_e(e.session)){let m=await _D(e.session,"close to expiry","recorded-file verification");if(m)return{success:!1,error:m}}n=!1;let s=Date.now(),i=await e.run(p_e(e.session));h_e(e.session,Date.now()-s);let a=r.size;if("sentPaths"in i){for(let m of i.sentPaths)r.add(m);if(i.output!=="understood"||i.filesSent!==i.sentPaths.length)o=!1}let c=r.size>a,l=sxt(i),d=Boolean(e.session.lease&&e.session.lease.expiresAtMs<=Date.now()&&(i.error!==void 0||("absent"in i)&&i.absent.length>0)),f=l??(d?"The credential lease expired while the recorded-file check was running":void 0);if(!f){if(!i.success)return{success:!1,error:i.error??`Failed to run the recorded-file ${e.operation}`};if("sentPaths"in i)return{success:!0,outcome:{...i,filesSent:o?r.size:i.filesSent,sentPaths:[...r],output:o?i.output:vD(i.output,"unrecognized")}};return{success:!0,outcome:i}}if(!e.session.lease||!e.session.renewLease)return{success:!1,error:i.error??`Expired upload credentials interrupted the recorded-file ${e.operation}: ${f}`};if(c)t=0;else t++;if(t>=x6)return{success:!1,error:`Recorded-file ${e.operation} keeps failing with expired credentials: ${f}`};let p=await _D(e.session,l?"expired during recorded-file verification":"lease expired during recorded-file verification","recorded-file verification");if(p)return{success:!1,error:p};n=!0}}function vD(e,t){return e==="unrecognized"||t==="unrecognized"?"unrecognized":e==="partial"||t==="partial"?"partial":"understood"}async function axt(e){let t=0,n="understood";for(let r of ixt(e.paths,e.sizes,e.batchMaxFiles))for(let o of fo(r)){let s=await g_e({session:e.credentialSession,operation:"copy check",run:(i)=>cw(e.absolutePath,e.remote,o,e.jobs,i)});if(!s.success)return s;t+=s.outcome.filesSent,n=vD(n,s.outcome.output)}return{success:!0,filesSent:t,output:n}}async function cxt(e){let t=0,n=[],r=[],o="understood";for(let s of fo(e.paths)){let i=await g_e({session:e.credentialSession,operation:"presence check",run:(a)=>ybe(e.absolutePath,e.remote,s,e.jobs,a)});if(!i.success)return{success:!1,error:i.error,present:t,absent:n,unanswered:r,output:o};t+=i.outcome.present,n=n.concat(i.outcome.absent),r=r.concat(i.outcome.unanswered),o=vD(o,i.outcome.output)}return{success:!0,present:t,absent:n,unanswered:r,output:o}}async function lxt(e){let t=0,n=0,r=new Set,o="understood",s=(i)=>({success:!1,error:i,filesCopied:t,filesSent:n,output:o});for(let i of e.batches){let a=0,c=!1;for(;;){let l;try{l=await ap(e.absolutePath,e.remote,i)}catch(b){return s(`Could not read the annex location log before copying: ${G(b)}`)}let d=i.filter((b)=>l.has(b));if(d.length===0)break;if(c)c=!1;else if(m_e(e.credentialSession)){let b=await _D(e.credentialSession,"close to expiry","copy");if(b)return s(b)}let f=Date.now(),p=await cw(e.absolutePath,e.remote,d,e.jobs,p_e(e.credentialSession));h_e(e.credentialSession,Date.now()-f);let m;try{m=await ap(e.absolutePath,e.remote,i)}catch(b){return s(`Could not read the annex location log after copying: ${G(b)}`)}let h=d.filter((b)=>m.has(b)),g=d.length-h.length;t+=g;for(let b of p.sentPaths)r.add(b);if(n=r.size,o=vD(o,p.output),h.length===0)break;if(p.success)break;if(!E6(p.error))return s(p.error??"Failed to copy pending files to the remote");if(!e.credentialSession.lease||!e.credentialSession.renewLease)return s(p.error??"Expired upload credentials cannot be renewed in this remote");if(a=g>0?0:a+1,a>=x6)return s(`Copy keeps failing with expired credentials and the pending location-log set did not shrink: ${p.error??"expired credentials"}`);let y=await _D(e.credentialSession,"expired during copy","copy");if(y)return s(y);c=!0}}return{success:!0,filesCopied:t,filesSent:n,output:o}}async function i_e(e){let{absolutePath:t,remote:n,addTargets:r}=e,o,s;try{o=await Cd(t),s=[...await ap(t,n)].sort()}catch(U){return{status:"unreadable",error:G(U)}}let i=null;if(o.size>0&&e.remoteIdentity)try{i=await ur(t)}catch{}let a=(U)=>{if(!i)return null;let B=[];for(let P of U){let O=i.get(P);if(O===void 0)return null;B.push([P,O])}if(!e.remoteIdentity)return null;return Vwe(B,e.remoteIdentity)},c=a(o),l=rxt(r,o);if(l.blocking.length>0)return{status:"blocked",blocking:l.blocking.map((U)=>({path:U.path,size:U.size}))};let d={inGit:[],leftOut:[]};if(l.small.length>0){let U;try{U=await cp(t)}catch(B){return{status:"unreadable",error:G(B)}}for(let B of l.small)(U.has(B.path)?d.inGit:d.leftOut).push(B.path);d.inGit.sort(),d.leftOut.sort()}let f=new Set(s),p=[...o].filter((U)=>!f.has(U)).sort(),m=a(p),h=p.length>0&&c!==null&&m!==null&&e.skipRecordedCheck?.(p.length,m)===!0,g=p,y=[];if(p.length>0&&!h)try{let U=await ap(t,"here");y=p.filter((B)=>U.has(B)),g=p.filter((B)=>!U.has(B))}catch(U){return{status:"unreadable",error:G(U)}}let b=new Map(e.dataFiles.map((U)=>[U.path,U.size])),_=k6(s,b,{maxFiles:e.batchMaxFiles,maxBytes:e.batchMaxBytes});await e.onPlan?.({total:o.size,pending:s.length,copyBatchCount:_.length,recorded:p.length,recordedNoLocal:y.length,recordedCheckSkipped:h,smallNotAnnexed:d});let x={credentials:e.credentials,lease:e.lease,renewLease:e.renewLease,refreshes:0,longestBatchMs:0,onCredentialsRenewed:e.onCredentialsRenewed},k=await lxt({absolutePath:t,remote:n,batches:_,jobs:e.jobs,credentialSession:x});if(!k.success)return{status:"copy_failed",error:k.error??"Failed to copy to remote"};let v=0,C="understood",T=[],z=[];if(!h){let U=await axt({absolutePath:t,remote:n,paths:g,sizes:b,jobs:e.jobs,batchMaxFiles:e.batchMaxFiles,credentialSession:x});if(!U.success)return{status:"copy_failed",error:U.error??"Failed to check the remote"};if(v=U.filesSent,C=U.output,y.length>0){let B=await cxt({absolutePath:t,remote:n,paths:y,jobs:e.jobs,credentialSession:x});if(!B.success)return{status:"copy_failed",error:B.error??"Failed to check the remote"};if(T=B.absent,z=B.unanswered,B.output!=="understood"&&C==="understood")C=B.output}}let A;try{A=[...await ap(t,n)].sort()}catch(U){return{status:"unverifiable",error:G(U)}}let F=new Set(A),M=[...T.filter((U)=>!F.has(U.file)).map((U)=>({file:U.file,why:U.errors[0]??"no reason given"})),...z.map((U)=>({file:U,why:"git-annex gave no result for it"}))];if(M.length>0){let U=M[0];return{status:"unverifiable",error:`git-annex could not confirm that ${M.length} recorded ${M.length===1?"file":"files"} with no local content ${M.length===1?"is":"are"} at the remote (${Kr(U.file)}: ${U.why})`}}if(A.length>0){let U=o.size+A.filter((O)=>!o.has(O)).length,B=[],P=!0;try{let O=await ap(t,"here");B=A.filter((H)=>O.has(H))}catch{P=!1;let O=new Set([...y,...T.map((H)=>H.file)]);B=A.filter((H)=>O.has(H))}return{status:"incomplete",missing:A,total:U,notLocal:B,notLocalKnown:P,lostAtRemote:T.map((O)=>O.file).sort()}}return{status:"ok",total:o.size,attempted:s.length,confirmed:k.filesCopied,sent:k.filesSent,resent:v,recordedNoLocal:y.length,recordedCheckSkipped:h,output:k.output,recordedOutput:C,remoteConfirmed:!h&&k.output==="understood"&&C==="understood",recordedCheckFingerprint:c,annexedPaths:o,smallNotAnnexed:d}}async function uxt(e,t,n){yl(t,"tracking");let r=Nr(e,t),o=n,s=null,i=[];try{let a=await cp(e);o=n.filter((c)=>a.has(c)),await zS(e,o),s=o.length}catch(a){i.push(G(a))}if(!r)i.push("the upload progress could not be saved, so the next run may skip the tracking step; if it does, run the upload with --restart");return{unstaged:s,staged:o,...i.length>0?{error:i.join("; ")}:{}}}function wD(e,t=5){let n=e.slice(0,t).map((r)=>` - ${Kr(r)}`);if(e.length>t)n.push(` ... and ${e.length-t} more`);return n}function y_e(e){return`'${e.replace(/'/g,"'\\''")}'`}function fxt(e,t){let n=e.map((o)=>o.path),r=[`${zi(e.length)} over ${BS()} ${e.length===1?"was":"were"} not added to git-annex and would be committed to git instead of uploaded to S3:`,...wD(n)];if(t.unstaged!==null){if(r.push(t.unstaged>0?` ${t.unstaged} of them ${Rd(t.unstaged)} unstaged so the next run can annex them; the files themselves are untouched.`:" None of them was staged, so nothing needed unstaging."),t.error)r.push(` But: ${t.error}.`)}else if(r.push(` Could not finish making the next run able to annex them: ${t.error}.`),t.staged.length===0)r.push(" None of them is staged, so fixing the cause is all that is left.");else if(t.staged.length>dxt)r.push(` ${t.staged.length} paths are involved; the next run tries again, unstaging them.`);else if(!t.staged.every(tc))r.push(" A name has a character that cannot go in a command; the next run tries again, unstaging them.");else r.push(" The next run tries again; to do it now, run this in the dataset directory:",` git --literal-pathspecs rm --cached --quiet --ignore-unmatch -- ${t.staged.map(y_e).join(" ")}`);return r.push(" Find out why git-annex declined them, fix that, then re-run `nemar dataset upload`:"," - a .gitattributes `annex.largefiles` setting overrides NEMAR's annex policy"," - a .gitignore pattern matches the file: git-annex skips an ignored file without saying so, while the upload plan lists every file on disk"),r}async function b_e(e,t){let{stdout:n,stderr:r,exitCode:o}=await R(["git","config","--get",`remote.${t}.annex-uuid`],{cwd:e});if(o===1)return!1;if(o!==0)throw Error(xD("git config",r,o));return n.trim().length>0}async function D6(e,t){return[...await b_e(e,t)?await ap(e,t):await Cd(e)].sort()}function pxt(e,t){return async()=>{let n=D("Requesting upload credentials...").start(),r;try{r=await Gr(t.dataset_id),n.succeed("Upload credentials received (2h expiry)")}catch(a){return n.fail(`Could not get upload credentials: ${G(a)}`),console.log(u.red(" Upload credentials are required for S3 access.")),console.log(u.dim(" Re-run the command to retry.")),Ne}n=D("Configuring S3 remote...").start();let o={name:mc,bucket:r.s3.bucket,prefix:`${t.dataset_id}/objects`,region:r.s3.region,publicUrl:t.s3_config.public_url},s=await Fo(e,o,lr(r.credentials));if(!s.success)return n.fail(`Failed to configure S3 remote: ${s.error}`),console.log(u.dim(" Re-run the command to retry.")),Ne;n.succeed("S3 remote configured");let i=v6(lr(r.credentials),r.credentials.expiration);return fn({credentials:i.credentials,lease:i,renewLease:async()=>{let a=await Gr(t.dataset_id);return v6(lr(a.credentials),a.credentials.expiration)},remoteIdentity:JSON.stringify([mc,PF(o)])})}}function gxt(e){if(e<60)return"under a minute";let t=Math.round(e/60);if(t<60)return`about ${t} ${t===1?"minute":"minutes"}`;let n=Math.floor(t/60),r=t%60,o=`${n} ${n===1?"hour":"hours"}`;return r===0?`about ${o}`:`about ${o} ${r} ${r===1?"minute":"minutes"}`}function yxt(e,t){let n=[];if(e.recorded===0)return n;if(e.recordedCheckSkipped)return n.push(` These ${e.recorded} recorded files and their annex keys passed a check at this destination within the last ${kw}; the remote is not asked about them again.`),n;if(e.recordedNoLocal>0)n.push(` ${zi(e.recordedNoLocal)} recorded at the S3 remote ${e.recordedNoLocal===1?"has":"have"} no content in this repository, so the remote is asked about ${e.recordedNoLocal===1?"it":"them"} with git-annex fsck.`);if(e.recorded>mxt){let r=Math.ceil(e.recorded*hxt/Math.max(1,t));n.push(` The remote is asked about each of the ${e.recorded.toLocaleString("en-US")} files already recorded there, one request each: ${gxt(r)} with ${t} parallel ${t===1?"job":"jobs"} (50 to 100 ms a request; --jobs changes it). A run that gets through it, with git-annex's answers understood, lets a re-run within ${kw} skip it.`)}return n}async function bxt(e){let{absolutePath:t,progress:n,addTargets:r}=e,o=null,s=(p)=>{if(o)o.fail(p);else console.log(u.red(p))};await Xr(t);let i,a=null,c=0;try{let p=await e.openRemote();if(p.status==="fail")return Ne;let m={absolutePath:t,remote:mc,remoteIdentity:p.value.remoteIdentity,addTargets:r,dataFiles:e.dataFiles,jobs:e.jobs,credentials:p.value.credentials,lease:p.value.lease,renewLease:p.value.renewLease,batchMaxFiles:e.copyBatchMaxFiles,onCredentialsRenewed:(h,g)=>{let y=`Renewed upload credentials (${g}; renewal ${h})`;if(o)o.info(y),o=D("Uploading data files to S3...").start();else console.log(u.dim(` ${y}`))},skipRecordedCheck:(h,g)=>Gwe(n,h,g),onPlan:(h)=>{let{inGit:g,leftOut:y}=h.smallNotAnnexed;if(g.length>0){console.log(u.dim(` ${g.length} small data file(s) (<= ${BS()}) were stored in git rather than the annex:`));for(let _ of wD(g,3))console.log(u.dim(_))}if(y.length>0){console.log(u.yellow(` Warning: ${y.length} small data file(s) (<= ${BS()}) are in neither git nor the annex and will NOT be uploaded; a .gitignore pattern probably matches them:`));for(let _ of wD(y,3))console.log(u.yellow(_))}for(let _ of yxt(h,e.jobs))console.log(u.dim(_));let b=h.recordedCheckSkipped?0:h.recorded;if(h.pending>0)o=D(`Uploading ${zi(h.pending)} in ${h.copyBatchCount.toLocaleString()} ${h.copyBatchCount===1?"copy batch":"copy batches"} to S3${b>0?` (then checking the S3 remote for ${zi(b)} already recorded)`:""}...`).start();else if(b>0)o=D(`Checking the S3 remote for ${zi(b)}...`).start()}};i=await i_e(m);while(i.status==="blocked"){let h=i.blocking.map((y)=>y.path);if(a=await uxt(t,n,h),c>0||a.unstaged===null)break;let g=await f_e(t,h,{annexJobs:e.annexJobs,onInactivityWarning:(y)=>{o=Q_t(o,a_e(y))}});if(!g.success){if(console.log(u.red(`Failed to track data files: ${g.error}`)),a.error)console.log(u.yellow(`The recovery before it also reported: ${a.error}`));return console.log(u.yellow("Re-run the same command to resume tracking.")),Ne}c=h.length,i=await i_e(m)}}finally{await Xr(t)}let l=i.status==="ok"||i.status==="copy_failed"||i.status==="incomplete"||i.status==="unverifiable";if(c>0&&l)gl(n,"tracking"),Nr(t,n),console.log(u.dim(` ${zi(c)} git-annex had declined ${Rd(c)} unstaged and added again; ${c===1?"it is":"they are"} annexed now.`));switch(i.status){case"unreadable":return console.log(u.red(`Could not read the annex location log: ${i.error}`)),console.log(u.yellow("Re-run the same command to retry.")),Ne;case"blocked":{let p=a??{unstaged:null,staged:[],error:"no recovery ran"};for(let m of fxt(i.blocking,p))console.log(m.startsWith(" ")?u.yellow(m):u.red(m));return Ne}case"copy_failed":return s(`S3 upload failed: ${i.error}`),console.log(u.yellow("Re-run the same command to resume uploading.")),Ne;case"unverifiable":return s(`Could not confirm the S3 upload is recorded: ${i.error}`),console.log(u.yellow("Re-run the same command to retry.")),Ne;case"incomplete":{s(`S3 upload incomplete: ${i.missing.length} of ${i.total} annexed data files are not recorded at the S3 remote`);for(let h of wD(i.missing))console.log(u.red(h));let p=i.lostAtRemote.length;if(p>0)console.log(u.red(`git-annex reports that the S3 remote no longer holds ${p} of them: fsck did not find ${p===1?"it":"them"} there and struck ${p===1?"it":"them"} from the location log.`)),console.log(u.yellow(`If the remote could not be read, rather than having lost the objects, \`git annex fsck --fast --from ${mc}\` puts back the keys that were struck only for that reason.`));let m=i.notLocal.length;if(m>0){let h=i.notLocal[0],y=m===1&&i.notLocalKnown&&tc(h)?`git annex get -- ${y_e(h)}`:`git annex get --not --in ${mc}`,_=`${i.notLocalKnown?"":"At least "}${m} of them ${m===1?"has":"have"} no content in this repository, so ${m===1?"it cannot":"they cannot"} be uploaded from here.`;console.log(u.yellow(`${_} ${p>0?"Get the content from another copy of the dataset":`Fetch ${m===1?"it":"them"}`} with \`${y}\`, then re-run.`))}else if(!i.notLocalKnown)console.log(u.yellow(`Which of them have no content in this repository could not be read. If re-running does not help, fetch the missing content with \`git annex get --not --in ${mc}\`, then re-run.`));else console.log(u.yellow("Re-run the same command to resume uploading."));return Ne}case"ok":break}for(let p of r)Xwe(n,p.path,{size:p.size,mtimeMs:p.mtimeMs});if(i.remoteConfirmed&&i.recordedCheckFingerprint!==null)Wwe(n,i.total,i.recordedCheckFingerprint);Nr(t,n);let d=oxt(i.total,i.attempted,i.confirmed,{sent:i.sent,resent:i.resent,recordedNoLocal:i.recordedNoLocal,recordedCheckSkipped:i.recordedCheckSkipped,output:i.output,recordedOutput:i.recordedOutput}),f=i.output!=="understood"||i.recordedOutput!=="understood";if(o)if(f)o.warn(d);else o.succeed(d);else console.log(f?u.yellow(d):d);return fn({annexedPaths:i.annexedPaths})}async function w_e(e,t,n,r,o,s,i={}){let a=o,c,l=null;if(!a)a=Jwe(e,s.dataset_id,n);else{if(Hi(a,"tracking")&&Qwe(a,n))yl(a,"tracking"),console.log(u.dim(" Data files changed since the last run; re-running git-annex add"));for(let x of n)if(!a.files[x.path])a.files[x.path]={status:"pending",size:x.size,mtimeMs:x.mtimeMs,updated_at:new Date().toISOString()};Nr(e,a)}let d;try{d=await cp(e)}catch(x){return console.log(u.red(`Failed to read the git index: ${G(x)}`)),console.log(u.dim(" Re-run the command to retry.")),Ne}let f=nxt(r,n,d),p=t.annexJobs===void 0?qg:Number(t.annexJobs),m,h;try{h=await b_e(e,mc),m=await D6(e,mc)}catch(x){return console.log(u.red(`Could not read the annex location log: ${G(x)}`)),console.log(u.yellow("Re-run the same command to retry.")),Ne}let g=f.length>0||m.length>0,y=f.length-r.length,b=y>0&&Hi(a,"tracking"),_=g&&Hi(a,"s3_upload");if(b)yl(a,"tracking");if(_)yl(a,"s3_upload"),yl(a,"dataset_save"),yl(a,"github_push");if(b||_)Nr(e,a);if(b)console.log(u.yellow(` ${y} data files are missing from git despite recorded progress; re-tracking them`));if(_)console.log(u.yellow(f.length>0?` ${f.length} data file(s) still need upload despite a completed s3_upload step; resuming`:h?` ${m.length} annexed data file(s) are not recorded at the S3 remote despite a completed s3_upload step; resuming`:" The S3 remote is not set up in this repository, so nothing can be recorded there despite a completed s3_upload step; resuming and checking every annexed data file against it"));if(!Hi(a,"s3_upload")){if(g){if(f.length>0&&!Hi(a,"tracking")){let k=i.primeMinBytes??Mwe,v={...i.primeChunkPaths===void 0?{}:{chunkPaths:i.primeChunkPaths},...i.primeSpinnerStream?{stream:i.primeSpinnerStream}:{}};if(!await s_e(e,f,k,"before",v))return Ne;c=D(`Tracking ${f.length} data files with git-annex...`).start();let C=await f_e(e,f.map((T)=>T.path),{annexJobs:p,onInactivityWarning:(T)=>{c=Sw(c,a_e(T))}});if(!C.success)return c.fail(`Failed to track data files: ${C.error}`),console.log(u.yellow("Re-run the same command to resume tracking.")),Ne;if(c.succeed("Data files tracked by git-annex"),gl(a,"tracking"),Nr(e,a),!await s_e(e,f,k,"after",{...v,...i.primeOnSuspended?{onSuspended:i.primeOnSuspended}:{}}))return Ne}else if(f.length>0)console.log(u.dim(" Data files already tracked by git-annex (skipping)"));let x=await bxt({absolutePath:e,progress:a,addTargets:f,dataFiles:n,jobs:Number.parseInt(t.jobs,10),annexJobs:p,openRemote:i.openRemote??pxt(e,s)});if(x.status==="fail")return Ne;l=x.value.annexedPaths}else console.log(u.dim("No data files to upload to S3"));gl(a,"s3_upload"),Nr(e,a)}else console.log(u.dim(" S3 upload already completed (skipping)"));return fn({progress:a,annexedPaths:l})}var qg=4,Rd=(e)=>e===1?"was":"were",dxt=50,mc="nemar-s3",mxt=5000,hxt=0.075;var Ad=V(()=>{He();ro();Za();ec();Je();sp();fD();qf();rc();y6();ji();Fi();ug();qt();cc();Pr();gD();_6();ip()});import{existsSync as wxt,readFileSync as _xt,writeFileSync as xxt}from"fs";import{join as vxt}from"path";function kxt(e){return e.startsWith("ASIA")}function Ext(e){if(e==="inherit")return;if(kxt(e.accessKeyId)&&!e.sessionToken)throw Error(`Refusing to transfer with temporary AWS credentials that carry no session token: S3 rejects every such request with a bare 403. Pass the session token the credential response returned, or say "inherit" to use the environment's own credentials.`);return e}function $xt(e){return(e.split("/").pop()??e).startsWith(".git")}function Od(e){let t=e.endsWith(`
|
|
198
198
|
`),n=e.split(`
|
|
199
199
|
`);if(t)n.pop();let r=[],o=[],s=0;for(let a of n){let c=a.trim();if(c===""||c.startsWith("#")){r.push(a);continue}if(/["']/.test(c)&&c.includes("annex.largefiles")){o.push(c),r.push(a);continue}let l=c.split(/\s+/),[d,...f]=l;if($xt(d)){r.push(a);continue}let p=f.filter((h)=>!Sxt.test(h)),m=f.length-p.length;if(m===0){r.push(a);continue}if(s+=m,p.length>0)r.push([d,...p].join(" "))}return{content:r.length===0?"":r.join(`
|
|
200
200
|
`)+(t?`
|
|
@@ -204,7 +204,7 @@ ${vw(e,t,a,n())}
|
|
|
204
204
|
${p}`:", ";return`${e.slice(0,c)}${h}${m}${e.slice(c)}`}function Aw(e){try{return Ow(e).isFile()}catch{return!1}}async function Xxt(e){let t=[["git","diff","--name-only","-z","--no-renames","HEAD","--"],["git","ls-files","--others","--exclude-standard","-z"]],n=[];for(let r of t){let o=await R(r,{cwd:e});if(o.exitCode!==0)throw Error("git could not list the paths changed since HEAD");n.push(...o.stdout.split("\x00").filter((s)=>s!==""))}return n}async function Qxt(e,t){for(let n of fo(t))if((await R(["git","-c","annex.largefiles=nothing","add","--",...n],{cwd:e})).exitCode!==0)throw Error(`git add failed for ${n.length} scrubbed file(s)`)}function Zxt(e){let t=mi(e,ho);if(!Txt(t))return!1;let n;try{n=Wbe(t)}catch{return!0}let r=!1;for(let o of n){if(o.action==="history-rewritten")r=!1;if(o.action==="import-scrubbed"&&((o.counts.json_values_blanked??0)>0||(o.counts.git_held_recordings_scrubbed??0)>0))r=!0}return r}async function P6(e){try{return await evt(e)}catch(t){if(t instanceof Gt)throw t;throw new Gt("scrub-failed",yo(t))}}async function evt(e){let{datasetPath:t}=e,n=Wxt(),r=[...await cp(t)].sort(),o=e.scope,s=o?r.filter((W)=>o.has(W)):r;if(o){let W=(await Xxt(t)).filter((J)=>!o.has(J)).length;if(W>0)throw new Gt("scope-incomplete",`${W} path(s) changed since HEAD, or untracked, are outside the scrub's scope`)}let i=await ur(t),a=s.filter((W)=>Mo.test(W));n.recordings=a.length;let c=!e.reimport,l=[],d=[],f=new Set,p=[];for(let W of a){let J=i.get(W);if(J===void 0){l.push(W);continue}if(e.skipData){n.headers_not_read_skip_data++;continue}if(No(J)===0){n.headers_not_edf++,f.add(J);continue}if(e.sourceOf){let It=e.sourceOf(J);if(It==="held")n.headers_not_read_nemar_held++;else if(It===null)n.headers_not_read_no_source++;else d.push({path:W,key:J,source:It});continue}let le=e.keyUrlMap.get(J);if(le===void 0){if(e.reimport)n.headers_not_read_nemar_held++;else n.headers_not_read_no_source++;continue}let ne=j$(le),Ue=ne?{kind:"s3",ref:ne}:/^https?:\/\//.test(le)?{kind:"url",url:le}:null;if(!Ue){p.push("source-unsupported");continue}d.push({path:W,key:J,source:Ue})}let m=[];for(let W of l){let J=C6(mi(t,W));if(J===null){p.push("local-unreadable");continue}n.headers_read++;let le=A6(J,c);if(le===null){n.headers_not_edf++;continue}if(le.change.datesLeft)n.headers_dates_left++;if(le.change.datesUnproven)n.headers_dates_unproven++;if(le.change.scrub||le.change.dates)m.push({path:W,change:le.change})}let h=await Kxt(d,e.concurrency??16,(W)=>e.reader.header(W.source)),g=[...p],y=[],b=[];if(h.forEach((W,J)=>{let le=d[J];if(!W.ok){g.push(W.failure);return}let ne=No(le.key);if(ne!==null&&W.total===null){g.push("no-length");return}if(ne!==null&&W.total!==ne){y.push(le.key);return}n.headers_read++,f.add(le.key);let Ue=A6(W.bytes,c);if(Ue===null){n.headers_not_edf++;return}if(Ue.change.datesLeft)n.headers_dates_left++;if(Ue.change.datesUnproven)n.headers_dates_unproven++;if(Ue.change.scrub||Ue.change.dates)b.push({...le,size:ne??0,change:Ue.change})}),g.length>0){let W=g.every((J)=>J==="http-403"||J==="http-404");throw new Gt("header-unreadable",`${g.length} of ${a.length} recording header(s) could not be read: ${Jxt(g)}`,W)}if(y.length>0)throw new Gt("upstream-size-mismatch",`${y.length} upstream object(s) are not the size their annex key declares`);let _=b.filter((W)=>W.change.scrub),x=m.filter((W)=>W.change.scrub),k=_.length+x.length;if(e.reimport&&k>0)throw new Gt("already-imported-unscrubbed",`${k} recording(s) in the dataset's own tree need a scrub; correct it with ADR 0085's procedure, not by re-importing`);let v=(W)=>Ed.test(W.key)&&W.size>0;if(_.some((W)=>!v(W))){let W=_.filter((J)=>!v(J)).length;throw new Gt("unsupported-key-backend",`${W} recording key(s) to replace are not SHA256E with a declared size`)}let C=e.maxBytes??$w,T=_.reduce((W,J)=>W+J.size,0),z=e.unannexedData.reduce((W,J)=>W+J.size,0);if(T+z>C)throw new Gt("bound-exceeded",`${_.length} recording(s) to scrub, ${(T/1073741824).toFixed(1)} GiB to download and ${(z/1073741824).toFixed(1)} GiB of git-held data to upload, over the ${(C/1073741824).toFixed(1)} GiB bound; run on a host that can move them with --normalize-max-gb`);let A=b.filter((W)=>!W.change.scrub),F=A.filter(v);n.headers_dates_left+=A.length-F.length;let M=F.reduce((W,J)=>W+J.size,0),U=T+z+M<=C;if(!U)n.headers_dates_over_bound=F.length,n.headers_dates_left+=F.length;let B=new Set(U?F:[]),P=b.filter((W)=>W.change.scrub||B.has(W)),O=[];if(o&&(P.length>0||m.length>0)){let W=[Ds,di].filter((J)=>!o.has(J)&&r.includes(J)).length;if(W>0)throw new Gt("provenance-out-of-scope",`${W} provenance file(s) are outside the scope of a scrub that changes headers`)}for(let W of P){let J=mi(t,W.path),le=`${J}.nemar-scrub-download`,ne=await e.reader.download(W.source,le);if(!W.change.scrub){let It=Ed.exec(W.key)?.[2],mr=ne.ok&&ne.bytes===W.size&&await S_e(le)===It;if(mr)try{R6(le,c)}catch{mr=!1}if(!mr){Pd(le,{force:!0}),n.headers_dates_failed++,n.headers_dates_left++;continue}n.bytes_downloaded+=W.size,Pd(J,{force:!0}),__e(le,J),O.push(W);continue}if(!ne.ok)throw new Gt("header-unreadable",`a recording to scrub could not be downloaded: ${ne.failure}`,ne.failure==="http-403"||ne.failure==="http-404");let Ue=Ed.exec(W.key)?.[2];if(ne.bytes!==W.size||await S_e(le)!==Ue)throw Pd(le,{force:!0}),new Gt("content-mismatch","a downloaded recording does not hash to the key it was downloaded for");n.bytes_downloaded+=ne.bytes,R6(le,c),Pd(J,{force:!0}),__e(le,J),O.push(W)}for(let W of m)R6(mi(t,W.path),c);n.headers_scrubbed=k,n.git_held_recordings_scrubbed=x.length;let H=m.filter((W)=>W.change.dates).length;n.headers_dates_normalized=O.filter((W)=>W.change.dates).length+H,n.git_held_recordings_dates_normalized=H;let re=[],Ee=new Set,Qt=new Set,ft=[],Ze=m.map((W)=>W.path),oe=[...O.map((W)=>({path:W.path,size:W.size})),...e.skipData?[]:Ze.map((W)=>({path:W,size:Ow(mi(t,W)).size}))];if(e.skipData)ft.push(...Ze);if(oe.length>0){if(!e.upload)throw Error("scrubbed recordings need an upload strategy");let W;try{W=await Dw({datasetPath:t,files:oe,remoteName:e.remoteName,bucket:e.bucket,nemarId:e.nemarId,maxBytes:C,upload:e.upload,backend:"SHA256E"})}catch(ne){throw new Gt("upload-failed",`${oe.length} scrubbed recording(s) could not be annexed or uploaded: ${yo(ne)}`)}re.push(...W.items);for(let ne of Ze)Qt.add(ne);let J=new Map(W.files.map((ne)=>[ne.path,ne.key])),le={};for(let ne of O){let Ue=J.get(ne.path);if(!Ue||!Ed.test(Ue)||Ue===ne.key)throw new Gt("scrub-unverified","a scrubbed recording has no new key");le[ne.key]=Ue,Ee.add(ne.key)}if(n.upstream_keys_replaced=Ee.size,Ee.size>0){let ne;try{ne=await owe({repo:t,keymap:le,remoteUuids:[],execute:!0})}catch(It){throw new Gt("retire-failed",`the git-annex branch could not be updated: ${yo(It)}`)}let Ue=new Set(Object.values(le)).size;if(ne.oldStillHeld!==0||ne.oldDead!==ne.oldKeys||ne.deadRefused!==0||ne.newPresent!==Ue)throw new Gt("retire-failed",`${ne.oldKeys-ne.oldDead} of ${ne.oldKeys} replaced key(s) not recorded dead, ${Ue-ne.newPresent} new key(s) not recorded at the remote`)}}for(let W of s){if(!lp.test(W))continue;if(i.has(W)){n.json_files_annexed++;continue}let J=mi(t,W);if(!Aw(J)||Ow(J).size>O6){n.json_files_unread++;continue}let le;try{le=jg(ED(J))}catch(ne){if(ne instanceof op)throw new Gt("scrub-unverified","a blanked JSON file failed its proof");throw ne}if(le.status==="unreadable"){n.json_files_unread++;continue}if(n.json_files_read++,le.status==="blanked"&&le.bytes)Cw(J,le.bytes),ft.push(W),n.json_files_blanked++,n.json_values_blanked+=le.blanked}if(c)for(let W of s){if(!up.test(W))continue;if(i.has(W)){n.scans_tables_annexed++;continue}let J=mi(t,W);if(!Aw(J)||Ow(J).size>T6){n.scans_tables_unread++;continue}let le;try{le=lD(ED(J))}catch{le={status:"unreadable",values:0}}if(le.status==="unreadable"){n.scans_tables_unread++;continue}if(n.scans_tables_read++,le.status==="normalized"&&le.bytes)Cw(J,le.bytes),ft.push(W),n.scans_tables_normalized++,n.scans_values_normalized+=le.values}n.images_or_documents_held=Y$(s).filter((W)=>W.kind==="image-or-document-file").length;let je=n.headers_scrubbed>0||n.headers_dates_normalized>0||n.json_values_blanked>0||n.scans_values_normalized>0,Ie=e.now??new Date,Q=Ie.toISOString().slice(0,10),pt=n.headers_scrubbed>0?n.headers_dates_normalized>0?"scrubbed-and-dates-set":"scrubbed-in-place":n.headers_dates_normalized>0?"dates-set":null;if(pt!==null){let W=mi(t,Ds);if(s.includes(Ds)&&Aw(W)){let le=ED(W,"utf8"),ne=le.charCodeAt(0)===65279?String.fromCharCode(65279):"",Ue=Yxt(le.slice(ne.length),Tg,Hbe(Q,pt));if(Ue!==null)Cw(W,`${ne}${Ue}`),ft.push(Ds),n.provenance_annotated=1;else n.provenance_malformed++}else if(s.includes(Ds))n.provenance_not_annotated++;let J=mi(t,di);if(s.includes(di)&&Aw(J)){let le=X$(Q,pt),ne=ED(J,"utf8");if(!ne.endsWith(le))Cw(J,`${ne}${ne===""||ne.endsWith(`
|
|
205
205
|
`)?"":`
|
|
206
206
|
`}${le}`),ft.push(di);n.provenance_readme_annotated=1}else if(s.includes(di))n.provenance_not_annotated++}let Be=!1;if(je){let W=process.env.GITHUB_ACTOR,J=e.actor??(W&&Uxt.test(W)?W:Bxt);Gbe(mi(t,ho),{version:1,at:Ie.toISOString(),dataset:e.nemarId,action:e.ledgerAction??"import-scrubbed",versions:[],counts:{...n},scanner:qxt,verification:"scanner-clean+payload-identical",actor:J}),ft.push(ho),await Qxt(t,ft);let le=[`Recording headers scrubbed: ${n.headers_scrubbed} (identification fields only; signal bytes unchanged).`,`Acquisition dates set to 1 January of their year: ${n.headers_dates_normalized} recording header(s), ${n.scans_values_normalized} scans table value(s) in ${n.scans_tables_normalized} file(s).`,`JSON values blanked: ${n.json_values_blanked} in ${n.json_files_blanked} file(s).`,`Images and documents left for review: ${n.images_or_documents_held}.`,`Recorded in ${ho}.`].join(`
|
|
207
|
-
`),ne=[...new Set([...ft,...oe.map((mr)=>mr.path)])],Ue=Pxt(mi(Fxt(),"nemar-scrub-pathspec-")),It=mi(Ue,"paths");Cw(It,`${ne.join("\x00")}\x00`,{mode:384});try{if((await R(["git","-c","annex.largefiles=nothing","commit","-m","Privacy correction on import (ADR 0089)","-m",le,`--pathspec-from-file=${It}`,"--pathspec-file-nul"],{cwd:t})).exitCode!==0)throw Error("could not commit the import scrub")}finally{Pd(Ue,{recursive:!0,force:!0})}Be=!0}return{counts:n,items:re,replacedKeys:Ee,handledPaths:Qt,historyHoldsOriginals:n.json_values_blanked>0||n.git_held_recordings_scrubbed>0||e.reimport&&Zxt(t),headerReadKeys:f,committed:Be}}async function tvt(e,t,n){try{return await nvt(e,t,n)}catch(r){if(r instanceof Gt)throw r;throw new Gt("scrub-failed",yo(r))}}async function nvt(e,t,n){let r=new Set((await ur(e)).values()),o=[...n].filter((d)=>r.has(d)).length;if(o>0)throw new Gt("old-key-still-named",`${o} replaced key(s) are still named by the tree`);let s=new Map;for(let d of t)if(!s.has(d.key))s.set(d.key,d);let i=[...s.values()].filter((d)=>r.has(d.key)),a=s.size-i.length,c=await Ig(e,i.map((d)=>d.key)),l=i.filter((d,f)=>!fi(c[f]??""));return{items:l,droppedNotInTree:a,droppedDead:i.length-l.length}}function I6(e,t,n){let r=new Set([...t].filter(([s])=>Mo.test(s)).map(([,s])=>s)),o=e.filter((s)=>!fl(s)&&r.has(s.key)&&!n.has(s.key)).length;if(o>0)throw new Gt("header-unreadable",`${o} recording(s) in the copy manifest whose header this run did not read`)}async function O_e(e){let t=await P6({datasetPath:e.datasetPath,nemarId:e.nemarId,keyUrlMap:e.keyUrlMap,unannexedData:e.unannexedData,reimport:e.reimport,skipData:e.skipData,maxBytes:e.maxBytes,reader:e.reader,upload:e.upload,remoteName:e.remoteName,bucket:e.bucket,now:e.now,actor:e.actor}),n=await kD({datasetPath:e.datasetPath,nemarId:e.nemarId,bucket:e.bucket,remoteName:e.remoteName,unannexedData:e.unannexedData.filter((s)=>!t.handledPaths.has(s.path)),upstreamKeys:new Set(e.keyUrlMap.keys()),carryOverUnaccountedKeys:e.reimport&&!e.skipData,upload:e.upload,maxBytes:e.maxBytes}),r=e.skipData?{items:[],droppedNotInTree:0,droppedDead:0}:await tvt(e.datasetPath,[...e.upstreamItems,...t.items,...n.items],t.replacedKeys),o;try{o=await ur(e.datasetPath)}catch(s){throw new Gt("scrub-failed",yo(s))}return I6(r.items,o,t.headerReadKeys),{scrub:t,normalized:n,manifest:r,privacy:{version:1,historyHoldsOriginals:t.historyHoldsOriginals}}}var C_e,Gt,jxt,Lxt,qxt,Bxt="nemar-importer",Uxt,O6=1048576,T6=8388608,Mo,lp,up,x_e="nemar-cli-import-scrub",zxt;var Vi=V(()=>{Q$();$d();ep();ml();_w();ji();qt();Pr();u6();Td();cs();Ad();C_e=["header-unreadable","upstream-size-mismatch","bound-exceeded","content-mismatch","unsupported-key-backend","already-imported-unscrubbed","old-key-still-named","retire-failed","scrub-unverified","upload-failed","provenance-out-of-scope","scope-incomplete","scrub-failed"];Gt=class Gt extends Error{code;constructor(e,t,n=!1){super(`${n?`${dD} `:""}${Awe} refused: ${e} (${t}). Nothing was pushed, and the copy phase did not run.`);this.code=e;this.name="ImportScrubRefused"}};jxt=new Set(["GitScrubError","ContractError","LedgerRefused"]),Lxt=/^[A-Z][A-Z0-9_]{1,20}$/;qxt=`identifier-scan@${"465a827fb0758d21"}`,Uxt=/^[a-z0-9][a-z0-9-]{0,38}$/i,Mo=/\.(edf|bdf)$/i,lp=/\.json$/i,up=/_scans\.tsv$/;zxt=new Set(["ENOSPC","EACCES","EPERM","EROFS","EIO","EMFILE","ENFILE"])});function I_e(e){let t=e.map((o,s)=>`$a${s}: ID!`).join(", "),n=e.map((o,s)=>`a${s}: dataset(id: $a${s}) { id latestSnapshot { tag created } snapshots { tag created } }`).join(" "),r={};return e.forEach((o,s)=>{r[`a${s}`]=o}),{query:`query UpstreamSnapshots(${t}) { ${n} }`,variables:r}}function rvt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function bl(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function T_e(e){if(!bl(e)||typeof e.tag!=="string"||e.tag==="")return null;let t=e.created;if(t!==void 0&&t!==null&&typeof t!=="string")return null;return{tag:e.tag,created:typeof t==="string"?t:null}}function ovt(e,t){if(e.id!==t)return{kind:"error",reason:`OpenNeuro answered ${String(e.id)} where ${t} was asked`};if(!Array.isArray(e.snapshots))return{kind:"error",reason:`OpenNeuro sent no snapshot list for ${t}`};let n=[];for(let o of e.snapshots){let s=T_e(o);if(!s)return{kind:"error",reason:`OpenNeuro sent a malformed snapshot for ${t}`};n.push(s)}let r=null;if(e.latestSnapshot!==null&&e.latestSnapshot!==void 0){if(r=T_e(e.latestSnapshot),!r)return{kind:"error",reason:`OpenNeuro sent a malformed latest snapshot for ${t}`}}else if(n.length>0)return{kind:"error",reason:`OpenNeuro sent snapshots for ${t} but no latest snapshot`};return{kind:"snapshot",latest:r,snapshots:n}}function P_e(e,t){if(!Array.isArray(e))return null;for(let n of e)if(bl(n)&&Array.isArray(n.path)&&n.path[0]===t)return n;return null}function N_e(e,t){let n=new Map,r=bl(e)?e.data:void 0;if(!bl(e)||!bl(r)){let o=bl(e)&&Array.isArray(e.errors)?e.errors[0]:void 0,s=bl(o)&&typeof o.message==="string"?o.message:"the response carried no data";for(let i of t)n.set(i,{kind:"error",reason:`OpenNeuro: ${s}`});return n}return t.forEach((o,s)=>{let i=`a${s}`,a=r[i];if(bl(a)){let c=P_e(e.errors,i);if(c){let l=typeof c.message==="string"?c.message:"an error";n.set(o,{kind:"error",reason:`OpenNeuro sent data and an error for ${o}: ${l}`});return}n.set(o,ovt(a,o));return}if(a===null){let c=P_e(e.errors,i),l=c&&typeof c.message==="string"?c.message:null,d=c&&bl(c.extensions)?c.extensions.code:void 0;if(l===null)n.set(o,{kind:"error",reason:`OpenNeuro sent null for ${o} without saying why`});else if(d==="DELETED_DATASET")n.set(o,{kind:"deleted",reason:l});else if(new RegExp(`^Dataset ${rvt(o)} does not exist\\.?$`).test(l))n.set(o,{kind:"absent",reason:l});else n.set(o,{kind:"error",reason:l});return}n.set(o,{kind:"error",reason:`OpenNeuro did not answer ${o}`})}),n}function Tw(e){return e.checksum_algorithm==="git"}var F_e="Published file is missing from storage",svt,M_e,j_e;var $D=V(()=>{Ko();svt=ee({path:S().min(1),size:j().int().nonnegative(),checksum:S().optional(),checksum_algorithm:S().optional(),bytes_url:S().min(1),url:S().nullish(),error:S().optional()}).passthrough(),M_e=he(svt),j_e=ee({dataset_id:S().optional(),latest:S().nullish(),versions:he(ee({version:S().min(1)}).passthrough())}).passthrough()});import{existsSync as N6,mkdirSync as B_e,rmSync as ivt,statSync as avt}from"fs";import{dirname as cvt,join as lvt,resolve as L_e}from"path";function q_e(e){return e===null?!0:e!==404}function dvt(e){return e===408||e===425||e===429||e>=500}async function pvt(e){if(!(e.headers.get("content-type")??"").includes("json"))return!1;if(Number(e.headers.get("content-length")??0)>fvt)return!1;try{return(await e.json())?.error===F_e}catch{return!1}}async function mvt(e,t,n){let r=lvt(t,e.path),o=L_e(t),s=L_e(r);if(s!==o&&!s.startsWith(`${o}/`))return{written:null,error:{message:`${e.path}: refusing to write outside the output directory`,infrastructure:!0}};if(N6(r))try{if(avt(r).size===e.size)return{written:null}}catch(l){console.warn(u.dim(` could not read existing ${e.path} (${l instanceof Error?l.message:String(l)}); re-fetching`))}let i=cvt(r);if(!N6(i))B_e(i,{recursive:!0});let a=`${e.path}: download failed`,c=!0;for(let l=1;l<=n;l++){let d=()=>Bun.sleep(250*2**(l-1)),f;try{f=await fetch(e.url,{redirect:"follow"})}catch(m){if(a=`${e.path}: ${m instanceof Error?m.message:String(m)}`,c=q_e(null),l<n){await d();continue}break}if(!f.ok){if(a=`${e.path}: HTTP ${f.status}`,c=q_e(f.status),f.status===502&&await pvt(f)){a=`${e.path}: HTTP 502 (listed in the manifest, missing from storage)`,c=!1;break}if(dvt(f.status)&&l<n){await d();continue}break}let p;try{p=await Bun.write(r,f)}catch(m){a=`${e.path}: ${m instanceof Error?m.message:String(m)}`,c=!0;break}if(p===e.size)return{written:p};try{ivt(r,{force:!0})}catch{}if(a=`${e.path}: expected ${e.size} bytes, received ${p}`,c=!0,l<n){await d();continue}break}return{written:null,error:{message:a,infrastructure:c}}}async function DD(e,t,n={}){let r=Math.max(1,Math.min(n.concurrency??4,wl)),o=Math.max(1,n.attempts??uvt);if(!N6(t))B_e(t,{recursive:!0});let s=[...e],i={filesDownloaded:0,filesSkipped:0,bytesDownloaded:0,bytesSkipped:0,errors:[],hadInfrastructureFailure:!1},a=0,c=async()=>{for(;;){let l=s.shift();if(!l)return;let d=await mvt(l,t,o);if(d.error){if(i.errors.push(d.error.message),d.error.infrastructure)i.hadInfrastructureFailure=!0}else if(d.written===null)i.filesSkipped++,i.bytesSkipped+=l.size;else i.filesDownloaded++,i.bytesDownloaded+=d.written;a++,n.onProgress?.(a,e.length,i.bytesDownloaded)}};return await Promise.all(Array.from({length:Math.min(r,e.length||1)},()=>c())),i}var wl=16,uvt=3,fvt=4096;var RD=V(()=>{He();$D()});var{spawn:z_e}=globalThis.Bun;function G_e(e){return hvt.test(e)}async function W_e(e,t={}){let n=t.graphqlUrl??Bg,r=Math.max(1,t.attempts??3),o="no attempt was made";for(let s=1;s<=r;s++){let i;try{let h=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":"nemar-cli"},body:JSON.stringify({query:"query LatestTag($id: ID!) { dataset(id: $id) { latestSnapshot { tag } } }",variables:{id:e}}),signal:AbortSignal.timeout(t.timeoutMs??30000)});if(!h.ok){if(o=`OpenNeuro GraphQL answered HTTP ${h.status}`,s<r)await CD(t.retryDelayMs??2000*s);continue}i=await h.json()}catch(h){if(o=`OpenNeuro GraphQL unreachable (${h instanceof Error?h.message:String(h)})`,s<r)await CD(t.retryDelayMs??2000*s);continue}let a=hc(i)?i:{},c=hc(a.data)?a.data:{},l=hc(c.dataset)?c.dataset:null,f=(l&&hc(l.latestSnapshot)?l.latestSnapshot:null)?.tag;if(Jo(f))return{tag:f};if(typeof f==="string")return{tag:null,reason:"OpenNeuro named a latest tag of an unexpected shape"};let m=(Array.isArray(a.errors)?a.errors:[]).map((h)=>hc(h)&&typeof h.message==="string"?h.message:null).filter((h)=>h!==null).join("; ").slice(0,200);if(l===null)return{tag:null,reason:m?`OpenNeuro: ${m}`:"OpenNeuro knows no such dataset"};return{tag:null,reason:"OpenNeuro names no snapshot for this dataset yet"}}return{tag:null,reason:o}}function U_e(e,t){let n=hc(e)?e.files:void 0;if(!Array.isArray(n))return`OpenNeuro sent no file list for the ${t} snapshot`;let r=[],o=new Set;for(let[s,i]of n.entries()){if(!(hc(i)&&typeof i.filename==="string"&&typeof i.id==="string"&&typeof i.annexed==="boolean"&&(i.size===null||Number.isSafeInteger(i.size)&&i.size>=0)&&(i.directory===void 0||i.directory===null||typeof i.directory==="boolean")))return`OpenNeuro sent a malformed file entry (${t} snapshot, entry ${s})`;let c=i;if(o.has(c.filename))return`OpenNeuro listed ${c.filename} twice (${t} snapshot, entry ${s})`;o.add(c.filename),r.push({filename:c.filename,id:c.id,size:c.size,annexed:c.annexed,directory:c.directory===!0})}if(!r.some((s)=>!s.directory))return`OpenNeuro sent an empty file list for the ${t} snapshot`;if(!r.some((s)=>!s.directory&&s.filename==="dataset_description.json"))return`OpenNeuro sent a file list with no root dataset_description.json for the ${t} snapshot`;return r}async function K_e(e,t,n,r={}){let o;try{let p=await fetch(r.graphqlUrl??Bg,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":"nemar-cli"},body:JSON.stringify({query:gvt,variables:{ds:e,from:t,to:n}}),signal:AbortSignal.timeout(r.timeoutMs??120000)});if(!p.ok)return{ok:!1,error:`OpenNeuro GraphQL answered HTTP ${p.status}`,transport:!0};o=await p.json()}catch(p){return{ok:!1,error:`OpenNeuro GraphQL unreadable (${p instanceof Error?p.message:String(p)})`,transport:!0}}let s=hc(o)?o:{},i=hc(s.data)?s.data:{},a=Array.isArray(s.errors)?s.errors:[],c=a.map((p)=>hc(p)&&typeof p.message==="string"?p.message:null).filter((p)=>p!==null).join("; ").slice(0,200);if(a.length>0)return{ok:!1,error:`OpenNeuro reported an error${c?`: ${c}`:""}`,transport:!1};let l=U_e(i.a,t),d=U_e(i.b,n);if(typeof l!=="string"&&typeof d!=="string")return{ok:!0,from:l,to:d};return{ok:!1,error:typeof l==="string"?l:d,transport:!1}}async function J_e(e,t={}){let n=t.graphqlUrl??Bg,r=Math.max(1,t.attempts??3),o="no attempt was made";for(let s=1;s<=r;s++){let i;try{let a=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","User-Agent":"nemar-cli"},body:JSON.stringify(I_e([e])),signal:AbortSignal.timeout(t.timeoutMs??30000)});if(!a.ok){if(await a.body?.cancel().catch(()=>{}),o=`OpenNeuro GraphQL answered HTTP ${a.status}`,s<r)await CD(t.retryDelayMs??2000*s);continue}i=await a.json()}catch(a){if(o=`OpenNeuro GraphQL unreachable (${a instanceof Error?a.message:String(a)})`,s<r)await CD(t.retryDelayMs??2000*s);continue}return N_e(i,[e]).get(e)??{kind:"error",reason:`OpenNeuro did not answer ${e}`}}return{kind:"error",reason:o}}function CD(e){return new Promise((t)=>setTimeout(t,e))}function hc(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function H_e(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/'/g,"'").replace(/"/g,'"')}async function Y_e(e,t){if(t??await Kf())try{let i=z_e({cmd:["aws","s3","ls","--no-sign-request","--region",V_e,`s3://${F6}/${e}/`],stdout:"pipe",stderr:"pipe"}),a=await new Response(i.stdout).text();if(await i.exited!==0)return!1;return a.trim().length>0}catch{}let r=`${M6}?list-type=2&prefix=${e}/&max-keys=1`,o=await fetch(r);if(!o.ok)return!1;return(await o.text()).includes("<Key>")}async function X_e(e){let t=[],n;do{let r=`${M6}?list-type=2&prefix=${e}/`;if(n)r+=`&continuation-token=${encodeURIComponent(n)}`;let o=await fetch(r);if(!o.ok)throw Error(`Failed to list OpenNeuro dataset: HTTP ${o.status}`);let s=await o.text(),i=s.match(/<Contents>[\s\S]*?<\/Contents>/g)||[];for(let c of i){let l=c.match(/<Key>([^<]+)<\/Key>/),d=c.match(/<Size>(\d+)<\/Size>/);if(l&&d){let f=H_e(l[1]),p=Number.parseInt(d[1],10);if(f.endsWith("/")&&p===0)continue;t.push({key:f,size:p})}}if(s.includes("<IsTruncated>true</IsTruncated>")){let c=s.match(/<NextContinuationToken>([^<]+)<\/NextContinuationToken>/);if(!c)throw Error(`S3 listing indicated more results but no continuation token was provided. Got ${t.length} objects so far.`);n=H_e(c[1])}else n=void 0}while(n);return t}async function Q_e(e,t,n){let r=`s3://${F6}/${e}/`,o=["aws","s3","sync","--no-sign-request","--region",V_e,r,t],s;try{s=z_e({cmd:o,stdout:"pipe",stderr:"pipe"})}catch(p){return{success:!1,filesDownloaded:0,totalBytes:0,method:"aws-cli",error:`Failed to start AWS CLI: ${p.message}`}}let i=0,a=[],c=/^download:\s+s3:\/\/[^\s]+\/(.*?)\s+to\s+/;function l(p,m){if(p.startsWith("download:")){i++;let h=p.match(c);n?.(i,h?.[1]||"")}else if(m)a.push(p)}async function d(p,m){let h=p.getReader(),g=new TextDecoder,y="";try{while(!0){let{done:_,value:x}=await h.read();if(_)break;y+=g.decode(x,{stream:!0});let k=y.split(`
|
|
207
|
+
`),ne=[...new Set([...ft,...oe.map((mr)=>mr.path)])],Ue=Pxt(mi(Fxt(),"nemar-scrub-pathspec-")),It=mi(Ue,"paths");Cw(It,`${ne.join("\x00")}\x00`,{mode:384});try{if((await R(["git","-c","annex.largefiles=nothing","commit","-m","Privacy correction on import (ADR 0089)","-m",le,`--pathspec-from-file=${It}`,"--pathspec-file-nul"],{cwd:t})).exitCode!==0)throw Error("could not commit the import scrub")}finally{Pd(Ue,{recursive:!0,force:!0})}Be=!0}return{counts:n,items:re,replacedKeys:Ee,handledPaths:Qt,historyHoldsOriginals:n.json_values_blanked>0||n.git_held_recordings_scrubbed>0||e.reimport&&Zxt(t),headerReadKeys:f,committed:Be}}async function tvt(e,t,n){try{return await nvt(e,t,n)}catch(r){if(r instanceof Gt)throw r;throw new Gt("scrub-failed",yo(r))}}async function nvt(e,t,n){let r=new Set((await ur(e)).values()),o=[...n].filter((d)=>r.has(d)).length;if(o>0)throw new Gt("old-key-still-named",`${o} replaced key(s) are still named by the tree`);let s=new Map;for(let d of t)if(!s.has(d.key))s.set(d.key,d);let i=[...s.values()].filter((d)=>r.has(d.key)),a=s.size-i.length,c=await Ig(e,i.map((d)=>d.key)),l=i.filter((d,f)=>!fi(c[f]??""));return{items:l,droppedNotInTree:a,droppedDead:i.length-l.length}}function I6(e,t,n){let r=new Set([...t].filter(([s])=>Mo.test(s)).map(([,s])=>s)),o=e.filter((s)=>!fl(s)&&r.has(s.key)&&!n.has(s.key)).length;if(o>0)throw new Gt("header-unreadable",`${o} recording(s) in the copy manifest whose header this run did not read`)}async function O_e(e){let t=await P6({datasetPath:e.datasetPath,nemarId:e.nemarId,keyUrlMap:e.keyUrlMap,unannexedData:e.unannexedData,reimport:e.reimport,skipData:e.skipData,maxBytes:e.maxBytes,reader:e.reader,upload:e.upload,remoteName:e.remoteName,bucket:e.bucket,now:e.now,actor:e.actor}),n=await kD({datasetPath:e.datasetPath,nemarId:e.nemarId,bucket:e.bucket,remoteName:e.remoteName,unannexedData:e.unannexedData.filter((s)=>!t.handledPaths.has(s.path)),upstreamKeys:new Set(e.keyUrlMap.keys()),carryOverUnaccountedKeys:e.reimport&&!e.skipData,upload:e.upload,maxBytes:e.maxBytes}),r=e.skipData?{items:[],droppedNotInTree:0,droppedDead:0}:await tvt(e.datasetPath,[...e.upstreamItems,...t.items,...n.items],t.replacedKeys),o;try{o=await ur(e.datasetPath)}catch(s){throw new Gt("scrub-failed",yo(s))}return I6(r.items,o,t.headerReadKeys),{scrub:t,normalized:n,manifest:r,privacy:{version:1,historyHoldsOriginals:t.historyHoldsOriginals}}}var C_e,Gt,jxt,Lxt,qxt,Bxt="nemar-importer",Uxt,O6=1048576,T6=8388608,Mo,lp,up,x_e="nemar-cli-import-scrub",zxt;var Vi=V(()=>{Q$();$d();ep();ml();_w();ji();qt();Pr();u6();Td();cs();Ad();C_e=["header-unreadable","upstream-size-mismatch","bound-exceeded","content-mismatch","unsupported-key-backend","already-imported-unscrubbed","old-key-still-named","retire-failed","scrub-unverified","upload-failed","provenance-out-of-scope","scope-incomplete","scrub-failed"];Gt=class Gt extends Error{code;constructor(e,t,n=!1){super(`${n?`${dD} `:""}${Awe} refused: ${e} (${t}). Nothing was pushed, and the copy phase did not run.`);this.code=e;this.name="ImportScrubRefused"}};jxt=new Set(["GitScrubError","ContractError","LedgerRefused"]),Lxt=/^[A-Z][A-Z0-9_]{1,20}$/;qxt=`identifier-scan@${"465a827fb0758d21"}`,Uxt=/^[a-z0-9][a-z0-9-]{0,38}$/i,Mo=/\.(edf|bdf)$/i,lp=/\.json$/i,up=/_scans\.tsv$/;zxt=new Set(["ENOSPC","EACCES","EPERM","EROFS","EIO","EMFILE","ENFILE"])});function I_e(e){let t=e.map((o,s)=>`$a${s}: ID!`).join(", "),n=e.map((o,s)=>`a${s}: dataset(id: $a${s}) { id latestSnapshot { tag created } snapshots { tag created } }`).join(" "),r={};return e.forEach((o,s)=>{r[`a${s}`]=o}),{query:`query UpstreamSnapshots(${t}) { ${n} }`,variables:r}}function rvt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function bl(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function T_e(e){if(!bl(e)||typeof e.tag!=="string"||e.tag==="")return null;let t=e.created;if(t!==void 0&&t!==null&&typeof t!=="string")return null;return{tag:e.tag,created:typeof t==="string"?t:null}}function ovt(e,t){if(e.id!==t)return{kind:"error",reason:`OpenNeuro answered ${String(e.id)} where ${t} was asked`};if(!Array.isArray(e.snapshots))return{kind:"error",reason:`OpenNeuro sent no snapshot list for ${t}`};let n=[];for(let o of e.snapshots){let s=T_e(o);if(!s)return{kind:"error",reason:`OpenNeuro sent a malformed snapshot for ${t}`};n.push(s)}let r=null;if(e.latestSnapshot!==null&&e.latestSnapshot!==void 0){if(r=T_e(e.latestSnapshot),!r)return{kind:"error",reason:`OpenNeuro sent a malformed latest snapshot for ${t}`}}else if(n.length>0)return{kind:"error",reason:`OpenNeuro sent snapshots for ${t} but no latest snapshot`};return{kind:"snapshot",latest:r,snapshots:n}}function P_e(e,t){if(!Array.isArray(e))return null;for(let n of e)if(bl(n)&&Array.isArray(n.path)&&n.path[0]===t)return n;return null}function N_e(e,t){let n=new Map,r=bl(e)?e.data:void 0;if(!bl(e)||!bl(r)){let o=bl(e)&&Array.isArray(e.errors)?e.errors[0]:void 0,s=bl(o)&&typeof o.message==="string"?o.message:"the response carried no data";for(let i of t)n.set(i,{kind:"error",reason:`OpenNeuro: ${s}`});return n}return t.forEach((o,s)=>{let i=`a${s}`,a=r[i];if(bl(a)){let c=P_e(e.errors,i);if(c){let l=typeof c.message==="string"?c.message:"an error";n.set(o,{kind:"error",reason:`OpenNeuro sent data and an error for ${o}: ${l}`});return}n.set(o,ovt(a,o));return}if(a===null){let c=P_e(e.errors,i),l=c&&typeof c.message==="string"?c.message:null,d=c&&bl(c.extensions)?c.extensions.code:void 0;if(l===null)n.set(o,{kind:"error",reason:`OpenNeuro sent null for ${o} without saying why`});else if(d==="DELETED_DATASET")n.set(o,{kind:"deleted",reason:l});else if(new RegExp(`^Dataset ${rvt(o)} does not exist\\.?$`).test(l))n.set(o,{kind:"absent",reason:l});else n.set(o,{kind:"error",reason:l});return}n.set(o,{kind:"error",reason:`OpenNeuro did not answer ${o}`})}),n}function Tw(e){return e.checksum_algorithm==="git"}var F_e="Published file is missing from storage",svt,M_e,j_e;var $D=V(()=>{Ko();svt=ee({path:S().min(1),size:j().int().nonnegative(),checksum:S().optional(),checksum_algorithm:S().optional(),bytes_url:S().min(1),url:S().nullish(),error:S().optional()}).passthrough(),M_e=he(svt),j_e=ee({dataset_id:S().optional(),latest:S().nullish(),versions:he(ee({version:S().min(1),mirror:Ke().nullable().optional()}).passthrough())}).passthrough()});import{existsSync as N6,mkdirSync as B_e,rmSync as ivt,statSync as avt}from"fs";import{dirname as cvt,join as lvt,resolve as L_e}from"path";function q_e(e){return e===null?!0:e!==404}function dvt(e){return e===408||e===425||e===429||e>=500}async function pvt(e){if(!(e.headers.get("content-type")??"").includes("json"))return!1;if(Number(e.headers.get("content-length")??0)>fvt)return!1;try{return(await e.json())?.error===F_e}catch{return!1}}async function mvt(e,t,n){let r=lvt(t,e.path),o=L_e(t),s=L_e(r);if(s!==o&&!s.startsWith(`${o}/`))return{written:null,error:{message:`${e.path}: refusing to write outside the output directory`,infrastructure:!0}};if(N6(r))try{if(avt(r).size===e.size)return{written:null}}catch(l){console.warn(u.dim(` could not read existing ${e.path} (${l instanceof Error?l.message:String(l)}); re-fetching`))}let i=cvt(r);if(!N6(i))B_e(i,{recursive:!0});let a=`${e.path}: download failed`,c=!0;for(let l=1;l<=n;l++){let d=()=>Bun.sleep(250*2**(l-1)),f;try{f=await fetch(e.url,{redirect:"follow"})}catch(m){if(a=`${e.path}: ${m instanceof Error?m.message:String(m)}`,c=q_e(null),l<n){await d();continue}break}if(!f.ok){if(a=`${e.path}: HTTP ${f.status}`,c=q_e(f.status),f.status===502&&await pvt(f)){a=`${e.path}: HTTP 502 (listed in the manifest, missing from storage)`,c=!1;break}if(dvt(f.status)&&l<n){await d();continue}break}let p;try{p=await Bun.write(r,f)}catch(m){a=`${e.path}: ${m instanceof Error?m.message:String(m)}`,c=!0;break}if(p===e.size)return{written:p};try{ivt(r,{force:!0})}catch{}if(a=`${e.path}: expected ${e.size} bytes, received ${p}`,c=!0,l<n){await d();continue}break}return{written:null,error:{message:a,infrastructure:c}}}async function DD(e,t,n={}){let r=Math.max(1,Math.min(n.concurrency??4,wl)),o=Math.max(1,n.attempts??uvt);if(!N6(t))B_e(t,{recursive:!0});let s=[...e],i={filesDownloaded:0,filesSkipped:0,bytesDownloaded:0,bytesSkipped:0,errors:[],hadInfrastructureFailure:!1},a=0,c=async()=>{for(;;){let l=s.shift();if(!l)return;let d=await mvt(l,t,o);if(d.error){if(i.errors.push(d.error.message),d.error.infrastructure)i.hadInfrastructureFailure=!0}else if(d.written===null)i.filesSkipped++,i.bytesSkipped+=l.size;else i.filesDownloaded++,i.bytesDownloaded+=d.written;a++,n.onProgress?.(a,e.length,i.bytesDownloaded)}};return await Promise.all(Array.from({length:Math.min(r,e.length||1)},()=>c())),i}var wl=16,uvt=3,fvt=4096;var RD=V(()=>{He();$D()});var{spawn:z_e}=globalThis.Bun;function G_e(e){return hvt.test(e)}async function W_e(e,t={}){let n=t.graphqlUrl??Bg,r=Math.max(1,t.attempts??3),o="no attempt was made";for(let s=1;s<=r;s++){let i;try{let h=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":"nemar-cli"},body:JSON.stringify({query:"query LatestTag($id: ID!) { dataset(id: $id) { latestSnapshot { tag } } }",variables:{id:e}}),signal:AbortSignal.timeout(t.timeoutMs??30000)});if(!h.ok){if(o=`OpenNeuro GraphQL answered HTTP ${h.status}`,s<r)await CD(t.retryDelayMs??2000*s);continue}i=await h.json()}catch(h){if(o=`OpenNeuro GraphQL unreachable (${h instanceof Error?h.message:String(h)})`,s<r)await CD(t.retryDelayMs??2000*s);continue}let a=hc(i)?i:{},c=hc(a.data)?a.data:{},l=hc(c.dataset)?c.dataset:null,f=(l&&hc(l.latestSnapshot)?l.latestSnapshot:null)?.tag;if(Jo(f))return{tag:f};if(typeof f==="string")return{tag:null,reason:"OpenNeuro named a latest tag of an unexpected shape"};let m=(Array.isArray(a.errors)?a.errors:[]).map((h)=>hc(h)&&typeof h.message==="string"?h.message:null).filter((h)=>h!==null).join("; ").slice(0,200);if(l===null)return{tag:null,reason:m?`OpenNeuro: ${m}`:"OpenNeuro knows no such dataset"};return{tag:null,reason:"OpenNeuro names no snapshot for this dataset yet"}}return{tag:null,reason:o}}function U_e(e,t){let n=hc(e)?e.files:void 0;if(!Array.isArray(n))return`OpenNeuro sent no file list for the ${t} snapshot`;let r=[],o=new Set;for(let[s,i]of n.entries()){if(!(hc(i)&&typeof i.filename==="string"&&typeof i.id==="string"&&typeof i.annexed==="boolean"&&(i.size===null||Number.isSafeInteger(i.size)&&i.size>=0)&&(i.directory===void 0||i.directory===null||typeof i.directory==="boolean")))return`OpenNeuro sent a malformed file entry (${t} snapshot, entry ${s})`;let c=i;if(o.has(c.filename))return`OpenNeuro listed ${c.filename} twice (${t} snapshot, entry ${s})`;o.add(c.filename),r.push({filename:c.filename,id:c.id,size:c.size,annexed:c.annexed,directory:c.directory===!0})}if(!r.some((s)=>!s.directory))return`OpenNeuro sent an empty file list for the ${t} snapshot`;if(!r.some((s)=>!s.directory&&s.filename==="dataset_description.json"))return`OpenNeuro sent a file list with no root dataset_description.json for the ${t} snapshot`;return r}async function K_e(e,t,n,r={}){let o;try{let p=await fetch(r.graphqlUrl??Bg,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":"nemar-cli"},body:JSON.stringify({query:gvt,variables:{ds:e,from:t,to:n}}),signal:AbortSignal.timeout(r.timeoutMs??120000)});if(!p.ok)return{ok:!1,error:`OpenNeuro GraphQL answered HTTP ${p.status}`,transport:!0};o=await p.json()}catch(p){return{ok:!1,error:`OpenNeuro GraphQL unreadable (${p instanceof Error?p.message:String(p)})`,transport:!0}}let s=hc(o)?o:{},i=hc(s.data)?s.data:{},a=Array.isArray(s.errors)?s.errors:[],c=a.map((p)=>hc(p)&&typeof p.message==="string"?p.message:null).filter((p)=>p!==null).join("; ").slice(0,200);if(a.length>0)return{ok:!1,error:`OpenNeuro reported an error${c?`: ${c}`:""}`,transport:!1};let l=U_e(i.a,t),d=U_e(i.b,n);if(typeof l!=="string"&&typeof d!=="string")return{ok:!0,from:l,to:d};return{ok:!1,error:typeof l==="string"?l:d,transport:!1}}async function J_e(e,t={}){let n=t.graphqlUrl??Bg,r=Math.max(1,t.attempts??3),o="no attempt was made";for(let s=1;s<=r;s++){let i;try{let a=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","User-Agent":"nemar-cli"},body:JSON.stringify(I_e([e])),signal:AbortSignal.timeout(t.timeoutMs??30000)});if(!a.ok){if(await a.body?.cancel().catch(()=>{}),o=`OpenNeuro GraphQL answered HTTP ${a.status}`,s<r)await CD(t.retryDelayMs??2000*s);continue}i=await a.json()}catch(a){if(o=`OpenNeuro GraphQL unreachable (${a instanceof Error?a.message:String(a)})`,s<r)await CD(t.retryDelayMs??2000*s);continue}return N_e(i,[e]).get(e)??{kind:"error",reason:`OpenNeuro did not answer ${e}`}}return{kind:"error",reason:o}}function CD(e){return new Promise((t)=>setTimeout(t,e))}function hc(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function H_e(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/'/g,"'").replace(/"/g,'"')}async function Y_e(e,t){if(t??await Kf())try{let i=z_e({cmd:["aws","s3","ls","--no-sign-request","--region",V_e,`s3://${F6}/${e}/`],stdout:"pipe",stderr:"pipe"}),a=await new Response(i.stdout).text();if(await i.exited!==0)return!1;return a.trim().length>0}catch{}let r=`${M6}?list-type=2&prefix=${e}/&max-keys=1`,o=await fetch(r);if(!o.ok)return!1;return(await o.text()).includes("<Key>")}async function X_e(e){let t=[],n;do{let r=`${M6}?list-type=2&prefix=${e}/`;if(n)r+=`&continuation-token=${encodeURIComponent(n)}`;let o=await fetch(r);if(!o.ok)throw Error(`Failed to list OpenNeuro dataset: HTTP ${o.status}`);let s=await o.text(),i=s.match(/<Contents>[\s\S]*?<\/Contents>/g)||[];for(let c of i){let l=c.match(/<Key>([^<]+)<\/Key>/),d=c.match(/<Size>(\d+)<\/Size>/);if(l&&d){let f=H_e(l[1]),p=Number.parseInt(d[1],10);if(f.endsWith("/")&&p===0)continue;t.push({key:f,size:p})}}if(s.includes("<IsTruncated>true</IsTruncated>")){let c=s.match(/<NextContinuationToken>([^<]+)<\/NextContinuationToken>/);if(!c)throw Error(`S3 listing indicated more results but no continuation token was provided. Got ${t.length} objects so far.`);n=H_e(c[1])}else n=void 0}while(n);return t}async function Q_e(e,t,n){let r=`s3://${F6}/${e}/`,o=["aws","s3","sync","--no-sign-request","--region",V_e,r,t],s;try{s=z_e({cmd:o,stdout:"pipe",stderr:"pipe"})}catch(p){return{success:!1,filesDownloaded:0,totalBytes:0,method:"aws-cli",error:`Failed to start AWS CLI: ${p.message}`}}let i=0,a=[],c=/^download:\s+s3:\/\/[^\s]+\/(.*?)\s+to\s+/;function l(p,m){if(p.startsWith("download:")){i++;let h=p.match(c);n?.(i,h?.[1]||"")}else if(m)a.push(p)}async function d(p,m){let h=p.getReader(),g=new TextDecoder,y="";try{while(!0){let{done:_,value:x}=await h.read();if(_)break;y+=g.decode(x,{stream:!0});let k=y.split(`
|
|
208
208
|
`);y=k.pop()||"";for(let v of k){let C=v.trim();if(C)l(C,m)}}let b=y.trim();if(b)l(b,m)}finally{h.releaseLock()}}await Promise.all([d(s.stdout,!1),d(s.stderr,!0)]);let f=await s.exited;if(f!==0)return{success:!1,filesDownloaded:i,totalBytes:0,method:"aws-cli",error:a.join(`
|
|
209
209
|
`)||`aws s3 sync exited with code ${f}`};return{success:!0,filesDownloaded:i,totalBytes:0,method:"aws-cli"}}async function Z_e(e,t,n,r={}){let{concurrency:o=8,onProgress:s}=r,i=n.reduce((d,f)=>d+f.size,0),a=n.map((d)=>({path:d.key.substring(e.length+1),url:`${M6}/${d.key.split("/").map((f)=>encodeURIComponent(f)).join("/")}`,size:d.size})),c=await DD(a,t,{concurrency:o,onProgress:(d,f,p)=>s?.(d,f,p,i)}),l=c.errors;return{success:l.length===0,filesDownloaded:c.filesDownloaded+c.filesSkipped,totalBytes:c.bytesDownloaded+c.bytesSkipped,method:"https",error:l.length>0?`${l.length} file(s) failed:
|
|
210
210
|
${l.slice(0,10).join(`
|
|
@@ -221,16 +221,16 @@ This dataset is mirrored on NEMAR from OpenNeuro.
|
|
|
221
221
|
- Source: [${e}](${r})${o}
|
|
222
222
|
`}function G6(e){let t=[];for(let n of Cvt){let r=e.find((o)=>o.path===n);if(r)t.push(r)}return{found:t,contentSource:t[0],remove:t.filter((n)=>n.path!=="README.md")}}function W6(e){let t=`https://doi.org/${e}`;return`[}-blue`})](${t})`}function axe(e){let{readmeContent:t,doiBadge:n,conceptDoi:r,contentSourcePath:o}=e,s=o!==void 0&&o!=="README.md",i=t.includes("zenodo.org/badge/DOI")||t.includes("img.shields.io/badge/DOI"),a=encodeURIComponent(r),c=i&&(t.includes(r)||t.includes(a));if(c&&!s)return{commit:!1,reason:"badge already points to current concept DOI"};let l=c?t:`${n}
|
|
223
223
|
|
|
224
|
-
${t}`,d=i&&!c?"Replace stale":"Add",f=s?`Rename ${o} to README.md and ${d.toLowerCase()}`:d;return{commit:!0,content:l,message:`${f} DOI badge: ${r}`}}var V6,Cvt;var K6=V(()=>{V6=/^README(\.[A-Za-z0-9]+)?$/i;Cvt=["README.md","README.rst","README.txt","README"]});function xR(e,t){let n=e.filter((i)=>!cr(i.key,t)),r=n.filter((i)=>fl(i)).length,o=n.length-r;if(n.length===0)return{missing:n,missingLocal:r,missingUpstream:o,message:null};let s=[o>0?`${o} copied from upstream: re-run the copy phase (a shard likely failed or was cancelled)`:null,r>0?`${r} uploaded by prepare from the clone: re-run PREPARE, not copy -- the copy phase skips these keys by design and their content exists only in a clone`:null].filter(Boolean).join("; ");return{missing:n,missingLocal:r,missingUpstream:o,message:`${n.length} of ${e.length} objects missing or wrong size at the destination. ${s}.`}}function vR(e,t,n){let r=K0e(e,t);if(r.length>0){let s=CF({annexed:[...e],missingContent:r}),i=s<M$?`, below the ${(M$*100).toFixed(0)}% a listed dataset must reach (ADR 0064)`:"";return{ok:!1,unbacked:r,available:s,message:[`${_ke} ${(s*100).toFixed(1)}% of data keys available.`,`${r.length} of ${e.size} annexed key(s) in the tree have no object in s3://${n.bucket}/${n.datasetId}/objects/`,`(e.g. ${r.slice(0,3).join(", ")}).`,`That is ${(s*100).toFixed(1)}% of its data available${i}.`,`The manifest accounted for ${n.manifestItems}.`,"Refusing to register: those keys would be advertised as NEMAR content that no clone can fetch.","Re-run the copy phase, or prepare if the content exists only in a clone.","If the copy phase cannot get them, check whether OpenNeuro still serves them before assuming a NEMAR bug:",`\`nemar admin fleet content-recovery ${n.datasetId}\` reports, per key, whether any recorded source is readable.`].join(" ")}}let o=[...e].filter((s)=>No(s)===null);return{ok:!0,unsized:o,message:o.length===0?`Every one of ${e.size} annexed key(s) has an object of its declared size`:`Every one of ${e.size} annexed key(s) has an object; ${o.length} declare no size and were checked by name only`}}async function xke(e,t,n){let r=await xd(e,[...t],n);if(r.failed>0)return{ok:!1,message:`${r.failed} of ${t.length} git-annex key registrations are not in the location log (e.g. ${r.missing.slice(0,3).join(", ")}). Aborting before publish \u2014 those blobs would be unfindable for clones. Re-run finalize to retry.`};return{ok:!0,registered:r.success,message:`Registered ${r.success} files in git-annex`}}var _ke="[nemar-data-unavailable]";var kR=V(()=>{Pr();cs()});function Yt(e){throw new SR(e)}function o_(e,t,n){for(let r of Object.keys(e))if(!t.includes(r))Yt(n)}function HM(e,t,n,r){if(!ay(e)||Object.keys(e).length>n)Yt(r);let o={};for(let[s,i]of Object.entries(e)){if(!t(s)||!r_(i))Yt(r);o[s]=i}return o}function VM(e){let t=e.indexOf("/");if(t<0)return!1;let n=e.slice(0,t),r=e.slice(t+1);return a$t.has(n)&&(c$t.has(r)||l$t.test(r))}function d$t(e){let t=Object.keys(e.findings_by_kind??{}),n=Object.values(e.unscreened_formats??{}).reduce((s,i)=>s+i,0),r=e.files;if(r){let s=r.header_read!==r.edf_bdf||e.incomplete_reasons.length>0;if(e.incomplete!==s)Yt("scan-status")}if(e.status==="clean"||e.status==="dates-only"||e.status==="no-recordings"){if(!r||e.incomplete||n>0||(e.edf_bdf_files_flagged??0)>0)Yt("scan-status");if(e.status==="no-recordings"){if(r.edf_bdf!==0)Yt("scan-status")}else if(r.edf_bdf===0)Yt("scan-status");if(e.status==="clean"&&t.length>0)Yt("scan-status");if(e.status!=="clean"&&!t.every((s)=>Qf.has(s)))Yt("scan-status")}if(e.status==="unchecked"&&!e.incomplete)Yt("scan-status")}function f$t(e){if(typeof e.scanned_at!=="string"||!u$t.test(e.scanned_at))Yt("scan-time");if(!WM.includes(e.status))Yt("scan-status");if(typeof e.incomplete!=="boolean")Yt("scan-incomplete");if(!Array.isArray(e.incomplete_reasons)||e.incomplete_reasons.length>40||!e.incomplete_reasons.every((n)=>typeof n==="string"&&i$t.has(n)))Yt("scan-reasons");let t={scanned_at:e.scanned_at,status:e.status,incomplete:e.incomplete,incomplete_reasons:e.incomplete_reasons};if(e.manifest_source!==void 0){if(typeof e.manifest_source!=="string"||!n$t.has(e.manifest_source))Yt("scan-source");t.manifest_source=e.manifest_source}if(e.files!==void 0){let n=e.files;if(!ay(n))Yt("scan-files");let r=n;o_(r,["total","edf_bdf","header_read","header_read_failed"],"scan-files");for(let o of["total","edf_bdf","header_read","header_read_failed"])if(!r_(r[o]))Yt("scan-files");t.files=r}if(e.sampling!==void 0){let n=e.sampling;if(!ay(n))Yt("scan-sampling");let r=n,o=["edf_headers","scans_tables","json_files","text_files"];o_(r,o,"scan-sampling");for(let s of o){let i=r[s];if(!ay(i))Yt("scan-sampling");let a=i;o_(a,["candidates","oversize","selected","scanned"],"scan-sampling");for(let c of["candidates","oversize","selected","scanned"])if(!r_(a[c]))Yt("scan-sampling")}t.sampling=r}if(e.read_failures!==void 0)t.read_failures=HM(e.read_failures,VM,60,"scan-failures");for(let n of["edf_bdf_files_flagged","distinct_patient_field_values","distinct_subjects_with_edf_bdf","distinct_patient_code_subfield","distinct_patient_name_subfield","distinct_patient_birth_subfield","distinct_patient_field_values_in_flagged_files","side_reads_failed"])if(e[n]!==void 0){if(!r_(e[n]))Yt("scan-count");t[n]=e[n]}for(let n of["findings_by_kind","edf_bdf_files_by_kind"])if(e[n]!==void 0)t[n]=HM(e[n],(r)=>t$t.has(r),40,"scan-kinds");if(e.unscreened_formats!==void 0)t.unscreened_formats=HM(e.unscreened_formats,(n)=>o$t.test(n),60,"scan-formats");return t}function Bd(e){switch(e){case"clean":case"dates-only":case"no-recordings":return"clear";case"direct-identifiers":return"blocks";case"review":case"unchecked":case"not-screened":case"clean-edf-only-others-unscreened":return"acknowledge";case"pending":return"wait";default:return"rerun"}}function kke(e){return e==="pending"||e==="error"||e==="unreported"||WM.includes(e)}function m$t(e){return Object.entries(e??{}).map(([t,n])=>`${t} x${n}`).join(", ")}function $R(e){let t=0;for(let[n,r]of Object.entries(e??{}))if(Qf.has(n)&&r_(r))t+=r;return t}function h$t(e){let t=$R(e?.findings_by_kind),n="in recording headers or scans tables";if(t>0){let r=`${e?.incomplete===!0?"at least ":""}${t} ${t===1?"entry":"entries"}`;n=`${n} (${r})`}else if(e?.status!=="dates-only")return[];return[`${Eke} ${n}.`,...Ske]}function $ke(e){return e.startsWith(Eke)||Ske.includes(e)}function Dke(e){return`Acquisition dates in ${`${e} recording header${e===1?"":"s"}`} were set to 1 January of their year.`}function Rke(e){return["Your request was received.","NEMAR is checking publication eligibility.","If every check passes, an administrator is notified to approve it.","You will be emailed if a check needs your attention, and when an administrator decides.",`Run 'nemar dataset publish status ${e}' to see where it stands.`]}function g$t(e){let t=[];if(e.files){let o=e.files.header_read_failed>0?` (${e.files.header_read_failed} unreadable)`:"";t.push(`Files: ${e.files.total}; EDF/BDF headers read: ${e.files.header_read} of ${e.files.edf_bdf}${o}.`)}let n=m$t(e.findings_by_kind);if(n)t.push(`Findings by kind: ${n}.`);if(e.edf_bdf_files_flagged)t.push(`EDF/BDF files with an identifier finding: ${e.edf_bdf_files_flagged}.`);let r=Object.entries(e.unscreened_formats??{});if(r.length>0)t.push(`Not screened (format x files): ${r.map(([o,s])=>`${o} x${s}`).join(", ")}.`);if(e.incomplete_reasons.length>0)t.push(`Incomplete: ${e.incomplete_reasons.join(", ")}.`);return t}function Ake(e){let t=e?.read_failures;if(typeof t!=="object"||t===null)return e;let n={},r=(s,i)=>{n[s]=(n[s]??0)+i};for(let[s,i]of Object.entries(t)){let a=s.toLowerCase();if(VM(a)){r(a,i);continue}let c=a.slice(0,Math.max(0,a.indexOf("/")));r(`${VM(`${c}/${n_}`)?c:n_}/${n_}`,i)}let o=Object.entries(n).sort(([,s],[,i])=>i-s);if(o.length>zM){let s=Object.fromEntries(o.slice(0,zM-1)),i=`${n_}/${n_}`;for(let[,a]of o.slice(zM-1))s[i]=(s[i]??0)+a;return{...e,read_failures:s}}return{...e,read_failures:n}}function Oke(e){let t=e?.unscreened_formats;if(typeof t!=="object"||t===null)return e;let n={};for(let[r,o]of Object.entries(t)){let s=DR.has(r)?r:Cke;n[s]=(n[s]??0)+o}return{...e,unscreened_formats:n}}function KM(e){if(!ay(e))return Yt("scan-shape");o_(e,vke,"scan-key");for(let n of vke)if(e[n]===void 0)Yt("scan-missing");let t=f$t(e);for(let n of Object.keys(t.unscreened_formats))if(!DR.has(n))Yt("scan-formats");return d$t(t),t}function Tke(e){if(!ay(e))return Yt("preflight-shape");if(o_(e,["version","scanner","scan","acknowledged_via"],"preflight-key"),e.version!==ER)Yt("preflight-version");if(typeof e.scanner!=="string"||!y$t.test(e.scanner))Yt("preflight-scanner");let t=KM(e.scan),n=e.acknowledged_via;if(n!==null&&n!=="prompt"&&n!=="flag")Yt("preflight-ack");if(Bd(t.status)==="acknowledge"!==(n!==null))Yt("preflight-ack");return{version:ER,scanner:e.scanner,scan:t,acknowledged_via:n}}function JM(e,t){let n=p$t[e.status],r=g$t(e);if(r.push(...h$t(e)),t==="prompt")r.push("Acknowledged by the uploader at the prompt.");if(t==="flag")r.push("Acknowledged by the uploader with --acknowledge-identifier-preflight.");return{headline:`Identifier preflight: ${n.verdict}`,tone:n.tone,lines:r}}var e$t,GM,t$t,WM,n$t,r$t,krn,SR,ay=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),r_=(e)=>typeof e==="number"&&Number.isSafeInteger(e)&&e>=0,o$t,s$t,i$t,a$t,c$t,l$t,u$t,p$t,Eke="Warning: acquisition dates finer than year and month were found",Ske,Cke=".other",n_="internal",zM=60,ER=1,DR,vke,RR,y$t;var Ep=V(()=>{ml();e$t={"edf-unreadable":!0,"edf-patient-nonascii":!0,"edf-recording-nonascii":!0,"path-subject-label":!0,"edf-patient-name":!0,"edf-patient-code":!0,"edf-patient-recordnumber":!0,"edf-patient-age":!0,"edf-patient-freetext":!0,"edf-patient-birthdate":!0,"edf-recording-startdate":!0,"edf-recording-freetext":!0,"edf-recording-technician":!0,"edf-startdate":!0,"edf-startdate-unparsed":!0,"participants-identifier-column":!0,"json-identifier-key":!0,"acq-time-dated":!0,"image-or-document-file":!0,"tooling-debris":!0,"local-user-path":!0},GM=Object.keys(e$t),t$t=new Set(GM),WM=["direct-identifiers","dates-only","review","clean","clean-edf-only-others-unscreened","not-screened","no-recordings","unchecked"],n$t=new Set(["manifest.json","s3-version-manifest","git-tree","clone"]),r$t=["dispatch-unconfigured","dispatch-failed","no-report-in-time","workflow-failed","clone-failed","credentials-missing","deadline"],krn=new Set(r$t);SR=class SR extends Error{constructor(e){super(e);this.name="ReportError"}};o$t=/^(\.[a-z0-9]{1,12}(\.[a-z0-9]{1,12})?\/?|\(no extension\))$/,s$t=["edf-headers-oversize","edf-headers-sampled","edf-headers-unread","json-oversize","json-sampled","json-unread","text-oversize","text-sampled","text-unread","scans-unread","participants-unread","participants-truncated","history-unread","submodule-unread","no-latest-version","manifest-shape","tree-truncated","credentials-missing","deadline"],i$t=new Set(s$t),a$t=new Set(["edf","participants","scans","json","text","internal"]),c$t=new Set(["timeout","network","deadline","credentials-missing","header-truncated","json-parse","no-body","short-body","unreadable-entry","superseded-absent","blob-missing","blob-closed","internal","error-error","error-rangeerror","error-typeerror","error-syntaxerror","error-referenceerror","error-evalerror","error-urierror","error-aborterror","error-timeouterror"]),l$t=/^http-[1-5]\d\d$/;u$t=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?Z$/;p$t={pending:{verdict:"running",tone:"note"},clean:{verdict:"clean",tone:"ok"},"dates-only":{verdict:"clean (acquisition dates only)",tone:"ok"},"no-recordings":{verdict:"clean (no recordings)",tone:"ok"},review:{verdict:"needs review",tone:"warn"},"direct-identifiers":{verdict:"FOUND IDENTIFIERS",tone:"stop"},unchecked:{verdict:"INCOMPLETE",tone:"warn"},"not-screened":{verdict:"recordings NOT screened",tone:"warn"},"clean-edf-only-others-unscreened":{verdict:"EDF/BDF clean, other recordings NOT screened",tone:"warn"},error:{verdict:"DID NOT RUN",tone:"stop"},unreported:{verdict:"DID NOT REPORT",tone:"stop"}};Ske=["NEMAR does not change them.","A date can help identify a participant when it is combined with other information.","Remove or coarsen any date that could identify someone before uploading or requesting publication.","Administrators are told of these findings when publication is requested."];DR=new Set([...YF,...W$.map((e)=>`${e}/`),".eeg",".vmrk",".mef",".kdf",".mrk",".elp",".hsp",".raw",".mhd",".tsv.gz","(no extension)",Cke]);vke=["scanned_at","status","incomplete","incomplete_reasons","files","findings_by_kind","edf_bdf_files_flagged","unscreened_formats","read_failures"],RR=WM.filter((e)=>Bd(e)==="acknowledge"),y$t=/^nemar-cli@\d{1,4}\.\d{1,4}\.\d{1,6}(-[0-9a-z.]{1,24})?$/});function Fke(e){let t=w$t-_$t-e;return Math.min(Nke,Math.max(x$t,t))}function E$t(e){return Bd(kke(e)?e:null)}function S$t(e){return e instanceof L&&(e.statusCode===401||e.statusCode===403||e.statusCode===404)}function $$t(e){if(typeof e!=="object"||e===null)return!1;let t=e;return t.version===1&&typeof t.historyHoldsOriginals==="boolean"}function D$t(e){if(!(e instanceof L)||e.statusCode!==409)return null;if(e.code!=="identifier_screen_not_clear")return null;let t=e.rawBody;return typeof t?.gate==="string"?t.gate:"unknown"}async function Mke(e){let t=e.now??Date.now,n=e.sleep??((l)=>new Promise((d)=>setTimeout(d,l))),r=e.pollMs??v$t,o=t()+(e.waitMs??Nke),s=e.onProgress??(()=>{return}),i=0,a=!$$t(e.privacy)?"no-scrub-record":e.privacy.historyHoldsOriginals?"history-holds-originals":null;if(a)for(let l=1;;l++)try{return s("Recording the importer's hold on the publication request"),await tg(e.nemarId,b$t[a]),{outcome:"review",reason:a}}catch{if(l>=Pke)throw Error(`could not record the importer's hold (${a}) on the publication request after ${Pke} attempts; deny it by hand before anyone approves it`);await n(e.approveRetryMs??Ike)}let c=async()=>{let l=!1;for(;;){try{let p=(await eg(e.nemarId)).identifier_screen;if(!p||typeof p!=="object")return{kind:"no-view"};l=!0;let m=E$t(p.state);if(m!=="wait")return{kind:"verdict",gate:m}}catch(f){if(S$t(f))return{kind:"refused"}}let d=o-t();if(d<=0)return{kind:l?"timeout":"unreadable"};s(`Waiting for the identifier screen (${Math.ceil(d/60000)} min left)`),await n(Math.min(r,d))}};for(;;){let l=await c();if(l.kind==="timeout")return{outcome:"unchecked",reason:"timeout"};if(l.kind==="unreadable")return{outcome:"unchecked",reason:"status-unreadable"};if(l.kind==="no-view")return{outcome:"unchecked",reason:"no-screen-view"};if(l.kind==="refused")return{outcome:"unchecked",reason:"status-refused"};let d=l.gate;if(d==="blocks")return{outcome:"blocked"};if(d==="acknowledge")return{outcome:"review",reason:"acknowledgment-needed"};if(d==="rerun")return{outcome:"unchecked",reason:"no-verdict"};if(d==="wait")return{outcome:"unchecked",reason:"timeout"};let f=null;for(let p=1;p<=YM;p++)try{return s(`Approving publication (attempt ${p}/${YM})`),await rg(e.nemarId,p>1,!1,e.skipCiCheck),{outcome:"published"}}catch(m){if(f=D$t(m),f!==null)break;if(p===YM)throw m;await n(e.approveRetryMs??Ike)}if(f==="stale"){if(i>=k$t)return{outcome:"unchecked",reason:"stale"};i++,s("The screened commit is no longer main; re-running the identifier screen");try{await _S(e.nemarId)}catch{return{outcome:"unchecked",reason:"rerun-failed"}}continue}if(f==="unverified"){if(o-t()<=0)return{outcome:"unchecked",reason:"unverified"};await n(Math.min(r,Math.max(0,o-t())));continue}if(o-t()<=0)return{outcome:"unchecked",reason:"timeout"};await n(Math.min(r,Math.max(0,o-t())))}}function jke(e,t){switch(t.outcome){case"published":return"Identifier screen: clear; publication approved";case"already-published":return`${e} was already published; publication not requested (data re-copy only)`;case"blocked":return"Identifier screen: blocked; publication not approved. The data must be corrected and publication requested again.";case"review":return t.reason==="history-holds-originals"||t.reason==="no-scrub-record"?`Import held (${t.reason}); the publication request was denied with that reason. An admin decides: nemar admin publish list`:`Identifier screen: review (${t.reason}); publication not approved. An admin decides: nemar admin publish list`;case"unchecked":return`Identifier screen: unchecked (${t.reason}); publication not approved. An admin decides: nemar admin publish screen ${e}`}}var b$t,Pke=3,Nke=2700000,w$t=5400000,_$t=1800000,x$t=300000,v$t=30000,k$t=1,YM=10,Ike=3000;var Lke=V(()=>{Ep();Ke();Ni();b$t={"history-holds-originals":"Held by the importer (ADR 0089): its identifier scrub changed files git tracks, and the pushed history still holds their original content. Rewrite the history with ADR 0085's tools, or request publication again to publish the history as it is.","no-scrub-record":"Held by the importer (ADR 0089): the import's staging manifest has no valid record of the identifier scrub, so whether it ran is unknown. Re-run the import's prepare phase, or check the dataset and request publication again."}});import{chmodSync as R$t,existsSync as Uke,mkdirSync as C$t,mkdtempSync as XM,readFileSync as A$t,readdirSync as cy,readlinkSync as O$t,renameSync as T$t,rmSync as Hke,statSync as P$t,writeFileSync as OR}from"fs";import{tmpdir as QM}from"os";import{join as Mr}from"path";async function ZM(e,t,n=120000,r=5000){let o=Date.now()+n,s,i=!1;while(Date.now()<o){try{let c=await RS(e);if(i=!0,c.bids_validation.present&&c.bids_validation.status!=="no_runs")return{kind:"found"}}catch(c){s=c}let a=Math.max(0,o-Date.now());t.text=`Waiting for BIDS validation run to register... (${Math.ceil(a/1000)}s left)`,await new Promise((c)=>setTimeout(c,Math.min(r,a)))}if(!i&&s!==void 0)return{kind:"error",lastError:s};return{kind:"timeout"}}function F$t(e){if(!e.ciDeployed)return{skipCiCheck:!1,abortReason:"CI workflows did not deploy. Aborting before approval: --trust-upstream bypasses validation lookup, not workflow deployment. Re-run after fixing the deploy failure, or run `nemar admin ci add <id>` manually before approving."};let t=e.poll;if(t===null||t.kind==="found")return{skipCiCheck:!1};if(t.kind==="error")return{skipCiCheck:!1,abortReason:`Every BIDS validation poll attempt failed (last error: ${t.lastError instanceof Error?t.lastError.message:String(t.lastError)}). Refusing to bypass under --trust-upstream because validation state was never actually observed. Investigate API/auth health and re-run.`};if(e.trustUpstream)return{skipCiCheck:!0};return{skipCiCheck:!1,abortReason:"BIDS validation run did not register within the bounded poll window. Re-run with --trust-upstream to bypass (OpenNeuro datasets are pre-validated upstream), or investigate why the deployed CI did not trigger."}}function M$t(e){return e.includes("already exists")||e.includes("409")}function j$t(e){return e==="public"?"skip-already-published":"request"}function L$t(e){if(e.originMainSha===null||e.originMainSha==="")return"none";if(e.recordedTag!==null&&!Sr(e.recordedTag,e.importTag))return"moved";return e.currentBranch==="main"?"hard-reset":"none"}function q$t(e){return e.kind!=="hard-reset"}async function B$t(e,t){let n=await R(["git","ls-remote","--exit-code","origin","refs/heads/main"],{cwd:e});if(n.exitCode===2)return{kind:"none",recordedTag:null};let r=n.exitCode===0?await R(["git","fetch","origin","main"],{cwd:e}):n;if(r.exitCode!==0)throw Error(`Could not fetch ${t.nemarId}'s main from origin (${r.stderr.trim()}). Without it the upstream-moved guard cannot run; nothing was reset or pushed.`);let o=await R(["git","rev-parse","--verify","--quiet","origin/main"],{cwd:e}),s=await R(["git","rev-parse","--abbrev-ref","HEAD"],{cwd:e}),i=await z$t(e,t.sourceId),a=i.tag,c=i.tag===null&&(o.stdout.trim()||null)!==null?i.why:void 0;if(c!==void 0)console.log(u.yellow(` Warning: ${t.nemarId}'s main ${c}, so the upstream-moved guard cannot check this import at ${t.importTag}. If ${t.nemarId} has released a version and its upstream has moved since, this re-import keeps the old tree while copying the new tag's data (#993).`));let l=L$t({originMainSha:o.stdout.trim()||null,currentBranch:s.stdout.trim(),recordedTag:a,importTag:t.importTag}),d=c!==void 0?{unrecorded:c}:{};if(l==="none")return{kind:"none",recordedTag:a,...d};if(l==="hard-reset"){let h=await R(["git","reset","--hard","origin/main"],{cwd:e});if(h.exitCode!==0)return console.log(u.yellow(` Warning: found origin/main for ${t.nemarId} (re-import) but could not reset onto it (${h.stderr.trim()}). Falling back to the normal push path.`)),{kind:"none",recordedTag:a,...d};return{kind:"hard-reset",recordedTag:a,...d}}let f;try{f=await t.released()}catch(h){throw Error(`${t.nemarId}'s main records upstream tag ${a}, this import is at ${t.importTag}, and whether ${t.nemarId} has released a version could not be read (${h instanceof Error?h.message:String(h)}). Nothing was reset or pushed; re-run once the backend answers.`)}if(f)throw new hl(c6,`${t.sourceId}: ${t.nemarId} has released a version and its main records upstream tag ${a}; this import is at ${t.importTag}. Moving a released mirror to a new snapshot is an upstream re-pull (ADR 0111), not a re-import. Nothing was reset, copied or pushed. To pull a newer snapshot as the next major, plan an upstream re-pull: \`nemar admin repull plan ${t.nemarId}\` (OpenNeuro's latest snapshot by default; \`--to-tag ${t.importTag}\` names this one). To repair the released version's data at the tag it mirrors: nemar admin import-openneuro ${t.sourceId} --tag ${a}`);let p=await U$t(e);if(p!==0)throw Error(`${t.nemarId}'s main ${p==="unreadable"?`has a ${ho} git could not read`:`records ${p} line(s) in ${ho} that retargeting it from upstream tag ${a} to ${t.importTag} would drop`} (a privacy correction, ADR 0085, or a scrub whose originals origin's history still holds, ADR 0089). Nothing was reset or pushed; a person decides how this dataset moves.`);if(s.stdout.trim()!=="main")throw Error(`${t.nemarId}'s unreleased import moved from upstream tag ${a} to ${t.importTag}, but the clone is on ${s.stdout.trim()}, not main, which cannot be retargeted safely. Nothing was reset or pushed.`);let m=await R(["git","reset","--soft","origin/main"],{cwd:e});if(m.exitCode!==0)throw Error(`Could not move ${t.nemarId}'s unreleased import from upstream tag ${a} to ${t.importTag}: git reset --soft origin/main failed (${m.stderr.trim()}). Nothing was pushed.`);return{kind:"retarget",recordedTag:a}}async function zke(e,t){let n=await R(["git","ls-tree","--name-only","origin/main","--",t],{cwd:e});if(n.exitCode!==0)return"unreadable";return n.stdout.split(`
|
|
224
|
+
${t}`,d=i&&!c?"Replace stale":"Add",f=s?`Rename ${o} to README.md and ${d.toLowerCase()}`:d;return{commit:!0,content:l,message:`${f} DOI badge: ${r}`}}var V6,Cvt;var K6=V(()=>{V6=/^README(\.[A-Za-z0-9]+)?$/i;Cvt=["README.md","README.rst","README.txt","README"]});function xR(e,t){let n=e.filter((i)=>!cr(i.key,t)),r=n.filter((i)=>fl(i)).length,o=n.length-r;if(n.length===0)return{missing:n,missingLocal:r,missingUpstream:o,message:null};let s=[o>0?`${o} copied from upstream: re-run the copy phase (a shard likely failed or was cancelled)`:null,r>0?`${r} uploaded by prepare from the clone: re-run PREPARE, not copy -- the copy phase skips these keys by design and their content exists only in a clone`:null].filter(Boolean).join("; ");return{missing:n,missingLocal:r,missingUpstream:o,message:`${n.length} of ${e.length} objects missing or wrong size at the destination. ${s}.`}}function vR(e,t,n){let r=K0e(e,t);if(r.length>0){let s=CF({annexed:[...e],missingContent:r}),i=s<M$?`, below the ${(M$*100).toFixed(0)}% a listed dataset must reach (ADR 0064)`:"";return{ok:!1,unbacked:r,available:s,message:[`${_ke} ${(s*100).toFixed(1)}% of data keys available.`,`${r.length} of ${e.size} annexed key(s) in the tree have no object in s3://${n.bucket}/${n.datasetId}/objects/`,`(e.g. ${r.slice(0,3).join(", ")}).`,`That is ${(s*100).toFixed(1)}% of its data available${i}.`,`The manifest accounted for ${n.manifestItems}.`,"Refusing to register: those keys would be advertised as NEMAR content that no clone can fetch.","Re-run the copy phase, or prepare if the content exists only in a clone.","If the copy phase cannot get them, check whether OpenNeuro still serves them before assuming a NEMAR bug:",`\`nemar admin fleet content-recovery ${n.datasetId}\` reports, per key, whether any recorded source is readable.`].join(" ")}}let o=[...e].filter((s)=>No(s)===null);return{ok:!0,unsized:o,message:o.length===0?`Every one of ${e.size} annexed key(s) has an object of its declared size`:`Every one of ${e.size} annexed key(s) has an object; ${o.length} declare no size and were checked by name only`}}async function xke(e,t,n){let r=await xd(e,[...t],n);if(r.failed>0)return{ok:!1,message:`${r.failed} of ${t.length} git-annex key registrations are not in the location log (e.g. ${r.missing.slice(0,3).join(", ")}). Aborting before publish \u2014 those blobs would be unfindable for clones. Re-run finalize to retry.`};return{ok:!0,registered:r.success,message:`Registered ${r.success} files in git-annex`}}var _ke="[nemar-data-unavailable]";var kR=V(()=>{Pr();cs()});function Yt(e){throw new SR(e)}function o_(e,t,n){for(let r of Object.keys(e))if(!t.includes(r))Yt(n)}function HM(e,t,n,r){if(!ay(e)||Object.keys(e).length>n)Yt(r);let o={};for(let[s,i]of Object.entries(e)){if(!t(s)||!r_(i))Yt(r);o[s]=i}return o}function VM(e){let t=e.indexOf("/");if(t<0)return!1;let n=e.slice(0,t),r=e.slice(t+1);return a$t.has(n)&&(c$t.has(r)||l$t.test(r))}function d$t(e){let t=Object.keys(e.findings_by_kind??{}),n=Object.values(e.unscreened_formats??{}).reduce((s,i)=>s+i,0),r=e.files;if(r){let s=r.header_read!==r.edf_bdf||e.incomplete_reasons.length>0;if(e.incomplete!==s)Yt("scan-status")}if(e.status==="clean"||e.status==="dates-only"||e.status==="no-recordings"){if(!r||e.incomplete||n>0||(e.edf_bdf_files_flagged??0)>0)Yt("scan-status");if(e.status==="no-recordings"){if(r.edf_bdf!==0)Yt("scan-status")}else if(r.edf_bdf===0)Yt("scan-status");if(e.status==="clean"&&t.length>0)Yt("scan-status");if(e.status!=="clean"&&!t.every((s)=>Qf.has(s)))Yt("scan-status")}if(e.status==="unchecked"&&!e.incomplete)Yt("scan-status")}function f$t(e){if(typeof e.scanned_at!=="string"||!u$t.test(e.scanned_at))Yt("scan-time");if(!WM.includes(e.status))Yt("scan-status");if(typeof e.incomplete!=="boolean")Yt("scan-incomplete");if(!Array.isArray(e.incomplete_reasons)||e.incomplete_reasons.length>40||!e.incomplete_reasons.every((n)=>typeof n==="string"&&i$t.has(n)))Yt("scan-reasons");let t={scanned_at:e.scanned_at,status:e.status,incomplete:e.incomplete,incomplete_reasons:e.incomplete_reasons};if(e.manifest_source!==void 0){if(typeof e.manifest_source!=="string"||!n$t.has(e.manifest_source))Yt("scan-source");t.manifest_source=e.manifest_source}if(e.files!==void 0){let n=e.files;if(!ay(n))Yt("scan-files");let r=n;o_(r,["total","edf_bdf","header_read","header_read_failed"],"scan-files");for(let o of["total","edf_bdf","header_read","header_read_failed"])if(!r_(r[o]))Yt("scan-files");t.files=r}if(e.sampling!==void 0){let n=e.sampling;if(!ay(n))Yt("scan-sampling");let r=n,o=["edf_headers","scans_tables","json_files","text_files"];o_(r,o,"scan-sampling");for(let s of o){let i=r[s];if(!ay(i))Yt("scan-sampling");let a=i;o_(a,["candidates","oversize","selected","scanned"],"scan-sampling");for(let c of["candidates","oversize","selected","scanned"])if(!r_(a[c]))Yt("scan-sampling")}t.sampling=r}if(e.read_failures!==void 0)t.read_failures=HM(e.read_failures,VM,60,"scan-failures");for(let n of["edf_bdf_files_flagged","distinct_patient_field_values","distinct_subjects_with_edf_bdf","distinct_patient_code_subfield","distinct_patient_name_subfield","distinct_patient_birth_subfield","distinct_patient_field_values_in_flagged_files","side_reads_failed"])if(e[n]!==void 0){if(!r_(e[n]))Yt("scan-count");t[n]=e[n]}for(let n of["findings_by_kind","edf_bdf_files_by_kind"])if(e[n]!==void 0)t[n]=HM(e[n],(r)=>t$t.has(r),40,"scan-kinds");if(e.unscreened_formats!==void 0)t.unscreened_formats=HM(e.unscreened_formats,(n)=>o$t.test(n),60,"scan-formats");return t}function Bd(e){switch(e){case"clean":case"dates-only":case"no-recordings":return"clear";case"direct-identifiers":return"blocks";case"review":case"unchecked":case"not-screened":case"clean-edf-only-others-unscreened":return"acknowledge";case"pending":return"wait";default:return"rerun"}}function kke(e){return e==="pending"||e==="error"||e==="unreported"||WM.includes(e)}function m$t(e){return Object.entries(e??{}).map(([t,n])=>`${t} x${n}`).join(", ")}function $R(e){let t=0;for(let[n,r]of Object.entries(e??{}))if(Qf.has(n)&&r_(r))t+=r;return t}function h$t(e){let t=$R(e?.findings_by_kind),n="in recording headers or scans tables";if(t>0){let r=`${e?.incomplete===!0?"at least ":""}${t} ${t===1?"entry":"entries"}`;n=`${n} (${r})`}else if(e?.status!=="dates-only")return[];return[`${Eke} ${n}.`,...Ske]}function $ke(e){return e.startsWith(Eke)||Ske.includes(e)}function Dke(e){return`Acquisition dates in ${`${e} recording header${e===1?"":"s"}`} were set to 1 January of their year.`}function Rke(e){return["Your request was received.","NEMAR is checking publication eligibility.","If every check passes, an administrator is notified to approve it.","You will be emailed if a check needs your attention, and when an administrator decides.",`Run 'nemar dataset publish status ${e}' to see where it stands.`]}function g$t(e){let t=[];if(e.files){let o=e.files.header_read_failed>0?` (${e.files.header_read_failed} unreadable)`:"";t.push(`Files: ${e.files.total}; EDF/BDF headers read: ${e.files.header_read} of ${e.files.edf_bdf}${o}.`)}let n=m$t(e.findings_by_kind);if(n)t.push(`Findings by kind: ${n}.`);if(e.edf_bdf_files_flagged)t.push(`EDF/BDF files with an identifier finding: ${e.edf_bdf_files_flagged}.`);let r=Object.entries(e.unscreened_formats??{});if(r.length>0)t.push(`Not screened (format x files): ${r.map(([o,s])=>`${o} x${s}`).join(", ")}.`);if(e.incomplete_reasons.length>0)t.push(`Incomplete: ${e.incomplete_reasons.join(", ")}.`);return t}function Ake(e){let t=e?.read_failures;if(typeof t!=="object"||t===null)return e;let n={},r=(s,i)=>{n[s]=(n[s]??0)+i};for(let[s,i]of Object.entries(t)){let a=s.toLowerCase();if(VM(a)){r(a,i);continue}let c=a.slice(0,Math.max(0,a.indexOf("/")));r(`${VM(`${c}/${n_}`)?c:n_}/${n_}`,i)}let o=Object.entries(n).sort(([,s],[,i])=>i-s);if(o.length>zM){let s=Object.fromEntries(o.slice(0,zM-1)),i=`${n_}/${n_}`;for(let[,a]of o.slice(zM-1))s[i]=(s[i]??0)+a;return{...e,read_failures:s}}return{...e,read_failures:n}}function Oke(e){let t=e?.unscreened_formats;if(typeof t!=="object"||t===null)return e;let n={};for(let[r,o]of Object.entries(t)){let s=DR.has(r)?r:Cke;n[s]=(n[s]??0)+o}return{...e,unscreened_formats:n}}function KM(e){if(!ay(e))return Yt("scan-shape");o_(e,vke,"scan-key");for(let n of vke)if(e[n]===void 0)Yt("scan-missing");let t=f$t(e);for(let n of Object.keys(t.unscreened_formats))if(!DR.has(n))Yt("scan-formats");return d$t(t),t}function Tke(e){if(!ay(e))return Yt("preflight-shape");if(o_(e,["version","scanner","scan","acknowledged_via"],"preflight-key"),e.version!==ER)Yt("preflight-version");if(typeof e.scanner!=="string"||!y$t.test(e.scanner))Yt("preflight-scanner");let t=KM(e.scan),n=e.acknowledged_via;if(n!==null&&n!=="prompt"&&n!=="flag")Yt("preflight-ack");if(Bd(t.status)==="acknowledge"!==(n!==null))Yt("preflight-ack");return{version:ER,scanner:e.scanner,scan:t,acknowledged_via:n}}function JM(e,t){let n=p$t[e.status],r=g$t(e);if(r.push(...h$t(e)),t==="prompt")r.push("Acknowledged by the uploader at the prompt.");if(t==="flag")r.push("Acknowledged by the uploader with --acknowledge-identifier-preflight.");return{headline:`Identifier preflight: ${n.verdict}`,tone:n.tone,lines:r}}var e$t,GM,t$t,WM,n$t,r$t,krn,SR,ay=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e),r_=(e)=>typeof e==="number"&&Number.isSafeInteger(e)&&e>=0,o$t,s$t,i$t,a$t,c$t,l$t,u$t,p$t,Eke="Warning: acquisition dates finer than year and month were found",Ske,Cke=".other",n_="internal",zM=60,ER=1,DR,vke,RR,y$t;var Ep=V(()=>{ml();e$t={"edf-unreadable":!0,"edf-patient-nonascii":!0,"edf-recording-nonascii":!0,"path-subject-label":!0,"edf-patient-name":!0,"edf-patient-code":!0,"edf-patient-recordnumber":!0,"edf-patient-age":!0,"edf-patient-freetext":!0,"edf-patient-birthdate":!0,"edf-recording-startdate":!0,"edf-recording-freetext":!0,"edf-recording-technician":!0,"edf-startdate":!0,"edf-startdate-unparsed":!0,"participants-identifier-column":!0,"json-identifier-key":!0,"acq-time-dated":!0,"image-or-document-file":!0,"tooling-debris":!0,"local-user-path":!0},GM=Object.keys(e$t),t$t=new Set(GM),WM=["direct-identifiers","dates-only","review","clean","clean-edf-only-others-unscreened","not-screened","no-recordings","unchecked"],n$t=new Set(["manifest.json","s3-version-manifest","git-tree","clone"]),r$t=["dispatch-unconfigured","dispatch-failed","no-report-in-time","workflow-failed","clone-failed","credentials-missing","deadline"],krn=new Set(r$t);SR=class SR extends Error{constructor(e){super(e);this.name="ReportError"}};o$t=/^(\.[a-z0-9]{1,12}(\.[a-z0-9]{1,12})?\/?|\(no extension\))$/,s$t=["edf-headers-oversize","edf-headers-sampled","edf-headers-unread","json-oversize","json-sampled","json-unread","text-oversize","text-sampled","text-unread","scans-unread","participants-unread","participants-truncated","history-unread","submodule-unread","no-latest-version","manifest-shape","tree-truncated","credentials-missing","deadline"],i$t=new Set(s$t),a$t=new Set(["edf","participants","scans","json","text","internal"]),c$t=new Set(["timeout","network","deadline","credentials-missing","header-truncated","json-parse","no-body","short-body","unreadable-entry","superseded-absent","blob-missing","blob-closed","internal","error-error","error-rangeerror","error-typeerror","error-syntaxerror","error-referenceerror","error-evalerror","error-urierror","error-aborterror","error-timeouterror"]),l$t=/^http-[1-5]\d\d$/;u$t=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?Z$/;p$t={pending:{verdict:"running",tone:"note"},clean:{verdict:"clean",tone:"ok"},"dates-only":{verdict:"clean (acquisition dates only)",tone:"ok"},"no-recordings":{verdict:"clean (no recordings)",tone:"ok"},review:{verdict:"needs review",tone:"warn"},"direct-identifiers":{verdict:"FOUND IDENTIFIERS",tone:"stop"},unchecked:{verdict:"INCOMPLETE",tone:"warn"},"not-screened":{verdict:"recordings NOT screened",tone:"warn"},"clean-edf-only-others-unscreened":{verdict:"EDF/BDF clean, other recordings NOT screened",tone:"warn"},error:{verdict:"DID NOT RUN",tone:"stop"},unreported:{verdict:"DID NOT REPORT",tone:"stop"}};Ske=["NEMAR does not change them.","A date can help identify a participant when it is combined with other information.","Remove or coarsen any date that could identify someone before uploading or requesting publication.","Administrators are told of these findings when publication is requested."];DR=new Set([...YF,...W$.map((e)=>`${e}/`),".eeg",".vmrk",".mef",".kdf",".mrk",".elp",".hsp",".raw",".mhd",".tsv.gz","(no extension)",Cke]);vke=["scanned_at","status","incomplete","incomplete_reasons","files","findings_by_kind","edf_bdf_files_flagged","unscreened_formats","read_failures"],RR=WM.filter((e)=>Bd(e)==="acknowledge"),y$t=/^nemar-cli@\d{1,4}\.\d{1,4}\.\d{1,6}(-[0-9a-z.]{1,24})?$/});function Fke(e){let t=w$t-_$t-e;return Math.min(Nke,Math.max(x$t,t))}function E$t(e){return Bd(kke(e)?e:null)}function S$t(e){return e instanceof L&&(e.statusCode===401||e.statusCode===403||e.statusCode===404)}function $$t(e){if(typeof e!=="object"||e===null)return!1;let t=e;return t.version===1&&typeof t.historyHoldsOriginals==="boolean"}function D$t(e){if(!(e instanceof L)||e.statusCode!==409)return null;if(e.code!=="identifier_screen_not_clear")return null;let t=e.rawBody;return typeof t?.gate==="string"?t.gate:"unknown"}async function Mke(e){let t=e.now??Date.now,n=e.sleep??((l)=>new Promise((d)=>setTimeout(d,l))),r=e.pollMs??v$t,o=t()+(e.waitMs??Nke),s=e.onProgress??(()=>{return}),i=0,a=!$$t(e.privacy)?"no-scrub-record":e.privacy.historyHoldsOriginals?"history-holds-originals":null;if(a)for(let l=1;;l++)try{return s("Recording the importer's hold on the publication request"),await tg(e.nemarId,b$t[a]),{outcome:"review",reason:a}}catch{if(l>=Pke)throw Error(`could not record the importer's hold (${a}) on the publication request after ${Pke} attempts; deny it by hand before anyone approves it`);await n(e.approveRetryMs??Ike)}let c=async()=>{let l=!1;for(;;){try{let p=(await eg(e.nemarId)).identifier_screen;if(!p||typeof p!=="object")return{kind:"no-view"};l=!0;let m=E$t(p.state);if(m!=="wait")return{kind:"verdict",gate:m}}catch(f){if(S$t(f))return{kind:"refused"}}let d=o-t();if(d<=0)return{kind:l?"timeout":"unreadable"};s(`Waiting for the identifier screen (${Math.ceil(d/60000)} min left)`),await n(Math.min(r,d))}};for(;;){let l=await c();if(l.kind==="timeout")return{outcome:"unchecked",reason:"timeout"};if(l.kind==="unreadable")return{outcome:"unchecked",reason:"status-unreadable"};if(l.kind==="no-view")return{outcome:"unchecked",reason:"no-screen-view"};if(l.kind==="refused")return{outcome:"unchecked",reason:"status-refused"};let d=l.gate;if(d==="blocks")return{outcome:"blocked"};if(d==="acknowledge")return{outcome:"review",reason:"acknowledgment-needed"};if(d==="rerun")return{outcome:"unchecked",reason:"no-verdict"};if(d==="wait")return{outcome:"unchecked",reason:"timeout"};let f=null;for(let p=1;p<=YM;p++)try{return s(`Approving publication (attempt ${p}/${YM})`),await rg(e.nemarId,p>1,!1,e.skipCiCheck),{outcome:"published"}}catch(m){if(f=D$t(m),f!==null)break;if(p===YM)throw m;await n(e.approveRetryMs??Ike)}if(f==="stale"){if(i>=k$t)return{outcome:"unchecked",reason:"stale"};i++,s("The screened commit is no longer main; re-running the identifier screen");try{await _S(e.nemarId)}catch{return{outcome:"unchecked",reason:"rerun-failed"}}continue}if(f==="unverified"){if(o-t()<=0)return{outcome:"unchecked",reason:"unverified"};await n(Math.min(r,Math.max(0,o-t())));continue}if(o-t()<=0)return{outcome:"unchecked",reason:"timeout"};await n(Math.min(r,Math.max(0,o-t())))}}function jke(e,t){switch(t.outcome){case"published":return"Identifier screen: clear; publication approved";case"already-published":return`${e} was already published; publication not requested (data re-copy only)`;case"blocked":return"Identifier screen: blocked; publication not approved. The data must be corrected and publication requested again.";case"review":return t.reason==="history-holds-originals"||t.reason==="no-scrub-record"?`Import held (${t.reason}); the publication request was denied with that reason. An admin decides: nemar admin publish list`:`Identifier screen: review (${t.reason}); publication not approved. An admin decides: nemar admin publish list`;case"unchecked":return`Identifier screen: unchecked (${t.reason}); publication not approved. An admin decides: nemar admin publish screen ${e}`}}var b$t,Pke=3,Nke=2700000,w$t=5400000,_$t=1800000,x$t=300000,v$t=30000,k$t=1,YM=10,Ike=3000;var Lke=V(()=>{Ep();Je();Ni();b$t={"history-holds-originals":"Held by the importer (ADR 0089): its identifier scrub changed files git tracks, and the pushed history still holds their original content. Rewrite the history with ADR 0085's tools, or request publication again to publish the history as it is.","no-scrub-record":"Held by the importer (ADR 0089): the import's staging manifest has no valid record of the identifier scrub, so whether it ran is unknown. Re-run the import's prepare phase, or check the dataset and request publication again."}});import{chmodSync as R$t,existsSync as Uke,mkdirSync as C$t,mkdtempSync as XM,readFileSync as A$t,readdirSync as cy,readlinkSync as O$t,renameSync as T$t,rmSync as Hke,statSync as P$t,writeFileSync as OR}from"fs";import{tmpdir as QM}from"os";import{join as Mr}from"path";async function ZM(e,t,n=120000,r=5000){let o=Date.now()+n,s,i=!1;while(Date.now()<o){try{let c=await RS(e);if(i=!0,c.bids_validation.present&&c.bids_validation.status!=="no_runs")return{kind:"found"}}catch(c){s=c}let a=Math.max(0,o-Date.now());t.text=`Waiting for BIDS validation run to register... (${Math.ceil(a/1000)}s left)`,await new Promise((c)=>setTimeout(c,Math.min(r,a)))}if(!i&&s!==void 0)return{kind:"error",lastError:s};return{kind:"timeout"}}function F$t(e){if(!e.ciDeployed)return{skipCiCheck:!1,abortReason:"CI workflows did not deploy. Aborting before approval: --trust-upstream bypasses validation lookup, not workflow deployment. Re-run after fixing the deploy failure, or run `nemar admin ci add <id>` manually before approving."};let t=e.poll;if(t===null||t.kind==="found")return{skipCiCheck:!1};if(t.kind==="error")return{skipCiCheck:!1,abortReason:`Every BIDS validation poll attempt failed (last error: ${t.lastError instanceof Error?t.lastError.message:String(t.lastError)}). Refusing to bypass under --trust-upstream because validation state was never actually observed. Investigate API/auth health and re-run.`};if(e.trustUpstream)return{skipCiCheck:!0};return{skipCiCheck:!1,abortReason:"BIDS validation run did not register within the bounded poll window. Re-run with --trust-upstream to bypass (OpenNeuro datasets are pre-validated upstream), or investigate why the deployed CI did not trigger."}}function M$t(e){return e.includes("already exists")||e.includes("409")}function j$t(e){return e==="public"?"skip-already-published":"request"}function L$t(e){if(e.originMainSha===null||e.originMainSha==="")return"none";if(e.recordedTag!==null&&!Sr(e.recordedTag,e.importTag))return"moved";return e.currentBranch==="main"?"hard-reset":"none"}function q$t(e){return e.kind!=="hard-reset"}async function B$t(e,t){let n=await R(["git","ls-remote","--exit-code","origin","refs/heads/main"],{cwd:e});if(n.exitCode===2)return{kind:"none",recordedTag:null};let r=n.exitCode===0?await R(["git","fetch","origin","main"],{cwd:e}):n;if(r.exitCode!==0)throw Error(`Could not fetch ${t.nemarId}'s main from origin (${r.stderr.trim()}). Without it the upstream-moved guard cannot run; nothing was reset or pushed.`);let o=await R(["git","rev-parse","--verify","--quiet","origin/main"],{cwd:e}),s=await R(["git","rev-parse","--abbrev-ref","HEAD"],{cwd:e}),i=await z$t(e,t.sourceId),a=i.tag,c=i.tag===null&&(o.stdout.trim()||null)!==null?i.why:void 0;if(c!==void 0)console.log(u.yellow(` Warning: ${t.nemarId}'s main ${c}, so the upstream-moved guard cannot check this import at ${t.importTag}. If ${t.nemarId} has released a version and its upstream has moved since, this re-import keeps the old tree while copying the new tag's data (#993).`));let l=L$t({originMainSha:o.stdout.trim()||null,currentBranch:s.stdout.trim(),recordedTag:a,importTag:t.importTag}),d=c!==void 0?{unrecorded:c}:{};if(l==="none")return{kind:"none",recordedTag:a,...d};if(l==="hard-reset"){let h=await R(["git","reset","--hard","origin/main"],{cwd:e});if(h.exitCode!==0)return console.log(u.yellow(` Warning: found origin/main for ${t.nemarId} (re-import) but could not reset onto it (${h.stderr.trim()}). Falling back to the normal push path.`)),{kind:"none",recordedTag:a,...d};return{kind:"hard-reset",recordedTag:a,...d}}let f;try{f=await t.released()}catch(h){throw Error(`${t.nemarId}'s main records upstream tag ${a}, this import is at ${t.importTag}, and whether ${t.nemarId} has released a version could not be read (${h instanceof Error?h.message:String(h)}). Nothing was reset or pushed; re-run once the backend answers.`)}if(f)throw new hl(c6,`${t.sourceId}: ${t.nemarId} has released a version and its main records upstream tag ${a}; this import is at ${t.importTag}. Moving a released mirror to a new snapshot is an upstream re-pull (ADR 0111), not a re-import. Nothing was reset, copied or pushed. To pull a newer snapshot as the next major, plan an upstream re-pull: \`nemar admin repull plan ${t.nemarId}\` (OpenNeuro's latest snapshot by default; \`--to-tag ${t.importTag}\` names this one). To repair the released version's data at the tag it mirrors: nemar admin import-openneuro ${t.sourceId} --tag ${a}`);let p=await U$t(e);if(p!==0)throw Error(`${t.nemarId}'s main ${p==="unreadable"?`has a ${ho} git could not read`:`records ${p} line(s) in ${ho} that retargeting it from upstream tag ${a} to ${t.importTag} would drop`} (a privacy correction, ADR 0085, or a scrub whose originals origin's history still holds, ADR 0089). Nothing was reset or pushed; a person decides how this dataset moves.`);if(s.stdout.trim()!=="main")throw Error(`${t.nemarId}'s unreleased import moved from upstream tag ${a} to ${t.importTag}, but the clone is on ${s.stdout.trim()}, not main, which cannot be retargeted safely. Nothing was reset or pushed.`);let m=await R(["git","reset","--soft","origin/main"],{cwd:e});if(m.exitCode!==0)throw Error(`Could not move ${t.nemarId}'s unreleased import from upstream tag ${a} to ${t.importTag}: git reset --soft origin/main failed (${m.stderr.trim()}). Nothing was pushed.`);return{kind:"retarget",recordedTag:a}}async function zke(e,t){let n=await R(["git","ls-tree","--name-only","origin/main","--",t],{cwd:e});if(n.exitCode!==0)return"unreadable";return n.stdout.split(`
|
|
225
225
|
`).some((r)=>r===t)}async function U$t(e){let t=await zke(e,ho);if(t==="unreadable")return"unreadable";if(!t)return 0;let n=await R(["git","show",`origin/main:${ho}`],{cwd:e});if(n.exitCode!==0)return"unreadable";let r=0;for(let o of n.stdout.split(`
|
|
226
226
|
`)){if(o.trim()==="")continue;let s;try{s=JSON.parse(o)}catch{r+=1;continue}let i=typeof s==="object"&&s!==null?s:{};if(i.action!=="import-scrubbed"){r+=1;continue}let a=(c)=>Number(i.counts?.[c]??0)>0;if(a("json_values_blanked")||a("git_held_recordings_scrubbed"))r+=1}return r}function H$t(e,t){if(!e||typeof e!=="object"||Array.isArray(e))return!1;let n=e.SourceDatasets;return(Array.isArray(n)?n:[n]).some((r)=>Fg(r,t))}async function z$t(e,t){let n=await zke(e,"dataset_description.json");if(n==="unreadable")return{tag:null,why:"has a tree git could not list"};if(!n)return{tag:null,why:"has no dataset_description.json"};let r=await R(["git","show","origin/main:dataset_description.json"],{cwd:e});if(r.exitCode!==0)return{tag:null,why:`has a dataset_description.json git could not read (${r.stderr.trim()})`};let o;try{o=JSON.parse(r.stdout)}catch{return{tag:null,why:"has a dataset_description.json that is not JSON"}}let s=Mg(o,t);if(s.source_version!==null)return{tag:s.source_version};return{tag:null,why:H$t(o,t)?`names ${t} in SourceDatasets but records no single upstream tag for it (no entry carries one, they disagree, or one names another dataset too)`:`records no upstream tag for ${t}`}}function ej(e){let t=e.match(/^ds(\d{6})$/);if(!t)throw Error(`Invalid OpenNeuro ID "${e}". Expected format: ds###### (e.g., ds007262)`);return`on${t[1]}`}async function CR(e){let[t,n]=await Promise.all([cp(e),Cd(e)]),r=[];for(let o of t){if(n.has(o))continue;let s;try{s=P$t(Mr(e,o)).size}catch(i){let a=i.code;if(a==="ENOENT"||a==="ENOTDIR")continue;throw Error(`Cannot stat tracked file ${o}: ${i instanceof Error?i.message:String(i)}`)}if(To(o,s))r.push({path:o,size:s})}return r}function V$t(e){let t;try{t=cy(e,{withFileTypes:!0})}catch(r){let o=r.code;if(o==="ENOENT"||o==="ENOTDIR")return[];throw Error(`Cannot scan ${e} for annexed metadata: ${r instanceof Error?r.message:String(r)}`)}let n=[];for(let r of t){if(!r.isSymbolicLink())continue;if(!Uf(r.name))continue;try{if(O$t(Mr(e,r.name)).includes("annex/objects"))n.push(r.name)}catch{}}return n.sort()}function G$t(e,t){let n=t.split("/").map(encodeURIComponent).join("/");return`https://s3.amazonaws.com/openneuro.org/${e}/${n}`}async function W$t(e,t){let n=V$t(e);if(n.length===0)return[];let r=[];for(let s of n){let i=G$t(t,s),a;try{let l=await fetch(i);if(!l.ok){r.push(`${s} (HTTP ${l.status})`);continue}a=Buffer.from(await l.arrayBuffer())}catch(l){r.push(`${s} (fetch failed: ${l instanceof Error?l.message:String(l)})`);continue}if(a.length===0){r.push(`${s} (HTTP 200 but empty body)`);continue}let c=Mr(e,s);try{Hke(c,{force:!0}),OR(c,a)}catch(l){throw Error(`Failed to write fetched metadata ${s} to ${c} (local error, not OpenNeuro): ${l instanceof Error?l.message:String(l)}`)}}if(r.length>0)throw Error(`${dD} cannot fetch metadata from OpenNeuro: ${r.join(", ")}. These objects are not anonymously readable and NEMAR has no signed OpenNeuro login. This is an OpenNeuro-side access problem, not a NEMAR import bug. (Any files that did fetch are left as regular files on disk, unstaged.)`);let o=await R(["git","-c","annex.largefiles=nothing","add",...n],{cwd:e});if(o.exitCode!==0)throw Error(`Failed to stage un-annexed metadata (${n.join(", ")}): ${o.stderr.trim()}. The files are already regular files on disk; recover with: git -C ${e} -c annex.largefiles=nothing add ${n.join(" ")}`);return n}function Vke(e){let t=Mr(e,"dataset_description.json");if(!Uke(t))throw Error(`dataset_description.json not found at ${t}`);try{return JSON.parse(A$t(t,"utf-8"))}catch(n){throw Error(`Failed to parse dataset_description.json at ${t}: ${n instanceof Error?n.message:String(n)}`)}}function Gke(){let e=process.env.AWS_ACCESS_KEY_ID,t=process.env.AWS_SECRET_ACCESS_KEY;if(!e||!t)throw Error("AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY must be set in environment for S3 operations");return{accessKeyId:e,secretAccessKey:t,sessionToken:process.env.AWS_SESSION_TOKEN}}function K$t(e){return typeof e.DatasetDOI==="string"?e.DatasetDOI.replace(/^doi:/,""):null}function J$t(e){let t=new Set,n=[];try{n=cy(e,{withFileTypes:!0}).filter((r)=>r.isDirectory()&&r.name.startsWith("sub-")).map((r)=>r.name)}catch{return[]}for(let r of n){let o=Mr(e,r),s=[];try{s=cy(o,{withFileTypes:!0})}catch{continue}for(let i of s){if(!i.isDirectory())continue;if(i.name.startsWith("ses-")){let a=[];try{a=cy(Mr(o,i.name),{withFileTypes:!0})}catch{continue}for(let c of a)if(c.isDirectory()&&qke.includes(c.name))t.add(c.name)}else if(qke.includes(i.name))t.add(i.name)}}return[...t].sort()}function Y$t(e){let t=e.Funding;if(!Array.isArray(t))return[];return t.filter((n)=>typeof n==="string"&&n.trim().length>0).map((n)=>({funder_name:n.trim()}))}function X$t(e,t,n,r,o){let s=Mr(e,".nemar");if(!Uke(s))C$t(s,{recursive:!0});let i=o?[{identifier:o,identifier_type:"DOI",relation_type:"IsIdenticalTo"}]:[],a=J$t(e),c=Y$t(r),l={version:"2.0",dataset_id:t,source:"openneuro",source_id:n,title:r.Name||t,authors:Array.isArray(r.Authors)?Object.fromEntries(r.Authors.map((d)=>[d,{}])):{},license:r.License||"CC0",dataset_type:r.DatasetType||"raw",related_identifiers:i,pipeline_stage:"seeded"};if(typeof r.BIDSVersion==="string")l.bids_version=r.BIDSVersion;if(a.length>0)l.recording_modality=a;if(a.length>0)l.datatypes=a;if(c.length>0)l.funding_references=c;if(typeof r.Acknowledgements==="string"&&r.Acknowledgements.trim().length>0)l.acknowledgements=r.Acknowledgements.trim();OR(Mr(s,"metadata.json"),`${JSON.stringify(l,null,2)}
|
|
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 (ADR 0111 decision 8 is not built), 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
|
-
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();
|
|
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(`
|
|
234
234
|
`).filter(Boolean)){let s=await R(["git","annex","lookupkey","--",o],{cwd:e});if(s.exitCode===0&&s.stdout.trim())r.add(s.stdout.trim())}return[...r].sort()}async function fDt(e,t){let n=await R(["git","remote","get-url","origin"],{cwd:e});if(n.exitCode!==0||!n.stdout.includes(`/${t}`))throw Error(`${e} exists but its origin is not ${t} (${n.stdout.trim()||"no origin"}). Point --dir somewhere else.`);let r=await R(["git","fetch","origin","main"],{cwd:e});if(r.exitCode!==0)throw Error(`Could not fetch origin/main in ${e}: ${r.stderr.trim()}`);if((await R(["git","merge-base","--is-ancestor","origin/main","HEAD"],{cwd:e})).exitCode!==0)throw Error(`${e} is behind or diverged from origin/main. Delete it and let this re-clone, rather than committing onto a stale tree.`);let s=await R(["git","status","--porcelain"],{cwd:e});if(s.exitCode!==0)throw Error(`Could not read the status of ${e}: ${s.stderr.trim()}`);if(s.stdout.trim()!=="")throw Error(`${e} has uncommitted changes, most likely a previous attempt that stopped after annexing but before committing. Reset it (git -C ${e} reset --hard origin/main) or delete it, then re-run: continuing from here would find nothing left to move and report success without migrating anything.`)}async function pDt(e,t){let r=(await R(["git","rev-parse","--abbrev-ref","HEAD"],{cwd:e})).stdout.trim();if(r==="main"||r.startsWith("adjusted/main"))return;let s=await R(["git","checkout",...r==="git-annex"?["--force"]:[],"main"],{cwd:e});if(s.exitCode!==0)throw Error(`${t} is checked out on "${r}" and switching to main failed: ${s.stderr.trim()||`exit ${s.exitCode}`}. Its default branch is not main, and this migration only has meaning on main.`)}async function mDt(e){let{stdout:t,exitCode:n,stderr:r}=await R(["git","grep","-l","annex.largefiles","HEAD","--",".gitattributes","*/.gitattributes"],{cwd:e});if(n>1)throw Error(`git grep failed: ${r.trim()||`exit ${n}`}`);let o=t.split(`
|
|
235
235
|
`).filter(Boolean).map((i)=>i.replace(/^HEAD:/,"")),s=[];for(let i of o){let a=await R(["git","show",`HEAD:${i}`],{cwd:e});if(a.exitCode!==0)continue;let c=Od(a.stdout);if(c.stripped>0||c.skipped.length>0)s.push(i)}return s}async function PR(e,t={}){let n=t.remoteName??Yke,{datasetId:r,datasetPath:o}=e,s,i,a;if(t.upload)s=t.upload,i=Qke(o,n);else if(e.files.length===0&&(e.pendingKeys?.length??0)===0)s=async({files:m})=>{throw Error(`${r}: ${m.length} file(s) reached the upload leg although the plan found no data to move. Refusing to continue: no credentials were obtained for this run.`)},i=async()=>({present:[],absent:[],unconfirmed:[],method:"no keys"});else if(n!==Yke)s=Rw({credentials:"inherit"}),i=Qke(o,n);else if(t.credentials==="ambient"){let m=await gDt(o,n);if(!m)throw Error(`${r} has no ${n} remote recorded in its git-annex branch, so there is no UUID to register keys against. Was this dataset ever uploaded?`);s=oj({bucket:"nemar",datasetId:r,region:"us-east-2",remoteUuid:m,workDir:Sp(o,"..")}),i=Xke({bucket:"nemar",region:"us-east-2",prefix:`${r}/objects`})}else{let m=await Gr(r),h=await N$({credentials:m.credentials,bucket:m.s3.bucket,region:m.s3.region,prefix:m.s3.prefix});if(h.outcome==="refused")throw Error(`The credentials the API minted for ${r} cannot read s3://${h.bucket}/${h.prefix}/: ${h.detail}. Refusing to start the migration. Check that the API's S3 identity still covers the bucket and that the session policy names this dataset; \`nemar admin s3 credential-check ${r}\` reports both. \`--via-aws-cli\` moves the same content with this machine's own AWS configuration instead.`);if(h.outcome==="unavailable")throw Error(`${r}: ${h.detail??"the aws CLI is unavailable"}, so nothing on this host can confirm the upload reached S3. Install the aws CLI (nemar doctor lists it) or run with --via-aws-cli on a host that has it.`);if(h.outcome!=="reachable")a=`credential preflight inconclusive (${h.outcome}${h.detail?`: ${h.detail}`:""})`;let g=await Fo(o,{name:n,bucket:m.s3.bucket,prefix:m.s3.prefix,region:m.s3.region},lr(m.credentials));if(!g.success)throw Error(`Failed to enable ${n}: ${g.error}`);if(!await _d(o,n))throw Error(`Could not resolve the ${n} UUID after enabling it. Aborting: keys registered against an unknown remote are unfindable for clones.`);s=Rw({credentials:lr(m.credentials)}),i=Xke({credentials:m.credentials,bucket:m.s3.bucket,region:m.s3.region,prefix:m.s3.prefix})}let c=await kD({datasetPath:o,nemarId:r,bucket:"nemar",remoteName:n,unannexedData:e.files,upstreamKeys:new Set,carryOverUnaccountedKeys:!1,maxBytes:t.maxBytes,upload:s}),l=[...new Set([...(c.data?.files??[]).map((m)=>m.key),...e.pendingKeys??[]])],d=l.length>0?await i(l):null;if(d&&d.present.length!==l.length){let m=d.absent[0],h=d.unconfirmed[0],g=m?`first absent: ${m}`:h?`first unconfirmed: ${h}`:"none named";throw Error(`${r}: the remote confirms ${d.present.length} of ${l.length} uploaded key(s) (${d.absent.length} absent, ${d.unconfirmed.length} unconfirmed, checked by ${d.method}). NOTHING HAS BEEN PUSHED, so no clone can see a tree naming content that is not there. ${g}${d.detail?` (${d.detail})`:""}. The work is intact at ${o}; re-run with --dir ${o} to resume the upload rather than starting over.`)}let f=!1,p=t.push?await hDt(o):[];if(p.length>0){let m=await sr(o,"origin");if(!m.success)throw Error(`Normalized ${r} (${p.join(", ")} ahead of origin), but the push failed: ${m.error}. Any content is already in S3 and the work is local; re-run the push from ${o} rather than redoing the upload.`);if(m.warning)throw Error(`Pushed main for ${r} but the git-annex branch did not land: ${m.warning}. Clones cannot find the new keys until it does -- push the git-annex branch from ${o} before considering this done.`);f=!0}return{plan:e,keys:l,committed:c.committed,pushed:f,notes:a?[a,...c.notes]:c.notes,verification:d}}function Xke(e){return async(t)=>{let n=await L0e({...e,keys:t}),r={present:n.filter((o)=>o.outcome==="present").map((o)=>o.key),absent:n.filter((o)=>o.outcome==="absent").map((o)=>o.key),unconfirmed:n.filter((o)=>o.outcome==="unknown").map((o)=>o.key),method:`s3 head-object on ${e.bucket}/${e.prefix}`};return r.detail=n.find((o)=>o.detail)?.detail,r}}function Qke(e,t){return async(n)=>{let r=`fsck --from ${t}, then the location log`,o=await R(["git","annex","fsck","--from",t,"--fast","--quiet","--all"],{cwd:e}),s=await R(["git","annex","find","--include","*","--in",t,"--format=${key}\n"],{cwd:e}),i=new Set(s.exitCode===0?s.stdout.split(`
|
|
236
236
|
`).filter(Boolean):[]),a=n.filter((d)=>i.has(d)),c=n.filter((d)=>!i.has(d)),l=(o.stderr||o.stdout).trim().split(`
|
|
@@ -247,14 +247,14 @@ sub-02 30 F
|
|
|
247
247
|
[finalize] ${s} -> ${o}
|
|
248
248
|
`)),t.keys.length>0){let _=D("Verifying copied data...").start(),x=await dl(x_,`${o}/objects/`,Op),k=TAt(t.keys,x);if(k.length>0){let F=`${k.length} of ${t.keys.length} objects missing at s3://${x_}/${o}/objects/. Re-run the copy phase before finalizing.`;throw _.fail(F),Error(F)}_.succeed(`Verified ${t.keys.length} objects present`);let v=await _d(r,e.devRemote??rL);if(v!==i){let F=`${e.devRemote??rL} uuid drifted (prepare=${i} now=${v}). Aborting before registering keys against the wrong remote.`;throw console.error(u.red(F)),Error(F)}let C=D("Registering files in git-annex...").start(),T=await xd(r,t.keys,i);if(T.failed>0){let F=`${T.failed} of ${t.keys.length} git-annex key registrations are not in the location log (e.g. ${T.missing.slice(0,3).join(", ")}). Re-run finalize to retry.`;throw C.fail(F),Error(F)}C.succeed(`Registered ${T.success} files in git-annex`);let z=D("Pushing git-annex branch...").start(),A=await sr(r,"origin");if(!A.success){let F=`Failed to push git-annex branch: ${A.error}`;throw z.fail(F),Error(F)}if(A.warning){let F=`git-annex branch push failed: ${A.warning}`;throw z.fail(F),Error(F)}z.succeed("Pushed git-annex branch")}let a=!1,c=D("Deploying CI workflows...").start();try{await il(o),c.succeed("CI workflows deployed (BIDS validation, LLM enrichment, archive generation)"),a=!0}catch(_){let x=_ instanceof Error?_.message:String(_);c.fail(`CI deployment failed: ${x}`),console.log(u.dim(` After fixing the deploy failure, run 'nemar admin ci add ${o}'.`))}if(a){let _=D("Waiting for BIDS validation run to register...").start(),x=await ZM(o,_);if(x.kind==="found")_.succeed("BIDS validation run registered");else if(x.kind==="timeout")_.warn("BIDS validation run did not register within 120s; continuing (ci_check retries at approval).");else{let k=x.lastError instanceof Error?x.lastError.message:String(x.lastError);_.fail(`BIDS validation polls failed: ${k}`)}}let l=!1,d=D("Refreshing metadata + LLM enrichment...").start();try{let _=await ig(o),x=_.enrichment?.status==="ok",k=_.sync?.metadata_columns_written===!0;if(l=x&&k,l)d.succeed("Refreshed enrichment + metadata columns");else d.warn(`Partial reindex (run 'nemar admin reindex ${o}' to retry)`)}catch(_){let x=_ instanceof Error?_.message:String(_);d.warn(`Reindex failed (non-fatal): ${x}`)}if(!n.publish){console.log(u.green(`
|
|
249
249
|
Exemplar clone complete: ${s} -> ${o} (not published; re-run with --publish).`));return}if(!l)throw Error(`Refusing to publish ${o}: metadata reindex did not fully succeed, so .nemar/metadata.json may still carry the source dataset's real identity. Re-run 'nemar admin reindex ${o}' until it succeeds, then 'nemar admin publish request/approve ${o}' to publish manually.`);let f=5,p=300000,m=D("Requesting publication...").start(),h=!1;for(let _=1;_<=f;_++)try{await Zh(o),h=!0;break}catch(x){let k=x instanceof Error?x.message:String(x);if(!k.includes("BIDS validation is currently running")){let v=`Failed to request publication: ${k}`;throw m.fail(v),Error(v)}if(_===f){let v=`BIDS validation still running after ${f} attempts. Re-run 'nemar admin publish request/approve ${o}' once validation completes.`;throw m.fail(v),Error(v)}m.text=`Waiting for BIDS validation to complete... (attempt ${_}/${f})`,await new Promise((v)=>setTimeout(v,p))}if(h)m.succeed("Publication requested");let g=D("Approving publication (sandbox DOI)...").start(),y=10,b=!1;for(let _=1;_<=y;_++)try{await rg(o,_>1,!0),b=!0;break}catch(x){let k=x instanceof Error?x.message:String(x);if(_<y)g.text=`Approving publication... (attempt ${_+1}/${y})`,await new Promise((v)=>setTimeout(v,3000));else{let v=`Failed to approve publication after ${y} attempts: ${k}`;throw g.fail(v),Error(v)}}if(b)g.succeed("Publication approved (sandbox DOI)");console.log(u.green(`
|
|
250
|
-
Exemplar clone + publish complete: ${s} -> ${o}`)),console.log(u.dim(` GitHub: https://github.com/${__}/${o}`))}async function iL(e){let t=await AAt(e.xxId,e.sourceId,{workDir:e.workDir,name:e.name,description:e.description,...e.mirror!==void 0?{mirror:e.mirror}:{}}),n=await OAt(t,{includeDerived:e.includeDerived});await PAt(t,n,{publish:e.publish})}var __="nemarDatasets",c$e="nemar",x_="nemar-dev",Op="us-east-2",d$e=16,f$e,p$e,tL="nemar-s3",rL="nemar-s3-dev",l$e="nemar-s3-source",DAt="annex-uuid";var l1=V(()=>{He();ro();Qa();
|
|
250
|
+
Exemplar clone + publish complete: ${s} -> ${o}`)),console.log(u.dim(` GitHub: https://github.com/${__}/${o}`))}async function iL(e){let t=await AAt(e.xxId,e.sourceId,{workDir:e.workDir,name:e.name,description:e.description,...e.mirror!==void 0?{mirror:e.mirror}:{}}),n=await OAt(t,{includeDerived:e.includeDerived});await PAt(t,n,{publish:e.publish})}var __="nemarDatasets",c$e="nemar",x_="nemar-dev",Op="us-east-2",d$e=16,f$e,p$e,tL="nemar-s3",rL="nemar-s3-dev",l$e="nemar-s3-source",DAt="annex-uuid";var l1=V(()=>{He();ro();Qa();Je();Ni();ii();rc();qt();cc();Pr();s_();cs();f$e=/^xx0999\d{2}$/,p$e=/^(nm|on)\d{6}$/});import{rmSync as IAt}from"fs";function k_(e){let t=!aL(e),n=e.gitResidentData.length>0;if(t&&n)return"policy-and-data";if(n)return"data";if(t)return"policy";return"compliant"}function FAt(e){let t=new Map;for(let r of e.split(`
|
|
251
251
|
`)){let o=r.match(/^(\d+(?:\.\d+)?)s\s+(\S+)\s*(.*)$/);if(!o)continue;let[,s,i,a]=o,c=Number(s),l=a.trim(),d=t.get(i);if(!d||d.at<=c)t.set(i,{at:c,value:l})}let n=new Map;for(let[r,{value:o}]of t)if(o!=="")n.set(r,o);return n}function MAt(e){let t=[];for(let[i,a]of e.attributeContents){let c=Od(a);if(c.stripped===0&&c.skipped.length===0)continue;t.push({path:i,rulesRemoved:c.stripped,declined:c.skipped})}t.sort((i,a)=>i.path.localeCompare(a.path));let r=(e.configLog?FAt(e.configLog):new Map).get("annex.largefiles")??null,o=[],s=[];for(let i of e.entries){if(i.mode!=="100644"&&i.mode!=="100755")continue;let a=i.size??Number.POSITIVE_INFINITY;if(!To(i.path,a))continue;if(a<=cL){s.push(i.path);continue}o.push({path:i.path,size:a})}return{datasetId:e.datasetId,attributeFiles:t,policyConfigured:r!==null&&ghe(r),configuredExpression:r,gitResidentData:o,pointerSuspects:s,treeTruncated:e.treeTruncated}}function jAt(e){return e.filter((t)=>t.path===".gitattributes"||t.path.endsWith("/.gitattributes")).map((t)=>t.path).sort()}async function y$e(e={}){let t=e.baseUrl??"https://api.github.com",n=process.env.GH_TOKEN?.trim()||process.env.GITHUB_TOKEN?.trim()||"";if(!n){let{stdout:r,exitCode:o,stderr:s}=await R(["gh","auth","token"],{sensitiveOutput:!0});if(o!==0||!r.trim())throw Error(`No GitHub token available: set GH_TOKEN, or run \`gh auth login\` (gh said: ${s.trim()||`exit ${o}`}). A sweep of the fleet cannot run on the anonymous rate limit.`);n=r.trim()}return{async get(r){let o=`${t}/${r.replace(/^\//,"")}`,s="";for(let i=0;i<3;i++){let a;try{a=await fetch(o,{headers:{Authorization:`Bearer ${n}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"nemar-cli fleet annex-policy sweep"}})}catch(c){s=c instanceof Error?c.message:String(c),await new Promise((l)=>setTimeout(l,500*(i+1)));continue}if(a.status===403||a.status===429){let c=a.headers.get("x-ratelimit-remaining"),l=a.headers.get("x-ratelimit-reset");if(c==="0"){let d=l?new Date(Number(l)*1000).toISOString():"unknown";throw new Dc(`GitHub rate limit exhausted; it resets at ${d}. Re-run the sweep after that, or narrow it with --limit.`,a.status,!0)}}if(a.status>=500||a.status===429){s=`HTTP ${a.status}`,await new Promise((c)=>setTimeout(c,500*(i+1)));continue}return{status:a.status,body:await a.text()}}throw new Dc(`GET ${r} failed after 3 attempts: ${s}`,0)}}}function h$e(e,t){let n=JSON.parse(e);if(n.encoding!=="base64"||typeof n.content!=="string")throw Error(`${t}: expected a base64 blob, got encoding=${n.encoding}`);return Buffer.from(n.content.replace(/\n/g,""),"base64").toString("utf8")}async function u1(e,t,n={}){let r=n.branch??"main",o=`repos/${NAt}/${e}`,s=await t.get(`${o}/git/trees/${r}?recursive=1`);if(s.status!==200)throw new Dc(`Could not read ${e}'s ${r} tree: HTTP ${s.status}`,s.status);let i=JSON.parse(s.body),a=(i.tree??[]).filter((p)=>p.type==="blob"),c=a.map((p)=>({path:p.path,mode:p.mode,size:p.size})),l=new Map;for(let p of jAt(c)){let m=a.find((g)=>g.path===p)?.sha;if(!m)continue;let h=await t.get(`${o}/git/blobs/${m}`);if(h.status!==200)throw new Dc(`Could not read ${e}:${p} (blob ${m.slice(0,8)}): HTTP ${h.status}`,h.status);l.set(p,h$e(h.body,`${e}:${p}`))}let d=await t.get(`${o}/contents/config.log?ref=git-annex`),f=null;if(d.status===200)f=h$e(d.body,`${e}:git-annex:config.log`);else if(d.status!==404)throw new Dc(`Could not read ${e}'s git-annex config.log: HTTP ${d.status}`,d.status);return MAt({datasetId:e,entries:c,treeTruncated:Boolean(i.truncated),attributeContents:l,configLog:f})}async function LAt(e){await R(["chmod","-R","u+w",e]),IAt(e,{recursive:!0,force:!0})}async function b$e(e,t,n){let r=await u1(e,t),o=k_(r);if(o==="compliant")return{datasetId:e,before:r,action:"compliant"};if((o==="data"||o==="policy-and-data")&&!n.includeData)return{datasetId:e,before:r,action:"skipped-has-data",notes:[`${r.gitResidentData.length} file(s) NEMAR policy calls data are in git; that needs the S3 leg (nemar admin annex-normalize ${e})`]};let s=`${n.workRoot.replace(/\/$/,"")}/${e}`;try{let i=await TR(e,{workDir:n.workRoot,originUrl:n.originUrl});if(i.files.length>0&&!n.includeData)return{datasetId:e,before:r,action:"skipped-has-data",notes:[`the clone found ${i.files.length} data file(s) in git that the tree listing did not; re-run with --include-data or use nemar admin annex-normalize ${e}`]};let a=await PR(i,{push:n.push!==!1,credentials:n.credentials,maxBytes:n.maxBytes});if(!a.committed&&!a.pushed)return{datasetId:e,before:r,action:"compliant",committed:!1,pushed:!1,notes:[...a.notes,"the clone found nothing to change"]};let c;if(n.push!==!1)try{c=await qAt(e,t)}catch(d){if(d instanceof Dc&&d.fatal)throw d;return{datasetId:e,before:r,action:"unverified",committed:a.committed,pushed:a.pushed,notes:[...a.notes,`pushed, but the read-back could not be completed: ${d instanceof Error?d.message:String(d)}. Re-run the read-only report for this dataset to confirm.`]}}let l=[...a.notes];if(c?.remainingDeclined.length)l.push(`left alone: ${c.remainingDeclined.join(", ")} (a quoted pattern the strip will not split; fix by hand)`);return{datasetId:e,before:r,action:c===void 0||c.landed?"applied":"unverified",committed:a.committed,pushed:a.pushed,notes:l,after:c?.state}}catch(i){return{datasetId:e,before:r,action:"failed",error:i instanceof Error?i.message:String(i)}}finally{if(!n.keepClone)try{await LAt(s)}catch{}}}async function qAt(e,t,n={}){let r=n.attempts??3,o=n.delayMs??3000,s=await u1(e,t);for(let i=1;i<r;i++){if(aL(s))break;await new Promise((a)=>setTimeout(a,o)),s=await u1(e,t)}return{landed:aL(s),state:s,remainingDeclined:s.attributeFiles.filter((i)=>i.declined.length>0).map((i)=>i.path)}}function aL(e){if(e.treeTruncated)return!1;return e.policyConfigured&&e.attributeFiles.every((t)=>t.rulesRemoved===0)}function g$e(e){let t={compliant:[],policy:[],"policy-and-data":[],data:[]},n=[],r=[],o=[];for(let s of e)if(s.state){if(r.push(s.state),t[k_(s.state)].push(s.datasetId),s.state.treeTruncated)o.push(s.datasetId)}else if(s.error)n.push({datasetId:s.datasetId,error:s.error});return{scanned:r.length,byLabel:t,truncated:o,failed:n,states:r}}async function w$e(e,t,n={}){let r=[];await BAt(e,n.concurrency??4,async(s)=>{try{let i=await u1(s,t);n.onResult?.({datasetId:s,state:i}),r.push({datasetId:s,state:i})}catch(i){if(i instanceof Dc&&i.fatal)throw new d1(i,g$e(r));let a=i instanceof Error?i.message:String(i);n.onResult?.({datasetId:s,error:a}),r.push({datasetId:s,error:a})}});let o=new Map(e.map((s,i)=>[s,i]));return r.sort((s,i)=>(o.get(s.datasetId)??0)-(o.get(i.datasetId)??0)),g$e(r)}function _$e(e,t){let n=t.prefix??"on",r=t.exclude??new Set,o=e.map((s)=>s.dataset_id).filter((s)=>s.startsWith(n)).filter((s)=>t.force||!r.has(s)).sort();return t.limit!==void 0?o.slice(0,t.limit):o}async function BAt(e,t,n){let r=Array(e.length),o=0,s=Array.from({length:Math.max(1,Math.min(t,e.length))},()=>(async()=>{while(!0){let i=o++;if(i>=e.length)return;r[i]=await n(e[i],i)}})());return await Promise.all(s),r}var NAt="nemarDatasets",cL=256,Dc,d1;var f1=V(()=>{Fi();qt();Td();IR();Dc=class Dc extends Error{status;fatal;constructor(e,t,n=!1){super(e);this.status=t;this.fatal=n;this.name="GitHubReadError"}};d1=class d1 extends Error{cause;partial;constructor(e,t){super(e.message);this.cause=e;this.partial=t;this.name="FleetSweepAborted"}}});function EOt(e){return e.replace(/\/+$/,"")}function VDe(e,t=kOt){return`${EOt(t)}/dataset/${e}`}var zDe,Vfn,kOt="https://nemar.org";var DL=V(()=>{zDe=["IsCitedBy","Cites","IsSupplementTo","IsSupplementedBy","IsContinuedBy","Continues","IsDescribedBy","Describes","HasMetadata","IsMetadataFor","HasVersion","IsVersionOf","IsNewVersionOf","IsPreviousVersionOf","IsPartOf","HasPart","IsReferencedBy","References","IsDocumentedBy","Documents","IsCompiledBy","Compiles","IsVariantFormOf","IsOriginalFormOf","IsIdenticalTo","IsCollectedBy","Collects","IsRequiredBy","Requires","IsObsoletedBy","Obsoletes","IsDerivedFrom","IsSourceOf","IsReviewedBy","Reviews","IsPublishedIn","HasTranslation","IsTranslationOf"],Vfn=new Set(zDe)});var k1e=()=>{};function E1e(e){return e.replace(/^(doi:|https?:\/\/(dx\.)?doi\.org\/)/i,"").trim()}function S1e(e){let t=e.split(",").map((n)=>n.trim());if(t.length>=2)return{name:e,familyName:t[0],givenName:t.slice(1).join(", ")};return{name:e}}var $1e=V(()=>{DL();xa();k1e()});function SPt(e){let t=e,n=(t.match(/\(/g)??[]).length,r=(t.match(/\)/g)??[]).length;while(r>n&&t.endsWith(")"))t=t.slice(0,-1),r-=1;return t}function D1e(e){let t=e.trim().replace(/^(?:doi:|https?:\/\/(?:dx\.)?doi\.org\/)/i,""),n;do n=t,t=SPt(t).replace(/[.,;:]+$/,"").trim();while(t!==n);return t.toLowerCase()}var R1e=()=>{};function APt(e){if(RPt.has(e))return"absent";return e>=200&&e<300?"found":"failed"}function OPt(e){let t=e instanceof Error?`${e.name} ${e.message}`:String(e);return/AbortError|TimeoutError|timeout|fetch|network/i.test(t)}async function TPt(e,t,n){let{base:r,accept:o}=CPt[e],s=AbortSignal.timeout(DPt);try{let i=await fetch(`${r}/${encodeURIComponent(t)}`,{headers:{Accept:o,"User-Agent":$Pt},signal:n?AbortSignal.any([s,n]):s}),a=APt(i.status);if(a==="absent")return{outcome:"absent"};if(a==="failed"){let c=`HTTP ${i.status}`;return console.warn(`[doi-registry] ${e} returned ${c} for ${t}`),{outcome:"failed",detail:c}}return{outcome:"found",body:await i.json()}}catch(i){if(n?.aborted)return{outcome:"failed",detail:"deadline reached"};let a=i instanceof Error?i.message:String(i);if(OPt(i))console.warn(`[doi-registry] ${e} lookup failed for ${t}: ${a}`);else console.error(`[doi-registry] Unexpected error querying ${e} for ${t}:`,i);return{outcome:"failed",detail:a}}}function c3(e,t,n,r){let o=D1e(t),s=`${e}:${o}`,i=n?.get(s);if(i)return i;if(r?.aborted)return Promise.resolve({outcome:"failed",detail:"deadline reached"});let a=TPt(e,o,r);if(n){if(n.set(s,a),r)a.then((c)=>{if(c.outcome==="failed"&&r.aborted&&n.get(s)===a)n.delete(s)})}return a}var $Pt="NEMAR/1.0 (https://nemar.org; mailto:nemar@ucsd.edu)",DPt=1e4,RPt,CPt;var C1e=V(()=>{R1e();RPt=new Set([400,404,410]),CPt={DataCite:{base:"https://api.datacite.org/application/vnd.datacite.datacite+json",accept:"application/vnd.datacite.datacite+json"},Crossref:{base:"https://api.crossref.org/works",accept:"application/json"}}});function NPt(e){let t=[],n=new Set,r=(o,s)=>{let i=E1e(o).trim();if(PPt.test(i)&&!n.has(i))n.add(i),t.push({doi:i,source:s})};if(Array.isArray(e.SourceDatasets))for(let o of e.SourceDatasets){if(!o||typeof o!=="object")continue;let s=o;if(typeof s.DOI==="string")r(s.DOI,"SourceDatasets");else if(typeof s.URL==="string"){let i=s.URL.match(/(?:doi\.org\/|doi:)(10\.\d{4,}\/.+)/);if(i)r(i[1],"SourceDatasets")}}if(Array.isArray(e.ReferencesAndLinks))for(let o of e.ReferencesAndLinks){if(typeof o!=="string"||!o)continue;let s=o.match(/(?:doi\.org\/|^)(10\.\d{4,}\/[^\s]+)/);if(s)r(s[1],"ReferencesAndLinks")}if(typeof e.HowToAcknowledge==="string"){let s=e.HowToAcknowledge.matchAll(/(?:doi\.org\/|(?<=\s|^))(10\.\d{4,}\/[^\s,)]+)/g);for(let i of s)r(i[1].replace(/[.;:]+$/,""),"HowToAcknowledge")}return t}async function FPt(e,t){let n=await c3("DataCite",e,t);if(n.outcome!=="found")return null;let r=n.body;return{doi:e,creators:Array.isArray(r?.creators)?r.creators.map((o)=>({...o})):[]}}async function MPt(e,t){let n=await c3("Crossref",e,t);if(n.outcome!=="found")return null;let o=n.body?.message?.author;if(!Array.isArray(o)||o.length===0)return null;let s=o.map((i)=>{let a=[];if(i.ORCID)a.push({nameIdentifier:i.ORCID,nameIdentifierScheme:"ORCID"});return{name:i.family&&i.given?`${i.family}, ${i.given}`:i.name||i.family||"",givenName:i.given,familyName:i.family,nameIdentifiers:a,affiliation:(i.affiliation||[]).filter((c)=>c.name)}}).filter((i)=>i.name.trim()!=="");return{doi:e,creators:s}}async function jPt(e,t){let n=await FPt(e,t),r=await MPt(e,t);if(!n)return r;if(!r)return n;for(let o of n.creators){if(o.nameIdentifiers?.some((c)=>c.nameIdentifierScheme==="ORCID")||!o.familyName)continue;let a=r.creators.find((c)=>c.familyName&&_i(c.familyName)===_i(o.familyName))?.nameIdentifiers?.find((c)=>c.nameIdentifierScheme==="ORCID");if(a)o.nameIdentifiers=[...o.nameIdentifiers??[],a]}return n}function _i(e){return e.normalize("NFD").replace(/\p{Diacritic}/gu,"").replace(/\./g,"").toLowerCase().trim()}function A1e(e){if(!e)return"";return _i(e).charAt(0)}function LPt(e,t){let n=[],r=new Set,o=new Set,s=t.map((i)=>({original:i,parsed:S1e(i)}));for(let i=0;i<e.length;i++){if(o.has(i))continue;let a=e[i],c=_i(a.name);for(let l of s){if(r.has(l.original))continue;if(_i(l.original)===c){n.push({bidsAuthor:l.original,matchedCreator:a,confidence:"exact"}),r.add(l.original),o.add(i);break}if(l.parsed.familyName&&l.parsed.givenName){if(_i(`${l.parsed.givenName} ${l.parsed.familyName}`)===c){n.push({bidsAuthor:l.original,matchedCreator:a,confidence:"exact"}),r.add(l.original),o.add(i);break}}if(a.givenName&&a.familyName){let d=_i(`${a.givenName} ${a.familyName}`);if(_i(l.original)===d){n.push({bidsAuthor:l.original,matchedCreator:a,confidence:"exact"}),r.add(l.original),o.add(i);break}}}}for(let i=0;i<e.length;i++){if(o.has(i))continue;let a=e[i];if(!a.familyName)continue;let c=_i(a.familyName),l=A1e(a.givenName);for(let d of s){if(r.has(d.original))continue;if(!d.parsed.familyName)continue;if(_i(d.parsed.familyName)!==c)continue;let p=A1e(d.parsed.givenName);if(p&&l&&p===l){n.push({bidsAuthor:d.original,matchedCreator:a,confidence:"high"}),r.add(d.original),o.add(i);break}}}for(let i=0;i<e.length;i++){if(o.has(i))continue;let a=e[i];if(!a.familyName)continue;let c=_i(a.familyName);for(let l of s){if(r.has(l.original))continue;if(!l.parsed.familyName)continue;if(_i(l.parsed.familyName)===c){n.push({bidsAuthor:l.original,matchedCreator:a,confidence:"medium"}),r.add(l.original),o.add(i);break}}}return n}async function T1e(e,t,n,r){let o=NPt(e);if(n?.length)o.push(...n);if(o.length===0)return{discoveries:{},unresolvedDois:[],totalDoisQueried:0};let s=Array.isArray(e.Authors)?e.Authors.filter((f)=>typeof f==="string"):[];if(s.length===0)return{discoveries:{},unresolvedDois:[],totalDoisQueried:o.length};let i=new Set;if(t){for(let[f,p]of Object.entries(t))if(p.orcid)i.add(f)}let a=s.filter((f)=>!i.has(f));if(a.length===0)return{discoveries:{},unresolvedDois:[],totalDoisQueried:o.length};let c=[],l=new Map;for(let f=0;f<o.length;f+=O1e){let p=o.slice(f,f+O1e),m=await Promise.all(p.map((h)=>jPt(h.doi,r)));for(let h=0;h<p.length;h++)if(m[h])l.set(p[h].doi,m[h]?.creators??[]);else c.push(p[h].doi)}let d={};for(let[f,p]of l){let m=p.filter((g)=>g.nameIdentifiers?.some((y)=>y.nameIdentifierScheme==="ORCID"));if(m.length===0)continue;let h=LPt(m,a);for(let g of h){if(d[g.bidsAuthor])continue;let y=g.matchedCreator.nameIdentifiers.find((x)=>x.nameIdentifierScheme==="ORCID");if(!y)continue;let b=y.nameIdentifier.replace(/^https?:\/\/orcid\.org\//i,"").trim();if(!IPt.test(b))continue;let _=g.matchedCreator.affiliation?.filter((x)=>x.name).map((x)=>({name:x.name,...x.affiliationIdentifier&&{identifier:x.affiliationIdentifier},...x.affiliationIdentifierScheme&&{scheme:x.affiliationIdentifierScheme}}));d[g.bidsAuthor]={orcid:b,affiliations:_?.length?_:void 0,sourceDoi:f,confidence:g.confidence}}}return{discoveries:d,unresolvedDois:c,totalDoisQueried:o.length}}var PPt,IPt,O1e=5;var P1e=V(()=>{$1e();C1e();PPt=/^10\.\d{4,}\/[^\s]+$/,IPt=/^\d{4}-\d{4}-\d{4}-[\dX]{4}$/});var wC={};L3(wC,{program:()=>fq,createCommand:()=>pq,createOption:()=>mq,createArgument:()=>hq,Command:()=>gq,Option:()=>yq,Argument:()=>bq,Help:()=>wq,CommanderError:()=>_q,InvalidArgumentError:()=>xq,InvalidOptionArgumentError:()=>vq},{program:(dNt)=>fq=dNt,createCommand:(dNt)=>pq=dNt,createOption:(dNt)=>mq=dNt,createArgument:(dNt)=>hq=dNt,Command:(dNt)=>gq=dNt,Option:(dNt)=>yq=dNt,Argument:(dNt)=>bq=dNt,Help:(dNt)=>wq=dNt,CommanderError:(dNt)=>_q=dNt,InvalidArgumentError:(dNt)=>xq=dNt,InvalidOptionArgumentError:(dNt)=>vq=dNt});He();var{Argument:lq}=W_(),{Command:bC}=cq(),{CommanderError:WAe,InvalidArgumentError:uq}=Dy(),{Help:KAe}=mC(),{Option:dq}=hC();var fq=new bC,pq=(e)=>new bC(e),mq=(e,t)=>new dq(e,t),hq=(e,t)=>new lq(e,t),gq=bC,yq=dq,bq=lq,wq=KAe,_q=WAe,xq=uq,vq=uq;var{program:pNt,createCommand:mNt,createArgument:hNt,createOption:gNt,CommanderError:yNt,InvalidArgumentError:Ms,InvalidOptionArgumentError:bNt,Command:de,Argument:wNt,Option:zp,Help:_Nt}=wC;var _C={dataset:["search","download","upload","validate","status","list"],admin:["users","approve","revoke","publish","pr-reviews","mail","doi","make-public","delete-dataset","notify","doctor"]};var xC=process.argv.includes("--help-all");if(process.argv.includes("--no-color"))u.level=0;var kq=process.argv.indexOf("--help-all");if(kq!==-1)process.argv[kq]="--help";var Ry=de.prototype.addHelpText,Eq=`
|
|
252
252
|
Run with --help-all for examples and detailed descriptions.
|
|
253
253
|
`,K_=new WeakSet;de.prototype.addHelpText=function(e,t){if(e==="after"||e==="afterAll"){if(xC)return Ry.call(this,e,t);if(!K_.has(this))return K_.add(this),Ry.call(this,e,Eq);return this}return Ry.call(this,e,t)};function JAe(e){let t=[];for(let n=e;n?.parent;n=n.parent)t.unshift(n.name());return t.join(" ")}function Qn(e){let t=[];for(let n=e;n;n=n.parent)t.unshift(n.name());return t.join(" ")}var YAe={formatHelp(e,t){let n=t.helpWidth??80,r=2,o=2,s=40,i=Math.max(8,n-2-2-40),a=(T)=>Math.min(i,T.reduce((z,A)=>Math.max(z,A.length),0));function c(T,z,A,F){if(!A)return z;let M=F+2;if(T.length>F){let O=t.wrap(A,n-2-4,0);return`${z}
|
|
254
254
|
${O.replace(/^/gm," ")}`}let U=" ".repeat(Math.max(0,M-T.length)),B=`${T}${U}${A}`,P=t.wrap(B,n-2,M);return z+P.slice(T.length)}function l(T){return T.join(`
|
|
255
255
|
`).replace(/^/gm," ".repeat(2))}let d=[];d.push(`Usage: ${t.commandUsage(e)}`,"");let f=t.commandDescription(e);if(f.length>0)d.push(t.wrap(f,n,0),"");let p=t.visibleArguments(e),m=a(p.map((T)=>t.argumentTerm(T))),h=p.map((T)=>{let z=t.argumentTerm(T);return c(z,u.blue(z),t.argumentDescription(T),m)});if(h.length>0)d.push(u.bold("Arguments:"),l(h),"");let g=t.visibleOptions(e),y=a(g.map((T)=>t.optionTerm(T))),b=g.map((T)=>{let z=t.optionTerm(T);return c(z,u.cyan(z),t.optionDescription(T),y)});if(b.length>0)d.push(u.bold("Options:"),l(b),"");let _=(T,z)=>T.name().localeCompare(z.name()),x=(T)=>{let z=a(T.map((A)=>t.subcommandTerm(A)));return T.map((A)=>{let F=t.subcommandTerm(A);return c(F,u.bold.cyan(F),t.subcommandDescription(A),z)})},k=t.visibleCommands(e),v=JAe(e),C=xC||!Object.hasOwn(_C,v)?void 0:_C[v];if(C){let T=new Map(k.map((M)=>[M.name(),M])),z=C.map((M)=>T.get(M)).filter((M)=>M!==void 0),A=new Set(z.map((M)=>M.name())),F=k.filter((M)=>!A.has(M.name())&&M.name()!=="help").sort(_);if(z.length===0)return d.push(u.bold("Commands:"),l(x([...k].sort(_))),""),d.join(`
|
|
256
256
|
`);if(d.push(u.bold("Commands:"),l(x(z)),""),F.length>0){let M=F.map((U)=>U.name()).join(", ");d.push(u.bold("More commands")+u.dim(" (--help-all for details):"),t.wrap(M,n-2,0).replace(/^/gm," "),"")}}else if(k.length>0)d.push(u.bold("Commands:"),l(x([...k].sort(_))),"");return d.join(`
|
|
257
|
-
`)}};function Sq(e){$q(e)}function $q(e){e.configureHelp(YAe);for(let t of e.commands)$q(t)}function vr(e,t){if(xC)Ry.call(e,"after",t);else if(!K_.has(e))K_.add(e),Ry.call(e,"after",Eq)}He();He();import{existsSync as h1,mkdirSync as R$e,mkdtempSync as uL,readFileSync as UAt,writeFileSync as E_}from"fs";import{tmpdir as dL}from"os";import{join as Ml}from"path";Ws();ro();function dQ(e,t){return Math.min(Math.floor(Math.log(e)/Math.log(1024)),t)}function Ut(e){if(e===0)return"0 B";let t=["B","KB","MB","GB","TB"],n=dQ(e,t.length-1);return`${(e/1024**n).toFixed(n===0?0:1)} ${t[n]}`}function fQ(e){if(e===0)return"0 B";let t=["B","KB","MB","GB","TB"],n=dQ(e,t.length-1);return`${Number.parseFloat((e/1024**n).toFixed(2))} ${t[n]}`}B0();nh();var lk=50;var gZ=["store","node","registration","drift"];function yZ(e){let{verification:t,writerMode:n,now:r}=e;if(t===null)return n==="enabled"?{verdict:"unknown",note:"none recorded: the daily verification sweep has not run, which is unknown and not healthy"}:{verdict:"unchecked",note:null};let o=Date.parse(t.at),s=r.getTime()-o;if(Number.isNaN(o)||s>129600000){let i=Number.isNaN(o)?null:Math.floor(s/3600000);return{verdict:"unknown",note:i===null?"the last record has no readable time, so it says nothing about today":`the last record is ${i} hours old, so it says nothing about today`}}return{verdict:t.overall,note:null}}function RT(e){return e==="alarm"?1:e==="unknown"?2:0}var jWe=["store","node","registration","drift"];function LWe(e){return jWe.filter((t)=>e.checkDays[t].unchecked>0)}function CT(e){let t=[];if(e.coverageStatus==="alarm")t.push("coverage is alarming");if(e.coverageStatus==="unknown")t.push("coverage could not be determined");if(e.autoImportEnabled===!1)t.push("auto-import is OFF");if(e.dispatchLost===!0)t.push("dispatches are not landing");if(e.issuesClosed===null)t.push("no daily sweep activity was recorded, so the daily jobs may not be running");let n=e.neurobagel??null,r=[];if(n===null)t.push("no Neurobagel verification run was recorded, so that job may not be running");else{if(r=LWe(n),n.latest.overall==="alarm")t.push("Neurobagel verification is alarming");if(n.latest.overall==="unknown")t.push("Neurobagel verification could not be determined");if(n.days.alarm>0&&n.latest.overall!=="alarm")t.push(`Neurobagel verification alarmed on ${n.days.alarm} day(s) this week`);if(n.days.unknown>0&&n.latest.overall!=="unknown")t.push(`Neurobagel verification could not be determined on ${n.days.unknown} day(s)`);if(n.failedRuns>0)t.push(`the Neurobagel sweep itself failed on ${n.failedRuns} run(s)`);let o=Math.max(0,7-n.runs);if(o>1)t.push(`the daily Neurobagel verification is missing for ${o} of 7 day(s)`)}if(e.neurobagelFindings===null||e.neurobagelFindings===void 0)t.push("Neurobagel findings could not be counted");else if(e.neurobagelFindings>0)t.push(`${e.neurobagelFindings} Neurobagel finding(s) need attention (see the audit log)`);if(e.upstream===null||e.upstream===void 0)t.push("upstream freshness could not be determined");if(e.repulls===null||e.repulls===void 0)t.push("upstream re-pull activity could not be determined");else t.push(...e.repulls.attention);if(e.errors.length>0)t.push(`${e.errors.length} part(s) of this report failed`);return{attention:t.length>0,problems:t,notChecked:r}}xa();He();var rh=2000,Yo=10,Xo=500,xu=/^(nm|on|xx)\d{6}$/;Ke();Ni();gr();dn();function I(e){return typeof e==="string"?e.replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu,""):""}function Oo(e,t){let n=I(e);return n.length>t?`${n.slice(0,t-1)}\u2026`:n}function Fb(e,t=Date.now()){let n=Date.parse(e);if(Number.isNaN(n))return"?";let r=Math.max(0,Math.floor((t-n)/1000));if(r<3600)return`${Math.floor(r/60)}m`;if(r<86400)return`${Math.floor(r/3600)}h`;return`${Math.floor(r/86400)}d`}var JI={owner_name_missing:"Run `nemar admin backfill-names --apply` if the owner's ORCID record publishes their name; an ORCID-linked owner must otherwise make it public on ORCID and sign in again, and an owner with no linked ORCID can now type it into Settings on nemar.org (ADR 0042)."};function Gn(e){return e?(t)=>console.error(t):(t)=>console.log(t)}function og(e){if(!(e instanceof L))return!1;if(e.statusCode>=400&&e.statusCode<500)return!0;let t=ng(e);return t!==void 0&&t!=="internal"}function KI(e,t,n,r){if(t)t.fail(e);else n(u.red(e));if(r)n(u.dim(` ${r}`))}function Bfe(e,t,n,r,o){if(e instanceof L){let i=(e.blockReason?JI[e.blockReason]:void 0)??r?.[e.statusCode]??(e.statusCode===403?"This command requires admin privileges":void 0);KI(I(e.message),t,o,i);return}KI(n,t,o,`Error details: ${I(G(e))}`)}function Ct(e,t,n,r){Bfe(e,t,n,r,Gn(!1))}function yr(e,t,n,r,o={}){if(Bfe(e,t,n,r,Gn(o.json)),process.exitCode=1,og(e))ce();else Ob()}function dt(e,t){if(KI(I(e),t.spinner,Gn(t.json),t.hint),process.exitCode=1,t.answered)ce();else Ob()}function Xa(e,t){if(xu.test(e))return e;return dt(`"${e}" is not a dataset id (like nm000108).`,{json:t,answered:!0}),null}function fpt(e){return/^[a-z]{2}\d{0,6}$/.test(e)}function ppt(e){return/^(nm|on|xx)0\d{5}$/.test(e)}function Ufe(e,t){if(fpt(e))return e;return dt(`"${e}" is not a dataset id prefix: use two lowercase letters, then up to six digits (like nm or nm0001).`,{json:t,answered:!0}),null}function Hfe(e,t){if(ppt(e))return e;return dt(`"${e}" is not a dataset id (like nm000312). --after takes the last id of the previous page.`,{json:t,answered:!0}),null}function mn(e){if(ze())return!0;let t=Gn(e);return t(u.red("Error: Not authenticated")),t(u.dim(" Run 'nemar auth login' first")),process.exitCode=1,ce(),!1}He();B0();He();function sg(e){return(t)=>{try{return e(t)}catch{return String(t)}}}var uo={id:sg(u.cyan),metric:sg(u.magenta),label:sg(u.bold),warn:sg(u.yellow),muted:sg(u.dim),match:sg(u.green)};var mpt=/[\u001b\u009b][\[\]()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-PR-TZcf-ntqry=><~]/g,hpt=/[\n\r\t]+/g,gpt=/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/g;function br(e){return e.replace(mpt,"").replace(hpt," ").replace(gpt,"").trim()}var ypt=/(<mark>[\s\S]*?<\/mark>)/g,bpt=/^<mark>([\s\S]*)<\/mark>$/,zfe=400;function Vfe(e){if(!e||typeof e!=="string")return null;try{let t=e.length>zfe?e.slice(0,zfe):e,n=br(t);if(!n)return null;return n.split(ypt).filter((r)=>r.length>0).map((r)=>{let o=r.match(bpt);return o?uo.match(o[1]):uo.muted(r)}).join("")}catch{return null}}function Gfe(e,t){if(!Number.isFinite(t)||t<=0)return e;if(e.length<=t)return e;let n=e.split(","),r=[],o=0;for(let i of n){let a=r.length===0?i.length:o+1+i.length;if(a>t)break;r.push(i),o=a}let s=n.length-r.length;if(r.length===0){let i=n[0],a=Math.max(0,t-1),c=a>0?`${i.slice(0,a)}\u2026`:"\u2026",l=n.length-1;return l>0?`${c} +${l}`:c}return s>0?`${r.join(",")} +${s}`:r.join(",")}function jf(e){return br(e??"")}function YI(e){let t=e.match_kind;return typeof t==="string"&&AQ.includes(t)?t:void 0}function XI(e){let t=e.filter((n)=>YI(n)==="exact");return t.length===1?t[0]:null}function QI(e){return e.length>0&&e.every((t)=>YI(t)==="fuzzy")}function ZI(e){return e.length===0||e.some((t)=>YI(t)!==void 0)}function Wfe(e){if(e.length===0)return{kind:"none"};let t=XI(e);if(t)return{kind:"one",user:t,match:"exact"};let n=QI(e)?"fuzzy":"partial";if(e.length===1)return{kind:"one",user:e[0],match:n};return{kind:"many",users:[...e],match:n}}var kS=[["givenName","given_name"],["familyName","family_name"],["affiliation","affiliation"],["city","city"],["country","country"],["username","username"],["github","github_username"],["email","email"],["orcid","orcid"]];var vS=[{option:"clearAffiliation",valueOption:"affiliation",field:"affiliation"},{option:"clearGithub",valueOption:"github",field:"github_username"}];function ud(e){return`--${e.replace(/[A-Z]/g,(t)=>`-${t.toLowerCase()}`)}`}function Kfe(e){let t={};for(let[n,r]of kS){let o=e[n];if(typeof o!=="string")continue;if((r==="github_username"?o.trim().replace(/^@/,""):o.trim())===""){let i=vS.find((a)=>a.valueOption===n);return{ok:!1,message:i?`${ud(n)} needs a value. To remove it, say so with ${ud(i.option)}.`:`${ud(n)} needs a value.`}}t[r]=o}for(let{option:n,valueOption:r,field:o}of vS){if(e[n]!==!0)continue;if(o in t)return{ok:!1,message:`Use either ${ud(r)} or ${ud(n)}, not both.`};t[o]=""}return{ok:!0,body:t}}function Jfe(e,t){let n=[];for(let[,r]of kS){let o=t[r];if(o===void 0)continue;let s=e[r]??null;if((s??"")===o){if(r==="orcid"&&!e.orcid_verified)n.push({field:r,from:`${o} (unverified)`,to:`${o} (verified, attested)`});continue}n.push({field:r,from:s,to:o})}return n}function Es(e,t="-"){let n=jf(e);return n!==""?n:t}function Mb(e){if(e===null)return u.dim("(none)");if(e==="")return u.dim("(cleared)");return Es(e,u.dim("(blank)"))}function Mf(e){if(!e)return"-";let t=new Date(e.includes("T")?e:`${e.replace(" ","T")}Z`);return Number.isNaN(t.getTime())?jf(e):t.toISOString().replace("T"," ").slice(0,16)}function eN(e){let t=(a)=>u.dim(`${a}:`.padEnd(15)),n=[e.given_name,e.family_name].filter(Boolean).join(" "),r=[e.city,e.country].filter(Boolean).join(", "),o=e.role||"member",s=e.service_access===void 0||e.service_access===null?"unknown":e.service_access?"upload":"browse",i=[];if(i.push(`${u.cyan(Es(e.username??e.email))}${u.dim(` [${jf(o)}] id ${e.id}`)}${e.username===null?u.dim(" (no username)"):""}`),i.push(` ${t("Name")}${Es(n)}`),i.push(` ${t("Email")}${Es(e.email)} ${e.email_verified?u.green("(verified)"):u.yellow("(unverified)")}`),i.push(` ${t("GitHub")}${e.github_username?`@${Es(e.github_username)}`:"-"}`),i.push(` ${t("ORCID")}${e.orcid?`${Es(e.orcid)} ${e.orcid_verified?u.green("(verified)"):u.yellow("(unverified)")}`:"-"}`),i.push(` ${t("Affiliation")}${Es(e.affiliation)}`),i.push(` ${t("Location")}${Es(r)}`),i.push(` ${t("Status")}${jf(e.status)}`),i.push(` ${t("Upload access")}${s}${e.service_access&&e.service_access_granted_at?u.dim(` (granted ${Mf(e.service_access_granted_at)}${e.service_access_granted_by?` by id ${e.service_access_granted_by}`:""})`):""}`),e.upload_access_requested_at)i.push(` ${t("Asked")}${Mf(e.upload_access_requested_at)} (upload access)`);if(i.push(` ${t("Kind")}${jf(e.account_kind)||"-"}`),i.push(` ${t("Signed up via")}${Es(e.signup_source)}`),i.push(` ${t("Created")}${Mf(e.created_at)}`),e.approved_at)i.push(` ${t("Approved")}${Mf(e.approved_at)}`);if(e.revoked_at)i.push(` ${t("Revoked")}${Mf(e.revoked_at)}`);if(i.push(` ${t("Last changed")}${Mf(e.updated_at)}`),i.push(` ${t("Datasets")}${e.dataset_count??"-"}${u.dim(" API keys: ")}${e.active_tokens??"-"}`),i.push(` ${t("Sign-in")}${e.linked_identities&&e.linked_identities.length>0?e.linked_identities.map((a)=>jf(a)).join(", "):"-"}`),e.description)i.push(` ${t("Description")}${Es(e.description)}`);if(e.identity_conflict)i.push(` ${u.yellow("! Flagged as a duplicate identity: see 'nemar admin duplicates'")}`);if(e.username_auto_assigned)i.push(` ${u.dim("The username was derived from the name, not chosen")}`);if(e.deleted_at)i.push(` ${u.red(`Deleted ${Mf(e.deleted_at)} (tombstoned)`)}`);return i}function tN(e){let t=[e.given_name,e.family_name].filter(Boolean).join(" "),n=e.matched_in&&e.matched_in.length>0?u.dim(` matched: ${e.matched_in.map((r)=>jf(r)).join(", ")}`):"";return` ${String(e.id).padStart(5)} ${u.cyan(Es(e.username,"(no username)"))} ${Es(t,"")} ${u.dim(Es(e.email))}${n}`}Qa();Za();ec();Ke();lo();var wN=["critical","warning","maintenance","announcement","tip"];async function Bme(){return q("/notices",{},"optional")}async function Ume(){return q("/admin/notices",{},!0)}async function Hme(e){return q("/admin/notices",{method:"POST",body:JSON.stringify(e)},!0)}async function zme(e){return q(`/admin/notices/${e}`,{method:"DELETE"},!0)}gr();Ws();async function De(e,t,n=!1){if(t.no)return"declined";if(t.yes)return"confirmed";if(!process.stdin.isTTY)return console.error("Interactive prompt unavailable; use --yes or --no"),"cancelled";try{let{confirmed:r}=await Ae.prompt([{type:"confirm",name:"confirmed",message:e,default:n}]);return r?"confirmed":"cancelled"}catch(r){let o=r instanceof Error?r.message:String(r);if(o.includes("closed")||o.includes("TTY")||o.includes("SIGINT")||o.includes("readline"))console.error("Interactive prompt unavailable (non-interactive terminal or interrupted)"),console.error(" Use --yes or --no flags for non-interactive mode");else console.error("Prompt error:",o);return"cancelled"}}async function Vme(e,t,n){if(n.no)return"declined";if(n.yes)return"confirmed";if(!process.stdin.isTTY)return console.error("Interactive prompt unavailable; use --yes or --no"),"cancelled";try{let{input:r}=await Ae.prompt([{type:"input",name:"input",message:e,validate:(o)=>{if(o!==t)return`Input does not match. Expected: ${t}`;return!0}}]);return r===t?"confirmed":"cancelled"}catch(r){let o=r instanceof Error?r.message:String(r);if(o.includes("closed")||o.includes("TTY")||o.includes("SIGINT")||o.includes("readline"))console.error("Interactive prompt unavailable (non-interactive terminal or interrupted)"),console.error(" Use --yes or --no flags for non-interactive mode");else console.error("Prompt error:",o);return"cancelled"}}var Je="-y, --yes",yt="-n, --no",nt="Skip confirmation and proceed",ht="Skip confirmation and decline";dn();var Gme="__Host-nemar_docs_session";nh();lo();Ke();async function _N(e){return q("/auth/login",{method:"POST",body:JSON.stringify({api_key:e})})}async function Wme(e){return q("/auth/resend-verification",{method:"POST",body:JSON.stringify({email:e})})}async function Kme(e){return q("/auth/request-key-regeneration",{method:"POST",body:JSON.stringify({email:e})})}async function Wr(){return(await q("/users/me",{},!0,EQ)).user}async function Jme(e){return q("/sandbox/complete",{method:"POST",body:JSON.stringify({dataset_id:e})},!0)}async function Yme(){return q("/sandbox/reset",{method:"POST"},!0)}async function TS(){return q("/sandbox/status",{},!0)}async function Xme(e){return q("/users/me/upload-access/request",{method:"POST",body:JSON.stringify({why:e})},!0)}async function Qme(e){return q("/auth/email/change/request",{method:"POST",body:JSON.stringify({email:e})},!0)}async function Zme(e,t){return q("/auth/email/change/verify",{method:"POST",body:JSON.stringify({email:e,code:t})},!0)}async function xN(e){return q("/auth/profile",{method:"PATCH",body:JSON.stringify(e)},!0)}async function ehe(e){return q("/auth/orcid/cli-start",{method:"POST",body:JSON.stringify({mode:e})},!0)}async function the(){return q("/auth/orcid/unlink",{method:"POST"},!0)}async function nhe(e){return q("/auth/device/start",{method:"POST",body:JSON.stringify({machine_name:e})},!1,XQ)}function wpt(e){return typeof e==="string"&&Xv.options.includes(e)}function _pt(e){if(typeof e!=="object"||e===null)return;let t=e.message;return typeof t==="string"?t:void 0}async function rhe(e,t){try{return{status:"success",data:await q("/auth/device/token",{method:"POST",body:JSON.stringify({device_code:e}),signal:t},!1,ZQ)}}catch(n){if(n instanceof L&&n.statusCode===400){let r=QQ.safeParse(n.rawBody);if(r.success){let o=r.data;if(o.error==="authorization_pending")return{status:"pending"};if(o.error==="slow_down")return{status:"slow_down"};return{status:"terminal",error:o.error,reason:o.reason,message:o.message}}if(wpt(n.code)&&n.code!=="authorization_pending"&&n.code!=="slow_down")return{status:"terminal",error:n.code,reason:void 0,message:_pt(n.rawBody)??JQ[n.code]}}throw n}}async function ohe(){return q("/auth/keys",{},!0,Qv)}async function she(e){return q("/auth/keys",{method:"POST",body:JSON.stringify({name:e})},!0,Zv)}async function ihe(){return q("/auth/docs/cli-session",{method:"POST"},!0)}async function PS(e){return q(`/auth/keys/${e}`,{method:"DELETE"},!0)}async function ahe(e,t){return q(`/auth/keys/${e}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`}},!1)}async function che(){return q("/auth/profile/username-suggestion",{},!0,$Q)}var xpt="https://docs.nemar.org";function IS(){return process.env.NEMAR_DOCS_URL||xpt}var lhe=20000;function vpt(e){let t=e.trim();if(/^https?:\/\//i.test(t)){let r=new URL(t),o=new URL(IS()).hostname;if(r.hostname.toLowerCase()!==o.toLowerCase())throw Error(`Not a ${o} URL: ${e}`);t=r.pathname}if(t=t.replace(/[?#].*$/,""),!t.startsWith("/"))t=`/${t}`;if(t.length>1&&t.endsWith("/"))t=t.slice(0,-1);if(t===""||t==="/")return"/index.md";return t.slice(t.lastIndexOf("/")+1).includes(".")?t:`${t}.md`}function kpt(e,t){if(e===302||e===301||e===307||e===308){if(t?.includes("/auth/docs/authorize"))return"the documentation session was refused (it may have expired mid-run); try again";return`redirected to ${t??"an unknown location"}`}if(e===404)return"not found, or it is a gated page and this account is not an admin";if(e===401)return"the documentation session was rejected; it may have expired, try again";if(e===403)return"this account is no longer an admin, so the documentation session was refused";if(e===503)return"the documentation gate could not reach the API; try again shortly";return`unexpected status ${e}`}async function uhe(e){let t=e.map((i)=>{try{return{input:i,path:vpt(i)}}catch(a){return{input:i,error:a.message}}});if(!t.some((i)=>i.path))return t.map((i)=>({path:i.input,ok:!1,error:i.error??"not a usable documentation path"}));let n=await ihe();if(typeof n?.session!=="string"||n.session.length===0)throw Error("The API returned no documentation session value.");let r=IS().replace(/\/$/,""),o=`${Gme}=${n.session}`,s=[];for(let i of t){if(!i.path){s.push({path:i.input,ok:!1,error:i.error??"unusable path"});continue}let a=i.path;try{let c=await fetch(`${r}${a}`,{redirect:"manual",signal:AbortSignal.timeout(lhe),headers:{Cookie:o,"User-Agent":"nemar-cli"}});if(c.status===200){s.push({path:a,ok:!0,body:await c.text()});continue}s.push({path:a,ok:!1,error:kpt(c.status,c.headers.get("Location"))})}catch(c){let l=c.name;s.push({path:a,ok:!1,error:l==="TimeoutError"?`no response within ${lhe/1000}s`:c.message})}}return s}NS();ii();rc();qt();var p$=et(f$(),1);function syt(e,t){let n=p$.default.coerce(e),r=p$.default.coerce(t);if(!n||!r)return!1;return p$.default.gte(n,r)}async function Iye(){try{let{stdout:t,exitCode:n,stderr:r}=await R(["git-annex","version"]);if(n!==0)return console.warn("git-annex version returned non-zero exit code:",n),console.warn("stderr:",r),{installed:!1,minVersion:"10.0",error:`Version check failed: ${r.trim()}`};let o=t.match(/version:\s*(\d+\.\d+)/),s=o?o[1]:void 0;if(!s)console.warn("Could not parse git-annex version from output:",t);return{installed:!0,version:s,minVersion:"10.0",compatible:s?syt(s,"10.0"):void 0}}catch(t){let n=t instanceof Error?t.message:String(t);if(n.includes("ENOENT")||n.includes("not found"))return console.info("git-annex not found in PATH"),{installed:!1,minVersion:"10.0"};return console.error("Error checking git-annex installation:",n),{installed:!1,minVersion:"10.0",error:n}}}async function iyt(){if(process.env.GH_TOKEN)return{accessible:!0,username:"token-auth",useHttps:!0};try{let{stdout:e,stderr:t}=await R(["ssh","-T","-o","BatchMode=yes","-o","StrictHostKeyChecking=accept-new","-o","ConnectTimeout=10","git@github.com"]),n=e+t,r=n.match(/Hi ([^!]+)!/);if(r)return{accessible:!0,username:r[1]};if(n.includes("Permission denied"))return{accessible:!1};return{accessible:n.includes("successfully authenticated")}}catch(e){let t=e instanceof Error?e.message:String(e);if(t.includes("ENOENT")||t.includes("not found"))console.info("SSH command not found");else console.error("Error checking GitHub SSH access:",t);return{accessible:!1}}}function Nye(){let e=process.platform;if(e==="darwin")return"brew install git-annex";if(e==="linux")return"apt install git-annex (Debian/Ubuntu)";return"See https://git-annex.branchable.com/install/"}async function m$(){let[e,t]=await Promise.all([Iye(),iyt()]),n=[];if(!e.installed)n.push(`git-annex is not installed. Install: ${Nye()}`);else if(e.compatible===!1)n.push(`git-annex version ${e.version} is too old. Required: >= ${e.minVersion}`);if(!t.accessible){if(!(await Bf()).token)n.push("GitHub authentication not configured. Run 'gh auth login' to authenticate.")}return{gitAnnex:e,githubSSH:t,allPassed:n.length===0,errors:n}}async function Xb(){let e=await Iye(),t=[];if(!e.installed)t.push(`git-annex is not installed. Install: ${Nye()}`);else if(e.compatible===!1)t.push(`git-annex version ${e.version} is too old. Required: >= ${e.minVersion}`);return{gitAnnex:e,allPassed:t.length===0,errors:t}}ug();import{readFileSync as ayt}from"fs";var cyt=/^on\d{6}$/;function lyt(e){if(!Array.isArray(e))throw Error("Recover-datasets file must be a JSON array");return e.map((t,n)=>{if(typeof t!=="object"||t===null)throw Error(`Recover-datasets entry ${n} is not an object`);let{dataset_id:r,note:o}=t;if(typeof r!=="string"||!cyt.test(r))throw Error(`Recover-datasets entry ${n}: dataset_id "${r}" is not valid`);if(typeof o!=="string"||o.length===0)throw Error(`Recover-datasets entry ${n} (${r}): note is required`);return{dataset_id:r,note:o}})}function XN(e){let t;try{t=JSON.parse(ayt(e,"utf-8"))}catch(n){throw Error(`Failed to read/parse recover-datasets file at ${e}: ${n instanceof Error?n.message:String(n)}`)}return lyt(t)}function Fye(e,t,n){let r=new Set(t.map((o)=>o.dataset_id));for(let o of e)if(!r.has(o)&&!n.force)return{error:`${o} is not on the checked-in recover-datasets list. Pass --force to override.`};return{targets:e}}function Mye(e,t){let n=new Set(e),r=new Map;for(let s of t)if(n.has(s.dataset_id)&&s.source_id)r.set(s.dataset_id,s.source_id);let o=e.filter((s)=>!r.has(s));return{sourceByTarget:r,missingSource:o}}import{readFileSync as uyt}from"fs";var jye=new Set(["upstream_403","no_source","recovered"]),dyt=/^(nm|xx|on)\d{6}$/;function fyt(e){if(!Array.isArray(e))throw Error("Withdrawn-datasets file must be a JSON array");return e.map((t,n)=>{if(typeof t!=="object"||t===null)throw Error(`Withdrawn-datasets entry ${n} is not an object`);let{dataset_id:r,reason:o,note:s,withdrawn:i,data_available:a,data_keys_missing:c,data_keys_total:l}=t;if(typeof r!=="string"||!dyt.test(r))throw Error(`Withdrawn-datasets entry ${n}: dataset_id "${r}" is not valid`);if(typeof o!=="string"||!jye.has(o))throw Error(`Withdrawn-datasets entry ${n} (${r}): reason "${o}" must be one of ${[...jye].join(", ")}`);if(typeof s!=="string"||s.length===0)throw Error(`Withdrawn-datasets entry ${n} (${r}): note is required`);if(i!==void 0&&typeof i!=="boolean")throw Error(`Withdrawn-datasets entry ${n} (${r}): withdrawn must be a boolean`);if(a!==void 0&&(typeof a!=="number"||a<0||a>1))throw Error(`Withdrawn-datasets entry ${n} (${r}): data_available must be between 0 and 1`);let d=i??!0;if(o==="recovered"&&d)throw Error(`Withdrawn-datasets entry ${n} (${r}): reason "recovered" means the content came back, so withdrawn must be false`);let f=typeof c==="number",p=typeof l==="number";if(f!==p)throw Error(`Withdrawn-datasets entry ${n} (${r}): data_keys_missing and data_keys_total must be given together`);if(f&&p){if(c<0||l<0)throw Error(`Withdrawn-datasets entry ${n} (${r}): key counts cannot be negative`);if(c>l)throw Error(`Withdrawn-datasets entry ${n} (${r}): ${c} missing of ${l} total is not possible`);if(typeof a==="number"&&l>0){let m=(l-c)/l;if(Math.abs(m-a)>0.001)throw Error(`Withdrawn-datasets entry ${n} (${r}): data_available ${a} disagrees with ${c} missing of ${l} (${m.toFixed(4)})`)}}return{dataset_id:r,reason:o,note:s,withdrawn:d,...typeof a==="number"?{data_available:a}:{},...f?{data_keys_missing:c}:{},...p?{data_keys_total:l}:{}}})}function QN(e){let t;try{t=JSON.parse(uyt(e,"utf-8"))}catch(n){throw Error(`Failed to read/parse withdrawn-datasets file at ${e}: ${n instanceof Error?n.message:String(n)}`)}return fyt(t)}function Lye(e,t,n){let r=new Map(t.map((s)=>[s.dataset_id,s])),o=[];for(let s of e){let i=r.get(s);if(!i&&!n.force)return{error:`${s} is not on the checked-in withdrawn-datasets list. Pass --force to override.`};if(i?.withdrawn===!1&&!n.force)return{error:`${s} was reinstated (${i.reason}); its entry is a record, not a target. Pass --force to withdraw it again.`};let a=n.reason||i?.reason;if(!a)return{error:`${s}: no --reason given and it has no default entry in the list.`};o.push({datasetId:s,reason:a})}return{targets:o}}function ZN(e){return e.filter((t)=>t.withdrawn!==!1)}import{readFileSync as pyt}from"fs";var eF=["open","pending","escalated","closed","spam"],Qb=["open","pending","closed","spam"],tF=["fixed","round_robin","pool"];var nF=["only","include"];var rF=["address","domain","none"];Qa();Ke();gr();dn();qf();function myt(e){let t=e.indexOf("--");return(t===-1?e:e.slice(0,t)).includes("--json")}class Cn extends de{createCommand(e){return new Cn(e)}error(e){let t=e.replace(/^error: /,"").trim();if(myt(process.argv))console.error(JSON.stringify({error:t,code:"usage"}));else console.error(`Error: ${ve(t)}`);Ao(),process.exit(Vye)}}var oF=1,Vye=2,hyt=3,gyt=4;class Lt extends Error{}var qye={bad_request:"The server rejected the request as malformed; check the arguments and try again.",not_found:"There is no such ticket, or it is not visible to you.",forbidden:"Your account is not permitted to do that (an owner-only action, or an account that is not active).",ineligible_assignee:"That person cannot take it: on a restricted queue everyone named must be an owner, on any other an admin or an owner.",ticket_is_spam:"The ticket is marked spam; reopen it with 'status <id> open' before changing it.",ticket_closed:"The ticket is closed; reopen it with 'status <id> open' before changing it.",already_escalated:"The ticket is already escalated; nothing more to do.",no_escalation_owner:"The queue has no escalation owner; an owner sets one with 'queues set <tag> --escalation <user>'.",escalation_owner_ineligible:"The queue's escalation owner cannot take this ticket; an owner should name another with 'queues set <tag> --escalation <user>'.",restricted_locked:"The ticket is in a restricted queue, which locks this change; ask an owner.",restricted_flag_busy:"The queue still has open tickets, so its restricted flag cannot change: close or move them first.",restriction_mismatch:"The ticket's restricted flag no longer matches its queue, so it cannot be reopened; ask an owner.",reply_in_progress:"A reply with this key is still being sent; wait a moment and retry with the same key.",fallback_not_restrictable:"The '*' fallback queue is never restricted.",reply_not_sent:"Nothing was sent and the key is released; retry with the same key if you still want to reply.",summary_has_address:"The summary contains an email address. Rewrite it without names, addresses, account ids or quoted message text: describe the request and the outcome.",ticket_purged:"The ticket was purged under the retention policy; only its summary remains and nothing can be changed.",reply_delivery_unknown:"The mail provider did not confirm the send, so the reply may or may not have reached the requester. This key will never send it again, so retrying it is pointless: read the thread with 'nemar admin mail show', and ask the requester if needed. Only a new --idempotency-key sends again, and it may deliver a second copy.",block_sender_unverified:"The sender was not verified (DMARC did not pass), so its address may be forged. A domain is never blocked for such a sender; to block the address anyway, repeat with --force.",block_not_allowed:"That sender cannot be blocked: our own domain is never blocked, nor the domain of a shared mailbox provider or a public suffix (block the address instead). Those lists are best effort and not exhaustive, so think before blocking any domain.",inbound_not_configured:"This deployment has no inbound mail bucket, so there is nothing to reprocess.",internal:"The mail routes failed unexpectedly; try again, and report it if it keeps happening."};function Gye(e){let t=e.rawBody;if(t&&typeof t==="object"&&"code"in t&&typeof t.code==="string")return t.code;return}function yyt(e){return e!==void 0&&Object.hasOwn(qye,e)?qye[e]:void 0}function Wye(e,t="reply"){if(t==="note")return e.statusCode===0||e.statusCode>=500||e.statusCode===408||e.statusCode===429;let n=Gye(e);if(n==="reply_delivery_unknown")return!1;return n==="reply_in_progress"||n==="reply_not_sent"||e.statusCode===0||e.statusCode>=500}function byt(e,t,n){return Wye(e,n)?`Retry with: --idempotency-key ${t} (the same key never ${n==="note"?"stores the note":"sends the reply"} twice)`:void 0}function wyt(e,t,n="reply"){if(e instanceof Lt)return{message:e.message,code:"usage",exit:Vye,answered:!0};if(e instanceof L){let r=Gye(e),o=r==="not_found"||e.statusCode===404,s=r==="forbidden"||e.statusCode===403,i=yyt(r),a=t?byt(e,t,n):void 0,c=[i,a].filter(Boolean).join(" ")||void 0;return{message:e.message,code:r??(e.statusCode===0?"network_error":`http_${e.statusCode}`),exit:o?hyt:s?gyt:oF,hint:c,retryWithKey:t!==void 0&&Wye(e,n),answered:e.statusCode>=400&&e.statusCode<500}}return{message:G(e),code:"error",exit:oF,answered:!1}}async function Ar(e,t,n,r="reply"){if(!ze()){Bye(e,{message:"Not authenticated. Run 'nemar auth login' first.",code:"not_authenticated",exit:oF,answered:!0});return}try{await t()}catch(o){Bye(e,wyt(o,n?.(),r),n?.())}}function Bye(e,t,n){if(e){let r={error:t.message,code:t.code};if(n&&(t.retryWithKey||t.code==="reply_delivery_unknown"))r.idempotency_key=n;console.error(JSON.stringify(r))}else if(console.error(`Error: ${ve(t.message)}`),t.hint)console.error(` ${t.hint}`);if(process.exitCode=t.exit,t.answered)ce();else Ob()}function ve(e){return qb(String(e??"")).replace(/\n/g,"\\n").replace(/\t/g,"\\t")}function Or(e){console.log(JSON.stringify(e,null,2))}function Uye(e,t=" "){return e.split(`
|
|
257
|
+
`)}};function Sq(e){$q(e)}function $q(e){e.configureHelp(YAe);for(let t of e.commands)$q(t)}function vr(e,t){if(xC)Ry.call(e,"after",t);else if(!K_.has(e))K_.add(e),Ry.call(e,"after",Eq)}He();He();import{existsSync as h1,mkdirSync as R$e,mkdtempSync as uL,readFileSync as UAt,writeFileSync as E_}from"fs";import{tmpdir as dL}from"os";import{join as Ml}from"path";Ws();ro();function dQ(e,t){return Math.min(Math.floor(Math.log(e)/Math.log(1024)),t)}function Ut(e){if(e===0)return"0 B";let t=["B","KB","MB","GB","TB"],n=dQ(e,t.length-1);return`${(e/1024**n).toFixed(n===0?0:1)} ${t[n]}`}function fQ(e){if(e===0)return"0 B";let t=["B","KB","MB","GB","TB"],n=dQ(e,t.length-1);return`${Number.parseFloat((e/1024**n).toFixed(2))} ${t[n]}`}B0();nh();var lk=50;var gZ=["store","node","registration","drift"];function yZ(e){let{verification:t,writerMode:n,now:r}=e;if(t===null)return n==="enabled"?{verdict:"unknown",note:"none recorded: the daily verification sweep has not run, which is unknown and not healthy"}:{verdict:"unchecked",note:null};let o=Date.parse(t.at),s=r.getTime()-o;if(Number.isNaN(o)||s>129600000){let i=Number.isNaN(o)?null:Math.floor(s/3600000);return{verdict:"unknown",note:i===null?"the last record has no readable time, so it says nothing about today":`the last record is ${i} hours old, so it says nothing about today`}}return{verdict:t.overall,note:null}}function RT(e){return e==="alarm"?1:e==="unknown"?2:0}var jWe=["store","node","registration","drift"];function LWe(e){return jWe.filter((t)=>e.checkDays[t].unchecked>0)}function CT(e){let t=[];if(e.coverageStatus==="alarm")t.push("coverage is alarming");if(e.coverageStatus==="unknown")t.push("coverage could not be determined");if(e.autoImportEnabled===!1)t.push("auto-import is OFF");if(e.dispatchLost===!0)t.push("dispatches are not landing");if(e.issuesClosed===null)t.push("no daily sweep activity was recorded, so the daily jobs may not be running");let n=e.neurobagel??null,r=[];if(n===null)t.push("no Neurobagel verification run was recorded, so that job may not be running");else{if(r=LWe(n),n.latest.overall==="alarm")t.push("Neurobagel verification is alarming");if(n.latest.overall==="unknown")t.push("Neurobagel verification could not be determined");if(n.days.alarm>0&&n.latest.overall!=="alarm")t.push(`Neurobagel verification alarmed on ${n.days.alarm} day(s) this week`);if(n.days.unknown>0&&n.latest.overall!=="unknown")t.push(`Neurobagel verification could not be determined on ${n.days.unknown} day(s)`);if(n.failedRuns>0)t.push(`the Neurobagel sweep itself failed on ${n.failedRuns} run(s)`);let o=Math.max(0,7-n.runs);if(o>1)t.push(`the daily Neurobagel verification is missing for ${o} of 7 day(s)`)}if(e.neurobagelFindings===null||e.neurobagelFindings===void 0)t.push("Neurobagel findings could not be counted");else if(e.neurobagelFindings>0)t.push(`${e.neurobagelFindings} Neurobagel finding(s) need attention (see the audit log)`);if(e.upstream===null||e.upstream===void 0)t.push("upstream freshness could not be determined");if(e.repulls===null||e.repulls===void 0)t.push("upstream re-pull activity could not be determined");else t.push(...e.repulls.attention);if(e.errors.length>0)t.push(`${e.errors.length} part(s) of this report failed`);return{attention:t.length>0,problems:t,notChecked:r}}xa();He();var rh=2000,Yo=10,Xo=500,xu=/^(nm|on|xx)\d{6}$/;Je();Ni();gr();dn();function I(e){return typeof e==="string"?e.replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu,""):""}function Oo(e,t){let n=I(e);return n.length>t?`${n.slice(0,t-1)}\u2026`:n}function Fb(e,t=Date.now()){let n=Date.parse(e);if(Number.isNaN(n))return"?";let r=Math.max(0,Math.floor((t-n)/1000));if(r<3600)return`${Math.floor(r/60)}m`;if(r<86400)return`${Math.floor(r/3600)}h`;return`${Math.floor(r/86400)}d`}var JI={owner_name_missing:"Run `nemar admin backfill-names --apply` if the owner's ORCID record publishes their name; an ORCID-linked owner must otherwise make it public on ORCID and sign in again, and an owner with no linked ORCID can now type it into Settings on nemar.org (ADR 0042)."};function Gn(e){return e?(t)=>console.error(t):(t)=>console.log(t)}function og(e){if(!(e instanceof L))return!1;if(e.statusCode>=400&&e.statusCode<500)return!0;let t=ng(e);return t!==void 0&&t!=="internal"}function KI(e,t,n,r){if(t)t.fail(e);else n(u.red(e));if(r)n(u.dim(` ${r}`))}function Bfe(e,t,n,r,o){if(e instanceof L){let i=(e.blockReason?JI[e.blockReason]:void 0)??r?.[e.statusCode]??(e.statusCode===403?"This command requires admin privileges":void 0);KI(I(e.message),t,o,i);return}KI(n,t,o,`Error details: ${I(G(e))}`)}function Ct(e,t,n,r){Bfe(e,t,n,r,Gn(!1))}function yr(e,t,n,r,o={}){if(Bfe(e,t,n,r,Gn(o.json)),process.exitCode=1,og(e))ce();else Ob()}function dt(e,t){if(KI(I(e),t.spinner,Gn(t.json),t.hint),process.exitCode=1,t.answered)ce();else Ob()}function Xa(e,t){if(xu.test(e))return e;return dt(`"${e}" is not a dataset id (like nm000108).`,{json:t,answered:!0}),null}function fpt(e){return/^[a-z]{2}\d{0,6}$/.test(e)}function ppt(e){return/^(nm|on|xx)0\d{5}$/.test(e)}function Ufe(e,t){if(fpt(e))return e;return dt(`"${e}" is not a dataset id prefix: use two lowercase letters, then up to six digits (like nm or nm0001).`,{json:t,answered:!0}),null}function Hfe(e,t){if(ppt(e))return e;return dt(`"${e}" is not a dataset id (like nm000312). --after takes the last id of the previous page.`,{json:t,answered:!0}),null}function mn(e){if(ze())return!0;let t=Gn(e);return t(u.red("Error: Not authenticated")),t(u.dim(" Run 'nemar auth login' first")),process.exitCode=1,ce(),!1}He();B0();He();function sg(e){return(t)=>{try{return e(t)}catch{return String(t)}}}var uo={id:sg(u.cyan),metric:sg(u.magenta),label:sg(u.bold),warn:sg(u.yellow),muted:sg(u.dim),match:sg(u.green)};var mpt=/[\u001b\u009b][\[\]()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-PR-TZcf-ntqry=><~]/g,hpt=/[\n\r\t]+/g,gpt=/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/g;function br(e){return e.replace(mpt,"").replace(hpt," ").replace(gpt,"").trim()}var ypt=/(<mark>[\s\S]*?<\/mark>)/g,bpt=/^<mark>([\s\S]*)<\/mark>$/,zfe=400;function Vfe(e){if(!e||typeof e!=="string")return null;try{let t=e.length>zfe?e.slice(0,zfe):e,n=br(t);if(!n)return null;return n.split(ypt).filter((r)=>r.length>0).map((r)=>{let o=r.match(bpt);return o?uo.match(o[1]):uo.muted(r)}).join("")}catch{return null}}function Gfe(e,t){if(!Number.isFinite(t)||t<=0)return e;if(e.length<=t)return e;let n=e.split(","),r=[],o=0;for(let i of n){let a=r.length===0?i.length:o+1+i.length;if(a>t)break;r.push(i),o=a}let s=n.length-r.length;if(r.length===0){let i=n[0],a=Math.max(0,t-1),c=a>0?`${i.slice(0,a)}\u2026`:"\u2026",l=n.length-1;return l>0?`${c} +${l}`:c}return s>0?`${r.join(",")} +${s}`:r.join(",")}function jf(e){return br(e??"")}function YI(e){let t=e.match_kind;return typeof t==="string"&&AQ.includes(t)?t:void 0}function XI(e){let t=e.filter((n)=>YI(n)==="exact");return t.length===1?t[0]:null}function QI(e){return e.length>0&&e.every((t)=>YI(t)==="fuzzy")}function ZI(e){return e.length===0||e.some((t)=>YI(t)!==void 0)}function Wfe(e){if(e.length===0)return{kind:"none"};let t=XI(e);if(t)return{kind:"one",user:t,match:"exact"};let n=QI(e)?"fuzzy":"partial";if(e.length===1)return{kind:"one",user:e[0],match:n};return{kind:"many",users:[...e],match:n}}var kS=[["givenName","given_name"],["familyName","family_name"],["affiliation","affiliation"],["city","city"],["country","country"],["username","username"],["github","github_username"],["email","email"],["orcid","orcid"]];var vS=[{option:"clearAffiliation",valueOption:"affiliation",field:"affiliation"},{option:"clearGithub",valueOption:"github",field:"github_username"}];function ud(e){return`--${e.replace(/[A-Z]/g,(t)=>`-${t.toLowerCase()}`)}`}function Kfe(e){let t={};for(let[n,r]of kS){let o=e[n];if(typeof o!=="string")continue;if((r==="github_username"?o.trim().replace(/^@/,""):o.trim())===""){let i=vS.find((a)=>a.valueOption===n);return{ok:!1,message:i?`${ud(n)} needs a value. To remove it, say so with ${ud(i.option)}.`:`${ud(n)} needs a value.`}}t[r]=o}for(let{option:n,valueOption:r,field:o}of vS){if(e[n]!==!0)continue;if(o in t)return{ok:!1,message:`Use either ${ud(r)} or ${ud(n)}, not both.`};t[o]=""}return{ok:!0,body:t}}function Jfe(e,t){let n=[];for(let[,r]of kS){let o=t[r];if(o===void 0)continue;let s=e[r]??null;if((s??"")===o){if(r==="orcid"&&!e.orcid_verified)n.push({field:r,from:`${o} (unverified)`,to:`${o} (verified, attested)`});continue}n.push({field:r,from:s,to:o})}return n}function Es(e,t="-"){let n=jf(e);return n!==""?n:t}function Mb(e){if(e===null)return u.dim("(none)");if(e==="")return u.dim("(cleared)");return Es(e,u.dim("(blank)"))}function Mf(e){if(!e)return"-";let t=new Date(e.includes("T")?e:`${e.replace(" ","T")}Z`);return Number.isNaN(t.getTime())?jf(e):t.toISOString().replace("T"," ").slice(0,16)}function eN(e){let t=(a)=>u.dim(`${a}:`.padEnd(15)),n=[e.given_name,e.family_name].filter(Boolean).join(" "),r=[e.city,e.country].filter(Boolean).join(", "),o=e.role||"member",s=e.service_access===void 0||e.service_access===null?"unknown":e.service_access?"upload":"browse",i=[];if(i.push(`${u.cyan(Es(e.username??e.email))}${u.dim(` [${jf(o)}] id ${e.id}`)}${e.username===null?u.dim(" (no username)"):""}`),i.push(` ${t("Name")}${Es(n)}`),i.push(` ${t("Email")}${Es(e.email)} ${e.email_verified?u.green("(verified)"):u.yellow("(unverified)")}`),i.push(` ${t("GitHub")}${e.github_username?`@${Es(e.github_username)}`:"-"}`),i.push(` ${t("ORCID")}${e.orcid?`${Es(e.orcid)} ${e.orcid_verified?u.green("(verified)"):u.yellow("(unverified)")}`:"-"}`),i.push(` ${t("Affiliation")}${Es(e.affiliation)}`),i.push(` ${t("Location")}${Es(r)}`),i.push(` ${t("Status")}${jf(e.status)}`),i.push(` ${t("Upload access")}${s}${e.service_access&&e.service_access_granted_at?u.dim(` (granted ${Mf(e.service_access_granted_at)}${e.service_access_granted_by?` by id ${e.service_access_granted_by}`:""})`):""}`),e.upload_access_requested_at)i.push(` ${t("Asked")}${Mf(e.upload_access_requested_at)} (upload access)`);if(i.push(` ${t("Kind")}${jf(e.account_kind)||"-"}`),i.push(` ${t("Signed up via")}${Es(e.signup_source)}`),i.push(` ${t("Created")}${Mf(e.created_at)}`),e.approved_at)i.push(` ${t("Approved")}${Mf(e.approved_at)}`);if(e.revoked_at)i.push(` ${t("Revoked")}${Mf(e.revoked_at)}`);if(i.push(` ${t("Last changed")}${Mf(e.updated_at)}`),i.push(` ${t("Datasets")}${e.dataset_count??"-"}${u.dim(" API keys: ")}${e.active_tokens??"-"}`),i.push(` ${t("Sign-in")}${e.linked_identities&&e.linked_identities.length>0?e.linked_identities.map((a)=>jf(a)).join(", "):"-"}`),e.description)i.push(` ${t("Description")}${Es(e.description)}`);if(e.identity_conflict)i.push(` ${u.yellow("! Flagged as a duplicate identity: see 'nemar admin duplicates'")}`);if(e.username_auto_assigned)i.push(` ${u.dim("The username was derived from the name, not chosen")}`);if(e.deleted_at)i.push(` ${u.red(`Deleted ${Mf(e.deleted_at)} (tombstoned)`)}`);return i}function tN(e){let t=[e.given_name,e.family_name].filter(Boolean).join(" "),n=e.matched_in&&e.matched_in.length>0?u.dim(` matched: ${e.matched_in.map((r)=>jf(r)).join(", ")}`):"";return` ${String(e.id).padStart(5)} ${u.cyan(Es(e.username,"(no username)"))} ${Es(t,"")} ${u.dim(Es(e.email))}${n}`}Qa();Za();ec();Je();lo();var wN=["critical","warning","maintenance","announcement","tip"];async function Bme(){return q("/notices",{},"optional")}async function Ume(){return q("/admin/notices",{},!0)}async function Hme(e){return q("/admin/notices",{method:"POST",body:JSON.stringify(e)},!0)}async function zme(e){return q(`/admin/notices/${e}`,{method:"DELETE"},!0)}gr();Ws();async function De(e,t,n=!1){if(t.no)return"declined";if(t.yes)return"confirmed";if(!process.stdin.isTTY)return console.error("Interactive prompt unavailable; use --yes or --no"),"cancelled";try{let{confirmed:r}=await Ae.prompt([{type:"confirm",name:"confirmed",message:e,default:n}]);return r?"confirmed":"cancelled"}catch(r){let o=r instanceof Error?r.message:String(r);if(o.includes("closed")||o.includes("TTY")||o.includes("SIGINT")||o.includes("readline"))console.error("Interactive prompt unavailable (non-interactive terminal or interrupted)"),console.error(" Use --yes or --no flags for non-interactive mode");else console.error("Prompt error:",o);return"cancelled"}}async function Vme(e,t,n){if(n.no)return"declined";if(n.yes)return"confirmed";if(!process.stdin.isTTY)return console.error("Interactive prompt unavailable; use --yes or --no"),"cancelled";try{let{input:r}=await Ae.prompt([{type:"input",name:"input",message:e,validate:(o)=>{if(o!==t)return`Input does not match. Expected: ${t}`;return!0}}]);return r===t?"confirmed":"cancelled"}catch(r){let o=r instanceof Error?r.message:String(r);if(o.includes("closed")||o.includes("TTY")||o.includes("SIGINT")||o.includes("readline"))console.error("Interactive prompt unavailable (non-interactive terminal or interrupted)"),console.error(" Use --yes or --no flags for non-interactive mode");else console.error("Prompt error:",o);return"cancelled"}}var Ye="-y, --yes",yt="-n, --no",nt="Skip confirmation and proceed",ht="Skip confirmation and decline";dn();var Gme="__Host-nemar_docs_session";nh();lo();Je();async function _N(e){return q("/auth/login",{method:"POST",body:JSON.stringify({api_key:e})})}async function Wme(e){return q("/auth/resend-verification",{method:"POST",body:JSON.stringify({email:e})})}async function Kme(e){return q("/auth/request-key-regeneration",{method:"POST",body:JSON.stringify({email:e})})}async function Wr(){return(await q("/users/me",{},!0,EQ)).user}async function Jme(e){return q("/sandbox/complete",{method:"POST",body:JSON.stringify({dataset_id:e})},!0)}async function Yme(){return q("/sandbox/reset",{method:"POST"},!0)}async function TS(){return q("/sandbox/status",{},!0)}async function Xme(e){return q("/users/me/upload-access/request",{method:"POST",body:JSON.stringify({why:e})},!0)}async function Qme(e){return q("/auth/email/change/request",{method:"POST",body:JSON.stringify({email:e})},!0)}async function Zme(e,t){return q("/auth/email/change/verify",{method:"POST",body:JSON.stringify({email:e,code:t})},!0)}async function xN(e){return q("/auth/profile",{method:"PATCH",body:JSON.stringify(e)},!0)}async function ehe(e){return q("/auth/orcid/cli-start",{method:"POST",body:JSON.stringify({mode:e})},!0)}async function the(){return q("/auth/orcid/unlink",{method:"POST"},!0)}async function nhe(e){return q("/auth/device/start",{method:"POST",body:JSON.stringify({machine_name:e})},!1,XQ)}function wpt(e){return typeof e==="string"&&Xv.options.includes(e)}function _pt(e){if(typeof e!=="object"||e===null)return;let t=e.message;return typeof t==="string"?t:void 0}async function rhe(e,t){try{return{status:"success",data:await q("/auth/device/token",{method:"POST",body:JSON.stringify({device_code:e}),signal:t},!1,ZQ)}}catch(n){if(n instanceof L&&n.statusCode===400){let r=QQ.safeParse(n.rawBody);if(r.success){let o=r.data;if(o.error==="authorization_pending")return{status:"pending"};if(o.error==="slow_down")return{status:"slow_down"};return{status:"terminal",error:o.error,reason:o.reason,message:o.message}}if(wpt(n.code)&&n.code!=="authorization_pending"&&n.code!=="slow_down")return{status:"terminal",error:n.code,reason:void 0,message:_pt(n.rawBody)??JQ[n.code]}}throw n}}async function ohe(){return q("/auth/keys",{},!0,Qv)}async function she(e){return q("/auth/keys",{method:"POST",body:JSON.stringify({name:e})},!0,Zv)}async function ihe(){return q("/auth/docs/cli-session",{method:"POST"},!0)}async function PS(e){return q(`/auth/keys/${e}`,{method:"DELETE"},!0)}async function ahe(e,t){return q(`/auth/keys/${e}`,{method:"DELETE",headers:{Authorization:`Bearer ${t}`}},!1)}async function che(){return q("/auth/profile/username-suggestion",{},!0,$Q)}var xpt="https://docs.nemar.org";function IS(){return process.env.NEMAR_DOCS_URL||xpt}var lhe=20000;function vpt(e){let t=e.trim();if(/^https?:\/\//i.test(t)){let r=new URL(t),o=new URL(IS()).hostname;if(r.hostname.toLowerCase()!==o.toLowerCase())throw Error(`Not a ${o} URL: ${e}`);t=r.pathname}if(t=t.replace(/[?#].*$/,""),!t.startsWith("/"))t=`/${t}`;if(t.length>1&&t.endsWith("/"))t=t.slice(0,-1);if(t===""||t==="/")return"/index.md";return t.slice(t.lastIndexOf("/")+1).includes(".")?t:`${t}.md`}function kpt(e,t){if(e===302||e===301||e===307||e===308){if(t?.includes("/auth/docs/authorize"))return"the documentation session was refused (it may have expired mid-run); try again";return`redirected to ${t??"an unknown location"}`}if(e===404)return"not found, or it is a gated page and this account is not an admin";if(e===401)return"the documentation session was rejected; it may have expired, try again";if(e===403)return"this account is no longer an admin, so the documentation session was refused";if(e===503)return"the documentation gate could not reach the API; try again shortly";return`unexpected status ${e}`}async function uhe(e){let t=e.map((i)=>{try{return{input:i,path:vpt(i)}}catch(a){return{input:i,error:a.message}}});if(!t.some((i)=>i.path))return t.map((i)=>({path:i.input,ok:!1,error:i.error??"not a usable documentation path"}));let n=await ihe();if(typeof n?.session!=="string"||n.session.length===0)throw Error("The API returned no documentation session value.");let r=IS().replace(/\/$/,""),o=`${Gme}=${n.session}`,s=[];for(let i of t){if(!i.path){s.push({path:i.input,ok:!1,error:i.error??"unusable path"});continue}let a=i.path;try{let c=await fetch(`${r}${a}`,{redirect:"manual",signal:AbortSignal.timeout(lhe),headers:{Cookie:o,"User-Agent":"nemar-cli"}});if(c.status===200){s.push({path:a,ok:!0,body:await c.text()});continue}s.push({path:a,ok:!1,error:kpt(c.status,c.headers.get("Location"))})}catch(c){let l=c.name;s.push({path:a,ok:!1,error:l==="TimeoutError"?`no response within ${lhe/1000}s`:c.message})}}return s}NS();ii();rc();qt();var p$=et(f$(),1);function syt(e,t){let n=p$.default.coerce(e),r=p$.default.coerce(t);if(!n||!r)return!1;return p$.default.gte(n,r)}async function Iye(){try{let{stdout:t,exitCode:n,stderr:r}=await R(["git-annex","version"]);if(n!==0)return console.warn("git-annex version returned non-zero exit code:",n),console.warn("stderr:",r),{installed:!1,minVersion:"10.0",error:`Version check failed: ${r.trim()}`};let o=t.match(/version:\s*(\d+\.\d+)/),s=o?o[1]:void 0;if(!s)console.warn("Could not parse git-annex version from output:",t);return{installed:!0,version:s,minVersion:"10.0",compatible:s?syt(s,"10.0"):void 0}}catch(t){let n=t instanceof Error?t.message:String(t);if(n.includes("ENOENT")||n.includes("not found"))return console.info("git-annex not found in PATH"),{installed:!1,minVersion:"10.0"};return console.error("Error checking git-annex installation:",n),{installed:!1,minVersion:"10.0",error:n}}}async function iyt(){if(process.env.GH_TOKEN)return{accessible:!0,username:"token-auth",useHttps:!0};try{let{stdout:e,stderr:t}=await R(["ssh","-T","-o","BatchMode=yes","-o","StrictHostKeyChecking=accept-new","-o","ConnectTimeout=10","git@github.com"]),n=e+t,r=n.match(/Hi ([^!]+)!/);if(r)return{accessible:!0,username:r[1]};if(n.includes("Permission denied"))return{accessible:!1};return{accessible:n.includes("successfully authenticated")}}catch(e){let t=e instanceof Error?e.message:String(e);if(t.includes("ENOENT")||t.includes("not found"))console.info("SSH command not found");else console.error("Error checking GitHub SSH access:",t);return{accessible:!1}}}function Nye(){let e=process.platform;if(e==="darwin")return"brew install git-annex";if(e==="linux")return"apt install git-annex (Debian/Ubuntu)";return"See https://git-annex.branchable.com/install/"}async function m$(){let[e,t]=await Promise.all([Iye(),iyt()]),n=[];if(!e.installed)n.push(`git-annex is not installed. Install: ${Nye()}`);else if(e.compatible===!1)n.push(`git-annex version ${e.version} is too old. Required: >= ${e.minVersion}`);if(!t.accessible){if(!(await Bf()).token)n.push("GitHub authentication not configured. Run 'gh auth login' to authenticate.")}return{gitAnnex:e,githubSSH:t,allPassed:n.length===0,errors:n}}async function Xb(){let e=await Iye(),t=[];if(!e.installed)t.push(`git-annex is not installed. Install: ${Nye()}`);else if(e.compatible===!1)t.push(`git-annex version ${e.version} is too old. Required: >= ${e.minVersion}`);return{gitAnnex:e,allPassed:t.length===0,errors:t}}ug();import{readFileSync as ayt}from"fs";var cyt=/^on\d{6}$/;function lyt(e){if(!Array.isArray(e))throw Error("Recover-datasets file must be a JSON array");return e.map((t,n)=>{if(typeof t!=="object"||t===null)throw Error(`Recover-datasets entry ${n} is not an object`);let{dataset_id:r,note:o}=t;if(typeof r!=="string"||!cyt.test(r))throw Error(`Recover-datasets entry ${n}: dataset_id "${r}" is not valid`);if(typeof o!=="string"||o.length===0)throw Error(`Recover-datasets entry ${n} (${r}): note is required`);return{dataset_id:r,note:o}})}function XN(e){let t;try{t=JSON.parse(ayt(e,"utf-8"))}catch(n){throw Error(`Failed to read/parse recover-datasets file at ${e}: ${n instanceof Error?n.message:String(n)}`)}return lyt(t)}function Fye(e,t,n){let r=new Set(t.map((o)=>o.dataset_id));for(let o of e)if(!r.has(o)&&!n.force)return{error:`${o} is not on the checked-in recover-datasets list. Pass --force to override.`};return{targets:e}}function Mye(e,t){let n=new Set(e),r=new Map;for(let s of t)if(n.has(s.dataset_id)&&s.source_id)r.set(s.dataset_id,s.source_id);let o=e.filter((s)=>!r.has(s));return{sourceByTarget:r,missingSource:o}}import{readFileSync as uyt}from"fs";var jye=new Set(["upstream_403","no_source","recovered"]),dyt=/^(nm|xx|on)\d{6}$/;function fyt(e){if(!Array.isArray(e))throw Error("Withdrawn-datasets file must be a JSON array");return e.map((t,n)=>{if(typeof t!=="object"||t===null)throw Error(`Withdrawn-datasets entry ${n} is not an object`);let{dataset_id:r,reason:o,note:s,withdrawn:i,data_available:a,data_keys_missing:c,data_keys_total:l}=t;if(typeof r!=="string"||!dyt.test(r))throw Error(`Withdrawn-datasets entry ${n}: dataset_id "${r}" is not valid`);if(typeof o!=="string"||!jye.has(o))throw Error(`Withdrawn-datasets entry ${n} (${r}): reason "${o}" must be one of ${[...jye].join(", ")}`);if(typeof s!=="string"||s.length===0)throw Error(`Withdrawn-datasets entry ${n} (${r}): note is required`);if(i!==void 0&&typeof i!=="boolean")throw Error(`Withdrawn-datasets entry ${n} (${r}): withdrawn must be a boolean`);if(a!==void 0&&(typeof a!=="number"||a<0||a>1))throw Error(`Withdrawn-datasets entry ${n} (${r}): data_available must be between 0 and 1`);let d=i??!0;if(o==="recovered"&&d)throw Error(`Withdrawn-datasets entry ${n} (${r}): reason "recovered" means the content came back, so withdrawn must be false`);let f=typeof c==="number",p=typeof l==="number";if(f!==p)throw Error(`Withdrawn-datasets entry ${n} (${r}): data_keys_missing and data_keys_total must be given together`);if(f&&p){if(c<0||l<0)throw Error(`Withdrawn-datasets entry ${n} (${r}): key counts cannot be negative`);if(c>l)throw Error(`Withdrawn-datasets entry ${n} (${r}): ${c} missing of ${l} total is not possible`);if(typeof a==="number"&&l>0){let m=(l-c)/l;if(Math.abs(m-a)>0.001)throw Error(`Withdrawn-datasets entry ${n} (${r}): data_available ${a} disagrees with ${c} missing of ${l} (${m.toFixed(4)})`)}}return{dataset_id:r,reason:o,note:s,withdrawn:d,...typeof a==="number"?{data_available:a}:{},...f?{data_keys_missing:c}:{},...p?{data_keys_total:l}:{}}})}function QN(e){let t;try{t=JSON.parse(uyt(e,"utf-8"))}catch(n){throw Error(`Failed to read/parse withdrawn-datasets file at ${e}: ${n instanceof Error?n.message:String(n)}`)}return fyt(t)}function Lye(e,t,n){let r=new Map(t.map((s)=>[s.dataset_id,s])),o=[];for(let s of e){let i=r.get(s);if(!i&&!n.force)return{error:`${s} is not on the checked-in withdrawn-datasets list. Pass --force to override.`};if(i?.withdrawn===!1&&!n.force)return{error:`${s} was reinstated (${i.reason}); its entry is a record, not a target. Pass --force to withdraw it again.`};let a=n.reason||i?.reason;if(!a)return{error:`${s}: no --reason given and it has no default entry in the list.`};o.push({datasetId:s,reason:a})}return{targets:o}}function ZN(e){return e.filter((t)=>t.withdrawn!==!1)}import{readFileSync as pyt}from"fs";var eF=["open","pending","escalated","closed","spam"],Qb=["open","pending","closed","spam"],tF=["fixed","round_robin","pool"];var nF=["only","include"];var rF=["address","domain","none"];Qa();Je();gr();dn();qf();function myt(e){let t=e.indexOf("--");return(t===-1?e:e.slice(0,t)).includes("--json")}class Cn extends de{createCommand(e){return new Cn(e)}error(e){let t=e.replace(/^error: /,"").trim();if(myt(process.argv))console.error(JSON.stringify({error:t,code:"usage"}));else console.error(`Error: ${ve(t)}`);Ao(),process.exit(Vye)}}var oF=1,Vye=2,hyt=3,gyt=4;class Lt extends Error{}var qye={bad_request:"The server rejected the request as malformed; check the arguments and try again.",not_found:"There is no such ticket, or it is not visible to you.",forbidden:"Your account is not permitted to do that (an owner-only action, or an account that is not active).",ineligible_assignee:"That person cannot take it: on a restricted queue everyone named must be an owner, on any other an admin or an owner.",ticket_is_spam:"The ticket is marked spam; reopen it with 'status <id> open' before changing it.",ticket_closed:"The ticket is closed; reopen it with 'status <id> open' before changing it.",already_escalated:"The ticket is already escalated; nothing more to do.",no_escalation_owner:"The queue has no escalation owner; an owner sets one with 'queues set <tag> --escalation <user>'.",escalation_owner_ineligible:"The queue's escalation owner cannot take this ticket; an owner should name another with 'queues set <tag> --escalation <user>'.",restricted_locked:"The ticket is in a restricted queue, which locks this change; ask an owner.",restricted_flag_busy:"The queue still has open tickets, so its restricted flag cannot change: close or move them first.",restriction_mismatch:"The ticket's restricted flag no longer matches its queue, so it cannot be reopened; ask an owner.",reply_in_progress:"A reply with this key is still being sent; wait a moment and retry with the same key.",fallback_not_restrictable:"The '*' fallback queue is never restricted.",reply_not_sent:"Nothing was sent and the key is released; retry with the same key if you still want to reply.",summary_has_address:"The summary contains an email address. Rewrite it without names, addresses, account ids or quoted message text: describe the request and the outcome.",ticket_purged:"The ticket was purged under the retention policy; only its summary remains and nothing can be changed.",reply_delivery_unknown:"The mail provider did not confirm the send, so the reply may or may not have reached the requester. This key will never send it again, so retrying it is pointless: read the thread with 'nemar admin mail show', and ask the requester if needed. Only a new --idempotency-key sends again, and it may deliver a second copy.",block_sender_unverified:"The sender was not verified (DMARC did not pass), so its address may be forged. A domain is never blocked for such a sender; to block the address anyway, repeat with --force.",block_not_allowed:"That sender cannot be blocked: our own domain is never blocked, nor the domain of a shared mailbox provider or a public suffix (block the address instead). Those lists are best effort and not exhaustive, so think before blocking any domain.",inbound_not_configured:"This deployment has no inbound mail bucket, so there is nothing to reprocess.",internal:"The mail routes failed unexpectedly; try again, and report it if it keeps happening."};function Gye(e){let t=e.rawBody;if(t&&typeof t==="object"&&"code"in t&&typeof t.code==="string")return t.code;return}function yyt(e){return e!==void 0&&Object.hasOwn(qye,e)?qye[e]:void 0}function Wye(e,t="reply"){if(t==="note")return e.statusCode===0||e.statusCode>=500||e.statusCode===408||e.statusCode===429;let n=Gye(e);if(n==="reply_delivery_unknown")return!1;return n==="reply_in_progress"||n==="reply_not_sent"||e.statusCode===0||e.statusCode>=500}function byt(e,t,n){return Wye(e,n)?`Retry with: --idempotency-key ${t} (the same key never ${n==="note"?"stores the note":"sends the reply"} twice)`:void 0}function wyt(e,t,n="reply"){if(e instanceof Lt)return{message:e.message,code:"usage",exit:Vye,answered:!0};if(e instanceof L){let r=Gye(e),o=r==="not_found"||e.statusCode===404,s=r==="forbidden"||e.statusCode===403,i=yyt(r),a=t?byt(e,t,n):void 0,c=[i,a].filter(Boolean).join(" ")||void 0;return{message:e.message,code:r??(e.statusCode===0?"network_error":`http_${e.statusCode}`),exit:o?hyt:s?gyt:oF,hint:c,retryWithKey:t!==void 0&&Wye(e,n),answered:e.statusCode>=400&&e.statusCode<500}}return{message:G(e),code:"error",exit:oF,answered:!1}}async function Ar(e,t,n,r="reply"){if(!ze()){Bye(e,{message:"Not authenticated. Run 'nemar auth login' first.",code:"not_authenticated",exit:oF,answered:!0});return}try{await t()}catch(o){Bye(e,wyt(o,n?.(),r),n?.())}}function Bye(e,t,n){if(e){let r={error:t.message,code:t.code};if(n&&(t.retryWithKey||t.code==="reply_delivery_unknown"))r.idempotency_key=n;console.error(JSON.stringify(r))}else if(console.error(`Error: ${ve(t.message)}`),t.hint)console.error(` ${t.hint}`);if(process.exitCode=t.exit,t.answered)ce();else Ob()}function ve(e){return qb(String(e??"")).replace(/\n/g,"\\n").replace(/\t/g,"\\t")}function Or(e){console.log(JSON.stringify(e,null,2))}function Uye(e,t=" "){return e.split(`
|
|
258
258
|
`).map((n)=>n===""?n:`${t}${n}`).join(`
|
|
259
259
|
`)}function _yt(e,t){return e.length>=t?e:e+" ".repeat(t-e.length)}var xyt=/^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/;class li{names=new Map;ids=new Map;me;async resolve(e,t,n=!1){if(e==="none"){if(n)return null;throw new Lt(`${t} cannot be 'none' here.`)}if(e==="me")return this.whoAmI();let r=e.startsWith("@");if(!r&&/^\d{1,12}$/.test(e))return Number(e);let o=r?e.slice(1):e;if(!xyt.test(o))throw new Lt(`${t}: '${ve(e)}' is not me${n?", none":""}, a user id, a username or @username.`);let s=this.ids.get(o);if(s!==void 0)return s;let{user:i}=await $S(o);if(typeof i.id!=="number")throw new L(500,`The user lookup for '${ve(e)}' did not return an id.`);if(this.ids.set(o,i.id),i.username)this.names.set(i.id,Promise.resolve(i.username));return i.id}async whoAmI(){if(this.me===void 0){let e=await Wr();if(this.me=e.id,e.username)this.names.set(e.id,Promise.resolve(e.username))}return this.me}async name(e){if(e===null||e===void 0)return"-";let t=this.names.get(e);if(!t)t=kme(e).then((n)=>n||`#${e}`,(n)=>{if(n instanceof L&&n.statusCode===404)return`#${e}`;throw n}),this.names.set(e,t);return ve(await t)}async list(e){let t=await Promise.all(e.map((n)=>this.name(n)));return t.length>0?t.join(", "):"-"}}function vyt(e,t){return`#${e.id} ${ve(e.ref)} ${ve(e.status)}${e.purged?" (purged)":""}${e.filtered?` (filtered: ${ve(e.filtered)})`:""} ${ve(e.queue_tag)}${e.restricted?" (restricted)":""} assignee ${t} ${ve(e.subject)}`}async function h$(e,t,n){console.log(`${e}: ${vyt(t,await n.name(t.assignee_user_id))}`)}async function kyt(e,t){if(e.length===0){console.log("No tickets.");return}let n=[];for(let i of e)n.push([i.unread?"new":"",`#${i.id}`,ve(i.ref),`${ve(i.status)}${i.purged?" (purged)":""}${i.filtered?` [${ve(i.filtered)}]`:""}`,`${ve(i.queue_tag)}${i.restricted?"*":""}`,await t.name(i.assignee_user_id),ve(i.last_message_at),ve(i.requester_email),ve(i.subject)]);let r=["NEW","ID","REF","STATUS","QUEUE","ASSIGNEE","LAST MESSAGE","FROM","SUBJECT"],o=r.map((i,a)=>Math.max(i.length,...n.map((c)=>c[a].length))),s=(i)=>i.map((a,c)=>c===i.length-1?a:_yt(a,o[c])).join(" ").trimEnd();console.log(s(r));for(let i of n)console.log(s(i));console.log(`
|
|
260
260
|
* restricted queue`)}async function Eyt(e,t){let n=[],r=e.ticket;if(n.push(`Ticket #${r.id} ${ve(r.ref)}`),n.push(`Subject: ${ve(r.subject)}`),n.push(`Status: ${ve(r.status)}`),r.filtered)n.push(`Filtered: ${ve(r.filtered)} (filed quietly: not assigned, nobody was told)`);n.push(`Queue: ${ve(r.queue_tag)}${r.restricted?" (restricted)":""}`),n.push(`Assignee: ${await t.name(r.assignee_user_id)}`);let o=r.requester_user_id===null?ve(r.requester_email):`${ve(r.requester_email)} (account ${await t.name(r.requester_user_id)})`;if(n.push(`Requester: ${o}`),n.push(`Tags: ${e.tags.length>0?e.tags.map(ve).join(", "):"-"}`),n.push(`Created: ${ve(r.created_at)}`),n.push(`Updated: ${ve(r.updated_at)}`),e.purged_at)n.push(`Purged on: ${ve(e.purged_at)} (retention: only the summary is kept)`);if(e.summary!==null&&e.summary!==void 0){let a=await t.name(e.summary_author_user_id);n.push(`
|
|
@@ -336,10 +336,10 @@ ${p.join(`
|
|
|
336
336
|
`)}`:"No findings.",E0t(t.evidence),Vf,n==="uncertain"?`${hg(Gf)} needs to look at this pull request.`:"",R0t(t)].filter((h)=>h!=="").join(`
|
|
337
337
|
|
|
338
338
|
`);return{title:l,summary:d.join(`
|
|
339
|
-
`),text:m}}Qa();
|
|
339
|
+
`),text:m}}Qa();Je();dn();import{spawn as C0t}from"child_process";function A0t(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 gg(e){if(process.env.NEMAR_NO_BROWSER==="1")return!1;let t=A0t(process.platform,e);if(!t)return!1;try{let n=C0t(t.command,t.args,{stdio:"ignore",detached:!0});return n.on("error",(r)=>{Dn(`openInBrowser: ${t.command} failed: ${r instanceof Error?r.message:r}`)}),n.unref(),!0}catch(n){return Dn(`openInBrowser: could not spawn ${t.command}: ${n instanceof Error?n.message:n}`),!1}}gr();dn();qt();var Ss="nemarDatasets",yg=20000,c0e=15000;function _$(e,t){return`https://github.com/${Ss}/${e}/pull/${t}`}function u0e(e,t){return`gh pr review ${t} --repo ${Ss}/${e} --approve`}function kn(e=process.env){let t=e.NEMAR_GITHUB_API_URL?.trim();if(!t)return"https://api.github.com";try{let n=new URL(t),r=["127.0.0.1","localhost","[::1]"].includes(n.hostname);if(n.protocol==="http:"&&r)return t.replace(/\/+$/,"")}catch{}throw Error("NEMAR_GITHUB_API_URL is set but is not an http://127.0.0.1, http://localhost or http://[::1] address. It is only for tests, so it is refused rather than ignored; unset it to use GitHub.")}async function ui(e=process.env,t=R){let n=e.GH_TOKEN?.trim();if(n)return{ok:!0,token:n,source:"GH_TOKEN"};try{let{stdout:r,exitCode:o,stderr:s,timedOut:i}=await t(["gh","auth","token","--hostname","github.com"],{unsetEnv:["GH_TOKEN","GITHUB_TOKEN"],timeout:c0e,sensitiveOutput:!0});if(i)return{ok:!1,reason:`gh did not answer within ${c0e/1000} seconds (a locked keyring waiting for a prompt?). Set GH_TOKEN, or run 'gh auth status'.`};if(o===0&&r.trim())return{ok:!0,token:r.trim(),source:"gh"};return{ok:!1,reason:`gh has no signed-in account for github.com (${s.trim().split(`
|
|
340
340
|
`)[0]||`exit ${o}`}).`}}catch(r){let o=r instanceof Error?r.message:String(r);return{ok:!1,reason:o.includes("ENOENT")||o.includes("not found")?"The GitHub CLI (gh) is not installed.":`gh could not be run: ${o}`}}}function bg(e){return{Authorization:`Bearer ${e}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"nemar-cli pr-reviews","Content-Type":"application/json"}}async function x$(e,t=kn()){let n;try{n=await fetch(`${t}/user`,{headers:bg(e),signal:AbortSignal.timeout(yg)})}catch(i){return{ok:!1,kind:"unreachable",reason:`GitHub could not be reached (${i instanceof Error?i.message:String(i)}).`}}if(n.status===401)return{ok:!1,kind:"rejected",reason:"GitHub rejected this token."};if(!n.ok){let i=await n.text().catch(()=>"");if(n.status===403&&!/rate limit|abuse/i.test(i))return{ok:!1,kind:"not_a_person",reason:"This token does not belong to a GitHub user (an app or workflow token cannot approve for you)."};return{ok:!1,kind:"unreachable",reason:`GitHub answered HTTP ${n.status} when asked whose token this is. Try again in a moment.`}}let r=Symbol("unreadable"),o=await n.json().catch(()=>r);if(o===r)return{ok:!1,kind:"unreachable",reason:"GitHub answered, but the answer could not be read when asked whose token this is. Try again in a moment."};let s=o;if(typeof s?.login!=="string"||typeof s.id!=="number"||s.type!=="User"||s.login.endsWith("[bot]"))return{ok:!1,kind:"not_a_person",reason:"This token does not belong to a GitHub user, so it cannot approve for you."};return{ok:!0,user:{login:s.login,id:s.id}}}function v$(e,t){if(!e)return"unlinked";return e.toLowerCase()===t.toLowerCase()?"match":"mismatch"}function rw(e,t){let n=typeof t==="object"&&t!==null&&"message"in t?qi(t.message,160):"";return n?`${n} (HTTP ${e})`:`GitHub answered HTTP ${e}.`}async function Bi(e,t,n,r=kn()){let o;try{o=await fetch(`${r}/repos/${Ss}/${t}/pulls/${n}`,{headers:bg(e),signal:AbortSignal.timeout(yg)})}catch(d){return{ok:!1,status:0,reason:`GitHub could not be reached (${d instanceof Error?d.message:String(d)}).`}}let s=await o.json().catch(()=>null);if(!o.ok)return{ok:!1,status:o.status,reason:o.status===404?`${Ss}/${t} has no pull request #${n}, or your GitHub account cannot see it.`:rw(o.status,s)};let i=s?.head,a=s?.base,c=s?.user;if(typeof i?.sha!=="string"||!/^[0-9a-f]{40}$/.test(i.sha))return{ok:!1,status:o.status,reason:"GitHub's answer had no head commit."};let l=(d)=>typeof d?.full_name==="string"?d.full_name:null;return{ok:!0,value:{state:s?.merged===!0?"merged":s?.state==="open"?"open":"closed",draft:s?.draft===!0,baseRef:typeof a?.ref==="string"?a.ref:"",headRef:typeof i.ref==="string"?i.ref:"",headSha:i.sha,headRepo:l(i.repo),baseRepo:l(a?.repo),authorLogin:typeof c?.login==="string"?c.login:"",mergeableState:typeof s?.mergeable_state==="string"?s.mergeable_state:"unknown"}}}function d0e(e){if(e.state==="merged")return"This pull request is already merged.";if(e.state==="closed")return"This pull request is closed.";if(e.baseRef!=="main")return`This pull request targets ${qi(e.baseRef,40)||"another branch"}, not main. The review queue covers pull requests to main.`;if(e.draft)return"This pull request is a draft. Ask the author to mark it ready first.";return null}function O0t(e){return typeof e==="string"&&zf.includes(e)?e:null}var T0t=["pass","fail","uncertain"];function k$(e,t){let n=typeof e==="object"&&e!==null?e:null;if(!n)return{ok:!1,why:"the NEMAR API sent no review"};let r=O0t(n.verdict);if(r===null)return{ok:!1,why:"the NEMAR API sent a verdict this version of the CLI does not know; update the CLI"};if(n.head_sha!==t)return{ok:!1,why:"the NEMAR API answered about a different commit than GitHub reports"};let o=n.stale_verdict??null;if(o!==null&&!T0t.includes(o))return{ok:!1,why:"the NEMAR API sent a review this version of the CLI cannot read"};let s=n.review_current??null;if(s!==null&&typeof s!=="boolean")return{ok:!1,why:"the NEMAR API sent a review this version of the CLI cannot read"};let i=n.author?.standing,a=i?.paused===!0?`The contributor's pull requests are not reviewed automatically (paused${i.because==="maintainer"?" by an administrator's block":""}).`:null;return{ok:!0,verdict:r,detail:typeof n.detail==="string"?n.detail:null,staleVerdict:o,reviewCurrent:s,contributorNote:a,outcome:s===!0?n.review?.outcome??null:null}}function E$(e){if(e.unread)return{kind:"needs_force",reason:`The automated review could not be read (${e.unread}), so its verdict is unknown. Pass --force to approve without it.`};switch(e.verdict){case"pass":return{kind:"proceed"};case"fail":return{kind:"needs_force",reason:"The automated review says this pull request needs changes. Read it with `show`, and pass --force to approve it anyway."};case"in_progress":return{kind:"needs_force",reason:"The automated review of this commit is still running. Wait for it, or pass --force to approve without it."};case"uncertain":return{kind:"confirm",warning:"The automated review could not decide whether this is a good change."};case"could_not_decide":return{kind:"confirm",warning:"The automated review ended without a verdict."};case"not_reviewed":return{kind:"confirm",warning:e.staleVerdict===null?"The automated review has not read this commit.":`The automated review read a different commit of this pull request (it said: ${e.staleVerdict}), not this one.`};case"exempt":return{kind:"confirm",warning:`The automated review did not run on this commit: a NEMAR owner or administrator opened this pull request, and they are not reviewed.${e.staleVerdict===null?"":` An earlier commit of it was reviewed and read ${e.staleVerdict}.`}`}}}function S$(e){return{ok:!1,outcome:"unknown",status:0,reason:`GitHub did not answer (${e instanceof Error?e.message:String(e)}).`}}async function gF(e,t,n,r,o,s,i=kn()){let a;try{a=await fetch(`${i}/repos/${Ss}/${t}/pulls/${n}/reviews`,{method:"POST",headers:bg(e),body:JSON.stringify({commit_id:r,event:"APPROVE",body:s}),signal:AbortSignal.timeout(yg)})}catch(d){return S$(d)}let c=await a.json().catch(()=>null);if(!a.ok)return{ok:!1,outcome:a.status>=500?"unknown":"refused",status:a.status,reason:rw(a.status,c)};if(typeof c?.state!=="string")return{ok:!1,outcome:"unknown",status:a.status,reason:`GitHub answered HTTP ${a.status}, but its answer could not be read.`};let l=typeof c.user?.login==="string"?c.user.login:"";if(c.state!=="APPROVED"||c.commit_id!==r||l.toLowerCase()!==o.toLowerCase()){let d=[c.state!=="APPROVED"?`state ${qi(c.state,20)}`:"",l.toLowerCase()!==o.toLowerCase()?`by @${qi(l,40)||"?"}`:"",c.commit_id!==r?`commit ${typeof c.commit_id==="string"?qi(c.commit_id,40).slice(0,7):"?"}`:""].filter(Boolean);return{ok:!1,outcome:"different",status:a.status,reason:`GitHub recorded a review, but not the approval that was asked for (${d.join(", ")}).`}}return{ok:!0}}async function f0e(e,t,n,r,o=kn()){let s;try{s=await fetch(`${o}/repos/${Ss}/${t}/issues/${n}/comments`,{method:"POST",headers:bg(e),body:JSON.stringify({body:r}),signal:AbortSignal.timeout(yg)})}catch(a){return S$(a)}let i=await s.json().catch(()=>null);if(!s.ok)return{ok:!1,outcome:s.status>=500?"unknown":"refused",status:s.status,reason:rw(s.status,i)};if(typeof i?.id!=="number")return{ok:!1,outcome:"unknown",status:s.status,reason:`GitHub answered HTTP ${s.status}, but its answer could not be read.`};return{ok:!0}}async function $$(e,t,n,r=kn()){let o;try{o=await fetch(`${r}/repos/${Ss}/${t}/pulls/${n}`,{method:"PATCH",headers:bg(e),body:JSON.stringify({state:"closed"}),signal:AbortSignal.timeout(yg)})}catch(i){return S$(i)}let s=await o.json().catch(()=>null);if(!o.ok)return{ok:!1,outcome:o.status>=500?"unknown":"refused",status:o.status,reason:rw(o.status,s)};if(typeof s?.state!=="string")return{ok:!1,outcome:"unknown",status:o.status,reason:`GitHub answered HTTP ${o.status}, but its answer could not be read.`};if(s.state!=="closed")return{ok:!1,outcome:"different",status:o.status,reason:`GitHub answered, but the pull request is ${qi(s.state,20)}, not closed.`};return{ok:!0}}var D$=["merge","squash","rebase"],P0t="clean",I0t=new Map([["blocked","a required check or review is not satisfied (the BIDS validation, the version check or, where its ruleset is in force, the NEMAR PR Review); this tool names the NEMAR PR Review check, and no other, as one an owner or administrator can override in the GitHub UI, and only where its ruleset is in force, and it never uses the bypass itself"],["behind","the branch is behind main"],["dirty","it has merge conflicts"],["unstable","a check or status that is not required is not passing or has not reported, for example the automated review holding the pull request"],["draft","it is a draft"],["unknown","GitHub has not said whether it can be merged"]]);function l0e(e){return I0t.get(e)??"this tool merges only a pull request GitHub reports as clean"}function wg(e){let t=e&&e.length>0?e:"unknown";if(t===P0t)return{ok:!0};return{ok:!1,why:`GitHub reports this pull request as '${w$(t)}' (${l0e(t)}), so a merge would not be attempted.`,card:`${l0e(t)} (GitHub: ${w$(t)})`,advice:t==="unknown"?"retry":"without_merge"}}function w$(e){return/^[a-z][a-z_]{0,29}$/.test(e)?e:"unrecognised"}async function _g(e,t,n,r,o={}){let s=o.base??kn(),i=o.sleep??((d)=>new Promise((f)=>setTimeout(f,d))),a=o.tries??5,c=r.mergeableState,l=c===null?0:1;for(;;){if(c===null){let d=await Bi(e,t,n,s);if(!d.ok)return{ok:!1,kind:"unreadable",status:d.status,reason:d.reason};if(d.value.state!=="open")return{ok:!1,kind:"closed",merged:d.value.state==="merged"};if(d.value.headSha!==r.headSha)return{ok:!1,kind:"moved"};c=d.value.mergeableState,l++}if(c!=="unknown"||l>=a)return{ok:!0,state:c};await i(1000),c=null}}function p0e(e){if(e.kind==="moved")return{ok:!1,why:"The pull request changed since it was read.",card:"the pull request changed since it was read",advice:"rerun"};if(e.kind==="closed")return{ok:!1,why:`The pull request is no longer open (it was ${e.merged?"merged":"closed"}).`,card:"the pull request is no longer open",advice:"none"};let t=e.reason.replace(/\.$/,"");return{ok:!1,why:`Could not check whether it can be merged (${t}).`,card:`could not be checked (${t})`,advice:"retry"}}async function xg(e,t,n,r,o={}){let s=await _g(e,t,n,r,o);return s.ok?wg(s.state):p0e(s)}async function yF(e,t,n,r,o={}){let s=await xg(e,t,n,{headSha:r,mergeableState:null},o);return s.ok?s:{...s,why:`Checked again just before approving: ${s.why}`}}async function ow(e,t,n,r,o,s={}){let i=s.base??kn(),a=await _g(e,t,n,{headSha:r,mergeableState:null},s);if(!a.ok){if(a.kind==="moved")return{ok:!1,outcome:"not_sent",status:409,reason:"The pull request changed after it was approved, so it was not merged."};if(a.kind==="closed")return{ok:!1,outcome:"not_sent",status:409,reason:`Not merged: ${p0e(a).why} The approval stands.`};return{ok:!1,outcome:"not_sent",status:a.status,reason:`Not merged: ${a.reason} The approval stands.`}}let c=s.state==="unstable"?a.state==="unstable"?{ok:!0}:{ok:!1,why:`GitHub reports this pull request as '${w$(a.state)}', not 'unstable', so a merge over a failed BIDS validation would not be attempted.`,card:`not unstable (GitHub: ${w$(a.state)})`,advice:"none"}:wg(a.state);if(!c.ok)return{ok:!1,outcome:"not_sent",status:405,merge:c,reason:`Not merged: ${c.why} The approval stands.`};let l;try{l=await fetch(`${i}/repos/${Ss}/${t}/pulls/${n}/merge`,{method:"PUT",headers:bg(e),body:JSON.stringify({sha:r,merge_method:o,...s.commit?{commit_title:s.commit.title,commit_message:s.commit.message}:{}}),signal:AbortSignal.timeout(yg)})}catch(f){return S$(f)}let d=await l.json().catch(()=>null);if(!l.ok)return{ok:!1,outcome:l.status>=500?"unknown":"refused",status:l.status,reason:rw(l.status,d)};if(d?.merged!==!0)return{ok:!1,outcome:"unknown",status:l.status,reason:`GitHub answered HTTP ${l.status}, but did not say the pull request was merged.`};return{ok:!0}}function h0e(e){switch(e.trim().toLowerCase()){case"y":case"yes":return"approve";case"n":case"no":return"close";case"c":case"comment":return"comment";case"d":case"details":return"details";case"s":case"skip":return"skip";case"q":case"quit":return"quit";default:return null}}function g0e(e){let t=[];if(e.bids!=="pass"||e.version!=="pass")t.push(`A required check is not green (BIDS ${m0e(e.bids)}, version ${m0e(e.version)}), so GitHub would not let it merge.`);if(!e.merge.ok)t.push(e.merge.why);if(e.gate.kind==="needs_force"&&!e.force)t.push(e.gate.reason);return t.length===0?{ok:!0}:{ok:!1,reason:t.join(" ")}}function m0e(e){switch(e){case"pass":return"ok";case"fail":return"failing";case"pending":return"pending";case"missing":return"missing";default:return"unknown"}}function R$(e){return`${e.dataset_id}#${e.pr_number}`}function y0e(e,t){if(t.aborted)return Promise.resolve({aborted:!0});return new Promise((n,r)=>{let o=()=>n({aborted:!0});t.addEventListener("abort",o,{once:!0}),e.then((s)=>{t.removeEventListener("abort",o),n({aborted:!1,value:s})},(s)=>{t.removeEventListener("abort",o),r(s)})})}async function b0e(e,t,n){let r=[],o=t.now??Date.now,s=new Map,i=0,a=0,c=null;while(i<e.length){if(n.signal.aborted){c="interrupted";break}if(s.size>=n.concurrency){if(t.onWait?.({running:s.size,remaining:e.length-i}),await t.sleep(n.pollMs,n.signal),n.signal.aborted)continue;for(let[m,h]of[...s])if(o()-h.since>=n.maxHoldMs)s.delete(m);if(s.size<n.concurrency)continue;let f=await y0e(t.inProgress().catch(()=>null),n.signal);if(f.aborted)continue;let p=f.value;if(p===null){if(a++,t.onUnknown?.({count:a,max:n.maxUnknownPolls}),a>=n.maxUnknownPolls){c="unknown_polls";break}continue}a=0;for(let[m,h]of[...s]){if(p.has(m))continue;if(!t.confirmFinished){s.delete(m);continue}let g=await y0e(t.confirmFinished(h.entry).catch(()=>!1),n.signal);if(g.aborted)break;if(g.value)s.delete(m)}continue}let l=e[i++],d;try{d={answer:await t.start(l)}}catch(f){d={error:f}}if(r.push({entry:l,...d}),t.onResult(l,d),"answer"in d){if(t.isRunning(d.answer))s.set(R$(l),{entry:l,since:o()});if(t.stopAfter?.(d.answer)){c="answer";break}}else if(t.maybeRunning?.(d.error))s.set(R$(l),{entry:l,since:o()})}return{results:r,notStarted:e.slice(i),stoppedBy:c}}function w0e(e,t){return new Promise((n)=>{if(t.aborted){n();return}let r=()=>{clearTimeout(o),t.removeEventListener("abort",r),n()},o=setTimeout(r,e);t.addEventListener("abort",r,{once:!0})})}function _0e(e){if(!/^[1-9][0-9]{0,5}$/.test(e.trim()))return null;return Number(e.trim())}import{createInterface as N0t}from"readline";var C$=250;class Wf{rl;lines=[];waiting=[];output;typeAhead;ended=!1;wasInterrupted=!1;constructor(e=process.stdin,t=process.stdout,n={}){this.output=t,this.typeAhead=n.typeAhead??(e.isTTY===!0?"discard":"keep"),this.rl=N0t({input:e,output:t,terminal:e.isTTY===!0}),this.rl.on("line",(r)=>{let o=this.waiting.shift();if(o)o(r);else this.lines.push(r)}),this.rl.on("SIGINT",()=>this.interrupt()),this.rl.on("close",()=>{this.ended=!0;for(let r of this.waiting.splice(0))r(null)})}get open(){return!this.ended}get canAnswer(){return!this.wasInterrupted&&(!this.ended||this.lines.length>0)}get interrupted(){return this.wasInterrupted}interrupt(){this.wasInterrupted=!0,this.lines.length=0,this.rl.close()}ask(e){if(this.wasInterrupted)return Promise.resolve(null);let t=this.lines.shift();if(t!==void 0)return this.output.write(`${e}${t}
|
|
341
341
|
`),Promise.resolve(t);if(this.ended)return Promise.resolve(null);return this.rl.setPrompt(e),this.rl.prompt(),new Promise((n)=>this.waiting.push(n))}async discardTyped(e=0){if(this.typeAhead!=="discard")return 0;if(e>0)await new Promise((n)=>setTimeout(n,e));let t=this.lines.length;return this.lines.length=0,t}close(){this.rl.close()}}import{dirname as jEt,join as LEt}from"path";var x0e="nemarDatasets";function yd(e,t){return typeof e==="string"&&e.toLowerCase()===`nemarDatasets/${t}`.toLowerCase()}var E0e=["planned","prepared","copied","registered","pr_open","gates_clear","merged","released","patch_synthesized","patch_gates_clear","patch_merged","patch_released","complete","abandoned","failed","superseded","patch_declined"],F0t=["complete","abandoned","failed","superseded","patch_declined"];function bF(e){return F0t.includes(e)}var vg=["planned","prepared","copied","registered","pr_open","gates_clear"],wF=["released","patch_synthesized","patch_gates_clear"],M0t=E0e.filter((e)=>!bF(e)),sJt=(()=>{let e=[["planned","planned"],["planned","prepared"],["prepared","prepared"],["prepared","copied"],["copied","copied"],["copied","registered"],["registered","registered"],["registered","pr_open"],["pr_open","pr_open"],["pr_open","gates_clear"],["pr_open","merged"],["gates_clear","pr_open"],["gates_clear","gates_clear"],["gates_clear","merged"],["merged","merged"],["merged","released"],["released","released"],["released","complete"],["released","patch_synthesized"],["patch_synthesized","patch_synthesized"],["patch_synthesized","patch_gates_clear"],["patch_synthesized","patch_merged"],["patch_gates_clear","patch_synthesized"],["patch_gates_clear","patch_gates_clear"],["patch_gates_clear","patch_merged"],["patch_merged","patch_merged"],["patch_merged","patch_released"],["patch_released","complete"]],t=new Map(E0e.map((r)=>[r,[]])),n=(r,o)=>t.get(r)?.push(o);for(let[r,o]of e)n(r,o);for(let r of vg)n(r,"abandoned"),n(r,"superseded");for(let r of wF)n(r,"patch_declined");for(let r of M0t)n(r,"failed");return Object.fromEntries(t)})();var A$=/^\d+\.\d+\.\d+$/;var j0t=["n0","n1"],Tr={n0:{number:"pr_number",branch:"branch",head:"head_sha",gates:"gates_sha",claimedAt:"merge_claimed_at",claimSha:"merge_claim_sha",mergeSha:"merge_sha",tagSha:"tag_sha",version:"to_version",open:"pr_open",gatesClear:"gates_clear",merged:"merged",released:"released"},n1:{number:"patch_pr_number",branch:"patch_branch",head:"patch_head_sha",gates:"patch_gates_sha",claimedAt:"patch_merge_claimed_at",claimSha:"patch_merge_claim_sha",mergeSha:"patch_merge_sha",tagSha:"patch_tag_sha",version:"patch_version",open:"patch_synthesized",gatesClear:"patch_gates_clear",merged:"patch_merged",released:"patch_released"}};function S0e(e){for(let t of j0t)if(Tr[t].gatesClear===e)return t;return null}function O$(e){if(!A$.test(e))return null;let[t]=e.split(".");return`${t}.0.1`}var L0t=["auto-production-only","auto-repull-off","auto-on-only","auto-planner-version","auto-not-clean-plan","auto-copy-too-large","dispatch-token","dispatch-mismatch","dispatch-unconfigured","dispatch-refused","dispatch-failed","dispatch-deferred","invalid-body","invalid-token","already-started","kind-mismatch","repull-mismatch","repull-not-ready","stale-dispatch","dispatch-invalid","runner-disk","auto-cli-version","runner-credentials","runner-failed","auto-no-app-token","auto-token-on-argv","auto-verbose","auto-option","auto-api-not-production","auto-token-hour","auto-token-clock","auto-copy-too-long","token-expired","not-planned","head-foreign","head-unreadable","finish-not-merged","finish-incomplete","report-unanswered","no-code","key-without-pin","ledger-correction-unexplained","dead-recording-unpinned","target-names-dead-key","concept-doi-disagrees","gitlink","anonymous-dataset","not-a-mirror","plan-refused","record-refused","prepare-failed","scrub-failed","copy-failed","register-failed","pr-failed","settle-failed","finish-failed"];function _F(e){return typeof e==="string"&&L0t.includes(e)}var $0e={plan:"plan-refused",record:"record-refused",prepare:"prepare-failed",copy:"copy-failed",register:"register-failed",pr:"pr-failed",settle:"settle-failed",finish:"finish-failed"};var v0e=2,k0e=1099511627776;function D0e(e,t){if(e!==v0e)return{code:"auto-planner-version",message:`An automatic re-pull takes only a plan of planner ${v0e}.`};if(["unexplained","conflicts","corrections"].some((r)=>t[r]!==0))return{code:"auto-not-clean-plan",message:"An automatic re-pull takes only a plan that states zero unexplained paths, zero conflicts and zero corrections."};let n=t.copy_bytes;if(typeof n!=="number"||n>k0e)return{code:"auto-copy-too-large",message:`An automatic re-pull takes only a plan whose copy size is stated and at most ${k0e} bytes.`};return null}var R0e=/^[0-9a-f]{64}$/,sw=3300,xF=360,C0e=300,q0t=1740,vF=sw-xF-q0t,B0t=31457280,U0t=1;function kF(e){return e.bytes/B0t+e.objects*U0t}var T$=/^[1-9][0-9]{0,14}$/;var EF="[auto:";var SF="Repull-Patch";function iw(e){return[`Upstream-Snapshot: ${e.upstream_ds}@${e.to_tag}`,`Repull-Plan: ${e.plan_digest}`]}function A0e(e,t,n="n0",r="gate"){let[o,s]=iw(e),i=n==="n1"?e.counts?.corrections:void 0,a=r==="worker"?"squash-merged by the Worker as a machine-clean automatic re-pull":"squash-merged through the re-pull's merge gate";return{title:`Release v${e[Tr[n].version]} (#${t})`,message:[n==="n0"?`Re-pull of upstream ${e.upstream_ds} from snapshot ${e.from_tag} to ${e.to_tag} (re-pull #${e.id}), ${a} (ADR 0111).`:`NEMAR's corrections of re-pull #${e.id} (upstream ${e.upstream_ds} ${e.from_tag} to ${e.to_tag}), replayed onto v${e.to_version}, ${a} (ADR 0111).`,"",o,s,...n==="n1"&&typeof i==="number"?[`${SF}: corrections=${i}`]:[]].join(`
|
|
342
|
-
`)}}Qa();
|
|
342
|
+
`)}}Qa();Je();lo();Je();async function O0e(e){return q("/admin/repulls",{method:"POST",body:JSON.stringify(e)},!0)}async function P$(e){return(await q(`/admin/repulls/${e}`,{},!0)).repull}async function Io(e={}){let t=new URLSearchParams;if(e.dataset)t.set("dataset",e.dataset);if(e.open)t.set("open","1");if(e.origin)t.set("origin",e.origin);if(e.after!==void 0)t.set("after",String(e.after));if(e.limit!==void 0)t.set("limit",String(e.limit));let n=t.toString()?`?${t.toString()}`:"";return q(`/admin/repulls${n}`,{},!0)}async function T0e(){return q("/admin/repulls/switches",{},!0)}async function P0e(e={}){let t=new URLSearchParams;if(e.dataset)t.set("dataset",e.dataset);if(e.status)t.set("status",e.status);if(e.after!==void 0)t.set("after",String(e.after));if(e.limit!==void 0)t.set("limit",String(e.limit));let n=t.toString()?`?${t.toString()}`:"";return q(`/admin/repulls/dispatches${n}`,{},!0)}async function Zn(e,t){return(await q(`/admin/repulls/${e}/transition`,{method:"POST",body:JSON.stringify(t)},!0)).repull}async function kg(e){return q(`/admin/repulls/${e}/screens`,{},!0)}async function I0e(e,t){return q(`/admin/repulls/${e}/screen`,{method:"POST",body:JSON.stringify(t)},!0)}async function N0e(e,t){return q(`/admin/repulls/${e}/screen/acknowledge`,{method:"POST",body:JSON.stringify(t)},!0)}async function F0e(e,t){return(await q(`/admin/repulls/${e}/merge-claim/release`,{method:"POST",body:JSON.stringify(t)},!0)).repull}async function M0e(e,t){return(await q(`/admin/repulls/${e}/merge-claim/check`,{method:"POST",body:JSON.stringify(t)},!0)).repull}async function I$(e,t){return q(`/admin/repulls/${e}/merged`,{method:"POST",body:JSON.stringify({pr:t})},!0)}async function j0e(e,t){return q(`/admin/repulls/${e}/released`,{method:"POST",body:JSON.stringify(t)},!0)}function An(e){if(!(e instanceof L))return;let t=e.rawBody;if(typeof t!=="object"||t===null||Array.isArray(t))return;let n=t.code;return typeof n==="string"?n:void 0}ec();Je();async function ac(e){let t=null;try{t=await Wn(e)}catch(r){if(!(r instanceof L&&r.statusCode===404))throw r}let n=null;if(t)try{n=(await Lf(e)).versions.map((o)=>({version:o.version,source_version:o.source_version??null,source_version_basis:o.source_version_basis??null}))}catch(r){if(!(r instanceof L&&r.statusCode===404))throw r}return{dataset:t,versions:n}}var ll=".nemar/";function ul(e,t){if(e.includes(t))return{content:e,changed:!1};return{content:e?`${e.trimEnd()}
|
|
343
343
|
${t}
|
|
344
344
|
`:`${t}
|
|
345
345
|
`,changed:!0}}function Eg(e){let t=new Set,n=/^(sub-[0-9A-Za-z]+)(?:\/|$)/;for(let r of e){let o=n.exec(r.path);if(o)t.add(o[1])}return[...t].sort()}function Sg(e){if(e.length===0)throw Error("buildPlaceholderParticipantsTsv: refusing to emit a header-only TSV");let t="participant_id\tage\tsex",n=e.map((r)=>`${r} n/a n/a`);return`${[t,...n].join(`
|
|
@@ -384,7 +384,7 @@ ${s}
|
|
|
384
384
|
`;let i=e.includes(`\r
|
|
385
385
|
`)?`\r
|
|
386
386
|
`:`
|
|
387
|
-
`,a=e.split(/\r?\n/),c=a.findIndex((d)=>Kkt.test(d)),l=c<0?0:c;return[...a.slice(0,l),o,"",s,"",...a.slice(l)].join(i)}function cve(e,t){switch(e.outcome){case"created":return`Created ${e.file} with an entry for ${t}`;case"added":return`Added an entry for ${t} to ${e.file}`;case"present":return`${e.file} already has an entry for ${t}; left as it is`}}function eve(e){return[/^changes/i.test(e)?0:1,e.includes(".")?1:0,e]}function Qkt(e,t){let[n,r]=[eve(e),eve(t)];return n[0]-r[0]||n[1]-r[1]||(n[2]<r[2]?-1:n[2]>r[2]?1:0)}function Zkt(e,t){if(t[0]===239&&t[1]===187&&t[2]===191)throw Error(`${e} starts with a byte order mark, which the review cannot read past; save it as UTF-8 without one and run this again`);try{new TextDecoder("utf-8",{fatal:!0}).decode(t)}catch{throw Error(`${e} is not valid UTF-8, so adding the entry would damage it; convert it to UTF-8 and run this again`)}}function wM(e,t){let n=Fkt(e).filter((l)=>Wkt.test(l)),r=n.filter((l)=>Ikt(mM(e,l)).isFile()).sort(Qkt),o=n.find((l)=>!r.includes(l));if(r.length===0&&o!==void 0)throw Error(`${o} exists but is not a regular file (a link or a directory), so the entry cannot be added; replace it with a regular file and run this again`);let s=r.map((l)=>({name:l,bytes:Nkt(mM(e,l))})),i=s.map(({bytes:l})=>l.toString("utf8")),a=i.findIndex((l)=>Ykt(l,t)),c=s[0];if(c!==void 0&&a<0)Zkt(c.name,c.bytes);return{file:c?.name??null,text:i[0]??null,presentIn:a<0?null:r[a]??null}}function lve(e,t,n,r){let o=wM(e,t);if(o.presentIn!==null)return{file:o.presentIn,outcome:"present"};let s=o.file??"CHANGES";return Mkt(mM(e,s),Xkt(o.text,t,n,r)),{file:s,outcome:o.file===null?"created":"added"}}function uve(e){let t=(n)=>String(n).padStart(2,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}`}class
|
|
387
|
+
`,a=e.split(/\r?\n/),c=a.findIndex((d)=>Kkt.test(d)),l=c<0?0:c;return[...a.slice(0,l),o,"",s,"",...a.slice(l)].join(i)}function cve(e,t){switch(e.outcome){case"created":return`Created ${e.file} with an entry for ${t}`;case"added":return`Added an entry for ${t} to ${e.file}`;case"present":return`${e.file} already has an entry for ${t}; left as it is`}}function eve(e){return[/^changes/i.test(e)?0:1,e.includes(".")?1:0,e]}function Qkt(e,t){let[n,r]=[eve(e),eve(t)];return n[0]-r[0]||n[1]-r[1]||(n[2]<r[2]?-1:n[2]>r[2]?1:0)}function Zkt(e,t){if(t[0]===239&&t[1]===187&&t[2]===191)throw Error(`${e} starts with a byte order mark, which the review cannot read past; save it as UTF-8 without one and run this again`);try{new TextDecoder("utf-8",{fatal:!0}).decode(t)}catch{throw Error(`${e} is not valid UTF-8, so adding the entry would damage it; convert it to UTF-8 and run this again`)}}function wM(e,t){let n=Fkt(e).filter((l)=>Wkt.test(l)),r=n.filter((l)=>Ikt(mM(e,l)).isFile()).sort(Qkt),o=n.find((l)=>!r.includes(l));if(r.length===0&&o!==void 0)throw Error(`${o} exists but is not a regular file (a link or a directory), so the entry cannot be added; replace it with a regular file and run this again`);let s=r.map((l)=>({name:l,bytes:Nkt(mM(e,l))})),i=s.map(({bytes:l})=>l.toString("utf8")),a=i.findIndex((l)=>Ykt(l,t)),c=s[0];if(c!==void 0&&a<0)Zkt(c.name,c.bytes);return{file:c?.name??null,text:i[0]??null,presentIn:a<0?null:r[a]??null}}function lve(e,t,n,r){let o=wM(e,t);if(o.presentIn!==null)return{file:o.presentIn,outcome:"present"};let s=o.file??"CHANGES";return Mkt(mM(e,s),Xkt(o.text,t,n,r)),{file:s,outcome:o.file===null?"created":"added"}}function uve(e){let t=(n)=>String(n).padStart(2,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}`}class Xe extends Error{what;constructor(e){super(`A re-pull write was refused by the write guard: ${e}.`);this.what=e;this.name="RepullWriteRefused"}}var eEt=/^[0-9a-f]{40}$/,tEt=/^\d+\.\d+\.\d+$/;function nEt(e){return`refs/heads/release/v${e}`}function dve(e,t){if(!t.versions.every((m)=>tEt.test(m)))throw new Xe("bad-version");let n=new Set(t.versions.map(nEt));if(e[0]!=="push")throw new Xe("not-a-push");let r=e.slice(1),o=r.indexOf("origin");if(o<0||r.lastIndexOf("origin")!==o)throw new Xe("remote-not-origin");let s=r.slice(0,o),i=r.slice(o+1),a=null,c=!1;for(let m of s){if(m==="--quiet"||m==="--porcelain")continue;let h=/^--force-with-lease=(refs\/heads\/release\/v\d+\.\d+\.\d+):([0-9a-f]{40})$/.exec(m);if(h&&!a){a={ref:h[1],sha:h[2]};continue}throw new Xe("option-not-allowed")}if(i[0]==="--delete")c=!0,i.shift();if(i.length!==1)throw new Xe("one-refspec-only");let l=i[0];if(c){if(!n.has(l))throw new Xe("delete-not-a-release-branch");if(!a||a.ref!==l)throw new Xe("delete-without-lease");return}let d=l.indexOf(":"),f=d<0?"":l.slice(0,d),p=d<0?"":l.slice(d+1);if(!eEt.test(f))throw new Xe("source-not-a-commit-id");if(a){if(p!==a.ref||!n.has(p))throw new Xe("lease-mismatch");return}if(n.has(p)||p==="refs/heads/git-annex")return;throw new Xe("destination-not-allowed")}var _M=/^[A-Za-z0-9._-]{1,1024}$/,xM="version id has a character the guard does not allow",rEt=/^[A-Za-z0-9._~=+/-]{1,1024}$/;function oEt(e){let t=new Map;for(let n=0;n<e.length;n++){let r=e[n];if(!r.startsWith("--")||r.includes("="))throw new Xe("bad-argument");if(t.has(r))throw new Xe("argument-repeated");if(r==="--no-paginate"){t.set(r,"");continue}let o=e[n+1];if(o===void 0||o.startsWith("--"))throw new Xe("argument-without-value");t.set(r,o),n++}return t}var sEt={"head-object":["--bucket","--key","--version-id"],"copy-object":["--bucket","--key","--copy-source","--copy-source-if-match"],"create-multipart-upload":["--bucket","--key"],"upload-part-copy":["--bucket","--key","--upload-id","--part-number","--copy-source","--copy-source-range","--copy-source-if-match"],"complete-multipart-upload":["--bucket","--key","--upload-id","--multipart-upload"],"abort-multipart-upload":["--bucket","--key","--upload-id"],"list-objects-v2":["--bucket","--prefix","--max-keys","--no-paginate","--continuation-token"],"put-object":["--bucket","--key","--body","--content-type"],"delete-object":["--bucket","--key","--version-id"],"list-object-versions":["--bucket","--prefix","--max-keys","--no-paginate","--key-marker","--version-id-marker"],"list-multipart-uploads":["--bucket","--prefix","--max-uploads","--no-paginate"]},iEt=new Set(["list-object-versions","list-multipart-uploads"]),aEt=new Set(["copy-object","create-multipart-upload","upload-part-copy","complete-multipart-upload","abort-multipart-upload"]);function ZD(e,t=!1){let n=e.split("/");if(t&&n[n.length-1]==="")n.pop();return n.some((r)=>r===""||r==="."||r==="..")}function Ww(e,t){return typeof e==="string"&&t.endsWith("/")&&e.startsWith(t)&&e.length>t.length&&!ZD(e)}function cEt(e,t){if(e===void 0)throw new Xe("copy-source-missing");let n=e.lastIndexOf("?versionId=");if(n<0)throw new Xe("copy-source-unversioned");let r=e.slice(0,n),o=e.slice(n+11);if(!_M.test(o))throw new Xe(xM);if(!r.startsWith(`${t.sourceBucket}/`))throw new Xe("copy-source-bucket");if(!Ww(r.slice(t.sourceBucket.length+1),t.sourcePrefix))throw new Xe("copy-source-prefix")}function lEt(e,t,n){if(!n.prefix.endsWith("/")||!n.sourcePrefix.endsWith("/")||ZD(n.prefix,!0)||ZD(n.sourcePrefix,!0))throw new Xe("bad-context");let r=sEt[e];if(!r)throw new Xe("operation-not-allowed");if(iEt.has(e)&&!n.canary)throw new Xe("operation-not-allowed");let o=oEt(t);for(let a of o.keys())if(!r.includes(a))throw new Xe("option-not-allowed");let s=o.get("--bucket"),i=o.get("--key");if(e==="head-object"){if(s===n.sourceBucket){if(!Ww(i,n.sourcePrefix))throw new Xe("source-key-prefix");let a=o.get("--version-id")??"";if(a==="")throw new Xe("source-read-unversioned");if(!_M.test(a))throw new Xe(xM);return}if(s!==n.destBucket)throw new Xe("bucket-not-allowed");if(!Ww(i,n.prefix)&&i!==n.stagingKey)throw new Xe("key-outside-prefix");return}if(s!==n.destBucket)throw new Xe("bucket-not-allowed");if(aEt.has(e)){if(!Ww(i,n.prefix))throw new Xe("key-outside-prefix");if(e==="copy-object"||e==="upload-part-copy"){if(cEt(o.get("--copy-source"),n),!o.get("--copy-source-if-match"))throw new Xe("copy-without-if-match")}if(e==="upload-part-copy"){let a=Number(o.get("--part-number"));if(!Number.isInteger(a)||a<1||a>1e4)throw new Xe("part-number");if(!/^bytes=\d+-\d+$/.test(o.get("--copy-source-range")??""))throw new Xe("copy-source-range")}if(e!=="copy-object"&&e!=="create-multipart-upload"){if(!rEt.test(o.get("--upload-id")??""))throw new Xe("upload-id")}return}if(e==="list-objects-v2"||e==="list-object-versions"||e==="list-multipart-uploads"){let a=o.get("--prefix");if(a===void 0||!a.startsWith(n.prefix)||ZD(a,!0))throw new Xe("listing-outside-prefix");return}if(e==="put-object"){if(i!==n.stagingKey)throw new Xe("put-not-the-staging-key");if(!o.get("--body"))throw new Xe("put-without-body");return}if(e==="delete-object"){let a=o.get("--version-id")??"";if(a==="")throw new Xe("delete-unversioned");if(!_M.test(a))throw new Xe(xM);if(!Ww(i,n.prefix)&&!(n.canary&&i===n.stagingKey))throw new Xe("key-outside-prefix");return}throw new Xe("operation-not-allowed")}function fve(e,t){return{async api(n,r,o){return lEt(n,r,t),e.api(n,r,o)}}}function yi(e){switch(e){case"moved":return"the remote moved under the push";case"protected-branch":return"the remote refused it as a protected branch";case"hook-declined":return"a hook on the remote declined it";case"remote-refused":return"the remote refused it";case"authentication":return"the credentials were refused";case"network":return"the remote could not be reached";default:return"for a reason git did not classify"}}function uEt(e){if(/Authentication failed|could not read Username|Permission denied|HTTP 40[13]|The requested URL returned error: 40[13]/i.test(e))return"authentication";if(/Could not resolve host|unable to access|Connection (refused|timed out|reset)|Failed to connect|early EOF/i.test(e))return"network";return"unknown"}async function xc(e,t,n,r,o=[]){let s=["push","--porcelain",...o,"origin",...t];dve(s,n);let i=await te(e,s,{ok:!0,...r?{env:r}:{}}),a=i.stdout.split(`
|
|
388
388
|
`).map((d)=>/^([ +\-*!=])\t[^\t]*\t(.*)$/.exec(d)).filter((d)=>d!==null),c=a.filter((d)=>d[1]==="!");if(c.length>0){let d=c.map((p)=>p[2]).join(" "),f=/incorrect old value provided|failed to update ref|cannot lock ref|stale info|fetch first|non-fast-forward/i;if(/\[remote rejected\]/i.test(d)&&!f.test(d)){let p=`${d} ${i.stderr}`;return{outcome:"remote-rejected",cause:/protected branch|GH006|GH013|repository rule violations/i.test(p)?"protected-branch":/hook declined/i.test(d)?"hook-declined":"remote-refused"}}return{outcome:"rejected",cause:"moved"}}if(i.exitCode!==0){if(/\[remote rejected\]|pre-receive hook declined|protected branch hook declined/i.test(i.stderr))return{outcome:"remote-rejected",cause:"remote-refused"};return{outcome:"failed",cause:uEt(i.stderr)}}let l=a.map((d)=>d[1]);return{outcome:l.length>0&&l.every((d)=>d==="=")?"up-to-date":"pushed",cause:null}}var dEt=20000;function Kn(e){return`refs/heads/release/v${e}`}async function pve(e,t,n){let r=await te(e,["ls-remote","origin",...t],{...n?{env:n}:{},code:"origin-unreadable",step:"ls-remote"}),o=new Map;for(let s of r.stdout.split(`
|
|
389
389
|
`)){let[i,a]=s.split("\t");if(i&&a&&/^[0-9a-f]{40}$/.test(i))o.set(a,i)}return o}async function fEt(e,t,n){let r=t.replace(/^refs\/heads\//,"refs/remotes/origin/");await te(e,["fetch","--quiet","--no-tags",`--depth=${us}`,"origin",`+${t}:${r}`],{...n?{env:n}:{},code:"origin-unreadable",step:"fetch"})}async function As(e){if(e.head===e.from)return"ok";await fEt(e.work,e.ref,e.env);let t=await _c(e.work,e.from,e.head);if(t.ok)return"ok";return t.code==="unreadable"?"unreadable":"foreign"}async function Cl(e){let n=(await pve(e.work,["refs/heads/main"],e.env)).get("refs/heads/main");if(!n)throw new N("origin-unreadable","NEMAR's main could not be read.");let r=await As({work:e.work,from:e.baseSha,head:n,ref:"refs/heads/main",env:e.env});if(r==="unreadable")throw new N("main-unreadable","Whether NEMAR's main moved only by commits enrichment makes could not be read from the working clone; nothing was pushed. Run again; if it persists, this re-pull's record has to be ended (nemar admin repull abandon <id>).");if(r!=="ok")throw new N("main-moved","NEMAR's main moved since the re-pull was prepared, by a commit enrichment does not make: this re-pull cannot continue, and its record has to be ended (nemar admin repull abandon <id>) and the dataset planned again.");return n}async function eR(e){let t=Kn(e.version);for(let n=1;n<=2;n++){let r=(await pve(e.work,[t],e.env)).get(t);if(r){let s=await As({work:e.work,from:e.synthSha,head:r,ref:t,env:e.env});if(s==="unreadable")throw new N("branch-unreadable",`Whether release/v${e.version} holds only this re-pull's commit and enrichment's could not be read from the working clone; nothing was pushed.`);if(s!=="ok")throw new N("branch-foreign",`release/v${e.version} exists on NEMAR's repository and is not this re-pull's commit: it holds a commit enrichment does not make. Remove the branch after checking what it holds, or end this re-pull's record (nemar admin repull abandon <id>).`);return{head:r,pushed:!1}}let o=await xc(e.work,[`${e.synthSha}:${t}`],e.push,e.env);if(o.outcome==="pushed"||o.outcome==="up-to-date")return{head:e.synthSha,pushed:!0};if(o.outcome==="remote-rejected")throw new N("push-refused",`release/v${e.version} was refused by NEMAR's repository (${yi(o.cause)}); a second push would be refused the same way.`);if(o.outcome==="failed")throw new N("push-failed",`release/v${e.version} could not be pushed to NEMAR's repository (${yi(o.cause)}).`)}throw new N("push-failed",`release/v${e.version} was refused twice because the remote moved under the push, and does not hold this re-pull's commit.`)}function pEt(e){return{Authorization:`Bearer ${e}`,Accept:"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"nemar-cli repull","Content-Type":"application/json"}}async function mEt(e,t){try{let n=await fetch(e,{method:t.method,headers:pEt(t.token),...t.body!==void 0?{body:JSON.stringify(t.body)}:{},signal:AbortSignal.timeout(dEt)});return{status:n.status,body:await n.json().catch(()=>null)}}catch{return null}}async function hEt(e){let t=`${Ss}/${e.datasetId}`,n=await Qg({token:e.token,base:e.base,datasetId:e.datasetId,state:"open"});if(!n.ok)throw new N("github-unreadable",`GitHub's open pull requests of ${t} could not be read whole (${Xg(n)}).`);let r=n.pulls,o=`release/v${e.version}`,s=r.filter((c)=>c.headRef.startsWith("release/")),i=s.filter((c)=>c.headRef===o&&yd(c.headRepo,e.datasetId)),a=s.filter((c)=>!i.includes(c));if(a.length>0||i.length>1)throw new N("release-pr-open",`Another release pull request is open on ${t} (#${(a[0]??i[1])?.number}); a re-pull's pull request is never open beside another.`);return i[0]??null}async function tR(e){let t=`release/v${e.version}`,n=await hEt(e);if(n){let c=n.baseRef==="main"?await e.acceptHead(n.headSha):"foreign";if(c==="unreadable")throw new N("pr-unreadable",`Whether the open pull request of ${t} (#${n.number}) is at this re-pull's commit could not be read from the working clone.`);if(c!=="ok")throw new N("pr-foreign",`The open pull request of ${t} (#${n.number}) is not into main at this re-pull's commit.`);return{number:n.number,head:n.headSha,reused:!0}}let r=Gw(e.version),o=XD(r);if(o)throw new N("pr-title",`The title would be refused: ${o.reason}.`);let s=await mEt(`${e.base}/repos/${Ss}/${e.datasetId}/pulls`,{method:"POST",token:e.token,body:{title:r,head:t,base:"main",body:e.body,maintainer_can_modify:!1}});if(!s||s.status>=500)throw new N("pr-create-unknown",`GitHub did not say whether the pull request of ${t} was opened${s?` (HTTP ${s.status})`:""}; the next run looks for it before opening one.`);let i=s.status===201?nM(s.body):null;if(s.status===201&&!i)throw new N("pr-created-unreadable",`GitHub opened the pull request of ${t} (HTTP 201) but its answer could not be read; the next run looks for it before opening one.`);if(!i){let c=typeof s.body==="object"&&s.body!==null&&"message"in s.body?qi(s.body.message,160):"";throw new N("pr-create-refused",`GitHub refused to open the pull request of ${t} (HTTP ${s.status}${c?`: ${c}`:""}).`)}let a=i.headRef===t&&i.baseRef==="main"?await e.acceptHead(i.headSha):"foreign";if(a==="unreadable")throw new N("pr-unreadable",`GitHub opened pull request #${i.number}, but whether it is at this re-pull's commit could not be read from the working clone.`);if(a!=="ok")throw new N("pr-foreign",`GitHub opened pull request #${i.number}, but not of ${t} into main at this re-pull's commit.`);return{number:i.number,head:i.headSha,reused:!1}}function mve(e){let t=(n)=>typeof e.counts[n]==="number"?String(e.counts[n]):"unknown";return[`Re-pull of upstream ${e.ds} from snapshot ${e.fromTag} to ${e.toTag}, as v${e.toVersion} of ${e.datasetId} (ADR 0111).`,"",`This pull request replays upstream's snapshot ${e.ds}@${e.toTag} onto NEMAR's main as one synthesized commit, scrubbed before anything was copied or pushed. Upstream wins every conflict in v${e.toVersion}${e.patchVersion?`; NEMAR's corrections follow as v${e.patchVersion} once this is merged and tagged`:""}.`,"",`- Re-pull record: #${e.repullId}`,`- Plan digest: ${e.digest}`,`- Delta paths: ${t("delta_paths")} (written ${t("written")}, deleted ${t("deleted")})`,`- Keys copied from upstream by version: ${t("annex_copy_items")}; uploaded from the administrator's machine: ${t("local_uploads")}`,`- Recording headers scrubbed: ${t("scrubbed_recordings")}; acquisition dates set: ${t("dated_recordings")}; JSON files blanked: ${t("scrubbed_json")}`,`- Version DOIs the re-pull mints when merged: ${e.doiCount}`,"",`\`nemar admin repull execute\` never merges. \`nemar admin repull resume ${e.datasetId}\` takes this pull request through the identifier screen and the gates, and \`nemar admin repull merge ${e.datasetId}\` (or \`nemar admin pr-reviews\`, through the same gate) squash-merges it under the daily merge cap; a merge mints a version DOI that cannot be withdrawn.`,"","The squash commit message must end with both trailers of the re-pull commit, as its last paragraph; the merge path writes that message itself and refuses one that does not:","","```",`Upstream-Snapshot: ${e.ds}@${e.toTag}`,`Repull-Plan: ${e.digest}`,"```","","GitHub's default squash message lists each commit as a bullet, which puts the trailers mid-message; the privacy ledger's fresh-clone proof (ADR 0085) then fails the dataset. Do not merge this from GitHub's page."].join(`
|
|
390
390
|
`)}$d();ep();Dg();import{join as DEt}from"path";import{join as SEt}from"path";$d();import{tmpdir as gEt}from"os";qt();async function Al(e,t){let n=await R(["git","interpret-trailers","--parse","--no-divider"],{cwd:gEt(),stdin:e,env:{...wp}});if(n.exitCode!==0)return"git could not read the message's trailers";let r=n.stdout.split(`
|
|
@@ -406,18 +406,18 @@ ${s}
|
|
|
406
406
|
|
|
407
407
|
`);if(i<0)throw on("synthesis-mismatch","N.0.1's commit has no message.");let a=$M(s.slice(0,i)),c=s.slice(i+2),l=new Map((await Ps(t,o)).map((y)=>[y.path,y])),d=new Map((await Ps(t,n)).map((y)=>[y.path,y])),f=new Map((await Ps(t,r)).map((y)=>[y.path,y])),p=(y,b)=>y?.mode===b?.mode&&y?.oid===b?.oid,m=new Set;for(let y of new Set([...l.keys(),...d.keys()]))if(!p(l.get(y),d.get(y)))m.add(y);for(let y of m){if(!p(l.get(y),f.get(y)))throw on("patch-main-moved","NEMAR's main moved by enrichment on a path N.0.1 replays, so N.0.1 is not made again on it; decline N.0.1 (nemar admin repull abandon) and correct the dataset by hand.");let b=d.get(y);if(b)f.set(y,b);else f.delete(y)}let h=await Pve(t,[...f.values()],"patch-again.index");return{sha:await Ive(t,h,r,c,a),tree:h}}async function Fve(e){let{dir:t,row:n}=e,r=e.head;for(let o=0;o<=_p;o++){let s=await CM(t,r);if(!s)return null;if((await _c(t,n.patch_base_sha,s)).ok)try{let i=await AM({dir:t,commit:e.recorded,newMain:s});if(i.sha===r)return(await _c(t,r,e.head)).ok?{sha:r,tree:i.tree,baseSha:s}:null}catch(i){if(!(i instanceof N))throw i}r=s}return null}var sn=(e,t)=>({ok:!1,stage:e,reason:t});async function qEt(e,t){let n;for(let r=0;r<20;r++){let o=await Io({dataset:e,limit:50,after:n});for(let s of o.repulls){if(s.pr_number===t)return{row:s,pr:"n0"};if(s.patch_pr_number===t)return{row:s,pr:"n1"}}if(o.next_after===null)return null;n=o.next_after}throw Error("the re-pull records of this dataset could not be read to the end")}async function OM(e){if(e.headRef==="")return{kind:"refused",reason:"GitHub's answer did not name the pull request's head branch, so whether it is an upstream re-pull's cannot be told, and a re-pull's merges only through its gate."};if(!e.headRef.startsWith("release/"))return{kind:"ordinary"};let t;try{t=await qEt(e.datasetId,e.prNumber)}catch(o){return{kind:"refused",reason:`Could not tell whether this is an upstream re-pull's pull request (the NEMAR API answered ${kp(o)}), and a re-pull's merges only through its gate.`}}if(!t)return{kind:"ordinary"};let n={datasetId:e.datasetId,token:e.token,base:e.base,env:e.env,configDir:e.configDir,force:e.force},r=await TM(n,{row:t.row,prNumber:e.prNumber});if(!r.ok)return{kind:"refused",reason:`This is upstream re-pull #${t.row.id}'s pull request, which merges only through its gate, and the gate refuses (${r.stage}): ${r.reason}`};return{kind:"repull",ctx:n,check:r.check}}function BEt(e,t,n="n0"){return A0e(e,t,n,"gate")}async function Mve(e,t,n){let r,o="not_reviewed",s=null;try{let i=k$(await cg(e,t,n),n);if(i.ok)o=i.verdict,s=i.staleVerdict;else r=i.why}catch(i){let a=An(i);if(a==="not_owned_here"||a==="github_unavailable"||a==="no_such_pull_request")r=i instanceof Error?i.message:"the NEMAR API did not answer";else return sn("review",`The automated review of ${n.slice(0,12)} could not be read (${i instanceof L?`HTTP ${i.statusCode}`:"no answer"}); nothing was claimed or merged.`)}return E$({verdict:o,staleVerdict:s,unread:r})}async function TM(e,t){return Fd(()=>UEt(e,t))}async function UEt(e,t){let n=e.datasetId,r;try{r=t?await P$(t.row.id):(await Io({dataset:n,open:!0,limit:1})).repulls[0]??null}catch(x){return sn("not-ready",`The re-pull record could not be read (${kp(x)}).`)}if(!r)return sn("not-ready",`${n} has no open re-pull.`);let o=t?r.pr_number===t.prNumber?"n0":r.patch_pr_number===t.prNumber?"n1":null:S0e(r.status);if(t&&o===null)return sn("not-ready",`Pull request #${t.prNumber} is not one of re-pull #${r.id}'s pull requests.`);let s=o??"n0",i=Tr[s];if(r.status!==i.gatesClear)return sn("not-ready",r.status==="pr_open"||r.status==="patch_synthesized"?`Re-pull #${r.id}'s gates are not recorded: run nemar admin repull resume ${n} (the identifier screen and GitHub's state).`:`Re-pull #${r.id} is ${r.status}; its ${s==="n0"?"N.0.0":"N.0.1"} pull request is merged only from ${i.gatesClear}.`);let a=r[i.number],c=r[i.gates],l=r[i.branch],d=s==="n0"?r.base_sha:r.patch_base_sha;if(e.bidsFailureReason!==void 0&&r.origin!=="administrator")return sn("bids",`Re-pull #${r.id} was opened by the automatic path, and its pull request is not merged over a failed BIDS validation; nothing was claimed or merged. Merge it once BIDS validation passes, or abandon it (nemar admin repull abandon ${n}) and re-pull it by hand.`);try{El(await ac(n))}catch(x){return sn("not-ready",x instanceof Error?x.message:String(x))}let f=await Bi(e.token,n,a,e.base);if(!f.ok)return sn("github",`Pull request #${a} could not be read: ${f.reason}`);if(f.value.state!=="open")return sn("not-ready",`Pull request #${a} is ${f.value.state}; run nemar admin repull resume ${n}, which records it.`);if(f.value.draft)return sn("not-ready",`Pull request #${a} is a draft.`);if(f.value.baseRef!=="main"||f.value.headRef!==l)return sn("not-ready",`Pull request #${a} is not ${l} into main.`);if(!yd(f.value.headRepo,n)||!yd(f.value.baseRepo,n))return sn("not-ready",`Pull request #${a} is not from and into ${Ss}/${n} itself (its head is ${f.value.headRepo??"a repository GitHub no longer names"}, its base ${f.value.baseRepo??"a repository GitHub no longer names"}): a fork's pull request is never merged as a re-pull's. Nothing was claimed or merged.`);if(f.value.headSha!==c)return sn("not-ready",`Pull request #${a} is at ${f.value.headSha.slice(0,12)}, not the screened ${c.slice(0,12)}: run nemar admin repull resume ${n}.`);let p=await Dl({configDir:e.configDir,datasetId:n,digest:r.plan_digest,purpose:"merge",env:e.env,token:e.token});try{let x=await Cl({work:p.dir,baseSha:d,env:p.env});if(x!==d){let k=await zw(p.dir,d,x);if(k===null)return sn("github","Whether NEMAR's main moved outside .nemar/ and .github/ since the gates could not be read; nothing was claimed or merged.");if(k.length>0)return sn("merge-main-moved",`NEMAR's main moved by enrichment since the gates, on ${k.length} path(s) outside .nemar/ and .github/, so the squash would tag a tree the gates did not clear; nothing was claimed or merged. Run nemar admin repull resume ${n}: it makes the commit again on the new main, whose screen and gates run again.`)}}catch(x){if(x instanceof N&&x.code==="main-moved")return sn("main-moved",`${x.message} Nothing was claimed or merged.`);return sn("github",x instanceof Error?x.message:String(x))}finally{p.close()}let m=await Mve(n,a,c);if("ok"in m)return m;if(m.kind==="needs_force"&&!e.force)return sn("review",m.reason);let h=m.kind==="confirm"?[m.warning]:m.kind==="needs_force"?["Merging anyway (--force): the automated review failed, is running or was not read."]:[],g;try{g=await kg(r.id)}catch(x){return sn("screen",`The identifier screen could not be read (${kp(x)}).`)}if(!g.exempt){let x=g.screens.find((v)=>v.pr===s&&v.sha===c);if(!(x!==void 0&&(x.gate==="clear"||x.gate==="acknowledge"&&x.acknowledged_at!==null)))return sn("screen",`${x?x.headline:"No identifier screen of this head is recorded"}; run nemar admin repull resume ${n}.`)}if(e.bidsFailureReason!==void 0){let x=await HEt(e,a,c,f.value.mergeableState);if(x)return x}else{let x=await xg(e.token,n,a,{headSha:c,mergeableState:f.value.mergeableState},{base:e.base,...e.sleep?{sleep:e.sleep}:{}});if(!x.ok)return sn("github",`${x.why} Nothing was claimed or merged.`)}let y=r.counts?.corrections;if(s==="n1"&&(typeof y!=="number"||!Number.isSafeInteger(y)||y<0))return sn("message",`Re-pull #${r.id} does not state how many corrections N.0.1 replays, so its squash message would not carry ${iR}:; nothing was claimed or merged.`);let b=BEt(r,a,s),_=await Al(`${b.title}
|
|
408
408
|
|
|
409
|
-
${b.message}`,r);if(_)return sn("message",`The squash message would not carry the re-pull's trailers: ${_}.`);return{ok:!0,check:{row:r,pr:s,version:r[i.version],prNumber:a,head:c,squash:b,heldClaim:r[i.claimSha]===c,warnings:h}}}async function HEt(e,t,n,r){let o=await _g(e.token,e.datasetId,t,{headSha:n,mergeableState:r},{base:e.base,...e.sleep?{sleep:e.sleep}:{}});if(!o.ok){if(o.kind==="unreadable")return sn("github",`Pull request #${t} could not be read: ${o.reason} Nothing was claimed or merged.`);return sn("not-ready",o.kind==="moved"?`Pull request #${t} changed since it was read; run the merge again. Nothing was claimed or merged.`:`Pull request #${t} is no longer open; nothing was claimed or merged.`)}if(o.state==="unstable")return null;if(o.state==="blocked")return sn("bids","GitHub reports the pull request blocked: this dataset's rules require BIDS validation, and merging would be a bypass, which a re-pull never uses. Nothing was claimed or merged.");if(o.state==="clean")return sn("bids","GitHub reports the pull request clean, so no check fails: merge it without --bids-failure-reason. Nothing was claimed or merged.");let s=wg(o.state);return sn("github",`${s.ok?"GitHub's state is not unstable.":s.why} Nothing was claimed or merged.`)}function kp(e){return e instanceof L?`HTTP ${e.statusCode}`:e instanceof Error?e.message:String(e)}function aR(e,t="n0"){return`This merge mints one irreversible version DOI, v${e[Tr[t].version]}, and takes one unit of today's re-pull merge cap.`}async function Yw(e,t,n){let{row:r,prNumber:o}=t,s=await Mve(e.datasetId,o,t.head);if("ok"in s)return{merged:!1,stage:s.stage,reason:s.reason};if(s.kind==="needs_force"&&!e.force)return{merged:!1,stage:"review",reason:s.reason};if(n.confirm){let c=[aR(r,t.pr),...t.warnings];if(!await n.confirm(`${c.join(" ")} Merge pull request #${o} of ${e.datasetId}?`))return{merged:!1,stage:"declined",reason:"Not confirmed; nothing was claimed or merged."}}let i=wc(e.configDir,e.datasetId,r.plan_digest);wo(jEt(i.lock),LEt(e.configDir,"repull"));let a;try{a=$l(i.lock)}catch(c){if(!(c instanceof N))throw c;return{merged:!1,stage:"not-ready",reason:`${c.message} A resume or an execution of re-pull #${r.id} runs now; nothing was claimed or merged.`}}try{return await WEt(e,t,n)}finally{a()}}function zEt(e,t){let n=An(e);if(!(e instanceof L)||e.statusCode===0||e.statusCode>=500)return{merged:!1,stage:"github",claimHeld:!0,reason:`The claim to merge got no usable answer (${kp(e)}), so a claim may be held. Nothing was merged. nemar admin repull resume ${t} reads the record, and expires a claim nothing merged under once it is 30 minutes old.`};let r=`The claim to merge was refused (${n??kp(e)}): ${e.message} Nothing was merged.`;if(n==="merge-cap"||n==="merge-cap-unreadable")return{merged:!1,stage:"cap",reason:r};if(n==="screen-not-clear"||n==="screen-changed")return{merged:!1,stage:"screen",reason:r};if(n?.startsWith("bids-override-"))return{merged:!1,stage:"bids",reason:r};return{merged:!1,stage:"not-ready",reason:r}}function VEt(e,t){let n=An(e),r=e instanceof Error?e.message:String(e);return{merged:!1,stage:n==="screen-not-clear"?"screen":!(e instanceof L)||e.statusCode===0||e.statusCode>=500||n==="github-unreadable"?"github":"not-ready",claimHeld:!0,reason:`The claim to merge already held was not used (${n??kp(e)}): ${r} Nothing was merged. nemar admin repull resume ${t} reads GitHub, records a merge that happened, and expires the claim once it is 30 minutes old.`}}function GEt(e){if(e.outcome==="refused")return`GitHub refused the merge: ${e.reason}`;if(e.merge)return e.merge.why;return e.status===409?"The pull request changed after the gate read it (its head moved, or it was closed), so the merge was not sent.":`GitHub could not be read at the last look before the merge (${e.status===0?"no answer":`HTTP ${e.status}`}), so the merge was not sent.`}async function WEt(e,t,n){let{row:r,prNumber:o,head:s,pr:i}=t,a=Tr[i],c=e.bidsFailureReason;if(c!==void 0&&t.heldClaim)return{merged:!1,stage:"bids",claimHeld:!0,reason:`A claim to merge ${s.slice(0,12)} is already held, and a merge over a failed BIDS validation is sent only under a claim of its own, which records its reason. Nothing was merged. nemar admin repull resume ${e.datasetId} records a merge that happened, or expires the claim once it is 30 minutes old; then run this again.`};if(!t.heldClaim){try{await Zn(r.id,{from:a.gatesClear,to:a.gatesClear,fields:{[a.claimSha]:s},...c!==void 0?{override:{kind:"bids-failure",reason:c}}:{}})}catch(d){return zEt(d,e.datasetId)}if(n.out(`Claimed one unit of today's re-pull merge cap for ${s.slice(0,12)}.`),c!==void 0)n.out("Recorded with the claim: the merge is over a failed BIDS validation, and why.")}else{try{await M0e(r.id,{pr:i,sha:s})}catch(d){return VEt(d,e.datasetId)}n.out(`A claim to merge ${s.slice(0,12)} is already held; the merge is sent again under it.`)}let l=await ow(e.token,e.datasetId,o,s,"squash",{base:e.base,commit:t.squash,...c!==void 0?{state:"unstable"}:{},...e.sleep?{sleep:e.sleep}:{},...n.tries!==void 0?{tries:n.tries}:{}});if(l.ok)try{let d=await I$(r.id,i);return{merged:!0,row:d.repull,mergeSha:d.repull[a.mergeSha],recorded:!0}}catch(d){return n.out(`GitHub merged pull request #${o}, and the merge could not be recorded yet (${An(d)??kp(d)}); nemar admin repull resume ${e.datasetId} records it.`),{merged:!0,row:r,mergeSha:null,recorded:!1}}if(l.outcome==="unknown"||l.outcome==="different")return{merged:!1,stage:"github",outcome:l.outcome,claimHeld:!0,reason:`${l.reason} GitHub may have merged it: the claim is kept, and nemar admin repull resume ${e.datasetId} reads GitHub and records the merge.`};return{merged:!1,stage:"github",outcome:l.outcome,claimHeld:!0,reason:`${GEt(l)} The claim to merge is kept: run nemar admin repull merge ${e.datasetId} again within 25 minutes of the claim to send the merge under it, once GitHub reports the pull request clean at the same head; if the head moved, nemar admin repull resume ${e.datasetId} expires the claim once it is 30 minutes old and then records the new head.`}}Ke();dn();import{dirname as kSt,join as ESt}from"path";gr();ml();var{spawn:jve}=globalThis.Bun;var lR=1048576,KEt=1024*lR,Htn=5*lR,ztn=8*lR,Vtn=5*lR,Lve=4*KEt,qve=1e4;var JEt={failed:1,usage:2,refused:3,unreadable:4,remainder:5};class Bve extends Error{word;exitCode;constructor(e,t=JEt.failed){super(e);this.word=e;this.exitCode=t;this.name="StageError"}}class Bt extends Error{code;op;constructor(e,t){super(`${t}:${e}`);this.code=e;this.op=t;this.name="AwsCliError"}}var YEt={AccessDenied:"access-denied","403":"access-denied",NoSuchKey:"not-found",NoSuchVersion:"not-found",NoSuchObjectLockConfiguration:"not-found",NotFound:"not-found","404":"not-found",NoSuchUpload:"no-such-upload",PreconditionFailed:"precondition-failed","412":"precondition-failed",ConditionalRequestConflict:"precondition-failed",InvalidRange:"invalid-range","416":"invalid-range",SlowDown:"throttled",Throttling:"throttled",ThrottlingException:"throttled",RequestLimitExceeded:"throttled","503":"throttled",ExpiredToken:"credentials",InvalidAccessKeyId:"credentials",InvalidToken:"credentials",SignatureDoesNotMatch:"credentials","401":"credentials"};function XEt(e,t){return new Bt(YEt[e]??"failed",t)}function QEt(e,t){let n=/An error occurred \(([A-Za-z0-9]+)\) when calling the (\w+) operation/.exec(e);if(n)return XEt(n[1],n[2]);if(/Could not connect to the endpoint URL|Connection was closed|Read timeout/.test(e))return new Bt("unreachable",t);if(/Unable to locate credentials|SSO session|token has expired/i.test(e))return new Bt("credentials",t);return new Bt("failed",t)}function jd(e){if(e instanceof Bve)return e.word;if(e instanceof Bt)return`${e.op}:${e.code}`;return"unexpected"}var cR=new Set;var uR=120000,ZEt=5;function dR(e={}){let t=e.command??["aws","configure","export-credentials","--format","process"],n=e.skewMs??120000,r=e.now??Date.now,o=e.timeoutMs??60000,s,i;async function a(){let c;try{c=jve({cmd:t,...e.commandEnv?{env:e.commandEnv}:{},stdout:"pipe",stderr:"ignore"})}catch{throw new Bt("credentials","ExportCredentials")}cR.add(c);let l=setTimeout(()=>c.kill("SIGKILL"),o),d,f;try{[d,f]=await Promise.all([new Response(c.stdout).text(),c.exited])}finally{clearTimeout(l),cR.delete(c)}if(f!==0)throw new Bt("credentials","ExportCredentials");let p;try{p=JSON.parse(d)}catch{throw new Bt("bad-output","ExportCredentials")}let m=typeof p.AccessKeyId==="string"?p.AccessKeyId:"",h=typeof p.SecretAccessKey==="string"?p.SecretAccessKey:"",g=typeof p.SessionToken==="string"?p.SessionToken:"";if(!m||!h)throw new Bt("bad-output","ExportCredentials");if(!m.startsWith("ASIA")||!g)throw new Bt("long-lived-credentials","ExportCredentials");let y=typeof p.Expiration==="string"?Date.parse(p.Expiration):Number.NaN,b={AWS_ACCESS_KEY_ID:m,AWS_SECRET_ACCESS_KEY:h,AWS_SESSION_TOKEN:g};return s={env:b,expiresAt:Number.isFinite(y)?y:r()+n*2},b}return{async env(){if(s&&s.expiresAt-n>r())return s.env;return i??=a().finally(()=>{i=void 0}),i}}}var eSt="when_supported";function fR(e){let t={};for(let[n,r]of Object.entries(e.env??process.env))if(r!==void 0)t[n]=r;if(t.AWS_PAGER="",t.AWS_REQUEST_CHECKSUM_CALCULATION=eSt,e.endpointUrl)t.AWS_ENDPOINT_URL_S3=e.endpointUrl;return{async api(n,r,o={}){let s=n.split("-").map((p)=>p.charAt(0).toUpperCase()+p.slice(1)).join(""),i=["aws","s3api",n,...r,"--region",e.region,"--output","json"],a=e.credentials?await e.credentials.env():{},c;try{c=jve({cmd:i,env:{...t,...a},stdout:"pipe",stderr:"pipe"})}catch{throw new Bt("spawn-failed",s)}cR.add(c);let l=e.timeoutMs*(o.slow?ZEt:1),d=!1,f=setTimeout(()=>{d=!0,c.kill("SIGKILL")},l);try{let[p,m,h]=await Promise.all([new Response(c.stdout).text(),new Response(c.stderr).text(),c.exited]);if(d)throw new Bt("timeout",s);if(h!==0)throw QEt(m,s);let g=p.trim();if(g==="")return{};try{let y=JSON.parse(g);if(typeof y!=="object"||y===null||Array.isArray(y))throw new Bt("bad-output",s);return y}catch(y){if(y instanceof Bt)throw y;throw new Bt("bad-output",s)}}finally{clearTimeout(f),cR.delete(c)}}}}async function Uve(e,t,n,r=()=>!1){let o=Array(e.length).fill(void 0),s=0,i=async()=>{while(s<e.length&&!r()){let a=s++;o[a]=await n(e[a],a)}};return await Promise.all(Array.from({length:Math.max(1,t)},i)),o}lo();import{chmodSync as tSt,rmSync as nSt,writeFileSync as rSt}from"fs";import{join as oSt}from"path";cs();var sSt=5368709120,zve="us-east-1",iSt=8;function pR(e,t){return`${e}/staging/repull-${t}.json`}var Ol=(e)=>typeof e==="string"?e:void 0;async function Ld(e,t,n){let r=new Map,o=new Set,s=null;for(;;){let i=await e.api("list-objects-v2",["--bucket",t,"--prefix",n,"--max-keys","1000","--no-paginate",...s?["--continuation-token",s]:[]]),a=i.Contents;if(a!==void 0&&!Array.isArray(a))throw new Bt("bad-output","ListObjectsV2");for(let c of a??[]){let l=Ol(c.Key);if(l===void 0||typeof c.Size!=="number")throw new Bt("bad-output","ListObjectsV2");if(l.startsWith(n)&&l.length>n.length)r.set(l.slice(n.length),c.Size)}if(i.IsTruncated!==!0)return r;if(s=Ol(i.NextContinuationToken)??null,!s||o.has(s))throw new Bt("bad-output","ListObjectsV2");o.add(s)}}async function Vve(e){let t=oSt(e.dir,"staging-manifest.json");rSt(t,uc(e.manifest),{mode:384}),tSt(t,384);try{await e.aws.api("put-object",["--bucket",e.bucket,"--key",e.key,"--body",t,"--content-type","application/json"])}finally{nSt(t,{force:!0})}}async function Hve(e,t,n,r){let o;try{o=await e.api("head-object",["--bucket",t,"--key",n,...r?["--version-id",r]:[]])}catch(i){if(i instanceof Bt&&i.code==="not-found")return null;throw i}let s=Ol(o.ETag);if(typeof o.ContentLength!=="number"||s===void 0)throw new Bt("bad-output","HeadObject");return{size:o.ContentLength,etag:s,versionId:Ol(o.VersionId)}}function aSt(e){return`${e.bucket}/${e.object}?versionId=${e.version}`}function cSt(e,t){return Math.max(t,Math.ceil(e/qve))}async function lSt(e){let{aws:t,bucket:n,key:r}=e,o=await t.api("create-multipart-upload",["--bucket",n,"--key",r]),s=Ol(o.UploadId);if(!s)throw new Bt("bad-output","CreateMultipartUpload");try{let i=cSt(e.size,e.partBytes),a=[];for(let c=0,l=1;c<e.size;c+=i,l++){let d=Math.min(c+i,e.size)-1,f=await t.api("upload-part-copy",["--bucket",n,"--key",r,"--upload-id",s,"--part-number",String(l),"--copy-source",e.source,"--copy-source-range",`bytes=${c}-${d}`,"--copy-source-if-match",e.etag],{slow:!0}),p=f.CopyPartResult,m=p?Ol(p.ETag):void 0;if(!m)throw new Bt("bad-output","UploadPartCopy");if(Ol(f.CopySourceVersionId)!==e.version)throw new N("pin-version-mismatch",`S3 copied part ${l} of a multipart copy from another version than the pinned one`);a.push({ETag:m,PartNumber:l})}await t.api("complete-multipart-upload",["--bucket",n,"--key",r,"--upload-id",s,"--multipart-upload",JSON.stringify({Parts:a})],{slow:!0})}catch(i){try{await t.api("abort-multipart-upload",["--bucket",n,"--key",r,"--upload-id",s])}catch{e.open.push({key:r,uploadId:s})}throw i}}async function uSt(e,t,n,r){let o=Ol(r.VersionId);if(o===void 0)return!1;try{return await e.api("delete-object",["--bucket",t,"--key",n,"--version-id",o]),!0}catch{return!1}}function dSt(e){if(e instanceof N)return e;if(e instanceof Ye)return new N("write-refused",e.message);if(e instanceof Bt){if(e.op==="CopyObject"||e.op==="UploadPartCopy"){if(e.code==="not-found")return new N("pin-absent","a pinned upstream version is no longer served");if(e.code==="precondition-failed")return new N("pin-changed","a pinned upstream version changed its ETag")}return new N("copy-failed",`an S3 call failed (${jd(e)})`)}return new N("copy-failed",`a copy failed (${e instanceof Error?e.name:"error"})`)}async function Gve(e){let t=e.singleCopyMax??sSt,n=e.partBytes??Lve,r=0,o=0,s=0,i=[],a=[],c=e.manifest.items;if(await Uve(c,e.concurrency??iSt,async(l)=>{try{let d=No(l.key),f=e.existing.get(l.key);if(d!==null&&f===d){o++;return}let p=await Hve(e.aws.source,l.bucket,l.object,l.version);if(!p)throw new N("pin-absent","a pinned upstream version is not served");if(p.versionId!==l.version)throw new N("pin-version-mismatch","upstream answered for another version than the pinned one, or for none");if(d!==null&&p.size!==d)throw new N("pin-size-mismatch","a pinned upstream version is not the size its key declares");if(d===null&&f===p.size){o++;return}let m=`${e.prefix}${l.key}`,h=aSt(l);if(p.size<=t){let y=await e.aws.dest.api("copy-object",["--bucket",e.destBucket,"--key",m,"--copy-source",h,"--copy-source-if-match",p.etag],{slow:!0});if(Ol(y.CopySourceVersionId)!==l.version){let b=await uSt(e.aws.dest,e.destBucket,m,y);throw new N("pin-version-mismatch",b?"S3 copied from another version than the pinned one; the copy was removed":"S3 copied from another version than the pinned one and the copy could not be removed: delete it by hand before a rerun")}}else await lSt({aws:e.aws.dest,source:h,version:l.version,etag:p.etag,size:p.size,bucket:e.destBucket,key:m,partBytes:n,open:a});let g=await Hve(e.aws.dest,e.destBucket,m);if(!g||g.size!==p.size)throw new N("copy-size-mismatch","a copied object is not the size of the version it was copied from");r++,s+=p.size}catch(d){i.push(dSt(d))}},()=>i.length>0),i.length>0){let l=i[0],d=a.length>0?` ${a.length} multipart upload(s) could not be aborted and stay open (abort them with abort-multipart-upload): ${a.map((f)=>f.uploadId).join(", ")}.`:"";throw new N(l.code,`The copy stopped: ${l.message}; ${i.length} of ${c.length} item(s) refused, ${r} copied and ${o} already present this run. Nothing is registered for a partial copy, and a rerun skips what landed.${d}`)}return{copied:r,skipped:o,bytes:s}}import{createHash as fSt}from"crypto";import{readFileSync as pSt}from"fs";import{join as mSt}from"path";Za();ec();Ke();Ke();function fs(e,t){if(t instanceof N)return`[${e}:${t.code}] ${t.message}`.slice(0,2000);let n=t instanceof Error?t.name:"unknown";return`[${e}:${e}-failed] The step failed (${n}).`}function Pt(e,t){let n=new N(e,t);return n.resumable=!0,n}function Qr(e,t){let n=An(e)??(e instanceof L?"record-refused":"github-failed"),r=e instanceof Error?e.message:String(e);return Pt(n,`${t}: ${r}`)}function PM(e){if(e.status==="pr_open")return{branch:e.branch,pr_number:e.pr_number,head_sha:e.head_sha};if(e.status==="patch_synthesized")return{patch_version:e.patch_version,patch_branch:e.patch_branch,patch_pr_number:e.patch_pr_number,patch_head_sha:e.patch_head_sha,patch_base_sha:e.patch_base_sha};return{}}async function Zr(e,t,n){let r=PM(e);try{await Zn(e.id,{from:e.status,to:e.status,fields:r,error:t})}catch(o){n(`The failure could not be recorded on re-pull #${e.id} (${An(o)??(o instanceof L?`HTTP ${o.statusCode}`:"no answer")}); its record keeps the last error it had.`)}}async function Wve(e,t){let n=await te(e,["ls-tree","-r","-z","--full-tree",t],{ok:!0});if(n.exitCode!==0)return null;return n.stdout.split("\x00").filter(Boolean).map((r)=>/^(\d{6}) [a-z]+ ([0-9a-f]{40})\t(.+)$/s.exec(r)).filter((r)=>r!==null).filter((r)=>!r[3].startsWith(".nemar/")&&!r[3].startsWith(".github/")).map((r)=>`${r[1]} ${r[2]} ${r[3]}`).sort().join(`
|
|
409
|
+
${b.message}`,r);if(_)return sn("message",`The squash message would not carry the re-pull's trailers: ${_}.`);return{ok:!0,check:{row:r,pr:s,version:r[i.version],prNumber:a,head:c,squash:b,heldClaim:r[i.claimSha]===c,warnings:h}}}async function HEt(e,t,n,r){let o=await _g(e.token,e.datasetId,t,{headSha:n,mergeableState:r},{base:e.base,...e.sleep?{sleep:e.sleep}:{}});if(!o.ok){if(o.kind==="unreadable")return sn("github",`Pull request #${t} could not be read: ${o.reason} Nothing was claimed or merged.`);return sn("not-ready",o.kind==="moved"?`Pull request #${t} changed since it was read; run the merge again. Nothing was claimed or merged.`:`Pull request #${t} is no longer open; nothing was claimed or merged.`)}if(o.state==="unstable")return null;if(o.state==="blocked")return sn("bids","GitHub reports the pull request blocked: this dataset's rules require BIDS validation, and merging would be a bypass, which a re-pull never uses. Nothing was claimed or merged.");if(o.state==="clean")return sn("bids","GitHub reports the pull request clean, so no check fails: merge it without --bids-failure-reason. Nothing was claimed or merged.");let s=wg(o.state);return sn("github",`${s.ok?"GitHub's state is not unstable.":s.why} Nothing was claimed or merged.`)}function kp(e){return e instanceof L?`HTTP ${e.statusCode}`:e instanceof Error?e.message:String(e)}function aR(e,t="n0"){return`This merge mints one irreversible version DOI, v${e[Tr[t].version]}, and takes one unit of today's re-pull merge cap.`}async function Yw(e,t,n){let{row:r,prNumber:o}=t,s=await Mve(e.datasetId,o,t.head);if("ok"in s)return{merged:!1,stage:s.stage,reason:s.reason};if(s.kind==="needs_force"&&!e.force)return{merged:!1,stage:"review",reason:s.reason};if(n.confirm){let c=[aR(r,t.pr),...t.warnings];if(!await n.confirm(`${c.join(" ")} Merge pull request #${o} of ${e.datasetId}?`))return{merged:!1,stage:"declined",reason:"Not confirmed; nothing was claimed or merged."}}let i=wc(e.configDir,e.datasetId,r.plan_digest);wo(jEt(i.lock),LEt(e.configDir,"repull"));let a;try{a=$l(i.lock)}catch(c){if(!(c instanceof N))throw c;return{merged:!1,stage:"not-ready",reason:`${c.message} A resume or an execution of re-pull #${r.id} runs now; nothing was claimed or merged.`}}try{return await WEt(e,t,n)}finally{a()}}function zEt(e,t){let n=An(e);if(!(e instanceof L)||e.statusCode===0||e.statusCode>=500)return{merged:!1,stage:"github",claimHeld:!0,reason:`The claim to merge got no usable answer (${kp(e)}), so a claim may be held. Nothing was merged. nemar admin repull resume ${t} reads the record, and expires a claim nothing merged under once it is 30 minutes old.`};let r=`The claim to merge was refused (${n??kp(e)}): ${e.message} Nothing was merged.`;if(n==="merge-cap"||n==="merge-cap-unreadable")return{merged:!1,stage:"cap",reason:r};if(n==="screen-not-clear"||n==="screen-changed")return{merged:!1,stage:"screen",reason:r};if(n?.startsWith("bids-override-"))return{merged:!1,stage:"bids",reason:r};return{merged:!1,stage:"not-ready",reason:r}}function VEt(e,t){let n=An(e),r=e instanceof Error?e.message:String(e);return{merged:!1,stage:n==="screen-not-clear"?"screen":!(e instanceof L)||e.statusCode===0||e.statusCode>=500||n==="github-unreadable"?"github":"not-ready",claimHeld:!0,reason:`The claim to merge already held was not used (${n??kp(e)}): ${r} Nothing was merged. nemar admin repull resume ${t} reads GitHub, records a merge that happened, and expires the claim once it is 30 minutes old.`}}function GEt(e){if(e.outcome==="refused")return`GitHub refused the merge: ${e.reason}`;if(e.merge)return e.merge.why;return e.status===409?"The pull request changed after the gate read it (its head moved, or it was closed), so the merge was not sent.":`GitHub could not be read at the last look before the merge (${e.status===0?"no answer":`HTTP ${e.status}`}), so the merge was not sent.`}async function WEt(e,t,n){let{row:r,prNumber:o,head:s,pr:i}=t,a=Tr[i],c=e.bidsFailureReason;if(c!==void 0&&t.heldClaim)return{merged:!1,stage:"bids",claimHeld:!0,reason:`A claim to merge ${s.slice(0,12)} is already held, and a merge over a failed BIDS validation is sent only under a claim of its own, which records its reason. Nothing was merged. nemar admin repull resume ${e.datasetId} records a merge that happened, or expires the claim once it is 30 minutes old; then run this again.`};if(!t.heldClaim){try{await Zn(r.id,{from:a.gatesClear,to:a.gatesClear,fields:{[a.claimSha]:s},...c!==void 0?{override:{kind:"bids-failure",reason:c}}:{}})}catch(d){return zEt(d,e.datasetId)}if(n.out(`Claimed one unit of today's re-pull merge cap for ${s.slice(0,12)}.`),c!==void 0)n.out("Recorded with the claim: the merge is over a failed BIDS validation, and why.")}else{try{await M0e(r.id,{pr:i,sha:s})}catch(d){return VEt(d,e.datasetId)}n.out(`A claim to merge ${s.slice(0,12)} is already held; the merge is sent again under it.`)}let l=await ow(e.token,e.datasetId,o,s,"squash",{base:e.base,commit:t.squash,...c!==void 0?{state:"unstable"}:{},...e.sleep?{sleep:e.sleep}:{},...n.tries!==void 0?{tries:n.tries}:{}});if(l.ok)try{let d=await I$(r.id,i);return{merged:!0,row:d.repull,mergeSha:d.repull[a.mergeSha],recorded:!0}}catch(d){return n.out(`GitHub merged pull request #${o}, and the merge could not be recorded yet (${An(d)??kp(d)}); nemar admin repull resume ${e.datasetId} records it.`),{merged:!0,row:r,mergeSha:null,recorded:!1}}if(l.outcome==="unknown"||l.outcome==="different")return{merged:!1,stage:"github",outcome:l.outcome,claimHeld:!0,reason:`${l.reason} GitHub may have merged it: the claim is kept, and nemar admin repull resume ${e.datasetId} reads GitHub and records the merge.`};return{merged:!1,stage:"github",outcome:l.outcome,claimHeld:!0,reason:`${GEt(l)} The claim to merge is kept: run nemar admin repull merge ${e.datasetId} again within 25 minutes of the claim to send the merge under it, once GitHub reports the pull request clean at the same head; if the head moved, nemar admin repull resume ${e.datasetId} expires the claim once it is 30 minutes old and then records the new head.`}}Je();dn();import{dirname as kSt,join as ESt}from"path";gr();ml();var{spawn:jve}=globalThis.Bun;var lR=1048576,KEt=1024*lR,Htn=5*lR,ztn=8*lR,Vtn=5*lR,Lve=4*KEt,qve=1e4;var JEt={failed:1,usage:2,refused:3,unreadable:4,remainder:5};class Bve extends Error{word;exitCode;constructor(e,t=JEt.failed){super(e);this.word=e;this.exitCode=t;this.name="StageError"}}class Bt extends Error{code;op;constructor(e,t){super(`${t}:${e}`);this.code=e;this.op=t;this.name="AwsCliError"}}var YEt={AccessDenied:"access-denied","403":"access-denied",NoSuchKey:"not-found",NoSuchVersion:"not-found",NoSuchObjectLockConfiguration:"not-found",NotFound:"not-found","404":"not-found",NoSuchUpload:"no-such-upload",PreconditionFailed:"precondition-failed","412":"precondition-failed",ConditionalRequestConflict:"precondition-failed",InvalidRange:"invalid-range","416":"invalid-range",SlowDown:"throttled",Throttling:"throttled",ThrottlingException:"throttled",RequestLimitExceeded:"throttled","503":"throttled",ExpiredToken:"credentials",InvalidAccessKeyId:"credentials",InvalidToken:"credentials",SignatureDoesNotMatch:"credentials","401":"credentials"};function XEt(e,t){return new Bt(YEt[e]??"failed",t)}function QEt(e,t){let n=/An error occurred \(([A-Za-z0-9]+)\) when calling the (\w+) operation/.exec(e);if(n)return XEt(n[1],n[2]);if(/Could not connect to the endpoint URL|Connection was closed|Read timeout/.test(e))return new Bt("unreachable",t);if(/Unable to locate credentials|SSO session|token has expired/i.test(e))return new Bt("credentials",t);return new Bt("failed",t)}function jd(e){if(e instanceof Bve)return e.word;if(e instanceof Bt)return`${e.op}:${e.code}`;return"unexpected"}var cR=new Set;var uR=120000,ZEt=5;function dR(e={}){let t=e.command??["aws","configure","export-credentials","--format","process"],n=e.skewMs??120000,r=e.now??Date.now,o=e.timeoutMs??60000,s,i;async function a(){let c;try{c=jve({cmd:t,...e.commandEnv?{env:e.commandEnv}:{},stdout:"pipe",stderr:"ignore"})}catch{throw new Bt("credentials","ExportCredentials")}cR.add(c);let l=setTimeout(()=>c.kill("SIGKILL"),o),d,f;try{[d,f]=await Promise.all([new Response(c.stdout).text(),c.exited])}finally{clearTimeout(l),cR.delete(c)}if(f!==0)throw new Bt("credentials","ExportCredentials");let p;try{p=JSON.parse(d)}catch{throw new Bt("bad-output","ExportCredentials")}let m=typeof p.AccessKeyId==="string"?p.AccessKeyId:"",h=typeof p.SecretAccessKey==="string"?p.SecretAccessKey:"",g=typeof p.SessionToken==="string"?p.SessionToken:"";if(!m||!h)throw new Bt("bad-output","ExportCredentials");if(!m.startsWith("ASIA")||!g)throw new Bt("long-lived-credentials","ExportCredentials");let y=typeof p.Expiration==="string"?Date.parse(p.Expiration):Number.NaN,b={AWS_ACCESS_KEY_ID:m,AWS_SECRET_ACCESS_KEY:h,AWS_SESSION_TOKEN:g};return s={env:b,expiresAt:Number.isFinite(y)?y:r()+n*2},b}return{async env(){if(s&&s.expiresAt-n>r())return s.env;return i??=a().finally(()=>{i=void 0}),i}}}var eSt="when_supported";function fR(e){let t={};for(let[n,r]of Object.entries(e.env??process.env))if(r!==void 0)t[n]=r;if(t.AWS_PAGER="",t.AWS_REQUEST_CHECKSUM_CALCULATION=eSt,e.endpointUrl)t.AWS_ENDPOINT_URL_S3=e.endpointUrl;return{async api(n,r,o={}){let s=n.split("-").map((p)=>p.charAt(0).toUpperCase()+p.slice(1)).join(""),i=["aws","s3api",n,...r,"--region",e.region,"--output","json"],a=e.credentials?await e.credentials.env():{},c;try{c=jve({cmd:i,env:{...t,...a},stdout:"pipe",stderr:"pipe"})}catch{throw new Bt("spawn-failed",s)}cR.add(c);let l=e.timeoutMs*(o.slow?ZEt:1),d=!1,f=setTimeout(()=>{d=!0,c.kill("SIGKILL")},l);try{let[p,m,h]=await Promise.all([new Response(c.stdout).text(),new Response(c.stderr).text(),c.exited]);if(d)throw new Bt("timeout",s);if(h!==0)throw QEt(m,s);let g=p.trim();if(g==="")return{};try{let y=JSON.parse(g);if(typeof y!=="object"||y===null||Array.isArray(y))throw new Bt("bad-output",s);return y}catch(y){if(y instanceof Bt)throw y;throw new Bt("bad-output",s)}}finally{clearTimeout(f),cR.delete(c)}}}}async function Uve(e,t,n,r=()=>!1){let o=Array(e.length).fill(void 0),s=0,i=async()=>{while(s<e.length&&!r()){let a=s++;o[a]=await n(e[a],a)}};return await Promise.all(Array.from({length:Math.max(1,t)},i)),o}lo();import{chmodSync as tSt,rmSync as nSt,writeFileSync as rSt}from"fs";import{join as oSt}from"path";cs();var sSt=5368709120,zve="us-east-1",iSt=8;function pR(e,t){return`${e}/staging/repull-${t}.json`}var Ol=(e)=>typeof e==="string"?e:void 0;async function Ld(e,t,n){let r=new Map,o=new Set,s=null;for(;;){let i=await e.api("list-objects-v2",["--bucket",t,"--prefix",n,"--max-keys","1000","--no-paginate",...s?["--continuation-token",s]:[]]),a=i.Contents;if(a!==void 0&&!Array.isArray(a))throw new Bt("bad-output","ListObjectsV2");for(let c of a??[]){let l=Ol(c.Key);if(l===void 0||typeof c.Size!=="number")throw new Bt("bad-output","ListObjectsV2");if(l.startsWith(n)&&l.length>n.length)r.set(l.slice(n.length),c.Size)}if(i.IsTruncated!==!0)return r;if(s=Ol(i.NextContinuationToken)??null,!s||o.has(s))throw new Bt("bad-output","ListObjectsV2");o.add(s)}}async function Vve(e){let t=oSt(e.dir,"staging-manifest.json");rSt(t,uc(e.manifest),{mode:384}),tSt(t,384);try{await e.aws.api("put-object",["--bucket",e.bucket,"--key",e.key,"--body",t,"--content-type","application/json"])}finally{nSt(t,{force:!0})}}async function Hve(e,t,n,r){let o;try{o=await e.api("head-object",["--bucket",t,"--key",n,...r?["--version-id",r]:[]])}catch(i){if(i instanceof Bt&&i.code==="not-found")return null;throw i}let s=Ol(o.ETag);if(typeof o.ContentLength!=="number"||s===void 0)throw new Bt("bad-output","HeadObject");return{size:o.ContentLength,etag:s,versionId:Ol(o.VersionId)}}function aSt(e){return`${e.bucket}/${e.object}?versionId=${e.version}`}function cSt(e,t){return Math.max(t,Math.ceil(e/qve))}async function lSt(e){let{aws:t,bucket:n,key:r}=e,o=await t.api("create-multipart-upload",["--bucket",n,"--key",r]),s=Ol(o.UploadId);if(!s)throw new Bt("bad-output","CreateMultipartUpload");try{let i=cSt(e.size,e.partBytes),a=[];for(let c=0,l=1;c<e.size;c+=i,l++){let d=Math.min(c+i,e.size)-1,f=await t.api("upload-part-copy",["--bucket",n,"--key",r,"--upload-id",s,"--part-number",String(l),"--copy-source",e.source,"--copy-source-range",`bytes=${c}-${d}`,"--copy-source-if-match",e.etag],{slow:!0}),p=f.CopyPartResult,m=p?Ol(p.ETag):void 0;if(!m)throw new Bt("bad-output","UploadPartCopy");if(Ol(f.CopySourceVersionId)!==e.version)throw new N("pin-version-mismatch",`S3 copied part ${l} of a multipart copy from another version than the pinned one`);a.push({ETag:m,PartNumber:l})}await t.api("complete-multipart-upload",["--bucket",n,"--key",r,"--upload-id",s,"--multipart-upload",JSON.stringify({Parts:a})],{slow:!0})}catch(i){try{await t.api("abort-multipart-upload",["--bucket",n,"--key",r,"--upload-id",s])}catch{e.open.push({key:r,uploadId:s})}throw i}}async function uSt(e,t,n,r){let o=Ol(r.VersionId);if(o===void 0)return!1;try{return await e.api("delete-object",["--bucket",t,"--key",n,"--version-id",o]),!0}catch{return!1}}function dSt(e){if(e instanceof N)return e;if(e instanceof Xe)return new N("write-refused",e.message);if(e instanceof Bt){if(e.op==="CopyObject"||e.op==="UploadPartCopy"){if(e.code==="not-found")return new N("pin-absent","a pinned upstream version is no longer served");if(e.code==="precondition-failed")return new N("pin-changed","a pinned upstream version changed its ETag")}return new N("copy-failed",`an S3 call failed (${jd(e)})`)}return new N("copy-failed",`a copy failed (${e instanceof Error?e.name:"error"})`)}async function Gve(e){let t=e.singleCopyMax??sSt,n=e.partBytes??Lve,r=0,o=0,s=0,i=[],a=[],c=e.manifest.items;if(await Uve(c,e.concurrency??iSt,async(l)=>{try{let d=No(l.key),f=e.existing.get(l.key);if(d!==null&&f===d){o++;return}let p=await Hve(e.aws.source,l.bucket,l.object,l.version);if(!p)throw new N("pin-absent","a pinned upstream version is not served");if(p.versionId!==l.version)throw new N("pin-version-mismatch","upstream answered for another version than the pinned one, or for none");if(d!==null&&p.size!==d)throw new N("pin-size-mismatch","a pinned upstream version is not the size its key declares");if(d===null&&f===p.size){o++;return}let m=`${e.prefix}${l.key}`,h=aSt(l);if(p.size<=t){let y=await e.aws.dest.api("copy-object",["--bucket",e.destBucket,"--key",m,"--copy-source",h,"--copy-source-if-match",p.etag],{slow:!0});if(Ol(y.CopySourceVersionId)!==l.version){let b=await uSt(e.aws.dest,e.destBucket,m,y);throw new N("pin-version-mismatch",b?"S3 copied from another version than the pinned one; the copy was removed":"S3 copied from another version than the pinned one and the copy could not be removed: delete it by hand before a rerun")}}else await lSt({aws:e.aws.dest,source:h,version:l.version,etag:p.etag,size:p.size,bucket:e.destBucket,key:m,partBytes:n,open:a});let g=await Hve(e.aws.dest,e.destBucket,m);if(!g||g.size!==p.size)throw new N("copy-size-mismatch","a copied object is not the size of the version it was copied from");r++,s+=p.size}catch(d){i.push(dSt(d))}},()=>i.length>0),i.length>0){let l=i[0],d=a.length>0?` ${a.length} multipart upload(s) could not be aborted and stay open (abort them with abort-multipart-upload): ${a.map((f)=>f.uploadId).join(", ")}.`:"";throw new N(l.code,`The copy stopped: ${l.message}; ${i.length} of ${c.length} item(s) refused, ${r} copied and ${o} already present this run. Nothing is registered for a partial copy, and a rerun skips what landed.${d}`)}return{copied:r,skipped:o,bytes:s}}import{createHash as fSt}from"crypto";import{readFileSync as pSt}from"fs";import{join as mSt}from"path";Za();ec();Je();Je();function fs(e,t){if(t instanceof N)return`[${e}:${t.code}] ${t.message}`.slice(0,2000);let n=t instanceof Error?t.name:"unknown";return`[${e}:${e}-failed] The step failed (${n}).`}function Pt(e,t){let n=new N(e,t);return n.resumable=!0,n}function Qr(e,t){let n=An(e)??(e instanceof L?"record-refused":"github-failed"),r=e instanceof Error?e.message:String(e);return Pt(n,`${t}: ${r}`)}function PM(e){if(e.status==="pr_open")return{branch:e.branch,pr_number:e.pr_number,head_sha:e.head_sha};if(e.status==="patch_synthesized")return{patch_version:e.patch_version,patch_branch:e.patch_branch,patch_pr_number:e.patch_pr_number,patch_head_sha:e.patch_head_sha,patch_base_sha:e.patch_base_sha};return{}}async function Zr(e,t,n){let r=PM(e);try{await Zn(e.id,{from:e.status,to:e.status,fields:r,error:t})}catch(o){n(`The failure could not be recorded on re-pull #${e.id} (${An(o)??(o instanceof L?`HTTP ${o.statusCode}`:"no answer")}); its record keeps the last error it had.`)}}async function Wve(e,t){let n=await te(e,["ls-tree","-r","-z","--full-tree",t],{ok:!0});if(n.exitCode!==0)return null;return n.stdout.split("\x00").filter(Boolean).map((r)=>/^(\d{6}) [a-z]+ ([0-9a-f]{40})\t(.+)$/s.exec(r)).filter((r)=>r!==null).filter((r)=>!r[3].startsWith(".nemar/")&&!r[3].startsWith(".github/")).map((r)=>`${r[1]} ${r[2]} ${r[3]}`).sort().join(`
|
|
410
410
|
`)}async function Kve(e,t,n,r){let o=Tr[r],s=r==="n0"?t.synth_sha:t[o.gates];if(!await _r(e,n,1))return"tag-unread";let i=async()=>(await te(e.dir,["cat-file","-e",`${s}^{commit}`],{ok:!0})).exitCode===0;if(!await i()){for(let l of[s,Kn(t[o.version]),`refs/pull/${t[o.number]}/head`])if(await _r(e,l,us)&&await i())break}if(!await i())return"commit-unread";let a=await Wve(e.dir,n),c=await Wve(e.dir,s);if(a===null||c===null)return"tag-unread";return a===c?"same":"differs"}async function hSt(e,t,n,r){let o=await Kve(e,t,n,"n0");if(o==="same")return!0;return r(o==="tag-unread"?"The tagged commit could not be fetched, so its tree is not verified (lineage is not recorded).":o==="commit-unread"?"The re-pull's commit could not be fetched, so the tagged tree is not verified (lineage is not recorded).":"The tagged tree is not the re-pull's commit outside .nemar/ and .github/, so lineage is not recorded for it."),!1}async function gSt(e,t,n,r){let o=await Kve(t,n,r,"n1");if(o==="same")return;let s=n.patch_gates_sha.slice(0,12);if(o==="differs"&&e.opts.acceptTagTree){e.opts.out(`The tag v${n.patch_version} is not N.0.1's gated head ${s} outside .nemar/ and .github/; its release is recorded on your reason: ${e.opts.acceptTagTree}`);return}let i=o==="differs"?Pt("patch-tree-mismatch",`The tag v${n.patch_version} on NEMAR's main is not N.0.1's gated head outside .nemar/ and .github/, so its release is not recorded and the record stays ${n.status}. Read the difference (git diff ${s} v${n.patch_version} -- . ':!.nemar' ':!.github'), then record the release with nemar admin repull resume ${n.dataset_id} --accept-tag-tree "<reason>".`):Pt("origin-unreadable",`The tag v${n.patch_version} or N.0.1's gated head could not be read from NEMAR's repository, so the tagged tree is not verified and its release is not recorded; run resume again.`);throw await Zr(n,fs("release",i),e.opts.out),i}async function ySt(e,t){return(await Lf(e)).versions.some((r)=>r.version===t||r.version===`v${t}`)}async function bSt(e,t,n,r){let o=n[Tr[r].mergeSha],s=async(l,d)=>{let f=Pt(l,d);return await Zr(n,fs("release",f),e.opts.out),f};if(!await _r(t,o,1))throw await s("merge-unreadable",`The merge commit ${o.slice(0,12)} could not be fetched from NEMAR's repository, so its trailers were not read; nothing was recorded past merged.`);let i=await te(t.dir,["cat-file","commit",o],{ok:!0}),a=i.stdout.indexOf(`
|
|
411
411
|
|
|
412
412
|
`),c=i.exitCode!==0||a<0?"its message could not be read":await Al(i.stdout.slice(a+2),n);if(c)throw await s("merge-trailers",`The merge commit ${o.slice(0,12)} on main does not end with the re-pull commit's two trailers (${c}), so the privacy ledger's fresh-clone proof would not read it as the re-pull's commit. The record stays ${n.status}; an administrator decides what follows.`)}async function IM(e,t,n){let r=t[Tr[n].version],o=`refs/tags/v${r}`,s=await e.origin();await bSt(e,s,t,n);let i;try{i=(await Rl(s,[o])).get(o)}catch(d){if(d instanceof N)d.resumable=!0;throw d}if(!i)return{kind:"wait",row:t,waitingFor:`the tag v${r} on NEMAR's repository`};let a;try{a=await ySt(e.datasetId,r)}catch(d){throw Qr(d,"The dataset's versions could not be read")}if(!a)return{kind:"wait",row:t,waitingFor:`the version row of v${r} (its DOI)`};if(n==="n1")await gSt(e,s,t,i);let c=n==="n0"?await hSt(s,t,i,e.opts.out):!1,l;try{l=await j0e(t.id,{pr:n,tag_sha:i,tree_verified:c})}catch(d){let f=An(d);if(f==="not-released")return{kind:"wait",row:t,waitingFor:`the DOI of v${r}`};let p=Pt(f??"release-failed",`The release of v${r} could not be recorded: ${d instanceof Error?d.message:String(d)}`);if(d instanceof L)await Zr(t,fs("release",p),e.opts.out);throw p}return e.opts.out(`Re-pull #${t.id} is released: v${r} at ${i.slice(0,12)}${n==="n1"?"":l.lineage_rows?`, lineage recorded for v${r}`:c?"":", lineage not recorded"}; the dataset's sweeps read it again.`),{kind:"next",row:l.repull}}async function Xw(e){let t=await e.origin();if(!await _r(t,"refs/heads/git-annex",1))throw Pt("origin-unreadable","NEMAR's git-annex branch could not be fetched.");let n=await te(t.dir,["cat-file","blob","refs/remotes/origin/heads/git-annex:remote.log"],{ok:!0}),r=yp(n.exitCode===0?n.stdout:"",e.datasetId),o=r.record?.bucket;if(n.exitCode!==0||!r.uuid||!o)throw Pt("no-nemar-s3","NEMAR's remote.log names no single nemar-s3 bucket.");let s={};for(let[a,c]of Object.entries(e.env))if(c!==void 0)s[a]=c;let i=fR({region:r.region,timeoutMs:uR,env:s,credentials:dR({commandEnv:s})});return{scratch:t,uuid:r.uuid,bucket:o,region:r.region,prefix:r.prefix,aws:i}}async function NM(e,t,n){let{scratch:r,bucket:o,aws:s}=n??await Xw(e),i=mSt(r.dir,"staging-manifest.json"),a=!1;for(let f of new Set([t.to_tag,`v${t.to_tag}`]))try{await s.api("get-object",["--bucket",o,"--key",pR(e.datasetId,f),i]),a=!0;break}catch(p){if(!(p instanceof Bt))throw p;if(p.code!=="not-found")throw Pt("staging-unreadable",`The staging manifest of re-pull #${t.id} could not be read (${jd(p)}); the ambient AWS credentials read it, as the copy wrote it.`)}if(!a)throw Pt("staging-unreadable",`The staging manifest of re-pull #${t.id} is not in NEMAR's bucket, so which objects its copy wrote is not known.`);let c=pSt(i);if(`sha256:${fSt("sha256").update(c).digest("hex")}`!==t.manifest_digest)throw Pt("manifest-mismatch","The staging manifest in NEMAR's bucket is not the copy manifest recorded at prepared.");let l=JSON.parse(c.toString("utf8")),d=[...l.items??[],...l.local??[]].map((f)=>f.key);if(!d.every((f)=>typeof f==="string"))throw Pt("manifest-mismatch","The staging manifest names an object without a key.");return[...new Set(d)].sort()}async function Jve(e,t){if(typeof t.counts.locked==="number")return{kind:"next",row:t};let n=async(c,l)=>{let d=Pt(c,l);return await Zr(t,fs("lock",d),e.opts.out),d},r;try{r=await NM(e,t)}catch(c){if(c instanceof N)throw await n(c.code,c.message);throw c}let o;try{o=r.length>0?await Dme(e.datasetId,r):{locked:0,failed:[],objects:[]}}catch(c){throw await n("lock-failed",`The objects of v${t.to_version} could not be locked (${c instanceof L?`HTTP ${c.statusCode}`:"no answer"}); run resume again.`)}let s=new Set(o.objects.map((c)=>c.key)),i=r.filter((c)=>!s.has(c)).length;if(o.failed.length>0||i>0)throw await n("lock-incomplete",`${i} of the ${r.length} object(s) N.0.0's copy and uploads wrote were not locked (${r.length-i} were); run resume again, which locks them again.`);let a;try{a=await Zn(t.id,{from:"released",to:"released",fields:{counts:{locked:r.length}}})}catch(c){throw Qr(c,"The count of locked objects could not be recorded")}return e.opts.out(`Locked the ${r.length} object(s) N.0.0's copy and uploads wrote under the governance lock.`),{kind:"next",row:a}}async function Yve(e,t,n){let r;try{r=await Zn(t.id,{from:"released",to:"complete"})}catch(o){throw Qr(o,"The record could not be completed")}return e.opts.out(`Re-pull #${t.id} of ${e.datasetId} is complete${n}.`),{kind:"done",result:{row:r,outcome:"complete"}}}async function wSt(e,t){let n=e.opts.plan??Ag(e.configDir,e.datasetId,t.to_tag,t.plan_digest),{file:r,body:o}=bp(n,{environment:Cr(),env:e.env,openNeuroGraphqlUrl:kl(e.env)});if(r.digest!==t.plan_digest)throw new N("plan-not-the-record",`The plan file is not the plan re-pull #${t.id} was made from (its digest differs); pass the reviewed plan with --plan <file>.`);return o}function _St(e,t,n){return[`NEMAR's corrections of re-pull #${e.id} (upstream ${e.upstream_ds} ${e.from_tag} to ${e.to_tag}), replayed onto v${e.to_version} as v${n} of ${e.dataset_id} (ADR 0111).`,"",`v${e.to_version} is upstream's snapshot ${e.upstream_ds}@${e.to_tag} with NEMAR's standard edits; this pull request puts back NEMAR's own side of what the plan listed as a correction, and of each conflict an administrator resolved to NEMAR's side. Nothing is scrubbed and nothing is copied: every replayed byte is in a version NEMAR already published.`,"",`- Re-pull record: #${e.id}`,`- Plan digest: ${e.plan_digest}`,`- Corrections the plan listed: ${t.corrections}; conflicts resolved to NEMAR's side: ${t.resolutions}`,`- Paths replayed: ${t.paths.length}; description keys replayed: ${t.keys.length}`,"- Version DOIs this pull request mints when merged: 1","",`\`nemar admin repull resume ${e.dataset_id}\` takes this pull request through the identifier screen and the gates, and \`nemar admin repull merge ${e.dataset_id}\` (or \`nemar admin pr-reviews\`, through the same gate) squash-merges it under the daily merge cap; a merge mints a version DOI that cannot be withdrawn.`,"","The squash commit message must end with the re-pull's trailers, as its last paragraph; the merge path writes that message itself and refuses one that does not:","","```",`Upstream-Snapshot: ${e.upstream_ds}@${e.to_tag}`,`Repull-Plan: ${e.plan_digest}`,`Repull-Patch: corrections=${t.corrections}`,"```","","Do not merge this from GitHub's page."].join(`
|
|
413
|
-
`)}async function Xve(e,t){let n=t.counts.corrections,r=t.counts.conflicts,o=e.opts.takeOurs??[];if(typeof n!=="number"||typeof r!=="number")return e.opts.out(`Re-pull #${t.id}'s record does not say how many corrections and conflicts its plan has, so it is not completed; it stays released.`),{kind:"done",result:{row:t,outcome:"released"}};if(n===0&&r===0&&o.length===0)return Yve(e,t,"");if(r>0&&o.length===0&&!e.opts.keepUpstream)return{kind:"done",result:{row:t,outcome:"waiting",waitingFor:`an administrator's decision on the ${r} conflict(s) the plan lists, before N.0.1 is made: resolve one to NEMAR's side with --take-ours <path> (or --take-ours dataset_description.json#<Key>), or leave every one on upstream's side with --keep-upstream (the reviewed plan file names them, under conflicts and description.keys)`}};let s=O$(t.to_version);try{let i=await wSt(e,t);Ave(i);let a=Ove(i,o);if(a.corrections!==n)throw new N("patch-plan-mismatch",`The plan lists ${a.corrections} correction(s) and re-pull #${t.id} records ${n}; they are the same plan only when they agree.`);if(a.unresolved>0&&!e.opts.keepUpstream)return{kind:"done",result:{row:t,outcome:"waiting",waitingFor:`an administrator's decision on the ${a.unresolved} conflict(s) the plan lists that no --take-ours names, before N.0.1 is made: name each to take NEMAR's side, or add --keep-upstream to leave them on upstream's side`}};if(!Tve(a))return Yve(e,t,": the plan has no correction, and every conflict stays on upstream's side");return await vSt(e,t,a,s)}catch(i){if(i instanceof N&&!xSt.has(i.code))i.resumable=!0,await Zr(t,fs("patch",i),e.opts.out);throw i}}var xSt=new Set(["take-ours-invalid","declined","plan-unreadable","plan-schema","plan-environment","plan-sources","planner-version","plan-tampered","plan-not-the-record"]);async function vSt(e,t,n,r){let o=await Xw(e),{scratch:s}=o;if(o.prefix!==`${e.datasetId}/objects/`)throw new N("destination-prefix",`NEMAR's nemar-s3 is not at ${e.datasetId}/objects/, where the keys N.0.1 replays are read.`);let i=await Cl({work:s.dir,baseSha:t.merge_sha,env:s.env}),a=Kn(r),c=(await Rl(s,[a])).get(a),l,d,f;if(c){if(!await _r(s,a,us))throw Pt("origin-unreadable",`release/v${r} could not be fetched.`);let y=await oy({dir:s.dir,row:t,head:c}),b=y?await RM({scratch:s,row:t,selection:n,parent:y.parent}):null;if(!y||!b||b.sha!==y.commit)throw new N("branch-foreign",`release/v${r} exists on NEMAR's repository and is not this re-pull's N.0.1 commit with these resolutions; run resume with the resolutions the earlier run was given, or decline N.0.1 with nemar admin repull abandon ${e.datasetId}.`);l=y.commit,d=y.parent,f=b.keys}else{let y=await RM({scratch:s,row:t,selection:n,parent:i});l=y.sha,d=i,f=y.keys}let p;try{p=f.length>0?await Ld(o.aws,o.bucket,o.prefix):new Map}catch(y){if(!(y instanceof Bt))throw y;throw new N("s3-failed",`NEMAR's bucket could not be listed for the keys N.0.1 replays (${jd(y)}); the ambient AWS credentials list it.`)}if(await Nve({dir:s.dir,annexRef:"refs/remotes/origin/heads/git-annex",keys:f,nemarUuid:o.uuid,listing:p}),!c&&e.opts.confirm&&!await e.opts.confirm(`Make v${r} of ${e.datasetId}: replay ${n.paths.length} path(s) and ${n.keys.length} description key(s) onto main (${n.corrections} correction(s), ${n.resolutions} conflict(s) resolved to NEMAR's side, ${n.unresolved} left on upstream's side), push release/v${r} and open its pull request? Its merge will mint one more version DOI, which cannot be withdrawn.`))throw new N("declined","Not confirmed; nothing was pushed.");let m=await eR({work:s.dir,synthSha:l,version:r,push:{versions:[r]},env:s.env});e.opts.out(m.pushed?`Pushed release/v${r} (${l.slice(0,12)}).`:`release/v${r} is already this re-pull's N.0.1 commit${m.head===l?"":" (moved by enrichment)"}.`);let h=await tR({token:e.token,base:e.base,datasetId:e.datasetId,version:r,body:_St(t,n,r),acceptHead:(y)=>As({work:s.dir,from:l,head:y,ref:a,env:s.env})}),g;try{g=await Zn(t.id,{from:"released",to:"patch_synthesized",fields:{patch_version:r,patch_branch:`release/v${r}`,patch_pr_number:h.number,patch_head_sha:h.head,patch_base_sha:d,counts:{resolutions:n.resolutions}}})}catch(y){throw Qr(y,"N.0.1's pull request could not be recorded")}return e.opts.out(`${h.reused?"Found":"Opened"} N.0.1's pull request #${h.number} of release/v${r} (${n.resolutions} conflict(s) resolved to NEMAR's side, ${n.unresolved} left on upstream's side); re-pull #${t.id} is patch_synthesized. Resume never merges.`),{kind:"next",row:g}}async function SSt(e){try{return(await Io({dataset:e,open:!0,limit:1})).repulls[0]??null}catch(t){throw Qr(t,"The NEMAR API could not list the re-pulls")}}async function mR(e){return Fd(()=>$St(e))}async function $St(e){let t=e.env??process.env,n=kn(t),r=await ui(t);if(!r.ok)throw new N("no-github-token",`No GitHub token (${r.reason}): resume reads the pull request with the administrator's own (GH_TOKEN, or gh auth login).`);El(await ac(e.datasetId));let o=await SSt(e.datasetId);if(!o){let d=(await Io({dataset:e.datasetId,limit:1})).repulls[0]??null,f=e.automaticFinish;if(f&&!(d?.id===f.repullId&&d.status==="complete"))throw new N("finish-not-merged",`Re-pull #${f.repullId} is not open: a finish takes up only a merged re-pull.`);return{row:d,outcome:f?"complete":"nothing"}}if(e.automaticFinish)DSt(o,e.automaticFinish.repullId);let s=Vn(),i=wc(s,e.datasetId,o.plan_digest);wo(kSt(i.lock),ESt(s,"repull"));let a=$l(i.lock),c=null,l={datasetId:e.datasetId,token:r.token,base:n,env:t,configDir:s,opts:e,origin:async()=>(c??=await Dl({configDir:s,datasetId:e.datasetId,digest:o.plan_digest,purpose:"resume",env:t,token:r.token}),c),replaced:new Set,sleep:(d)=>new Promise((f)=>setTimeout(f,d))};if(((e.takeOurs?.length??0)>0||e.keepUpstream)&&o.status.startsWith("patch_"))e.out(`Re-pull #${o.id} is ${o.status}: N.0.1 is already made, so --take-ours and --keep-upstream change nothing now.`);try{return await RSt(l,o)}finally{c?.close(),a()}}function DSt(e,t){if(e.id!==t||e.origin!=="automatic")throw new N("repull-mismatch",`The dataset's open re-pull is #${e.id} (origin ${e.origin}); the finish takes up only #${t}, an automatic re-pull.`);if(e.status!=="merged"&&e.status!=="released")throw new N("finish-not-merged",`Re-pull #${e.id} is ${e.status}: a finish takes up only a merged re-pull.`)}async function RSt(e,t){let n=Date.now()+Math.max(0,e.opts.waitMinutes)*60000,r=Math.max(100,e.opts.pollMs??15000),o=t;for(let s=0;;){if(s>20)throw Pt("resume-looped",`Re-pull #${o.id} did not settle; run resume again.`);let i=await CSt(e,o);if(i.kind==="done")return i.result;if(i.kind==="next"){o=i.row,s++;continue}if(s=0,Date.now()+r>n)return{row:i.row,outcome:"waiting",waitingFor:i.waitingFor};e.opts.out(`Waiting for ${i.waitingFor}.`),await e.sleep(r);try{o=await P$(i.row.id)}catch(a){throw Qr(a,"The NEMAR API could not read the re-pull")}}}async function CSt(e,t){switch(t.status){case"planned":case"prepared":case"copied":case"registered":throw new N("use-execute",`Re-pull #${t.id} is ${t.status}: it is taken up by nemar admin repull execute <plan-file>, with the plan it was made from.`);case"pr_open":return Qve(e,t,"n0");case"patch_synthesized":return Qve(e,t,"n1");case"gates_clear":return Zve(e,t,"n0");case"patch_gates_clear":return Zve(e,t,"n1");case"merged":return IM(e,t,"n0");case"patch_merged":return IM(e,t,"n1");case"released":{let n=await Jve(e,t);return n.kind==="next"?Xve(e,n.row):n}case"patch_released":return ISt(e,t);default:throw new N("not-built",`Re-pull #${t.id} is ${t.status}, which resume does not take on.`)}}function eke(e,t){let n=Tr[t];return{pr:t,number:e[n.number],branch:e[n.branch],head:e[n.head],gates:e[n.gates],claimSha:e[n.claimSha],claimedAt:e[n.claimedAt],version:e[n.version],base:t==="n0"?e.base_sha:e.patch_base_sha,anchor:t==="n0"?e.synth_sha:e.patch_head_sha,closedTo:t==="n0"?"abandoned":"patch_declined"}}async function tke(e,t){let n=await Bi(e.token,e.datasetId,t.number,e.base);if(!n.ok)throw Pt("github-unreadable",`Pull request #${t.number} could not be read on GitHub (${n.reason})`);return n.value}async function nke(e,t,n){let r;try{r=await I$(t.id,n.pr)}catch(s){throw Qr(s,`The merge of pull request #${n.number} could not be recorded`)}let o=[r.merged_outside_tool?"no NEMAR tool held a claim for it":null,r.merged_unscreened_head?"at a head other than the screened one":null].filter(Boolean);return e.opts.out(`Pull request #${n.number} is merged; re-pull #${t.id} records it${o.length>0?` (${o.join(", ")})`:""}.`),{kind:"next",row:r.repull}}async function sy(e,t,n,r){try{return await Zn(e.id,{from:e.status,to:t,fields:n})}catch(o){throw Qr(o,r)}}function Qw(e,t,n,r){let o={...PM(e)};if(t.pr==="n0"){if(o.head_sha=n,r)o.synth_sha=r.synthSha,o.synth_tree=r.synthTree,o.base_sha=r.baseSha}else if(o.patch_head_sha=n,r)o.patch_base_sha=r.baseSha;return o}async function rke(e,t,n){let r=await sy(t,n.closedTo,{},"The record could not be ended");return e.opts.out(n.pr==="n0"?`Pull request #${n.number} was closed without being merged: re-pull #${t.id} is abandoned. Plan the dataset again to re-pull it.`:`N.0.1's pull request #${n.number} was closed without being merged: re-pull #${t.id} is patch_declined, and v${t.to_version} stays released; its corrections remain corrections in the next plan.`),{kind:"done",result:{row:r,outcome:"ended"}}}async function oke(e,t,n){return As({work:e.dir,from:t.anchor,head:n,ref:Kn(t.version),env:e.env})}async function ASt(e,t,n,r){if(n.pr==="n0")return Cve({scratch:e,row:t,head:r});let o=await ske(e,t,n);if(!o)return null;let s=await Fve({dir:e.dir,row:t,recorded:o,head:r});return s?{synthSha:s.sha,synthTree:s.tree,baseSha:s.baseSha}:null}async function ske(e,t,n){if(!await _r(e,n.anchor,us))return null;return await _r(e,t.merge_sha,us),(await oy({dir:e.dir,row:t,head:n.anchor}))?.commit??null}async function Qve(e,t,n){let r=eke(t,n),o=await tke(e,r);if(o.state==="merged")return nke(e,t,r);if(o.state==="closed")return rke(e,t,r);if(o.baseRef!=="main"||o.headRef!==r.branch){let h=Pt("pr-foreign",`Pull request #${r.number} is not ${r.branch} into main.`);throw await Zr(t,fs("gates",h),e.opts.out),h}if(!yd(o.headRepo,t.dataset_id)||!yd(o.baseRepo,t.dataset_id)){let h=Pt("pr-foreign",`Pull request #${r.number} is not from and into ${x0e}/${t.dataset_id} itself (its head is ${o.headRepo??"a repository GitHub no longer names"}, its base ${o.baseRepo??"a repository GitHub no longer names"}): a fork's pull request is never merged as a re-pull's.`);throw await Zr(t,fs("gates",h),e.opts.out),h}if(o.headSha!==r.head){if(e.replaced.has(o.headSha))return{kind:"wait",row:t,waitingFor:"GitHub to show the re-synthesized head"};let h=await e.origin(),g=await oke(h,r,o.headSha);if(g!=="ok"){let b=await ASt(h,t,r,o.headSha);if(b){let x=await sy(t,t.status,Qw(t,r,o.headSha,b),"The re-synthesized commit could not be recorded");return e.opts.out(`${r.branch} holds this re-pull's commit made again on a moved main (${b.synthSha.slice(0,12)}), pushed by an earlier run; re-pull #${t.id} records it.`),{kind:"next",row:x}}let _=g==="unreadable"?Pt("branch-unreadable",`Whether the head of ${r.branch} is this re-pull's commit and enrichment's could not be read.`):Pt("head-foreign",`${r.branch} holds a commit enrichment does not make: this pull request cannot be merged as it is; end the record with nemar admin repull abandon ${e.datasetId}.`);throw await Zr(t,fs("gates",_),e.opts.out),_}let y=await sy(t,t.status,Qw(t,r,o.headSha),"The moved head could not be recorded");return e.opts.out(`${r.branch} moved by enrichment to ${o.headSha.slice(0,12)}; re-pull #${t.id} records it.`),{kind:"next",row:y}}let s=await e.origin(),i;try{i=await Cl({work:s.dir,baseSha:r.base,env:s.env})}catch(h){if(h instanceof N)h.resumable=!0,await Zr(t,fs("gates",h),e.opts.out);throw h}let a=await _g(e.token,e.datasetId,r.number,{headSha:o.headSha,mergeableState:o.mergeableState},{base:e.base,sleep:e.sleep});if(!a.ok){if(a.kind==="unreadable")throw Pt("github-unreadable",`GitHub could not say whether #${r.number} can be merged.`);return{kind:"wait",row:t,waitingFor:`pull request #${r.number} to settle on GitHub`}}let c=a.state,l=i===r.base?[]:await zw(s.dir,r.base,i);if(l===null)throw Pt("main-unreadable","Whether NEMAR's main moved outside .nemar/ and .github/ could not be read; run resume again.");if(i!==r.base&&(c==="dirty"||c==="behind"||l.length>0))return PSt(e,t,r,i,o.headSha,l.length>0?`enrichment changed ${l.length} path(s) outside .nemar/ and .github/ on it`:`GitHub reports its pull request '${c}'`);let d=await OSt(e,t,r),f=[];if(d!==null)f.push(d);if(c!=="clean")f.push(`GitHub to report pull request #${r.number} clean (it reports '${c}')`);if(f.length>0)return{kind:"wait",row:t,waitingFor:f.join(", and ")};let p=Tr[n],m;try{m=await Zn(t.id,{from:p.open,to:p.gatesClear,fields:{[p.gates]:r.head}})}catch(h){let g=An(h);if(g==="head-moved"||g==="screen-changed")return{kind:"next",row:t};if(g==="screen-not-clear")return{kind:"wait",row:t,waitingFor:"the identifier screen to pass for this head"};throw Qr(h,"The gates could not be recorded")}return e.opts.out(`The identifier screen and GitHub pass for ${r.head.slice(0,12)}: re-pull #${t.id} is ${p.gatesClear}.`),{kind:"done",result:{row:m,outcome:"ready"}}}async function OSt(e,t,n){let r=n.head,o;try{o=await kg(t.id)}catch(i){throw Qr(i,"The identifier screens could not be read")}if(o.exempt)return null;let s=o.screens.find((i)=>i.pr===n.pr&&i.sha===r)??null;if(s===null||s.gate==="rerun"){try{let i=await I0e(t.id,{pr:n.pr,sha:r});if(i.exempt)return null;e.opts.out(`Dispatched the identifier screen of ${r.slice(0,12)}.`),s=i.screen}catch(i){if(An(i)!=="screen-exists")throw Qr(i,"The identifier screen could not be dispatched");s=i.rawBody?.screen??null}if(s===null||s.gate==="rerun"||s.gate==="wait")return`the identifier screen of ${r.slice(0,12)}`}switch(s.gate){case"clear":return null;case"wait":return`the identifier screen of ${r.slice(0,12)} (running)`;case"blocks":{let i=Pt("screen-blocks",`${s.headline}. A direct identifier cannot be acknowledged: this commit is not merged.`);throw await Zr(t,fs("gates",i),e.opts.out),i}case"acknowledge":{if(s.acknowledged_at!==null)return null;if(!e.opts.acknowledgment)return`an administrator's reason for the identifier screen (${s.headline}); read it with nemar admin repull status ${e.datasetId}, then run nemar admin repull resume ${e.datasetId} --acknowledge-identifier-screen "<reason>"`;try{await N0e(t.id,{pr:n.pr,sha:r,reason:e.opts.acknowledgment})}catch(i){throw Qr(i,"The acknowledgment could not be recorded")}return e.opts.out(`Recorded your acknowledgment of the identifier screen of ${r.slice(0,12)}.`),null}default:return`the identifier screen of ${r.slice(0,12)}`}}async function TSt(e,t,n,r,o){let s=await ske(e,t,n);if(!s)throw new N("origin-unreadable","N.0.1's commit could not be found beneath its recorded head on NEMAR's repository.");let i=await AM({dir:e.dir,commit:s,newMain:r}),a=Kn(n.version),c=await xc(e.dir,[`${i.sha}:${a}`],{versions:[n.version]},e.env,[`--force-with-lease=${a}:${o}`]);if(c.outcome==="rejected")throw new N("branch-moved",`release/v${n.version} moved while it was re-synthesized; nothing was replaced. Run resume again.`);if(c.outcome==="remote-rejected"||c.outcome==="failed")throw new N("push-failed",`The re-synthesized release/v${n.version} could not be pushed (${yi(c.cause)}).`);return{synthSha:i.sha,synthTree:i.tree}}async function PSt(e,t,n,r,o,s){if(e.opts.confirm&&!await e.opts.confirm(`NEMAR's main moved by enrichment since re-pull #${t.id}'s ${n.pr==="n0"?"commit":"N.0.1 commit"} was made, and ${s}. Make the commit again on the new main and push ${n.branch} with a lease (nothing enrichment wrote is undone)?`))throw new N("declined","Not confirmed; nothing was pushed.");let i=await e.origin(),a;try{a=n.pr==="n0"?await Rve({scratch:i,row:t,newMain:r,liveHead:o}):await TSt(i,t,n,r,o)}catch(l){if(l instanceof N)l.resumable=!0,await Zr(t,fs("gates",l),e.opts.out);throw l}e.replaced.add(o);let c=await sy(t,t.status,Qw(t,n,a.synthSha,{...a,baseSha:r}),"The re-synthesized commit could not be recorded");return e.opts.out(`Made re-pull #${t.id}'s commit again on the new main (${a.synthSha.slice(0,12)}) and pushed ${n.branch}; its identifier screen runs again for the new head.`),{kind:"next",row:c}}async function Zve(e,t,n){let r=eke(t,n),o=await tke(e,r);if(o.state==="merged")return nke(e,t,r);if(r.claimSha!==null)try{let c=await F0e(t.id,{pr:n,sha:r.claimSha,outcome:"expired"});return e.opts.out(`The claim to merge made at ${r.claimedAt} expired: GitHub says pull request #${r.number} did not merge, and its unit of today's merge cap is free.`),{kind:"next",row:c}}catch(c){let l=An(c);if(l==="pull-request-merged")return{kind:"next",row:t};if(l==="claim-too-recent")return{kind:"done",result:{row:t,outcome:"waiting",waitingFor:`the claim to merge made at ${r.claimedAt} to be resolved: run nemar admin repull merge ${e.datasetId} to send the merge again under it, or resume later to expire it`}};throw Qr(c,"The claim to merge could not be resolved")}if(o.state==="closed")return rke(e,t,r);if(o.headSha!==r.gates){let c=await e.origin(),l=await oke(c,r,o.headSha);if(l!=="ok")throw Pt(l==="unreadable"?"branch-unreadable":"head-foreign",`${r.branch} moved since its gates were recorded, ${l==="unreadable"?"and whether by enrichment only could not be read":"by a commit enrichment does not make"}.`);let d=await sy(t,Tr[n].open,Qw({...t,status:Tr[n].open},r,o.headSha),"The moved head could not be recorded");return e.opts.out(`${r.branch} moved by enrichment since its gates were recorded; re-pull #${t.id} is ${Tr[n].open} again, and its screen runs for the new head.`),{kind:"next",row:d}}let s=await e.origin(),i;try{i=await Cl({work:s.dir,baseSha:r.base,env:s.env})}catch(c){if(c instanceof N)c.resumable=!0;throw c}let a=i===r.base?[]:await zw(s.dir,r.base,i);if(a===null)throw Pt("main-unreadable","Whether NEMAR's main moved outside .nemar/ and .github/ since the gates could not be read; run resume again.");if(a.length>0){let c=Tr[n].open,l=await sy(t,c,Qw({...t,status:c},r,o.headSha),"The return to the open pull request could not be recorded");return e.opts.out(`NEMAR's main moved by enrichment since the gates, on ${a.length} path(s) outside .nemar/ and .github/: re-pull #${t.id} is ${c} again, and its commit is made again on the new main.`),{kind:"next",row:l}}return{kind:"done",result:{row:t,outcome:"ready"}}}async function ISt(e,t){let n;try{n=await Zn(t.id,{from:"patch_released",to:"complete"})}catch(r){throw Qr(r,"The record could not be completed")}return e.opts.out(`Re-pull #${t.id} of ${e.datasetId} is complete: v${t.to_version} and v${t.patch_version} are released.`),{kind:"done",result:{row:n,outcome:"complete"}}}var qo=(e)=>e?e.slice(0,12):"none";function NSt(e){let t=e.dataset_id;switch(e.status){case"planned":case"prepared":case"copied":case"registered":return"nemar admin repull execute <plan-file> (the reviewed plan this record was made from)";case"pr_open":return`nemar admin repull resume ${t} (the identifier screen and the gates)`;case"gates_clear":return e.merge_claim_sha?`nemar admin repull merge ${t} (sends the merge again under the held claim), or resume ${t} once the claim is old enough to expire`:`nemar admin repull merge ${t} (mints one version DOI, v${e.to_version})`;case"merged":return`nemar admin repull resume ${t} (the release, the lock, then N.0.1 or the end)`;case"released":return typeof e.counts.conflicts==="number"&&e.counts.conflicts>0?`nemar admin repull resume ${t} --take-ours <path> or --keep-upstream (the lock, then N.0.1 or the end; the plan's ${e.counts.conflicts} conflict(s) wait for your decision), or nemar admin repull abandon ${t} (declines N.0.1)`:`nemar admin repull resume ${t} (the lock, then N.0.1 or the end)`;case"patch_synthesized":return`nemar admin repull resume ${t} (N.0.1's identifier screen and gates)`;case"patch_gates_clear":return e.patch_merge_claim_sha?`nemar admin repull merge ${t} (sends N.0.1's merge again under the held claim), or resume ${t} once the claim is old enough to expire`:`nemar admin repull merge ${t} (mints one version DOI, v${e.patch_version})`;case"patch_merged":case"patch_released":return`nemar admin repull resume ${t} (N.0.1's release and the end)`;default:return bF(e.status)?null:`nemar admin repull resume ${t}`}}function ike(e,t){let n=[`Re-pull #${e.id} of ${e.dataset_id}: ${e.status} (attempt ${e.attempt}, ${e.origin})`,` Upstream ${e.upstream_ds}: ${e.from_tag} -> ${e.to_tag}, as v${e.to_version} (from v${e.from_version})`,` Plan: ${e.plan_digest} (planner ${e.planner})`,` Base: ${qo(e.base_sha)} Commit: ${qo(e.synth_sha)} Tree: ${qo(e.synth_tree)}`];if(e.pr_number!==null)n.push(` Pull request: #${e.pr_number} of ${e.branch}, head ${qo(e.head_sha)}`);if(e.gates_sha)n.push(` Gates clear at: ${qo(e.gates_sha)}`);if(e.merge_claim_sha)n.push(` Claim to merge: ${qo(e.merge_claim_sha)}, made ${e.merge_claimed_at} UTC`);if(e.merge_sha)n.push(` Merge: ${qo(e.merge_sha)}`);if(e.tag_sha)n.push(` Tag v${e.to_version}: ${qo(e.tag_sha)}`);if(e.patch_pr_number!==null)n.push(` N.0.1 pull request: #${e.patch_pr_number} of ${e.patch_branch}, head ${qo(e.patch_head_sha)}, base ${qo(e.patch_base_sha)}`);if(e.patch_gates_sha)n.push(` N.0.1 gates clear at: ${qo(e.patch_gates_sha)}`);if(e.patch_merge_claim_sha)n.push(` N.0.1 claim to merge: ${qo(e.patch_merge_claim_sha)}, made ${e.patch_merge_claimed_at} UTC`);if(e.patch_merge_sha)n.push(` N.0.1 merge: ${qo(e.patch_merge_sha)}`);if(e.patch_tag_sha)n.push(` Tag v${e.patch_version}: ${qo(e.patch_tag_sha)}`);if(e.status==="released")n.push(typeof e.counts.locked==="number"?` Objects locked: ${e.counts.locked}`:" Objects locked: not yet (resume applies the lock)");let r=Object.entries(e.counts).sort(([s],[i])=>s.localeCompare(i)).map(([s,i])=>`${s}=${i}`);if(r.length>0)n.push(` Counts: ${r.join(", ")}`);if(e.last_error)n.push(` Last error: ${e.last_error}`);if(n.push(` Created ${e.created_at} UTC, updated ${e.updated_at} UTC`),t===null)n.push(" Identifier screens: an xx dataset is not screened");else for(let s of t){let i=s.acknowledged_at!==null?`; acknowledged by administrator #${s.acknowledged_by} at ${s.acknowledged_at} UTC`:"";n.push(` Identifier screen of ${qo(s.sha)} (${s.pr}): ${s.headline} (gate: ${s.gate}${s.waiting?", running":""}${i})`);for(let a of s.lines)n.push(` ${a}`)}let o=NSt(e);if(o)n.push(` Next: ${o}`);return n}function ake(e){return` #${e.id}: ${e.from_tag} -> ${e.to_tag}, attempt ${e.attempt}, ${e.status}${e.terminal_at?` (${e.terminal_at} UTC)`:""}`}xa();import{mkdirSync as gRt,mkdtempSync as yRt,readFileSync as bRt,rmSync as TEe}from"fs";import{dirname as wRt,join as OEe}from"path";lo();Ke();gr();dn();xa();import{existsSync as FM,mkdirSync as FSt,readFileSync as MM,readdirSync as MSt,renameSync as jSt,rmSync as LSt,statSync as qSt,writeFileSync as jM}from"fs";import{join as qd}from"path";lo();dn();Vi();If();var cke="--automatic-dispatch",BSt="run-upstream-repull",lke=["mode","dataset_id","upstream_ds","from_tag","to_tag","dispatch_id","dispatch_token","cli_version","repull_id"],USt=new Set(["repull_id"]);function LM(e){return T$.test(e)?Number(e):null}function pr(e){return new N("dispatch-invalid",`The dispatch's ${e} is not what the Worker sends, so the run does not act on it.`)}function HSt(e){if(e===null||typeof e!=="object"||Array.isArray(e))throw pr("payload");let t=e,n=lke;for(let m of Object.keys(t))if(!n.includes(m))throw pr("set of keys");for(let m of lke){if(!(m in t)){if(!USt.has(m))throw pr("set of keys");continue}if(typeof t[m]!=="string")throw pr(m)}let r=t,o=r.mode;if(o!=="open"&&o!=="finish")throw pr("mode");let s=r.dataset_id;if(!/^on\d{6}$/.test(s))throw pr("dataset_id");let i=r.upstream_ds;if(!/^ds\d{6}$/.test(i))throw pr("upstream_ds");let{from_tag:a,to_tag:c}=r;if(!Jo(a))throw pr("from_tag");if(!Jo(c))throw pr("to_tag");if(Sr(a,c))throw pr("tag pair");let l=LM(r.dispatch_id);if(l===null)throw pr("dispatch_id");let d=null;if(r.repull_id!==void 0){if(d=LM(r.repull_id),d===null)throw pr("repull_id")}if(o==="finish"&&d===null)throw pr("repull_id");let f=r.dispatch_token;if(!R0e.test(f))throw pr("dispatch_token");let p=r.cli_version;if(!A$.test(p))throw pr("cli_version");return{mode:o,datasetId:s,upstreamDs:i,fromTag:a,toTag:c,dispatchId:l,repullId:d,token:f,cliVersion:p}}var zSt=1048576;function VSt(e){let t=e.GITHUB_EVENT_PATH,n=()=>new N("runner-failed","No dispatch event file: the automatic mode runs only inside the run-upstream-repull workflow.");if(!t)throw n();let r;try{if(qSt(t).size>zSt)throw pr("event");r=JSON.parse(MM(t,"utf8"))}catch(s){if(s instanceof N)throw s;if(s.code==="ENOENT")throw n();throw pr("event")}if(r===null||typeof r!=="object"||Array.isArray(r))throw pr("event");let o=r;if(o.action!==BSt)throw pr("event type");return HSt(o.client_payload)}var GSt=/^[a-z][a-z0-9-]{0,31}$/,WSt=/^[a-z][a-z0-9_]{0,31}$/,KSt=/^[a-z0-9_.-]{1,64}$/;function Zw(e,t={}){if(!GSt.test(e))return"repull-auto: unprintable-line";let n=[`repull-auto: ${e}`];for(let[r,o]of Object.entries(t)){let s=typeof o==="boolean"?o?"yes":"no":typeof o==="number"?Number.isSafeInteger(o)&&o>=0?String(o):"invalid":o;if(!WSt.test(r)||!KSt.test(s))return"repull-auto: unprintable-line";n.push(`${r}=${s}`)}return n.join(" ")}var hR=null;function gR(){if(hR)return hR;let e=process.stdout.write.bind(process.stdout),t=0,n=(...d)=>{t++;let f=d[d.length-1];if(typeof f==="function")queueMicrotask(()=>f(null));return!0},r=()=>{t++};for(let d of["log","info","warn","error","debug","trace","dir","table"])console[d]=r;process.stdout.write=n,process.stderr.write=n;let o=null,s=null,i=new Map,a=()=>{let d={suppressed:t};for(let[f,p]of i)d[`${f}_s`]=p;return d},c=()=>{let d=s;if(o=d?d.phase:"failed",e(`${Zw("quiet",a())}
|
|
413
|
+
`)}async function Xve(e,t){let n=t.counts.corrections,r=t.counts.conflicts,o=e.opts.takeOurs??[];if(typeof n!=="number"||typeof r!=="number")return e.opts.out(`Re-pull #${t.id}'s record does not say how many corrections and conflicts its plan has, so it is not completed; it stays released.`),{kind:"done",result:{row:t,outcome:"released"}};if(n===0&&r===0&&o.length===0)return Yve(e,t,"");if(r>0&&o.length===0&&!e.opts.keepUpstream)return{kind:"done",result:{row:t,outcome:"waiting",waitingFor:`an administrator's decision on the ${r} conflict(s) the plan lists, before N.0.1 is made: resolve one to NEMAR's side with --take-ours <path> (or --take-ours dataset_description.json#<Key>), or leave every one on upstream's side with --keep-upstream (the reviewed plan file names them, under conflicts and description.keys)`}};let s=O$(t.to_version);try{let i=await wSt(e,t);Ave(i);let a=Ove(i,o);if(a.corrections!==n)throw new N("patch-plan-mismatch",`The plan lists ${a.corrections} correction(s) and re-pull #${t.id} records ${n}; they are the same plan only when they agree.`);if(a.unresolved>0&&!e.opts.keepUpstream)return{kind:"done",result:{row:t,outcome:"waiting",waitingFor:`an administrator's decision on the ${a.unresolved} conflict(s) the plan lists that no --take-ours names, before N.0.1 is made: name each to take NEMAR's side, or add --keep-upstream to leave them on upstream's side`}};if(!Tve(a))return Yve(e,t,": the plan has no correction, and every conflict stays on upstream's side");return await vSt(e,t,a,s)}catch(i){if(i instanceof N&&!xSt.has(i.code))i.resumable=!0,await Zr(t,fs("patch",i),e.opts.out);throw i}}var xSt=new Set(["take-ours-invalid","declined","plan-unreadable","plan-schema","plan-environment","plan-sources","planner-version","plan-tampered","plan-not-the-record"]);async function vSt(e,t,n,r){let o=await Xw(e),{scratch:s}=o;if(o.prefix!==`${e.datasetId}/objects/`)throw new N("destination-prefix",`NEMAR's nemar-s3 is not at ${e.datasetId}/objects/, where the keys N.0.1 replays are read.`);let i=await Cl({work:s.dir,baseSha:t.merge_sha,env:s.env}),a=Kn(r),c=(await Rl(s,[a])).get(a),l,d,f;if(c){if(!await _r(s,a,us))throw Pt("origin-unreadable",`release/v${r} could not be fetched.`);let y=await oy({dir:s.dir,row:t,head:c}),b=y?await RM({scratch:s,row:t,selection:n,parent:y.parent}):null;if(!y||!b||b.sha!==y.commit)throw new N("branch-foreign",`release/v${r} exists on NEMAR's repository and is not this re-pull's N.0.1 commit with these resolutions; run resume with the resolutions the earlier run was given, or decline N.0.1 with nemar admin repull abandon ${e.datasetId}.`);l=y.commit,d=y.parent,f=b.keys}else{let y=await RM({scratch:s,row:t,selection:n,parent:i});l=y.sha,d=i,f=y.keys}let p;try{p=f.length>0?await Ld(o.aws,o.bucket,o.prefix):new Map}catch(y){if(!(y instanceof Bt))throw y;throw new N("s3-failed",`NEMAR's bucket could not be listed for the keys N.0.1 replays (${jd(y)}); the ambient AWS credentials list it.`)}if(await Nve({dir:s.dir,annexRef:"refs/remotes/origin/heads/git-annex",keys:f,nemarUuid:o.uuid,listing:p}),!c&&e.opts.confirm&&!await e.opts.confirm(`Make v${r} of ${e.datasetId}: replay ${n.paths.length} path(s) and ${n.keys.length} description key(s) onto main (${n.corrections} correction(s), ${n.resolutions} conflict(s) resolved to NEMAR's side, ${n.unresolved} left on upstream's side), push release/v${r} and open its pull request? Its merge will mint one more version DOI, which cannot be withdrawn.`))throw new N("declined","Not confirmed; nothing was pushed.");let m=await eR({work:s.dir,synthSha:l,version:r,push:{versions:[r]},env:s.env});e.opts.out(m.pushed?`Pushed release/v${r} (${l.slice(0,12)}).`:`release/v${r} is already this re-pull's N.0.1 commit${m.head===l?"":" (moved by enrichment)"}.`);let h=await tR({token:e.token,base:e.base,datasetId:e.datasetId,version:r,body:_St(t,n,r),acceptHead:(y)=>As({work:s.dir,from:l,head:y,ref:a,env:s.env})}),g;try{g=await Zn(t.id,{from:"released",to:"patch_synthesized",fields:{patch_version:r,patch_branch:`release/v${r}`,patch_pr_number:h.number,patch_head_sha:h.head,patch_base_sha:d,counts:{resolutions:n.resolutions}}})}catch(y){throw Qr(y,"N.0.1's pull request could not be recorded")}return e.opts.out(`${h.reused?"Found":"Opened"} N.0.1's pull request #${h.number} of release/v${r} (${n.resolutions} conflict(s) resolved to NEMAR's side, ${n.unresolved} left on upstream's side); re-pull #${t.id} is patch_synthesized. Resume never merges.`),{kind:"next",row:g}}async function SSt(e){try{return(await Io({dataset:e,open:!0,limit:1})).repulls[0]??null}catch(t){throw Qr(t,"The NEMAR API could not list the re-pulls")}}async function mR(e){return Fd(()=>$St(e))}async function $St(e){let t=e.env??process.env,n=kn(t),r=await ui(t);if(!r.ok)throw new N("no-github-token",`No GitHub token (${r.reason}): resume reads the pull request with the administrator's own (GH_TOKEN, or gh auth login).`);El(await ac(e.datasetId));let o=await SSt(e.datasetId);if(!o){let d=(await Io({dataset:e.datasetId,limit:1})).repulls[0]??null,f=e.automaticFinish;if(f&&!(d?.id===f.repullId&&d.status==="complete"))throw new N("finish-not-merged",`Re-pull #${f.repullId} is not open: a finish takes up only a merged re-pull.`);return{row:d,outcome:f?"complete":"nothing"}}if(e.automaticFinish)DSt(o,e.automaticFinish.repullId);let s=Vn(),i=wc(s,e.datasetId,o.plan_digest);wo(kSt(i.lock),ESt(s,"repull"));let a=$l(i.lock),c=null,l={datasetId:e.datasetId,token:r.token,base:n,env:t,configDir:s,opts:e,origin:async()=>(c??=await Dl({configDir:s,datasetId:e.datasetId,digest:o.plan_digest,purpose:"resume",env:t,token:r.token}),c),replaced:new Set,sleep:(d)=>new Promise((f)=>setTimeout(f,d))};if(((e.takeOurs?.length??0)>0||e.keepUpstream)&&o.status.startsWith("patch_"))e.out(`Re-pull #${o.id} is ${o.status}: N.0.1 is already made, so --take-ours and --keep-upstream change nothing now.`);try{return await RSt(l,o)}finally{c?.close(),a()}}function DSt(e,t){if(e.id!==t||e.origin!=="automatic")throw new N("repull-mismatch",`The dataset's open re-pull is #${e.id} (origin ${e.origin}); the finish takes up only #${t}, an automatic re-pull.`);if(e.status!=="merged"&&e.status!=="released")throw new N("finish-not-merged",`Re-pull #${e.id} is ${e.status}: a finish takes up only a merged re-pull.`)}async function RSt(e,t){let n=Date.now()+Math.max(0,e.opts.waitMinutes)*60000,r=Math.max(100,e.opts.pollMs??15000),o=t;for(let s=0;;){if(s>20)throw Pt("resume-looped",`Re-pull #${o.id} did not settle; run resume again.`);let i=await CSt(e,o);if(i.kind==="done")return i.result;if(i.kind==="next"){o=i.row,s++;continue}if(s=0,Date.now()+r>n)return{row:i.row,outcome:"waiting",waitingFor:i.waitingFor};e.opts.out(`Waiting for ${i.waitingFor}.`),await e.sleep(r);try{o=await P$(i.row.id)}catch(a){throw Qr(a,"The NEMAR API could not read the re-pull")}}}async function CSt(e,t){switch(t.status){case"planned":case"prepared":case"copied":case"registered":throw new N("use-execute",`Re-pull #${t.id} is ${t.status}: it is taken up by nemar admin repull execute <plan-file>, with the plan it was made from.`);case"pr_open":return Qve(e,t,"n0");case"patch_synthesized":return Qve(e,t,"n1");case"gates_clear":return Zve(e,t,"n0");case"patch_gates_clear":return Zve(e,t,"n1");case"merged":return IM(e,t,"n0");case"patch_merged":return IM(e,t,"n1");case"released":{let n=await Jve(e,t);return n.kind==="next"?Xve(e,n.row):n}case"patch_released":return ISt(e,t);default:throw new N("not-built",`Re-pull #${t.id} is ${t.status}, which resume does not take on.`)}}function eke(e,t){let n=Tr[t];return{pr:t,number:e[n.number],branch:e[n.branch],head:e[n.head],gates:e[n.gates],claimSha:e[n.claimSha],claimedAt:e[n.claimedAt],version:e[n.version],base:t==="n0"?e.base_sha:e.patch_base_sha,anchor:t==="n0"?e.synth_sha:e.patch_head_sha,closedTo:t==="n0"?"abandoned":"patch_declined"}}async function tke(e,t){let n=await Bi(e.token,e.datasetId,t.number,e.base);if(!n.ok)throw Pt("github-unreadable",`Pull request #${t.number} could not be read on GitHub (${n.reason})`);return n.value}async function nke(e,t,n){let r;try{r=await I$(t.id,n.pr)}catch(s){throw Qr(s,`The merge of pull request #${n.number} could not be recorded`)}let o=[r.merged_outside_tool?"no NEMAR tool held a claim for it":null,r.merged_unscreened_head?"at a head other than the screened one":null].filter(Boolean);return e.opts.out(`Pull request #${n.number} is merged; re-pull #${t.id} records it${o.length>0?` (${o.join(", ")})`:""}.`),{kind:"next",row:r.repull}}async function sy(e,t,n,r){try{return await Zn(e.id,{from:e.status,to:t,fields:n})}catch(o){throw Qr(o,r)}}function Qw(e,t,n,r){let o={...PM(e)};if(t.pr==="n0"){if(o.head_sha=n,r)o.synth_sha=r.synthSha,o.synth_tree=r.synthTree,o.base_sha=r.baseSha}else if(o.patch_head_sha=n,r)o.patch_base_sha=r.baseSha;return o}async function rke(e,t,n){let r=await sy(t,n.closedTo,{},"The record could not be ended");return e.opts.out(n.pr==="n0"?`Pull request #${n.number} was closed without being merged: re-pull #${t.id} is abandoned. Plan the dataset again to re-pull it.`:`N.0.1's pull request #${n.number} was closed without being merged: re-pull #${t.id} is patch_declined, and v${t.to_version} stays released; its corrections remain corrections in the next plan.`),{kind:"done",result:{row:r,outcome:"ended"}}}async function oke(e,t,n){return As({work:e.dir,from:t.anchor,head:n,ref:Kn(t.version),env:e.env})}async function ASt(e,t,n,r){if(n.pr==="n0")return Cve({scratch:e,row:t,head:r});let o=await ske(e,t,n);if(!o)return null;let s=await Fve({dir:e.dir,row:t,recorded:o,head:r});return s?{synthSha:s.sha,synthTree:s.tree,baseSha:s.baseSha}:null}async function ske(e,t,n){if(!await _r(e,n.anchor,us))return null;return await _r(e,t.merge_sha,us),(await oy({dir:e.dir,row:t,head:n.anchor}))?.commit??null}async function Qve(e,t,n){let r=eke(t,n),o=await tke(e,r);if(o.state==="merged")return nke(e,t,r);if(o.state==="closed")return rke(e,t,r);if(o.baseRef!=="main"||o.headRef!==r.branch){let h=Pt("pr-foreign",`Pull request #${r.number} is not ${r.branch} into main.`);throw await Zr(t,fs("gates",h),e.opts.out),h}if(!yd(o.headRepo,t.dataset_id)||!yd(o.baseRepo,t.dataset_id)){let h=Pt("pr-foreign",`Pull request #${r.number} is not from and into ${x0e}/${t.dataset_id} itself (its head is ${o.headRepo??"a repository GitHub no longer names"}, its base ${o.baseRepo??"a repository GitHub no longer names"}): a fork's pull request is never merged as a re-pull's.`);throw await Zr(t,fs("gates",h),e.opts.out),h}if(o.headSha!==r.head){if(e.replaced.has(o.headSha))return{kind:"wait",row:t,waitingFor:"GitHub to show the re-synthesized head"};let h=await e.origin(),g=await oke(h,r,o.headSha);if(g!=="ok"){let b=await ASt(h,t,r,o.headSha);if(b){let x=await sy(t,t.status,Qw(t,r,o.headSha,b),"The re-synthesized commit could not be recorded");return e.opts.out(`${r.branch} holds this re-pull's commit made again on a moved main (${b.synthSha.slice(0,12)}), pushed by an earlier run; re-pull #${t.id} records it.`),{kind:"next",row:x}}let _=g==="unreadable"?Pt("branch-unreadable",`Whether the head of ${r.branch} is this re-pull's commit and enrichment's could not be read.`):Pt("head-foreign",`${r.branch} holds a commit enrichment does not make: this pull request cannot be merged as it is; end the record with nemar admin repull abandon ${e.datasetId}.`);throw await Zr(t,fs("gates",_),e.opts.out),_}let y=await sy(t,t.status,Qw(t,r,o.headSha),"The moved head could not be recorded");return e.opts.out(`${r.branch} moved by enrichment to ${o.headSha.slice(0,12)}; re-pull #${t.id} records it.`),{kind:"next",row:y}}let s=await e.origin(),i;try{i=await Cl({work:s.dir,baseSha:r.base,env:s.env})}catch(h){if(h instanceof N)h.resumable=!0,await Zr(t,fs("gates",h),e.opts.out);throw h}let a=await _g(e.token,e.datasetId,r.number,{headSha:o.headSha,mergeableState:o.mergeableState},{base:e.base,sleep:e.sleep});if(!a.ok){if(a.kind==="unreadable")throw Pt("github-unreadable",`GitHub could not say whether #${r.number} can be merged.`);return{kind:"wait",row:t,waitingFor:`pull request #${r.number} to settle on GitHub`}}let c=a.state,l=i===r.base?[]:await zw(s.dir,r.base,i);if(l===null)throw Pt("main-unreadable","Whether NEMAR's main moved outside .nemar/ and .github/ could not be read; run resume again.");if(i!==r.base&&(c==="dirty"||c==="behind"||l.length>0))return PSt(e,t,r,i,o.headSha,l.length>0?`enrichment changed ${l.length} path(s) outside .nemar/ and .github/ on it`:`GitHub reports its pull request '${c}'`);let d=await OSt(e,t,r),f=[];if(d!==null)f.push(d);if(c!=="clean")f.push(`GitHub to report pull request #${r.number} clean (it reports '${c}')`);if(f.length>0)return{kind:"wait",row:t,waitingFor:f.join(", and ")};let p=Tr[n],m;try{m=await Zn(t.id,{from:p.open,to:p.gatesClear,fields:{[p.gates]:r.head}})}catch(h){let g=An(h);if(g==="head-moved"||g==="screen-changed")return{kind:"next",row:t};if(g==="screen-not-clear")return{kind:"wait",row:t,waitingFor:"the identifier screen to pass for this head"};throw Qr(h,"The gates could not be recorded")}return e.opts.out(`The identifier screen and GitHub pass for ${r.head.slice(0,12)}: re-pull #${t.id} is ${p.gatesClear}.`),{kind:"done",result:{row:m,outcome:"ready"}}}async function OSt(e,t,n){let r=n.head,o;try{o=await kg(t.id)}catch(i){throw Qr(i,"The identifier screens could not be read")}if(o.exempt)return null;let s=o.screens.find((i)=>i.pr===n.pr&&i.sha===r)??null;if(s===null||s.gate==="rerun"){try{let i=await I0e(t.id,{pr:n.pr,sha:r});if(i.exempt)return null;e.opts.out(`Dispatched the identifier screen of ${r.slice(0,12)}.`),s=i.screen}catch(i){if(An(i)!=="screen-exists")throw Qr(i,"The identifier screen could not be dispatched");s=i.rawBody?.screen??null}if(s===null||s.gate==="rerun"||s.gate==="wait")return`the identifier screen of ${r.slice(0,12)}`}switch(s.gate){case"clear":return null;case"wait":return`the identifier screen of ${r.slice(0,12)} (running)`;case"blocks":{let i=Pt("screen-blocks",`${s.headline}. A direct identifier cannot be acknowledged: this commit is not merged.`);throw await Zr(t,fs("gates",i),e.opts.out),i}case"acknowledge":{if(s.acknowledged_at!==null)return null;if(!e.opts.acknowledgment)return`an administrator's reason for the identifier screen (${s.headline}); read it with nemar admin repull status ${e.datasetId}, then run nemar admin repull resume ${e.datasetId} --acknowledge-identifier-screen "<reason>"`;try{await N0e(t.id,{pr:n.pr,sha:r,reason:e.opts.acknowledgment})}catch(i){throw Qr(i,"The acknowledgment could not be recorded")}return e.opts.out(`Recorded your acknowledgment of the identifier screen of ${r.slice(0,12)}.`),null}default:return`the identifier screen of ${r.slice(0,12)}`}}async function TSt(e,t,n,r,o){let s=await ske(e,t,n);if(!s)throw new N("origin-unreadable","N.0.1's commit could not be found beneath its recorded head on NEMAR's repository.");let i=await AM({dir:e.dir,commit:s,newMain:r}),a=Kn(n.version),c=await xc(e.dir,[`${i.sha}:${a}`],{versions:[n.version]},e.env,[`--force-with-lease=${a}:${o}`]);if(c.outcome==="rejected")throw new N("branch-moved",`release/v${n.version} moved while it was re-synthesized; nothing was replaced. Run resume again.`);if(c.outcome==="remote-rejected"||c.outcome==="failed")throw new N("push-failed",`The re-synthesized release/v${n.version} could not be pushed (${yi(c.cause)}).`);return{synthSha:i.sha,synthTree:i.tree}}async function PSt(e,t,n,r,o,s){if(e.opts.confirm&&!await e.opts.confirm(`NEMAR's main moved by enrichment since re-pull #${t.id}'s ${n.pr==="n0"?"commit":"N.0.1 commit"} was made, and ${s}. Make the commit again on the new main and push ${n.branch} with a lease (nothing enrichment wrote is undone)?`))throw new N("declined","Not confirmed; nothing was pushed.");let i=await e.origin(),a;try{a=n.pr==="n0"?await Rve({scratch:i,row:t,newMain:r,liveHead:o}):await TSt(i,t,n,r,o)}catch(l){if(l instanceof N)l.resumable=!0,await Zr(t,fs("gates",l),e.opts.out);throw l}e.replaced.add(o);let c=await sy(t,t.status,Qw(t,n,a.synthSha,{...a,baseSha:r}),"The re-synthesized commit could not be recorded");return e.opts.out(`Made re-pull #${t.id}'s commit again on the new main (${a.synthSha.slice(0,12)}) and pushed ${n.branch}; its identifier screen runs again for the new head.`),{kind:"next",row:c}}async function Zve(e,t,n){let r=eke(t,n),o=await tke(e,r);if(o.state==="merged")return nke(e,t,r);if(r.claimSha!==null)try{let c=await F0e(t.id,{pr:n,sha:r.claimSha,outcome:"expired"});return e.opts.out(`The claim to merge made at ${r.claimedAt} expired: GitHub says pull request #${r.number} did not merge, and its unit of today's merge cap is free.`),{kind:"next",row:c}}catch(c){let l=An(c);if(l==="pull-request-merged")return{kind:"next",row:t};if(l==="claim-too-recent")return{kind:"done",result:{row:t,outcome:"waiting",waitingFor:`the claim to merge made at ${r.claimedAt} to be resolved: run nemar admin repull merge ${e.datasetId} to send the merge again under it, or resume later to expire it`}};throw Qr(c,"The claim to merge could not be resolved")}if(o.state==="closed")return rke(e,t,r);if(o.headSha!==r.gates){let c=await e.origin(),l=await oke(c,r,o.headSha);if(l!=="ok")throw Pt(l==="unreadable"?"branch-unreadable":"head-foreign",`${r.branch} moved since its gates were recorded, ${l==="unreadable"?"and whether by enrichment only could not be read":"by a commit enrichment does not make"}.`);let d=await sy(t,Tr[n].open,Qw({...t,status:Tr[n].open},r,o.headSha),"The moved head could not be recorded");return e.opts.out(`${r.branch} moved by enrichment since its gates were recorded; re-pull #${t.id} is ${Tr[n].open} again, and its screen runs for the new head.`),{kind:"next",row:d}}let s=await e.origin(),i;try{i=await Cl({work:s.dir,baseSha:r.base,env:s.env})}catch(c){if(c instanceof N)c.resumable=!0;throw c}let a=i===r.base?[]:await zw(s.dir,r.base,i);if(a===null)throw Pt("main-unreadable","Whether NEMAR's main moved outside .nemar/ and .github/ since the gates could not be read; run resume again.");if(a.length>0){let c=Tr[n].open,l=await sy(t,c,Qw({...t,status:c},r,o.headSha),"The return to the open pull request could not be recorded");return e.opts.out(`NEMAR's main moved by enrichment since the gates, on ${a.length} path(s) outside .nemar/ and .github/: re-pull #${t.id} is ${c} again, and its commit is made again on the new main.`),{kind:"next",row:l}}return{kind:"done",result:{row:t,outcome:"ready"}}}async function ISt(e,t){let n;try{n=await Zn(t.id,{from:"patch_released",to:"complete"})}catch(r){throw Qr(r,"The record could not be completed")}return e.opts.out(`Re-pull #${t.id} of ${e.datasetId} is complete: v${t.to_version} and v${t.patch_version} are released.`),{kind:"done",result:{row:n,outcome:"complete"}}}var qo=(e)=>e?e.slice(0,12):"none";function NSt(e){let t=e.dataset_id;switch(e.status){case"planned":case"prepared":case"copied":case"registered":return"nemar admin repull execute <plan-file> (the reviewed plan this record was made from)";case"pr_open":return`nemar admin repull resume ${t} (the identifier screen and the gates)`;case"gates_clear":return e.merge_claim_sha?`nemar admin repull merge ${t} (sends the merge again under the held claim), or resume ${t} once the claim is old enough to expire`:`nemar admin repull merge ${t} (mints one version DOI, v${e.to_version})`;case"merged":return`nemar admin repull resume ${t} (the release, the lock, then N.0.1 or the end)`;case"released":return typeof e.counts.conflicts==="number"&&e.counts.conflicts>0?`nemar admin repull resume ${t} --take-ours <path> or --keep-upstream (the lock, then N.0.1 or the end; the plan's ${e.counts.conflicts} conflict(s) wait for your decision), or nemar admin repull abandon ${t} (declines N.0.1)`:`nemar admin repull resume ${t} (the lock, then N.0.1 or the end)`;case"patch_synthesized":return`nemar admin repull resume ${t} (N.0.1's identifier screen and gates)`;case"patch_gates_clear":return e.patch_merge_claim_sha?`nemar admin repull merge ${t} (sends N.0.1's merge again under the held claim), or resume ${t} once the claim is old enough to expire`:`nemar admin repull merge ${t} (mints one version DOI, v${e.patch_version})`;case"patch_merged":case"patch_released":return`nemar admin repull resume ${t} (N.0.1's release and the end)`;default:return bF(e.status)?null:`nemar admin repull resume ${t}`}}function ike(e,t){let n=[`Re-pull #${e.id} of ${e.dataset_id}: ${e.status} (attempt ${e.attempt}, ${e.origin})`,` Upstream ${e.upstream_ds}: ${e.from_tag} -> ${e.to_tag}, as v${e.to_version} (from v${e.from_version})`,` Plan: ${e.plan_digest} (planner ${e.planner})`,` Base: ${qo(e.base_sha)} Commit: ${qo(e.synth_sha)} Tree: ${qo(e.synth_tree)}`];if(e.pr_number!==null)n.push(` Pull request: #${e.pr_number} of ${e.branch}, head ${qo(e.head_sha)}`);if(e.gates_sha)n.push(` Gates clear at: ${qo(e.gates_sha)}`);if(e.merge_claim_sha)n.push(` Claim to merge: ${qo(e.merge_claim_sha)}, made ${e.merge_claimed_at} UTC`);if(e.merge_sha)n.push(` Merge: ${qo(e.merge_sha)}`);if(e.tag_sha)n.push(` Tag v${e.to_version}: ${qo(e.tag_sha)}`);if(e.patch_pr_number!==null)n.push(` N.0.1 pull request: #${e.patch_pr_number} of ${e.patch_branch}, head ${qo(e.patch_head_sha)}, base ${qo(e.patch_base_sha)}`);if(e.patch_gates_sha)n.push(` N.0.1 gates clear at: ${qo(e.patch_gates_sha)}`);if(e.patch_merge_claim_sha)n.push(` N.0.1 claim to merge: ${qo(e.patch_merge_claim_sha)}, made ${e.patch_merge_claimed_at} UTC`);if(e.patch_merge_sha)n.push(` N.0.1 merge: ${qo(e.patch_merge_sha)}`);if(e.patch_tag_sha)n.push(` Tag v${e.patch_version}: ${qo(e.patch_tag_sha)}`);if(e.status==="released")n.push(typeof e.counts.locked==="number"?` Objects locked: ${e.counts.locked}`:" Objects locked: not yet (resume applies the lock)");let r=Object.entries(e.counts).sort(([s],[i])=>s.localeCompare(i)).map(([s,i])=>`${s}=${i}`);if(r.length>0)n.push(` Counts: ${r.join(", ")}`);if(e.last_error)n.push(` Last error: ${e.last_error}`);if(n.push(` Created ${e.created_at} UTC, updated ${e.updated_at} UTC`),t===null)n.push(" Identifier screens: an xx dataset is not screened");else for(let s of t){let i=s.acknowledged_at!==null?`; acknowledged by administrator #${s.acknowledged_by} at ${s.acknowledged_at} UTC`:"";n.push(` Identifier screen of ${qo(s.sha)} (${s.pr}): ${s.headline} (gate: ${s.gate}${s.waiting?", running":""}${i})`);for(let a of s.lines)n.push(` ${a}`)}let o=NSt(e);if(o)n.push(` Next: ${o}`);return n}function ake(e){return` #${e.id}: ${e.from_tag} -> ${e.to_tag}, attempt ${e.attempt}, ${e.status}${e.terminal_at?` (${e.terminal_at} UTC)`:""}`}xa();import{mkdirSync as gRt,mkdtempSync as yRt,readFileSync as bRt,rmSync as TEe}from"fs";import{dirname as wRt,join as OEe}from"path";lo();Je();gr();dn();xa();import{existsSync as FM,mkdirSync as FSt,readFileSync as MM,readdirSync as MSt,renameSync as jSt,rmSync as LSt,statSync as qSt,writeFileSync as jM}from"fs";import{join as qd}from"path";lo();dn();Vi();If();var cke="--automatic-dispatch",BSt="run-upstream-repull",lke=["mode","dataset_id","upstream_ds","from_tag","to_tag","dispatch_id","dispatch_token","cli_version","repull_id"],USt=new Set(["repull_id"]);function LM(e){return T$.test(e)?Number(e):null}function pr(e){return new N("dispatch-invalid",`The dispatch's ${e} is not what the Worker sends, so the run does not act on it.`)}function HSt(e){if(e===null||typeof e!=="object"||Array.isArray(e))throw pr("payload");let t=e,n=lke;for(let m of Object.keys(t))if(!n.includes(m))throw pr("set of keys");for(let m of lke){if(!(m in t)){if(!USt.has(m))throw pr("set of keys");continue}if(typeof t[m]!=="string")throw pr(m)}let r=t,o=r.mode;if(o!=="open"&&o!=="finish")throw pr("mode");let s=r.dataset_id;if(!/^on\d{6}$/.test(s))throw pr("dataset_id");let i=r.upstream_ds;if(!/^ds\d{6}$/.test(i))throw pr("upstream_ds");let{from_tag:a,to_tag:c}=r;if(!Jo(a))throw pr("from_tag");if(!Jo(c))throw pr("to_tag");if(Sr(a,c))throw pr("tag pair");let l=LM(r.dispatch_id);if(l===null)throw pr("dispatch_id");let d=null;if(r.repull_id!==void 0){if(d=LM(r.repull_id),d===null)throw pr("repull_id")}if(o==="finish"&&d===null)throw pr("repull_id");let f=r.dispatch_token;if(!R0e.test(f))throw pr("dispatch_token");let p=r.cli_version;if(!A$.test(p))throw pr("cli_version");return{mode:o,datasetId:s,upstreamDs:i,fromTag:a,toTag:c,dispatchId:l,repullId:d,token:f,cliVersion:p}}var zSt=1048576;function VSt(e){let t=e.GITHUB_EVENT_PATH,n=()=>new N("runner-failed","No dispatch event file: the automatic mode runs only inside the run-upstream-repull workflow.");if(!t)throw n();let r;try{if(qSt(t).size>zSt)throw pr("event");r=JSON.parse(MM(t,"utf8"))}catch(s){if(s instanceof N)throw s;if(s.code==="ENOENT")throw n();throw pr("event")}if(r===null||typeof r!=="object"||Array.isArray(r))throw pr("event");let o=r;if(o.action!==BSt)throw pr("event type");return HSt(o.client_payload)}var GSt=/^[a-z][a-z0-9-]{0,31}$/,WSt=/^[a-z][a-z0-9_]{0,31}$/,KSt=/^[a-z0-9_.-]{1,64}$/;function Zw(e,t={}){if(!GSt.test(e))return"repull-auto: unprintable-line";let n=[`repull-auto: ${e}`];for(let[r,o]of Object.entries(t)){let s=typeof o==="boolean"?o?"yes":"no":typeof o==="number"?Number.isSafeInteger(o)&&o>=0?String(o):"invalid":o;if(!WSt.test(r)||!KSt.test(s))return"repull-auto: unprintable-line";n.push(`${r}=${s}`)}return n.join(" ")}var hR=null;function gR(){if(hR)return hR;let e=process.stdout.write.bind(process.stdout),t=0,n=(...d)=>{t++;let f=d[d.length-1];if(typeof f==="function")queueMicrotask(()=>f(null));return!0},r=()=>{t++};for(let d of["log","info","warn","error","debug","trace","dir","table"])console[d]=r;process.stdout.write=n,process.stderr.write=n;let o=null,s=null,i=new Map,a=()=>{let d={suppressed:t};for(let[f,p]of i)d[`${f}_s`]=p;return d},c=()=>{let d=s;if(o=d?d.phase:"failed",e(`${Zw("quiet",a())}
|
|
414
414
|
`),d){e(`${Zw("report-stands",{phase:d.phase})}
|
|
415
415
|
`);let{phase:f,code:p}=d;e(`${Zw("result",p===void 0?{phase:f}:{phase:f,code:p})}
|
|
416
416
|
`);return}e(`${Zw("result",{phase:"failed",code:"runner-failed"})}
|
|
417
417
|
`)};hR={emit(d,f){if(d==="result")o=String(f?.phase??"failed");e(`${Zw(d,f)}
|
|
418
418
|
`)},drop(){t++},dropped:()=>t,stored(d,f){s={phase:d,code:d==="refused"||d==="failed"?f:void 0}},time(d,f){i.set(d,f)},quietFields:a},process.on("exit",()=>{if(o===null)c()});let l=()=>{try{t++;let d=o;if(s?d!==s.phase:d===null||d==="planned"||d==="opened"||d==="finished")c()}finally{process.exit(1)}};return process.on("uncaughtException",l),process.on("unhandledRejection",l),hR}function qM(e){return e.some((t)=>t===cke||t.startsWith(`${cke}=`))}function JSt(e){let t=e.GITHUB_RUN_ID??"";if(e.GITHUB_SERVER_URL==="https://github.com"&&e.GITHUB_REPOSITORY==="nemarDatasets/.github"&&/^[0-9]{1,20}$/.test(t))return`https://github.com/nemarDatasets/.github/actions/runs/${t}`;return null}function fke(e,t,n){let r=LM(e);if(r===null)throw pr("id on the command line");let o=VSt(t);if(o.dispatchId!==r)throw new N("dispatch-mismatch","The dispatch named on the command line is not the one the event delivered.");let s=t.RUNNER_TEMP;return{dispatch:o,runUrl:JSt(t),marker:s?qd(s,"repull-reported"):null,sink:n}}var YSt="https://api.nemar.org";function pke(e){let t;try{t=new URL(e)}catch{return!1}if(t.username||t.password||t.search||t.hash||t.pathname!=="/"&&t.pathname!=="")return!1;if(t.protocol==="https:")return t.host===new URL(YSt).host;return t.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(t.hostname)}function BM(e,t){if(!t.some((n)=>n.includes(e.token)))return null;return new N("auto-token-on-argv","The dispatch token is on the command line, where the public log shows it.")}function mke(e,t){let n=BM(e,t.argv);if(n)return n;let r=t.ownVersion??ks;if((t.devBuild??Nf)||!A$.test(r)||r!==e.cliVersion)return new N("auto-cli-version","This CLI is not the release the dispatch names: an automatic run uses only that release.");if(t.verbose??(Jh()||sl()||t.argv.includes("--verbose")||t.argv.includes("--debug")))return new N("auto-verbose","Verbose or debug output is on, and it prints what the run reads; an automatic run takes neither.");if(e.mode!==t.mode||e.datasetId!==t.datasetId)return new N("dispatch-mismatch","The command is not the one the dispatch asks for: another kind of run, or another dataset.");if(!t.env.GH_TOKEN?.trim())return new N("auto-no-app-token","GH_TOKEN is not set: an automatic run pushes and opens its pull request with the App token minted for this dataset.");if(yR(t.env,t.nowMs??Date.now())===null)return new N("auto-token-clock",`${hke} does not say when the App token was minted, so the run cannot keep its pushes inside the token's hour.`);return null}var hke="NEMAR_REPULL_TOKEN_SINCE";function yR(e,t){let n=e[hke]?.trim()??"";if(!/^[1-9][0-9]{0,11}$/.test(n))return null;let r=Number(n);return r*1000<=t+300000?r:null}function XSt(e,t){return(e+sw)*1000-t}function e_(e,t,n){let r=(n+C0e+xF)*1000;if(XSt(e,t)>=r)return null;return new N("auto-token-hour","What is left to do would pass the App token's usable hour, so the run stops before this step; the record, if there is one, stays where it stopped.")}function t_(e){let t=kc(e);return kF({bytes:t.copy_bytes??0,objects:t.copy_items??0})}function iy(e,t){return new N("auto-option",t==="required"?`An automatic run needs ${e}.`:`An automatic run does not take ${e}.`)}function gke(e){if(!e.executable)throw new N("not-executable","The plan is not executable.");bR(e.body)}function bR(e){let t=kc(e),n=D0e(e.planner,t);if(n)throw new N(n.code,n.message);if(t.copy_bytes_unknown!==0)throw new N("auto-copy-too-large","An automatic re-pull takes only a plan whose copy size is known for every key.");let{copy_bytes:r,copy_items:o,local_bytes:s,local_uploads:i}=t,a=QSt();if(r===void 0||o===void 0||s===void 0||i===void 0||t.local_bytes_unknown!==0||kF({bytes:r+s,objects:o+i})>a)throw new N("auto-copy-too-long",`An automatic re-pull takes only a plan whose copy, by its known size and count, fits ${Math.floor(a/60)} minutes: the App token that pushes it lasts an hour.`)}function wR(e){return`${e}.planner`}function yke(e,t,n,r){FSt(qd(t,"computed"),{mode:448});for(let[s,i]of n)jM(qd(t,"computed",s),i,{mode:384});jM(qd(t,"digest"),`${r}
|
|
419
419
|
`,{mode:384});let o=wR(e);LSt(o,{recursive:!0,force:!0}),jSt(t,o)}function bke(e,t){let n=wR(e),r=qd(n,"computed"),o=qd(n,"digest");if(!FM(qd(n,"upstream.git"))||!FM(r)||!FM(o)||MM(o,"utf8").trim()!==t)throw new N("not-planned","No handoff of this plan's own plan step is beside the plan file; an automatic execute plans nothing itself.");let s=new Map;for(let i of MSt(r))s.set(i,MM(qd(r,i)));return{workdir:n,computed:s}}function QSt(e=process.env){let t=e.NEMAR_REPULL_COPY_BUDGET_SECONDS?.trim()??"",n=/^\d{1,9}$/.test(t)?Number(t):Number.NaN;return Number.isFinite(n)&&n<vF?n:vF}async function wke(e,t,n=fetch){let r=t.GH_TOKEN?.trim();if(!r)return!1;let o;try{o=kn(t)}catch{return!1}try{let s=await n(`${o}/repos/nemarDatasets/${e}`,{redirect:"error",headers:{Authorization:`Bearer ${r}`,Accept:"application/vnd.github+json","User-Agent":"nemar-cli"},signal:AbortSignal.timeout(1e4)});return await s.body?.cancel().catch(()=>{return}),s.status===401}catch{return!1}}function _R(e,t){if(_F(e))return e;if(t===void 0)return"no-code";if(t==="prepare"&&C_e.includes(e??""))return"scrub-failed";return $0e[t]}var ZSt=15000,uke=["opened","finished","refused","failed"];async function UM(e,t,n={},r={}){let o={dispatch_id:e.dispatch.dispatchId,dataset_id:e.dispatch.datasetId,phase:t};if(t==="refused"||t==="failed")o.code=_R(n.code);if(t==="opened")o.repull_id=n.repullId;if(e.runUrl)o.workflow_run_url=e.runUrl;let s=r.fetchImpl??fetch,i=r.apiUrl??Cr(),a=Math.max(1,r.attempts??3),c={stored:!1,code:"report-unanswered"};for(let l=1;l<=a;l++){let d,f;try{let p=await s(`${i}/webhooks/repull-state`,{method:"POST",redirect:"error",headers:{"Content-Type":"application/json","X-Repull-Token":e.dispatch.token},body:JSON.stringify(o),signal:AbortSignal.timeout(r.timeoutMs??ZSt)});d=p.status,f=(await p.json().catch(()=>null))?.code}catch{if(c={stored:!1,code:"report-unanswered"},l<a)await dke(r.backoffMs??2000);continue}if(d===200){c={stored:!0};break}if(c={stored:!1,code:typeof f==="string"&&_F(f)?f:"report-unanswered"},d<500)break;if(l<a)await dke(r.backoffMs??2000)}if(e.sink.emit("report",{phase:t,answer:c.stored?"stored":c.code}),c.stored&&uke.includes(t))e.sink.stored(t,o.code);if(c.stored&&uke.includes(t)&&e.marker)try{jM(e.marker,`${t}
|
|
420
|
-
`,{mode:384})}catch{}return c}var dke=(e)=>new Promise((t)=>setTimeout(t,e));xa();import{existsSync as tRt,readdirSync as nRt,rmdirSync as rRt}from"fs";import{dirname as l_,join as c_}from"path";lo();
|
|
420
|
+
`,{mode:384})}catch{}return c}var dke=(e)=>new Promise((t)=>setTimeout(t,e));xa();import{existsSync as tRt,readdirSync as nRt,rmdirSync as rRt}from"fs";import{dirname as l_,join as c_}from"path";lo();Je();gr();lc();Pr();Td();Vi();IR();Dg();import{dirname as yDt,join as bDt}from"path";Je();gr();function Uo(e,t){return new N(e,t)}var sj=["registered","pr_open","gates_clear"];async function Zke(e,t,n){let r=await Qg({token:e.token,base:e.base,datasetId:e.datasetId,state:"all",head:t});if(!r.ok)throw Uo("github-unreadable",`GitHub's pull requests of ${t} could not be read whole (${Xg(r)}), so whether one merged is not known; nothing was closed.`);let o=new Set(r.pulls.filter((i)=>i.headRef===t).map((i)=>i.number));if(n!==null)o.add(n);let s=[];for(let i of[...o].sort((a,c)=>a-c)){let a=await Bi(e.token,e.datasetId,i,e.base);if(!a.ok)throw Uo("github-unreadable",`Pull request #${i} could not be read on GitHub (${a.reason}); nothing was closed.`);s.push({number:i,state:a.value.state,headSha:a.value.headSha})}return s}function wDt(e,t,n,r){return Uo("foreign-pull-request-merged",`GitHub says pull request #${t} of ${n} merged, and it is not this re-pull's (it recorded #${r}): that version was released outside the re-pull, which resume does not record. Nothing was closed or ended; read the dataset's history on GitHub (nemarDatasets/${e.datasetId}) to see what merged before this record is ended.`)}function eEe(e,t,n,r){return r!==null&&t!==r?wDt(e,t,n,r):tEe(e,t)}function tEe(e,t,n=!1){return(n?Pt:Uo)("pull-request-merged",`GitHub says pull request #${t} merged, so this re-pull is not ended: nemar admin repull resume ${e.datasetId} records the merge (a merge minted a DOI, and its release is recorded, not abandoned).`)}async function _Dt(e,t){let n=(await Ps(e,t)).filter((a)=>a.mode==="120000"||a.mode==="100644"||a.mode==="100755"),r=new Map;if(n.length>0){let a=await te(e,["cat-file","--batch-check"],{stdin:`${n.map((c)=>c.oid).join(`
|
|
421
421
|
`)}
|
|
422
422
|
`,code:"origin-unreadable",step:"cat-file"});for(let c of a.stdout.split(`
|
|
423
423
|
`)){let[l,d,f]=c.split(" ");if(l&&d==="blob"&&f)r.set(l,Number(f))}}let o=n.filter((a)=>a.mode==="120000"||(r.get(a.oid)??Number.POSITIVE_INFINITY)<=1024),s=await Nd(e,o.map((a)=>a.oid)),i=new Set;for(let a of o){let c=s.get(a.oid),l=c?fp(a.mode,c):null;if(l)i.add(l)}return i}async function xDt(e,t){if(t.status==="planned"||t.manifest_digest===null)return{orphans:null,why:"the record has no copy manifest yet, so what preparation may have uploaded is not listed"};try{let n=await Xw(e),r=await NM(e,t,n),o=n.scratch;if(!await _r(o,"refs/heads/main",1))return{orphans:null,why:"NEMAR's main could not be fetched"};let s=await _Dt(o.dir,"refs/remotes/origin/heads/main"),i=await Ld(n.aws,n.bucket,n.prefix),a=0,c=0;for(let l of r){if(s.has(l)||!cr(l,i))continue;a++,c+=i.get(l)??0}return{orphans:{objects:a,bytes:c}}}catch(n){if(n instanceof N&&n.code==="staging-unreadable")return{orphans:null,why:"the staging manifest the copy writes is not readable (it is written before the first copy)"};return{orphans:null,why:`they could not be read (${n instanceof N?n.code:n instanceof Error?n.name:"error"})`}}}async function vDt(e,t,n){let r=Kn(t),o=await xc(e.dir,["--delete",r],{versions:[t]},e.env,[`--force-with-lease=${r}:${n}`]);if(o.outcome==="rejected")throw Pt("branch-moved",`release/v${t} moved since it was judged this re-pull's, so it was not deleted and the record was not ended. Run abandon again.`);if(o.outcome!=="pushed"&&o.outcome!=="up-to-date")throw Pt("push-failed",`release/v${t} could not be deleted (${yi(o.cause)}); the record was not ended. Run abandon again.`)}async function kDt(e,t){let n=t.to_version;if(t.merge_claim_sha!==null)throw Uo("merge-claim-held",`A claim to merge re-pull #${t.id}'s pull request is held, so it may have merged: run nemar admin repull resume ${e.datasetId}, which reads GitHub and records the merge or expires the claim, then abandon again.`);let r={version:n,close:[],deleteHead:null,branch:"absent"};if(!sj.includes(t.status))return r;let o=`release/v${n}`,s=await e.origin(),i=async(c)=>c===t.head_sha||t.synth_sha!==null&&await As({work:s.dir,from:t.synth_sha,head:c,ref:Kn(n),env:s.env})==="ok";for(let c of await Zke(e,o,t.pr_number)){if(c.state==="merged")throw eEe(e,c.number,o,t.pr_number);if(c.state==="open"&&(c.number===t.pr_number||await i(c.headSha)))r.close.push(c.number)}let a=(await Rl(s,[Kn(n)])).get(Kn(n));if(a){let c=await EDt(s,t.synth_sha,a,n,t.head_sha);if(r.branch=c==="ok"?"deleted":c==="unreadable"?"kept-unreadable":"kept-foreign",c==="ok")r.deleteHead=a}return r}async function EDt(e,t,n,r,o){if(n===o||n===t)return"ok";if(t===null)return"foreign";return As({work:e.dir,from:t,head:n,ref:Kn(r),env:e.env})}async function SDt(e,t){let n=t.patch_version??`${t.to_version.split(".")[0]}.0.1`;if(t.patch_merge_claim_sha!==null)throw Uo("merge-claim-held",`A claim to merge re-pull #${t.id}'s N.0.1 pull request is held, so it may have merged: run nemar admin repull resume ${e.datasetId}, which reads GitHub and records the merge or expires the claim, then abandon again.`);let r=`release/v${n}`,o=Kn(n),s=await e.origin(),i=(await Rl(s,[o])).get(o),a=null;if(i)if(i===t.patch_head_sha)a="ok";else if(!await _r(s,o,us)||!await _r(s,t.merge_sha,us))a="unreadable";else a=await oy({dir:s.dir,row:t,head:i})?"ok":"foreign";let c={version:n,close:[],deleteHead:i&&a==="ok"?i:null,branch:a===null?"absent":a==="ok"?"deleted":a==="unreadable"?"kept-unreadable":"kept-foreign"};for(let l of await Zke(e,r,t.patch_pr_number)){if(l.state==="merged")throw eEe(e,l.number,r,t.patch_pr_number);let d=l.number===t.patch_pr_number||a==="ok"&&l.headSha===i;if(l.state==="open"&&d)c.close.push(l.number)}return c}async function nEe(e,t,n,r,o){for(let s of n.close){let i=await $$(e.token,e.datasetId,s,e.base),a=await Bi(e.token,e.datasetId,s,e.base);if(a.ok&&a.value.state==="merged")throw tEe(e,s,!0);if(!a.ok||a.value.state!=="closed")throw Pt("github-failed",`Pull request #${s} could not be closed (${i.ok?"it is not closed":i.reason}); the record was not ended. Run abandon again.`);e.out(`Closed pull request #${s}.`)}if(n.deleteHead!==null)await vDt(await e.origin(),n.version,n.deleteHead),e.out(`Deleted release/v${n.version}.`);try{return await Zn(t.id,{from:t.status,to:r,fields:o?{counts:{orphan_objects:o.objects,orphan_bytes:o.bytes}}:{}})}catch(s){let i=An(s)??(s instanceof L?"record-refused":"github-failed");throw Pt(i,`The record could not be ended: ${s instanceof Error?s.message:String(s)}`)}}async function ij(e,t,n,r,o={}){if(!vg.includes(t.status))throw Uo("bad-transition",`Re-pull #${t.id} is ${t.status}, not before its merge.`);let s=await kDt(e,t);if(o.branchMustGo&&(s.branch==="kept-foreign"||s.branch==="kept-unreadable"))throw Uo("branch-foreign",`release/v${s.version} ${s.branch==="kept-foreign"?`holds a commit that is not re-pull #${t.id}'s or enrichment's`:"could not be read"}, so it is not deleted, and the new record would push the same branch: nothing was closed or recorded. Check what the branch holds and remove it, then execute again.`);let{orphans:i,why:a}=await xDt(e,t),c=[s.close.length>0?`close pull request ${s.close.map((f)=>`#${f}`).join(", ")}`:null,s.deleteHead?`delete release/v${s.version}`:null,`end re-pull #${t.id} ${n}`].filter(Boolean),l=i?`${i.objects} object(s), ${i.bytes} byte(s), that its copy and uploads wrote stay in NEMAR's bucket, unlocked, and are not deleted`:`what its copy and uploads wrote stays in NEMAR's bucket, not deleted (not counted: ${a})`;if(r&&!await r(`${c.join(", ")}? The ${l}.`))throw Uo("declined","Not confirmed; nothing was closed, deleted or recorded.");let d=await nEe(e,t,s,n,i);return rEe(e,t),{row:d,report:{closed:s.close,branch:s.branch,orphans:i,...i?{}:{orphansUnknown:a}}}}async function $Dt(e,t,n){if(t.status==="released"&&typeof t.counts.locked!=="number")throw Uo("lock-unrecorded",`Re-pull #${t.id} records no count of locked objects: run nemar admin repull resume ${e.datasetId}, which locks what N.0.0's copy and uploads wrote, then abandon again to decline N.0.1.`);let r=await SDt(e,t),o=[r.close.length>0?`close N.0.1's pull request ${r.close.map((i)=>`#${i}`).join(", ")}`:null,r.deleteHead?`delete release/v${r.version}`:null,`end re-pull #${t.id} patch_declined`].filter(Boolean);if(n&&!await n(`${o.join(", ")}? v${t.to_version} stays released; its corrections remain corrections in the next plan.`))throw Uo("declined","Not confirmed; nothing was closed, deleted or recorded.");let s=await nEe(e,t,r,"patch_declined",null);return rEe(e,t),{row:s,report:{closed:r.close,branch:r.branch,orphans:null}}}function rEe(e,t){let n=wc(e.configDir,e.datasetId,t.plan_digest);for(let r of[n.root,n.bundle])try{Cs(r)}catch{e.out(`${r} could not be removed; remove it by hand (it may hold unscrubbed originals).`)}}async function oEe(e){return Fd(()=>DDt(e))}async function DDt(e){let t=e.env??process.env,n=kn(t),r=await ui(t);if(!r.ok)throw Uo("no-github-token",`No GitHub token (${r.reason}): abandon reads and closes the pull request with the administrator's own (GH_TOKEN, or gh auth login).`);let o;try{o=(await Io({dataset:e.datasetId,open:!0,limit:1})).repulls[0]??null}catch(d){throw Uo(An(d)??"record-refused",`The NEMAR API could not list the re-pulls: ${d instanceof Error?d.message:String(d)}`)}if(!o)return{row:(await Io({dataset:e.datasetId,limit:1})).repulls[0]??null,outcome:"nothing"};if(o.status==="merged"||o.status==="patch_merged"||o.status==="patch_released")throw Uo("wait-for-release",`Re-pull #${o.id} is ${o.status}: its merge minted a DOI, so its release is recorded first (nemar admin repull resume ${e.datasetId}); a merged pull request is never abandoned.${o.status==="merged"?" Once N.0.0 is released, abandon declines N.0.1.":""}`);let s=Vn(),i=wc(s,e.datasetId,o.plan_digest);wo(yDt(i.lock),bDt(s,"repull"));let a=$l(i.lock),c=null,l={datasetId:e.datasetId,token:r.token,base:n,env:t,configDir:s,out:e.out,origin:async()=>(c??=await Dl({configDir:s,datasetId:e.datasetId,digest:o.plan_digest,purpose:"resume",env:t,token:r.token}),c)};try{if(vg.includes(o.status)){let d=await ij(l,o,"abandoned",e.confirm);return{row:d.row,outcome:"abandoned",report:d.report}}if(wF.includes(o.status)){let d=await $Dt(l,o,e.confirm);return{row:d.row,outcome:"patch_declined",report:d.report}}throw Uo("bad-transition",`Re-pull #${o.id} is ${o.status}, which abandon does not end.`)}finally{c?.close(),a()}}import{dirname as bEe}from"path";iD();lc();kR();Vi();$d();kR();Vi();import{mkdtempSync as RDt,rmSync as CDt,writeFileSync as ADt}from"fs";import{join as aj}from"path";var cj="refs/remotes/origin/git-annex",sEe=3;async function NR(e,t){let n=await te(e,["annex","find","--include","*",`--branch=${t}`,"--format=${key}\\t${file}\\n"],{code:"registration-failed",step:"annex find"}),r=new Map;for(let o of n.stdout.split(`
|
|
@@ -439,8 +439,8 @@ ${b.message}`,r);if(_)return sn("message",`The squash message would not carry th
|
|
|
439
439
|
`)return!1;try{return JSON.parse(r).action==="repull-scrubbed"}catch{return!1}}function VDt(e){let{tree:t,base:n,expected:r,preScrub:o,scope:s,scrub:i}=e,a=new Set(e.uploaded.map((k)=>k.key)),c=(k)=>k?.mode===UDt,l=0,d=0,f=0,p=new Set([...t.keys(),...n.keys(),...r.keys()]);for(let k of p){let v=t.get(k),C=a_(v),T=r.get(k);if(Gi(k)){if(k===FR){if(!zDt({got:v,base:n.get(k),text:e.ledger,changed:HDt(i)}))f++}else if(k===BDt&&T!==void 0){if(C!==T||v?.key!==null)d++}else if(ly(v)!==ly(n.get(k)))d++;continue}let z=(A)=>s.has(k)&&v!==void 0&&v.key===null&&a_(o.get(k))===A&&v.mode===o.get(k)?.mode&&C!==A&&(lp.test(k)||up.test(k)||lj.has(k));if(T===void 0){let A=n.get(k);if(ly(v)!==ly(A)&&!(lj.has(k)&&z(a_(A))))l++;continue}if(T==="absent"){if(v)l++;continue}if(T.startsWith("A:")){let A=T.slice(2),F=Mo.test(k)&&i.replacedKeys.has(A)&&v?.key!=null&&a.has(v.key);if(C!==T&&!F||!c(v))l++;continue}if(T.startsWith("L:")){if(!v?.key||!a.has(v.key)||!c(v))l++;continue}if(C!==T&&!z(T))l++}if(l>0)throw Tl("path(s) differ from their target",l);if(d>0)throw Tl("NEMAR-owned path(s) differ from NEMAR's side",d);if(f>0)throw Tl("privacy ledger(s) not the base's plus the scrub's one line",f);let m=new Set;for(let[k,v]of t)if(v.key&&!Gi(k))m.add(v.key);let h=[...m].filter((k)=>i.replacedKeys.has(k)).length;if(h>0)throw Tl("key(s) the scrub replaced are still named",h);let g=new Set(ds(e.body).filter((k)=>k.purpose==="copy").map((k)=>k.key)),y=[...m].filter((k)=>!e.held.has(k)&&!g.has(k)&&!a.has(k)).length;if(y>0)throw Tl("named key(s) are neither held, copied by the plan, nor uploaded",y);let b=e.manifest.items.filter((k)=>!g.has(k.key)).length;if(b>0)throw Tl("copy key(s) are outside the plan",b);let _=e.manifest.local.filter((k)=>!a.has(k.key)).length;if(_>0)throw Tl("local key(s) were not uploaded by this run",_);let x=e.uploaded.filter((k)=>!fl(k)||!m.has(k.key)).length;if(x>0)throw Tl("upload(s) are not a local upload the tree names",x)}async function GDt(e,t){let n=await te(e,["rev-list","--objects",t],{code:"synthesis-failed",step:"rev-list"}),r=new Set;for(let o of n.stdout.split(`
|
|
440
440
|
`)){let s=o.slice(0,40);if(/^[0-9a-f]{40}$/.test(s))r.add(s)}return r}function pj(e){let t=/[zZ]|[+-]\d\d:\d\d$/.test(e)?e:`${e.replace(" ","T")}Z`,n=new Date(t);if(Number.isNaN(n.getTime()))throw new N("synthesis-failed","The re-pull record's creation time does not parse.");return n}async function yEe(e){let{work:t}=e,n=Fr(e.body),r=(await te(t,["write-tree"],{code:"synthesis-failed",step:"write-tree"})).stdout.trim(),o=await fj(t),s=new Set;for(let[h,g]of o)if(g.key&&!Gi(h))s.add(g.key);let i=dj({named:s,body:e.body,digest:e.digest,held:e.held}),a=async(h)=>{let g=await te(t,["cat-file","blob",h],{ok:!0});return g.exitCode===0?g.stdout:null},c=o.get(FR);VDt({tree:o,base:e.base,expected:e.expected,preScrub:e.preScrub,scope:e.scope,body:e.body,scrub:e.scrub,uploaded:e.uploaded,held:e.held,manifest:i,ledger:{base:e.base.has(FR)?await a(`${e.baseSha}:${FR}`):null,synth:c?await a(c.oid):null}});let l=e.scrub.counts,d=[`Re-pull ${n.ds} ${n.fromTag} to ${n.toTag} as v${n.toVersion}`,"",[`Upstream's snapshot ${n.toTag} of ${n.ds}, replayed onto NEMAR's main as one commit (ADR 0111).`,`Paths written: ${e.counts.written}; deleted: ${e.counts.deleted}.`,`Keys copied from upstream by version: ${i.items.length}; uploaded from this host: ${i.local.length}.`,`Recording headers scrubbed: ${l.headers_scrubbed}; acquisition dates set: ${l.headers_dates_normalized}; JSON values blanked: ${l.json_values_blanked}.`].join(`
|
|
441
441
|
`),"",`Upstream-Snapshot: ${n.ds}@${n.toTag}`,`Repull-Plan: ${e.digest}`,""].join(`
|
|
442
|
-
`),f=`${Math.floor(pj(e.createdAt).getTime()/1000)} +0000`,p=(await te(t,["commit-tree","--no-gpg-sign",r,"-p",e.baseSha,"-F","-"],{stdin:d,code:"synthesis-failed",step:"commit-tree",env:{GIT_AUTHOR_NAME:cn.name,GIT_AUTHOR_EMAIL:cn.email,GIT_AUTHOR_DATE:f,GIT_COMMITTER_NAME:cn.name,GIT_COMMITTER_EMAIL:cn.email,GIT_COMMITTER_DATE:f}})).stdout.trim(),m=new Set;for(let h of e.scope){let g=e.preScrub.get(h),y=o.get(h);if(!g||g.key!==null||g.mode==="120000")continue;if(lj.has(h))continue;if(a_(g)!==a_(y))m.add(g.oid)}if(m.size>0){let h=await GDt(t,p),g=[...m].filter((y)=>h.has(y)).length;if(g>0)throw Tl("scrubbed original(s) are reachable from the commit",g)}return await te(t,["update-ref",`refs/heads/${Sl}`,p],{code:"synthesis-failed",step:"update-ref"}),{synthSha:p,synthTree:r,manifest:i,manifestDigest:uj(i)}}var ps=["planned","prepared","copied","registered","pr_open"];function $p(e,t){let n=ps,r=n.indexOf(e);return r<0||r>=n.indexOf(t)}function wEe(e,t){if(t instanceof N)return`[${e}:${t.code}] ${t.message}`;if(t instanceof
|
|
443
|
-
`).map((c)=>c.split("\t")).filter((c)=>c.length===2).map(([c,l])=>[l,c])),a=i.get(`refs/tags/${n.toTag}^{}`)??i.get(`refs/tags/${n.toTag}`)??null;if(s.exitCode!==0||a===null)throw new N("upstream-unreadable",`Upstream's tag ${n.toTag} could not be read.`);if(a!==n.toCommit)throw new N("upstream-tag-moved",`Upstream's tag ${n.toTag} names another commit than the one the plan read: OpenNeuro re-created the snapshot. This re-pull cannot continue: its record has to be ended (nemar admin repull abandon <id>) and the dataset planned again.`)}async function JDt(e,t){let{synth_sha:n,synth_tree:r}=t,o=e.paths.repo,s=async(c)=>(await te(o,["rev-parse","--verify","--quiet",c],{ok:!0})).stdout.trim();try{if(await s("HEAD")===n&&await s("HEAD^{tree}")===r)return o}catch{}wo(e.paths.root,bEe(bEe(e.paths.lock)));let i=Fr(e.body).annexCommit,a=await WD({dir:o,bundle:e.paths.bundle,originUrl:gi(e.datasetId,e.env),baseSha:t.base_sha,token:e.token,annexCommit:t.status==="prepared"?i:null,bundleAnnex:i,synthSha:n,synthTree:r});if(a!==null)throw new N("checkpoint-lost",`Re-pull #${t.id}'s working clone and its checkpoint do not hold the recorded commit (${a}); this re-pull cannot continue: its record has to be ended (nemar admin repull abandon <id>) and the dataset planned again.`);return e.out(`Re-pull #${t.id}'s working clone was restored from the checkpoint.`),o}async function YDt(e,t,n){let r=new Set;for(let[i,a]of await NR(e,n.synth_sha))if(!Gi(i))r.add(a);let o=new Set((await NR(e,n.base_sha)).values()),s=dj({named:r,body:t.body,digest:t.digest,held:i_(t.body,o)});if(uj(s)!==n.manifest_digest)throw new N("manifest-mismatch","The copy manifest rebuilt from the synthesized commit is not the one recorded at prepared.");return s}function XDt(e,t,n){let r={};for(let[i,a]of Object.entries(e.env))if(a!==void 0)r[i]=a;let o=dR({commandEnv:r}),s=(i)=>fve(fR({region:i,timeoutMs:uR,env:r,credentials:o}),n);return{source:s(zve),dest:s(t)}}function QDt(e,t,n){return[...e.items.map((r)=>({key:r.key,sourceUrl:null,source:null,destUri:`s3://${t}/${n}${r.key}`})),...e.local.map((r)=>({key:r.key,sourceUrl:null,source:null,destUri:`s3://${t}/${n}${r.key}`,origin:"local"}))]}function hj(e,t,n){if(t){n(`Working directory kept at ${e.root}; it holds the delta's unscrubbed originals.`);return}try{Cs(e.root)}catch(r){n(`The working directory ${e.root} could not be removed (${r instanceof N?r.code:yo(r)}); remove it by hand: it holds the delta's unscrubbed originals.`)}}async function MR(e,t,n,r,o){let s=Date.now();try{return r?.beforeStep?.(e),await o()}catch(i){throw await n.recordError(t,wEe(e,i).slice(0,2000)),yc(WDt(e,i),e)}finally{r?.timed?.(e,Date.now()-s)}}async function gj(e,t,n,r){let o=t;if($p(o.status,n))return o;let s=Fr(e.body),i={versions:[s.toVersion]},a=$s(gi(e.datasetId,e.env),e.token),c=await MR(o.status==="prepared"?"copy":o.status==="copied"?"register":"pr",o,r,null,async()=>{let h=await JDt(e,o),g=await KDt(h,e.datasetId),y=await YDt(h,e,o),b={destBucket:g.bucket,prefix:g.prefix,stagingKey:pR(e.datasetId,s.toTag),sourceBucket:rp,sourcePrefix:`${s.ds}/`};return{work:h,remote:g,manifest:y,guard:b,aws:XDt(e,g.region,b)}}),{work:l,remote:d,manifest:f,guard:p,aws:m}=c;if(o.status==="prepared"){let h=await MR("copy",o,r,e,async()=>{if(await mj(l,e),f.items.some((x)=>x.bucket!==rp))throw new N("copy-source","A copy item names another bucket than upstream's.");await Vve({aws:m.dest,bucket:d.bucket,key:p.stagingKey,manifest:f,dir:e.paths.root});let g=await Ld(m.dest,d.bucket,d.prefix),y=await Gve({aws:m,manifest:f,destBucket:d.bucket,prefix:d.prefix,existing:g,...e.copy??{}}),b=await Ld(m.dest,d.bucket,d.prefix),_=xR(QDt(f,d.bucket,d.prefix),b);if(_.message!==null)throw new N("copy-unverified",`${_.missing.length} of ${f.items.length+f.local.length} manifest object(s) are not at their declared size in NEMAR's bucket after the copy (${_.missingUpstream} copied from upstream, ${_.missingLocal} uploaded at prepare).`);return y});if(o=await r.transition(o,"copied",{counts:{copied:h.copied,skipped:h.skipped,bytes:h.bytes}}),e.out(`Copied re-pull #${o.id}: ${h.copied} object(s) copied by version, ${h.skipped} already present.`),$p(o.status,n))return o}if(o.status==="copied"){let h=await MR("register",o,r,e,async()=>{if(!e.token)throw new N("no-github-token","No GitHub token: the registration and the release branch are pushed with the administrator's own (GH_TOKEN, or gh auth login).");await mj(l,e);let g=await Ld(m.dest,d.bucket,d.prefix);return fEe({work:l,synthSha:o.synth_sha,body:e.body,manifest:f,nemarUuid:d.uuid,listing:g,bucket:d.bucket,datasetId:e.datasetId,push:i,env:a})});if(o=await r.transition(o,"registered",{counts:{registered:h.treeKeys}}),e.out(`Registered re-pull #${o.id}: ${h.treeKeys} key(s) at nemar-s3 (${h.registered} recorded now, ${h.retired} replaced key(s) retired).`),$p(o.status,n))return o}if(o.status==="registered"){let h=o.synth_sha,g=Kn(s.toVersion),y=await MR("pr",o,r,e,async()=>{let b=e.token;if(!b)throw new N("no-github-token","No GitHub token: the pull request is opened with the administrator's own (GH_TOKEN, or gh auth login).");await mj(l,e),await Cl({work:l,baseSha:o.base_sha,env:a});let _=await eR({work:l,synthSha:h,version:s.toVersion,push:i,env:a});return e.out(_.pushed?`Pushed release/v${s.toVersion}.`:`release/v${s.toVersion} is already this re-pull's commit${_.head===h?"":" (moved by enrichment)"}.`),tR({token:b,base:e.apiBase,datasetId:e.datasetId,version:s.toVersion,body:mve({datasetId:e.datasetId,repullId:o.id,ds:s.ds,fromTag:s.fromTag,toTag:s.toTag,toVersion:s.toVersion,patchVersion:s.patchVersion,digest:e.digest,doiCount:kc(e.body).doi_count??1,counts:o.counts}),acceptHead:(x)=>As({work:l,from:h,head:x,ref:g,env:a})})});o=await r.transition(o,"pr_open",{branch:`release/v${s.toVersion}`,pr_number:y.number,head_sha:y.head}),e.out(`${y.reused?"Found":"Opened"} pull request #${y.number} of release/v${s.toVersion}; re-pull #${o.id} is pr_open. Execute never merges.`),hj(e.paths,e.keepWorkdir,e.out)}return o}Ke();var _Ee=300000,xEe=15000,vEe=30;async function kEe(e){let t=e.now??Date.now,n=e.sleep??((b)=>new Promise((_)=>setTimeout(_,b))),r=e.row;if(r.status!=="pr_open"||!r.synth_sha||!r.branch||!r.head_sha)throw new N("repull-not-ready",`Re-pull #${r.id} is ${r.status}, not an open pull request with a recorded head.`);let o=Kn(r.to_version),s=t(),i=e.deadlineMs===void 0?Number.POSITIVE_INFINITY:e.deadlineMs-s,a=Math.min(e.opts.maxWaitMs,i),c=i<e.opts.maxWaitMs,l=async(b,_,x,k)=>{let v=`${r.branch} could not be read while the run settled it (${b}); the pull request stays open, and an administrator's resume settles it.`;return await Zr(r,`${EF}head-unreadable] ${v}`,e.out),{outcome:"unreadable",row:r,reads:_,moves:x,unreadable:k,cause:b}};if(i<=0)return l("token-hour",0,0,0);let d=null,f=null,p=null,m=0,h=0,g=0,y=!1;for(;;){m++;let b=null;try{if(b=(await Rl(e.scratch,[o])).get(o)??null,b===null)p="branch-absent"}catch(x){p=ZDt(x)}if(b===null)g++;else if(b===r.head_sha)f=t(),d??=f;else{let x=await As({work:e.scratch.dir,from:r.synth_sha,head:b,ref:o,env:e.scratch.env});if(x==="foreign"){let k=`${r.branch} moved by a commit enrichment does not make while the run settled it: the pull request is left open at the recorded head, and the record is to be abandoned.`;return await Zr(r,`${EF}head-foreign] ${k}`,e.out),{outcome:"foreign",row:r,reads:m,moves:h,unreadable:g,cause:p}}if(x==="unreadable")g++,p="branch-unreadable";else r=await eRt(r,b),h++,f=t(),d=f,e.out(`${r.branch} moved by enrichment; re-pull #${r.id} records the new head.`)}let _=t();if(y=d!==null&&f!==null&&f-d>=e.opts.quietMs,y||_-s>=a)break;await n(Math.max(0,Math.min(e.opts.pollMs,a-(_-s))))}if(f===null||f<t()-e.opts.quietMs)return l(p??"unknown",m,h,g);if(c&&!y)return l("token-hour",m,h,g);return{outcome:"settled",row:r,reads:m,moves:h,unreadable:g,cause:p}}function ZDt(e){if(e instanceof N)return e.code;let t=e instanceof Error?e.name:"";return/^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(t)?t:"error"}async function eRt(e,t){try{return await Zn(e.id,{from:"pr_open",to:"pr_open",fields:{branch:e.branch,pr_number:e.pr_number,head_sha:t}})}catch(n){let r=An(n),o=new N(r??(n instanceof L?"record-refused":"github-failed"),`The moved head of ${e.branch} could not be recorded on re-pull #${e.id}.`);throw o.resumable=!0,o}}var CEe=["planned","prepared"];function oRt(e){let t=e.NEMAR_REPULL_UPSTREAM_OBJECTS_BASE?.trim();if(!t)return;try{let n=new URL(t);if(n.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(n.hostname))return t.replace(/\/+$/,"")}catch{}throw new N("test-base-refused","NEMAR_REPULL_UPSTREAM_OBJECTS_BASE is set but is not an http://127.0.0.1, http://localhost or http://[::1] address. It is only for tests, so it is refused rather than ignored.")}function _j(e){let t=An(e);return new N(t??"record-refused",`The NEMAR API refused the record${t?` (${t})`:""}: ${e instanceof Error?e.message:String(e)}`)}var bj="[prepare:";function sRt(e){if(e instanceof N)return`${bj}${e.code}] ${e.message}`;return`${bj}prepare-failed] The preparation failed: ${yo(e)}.`}function EEe(e,t){try{Cs(e)}catch(n){t(`The scratch directory ${e} could not be removed (${n instanceof N?n.code:yo(n)}); remove it by hand.`)}}function SEe(e){try{if(nRt(e).length===0)rRt(e)}catch{}}async function BR(e){let t=e.env??process.env,n=e.until??"pr_open";if(!ps.includes(n))throw new N("until-not-allowed",`Execution stops at ${ps.join(", ")}; it never goes past the open pull request.`);return Fd(()=>aRt(e,t,n))}function AEe(e,t){if(t.origin!=="automatic")throw yc(new N("repull-in-flight",`Re-pull #${t.id} of ${t.dataset_id} is an administrator's: a dispatched run never takes it up.`),"record");if(e.repullId!==null&&t.id!==e.repullId)throw yc(new N("repull-mismatch",`The dispatch continues re-pull #${e.repullId}, and the record found is #${t.id}.`),"record")}async function jR(e,t,n,r,o){if(!e.automatic||o.status!=="pr_open")return;let s=await Dl({configDir:Vn(),datasetId:o.dataset_id,digest:r,purpose:"settle",env:t,token:n}),i=e.automatic;try{return await xj(i,"settle",()=>kEe({scratch:s,row:o,opts:i.settle,out:e.out,deadlineMs:(i.tokenSince+sw)*1000,...i.now?{now:i.now}:{}}))}catch(a){throw qR(yc(a,"settle"))}finally{s.close()}}async function iRt(e){try{return(await Io({dataset:e,open:!0,limit:1})).repulls[0]??null}catch(t){if(t instanceof L)throw yc(_j(t),"record");throw t}}async function $Ee(e,t,n,r,o){if(!e.confirm)return;let s=Fr(t);if(!await e.confirm({...o?{supersedes:{id:o.id,toTag:o.to_tag,status:o.status,prNumber:o.pr_number}}:{},datasetId:s.datasetId,fromTag:s.fromTag,toTag:s.toTag,toVersion:s.toVersion,doiCount:kc(t).doi_count??1,copyItems:ds(t).filter((a)=>a.purpose==="copy").length,status:n,until:r}))throw new N("declined","Not confirmed; nothing was written.")}async function xj(e,t,n){let r=e?.measured;if(!r)return n();let o=Date.now();try{return await n()}finally{r(t,Math.round((Date.now()-o)/1000))}}function DEe(e,t){if(!e)return{};let n=e.now??Date.now;return{beforeStep(r){let o=r==="copy"?t_(t):0,s=e_(e.tokenSince,n(),o);if(s)throw s},timed:(r,o)=>e.measured?.(r,Math.round(o/1000))}}function qR(e){if(e instanceof N)e.resumable=!0;return e}async function aRt(e,t,n){let{datasetId:r,digest:o}=VD(e.planPath),s=kn(t),i=kl(t),a=oRt(t),c=Vn(),l=wc(c,r,o),d=c_(c,"repull");wo(l_(l.lock),d);let f=$l(l.lock);try{let p=await ui(t);if(!p.ok)e.out(`No GitHub token (${p.reason}); release-pr will be unchecked.`);let m=await ac(r);El(m);let h=await iRt(r),g=h&&h.plan_digest!==o?lRt(h,e,r,bp(e.planPath,{environment:Cr(),env:t,openNeuroGraphqlUrl:i}).body):null;if(h&&h.plan_digest===o&&e.supersede)e.out(`Re-pull #${h.id} is this plan's own record; --supersede has nothing to supersede.`);if(h&&h.plan_digest===o&&!CEe.includes(h.status)){let{body:_}=bp(e.planPath,{environment:Cr(),env:t,openNeuroGraphqlUrl:i});if(e.automatic)AEe(e.automatic,h),bR(_);let x={env:t,token:p.ok?p.token:null,datasetId:r,digest:o,body:_,paths:l,apiBase:s,keepWorkdir:e.keepWorkdir===!0,out:e.out,...e.copy?{copy:e.copy}:{},...DEe(e.automatic,_)};if(e.out(`Found re-pull #${h.id} of ${r}, ${h.status}.`),$p(h.status,"pr_open"))hj(l,x.keepWorkdir,e.out);if($p(h.status,n)){if(!ps.includes(h.status))e.out(`Re-pull #${h.id} is past the open pull request; execute never merges. Take it on with: nemar admin repull resume ${r}`);let C=await jR(e,t,x.token,o,h);return{row:C?.row??h,stoppedAt:h.status,...C?{settled:C}:{}}}await $Ee(e,_,h.status,n);let k;try{k=await gj(x,h,n,REe(e.out))}catch(C){throw qR(C)}let v=await jR(e,t,x.token,o,k);return{row:v?.row??k,stoppedAt:k.status,...v?{settled:v}:{}}}let y;try{if(e.automatic)y=cRt(e.planPath,e.automatic,t,i);else{Cs(l.plan),wo(l.plan,d);let _=new Map,x=await Uxe(e.planPath,{catalog:m,github:{token:p.ok?p.token:null,apiBase:s},environment:Cr(),env:t,workRoot:l.plan,collect:{computed:_},openNeuroGraphqlUrl:i,...e.maxFetchBytes!==void 0?{maxFetchBytes:e.maxFetchBytes}:{},...g?{ownRelease:(k)=>uRt(g,k)}:{}});y={body:x.live.body,plannerDir:x.workdir,computed:_,rebasedOnto:x.rebasedOnto}}}catch(_){throw EEe(l.plan,e.out),SEe(l.root),SEe(l_(l.root)),_}let b={env:t,token:p.ok?p.token:null,datasetId:r,digest:o,body:y.body,paths:l,plannerDir:y.plannerDir,computed:y.computed,objectsBase:a,normalizeMaxBytes:e.normalizeMaxBytes??$w,automatic:e.automatic,out:e.out};try{if(await $Ee(e,b.body,h?.plan_digest===o?h.status:null,n,g??void 0),g)await dRt(g,{datasetId:r,token:p.ok?p.token:null,apiBase:s,env:t,configDir:c,out:e.out});let _=await fRt(b,y.rebasedOnto,n);if($p(_.row.status,n)){let v=await jR(e,t,b.token,o,_.row);return v?{..._,row:v.row,settled:v}:_}let x;try{x=await gj({env:t,token:b.token,datasetId:r,digest:o,body:b.body,paths:l,apiBase:s,keepWorkdir:e.keepWorkdir===!0,out:e.out,...e.copy?{copy:e.copy}:{},...DEe(e.automatic,b.body)},_.row,n,REe(e.out))}catch(v){throw qR(v)}let k=await jR(e,t,b.token,o,x);return{row:k?.row??x,stoppedAt:x.status,...k?{settled:k}:{}}}finally{if(!e.keepWorkdir)EEe(l.plan,e.out)}}finally{f()}}function cRt(e,t,n,r){let{body:o}=bp(e,{environment:Cr(),env:n,openNeuroGraphqlUrl:r});bR(o);let s=e_(t.tokenSince,(t.now??Date.now)(),t_(o));if(s)throw s;let{workdir:i,computed:a}=bke(e,dc(o));return{body:o,plannerDir:i,computed:a,rebasedOnto:null}}function lRt(e,t,n,r){if(!t.supersede)throw yc(new N("repull-in-flight",`Re-pull #${e.id} of ${n} (${e.from_tag} to ${e.to_tag}) is ${e.status}, and a dataset has one open re-pull at a time: pass --supersede to end it and execute this plan (a newer tag, before its merge), or end it with nemar admin repull abandon ${n}.`),"record");let o=Fr(r);if(e.origin!=="administrator")throw new N("supersede-automatic",`Re-pull #${e.id} was opened by the automatic path; an administrator takes one over by ending it (nemar admin repull abandon ${n}) and executing again, never by a supersede.`);if(Sr(e.to_tag,o.toTag))throw new N("supersede-same-tag",`Re-pull #${e.id} pulls ${e.to_tag} too: a supersede is for a newer tag. End it with nemar admin repull abandon ${n}, then execute this plan.`);if(!Sr(e.from_tag,o.fromTag))throw new N("supersede-from-tag",`Re-pull #${e.id} pulls from ${e.from_tag} and this plan from ${o.fromTag}; a superseding plan is made again from the same from_tag.`);if(!vg.includes(e.status))throw new N("supersede-too-late",`Re-pull #${e.id} is ${e.status}: past its merge it is released (nemar admin repull resume ${n}), never superseded.`);if(e.merge_claim_sha!==null)throw new N("merge-claim-held",`A claim to merge re-pull #${e.id}'s pull request is held, so it may have merged: run nemar admin repull resume ${n}, which reads GitHub and records the merge or expires the claim.`);return e}function uRt(e,t){let n=`release/v${e.to_version}`,r=sj.includes(e.status),o=t.branches.filter((l)=>!(r&&l===`refs/heads/${n}`));if(o.length>0){let l=o.map((d)=>d.replace(/^refs\/heads\//,"")).join(", ");return{ok:!1,why:r?`release branch(es) other than re-pull #${e.id}'s own exist (${l}); delete them by hand if they are stale`:`re-pull #${e.id} is ${e.status} and pushed no branch, yet release branch(es) exist (${l})`}}if(t.pulls===null)return{ok:!1,why:`the open pull requests were not read whole (${t.pullsUnread??"unread"})`};let s=`${Gg}/${e.dataset_id}`,i=t.pulls.filter((l)=>l.headRef.startsWith("release/")),a=i.filter((l)=>r&&l.headRef===n&&l.headRepo===s&&(e.pr_number===null||l.number===e.pr_number)),c=i.filter((l)=>!a.includes(l));if(c.length>0)return{ok:!1,why:`another release pull request is open (#${c[0]?.number})`};if(a.length>1)return{ok:!1,why:`re-pull #${e.id} recorded no pull request, and ${a.length} are open of ${n} (#${a.map((l)=>l.number).join(", #")}), so which is its own is not known`};return{ok:!0}}async function dRt(e,t){let n=t.configDir??Vn(),r=t.out??(()=>{});if(!t.token)throw new N("no-github-token","No GitHub token: the superseded record's pull request is closed with the administrator's own (GH_TOKEN, or gh auth login).");let o=t.token,s=wc(n,t.datasetId,e.plan_digest);wo(l_(s.lock),c_(n,"repull"));let i=$l(s.lock),a=null;try{let c=await ij({datasetId:t.datasetId,token:o,base:t.apiBase,env:t.env,configDir:n,out:r,origin:async()=>(a??=await Dl({configDir:n,datasetId:t.datasetId,digest:e.plan_digest,purpose:"resume",env:t.env,token:o}),a)},e,"superseded",void 0,{branchMustGo:!0}),l=c.report.orphans;r(`Re-pull #${e.id} (${e.from_tag} to ${e.to_tag}) is superseded${l?`; ${l.objects} object(s), ${l.bytes} byte(s), its copy and uploads wrote stay in NEMAR's bucket, not deleted`:`; what its copy and uploads wrote stays in NEMAR's bucket (not counted: ${c.report.orphansUnknown})`}.`)}finally{a?.close(),i()}}async function fRt(e,t,n){let r=Fr(e.body),o=t??r.mainCommit;if(t)e.out("NEMAR's main moved by .nemar/** only since the plan; executing on the live main.");let s=kc(e.body),i;try{i=await O0e({dataset_id:e.datasetId,upstream_ds:r.ds,from_tag:r.fromTag,to_tag:r.toTag,from_version:r.fromVersion,to_version:r.toVersion,plan_digest:e.digest,planner:r.planner,base_sha:o,lineage_recordable:r.lineageRecordable,counts:{delta_paths:s.delta_paths??0,unexplained:s.unexplained??0,conflicts:s.conflicts??0,corrections:s.corrections??0,...e.automatic&&s.copy_bytes!==void 0?{copy_bytes:s.copy_bytes}:{}},...e.automatic?{dispatch_id:e.automatic.dispatchId,dispatch_token:e.automatic.token}:{}})}catch(c){if(c instanceof L)throw yc(_j(c),"record");throw c}let a=i.repull;if(e.automatic)AEe(e.automatic,a);if(e.out(i.created?`Recorded re-pull #${a.id} of ${e.datasetId} (${r.fromTag} -> ${r.toTag}), planned.`:`Found re-pull #${a.id} of ${e.datasetId}, ${a.status}.`),n==="planned"||!CEe.includes(a.status))return{row:a,stoppedAt:a.status};try{wo(e.paths.root,l_(l_(e.paths.lock)));let c=a;a=await xj(e.automatic,"prepare",()=>c.status==="planned"?pRt(e,c,o):mRt(e,c,o))}catch(c){throw qR(yc(c,"prepare"))}return{row:a,stoppedAt:a.status}}function REe(e){return{transition:(t,n,r)=>UR(t,n,r),async recordError(t,n){let r=t.status==="prepared"?vj(t):{};try{await Zn(t.id,{from:t.status,to:t.status,fields:r,error:n})}catch(o){e(`The failure could not be recorded on re-pull #${t.id} (${An(o)??(o instanceof L?`HTTP ${o.statusCode}`:yo(o))}); its record keeps the last error it had.`)}}}}async function pRt(e,t,n){let r;try{r=await wj(e,t,n)}catch(s){throw await LR(e,t,"planned",{},s),s}let o=await UR(t,"prepared",{synth_tree:r.synthTree,synth_sha:r.synthSha,manifest_digest:r.manifestDigest,...n!==t.base_sha?{base_sha:n}:{},counts:r.counts});return e.out(`Prepared re-pull #${t.id}: commit ${r.synthSha.slice(0,12)}.`),o}function vj(e){return{synth_tree:e.synth_tree,synth_sha:e.synth_sha,manifest_digest:e.manifest_digest}}async function yj(e){if(e.last_error===null||!e.last_error.startsWith(bj))return e;return UR(e,"prepared",vj(e))}async function mRt(e,t,n){let r=vj(t);if(n!==t.base_sha){let a;try{a=await wj(e,t,n)}catch(c){throw await LR(e,t,"prepared",r,c),c}return e.out(`Re-pull #${t.id} prepared again onto the live main.`),UR(t,"prepared",{synth_tree:a.synthTree,synth_sha:a.synthSha,manifest_digest:a.manifestDigest,base_sha:n,counts:a.counts})}let o=await hRt(e.paths.repo,r.synth_sha,r.synth_tree);if(o===null){if(e.out(`Re-pull #${t.id} is prepared, and its working clone holds its commit.`),!tRt(e.paths.bundle))await fM(e.paths.repo,e.paths.bundle,n);return yj(t)}e.out(`Re-pull #${t.id}'s working clone is not usable (${o}).`);let s=await WD({dir:e.paths.repo,bundle:e.paths.bundle,originUrl:gi(e.datasetId,e.env),baseSha:n,token:e.token,annexCommit:Fr(e.body).annexCommit,synthSha:r.synth_sha,synthTree:r.synth_tree});if(s===null)return e.out(`Re-pull #${t.id} is prepared; its working clone was restored from the checkpoint.`),yj(t);e.out(`Re-pull #${t.id}'s checkpoint was not used (${s}); preparing again.`);let i;try{i=await wj(e,t,n)}catch(a){throw await LR(e,t,"prepared",r,a),a}if(i.synthTree!==r.synth_tree||i.synthSha!==r.synth_sha||i.manifestDigest!==r.manifest_digest){let a=new N("prepare-not-reproducible",`Preparing again from the same plan and base gave another tree, commit or copy manifest than the one recorded; this re-pull cannot continue: end its record with nemar admin repull abandon ${e.datasetId} and plan the dataset again.`);throw await LR(e,t,"prepared",r,a),a}return e.out(`Re-pull #${t.id} is prepared; its working clone was prepared again, to the same commit.`),yj(t)}async function hRt(e,t,n){let r,o;try{r=(await te(e,["rev-parse","--verify","--quiet","HEAD"],{ok:!0})).stdout,o=(await te(e,["rev-parse","--verify","--quiet","HEAD^{tree}"],{ok:!0})).stdout}catch{return"no-working-clone"}return r.trim()===t&&o.trim()===n?null:"clone-at-another-commit"}async function UR(e,t,n,r){try{return await Zn(e.id,{from:e.status,to:t,fields:n,...r?{error:r}:{}})}catch(o){if(o instanceof L)throw _j(o);throw o}}async function LR(e,t,n,r,o){try{await Zn(t.id,{from:n,to:n,fields:r,error:sRt(o).slice(0,2000)})}catch(s){e.out(`The failure could not be recorded on re-pull #${t.id} (${An(s)??(s instanceof L?`HTTP ${s.statusCode}`:yo(s))}); its record keeps the last error it had.`)}}async function wj(e,t,n){let{body:r,datasetId:o,paths:s}=e,i=Fr(r),a=await xj(e.automatic,"clone",()=>dM({dir:s.repo,originUrl:gi(o,e.env),baseSha:n,token:e.token,annexCommit:i.annexCommit})),c=yp(await gp(a),o),l=c.record?.bucket;if(!c.uuid||!l)throw new N("no-nemar-s3","NEMAR's remote.log names no single nemar-s3 bucket.");let d=`${o}/objects/`;if(nR(r).destinationPrefix!==d||c.prefix!==d)throw new N("destination-prefix",`The plan's destination is not ${d}, the only prefix a re-pull uploads to.`);let f=oj({bucket:l,datasetId:o,region:c.region,remoteUuid:c.uuid,workDir:s.upload}),p=SD({baseUrl:e.objectsBase}),m=await ur(a),h=await gEe(a,n,m),g=new Set(m.values()),y=c_(s.root,"scratch");Cs(y),wo(y,s.root);let b=await kve({work:a,body:r,upstreamBare:c_(e.plannerDir,"upstream.git"),upstreamEnv:$s(Wg(i.ds,e.env),null),computed:e.computed,reader:p,scratch:y});if(b.nemarOwned.left.length>0)e.out(`NEMAR-owned edit(s) the plan listed and the preparation left as they are: ${b.nemarOwned.left.length} (${b.nemarOwned.left.join(", ")}).`);let _=new Set(b.deltaPaths),x=await te(a,["ls-files","-z","--",Ds,di]);for(let P of x.stdout.split("\x00"))if(P)_.add(P);let k=pj(t.created_at);await Eve(a,n,_,k);let v=new Map;for(let[P,O]of await fj(a))if(_.has(P))v.set(P,O);let{scrub:C,uploaded:T}=await hEe({work:a,datasetId:o,scope:_,body:r,oursKeys:g,annexFromGit:b.annexFromGit,reader:p,upload:f,bucket:l,now:k,maxBytes:e.normalizeMaxBytes,upstreamBare:c_(e.plannerDir,"upstream.git")});Cs(y);let z=i_(r,g),A=await yEe({work:a,baseSha:n,createdAt:t.created_at,body:r,digest:e.digest,scrub:C,uploaded:T,held:z,base:h,expected:b.expected,preScrub:v,scope:_,counts:{written:b.written,deleted:b.deleted}});await fM(a,s.bundle,n);let F=(P)=>P.every((O)=>O.size!==null)?{known:!0,bytes:P.reduce((O,H)=>O+(H.size??0),0)}:{known:!1,bytes:0},M=F(A.manifest.items),U=F(A.manifest.local),B=C.counts;return{synthSha:A.synthSha,synthTree:A.synthTree,manifestDigest:A.manifestDigest,counts:{delta_paths:b.deltaPaths.size,written:b.written,deleted:b.deleted,annex_copy_items:A.manifest.items.length,...M.known?{copy_bytes:M.bytes}:{},local_uploads:A.manifest.local.length,...U.known?{local_upload_bytes:U.bytes}:{},scrubbed_recordings:B.headers_scrubbed,dated_recordings:B.headers_dates_normalized,scrubbed_json:B.json_files_blanked,headers_not_read_nemar_held:B.headers_not_read_nemar_held,headers_not_read_no_source:B.headers_not_read_no_source,json_files_unread:B.json_files_unread,json_files_annexed:B.json_files_annexed,scans_tables_unread:B.scans_tables_unread,headers_dates_unproven:B.headers_dates_unproven,headers_dates_left:B.headers_dates_left,nemar_owned_edits:b.nemarOwned.applied,nemar_owned_edits_left:b.nemarOwned.left.length}}}var u_=`--automatic-dispatch <id> is the central run-upstream-repull workflow's, never an
|
|
442
|
+
`),f=`${Math.floor(pj(e.createdAt).getTime()/1000)} +0000`,p=(await te(t,["commit-tree","--no-gpg-sign",r,"-p",e.baseSha,"-F","-"],{stdin:d,code:"synthesis-failed",step:"commit-tree",env:{GIT_AUTHOR_NAME:cn.name,GIT_AUTHOR_EMAIL:cn.email,GIT_AUTHOR_DATE:f,GIT_COMMITTER_NAME:cn.name,GIT_COMMITTER_EMAIL:cn.email,GIT_COMMITTER_DATE:f}})).stdout.trim(),m=new Set;for(let h of e.scope){let g=e.preScrub.get(h),y=o.get(h);if(!g||g.key!==null||g.mode==="120000")continue;if(lj.has(h))continue;if(a_(g)!==a_(y))m.add(g.oid)}if(m.size>0){let h=await GDt(t,p),g=[...m].filter((y)=>h.has(y)).length;if(g>0)throw Tl("scrubbed original(s) are reachable from the commit",g)}return await te(t,["update-ref",`refs/heads/${Sl}`,p],{code:"synthesis-failed",step:"update-ref"}),{synthSha:p,synthTree:r,manifest:i,manifestDigest:uj(i)}}var ps=["planned","prepared","copied","registered","pr_open"];function $p(e,t){let n=ps,r=n.indexOf(e);return r<0||r>=n.indexOf(t)}function wEe(e,t){if(t instanceof N)return`[${e}:${t.code}] ${t.message}`;if(t instanceof Xe)return`[${e}:write-refused] ${t.message}`;if(t instanceof Bt)return`[${e}:s3-failed] An S3 call failed (${jd(t)}).`;return`[${e}:${e}-failed] The step failed: ${yo(t)}.`}function WDt(e,t){if(t instanceof N)return t;let n=wEe(e,t),r=/^\[[a-z]+:([a-z0-9-]+)\]/.exec(n)?.[1]??`${e}-failed`;return new N(r,n.replace(/^\[[^\]]+\] /,""))}async function KDt(e,t){let n=yp(await gp(e),t),r=n.record?.bucket,o=`${t}/objects/`;if(!n.uuid||!r)throw new N("no-nemar-s3","NEMAR's remote.log names no single nemar-s3 bucket.");if(n.prefix!==o)throw new N("destination-prefix",`NEMAR's nemar-s3 is not at ${o}, the only prefix a re-pull writes to.`);return{uuid:n.uuid,bucket:r,region:n.region,prefix:o}}async function mj(e,t){let n=Fr(t.body),r=Wg(n.ds,t.env),o=$s(r,null),s=await te(e,["ls-remote",r,`refs/tags/${n.toTag}`],{...o?{env:o}:{},ok:!0}),i=new Map(s.stdout.split(`
|
|
443
|
+
`).map((c)=>c.split("\t")).filter((c)=>c.length===2).map(([c,l])=>[l,c])),a=i.get(`refs/tags/${n.toTag}^{}`)??i.get(`refs/tags/${n.toTag}`)??null;if(s.exitCode!==0||a===null)throw new N("upstream-unreadable",`Upstream's tag ${n.toTag} could not be read.`);if(a!==n.toCommit)throw new N("upstream-tag-moved",`Upstream's tag ${n.toTag} names another commit than the one the plan read: OpenNeuro re-created the snapshot. This re-pull cannot continue: its record has to be ended (nemar admin repull abandon <id>) and the dataset planned again.`)}async function JDt(e,t){let{synth_sha:n,synth_tree:r}=t,o=e.paths.repo,s=async(c)=>(await te(o,["rev-parse","--verify","--quiet",c],{ok:!0})).stdout.trim();try{if(await s("HEAD")===n&&await s("HEAD^{tree}")===r)return o}catch{}wo(e.paths.root,bEe(bEe(e.paths.lock)));let i=Fr(e.body).annexCommit,a=await WD({dir:o,bundle:e.paths.bundle,originUrl:gi(e.datasetId,e.env),baseSha:t.base_sha,token:e.token,annexCommit:t.status==="prepared"?i:null,bundleAnnex:i,synthSha:n,synthTree:r});if(a!==null)throw new N("checkpoint-lost",`Re-pull #${t.id}'s working clone and its checkpoint do not hold the recorded commit (${a}); this re-pull cannot continue: its record has to be ended (nemar admin repull abandon <id>) and the dataset planned again.`);return e.out(`Re-pull #${t.id}'s working clone was restored from the checkpoint.`),o}async function YDt(e,t,n){let r=new Set;for(let[i,a]of await NR(e,n.synth_sha))if(!Gi(i))r.add(a);let o=new Set((await NR(e,n.base_sha)).values()),s=dj({named:r,body:t.body,digest:t.digest,held:i_(t.body,o)});if(uj(s)!==n.manifest_digest)throw new N("manifest-mismatch","The copy manifest rebuilt from the synthesized commit is not the one recorded at prepared.");return s}function XDt(e,t,n){let r={};for(let[i,a]of Object.entries(e.env))if(a!==void 0)r[i]=a;let o=dR({commandEnv:r}),s=(i)=>fve(fR({region:i,timeoutMs:uR,env:r,credentials:o}),n);return{source:s(zve),dest:s(t)}}function QDt(e,t,n){return[...e.items.map((r)=>({key:r.key,sourceUrl:null,source:null,destUri:`s3://${t}/${n}${r.key}`})),...e.local.map((r)=>({key:r.key,sourceUrl:null,source:null,destUri:`s3://${t}/${n}${r.key}`,origin:"local"}))]}function hj(e,t,n){if(t){n(`Working directory kept at ${e.root}; it holds the delta's unscrubbed originals.`);return}try{Cs(e.root)}catch(r){n(`The working directory ${e.root} could not be removed (${r instanceof N?r.code:yo(r)}); remove it by hand: it holds the delta's unscrubbed originals.`)}}async function MR(e,t,n,r,o){let s=Date.now();try{return r?.beforeStep?.(e),await o()}catch(i){throw await n.recordError(t,wEe(e,i).slice(0,2000)),yc(WDt(e,i),e)}finally{r?.timed?.(e,Date.now()-s)}}async function gj(e,t,n,r){let o=t;if($p(o.status,n))return o;let s=Fr(e.body),i={versions:[s.toVersion]},a=$s(gi(e.datasetId,e.env),e.token),c=await MR(o.status==="prepared"?"copy":o.status==="copied"?"register":"pr",o,r,null,async()=>{let h=await JDt(e,o),g=await KDt(h,e.datasetId),y=await YDt(h,e,o),b={destBucket:g.bucket,prefix:g.prefix,stagingKey:pR(e.datasetId,s.toTag),sourceBucket:rp,sourcePrefix:`${s.ds}/`};return{work:h,remote:g,manifest:y,guard:b,aws:XDt(e,g.region,b)}}),{work:l,remote:d,manifest:f,guard:p,aws:m}=c;if(o.status==="prepared"){let h=await MR("copy",o,r,e,async()=>{if(await mj(l,e),f.items.some((x)=>x.bucket!==rp))throw new N("copy-source","A copy item names another bucket than upstream's.");await Vve({aws:m.dest,bucket:d.bucket,key:p.stagingKey,manifest:f,dir:e.paths.root});let g=await Ld(m.dest,d.bucket,d.prefix),y=await Gve({aws:m,manifest:f,destBucket:d.bucket,prefix:d.prefix,existing:g,...e.copy??{}}),b=await Ld(m.dest,d.bucket,d.prefix),_=xR(QDt(f,d.bucket,d.prefix),b);if(_.message!==null)throw new N("copy-unverified",`${_.missing.length} of ${f.items.length+f.local.length} manifest object(s) are not at their declared size in NEMAR's bucket after the copy (${_.missingUpstream} copied from upstream, ${_.missingLocal} uploaded at prepare).`);return y});if(o=await r.transition(o,"copied",{counts:{copied:h.copied,skipped:h.skipped,bytes:h.bytes}}),e.out(`Copied re-pull #${o.id}: ${h.copied} object(s) copied by version, ${h.skipped} already present.`),$p(o.status,n))return o}if(o.status==="copied"){let h=await MR("register",o,r,e,async()=>{if(!e.token)throw new N("no-github-token","No GitHub token: the registration and the release branch are pushed with the administrator's own (GH_TOKEN, or gh auth login).");await mj(l,e);let g=await Ld(m.dest,d.bucket,d.prefix);return fEe({work:l,synthSha:o.synth_sha,body:e.body,manifest:f,nemarUuid:d.uuid,listing:g,bucket:d.bucket,datasetId:e.datasetId,push:i,env:a})});if(o=await r.transition(o,"registered",{counts:{registered:h.treeKeys}}),e.out(`Registered re-pull #${o.id}: ${h.treeKeys} key(s) at nemar-s3 (${h.registered} recorded now, ${h.retired} replaced key(s) retired).`),$p(o.status,n))return o}if(o.status==="registered"){let h=o.synth_sha,g=Kn(s.toVersion),y=await MR("pr",o,r,e,async()=>{let b=e.token;if(!b)throw new N("no-github-token","No GitHub token: the pull request is opened with the administrator's own (GH_TOKEN, or gh auth login).");await mj(l,e),await Cl({work:l,baseSha:o.base_sha,env:a});let _=await eR({work:l,synthSha:h,version:s.toVersion,push:i,env:a});return e.out(_.pushed?`Pushed release/v${s.toVersion}.`:`release/v${s.toVersion} is already this re-pull's commit${_.head===h?"":" (moved by enrichment)"}.`),tR({token:b,base:e.apiBase,datasetId:e.datasetId,version:s.toVersion,body:mve({datasetId:e.datasetId,repullId:o.id,ds:s.ds,fromTag:s.fromTag,toTag:s.toTag,toVersion:s.toVersion,patchVersion:s.patchVersion,digest:e.digest,doiCount:kc(e.body).doi_count??1,counts:o.counts}),acceptHead:(x)=>As({work:l,from:h,head:x,ref:g,env:a})})});o=await r.transition(o,"pr_open",{branch:`release/v${s.toVersion}`,pr_number:y.number,head_sha:y.head}),e.out(`${y.reused?"Found":"Opened"} pull request #${y.number} of release/v${s.toVersion}; re-pull #${o.id} is pr_open. Execute never merges.`),hj(e.paths,e.keepWorkdir,e.out)}return o}Je();var _Ee=300000,xEe=15000,vEe=30;async function kEe(e){let t=e.now??Date.now,n=e.sleep??((b)=>new Promise((_)=>setTimeout(_,b))),r=e.row;if(r.status!=="pr_open"||!r.synth_sha||!r.branch||!r.head_sha)throw new N("repull-not-ready",`Re-pull #${r.id} is ${r.status}, not an open pull request with a recorded head.`);let o=Kn(r.to_version),s=t(),i=e.deadlineMs===void 0?Number.POSITIVE_INFINITY:e.deadlineMs-s,a=Math.min(e.opts.maxWaitMs,i),c=i<e.opts.maxWaitMs,l=async(b,_,x,k)=>{let v=`${r.branch} could not be read while the run settled it (${b}); the pull request stays open, and an administrator's resume settles it.`;return await Zr(r,`${EF}head-unreadable] ${v}`,e.out),{outcome:"unreadable",row:r,reads:_,moves:x,unreadable:k,cause:b}};if(i<=0)return l("token-hour",0,0,0);let d=null,f=null,p=null,m=0,h=0,g=0,y=!1;for(;;){m++;let b=null;try{if(b=(await Rl(e.scratch,[o])).get(o)??null,b===null)p="branch-absent"}catch(x){p=ZDt(x)}if(b===null)g++;else if(b===r.head_sha)f=t(),d??=f;else{let x=await As({work:e.scratch.dir,from:r.synth_sha,head:b,ref:o,env:e.scratch.env});if(x==="foreign"){let k=`${r.branch} moved by a commit enrichment does not make while the run settled it: the pull request is left open at the recorded head, and the record is to be abandoned.`;return await Zr(r,`${EF}head-foreign] ${k}`,e.out),{outcome:"foreign",row:r,reads:m,moves:h,unreadable:g,cause:p}}if(x==="unreadable")g++,p="branch-unreadable";else r=await eRt(r,b),h++,f=t(),d=f,e.out(`${r.branch} moved by enrichment; re-pull #${r.id} records the new head.`)}let _=t();if(y=d!==null&&f!==null&&f-d>=e.opts.quietMs,y||_-s>=a)break;await n(Math.max(0,Math.min(e.opts.pollMs,a-(_-s))))}if(f===null||f<t()-e.opts.quietMs)return l(p??"unknown",m,h,g);if(c&&!y)return l("token-hour",m,h,g);return{outcome:"settled",row:r,reads:m,moves:h,unreadable:g,cause:p}}function ZDt(e){if(e instanceof N)return e.code;let t=e instanceof Error?e.name:"";return/^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(t)?t:"error"}async function eRt(e,t){try{return await Zn(e.id,{from:"pr_open",to:"pr_open",fields:{branch:e.branch,pr_number:e.pr_number,head_sha:t}})}catch(n){let r=An(n),o=new N(r??(n instanceof L?"record-refused":"github-failed"),`The moved head of ${e.branch} could not be recorded on re-pull #${e.id}.`);throw o.resumable=!0,o}}var CEe=["planned","prepared"];function oRt(e){let t=e.NEMAR_REPULL_UPSTREAM_OBJECTS_BASE?.trim();if(!t)return;try{let n=new URL(t);if(n.protocol==="http:"&&["127.0.0.1","localhost","[::1]"].includes(n.hostname))return t.replace(/\/+$/,"")}catch{}throw new N("test-base-refused","NEMAR_REPULL_UPSTREAM_OBJECTS_BASE is set but is not an http://127.0.0.1, http://localhost or http://[::1] address. It is only for tests, so it is refused rather than ignored.")}function _j(e){let t=An(e);return new N(t??"record-refused",`The NEMAR API refused the record${t?` (${t})`:""}: ${e instanceof Error?e.message:String(e)}`)}var bj="[prepare:";function sRt(e){if(e instanceof N)return`${bj}${e.code}] ${e.message}`;return`${bj}prepare-failed] The preparation failed: ${yo(e)}.`}function EEe(e,t){try{Cs(e)}catch(n){t(`The scratch directory ${e} could not be removed (${n instanceof N?n.code:yo(n)}); remove it by hand.`)}}function SEe(e){try{if(nRt(e).length===0)rRt(e)}catch{}}async function BR(e){let t=e.env??process.env,n=e.until??"pr_open";if(!ps.includes(n))throw new N("until-not-allowed",`Execution stops at ${ps.join(", ")}; it never goes past the open pull request.`);return Fd(()=>aRt(e,t,n))}function AEe(e,t){if(t.origin!=="automatic")throw yc(new N("repull-in-flight",`Re-pull #${t.id} of ${t.dataset_id} is an administrator's: a dispatched run never takes it up.`),"record");if(e.repullId!==null&&t.id!==e.repullId)throw yc(new N("repull-mismatch",`The dispatch continues re-pull #${e.repullId}, and the record found is #${t.id}.`),"record")}async function jR(e,t,n,r,o){if(!e.automatic||o.status!=="pr_open")return;let s=await Dl({configDir:Vn(),datasetId:o.dataset_id,digest:r,purpose:"settle",env:t,token:n}),i=e.automatic;try{return await xj(i,"settle",()=>kEe({scratch:s,row:o,opts:i.settle,out:e.out,deadlineMs:(i.tokenSince+sw)*1000,...i.now?{now:i.now}:{}}))}catch(a){throw qR(yc(a,"settle"))}finally{s.close()}}async function iRt(e){try{return(await Io({dataset:e,open:!0,limit:1})).repulls[0]??null}catch(t){if(t instanceof L)throw yc(_j(t),"record");throw t}}async function $Ee(e,t,n,r,o){if(!e.confirm)return;let s=Fr(t);if(!await e.confirm({...o?{supersedes:{id:o.id,toTag:o.to_tag,status:o.status,prNumber:o.pr_number}}:{},datasetId:s.datasetId,fromTag:s.fromTag,toTag:s.toTag,toVersion:s.toVersion,doiCount:kc(t).doi_count??1,copyItems:ds(t).filter((a)=>a.purpose==="copy").length,status:n,until:r}))throw new N("declined","Not confirmed; nothing was written.")}async function xj(e,t,n){let r=e?.measured;if(!r)return n();let o=Date.now();try{return await n()}finally{r(t,Math.round((Date.now()-o)/1000))}}function DEe(e,t){if(!e)return{};let n=e.now??Date.now;return{beforeStep(r){let o=r==="copy"?t_(t):0,s=e_(e.tokenSince,n(),o);if(s)throw s},timed:(r,o)=>e.measured?.(r,Math.round(o/1000))}}function qR(e){if(e instanceof N)e.resumable=!0;return e}async function aRt(e,t,n){let{datasetId:r,digest:o}=VD(e.planPath),s=kn(t),i=kl(t),a=oRt(t),c=Vn(),l=wc(c,r,o),d=c_(c,"repull");wo(l_(l.lock),d);let f=$l(l.lock);try{let p=await ui(t);if(!p.ok)e.out(`No GitHub token (${p.reason}); release-pr will be unchecked.`);let m=await ac(r);El(m);let h=await iRt(r),g=h&&h.plan_digest!==o?lRt(h,e,r,bp(e.planPath,{environment:Cr(),env:t,openNeuroGraphqlUrl:i}).body):null;if(h&&h.plan_digest===o&&e.supersede)e.out(`Re-pull #${h.id} is this plan's own record; --supersede has nothing to supersede.`);if(h&&h.plan_digest===o&&!CEe.includes(h.status)){let{body:_}=bp(e.planPath,{environment:Cr(),env:t,openNeuroGraphqlUrl:i});if(e.automatic)AEe(e.automatic,h),bR(_);let x={env:t,token:p.ok?p.token:null,datasetId:r,digest:o,body:_,paths:l,apiBase:s,keepWorkdir:e.keepWorkdir===!0,out:e.out,...e.copy?{copy:e.copy}:{},...DEe(e.automatic,_)};if(e.out(`Found re-pull #${h.id} of ${r}, ${h.status}.`),$p(h.status,"pr_open"))hj(l,x.keepWorkdir,e.out);if($p(h.status,n)){if(!ps.includes(h.status))e.out(`Re-pull #${h.id} is past the open pull request; execute never merges. Take it on with: nemar admin repull resume ${r}`);let C=await jR(e,t,x.token,o,h);return{row:C?.row??h,stoppedAt:h.status,...C?{settled:C}:{}}}await $Ee(e,_,h.status,n);let k;try{k=await gj(x,h,n,REe(e.out))}catch(C){throw qR(C)}let v=await jR(e,t,x.token,o,k);return{row:v?.row??k,stoppedAt:k.status,...v?{settled:v}:{}}}let y;try{if(e.automatic)y=cRt(e.planPath,e.automatic,t,i);else{Cs(l.plan),wo(l.plan,d);let _=new Map,x=await Uxe(e.planPath,{catalog:m,github:{token:p.ok?p.token:null,apiBase:s},environment:Cr(),env:t,workRoot:l.plan,collect:{computed:_},openNeuroGraphqlUrl:i,...e.maxFetchBytes!==void 0?{maxFetchBytes:e.maxFetchBytes}:{},...g?{ownRelease:(k)=>uRt(g,k)}:{}});y={body:x.live.body,plannerDir:x.workdir,computed:_,rebasedOnto:x.rebasedOnto}}}catch(_){throw EEe(l.plan,e.out),SEe(l.root),SEe(l_(l.root)),_}let b={env:t,token:p.ok?p.token:null,datasetId:r,digest:o,body:y.body,paths:l,plannerDir:y.plannerDir,computed:y.computed,objectsBase:a,normalizeMaxBytes:e.normalizeMaxBytes??$w,automatic:e.automatic,out:e.out};try{if(await $Ee(e,b.body,h?.plan_digest===o?h.status:null,n,g??void 0),g)await dRt(g,{datasetId:r,token:p.ok?p.token:null,apiBase:s,env:t,configDir:c,out:e.out});let _=await fRt(b,y.rebasedOnto,n);if($p(_.row.status,n)){let v=await jR(e,t,b.token,o,_.row);return v?{..._,row:v.row,settled:v}:_}let x;try{x=await gj({env:t,token:b.token,datasetId:r,digest:o,body:b.body,paths:l,apiBase:s,keepWorkdir:e.keepWorkdir===!0,out:e.out,...e.copy?{copy:e.copy}:{},...DEe(e.automatic,b.body)},_.row,n,REe(e.out))}catch(v){throw qR(v)}let k=await jR(e,t,b.token,o,x);return{row:k?.row??x,stoppedAt:x.status,...k?{settled:k}:{}}}finally{if(!e.keepWorkdir)EEe(l.plan,e.out)}}finally{f()}}function cRt(e,t,n,r){let{body:o}=bp(e,{environment:Cr(),env:n,openNeuroGraphqlUrl:r});bR(o);let s=e_(t.tokenSince,(t.now??Date.now)(),t_(o));if(s)throw s;let{workdir:i,computed:a}=bke(e,dc(o));return{body:o,plannerDir:i,computed:a,rebasedOnto:null}}function lRt(e,t,n,r){if(!t.supersede)throw yc(new N("repull-in-flight",`Re-pull #${e.id} of ${n} (${e.from_tag} to ${e.to_tag}) is ${e.status}, and a dataset has one open re-pull at a time: pass --supersede to end it and execute this plan (a newer tag, before its merge), or end it with nemar admin repull abandon ${n}.`),"record");let o=Fr(r);if(e.origin!=="administrator")throw new N("supersede-automatic",`Re-pull #${e.id} was opened by the automatic path; an administrator takes one over by ending it (nemar admin repull abandon ${n}) and executing again, never by a supersede.`);if(Sr(e.to_tag,o.toTag))throw new N("supersede-same-tag",`Re-pull #${e.id} pulls ${e.to_tag} too: a supersede is for a newer tag. End it with nemar admin repull abandon ${n}, then execute this plan.`);if(!Sr(e.from_tag,o.fromTag))throw new N("supersede-from-tag",`Re-pull #${e.id} pulls from ${e.from_tag} and this plan from ${o.fromTag}; a superseding plan is made again from the same from_tag.`);if(!vg.includes(e.status))throw new N("supersede-too-late",`Re-pull #${e.id} is ${e.status}: past its merge it is released (nemar admin repull resume ${n}), never superseded.`);if(e.merge_claim_sha!==null)throw new N("merge-claim-held",`A claim to merge re-pull #${e.id}'s pull request is held, so it may have merged: run nemar admin repull resume ${n}, which reads GitHub and records the merge or expires the claim.`);return e}function uRt(e,t){let n=`release/v${e.to_version}`,r=sj.includes(e.status),o=t.branches.filter((l)=>!(r&&l===`refs/heads/${n}`));if(o.length>0){let l=o.map((d)=>d.replace(/^refs\/heads\//,"")).join(", ");return{ok:!1,why:r?`release branch(es) other than re-pull #${e.id}'s own exist (${l}); delete them by hand if they are stale`:`re-pull #${e.id} is ${e.status} and pushed no branch, yet release branch(es) exist (${l})`}}if(t.pulls===null)return{ok:!1,why:`the open pull requests were not read whole (${t.pullsUnread??"unread"})`};let s=`${Gg}/${e.dataset_id}`,i=t.pulls.filter((l)=>l.headRef.startsWith("release/")),a=i.filter((l)=>r&&l.headRef===n&&l.headRepo===s&&(e.pr_number===null||l.number===e.pr_number)),c=i.filter((l)=>!a.includes(l));if(c.length>0)return{ok:!1,why:`another release pull request is open (#${c[0]?.number})`};if(a.length>1)return{ok:!1,why:`re-pull #${e.id} recorded no pull request, and ${a.length} are open of ${n} (#${a.map((l)=>l.number).join(", #")}), so which is its own is not known`};return{ok:!0}}async function dRt(e,t){let n=t.configDir??Vn(),r=t.out??(()=>{});if(!t.token)throw new N("no-github-token","No GitHub token: the superseded record's pull request is closed with the administrator's own (GH_TOKEN, or gh auth login).");let o=t.token,s=wc(n,t.datasetId,e.plan_digest);wo(l_(s.lock),c_(n,"repull"));let i=$l(s.lock),a=null;try{let c=await ij({datasetId:t.datasetId,token:o,base:t.apiBase,env:t.env,configDir:n,out:r,origin:async()=>(a??=await Dl({configDir:n,datasetId:t.datasetId,digest:e.plan_digest,purpose:"resume",env:t.env,token:o}),a)},e,"superseded",void 0,{branchMustGo:!0}),l=c.report.orphans;r(`Re-pull #${e.id} (${e.from_tag} to ${e.to_tag}) is superseded${l?`; ${l.objects} object(s), ${l.bytes} byte(s), its copy and uploads wrote stay in NEMAR's bucket, not deleted`:`; what its copy and uploads wrote stays in NEMAR's bucket (not counted: ${c.report.orphansUnknown})`}.`)}finally{a?.close(),i()}}async function fRt(e,t,n){let r=Fr(e.body),o=t??r.mainCommit;if(t)e.out("NEMAR's main moved by .nemar/** only since the plan; executing on the live main.");let s=kc(e.body),i;try{i=await O0e({dataset_id:e.datasetId,upstream_ds:r.ds,from_tag:r.fromTag,to_tag:r.toTag,from_version:r.fromVersion,to_version:r.toVersion,plan_digest:e.digest,planner:r.planner,base_sha:o,lineage_recordable:r.lineageRecordable,counts:{delta_paths:s.delta_paths??0,unexplained:s.unexplained??0,conflicts:s.conflicts??0,corrections:s.corrections??0,...e.automatic&&s.copy_bytes!==void 0?{copy_bytes:s.copy_bytes}:{}},...e.automatic?{dispatch_id:e.automatic.dispatchId,dispatch_token:e.automatic.token}:{}})}catch(c){if(c instanceof L)throw yc(_j(c),"record");throw c}let a=i.repull;if(e.automatic)AEe(e.automatic,a);if(e.out(i.created?`Recorded re-pull #${a.id} of ${e.datasetId} (${r.fromTag} -> ${r.toTag}), planned.`:`Found re-pull #${a.id} of ${e.datasetId}, ${a.status}.`),n==="planned"||!CEe.includes(a.status))return{row:a,stoppedAt:a.status};try{wo(e.paths.root,l_(l_(e.paths.lock)));let c=a;a=await xj(e.automatic,"prepare",()=>c.status==="planned"?pRt(e,c,o):mRt(e,c,o))}catch(c){throw qR(yc(c,"prepare"))}return{row:a,stoppedAt:a.status}}function REe(e){return{transition:(t,n,r)=>UR(t,n,r),async recordError(t,n){let r=t.status==="prepared"?vj(t):{};try{await Zn(t.id,{from:t.status,to:t.status,fields:r,error:n})}catch(o){e(`The failure could not be recorded on re-pull #${t.id} (${An(o)??(o instanceof L?`HTTP ${o.statusCode}`:yo(o))}); its record keeps the last error it had.`)}}}}async function pRt(e,t,n){let r;try{r=await wj(e,t,n)}catch(s){throw await LR(e,t,"planned",{},s),s}let o=await UR(t,"prepared",{synth_tree:r.synthTree,synth_sha:r.synthSha,manifest_digest:r.manifestDigest,...n!==t.base_sha?{base_sha:n}:{},counts:r.counts});return e.out(`Prepared re-pull #${t.id}: commit ${r.synthSha.slice(0,12)}.`),o}function vj(e){return{synth_tree:e.synth_tree,synth_sha:e.synth_sha,manifest_digest:e.manifest_digest}}async function yj(e){if(e.last_error===null||!e.last_error.startsWith(bj))return e;return UR(e,"prepared",vj(e))}async function mRt(e,t,n){let r=vj(t);if(n!==t.base_sha){let a;try{a=await wj(e,t,n)}catch(c){throw await LR(e,t,"prepared",r,c),c}return e.out(`Re-pull #${t.id} prepared again onto the live main.`),UR(t,"prepared",{synth_tree:a.synthTree,synth_sha:a.synthSha,manifest_digest:a.manifestDigest,base_sha:n,counts:a.counts})}let o=await hRt(e.paths.repo,r.synth_sha,r.synth_tree);if(o===null){if(e.out(`Re-pull #${t.id} is prepared, and its working clone holds its commit.`),!tRt(e.paths.bundle))await fM(e.paths.repo,e.paths.bundle,n);return yj(t)}e.out(`Re-pull #${t.id}'s working clone is not usable (${o}).`);let s=await WD({dir:e.paths.repo,bundle:e.paths.bundle,originUrl:gi(e.datasetId,e.env),baseSha:n,token:e.token,annexCommit:Fr(e.body).annexCommit,synthSha:r.synth_sha,synthTree:r.synth_tree});if(s===null)return e.out(`Re-pull #${t.id} is prepared; its working clone was restored from the checkpoint.`),yj(t);e.out(`Re-pull #${t.id}'s checkpoint was not used (${s}); preparing again.`);let i;try{i=await wj(e,t,n)}catch(a){throw await LR(e,t,"prepared",r,a),a}if(i.synthTree!==r.synth_tree||i.synthSha!==r.synth_sha||i.manifestDigest!==r.manifest_digest){let a=new N("prepare-not-reproducible",`Preparing again from the same plan and base gave another tree, commit or copy manifest than the one recorded; this re-pull cannot continue: end its record with nemar admin repull abandon ${e.datasetId} and plan the dataset again.`);throw await LR(e,t,"prepared",r,a),a}return e.out(`Re-pull #${t.id} is prepared; its working clone was prepared again, to the same commit.`),yj(t)}async function hRt(e,t,n){let r,o;try{r=(await te(e,["rev-parse","--verify","--quiet","HEAD"],{ok:!0})).stdout,o=(await te(e,["rev-parse","--verify","--quiet","HEAD^{tree}"],{ok:!0})).stdout}catch{return"no-working-clone"}return r.trim()===t&&o.trim()===n?null:"clone-at-another-commit"}async function UR(e,t,n,r){try{return await Zn(e.id,{from:e.status,to:t,fields:n,...r?{error:r}:{}})}catch(o){if(o instanceof L)throw _j(o);throw o}}async function LR(e,t,n,r,o){try{await Zn(t.id,{from:n,to:n,fields:r,error:sRt(o).slice(0,2000)})}catch(s){e.out(`The failure could not be recorded on re-pull #${t.id} (${An(s)??(s instanceof L?`HTTP ${s.statusCode}`:yo(s))}); its record keeps the last error it had.`)}}async function wj(e,t,n){let{body:r,datasetId:o,paths:s}=e,i=Fr(r),a=await xj(e.automatic,"clone",()=>dM({dir:s.repo,originUrl:gi(o,e.env),baseSha:n,token:e.token,annexCommit:i.annexCommit})),c=yp(await gp(a),o),l=c.record?.bucket;if(!c.uuid||!l)throw new N("no-nemar-s3","NEMAR's remote.log names no single nemar-s3 bucket.");let d=`${o}/objects/`;if(nR(r).destinationPrefix!==d||c.prefix!==d)throw new N("destination-prefix",`The plan's destination is not ${d}, the only prefix a re-pull uploads to.`);let f=oj({bucket:l,datasetId:o,region:c.region,remoteUuid:c.uuid,workDir:s.upload}),p=SD({baseUrl:e.objectsBase}),m=await ur(a),h=await gEe(a,n,m),g=new Set(m.values()),y=c_(s.root,"scratch");Cs(y),wo(y,s.root);let b=await kve({work:a,body:r,upstreamBare:c_(e.plannerDir,"upstream.git"),upstreamEnv:$s(Wg(i.ds,e.env),null),computed:e.computed,reader:p,scratch:y});if(b.nemarOwned.left.length>0)e.out(`NEMAR-owned edit(s) the plan listed and the preparation left as they are: ${b.nemarOwned.left.length} (${b.nemarOwned.left.join(", ")}).`);let _=new Set(b.deltaPaths),x=await te(a,["ls-files","-z","--",Ds,di]);for(let P of x.stdout.split("\x00"))if(P)_.add(P);let k=pj(t.created_at);await Eve(a,n,_,k);let v=new Map;for(let[P,O]of await fj(a))if(_.has(P))v.set(P,O);let{scrub:C,uploaded:T}=await hEe({work:a,datasetId:o,scope:_,body:r,oursKeys:g,annexFromGit:b.annexFromGit,reader:p,upload:f,bucket:l,now:k,maxBytes:e.normalizeMaxBytes,upstreamBare:c_(e.plannerDir,"upstream.git")});Cs(y);let z=i_(r,g),A=await yEe({work:a,baseSha:n,createdAt:t.created_at,body:r,digest:e.digest,scrub:C,uploaded:T,held:z,base:h,expected:b.expected,preScrub:v,scope:_,counts:{written:b.written,deleted:b.deleted}});await fM(a,s.bundle,n);let F=(P)=>P.every((O)=>O.size!==null)?{known:!0,bytes:P.reduce((O,H)=>O+(H.size??0),0)}:{known:!1,bytes:0},M=F(A.manifest.items),U=F(A.manifest.local),B=C.counts;return{synthSha:A.synthSha,synthTree:A.synthTree,manifestDigest:A.manifestDigest,counts:{delta_paths:b.deltaPaths.size,written:b.written,deleted:b.deleted,annex_copy_items:A.manifest.items.length,...M.known?{copy_bytes:M.bytes}:{},local_uploads:A.manifest.local.length,...U.known?{local_upload_bytes:U.bytes}:{},scrubbed_recordings:B.headers_scrubbed,dated_recordings:B.headers_dates_normalized,scrubbed_json:B.json_files_blanked,headers_not_read_nemar_held:B.headers_not_read_nemar_held,headers_not_read_no_source:B.headers_not_read_no_source,json_files_unread:B.json_files_unread,json_files_annexed:B.json_files_annexed,scans_tables_unread:B.scans_tables_unread,headers_dates_unproven:B.headers_dates_unproven,headers_dates_left:B.headers_dates_left,nemar_owned_edits:b.nemarOwned.applied,nemar_owned_edits_left:b.nemarOwned.left.length}}}var u_=`--automatic-dispatch <id> is the central run-upstream-repull workflow's, never an
|
|
444
444
|
administrator's: the run reads its dispatch from the event file GitHub delivered, reports to the
|
|
445
445
|
Worker with the dispatch's token, and prints only fixed lines (repull-auto: ...) because its log
|
|
446
446
|
is public. It refuses anything but the release the dispatch names, and needs GH_TOKEN.`;function PEe(e){let t=process.env.NEMAR_REPULL_POLL_MS;return t&&/^\d+$/.test(t)?Math.max(100,Number(t)):e}function _Rt(e){if(e instanceof N){let t=e.step?{step:e.step}:{};return e.resumable?{phase:"failed",code:e.code,exit:3,...t}:{phase:"refused",code:e.code,exit:1,...t}}return{phase:"failed",code:"runner-failed",exit:1}}var xRt=new Set(["auto-token-on-argv","auto-token-hour","auto-token-clock","head-unreadable","head-foreign"]),IEe=(e)=>Math.max(0,Math.round((Date.now()-e)/1000));function NEe(){let e=yR(process.env,Date.now());if(e===null)throw new N("auto-token-clock","When the App token was minted is not known.");return e}function HR(e,t,n){if(e.time("run",IEe(n)),e.emit("quiet",e.quietFields()),t.phase==="refused"||t.phase==="failed")e.emit("result",{phase:t.phase,code:_R(t.code)}),process.exitCode=t.exit;else e.emit("result",{phase:t.phase}),process.exitCode=0;ce()}async function kj(e){let t;try{t=await vRt(e)}finally{try{e.cleanup?.(t)}catch{}}}async function vRt(e){let t=Date.now(),n=gR();ce(),n.emit("start",{command:e.command,...T$.test(e.option)?{dispatch:e.option}:{}});let r=yR(process.env,t);if(r!==null)n.time("token_age",Math.max(0,Math.round(t/1000-r)));let o;try{o=fke(e.option,process.env,n)}catch(a){HR(n,{phase:"failed",code:a instanceof N?a.code:"runner-failed",exit:1},t);return}if(!pke(Cr())){HR(n,{phase:"failed",code:"auto-api-not-production",exit:1},t);return}let s;try{let a=BM(o.dispatch,process.argv);if(a)throw a;let c=mke(o.dispatch,{mode:e.mode,datasetId:e.datasetOf(),argv:process.argv,env:process.env});if(c)throw c;if(!ze())throw new N("runner-failed","The CLI is not signed in to NEMAR.");if(e.reportsStart){let l=await UM(o,"started");if(!l.stored&&l.code!=="already-started"){HR(n,{phase:"failed",code:l.code,exit:1},t);return}}s=await e.body(o)}catch(a){s=_Rt(a)}let i=s.phase==="refused"||s.phase==="failed"?s.code:void 0;if((s.phase==="refused"||s.phase==="failed")&&!xRt.has(s.code)&&await wke(o.dispatch.datasetId,process.env))s={phase:e.mode==="open"&&s.phase==="failed"&&s.exit===3?"refused":"failed",code:"token-expired",exit:s.exit};if(s.phase==="refused"||s.phase==="failed")s={...s,code:_R(s.code,s.step??e.step)};if(s.phase!=="planned"){let a=await UM(o,s.phase,s.phase==="opened"?{repullId:s.repullId}:s.phase==="refused"||s.phase==="failed"?{code:s.code}:{});if(!a.stored&&(s.phase==="opened"||s.phase==="finished"))s={phase:"failed",code:a.code,exit:1}}return HR(n,s,t),i}async function kRt(e){try{return await ac(e)}catch(t){if(t instanceof L)throw new N("record-refused","The NEMAR API did not answer for the dataset.");throw t}}function ERt(e){let n=(Array.isArray(e.body.refusals)?e.body.refusals:[]).find((s)=>typeof s?.code==="string");if(n)return n.code;let r=e.body.copy;if(Array.isArray(r?.unpinned)&&r.unpinned.length>0)return"key-without-pin";let o=e.preflight.find((s)=>s.status!=="ok");return o?.code??o?.name??"not-executable"}function Ej(e){for(let[t,n]of e)if(n)throw iy(t,"not-taken")}function FEe(e,t,n){return kj({command:"plan",mode:"open",step:"plan",option:e,datasetOf:()=>t,reportsStart:!0,async body(r){if(Ej([["--json",n.json===!0],["--counts",n.counts===!0],["--keep-workdir",n.keepWorkdir===!0],["--from-tag",n.fromTag!==void 0]]),!n.bucketListing)throw iy("--bucket-listing","required");if(!n.toTag)throw iy("--to-tag","required");if(!Sr(n.toTag,r.dispatch.toTag))throw new N("dispatch-mismatch","--to-tag is not the dispatch's tag.");let o=NEe(),s=await kRt(t);El(s);let i=n.out?wRt(n.out):OEe(Vn(),"repull",t);gRt(i,{recursive:!0,mode:448});let a=yRt(OEe(i,".planning-"));try{let c=new Map,l,d=Date.now();try{l=await Zg({datasetId:t,toTag:r.dispatch.toTag,maxFetchBytes:Math.floor(n.maxFetchGb*1073741824),keepWorkdir:!0,workRoot:a,collect:{computed:c},catalog:s,github:{token:process.env.GH_TOKEN?.trim()??null,apiBase:kn()},environment:Cr(),presence:"bucket-listing",openNeuroGraphqlUrl:kl(process.env)})}catch(b){if(b instanceof bo)return{phase:"failed",code:"not-planned",exit:1};throw b}finally{r.sink.time("plan",IEe(d))}if(!l.planned)return{phase:"refused",code:l.reason,exit:1};let f=l.file,p=Fr(f.body);if(p.ds!==r.dispatch.upstreamDs||!Sr(p.fromTag,r.dispatch.fromTag))return{phase:"refused",code:"dispatch-mismatch",exit:1};let m=n.out??Ag(Vn(),t,p.toTag,f.digest);V$(m,f);let h=kc(f.body),g={executable:f.executable};for(let b of["delta_paths","copy_items","unexplained","conflicts","corrections"])if(h[b]!==void 0)g[b]=h[b];if(r.sink.emit("plan",g),!f.executable)return{phase:"refused",code:ERt(f),exit:3};try{gke(f)}catch(b){if(b instanceof N)return{phase:"refused",code:b.code,exit:3};throw b}let y=e_(o,Date.now(),t_(f.body));if(y)return{phase:"refused",code:y.code,exit:1};if(l.workdir===null)return{phase:"failed",code:"not-planned",exit:1};return yke(m,l.workdir,c,f.digest),{phase:"planned"}}finally{TEe(a,{recursive:!0,force:!0,maxRetries:5,retryDelay:50})}}})}function MEe(e,t,n){return kj({command:"execute",mode:"open",step:"plan",option:e,datasetOf:()=>VD(t).datasetId,reportsStart:!1,cleanup:(r)=>{if(r!=="execution-locked")TEe(wR(t),{recursive:!0,force:!0})},async body(r){if(Ej([["--json",n.json===!0],["--keep-workdir",n.keepWorkdir===!0],["--until",n.until!=="pr_open"]]),!n.yes)throw iy("--yes","required");let o=Fr(z$(bRt(t,"utf8")).body);if(o.ds!==r.dispatch.upstreamDs||!Sr(o.fromTag,r.dispatch.fromTag)||!Sr(o.toTag,r.dispatch.toTag))throw new N("dispatch-mismatch","The plan is not for the dispatch's tags.");let s=await BR({planPath:t,until:"pr_open",keepWorkdir:!1,...n.normalizeMaxGb!==void 0?{normalizeMaxBytes:Math.floor(n.normalizeMaxGb*1073741824)}:{},maxFetchBytes:Math.floor(n.maxFetchGb*1073741824),automatic:{dispatchId:r.dispatch.dispatchId,token:r.dispatch.token,repullId:r.dispatch.repullId,settle:{maxWaitMs:(n.settleMinutes??vEe)*60000,quietMs:_Ee,pollMs:PEe(xEe)},tokenSince:NEe(),measured:(a,c)=>r.sink.time(a,c)},out:(a)=>r.sink.drop(a)}),i=s.row;if(r.sink.emit("execute",{status:i.status,repull:i.id,pr:i.pr_number??0}),s.settled){let a=s.settled;if(r.sink.emit("settle",{reads:a.reads,moves:a.moves,unreadable:a.unreadable}),a.outcome==="foreign")return{phase:"failed",code:"head-foreign",exit:1};if(a.outcome==="unreadable")return{phase:"failed",code:"head-unreadable",exit:3}}return{phase:"opened",repullId:i.id}}})}function jEe(e,t,n){return kj({command:"resume",mode:"finish",step:"finish",option:e,datasetOf:()=>t,reportsStart:!0,async body(r){if(Ej([["--json",n.json===!0],["--acknowledge-identifier-screen",n.acknowledgeIdentifierScreen!==void 0]]),!n.yes)throw iy("--yes","required");let o=r.dispatch.repullId,s=await mR({datasetId:t,waitMinutes:n.waitMinutes,automaticFinish:{repullId:o},out:(i)=>r.sink.drop(i),pollMs:PEe(15000)});if(r.sink.emit("resume",{status:s.row?.status??"none",outcome:s.outcome}),s.outcome==="complete")return{phase:"finished"};if(s.outcome==="ended"||s.outcome==="nothing")return{phase:"refused",code:"finish-not-merged",exit:1};return{phase:"failed",code:"finish-incomplete",exit:3}}})}var Dp=3;function uy(e,t){if(/^[a-z]{2}\d{6}$/.test(e))return e;return dt(`"${e}" is not a dataset id (like on004362).`,{json:t,answered:!0}),Ao(),null}function Sj(e){let t=Number(e);if(!/^\d{1,3}$/.test(e.trim())||t>120)throw new Ms("a whole number of minutes from 0 to 120 is required.");return t}function LEe(e){let t=e.trim();if(t.length<Yo||t.length>Xo)throw new Ms(`a reason of ${Yo} to ${Xo} characters is required.`);return t}function $j(e,t,n){if(e instanceof N){dt(`Refused (${e.code}): ${e.message}`,{json:t,answered:!0});for(let r of e.lines)n(r);if(e.resumable)process.exitCode=Dp;return}dt(`Failed: ${G(e)}`,{json:t,answered:e instanceof L})}var qEe=new de("status").argument("<datasetId>").description("Show the record of a dataset's re-pulls: state, pull request, screen, what is next").option("--json","Print the records and the newest one's screens as JSON").action(async(e,t)=>{let n=t.json===!0;if(!mn(n))return;if(!uy(e,n))return;try{let{repulls:r}=await Io({dataset:e,limit:5}),o=r[0],s=o?await kg(o.id):null;if(n){console.log(JSON.stringify({repulls:r,screens:s},null,2));return}if(!o){console.log(`${e} has no re-pull on record.`);return}for(let i of ike(o,s?.exempt?null:s?.screens??[]))console.log(i);if(r.length>1){console.log("Earlier attempts:");for(let i of r.slice(1))console.log(ake(i))}}catch(r){dt(`Could not read the re-pulls of ${e}: ${G(r)}`,{json:n,answered:r instanceof L})}}),SRt=`
|
|
@@ -661,7 +661,7 @@ allow <dataset> <pr> --admin
|
|
|
661
661
|
A NEMAR owner or administrator is exempt from the review whatever is decided here: their pull
|
|
662
662
|
requests are not reviewed, so a block does not hold them back and an allow changes nothing. (A
|
|
663
663
|
commit a review is already on record for is handled as before, a block included.)
|
|
664
|
-
`).action(async(e,t)=>{if(!Pl(t.json))process.exit(1);if(t.reason&&t.reason.length>VR)Xt(`The reason is ${t.reason.length} characters; ${VR} is the most that is kept.`,void 0,t.json);await aSe("block",e,t)});Xi.command("clear <login>").description("Remove an allow or block (a contributor with neither is reviewed automatically)").option("--json","Output the raw JSON").action(async(e,t)=>{if(!Pl(t.json))process.exit(1);let n=f_(e,t.json),r=t.json?null:D(`Clearing ${n}...`).start();try{let o=await ame(n);if(r?.stop(),t.json){console.log(JSON.stringify(o,null,2));return}console.log(o.removed?u.green(`Removed the ${o.removed} for ${I(o.standing.login)}. Their pull requests are reviewed automatically.`):o.standing.resolved_from==="history"?u.yellow(`No allow or block found for ${I(o.standing.login)} under the id the Worker has on file (GitHub did not confirm this login).`):u.dim(`${I(o.standing.login)} had no allow or block.`)),console.log();for(let s of YR(o.standing))console.log(s);Cp(o.environment)}catch(o){Yi(o,r,`Could not clear ${n}`,t.json)}});Xi.command("standing <login>").description("A contributor's record of rejected pull requests (information only), and any allow or block").option("--json","Output the raw JSON").action(async(e,t)=>{if(!Pl(t.json))process.exit(1);let n=f_(e,t.json),r=t.json?null:D(`Reading ${n}...`).start();try{let o=await sme(n);if(r?.stop(),t.json){console.log(JSON.stringify(o,null,2));return}console.log();for(let s of YR(o))console.log(s);console.log()}catch(o){Yi(o,r,`Could not read ${n}`,t.json)}});He();Ws();ro();Ni();dn();Ep();var Oj=25;function s1t(e){return`Dataset Name must be a descriptive title of at least 25 characters${e===void 0?"":` (currently ${e})`}. If the study is known by a short acronym, expand it with a subtitle, e.g. "ACRO: auditory cortex recordings during natural speech".`}function i1t(e){return`This is an anonymous release, but Authors in dataset_description.json still names ${e===void 0?"somebody":e.join(", ")}. That file is part of the dataset and is served publicly, so NEMAR cannot conceal what it says. Replace the entries with a placeholder such as "Anonymous", commit, and request the release again. Restore the real names when you publish after acceptance.`}var _an={description_missing:"dataset_description.json was not found at the dataset root.",description_not_json:"dataset_description.json is not valid JSON.",description_not_object:"dataset_description.json is not a JSON object.",name_too_short:s1t(),authors_missing:"Authors in dataset_description.json must name the people responsible for the dataset; anonymous submissions and placeholder entries are not accepted.",authors_empty_for_anonymous:'Authors in dataset_description.json must not be empty, even for an anonymous release: set it to a placeholder such as "Anonymous" so the field states that attribution is withheld rather than missing.',authors_not_blinded:i1t(),ethics_statement_missing:"An ethics approval statement is required: fill the EthicsApprovals field of dataset_description.json, or add an ethics/IRB statement to the README."};var Tj=50;var m_=["complete_and_honest","meets_standards","authors_and_license","name_adequate"];var t1=["readme","dataset_description","changes","license","participants_json"];var a1t=["sent","sent_cut","absent","withheld_finding","withheld_unreadable","withheld_not_utf8","withheld_annexed","withheld_not_json"],c1t=a1t.filter((e)=>e.startsWith("withheld_"));function l1t(e){return c1t.includes(e)}var u1t={complete_and_honest:["readme","changes"],meets_standards:["readme","dataset_description"],authors_and_license:["dataset_description","license"],name_adequate:["dataset_description"]};var Can=new Set([...DR,".edf",".bdf"]);var d1t="1.0.0";function n1(e){if(e.version_shape==="ok")return e.version;if(e.version_shape==="missing")return d1t;return null}var f1t=xu;var Aan=new Set(GM);var p1t={readme_absent:"no README was found at the dataset root",text_not_seen_in_full:"the reviewer was not shown all of the text this question needs",no_recordings:"the dataset's structure shows no recordings",license_field_missing:"dataset_description.json sets no License",name_too_short:`the Name in dataset_description.json is shorter than ${Oj} characters`,placeholder_author:"Authors names a placeholder instead of a person"},cSe={pass:2,unknown:1,fail:0};function m1t(e){let t={...e.questions},n=[],r=(s,i,a,c)=>{if(cSe[c]<cSe[t[s]])t[s]=c,n.push({question:s,code:a,fact:i,result:c})},o=e.evidence;if(o.documents.readme==="absent")r("complete_and_honest","readme_absent","readme_missing_or_stub","fail");for(let s of m_)if(u1t[s].map((a)=>o.documents[a]).some((a)=>a==="sent_cut"||l1t(a)))r(s,"text_not_seen_in_full","evidence_incomplete","unknown");if(o.summary.recordings===0)r("complete_and_honest","no_recordings","evidence_incomplete","unknown");if(!o.license_field)r("authors_and_license","license_field_missing","license_missing","fail");if(o.name_length<Oj)r("name_adequate","name_too_short","name_not_descriptive","fail");if(!o.anonymous&&o.placeholder_authors>0)r("authors_and_license","placeholder_author","authors_placeholder","fail");return{answers:t,notes:n}}function h1t(e){return m1t(e).notes.map(({question:t,fact:n,result:r})=>({question:t,fact:n,result:r,text:p1t[n]}))}var g1t=["depositor_limit","platform_limit"],y1t=["evidence_unavailable","stale_head","auth_failed","model_unavailable","model_refused","model_truncated","model_invalid","report_invalid","dispatch_failed","dispatch_unconfigured","review_disabled","workflow_failed"];function b1t(e){return tw(y1t,e)}function w1t(e){return tw(g1t,e)}var my=["request_blocked","submission_minimum_failed","identifier_screen_blocks","identifier_screen_not_run","identifier_screen_pending","identifier_screen_stale","version_kept_after_anonymous_release","identifier_screen_needs_acknowledgment","question_failed","steering_attempt","bids_failed_at_review","version_already_released","version_malformed","stored_verdict_fail","review_not_started","review_running","review_did_not_report","review_limit_reached","review_could_not_run","text_withheld","question_unknown","bids_unconcluded_at_review","version_missing","doi_state_unexpected"],uSe=" (--force)",jr=`An administrator may approve over it; the approval records the override${uSe}.`,Oan=jr.replace(uSe,""),ZR=`A review starts only for a request that is waiting for its decision. ${jr}`,e1="nemar admin publish screen <dataset>",Il="nemar admin publish start <dataset>",p_="nemar admin publish show <dataset>",_1t="nemar admin publish approve <dataset>",x1t="nemar admin publish deny <dataset>",v1t='--acknowledge-identifier-screen "<reason>"',lSe=`${_1t} ${v1t}`;function dSe(e,t){return e.replaceAll("<dataset>",t)}var Sc={request_blocked:{class:"fail",clearedBy:"nothing",sentence:"The request is blocked.",cure:"The depositor fixes what blocked it and requests publication again."},submission_minimum_failed:{class:"fail",clearedBy:"nothing",sentence:"A submission minimum failed at the reviewed commit.",cure:"The depositor fixes the dataset and requests publication again; a request still waiting for its decision is moved to blocked."},identifier_screen_blocks:{class:"fail",clearedBy:"nothing",sentence:"The identifier screen found a direct identifier.",cure:"The depositor removes it and requests publication again, which runs the screen again."},identifier_screen_not_run:{class:"unknown",clearedBy:"nothing",sentence:"The identifier screen has no verdict about the current commit.",cure:`An administrator runs the screen again: ${e1}.`,command:e1},identifier_screen_pending:{class:"unknown",clearedBy:"nothing",sentence:"The identifier screen is still running.",cure:"Wait for it to report; the review starts when it does."},identifier_screen_stale:{class:"unknown",clearedBy:"nothing",sentence:"The identifier screen read a commit that is no longer the head of main.",cure:`An administrator runs the screen again: ${e1}.`,command:e1},version_kept_after_anonymous_release:{class:"fail",clearedBy:"nothing",sentence:"This named publication keeps the version that an earlier anonymous release of the dataset used.",cure:"The depositor raises Version in dataset_description.json and requests publication again."},identifier_screen_needs_acknowledgment:{class:"unknown",clearedBy:"screen_acknowledgment",sentence:"The identifier screen found something a person must look at, or could not read everything.",cure:`An administrator reads what the screen reported and approves with a recorded reason: ${lSe}.`,command:lSe},question_failed:{class:"fail",clearedBy:"override",sentence:"A question of the review failed.",cure:`Read any findings and the dataset's text. ${jr}`},steering_attempt:{class:"fail",clearedBy:"override",sentence:"Text in the dataset tried to instruct the reviewer.",cure:`Read the dataset's text yourself; the review's answers cannot be relied on. ${jr}`},bids_failed_at_review:{class:"fail",clearedBy:"override",sentence:"BIDS validation failed at the reviewed commit.",cure:`The depositor fixes the validation errors and requests publication again. ${jr}`},version_already_released:{class:"fail",clearedBy:"override",sentence:"This version was already released: NEMAR has a release of it, or its tag names another commit.",cure:`The depositor raises Version in dataset_description.json. ${jr}`},version_malformed:{class:"fail",clearedBy:"override",sentence:"Version in dataset_description.json is not of the form X.Y.Z.",cure:`The depositor corrects Version. ${jr}`},stored_verdict_fail:{class:"fail",clearedBy:"override",sentence:"The stored review concluded fail, and its report no longer shows why.",cure:`Read the review's record: ${p_}. ${jr}`,command:p_},review_not_started:{class:"unknown",clearedBy:"override",sentence:"No review of the screened commit has started.",cure:`Start it: ${Il}. ${jr}`,command:Il,cureNotStartable:ZR},review_running:{class:"unknown",clearedBy:"override",sentence:"The review is running.",cure:`Wait for it to report; it usually takes minutes. ${jr}`},review_did_not_report:{class:"unknown",clearedBy:"override",sentence:"The review did not report in time.",cure:`Start it again: ${Il}. ${jr}`,command:Il,cureNotStartable:ZR},review_limit_reached:{class:"unknown",clearedBy:"override",sentence:"The daily limit of automated reviews was reached.",cure:`Start it later: ${Il}; an administrator's start is held by the platform's limit only. ${jr}`,command:Il,cureNotStartable:ZR},review_could_not_run:{class:"unknown",clearedBy:"override",sentence:"The review could not run.",cure:`Once the cause is fixed, start it again: ${Il}. ${jr}`,command:Il,cureNotStartable:ZR},text_withheld:{class:"unknown",clearedBy:"override",sentence:"Some of the dataset's text was withheld from the reviewer.",cure:`Read the withheld documents yourself. ${jr}`},question_unknown:{class:"unknown",clearedBy:"override",sentence:"A question of the review could not be answered.",cure:`Answer it yourself from the dataset. ${jr}`},bids_unconcluded_at_review:{class:"unknown",clearedBy:"override",sentence:"BIDS validation had not concluded at the reviewed commit.",cure:`Check the validation run of that commit. ${jr}`},version_missing:{class:"unknown",clearedBy:"override",sentence:"dataset_description.json sets no Version, so the publication would be 1.0.0.",cure:`Confirm that 1.0.0 is right, or have the depositor set Version. ${jr}`},doi_state_unexpected:{class:"unknown",clearedBy:"override",sentence:"The dataset already has a concept DOI that no earlier anonymous release reserved.",cure:`Check the DOI record before approving. ${jr}`}},Tan=my.filter((e)=>Sc[e].clearedBy==="nothing"),Pan=my.filter((e)=>Sc[e].clearedBy==="override");function fSe(e){return e.filter((t)=>Sc[t.code].clearedBy==="nothing")}function k1t(e){return e.filter((t)=>Sc[t.code].clearedBy==="override")}function Pj(e,t){let n=new Set(t),r=new Set(k1t(e).map((o)=>o.code));return my.filter((o)=>r.has(o)&&!n.has(o))}var Ian=my.filter((e)=>Sc[e].cureNotStartable!==void 0);function E1t(e,t){let n=!t&&e.cureNotStartable!==void 0;return{text:n?e.cureNotStartable:e.cure,alternative:n}}function pSe(e){return f1t.test(e)?e:"<dataset>"}function S1t(e,t,n){return dSe(E1t(Sc[e],n).text,pSe(t))}var Ij={complete_and_honest:"the README is complete and agrees with the dataset",meets_standards:"the submission standards and the ethics and provenance statements are met",authors_and_license:"the authors and the license are real and consistent",name_adequate:"the name describes the dataset"},Nj={readme_missing_or_stub:"README missing or a stub",readme_mismatch:"README does not match the dataset",description_incomplete:"Description incomplete",ethics_statement_missing:"Ethics statement missing",ethics_statement_inadequate:"Ethics statement inadequate",authors_placeholder:"Placeholder authors",authors_inconsistent:"Authors inconsistent",license_missing:"License missing",license_inconsistent:"License inconsistent",name_not_descriptive:"Name not descriptive",changes_inconsistent:"CHANGES inconsistent",provenance_unclear:"Provenance unclear",source_license_conflict:"License conflicts with a source",evidence_incomplete:"Evidence incomplete",steering_attempt:"Text tried to instruct the reviewer",other:"Other"},r1={readme:"README",dataset_description:"dataset_description.json",changes:"CHANGES",license:"LICENSE",participants_json:"participants.json"},$1t={evidence_unavailable:"the dataset could not be read at the reviewed commit",stale_head:"the request or its screened commit changed before the review started",auth_failed:"the review job could not sign in to the model",model_unavailable:"the reviewing model was unavailable",model_refused:"the reviewing model declined to review",model_truncated:"the reviewing model ran out of room before it finished",model_invalid:"the reviewing model did not return a usable answer",report_invalid:"the review's report could not be read back",dispatch_failed:"GitHub did not start the review job",dispatch_unconfigured:"the Worker had no GitHub credential or callback secret to start the review",review_disabled:"the automated review was off when the job tried to start",workflow_failed:"the review job failed before it finished"},D1t={depositor_limit:"this depositor's daily limit",platform_limit:"the platform's daily limit"};function R1t(e,t){let n=e.detail;if(n===null)return null;switch(e.code){case"question_failed":case"question_unknown":{if(!tw(m_,n))return n;let r=e.code==="question_failed"?"fail":"unknown",o=[Ij[n]];if(t!==null){for(let a of h1t(t))if(a.question===n&&a.result===r)o.push(a.text)}let s=(t?.findings??[]).filter((a)=>a.question===n).map((a)=>Nj[a.code]),i=[...new Set(s)];if(i.length>0)o.push(`findings: ${i.join(", ")}`);return o.join("; ")}case"text_withheld":return n.split(",").map((r)=>tw(t1,r)?r1[r]:r).join(", ");case"review_could_not_run":return b1t(n)?$1t[n]:n;case"review_limit_reached":return w1t(n)?D1t[n]:n;default:return n.replaceAll(",",", ")}}function C1t(e,t){let n=Sc[e.code],r=R1t(e,t);return r===null?n.sentence:`${n.sentence.replace(/\.$/,"")} (${r}).`}function mSe(e,t,n,r){return`${C1t(e,n)} ${S1t(e.code,t,r)}`}var Nan=`This approval stopped before it started publishing, and a reason that nothing clears now stands, so it cannot be resumed. Deny it with a reason (${x1t}); the depositor can request again.`;var A1t={hard_reason:"The publication review gives a reason that no override clears, so the approval is refused.",needs_override:`The publication review is not a pass. Read it (${p_}), then approve over it with --force, which records the override with your account.`,override_not_covering:`The review now gives a reason the override was not given for. Read it again (${p_}) before approving.`,review_changed:`The review the override was given for is no longer the review of this request, or it changed while the approval was being checked. Read it again (${p_}) before approving.`,no_review_row:`No review of this commit is on record to attach the override to. Start it (${Il}), or approve from a terminal with --force.`,unverified:"The publication review could not be checked just now, so the approval is refused. Try again."};function Fj(e,t){return dSe(A1t[e],pSe(t))}Ke();Ni();var O1t=["enforced","off","n/a"],gSe=my,Ud=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e);function T1t(e){return Ud(e)&&typeof e.code==="string"&&gSe.includes(e.code)&&typeof e.sentence==="string"&&typeof e.cure==="string"&&(e.detail===null||typeof e.detail==="string")&&(e.line===void 0||typeof e.line==="string")&&e.cleared_by===Sc[e.code].clearedBy}function P1t(e){return Ud(e)&&Array.isArray(e.reasons)&&e.reasons.some((t)=>Ud(t)&&typeof t.code==="string"&&gSe.includes(t.code)&&typeof t.cleared_by==="string"&&t.cleared_by!==Sc[t.code].clearedBy)}function I1t(e){if(!Ud(e)||typeof e.id!=="number"||!Number.isInteger(e.id))return!1;let t=e.override;return t===null||Ud(t)&&typeof t.by==="number"&&typeof t.at==="string"&&Array.isArray(t.reasons)&&t.reasons.every((n)=>typeof n==="string")}function N1t(e){if(!Ud(e))return null;let t=e.screen_acknowledgment;return typeof e.request_status==="string"&&typeof e.gate==="string"&&O1t.includes(e.gate)&&typeof e.started_publishing==="boolean"&&(e.block_reason===null||typeof e.block_reason==="string")&&(t===null||Ud(t)&&typeof t.by==="number"&&typeof t.at==="string")&&Array.isArray(e.reasons)&&e.reasons.every(T1t)&&(e.review===null||I1t(e.review))&&Ud(e.description)&&typeof e.description.headline==="string"&&Array.isArray(e.description.lines)&&e.description.lines.every((r)=>typeof r==="string")?e:null}var F1t=[400,401,403];async function hy(e){try{let t=await xS(e),n=N1t(t);if(n!==null)return{kind:"detail",detail:n};return{kind:"unreadable",why:P1t(t)?"this version of the CLI classifies a reason differently from the API":"the NEMAR API sent a review this version of the CLI cannot read"}}catch(t){if(t instanceof L&&t.statusCode===404)return{kind:"absent",why:ng(t)==="not_found"?"no_request":"no_route"};let n=t instanceof L&&t.statusCode!==0?`HTTP ${t.statusCode}`:G(t);return t instanceof L&&F1t.includes(t.statusCode)?{kind:"unreadable",why:n,refused:t}:{kind:"unreadable",why:n}}}function Hd(e){return typeof e.line==="string"&&e.line!==""?e.line:`${e.sentence} ${e.cure}`}function hSe(e,t){return`nemar admin publish approve ${e}${t.resume?" --resume":""}${t.acknowledge?' --acknowledge-identifier-screen "<reason>"':""}${t.force?" --force":""}`}function h_(e,t,n){if(t.kind!=="detail"){let p=t.kind==="unreadable"?`The publication review could not be read (${t.why}); the API still checks it.`:t.why==="no_route"?"This API has no publication review.":`No active publication request was found for ${e}; the API decides.`;return{kind:"proceed",override:null,notes:n.force?[p,"--force was not sent: no review could be read to approve over."]:[p]}}let{detail:r}=t,o=e;if(r.started_publishing){if(!n.resume)return{kind:"refuse",why:"needs_resume",lines:[`This approval has already started publishing. Continue it with: nemar admin publish approve ${o} --resume`]};return{kind:"proceed",override:null,notes:["It passed the gates when it started; a resume that has started publishing is not gated again."]}}if(r.request_status==="blocked"){let p=r.block_reason===null?void 0:JI[r.block_reason],m=[mSe({code:"request_blocked",detail:r.block_reason},o,null,!1)];if(p)m.push(p);return{kind:"refuse",why:"blocked",lines:m}}if(r.gate!=="enforced")return{kind:"proceed",override:null,notes:n.force?[`--force changes nothing: the review gate is ${r.gate}.`]:[]};let s=n.resume||r.request_status==="approving",i=n.acknowledge!==void 0,a=fSe(r.reasons);if(a.length>0)return{kind:"refuse",why:"hard",lines:[Fj("hard_reason",o),...a.map(Hd)]};let c=Pj(r.reasons,[]),l=r.review?.override??null,d=l!==null&&Pj(r.reasons,l.reasons).length===0,f=r.reasons.find((p)=>p.code==="identifier_screen_needs_acknowledgment");if(f!==void 0&&!i&&r.screen_acknowledgment===null){let p=[Hd(f)];if(c.length>0&&!n.force&&!d)p.push(`The review is not a pass either, so that command also needs --force: ${hSe(o,{resume:s,acknowledge:!0,force:!0})}`);return{kind:"refuse",why:"needs_ack",lines:p}}if(c.length===0)return{kind:"proceed",override:null,notes:[]};if(n.force)return{kind:"proceed",override:{review_id:r.review?.id??null,reasons:c},notes:[`Approving over: ${c.join(", ")} (--force; recorded with your account).`]};if(l!==null&&d)return{kind:"proceed",override:null,notes:[`An override by administrator #${l.by} at ${l.at} covers these reasons. The API accepts it only for a run recorded as theirs.`]};return{kind:"refuse",why:"needs_force",lines:[Fj("needs_override",o),`To approve over them, run: ${hSe(o,{resume:s,acknowledge:i,force:!0})}`]}}He();He();Ep();var M1t={ok:u.green,note:u.cyan,warn:u.yellow,stop:u.red};function $c(e,t=2){if(!e||typeof e.headline!=="string")return[];let n=" ".repeat(t),r=M1t[e.tone]??u.white,o=[`${n}${r(e.headline)}`];for(let s of Array.isArray(e.lines)?e.lines:[])o.push(`${n} ${$ke(s)?u.yellow(s):u.dim(s)}`);return o}var j1t={ok:u.green,note:u.cyan,warn:u.yellow,stop:u.red};function g_(e){return j1t[e]??u.yellow}var gy="This is the non-production Worker. It holds its own record and answers only for the datasets it owns; it does not change what production reviews.",L1t="written by the model; the depositor's text can steer them",q1t="written by the model; the depositor's text can steer it";function ySe(e,t){let n=I(t);switch(e){case"dispatched":return`${n}: review started.`;case"redispatched":return`${n}: review started again.`;case"dispatch_claimed":return`${n}: a review of this commit was already handed over and stands.`;default:return`${n}: review started (${I(e)}).`}}function o1(e,t){if(!e||typeof e.headline!=="string")return[];return $c({...e,headline:I(e.headline),lines:Array.isArray(e.lines)?e.lines.map(I):[]},t)}function bSe(e,t=4){if(!e||e.outcome===null||e.outcome===void 0)return null;let n=(Array.isArray(e.reasons)?e.reasons:[]).map(I).join(", ");return`${" ".repeat(t)}${g_(e.tone)(I(e.headline))}${n===""?"":` ${u.dim(n)}`}`}var Mj=(e,t)=>`${e} ${t}${e===1?"":"s"}`,B1t={absent:"tag absent",at_head:"tag at the reviewed commit",elsewhere:"tag at another commit"};function U1t(e){let t=n1(e);if(t===null)return"version malformed (X.Y.Z expected)";let n=[];if(e.version_shape==="missing")n.push("dataset_description.json sets no Version");let r=B1t[e.tag];if(r)n.push(r);return`version ${I(t)}${n.length>0?` (${n.join("; ")})`:""}`}function H1t(e){let t=e.summary,n=[U1t(e),`BIDS ${I(e.bids)}`];n.push(e.minimums==="met"?"minimums met":`minimums failed (${e.minimum_failures.map(I).join(", ")})`),n.push(Mj(t.subjects,"subject"),Mj(t.sessions,"session"));let r=Object.entries(t.formats).map(([o,s])=>`${I(o)} ${s}`).join(", ");if(n.push(`${Mj(t.recordings,"recording")}${r===""?"":` (${r})`}`),n.push(`datatypes ${t.datatypes.length===0?"none":t.datatypes.map(I).join(", ")}`),t.sampling_rates_hz.length>0)n.push(`sampling rates ${t.sampling_rates_hz.join(", ")} Hz`);if(t.channel_counts.length>0)n.push(`channel counts ${t.channel_counts.join(", ")}`);return n.push(`sidecars read ${t.sidecars_read} of ${t.sidecars_total}`),`Evidence: ${n.join(", ")}`}function z1t(e){if(e==="sent_cut")return"sent (cut)";if(e.startsWith("withheld_"))return`withheld (${I(e.slice(9)).replaceAll("_"," ")})`;return I(e).replaceAll("_"," ")}function wSe(e){return`Shown to the model: ${t1.map((n)=>{let r=e.documents[n],o=`${r1[n]} ${z1t(r)}`;if(n==="dataset_description"&&(r==="sent"||r==="sent_cut"))o+=` (${e.description_keys_shown} keys shown, ${e.description_keys_not_shown} not)`;return o}).join(", ")}`}function _Se(e){let t=Object.entries(e.withheld_findings??{});if(t.length===0)return null;return`Withheld for findings: ${t.map(([n,r])=>`${I(n)} ${r}`).join(", ")}`}var jj=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e);function V1t(e){if(!jj(e))return!1;let t=e.documents;if(!jj(t))return!1;if(!t1.every((r)=>typeof t[r]==="string"))return!1;if(typeof e.description_keys_shown!=="number")return!1;if(typeof e.description_keys_not_shown!=="number")return!1;let n=e.withheld_findings;if(n===void 0||n===null)return!0;return jj(n)&&Object.values(n).every((r)=>typeof r==="number")}function xSe(e,t){let n=e?.evidence;if(!V1t(n))return[];let r=_Se(n);return[wSe(n),...r===null?[]:[r],`The whole review, with the model's questions and findings: nemar admin publish show ${I(t)}`]}var G1t={pass:u.green,fail:u.red,unknown:u.yellow};function W1t(e){if(e===null)return[];let t=[...m_.filter((r)=>(r in e)),...Object.keys(e).filter((r)=>!m_.includes(r))],n=Math.max(0,...t.map((r)=>r.length));return t.map((r)=>{let o=I(e[r]),s=Ij[r]??"";return` ${I(r).padEnd(n)} ${(G1t[o]??u.yellow)(o.padEnd(7))} ${s}`})}var K1t={blocker:u.red,concern:u.yellow,note:u.dim};function J1t(e){return e.map((t)=>{let n=Nj[t.code]??I(t.code),r=t.document===null?"":` (${r1[t.document]??I(t.document)})`,o=I(t.note),s=I(t.severity);return` ${(K1t[s]??u.yellow)(`[${s}]`)} ${n}${r}${o===""?"":`: ${o}`}`})}function Y1t(e){let t=e.review?.id??null,n=e.history.length===1&&e.history[0].id===t;if(e.history.length===0||n)return[];let r=[u.bold("History")];for(let o of e.history){let s=o.stored_verdict===null?"-":I(o.stored_verdict);r.push(` #${I(String(o.id)).padEnd(5)} ${I(o.head_sha).slice(0,12)} ${I(o.state).padEnd(10)} ${s.padEnd(15)} ${u.dim(I(o.created_at))}${o.id===t?u.dim(" in force"):""}`)}if(e.history_truncated)r.push(u.dim(" (older reviews not shown)"));return r}var X1t={enforced:"enforced",off:"off (advice only)","n/a":"n/a"};function s1(e){let t=[],n=e.anonymous?u.yellow("ANONYMOUS RELEASE"):"named publication",r=e.block_reason===null||e.block_reason===void 0?I(e.request_status):`${I(e.request_status)} (${I(e.block_reason)})`;if(t.push(`${u.bold(I(e.dataset_id))} request ${I(String(e.request_id))}, ${r}, ${n}`),e.environment!=="production")t.push(` ${u.yellow(gy)}`);if(t.push(""),t.push(...o1(e.identifier_screen,0)),e.screen_acknowledgment)t.push(` Acknowledged by administrator ${I(String(e.screen_acknowledgment.by))} at ${I(e.screen_acknowledgment.at)}.`);t.push("");let o=e.description;t.push(u.bold(g_(o.tone)(I(o.headline)))),t.push(` Gate: ${X1t[e.gate]??I(e.gate)}`);let s=o.lines.length>0?o.lines[o.lines.length-1]:null;for(let c of o.lines.slice(0,-1))t.push(` ${I(c)}`);let i=e.review;if(i!==null){let c=W1t(i.questions);if(c.length>0)t.push(" Questions:",...c);if(i.fact_notes.length>0){t.push(" Platform facts that lowered an answer:");for(let d of i.fact_notes)t.push(` ${I(d.question)}: ${I(d.text)}`)}if(i.findings.length>0)t.push(` Findings (${L1t}):`,...J1t(i.findings));let l=i.summary??o.summary;if(l!==null&&l!==void 0&&I(l)!=="")t.push(` Summary (${q1t}):`,` ${I(l)}`);if(i.evidence!==null){t.push(` ${H1t(i.evidence)}`,` ${wSe(i.evidence)}`);let d=_Se(i.evidence);if(d!==null)t.push(` ${d}`)}if(i.override!==null)t.push(` Override: by administrator ${I(String(i.override.by))} at ${I(i.override.at)} for ${i.override.reasons.map(I).join(", ")}`)}if(s!==null)t.push(` ${u.dim(I(s))}`);if(o.next!==null&&o.next!==void 0)t.push(` Next: ${I(o.next)}`);let a=Y1t(e);if(a.length>0)t.push("",...a);return t}var Q1t=new Set(["review_running","identifier_screen_pending"]);function yy(e){if(e.approval_in_flight===!0)return!1;if(e.status==="approving")return!0;if(e.status!=="requested")return!1;if(e.identifier_screen?.state==="pending")return!1;let t=e.publication_review?.reasons??[];return t.length===0||!t.every((n)=>Q1t.has(n))}function Lj(e){return[...e].sort((t,n)=>t.requested_at===n.requested_at?t.id-n.id:t.requested_at<n.requested_at?-1:1)}function vSe(e){return Lj(e.filter((t)=>t.status==="requested"&&t.publication_review?.start_offered===!0))}var Z1t=["requested","approving","blocked"],qj=["requested","approving","blocked","published","denied"];function Bj(e){if(e.all)return;let t=new Set(kSe(e));for(let r of qj)if(e[r])t.add(r);if(t.size===0)return[...Z1t];let n=qj.filter((r)=>t.has(r));return[...n,...[...t].filter((r)=>!n.includes(r))]}function kSe(e){return(e.status??"").split(",").map((t)=>t.trim()).filter(Boolean)}function Uj(e){return e.all===!0||qj.some((t)=>e[t])||kSe(e).length>0}function ESe(e){let t=Bj(e);if(!t)return"all requests";if(!Uj(e))return"active requests";return`requests with status ${t.join(" or ")}`}He();ro();dk();mk();Ke();Ni();dn();var wi="NEMAR_APPROVAL_DISPATCH_TOKEN",eCt=`This run presents the dispatch token in ${wi} (an executor's run for a web approval); unset the variable to approve as yourself.`,tCt=`If you are not running a dispatched approval, unset ${wi} and run it again.`;function nCt(e){let t=e?.trim()??"";if(t==="")return{kind:"none"};if(/^[\x21-\x7e]+$/.test(t))return{kind:"token",value:t};return{kind:"malformed",problem:/\s/.test(t)?"it contains whitespace":"it contains a character outside printable ASCII"}}function rCt(e){return e instanceof L&&e.statusCode===409&&(e.code==="dispatch_superseded"||e.code==="dispatch_expired")}function $Se(e){e.command("approve").description("Approve and publish a dataset (runs orchestrator)").argument("<dataset-id>","Dataset ID").option("--resume","Resume from last failed step").option("--sandbox",`Use Zenodo sandbox for testing (refused while ${wi} is set)`).option("--skip-ci-check",`Skip the orchestrator's live BIDS validation check (recorded; clears no review reason; refused while ${wi} is set)`).option("--acknowledge-identifier-screen <reason>",`Approve over an identifier screen that needs review, recording why (${Yo} to ${Xo} characters; refused while ${wi} is set)`).option("--force",`Approve over a publication review that is not a pass, recorded with your account (refused while ${wi} is set)`).option("--request-id <n>","The request this approval is for (default: the one shown); refused if it is not the request in force").option(Je,nt).option(yt,ht).addHelpText("after",`
|
|
664
|
+
`).action(async(e,t)=>{if(!Pl(t.json))process.exit(1);if(t.reason&&t.reason.length>VR)Xt(`The reason is ${t.reason.length} characters; ${VR} is the most that is kept.`,void 0,t.json);await aSe("block",e,t)});Xi.command("clear <login>").description("Remove an allow or block (a contributor with neither is reviewed automatically)").option("--json","Output the raw JSON").action(async(e,t)=>{if(!Pl(t.json))process.exit(1);let n=f_(e,t.json),r=t.json?null:D(`Clearing ${n}...`).start();try{let o=await ame(n);if(r?.stop(),t.json){console.log(JSON.stringify(o,null,2));return}console.log(o.removed?u.green(`Removed the ${o.removed} for ${I(o.standing.login)}. Their pull requests are reviewed automatically.`):o.standing.resolved_from==="history"?u.yellow(`No allow or block found for ${I(o.standing.login)} under the id the Worker has on file (GitHub did not confirm this login).`):u.dim(`${I(o.standing.login)} had no allow or block.`)),console.log();for(let s of YR(o.standing))console.log(s);Cp(o.environment)}catch(o){Yi(o,r,`Could not clear ${n}`,t.json)}});Xi.command("standing <login>").description("A contributor's record of rejected pull requests (information only), and any allow or block").option("--json","Output the raw JSON").action(async(e,t)=>{if(!Pl(t.json))process.exit(1);let n=f_(e,t.json),r=t.json?null:D(`Reading ${n}...`).start();try{let o=await sme(n);if(r?.stop(),t.json){console.log(JSON.stringify(o,null,2));return}console.log();for(let s of YR(o))console.log(s);console.log()}catch(o){Yi(o,r,`Could not read ${n}`,t.json)}});He();Ws();ro();Ni();dn();Ep();var Oj=25;function s1t(e){return`Dataset Name must be a descriptive title of at least 25 characters${e===void 0?"":` (currently ${e})`}. If the study is known by a short acronym, expand it with a subtitle, e.g. "ACRO: auditory cortex recordings during natural speech".`}function i1t(e){return`This is an anonymous release, but Authors in dataset_description.json still names ${e===void 0?"somebody":e.join(", ")}. That file is part of the dataset and is served publicly, so NEMAR cannot conceal what it says. Replace the entries with a placeholder such as "Anonymous", commit, and request the release again. Restore the real names when you publish after acceptance.`}var _an={description_missing:"dataset_description.json was not found at the dataset root.",description_not_json:"dataset_description.json is not valid JSON.",description_not_object:"dataset_description.json is not a JSON object.",name_too_short:s1t(),authors_missing:"Authors in dataset_description.json must name the people responsible for the dataset; anonymous submissions and placeholder entries are not accepted.",authors_empty_for_anonymous:'Authors in dataset_description.json must not be empty, even for an anonymous release: set it to a placeholder such as "Anonymous" so the field states that attribution is withheld rather than missing.',authors_not_blinded:i1t(),ethics_statement_missing:"An ethics approval statement is required: fill the EthicsApprovals field of dataset_description.json, or add an ethics/IRB statement to the README."};var Tj=50;var m_=["complete_and_honest","meets_standards","authors_and_license","name_adequate"];var t1=["readme","dataset_description","changes","license","participants_json"];var a1t=["sent","sent_cut","absent","withheld_finding","withheld_unreadable","withheld_not_utf8","withheld_annexed","withheld_not_json"],c1t=a1t.filter((e)=>e.startsWith("withheld_"));function l1t(e){return c1t.includes(e)}var u1t={complete_and_honest:["readme","changes"],meets_standards:["readme","dataset_description"],authors_and_license:["dataset_description","license"],name_adequate:["dataset_description"]};var Can=new Set([...DR,".edf",".bdf"]);var d1t="1.0.0";function n1(e){if(e.version_shape==="ok")return e.version;if(e.version_shape==="missing")return d1t;return null}var f1t=xu;var Aan=new Set(GM);var p1t={readme_absent:"no README was found at the dataset root",text_not_seen_in_full:"the reviewer was not shown all of the text this question needs",no_recordings:"the dataset's structure shows no recordings",license_field_missing:"dataset_description.json sets no License",name_too_short:`the Name in dataset_description.json is shorter than ${Oj} characters`,placeholder_author:"Authors names a placeholder instead of a person"},cSe={pass:2,unknown:1,fail:0};function m1t(e){let t={...e.questions},n=[],r=(s,i,a,c)=>{if(cSe[c]<cSe[t[s]])t[s]=c,n.push({question:s,code:a,fact:i,result:c})},o=e.evidence;if(o.documents.readme==="absent")r("complete_and_honest","readme_absent","readme_missing_or_stub","fail");for(let s of m_)if(u1t[s].map((a)=>o.documents[a]).some((a)=>a==="sent_cut"||l1t(a)))r(s,"text_not_seen_in_full","evidence_incomplete","unknown");if(o.summary.recordings===0)r("complete_and_honest","no_recordings","evidence_incomplete","unknown");if(!o.license_field)r("authors_and_license","license_field_missing","license_missing","fail");if(o.name_length<Oj)r("name_adequate","name_too_short","name_not_descriptive","fail");if(!o.anonymous&&o.placeholder_authors>0)r("authors_and_license","placeholder_author","authors_placeholder","fail");return{answers:t,notes:n}}function h1t(e){return m1t(e).notes.map(({question:t,fact:n,result:r})=>({question:t,fact:n,result:r,text:p1t[n]}))}var g1t=["depositor_limit","platform_limit"],y1t=["evidence_unavailable","stale_head","auth_failed","model_unavailable","model_refused","model_truncated","model_invalid","report_invalid","dispatch_failed","dispatch_unconfigured","review_disabled","workflow_failed"];function b1t(e){return tw(y1t,e)}function w1t(e){return tw(g1t,e)}var my=["request_blocked","submission_minimum_failed","identifier_screen_blocks","identifier_screen_not_run","identifier_screen_pending","identifier_screen_stale","version_kept_after_anonymous_release","identifier_screen_needs_acknowledgment","question_failed","steering_attempt","bids_failed_at_review","version_already_released","version_malformed","stored_verdict_fail","review_not_started","review_running","review_did_not_report","review_limit_reached","review_could_not_run","text_withheld","question_unknown","bids_unconcluded_at_review","version_missing","doi_state_unexpected"],uSe=" (--force)",jr=`An administrator may approve over it; the approval records the override${uSe}.`,Oan=jr.replace(uSe,""),ZR=`A review starts only for a request that is waiting for its decision. ${jr}`,e1="nemar admin publish screen <dataset>",Il="nemar admin publish start <dataset>",p_="nemar admin publish show <dataset>",_1t="nemar admin publish approve <dataset>",x1t="nemar admin publish deny <dataset>",v1t='--acknowledge-identifier-screen "<reason>"',lSe=`${_1t} ${v1t}`;function dSe(e,t){return e.replaceAll("<dataset>",t)}var Sc={request_blocked:{class:"fail",clearedBy:"nothing",sentence:"The request is blocked.",cure:"The depositor fixes what blocked it and requests publication again."},submission_minimum_failed:{class:"fail",clearedBy:"nothing",sentence:"A submission minimum failed at the reviewed commit.",cure:"The depositor fixes the dataset and requests publication again; a request still waiting for its decision is moved to blocked."},identifier_screen_blocks:{class:"fail",clearedBy:"nothing",sentence:"The identifier screen found a direct identifier.",cure:"The depositor removes it and requests publication again, which runs the screen again."},identifier_screen_not_run:{class:"unknown",clearedBy:"nothing",sentence:"The identifier screen has no verdict about the current commit.",cure:`An administrator runs the screen again: ${e1}.`,command:e1},identifier_screen_pending:{class:"unknown",clearedBy:"nothing",sentence:"The identifier screen is still running.",cure:"Wait for it to report; the review starts when it does."},identifier_screen_stale:{class:"unknown",clearedBy:"nothing",sentence:"The identifier screen read a commit that is no longer the head of main.",cure:`An administrator runs the screen again: ${e1}.`,command:e1},version_kept_after_anonymous_release:{class:"fail",clearedBy:"nothing",sentence:"This named publication keeps the version that an earlier anonymous release of the dataset used.",cure:"The depositor raises Version in dataset_description.json and requests publication again."},identifier_screen_needs_acknowledgment:{class:"unknown",clearedBy:"screen_acknowledgment",sentence:"The identifier screen found something a person must look at, or could not read everything.",cure:`An administrator reads what the screen reported and approves with a recorded reason: ${lSe}.`,command:lSe},question_failed:{class:"fail",clearedBy:"override",sentence:"A question of the review failed.",cure:`Read any findings and the dataset's text. ${jr}`},steering_attempt:{class:"fail",clearedBy:"override",sentence:"Text in the dataset tried to instruct the reviewer.",cure:`Read the dataset's text yourself; the review's answers cannot be relied on. ${jr}`},bids_failed_at_review:{class:"fail",clearedBy:"override",sentence:"BIDS validation failed at the reviewed commit.",cure:`The depositor fixes the validation errors and requests publication again. ${jr}`},version_already_released:{class:"fail",clearedBy:"override",sentence:"This version was already released: NEMAR has a release of it, or its tag names another commit.",cure:`The depositor raises Version in dataset_description.json. ${jr}`},version_malformed:{class:"fail",clearedBy:"override",sentence:"Version in dataset_description.json is not of the form X.Y.Z.",cure:`The depositor corrects Version. ${jr}`},stored_verdict_fail:{class:"fail",clearedBy:"override",sentence:"The stored review concluded fail, and its report no longer shows why.",cure:`Read the review's record: ${p_}. ${jr}`,command:p_},review_not_started:{class:"unknown",clearedBy:"override",sentence:"No review of the screened commit has started.",cure:`Start it: ${Il}. ${jr}`,command:Il,cureNotStartable:ZR},review_running:{class:"unknown",clearedBy:"override",sentence:"The review is running.",cure:`Wait for it to report; it usually takes minutes. ${jr}`},review_did_not_report:{class:"unknown",clearedBy:"override",sentence:"The review did not report in time.",cure:`Start it again: ${Il}. ${jr}`,command:Il,cureNotStartable:ZR},review_limit_reached:{class:"unknown",clearedBy:"override",sentence:"The daily limit of automated reviews was reached.",cure:`Start it later: ${Il}; an administrator's start is held by the platform's limit only. ${jr}`,command:Il,cureNotStartable:ZR},review_could_not_run:{class:"unknown",clearedBy:"override",sentence:"The review could not run.",cure:`Once the cause is fixed, start it again: ${Il}. ${jr}`,command:Il,cureNotStartable:ZR},text_withheld:{class:"unknown",clearedBy:"override",sentence:"Some of the dataset's text was withheld from the reviewer.",cure:`Read the withheld documents yourself. ${jr}`},question_unknown:{class:"unknown",clearedBy:"override",sentence:"A question of the review could not be answered.",cure:`Answer it yourself from the dataset. ${jr}`},bids_unconcluded_at_review:{class:"unknown",clearedBy:"override",sentence:"BIDS validation had not concluded at the reviewed commit.",cure:`Check the validation run of that commit. ${jr}`},version_missing:{class:"unknown",clearedBy:"override",sentence:"dataset_description.json sets no Version, so the publication would be 1.0.0.",cure:`Confirm that 1.0.0 is right, or have the depositor set Version. ${jr}`},doi_state_unexpected:{class:"unknown",clearedBy:"override",sentence:"The dataset already has a concept DOI that no earlier anonymous release reserved.",cure:`Check the DOI record before approving. ${jr}`}},Tan=my.filter((e)=>Sc[e].clearedBy==="nothing"),Pan=my.filter((e)=>Sc[e].clearedBy==="override");function fSe(e){return e.filter((t)=>Sc[t.code].clearedBy==="nothing")}function k1t(e){return e.filter((t)=>Sc[t.code].clearedBy==="override")}function Pj(e,t){let n=new Set(t),r=new Set(k1t(e).map((o)=>o.code));return my.filter((o)=>r.has(o)&&!n.has(o))}var Ian=my.filter((e)=>Sc[e].cureNotStartable!==void 0);function E1t(e,t){let n=!t&&e.cureNotStartable!==void 0;return{text:n?e.cureNotStartable:e.cure,alternative:n}}function pSe(e){return f1t.test(e)?e:"<dataset>"}function S1t(e,t,n){return dSe(E1t(Sc[e],n).text,pSe(t))}var Ij={complete_and_honest:"the README is complete and agrees with the dataset",meets_standards:"the submission standards and the ethics and provenance statements are met",authors_and_license:"the authors and the license are real and consistent",name_adequate:"the name describes the dataset"},Nj={readme_missing_or_stub:"README missing or a stub",readme_mismatch:"README does not match the dataset",description_incomplete:"Description incomplete",ethics_statement_missing:"Ethics statement missing",ethics_statement_inadequate:"Ethics statement inadequate",authors_placeholder:"Placeholder authors",authors_inconsistent:"Authors inconsistent",license_missing:"License missing",license_inconsistent:"License inconsistent",name_not_descriptive:"Name not descriptive",changes_inconsistent:"CHANGES inconsistent",provenance_unclear:"Provenance unclear",source_license_conflict:"License conflicts with a source",evidence_incomplete:"Evidence incomplete",steering_attempt:"Text tried to instruct the reviewer",other:"Other"},r1={readme:"README",dataset_description:"dataset_description.json",changes:"CHANGES",license:"LICENSE",participants_json:"participants.json"},$1t={evidence_unavailable:"the dataset could not be read at the reviewed commit",stale_head:"the request or its screened commit changed before the review started",auth_failed:"the review job could not sign in to the model",model_unavailable:"the reviewing model was unavailable",model_refused:"the reviewing model declined to review",model_truncated:"the reviewing model ran out of room before it finished",model_invalid:"the reviewing model did not return a usable answer",report_invalid:"the review's report could not be read back",dispatch_failed:"GitHub did not start the review job",dispatch_unconfigured:"the Worker had no GitHub credential or callback secret to start the review",review_disabled:"the automated review was off when the job tried to start",workflow_failed:"the review job failed before it finished"},D1t={depositor_limit:"this depositor's daily limit",platform_limit:"the platform's daily limit"};function R1t(e,t){let n=e.detail;if(n===null)return null;switch(e.code){case"question_failed":case"question_unknown":{if(!tw(m_,n))return n;let r=e.code==="question_failed"?"fail":"unknown",o=[Ij[n]];if(t!==null){for(let a of h1t(t))if(a.question===n&&a.result===r)o.push(a.text)}let s=(t?.findings??[]).filter((a)=>a.question===n).map((a)=>Nj[a.code]),i=[...new Set(s)];if(i.length>0)o.push(`findings: ${i.join(", ")}`);return o.join("; ")}case"text_withheld":return n.split(",").map((r)=>tw(t1,r)?r1[r]:r).join(", ");case"review_could_not_run":return b1t(n)?$1t[n]:n;case"review_limit_reached":return w1t(n)?D1t[n]:n;default:return n.replaceAll(",",", ")}}function C1t(e,t){let n=Sc[e.code],r=R1t(e,t);return r===null?n.sentence:`${n.sentence.replace(/\.$/,"")} (${r}).`}function mSe(e,t,n,r){return`${C1t(e,n)} ${S1t(e.code,t,r)}`}var Nan=`This approval stopped before it started publishing, and a reason that nothing clears now stands, so it cannot be resumed. Deny it with a reason (${x1t}); the depositor can request again.`;var A1t={hard_reason:"The publication review gives a reason that no override clears, so the approval is refused.",needs_override:`The publication review is not a pass. Read it (${p_}), then approve over it with --force, which records the override with your account.`,override_not_covering:`The review now gives a reason the override was not given for. Read it again (${p_}) before approving.`,review_changed:`The review the override was given for is no longer the review of this request, or it changed while the approval was being checked. Read it again (${p_}) before approving.`,no_review_row:`No review of this commit is on record to attach the override to. Start it (${Il}), or approve from a terminal with --force.`,unverified:"The publication review could not be checked just now, so the approval is refused. Try again."};function Fj(e,t){return dSe(A1t[e],pSe(t))}Je();Ni();var O1t=["enforced","off","n/a"],gSe=my,Ud=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e);function T1t(e){return Ud(e)&&typeof e.code==="string"&&gSe.includes(e.code)&&typeof e.sentence==="string"&&typeof e.cure==="string"&&(e.detail===null||typeof e.detail==="string")&&(e.line===void 0||typeof e.line==="string")&&e.cleared_by===Sc[e.code].clearedBy}function P1t(e){return Ud(e)&&Array.isArray(e.reasons)&&e.reasons.some((t)=>Ud(t)&&typeof t.code==="string"&&gSe.includes(t.code)&&typeof t.cleared_by==="string"&&t.cleared_by!==Sc[t.code].clearedBy)}function I1t(e){if(!Ud(e)||typeof e.id!=="number"||!Number.isInteger(e.id))return!1;let t=e.override;return t===null||Ud(t)&&typeof t.by==="number"&&typeof t.at==="string"&&Array.isArray(t.reasons)&&t.reasons.every((n)=>typeof n==="string")}function N1t(e){if(!Ud(e))return null;let t=e.screen_acknowledgment;return typeof e.request_status==="string"&&typeof e.gate==="string"&&O1t.includes(e.gate)&&typeof e.started_publishing==="boolean"&&(e.block_reason===null||typeof e.block_reason==="string")&&(t===null||Ud(t)&&typeof t.by==="number"&&typeof t.at==="string")&&Array.isArray(e.reasons)&&e.reasons.every(T1t)&&(e.review===null||I1t(e.review))&&Ud(e.description)&&typeof e.description.headline==="string"&&Array.isArray(e.description.lines)&&e.description.lines.every((r)=>typeof r==="string")?e:null}var F1t=[400,401,403];async function hy(e){try{let t=await xS(e),n=N1t(t);if(n!==null)return{kind:"detail",detail:n};return{kind:"unreadable",why:P1t(t)?"this version of the CLI classifies a reason differently from the API":"the NEMAR API sent a review this version of the CLI cannot read"}}catch(t){if(t instanceof L&&t.statusCode===404)return{kind:"absent",why:ng(t)==="not_found"?"no_request":"no_route"};let n=t instanceof L&&t.statusCode!==0?`HTTP ${t.statusCode}`:G(t);return t instanceof L&&F1t.includes(t.statusCode)?{kind:"unreadable",why:n,refused:t}:{kind:"unreadable",why:n}}}function Hd(e){return typeof e.line==="string"&&e.line!==""?e.line:`${e.sentence} ${e.cure}`}function hSe(e,t){return`nemar admin publish approve ${e}${t.resume?" --resume":""}${t.acknowledge?' --acknowledge-identifier-screen "<reason>"':""}${t.force?" --force":""}`}function h_(e,t,n){if(t.kind!=="detail"){let p=t.kind==="unreadable"?`The publication review could not be read (${t.why}); the API still checks it.`:t.why==="no_route"?"This API has no publication review.":`No active publication request was found for ${e}; the API decides.`;return{kind:"proceed",override:null,notes:n.force?[p,"--force was not sent: no review could be read to approve over."]:[p]}}let{detail:r}=t,o=e;if(r.started_publishing){if(!n.resume)return{kind:"refuse",why:"needs_resume",lines:[`This approval has already started publishing. Continue it with: nemar admin publish approve ${o} --resume`]};return{kind:"proceed",override:null,notes:["It passed the gates when it started; a resume that has started publishing is not gated again."]}}if(r.request_status==="blocked"){let p=r.block_reason===null?void 0:JI[r.block_reason],m=[mSe({code:"request_blocked",detail:r.block_reason},o,null,!1)];if(p)m.push(p);return{kind:"refuse",why:"blocked",lines:m}}if(r.gate!=="enforced")return{kind:"proceed",override:null,notes:n.force?[`--force changes nothing: the review gate is ${r.gate}.`]:[]};let s=n.resume||r.request_status==="approving",i=n.acknowledge!==void 0,a=fSe(r.reasons);if(a.length>0)return{kind:"refuse",why:"hard",lines:[Fj("hard_reason",o),...a.map(Hd)]};let c=Pj(r.reasons,[]),l=r.review?.override??null,d=l!==null&&Pj(r.reasons,l.reasons).length===0,f=r.reasons.find((p)=>p.code==="identifier_screen_needs_acknowledgment");if(f!==void 0&&!i&&r.screen_acknowledgment===null){let p=[Hd(f)];if(c.length>0&&!n.force&&!d)p.push(`The review is not a pass either, so that command also needs --force: ${hSe(o,{resume:s,acknowledge:!0,force:!0})}`);return{kind:"refuse",why:"needs_ack",lines:p}}if(c.length===0)return{kind:"proceed",override:null,notes:[]};if(n.force)return{kind:"proceed",override:{review_id:r.review?.id??null,reasons:c},notes:[`Approving over: ${c.join(", ")} (--force; recorded with your account).`]};if(l!==null&&d)return{kind:"proceed",override:null,notes:[`An override by administrator #${l.by} at ${l.at} covers these reasons. The API accepts it only for a run recorded as theirs.`]};return{kind:"refuse",why:"needs_force",lines:[Fj("needs_override",o),`To approve over them, run: ${hSe(o,{resume:s,acknowledge:i,force:!0})}`]}}He();He();Ep();var M1t={ok:u.green,note:u.cyan,warn:u.yellow,stop:u.red};function $c(e,t=2){if(!e||typeof e.headline!=="string")return[];let n=" ".repeat(t),r=M1t[e.tone]??u.white,o=[`${n}${r(e.headline)}`];for(let s of Array.isArray(e.lines)?e.lines:[])o.push(`${n} ${$ke(s)?u.yellow(s):u.dim(s)}`);return o}var j1t={ok:u.green,note:u.cyan,warn:u.yellow,stop:u.red};function g_(e){return j1t[e]??u.yellow}var gy="This is the non-production Worker. It holds its own record and answers only for the datasets it owns; it does not change what production reviews.",L1t="written by the model; the depositor's text can steer them",q1t="written by the model; the depositor's text can steer it";function ySe(e,t){let n=I(t);switch(e){case"dispatched":return`${n}: review started.`;case"redispatched":return`${n}: review started again.`;case"dispatch_claimed":return`${n}: a review of this commit was already handed over and stands.`;default:return`${n}: review started (${I(e)}).`}}function o1(e,t){if(!e||typeof e.headline!=="string")return[];return $c({...e,headline:I(e.headline),lines:Array.isArray(e.lines)?e.lines.map(I):[]},t)}function bSe(e,t=4){if(!e||e.outcome===null||e.outcome===void 0)return null;let n=(Array.isArray(e.reasons)?e.reasons:[]).map(I).join(", ");return`${" ".repeat(t)}${g_(e.tone)(I(e.headline))}${n===""?"":` ${u.dim(n)}`}`}var Mj=(e,t)=>`${e} ${t}${e===1?"":"s"}`,B1t={absent:"tag absent",at_head:"tag at the reviewed commit",elsewhere:"tag at another commit"};function U1t(e){let t=n1(e);if(t===null)return"version malformed (X.Y.Z expected)";let n=[];if(e.version_shape==="missing")n.push("dataset_description.json sets no Version");let r=B1t[e.tag];if(r)n.push(r);return`version ${I(t)}${n.length>0?` (${n.join("; ")})`:""}`}function H1t(e){let t=e.summary,n=[U1t(e),`BIDS ${I(e.bids)}`];n.push(e.minimums==="met"?"minimums met":`minimums failed (${e.minimum_failures.map(I).join(", ")})`),n.push(Mj(t.subjects,"subject"),Mj(t.sessions,"session"));let r=Object.entries(t.formats).map(([o,s])=>`${I(o)} ${s}`).join(", ");if(n.push(`${Mj(t.recordings,"recording")}${r===""?"":` (${r})`}`),n.push(`datatypes ${t.datatypes.length===0?"none":t.datatypes.map(I).join(", ")}`),t.sampling_rates_hz.length>0)n.push(`sampling rates ${t.sampling_rates_hz.join(", ")} Hz`);if(t.channel_counts.length>0)n.push(`channel counts ${t.channel_counts.join(", ")}`);return n.push(`sidecars read ${t.sidecars_read} of ${t.sidecars_total}`),`Evidence: ${n.join(", ")}`}function z1t(e){if(e==="sent_cut")return"sent (cut)";if(e.startsWith("withheld_"))return`withheld (${I(e.slice(9)).replaceAll("_"," ")})`;return I(e).replaceAll("_"," ")}function wSe(e){return`Shown to the model: ${t1.map((n)=>{let r=e.documents[n],o=`${r1[n]} ${z1t(r)}`;if(n==="dataset_description"&&(r==="sent"||r==="sent_cut"))o+=` (${e.description_keys_shown} keys shown, ${e.description_keys_not_shown} not)`;return o}).join(", ")}`}function _Se(e){let t=Object.entries(e.withheld_findings??{});if(t.length===0)return null;return`Withheld for findings: ${t.map(([n,r])=>`${I(n)} ${r}`).join(", ")}`}var jj=(e)=>typeof e==="object"&&e!==null&&!Array.isArray(e);function V1t(e){if(!jj(e))return!1;let t=e.documents;if(!jj(t))return!1;if(!t1.every((r)=>typeof t[r]==="string"))return!1;if(typeof e.description_keys_shown!=="number")return!1;if(typeof e.description_keys_not_shown!=="number")return!1;let n=e.withheld_findings;if(n===void 0||n===null)return!0;return jj(n)&&Object.values(n).every((r)=>typeof r==="number")}function xSe(e,t){let n=e?.evidence;if(!V1t(n))return[];let r=_Se(n);return[wSe(n),...r===null?[]:[r],`The whole review, with the model's questions and findings: nemar admin publish show ${I(t)}`]}var G1t={pass:u.green,fail:u.red,unknown:u.yellow};function W1t(e){if(e===null)return[];let t=[...m_.filter((r)=>(r in e)),...Object.keys(e).filter((r)=>!m_.includes(r))],n=Math.max(0,...t.map((r)=>r.length));return t.map((r)=>{let o=I(e[r]),s=Ij[r]??"";return` ${I(r).padEnd(n)} ${(G1t[o]??u.yellow)(o.padEnd(7))} ${s}`})}var K1t={blocker:u.red,concern:u.yellow,note:u.dim};function J1t(e){return e.map((t)=>{let n=Nj[t.code]??I(t.code),r=t.document===null?"":` (${r1[t.document]??I(t.document)})`,o=I(t.note),s=I(t.severity);return` ${(K1t[s]??u.yellow)(`[${s}]`)} ${n}${r}${o===""?"":`: ${o}`}`})}function Y1t(e){let t=e.review?.id??null,n=e.history.length===1&&e.history[0].id===t;if(e.history.length===0||n)return[];let r=[u.bold("History")];for(let o of e.history){let s=o.stored_verdict===null?"-":I(o.stored_verdict);r.push(` #${I(String(o.id)).padEnd(5)} ${I(o.head_sha).slice(0,12)} ${I(o.state).padEnd(10)} ${s.padEnd(15)} ${u.dim(I(o.created_at))}${o.id===t?u.dim(" in force"):""}`)}if(e.history_truncated)r.push(u.dim(" (older reviews not shown)"));return r}var X1t={enforced:"enforced",off:"off (advice only)","n/a":"n/a"};function s1(e){let t=[],n=e.anonymous?u.yellow("ANONYMOUS RELEASE"):"named publication",r=e.block_reason===null||e.block_reason===void 0?I(e.request_status):`${I(e.request_status)} (${I(e.block_reason)})`;if(t.push(`${u.bold(I(e.dataset_id))} request ${I(String(e.request_id))}, ${r}, ${n}`),e.environment!=="production")t.push(` ${u.yellow(gy)}`);if(t.push(""),t.push(...o1(e.identifier_screen,0)),e.screen_acknowledgment)t.push(` Acknowledged by administrator ${I(String(e.screen_acknowledgment.by))} at ${I(e.screen_acknowledgment.at)}.`);t.push("");let o=e.description;t.push(u.bold(g_(o.tone)(I(o.headline)))),t.push(` Gate: ${X1t[e.gate]??I(e.gate)}`);let s=o.lines.length>0?o.lines[o.lines.length-1]:null;for(let c of o.lines.slice(0,-1))t.push(` ${I(c)}`);let i=e.review;if(i!==null){let c=W1t(i.questions);if(c.length>0)t.push(" Questions:",...c);if(i.fact_notes.length>0){t.push(" Platform facts that lowered an answer:");for(let d of i.fact_notes)t.push(` ${I(d.question)}: ${I(d.text)}`)}if(i.findings.length>0)t.push(` Findings (${L1t}):`,...J1t(i.findings));let l=i.summary??o.summary;if(l!==null&&l!==void 0&&I(l)!=="")t.push(` Summary (${q1t}):`,` ${I(l)}`);if(i.evidence!==null){t.push(` ${H1t(i.evidence)}`,` ${wSe(i.evidence)}`);let d=_Se(i.evidence);if(d!==null)t.push(` ${d}`)}if(i.override!==null)t.push(` Override: by administrator ${I(String(i.override.by))} at ${I(i.override.at)} for ${i.override.reasons.map(I).join(", ")}`)}if(s!==null)t.push(` ${u.dim(I(s))}`);if(o.next!==null&&o.next!==void 0)t.push(` Next: ${I(o.next)}`);let a=Y1t(e);if(a.length>0)t.push("",...a);return t}var Q1t=new Set(["review_running","identifier_screen_pending"]);function yy(e){if(e.approval_in_flight===!0)return!1;if(e.status==="approving")return!0;if(e.status!=="requested")return!1;if(e.identifier_screen?.state==="pending")return!1;let t=e.publication_review?.reasons??[];return t.length===0||!t.every((n)=>Q1t.has(n))}function Lj(e){return[...e].sort((t,n)=>t.requested_at===n.requested_at?t.id-n.id:t.requested_at<n.requested_at?-1:1)}function vSe(e){return Lj(e.filter((t)=>t.status==="requested"&&t.publication_review?.start_offered===!0))}var Z1t=["requested","approving","blocked"],qj=["requested","approving","blocked","published","denied"];function Bj(e){if(e.all)return;let t=new Set(kSe(e));for(let r of qj)if(e[r])t.add(r);if(t.size===0)return[...Z1t];let n=qj.filter((r)=>t.has(r));return[...n,...[...t].filter((r)=>!n.includes(r))]}function kSe(e){return(e.status??"").split(",").map((t)=>t.trim()).filter(Boolean)}function Uj(e){return e.all===!0||qj.some((t)=>e[t])||kSe(e).length>0}function ESe(e){let t=Bj(e);if(!t)return"all requests";if(!Uj(e))return"active requests";return`requests with status ${t.join(" or ")}`}He();ro();dk();mk();Je();Ni();dn();var wi="NEMAR_APPROVAL_DISPATCH_TOKEN",eCt=`This run presents the dispatch token in ${wi} (an executor's run for a web approval); unset the variable to approve as yourself.`,tCt=`If you are not running a dispatched approval, unset ${wi} and run it again.`;function nCt(e){let t=e?.trim()??"";if(t==="")return{kind:"none"};if(/^[\x21-\x7e]+$/.test(t))return{kind:"token",value:t};return{kind:"malformed",problem:/\s/.test(t)?"it contains whitespace":"it contains a character outside printable ASCII"}}function rCt(e){return e instanceof L&&e.statusCode===409&&(e.code==="dispatch_superseded"||e.code==="dispatch_expired")}function $Se(e){e.command("approve").description("Approve and publish a dataset (runs orchestrator)").argument("<dataset-id>","Dataset ID").option("--resume","Resume from last failed step").option("--sandbox",`Use Zenodo sandbox for testing (refused while ${wi} is set)`).option("--skip-ci-check",`Skip the orchestrator's live BIDS validation check (recorded; clears no review reason; refused while ${wi} is set)`).option("--acknowledge-identifier-screen <reason>",`Approve over an identifier screen that needs review, recording why (${Yo} to ${Xo} characters; refused while ${wi} is set)`).option("--force",`Approve over a publication review that is not a pass, recorded with your account (refused while ${wi} is set)`).option("--request-id <n>","The request this approval is for (default: the one shown); refused if it is not the request in force").option(Ye,nt).option(yt,ht).addHelpText("after",`
|
|
665
665
|
Description:
|
|
666
666
|
Approve a publication request and run the automated orchestrator
|
|
667
667
|
to make the dataset publicly accessible with a permanent DOI.
|
|
@@ -828,7 +828,7 @@ ${d()}`));break}s.add(h.dataset_id);let g=await hy(h.dataset_id),y=CSe(h.dataset
|
|
|
828
828
|
${gy}`));console.log();for(let x of OSe({position:s.size,total:s.size-1+m.length,row:h,read:g,answer:y,force:n}))console.log(x);let _=await o.discardTyped();if(_>0)console.log(u.dim(` Ignored ${_} line(s) typed before this card was shown.`));for(;;){let x=await o.ask(`
|
|
829
829
|
${y.offered?"y approve, ":""}n deny, c comment, d details, s skip, q quit > `);if(x===null){console.log(u.dim(`
|
|
830
830
|
${d()}`));break e}let k=RSe(x);if(k===null){console.log(u.dim(" Type y, n, c, d, s or q."));continue}if(k==="quit")break e;if(k==="skip"){i.skipped++;break}let v;switch(k){case"details":xCt(b),v="again";break;case"approve":v=await vCt(a,b);break;case"deny":v=await kCt(a,b);break;case"comment":v=await ECt(a,b);break}if(v==="ended"){console.log(u.dim(`
|
|
831
|
-
${d()}`));break e}if(v==="done")break}if(r)break}f=!0}finally{o.close(),console.log(),console.log(Gj(i)),process.exitCode=f?Wj(i,o.interrupted):1}}function xCt(e){if(console.log(),e.read.kind==="detail"){let n;try{n=s1(e.read.detail)}catch{console.log(u.dim(" The review cannot be shown by this version of the CLI (the NEMAR API sent a shape it does not know). Update the CLI to read it."));return}for(let r of n)console.log(r);return}let t=e.read.kind==="unreadable"?`The review could not be read (${I(e.read.why)}), so there is nothing more to show.`:"The Worker has no review to show for this request.";console.log(u.dim(` ${t}`))}async function Kj(e,t,n){let r=await e.ask(t);if(r===null)return{kind:"ended"};let o=await e.discardTyped(C$);if(o>0)return console.log(u.yellow(`A ${n} is one line; ${o} more line(s) arrived with it. Nothing was sent.`)),{kind:"cancelled"};let s=r.trim();if(s==="")return console.log(u.dim(" Cancelled. Nothing was sent.")),{kind:"cancelled"};return{kind:"text",text:s}}async function vCt(e,t){let{answer:n,row:r,read:o}=t;if(!n.offered)return console.log(u.yellow(` Not approved: ${n.why}`)),"again";let s;if(n.askAcknowledgment)for(;;){let c=await Kj(e.reader,`Reason for approving over the identifier screen (${Yo} to ${Xo} characters; empty cancels): `,"reason");if(c.kind==="ended")return"ended";if(c.kind==="cancelled")return"again";if(c.text.length<Yo||c.text.length>Xo){console.log(u.yellow(`A reason is ${Yo} to ${Xo} characters; this one is ${c.text.length}.`));continue}s=c.text;break}if(n.overrideReasons.length>0){if(console.log(),console.log("Approving over:"),o.kind==="detail"){for(let l of o.detail.reasons)if(n.overrideReasons.includes(l.code))console.log(` ${I(Hd(l))}`)}await e.reader.discardTyped();let c=await e.reader.ask(`Approve over ${n.overrideReasons.join(", ")}? This records the override with your account. [y/N] `);if(c===null)return"ended";if(!["y","yes"].includes(c.trim().toLowerCase()))return console.log(u.dim(" Cancelled. Nothing was sent.")),"again"}let i=SCt(e,r.dataset_id),a;try{a=await Hj(r.dataset_id,{resume:Vj(r),sandbox:!1,skipCiCheck:!1,acknowledge:s,override:n.override,requestId:r.id})}finally{i()}if($Ct(e.reader),a.ok)e.tally.approved++;else e.tally.failed++;return"done"}async function kCt(e,t){let n=t.row.dataset_id,r=await Kj(e.reader,"Reason for the denial, mailed to the depositor (empty cancels): ","reason");if(r.kind==="ended")return"ended";if(r.kind==="cancelled")return"again";if(r.text.length>rh)return console.log(u.yellow(`A denial reason is at most ${rh} characters; this one is ${r.text.length}. Nothing was sent.`)),"again";try{await tg(n,r.text,t.row.id)}catch(o){return yr(o,null,`Could not deny ${I(n)}`),e.tally.failed++,"done"}return console.log(u.green(`Denied ${I(n)}; the depositor is mailed the reason.`)),e.tally.denied++,"done"}async function ECt(e,t){let n=t.row.dataset_id,r=await Kj(e.reader,"Message for the depositor (empty cancels): ","message");if(r.kind==="ended")return"ended";if(r.kind==="cancelled")return"again";if(r.text.length>AT)return console.log(u.yellow(`A message is at most ${AT} characters; this one is ${r.text.length}. Nothing was sent.`)),"again";try{await qfe(n,r.text)}catch(o){return yr(o,null,`Could not send the message for ${I(n)}`),e.tally.failed++,"done"}return console.log(u.green(`Mailed the message to the depositor of ${I(n)}; the request stays open.`)),e.tally.commented++,"done"}function SCt(e,t){let n=()=>{if(e.reader.interrupt(),process.stdin.isTTY)process.stdin.setRawMode(!1);let r=I(t);console.log(),console.log(u.yellow(`Interrupted while approving ${r}.`)),console.log(" The approval may still be running, or may have finished on the server. It is not counted below."),console.log(u.dim(` nemar admin publish show ${r} find out where it stands`)),console.log(u.dim(` nemar admin publish approve ${r} --resume continue it if it stopped`)),console.log(),console.log(Gj(e.tally)),process.exit(Wj(e.tally,!0))};return process.on("SIGINT",n),()=>{process.off("SIGINT",n)}}function $Ct(e){if(!process.stdin.isTTY||!e.open)return;process.stdin.setRawMode(!0),process.stdin.resume()}He();ro();
|
|
831
|
+
${d()}`));break e}if(v==="done")break}if(r)break}f=!0}finally{o.close(),console.log(),console.log(Gj(i)),process.exitCode=f?Wj(i,o.interrupted):1}}function xCt(e){if(console.log(),e.read.kind==="detail"){let n;try{n=s1(e.read.detail)}catch{console.log(u.dim(" The review cannot be shown by this version of the CLI (the NEMAR API sent a shape it does not know). Update the CLI to read it."));return}for(let r of n)console.log(r);return}let t=e.read.kind==="unreadable"?`The review could not be read (${I(e.read.why)}), so there is nothing more to show.`:"The Worker has no review to show for this request.";console.log(u.dim(` ${t}`))}async function Kj(e,t,n){let r=await e.ask(t);if(r===null)return{kind:"ended"};let o=await e.discardTyped(C$);if(o>0)return console.log(u.yellow(`A ${n} is one line; ${o} more line(s) arrived with it. Nothing was sent.`)),{kind:"cancelled"};let s=r.trim();if(s==="")return console.log(u.dim(" Cancelled. Nothing was sent.")),{kind:"cancelled"};return{kind:"text",text:s}}async function vCt(e,t){let{answer:n,row:r,read:o}=t;if(!n.offered)return console.log(u.yellow(` Not approved: ${n.why}`)),"again";let s;if(n.askAcknowledgment)for(;;){let c=await Kj(e.reader,`Reason for approving over the identifier screen (${Yo} to ${Xo} characters; empty cancels): `,"reason");if(c.kind==="ended")return"ended";if(c.kind==="cancelled")return"again";if(c.text.length<Yo||c.text.length>Xo){console.log(u.yellow(`A reason is ${Yo} to ${Xo} characters; this one is ${c.text.length}.`));continue}s=c.text;break}if(n.overrideReasons.length>0){if(console.log(),console.log("Approving over:"),o.kind==="detail"){for(let l of o.detail.reasons)if(n.overrideReasons.includes(l.code))console.log(` ${I(Hd(l))}`)}await e.reader.discardTyped();let c=await e.reader.ask(`Approve over ${n.overrideReasons.join(", ")}? This records the override with your account. [y/N] `);if(c===null)return"ended";if(!["y","yes"].includes(c.trim().toLowerCase()))return console.log(u.dim(" Cancelled. Nothing was sent.")),"again"}let i=SCt(e,r.dataset_id),a;try{a=await Hj(r.dataset_id,{resume:Vj(r),sandbox:!1,skipCiCheck:!1,acknowledge:s,override:n.override,requestId:r.id})}finally{i()}if($Ct(e.reader),a.ok)e.tally.approved++;else e.tally.failed++;return"done"}async function kCt(e,t){let n=t.row.dataset_id,r=await Kj(e.reader,"Reason for the denial, mailed to the depositor (empty cancels): ","reason");if(r.kind==="ended")return"ended";if(r.kind==="cancelled")return"again";if(r.text.length>rh)return console.log(u.yellow(`A denial reason is at most ${rh} characters; this one is ${r.text.length}. Nothing was sent.`)),"again";try{await tg(n,r.text,t.row.id)}catch(o){return yr(o,null,`Could not deny ${I(n)}`),e.tally.failed++,"done"}return console.log(u.green(`Denied ${I(n)}; the depositor is mailed the reason.`)),e.tally.denied++,"done"}async function ECt(e,t){let n=t.row.dataset_id,r=await Kj(e.reader,"Message for the depositor (empty cancels): ","message");if(r.kind==="ended")return"ended";if(r.kind==="cancelled")return"again";if(r.text.length>AT)return console.log(u.yellow(`A message is at most ${AT} characters; this one is ${r.text.length}. Nothing was sent.`)),"again";try{await qfe(n,r.text)}catch(o){return yr(o,null,`Could not send the message for ${I(n)}`),e.tally.failed++,"done"}return console.log(u.green(`Mailed the message to the depositor of ${I(n)}; the request stays open.`)),e.tally.commented++,"done"}function SCt(e,t){let n=()=>{if(e.reader.interrupt(),process.stdin.isTTY)process.stdin.setRawMode(!1);let r=I(t);console.log(),console.log(u.yellow(`Interrupted while approving ${r}.`)),console.log(" The approval may still be running, or may have finished on the server. It is not counted below."),console.log(u.dim(` nemar admin publish show ${r} find out where it stands`)),console.log(u.dim(` nemar admin publish approve ${r} --resume continue it if it stopped`)),console.log(),console.log(Gj(e.tally)),process.exit(Wj(e.tally,!0))};return process.on("SIGINT",n),()=>{process.off("SIGINT",n)}}function $Ct(e){if(!process.stdin.isTTY||!e.open)return;process.stdin.setRawMode(!0),process.stdin.resume()}He();ro();Je();Ni();dn();function FSe(e){e.command("show").description("Show the automated review of a publication request").argument("<dataset-id>","Dataset ID").option("--json","Output the detail as JSON instead of text").addHelpText("after",`
|
|
832
832
|
Description:
|
|
833
833
|
Read the review of the dataset's active publication request: its identifier
|
|
834
834
|
screen, then the review's outcome with every reason it is not a pass and what
|
|
@@ -842,7 +842,7 @@ Description:
|
|
|
842
842
|
|
|
843
843
|
Examples:
|
|
844
844
|
$ nemar admin publish show nm000480
|
|
845
|
-
$ nemar admin publish show nm000480 --json`).action(async(t,n)=>{let r=n.json===!0;if(!mn(r))return;let o=Xa(t,r);if(o===null)return;let s=r?null:D("Reading the review...").start();try{let i=await xS(o);if(s?.stop(),r){console.log(JSON.stringify(i,null,2));return}console.log();for(let a of s1(i))console.log(a);console.log()}catch(i){yr(i,s,"Could not read the review",void 0,{json:r})}}),e.command("start").description("Start the automated review of a publication request, or of every one waiting").argument("[dataset-id]","Dataset ID").option("--all","Every request whose review can be started, oldest first").option("--dry-run","With --all: list what would be started and start nothing").option(
|
|
845
|
+
$ nemar admin publish show nm000480 --json`).action(async(t,n)=>{let r=n.json===!0;if(!mn(r))return;let o=Xa(t,r);if(o===null)return;let s=r?null:D("Reading the review...").start();try{let i=await xS(o);if(s?.stop(),r){console.log(JSON.stringify(i,null,2));return}console.log();for(let a of s1(i))console.log(a);console.log()}catch(i){yr(i,s,"Could not read the review",void 0,{json:r})}}),e.command("start").description("Start the automated review of a publication request, or of every one waiting").argument("[dataset-id]","Dataset ID").option("--all","Every request whose review can be started, oldest first").option("--dry-run","With --all: list what would be started and start nothing").option(Ye,"With --all: do not ask before starting").option("--json","Output JSON instead of text").addHelpText("after",`
|
|
846
846
|
Description:
|
|
847
847
|
Start the review of the request's current screened commit, or start again one
|
|
848
848
|
that was declined, ended in an error, never reported or is past its deadline.
|
|
@@ -914,7 +914,7 @@ Examples:
|
|
|
914
914
|
`));return}if(console.log(`
|
|
915
915
|
${u.cyan("Publication Requests")} (${i.length}, ${a})
|
|
916
916
|
`),i.length===0)console.log(u.dim(` No publication request needs you now.
|
|
917
|
-
`));for(let f of i){let p=f.status==="published"?u.green:f.status==="denied"?u.red:f.status==="approving"?u.yellow:u.white,m=f.status==="denied"&&Boolean(f.withdrawn_at),h=I(f.dataset_name??""),g=yy(f)?` ${u.bold.cyan("*")}`:f.approval_in_flight===!0?` ${u.yellow("(approval running)")}`:"";if(console.log(` ${u.bold(I(f.dataset_id))} ${m?u.yellow("withdrawn"):p(I(f.status))} by ${I(f.requested_by_username)} ${u.dim(I(f.requested_at))}${h?` ${u.dim(h)}`:""}${g}`),f.anonymous===1)console.log(` ${u.yellow("! anonymous release:")} ${u.dim("repository stays private, DOI stays reserved, depositor is not named")}`);for(let b of o1(f.identifier_screen,4))console.log(b);let y=bSe(f.publication_review,4);if(y!==null)console.log(y);if(f.current_step&&f.status==="approving")console.log(` ${u.yellow(">")} ${I(f.current_step).replace(/_/g," ")}${f.last_error?u.red(` (${I(f.last_error)})`):""}`);if(f.prescreen_status==="concern"){let b=[];try{let x=JSON.parse(f.prescreen_reasons||"[]");if(Array.isArray(x))b=x.filter((k)=>typeof k==="string").map(I)}catch{}let _=b.length?b.join("; "):"see pre-screen";console.log(` ${u.yellow("! pre-screen advisory:")} ${u.dim(_)}`)}}let c=s.requests.length,l=i.length===c?`${c} request${c===1?"":"s"}`:`Showing ${i.length} of ${c} request${c===1?"":"s"}`,d=i.filter(yy).length;if(console.log(),console.log(`${l}, ${u.bold(String(d))} you can act on. ${u.dim("nemar admin publish next | show <dataset> | approve <dataset>")}`),s.requests.every((f)=>f.publication_review?.enabled===!1))console.log(u.dim(" The automated review is off on this Worker, so no review gates an approval."));console.log()}catch(s){yr(s,o,"Failed to list publication requests",void 0,{json:t})}});FSe(zd);async function PCt(){if(process.stdin.isTTY){let{inputReason:t}=await Ae.prompt([{type:"input",name:"inputReason",message:"Reason for denial:"}]);return typeof t==="string"&&t.trim()!==""?t:null}let e=new Wf;try{let t=await e.ask("");return t!==null&&t.trim()!==""?t.trim():null}finally{e.close()}}zd.command("deny").description("Deny a publication request").argument("<dataset-id>","Dataset ID").option("-r, --reason <reason>","Reason for denial").option("--request-id <n>","The request this denial is for (default: the one in force); refused if it is not the request in force").option(
|
|
917
|
+
`));for(let f of i){let p=f.status==="published"?u.green:f.status==="denied"?u.red:f.status==="approving"?u.yellow:u.white,m=f.status==="denied"&&Boolean(f.withdrawn_at),h=I(f.dataset_name??""),g=yy(f)?` ${u.bold.cyan("*")}`:f.approval_in_flight===!0?` ${u.yellow("(approval running)")}`:"";if(console.log(` ${u.bold(I(f.dataset_id))} ${m?u.yellow("withdrawn"):p(I(f.status))} by ${I(f.requested_by_username)} ${u.dim(I(f.requested_at))}${h?` ${u.dim(h)}`:""}${g}`),f.anonymous===1)console.log(` ${u.yellow("! anonymous release:")} ${u.dim("repository stays private, DOI stays reserved, depositor is not named")}`);for(let b of o1(f.identifier_screen,4))console.log(b);let y=bSe(f.publication_review,4);if(y!==null)console.log(y);if(f.current_step&&f.status==="approving")console.log(` ${u.yellow(">")} ${I(f.current_step).replace(/_/g," ")}${f.last_error?u.red(` (${I(f.last_error)})`):""}`);if(f.prescreen_status==="concern"){let b=[];try{let x=JSON.parse(f.prescreen_reasons||"[]");if(Array.isArray(x))b=x.filter((k)=>typeof k==="string").map(I)}catch{}let _=b.length?b.join("; "):"see pre-screen";console.log(` ${u.yellow("! pre-screen advisory:")} ${u.dim(_)}`)}}let c=s.requests.length,l=i.length===c?`${c} request${c===1?"":"s"}`:`Showing ${i.length} of ${c} request${c===1?"":"s"}`,d=i.filter(yy).length;if(console.log(),console.log(`${l}, ${u.bold(String(d))} you can act on. ${u.dim("nemar admin publish next | show <dataset> | approve <dataset>")}`),s.requests.every((f)=>f.publication_review?.enabled===!1))console.log(u.dim(" The automated review is off on this Worker, so no review gates an approval."));console.log()}catch(s){yr(s,o,"Failed to list publication requests",void 0,{json:t})}});FSe(zd);async function PCt(){if(process.stdin.isTTY){let{inputReason:t}=await Ae.prompt([{type:"input",name:"inputReason",message:"Reason for denial:"}]);return typeof t==="string"&&t.trim()!==""?t:null}let e=new Wf;try{let t=await e.ask("");return t!==null&&t.trim()!==""?t.trim():null}finally{e.close()}}zd.command("deny").description("Deny a publication request").argument("<dataset-id>","Dataset ID").option("-r, --reason <reason>","Reason for denial").option("--request-id <n>","The request this denial is for (default: the one in force); refused if it is not the request in force").option(Ye,nt).option(yt,ht).addHelpText("after",`
|
|
918
918
|
Description:
|
|
919
919
|
Deny a user's publication request with a specific reason.
|
|
920
920
|
The user will receive an email notification with your reason.
|
|
@@ -956,7 +956,7 @@ Description:
|
|
|
956
956
|
datasets, which are not screened.
|
|
957
957
|
|
|
958
958
|
Examples:
|
|
959
|
-
$ nemar admin publish screen nm099999`).action(async(e)=>{if(!mn())return;let t=Xa(e);if(t===null)return;let n=D(`Re-running the identifier screen for ${t}...`).start();try{let r=await _S(t);if(r.status==="pending")n.succeed(`Identifier screen dispatched for ${t}`),console.log(u.dim(" The admins are mailed when it reports."));else{n.warn(`The identifier screen for ${t} could not be started`);for(let o of o1(r.identifier_screen,2))console.log(o);console.log(u.dim(" Nothing is running. Run this command again once the cause is fixed; the Worker mails the admins when a screen cannot start.")),process.exitCode=1,ce()}}catch(r){yr(r,n,"Failed to re-run the identifier screen")}});$Se(zd);ISe(zd);He();lo();
|
|
959
|
+
$ nemar admin publish screen nm099999`).action(async(e)=>{if(!mn())return;let t=Xa(e);if(t===null)return;let n=D(`Re-running the identifier screen for ${t}...`).start();try{let r=await _S(t);if(r.status==="pending")n.succeed(`Identifier screen dispatched for ${t}`),console.log(u.dim(" The admins are mailed when it reports."));else{n.warn(`The identifier screen for ${t} could not be started`);for(let o of o1(r.identifier_screen,2))console.log(o);console.log(u.dim(" Nothing is running. Run this command again once the cause is fixed; the Worker mails the admins when a screen cannot start.")),process.exitCode=1,ce()}}catch(r){yr(r,n,"Failed to re-run the identifier screen")}});$Se(zd);ISe(zd);He();lo();Je();gr();dn();dn();var ICt=`
|
|
960
960
|
Ends the dataset's open re-pull, on this machine with your own GitHub token (GH_TOKEN, else
|
|
961
961
|
\`gh auth token\`). It reads every pull request of the re-pull's release branch first, and a merged
|
|
962
962
|
one refuses: a merge minted a DOI, and resume records it. A held claim to merge refuses too (resume
|
|
@@ -983,7 +983,7 @@ Exit codes:
|
|
|
983
983
|
0 the record is ended.
|
|
984
984
|
1 refused (nothing was closed, deleted or recorded), or nothing to end.
|
|
985
985
|
3 refused after something was closed or deleted (its why says which); resumable: run abandon
|
|
986
|
-
again.`;function NCt(e,t,n){let{row:r,report:o}=e;if(!r||!o)return;if(o.branch==="kept-foreign"||o.branch==="kept-unreadable")n(`The release branch was kept: it ${o.branch==="kept-foreign"?"holds a commit that is not this re-pull's or enrichment's":"could not be read"}; check what it holds before removing it by hand.`);if(e.outcome==="abandoned")n(o.orphans?`Orphans: ${o.orphans.objects} object(s), ${o.orphans.bytes} byte(s), stay in NEMAR's bucket (not locked, not deleted).`:`Orphans: not counted (${o.orphansUnknown}); what the copy wrote stays in NEMAR's bucket.`),n(`Re-pull #${r.id} of ${t} is abandoned. Plan the dataset again to re-pull ${r.to_tag}.`);else n(`Re-pull #${r.id} of ${t} is patch_declined: v${r.to_version} stays released, and N.0.1 is not made.`)}var LSe=new de("abandon").argument("<datasetId>").description("End an open re-pull: abandoned before its merge, patch_declined after its release").option("-y, --yes","Do not ask before closing and deleting").option("--json","Print the record as JSON").addHelpText("after",ICt).action(async(e,t)=>{let n=t.json===!0,r=Gn(n);if(!mn(n))return;if(!uy(e,n))return;let o;try{o=await oEe({datasetId:e,...t.yes?{}:{confirm:async(s)=>await De(s,{yes:!1})==="confirmed"},out:(s)=>r(s)})}catch(s){$j(s,n,r);return}if(n)console.log(JSON.stringify({repull:o.row,outcome:o.outcome,report:o.report??null},null,2));if(o.outcome==="nothing"){dt(o.row?`${e} has no open re-pull; the newest, #${o.row.id}, is ${o.row.status}.`:`${e} has no re-pull on record.`,{json:n,answered:!0}),process.exitCode=1,ce();return}NCt(o,e,r)});
|
|
986
|
+
again.`;function NCt(e,t,n){let{row:r,report:o}=e;if(!r||!o)return;if(o.branch==="kept-foreign"||o.branch==="kept-unreadable")n(`The release branch was kept: it ${o.branch==="kept-foreign"?"holds a commit that is not this re-pull's or enrichment's":"could not be read"}; check what it holds before removing it by hand.`);if(e.outcome==="abandoned")n(o.orphans?`Orphans: ${o.orphans.objects} object(s), ${o.orphans.bytes} byte(s), stay in NEMAR's bucket (not locked, not deleted).`:`Orphans: not counted (${o.orphansUnknown}); what the copy wrote stays in NEMAR's bucket.`),n(`Re-pull #${r.id} of ${t} is abandoned. Plan the dataset again to re-pull ${r.to_tag}.`);else n(`Re-pull #${r.id} of ${t} is patch_declined: v${r.to_version} stays released, and N.0.1 is not made.`)}var LSe=new de("abandon").argument("<datasetId>").description("End an open re-pull: abandoned before its merge, patch_declined after its release").option("-y, --yes","Do not ask before closing and deleting").option("--json","Print the record as JSON").addHelpText("after",ICt).action(async(e,t)=>{let n=t.json===!0,r=Gn(n);if(!mn(n))return;if(!uy(e,n))return;let o;try{o=await oEe({datasetId:e,...t.yes?{}:{confirm:async(s)=>await De(s,{yes:!1})==="confirmed"},out:(s)=>r(s)})}catch(s){$j(s,n,r);return}if(n)console.log(JSON.stringify({repull:o.row,outcome:o.outcome,report:o.report??null},null,2));if(o.outcome==="nothing"){dt(o.row?`${e} has no open re-pull; the newest, #${o.row.id}, is ${o.row.status}.`:`${e} has no re-pull on record.`,{json:n,answered:!0}),process.exitCode=1,ce();return}NCt(o,e,r)});Je();var FCt=20,USe=10;async function HSe(){let{switches:e,scheduler:t}=await T0e(),n=await P0e({limit:FCt}),r=[],o,s=!1;for(let i=1;;i++){let a=await Io({open:!0,origin:"automatic",limit:50,after:o});if(r.push(...a.repulls),a.next_after===null)break;if(i>=USe){s=!0;break}o=a.next_after}return{switches:e,scheduler:t,open:r,openTruncated:s,dispatches:n.dispatches,dispatchesFull:n.next_after!==null}}function zSe(e){return{switches:e.switches,scheduler:e.scheduler,open_automatic:e.open,open_automatic_truncated:e.openTruncated,dispatches:e.dispatches,dispatches_next_after:e.dispatchesFull?e.dispatches.at(-1)?.id??null:null}}var w_=(e)=>e===null?"never recorded":`${I(e)} UTC`,qSe=(e)=>e?"on":"off";function BSe(e){return e.source==="unreadable"?"unreadable, so it reads 0 (the binding is set to something the reader cannot take)":`${e.value} (${e.source==="set"?"set":"the default"})`}function MCt(e){if(e===null)return[" Unknown: the Worker found no scheduler row (migration 0112 inserts it), which is not the same as a scheduler that never ran."];let t=e.last_outcome===null?"":`, concluded ${I(e.last_outcome)}`;return[` Daily tick last ran: ${w_(e.last_tick_at)}${t}`,` Advance tick last ran: ${w_(e.last_advance_at)}`]}function jCt(e){let t=e.hold_reason===null?"":`, held for ${I(e.hold_reason)} since ${w_(e.hold_since)}`,n=e.merge_claimed_at!==null&&e.merge_sha===null?`, claim to merge held since ${w_(e.merge_claimed_at)}`:e.patch_merge_claimed_at!==null&&e.patch_merge_sha===null?`, N.0.1 claim to merge held since ${w_(e.patch_merge_claimed_at)}`:"",r=e.last_error===null?"":`; last error: ${Oo(e.last_error,100)}`;return` #${e.id} ${I(e.dataset_id)} v${I(e.to_version)} ${e.status}${t}${n}${r}`}function LCt(e){let t=e.code===null?"":` ${I(e.code)}`,n=e.repull_id===null?"":` (re-pull #${e.repull_id})`,r=e.workflow_run_url===null?"":` ${I(e.workflow_run_url)}`;return` #${e.id} ${e.kind} ${I(e.dataset_id)} ${e.status}${t}${n} ${I(e.dispatched_at)} UTC${r}`}function VSe(e){let t=e.switches,n=["Switches, as this Worker reads them",` Production Worker: ${t.environment_is_production?"yes":"no (a Worker that is not exactly production honors no switch)"}`,` AUTO_REPULL_ENABLED: ${qSe(t.auto_repull_enabled)}`,` AUTO_REPULL_MERGE_ENABLED: ${qSe(t.auto_repull_merge_enabled)}`,` REPULL_DAILY_OPEN_CAP: ${BSe(t.open_cap)}`,` REPULL_DAILY_MERGE_CAP: ${BSe(t.merge_cap)}`,"","Scheduler",...MCt(e.scheduler),""];if(e.open.length===0&&!e.openTruncated)n.push("Open automatic re-pulls: none");else{n.push(`Open automatic re-pulls: ${e.open.length}${e.openTruncated?" (read so far)":""}`);for(let r of e.open)n.push(jCt(r));if(e.openTruncated)n.push(` The list stopped after ${USe} pages; more are open than are shown.`)}if(n.push(""),e.dispatches.length===0)n.push("Recent dispatches: none");else{n.push(`Recent dispatches, newest first (${e.dispatches.length} shown${e.dispatchesFull?"; older ones exist":""})`);for(let r of e.dispatches)n.push(LCt(r))}return n.push("","The week's counts, and what asks for attention: nemar admin import-weekly"),n}var qCt=`
|
|
987
987
|
Shows the automatic re-pull as the Worker reads and records it. It changes nothing.
|
|
988
988
|
|
|
989
989
|
Switches AUTO_REPULL_ENABLED and AUTO_REPULL_MERGE_ENABLED (each on only as the exact string
|
|
@@ -1005,7 +1005,7 @@ repository never does. --json prints the same facts.
|
|
|
1005
1005
|
Exit codes:
|
|
1006
1006
|
0 read.
|
|
1007
1007
|
1 the Worker refused (you are not an administrator) or a read failed. Only the failure is
|
|
1008
|
-
printed then, never a table, because a partial table would claim what was not read.`,GSe=new de("auto").description("Show the automatic re-pull: its switches and caps, the scheduler, the open automatic re-pulls and the recent dispatches").option("--json","Print the same facts as JSON").addHelpText("after",qCt).action(async(e)=>{let t=e.json===!0;if(!mn(t))return;let n;try{n=await HSe()}catch(r){dt(`Could not read the automatic re-pull: ${G(r)}`,{json:t,answered:r instanceof L});return}if(t){console.log(JSON.stringify(zSe(n),null,2));return}for(let r of VSe(n))console.log(r)});
|
|
1008
|
+
printed then, never a table, because a partial table would claim what was not read.`,GSe=new de("auto").description("Show the automatic re-pull: its switches and caps, the scheduler, the open automatic re-pulls and the recent dispatches").option("--json","Print the same facts as JSON").addHelpText("after",qCt).action(async(e)=>{let t=e.json===!0;if(!mn(t))return;let n;try{n=await HSe()}catch(r){dt(`Could not read the automatic re-pull: ${G(r)}`,{json:t,answered:r instanceof L});return}if(t){console.log(JSON.stringify(zSe(n),null,2));return}for(let r of VSe(n))console.log(r)});Je();gr();dn();var BCt=`
|
|
1009
1009
|
Merges the dataset's re-pull pull request with your own GitHub login (GH_TOKEN, else \`gh auth
|
|
1010
1010
|
token\`; it must belong to a person, and when your NEMAR account names a GitHub login it must be
|
|
1011
1011
|
that one), once its record is gates_clear (\`nemar admin repull resume <id>\` gets it there).
|
|
@@ -1118,7 +1118,7 @@ Exit codes:
|
|
|
1118
1118
|
|
|
1119
1119
|
${u_} With it, execute settles the release head before it reports the
|
|
1120
1120
|
pull request open: it reads the branch until enrichment has not moved it for five minutes, at most
|
|
1121
|
-
--settle-minutes (default 30), recording each move enrichment made and refusing any other.`;function KCt(e){if(!ps.includes(e))throw new Ms(`one of ${ps.join(", ")} is required.`);return e}function JCt(e){let t=ps.indexOf(e.until),n=[];if(t>=ps.indexOf("prepared"))n.push("prepare it in a working clone and upload scrubbed recordings to NEMAR's bucket");if(t>=ps.indexOf("copied"))n.push(`copy up to ${e.copyItems} object(s) from upstream by version`);if(t>=ps.indexOf("registered"))n.push("register the keys on NEMAR's git-annex branch");if(t>=ps.indexOf("pr_open"))n.push(`push release/v${e.toVersion} and open its pull request`);if(n.length===0)return`record the re-pull and stop at ${e.until}`;return`${n.join(", ")}, and stop at ${e.until}`}function YCt(e){let t=e.status===null?`Execute the re-pull of ${e.datasetId}, upstream ${e.fromTag} to ${e.toTag}, as v${e.toVersion}`:`Continue the re-pull of ${e.datasetId} (${e.fromTag} to ${e.toTag}, v${e.toVersion}) from ${e.status}`;return`${e.supersedes?`First supersede re-pull #${e.supersedes.id} (to ${e.supersedes.toTag}, ${e.supersedes.status}): close its pull request${e.supersedes.prNumber?` #${e.supersedes.prNumber}`:""}, delete its release branch, and end it superseded; what its copy wrote stays in the bucket. Then: `:""}${t}: ${JCt(e)}. Execute never merges; a merge will mint ${e.doiCount} version DOI(s), which cannot be withdrawn. Proceed?`}Nl.command("execute <planFile>").description("Execute a reviewed re-pull plan through its pull request (never merges)").option("--until <status>",`Stop after this status (${ps.join(", ")})`,KCt,"pr_open").option("--keep-workdir","Keep the working directory after the pull request is open").option("--normalize-max-gb <n>","Bound on bytes this machine downloads and uploads for the scrub, in GB",Jj).option("--max-fetch-gb <n>","The planner's bound on large blobs fetched, in GB",Jj,5).option("--supersede","End the dataset's open re-pull of an older tag (yours, before its merge) as superseded first").option("-y, --yes","Do not ask before writing").option("--json","Print the record as JSON").option("--automatic-dispatch <id>","The central workflow's unattended run of a dispatch").option("--settle-minutes <n>","With --automatic-dispatch: how long to settle the release head at most (default 30)",Sj).addHelpText("after",WCt).action(async(e,t)=>{if(t.automaticDispatch!==void 0){await MEe(t.automaticDispatch,e,t);return}let n=t.json===!0,r=Gn(n);if(t.settleMinutes!==void 0){dt("--settle-minutes is for --automatic-dispatch only.",{json:n,answered:!0}),Ao();return}if(!mn(n))return;try{let{row:o,stoppedAt:s}=await BR({planPath:e,until:t.until,supersede:t.supersede===!0,keepWorkdir:t.keepWorkdir===!0,...t.normalizeMaxGb!==void 0?{normalizeMaxBytes:Math.floor(t.normalizeMaxGb*1073741824)}:{},maxFetchBytes:Math.floor(t.maxFetchGb*1073741824),...t.yes?{}:{confirm:async(i)=>await De(YCt(i),{yes:!1})==="confirmed"},out:(i)=>r(i)});if(n)console.log(JSON.stringify({repull:o,stopped_at:s},null,2));else console.log(`Re-pull #${o.id} of ${o.dataset_id} is ${o.status}${o.pr_number?`: pull request #${o.pr_number} of ${o.branch}`:""}.`)}catch(o){if(o instanceof N){dt(`Refused (${o.code}): ${o.message}`,{json:n,answered:!0});for(let s of o.lines)r(s);if(o.resumable)process.exitCode=GCt;return}dt(`Execution failed: ${G(o)}`,{json:n,answered:!1})}});Nl.addCommand(qEe);Nl.addCommand(BEe);Nl.addCommand(WSe);Nl.addCommand(LSe);Nl.addCommand(GSe);He();Qa();Ke();sp();dn();Pw();var XCt=5,QCt=10,KSe=2;function ZCt(e){return e.filter((t)=>pp.includes(t.state)).sort((t,n)=>t.dataset_id<n.dataset_id?-1:t.dataset_id>n.dataset_id?1:0)}function eAt(e,t,n,r={unknown:0,probably_stale:0,not_examined:0,unchecked:0,anomaly:0,in_progress:0,parked:0,unpublished:0}){let o=0,s=0,i=0,a=0,c=0,l=0,d=0,f=!1;for(let m of e){let h=m.delta;if(h===null){i++;continue}if(h.data_changing)s++;else o++;if(a+=h.added,c+=h.changed,l+=h.deleted,h.bytes_to_copy===null)f=!0;else d+=h.bytes_to_copy}let p=Math.max(0,t-e.length);return{stale:t,measured:e.length-i,not_measured:p,metadata_only:o,data_changing:s,delta_unknown:i,files_added:a,files_changed:c,files_deleted:l,bytes_to_copy:i>0||p>0||f?null:d,bytes_to_copy_known:d,not_comparable:r,catch_up_days:Math.ceil(n/KSe)}}async function JSe(e,t={}){let r=(t.now??Date.now)(),o=ZCt(e),s=t.limit===void 0?o:o.slice(0,t.limit),i=[],a=t.maxConsecutiveFailures??XCt,c=0,l=null;for(let[m,h]of s.entries()){if(l===null&&m>0&&m%QCt===0)t.onProgress?.(`measured ${m} of ${s.length} stale mirror(s)`);let g=h.recorded?.tag??null,y=h.upstream?.latest_tag??null,b={dataset_id:h.dataset_id,ds:h.ds,from_tag:g,to_tag:y};if(l!==null){i.push({...b,delta:null,reason:l});continue}if(m>0)await new Promise((x)=>setTimeout(x,t.pauseMs??500));if(h.ds===null||g===null||y===null){i.push({...b,delta:null,reason:"the row does not name both tags"});continue}let _=await K_e(h.ds,g,y,{graphqlUrl:t.graphqlUrl??Bg,timeoutMs:t.timeoutMs});if(_.ok)c=0,i.push({...b,delta:bxe(_.from,_.to),reason:null});else if(i.push({...b,delta:null,reason:_.error}),c=_.transport?c+1:0,c>=a)l=`not read: ${a} reads in a row failed to reach OpenNeuro, so the rest were skipped (last: ${_.error})`}let d=wxe(e,r),f=ID(e),p=eAt(i,o.length,d.catch_up,{unknown:f.states.unknown,probably_stale:f.probably_stale,not_examined:f.states.not_examined,unchecked:f.states.unchecked,anomaly:f.states.anomaly,in_progress:f.states.in_progress,parked:f.states.parked,unpublished:f.states.unpublished});return{measured_at:new Date(r).toISOString(),endpoint:t.graphqlUrl??Bg,scope:t.scope??"fleet",complete:p.bytes_to_copy!==null,deltas:i,totals:p,doi_volume:d}}function Yj(e){let t=["B","KiB","MiB","GiB","TiB"],n=e,r=0;while(r<t.length-1&&Math.round(n*10)/10>=1024)n/=1024,r++;return r===0?`${e} B`:`${n.toFixed(1)} ${t[r]}`}function tAt(e){if(e.bytes_to_copy!==null)return`Bytes to copy: ${e.bytes_to_copy} (${Yj(e.bytes_to_copy)})`;return`Bytes to copy: unknown; at least ${e.bytes_to_copy_known} (${Yj(e.bytes_to_copy_known)}) from the deltas with a known size`}var nAt={fleet:"the whole fleet",dataset:"one mirror (--dataset)",after:"the mirrors after a cursor (--after)"};function rAt(e){let t=e.totals.not_comparable,n=[`${t.unknown} unknown tag (${t.probably_stale} of them probably stale by date)`,`${t.not_examined} never examined`,`${t.unchecked} unchecked`,`${t.anomaly} anomaly`,`${t.in_progress} in progress`,`${t.parked} parked`,`${t.unpublished} unpublished`];return[` Scope: ${nAt[e.scope]}; only stale mirrors are measured.`,` Not covered by these totals (never measured, not zero): ${n.join(", ")}.`]}function oAt(e){let t=Object.entries(e.excluded).filter(([,n])=>n>0).map(([n,r])=>`${r} ${n}`);return t.length===0?null:` DOI estimate left out: ${t.join(", ")}.`}function YSe(e,t){let{totals:n,doi_volume:r}=e,o=[];o.push(`Measurement of ${n.stale} stale mirror(s), read from OpenNeuro at ${e.measured_at}:`),o.push(` Measured ${n.measured}: metadata-only ${n.metadata_only}, data-changing ${n.data_changing}; delta unknown ${n.delta_unknown}; not measured ${n.not_measured}.`);let s=e.complete?"":" (at least: not every delta was read)";o.push(` Files added ${n.files_added}, changed ${n.files_changed}, deleted ${n.files_deleted}${s}.`),o.push(` ${tAt(n)}.`),o.push(...rAt(e)),o.push(""),o.push(` DOI volume. Catch-up: ${r.catch_up} re-pull(s), up to ${r.upper_bound_with_patches.catch_up} DOIs with N.0.1 patches.`),o.push(` Trailing ${r.window_days} days of upstream churn over ${r.mirrors_counted} mirror(s): ${r.per_snapshot} under one re-pull per snapshot, ${r.at_most_every_30_days} under at most one per 30 days, busiest day ${r.busiest_day}; with patches at most ${r.upper_bound_with_patches.per_snapshot} and ${r.upper_bound_with_patches.at_most_every_30_days}.`);let i=oAt(r);if(i!==null)o.push(i);if(r.snapshots_dated_in_the_future>0)o.push(` ${r.snapshots_dated_in_the_future} snapshot(s) are dated in the future and are left out of those figures.`);if(r.snapshots_with_unreadable_dates>0)o.push(` ${r.snapshots_with_unreadable_dates} snapshot(s) had an unreadable creation date and are left out of those figures.`);if(o.push(` At REPULL_DAILY_OPEN_CAP=${KSe} the catch-up takes ${n.catch_up_days} day(s).`),e.deltas.length>0){o.push("");for(let a of e.deltas.slice(0,t)){let c=` ${a.dataset_id} ${a.ds??"-"} ${a.from_tag??"?"} -> ${a.to_tag??"?"}`;if(a.delta===null){o.push(`${c} delta unknown: ${a.reason??"no reason given"}`);continue}let l=a.delta,d=l.data_changing?"data-changing":"metadata-only",f=l.bytes_to_copy===null?"size unknown":Yj(l.bytes_to_copy);o.push(`${c} ${d} +${l.added} ~${l.changed} -${l.deleted} files, ${l.new_keys} new key(s), ${f}`)}if(e.deltas.length>t)o.push(` ... and ${e.deltas.length-t} more`)}return o.push(""),o.push(" Limit: the delta is upstream's between the two tags, not NEMAR's tree; NEMAR's own corrections, scrubs and annex policy are not in it."),o.push(" Limit: a tag recorded with basis doi is a declaration, not a tree comparison (ADR 0111, What `doi` means)."),o.push(" Not measured here: conflict and unexplained-path counts come from Phase 5's plan, `nemar admin repull plan`."),o}function XSe(e){let{pages:t}=e,n=new Map,r=[],o=[];for(let p of t){for(let m of p.rows)n.set(m.dataset_id,m);if(r.push(...p.errors),!p.ok){let m=p.error??"OpenNeuro could not be read";r.push(m),o.push(`a page was refused (HTTP 502): ${m}`)}}let s=[...n.values()],i=ID(s),a=t[0],c=t[t.length-1],l={start:a?.population_total??0,end:c?.population_total??0,withdrawn:c?.withdrawn??0,excluded_unmanaged:c?.excluded_unmanaged??0};if(i.states.unchecked>0)o.push(`${i.states.unchecked} mirror(s) could not be compared with OpenNeuro`);let d=t.reduce((p,m)=>p+m.errors.length,0);if(d>0)o.push(`OpenNeuro reported ${d} problem(s) (see errors)`);if(e.maxPagesReached)o.push("stopped at --max-pages before the end of the fleet");let f=c!==void 0&&c.next_cursor!==null;if(f&&!e.maxPagesReached&&!e.stoppedAtRefusal)o.push("the walk ended before the last page");if(e.scope==="fleet"){if(l.start!==l.end)o.push(`the population changed during the pass (${l.start} at the start, ${l.end} at the end); rerun`);else if(s.length!==l.end)o.push(`${s.length} mirror(s) were examined but the population is ${l.end}; the fleet changed during the pass, rerun`)}if(e.scope==="dataset"&&s.length!==1)o.push("the dataset did not answer with exactly one row");if(t.length===0)o.push("no page was read");return{examined:s.length,population:l,counts:i,rows:s,errors:r,complete:o.length===0&&!f,could_not_see:o}}function QSe(e){return e.could_not_see.length>0?2:0}var sAt={current:"at upstream's latest snapshot",stale_ready:"upstream is newer and the tag is on the GitHub mirror",mirror_lag:"upstream is newer; the tag is not on the GitHub mirror yet",stale_unverified:"upstream is newer; the GitHub mirror could not be checked",anomaly:"upstream and NEMAR disagree in a way that needs a look (kinds below)",unknown:"upstream tag unknown; NOT compared, so not verified clean",not_examined:"never examined for its tag; run nemar admin upstream-backfill",unpublished:"no NEMAR version yet",in_progress:"an import is running",parked:"parked (blocklisted, quarantined or rolled back)",unchecked:"could not be compared: OpenNeuro did not answer"},iAt=[...pp,"anomaly","unchecked"];function aAt(e){let t=e.recorded?.tag??"?",n=e.upstream?.latest_tag??"?";return`${e.dataset_id} ${e.ds??"-"} ${t} -> ${n} ${e.reason}`}function ZSe(e,t){let n=[],{population:r,counts:o}=e;n.push(`Examined ${e.examined} of ${r.end} managed OpenNeuro mirrors (${r.withdrawn} withdrawn and ${r.excluded_unmanaged} unmanaged on###### rows not compared).`),n.push("");let s=Math.max(...Lw.map((a)=>a.length));for(let a of Lw)n.push(` ${a.padEnd(s)} ${String(o.states[a]).padStart(5)} ${sAt[a]}`);let i=Object.entries(o.anomalies).filter(([,a])=>a>0);if(i.length>0)n.push(""),n.push(`Anomalies: ${i.map(([a,c])=>`${a}=${c}`).join(", ")}`);if(n.push(""),n.push(`Stale in total: ${o.stale}`),n.push(`Unknown tag and probably stale by date: ${o.probably_stale} (display only, not stale)`),o.states.unknown>0)n.push(`${o.states.unknown} mirror(s) have an unknown tag: they were not compared, whatever the lines above say about OpenNeuro.`);for(let a of iAt){let c=e.rows.filter((l)=>l.state===a);if(c.length===0)continue;n.push(""),n.push(`${a} (${c.length}):`);for(let l of c.slice(0,t))n.push(` ${aAt(l)}`);if(c.length>t)n.push(` ... and ${c.length-t} more`)}if(e.errors.length>0){n.push(""),n.push("Problems reported by the API:");for(let a of e.errors)n.push(` ${a}`)}return n}var cAt=250,e$e=/^on\d{6}$/;function a1(e,t){if(e===void 0)return t;return/^[0-9]+$/.test(e)&&Number.parseInt(e,10)>=1?Number.parseInt(e,10):null}var t$e=new de("upstream-status").description("Report which OpenNeuro mirrors are behind upstream (read-only)").option("--limit <n>","Mirrors per page (values above 100 are capped to 100)","100").option("--after <id>","Resume after this dataset id, e.g. on000123").option("--dataset <id>","Examine only this mirror, e.g. on003645").option("--max-pages <n>","Stop after this many pages","50").option("--list <n>","Rows printed per state, and per-mirror measurement lines with --measure","50").option("--measure","Also read OpenNeuro's file listings from this machine and total what a re-pull of each stale mirror would carry (only after a complete pass; a delta that cannot be read leaves the byte total unknown and exits 2)").option("--measure-limit <n>","With --measure, measure at most this many stale mirrors (the rest are not measured, so the byte total is unknown, shown as at least)").option("--json","Output one JSON document instead of the report").addHelpText("after",`
|
|
1121
|
+
--settle-minutes (default 30), recording each move enrichment made and refusing any other.`;function KCt(e){if(!ps.includes(e))throw new Ms(`one of ${ps.join(", ")} is required.`);return e}function JCt(e){let t=ps.indexOf(e.until),n=[];if(t>=ps.indexOf("prepared"))n.push("prepare it in a working clone and upload scrubbed recordings to NEMAR's bucket");if(t>=ps.indexOf("copied"))n.push(`copy up to ${e.copyItems} object(s) from upstream by version`);if(t>=ps.indexOf("registered"))n.push("register the keys on NEMAR's git-annex branch");if(t>=ps.indexOf("pr_open"))n.push(`push release/v${e.toVersion} and open its pull request`);if(n.length===0)return`record the re-pull and stop at ${e.until}`;return`${n.join(", ")}, and stop at ${e.until}`}function YCt(e){let t=e.status===null?`Execute the re-pull of ${e.datasetId}, upstream ${e.fromTag} to ${e.toTag}, as v${e.toVersion}`:`Continue the re-pull of ${e.datasetId} (${e.fromTag} to ${e.toTag}, v${e.toVersion}) from ${e.status}`;return`${e.supersedes?`First supersede re-pull #${e.supersedes.id} (to ${e.supersedes.toTag}, ${e.supersedes.status}): close its pull request${e.supersedes.prNumber?` #${e.supersedes.prNumber}`:""}, delete its release branch, and end it superseded; what its copy wrote stays in the bucket. Then: `:""}${t}: ${JCt(e)}. Execute never merges; a merge will mint ${e.doiCount} version DOI(s), which cannot be withdrawn. Proceed?`}Nl.command("execute <planFile>").description("Execute a reviewed re-pull plan through its pull request (never merges)").option("--until <status>",`Stop after this status (${ps.join(", ")})`,KCt,"pr_open").option("--keep-workdir","Keep the working directory after the pull request is open").option("--normalize-max-gb <n>","Bound on bytes this machine downloads and uploads for the scrub, in GB",Jj).option("--max-fetch-gb <n>","The planner's bound on large blobs fetched, in GB",Jj,5).option("--supersede","End the dataset's open re-pull of an older tag (yours, before its merge) as superseded first").option("-y, --yes","Do not ask before writing").option("--json","Print the record as JSON").option("--automatic-dispatch <id>","The central workflow's unattended run of a dispatch").option("--settle-minutes <n>","With --automatic-dispatch: how long to settle the release head at most (default 30)",Sj).addHelpText("after",WCt).action(async(e,t)=>{if(t.automaticDispatch!==void 0){await MEe(t.automaticDispatch,e,t);return}let n=t.json===!0,r=Gn(n);if(t.settleMinutes!==void 0){dt("--settle-minutes is for --automatic-dispatch only.",{json:n,answered:!0}),Ao();return}if(!mn(n))return;try{let{row:o,stoppedAt:s}=await BR({planPath:e,until:t.until,supersede:t.supersede===!0,keepWorkdir:t.keepWorkdir===!0,...t.normalizeMaxGb!==void 0?{normalizeMaxBytes:Math.floor(t.normalizeMaxGb*1073741824)}:{},maxFetchBytes:Math.floor(t.maxFetchGb*1073741824),...t.yes?{}:{confirm:async(i)=>await De(YCt(i),{yes:!1})==="confirmed"},out:(i)=>r(i)});if(n)console.log(JSON.stringify({repull:o,stopped_at:s},null,2));else console.log(`Re-pull #${o.id} of ${o.dataset_id} is ${o.status}${o.pr_number?`: pull request #${o.pr_number} of ${o.branch}`:""}.`)}catch(o){if(o instanceof N){dt(`Refused (${o.code}): ${o.message}`,{json:n,answered:!0});for(let s of o.lines)r(s);if(o.resumable)process.exitCode=GCt;return}dt(`Execution failed: ${G(o)}`,{json:n,answered:!1})}});Nl.addCommand(qEe);Nl.addCommand(BEe);Nl.addCommand(WSe);Nl.addCommand(LSe);Nl.addCommand(GSe);He();Qa();Je();sp();dn();Pw();var XCt=5,QCt=10,KSe=2;function ZCt(e){return e.filter((t)=>pp.includes(t.state)).sort((t,n)=>t.dataset_id<n.dataset_id?-1:t.dataset_id>n.dataset_id?1:0)}function eAt(e,t,n,r={unknown:0,probably_stale:0,not_examined:0,unchecked:0,anomaly:0,in_progress:0,parked:0,unpublished:0}){let o=0,s=0,i=0,a=0,c=0,l=0,d=0,f=!1;for(let m of e){let h=m.delta;if(h===null){i++;continue}if(h.data_changing)s++;else o++;if(a+=h.added,c+=h.changed,l+=h.deleted,h.bytes_to_copy===null)f=!0;else d+=h.bytes_to_copy}let p=Math.max(0,t-e.length);return{stale:t,measured:e.length-i,not_measured:p,metadata_only:o,data_changing:s,delta_unknown:i,files_added:a,files_changed:c,files_deleted:l,bytes_to_copy:i>0||p>0||f?null:d,bytes_to_copy_known:d,not_comparable:r,catch_up_days:Math.ceil(n/KSe)}}async function JSe(e,t={}){let r=(t.now??Date.now)(),o=ZCt(e),s=t.limit===void 0?o:o.slice(0,t.limit),i=[],a=t.maxConsecutiveFailures??XCt,c=0,l=null;for(let[m,h]of s.entries()){if(l===null&&m>0&&m%QCt===0)t.onProgress?.(`measured ${m} of ${s.length} stale mirror(s)`);let g=h.recorded?.tag??null,y=h.upstream?.latest_tag??null,b={dataset_id:h.dataset_id,ds:h.ds,from_tag:g,to_tag:y};if(l!==null){i.push({...b,delta:null,reason:l});continue}if(m>0)await new Promise((x)=>setTimeout(x,t.pauseMs??500));if(h.ds===null||g===null||y===null){i.push({...b,delta:null,reason:"the row does not name both tags"});continue}let _=await K_e(h.ds,g,y,{graphqlUrl:t.graphqlUrl??Bg,timeoutMs:t.timeoutMs});if(_.ok)c=0,i.push({...b,delta:bxe(_.from,_.to),reason:null});else if(i.push({...b,delta:null,reason:_.error}),c=_.transport?c+1:0,c>=a)l=`not read: ${a} reads in a row failed to reach OpenNeuro, so the rest were skipped (last: ${_.error})`}let d=wxe(e,r),f=ID(e),p=eAt(i,o.length,d.catch_up,{unknown:f.states.unknown,probably_stale:f.probably_stale,not_examined:f.states.not_examined,unchecked:f.states.unchecked,anomaly:f.states.anomaly,in_progress:f.states.in_progress,parked:f.states.parked,unpublished:f.states.unpublished});return{measured_at:new Date(r).toISOString(),endpoint:t.graphqlUrl??Bg,scope:t.scope??"fleet",complete:p.bytes_to_copy!==null,deltas:i,totals:p,doi_volume:d}}function Yj(e){let t=["B","KiB","MiB","GiB","TiB"],n=e,r=0;while(r<t.length-1&&Math.round(n*10)/10>=1024)n/=1024,r++;return r===0?`${e} B`:`${n.toFixed(1)} ${t[r]}`}function tAt(e){if(e.bytes_to_copy!==null)return`Bytes to copy: ${e.bytes_to_copy} (${Yj(e.bytes_to_copy)})`;return`Bytes to copy: unknown; at least ${e.bytes_to_copy_known} (${Yj(e.bytes_to_copy_known)}) from the deltas with a known size`}var nAt={fleet:"the whole fleet",dataset:"one mirror (--dataset)",after:"the mirrors after a cursor (--after)"};function rAt(e){let t=e.totals.not_comparable,n=[`${t.unknown} unknown tag (${t.probably_stale} of them probably stale by date)`,`${t.not_examined} never examined`,`${t.unchecked} unchecked`,`${t.anomaly} anomaly`,`${t.in_progress} in progress`,`${t.parked} parked`,`${t.unpublished} unpublished`];return[` Scope: ${nAt[e.scope]}; only stale mirrors are measured.`,` Not covered by these totals (never measured, not zero): ${n.join(", ")}.`]}function oAt(e){let t=Object.entries(e.excluded).filter(([,n])=>n>0).map(([n,r])=>`${r} ${n}`);return t.length===0?null:` DOI estimate left out: ${t.join(", ")}.`}function YSe(e,t){let{totals:n,doi_volume:r}=e,o=[];o.push(`Measurement of ${n.stale} stale mirror(s), read from OpenNeuro at ${e.measured_at}:`),o.push(` Measured ${n.measured}: metadata-only ${n.metadata_only}, data-changing ${n.data_changing}; delta unknown ${n.delta_unknown}; not measured ${n.not_measured}.`);let s=e.complete?"":" (at least: not every delta was read)";o.push(` Files added ${n.files_added}, changed ${n.files_changed}, deleted ${n.files_deleted}${s}.`),o.push(` ${tAt(n)}.`),o.push(...rAt(e)),o.push(""),o.push(` DOI volume. Catch-up: ${r.catch_up} re-pull(s), up to ${r.upper_bound_with_patches.catch_up} DOIs with N.0.1 patches.`),o.push(` Trailing ${r.window_days} days of upstream churn over ${r.mirrors_counted} mirror(s): ${r.per_snapshot} under one re-pull per snapshot, ${r.at_most_every_30_days} under at most one per 30 days, busiest day ${r.busiest_day}; with patches at most ${r.upper_bound_with_patches.per_snapshot} and ${r.upper_bound_with_patches.at_most_every_30_days}.`);let i=oAt(r);if(i!==null)o.push(i);if(r.snapshots_dated_in_the_future>0)o.push(` ${r.snapshots_dated_in_the_future} snapshot(s) are dated in the future and are left out of those figures.`);if(r.snapshots_with_unreadable_dates>0)o.push(` ${r.snapshots_with_unreadable_dates} snapshot(s) had an unreadable creation date and are left out of those figures.`);if(o.push(` At REPULL_DAILY_OPEN_CAP=${KSe} the catch-up takes ${n.catch_up_days} day(s).`),e.deltas.length>0){o.push("");for(let a of e.deltas.slice(0,t)){let c=` ${a.dataset_id} ${a.ds??"-"} ${a.from_tag??"?"} -> ${a.to_tag??"?"}`;if(a.delta===null){o.push(`${c} delta unknown: ${a.reason??"no reason given"}`);continue}let l=a.delta,d=l.data_changing?"data-changing":"metadata-only",f=l.bytes_to_copy===null?"size unknown":Yj(l.bytes_to_copy);o.push(`${c} ${d} +${l.added} ~${l.changed} -${l.deleted} files, ${l.new_keys} new key(s), ${f}`)}if(e.deltas.length>t)o.push(` ... and ${e.deltas.length-t} more`)}return o.push(""),o.push(" Limit: the delta is upstream's between the two tags, not NEMAR's tree; NEMAR's own corrections, scrubs and annex policy are not in it."),o.push(" Limit: a tag recorded with basis doi is a declaration, not a tree comparison (ADR 0111, What `doi` means)."),o.push(" Not measured here: conflict and unexplained-path counts come from Phase 5's plan, `nemar admin repull plan`."),o}function XSe(e){let{pages:t}=e,n=new Map,r=[],o=[];for(let p of t){for(let m of p.rows)n.set(m.dataset_id,m);if(r.push(...p.errors),!p.ok){let m=p.error??"OpenNeuro could not be read";r.push(m),o.push(`a page was refused (HTTP 502): ${m}`)}}let s=[...n.values()],i=ID(s),a=t[0],c=t[t.length-1],l={start:a?.population_total??0,end:c?.population_total??0,withdrawn:c?.withdrawn??0,excluded_unmanaged:c?.excluded_unmanaged??0};if(i.states.unchecked>0)o.push(`${i.states.unchecked} mirror(s) could not be compared with OpenNeuro`);let d=t.reduce((p,m)=>p+m.errors.length,0);if(d>0)o.push(`OpenNeuro reported ${d} problem(s) (see errors)`);if(e.maxPagesReached)o.push("stopped at --max-pages before the end of the fleet");let f=c!==void 0&&c.next_cursor!==null;if(f&&!e.maxPagesReached&&!e.stoppedAtRefusal)o.push("the walk ended before the last page");if(e.scope==="fleet"){if(l.start!==l.end)o.push(`the population changed during the pass (${l.start} at the start, ${l.end} at the end); rerun`);else if(s.length!==l.end)o.push(`${s.length} mirror(s) were examined but the population is ${l.end}; the fleet changed during the pass, rerun`)}if(e.scope==="dataset"&&s.length!==1)o.push("the dataset did not answer with exactly one row");if(t.length===0)o.push("no page was read");return{examined:s.length,population:l,counts:i,rows:s,errors:r,complete:o.length===0&&!f,could_not_see:o}}function QSe(e){return e.could_not_see.length>0?2:0}var sAt={current:"at upstream's latest snapshot",stale_ready:"upstream is newer and the tag is on the GitHub mirror",mirror_lag:"upstream is newer; the tag is not on the GitHub mirror yet",stale_unverified:"upstream is newer; the GitHub mirror could not be checked",anomaly:"upstream and NEMAR disagree in a way that needs a look (kinds below)",unknown:"upstream tag unknown; NOT compared, so not verified clean",not_examined:"never examined for its tag; run nemar admin upstream-backfill",unpublished:"no NEMAR version yet",in_progress:"an import is running",parked:"parked (blocklisted, quarantined or rolled back)",unchecked:"could not be compared: OpenNeuro did not answer"},iAt=[...pp,"anomaly","unchecked"];function aAt(e){let t=e.recorded?.tag??"?",n=e.upstream?.latest_tag??"?";return`${e.dataset_id} ${e.ds??"-"} ${t} -> ${n} ${e.reason}`}function ZSe(e,t){let n=[],{population:r,counts:o}=e;n.push(`Examined ${e.examined} of ${r.end} managed OpenNeuro mirrors (${r.withdrawn} withdrawn and ${r.excluded_unmanaged} unmanaged on###### rows not compared).`),n.push("");let s=Math.max(...Lw.map((a)=>a.length));for(let a of Lw)n.push(` ${a.padEnd(s)} ${String(o.states[a]).padStart(5)} ${sAt[a]}`);let i=Object.entries(o.anomalies).filter(([,a])=>a>0);if(i.length>0)n.push(""),n.push(`Anomalies: ${i.map(([a,c])=>`${a}=${c}`).join(", ")}`);if(n.push(""),n.push(`Stale in total: ${o.stale}`),n.push(`Unknown tag and probably stale by date: ${o.probably_stale} (display only, not stale)`),o.states.unknown>0)n.push(`${o.states.unknown} mirror(s) have an unknown tag: they were not compared, whatever the lines above say about OpenNeuro.`);for(let a of iAt){let c=e.rows.filter((l)=>l.state===a);if(c.length===0)continue;n.push(""),n.push(`${a} (${c.length}):`);for(let l of c.slice(0,t))n.push(` ${aAt(l)}`);if(c.length>t)n.push(` ... and ${c.length-t} more`)}if(e.errors.length>0){n.push(""),n.push("Problems reported by the API:");for(let a of e.errors)n.push(` ${a}`)}return n}var cAt=250,e$e=/^on\d{6}$/;function a1(e,t){if(e===void 0)return t;return/^[0-9]+$/.test(e)&&Number.parseInt(e,10)>=1?Number.parseInt(e,10):null}var t$e=new de("upstream-status").description("Report which OpenNeuro mirrors are behind upstream (read-only)").option("--limit <n>","Mirrors per page (values above 100 are capped to 100)","100").option("--after <id>","Resume after this dataset id, e.g. on000123").option("--dataset <id>","Examine only this mirror, e.g. on003645").option("--max-pages <n>","Stop after this many pages","50").option("--list <n>","Rows printed per state, and per-mirror measurement lines with --measure","50").option("--measure","Also read OpenNeuro's file listings from this machine and total what a re-pull of each stale mirror would carry (only after a complete pass; a delta that cannot be read leaves the byte total unknown and exits 2)").option("--measure-limit <n>","With --measure, measure at most this many stale mirrors (the rest are not measured, so the byte total is unknown, shown as at least)").option("--json","Output one JSON document instead of the report").addHelpText("after",`
|
|
1122
1122
|
Environment:
|
|
1123
1123
|
NEMAR_OPENNEURO_GRAPHQL_URL Read --measure file listings from this OpenNeuro GraphQL endpoint (for tests; default https://openneuro.org/crn/graphql)`).action(async(e)=>{Ir();let t=(y)=>{console.error(u.red(y)),process.exit(1)},n=a1(e.limit,100),r=a1(e.maxPages,50),o=a1(e.list,50);if(n===null)t("--limit must be a positive integer");if(r===null)t("--max-pages must be a positive integer");if(o===null)t("--list must be a positive integer");let s=e.measureLimit===void 0?void 0:a1(e.measureLimit,1);if(s===null)t("--measure-limit must be a positive integer");if(e.measureLimit!==void 0&&!e.measure)t("--measure-limit needs --measure");if(e.dataset!==void 0&&!e$e.test(e.dataset))t("--dataset must look like on003645");if(e.after!==void 0&&!e$e.test(e.after))t("--after must look like on000123");if(e.dataset!==void 0&&e.after!==void 0)t("--dataset and --after cannot be combined");let i=e.dataset?"dataset":e.after?"after":"fleet",a=[],c=e.after,l=null,d=!1,f=!1;for(let y=0;y<r;y++){let b;try{b=await Jpe({limit:n,after:c,dataset:e.dataset})}catch(_){l=G(_);break}if(a.push(b),!b.ok){f=!0;break}if(!b.next_cursor)break;if(c=b.next_cursor,y===r-1)d=!0;else await new Promise((_)=>setTimeout(_,cAt))}let p=XSe({pages:a,scope:i,maxPagesReached:d,stoppedAtRefusal:f}),m=null,h=null;if(e.measure&&l===null&&!p.complete)h="the pass did not finish cleanly, so the stale set may be partial";else if(e.measure&&l!==null)h="the pass failed before it finished";if(e.measure&&h===null){if(m=await JSe(p.rows,{limit:s??void 0,graphqlUrl:process.env.NEMAR_OPENNEURO_GRAPHQL_URL,scope:i,onProgress:(y)=>console.error(y)}),m.totals.delta_unknown>0)p.could_not_see.push(`${m.totals.delta_unknown} stale mirror(s) had a delta that could not be read from OpenNeuro`),p.complete=!1}if(e.json)console.log(JSON.stringify({examined:p.examined,population:p.population,counts:p.counts,rows:p.rows,errors:p.errors,complete:p.complete,could_not_see:p.could_not_see,...e.measure?{measurement:m,measurement_skipped:h}:{},failure:l},null,2));else{if(a.length>0)for(let y of ZSe(p,o))console.log(y);if(l)console.error(u.red(`Stopped: ${l}`));if(h!==null)console.log(""),console.log(u.yellow(`Not measured: ${h}.`));if(m!==null){console.log("");for(let y of YSe(m,o))console.log(y)}if(p.could_not_see.length>0){console.log(""),console.log(u.yellow("The pass could not see everything:"));for(let y of p.could_not_see)console.log(u.yellow(` ${y}`))}}if(l!==null)process.exit(1);if(QSe(p)===2)ce(),process.exit(2)});async function x$e(e,t){let{spawn:n}=await Promise.resolve(globalThis.Bun),r=t==="README"?`repos/${e}/readme`:`repos/${e}/contents/${t}`,o=n({cmd:["gh","api",r,"--jq",".content"],stdout:"pipe",stderr:"pipe"}),s=await new Response(o.stdout).text(),i=await new Response(o.stderr).text();if(await o.exited!==0){if(i.trim()&&!i.includes("404"))console.warn(`[fetchGitHubFileContent] Error fetching ${t}: ${i.trim()}`);return null}if(!s.trim())return null;return Buffer.from(s.trim(),"base64").toString("utf-8")}var Oe=new de("admin").description("Admin commands (requires admin privileges)").addHelpText("after",`
|
|
1124
1124
|
Description:
|
|
@@ -1211,7 +1211,7 @@ Examples:
|
|
|
1211
1211
|
$ nemar admin users show 0000-0002-1825-0097
|
|
1212
1212
|
$ nemar admin users show 42 # By numeric id (works for web/ORCID accounts)`).action(async(e,t,n)=>{if(!ke())return;if(A$e(n,"show"))return;let r=n.optsWithGlobals().includeDeleted===!0,o=D("Looking up account...").start();try{let s=await O$e(e,r,o,{mayIncludeDeleted:!0});if(!s)return;let{user:i}=await SS(s.user.id,r);console.log();for(let a of eN(i))console.log(a);if(console.log(),s.match==="fuzzy")process.exitCode=1,ce(),console.log(u.yellow(`No account matches "${br(e)}" exactly; this is the closest one (a typo or an accent away).
|
|
1213
1213
|
`));else if(s.match==="partial")console.log(u.dim(`Found by searching for "${br(e)}"; it is not an exact username, email, GitHub handle, ORCID iD or id.
|
|
1214
|
-
`))}catch(s){fL(s,o,"Failed to look up the account")}});C$e.command("edit").description("Edit one account: name, affiliation, location (owners: username, email, GitHub)").argument("<query>","Username, email, GitHub handle, ORCID iD or numeric id of the account").option("--given-name <text>","Given name").option("--family-name <text>","Family name").option("--affiliation <text>","Affiliation").option("--clear-affiliation","Remove the affiliation").option("--city <text>","City").option("--country <text>","Country").option("--username <name>","Username (owner only)").option("--github <handle>","GitHub handle (owner only)").option("--clear-github","Remove the GitHub handle (owner only)").option("--email <address>","Email address (owner only; marks it unconfirmed)").option("--orcid <iD>","ORCID iD, attested by an owner and marked verified (owner only; ADR 0106)").option(
|
|
1214
|
+
`))}catch(s){fL(s,o,"Failed to look up the account")}});C$e.command("edit").description("Edit one account: name, affiliation, location (owners: username, email, GitHub)").argument("<query>","Username, email, GitHub handle, ORCID iD or numeric id of the account").option("--given-name <text>","Given name").option("--family-name <text>","Family name").option("--affiliation <text>","Affiliation").option("--clear-affiliation","Remove the affiliation").option("--city <text>","City").option("--country <text>","Country").option("--username <name>","Username (owner only)").option("--github <handle>","GitHub handle (owner only)").option("--clear-github","Remove the GitHub handle (owner only)").option("--email <address>","Email address (owner only; marks it unconfirmed)").option("--orcid <iD>","ORCID iD, attested by an owner and marked verified (owner only; ADR 0106)").option(Ye,nt).option(yt,ht).addHelpText("after",`
|
|
1215
1215
|
Who can change what:
|
|
1216
1216
|
${fT.join(", ")}
|
|
1217
1217
|
any admin
|
|
@@ -1256,9 +1256,9 @@ Examples:
|
|
|
1256
1256
|
$ nemar admin users edit lovelace --email new@lab.org # Owner only`).action(async(e,t,n)=>{if(!ke())return;if(A$e(n,"edit"))return;let r=Kfe(t);if(!r.ok)console.error(u.red(r.message)),process.exit(1);let o=r.body;if(Object.keys(o).length===0){let i=[...kS.map(([a])=>ud(a)),...vS.map(({option:a})=>ud(a))];console.error(u.red(`Nothing to change. Pass at least one of: ${i.join(", ")}`)),process.exit(1)}let s=D("Looking up account...").start();try{let i=await O$e(e,!1,s,{mayIncludeDeleted:!1});if(!i)return;if(t.yes&&i.match!=="exact"){process.exitCode=1,ce();let p=`${br(i.user.username??i.user.email)} (id ${i.user.id})`;console.error(u.red(i.match==="fuzzy"?`"${br(e)}" is not the username, email, GitHub handle, ORCID iD or id of any account; the closest is ${p}.`:`"${br(e)}" matched ${p} by search, not by an exact username, email, GitHub handle, ORCID iD or id.`)),console.error(u.dim(` Repeat with the exact identifier, e.g. 'nemar admin users edit ${i.user.id} ...', or drop -y to confirm.`));return}let{user:a}=await SS(i.user.id),c=Jfe(a,o),l=`${br(a.username??a.email)} (id ${a.id})`;if(c.length===0){console.log(u.yellow(`Nothing to change: ${l} already has these values.`));return}if(console.log(`
|
|
1257
1257
|
${u.cyan("Edit")} ${l}
|
|
1258
1258
|
`),i.match==="fuzzy")console.log(u.yellow(` No account matches "${br(e)}" exactly; check this is the one you meant.
|
|
1259
|
-
`));for(let p of c)console.log(` ${p.field.padEnd(16)} ${Mb(p.from)} ${u.dim("->")} ${Mb(p.to)}`);console.log();let d=await De(`Apply ${c.length} change${c.length===1?"":"s"} to ${l}?`,t);if(d==="declined"){console.log(u.dim("Skipped"));return}if(d!=="confirmed"){process.exitCode=1,ce(),console.log(u.dim("Canceled: nothing was changed"));return}s.start(`Updating ${l}...`);let f=await Yfe(a.id,o);s.succeed(f.message);for(let[p,m]of Object.entries(f.changed))console.log(` ${p.padEnd(16)} ${Mb(m.from)} ${u.dim("->")} ${Mb(m.to)}`);for(let p of f.notes??[])console.log(u.yellow(` ! ${p}`))}catch(i){fL(i,s,"Failed to edit the account")}});Oe.command("approve").description("Approve a pending user").argument("[username]","Username to approve (CLI accounts)").option("--id <id>","Approve by numeric user id (web/ORCID accounts have no username)").option(
|
|
1259
|
+
`));for(let p of c)console.log(` ${p.field.padEnd(16)} ${Mb(p.from)} ${u.dim("->")} ${Mb(p.to)}`);console.log();let d=await De(`Apply ${c.length} change${c.length===1?"":"s"} to ${l}?`,t);if(d==="declined"){console.log(u.dim("Skipped"));return}if(d!=="confirmed"){process.exitCode=1,ce(),console.log(u.dim("Canceled: nothing was changed"));return}s.start(`Updating ${l}...`);let f=await Yfe(a.id,o);s.succeed(f.message);for(let[p,m]of Object.entries(f.changed))console.log(` ${p.padEnd(16)} ${Mb(m.from)} ${u.dim("->")} ${Mb(m.to)}`);for(let p of f.notes??[])console.log(u.yellow(` ! ${p}`))}catch(i){fL(i,s,"Failed to edit the account")}});Oe.command("approve").description("Approve a pending user").argument("[username]","Username to approve (CLI accounts)").option("--id <id>","Approve by numeric user id (web/ORCID accounts have no username)").option(Ye,nt).option(yt,ht).action(async(e,t)=>{let n=t.id!==void 0;if(!n&&!e)console.error(u.red("Error: provide a username or --id <id>")),console.error(u.dim("Web/ORCID accounts have no username; find their id with:")),console.error(u.dim(" nemar admin users --pending")),process.exit(1);if(n&&e)console.error(u.red("Error: username and --id are mutually exclusive; provide one")),process.exit(1);let r=0;if(n){if(r=Number.parseInt(t.id??"",10),!Number.isInteger(r)||r<=0)console.error(u.red(`Error: invalid user id: ${t.id}`)),process.exit(1)}if(!ke())return;let o=e??`user id ${r}`;if(console.log(u.cyan(`
|
|
1260
1260
|
Approving user: ${o}
|
|
1261
|
-
`)),console.log("This will:"),console.log(" 1. Mark the account approved and grant upload access"),e)console.log(" 2. Notify them that upload access is granted");else console.log(" 2. Notify them to sign in to the dashboard");console.log();let s=await De(`Approve ${o}?`,t,!0);if(s!=="confirmed"){console.log(u.dim(s==="declined"?"Skipped":"Cancelled"));return}let i=D(`Approving ${o}...`).start();try{let a=e?await Xfe(e):await Qfe(r);if(i.succeed(`Approved ${a.user.username??o}`),console.log(),console.log(` Email: ${a.user.email}`),console.log(` Status: ${u.green(a.user.status)}`),a.user.service_access===!0)console.log(` Tier: ${u.green("upload")}`);else console.log(` Tier: ${u.yellow("grant not confirmed by server")}`),console.log(u.yellow(" The account is approved but the API did not report upload access; verify with 'nemar admin users'."));if(a.note)console.log(u.dim(` ${a.note}`));if(console.log(),a.note);else if(a.email_sent)console.log(a.user.username?u.green("User notified that upload access is granted"):u.green("User notified to sign in at https://nemar.org/login"));else console.log(u.yellow("Warning: Notification email failed to send.")),console.log(a.user.username?u.yellow("Please notify the user manually that upload access is granted"):u.yellow("Please notify the user manually that their account is approved"))}catch(a){Ct(a,i,"Failed to approve user",{404:"User not found or not eligible for approval"})}});Oe.command("revoke").description("Revoke user access").argument("[username]","Username to revoke (CLI accounts)").option("--id <id>","Revoke by numeric user id (web/ORCID accounts have no username)").option(
|
|
1261
|
+
`)),console.log("This will:"),console.log(" 1. Mark the account approved and grant upload access"),e)console.log(" 2. Notify them that upload access is granted");else console.log(" 2. Notify them to sign in to the dashboard");console.log();let s=await De(`Approve ${o}?`,t,!0);if(s!=="confirmed"){console.log(u.dim(s==="declined"?"Skipped":"Cancelled"));return}let i=D(`Approving ${o}...`).start();try{let a=e?await Xfe(e):await Qfe(r);if(i.succeed(`Approved ${a.user.username??o}`),console.log(),console.log(` Email: ${a.user.email}`),console.log(` Status: ${u.green(a.user.status)}`),a.user.service_access===!0)console.log(` Tier: ${u.green("upload")}`);else console.log(` Tier: ${u.yellow("grant not confirmed by server")}`),console.log(u.yellow(" The account is approved but the API did not report upload access; verify with 'nemar admin users'."));if(a.note)console.log(u.dim(` ${a.note}`));if(console.log(),a.note);else if(a.email_sent)console.log(a.user.username?u.green("User notified that upload access is granted"):u.green("User notified to sign in at https://nemar.org/login"));else console.log(u.yellow("Warning: Notification email failed to send.")),console.log(a.user.username?u.yellow("Please notify the user manually that upload access is granted"):u.yellow("Please notify the user manually that their account is approved"))}catch(a){Ct(a,i,"Failed to approve user",{404:"User not found or not eligible for approval"})}});Oe.command("revoke").description("Revoke user access").argument("[username]","Username to revoke (CLI accounts)").option("--id <id>","Revoke by numeric user id (web/ORCID accounts have no username)").option(Ye,nt).option(yt,ht).action(async(e,t)=>{let n=t.id!==void 0;if(!n&&!e)console.error(u.red("Error: provide a username or --id <id>")),console.error(u.dim("Web/ORCID accounts have no username; find their id with:")),console.error(u.dim(" nemar admin users")),process.exit(1);if(n&&e)console.error(u.red("Error: username and --id are mutually exclusive; provide one")),process.exit(1);let r=0;if(n){if(r=Number.parseInt(t.id??"",10),!Number.isInteger(r)||r<=0)console.error(u.red(`Error: invalid user id: ${t.id}`)),process.exit(1)}if(!ke())return;let o=Vt();if(e&&o.username===e){console.log(u.red("Error: Cannot revoke your own access"));return}let s=e??`user id ${r}`,i=e??String(r);console.log(u.red(`
|
|
1262
1262
|
Revoking access for: ${s}
|
|
1263
1263
|
`)),console.log(u.yellow("This will:")),console.log(" 1. Invalidate all API keys for this user"),console.log(" 2. Remove them from datasets they have access to"),console.log(" 3. Revoke upload access, if they hold it"),console.log(" 4. Send them a notification email"),console.log();let a=await Vme(`Type '${i}' to confirm revocation:`,i,t);if(a!=="confirmed"){console.log(u.dim(a==="declined"?"Skipped":"Cancelled"));return}let c=D(`Revoking ${s}...`).start();try{await(e?Zfe(e):epe(r)),c.succeed(`Revoked access for ${s}`)}catch(l){Ct(l,c,"Failed to revoke user",{404:"User not found"})}});Oe.command("role").description("Change a user's role (owner only)").argument("<username>","Username to change role for").argument("<role>","New role: owner, admin, or member").option("-y, --yes","Skip confirmation prompt").addHelpText("after",`
|
|
1264
1264
|
Permission Model:
|
|
@@ -1275,7 +1275,7 @@ Rules:
|
|
|
1275
1275
|
Examples:
|
|
1276
1276
|
$ nemar admin role john_doe admin # Promote to admin
|
|
1277
1277
|
$ nemar admin role john_doe member # Demote to member
|
|
1278
|
-
$ nemar admin role jane_doe owner -y # Promote to owner (skip confirm)`).action(async(e,t,n)=>{if(!ke())return;if(!["owner","admin","member"].includes(t))console.error(u.red(`Invalid role '${t}'. Must be: owner, admin, or member`)),process.exit(1);if(!n.yes){let{confirmed:o}=await Ae.prompt([{type:"confirm",name:"confirmed",message:`Change ${e}'s role to '${t}'?`,default:!1}]);if(!o){console.log(u.dim("Cancelled"));return}}let r=D(`Changing ${e}'s role to '${t}'...`).start();try{let o=await npe(e,t);if(r.succeed(o.message),o.tokens_revoked!==void 0&&o.tokens_revoked>0)console.log(u.yellow(` ${o.tokens_revoked} token(s) revoked (user must re-login)`))}catch(o){Ct(o,r,"Failed to change role",{400:"Invalid request (check if you are an owner)",403:"Owner access required",404:"User not found",409:"User already has that role"})}});Oe.command("verify").description("Mark a pending account's email as verified (owner only)").argument("<id>","Numeric user id (find it with 'nemar admin users --pending')").option(
|
|
1278
|
+
$ nemar admin role jane_doe owner -y # Promote to owner (skip confirm)`).action(async(e,t,n)=>{if(!ke())return;if(!["owner","admin","member"].includes(t))console.error(u.red(`Invalid role '${t}'. Must be: owner, admin, or member`)),process.exit(1);if(!n.yes){let{confirmed:o}=await Ae.prompt([{type:"confirm",name:"confirmed",message:`Change ${e}'s role to '${t}'?`,default:!1}]);if(!o){console.log(u.dim("Cancelled"));return}}let r=D(`Changing ${e}'s role to '${t}'...`).start();try{let o=await npe(e,t);if(r.succeed(o.message),o.tokens_revoked!==void 0&&o.tokens_revoked>0)console.log(u.yellow(` ${o.tokens_revoked} token(s) revoked (user must re-login)`))}catch(o){Ct(o,r,"Failed to change role",{400:"Invalid request (check if you are an owner)",403:"Owner access required",404:"User not found",409:"User already has that role"})}});Oe.command("verify").description("Mark a pending account's email as verified (owner only)").argument("<id>","Numeric user id (find it with 'nemar admin users --pending')").option(Ye,nt).option(yt,ht).addHelpText("after",`
|
|
1279
1279
|
Moves a pending account to verified (the base tier) without the person
|
|
1280
1280
|
redeeming an email code. It is the same transition the code flow makes, and the
|
|
1281
1281
|
audit log records who did it.
|
|
@@ -1291,7 +1291,7 @@ Rules:
|
|
|
1291
1291
|
|
|
1292
1292
|
Examples:
|
|
1293
1293
|
$ nemar admin verify 80
|
|
1294
|
-
$ nemar admin verify 80 -y`).action(async(e,t)=>{let n=Number.parseInt(e,10);if(!Number.isInteger(n)||n<=0||String(n)!==e.trim())console.error(u.red(`Error: invalid user id: ${e}`)),process.exit(1);if(!ke())return;let r=await De(`Mark user id ${n}'s email as verified without a code?`,t);if(r!=="confirmed"){console.log(u.dim(r==="declined"?"Skipped":"Canceled"));return}let o=D(`Verifying user id ${n}...`).start();try{let s=await tpe(n);o.succeed(s.message)}catch(s){yr(s,o,"Failed to verify the account",uk(s)?void 0:{400:"Invalid user id",403:"Owner access required",404:"User not found",409:"Only a pending account can be force-verified"})}});Oe.command("kind").description("Change a user's account kind (owner only)").argument("<username>","Username to change the kind for").argument("<kind>","New kind: person, service, or test").option(
|
|
1294
|
+
$ nemar admin verify 80 -y`).action(async(e,t)=>{let n=Number.parseInt(e,10);if(!Number.isInteger(n)||n<=0||String(n)!==e.trim())console.error(u.red(`Error: invalid user id: ${e}`)),process.exit(1);if(!ke())return;let r=await De(`Mark user id ${n}'s email as verified without a code?`,t);if(r!=="confirmed"){console.log(u.dim(r==="declined"?"Skipped":"Canceled"));return}let o=D(`Verifying user id ${n}...`).start();try{let s=await tpe(n);o.succeed(s.message)}catch(s){yr(s,o,"Failed to verify the account",uk(s)?void 0:{400:"Invalid user id",403:"Owner access required",404:"User not found",409:"Only a pending account can be force-verified"})}});Oe.command("kind").description("Change a user's account kind (owner only)").argument("<username>","Username to change the kind for").argument("<kind>","New kind: person, service, or test").option(Ye,nt).option(yt,ht).addHelpText("after",`
|
|
1295
1295
|
Kinds:
|
|
1296
1296
|
person - a human's own account (the default)
|
|
1297
1297
|
service - operational automation; no human signs in to it directly, keys
|
|
@@ -1315,7 +1315,7 @@ ${u.cyan(`Keys for ${e}`)} (${n.keys.length} total)
|
|
|
1315
1315
|
Every page has a Markdown mirror; ${IS()}/llms.txt indexes them.
|
|
1316
1316
|
Pass several paths at once: they share one documentation session, which is
|
|
1317
1317
|
both faster and easier on the rate limit than one command per page.`).action(async(e,t)=>{if(!ze()){console.error(u.red("Error: Not authenticated")),console.error(u.dim(" Run 'nemar auth login' first")),process.exitCode=1;return}let n=D({text:e.length===1?"Fetching documentation...":`Fetching ${e.length} pages...`,stream:process.stderr}).start(),r;try{r=await uhe(e)}catch(o){n.stop();let s={401:"Sign in again with `nemar auth login`",403:"This account cannot use the API; see the message above",404:"This account does not have access to the operations documentation",429:"Too many documentation sessions from this address; wait a minute"},i=o instanceof L?s[o.statusCode]:void 0;if(console.error(u.red(o instanceof L?o.message:`Failed to fetch documentation: ${G(o)}`)),i)console.error(u.dim(` ${i}`));process.exitCode=1;return}n.stop();for(let o of r){if(!o.ok){console.error(u.red(`${o.path}: ${o.error}`)),process.exitCode=1;continue}if(t.headers&&r.length>1)console.error(u.cyan(`
|
|
1318
|
-
# ${o.path}`));console.log(o.body)}});var y1=new de("s3").description("S3 and IAM credential management");y1.command("regenerate-iam").description("Regenerate AWS IAM credentials for a user").argument("<username>","Username to regenerate credentials for").option(
|
|
1318
|
+
# ${o.path}`));console.log(o.body)}});var y1=new de("s3").description("S3 and IAM credential management");y1.command("regenerate-iam").description("Regenerate AWS IAM credentials for a user").argument("<username>","Username to regenerate credentials for").option(Ye,nt).option(yt,ht).action(T$e);y1.command("lock").description("Apply S3 Object Lock (Governance mode) to a dataset").argument("<dataset-id>","Dataset ID to lock").option(Ye,nt).option(yt,ht).action(async(e,t)=>{if(!ke())return;console.log(u.cyan(`
|
|
1319
1319
|
Apply S3 Object Lock to ${e}
|
|
1320
1320
|
`)),console.log("This will:"),console.log(" \u2022 Set GOVERNANCE mode Object Lock on all objects"),console.log(" \u2022 Retention period: 100 years"),console.log(" \u2022 Objects cannot be deleted or modified without bypass"),console.log();let n=await De(`Apply S3 Object Lock to ${e}?`,t);if(n!=="confirmed"){console.log(u.dim(n==="declined"?"Skipped":"Cancelled"));return}let r=D("Applying S3 Object Lock...").start();try{let o=await $me(e);if(o.failed.length>0){r.fail(`Partial lock: ${o.locked} locked, ${o.failed.length} failed`),console.log(u.yellow(`
|
|
1321
1321
|
Failed objects:`));for(let s of o.failed.slice(0,10))console.log(` \u2022 ${s.key}: ${u.dim(s.error)}`);if(o.failed.length>10)console.log(` ... and ${o.failed.length-10} more`)}else r.succeed(`All ${o.locked} objects locked successfully`)}catch(o){r.fail("S3 lock failed"),console.log(u.dim(` ${G(o)}`))}});y1.command("credential-check").description("Mint a dataset's upload credentials and ask S3 what they can actually do").argument("<dataset-id>","Dataset ID (e.g., on007788)").addHelpText("after",`
|
|
@@ -1331,22 +1331,22 @@ that is anonymously readable.
|
|
|
1331
1331
|
Examples:
|
|
1332
1332
|
$ nemar admin s3 credential-check on007788
|
|
1333
1333
|
$ nemar admin s3 credential-check nm099999
|
|
1334
|
-
`).action(async(e)=>{if(!ke())return;await Promise.resolve().then(() => Za());await Promise.resolve().then(() => $g());let r=D(`Minting upload credentials for ${e}...`).start(),o;try{o=await Gr(e)}catch(c){r.fail(`Could not mint upload credentials for ${e}`),console.log(u.dim(` ${G(c)}`)),process.exit(1)}let s=o.credentials.access_key_id.startsWith("ASIA");r.succeed(`Minted ${s?"temporary (STS)":"long-lived"} credentials, expiring ${o.credentials.expiration}`),console.log(` Scope: ${u.cyan(`s3://${o.s3.bucket}/${o.s3.prefix}/`)}`),console.log(u.dim(" The session policy names this dataset; the identity it is federated from covers the bucket."));let i=D("Asking S3 what they reach...").start(),a=await N$({credentials:o.credentials,bucket:o.s3.bucket,region:o.s3.region,prefix:o.s3.prefix});switch(a.outcome){case"reachable":if(i.succeed(`Listed and read ${a.object}`),console.log(u.green(` These credentials reach s3://${a.bucket}/${a.prefix}/.`)),s)console.log(u.dim(" A transfer must carry the session token too: git-annex caches an S3 remote's key and secret with nowhere to put it, so a copy that inherits the environment signs without one and every request comes back 403."));break;case"empty-prefix":i.warn(`Listing worked; there is no object under ${a.prefix}/ to read`),console.log(u.dim(" ListBucket is granted, so the credentials are valid. Reachability of an object is unproven because there is none."));break;case"unavailable":i.warn(`Could not probe: ${a.detail}`),console.log(u.dim(" Install the aws CLI (nemar doctor lists it) and re-run."));break;case"refused":i.fail(`S3 refused: ${a.detail}`),console.log(),console.log("Three things can produce this, in the order worth checking:"),console.log(" 1. the request dropped the session token (a temporary key alone is always 403)"),console.log(` 2. the session policy does not name ${e} (it is generated per dataset id)`),console.log(" 3. the identity the token is federated from no longer covers the bucket, so the intersection is empty"),process.exit(1)}});Oe.addCommand(y1);Oe.command("regenerate-iam",{hidden:!0}).argument("<username>").option(
|
|
1334
|
+
`).action(async(e)=>{if(!ke())return;await Promise.resolve().then(() => Za());await Promise.resolve().then(() => $g());let r=D(`Minting upload credentials for ${e}...`).start(),o;try{o=await Gr(e)}catch(c){r.fail(`Could not mint upload credentials for ${e}`),console.log(u.dim(` ${G(c)}`)),process.exit(1)}let s=o.credentials.access_key_id.startsWith("ASIA");r.succeed(`Minted ${s?"temporary (STS)":"long-lived"} credentials, expiring ${o.credentials.expiration}`),console.log(` Scope: ${u.cyan(`s3://${o.s3.bucket}/${o.s3.prefix}/`)}`),console.log(u.dim(" The session policy names this dataset; the identity it is federated from covers the bucket."));let i=D("Asking S3 what they reach...").start(),a=await N$({credentials:o.credentials,bucket:o.s3.bucket,region:o.s3.region,prefix:o.s3.prefix});switch(a.outcome){case"reachable":if(i.succeed(`Listed and read ${a.object}`),console.log(u.green(` These credentials reach s3://${a.bucket}/${a.prefix}/.`)),s)console.log(u.dim(" A transfer must carry the session token too: git-annex caches an S3 remote's key and secret with nowhere to put it, so a copy that inherits the environment signs without one and every request comes back 403."));break;case"empty-prefix":i.warn(`Listing worked; there is no object under ${a.prefix}/ to read`),console.log(u.dim(" ListBucket is granted, so the credentials are valid. Reachability of an object is unproven because there is none."));break;case"unavailable":i.warn(`Could not probe: ${a.detail}`),console.log(u.dim(" Install the aws CLI (nemar doctor lists it) and re-run."));break;case"refused":i.fail(`S3 refused: ${a.detail}`),console.log(),console.log("Three things can produce this, in the order worth checking:"),console.log(" 1. the request dropped the session token (a temporary key alone is always 403)"),console.log(` 2. the session policy does not name ${e} (it is generated per dataset id)`),console.log(" 3. the identity the token is federated from no longer covers the bucket, so the intersection is empty"),process.exit(1)}});Oe.addCommand(y1);Oe.command("regenerate-iam",{hidden:!0}).argument("<username>").option(Ye,nt).option(yt,ht).action(T$e);async function T$e(e,t){if(!ke())return;console.log(u.yellow(`
|
|
1335
1335
|
This command is deprecated.
|
|
1336
|
-
`)),console.log("S3 access is now managed through backend-scoped credentials."),console.log("Per-user IAM credentials are no longer needed."),console.log(),console.log(u.dim("Users can upload datasets without any IAM setup."))}var pL=new de("repo").description("Repository visibility management");pL.command("public").description("Make a dataset repository public").argument("<dataset-id>","Dataset ID (e.g., nm000104)").option(
|
|
1336
|
+
`)),console.log("S3 access is now managed through backend-scoped credentials."),console.log("Per-user IAM credentials are no longer needed."),console.log(),console.log(u.dim("Users can upload datasets without any IAM setup."))}var pL=new de("repo").description("Repository visibility management");pL.command("public").description("Make a dataset repository public").argument("<dataset-id>","Dataset ID (e.g., nm000104)").option(Ye,nt).option(yt,ht).action(async(e,t)=>{if(!ke())return;console.log(u.cyan(`
|
|
1337
1337
|
Making repository public: ${e}
|
|
1338
|
-
`)),console.log(u.yellow("Warning: This will make the dataset visible to everyone.")),console.log();let n=await De(`Make ${e} public?`,t);if(n!=="confirmed"){console.log(u.dim(n==="declined"?"Skipped":"Cancelled"));return}let r=D(`Setting ${e} to public...`).start();try{await rN(e,"public"),r.succeed(`Repository ${e} is now public`)}catch(o){Ct(o,r,"Failed to change visibility",{404:"Dataset not found"})}});pL.command("private").description("Make a dataset repository private").argument("<dataset-id>","Dataset ID (e.g., nm000104)").option(
|
|
1338
|
+
`)),console.log(u.yellow("Warning: This will make the dataset visible to everyone.")),console.log();let n=await De(`Make ${e} public?`,t);if(n!=="confirmed"){console.log(u.dim(n==="declined"?"Skipped":"Cancelled"));return}let r=D(`Setting ${e} to public...`).start();try{await rN(e,"public"),r.succeed(`Repository ${e} is now public`)}catch(o){Ct(o,r,"Failed to change visibility",{404:"Dataset not found"})}});pL.command("private").description("Make a dataset repository private").argument("<dataset-id>","Dataset ID (e.g., nm000104)").option(Ye,nt).option(yt,ht).action(async(e,t)=>{if(!ke())return;console.log(u.yellow(`
|
|
1339
1339
|
Making repository private: ${e}
|
|
1340
1340
|
`)),console.log("This will restrict access to collaborators only."),console.log();let n=await De(`Make ${e} private?`,t);if(n!=="confirmed"){console.log(u.dim(n==="declined"?"Skipped":"Cancelled"));return}let r=D(`Setting ${e} to private...`).start();try{await rN(e,"private"),r.succeed(`Repository ${e} is now private`)}catch(o){Ct(o,r,"Failed to change visibility",{404:"Dataset not found"})}});Oe.addCommand(pL);var S_=new de("ci").description("CI workflow management");S_.command("check").description("Check CI workflow status for a dataset").argument("<dataset-id>","Dataset ID (e.g., nm000104)").action(async(e)=>{if(!ke())return;let t=D(`Checking CI status for ${e}...`).start();try{let n=await cpe(e);t.stop(),console.log(`
|
|
1341
1341
|
${u.cyan("CI Status:")} ${e}
|
|
1342
|
-
`);let r=n.bids_validation.present,o=r?u.green("[x]"):u.red("[ ]");if(console.log(` ${o} BIDS Validation`),r){let a=n.bids_validation.status==="success"?u.green:n.bids_validation.status==="failure"?u.red:u.yellow;if(console.log(` Status: ${a(n.bids_validation.status)}`),n.bids_validation.url)console.log(` URL: ${u.dim(n.bids_validation.url)}`)}else console.log(` ${u.dim("Not deployed. Use 'nemar admin ci add' to deploy.")}`);let s=n.version_check.present,i=s?u.green("[x]"):u.red("[ ]");if(console.log(` ${i} Version Check`),!s)console.log(` ${u.dim("Not deployed. Use 'nemar admin ci add' to deploy.")}`);console.log()}catch(n){Ct(n,t,"Failed to check CI status",{404:"Dataset not found"})}});async function zAt(e,t=async()=>{let r=await oN(e);return{valid:r.valid,missing:r.missing,errors:r.errors}},n=[2500,5000]){let r=null;for(let o of n){if(o>0)await new Promise((s)=>setTimeout(s,o));try{if(r=await t(),r.missing.length===0||r.errors.length>0)return r}catch{return null}}return r}function P$e(e){if(console.log(),console.log(u.yellow("Validation warnings (best-effort; deploy succeeded):")),e.missing.length>0)console.log(` ${u.yellow("!")} Not listed by GitHub Actions (parse error or indexing lag): ${e.missing.join(", ")}`);for(let t of e.errors)console.log(` ${u.yellow("!")} ${t}`)}S_.command("add").description("Deploy CI workflows to a dataset repository (or all with --all)").argument("[dataset-id]","Dataset ID (e.g., nm000104)").option("--all","Deploy to all dataset repositories").option("--no-validate","Skip the post-deploy parseability poll on the single-dataset path. No-op for --all (fleet deploys always skip the poll).").option(
|
|
1342
|
+
`);let r=n.bids_validation.present,o=r?u.green("[x]"):u.red("[ ]");if(console.log(` ${o} BIDS Validation`),r){let a=n.bids_validation.status==="success"?u.green:n.bids_validation.status==="failure"?u.red:u.yellow;if(console.log(` Status: ${a(n.bids_validation.status)}`),n.bids_validation.url)console.log(` URL: ${u.dim(n.bids_validation.url)}`)}else console.log(` ${u.dim("Not deployed. Use 'nemar admin ci add' to deploy.")}`);let s=n.version_check.present,i=s?u.green("[x]"):u.red("[ ]");if(console.log(` ${i} Version Check`),!s)console.log(` ${u.dim("Not deployed. Use 'nemar admin ci add' to deploy.")}`);console.log()}catch(n){Ct(n,t,"Failed to check CI status",{404:"Dataset not found"})}});async function zAt(e,t=async()=>{let r=await oN(e);return{valid:r.valid,missing:r.missing,errors:r.errors}},n=[2500,5000]){let r=null;for(let o of n){if(o>0)await new Promise((s)=>setTimeout(s,o));try{if(r=await t(),r.missing.length===0||r.errors.length>0)return r}catch{return null}}return r}function P$e(e){if(console.log(),console.log(u.yellow("Validation warnings (best-effort; deploy succeeded):")),e.missing.length>0)console.log(` ${u.yellow("!")} Not listed by GitHub Actions (parse error or indexing lag): ${e.missing.join(", ")}`);for(let t of e.errors)console.log(` ${u.yellow("!")} ${t}`)}S_.command("add").description("Deploy CI workflows to a dataset repository (or all with --all)").argument("[dataset-id]","Dataset ID (e.g., nm000104)").option("--all","Deploy to all dataset repositories").option("--no-validate","Skip the post-deploy parseability poll on the single-dataset path. No-op for --all (fleet deploys always skip the poll).").option(Ye,nt).option(yt,ht).action(async(e,t)=>{if(!ke())return;let n=t.validate===!1;if(t.all){let i=D("Fetching dataset list...").start(),a;try{if(a=(await fd({limit:1000})).datasets,i.succeed(`Found ${a.length} datasets`),a.length>=1000)console.log(u.yellow("Warning: reached 1000 dataset limit; some datasets may be skipped"))}catch(f){Ct(f,i,"Failed to fetch datasets");return}console.log(u.cyan(`
|
|
1343
1343
|
Deploy CI workflows to ${a.length} datasets
|
|
1344
1344
|
`)),console.log("This will add/update the following workflows on each:"),console.log(" 1. BIDS Validation (runs on PRs)"),console.log(" 2. Version Check (ensures version bump on PRs)"),console.log(" 3. PR Merge Handler (creates releases, publishes DOIs)"),console.log(u.dim(" (post-deploy parseability poll skipped for --all; run 'nemar admin ci validate <id>' per dataset)")),console.log();let c=await De(`Deploy CI workflows to all ${a.length} datasets?`,t);if(c!=="confirmed"){console.log(u.dim(c==="declined"?"Skipped":"Cancelled"));return}let l=0,d=0;for(let f of a){let p=D(`Deploying to ${f.dataset_id}...`).start();try{await il(f.dataset_id),p.succeed(`${f.dataset_id}: deployed`),l++}catch(m){let h=m instanceof L?m.message:String(m);p.fail(`${f.dataset_id}: ${h}`),d++}}console.log(),console.log(u.cyan(`Done: ${l} succeeded, ${d} failed out of ${a.length}`));return}if(!e){console.error(u.red("Error: dataset-id is required (or use --all)"));return}if(console.log(u.cyan(`
|
|
1345
1345
|
Deploy CI workflows to: ${e}
|
|
1346
|
-
`)),console.log("This will add the following workflows:"),console.log(" 1. BIDS Validation (runs on PRs)"),console.log(" 2. Version Check (ensures version bump on PRs)"),console.log(" 3. PR Merge Handler (creates releases, publishes DOIs)"),n)console.log(u.dim(" (post-deploy parseability poll disabled via --no-validate)"));console.log();let r=await De(`Deploy CI workflows to ${e}?`,t);if(r!=="confirmed"){console.log(u.dim(r==="declined"?"Skipped":"Cancelled"));return}let o=D(`Deploying CI workflows to ${e}...`).start(),s;try{s=await il(e)}catch(i){Ct(i,o,"Failed to deploy CI workflows",{404:"Dataset not found"});return}o.succeed("CI workflows deployed"),console.log();for(let i of s.workflows_deployed)console.log(` ${u.green("[x]")} ${i}`);if(!n){let i=D("Verifying GitHub Actions can parse the workflows...").start(),a=await zAt(e);if(!a)i.warn("Could not verify workflow parseability (deploy succeeded)");else if(a.missing.length===0&&a.errors.length===0)i.succeed("All workflows parseable by GitHub Actions");else{let c=a.missing.length>0?"Some workflows missing from GitHub Actions listing":"Could not fully verify workflow parseability (GitHub API error)";i.warn(c),P$e(a)}}console.log()});S_.command("validate").description("Check whether GitHub Actions can parse the deployed CI workflows").argument("<dataset-id>","Dataset ID (e.g., nm000104)").action(async(e)=>{if(!ke())return;let t=D(`Validating CI workflows for ${e}...`).start();try{let n=await oN(e);if(n.missing.length===0&&n.errors.length===0)t.succeed(`All ${n.valid.length} workflows parseable by GitHub Actions`);else t.warn("Some workflows missing or unreadable"),P$e({missing:n.missing,errors:n.errors})}catch(n){Ct(n,t,"Failed to validate CI workflows",{404:"Dataset not found"})}});S_.command("sync").description("Sync deployed CI workflows to current templates (only writes drifted/missing files)").argument("[dataset-id]","Dataset ID (e.g., nm000104)").option("--all","Sync across all dataset repositories").option(
|
|
1346
|
+
`)),console.log("This will add the following workflows:"),console.log(" 1. BIDS Validation (runs on PRs)"),console.log(" 2. Version Check (ensures version bump on PRs)"),console.log(" 3. PR Merge Handler (creates releases, publishes DOIs)"),n)console.log(u.dim(" (post-deploy parseability poll disabled via --no-validate)"));console.log();let r=await De(`Deploy CI workflows to ${e}?`,t);if(r!=="confirmed"){console.log(u.dim(r==="declined"?"Skipped":"Cancelled"));return}let o=D(`Deploying CI workflows to ${e}...`).start(),s;try{s=await il(e)}catch(i){Ct(i,o,"Failed to deploy CI workflows",{404:"Dataset not found"});return}o.succeed("CI workflows deployed"),console.log();for(let i of s.workflows_deployed)console.log(` ${u.green("[x]")} ${i}`);if(!n){let i=D("Verifying GitHub Actions can parse the workflows...").start(),a=await zAt(e);if(!a)i.warn("Could not verify workflow parseability (deploy succeeded)");else if(a.missing.length===0&&a.errors.length===0)i.succeed("All workflows parseable by GitHub Actions");else{let c=a.missing.length>0?"Some workflows missing from GitHub Actions listing":"Could not fully verify workflow parseability (GitHub API error)";i.warn(c),P$e(a)}}console.log()});S_.command("validate").description("Check whether GitHub Actions can parse the deployed CI workflows").argument("<dataset-id>","Dataset ID (e.g., nm000104)").action(async(e)=>{if(!ke())return;let t=D(`Validating CI workflows for ${e}...`).start();try{let n=await oN(e);if(n.missing.length===0&&n.errors.length===0)t.succeed(`All ${n.valid.length} workflows parseable by GitHub Actions`);else t.warn("Some workflows missing or unreadable"),P$e({missing:n.missing,errors:n.errors})}catch(n){Ct(n,t,"Failed to validate CI workflows",{404:"Dataset not found"})}});S_.command("sync").description("Sync deployed CI workflows to current templates (only writes drifted/missing files)").argument("[dataset-id]","Dataset ID (e.g., nm000104)").option("--all","Sync across all dataset repositories").option(Ye,nt).option(yt,ht).action(async(e,t)=>{if(!ke())return;if(t.all){let r=D("Fetching dataset list...").start(),o;try{if(o=(await fd({limit:1000})).datasets,r.succeed(`Found ${o.length} datasets`),o.length>=1000)console.log(u.yellow("Warning: reached 1000 dataset limit; some datasets may be skipped"))}catch(l){Ct(l,r,"Failed to fetch datasets");return}console.log(u.cyan(`
|
|
1347
1347
|
Sync CI templates across ${o.length} datasets (writes only diffs)
|
|
1348
|
-
`));let s=await De(`Sync templates on all ${o.length} datasets?`,t);if(s!=="confirmed"){console.log(u.dim(s==="declined"?"Skipped":"Cancelled"));return}let i=0,a=0,c=0;for(let l of o){let d=D(`Syncing ${l.dataset_id}...`).start();try{let f=await sN(l.dataset_id),p=f.changed.length+f.added.length;if(f.errors.length>0)d.warn(`${l.dataset_id}: ${p} updated, ${f.errors.length} error(s)`),c++;else if(p===0)d.succeed(`${l.dataset_id}: up to date`),i++;else{let m=[];if(f.added.length>0)m.push(`+${f.added.length} added`);if(f.changed.length>0)m.push(`~${f.changed.length} updated`);d.succeed(`${l.dataset_id}: ${m.join(", ")}`),a++}}catch(f){let p=f instanceof L?f.message:String(f);d.fail(`${l.dataset_id}: ${p}`),c++}}console.log(),console.log(u.cyan(`Done: ${i} up-to-date, ${a} updated, ${c} with errors`));return}if(!e){console.error(u.red("Error: dataset-id is required (or use --all)"));return}let n=D(`Syncing CI templates for ${e}...`).start();try{let r=await sN(e),o=r.changed.length+r.added.length;if(r.errors.length>0)n.warn(`${e}: ${r.errors.length} error(s)`);else if(o===0)n.succeed(`${e}: already up to date`);else n.succeed(`${e}: synced`);if(console.log(),console.log(` ${u.dim("Checked:")} ${r.checked.join(", ")}`),r.added.length>0)console.log(` ${u.green("Added:")} ${r.added.join(", ")}`);if(r.changed.length>0)console.log(` ${u.yellow("Updated:")} ${r.changed.join(", ")}`);if(!r.committed&&o>0&&r.errors.length===0)console.log(` ${u.yellow("Note:")} listed changes were not committed`);if(r.list_failed)console.log(` ${u.red("Warning:")} workflow directory listing failed; presence is unknown`);if(r.errors.length>0){console.log(` ${u.red("Errors:")}`);for(let s of r.errors)console.log(` - ${s}`)}console.log()}catch(r){Ct(r,n,"Failed to sync CI templates",{404:"Dataset not found"})}});Oe.addCommand(S_);var $_=new de("doi").description("DOI management");$_.command("create").description("Create concept DOI for a dataset").argument("<dataset-id>","Dataset ID (e.g., nm000104)").option("--title <title>","DOI title (defaults to dataset name)").option("--description <desc>","DOI description").option("--provider <provider>","DOI provider: ezid (default) or zenodo","ezid").option("--sandbox","Use sandbox/test DOI").option(
|
|
1349
|
-
Dataset already has a concept DOI:`)),console.log(` Concept DOI: ${u.cyan(c.concept_doi)}`),c.zenodo_concept_url)console.log(` Zenodo URL: ${c.zenodo_concept_url}`);return}}catch(c){if(process.env.DEBUG)console.error("[debug] DOI info fetch:",c)}if(console.log(),console.log(u.cyan("Dataset Information:")),console.log(` ID: ${r.dataset_id}`),console.log(` Name: ${r.name}`),r.github_repo)console.log(` GitHub: ${r.github_repo}`);if(t.sandbox)console.log(` Mode: ${u.yellow("SANDBOX (test DOI)")}`);console.log();let o=t.provider==="zenodo"?"zenodo":"ezid";if(t.sandbox){if(console.log(u.yellow("\u2501".repeat(60))),console.log(u.yellow.bold(" SANDBOX MODE ENABLED")),console.log(u.yellow("\u2501".repeat(60))),o==="zenodo")console.log(u.yellow(" \u2022 Using Zenodo sandbox (sandbox.zenodo.org)"));else console.log(u.yellow(" \u2022 Using EZID test shoulder (doi:10.5072/FK2)")),console.log(u.yellow(" \u2022 Test DOIs auto-delete after 2 weeks"));console.log(u.yellow(" \u2022 DOI will NOT be indexed by DataCite")),console.log(u.yellow(" \u2022 DOI will NOT resolve in production")),console.log(u.yellow(" \u2022 Use this for testing workflows only")),console.log(u.yellow("\u2501".repeat(60))),console.log()}console.log(u.red("WARNING: DOIs are PERMANENT and cannot be deleted!")),console.log(u.dim("The DOI will be pre-reserved but not published until the first version release.")),console.log(` Provider: ${u.cyan(o.toUpperCase())}`),console.log();let s=t.sandbox?`Create TEST concept DOI via ${o.toUpperCase()} SANDBOX?`:`Create PERMANENT concept DOI via ${o.toUpperCase()} PRODUCTION?`,i=await De(s,t);if(i!=="confirmed"){console.log(u.dim(i==="declined"?"Skipped":"Cancelled"));return}let a=D(`Creating concept DOI via ${o.toUpperCase()}...`).start();try{let c=await lpe(e,{title:t.title,description:t.description,sandbox:t.sandbox,provider:o});a.succeed("Concept DOI created successfully");let l=D("Finalizing repository setup...").start();try{let d=await OS(e);if(d.warnings&&d.warnings.length>0){l.warn("Repository setup finalized with warnings");for(let f of d.warnings)console.log(u.yellow(` Warning: ${f}`))}else l.succeed("Repository setup finalized")}catch(d){if(l.warn("Could not finalize repository setup"),d instanceof L){if(console.log(u.dim(` ${d.message}`)),d.statusCode===403)console.log(u.dim(" Check admin credentials and permissions"))}else console.log(u.dim(` ${d instanceof Error?d.message:"Unknown error"}`))}if(console.log(),console.log(u.green("DOI Information:")),console.log(` Concept DOI: ${u.cyan(c.concept_doi)}`),console.log(` Provider: ${c.provider.toUpperCase()}`),c.provider==="ezid")console.log(` DOI URL: ${c.doi_url}`),console.log(` EZID ID: ${c.ezid_identifier}`);else console.log(` Zenodo URL: ${c.zenodo_url}`);if(c.metadata_warning)console.log(u.yellow(` Warning: ${c.metadata_warning}`));if(console.log(),console.log(u.yellow("Next steps:")),console.log(" 1. Update dataset_description.json with DatasetDOI field"),console.log(" 2. Create a PR and merge it to trigger version DOI publication"),console.log(),t.sandbox)console.log(u.dim("Note: This is a sandbox DOI and will not resolve in production."))}catch(c){if(c instanceof L){if(a.fail(c.message),c.statusCode===403)console.log(u.dim(" This command requires admin privileges"))}else a.fail("Failed to create concept DOI"),console.log(u.dim(` ${G(c)}`))}});$_.command("info").description("Get DOI info for a dataset").argument("<dataset-id>","Dataset ID (e.g., nm000104)").action(async(e)=>{if(!ke())return;let t=D("Fetching DOI info...").start();try{let n=await jb(e);if(t.stop(),console.log(),console.log(u.cyan(`DOI Information for ${e}:`)),console.log(` Dataset Name: ${n.name}`),console.log(),n.concept_doi){if(console.log(u.green("Concept DOI:")),console.log(` DOI: ${n.concept_doi}`),console.log(` URL: https://doi.org/${n.concept_doi}`),console.log(` Provider: ${(n.doi_provider||"zenodo").toUpperCase()}`),n.doi_provider==="ezid"){if(n.ezid_identifier)console.log(` EZID ID: ${n.ezid_identifier}`);if(n.ezid_status){let r=n.ezid_status==="public"?u.green:u.yellow;console.log(` Status: ${r(n.ezid_status)}`)}}if(n.zenodo_concept_url){if(console.log(` Zenodo: ${n.zenodo_concept_url}`),n.zenodo_concept_url.includes("sandbox.zenodo.org"))console.log(),console.log(u.yellow("Mode: SANDBOX (test DOI)")),console.log(u.yellow(" This DOI is not indexed by DataCite and will not resolve in production"))}}else console.log(u.yellow("No concept DOI created yet")),console.log(u.dim(" Use 'nemar admin doi create' to create one"));if(console.log(),n.latest_version_doi)console.log(u.green("Latest Version DOI:")),console.log(` DOI: ${n.latest_version_doi}`),console.log(` URL: https://doi.org/${n.latest_version_doi}`);else if(n.concept_doi)console.log(u.yellow("No version DOI published yet")),console.log(u.dim(" Version DOIs are created automatically on PR merge"))}catch(n){if(n instanceof L){if(t.fail(n.message),n.statusCode===404)console.log(u.dim(" Dataset not found"));else if(n.statusCode===403)console.log(u.dim(" This command requires admin privileges"))}else t.fail("Failed to fetch DOI info")}});$_.command("update").description("Update EZID DOI metadata or status").argument("<dataset-id>","Dataset ID (e.g., nm000104)").option("--make-public","Transition DOI from reserved to public (permanent)").option("--unavailable","Tombstone the concept DOI (EZID _status=unavailable); concept-only, reversible via --make-public. For a full withdrawal (visibility + every version DOI) use 'nemar admin withdraw' instead.").option("--refresh","Refresh metadata from dataset_description.json and .nemar/metadata.json").option(Je,nt).option(yt,ht).action(async(e,t)=>{if(!ke())return;if(t.makePublic&&t.unavailable){console.log(u.red("Use --make-public or --unavailable, not both."));return}if(!t.makePublic&&!t.unavailable&&!t.refresh){console.log(u.yellow("No action specified. Use --make-public, --unavailable, and/or --refresh."));return}if(t.makePublic){console.log(u.red("WARNING: Making a DOI public is PERMANENT!")),console.log(u.dim(" The DOI will be findable in DataCite and cannot be reverted.")),console.log();let r=await De(`Make DOI for ${e} PUBLIC and permanent?`,t);if(r!=="confirmed"){console.log(u.dim(r==="declined"?"Skipped":"Cancelled"));return}}if(t.unavailable){console.log(u.yellow("This tombstones the concept DOI (EZID _status=unavailable).")),console.log(u.dim(" Reversible with --make-public. Version DOIs are untouched.")),console.log();let r=await De(`Mark DOI for ${e} unavailable (tombstone)?`,t);if(r!=="confirmed"){console.log(u.dim(r==="declined"?"Skipped":"Cancelled"));return}}let n=D("Updating DOI...").start();try{let r=await iN(e,{status:t.makePublic?"public":t.unavailable?"unavailable":void 0,refresh_metadata:t.refresh});n.succeed("DOI updated successfully"),console.log(),console.log(` EZID ID: ${u.cyan(r.ezid_identifier)}`),console.log(` Status: ${r.status==="public"?u.green(r.status):u.yellow(r.status)}`),console.log(` URL: ${r.doi_url}`)}catch(r){if(r instanceof L){if(n.fail(r.message),r.statusCode===400)console.log(u.dim(" DOI update is only supported for EZID-managed DOIs"))}else n.fail("Failed to update DOI"),console.log(u.dim(` ${G(r)}`))}});$_.command("enrich").description("Enrich DOI metadata with ORCIDs, descriptions, funding, and more").argument("<dataset-id>","Dataset ID (e.g., nm000104)").option("--no-llm","Skip LLM-based enrichment from README").option("--sandbox","Use sandbox DOI").option(Je,nt).option(yt,ht).action(async(e,t)=>{if(!ke())return;let n=D("Fetching dataset and existing enrichment...").start(),r;try{r=await Wn(e),n.succeed(`Dataset: ${r.name}`)}catch(m){if(m instanceof L)n.fail(m.message);else n.fail("Failed to fetch dataset");return}let o,s=!1;try{o=await jb(e)}catch(m){if(m instanceof L&&m.statusCode===404);else s=!0,console.log(u.yellow(` Warning: Could not fetch DOI info: ${G(m)}`))}if(o?.concept_doi)console.log(` DOI: ${u.cyan(o.concept_doi)}`);let i={version:"2.0"};if(r.github_repo){let m=D("Reading existing metadata...").start(),h=await x$e(r.github_repo,".nemar/metadata.json");if(h)try{let g=JSON.parse(h);if(g&&typeof g==="object"&&g.version==="2.0")i=g,m.succeed(`Loaded existing metadata (stage: ${g.pipeline_stage||"unknown"})`);else m.warn("Existing metadata has unsupported version, starting fresh")}catch(g){m.warn(`Could not parse existing metadata (${g instanceof Error?g.message:String(g)}), starting fresh`)}else m.info("No existing .nemar/metadata.json found, starting fresh")}if(t.llm!==!1&&r.github_repo){console.log(),console.log(u.cyan("--- Running LLM enrichment pipeline (CI workflow) ---"));let m=D("Triggering run-enrichment workflow...").start();try{let{spawn:h}=await Promise.resolve(globalThis.Bun),g=r.github_repo,y="nemarDatasets/.github",b="run-enrichment.yml",_=h({cmd:["gh","workflow","run","run-enrichment.yml","--repo","nemarDatasets/.github","--ref","main","-f",`dataset_id=${e}`,"-f","ref=main","-f","force=true"],stdout:"pipe",stderr:"pipe"}),x=await new Response(_.stderr).text();if(await _.exited!==0)throw Error(`Failed to trigger workflow: ${x.trim()}`);m.text="Waiting for workflow to register...",await new Promise((A)=>setTimeout(A,3000)),m.text="Polling workflow status...";let v=60,C="",T=0;for(let A=0;A<v;A++){let F=h({cmd:["gh","run","list","--repo","nemarDatasets/.github","--workflow","run-enrichment.yml","-L","10","--json","databaseId,status,conclusion,displayTitle,event"],stdout:"pipe",stderr:"pipe"}),M=await new Response(F.stdout).text(),U=await new Response(F.stderr).text();if(await F.exited!==0){if(T++,T>=3){m.warn(`gh CLI error: ${U.trim()}`);break}await new Promise((P)=>setTimeout(P,5000));continue}try{let P=JSON.parse(M.trim());T=0;let O=P.find((H)=>H.event==="workflow_dispatch");if(O){if(O.status==="completed"){C=O.conclusion||"unknown";break}m.text=`Workflow ${O.status}... (${A*5}s)`}}catch(P){if(T++,T>=3){m.warn(`Unable to parse workflow status: ${P instanceof Error?P.message:String(P)} (raw: ${M.trim().slice(0,200)})`);break}}await new Promise((P)=>setTimeout(P,5000))}let z=!1;if(!C)m.warn("Workflow timed out after 5 minutes (may still be running)");else if(C==="success"){m.succeed("LLM enrichment workflow completed successfully");let A=await x$e(g,".nemar/metadata.json");if(A)try{let F=JSON.parse(A);if(F&&typeof F==="object"&&F.version==="2.0"){Object.assign(i,F),z=!0;let M=F.pipeline_stage||"unknown";if(console.log(u.dim(` Pipeline stage: ${M}`)),i.authors){let U=Object.keys(i.authors).length;console.log(u.dim(` Authors: ${U}`))}}}catch(F){console.log(u.yellow(` Warning: Could not parse updated metadata: ${F instanceof Error?F.message:String(F)}`)),console.log(u.dim(" Using pre-workflow enrichment data"))}else console.log(u.yellow(" Warning: Could not fetch updated metadata after successful workflow.")),console.log(u.dim(" Author data below may be from a previous run."))}else m.fail(`LLM enrichment workflow failed (conclusion: ${C})`);if(!z)console.log(u.yellow(" ORCID discovery did not complete. Authors below may be from previous metadata."))}catch(h){m.fail("LLM enrichment pipeline failed"),console.log(u.dim(` ${G(h)}`)),console.log(u.yellow(" ORCID discovery did not run. You will need to enter ORCIDs manually."))}}console.log(),console.log(u.cyan("--- Author ORCIDs ---"));let a=i.authors||{},c=Object.keys(a);if(c.length>0){let m=c.filter((g)=>a[g]?.orcid),h=c.filter((g)=>!a[g]?.orcid);console.log(u.dim(` Discovered ${c.length} authors from pipeline:`));for(let g of m)console.log(u.green(` [x] ${g}: ${a[g]?.orcid}`));for(let g of h)console.log(u.yellow(` [ ] ${g}: no ORCID found`));if(h.length>0)console.log(u.dim(` ${h.length} author(s) missing ORCIDs.`))}let{updateAuthors:l}=await Ae.prompt([{type:"confirm",name:"updateAuthors",message:c.length>0?"Add or correct author ORCIDs?":"Add author ORCIDs manually?",default:!1}]);if(l){let m={},h=!0;while(h){let{authorName:g}=await Ae.prompt([{type:"input",name:"authorName",message:'Author name (as in BIDS, e.g., "Shirazi, Yahya"):'}]);if(!g)break;let y=a[g];if(y?.orcid)console.log(u.dim(` Current ORCID: ${y.orcid}`));let{orcid:b}=await Ae.prompt([{type:"input",name:"orcid",message:`ORCID for "${g}" (Enter to ${y?.orcid?"keep current":"skip"}):`,validate:(v)=>{if(!v)return!0;return DS.test(v)||"Invalid ORCID format (XXXX-XXXX-XXXX-XXXX)"}}]),_={};if(b)_.orcid=b;let{affiliation:x}=await Ae.prompt([{type:"input",name:"affiliation",message:`Affiliation for "${g}" (optional):`}]);if(x)_.affiliations=[{name:x}];if(_.orcid||_.affiliations)m[g]=_;let{more:k}=await Ae.prompt([{type:"confirm",name:"more",message:"Add another author?",default:!0}]);h=k}if(Object.keys(m).length>0){let g={...i.authors||{}};for(let[y,b]of Object.entries(m)){let _=g[y]||{};g[y]={..._,...b,orcid:b.orcid||_.orcid}}i.authors=g}}console.log(),console.log(u.cyan("--- Dataset stats ---"));let d=D("Computing dataset sizes and formats...").start();try{let m=await Sme(e),h=Ut(m.total_size);i.sizes=[`${h} (${m.file_count} files)`],i.formats=m.extensions,d.succeed(`Sizes: ${h} (${m.file_count} files), Formats: ${m.extensions.join(", ")}`)}catch(m){d.warn("Could not compute dataset stats"),console.log(u.dim(` ${G(m)}`))}console.log(),console.log(u.cyan("--- Review ---")),console.log(JSON.stringify(i,null,2)),console.log();let f=await De("Commit to repo and refresh DOI?",t,!0);if(f!=="confirmed"){console.log(u.dim(f==="declined"?"Skipped":"Cancelled"));return}let p=D("Saving enrichment...").start();try{let m=await qme(e,i);if(p.succeed(m.message),m.bidsignore_updated)console.log(u.dim(" .bidsignore updated to include .nemar/"));if(!o&&s)try{o=await jb(e)}catch(h){if(process.env.DEBUG)console.error("[debug] DOI info re-fetch:",h)}if(o?.ezid_identifier){let h=D("Refreshing DOI metadata...").start();try{await iN(e,{refresh_metadata:!0}),h.succeed("DOI metadata refreshed")}catch(g){h.warn("Could not refresh DOI metadata"),console.log(u.dim(` ${G(g)}`))}}else if(s)console.log(u.yellow(" DOI refresh skipped: could not verify DOI exists. Run 'nemar admin doi update --refresh' manually."))}catch(m){if(m instanceof L)p.fail(m.message);else p.fail("Failed to save enrichment"),console.log(u.dim(` ${G(m)}`))}});Oe.addCommand($_);Oe.addCommand(zd);Oe.command("revert").description("Revert a dataset to a previous version (creates PR for review)").argument("<dataset-id>","Dataset ID (e.g., nm000104)").argument("[version]","Target version to revert to (e.g., 1.0.0)").option("--list","List available versions without reverting").option("--force","Direct push to main without PR (emergency only)").option("--message <msg>","Custom revert commit message").option("--dir <path>","Use existing local clone instead of cloning fresh").option(Je,nt).option(yt,ht).action(async(e,t,n)=>{if(!ke())return;let r=await Xb();if(!r.allPassed){console.log(u.red("Error: Missing prerequisites"));for(let v of r.errors)console.log(u.dim(` - ${v}`));return}let o,s=!0;if(n.dir){if(!h1(n.dir)){console.log(u.red(`Error: Directory not found: ${n.dir}`));return}o=n.dir,s=!1}else o=Ml(process.cwd(),`${e}-revert-${Date.now()}`);let i=D("Fetching dataset info...").start(),a;try{a=await Wn(e),i.succeed(`Found dataset: ${a.name}`)}catch(v){if(v instanceof L)if(i.fail(v.message),v.statusCode===404||v.statusCode===400)console.log(u.red(`Error: Dataset ${e} not found`)),console.log(u.dim(` ${v.message}`));else console.log(u.red(`Error: ${v.message}`));else{i.fail("Failed to fetch dataset");let C=v instanceof Error?v.message:String(v);console.log(u.red(`Error: Could not load dataset ${e}: ${C}`))}return}if(!a.github_repo){console.log(u.red("Error: Dataset has no GitHub repository"));return}if(s){let v=D(`Cloning ${e}...`).start(),C=`https://github.com/${a.github_repo}.git`,T=await po(C,o);if(!T.success){v.fail(`Clone failed: ${T.error}`);return}v.succeed(`Cloned to ${o}`)}let c=await Ehe(o);if(c.length===0){console.log(u.yellow("No versions found for this dataset")),console.log(u.dim(" Dataset may not have any tagged releases yet"));return}if(n.list){console.log(`
|
|
1348
|
+
`));let s=await De(`Sync templates on all ${o.length} datasets?`,t);if(s!=="confirmed"){console.log(u.dim(s==="declined"?"Skipped":"Cancelled"));return}let i=0,a=0,c=0;for(let l of o){let d=D(`Syncing ${l.dataset_id}...`).start();try{let f=await sN(l.dataset_id),p=f.changed.length+f.added.length;if(f.errors.length>0)d.warn(`${l.dataset_id}: ${p} updated, ${f.errors.length} error(s)`),c++;else if(p===0)d.succeed(`${l.dataset_id}: up to date`),i++;else{let m=[];if(f.added.length>0)m.push(`+${f.added.length} added`);if(f.changed.length>0)m.push(`~${f.changed.length} updated`);d.succeed(`${l.dataset_id}: ${m.join(", ")}`),a++}}catch(f){let p=f instanceof L?f.message:String(f);d.fail(`${l.dataset_id}: ${p}`),c++}}console.log(),console.log(u.cyan(`Done: ${i} up-to-date, ${a} updated, ${c} with errors`));return}if(!e){console.error(u.red("Error: dataset-id is required (or use --all)"));return}let n=D(`Syncing CI templates for ${e}...`).start();try{let r=await sN(e),o=r.changed.length+r.added.length;if(r.errors.length>0)n.warn(`${e}: ${r.errors.length} error(s)`);else if(o===0)n.succeed(`${e}: already up to date`);else n.succeed(`${e}: synced`);if(console.log(),console.log(` ${u.dim("Checked:")} ${r.checked.join(", ")}`),r.added.length>0)console.log(` ${u.green("Added:")} ${r.added.join(", ")}`);if(r.changed.length>0)console.log(` ${u.yellow("Updated:")} ${r.changed.join(", ")}`);if(!r.committed&&o>0&&r.errors.length===0)console.log(` ${u.yellow("Note:")} listed changes were not committed`);if(r.list_failed)console.log(` ${u.red("Warning:")} workflow directory listing failed; presence is unknown`);if(r.errors.length>0){console.log(` ${u.red("Errors:")}`);for(let s of r.errors)console.log(` - ${s}`)}console.log()}catch(r){Ct(r,n,"Failed to sync CI templates",{404:"Dataset not found"})}});Oe.addCommand(S_);var $_=new de("doi").description("DOI management");$_.command("create").description("Create concept DOI for a dataset").argument("<dataset-id>","Dataset ID (e.g., nm000104)").option("--title <title>","DOI title (defaults to dataset name)").option("--description <desc>","DOI description").option("--provider <provider>","DOI provider: ezid (default) or zenodo","ezid").option("--sandbox","Use sandbox/test DOI").option(Ye,nt).option(yt,ht).action(async(e,t)=>{if(!ke())return;let n=D("Fetching dataset info...").start(),r;try{r=await Wn(e),n.succeed(`Found dataset: ${r.name}`)}catch(c){if(c instanceof L){if(n.fail(c.message),c.statusCode===404)console.log(u.dim(" Dataset not found"))}else n.fail("Failed to fetch dataset");return}try{let c=await jb(e);if(c.concept_doi){if(console.log(u.yellow(`
|
|
1349
|
+
Dataset already has a concept DOI:`)),console.log(` Concept DOI: ${u.cyan(c.concept_doi)}`),c.zenodo_concept_url)console.log(` Zenodo URL: ${c.zenodo_concept_url}`);return}}catch(c){if(process.env.DEBUG)console.error("[debug] DOI info fetch:",c)}if(console.log(),console.log(u.cyan("Dataset Information:")),console.log(` ID: ${r.dataset_id}`),console.log(` Name: ${r.name}`),r.github_repo)console.log(` GitHub: ${r.github_repo}`);if(t.sandbox)console.log(` Mode: ${u.yellow("SANDBOX (test DOI)")}`);console.log();let o=t.provider==="zenodo"?"zenodo":"ezid";if(t.sandbox){if(console.log(u.yellow("\u2501".repeat(60))),console.log(u.yellow.bold(" SANDBOX MODE ENABLED")),console.log(u.yellow("\u2501".repeat(60))),o==="zenodo")console.log(u.yellow(" \u2022 Using Zenodo sandbox (sandbox.zenodo.org)"));else console.log(u.yellow(" \u2022 Using EZID test shoulder (doi:10.5072/FK2)")),console.log(u.yellow(" \u2022 Test DOIs auto-delete after 2 weeks"));console.log(u.yellow(" \u2022 DOI will NOT be indexed by DataCite")),console.log(u.yellow(" \u2022 DOI will NOT resolve in production")),console.log(u.yellow(" \u2022 Use this for testing workflows only")),console.log(u.yellow("\u2501".repeat(60))),console.log()}console.log(u.red("WARNING: DOIs are PERMANENT and cannot be deleted!")),console.log(u.dim("The DOI will be pre-reserved but not published until the first version release.")),console.log(` Provider: ${u.cyan(o.toUpperCase())}`),console.log();let s=t.sandbox?`Create TEST concept DOI via ${o.toUpperCase()} SANDBOX?`:`Create PERMANENT concept DOI via ${o.toUpperCase()} PRODUCTION?`,i=await De(s,t);if(i!=="confirmed"){console.log(u.dim(i==="declined"?"Skipped":"Cancelled"));return}let a=D(`Creating concept DOI via ${o.toUpperCase()}...`).start();try{let c=await lpe(e,{title:t.title,description:t.description,sandbox:t.sandbox,provider:o});a.succeed("Concept DOI created successfully");let l=D("Finalizing repository setup...").start();try{let d=await OS(e);if(d.warnings&&d.warnings.length>0){l.warn("Repository setup finalized with warnings");for(let f of d.warnings)console.log(u.yellow(` Warning: ${f}`))}else l.succeed("Repository setup finalized")}catch(d){if(l.warn("Could not finalize repository setup"),d instanceof L){if(console.log(u.dim(` ${d.message}`)),d.statusCode===403)console.log(u.dim(" Check admin credentials and permissions"))}else console.log(u.dim(` ${d instanceof Error?d.message:"Unknown error"}`))}if(console.log(),console.log(u.green("DOI Information:")),console.log(` Concept DOI: ${u.cyan(c.concept_doi)}`),console.log(` Provider: ${c.provider.toUpperCase()}`),c.provider==="ezid")console.log(` DOI URL: ${c.doi_url}`),console.log(` EZID ID: ${c.ezid_identifier}`);else console.log(` Zenodo URL: ${c.zenodo_url}`);if(c.metadata_warning)console.log(u.yellow(` Warning: ${c.metadata_warning}`));if(console.log(),console.log(u.yellow("Next steps:")),console.log(" 1. Update dataset_description.json with DatasetDOI field"),console.log(" 2. Create a PR and merge it to trigger version DOI publication"),console.log(),t.sandbox)console.log(u.dim("Note: This is a sandbox DOI and will not resolve in production."))}catch(c){if(c instanceof L){if(a.fail(c.message),c.statusCode===403)console.log(u.dim(" This command requires admin privileges"))}else a.fail("Failed to create concept DOI"),console.log(u.dim(` ${G(c)}`))}});$_.command("info").description("Get DOI info for a dataset").argument("<dataset-id>","Dataset ID (e.g., nm000104)").action(async(e)=>{if(!ke())return;let t=D("Fetching DOI info...").start();try{let n=await jb(e);if(t.stop(),console.log(),console.log(u.cyan(`DOI Information for ${e}:`)),console.log(` Dataset Name: ${n.name}`),console.log(),n.concept_doi){if(console.log(u.green("Concept DOI:")),console.log(` DOI: ${n.concept_doi}`),console.log(` URL: https://doi.org/${n.concept_doi}`),console.log(` Provider: ${(n.doi_provider||"zenodo").toUpperCase()}`),n.doi_provider==="ezid"){if(n.ezid_identifier)console.log(` EZID ID: ${n.ezid_identifier}`);if(n.ezid_status){let r=n.ezid_status==="public"?u.green:u.yellow;console.log(` Status: ${r(n.ezid_status)}`)}}if(n.zenodo_concept_url){if(console.log(` Zenodo: ${n.zenodo_concept_url}`),n.zenodo_concept_url.includes("sandbox.zenodo.org"))console.log(),console.log(u.yellow("Mode: SANDBOX (test DOI)")),console.log(u.yellow(" This DOI is not indexed by DataCite and will not resolve in production"))}}else console.log(u.yellow("No concept DOI created yet")),console.log(u.dim(" Use 'nemar admin doi create' to create one"));if(console.log(),n.latest_version_doi)console.log(u.green("Latest Version DOI:")),console.log(` DOI: ${n.latest_version_doi}`),console.log(` URL: https://doi.org/${n.latest_version_doi}`);else if(n.concept_doi)console.log(u.yellow("No version DOI published yet")),console.log(u.dim(" Version DOIs are created automatically on PR merge"))}catch(n){if(n instanceof L){if(t.fail(n.message),n.statusCode===404)console.log(u.dim(" Dataset not found"));else if(n.statusCode===403)console.log(u.dim(" This command requires admin privileges"))}else t.fail("Failed to fetch DOI info")}});$_.command("update").description("Update EZID DOI metadata or status").argument("<dataset-id>","Dataset ID (e.g., nm000104)").option("--make-public","Transition DOI from reserved to public (permanent)").option("--unavailable","Tombstone the concept DOI (EZID _status=unavailable); concept-only, reversible via --make-public. For a full withdrawal (visibility + every version DOI) use 'nemar admin withdraw' instead.").option("--refresh","Refresh metadata from dataset_description.json and .nemar/metadata.json").option(Ye,nt).option(yt,ht).action(async(e,t)=>{if(!ke())return;if(t.makePublic&&t.unavailable){console.log(u.red("Use --make-public or --unavailable, not both."));return}if(!t.makePublic&&!t.unavailable&&!t.refresh){console.log(u.yellow("No action specified. Use --make-public, --unavailable, and/or --refresh."));return}if(t.makePublic){console.log(u.red("WARNING: Making a DOI public is PERMANENT!")),console.log(u.dim(" The DOI will be findable in DataCite and cannot be reverted.")),console.log();let r=await De(`Make DOI for ${e} PUBLIC and permanent?`,t);if(r!=="confirmed"){console.log(u.dim(r==="declined"?"Skipped":"Cancelled"));return}}if(t.unavailable){console.log(u.yellow("This tombstones the concept DOI (EZID _status=unavailable).")),console.log(u.dim(" Reversible with --make-public. Version DOIs are untouched.")),console.log();let r=await De(`Mark DOI for ${e} unavailable (tombstone)?`,t);if(r!=="confirmed"){console.log(u.dim(r==="declined"?"Skipped":"Cancelled"));return}}let n=D("Updating DOI...").start();try{let r=await iN(e,{status:t.makePublic?"public":t.unavailable?"unavailable":void 0,refresh_metadata:t.refresh});n.succeed("DOI updated successfully"),console.log(),console.log(` EZID ID: ${u.cyan(r.ezid_identifier)}`),console.log(` Status: ${r.status==="public"?u.green(r.status):u.yellow(r.status)}`),console.log(` URL: ${r.doi_url}`)}catch(r){if(r instanceof L){if(n.fail(r.message),r.statusCode===400)console.log(u.dim(" DOI update is only supported for EZID-managed DOIs"))}else n.fail("Failed to update DOI"),console.log(u.dim(` ${G(r)}`))}});$_.command("enrich").description("Enrich DOI metadata with ORCIDs, descriptions, funding, and more").argument("<dataset-id>","Dataset ID (e.g., nm000104)").option("--no-llm","Skip LLM-based enrichment from README").option("--sandbox","Use sandbox DOI").option(Ye,nt).option(yt,ht).action(async(e,t)=>{if(!ke())return;let n=D("Fetching dataset and existing enrichment...").start(),r;try{r=await Wn(e),n.succeed(`Dataset: ${r.name}`)}catch(m){if(m instanceof L)n.fail(m.message);else n.fail("Failed to fetch dataset");return}let o,s=!1;try{o=await jb(e)}catch(m){if(m instanceof L&&m.statusCode===404);else s=!0,console.log(u.yellow(` Warning: Could not fetch DOI info: ${G(m)}`))}if(o?.concept_doi)console.log(` DOI: ${u.cyan(o.concept_doi)}`);let i={version:"2.0"};if(r.github_repo){let m=D("Reading existing metadata...").start(),h=await x$e(r.github_repo,".nemar/metadata.json");if(h)try{let g=JSON.parse(h);if(g&&typeof g==="object"&&g.version==="2.0")i=g,m.succeed(`Loaded existing metadata (stage: ${g.pipeline_stage||"unknown"})`);else m.warn("Existing metadata has unsupported version, starting fresh")}catch(g){m.warn(`Could not parse existing metadata (${g instanceof Error?g.message:String(g)}), starting fresh`)}else m.info("No existing .nemar/metadata.json found, starting fresh")}if(t.llm!==!1&&r.github_repo){console.log(),console.log(u.cyan("--- Running LLM enrichment pipeline (CI workflow) ---"));let m=D("Triggering run-enrichment workflow...").start();try{let{spawn:h}=await Promise.resolve(globalThis.Bun),g=r.github_repo,y="nemarDatasets/.github",b="run-enrichment.yml",_=h({cmd:["gh","workflow","run","run-enrichment.yml","--repo","nemarDatasets/.github","--ref","main","-f",`dataset_id=${e}`,"-f","ref=main","-f","force=true"],stdout:"pipe",stderr:"pipe"}),x=await new Response(_.stderr).text();if(await _.exited!==0)throw Error(`Failed to trigger workflow: ${x.trim()}`);m.text="Waiting for workflow to register...",await new Promise((A)=>setTimeout(A,3000)),m.text="Polling workflow status...";let v=60,C="",T=0;for(let A=0;A<v;A++){let F=h({cmd:["gh","run","list","--repo","nemarDatasets/.github","--workflow","run-enrichment.yml","-L","10","--json","databaseId,status,conclusion,displayTitle,event"],stdout:"pipe",stderr:"pipe"}),M=await new Response(F.stdout).text(),U=await new Response(F.stderr).text();if(await F.exited!==0){if(T++,T>=3){m.warn(`gh CLI error: ${U.trim()}`);break}await new Promise((P)=>setTimeout(P,5000));continue}try{let P=JSON.parse(M.trim());T=0;let O=P.find((H)=>H.event==="workflow_dispatch");if(O){if(O.status==="completed"){C=O.conclusion||"unknown";break}m.text=`Workflow ${O.status}... (${A*5}s)`}}catch(P){if(T++,T>=3){m.warn(`Unable to parse workflow status: ${P instanceof Error?P.message:String(P)} (raw: ${M.trim().slice(0,200)})`);break}}await new Promise((P)=>setTimeout(P,5000))}let z=!1;if(!C)m.warn("Workflow timed out after 5 minutes (may still be running)");else if(C==="success"){m.succeed("LLM enrichment workflow completed successfully");let A=await x$e(g,".nemar/metadata.json");if(A)try{let F=JSON.parse(A);if(F&&typeof F==="object"&&F.version==="2.0"){Object.assign(i,F),z=!0;let M=F.pipeline_stage||"unknown";if(console.log(u.dim(` Pipeline stage: ${M}`)),i.authors){let U=Object.keys(i.authors).length;console.log(u.dim(` Authors: ${U}`))}}}catch(F){console.log(u.yellow(` Warning: Could not parse updated metadata: ${F instanceof Error?F.message:String(F)}`)),console.log(u.dim(" Using pre-workflow enrichment data"))}else console.log(u.yellow(" Warning: Could not fetch updated metadata after successful workflow.")),console.log(u.dim(" Author data below may be from a previous run."))}else m.fail(`LLM enrichment workflow failed (conclusion: ${C})`);if(!z)console.log(u.yellow(" ORCID discovery did not complete. Authors below may be from previous metadata."))}catch(h){m.fail("LLM enrichment pipeline failed"),console.log(u.dim(` ${G(h)}`)),console.log(u.yellow(" ORCID discovery did not run. You will need to enter ORCIDs manually."))}}console.log(),console.log(u.cyan("--- Author ORCIDs ---"));let a=i.authors||{},c=Object.keys(a);if(c.length>0){let m=c.filter((g)=>a[g]?.orcid),h=c.filter((g)=>!a[g]?.orcid);console.log(u.dim(` Discovered ${c.length} authors from pipeline:`));for(let g of m)console.log(u.green(` [x] ${g}: ${a[g]?.orcid}`));for(let g of h)console.log(u.yellow(` [ ] ${g}: no ORCID found`));if(h.length>0)console.log(u.dim(` ${h.length} author(s) missing ORCIDs.`))}let{updateAuthors:l}=await Ae.prompt([{type:"confirm",name:"updateAuthors",message:c.length>0?"Add or correct author ORCIDs?":"Add author ORCIDs manually?",default:!1}]);if(l){let m={},h=!0;while(h){let{authorName:g}=await Ae.prompt([{type:"input",name:"authorName",message:'Author name (as in BIDS, e.g., "Shirazi, Yahya"):'}]);if(!g)break;let y=a[g];if(y?.orcid)console.log(u.dim(` Current ORCID: ${y.orcid}`));let{orcid:b}=await Ae.prompt([{type:"input",name:"orcid",message:`ORCID for "${g}" (Enter to ${y?.orcid?"keep current":"skip"}):`,validate:(v)=>{if(!v)return!0;return DS.test(v)||"Invalid ORCID format (XXXX-XXXX-XXXX-XXXX)"}}]),_={};if(b)_.orcid=b;let{affiliation:x}=await Ae.prompt([{type:"input",name:"affiliation",message:`Affiliation for "${g}" (optional):`}]);if(x)_.affiliations=[{name:x}];if(_.orcid||_.affiliations)m[g]=_;let{more:k}=await Ae.prompt([{type:"confirm",name:"more",message:"Add another author?",default:!0}]);h=k}if(Object.keys(m).length>0){let g={...i.authors||{}};for(let[y,b]of Object.entries(m)){let _=g[y]||{};g[y]={..._,...b,orcid:b.orcid||_.orcid}}i.authors=g}}console.log(),console.log(u.cyan("--- Dataset stats ---"));let d=D("Computing dataset sizes and formats...").start();try{let m=await Sme(e),h=Ut(m.total_size);i.sizes=[`${h} (${m.file_count} files)`],i.formats=m.extensions,d.succeed(`Sizes: ${h} (${m.file_count} files), Formats: ${m.extensions.join(", ")}`)}catch(m){d.warn("Could not compute dataset stats"),console.log(u.dim(` ${G(m)}`))}console.log(),console.log(u.cyan("--- Review ---")),console.log(JSON.stringify(i,null,2)),console.log();let f=await De("Commit to repo and refresh DOI?",t,!0);if(f!=="confirmed"){console.log(u.dim(f==="declined"?"Skipped":"Cancelled"));return}let p=D("Saving enrichment...").start();try{let m=await qme(e,i);if(p.succeed(m.message),m.bidsignore_updated)console.log(u.dim(" .bidsignore updated to include .nemar/"));if(!o&&s)try{o=await jb(e)}catch(h){if(process.env.DEBUG)console.error("[debug] DOI info re-fetch:",h)}if(o?.ezid_identifier){let h=D("Refreshing DOI metadata...").start();try{await iN(e,{refresh_metadata:!0}),h.succeed("DOI metadata refreshed")}catch(g){h.warn("Could not refresh DOI metadata"),console.log(u.dim(` ${G(g)}`))}}else if(s)console.log(u.yellow(" DOI refresh skipped: could not verify DOI exists. Run 'nemar admin doi update --refresh' manually."))}catch(m){if(m instanceof L)p.fail(m.message);else p.fail("Failed to save enrichment"),console.log(u.dim(` ${G(m)}`))}});Oe.addCommand($_);Oe.addCommand(zd);Oe.command("revert").description("Revert a dataset to a previous version (creates PR for review)").argument("<dataset-id>","Dataset ID (e.g., nm000104)").argument("[version]","Target version to revert to (e.g., 1.0.0)").option("--list","List available versions without reverting").option("--force","Direct push to main without PR (emergency only)").option("--message <msg>","Custom revert commit message").option("--dir <path>","Use existing local clone instead of cloning fresh").option(Ye,nt).option(yt,ht).action(async(e,t,n)=>{if(!ke())return;let r=await Xb();if(!r.allPassed){console.log(u.red("Error: Missing prerequisites"));for(let v of r.errors)console.log(u.dim(` - ${v}`));return}let o,s=!0;if(n.dir){if(!h1(n.dir)){console.log(u.red(`Error: Directory not found: ${n.dir}`));return}o=n.dir,s=!1}else o=Ml(process.cwd(),`${e}-revert-${Date.now()}`);let i=D("Fetching dataset info...").start(),a;try{a=await Wn(e),i.succeed(`Found dataset: ${a.name}`)}catch(v){if(v instanceof L)if(i.fail(v.message),v.statusCode===404||v.statusCode===400)console.log(u.red(`Error: Dataset ${e} not found`)),console.log(u.dim(` ${v.message}`));else console.log(u.red(`Error: ${v.message}`));else{i.fail("Failed to fetch dataset");let C=v instanceof Error?v.message:String(v);console.log(u.red(`Error: Could not load dataset ${e}: ${C}`))}return}if(!a.github_repo){console.log(u.red("Error: Dataset has no GitHub repository"));return}if(s){let v=D(`Cloning ${e}...`).start(),C=`https://github.com/${a.github_repo}.git`,T=await po(C,o);if(!T.success){v.fail(`Clone failed: ${T.error}`);return}v.succeed(`Cloned to ${o}`)}let c=await Ehe(o);if(c.length===0){console.log(u.yellow("No versions found for this dataset")),console.log(u.dim(" Dataset may not have any tagged releases yet"));return}if(n.list){console.log(`
|
|
1350
1350
|
${u.cyan("Available Versions:")}
|
|
1351
1351
|
`);for(let v of c)console.log(` ${u.green(v.version)} ${u.dim(v.date)} ${u.dim(v.commit)}`);return}let l=t;if(!l){console.log(`
|
|
1352
1352
|
${u.cyan("Available Versions:")}
|
|
@@ -1400,8 +1400,8 @@ Deletion summary:`)),console.log(` GitHub repo: ${s.steps.github.success?u.gree
|
|
|
1400
1400
|
Warnings:`));for(let i of s.warnings)console.log(u.yellow(` - ${i}`))}}catch(r){Ct(r,n,"Failed to delete dataset",{403:"Published datasets can only be deleted by the NEMAR owner",404:"Dataset not found",409:"Cannot delete dataset with active publication requests"}),process.exit(1)}});Oe.command("bulk-delete").description("Delete multiple phantom/orphaned datasets at once (owner only)").argument("<dataset-ids>","Comma-separated dataset IDs (e.g., nm000153,nm000154,nm000155)").option("--yes","Skip confirmation prompt").action(async(e,t)=>{if(!ke())return;let n=e.split(",").map((o)=>o.trim()).filter(Boolean);if(n.length===0)console.log(u.red("No dataset IDs provided.")),process.exit(1);if(console.log(u.bold(`
|
|
1401
1401
|
Bulk delete: ${n.length} datasets`)),console.log(u.dim(` IDs: ${n.slice(0,10).join(", ")}${n.length>10?` ... +${n.length-10} more`:""}`)),console.log(u.yellow(`
|
|
1402
1402
|
Only private datasets without DOIs will be deleted.`)),!t.yes){let{proceed:o}=await Ae.prompt([{type:"confirm",name:"proceed",message:u.red(`Delete ${n.length} datasets? This cannot be undone.`),default:!1}]);if(!o){console.log(u.dim("Cancelled."));return}}let r=D(`Deleting ${n.length} datasets...`).start();try{let o=await mpe(n);if(r.succeed(`Bulk delete complete: ${o.deleted} deleted, ${o.failed} failed`),o.failed>0){console.log(u.yellow(`
|
|
1403
|
-
Failed deletions:`));for(let s of o.results.filter((i)=>!i.deleted))console.log(u.yellow(` ${s.dataset_id}: ${s.error||"unknown error"}`))}}catch(o){Ct(o,r,"Bulk delete failed",{403:"Only the NEMAR owner can bulk-delete datasets"}),process.exit(1)}});function I$e(){let e=Ml(import.meta.dir,"..","..","scripts","withdrawn-datasets.json");if(h1(e))return e;return Ml(import.meta.dir,"..","scripts","withdrawn-datasets.json")}function N$e(e,t,n,r){if(r){console.log(` ${u.red("error".padEnd(8))} ${t}: ${r}`);return}if(!n)return;if("skipped"in n){console.log(` ${u.yellow("skipped".padEnd(8))} ${t}: ${n.skipped}`);return}let o=n.resumed?u.yellow(" (resumed)"):"";console.log(u.bold(` ${e}${t}${o}`));let s=n.visibility.status==="failed"?u.red:u.green;if(console.log(` visibility: ${s(n.visibility.status)}`),n.visibility.status==="failed"){if(console.log(u.red(` stage=${n.visibility.stage}: ${n.visibility.error}`)),"githubReverted"in n.visibility){let i="s3Reverted"in n.visibility?` s3Reverted=${n.visibility.s3Reverted}`:"",a=n.visibility.revertError?` revertError=${n.visibility.revertError}`:"";console.log(u.dim(` githubReverted=${n.visibility.githubReverted}${i}${a}`))}}for(let i of n.dois){let a=i.status==="failed"?u.red:i.status==="planned"?u.yellow:u.green,c=i.kind==="version"?`version ${i.version}`:"concept";if(console.log(` ${a(i.status.padEnd(8))} ${c} -> ${i.action} ${u.dim(i.doi)}`),i.error)console.log(u.red(` ${i.error}`))}if(n.warning)console.log(u.yellow(` warning: ${n.warning}`))}Oe.command("withdraw").description("Withdraw a broken published dataset: make it private and tombstone its EZID DOIs (concept + every version). Dry-run by default.").argument("[ids...]","Dataset id(s) to withdraw (omit when using --all)").option("--all","Target the still-withdrawn entries on the checked-in list").option("--reason <reason>","Withdrawal reason (default: the list entry's own reason)").option("--execute","Actually apply the withdrawal (default is a dry run)").option("--force","Allow a dataset id that is not on the checked-in withdrawn-datasets list").option("--withdrawn-file <path>","Path to the withdrawn-datasets JSON (default: scripts/withdrawn-datasets.json)").option(
|
|
1404
|
-
WARNING: this makes ${s.length} dataset(s) private and tombstones their EZID DOIs (concept + every version).`));let l=await De(`Execute withdrawal for ${s.length} dataset(s)?`,t);if(l!=="confirmed"){console.log(u.dim(l==="declined"?"Skipped":"Cancelled"));return}}let c=[];for(let l of s)try{let d=await upe(l.datasetId,{reason:l.reason,dryRun:i});c.push({dataset_id:l.datasetId,result:d})}catch(d){c.push({dataset_id:l.datasetId,error:G(d)})}if(t.json){console.log(JSON.stringify(c,null,2));return}console.log();for(let l of c)N$e(a,l.dataset_id,l.result,l.error)});Oe.command("restore").description("Reverse a withdrawal: make a dataset public again and restore its EZID DOIs (concept + every version). Dry-run by default.").argument("[ids...]","Dataset id(s) to restore (omit when using --all)").option("--all","Target the still-withdrawn entries on the checked-in list").option("--execute","Actually apply the restore (default is a dry run)").option("--withdrawn-file <path>","Path to the withdrawn-datasets JSON (default: scripts/withdrawn-datasets.json)").option(
|
|
1403
|
+
Failed deletions:`));for(let s of o.results.filter((i)=>!i.deleted))console.log(u.yellow(` ${s.dataset_id}: ${s.error||"unknown error"}`))}}catch(o){Ct(o,r,"Bulk delete failed",{403:"Only the NEMAR owner can bulk-delete datasets"}),process.exit(1)}});function I$e(){let e=Ml(import.meta.dir,"..","..","scripts","withdrawn-datasets.json");if(h1(e))return e;return Ml(import.meta.dir,"..","scripts","withdrawn-datasets.json")}function N$e(e,t,n,r){if(r){console.log(` ${u.red("error".padEnd(8))} ${t}: ${r}`);return}if(!n)return;if("skipped"in n){console.log(` ${u.yellow("skipped".padEnd(8))} ${t}: ${n.skipped}`);return}let o=n.resumed?u.yellow(" (resumed)"):"";console.log(u.bold(` ${e}${t}${o}`));let s=n.visibility.status==="failed"?u.red:u.green;if(console.log(` visibility: ${s(n.visibility.status)}`),n.visibility.status==="failed"){if(console.log(u.red(` stage=${n.visibility.stage}: ${n.visibility.error}`)),"githubReverted"in n.visibility){let i="s3Reverted"in n.visibility?` s3Reverted=${n.visibility.s3Reverted}`:"",a=n.visibility.revertError?` revertError=${n.visibility.revertError}`:"";console.log(u.dim(` githubReverted=${n.visibility.githubReverted}${i}${a}`))}}for(let i of n.dois){let a=i.status==="failed"?u.red:i.status==="planned"?u.yellow:u.green,c=i.kind==="version"?`version ${i.version}`:"concept";if(console.log(` ${a(i.status.padEnd(8))} ${c} -> ${i.action} ${u.dim(i.doi)}`),i.error)console.log(u.red(` ${i.error}`))}if(n.warning)console.log(u.yellow(` warning: ${n.warning}`))}Oe.command("withdraw").description("Withdraw a broken published dataset: make it private and tombstone its EZID DOIs (concept + every version). Dry-run by default.").argument("[ids...]","Dataset id(s) to withdraw (omit when using --all)").option("--all","Target the still-withdrawn entries on the checked-in list").option("--reason <reason>","Withdrawal reason (default: the list entry's own reason)").option("--execute","Actually apply the withdrawal (default is a dry run)").option("--force","Allow a dataset id that is not on the checked-in withdrawn-datasets list").option("--withdrawn-file <path>","Path to the withdrawn-datasets JSON (default: scripts/withdrawn-datasets.json)").option(Ye,nt).option(yt,ht).option("--json","Output raw JSON").action(async(e,t)=>{if(!ke())return;if(e.length===0&&!t.all)console.log(u.red("Error: provide dataset id(s) or use --all")),process.exit(1);if(e.length>0&&t.all)console.log(u.red("Error: provide dataset id(s) OR --all, not both")),process.exit(1);let n=t.withdrawnFile||I$e(),r;try{r=QN(n)}catch(l){console.error(u.red(`Failed to load withdrawn-datasets file: ${G(l)}`)),process.exit(1)}let o=t.all?{targets:ZN(r).map((l)=>({datasetId:l.dataset_id,reason:t.reason||l.reason}))}:Lye(e,r,{reason:t.reason,force:t.force});if("error"in o)console.error(u.red(o.error)),process.exit(1);let s=o.targets,i=!t.execute,a=i?"[dry-run] ":"";if(!i){console.log(u.red(`
|
|
1404
|
+
WARNING: this makes ${s.length} dataset(s) private and tombstones their EZID DOIs (concept + every version).`));let l=await De(`Execute withdrawal for ${s.length} dataset(s)?`,t);if(l!=="confirmed"){console.log(u.dim(l==="declined"?"Skipped":"Cancelled"));return}}let c=[];for(let l of s)try{let d=await upe(l.datasetId,{reason:l.reason,dryRun:i});c.push({dataset_id:l.datasetId,result:d})}catch(d){c.push({dataset_id:l.datasetId,error:G(d)})}if(t.json){console.log(JSON.stringify(c,null,2));return}console.log();for(let l of c)N$e(a,l.dataset_id,l.result,l.error)});Oe.command("restore").description("Reverse a withdrawal: make a dataset public again and restore its EZID DOIs (concept + every version). Dry-run by default.").argument("[ids...]","Dataset id(s) to restore (omit when using --all)").option("--all","Target the still-withdrawn entries on the checked-in list").option("--execute","Actually apply the restore (default is a dry run)").option("--withdrawn-file <path>","Path to the withdrawn-datasets JSON (default: scripts/withdrawn-datasets.json)").option(Ye,nt).option(yt,ht).option("--json","Output raw JSON").action(async(e,t)=>{if(!ke())return;if(e.length===0&&!t.all)console.log(u.red("Error: provide dataset id(s) or use --all")),process.exit(1);if(e.length>0&&t.all)console.log(u.red("Error: provide dataset id(s) OR --all, not both")),process.exit(1);let n;if(t.all){let i=t.withdrawnFile||I$e();try{n=ZN(QN(i)).map((a)=>a.dataset_id)}catch(a){console.error(u.red(`Failed to load withdrawn-datasets file: ${G(a)}`)),process.exit(1)}}else n=e;let r=!t.execute,o=r?"[dry-run] ":"";if(!r){console.log(u.yellow(`
|
|
1405
1405
|
This makes ${n.length} dataset(s) public again and restores their EZID DOIs.`));let i=await De(`Execute restore for ${n.length} dataset(s)?`,t);if(i!=="confirmed"){console.log(u.dim(i==="declined"?"Skipped":"Cancelled"));return}}let s=[];for(let i of n)try{let a=await dpe(i,{dryRun:r});s.push({dataset_id:i,result:a})}catch(a){s.push({dataset_id:i,error:G(a)})}if(t.json){console.log(JSON.stringify(s,null,2));return}console.log();for(let i of s)N$e(o,i.dataset_id,i.result,i.error)});var VAt=30;function GAt(e,t=VAt){if(e.length===0)return[];if(e.length<=t)return[e];let n=[];for(let r=0;r<e.length;r+=t)n.push(e.slice(r,r+t));return n}function WAt(e,t){return["--field",`openneuro_ids=${e.join(",")}`,...t!==void 0?["--field",`openneuro_tag=${t}`]:[]]}function KAt(e,t,n){if(e===void 0)return null;if(!Jo(e))return`Invalid --tag "${e}". Expected an OpenNeuro snapshot tag such as 1.0.1.`;if(t.length!==1)return"--tag applies to a single dataset ID";if(n!==void 0&&n!=="prepare")return"--tag is only valid with --phase prepare";return null}async function F$e(e,t){await Promise.resolve().then(() => qt());let r=GAt(e);if(r.length>1)console.log(u.dim(` Splitting ${e.length} datasets into ${r.length} dispatches (matrix job cap).`));for(let o=0;o<r.length;o++){let s=r[o],i=await R(["gh","workflow","run","onboard-openneuro.yml","--repo","nemarDatasets/.github",...WAt(s,t)]);if(i.exitCode!==0)return{ok:!1,error:`chunk ${o+1}/${r.length} (${s.join(",")}): ${i.stderr.trim()}`}}return{ok:!0}}Oe.command("annex-normalize <datasetId>").description("Move data an existing dataset keeps in git into the annex, and put NEMAR's annex policy in force (ADR 0060)").option("--dry-run","Clone and report what would change; touch nothing").option("--dir <path>","Working directory for the clone (reuse it to resume without re-cloning)").option("--no-push","Do everything except push, for a rehearsal").option("--normalize-max-gb <n>","Raise the ceiling on how much data will be uploaded from this host (default 5 GiB)").option("--via-aws-cli","Move the content with `aws s3 sync` rather than git-annex's S3 client, using whatever the aws CLI on this machine is already configured with. Faster for a large migration, and the only option on a host with no NEMAR credentials; the default path mints credentials scoped to this dataset instead.").option("-y, --yes","Skip the confirmation prompt").addHelpText("after",`
|
|
1406
1406
|
What this does (ADR 0060, issue #1159):
|
|
1407
1407
|
1. clones the dataset (full clone -- data in git has to be present to upload)
|
|
@@ -1451,7 +1451,7 @@ Upload dir: ${n.upload_dir}`)),console.log(u.dim(`Clone dir: ${n.clone_dir}`));
|
|
|
1451
1451
|
Import Jobs (${r.total})
|
|
1452
1452
|
`)),console.log(` ${u.yellow(`in-flight ${(s.preparing??0)+(s.copying??0)+(s.finalizing??0)}`)} ${u.green(`complete ${s.complete??0}`)} ${u.magenta(`incomplete ${s.incomplete??0}`)} ${u.red(`failed ${s.failed??0}`)} ${u.red(`quarantined ${s.quarantined??0}`)} ${u.dim(`rolled_back ${s.rolled_back??0}`)}
|
|
1453
1453
|
`),r.withdrawn)console.log(` ${u.red(`withdrawn ${r.withdrawn}`)} ${u.dim("(included in complete; content removed and DOI tombstoned)")}
|
|
1454
|
-
`);if(o.length===0){console.log(u.dim(" No import jobs match."));return}console.log(u.dim(` ${"ID".padEnd(12)} ${"Source".padEnd(12)} ${"Stage".padEnd(10)} ${"Status".padEnd(12)} ${"Updated".padEnd(20)}`)),console.log(u.dim(` ${"\u2500".repeat(70)}`));for(let i of o){let a=i.status==="complete"?u.green:i.status==="failed"||i.status==="quarantined"?u.red:i.status==="rolled_back"?u.dim:i.status==="incomplete"?u.magenta:u.yellow,c=i.updated_at?new Date(i.updated_at).toLocaleString():"-";if(console.log(` ${i.dataset_id.padEnd(12)} ${(i.source_id||"-").padEnd(12)} ${i.stage.padEnd(10)} ${a(i.status.padEnd(12))} ${c}`),i.last_error)console.log(u.red(` ${i.last_error}`));if(i.workflow_run_url)console.log(u.dim(` run: ${i.workflow_run_url}`));if(i.blocklisted)console.log(u.magenta(` blocklisted (${i.blocklist_reason??"unknown"}); recovery_attempts=${i.recovery_attempts}; next_retry=${i.next_retry_at??"-"}${i.maintainer_notified_at?`; maintainer notified ${i.maintainer_notified_at}`:""}`));else if(i.status==="incomplete"||i.status==="failed")console.log(u.dim(` recovery_attempts=${i.recovery_attempts}; next_retry=${i.next_retry_at??"-"}`))}}catch(r){n.fail("Failed to fetch import status"),console.error(u.red(G(r)))}});D_.command("rollback").description("Roll back a failed/quarantined import (deletes repo + S3 + D1)").argument("<dataset-id>","NEMAR dataset id (e.g., on007523)").action(async(e)=>{if(!ke())return;let{proceed:t}=await Ae.prompt([{type:"confirm",name:"proceed",message:u.red(`Roll back import ${e}? This deletes the GitHub repo, S3 objects, and D1 records. This cannot be undone.`),default:!1}]);if(!t){console.log(u.dim("Cancelled."));return}let n=D(`Rolling back ${e}...`).start();try{let r=await bpe(e);if(!r.rolled_back){n.fail(`Rollback incomplete for ${e} (kept quarantined); retry after fixing:`);for(let o of r.warnings)console.log(u.red(` - ${o}`))}else if(r.warnings.length>0){n.warn(`Rolled back ${e} with warnings`);for(let o of r.warnings)console.log(u.yellow(` - ${o}`))}else n.succeed(`Rolled back ${e}`)}catch(r){n.fail(`Failed to roll back ${e}`),console.error(u.red(G(r)))}});D_.command("retry").description("Reset a failed/quarantined import to 'preparing' for re-dispatch").argument("<dataset-id>","NEMAR dataset id (e.g., on007523)").action(async(e)=>{if(!ke())return;let t=D(`Resetting ${e}...`).start();try{await wpe(e),t.succeed(`${e} reset to 'preparing'. Re-run the onboard-openneuro workflow to retry.`)}catch(n){t.fail(`Failed to reset ${e}`),console.error(u.red(G(n)))}});D_.command("verify").description("Force a per-key S3 integrity check now (seeds the retry lane or confirms health)").argument("<dataset-id>","NEMAR dataset id (e.g., on007523)").action(async(e)=>{if(!ke())return;let t=D(`Verifying ${e} against S3...`).start();try{let n=await cN(e);if(n.complete)t.succeed(`${e} verified complete (${n.presentCount}/${n.expectedCount} objects present)`);else if(n.expectedCount===0)t.warn(`${e} not verifiable: no published manifest to compare against (${n.presentCount} object(s) in the bucket)`);else{t.warn(`${e} incomplete: ${n.missingKeys.length}/${n.expectedCount} object(s) missing${n.zeroByteKeys.length>0?` (${n.zeroByteKeys.length} zero-byte)`:""}`);for(let r of n.missingKeys.slice(0,20))console.log(u.dim(` ${r}`));if(n.missingKeys.length>20)console.log(u.dim(` ... and ${n.missingKeys.length-20} more`))}}catch(n){t.fail(`Failed to verify ${e}`),console.error(u.red(G(n)))}});Oe.addCommand(D_);function M$e(){let e=Ml(import.meta.dir,"..","..","scripts","recover-datasets.json");if(h1(e))return e;return Ml(import.meta.dir,"..","scripts","recover-datasets.json")}var mL=new de("recover").description("Re-copy epic #967 OpenNeuro imports published with 0-byte content, whose upstream is accessible (Phase 5, #972). Dry-run by default.");mL.argument("[ids...]","Dataset id(s) to recover (omit when using --all)").option("--all","Target every entry in the checked-in recover-datasets list").option("--execute","Actually verify + dispatch the re-copy (default is a dry run)").option("--force","Allow a dataset id that is not on the checked-in recover-datasets list").option("--recover-file <path>","Path to the recover-datasets JSON (default: scripts/recover-datasets.json)").option(
|
|
1454
|
+
`);if(o.length===0){console.log(u.dim(" No import jobs match."));return}console.log(u.dim(` ${"ID".padEnd(12)} ${"Source".padEnd(12)} ${"Stage".padEnd(10)} ${"Status".padEnd(12)} ${"Updated".padEnd(20)}`)),console.log(u.dim(` ${"\u2500".repeat(70)}`));for(let i of o){let a=i.status==="complete"?u.green:i.status==="failed"||i.status==="quarantined"?u.red:i.status==="rolled_back"?u.dim:i.status==="incomplete"?u.magenta:u.yellow,c=i.updated_at?new Date(i.updated_at).toLocaleString():"-";if(console.log(` ${i.dataset_id.padEnd(12)} ${(i.source_id||"-").padEnd(12)} ${i.stage.padEnd(10)} ${a(i.status.padEnd(12))} ${c}`),i.last_error)console.log(u.red(` ${i.last_error}`));if(i.workflow_run_url)console.log(u.dim(` run: ${i.workflow_run_url}`));if(i.blocklisted)console.log(u.magenta(` blocklisted (${i.blocklist_reason??"unknown"}); recovery_attempts=${i.recovery_attempts}; next_retry=${i.next_retry_at??"-"}${i.maintainer_notified_at?`; maintainer notified ${i.maintainer_notified_at}`:""}`));else if(i.status==="incomplete"||i.status==="failed")console.log(u.dim(` recovery_attempts=${i.recovery_attempts}; next_retry=${i.next_retry_at??"-"}`))}}catch(r){n.fail("Failed to fetch import status"),console.error(u.red(G(r)))}});D_.command("rollback").description("Roll back a failed/quarantined import (deletes repo + S3 + D1)").argument("<dataset-id>","NEMAR dataset id (e.g., on007523)").action(async(e)=>{if(!ke())return;let{proceed:t}=await Ae.prompt([{type:"confirm",name:"proceed",message:u.red(`Roll back import ${e}? This deletes the GitHub repo, S3 objects, and D1 records. This cannot be undone.`),default:!1}]);if(!t){console.log(u.dim("Cancelled."));return}let n=D(`Rolling back ${e}...`).start();try{let r=await bpe(e);if(!r.rolled_back){n.fail(`Rollback incomplete for ${e} (kept quarantined); retry after fixing:`);for(let o of r.warnings)console.log(u.red(` - ${o}`))}else if(r.warnings.length>0){n.warn(`Rolled back ${e} with warnings`);for(let o of r.warnings)console.log(u.yellow(` - ${o}`))}else n.succeed(`Rolled back ${e}`)}catch(r){n.fail(`Failed to roll back ${e}`),console.error(u.red(G(r)))}});D_.command("retry").description("Reset a failed/quarantined import to 'preparing' for re-dispatch").argument("<dataset-id>","NEMAR dataset id (e.g., on007523)").action(async(e)=>{if(!ke())return;let t=D(`Resetting ${e}...`).start();try{await wpe(e),t.succeed(`${e} reset to 'preparing'. Re-run the onboard-openneuro workflow to retry.`)}catch(n){t.fail(`Failed to reset ${e}`),console.error(u.red(G(n)))}});D_.command("verify").description("Force a per-key S3 integrity check now (seeds the retry lane or confirms health)").argument("<dataset-id>","NEMAR dataset id (e.g., on007523)").action(async(e)=>{if(!ke())return;let t=D(`Verifying ${e} against S3...`).start();try{let n=await cN(e);if(n.complete)t.succeed(`${e} verified complete (${n.presentCount}/${n.expectedCount} objects present)`);else if(n.expectedCount===0)t.warn(`${e} not verifiable: no published manifest to compare against (${n.presentCount} object(s) in the bucket)`);else{t.warn(`${e} incomplete: ${n.missingKeys.length}/${n.expectedCount} object(s) missing${n.zeroByteKeys.length>0?` (${n.zeroByteKeys.length} zero-byte)`:""}`);for(let r of n.missingKeys.slice(0,20))console.log(u.dim(` ${r}`));if(n.missingKeys.length>20)console.log(u.dim(` ... and ${n.missingKeys.length-20} more`))}}catch(n){t.fail(`Failed to verify ${e}`),console.error(u.red(G(n)))}});Oe.addCommand(D_);function M$e(){let e=Ml(import.meta.dir,"..","..","scripts","recover-datasets.json");if(h1(e))return e;return Ml(import.meta.dir,"..","scripts","recover-datasets.json")}var mL=new de("recover").description("Re-copy epic #967 OpenNeuro imports published with 0-byte content, whose upstream is accessible (Phase 5, #972). Dry-run by default.");mL.argument("[ids...]","Dataset id(s) to recover (omit when using --all)").option("--all","Target every entry in the checked-in recover-datasets list").option("--execute","Actually verify + dispatch the re-copy (default is a dry run)").option("--force","Allow a dataset id that is not on the checked-in recover-datasets list").option("--recover-file <path>","Path to the recover-datasets JSON (default: scripts/recover-datasets.json)").option(Ye,nt).option(yt,ht).option("--json","Output raw JSON").addHelpText("after",`
|
|
1455
1455
|
Description:
|
|
1456
1456
|
Re-dispatches the hardened OpenNeuro copy path (epic #967 Phases 1-3) for
|
|
1457
1457
|
datasets published with 0-byte content whose OpenNeuro upstream is still
|
|
@@ -1520,7 +1520,7 @@ Examples:
|
|
|
1520
1520
|
$ nemar admin fleet require-review --all --prefix nm --limit 50 --after nm000312 --apply
|
|
1521
1521
|
$ nemar admin fleet require-review nm000456 --remove --apply # roll one dataset back
|
|
1522
1522
|
`).action(async(e,t)=>{let n=Boolean(t.json);if(!mn(n))return;let r=(m,h)=>dt(m,{json:n,answered:!0,hint:h});if(e&&t.all)return r("Name a dataset OR use --all, not both.");if(!e&&!t.all)return r("Name a dataset, or use --all for a page of datasets.");if(!t.all&&(t.prefix!==void 0||t.after!==void 0||t.limit!==void 0))return r("--prefix, --after and --limit go with --all.");let o;if(t.limit!==void 0){if(o=/^\d+$/.test(t.limit)?Number.parseInt(t.limit,10):Number.NaN,!(o>=1&&o<=50))return r("--limit is a number from 1 to 50.")}let s=t.prefix===void 0?void 0:Ufe(t.prefix,n);if(s===null)return;let i=t.after===void 0?void 0:Hfe(t.after,n);if(i===null)return;let a=e?Xa(e,n):null;if(e&&!a)return;let c=!t.apply,l=Boolean(t.remove),d=c?"[dry run] ":"",f=n?null:D(`${d}Reading the review ruleset...`).start(),p=Gn(!1);try{if(a){let x=await Npe(a,{dryRun:c,remove:l});if(n){console.log(JSON.stringify(x,null,2));return}if(f?.stop(),p(`${d}${S$e(x,c)}`),p(u.dim(` The dataset is ${x.reviewable?"one the automated review covers":`not reviewed (${q$e[x.not_reviewable_because??""]??"not covered"})`}; the ruleset is to be ${x.intent==="require"?"put on":"taken off"}.`)),c&&x.payload){p(""),p(" The body that would be sent to GitHub:");for(let k of JSON.stringify(x.payload,null,2).split(`
|
|
1523
|
-
`))p(` ${k}`)}if(c&&x.intent==="require")p(""),p(E$e(x));if(c&&!x.review_enabled&&x.intent==="require")p(""),p(u.yellow(" The automated review is off in this environment (PR_REVIEW_ENABLED is not 1), so --apply would be refused: nothing would post the check. --remove --apply is not refused."));if(p(""),x.action==="skip")p(u.yellow("Nothing was changed: the default branch has to be main first. `nemar admin fleet drift` lists such repositories as DEFAULT_BRANCH_OUTLIER."));else if(c)p(u.dim("Dry run: nothing was changed. Add --apply to change it."));else p(x.applied?u.green("Done."):u.dim("Nothing needed to change."));return}let m=await Fpe({prefix:s,after:i,limit:o,dryRun:c,remove:l});if(n){if(console.log(JSON.stringify(m,null,2)),m.results.some((x)=>x.error))process.exitCode=1;return}f?.stop();let h=m.results[0]?.dataset_id,g=m.results[m.results.length-1]?.dataset_id;p(`${d}${m.count} dataset(s)${h&&g?` (${h} to ${g})`:""}${l?", taking the ruleset off":""}`);for(let x of m.results)p(` ${S$e(x,c)}`);let y=new Map;for(let x of m.results){let k=x.error?"error":x.action?L$e[x.action][c?"dry":"done"]:"unknown";y.set(k,(y.get(k)??0)+1)}p(""),p([...y.entries()].map(([x,k])=>`${k} ${x}`).join(", ")||u.dim("No datasets matched."));let b=new Set;for(let x of m.results)if(x.code&&x.error&&B$e[x.code]&&!b.has(x.code))b.add(x.code),p(u.yellow(I(x.error)));let _=m.results.filter((x)=>x.intent==="require").length;if(c&&_>0)p(E$e(m));if(c&&!m.review_enabled&&_>0)p(u.yellow(`The automated review is off in this environment (PR_REVIEW_ENABLED is not 1), so --apply would refuse the ${_} dataset(s) that would get the ruleset, and still take it off the rest. --remove --apply is not refused.`));if(m.next_after){let x=["nemar admin fleet require-review --all",t.prefix?`--prefix ${t.prefix}`:"",`--limit ${m.limit}`,`--after ${m.next_after}`,l?"--remove":"",c?"":"--apply"].filter(Boolean).join(" ");p(u.dim(`Next page: ${x}`))}if(c)p(u.dim("Dry run: nothing was changed. Add --apply to change it."));if(m.results.some((x)=>x.error))process.exitCode=1}catch(m){yr(m,f,"The review ruleset request failed",a?void 0:{403:QAt},{json:n})}});var by=(e)=>new Promise((t)=>setTimeout(t,e));async function ZAt(e,t,n){let r=Date.now()+t,o="no probe completed";while(Date.now()<r){try{let s=(await ag(e,!0)).result?.steps?.branch_ruleset;if(s?.status==="ok")return{status:"green"};if(s?.detail)o=s.detail}catch(s){o=s instanceof L?s.message:String(s)}await by(n)}return{status:"timeout",detail:o}}Vd.command("revalidate").description("Re-run BIDS validation on main HEAD for unprotected datasets, then optionally enforce (epic #713)").argument("[dataset-id]","Dataset to revalidate (omit when using --all/--prefix)").option("--all","Revalidate across unprotected public datasets").option("--prefix <prefix>","Filter by id prefix (with --all), e.g. nm000 / on").option("--enforce","After a dataset goes green, run enforce (dry-run unless --apply)").option("--apply","With --enforce, actually apply the ruleset (default is a dry run)").option("--force","Override the live-dataset guard (nm000103-107)").option("--limit <n>","Max repos for --all/--prefix (default 25)","25").option("--json","Output raw JSON").action(async(e,t)=>{if(!ze())console.log(u.red("Error: Not authenticated")),process.exit(1);let n=Boolean(t.all||!e&&t.prefix);if(!e&&!n)console.log(u.red("Error: provide a dataset-id, or --all/--prefix")),process.exit(1);let r;if(e)r=[e];else{let d=D("Fetching dataset list...").start();try{let f=[];for(let m=0;;m+=200){let h=await fd({limit:200,offset:m});if(f.push(...h.datasets),h.datasets.length<200||f.length>=h.total_count)break}let p=Number.parseInt(t.limit,10)||25;r=dhe(f,{prefix:t.prefix}).slice(0,p),d.succeed(`${r.length} target(s) (from ${f.length} datasets)`)}catch(f){Ct(f,d,"Failed to fetch datasets");return}}let o=Boolean(t.enforce),s=Boolean(t.apply),i={revalidated:0,green:0,locked:0,stillRed:0,skipped:0,errors:0},a=[],c=[],l=0;for(let d of r){if(l++,al.has(d)&&!t.force){console.log(` [${l}/${r.length}] ${u.dim(`${d}: skip (live; use --force)`)}`),i.skipped++;continue}try{let f=await Mpe(d,t.force);if(a.push(f),f.skipped)console.log(` [${l}/${r.length}] ${d}: ${u.dim(`skipped (${f.skipped})`)}`),i.skipped++;else i.revalidated++,c.push(d),console.log(` [${l}/${r.length}] ${d}: ${u.cyan(`revalidating (${f.triggered_by})`)}`)}catch(f){i.errors++,console.log(` [${l}/${r.length}] ${d}: ${u.red(f instanceof L?f.message:String(f))}`)}if(l<r.length)await by(4000)}if(o&&c.length>0)if(e){let d=c[0],f=D(`Waiting for ${d} validation to land...`).start(),p=await ZAt(d,300000,15000);if(p.status!=="green")f.warn(`${d}: not green within 5m \u2014 last: ${p.detail} (real errors or still running)`),i.stillRed++;else if(i.green++,!s)f.succeed(`${d}: green (would lock; pass --apply)`);else{let m=await ag(d,!1);if(m.result?.steps?.branch_ruleset?.status==="ok")f.succeed(`${d}: LOCKED`),i.locked++;else f.warn(`${d}: enforce ${m.result?.steps?.branch_ruleset?.status??"?"}`)}}else{let d=D("Waiting ~90s for validations to drain...").start();await by(90000),d.text="Enforcing green datasets...";for(let f of c)try{if((await ag(f,!0)).result?.steps?.branch_ruleset?.status!=="ok"){i.stillRed++;continue}if(i.green++,s){if((await ag(f,!1)).result?.steps?.branch_ruleset?.status==="ok")i.locked++}}catch{i.errors++}d.stop()}if(t.json){console.log(JSON.stringify({tally:i,raw:a},null,2));return}console.log(),console.log(u.cyan(`Done: revalidated=${i.revalidated} green=${i.green} locked=${i.locked} still-red=${i.stillRed} skipped=${i.skipped} errors=${i.errors}`))});Vd.command("annex-policy").description("Report, and optionally fix, dataset repos that NEMAR's annex policy does not actually govern (#1374, ADR 0060)").argument("[dataset-id...]","Specific datasets to act on (omit to sweep by prefix)").option("--prefix <prefix>","Dataset id prefix to sweep (default on: the imported fleet)","on").option("--limit <n>","Act on at most this many datasets, in id order").option("--apply","Make the change (default is a read-only report)").option("--include-data","Also move data a repo keeps in git, which uploads to S3").option("--via-aws-cli","With --include-data, move the bytes with this machine's aws CLI").option("--no-push","With --apply, commit locally and push nothing (a rehearsal)").option("--dir <path>","Where clones go while they are being fixed (default: a temp dir)").option("--keep-clones","Do not delete each clone after its dataset is done").option("--concurrency <n>","Parallel GitHub reads during the scan (default 4)","4").option("--json <path>","Write the full report as JSON").option("--force","Include the live datasets (nm000103-107)").option(
|
|
1523
|
+
`))p(` ${k}`)}if(c&&x.intent==="require")p(""),p(E$e(x));if(c&&!x.review_enabled&&x.intent==="require")p(""),p(u.yellow(" The automated review is off in this environment (PR_REVIEW_ENABLED is not 1), so --apply would be refused: nothing would post the check. --remove --apply is not refused."));if(p(""),x.action==="skip")p(u.yellow("Nothing was changed: the default branch has to be main first. `nemar admin fleet drift` lists such repositories as DEFAULT_BRANCH_OUTLIER."));else if(c)p(u.dim("Dry run: nothing was changed. Add --apply to change it."));else p(x.applied?u.green("Done."):u.dim("Nothing needed to change."));return}let m=await Fpe({prefix:s,after:i,limit:o,dryRun:c,remove:l});if(n){if(console.log(JSON.stringify(m,null,2)),m.results.some((x)=>x.error))process.exitCode=1;return}f?.stop();let h=m.results[0]?.dataset_id,g=m.results[m.results.length-1]?.dataset_id;p(`${d}${m.count} dataset(s)${h&&g?` (${h} to ${g})`:""}${l?", taking the ruleset off":""}`);for(let x of m.results)p(` ${S$e(x,c)}`);let y=new Map;for(let x of m.results){let k=x.error?"error":x.action?L$e[x.action][c?"dry":"done"]:"unknown";y.set(k,(y.get(k)??0)+1)}p(""),p([...y.entries()].map(([x,k])=>`${k} ${x}`).join(", ")||u.dim("No datasets matched."));let b=new Set;for(let x of m.results)if(x.code&&x.error&&B$e[x.code]&&!b.has(x.code))b.add(x.code),p(u.yellow(I(x.error)));let _=m.results.filter((x)=>x.intent==="require").length;if(c&&_>0)p(E$e(m));if(c&&!m.review_enabled&&_>0)p(u.yellow(`The automated review is off in this environment (PR_REVIEW_ENABLED is not 1), so --apply would refuse the ${_} dataset(s) that would get the ruleset, and still take it off the rest. --remove --apply is not refused.`));if(m.next_after){let x=["nemar admin fleet require-review --all",t.prefix?`--prefix ${t.prefix}`:"",`--limit ${m.limit}`,`--after ${m.next_after}`,l?"--remove":"",c?"":"--apply"].filter(Boolean).join(" ");p(u.dim(`Next page: ${x}`))}if(c)p(u.dim("Dry run: nothing was changed. Add --apply to change it."));if(m.results.some((x)=>x.error))process.exitCode=1}catch(m){yr(m,f,"The review ruleset request failed",a?void 0:{403:QAt},{json:n})}});var by=(e)=>new Promise((t)=>setTimeout(t,e));async function ZAt(e,t,n){let r=Date.now()+t,o="no probe completed";while(Date.now()<r){try{let s=(await ag(e,!0)).result?.steps?.branch_ruleset;if(s?.status==="ok")return{status:"green"};if(s?.detail)o=s.detail}catch(s){o=s instanceof L?s.message:String(s)}await by(n)}return{status:"timeout",detail:o}}Vd.command("revalidate").description("Re-run BIDS validation on main HEAD for unprotected datasets, then optionally enforce (epic #713)").argument("[dataset-id]","Dataset to revalidate (omit when using --all/--prefix)").option("--all","Revalidate across unprotected public datasets").option("--prefix <prefix>","Filter by id prefix (with --all), e.g. nm000 / on").option("--enforce","After a dataset goes green, run enforce (dry-run unless --apply)").option("--apply","With --enforce, actually apply the ruleset (default is a dry run)").option("--force","Override the live-dataset guard (nm000103-107)").option("--limit <n>","Max repos for --all/--prefix (default 25)","25").option("--json","Output raw JSON").action(async(e,t)=>{if(!ze())console.log(u.red("Error: Not authenticated")),process.exit(1);let n=Boolean(t.all||!e&&t.prefix);if(!e&&!n)console.log(u.red("Error: provide a dataset-id, or --all/--prefix")),process.exit(1);let r;if(e)r=[e];else{let d=D("Fetching dataset list...").start();try{let f=[];for(let m=0;;m+=200){let h=await fd({limit:200,offset:m});if(f.push(...h.datasets),h.datasets.length<200||f.length>=h.total_count)break}let p=Number.parseInt(t.limit,10)||25;r=dhe(f,{prefix:t.prefix}).slice(0,p),d.succeed(`${r.length} target(s) (from ${f.length} datasets)`)}catch(f){Ct(f,d,"Failed to fetch datasets");return}}let o=Boolean(t.enforce),s=Boolean(t.apply),i={revalidated:0,green:0,locked:0,stillRed:0,skipped:0,errors:0},a=[],c=[],l=0;for(let d of r){if(l++,al.has(d)&&!t.force){console.log(` [${l}/${r.length}] ${u.dim(`${d}: skip (live; use --force)`)}`),i.skipped++;continue}try{let f=await Mpe(d,t.force);if(a.push(f),f.skipped)console.log(` [${l}/${r.length}] ${d}: ${u.dim(`skipped (${f.skipped})`)}`),i.skipped++;else i.revalidated++,c.push(d),console.log(` [${l}/${r.length}] ${d}: ${u.cyan(`revalidating (${f.triggered_by})`)}`)}catch(f){i.errors++,console.log(` [${l}/${r.length}] ${d}: ${u.red(f instanceof L?f.message:String(f))}`)}if(l<r.length)await by(4000)}if(o&&c.length>0)if(e){let d=c[0],f=D(`Waiting for ${d} validation to land...`).start(),p=await ZAt(d,300000,15000);if(p.status!=="green")f.warn(`${d}: not green within 5m \u2014 last: ${p.detail} (real errors or still running)`),i.stillRed++;else if(i.green++,!s)f.succeed(`${d}: green (would lock; pass --apply)`);else{let m=await ag(d,!1);if(m.result?.steps?.branch_ruleset?.status==="ok")f.succeed(`${d}: LOCKED`),i.locked++;else f.warn(`${d}: enforce ${m.result?.steps?.branch_ruleset?.status??"?"}`)}}else{let d=D("Waiting ~90s for validations to drain...").start();await by(90000),d.text="Enforcing green datasets...";for(let f of c)try{if((await ag(f,!0)).result?.steps?.branch_ruleset?.status!=="ok"){i.stillRed++;continue}if(i.green++,s){if((await ag(f,!1)).result?.steps?.branch_ruleset?.status==="ok")i.locked++}}catch{i.errors++}d.stop()}if(t.json){console.log(JSON.stringify({tally:i,raw:a},null,2));return}console.log(),console.log(u.cyan(`Done: revalidated=${i.revalidated} green=${i.green} locked=${i.locked} still-red=${i.stillRed} skipped=${i.skipped} errors=${i.errors}`))});Vd.command("annex-policy").description("Report, and optionally fix, dataset repos that NEMAR's annex policy does not actually govern (#1374, ADR 0060)").argument("[dataset-id...]","Specific datasets to act on (omit to sweep by prefix)").option("--prefix <prefix>","Dataset id prefix to sweep (default on: the imported fleet)","on").option("--limit <n>","Act on at most this many datasets, in id order").option("--apply","Make the change (default is a read-only report)").option("--include-data","Also move data a repo keeps in git, which uploads to S3").option("--via-aws-cli","With --include-data, move the bytes with this machine's aws CLI").option("--no-push","With --apply, commit locally and push nothing (a rehearsal)").option("--dir <path>","Where clones go while they are being fixed (default: a temp dir)").option("--keep-clones","Do not delete each clone after its dataset is done").option("--concurrency <n>","Parallel GitHub reads during the scan (default 4)","4").option("--json <path>","Write the full report as JSON").option("--force","Include the live datasets (nm000103-107)").option(Ye,nt).option(yt,ht).addHelpText("after",`
|
|
1524
1524
|
Two things govern what git-annex takes, and an imported dataset has neither (#1374):
|
|
1525
1525
|
upstream's .gitattributes outranks NEMAR's configured expression, and the expression
|
|
1526
1526
|
was never written to the git-annex branch at all. The scan reads both from GitHub
|
|
@@ -1644,9 +1644,9 @@ Examples:
|
|
|
1644
1644
|
Read-only: nothing was copied. Add --apply to recover.`));else if(d.recoveredKeys>0)console.log(u.dim("\nThe location log still says nothing about these objects: run `nemar admin fleet key-registration <id> --apply` to record them."));if(d.tally.failed>0)process.exitCode=1});Oe.addCommand(Vd);var U$e=new de("reindex").description("Refresh dataset metadata: enrichment + first-class D1 columns");U$e.argument("[dataset-id]","Dataset ID to reindex (e.g., nm000103)").option("--all","Reindex every dataset with a GitHub repo").option("--missing-metadata","Reindex only datasets with NULL metadata columns").option("--stale","Reindex only datasets whose metadata is older than --older-than days").option("--older-than <days>","Threshold in days. Default 30 for --stale, 1 (24h) for --missing-metadata recency guard.").option("--skip-enrichment","Skip the LLM enrichment step").option("--skip-sync","Skip the D1 metadata-column refresh step").option("--ref <ref>","Ref to enrich from (single-dataset only; default: main)").option("--dry-run","List matched datasets without firing the reindex (bulk only)").option("--json","Print the raw JSON response instead of the summary").action(async(e,t)=>{if(!ke())return;let n=[t.all,t.missingMetadata,t.stale].filter(Boolean).length;if(e&&n>0)console.error(u.red("Provide either a dataset-id OR a bulk flag (--all/--missing-metadata/--stale), not both")),process.exit(1);if(!e&&n===0)console.error(u.red("Provide a dataset-id or one of: --all, --missing-metadata, --stale")),process.exit(1);if(n>1)console.error(u.red("Use only one of --all, --missing-metadata, --stale")),process.exit(1);if(t.skipEnrichment&&t.skipSync)console.error(u.red("--skip-enrichment and --skip-sync cannot both be set")),process.exit(1);if(e){let f=D(`Reindexing ${e}...`).start();try{let p={skip_enrichment:t.skipEnrichment===!0,skip_sync:t.skipSync===!0,...t.ref&&{ref:t.ref}},m=await ig(e,p),h=m.enrichment.status!=="failed"&&m.sync.status!=="failed";if(t.json){if(f.stop(),console.log(JSON.stringify(m,null,2)),!h)process.exit(1);return}if(h)f.succeed(`${e} reindexed`);else f.warn(`${e} reindexed with errors`);if(console.log(),k$e(m,{showRef:!0}),!h)process.exit(1)}catch(p){f.fail(`Failed to reindex ${e}`),console.error(u.red(G(p))),process.exit(1)}return}let r=t.all?"all":t.missingMetadata?"missing-metadata":"stale",o={skip_enrichment:t.skipEnrichment===!0,skip_sync:t.skipSync===!0,dry_run:t.dryRun===!0};if(t.olderThan!==void 0){let f=Number.parseInt(t.olderThan,10);if(!Number.isFinite(f)||f<0)console.error(u.red(`Invalid --older-than: "${t.olderThan}"`)),process.exit(1);o.older_than_days=f}else if(r==="missing-metadata")o.older_than_days=1;else if(r==="stale")o.older_than_days=30;let s=t.dryRun?`Listing ${r} datasets...`:`Reindexing ${r} datasets...`,i=D(s).start(),a;try{a=await xpe(r,o)}catch(f){i.fail("Bulk reindex failed"),console.error(u.red(G(f))),process.exit(1)}if(t.json){if(i.stop(),console.log(JSON.stringify(a,null,2)),(a.results??[]).some((p)=>p.enrichment.status==="failed"||p.sync.status==="failed"))process.exit(1);return}if(a.dry_run){if(i.succeed(`${a.total} datasets match filter=${r} (dry run, no changes)`),a.datasets)for(let f of a.datasets)console.log(u.dim(` - ${f}`));return}let c=a.results??[],l=c.filter((f)=>f.enrichment.status!=="failed"&&f.sync.status!=="failed").length,d=c.length-l;if(d===0)i.succeed(`${c.length}/${c.length} datasets reindexed in ${(a.elapsed_ms/1000).toFixed(1)}s`);else i.warn(`${l}/${c.length} ok; ${d} failed in ${(a.elapsed_ms/1000).toFixed(1)}s`);console.log();for(let f of c)k$e(f);if(d>0)process.exit(1)});Oe.addCommand(U$e);var e2t=new de("availability-report").description("Report how much of a dataset's declared data is present in S3, and exactly which files are missing + why (#1000). Dry-run by default. --all backfills every non-sandbox dataset that has a version and no report yet (#1001).").argument("[dataset-id]","Dataset ID (e.g., nm000103)").option("--write","Commit the report to .nemar/availability-report.json on main (default: preview only)").option("--all","Backfill every non-sandbox dataset that has a version and no report yet, instead of a single one (#1001)").option("--missing-only","With --all, sweep only datasets already known incomplete (data_complete=0)").option("--limit <n>","With --all, datasets per batch (server clamps to [1,30])","10").option("--reset","With --all, clear every stamped sweep row so it re-sweeps from scratch").option("--verbose","With --all, print per-batch progress").option("--json","Output raw JSON").action(async(e,t)=>{if(!ke())return;if(!e&&!t.all)console.error(u.red("Provide a dataset-id or --all")),process.exit(1);if(e&&(t.all||t.reset||t.missingOnly))console.error(u.red("--all/--reset/--missing-only cannot be combined with a dataset id")),process.exit(1);if(e){let l=D(t.write?`Generating and writing availability report for ${e}...`:`Previewing availability report for ${e}...`).start(),d;try{d=await Ape(e,{write:t.write===!0})}catch(g){l.fail(`Failed to generate availability report for ${e}`),console.error(u.red(G(g))),process.exit(1)}let f="report"in d?d.report:d,p="report"in d;if(l.succeed(p?`${e}: availability report written to .nemar/availability-report.json`:`${e}: availability report (dry run, not written)`),t.json){console.log(JSON.stringify(d,null,2));return}if(console.log(),f.version===null)console.log(u.yellow(" No published version manifest to compare against; completeness unknown."));else console.log(` Version: ${f.version}`);console.log(` Complete: ${f.complete?u.green("yes"):u.red("no")}`),console.log(` Files: ${f.completeness.files_present}/${f.completeness.files_declared} present`);let m=`${Ut(f.completeness.bytes_present)}/${Ut(f.completeness.bytes_declared)}`,h=f.completeness.pct_bytes!=null?` (${(f.completeness.pct_bytes*100).toFixed(1)}%)`:"";if(console.log(` Bytes: ${m}${h}`),f.blocklist_reason)console.log(u.yellow(` Blocklisted: ${f.blocklist_reason}`));if(f.missing.length>0){console.log(),console.log(u.dim(` Missing (${f.missing.length}):`));for(let g of f.missing)console.log(u.dim(` - ${g.path} [${g.reason}]`))}return}if(t.reset){let l=D("Resetting availability-report sweep state...").start();try{let d=await Tpe();if(l.succeed(`Cleared ${d.reset} stamped row(s); eligible datasets are candidates again`),t.json)console.log(JSON.stringify(d,null,2))}catch(d){l.fail("Reset failed"),console.error(u.red(G(d))),process.exit(1)}return}let n=Number.parseInt(t.limit??"10",10)||10,r=t.missingOnly===!0,o={processed:0,written:0,errors:0},s=D("Sweeping datasets for availability reports...").start(),i=0,a=null,c=null;try{let l;do{if(l=await Ope({limit:n,missingOnly:r}),i++,o.processed+=l.processed,o.written+=l.written,o.errors+=l.errors.length,a=l.remaining,t.verbose){s.stop(),console.log(` [batch ${i}] processed=${l.processed} written=${l.written} errors=${l.errors.length} remaining=${a??"?"}`);for(let d of l.errors)console.log(` ${u.red(d.dataset_id)}: ${d.error}`);s.start("Sweeping datasets for availability reports...")}else s.text=`Sweeping datasets for availability reports... ${o.processed} processed, ${a??"?"} remaining`;if(a!=null&&c!=null&&a>=c){s.warn(`No progress (remaining stuck at ${a}); stopping - see errors`);break}if(c=a,(a??0)>0)await by(1000)}while((a??0)>0);s.stop()}catch(l){s.fail("Availability-report sweep failed"),console.error(u.red(G(l))),process.exit(1)}if(t.json)console.log(JSON.stringify({...o,batches:i,remaining:a},null,2));else{if(console.log(),a===null)console.log(u.yellow("Warning: backend returned a null remaining count; the sweep may be incomplete - check server logs."));console.log(u.cyan(`Done in ${i} batch(es): processed=${o.processed} written=${o.written} errors=${o.errors} remaining=${a??"unknown"}`))}if(o.errors>0||a===null)process.exit(1)});Oe.addCommand(e2t);async function hL(e,t,n,r){let o=0,s=null,i=null;try{let a;do{if(a=await n(),o++,s=a.remaining,r(a,o,s),s!=null&&i!=null&&s>=i){e.warn(`No progress (remaining stuck at ${s}); stopping - see errors`);break}if(i=s,(s??0)>0)await by(1000)}while((s??0)>0);e.stop()}catch(a){e.fail(t),console.error(u.red(G(a))),process.exit(1)}return{batches:o,remaining:s}}var H$e=new de("hed-sweep").description("Backfill HED detection (has_hed / hed_version) for existing datasets (#869)");H$e.option("--limit <n>","Datasets per batch (server clamps to [1,30])","15").option("--reset","Clear every probed HED row so a corrected detector can re-sweep").option("--verbose","Print per-batch progress").option("--json","Output raw JSON instead of the human summary").action(async(e)=>{if(!ke())return;if(e.reset){let i=D("Resetting HED sweep state...").start();try{let a=await kpe();if(i.succeed(`Cleared ${a.reset} probed HED row(s); eligible datasets are candidates again`),e.json)console.log(JSON.stringify(a,null,2))}catch(a){i.fail("Reset failed"),console.error(u.red(G(a))),process.exit(1)}return}let t=Number.parseInt(e.limit??"15",10)||15,n={processed:0,withHed:0,withoutHed:0,unknown:0,errors:0},r=D("Sweeping datasets for HED...").start(),{batches:o,remaining:s}=await hL(r,"HED sweep failed",()=>vpe({limit:t}),(i,a,c)=>{if(n.processed+=i.processed,n.withHed+=i.withHed,n.withoutHed+=i.withoutHed,n.unknown+=i.unknown,n.errors+=i.errors.length,e.verbose){r.stop(),console.log(` [batch ${a}] processed=${i.processed} hed=${i.withHed} no-hed=${i.withoutHed} unknown=${i.unknown} errors=${i.errors.length} remaining=${c??"?"}`);for(let l of i.errors)console.log(` ${u.red(l.dataset_id)}: ${l.error}`);r.start("Sweeping datasets for HED...")}else r.text=`Sweeping datasets for HED... ${n.processed} processed, ${c??"?"} remaining`});if(e.json)console.log(JSON.stringify({...n,batches:o,remaining:s},null,2));else{if(console.log(),s===null)console.log(u.yellow("Warning: backend returned a null remaining count; the sweep may be incomplete - check server logs."));console.log(u.cyan(`Done in ${o} batch(es): processed=${n.processed} hed=${n.withHed} no-hed=${n.withoutHed} unknown=${n.unknown} errors=${n.errors} remaining=${s??"unknown"}`))}if(n.errors>0||s===null)process.exit(1)});Oe.addCommand(H$e);var z$e=new de("recording-stats-sweep").description("Backfill dataset-level recording duration/count/channel-range stats from each dataset's zarr index (migration 0070, #1146)");z$e.option("--limit <n>","Datasets per batch (server clamps to [1,200])","50").option("--reset","Clear every stamped recording-stats row so it re-sweeps from scratch").option("--verbose","Print per-batch progress").option("--json","Output raw JSON instead of the human summary").action(async(e)=>{if(!ke())return;if(e.reset){let i=D("Resetting recording-stats sweep state...").start();try{let a=await Spe();if(i.succeed(`Cleared ${a.reset} stamped recording-stats row(s); eligible datasets are candidates again`),e.json)console.log(JSON.stringify(a,null,2))}catch(a){i.fail("Reset failed"),console.error(u.red(G(a))),process.exit(1)}return}let t=Number.parseInt(e.limit??"50",10)||50,n={processed:0,measured:0,unmeasured:0,errors:0},r=D("Sweeping datasets for recording stats...").start(),{batches:o,remaining:s}=await hL(r,"Recording-stats sweep failed",()=>Epe({limit:t}),(i,a,c)=>{if(n.processed+=i.processed,n.measured+=i.measured,n.unmeasured+=i.unmeasured,n.errors+=i.errors.length,e.verbose){r.stop(),console.log(` [batch ${a}] processed=${i.processed} measured=${i.measured} unmeasured=${i.unmeasured} errors=${i.errors.length} remaining=${c??"?"}`);for(let l of i.errors)console.log(` ${u.red(l.dataset_id)}: ${l.error}`);r.start("Sweeping datasets for recording stats...")}else r.text=`Sweeping datasets for recording stats... ${n.processed} processed, ${c??"?"} remaining`});if(e.json)console.log(JSON.stringify({...n,batches:o,remaining:s},null,2));else{if(console.log(),s===null)console.log(u.yellow("Warning: backend returned a null remaining count; the sweep may be incomplete - check server logs."));console.log(u.cyan(`Done in ${o} batch(es): processed=${n.processed} measured=${n.measured} unmeasured=${n.unmeasured} errors=${n.errors} remaining=${s??"unknown"}`))}if(n.errors>0||s===null)process.exit(1)});Oe.addCommand(z$e);var V$e=new de("signal-defaults-sweep").description("Backfill BIDS signal defaults (sampling frequency, power line frequency, EEG reference, placement scheme) from each dataset's exemplar sidecar (migrations 0072/0073, #1153)");V$e.option("--limit <n>","Datasets per batch (server clamps to [1,30])","15").option("--reset","Clear every stamped signal-defaults row so it re-sweeps from scratch").option("--verbose","Print per-batch progress").option("--json","Output raw JSON instead of the human summary").action(async(e)=>{if(!ke())return;if(e.reset){let i=D("Resetting signal-defaults sweep state...").start();try{let a=await Dpe();if(i.succeed(`Cleared ${a.reset} stamped signal-defaults row(s); eligible datasets are candidates again`),e.json)console.log(JSON.stringify(a,null,2))}catch(a){i.fail("Reset failed"),console.error(u.red(G(a))),process.exit(1)}return}let t=Number.parseInt(e.limit??"15",10)||15,n={processed:0,populated:0,noData:0,errors:0},r=D("Sweeping datasets for signal defaults...").start(),{batches:o,remaining:s}=await hL(r,"Signal-defaults sweep failed",()=>$pe({limit:t}),(i,a,c)=>{if(n.processed+=i.processed,n.populated+=i.populated,n.noData+=i.noData,n.errors+=i.errors.length,e.verbose){r.stop(),console.log(` [batch ${a}] processed=${i.processed} populated=${i.populated} no-data=${i.noData} errors=${i.errors.length} remaining=${c??"?"}`);for(let l of i.errors)console.log(` ${u.red(l.dataset_id)}: ${l.error}`);r.start("Sweeping datasets for signal defaults...")}else r.text=`Sweeping datasets for signal defaults... ${n.processed} processed, ${c??"?"} remaining`});if(e.json)console.log(JSON.stringify({...n,batches:o,remaining:s},null,2));else{if(console.log(),s===null)console.log(u.yellow("Warning: backend returned a null remaining count; the sweep may be incomplete - check server logs."));console.log(u.cyan(`Done in ${o} batch(es): processed=${n.processed} populated=${n.populated} no-data=${n.noData} errors=${n.errors} remaining=${s??"unknown"}`))}if(n.errors>0||s===null)process.exit(1)});Oe.addCommand(V$e);async function t2t(e,t,n){let r=e(),o={processed:0,complete:0,incomplete:0,unknown:0,errors:0},s=0,i=null,a=null,c=!1;do{let l=await t(r);if(s++,o.processed+=l.processed,o.complete+=l.complete,o.incomplete+=l.incomplete,o.unknown+=l.unknown,o.errors+=l.errors.length,i=l.remaining,n?.onBatch?.(l,o,s),i!=null&&a!=null&&i>=a){c=!0;break}if(a=i,(i??0)>0)await n?.sleepBetweenBatches?.()}while((i??0)>0);return{batches:s,totals:o,remaining:i,stalled:c}}var G$e=new de("data-integrity-sweep").description("Audit datasets against their version manifest and backfill data_complete / bytes_present (epic #967 Phase 3, #970)");G$e.option("--limit <n>","Datasets per batch (server clamps to [1,30])","15").option("--older-than <days>","Also re-audit rows checked more than N days ago (periodic re-audit, not just the one-shot drain)").option("--reaudit","Re-verify every already-checked row using an anchored cutoff so the sweep fully converges to 0 (unlike --older-than's moving now()-relative window, which never reaches 0 on its own)").option("--reset","Clear every audited row so a corrected verifier can re-sweep").option("--verbose","Print per-batch progress").option("--json","Output raw JSON instead of the human summary").action(async(e)=>{if(!ke())return;if(e.reset){let c=D("Resetting data-integrity sweep state...").start();try{let l=await Cpe();if(c.succeed(`Cleared ${l.reset} audited row(s); eligible datasets are candidates again`),e.json)console.log(JSON.stringify(l,null,2))}catch(l){c.fail("Reset failed"),console.error(u.red(G(l))),process.exit(1)}return}let t=Number.parseInt(e.limit??"15",10)||15,n=e.olderThan?Number.parseInt(e.olderThan,10):void 0,r=D("Sweeping datasets for data integrity...").start(),o;try{if(o=await t2t(()=>e.reaudit?new Date().toISOString():void 0,async(c)=>{let l=await Rpe({limit:t,olderThan:n,before:c});return{processed:l.processed,complete:l.complete,incomplete:l.incomplete,unknown:l.unknown,errors:l.errors,remaining:l.remaining}},{onBatch:(c,l,d)=>{if(e.verbose){r.stop(),console.log(` [batch ${d}] processed=${c.processed} complete=${c.complete} incomplete=${c.incomplete} unknown=${c.unknown} errors=${c.errors.length} remaining=${c.remaining??"?"}`);for(let f of c.errors)console.log(` ${u.red(f.dataset_id)}: ${f.error}`);r.start("Sweeping datasets for data integrity...")}else r.text=`Sweeping datasets for data integrity... ${l.processed} processed, ${c.remaining??"?"} remaining`},sleepBetweenBatches:()=>by(1000)}),o.stalled)r.warn(`No progress (remaining stuck at ${o.remaining}); stopping - see errors`);else r.stop()}catch(c){r.fail("Data-integrity sweep failed"),console.error(u.red(G(c))),process.exit(1)}let{batches:s,totals:i,remaining:a}=o;if(e.json)console.log(JSON.stringify({...i,batches:s,remaining:a},null,2));else{if(console.log(),a===null)console.log(u.yellow("Warning: backend returned a null remaining count; the sweep may be incomplete - check server logs."));if(console.log(u.cyan(`Done in ${s} batch(es): processed=${i.processed} complete=${i.complete} incomplete=${i.incomplete} unknown=${i.unknown} errors=${i.errors} remaining=${a??"unknown"}`)),i.incomplete>0)console.log(u.yellow(`${i.incomplete} dataset(s) verified incomplete -- see 'nemar dataset list --json' (data_complete=0) for details.`))}if(i.errors>0||a===null)process.exit(1)});Oe.addCommand(G$e);var W$e=new de("zarr-fidelity-sweep").description("Re-verify published Zarr stores against their dataset's own BIDS metadata (#1068)");W$e.option("--limit <n>","Datasets per batch (server clamps to [1,25])","25").option("--json","Output raw JSON instead of the human summary").action(async(e)=>{if(!ke())return;let t=Number.parseInt(e.limit??"25",10)||25,n=D("Verifying Zarr store fidelity...").start(),r;try{r=await Wpe({limit:t}),n.stop()}catch(o){n.fail("Zarr fidelity sweep failed"),console.error(u.red(G(o))),process.exit(1);return}if(e.json)console.log(JSON.stringify(r,null,2));else{console.log(),console.log(u.cyan(`processed=${r.processed} verified=${r.verified} failed=${r.failed} unverifiable=${r.unverifiable} errors=${r.errors.length} remaining=${r.remaining??"unknown"}${r.budget_exhausted?" budget_exhausted=true":""}`));for(let o of r.results){let s=o.verdict==="verified"?u.green:o.verdict==="failed"?u.red:u.yellow;console.log(` ${s(o.verdict.padEnd(12))} ${o.dataset_id} (sampled=${o.sampled} checked=${o.checked})`);for(let i of o.examples)console.log(` ${u.red(i.code)}: ${i.path}`);if(o.examples_truncated)console.log(` ${u.dim(`(${o.mismatch_count} mismatches total; showing first ${o.examples.length})`)}`)}for(let o of r.errors)console.log(` ${u.red("error")} ${o.dataset_id}: ${o.error}`)}if(r.errors.length>0||r.remaining===null||r.budget_exhausted)process.exit(1)});Oe.addCommand(W$e);var n2t=250,K$e=new de("upstream-backfill").description("Record which upstream snapshot each mirrored version came from (dry run unless --execute)");K$e.option("--execute","Write the results; without it nothing is recorded").option("--limit <n>","Version rows per batch (server clamps to [1,50])","25").option("--after <cursor>","Resume after this key, e.g. on000123@1.0.0 (skips a stuck row)").option("--max-batches <n>","Stop after this many batches","200").option("--json","Output one JSON summary instead of progress lines").action(async(e)=>{if(!ke())return;let t=Number.parseInt(e.limit??"25",10)||25,n=Number.parseInt(e.maxBatches??"200",10)||200,r=e.execute===!0,o=(m)=>{if(!e.json)console.log(m)};if(!r)o(u.yellow("Dry run: nothing is written. Pass --execute to record."));o(u.dim("A recorded 'unknown' is final: it is never examined again. A read that fails or whose 404 a control read does not confirm is not recorded."));let s={batches:0,scanned:0,recorded:{doi:0,unknown:0},not_examined:0,unparseable:0,absent:0,skipped_existing:0},i=[],a=e.after,c=null,l=null,d=!1;for(let m=0;m<n;m++){let h;try{h=await Kpe({execute:r,limit:t,after:a})}catch(g){l=G(g);break}c=h,s.batches++,s.scanned+=h.scanned,s.recorded.doi+=h.recorded.doi,s.recorded.unknown+=h.recorded.unknown,s.not_examined+=h.not_examined,s.unparseable+=h.unparseable,s.absent+=h.absent,s.skipped_existing+=h.skipped_existing,i.push(...h.errors),o(`${u.cyan(`batch ${s.batches}`)} scanned=${h.scanned} ${r?"recorded":"would record"} doi=${h.recorded.doi} unknown=${h.recorded.unknown} not_examined=${h.not_examined} remaining=${h.remaining}`);for(let g of h.unknown_samples)o(` ${u.dim("unknown")} ${g.dataset_id}@${g.version}: ${g.reason}`);for(let g of h.errors)o(` ${u.red("error")} ${g.dataset_id}@${g.version}${g.kind==="needs_admin"?" [needs admin]":""}: ${g.error}`);if(!h.ok){d=h.suspect_credential,l=h.error??"the batch failed",a=h.next_cursor??a;break}if(a=h.next_cursor??void 0,!h.next_cursor)break;await new Promise((g)=>setTimeout(g,n2t))}let f=l===null&&c!==null&&c.next_cursor===null,p=f?null:a??null;if(e.json)console.log(JSON.stringify({execute:r,done:f,failure:l,suspect_credential:d,...s,errors:i,next_cursor:p,counts:c?.counts??null},null,2));else{if(l)console.error(u.red(`Stopped: ${l}`));if(!f&&!l)console.log(u.yellow(`Stopped at --max-batches ${n}; the pass is not done.`));if(p)console.log(`Resume with: --after ${p}`);if(f&&s.not_examined>0){let m=i.filter((g)=>g.kind==="needs_admin"),h=s.not_examined-m.length;if(h>0)console.log(u.yellow(`${h} row(s) were not examined after a transient error: rerun without --after to try them again.`));if(m.length>0)console.log(u.yellow(`${m.length} row(s) have no description at the tag or at main (or the default branch is not main): a rerun will not fix them and they need an admin look. They are the 'error' lines above (${m.slice(0,3).map((g)=>`${g.dataset_id}@${g.version}`).join(", ")}${m.length>3?", ...":""}).`))}if(c)console.log(u.cyan(`On versions now: doi=${c.counts.doi} lineage=${c.counts.lineage} unknown=${c.counts.unknown} not_examined=${c.counts.not_examined}`));if(!r)console.log(u.yellow("Dry run, pass --execute to record."))}if(l!==null||i.length>0||!f)process.exit(1)});Oe.addCommand(K$e);Oe.addCommand(t$e);var J$e=new de("anonymity-sweep").description("Re-check anonymous deposits against the identity-leak inventory (#1409)");J$e.option("--limit <n>","Datasets per batch (server clamps to [1,25])","10").option("--reset","Re-arm every anonymous deposit, then exit").option("--json","Output raw JSON instead of the human summary").action(async(e)=>{if(!ke())return;if(e.reset){let o=D("Re-arming anonymous deposits...").start();try{let s=await ome();o.succeed(`Re-armed ${s.reset} anonymous deposit(s).`)}catch(s){o.fail("Reset failed"),console.error(u.red(G(s))),process.exit(1)}return}let t=Number.parseInt(e.limit??"10",10)||10,n=D("Checking anonymous deposits...").start(),r;try{r=await rme({limit:t}),n.stop()}catch(o){n.fail("Anonymity sweep failed"),console.error(u.red(G(o))),process.exit(1);return}if(e.json)console.log(JSON.stringify(r,null,2));else{console.log(),console.log(u.cyan(`processed=${r.processed} verified=${r.verified} findings=${r.with_findings} unverifiable=${r.unverifiable} errors=${r.errors.length} mail_failures=${r.mail_failures.length} remaining=${r.remaining??"unknown"}${r.budget_exhausted?" budget_exhausted=true":""}`));for(let o of r.results){let s=o.status==="verified"?u.green:o.status==="findings"?u.red:u.yellow;console.log(` ${s(o.status.padEnd(13))} ${o.dataset_id} (files ${o.files_scanned}/${o.files_listed})`);for(let i of o.findings){let a=i.severity==="invariant"?u.red("NEMAR"):u.yellow("deposit");console.log(` ${a} ${i.check}: ${i.detail}`)}if(o.unchecked.length>0)console.log(` ${u.dim(`not checked: ${o.unchecked.join(", ")}`)}`)}for(let o of r.errors)console.log(` ${u.red("error")} ${o.dataset_id}: ${o.error}`);for(let o of r.mail_failures)console.log(` ${u.red("not mailed")} ${o.dataset_id} -> ${o.recipient}: ${o.error}`)}if(r.errors.length>0||r.mail_failures.length>0||r.remaining===null||r.budget_exhausted)process.exit(1)});Oe.addCommand(J$e);var w1=new de("doctor").description("Diagnose and heal stuck-dataset patterns (e.g. missing S3 version manifests)");function r2t(e){let t=0;for(let[n,r]of Object.entries(e.results)){t+=r.count;let o=r.count>0?u.red(`${r.count} finding(s)`):u.green("clean");console.log(`${u.bold(n)}: ${o} \u2014 ${r.description}`);for(let s of r.findings)console.log(` ${s.dataset_id}${s.version?`@v${s.version}`:""}`)}return t}w1.command("scan").description("Run diagnostic checks (read-only)").argument("[dataset-id]","Narrow the scan to one dataset").option("--check <name>","Run a single check (default: all checks)").option("--json","Output raw JSON instead of the human summary").action(async(e,t)=>{if(!ke())return;let n=D("Running doctor checks (read-only; a full-catalog scan can take ~1 minute)...").start();try{let r=await uN({check:t.check,datasetId:e});if(n.stop(),t.json){console.log(JSON.stringify(r,null,2));return}let o=r2t(r);if(o>0)console.log(u.yellow(`
|
|
1645
1645
|
${o} finding(s). Preview the remediation with: nemar admin doctor fix <check> --dry-run`))}catch(r){n.fail("Doctor scan failed"),console.error(u.red(G(r))),process.exit(1)}});w1.command("fix").description("Apply a check's remediation (writes; use --dry-run first)").argument("<check>","Check name (see: nemar admin doctor scan)").argument("[dataset-id]","Narrow to one dataset").option("--dry-run","List what would be fixed without writing").option("--json","Output raw JSON instead of the human summary").action(async(e,t,n)=>{if(!ke())return;if(n.dryRun){let c=D(`Listing ${e} findings (dry run)...`).start();try{let l=await dN({check:e,datasetId:t,dryRun:!0});if(c.stop(),n.json){console.log(JSON.stringify(l,null,2));return}console.log(`Would fix ${l.would_fix} finding(s) for ${u.bold(e)}:`);for(let d of l.findings)console.log(` ${d.dataset_id}${d.version?`@v${d.version}`:""}`)}catch(l){c.fail("Dry run failed"),console.error(u.red(G(l))),process.exit(1)}return}let r=D(`Scanning for ${e} findings...`).start(),o;try{o=(await uN({check:e,datasetId:t})).results[e]?.findings??[]}catch(c){r.fail("Doctor scan failed"),console.error(u.red(G(c))),process.exit(1);return}if(o.length===0){if(r.succeed(`${e}: nothing to fix`),n.json)console.log(JSON.stringify({check:e,total:0,results:[]},null,2));return}r.stop(),console.log(`${u.bold(e)}: ${o.length} finding(s) to fix`);let s=[...new Set(o.map((c)=>c.dataset_id))];r.start();let{totals:i,results:a}=await o2t(s,(c,l)=>{let d=o.filter((f)=>f.dataset_id===c&&f.version).map((f)=>`v${f.version}`).join(", ");return r.text=`Fixing ${c}${d?` (${d})`:""} [${l+1}/${s.length}]...`,dN({check:e,datasetId:c})},{onDataset:(c,l)=>{if(r.stop(),l.length===0)console.log(` resolved ${c}: healed between the scan and its fix turn`);for(let d of l){let f=`${d.dataset_id}${d.version?`@v${d.version}`:""}`;if(d.status==="fixed")console.log(` ${u.green("fixed")} ${f}`);else if(d.status==="skipped")console.log(` skipped ${f}: ${d.message??"already healthy"}`);else console.log(` ${u.red("FAILED")} ${f}: ${d.message??"unknown error"}`)}r.start()}});if(r.stop(),n.json)console.log(JSON.stringify({check:e,total:o.length,...i,results:a},null,2));else{let c=i.resolved>0?`, ${i.resolved} already resolved`:"";console.log(`
|
|
1646
1646
|
${u.bold(e)}: ${u.green(`${i.fixed} fixed`)}, ${i.skipped} skipped, ${i.failed>0?u.red(`${i.failed} failed`):"0 failed"}${c}`)}if(i.failed>0)process.exit(1)});async function o2t(e,t,n){let r={fixed:0,skipped:0,failed:0,resolved:0},o=[];for(let[s,i]of e.entries()){let a;try{let c=await t(i,s);if(a=c.results,a.length===0)r.resolved++;else r.fixed+=c.fixed,r.skipped+=c.skipped,r.failed+=c.failed}catch(c){r.failed++,a=[{dataset_id:i,status:"failed",message:G(c)}]}o.push(...a),n?.onDataset?.(i,a)}return{totals:r,results:o}}w1.command("kinds").description("Check that operational accounts carry their expected account kind (read-only)").action(async()=>{if(!ke())return;let e=Object.entries(xQ),t=D(`Checking ${e.length} operational account kind(s)...`).start(),n=[],r=[];try{for(let[o,s]of e)try{let{user:i}=await $S(o);if(i.account_kind!==s)n.push(`${o}: expected '${s}', found '${i.account_kind??"unknown"}'`)}catch(i){if(i instanceof L&&i.statusCode===404)r.push(o);else throw i}if(t.stop(),n.length===0&&r.length===0){console.log(u.green(`All ${e.length} operational account(s) carry their expected kind.`));return}for(let o of n)console.log(` ${u.yellow("kind mismatch")} ${o}`);for(let o of r)console.log(` ${u.yellow("account absent")} ${o}`);console.log(u.yellow(`
|
|
1647
|
-
${n.length+r.length} finding(s). Fix a mismatch with \`nemar admin kind <username> <kind>\`.`))}catch(o){t.fail("Doctor kinds check failed"),console.error(u.red(G(o))),process.exit(1)}});Oe.addCommand(w1);var gL=new de("email-preferences").description("Manage email notification preferences");gL.command("show").description("Show email notification preferences").option("--user <username>","(owner only) show another user's preferences").action(async(e)=>{if(!ze())console.error(u.red("Not authenticated. Run: nemar auth login")),process.exit(1);let t=D("Fetching email preferences...").start();try{let n=await jpe(e.user),r=n.username?`${n.username}'s`:"Your";t.succeed(`${r} email notification preferences:`),console.log();let o=[{key:"user_approval",label:"User approval notifications"},{key:"publication_request",label:"Publication request notifications"},{key:"announcements",label:"Announcement emails"},{key:"dataset_anonymity",label:"Anonymity sweep findings"},{key:"identifier_sweep",label:"Identifier sweep weekly report"},{key:"support_tickets",label:"Support tickets assigned to you"}];for(let s of o){let a=n[s.key]?u.green("enabled"):u.dim("disabled");console.log(` ${s.label.padEnd(40)} ${a}`)}console.log(),console.log(u.dim(" Use 'nemar admin email-preferences update' to change settings."))}catch(n){t.fail("Failed to fetch preferences"),console.error(u.red(G(n)))}});gL.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("--dataset-anonymity <bool>","Enable/disable anonymity sweep findings").option("--identifier-sweep <bool>","Enable/disable the identifier sweep weekly report").option("--support-tickets <bool>","Enable/disable support ticket notifications").option("--all <bool>","Enable/disable all notifications").option("--user <username>","(owner only) update another user's preferences").action(async(e)=>{if(!ze())console.error(u.red("Not authenticated. Run: nemar auth login")),process.exit(1);function t(o){if(o===void 0)return;let s=o.toLowerCase();if(s==="true"||s==="1"||s==="on"||s==="yes")return!0;if(s==="false"||s==="0"||s==="off"||s==="no")return!1;console.error(u.red(`Invalid boolean value: "${o}". Use true/false, on/off, yes/no.`)),process.exit(1)}let n={};if(e.all!==void 0){let o=t(e.all);n.user_approval=o,n.publication_request=o,n.announcements=o,n.dataset_anonymity=o,n.identifier_sweep=o,n.support_tickets=o}else{let o=t(e.userApproval),s=t(e.publicationRequest),i=t(e.announcements),a=t(e.datasetAnonymity),c=t(e.identifierSweep),l=t(e.supportTickets);if(o===void 0&&s===void 0&&i===void 0&&a===void 0&&c===void 0&&l===void 0)console.error(u.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(" --dataset-anonymity <bool> Anonymity sweep findings"),console.log(" --identifier-sweep <bool> Identifier sweep weekly report"),console.log(" --support-tickets <bool> Support ticket notifications"),console.log(" --all <bool> All notifications"),process.exit(1);if(o!==void 0)n.user_approval=o;if(s!==void 0)n.publication_request=s;if(i!==void 0)n.announcements=i;if(a!==void 0)n.dataset_anonymity=a;if(c!==void 0)n.identifier_sweep=c;if(l!==void 0)n.support_tickets=l}let r=D("Updating email preferences...").start();try{let o=await Lpe(n,e.user),s=o.username?`${o.username}'s`:"Your";r.succeed(`${s} email preferences updated:`),console.log(),console.log(` User approval: ${o.user_approval?u.green("enabled"):u.dim("disabled")}`),console.log(` Publication request: ${o.publication_request?u.green("enabled"):u.dim("disabled")}`),console.log(` Announcements: ${o.announcements?u.green("enabled"):u.dim("disabled")}`),console.log(` Anonymity findings: ${o.dataset_anonymity?u.green("enabled"):u.dim("disabled")}`),console.log(` Identifier sweep: ${o.identifier_sweep?u.green("enabled"):u.dim("disabled")}`),console.log(` Support tickets: ${o.support_tickets?u.green("enabled"):u.dim("disabled")}`)}catch(o){r.fail("Failed to update preferences"),console.error(u.red(G(o)))}});Oe.addCommand(gL);var _1=new de("notice").description("Manage system notices displayed to CLI users");_1.command("list").description("List all notices (including expired)").action(async()=>{if(!ze())console.error(u.red("Not authenticated. Run: nemar auth login")),process.exit(1);let e=D("Fetching notices...").start();try{let{notices:t}=await Ume();if(t.length===0){e.succeed("No notices found.");return}e.succeed(`${t.length} notice(s):`),console.log();for(let n of t){let o={critical:u.red.bold,warning:u.yellow,maintenance:u.magenta,announcement:u.green,tip:u.blue,info:u.blue}[n.level]||u.white,s=n.expires_at&&new Date(n.expires_at)<new Date?u.dim(" (expired)"):"";if(console.log(` ${u.dim(`#${n.id}`)} ${o(`[${n.level.toUpperCase()}]`)} ${u.dim(`scope:${n.scope}`)}${s}`),console.log(` ${n.message}`),console.log(` ${u.dim(`Created: ${n.created_at}`)}`),n.expires_at)console.log(` ${u.dim(`Expires: ${n.expires_at}`)}`);console.log()}}catch(t){Ct(t,e,"Failed to fetch notices")}});_1.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(!ze())console.error(u.red("Not authenticated. Run: nemar auth login")),process.exit(1);if(![...wN,"info"].includes(e.level))console.error(u.red(`Invalid level: ${e.level}. Use ${wN.join(", ")}.`)),process.exit(1);if(!["all","admins","members"].includes(e.scope))console.error(u.red(`Invalid scope: ${e.scope}. Use all, admins, or members.`)),process.exit(1);let t=D("Creating notice...").start();try{let n=await Hme({message:e.message,level:e.level,scope:e.scope,expires_at:e.expires});if(t.succeed(`Notice created (ID: ${n.id})`),console.log(` Level: ${n.level}`),console.log(` Scope: ${n.scope}`),console.log(` Message: ${n.message}`),n.expires_at)console.log(` Expires: ${n.expires_at}`)}catch(n){Ct(n,t,"Failed to create notice")}});_1.command("clear <id>").description("Delete a notice by ID").option(Je,nt).option(yt,ht).action(async(e,t)=>{if(!ze())console.error(u.red("Not authenticated. Run: nemar auth login")),process.exit(1);let n=Number.parseInt(e,10);if(Number.isNaN(n))console.error(u.red("Invalid notice ID")),process.exit(1);if(!await De(`Delete notice #${n}?`,t,!1))return;let o=D("Deleting notice...").start();try{await zme(n),o.succeed(`Notice #${n} deleted`)}catch(s){Ct(s,o,"Failed to delete notice")}});Oe.addCommand(_1);function s2t(e){let t=[`${u.bold(`Announcement ${e.id}`)} ${u.cyan(e.status)}`,` Subject: ${e.subject}`,` To: ${e.recipient_group}`,` Sent at: ${e.sent_at}`];if(e.status==="sent")t.push(` Delivered: ${e.queued_count>0?e.delivered_count:"n/a (sent inline)"}`),t.push(` Failed: ${e.failure_count}`);else{t.push(` Queued: ${e.queued_count}`),t.push(` Delivered: ${e.delivered_count}`),t.push(` Failed: ${e.failure_count}`),t.push(` Unconfirmed: ${e.unknown_count} (not retried; the provider never confirmed them)`);let n=e.queued_count-e.delivered_count-e.failure_count-e.unknown_count;if(n>0)t.push(` Pending: ${n}`)}if(e.failed_recipients.length>0){t.push(" Failed addresses are shown redacted and may not be unique:");for(let n of e.failed_recipients)t.push(u.red(` Failed: ${n}`))}return t}Oe.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").option("--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("--status <id>","Show the progress of a queued announcement by its ID").option("--json","Output raw JSON (with --status)").option(Je,nt).option(yt,ht).action(async(e)=>{if(!ze())console.error(u.red("Not authenticated. Run: nemar auth login")),process.exit(1);if(e.status!==void 0){let c=Number(e.status);if(!Number.isInteger(c)||c<1)console.error(u.red(`Invalid announcement ID: ${e.status}`)),process.exit(1);let l=e.json?null:D("Fetching announcement status...").start();try{let d=await qpe(c);if(e.json){console.log(JSON.stringify(d,null,2));return}l?.stop();for(let f of s2t(d))console.log(f)}catch(d){Ct(d,l??D(),"Failed to fetch announcement status")}return}if(!e.subject)console.error(u.red("Email subject required. Use --subject.")),process.exit(1);let t=e.subject;if(e.to&&e.user)console.error(u.red("--to and --user are mutually exclusive. Provide exactly one.")),process.exit(1);if(!e.to&&!e.user)console.error(u.red("Provide either --to <group> or --user <username>.")),process.exit(1);if(e.to&&!["all","admins","members"].includes(e.to))console.error(u.red(`Invalid group: ${e.to}. Use all, admins, or members.`)),process.exit(1);let n;if(e.bodyFile){if(!h1(e.bodyFile))console.error(u.red(`File not found: ${e.bodyFile}`)),process.exit(1);n=UAt(e.bodyFile,"utf-8")}else if(e.body)n=e.body;else console.error(u.red("Email body required. Use --body or --body-file.")),process.exit(1);let r=e.user?`user:${e.user}`:e.to,o=e.user?{user:e.user,subject:t,body:n}:{to:e.to,subject:t,body:n};if(e.dryRun){let c=D("Checking recipients...").start();try{let l=await lN({...o,dry_run:!0});if("dry_run"in l){c.succeed(`Dry run: ${l.recipient_count} recipient(s) for "${l.recipient_group}"`),console.log();for(let d of l.recipients)console.log(` ${d}`)}}catch(l){Ct(l,c,"Failed to check recipients")}return}console.log(u.bold("Email preview:")),console.log(` To: ${u.cyan(r)}`),console.log(` Subject: ${t}`),console.log(` Body: ${n.length>100?`${n.substring(0,100)}...`:n}`),console.log();let s=e.user?`Send this email to ${e.user}?`:"Send this broadcast email?";if(!await De(s,e,!1))return;let a=D(e.user?`Sending to ${e.user}...`:"Sending broadcast...").start();try{let c=await lN(o);if("broadcast_id"in c){if(c.error==="queue_enqueue_failed")a.warn(`Enqueue failed (ID ${c.broadcast_id}): ${c.recipient_count} queued, ${c.failure_count} not queued; check progress with: nemar admin notify --status ${c.broadcast_id}`);else if(c.status==="queued"&&c.failure_count===0)a.succeed(`Queued ${c.recipient_count} announcement(s) (ID ${c.broadcast_id}); check progress with: nemar admin notify --status ${c.broadcast_id}`);else if(c.failure_count>0){a.warn(`Email send: ${c.recipient_count} delivered, ${c.failure_count} failed`);for(let l of c.failed_recipients)console.log(u.red(` Failed: ${l}`))}else{let l=e.user?`Email sent to ${e.user}`:`Broadcast sent to ${c.recipient_count} recipient(s)`;a.succeed(`${l} (ID: ${c.broadcast_id})`)}if((c.suppressed_count??0)>0)console.log(u.yellow(` ${c.suppressed_count} recipient(s) withheld by the non-production delivery fence`))}}catch(c){Ct(c,a,"Failed to send email")}});var i2t=1500;function a2t(e){switch(e.kind){case"ok":return u.green(`ok ${e.schema_version}`);case"stale":return u.yellow(`stale ${e.schema_version}`);case"missing":return u.red("missing");case"error":return u.red(`error ${e.status||"?"}: ${e.message}`)}}function c2t(e){return e.kind==="stale"||e.kind==="missing"}function l2t(e){let n=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${n}$`)}var Y$e=new de("summary").description("summary.json coverage across published dataset versions");Y$e.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(Je,nt).option(yt,ht).action(async(e)=>{if(!ke())return;let t=D("Building coverage report...").start(),n;try{n=await Bpe()}catch(p){Ct(p,t,"Failed to fetch coverage report");return}t.succeed(`Coverage: target=schema ${n.target_schema}, versions=${n.totals.versions}`);let r=n.versions,o=null;if(e.id){if(r=r.filter((p)=>p.dataset_id===e.id),o=`dataset_id=${e.id}`,r.length===0){console.log(u.yellow(`No rows for ${o}`));return}}else if(e.match){let p=l2t(e.match);if(r=r.filter((m)=>p.test(m.dataset_id)),o=`--match ${e.match}`,r.length===0){console.log(u.yellow(`No rows match ${o}`));return}console.log(u.dim(`Scoped to ${r.length} version(s) matching ${e.match}`))}if(e.json){console.log(JSON.stringify(o?{...n,versions:r,totals:$$e(r)}:n,null,2));return}let s=e.onlyStale?r.filter((p)=>p.state.kind!=="ok"):r;if(s.length===0)console.log(u.green("All versions at target schema \u2014 no drift."));else{let p=Math.max(...s.map((h)=>h.dataset_id.length),10),m=Math.max(...s.map((h)=>h.version.length),7);for(let h of s)console.log(` ${h.dataset_id.padEnd(p)} ${h.version.padEnd(m)} ${a2t(h.state)}`)}let i=o?$$e(r):n.totals;if(console.log(),console.log(` Total: ${i.versions} ${u.green(`ok=${i.ok}`)} ${u.yellow(`stale=${i.stale}`)} ${u.red(`missing=${i.missing}`)} ${u.red(`error=${i.error}`)}`),!e.fix){if(i.stale+i.missing>0)console.log(u.dim(`
|
|
1647
|
+
${n.length+r.length} finding(s). Fix a mismatch with \`nemar admin kind <username> <kind>\`.`))}catch(o){t.fail("Doctor kinds check failed"),console.error(u.red(G(o))),process.exit(1)}});Oe.addCommand(w1);var gL=new de("email-preferences").description("Manage email notification preferences");gL.command("show").description("Show email notification preferences").option("--user <username>","(owner only) show another user's preferences").action(async(e)=>{if(!ze())console.error(u.red("Not authenticated. Run: nemar auth login")),process.exit(1);let t=D("Fetching email preferences...").start();try{let n=await jpe(e.user),r=n.username?`${n.username}'s`:"Your";t.succeed(`${r} email notification preferences:`),console.log();let o=[{key:"user_approval",label:"User approval notifications"},{key:"publication_request",label:"Publication request notifications"},{key:"announcements",label:"Announcement emails"},{key:"dataset_anonymity",label:"Anonymity sweep findings"},{key:"identifier_sweep",label:"Identifier sweep weekly report"},{key:"support_tickets",label:"Support tickets assigned to you"}];for(let s of o){let a=n[s.key]?u.green("enabled"):u.dim("disabled");console.log(` ${s.label.padEnd(40)} ${a}`)}console.log(),console.log(u.dim(" Use 'nemar admin email-preferences update' to change settings."))}catch(n){t.fail("Failed to fetch preferences"),console.error(u.red(G(n)))}});gL.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("--dataset-anonymity <bool>","Enable/disable anonymity sweep findings").option("--identifier-sweep <bool>","Enable/disable the identifier sweep weekly report").option("--support-tickets <bool>","Enable/disable support ticket notifications").option("--all <bool>","Enable/disable all notifications").option("--user <username>","(owner only) update another user's preferences").action(async(e)=>{if(!ze())console.error(u.red("Not authenticated. Run: nemar auth login")),process.exit(1);function t(o){if(o===void 0)return;let s=o.toLowerCase();if(s==="true"||s==="1"||s==="on"||s==="yes")return!0;if(s==="false"||s==="0"||s==="off"||s==="no")return!1;console.error(u.red(`Invalid boolean value: "${o}". Use true/false, on/off, yes/no.`)),process.exit(1)}let n={};if(e.all!==void 0){let o=t(e.all);n.user_approval=o,n.publication_request=o,n.announcements=o,n.dataset_anonymity=o,n.identifier_sweep=o,n.support_tickets=o}else{let o=t(e.userApproval),s=t(e.publicationRequest),i=t(e.announcements),a=t(e.datasetAnonymity),c=t(e.identifierSweep),l=t(e.supportTickets);if(o===void 0&&s===void 0&&i===void 0&&a===void 0&&c===void 0&&l===void 0)console.error(u.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(" --dataset-anonymity <bool> Anonymity sweep findings"),console.log(" --identifier-sweep <bool> Identifier sweep weekly report"),console.log(" --support-tickets <bool> Support ticket notifications"),console.log(" --all <bool> All notifications"),process.exit(1);if(o!==void 0)n.user_approval=o;if(s!==void 0)n.publication_request=s;if(i!==void 0)n.announcements=i;if(a!==void 0)n.dataset_anonymity=a;if(c!==void 0)n.identifier_sweep=c;if(l!==void 0)n.support_tickets=l}let r=D("Updating email preferences...").start();try{let o=await Lpe(n,e.user),s=o.username?`${o.username}'s`:"Your";r.succeed(`${s} email preferences updated:`),console.log(),console.log(` User approval: ${o.user_approval?u.green("enabled"):u.dim("disabled")}`),console.log(` Publication request: ${o.publication_request?u.green("enabled"):u.dim("disabled")}`),console.log(` Announcements: ${o.announcements?u.green("enabled"):u.dim("disabled")}`),console.log(` Anonymity findings: ${o.dataset_anonymity?u.green("enabled"):u.dim("disabled")}`),console.log(` Identifier sweep: ${o.identifier_sweep?u.green("enabled"):u.dim("disabled")}`),console.log(` Support tickets: ${o.support_tickets?u.green("enabled"):u.dim("disabled")}`)}catch(o){r.fail("Failed to update preferences"),console.error(u.red(G(o)))}});Oe.addCommand(gL);var _1=new de("notice").description("Manage system notices displayed to CLI users");_1.command("list").description("List all notices (including expired)").action(async()=>{if(!ze())console.error(u.red("Not authenticated. Run: nemar auth login")),process.exit(1);let e=D("Fetching notices...").start();try{let{notices:t}=await Ume();if(t.length===0){e.succeed("No notices found.");return}e.succeed(`${t.length} notice(s):`),console.log();for(let n of t){let o={critical:u.red.bold,warning:u.yellow,maintenance:u.magenta,announcement:u.green,tip:u.blue,info:u.blue}[n.level]||u.white,s=n.expires_at&&new Date(n.expires_at)<new Date?u.dim(" (expired)"):"";if(console.log(` ${u.dim(`#${n.id}`)} ${o(`[${n.level.toUpperCase()}]`)} ${u.dim(`scope:${n.scope}`)}${s}`),console.log(` ${n.message}`),console.log(` ${u.dim(`Created: ${n.created_at}`)}`),n.expires_at)console.log(` ${u.dim(`Expires: ${n.expires_at}`)}`);console.log()}}catch(t){Ct(t,e,"Failed to fetch notices")}});_1.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(!ze())console.error(u.red("Not authenticated. Run: nemar auth login")),process.exit(1);if(![...wN,"info"].includes(e.level))console.error(u.red(`Invalid level: ${e.level}. Use ${wN.join(", ")}.`)),process.exit(1);if(!["all","admins","members"].includes(e.scope))console.error(u.red(`Invalid scope: ${e.scope}. Use all, admins, or members.`)),process.exit(1);let t=D("Creating notice...").start();try{let n=await Hme({message:e.message,level:e.level,scope:e.scope,expires_at:e.expires});if(t.succeed(`Notice created (ID: ${n.id})`),console.log(` Level: ${n.level}`),console.log(` Scope: ${n.scope}`),console.log(` Message: ${n.message}`),n.expires_at)console.log(` Expires: ${n.expires_at}`)}catch(n){Ct(n,t,"Failed to create notice")}});_1.command("clear <id>").description("Delete a notice by ID").option(Ye,nt).option(yt,ht).action(async(e,t)=>{if(!ze())console.error(u.red("Not authenticated. Run: nemar auth login")),process.exit(1);let n=Number.parseInt(e,10);if(Number.isNaN(n))console.error(u.red("Invalid notice ID")),process.exit(1);if(!await De(`Delete notice #${n}?`,t,!1))return;let o=D("Deleting notice...").start();try{await zme(n),o.succeed(`Notice #${n} deleted`)}catch(s){Ct(s,o,"Failed to delete notice")}});Oe.addCommand(_1);function s2t(e){let t=[`${u.bold(`Announcement ${e.id}`)} ${u.cyan(e.status)}`,` Subject: ${e.subject}`,` To: ${e.recipient_group}`,` Sent at: ${e.sent_at}`];if(e.status==="sent")t.push(` Delivered: ${e.queued_count>0?e.delivered_count:"n/a (sent inline)"}`),t.push(` Failed: ${e.failure_count}`);else{t.push(` Queued: ${e.queued_count}`),t.push(` Delivered: ${e.delivered_count}`),t.push(` Failed: ${e.failure_count}`),t.push(` Unconfirmed: ${e.unknown_count} (not retried; the provider never confirmed them)`);let n=e.queued_count-e.delivered_count-e.failure_count-e.unknown_count;if(n>0)t.push(` Pending: ${n}`)}if(e.failed_recipients.length>0){t.push(" Failed addresses are shown redacted and may not be unique:");for(let n of e.failed_recipients)t.push(u.red(` Failed: ${n}`))}return t}Oe.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").option("--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("--status <id>","Show the progress of a queued announcement by its ID").option("--json","Output raw JSON (with --status)").option(Ye,nt).option(yt,ht).action(async(e)=>{if(!ze())console.error(u.red("Not authenticated. Run: nemar auth login")),process.exit(1);if(e.status!==void 0){let c=Number(e.status);if(!Number.isInteger(c)||c<1)console.error(u.red(`Invalid announcement ID: ${e.status}`)),process.exit(1);let l=e.json?null:D("Fetching announcement status...").start();try{let d=await qpe(c);if(e.json){console.log(JSON.stringify(d,null,2));return}l?.stop();for(let f of s2t(d))console.log(f)}catch(d){Ct(d,l??D(),"Failed to fetch announcement status")}return}if(!e.subject)console.error(u.red("Email subject required. Use --subject.")),process.exit(1);let t=e.subject;if(e.to&&e.user)console.error(u.red("--to and --user are mutually exclusive. Provide exactly one.")),process.exit(1);if(!e.to&&!e.user)console.error(u.red("Provide either --to <group> or --user <username>.")),process.exit(1);if(e.to&&!["all","admins","members"].includes(e.to))console.error(u.red(`Invalid group: ${e.to}. Use all, admins, or members.`)),process.exit(1);let n;if(e.bodyFile){if(!h1(e.bodyFile))console.error(u.red(`File not found: ${e.bodyFile}`)),process.exit(1);n=UAt(e.bodyFile,"utf-8")}else if(e.body)n=e.body;else console.error(u.red("Email body required. Use --body or --body-file.")),process.exit(1);let r=e.user?`user:${e.user}`:e.to,o=e.user?{user:e.user,subject:t,body:n}:{to:e.to,subject:t,body:n};if(e.dryRun){let c=D("Checking recipients...").start();try{let l=await lN({...o,dry_run:!0});if("dry_run"in l){c.succeed(`Dry run: ${l.recipient_count} recipient(s) for "${l.recipient_group}"`),console.log();for(let d of l.recipients)console.log(` ${d}`)}}catch(l){Ct(l,c,"Failed to check recipients")}return}console.log(u.bold("Email preview:")),console.log(` To: ${u.cyan(r)}`),console.log(` Subject: ${t}`),console.log(` Body: ${n.length>100?`${n.substring(0,100)}...`:n}`),console.log();let s=e.user?`Send this email to ${e.user}?`:"Send this broadcast email?";if(!await De(s,e,!1))return;let a=D(e.user?`Sending to ${e.user}...`:"Sending broadcast...").start();try{let c=await lN(o);if("broadcast_id"in c){if(c.error==="queue_enqueue_failed")a.warn(`Enqueue failed (ID ${c.broadcast_id}): ${c.recipient_count} queued, ${c.failure_count} not queued; check progress with: nemar admin notify --status ${c.broadcast_id}`);else if(c.status==="queued"&&c.failure_count===0)a.succeed(`Queued ${c.recipient_count} announcement(s) (ID ${c.broadcast_id}); check progress with: nemar admin notify --status ${c.broadcast_id}`);else if(c.failure_count>0){a.warn(`Email send: ${c.recipient_count} delivered, ${c.failure_count} failed`);for(let l of c.failed_recipients)console.log(u.red(` Failed: ${l}`))}else{let l=e.user?`Email sent to ${e.user}`:`Broadcast sent to ${c.recipient_count} recipient(s)`;a.succeed(`${l} (ID: ${c.broadcast_id})`)}if((c.suppressed_count??0)>0)console.log(u.yellow(` ${c.suppressed_count} recipient(s) withheld by the non-production delivery fence`))}}catch(c){Ct(c,a,"Failed to send email")}});var i2t=1500;function a2t(e){switch(e.kind){case"ok":return u.green(`ok ${e.schema_version}`);case"stale":return u.yellow(`stale ${e.schema_version}`);case"missing":return u.red("missing");case"error":return u.red(`error ${e.status||"?"}: ${e.message}`)}}function c2t(e){return e.kind==="stale"||e.kind==="missing"}function l2t(e){let n=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${n}$`)}var Y$e=new de("summary").description("summary.json coverage across published dataset versions");Y$e.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(Ye,nt).option(yt,ht).action(async(e)=>{if(!ke())return;let t=D("Building coverage report...").start(),n;try{n=await Bpe()}catch(p){Ct(p,t,"Failed to fetch coverage report");return}t.succeed(`Coverage: target=schema ${n.target_schema}, versions=${n.totals.versions}`);let r=n.versions,o=null;if(e.id){if(r=r.filter((p)=>p.dataset_id===e.id),o=`dataset_id=${e.id}`,r.length===0){console.log(u.yellow(`No rows for ${o}`));return}}else if(e.match){let p=l2t(e.match);if(r=r.filter((m)=>p.test(m.dataset_id)),o=`--match ${e.match}`,r.length===0){console.log(u.yellow(`No rows match ${o}`));return}console.log(u.dim(`Scoped to ${r.length} version(s) matching ${e.match}`))}if(e.json){console.log(JSON.stringify(o?{...n,versions:r,totals:$$e(r)}:n,null,2));return}let s=e.onlyStale?r.filter((p)=>p.state.kind!=="ok"):r;if(s.length===0)console.log(u.green("All versions at target schema \u2014 no drift."));else{let p=Math.max(...s.map((h)=>h.dataset_id.length),10),m=Math.max(...s.map((h)=>h.version.length),7);for(let h of s)console.log(` ${h.dataset_id.padEnd(p)} ${h.version.padEnd(m)} ${a2t(h.state)}`)}let i=o?$$e(r):n.totals;if(console.log(),console.log(` Total: ${i.versions} ${u.green(`ok=${i.ok}`)} ${u.yellow(`stale=${i.stale}`)} ${u.red(`missing=${i.missing}`)} ${u.red(`error=${i.error}`)}`),!e.fix){if(i.stale+i.missing>0)console.log(u.dim(`
|
|
1648
1648
|
Run with --fix to dispatch generate-manifest for the ${i.stale+i.missing} drifted version(s).`));return}let a=r.filter((p)=>c2t(p.state));if(a.length===0){console.log(u.green(`
|
|
1649
|
-
Nothing to dispatch.`));return}let c=o?` (scoped to ${o})`:"",l=await De(`Dispatch generate-manifest for ${a.length} version(s)${c}? Each dispatch queues a runner job on nemarDatasets/.github.`,e);if(l!=="confirmed"){console.log(u.dim(l==="declined"?"Skipped":"Cancelled"));return}let d=0,f=0;console.log();for(let[p,m]of a.entries()){let h=`${m.dataset_id}@${m.version}`,g=D(`[${p+1}/${a.length}] dispatching ${h}...`).start();try{await Upe(m.dataset_id,m.version),g.succeed(`[${p+1}/${a.length}] dispatched ${h}`),d++}catch(y){g.fail(`[${p+1}/${a.length}] ${h}: ${G(y)}`),f++}if(p<a.length-1)await new Promise((y)=>setTimeout(y,i2t))}if(console.log(),console.log(f===0?u.green(`All ${d} dispatches succeeded.`):u.yellow(`${d} succeeded, ${f} failed.`)),console.log(u.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 $$e(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}}Oe.addCommand(Y$e);var X$e=new de("zarr-catalog").description("Top-level Zarr discovery catalog (zarr-catalog.json)");X$e.command("publish").description("Rebuild and republish zarr-catalog.json to this environment's bucket").action(async()=>{if(!ke())return;let e=D("Publishing zarr-catalog.json...").start();try{let t=await Hpe();e.succeed(`Published zarr-catalog.json: ${t.count} dataset(s), ${t.bytes} bytes`)}catch(t){Ct(t,e,"Failed to publish zarr catalog"),process.exit(1)}});Oe.addCommand(X$e);var Q$e=new de("backfill-names").description("Fill missing researcher names from users' public ORCID records (dry run by default)");Q$e.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(!ke())return;let t=Number.parseInt(e.limit??"25",10)||25,n=e.apply===!0,r=D(n?"Backfilling names from ORCID...":"Checking ORCID for missing names...").start(),o;try{o=await Zpe({apply:n,limit:t}),r.stop()}catch(s){r.fail("Name backfill failed"),console.error(u.red(G(s))),process.exit(1);return}if(o.lookup_failed>0||(o.write_failed??0)>0||o.remaining===null)process.exitCode=1;if(e.json){console.log(JSON.stringify(o,null,2));return}if(console.log(),!o.apply)console.log(u.yellow("DRY RUN \u2014 nothing was written. Re-run with --apply."));console.log(u.cyan(`scanned=${o.scanned} ${o.apply?"filled":"would_fill"}=${o.apply?o.filled:o.would_fill} no_public_name=${o.no_public_name} lookup_failed=${o.lookup_failed} write_failed=${o.write_failed??0} remaining=${o.remaining??"unknown"}`));for(let s of o.results){let i=s.username??`id ${s.id} <${s.email}>`;if(s.outcome==="filled"||s.outcome==="would_fill"){let a=s.outcome==="filled"?u.green("filled "):u.cyan("would fill");console.log(` ${a} ${i}: ${s.given_name} ${s.family_name} (${s.orcid})`)}else if(s.outcome==="no_public_name")console.log(` ${u.yellow("no name ")} ${i}: ORCID ${s.orcid} does not publish a full name`);else if(s.outcome==="write_failed")console.log(` ${u.red("write ")} ${i}: ${s.error}; retry the batch`);else console.log(` ${u.red("error ")} ${i}: ${s.error}`)}if(o.warning)console.log(u.yellow(` Warning: ${o.warning}`));if(o.no_public_name>0)console.log(),console.log(u.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)."))});Oe.addCommand(Q$e);function u2t(e){return typeof e==="object"&&e!==null&&Array.isArray(e.errors)}function d2t(e){return typeof e==="object"&&e!==null&&Array.isArray(e.errors)}var p1=20,Z$e=new de("import-issue-triage").description("Close recovered import-failure issues and retire stale cause labels (dry run by default)");Z$e.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(!ke())return;let t=e.limit??"15",n=t.trim()===""?Number.NaN:Number(t);if(!Number.isInteger(n)||n<1){console.error(u.red(`Invalid --limit ${JSON.stringify(t)}: expected an integer >= 1.`)),process.exitCode=1;return}let r=e.apply===!0,o=D(r?"Triaging import-failure issues...":"Checking import-failure issues...").start(),s;try{s=await Ype({apply:r,limit:n}),o.stop()}catch(i){o.fail("Import-failure issue triage failed"),console.error(u.red(G(i)));let a=i instanceof L?i.details:void 0,c=u2t(a)?a.errors:[];if(e.json)console.log(JSON.stringify(i instanceof L?i.rawBody??{errors:c}:{errors:c},null,2));else for(let l of c)console.error(`${u.red("ERROR".padEnd(15))} #${l.issue} ${l.dataset_id??""} ${l.stage}: ${l.error}`);process.exitCode=1;return}if(s.errors.length>0)process.exitCode=1;if(e.json){console.log(JSON.stringify(s,null,2));return}if(console.log(),!s.applied)console.log(u.yellow("DRY RUN \u2014 nothing was written. Re-run with --apply."));for(let i of s.plan){let a=i.failed?"FAILED ":s.applied?"":"WOULD ",c=`#${i.issueNumber} ${i.datasetId??"(unknown)"}`;if(i.kind==="close"){let l=`${a}CLOSE`.padEnd(15);console.log(`${i.failed?u.red(l):u.green(l)} ${c} ${u.dim(i.reason)}`)}else if(i.kind==="relabel"){let l=`${a}RELABEL`.padEnd(15);console.log(`${i.failed?u.red(l):u.yellow(l)} ${c} ${u.dim(i.reason)}`)}else console.log(`${u.dim("KEEP".padEnd(15))} ${c} ${u.dim(i.reason)}`)}for(let i of s.rollups){let c=(i.outcome==="failed"?"FAILED RELEASE":i.outcome==="released"?"RELEASE":s.mode==="per-dataset"?"WOULD RELEASE":"ROLLUP").padEnd(15);console.log(`${i.outcome==="failed"?u.red(c):u.magenta(c)} #${i.number} ${u.dim(i.title)}`)}for(let i of s.errors)console.log(`${u.red("ERROR".padEnd(15))} #${i.issue} ${i.dataset_id??""} ${i.stage}: ${i.error}`);if(console.log(),console.log(u.cyan(`open=${s.openIssues} mode=${s.mode} examined=${s.examined} attempted=${s.attempted} ${s.applied?"closed":"would_close"}=${s.closed} ${s.applied?"relabelled":"would_relabel"}=${s.relabelled} kept=${s.kept} errors=${s.errors.length} remaining=${s.remaining}`)),s.remaining>0)console.log(u.dim(` ${s.remaining} candidate(s) outside this run's window; the window rotates daily.`));if(s.mode==="rollup")console.log(u.dim(" Rollup mode: new failures with a cause that already has a rollup join it instead of opening their own issue."));if(s.rollupsReleased>0)console.log(u.dim(` ${s.applied?"Released":"Would release"} ${s.rollupsReleased} rollup(s): the backlog has drained, so per-dataset filing resumes.`));if(s.audit_failed)console.log(u.yellow(` Changes were applied but the audit row failed to write: ${s.audit_failed}`));if(!s.applied&&(s.closed>0||s.relabelled>0||s.rollupsReleased>0))console.log(u.dim(" Re-run with --apply to perform these changes."));if(s.reconcile==null)console.log(),console.log(u.yellow(`reconcile=unknown${s.reconcileError?`: ${s.reconcileError}`:""}`));else{let i=s.reconcile;console.log(),console.log(u.cyan(`reconcile rows_without_issue=${i.rowsWithoutIssue.length} issues_without_row=${i.issuesWithoutRow.length} parked=${i.parked} quarantined=${i.quarantined} rows_examined=${i.rowsExamined} issues_examined=${i.issuesExamined}`));for(let l of i.rowsWithoutIssue.slice(0,p1))console.log(`${u.yellow("UNTRACKED".padEnd(15))} ${l.datasetId} (${l.sourceId}) ${l.status} at ${l.stage} ${u.dim(l.cause)}`);let a=i.rowsWithoutIssue.length-p1;if(a>0)console.log(u.dim(` ... and ${a} more untracked`));for(let l of i.issuesWithoutRow.slice(0,p1))console.log(`${u.yellow("NO IMPORT ROW".padEnd(15))} #${l.number} ${l.datasetId}`);let c=i.issuesWithoutRow.length-p1;if(c>0)console.log(u.dim(` ... and ${c} more`));if(console.log(u.dim(` ${i.reason}`)),i.rowsWithoutIssue.length>0||i.issuesWithoutRow.length>0)console.log(u.dim(" Reported only: this command files and closes nothing for these."))}});Oe.addCommand(Z$e);var eDe=new de("import-coverage").description("Check whether the import pipeline is keeping up with OpenNeuro (dry run by default)"),m1=20,D$e=5,f2t={created:"create",refreshed:"refresh",relabelled:"relabel",closed:"close"};eDe.option("--apply","File, update or close the tracking issue (production only)").option("--json","Output raw JSON instead of the human summary").action(async(e)=>{if(!ke())return;let t=e.apply===!0,n=D("Checking import coverage...").start(),r;try{r=await Xpe({apply:t}),n.stop()}catch(c){n.fail("Import coverage check failed"),console.error(u.red(G(c)));let l=c instanceof L?c.details:void 0,d=d2t(l)?l.errors:[];if(e.json)console.log(JSON.stringify(c instanceof L?c.rawBody??{errors:d}:{errors:d},null,2));else for(let f of d)console.error(`${u.red("ERROR".padEnd(12))} ${f.stage}: ${f.error}`);process.exitCode=c instanceof L&&c.statusCode===502?2:1;return}if(r.status==="unknown")process.exitCode=2;else if(r.status!=="healthy"||r.errors.length>0)process.exitCode=1;if(process.exitCode!==0)ce();if(e.json){console.log(JSON.stringify(r,null,2));return}let o=r.backlog,s=o.neverAttempted.length+o.untracked.length;console.log();let i=`${r.status.toUpperCase()}${r.kind?` (${r.kind})`:""}`;console.log(r.status==="healthy"?u.green(i):u.red(u.bold(i))),console.log(r.reason),console.log(),console.log(u.cyan(`auto_import=${r.enabled?"enabled":u.red("DISABLED")} last_dispatch=${r.dispatchAgeHours===null?"never":r.dispatchAgeHours<0?"dated in the future":`${r.dispatchAgeHours}h ago`}${r.lastDispatchSourceId?` (${r.lastDispatchSourceId})`:""} dispatch_lost=${r.dispatchLost}`));let a=r.importedInScan+r.inFlight+r.terminal+s+o.tracked.length+o.blocklisted.length;if(console.log(u.cyan(`discovered=${r.discovered} in_scan=${r.importedInScan} in_flight=${r.inFlight} terminal=${r.terminal} tracked=${o.tracked.length} blocklisted=${o.blocklisted.length}`)),console.log(u.cyan(`outstanding=${s} (never_attempted=${o.neverAttempted.length} untracked=${o.untracked.length})`)),r.importedNotInScan>0)console.log(u.dim(` ${r.importedNotInScan} of ${r.imported} mirror(s) are no longer in the scan (upstream removal, unreadable snapshot, or a modality retag). Drift, not a gap.`));if(a!==r.discovered)console.log(u.yellow(` Counts do not balance (${a} accounted for vs ${r.discovered} discovered): this run did not get a complete view, so treat the verdict as unreliable.`));if(o.neverAttempted.length>0){let c=o.neverAttempted.slice(0,m1).join(", "),l=o.neverAttempted.length-m1;console.log(u.dim(` never attempted: ${c}${l>0?` ... and ${l} more`:""}`))}if(o.untracked.length>0){let c=o.untracked.slice(0,m1).join(", "),l=o.untracked.length-m1;console.log(u.dim(` stale row nothing owns: ${c}${l>0?` ... and ${l} more`:""}`))}for(let c of r.errors){let l=`${c.stage}: ${c.error}`;console.log(c.stage==="anomaly"?`${u.yellow("ANOMALY".padEnd(12))} ${l}`:`${u.red("ERROR".padEnd(12))} ${l}`)}if(r.issue){let c=r.applied?r.issue.action:`would ${f2t[r.issue.action]??r.issue.action}`,l=r.issue.number===null?"":` #${r.issue.number}`;if(console.log(u.dim(` Issue: ${c}${l} on nemarDatasets/.github`)),r.issue.labelError)console.log(u.yellow(` The body was updated but its labels were not: ${r.issue.labelError}`));if(r.issue.commentError)console.log(u.yellow(` The issue changed but its comment failed: ${r.issue.commentError}`))}if(r.audit_failed)console.log(u.yellow(` Changes applied but the audit row failed to write: ${r.audit_failed}`));if(!r.applied&&r.issue)console.log(u.dim(" Re-run with --apply to perform this change."))});Oe.addCommand(eDe);var tDe=new de("import-weekly").description("Read this week's import summary (dry run by default; the cron posts it on Mondays)");function p2t(e){return CT(e).attention}function ln(e){return e==null?u.yellow("unknown"):String(e)}tDe.option("--apply","Actually file the issue (production only; the cron normally does this)").option("--json","Output raw JSON instead of the human summary").option("--body","Also print the issue body exactly as it would be posted").action(async(e)=>{if(!ke())return;let t=e.apply===!0,n=D("Building the weekly import summary...").start(),r;try{r=await Qpe({apply:t}),n.stop()}catch(a){n.fail("Weekly import summary failed"),console.error(u.red(G(a))),process.exitCode=1;return}let o=r.facts;if(o===null)process.exitCode=0;else if(o.errors.length>0)process.exitCode=2;else if(p2t(o))process.exitCode=1;if(process.exitCode!==0)ce();if(e.json){console.log(JSON.stringify(r,null,2));return}if(o===null){console.log(),console.log(u.yellow(`Nothing computed: ${r.gateReason}`)),console.log(u.dim(" The report is built once a week; --apply files it."));return}console.log(),console.log(u.bold(`Import summary ${o.week}`)),console.log(u.dim(`${o.windowStart} to ${o.windowEnd} (UTC)`)),console.log(),console.log(u.cyan(`imported_this_week=${ln(o.importedThisWeek)} total=${ln(o.importedTotal)} in_scope=${ln(o.discovered)} not_in_scope=${ln(o.importedNotInScan)}`));let s=o.coverageStatus===null?u.yellow("unknown"):o.coverageStatus==="healthy"?u.green(o.coverageStatus):u.red(o.coverageStatus);if(console.log(u.cyan(`coverage=${s} outstanding=${ln(o.outstanding)}`)),console.log(u.cyan(`auto_import=${o.autoImportEnabled===null?u.yellow("unknown"):o.autoImportEnabled?"enabled":u.red("DISABLED")} last_dispatch=${o.dispatchPhrase??u.yellow("unknown")} dispatch_lost=${o.dispatchLost===null?u.yellow("unknown"):o.dispatchLost}`)),console.log(u.cyan(`open_failures=${ln(o.openFailureTotal)} parked=${o.parked===null?u.yellow("unknown"):o.parked.length} closed_this_week=${ln(o.issuesClosed)} relabelled=${ln(o.issuesRelabelled)}`)),o.upstream==null)console.log(u.cyan(`upstream=${u.yellow("unknown")}`));else{let a=o.upstream.counts.states,c=o.upstream.truncated?` ${u.yellow("(did not reach every mirror)")}`:"",l=`upstream: stale=${ln(o.upstream.counts.stale)} current=${ln(a.current)} anomaly=${ln(a.anomaly)} unknown=${ln(a.unknown)} unchecked=${ln(a.unchecked)}`;console.log(u.cyan(`${l}${c}`))}if(o.repulls==null)console.log(u.cyan(`repulls=${u.yellow("unknown")}`));else{let a=o.repulls,c=a.switches,l=c.auto_repull_merge_enabled?"open+merge":c.auto_repull_enabled?"open":"off";console.log(u.cyan(`repulls: switches=${l} dispatched=${ln(a.dispatches.sent)} opened=${ln(a.dispatches.by_status.opened)} refused=${ln(a.dispatches.by_status.refused)} failed=${ln(a.dispatches.by_status.failed)} unreported=${ln(a.dispatches.by_status.unreported)} not_accepted=${ln(a.dispatches.by_status.dispatch_failed)}`)),console.log(u.cyan(`repulls: open=${ln(a.open_automatic.total)} held=${ln(a.open_automatic.held)} claims_held=${ln(a.held_claims)} ended_failed=${ln(a.ended_failed)} merged_worker=${ln(a.merged.worker)} merged_admin=${ln(a.merged.administrator)} merged_outside=${ln(a.merged.outside_tool)} merged_unattributed=${ln(a.merged.unattributed)}`))}if(o.failuresByCause!==null){let a=Object.entries(o.failuresByCause).filter(([,c])=>c>0);for(let[c,l]of a)console.log(u.dim(` ${c}: ${l}`))}if(o.parked!==null&&o.parked.length>0){for(let c of o.parked.slice(0,D$e))console.log(u.dim(` parked ${c.datasetId} (${c.reason??"unknown"}): ${c.parkedDays==null?"unknown":`${c.parkedDays} days`}`));let a=o.parked.length-D$e;if(a>0)console.log(u.dim(` ... and ${a} more parked`))}for(let a of o.errors)console.log(`${u.yellow("UNKNOWN".padEnd(10))} ${a.stage}: ${a.error}`);let i=CT(o);if(i.attention)console.log(u.yellow(`Needs attention: ${i.problems.join("; ")}.`));if(console.log(),!r.posted&&!t)console.log(u.dim("Dry run: nothing was filed.")),console.log(u.dim(" Re-run with --apply to file it (production only)."));else if(!r.posted)console.log(u.yellow(`Not posted: ${r.gateReason}`));else console.log(u.green(`Posted${r.issue?.number?` #${r.issue.number}`:""}${r.closedPrevious?`, closed #${r.closedPrevious}`:""}`));if(e.body)console.log(),console.log(u.dim("--- rendered issue body ---")),console.log(r.renderedBody??u.yellow("(no body was rendered)"))});Oe.addCommand(tDe);var nDe=new de("backfill-usernames").description("Give username-less accounts a username from their name (dry run by default)");nDe.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(!ke())return;let t=Number.parseInt(e.limit??"25",10)||25,n=e.apply===!0,r=D(n?"Assigning usernames...":"Checking which accounts need a username...").start(),o;try{o=await eme({apply:n,limit:t}),r.stop()}catch(s){r.fail("Username backfill failed"),console.error(u.red(G(s))),process.exit(1);return}if(o.lookup_failed>0||o.conflict>0||(o.exhausted??0)>0||(o.write_failed??0)>0||(o.verify_failed??0)>0||(o.verify_rate_limited??0)>0||o.remaining===null)process.exitCode=1;if(e.json){console.log(JSON.stringify(o,null,2));return}if(console.log(),!o.apply)console.log(u.yellow("DRY RUN \u2014 nothing was written. Re-run with --apply."));console.log(u.cyan(`scanned=${o.scanned} ${o.apply?"assigned":"would_assign"}=${o.apply?o.assigned:o.would_assign} single_name=${o.single_name} no_name=${o.no_name} lookup_failed=${o.lookup_failed} conflict=${o.conflict} exhausted=${o.exhausted??0} write_failed=${o.write_failed??0} verify_sent=${o.verify_sent} verify_failed=${o.verify_failed??0} verify_rate_limited=${o.verify_rate_limited??0} remaining=${o.remaining??"unknown"}`));for(let s of o.results){let i=`id ${s.id} <${s.email}>`,a=[s.given_name,s.family_name].filter(Boolean).join(" ");if(s.outcome==="assigned"||s.outcome==="would_assign"){let c=s.outcome==="assigned"?u.green("assigned "):u.cyan("would give"),l=s.outcome==="assigned"?` [verify: ${s.verify}]`:"";console.log(` ${c} ${i}: ${u.cyan(s.username??"?")} (${a})${l}`)}else if(s.outcome==="single_name")console.log(` ${u.yellow("one name ")} ${i}: only "${a}" on record; pick a username by hand`);else if(s.outcome==="no_name")console.log(` ${u.yellow("no name ")} ${i}: run 'nemar admin backfill-names --apply' first`);else if(s.outcome==="conflict")console.log(` ${u.yellow("conflict ")} ${i}: ${s.error}`);else if(s.outcome==="exhausted")console.log(` ${u.yellow("exhausted ")} ${i}: ${s.error}; pick a username by hand`);else if(s.outcome==="write_failed")console.log(` ${u.red("write ")} ${i}: ${s.error}; retry the batch`);else console.log(` ${u.red("error ")} ${i}: ${s.error}`)}for(let s of o.verify_retries??[]){let i=s.verify==="sent"?u.green("re-sent "):s.verify==="not_attempted"?u.cyan("would send"):u.yellow(`verify ${s.verify}`);console.log(` ${i} id ${s.id} <${s.email}>`)}if(o.warning)console.log(u.yellow(` Warning: ${o.warning}`));if(o.single_name>0||o.no_name>0)console.log(),console.log(u.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."))});Oe.addCommand(nDe);var rDe=new de("duplicates").description("Report live accounts sharing an ORCID iD, email, or GitHub handle");function m2t(e){let t=e.username??u.dim("(no username)"),n=[];if(e.canonical)n.push(u.green("canonical"));if(e.identity_conflict===1)n.push(u.yellow("flagged"));if(e.has_oauth_identity)n.push(u.dim("orcid-login"));let r=n.length>0?` [${n.join(", ")}]`:"",o=`created ${e.created_at} datasets=${e.dataset_count}`;console.log(` id ${String(e.id).padEnd(5)} ${t} <${e.email}> ${o}${r}`)}rDe.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(!ke())return;if(e.clear!==void 0){let r=Number.parseInt(e.clear,10);if(!Number.isInteger(r)||r<=0){console.error(u.red(`Invalid user id: ${e.clear}`)),process.exit(1);return}let o=D(`Clearing identity-conflict flag on user ${r}...`).start();try{let s=await nme(r);if(o.stop(),e.json){console.log(JSON.stringify(s,null,2));return}console.log(s.cleared?u.green(`Cleared the identity-conflict flag on user ${r}.`):u.dim(`User ${r} was not flagged; nothing to clear.`))}catch(s){o.fail(s instanceof L&&s.statusCode===409?"Still colliding; flag not cleared":"Failed to clear the identity-conflict flag"),console.error(u.red(G(s))),process.exit(1)}return}let t=D("Checking for duplicate accounts...").start(),n;try{n=await tme(),t.stop()}catch(r){t.fail("Duplicate report failed"),console.error(u.red(G(r))),process.exit(1);return}if(e.json){console.log(JSON.stringify(n,null,2));return}if(console.log(),n.groups.length===0){if(console.log(u.green("No duplicate accounts.")),n.flagged_count>0)console.log(u.yellow(`${n.flagged_count} account(s) still carry an identity-conflict flag with no remaining collision.`)),console.log(u.dim(" Clear each with 'nemar admin duplicates --clear <id>'."));return}console.log(u.cyan(`${n.group_count} duplicate group(s); ${n.flagged_count} account(s) flagged`));for(let r of n.groups){console.log(),console.log(` ${u.bold(r.kind)} ${r.value}`);for(let o of r.accounts)m2t(o)}console.log(),console.log(u.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});Oe.addCommand(rDe);var x1=new de("neurobagel").description("Neurobagel federation artifacts: regenerate and inspect the private store (epic #1586)"),Qi=(e)=>e===null?u.yellow("unknown"):String(e),lL=(e)=>e==="healthy"?u.green(e):e==="alarm"?u.red(e):e==="unknown"?u.yellow(e):u.dim(e);function oDe(e){console.log(`${u.bold("Verification")} ${lL(e.overall)} ${e.at} (${e.trigger})${e.failed?u.red(` the sweep itself failed: ${e.error??"no reason recorded"}`):""}`);for(let t of gZ){let n=e.checks[t];console.log(` ${t.padEnd(13)}${lL(n.verdict)} ${n.reason}`)}for(let t of e.warnings)console.log(u.yellow(` warning: ${t}`))}function h2t(e){if(console.log(),e.dry_run)console.log(u.yellow("DRY RUN: nothing was written. Re-run with --execute to write."));if(e.status!=="ok"){let t=e.status==="disabled"?"the writer is disabled (NEUROBAGEL_WRITER_ENABLED is not 1)":e.status==="store_unconfigured"?"no NEUROBAGEL bucket is bound":e.error??"the run failed";console.log(u.red(`status=${e.status}: ${t}`))}console.log(u.cyan(`eligible=${Qi(e.eligible)} examined=${e.examined} limit=${e.limit} unexamined=${e.unexamined} removed=${e.removed.length} removals_pending=${e.removals_pending} index_entries=${Qi(e.index.entries)} index_written=${e.index.written} index_patched=${e.index.patched??0} anonymity_findings=${e.anonymity_findings} ops=${e.ops.spent}/${e.ops.budget}`));for(let t of e.results)switch(t.outcome){case"written":console.log(` ${u.green("written ")} ${t.id}${t.flags.length>0?` needs review: ${t.flags.join(", ")}`:""}`);break;case"would_write":console.log(` ${u.cyan("would write")} ${t.id} (${t.reason})`);break;case"unchanged":console.log(` ${u.dim("unchanged ")} ${t.id}`);break;case"would_remove":console.log(` ${u.cyan("would remove")} ${t.id}`);break;case"removed":console.log(` ${u.green("removed ")} ${t.id}`);break;case"refused":console.log(` ${u.red("refused ")} ${t.id} ${t.code}${t.detail?`: ${t.detail}`:""}`);break;case"error":console.log(` ${u.red("error ")} ${t.id} ${t.error}`);break}if(e.stopped==="ops_budget")console.log(u.yellow(` the run spent its operation budget (${e.ops.spent} of ${e.ops.budget}, ${e.ops.reserved} of it held back to finish) with ${e.unexamined} dataset(s) not yet examined: run the same command again to continue`));else if(e.unexamined>0&&e.stopped===null)console.log(u.yellow(` ${e.unexamined} dataset(s) are still waiting beyond this call's limit: run the same command again to continue`));if(e.index.contended)console.log(u.red(" the index was replaced by another run during this one; re-run to settle it"));for(let t of e.index.problems??[])console.log(u.red(` index not written: ${t}`));for(let t of e.warnings)console.log(u.yellow(` warning: ${t}`));if(e.anonymity_findings>0)console.log(u.red(` ${e.anonymity_findings} dataset(s) were refused because their data says anonymous. They are in the audit log (neurobagel_anonymity_finding); nothing was filed or mailed.`))}x1.command("regenerate").description("Examine datasets and write what changed to the Neurobagel artifact store (dry run unless --execute)").option("--execute","Write to the store (without it, only report what would change)").option("--dataset <ids...>","Examine exactly these dataset ids instead of the next ones due").option("--limit <n>",`Datasets to examine (default: the server's per-tick bound, at most ${lk}); run again to continue`).option("--force","Rewrite even when the fingerprint matches").option("--json","Output raw JSON instead of the human summary").action(async(e)=>{if(!ke())return;let t=e.limit===void 0?void 0:/^[1-9][0-9]*$/.test(e.limit)?Number(e.limit):Number.NaN;if(t!==void 0&&!Number.isInteger(t)){console.error(u.red("--limit must be a positive whole number")),process.exit(1);return}if(t!==void 0&&t>lk){console.error(u.red(`--limit is at most ${lk} per call (each call runs inside one request); run the command again to continue`)),process.exit(1);return}let n=e.execute===!0,r=D(n?"Regenerating Neurobagel artifacts...":"Checking what would change...").start(),o;try{o=await zpe({...n?{execute:!0}:{},...e.dataset&&e.dataset.length>0?{datasets:e.dataset}:{},...t!==void 0?{limit:t}:{},...e.force?{force:!0}:{}}),r.stop()}catch(i){Ct(i,r,"Neurobagel regenerate failed",{409:"Set NEUROBAGEL_WRITER_ENABLED=1 (and bind the bucket) to write. A dry run needs neither the switch nor --execute."}),process.exit(1);return}if(e.json)console.log(JSON.stringify(o,null,2));else h2t(o);let s=o.results.some((i)=>i.outcome==="error");if(o.status!=="ok"||s||o.index.contended||o.stopped==="index_patch"||(o.index.problems?.length??0)>0||o.anonymity_findings>0)process.exitCode=1});x1.command("status").description("What is eligible, written, stale and waiting on a person in the Neurobagel store, and the latest verification (exit 0 healthy, 1 alarm, 2 unknown)").option("--json","Output raw JSON instead of the human summary").action(async(e)=>{if(!ke())return;let t=D("Reading the Neurobagel store...").start(),n;try{n=await Vpe(),t.stop()}catch(l){Ct(l,t,"Neurobagel status failed"),process.exit(1);return}if(e.json){console.log(JSON.stringify(n,null,2));return}let r=n.writer.mode==="enabled"?u.green("enabled"):n.writer.mode==="disabled"?u.yellow("disabled (NEUROBAGEL_WRITER_ENABLED is not 1)"):u.red("store_unconfigured (no NEUROBAGEL bucket is bound)");console.log(),console.log(`${u.bold("Writer")} ${r}`),console.log(`${u.bold("Read route")} ${n.read_route.token_configured?u.green("token configured"):u.yellow("no NEUROBAGEL_READ_TOKEN: the route answers 404")}`),console.log(`${u.bold("Per tick")} ${n.limits.reconcile_max} datasets (hard limit ${n.limits.hard_max})`),console.log();let o=n.counts;console.log(`${u.bold("Datasets")} eligible=${Qi(o.eligible)} written=${Qi(o.written)} missing=${Qi(o.missing)} stale=${Qi(o.stale)} incomplete=${Qi(o.incomplete)} waiting to be removed=${Qi(o.residue)}`),console.log(`${u.bold("Store")} objects=${Qi(n.store.objects)} bytes=${Qi(n.store.total_bytes)}${n.store.over_loader_cap?u.red(" OVER the loader's total cap"):""}${(n.store.unexpected_objects??0)>0?u.yellow(` ${n.store.unexpected_objects} object(s) that are not the writer's`):""}`);let s=n.index.matches_store===null?u.yellow("unknown"):n.index.matches_store?u.green("matches the store"):u.yellow("differs from what the store and eligibility imply (the next run settles it)");console.log(`${u.bold("Index")} ${n.index.present===null?u.yellow("unknown"):n.index.present?`${Qi(n.index.entries)} entries, generated ${n.index.generated_at??"?"}`:u.dim("not written yet")} ${s}`);let i=n.last_reconcile;console.log(`${u.bold("Last reconcile")} ${i?`${i.at} (${JSON.stringify(i.summary)})`:u.dim("none recorded")}`),console.log(`${u.bold("Anonymity")} ${n.anonymity_findings===null?u.yellow("unknown"):n.anonymity_findings===0?"no findings":u.red(`${n.anonymity_findings} finding(s): see the audit log (neurobagel_anonymity_finding); ids are not shown here`)}`);let a=yZ({verification:n.verification,writerMode:n.writer.mode,now:new Date});if(n.verification)oDe(n.verification);if(a.note)console.log(`${u.bold("Verification")} ${lL(a.verdict)} ${a.note}`);else if(!n.verification)console.log(`${u.bold("Verification")} ${u.dim("none recorded; the writer is off, so none is expected")}`);if(n.needs_review.length>0){console.log(),console.log(u.bold(`Needs review (${n.needs_review.length})`));for(let l of n.needs_review)console.log(` ${l.id} ${l.source==="refusal"?u.red(`refused: ${l.code}${l.since?` (last confirmed ${l.since})`:""}`):u.yellow((l.flags??[]).join(", "))}`)}for(let l of n.warnings)console.log(u.yellow(`warning: ${l}`));let c=n.writer.mode==="store_unconfigured"||(n.anonymity_findings??0)>0||n.counts.eligible===null||a.verdict==="alarm";process.exitCode=c?1:RT(a.verdict)}).addHelpText("after","\nExit codes: 0 healthy or nothing to check, 1 an alarm, 2 could not be determined (no verification recorded while the writer is on, a record over 36 hours old, or an unknown verdict). The same as `verify`.");x1.command("verify").description("Run the verification sweep now: the store against eligibility, the node, registration and upstream drift (reports only; exit 0 healthy, 1 alarm, 2 unknown)").option("--json","Output raw JSON instead of the human summary").action(async(e)=>{if(!ke())return;let t=D("Verifying the Neurobagel federation...").start(),n;try{n=await Gpe(),t.stop()}catch(r){Ct(r,t,"Neurobagel verify failed"),process.exit(1);return}if(e.json)console.log(JSON.stringify(n,null,2));else if(console.log(),oDe(n),!n.heartbeat_written)console.log(u.yellow("The heartbeat could not be written: this run is not recorded."));process.exitCode=RT(n.overall)}).addHelpText("after","\nExit codes: 0 healthy or nothing to check, 1 an alarm, 2 could not be determined. The same as `status`.");Oe.addCommand(x1);Oe.addCommand(Xi);Oe.addCommand(Nl);Oe.addCommand(Qye);He();Ws();ro();Zm();th();Ym();He();Zm();th();var g2t=Nn["cli.gaps.section.title"];function sDe(e){if(e.gaps===void 0)return[e.unknownReason??Nn["cli.gaps.unknown"]];let t=nk(e.gaps,{orcidVerified:e.orcidVerified}).map(oZ);if(e.sandboxCompleted===!1)t.push(rk());return t.length>0?t:[Nn["gaps.none"]]}function y2t(e){let t=sDe(e);return t.length===1&&t[0]===Nn["gaps.none"]}function R_(e){let t=e.gaps===void 0||y2t(e);console.log(),console.log(u.bold(g2t));for(let n of sDe(e))console.log(` ${t?u.dim(n):u.yellow(n)}`)}function v1(e,t,n={}){let r=n.indent??" ";console.log(),console.log(`${r}${e}`);for(let o of t)console.log(`${r} ${u.yellow(o.label)} ${ET(o)}`)}Ke();sp();gr();dn();He();ek();import{hostname as b2t}from"os";Ke();dn();function w2t(e){let t=e.replace(/[\x00-\x1f\x7f]/g,"").replace(/\s+/g," ").trim();return t?t.slice(0,KQ):xT}function _2t(){try{return w2t(b2t())}catch{return xT}}function x2t(e,t,n=_T){return e+(t+n)*1000}function cDe(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 v2t=15000,iDe=1000,k2t=5000,aDe=3;function E2t(e){if(e instanceof L&&e.statusCode!==0)return`HTTP ${e.statusCode}`;return G(e)}function S2t(e){if(typeof AbortSignal.any==="function")return AbortSignal.any(e);let t=new AbortController;for(let n of e){if(n.aborted){t.abort();break}n.addEventListener("abort",()=>t.abort(),{once:!0})}return t.signal}function $2t(e,t){return new Promise((n)=>{if(t.aborted){n();return}let r=setTimeout(()=>{t.removeEventListener("abort",o),n()},e);function o(){clearTimeout(r),n()}t.addEventListener("abort",o,{once:!0})})}async function D2t(e,t={}){let n=Date.now(),r=x2t(n,e.expires_in,t.graceSeconds??_T),o=Math.max(e.interval*1000,iDe),s=new AbortController,i=()=>s.abort();process.on("SIGINT",i);let a=0;try{while(!0){if(s.signal.aborted)return{kind:"cancelled"};if(Date.now()>=r)return{kind:"unreachable",detail:"gave up waiting to reach NEMAR"};if(await $2t(o,s.signal),s.signal.aborted)return{kind:"cancelled"};let c=S2t([s.signal,AbortSignal.timeout(v2t)]),l;try{l=await rhe(e.device_code,c),a=0}catch(d){if(s.signal.aborted)return{kind:"cancelled"};if(d instanceof L&&d.statusCode===0){console.log(u.dim(" NEMAR is unreachable; retrying...")),a=0;continue}let f=E2t(d);if(a+=1,Dn(`poll error ${a}/${aDe}: ${f} -- ${G(d)}`),console.log(u.dim(` NEMAR answered with an error (${f}); retrying...`)),a>=aDe)return{kind:"server_error",detail:f};continue}if(l.status==="pending")continue;if(l.status==="slow_down"){o=Math.max(o+k2t,e.interval*1000,iDe);continue}if(l.status==="success")return{...l.data,kind:"success"};if(l.error==="expired_token")return{kind:"expired",message:l.message};if(l.error==="access_denied")return{kind:"denied",message:l.message};return{kind:"invalid",message:l.message}}}finally{process.off("SIGINT",i)}}async function yL(e={}){let t;try{t=await nhe(_2t())}catch(n){return{kind:"start_failed",detail:G(n)}}if(console.log(` ${t.verification_uri_complete}`),console.log(` Code: ${u.cyan(t.user_code)}`),console.log(u.dim(" (if the page asks for it)")),console.log(),e.open!==!1&&gg(t.verification_uri_complete))console.log(u.dim(" (trying to open your browser; use the link above if it doesn't)")),console.log();return D2t(t)}lo();var lDe="NEMAR_DATA_HOSTS",R2t="NEMAR_DATA_HOSTS_ONLY",C2t="https://private.nemar.org",A2t="https://private-test.nemar.org",O2t=/^[a-z]{2,3}[0-9]{6}$/;function k1(e){return O2t.test(e)}function T2t(e){return e}function uDe(e){return e==="127.0.0.1"||e==="localhost"||e==="[::1]"}function dDe(e){let t=e.trim();if(t===""||/[?#@]/.test(t))return null;let n;try{n=new URL(t)}catch{return null}if(n.username!==""||n.password!=="")return null;if(n.pathname!=="/")return null;if(n.protocol==="https:")return n.origin;if(n.protocol==="http:"&&uDe(n.hostname))return n.origin;return null}function fDe(e){let t=[],n=[];for(let r of(e??"").split(",")){let o=r.trim();if(o==="")continue;let s=dDe(o);if(s===null)n.push(o);else if(!t.includes(s))t.push(s)}return{origins:t,rejected:n}}function pDe(e){return e.env??process.env}function E1(e={}){let t=pDe(e),n=e.isDevBuild??Nf,r=t[R2t]==="1"?[]:[n?A2t:C2t],{origins:o}=fDe(t[lDe]);return[...r,...o.filter((s)=>!r.includes(s))].map(T2t)}function mDe(e={}){return fDe(pDe(e)[lDe]).rejected}function S1(e,t={}){let n=dDe(e);if(n===null)return null;return E1(t).find((r)=>r===n)??null}function $1(e,t={}){return S1(e,t)!==null}function hDe(e,t={}){let n;try{n=new URL(e)}catch{return null}if(n.username!==""||n.password!=="")return null;return S1(n.origin,t)}function Zdn(e,t){if(e.protocol==="https:")return!0;return e.protocol==="http:"&&uDe(e.hostname)&&new URL(t).protocol==="http:"}var P2t="NEMAR_DATA_HOST_TIMEOUT_MS";function gDe(e,t=process.env){let n=t[P2t];if(n===void 0||!/^[0-9]+$/.test(n))return e;let r=Number(n);return r>0&&r<e?r:e}function yDe(e){if(!(e instanceof Error))return"error";let t=e.code;return typeof t==="string"&&/^[A-Z][A-Z0-9_]+$/.test(t)?`${e.name} ${t}`:e.name}var I2t="nemar";function bDe(e){let t={};for(let n of e.split(`
|
|
1649
|
+
Nothing to dispatch.`));return}let c=o?` (scoped to ${o})`:"",l=await De(`Dispatch generate-manifest for ${a.length} version(s)${c}? Each dispatch queues a runner job on nemarDatasets/.github.`,e);if(l!=="confirmed"){console.log(u.dim(l==="declined"?"Skipped":"Cancelled"));return}let d=0,f=0;console.log();for(let[p,m]of a.entries()){let h=`${m.dataset_id}@${m.version}`,g=D(`[${p+1}/${a.length}] dispatching ${h}...`).start();try{await Upe(m.dataset_id,m.version),g.succeed(`[${p+1}/${a.length}] dispatched ${h}`),d++}catch(y){g.fail(`[${p+1}/${a.length}] ${h}: ${G(y)}`),f++}if(p<a.length-1)await new Promise((y)=>setTimeout(y,i2t))}if(console.log(),console.log(f===0?u.green(`All ${d} dispatches succeeded.`):u.yellow(`${d} succeeded, ${f} failed.`)),console.log(u.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 $$e(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}}Oe.addCommand(Y$e);var X$e=new de("zarr-catalog").description("Top-level Zarr discovery catalog (zarr-catalog.json)");X$e.command("publish").description("Rebuild and republish zarr-catalog.json to this environment's bucket").action(async()=>{if(!ke())return;let e=D("Publishing zarr-catalog.json...").start();try{let t=await Hpe();e.succeed(`Published zarr-catalog.json: ${t.count} dataset(s), ${t.bytes} bytes`)}catch(t){Ct(t,e,"Failed to publish zarr catalog"),process.exit(1)}});Oe.addCommand(X$e);var Q$e=new de("backfill-names").description("Fill missing researcher names from users' public ORCID records (dry run by default)");Q$e.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(!ke())return;let t=Number.parseInt(e.limit??"25",10)||25,n=e.apply===!0,r=D(n?"Backfilling names from ORCID...":"Checking ORCID for missing names...").start(),o;try{o=await Zpe({apply:n,limit:t}),r.stop()}catch(s){r.fail("Name backfill failed"),console.error(u.red(G(s))),process.exit(1);return}if(o.lookup_failed>0||(o.write_failed??0)>0||o.remaining===null)process.exitCode=1;if(e.json){console.log(JSON.stringify(o,null,2));return}if(console.log(),!o.apply)console.log(u.yellow("DRY RUN \u2014 nothing was written. Re-run with --apply."));console.log(u.cyan(`scanned=${o.scanned} ${o.apply?"filled":"would_fill"}=${o.apply?o.filled:o.would_fill} no_public_name=${o.no_public_name} lookup_failed=${o.lookup_failed} write_failed=${o.write_failed??0} remaining=${o.remaining??"unknown"}`));for(let s of o.results){let i=s.username??`id ${s.id} <${s.email}>`;if(s.outcome==="filled"||s.outcome==="would_fill"){let a=s.outcome==="filled"?u.green("filled "):u.cyan("would fill");console.log(` ${a} ${i}: ${s.given_name} ${s.family_name} (${s.orcid})`)}else if(s.outcome==="no_public_name")console.log(` ${u.yellow("no name ")} ${i}: ORCID ${s.orcid} does not publish a full name`);else if(s.outcome==="write_failed")console.log(` ${u.red("write ")} ${i}: ${s.error}; retry the batch`);else console.log(` ${u.red("error ")} ${i}: ${s.error}`)}if(o.warning)console.log(u.yellow(` Warning: ${o.warning}`));if(o.no_public_name>0)console.log(),console.log(u.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)."))});Oe.addCommand(Q$e);function u2t(e){return typeof e==="object"&&e!==null&&Array.isArray(e.errors)}function d2t(e){return typeof e==="object"&&e!==null&&Array.isArray(e.errors)}var p1=20,Z$e=new de("import-issue-triage").description("Close recovered import-failure issues and retire stale cause labels (dry run by default)");Z$e.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(!ke())return;let t=e.limit??"15",n=t.trim()===""?Number.NaN:Number(t);if(!Number.isInteger(n)||n<1){console.error(u.red(`Invalid --limit ${JSON.stringify(t)}: expected an integer >= 1.`)),process.exitCode=1;return}let r=e.apply===!0,o=D(r?"Triaging import-failure issues...":"Checking import-failure issues...").start(),s;try{s=await Ype({apply:r,limit:n}),o.stop()}catch(i){o.fail("Import-failure issue triage failed"),console.error(u.red(G(i)));let a=i instanceof L?i.details:void 0,c=u2t(a)?a.errors:[];if(e.json)console.log(JSON.stringify(i instanceof L?i.rawBody??{errors:c}:{errors:c},null,2));else for(let l of c)console.error(`${u.red("ERROR".padEnd(15))} #${l.issue} ${l.dataset_id??""} ${l.stage}: ${l.error}`);process.exitCode=1;return}if(s.errors.length>0)process.exitCode=1;if(e.json){console.log(JSON.stringify(s,null,2));return}if(console.log(),!s.applied)console.log(u.yellow("DRY RUN \u2014 nothing was written. Re-run with --apply."));for(let i of s.plan){let a=i.failed?"FAILED ":s.applied?"":"WOULD ",c=`#${i.issueNumber} ${i.datasetId??"(unknown)"}`;if(i.kind==="close"){let l=`${a}CLOSE`.padEnd(15);console.log(`${i.failed?u.red(l):u.green(l)} ${c} ${u.dim(i.reason)}`)}else if(i.kind==="relabel"){let l=`${a}RELABEL`.padEnd(15);console.log(`${i.failed?u.red(l):u.yellow(l)} ${c} ${u.dim(i.reason)}`)}else console.log(`${u.dim("KEEP".padEnd(15))} ${c} ${u.dim(i.reason)}`)}for(let i of s.rollups){let c=(i.outcome==="failed"?"FAILED RELEASE":i.outcome==="released"?"RELEASE":s.mode==="per-dataset"?"WOULD RELEASE":"ROLLUP").padEnd(15);console.log(`${i.outcome==="failed"?u.red(c):u.magenta(c)} #${i.number} ${u.dim(i.title)}`)}for(let i of s.errors)console.log(`${u.red("ERROR".padEnd(15))} #${i.issue} ${i.dataset_id??""} ${i.stage}: ${i.error}`);if(console.log(),console.log(u.cyan(`open=${s.openIssues} mode=${s.mode} examined=${s.examined} attempted=${s.attempted} ${s.applied?"closed":"would_close"}=${s.closed} ${s.applied?"relabelled":"would_relabel"}=${s.relabelled} kept=${s.kept} errors=${s.errors.length} remaining=${s.remaining}`)),s.remaining>0)console.log(u.dim(` ${s.remaining} candidate(s) outside this run's window; the window rotates daily.`));if(s.mode==="rollup")console.log(u.dim(" Rollup mode: new failures with a cause that already has a rollup join it instead of opening their own issue."));if(s.rollupsReleased>0)console.log(u.dim(` ${s.applied?"Released":"Would release"} ${s.rollupsReleased} rollup(s): the backlog has drained, so per-dataset filing resumes.`));if(s.audit_failed)console.log(u.yellow(` Changes were applied but the audit row failed to write: ${s.audit_failed}`));if(!s.applied&&(s.closed>0||s.relabelled>0||s.rollupsReleased>0))console.log(u.dim(" Re-run with --apply to perform these changes."));if(s.reconcile==null)console.log(),console.log(u.yellow(`reconcile=unknown${s.reconcileError?`: ${s.reconcileError}`:""}`));else{let i=s.reconcile;console.log(),console.log(u.cyan(`reconcile rows_without_issue=${i.rowsWithoutIssue.length} issues_without_row=${i.issuesWithoutRow.length} parked=${i.parked} quarantined=${i.quarantined} rows_examined=${i.rowsExamined} issues_examined=${i.issuesExamined}`));for(let l of i.rowsWithoutIssue.slice(0,p1))console.log(`${u.yellow("UNTRACKED".padEnd(15))} ${l.datasetId} (${l.sourceId}) ${l.status} at ${l.stage} ${u.dim(l.cause)}`);let a=i.rowsWithoutIssue.length-p1;if(a>0)console.log(u.dim(` ... and ${a} more untracked`));for(let l of i.issuesWithoutRow.slice(0,p1))console.log(`${u.yellow("NO IMPORT ROW".padEnd(15))} #${l.number} ${l.datasetId}`);let c=i.issuesWithoutRow.length-p1;if(c>0)console.log(u.dim(` ... and ${c} more`));if(console.log(u.dim(` ${i.reason}`)),i.rowsWithoutIssue.length>0||i.issuesWithoutRow.length>0)console.log(u.dim(" Reported only: this command files and closes nothing for these."))}});Oe.addCommand(Z$e);var eDe=new de("import-coverage").description("Check whether the import pipeline is keeping up with OpenNeuro (dry run by default)"),m1=20,D$e=5,f2t={created:"create",refreshed:"refresh",relabelled:"relabel",closed:"close"};eDe.option("--apply","File, update or close the tracking issue (production only)").option("--json","Output raw JSON instead of the human summary").action(async(e)=>{if(!ke())return;let t=e.apply===!0,n=D("Checking import coverage...").start(),r;try{r=await Xpe({apply:t}),n.stop()}catch(c){n.fail("Import coverage check failed"),console.error(u.red(G(c)));let l=c instanceof L?c.details:void 0,d=d2t(l)?l.errors:[];if(e.json)console.log(JSON.stringify(c instanceof L?c.rawBody??{errors:d}:{errors:d},null,2));else for(let f of d)console.error(`${u.red("ERROR".padEnd(12))} ${f.stage}: ${f.error}`);process.exitCode=c instanceof L&&c.statusCode===502?2:1;return}if(r.status==="unknown")process.exitCode=2;else if(r.status!=="healthy"||r.errors.length>0)process.exitCode=1;if(process.exitCode!==0)ce();if(e.json){console.log(JSON.stringify(r,null,2));return}let o=r.backlog,s=o.neverAttempted.length+o.untracked.length;console.log();let i=`${r.status.toUpperCase()}${r.kind?` (${r.kind})`:""}`;console.log(r.status==="healthy"?u.green(i):u.red(u.bold(i))),console.log(r.reason),console.log(),console.log(u.cyan(`auto_import=${r.enabled?"enabled":u.red("DISABLED")} last_dispatch=${r.dispatchAgeHours===null?"never":r.dispatchAgeHours<0?"dated in the future":`${r.dispatchAgeHours}h ago`}${r.lastDispatchSourceId?` (${r.lastDispatchSourceId})`:""} dispatch_lost=${r.dispatchLost}`));let a=r.importedInScan+r.inFlight+r.terminal+s+o.tracked.length+o.blocklisted.length;if(console.log(u.cyan(`discovered=${r.discovered} in_scan=${r.importedInScan} in_flight=${r.inFlight} terminal=${r.terminal} tracked=${o.tracked.length} blocklisted=${o.blocklisted.length}`)),console.log(u.cyan(`outstanding=${s} (never_attempted=${o.neverAttempted.length} untracked=${o.untracked.length})`)),r.importedNotInScan>0)console.log(u.dim(` ${r.importedNotInScan} of ${r.imported} mirror(s) are no longer in the scan (upstream removal, unreadable snapshot, or a modality retag). Drift, not a gap.`));if(a!==r.discovered)console.log(u.yellow(` Counts do not balance (${a} accounted for vs ${r.discovered} discovered): this run did not get a complete view, so treat the verdict as unreliable.`));if(o.neverAttempted.length>0){let c=o.neverAttempted.slice(0,m1).join(", "),l=o.neverAttempted.length-m1;console.log(u.dim(` never attempted: ${c}${l>0?` ... and ${l} more`:""}`))}if(o.untracked.length>0){let c=o.untracked.slice(0,m1).join(", "),l=o.untracked.length-m1;console.log(u.dim(` stale row nothing owns: ${c}${l>0?` ... and ${l} more`:""}`))}for(let c of r.errors){let l=`${c.stage}: ${c.error}`;console.log(c.stage==="anomaly"?`${u.yellow("ANOMALY".padEnd(12))} ${l}`:`${u.red("ERROR".padEnd(12))} ${l}`)}if(r.issue){let c=r.applied?r.issue.action:`would ${f2t[r.issue.action]??r.issue.action}`,l=r.issue.number===null?"":` #${r.issue.number}`;if(console.log(u.dim(` Issue: ${c}${l} on nemarDatasets/.github`)),r.issue.labelError)console.log(u.yellow(` The body was updated but its labels were not: ${r.issue.labelError}`));if(r.issue.commentError)console.log(u.yellow(` The issue changed but its comment failed: ${r.issue.commentError}`))}if(r.audit_failed)console.log(u.yellow(` Changes applied but the audit row failed to write: ${r.audit_failed}`));if(!r.applied&&r.issue)console.log(u.dim(" Re-run with --apply to perform this change."))});Oe.addCommand(eDe);var tDe=new de("import-weekly").description("Read this week's import summary (dry run by default; the cron posts it on Mondays)");function p2t(e){return CT(e).attention}function ln(e){return e==null?u.yellow("unknown"):String(e)}tDe.option("--apply","Actually file the issue (production only; the cron normally does this)").option("--json","Output raw JSON instead of the human summary").option("--body","Also print the issue body exactly as it would be posted").action(async(e)=>{if(!ke())return;let t=e.apply===!0,n=D("Building the weekly import summary...").start(),r;try{r=await Qpe({apply:t}),n.stop()}catch(a){n.fail("Weekly import summary failed"),console.error(u.red(G(a))),process.exitCode=1;return}let o=r.facts;if(o===null)process.exitCode=0;else if(o.errors.length>0)process.exitCode=2;else if(p2t(o))process.exitCode=1;if(process.exitCode!==0)ce();if(e.json){console.log(JSON.stringify(r,null,2));return}if(o===null){console.log(),console.log(u.yellow(`Nothing computed: ${r.gateReason}`)),console.log(u.dim(" The report is built once a week; --apply files it."));return}console.log(),console.log(u.bold(`Import summary ${o.week}`)),console.log(u.dim(`${o.windowStart} to ${o.windowEnd} (UTC)`)),console.log(),console.log(u.cyan(`imported_this_week=${ln(o.importedThisWeek)} total=${ln(o.importedTotal)} in_scope=${ln(o.discovered)} not_in_scope=${ln(o.importedNotInScan)}`));let s=o.coverageStatus===null?u.yellow("unknown"):o.coverageStatus==="healthy"?u.green(o.coverageStatus):u.red(o.coverageStatus);if(console.log(u.cyan(`coverage=${s} outstanding=${ln(o.outstanding)}`)),console.log(u.cyan(`auto_import=${o.autoImportEnabled===null?u.yellow("unknown"):o.autoImportEnabled?"enabled":u.red("DISABLED")} last_dispatch=${o.dispatchPhrase??u.yellow("unknown")} dispatch_lost=${o.dispatchLost===null?u.yellow("unknown"):o.dispatchLost}`)),console.log(u.cyan(`open_failures=${ln(o.openFailureTotal)} parked=${o.parked===null?u.yellow("unknown"):o.parked.length} closed_this_week=${ln(o.issuesClosed)} relabelled=${ln(o.issuesRelabelled)}`)),o.upstream==null)console.log(u.cyan(`upstream=${u.yellow("unknown")}`));else{let a=o.upstream.counts.states,c=o.upstream.truncated?` ${u.yellow("(did not reach every mirror)")}`:"",l=`upstream: stale=${ln(o.upstream.counts.stale)} current=${ln(a.current)} anomaly=${ln(a.anomaly)} unknown=${ln(a.unknown)} unchecked=${ln(a.unchecked)}`;console.log(u.cyan(`${l}${c}`))}if(o.repulls==null)console.log(u.cyan(`repulls=${u.yellow("unknown")}`));else{let a=o.repulls,c=a.switches,l=c.auto_repull_merge_enabled?"open+merge":c.auto_repull_enabled?"open":"off";console.log(u.cyan(`repulls: switches=${l} dispatched=${ln(a.dispatches.sent)} opened=${ln(a.dispatches.by_status.opened)} refused=${ln(a.dispatches.by_status.refused)} failed=${ln(a.dispatches.by_status.failed)} unreported=${ln(a.dispatches.by_status.unreported)} not_accepted=${ln(a.dispatches.by_status.dispatch_failed)}`)),console.log(u.cyan(`repulls: open=${ln(a.open_automatic.total)} held=${ln(a.open_automatic.held)} claims_held=${ln(a.held_claims)} ended_failed=${ln(a.ended_failed)} merged_worker=${ln(a.merged.worker)} merged_admin=${ln(a.merged.administrator)} merged_outside=${ln(a.merged.outside_tool)} merged_unattributed=${ln(a.merged.unattributed)}`))}if(o.failuresByCause!==null){let a=Object.entries(o.failuresByCause).filter(([,c])=>c>0);for(let[c,l]of a)console.log(u.dim(` ${c}: ${l}`))}if(o.parked!==null&&o.parked.length>0){for(let c of o.parked.slice(0,D$e))console.log(u.dim(` parked ${c.datasetId} (${c.reason??"unknown"}): ${c.parkedDays==null?"unknown":`${c.parkedDays} days`}`));let a=o.parked.length-D$e;if(a>0)console.log(u.dim(` ... and ${a} more parked`))}for(let a of o.errors)console.log(`${u.yellow("UNKNOWN".padEnd(10))} ${a.stage}: ${a.error}`);let i=CT(o);if(i.attention)console.log(u.yellow(`Needs attention: ${i.problems.join("; ")}.`));if(console.log(),!r.posted&&!t)console.log(u.dim("Dry run: nothing was filed.")),console.log(u.dim(" Re-run with --apply to file it (production only)."));else if(!r.posted)console.log(u.yellow(`Not posted: ${r.gateReason}`));else console.log(u.green(`Posted${r.issue?.number?` #${r.issue.number}`:""}${r.closedPrevious?`, closed #${r.closedPrevious}`:""}`));if(e.body)console.log(),console.log(u.dim("--- rendered issue body ---")),console.log(r.renderedBody??u.yellow("(no body was rendered)"))});Oe.addCommand(tDe);var nDe=new de("backfill-usernames").description("Give username-less accounts a username from their name (dry run by default)");nDe.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(!ke())return;let t=Number.parseInt(e.limit??"25",10)||25,n=e.apply===!0,r=D(n?"Assigning usernames...":"Checking which accounts need a username...").start(),o;try{o=await eme({apply:n,limit:t}),r.stop()}catch(s){r.fail("Username backfill failed"),console.error(u.red(G(s))),process.exit(1);return}if(o.lookup_failed>0||o.conflict>0||(o.exhausted??0)>0||(o.write_failed??0)>0||(o.verify_failed??0)>0||(o.verify_rate_limited??0)>0||o.remaining===null)process.exitCode=1;if(e.json){console.log(JSON.stringify(o,null,2));return}if(console.log(),!o.apply)console.log(u.yellow("DRY RUN \u2014 nothing was written. Re-run with --apply."));console.log(u.cyan(`scanned=${o.scanned} ${o.apply?"assigned":"would_assign"}=${o.apply?o.assigned:o.would_assign} single_name=${o.single_name} no_name=${o.no_name} lookup_failed=${o.lookup_failed} conflict=${o.conflict} exhausted=${o.exhausted??0} write_failed=${o.write_failed??0} verify_sent=${o.verify_sent} verify_failed=${o.verify_failed??0} verify_rate_limited=${o.verify_rate_limited??0} remaining=${o.remaining??"unknown"}`));for(let s of o.results){let i=`id ${s.id} <${s.email}>`,a=[s.given_name,s.family_name].filter(Boolean).join(" ");if(s.outcome==="assigned"||s.outcome==="would_assign"){let c=s.outcome==="assigned"?u.green("assigned "):u.cyan("would give"),l=s.outcome==="assigned"?` [verify: ${s.verify}]`:"";console.log(` ${c} ${i}: ${u.cyan(s.username??"?")} (${a})${l}`)}else if(s.outcome==="single_name")console.log(` ${u.yellow("one name ")} ${i}: only "${a}" on record; pick a username by hand`);else if(s.outcome==="no_name")console.log(` ${u.yellow("no name ")} ${i}: run 'nemar admin backfill-names --apply' first`);else if(s.outcome==="conflict")console.log(` ${u.yellow("conflict ")} ${i}: ${s.error}`);else if(s.outcome==="exhausted")console.log(` ${u.yellow("exhausted ")} ${i}: ${s.error}; pick a username by hand`);else if(s.outcome==="write_failed")console.log(` ${u.red("write ")} ${i}: ${s.error}; retry the batch`);else console.log(` ${u.red("error ")} ${i}: ${s.error}`)}for(let s of o.verify_retries??[]){let i=s.verify==="sent"?u.green("re-sent "):s.verify==="not_attempted"?u.cyan("would send"):u.yellow(`verify ${s.verify}`);console.log(` ${i} id ${s.id} <${s.email}>`)}if(o.warning)console.log(u.yellow(` Warning: ${o.warning}`));if(o.single_name>0||o.no_name>0)console.log(),console.log(u.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."))});Oe.addCommand(nDe);var rDe=new de("duplicates").description("Report live accounts sharing an ORCID iD, email, or GitHub handle");function m2t(e){let t=e.username??u.dim("(no username)"),n=[];if(e.canonical)n.push(u.green("canonical"));if(e.identity_conflict===1)n.push(u.yellow("flagged"));if(e.has_oauth_identity)n.push(u.dim("orcid-login"));let r=n.length>0?` [${n.join(", ")}]`:"",o=`created ${e.created_at} datasets=${e.dataset_count}`;console.log(` id ${String(e.id).padEnd(5)} ${t} <${e.email}> ${o}${r}`)}rDe.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(!ke())return;if(e.clear!==void 0){let r=Number.parseInt(e.clear,10);if(!Number.isInteger(r)||r<=0){console.error(u.red(`Invalid user id: ${e.clear}`)),process.exit(1);return}let o=D(`Clearing identity-conflict flag on user ${r}...`).start();try{let s=await nme(r);if(o.stop(),e.json){console.log(JSON.stringify(s,null,2));return}console.log(s.cleared?u.green(`Cleared the identity-conflict flag on user ${r}.`):u.dim(`User ${r} was not flagged; nothing to clear.`))}catch(s){o.fail(s instanceof L&&s.statusCode===409?"Still colliding; flag not cleared":"Failed to clear the identity-conflict flag"),console.error(u.red(G(s))),process.exit(1)}return}let t=D("Checking for duplicate accounts...").start(),n;try{n=await tme(),t.stop()}catch(r){t.fail("Duplicate report failed"),console.error(u.red(G(r))),process.exit(1);return}if(e.json){console.log(JSON.stringify(n,null,2));return}if(console.log(),n.groups.length===0){if(console.log(u.green("No duplicate accounts.")),n.flagged_count>0)console.log(u.yellow(`${n.flagged_count} account(s) still carry an identity-conflict flag with no remaining collision.`)),console.log(u.dim(" Clear each with 'nemar admin duplicates --clear <id>'."));return}console.log(u.cyan(`${n.group_count} duplicate group(s); ${n.flagged_count} account(s) flagged`));for(let r of n.groups){console.log(),console.log(` ${u.bold(r.kind)} ${r.value}`);for(let o of r.accounts)m2t(o)}console.log(),console.log(u.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});Oe.addCommand(rDe);var x1=new de("neurobagel").description("Neurobagel federation artifacts: regenerate and inspect the private store (epic #1586)"),Qi=(e)=>e===null?u.yellow("unknown"):String(e),lL=(e)=>e==="healthy"?u.green(e):e==="alarm"?u.red(e):e==="unknown"?u.yellow(e):u.dim(e);function oDe(e){console.log(`${u.bold("Verification")} ${lL(e.overall)} ${e.at} (${e.trigger})${e.failed?u.red(` the sweep itself failed: ${e.error??"no reason recorded"}`):""}`);for(let t of gZ){let n=e.checks[t];console.log(` ${t.padEnd(13)}${lL(n.verdict)} ${n.reason}`)}for(let t of e.warnings)console.log(u.yellow(` warning: ${t}`))}function h2t(e){if(console.log(),e.dry_run)console.log(u.yellow("DRY RUN: nothing was written. Re-run with --execute to write."));if(e.status!=="ok"){let t=e.status==="disabled"?"the writer is disabled (NEUROBAGEL_WRITER_ENABLED is not 1)":e.status==="store_unconfigured"?"no NEUROBAGEL bucket is bound":e.error??"the run failed";console.log(u.red(`status=${e.status}: ${t}`))}console.log(u.cyan(`eligible=${Qi(e.eligible)} examined=${e.examined} limit=${e.limit} unexamined=${e.unexamined} removed=${e.removed.length} removals_pending=${e.removals_pending} index_entries=${Qi(e.index.entries)} index_written=${e.index.written} index_patched=${e.index.patched??0} anonymity_findings=${e.anonymity_findings} ops=${e.ops.spent}/${e.ops.budget}`));for(let t of e.results)switch(t.outcome){case"written":console.log(` ${u.green("written ")} ${t.id}${t.flags.length>0?` needs review: ${t.flags.join(", ")}`:""}`);break;case"would_write":console.log(` ${u.cyan("would write")} ${t.id} (${t.reason})`);break;case"unchanged":console.log(` ${u.dim("unchanged ")} ${t.id}`);break;case"would_remove":console.log(` ${u.cyan("would remove")} ${t.id}`);break;case"removed":console.log(` ${u.green("removed ")} ${t.id}`);break;case"refused":console.log(` ${u.red("refused ")} ${t.id} ${t.code}${t.detail?`: ${t.detail}`:""}`);break;case"error":console.log(` ${u.red("error ")} ${t.id} ${t.error}`);break}if(e.stopped==="ops_budget")console.log(u.yellow(` the run spent its operation budget (${e.ops.spent} of ${e.ops.budget}, ${e.ops.reserved} of it held back to finish) with ${e.unexamined} dataset(s) not yet examined: run the same command again to continue`));else if(e.unexamined>0&&e.stopped===null)console.log(u.yellow(` ${e.unexamined} dataset(s) are still waiting beyond this call's limit: run the same command again to continue`));if(e.index.contended)console.log(u.red(" the index was replaced by another run during this one; re-run to settle it"));for(let t of e.index.problems??[])console.log(u.red(` index not written: ${t}`));for(let t of e.warnings)console.log(u.yellow(` warning: ${t}`));if(e.anonymity_findings>0)console.log(u.red(` ${e.anonymity_findings} dataset(s) were refused because their data says anonymous. They are in the audit log (neurobagel_anonymity_finding); nothing was filed or mailed.`))}x1.command("regenerate").description("Examine datasets and write what changed to the Neurobagel artifact store (dry run unless --execute)").option("--execute","Write to the store (without it, only report what would change)").option("--dataset <ids...>","Examine exactly these dataset ids instead of the next ones due").option("--limit <n>",`Datasets to examine (default: the server's per-tick bound, at most ${lk}); run again to continue`).option("--force","Rewrite even when the fingerprint matches").option("--json","Output raw JSON instead of the human summary").action(async(e)=>{if(!ke())return;let t=e.limit===void 0?void 0:/^[1-9][0-9]*$/.test(e.limit)?Number(e.limit):Number.NaN;if(t!==void 0&&!Number.isInteger(t)){console.error(u.red("--limit must be a positive whole number")),process.exit(1);return}if(t!==void 0&&t>lk){console.error(u.red(`--limit is at most ${lk} per call (each call runs inside one request); run the command again to continue`)),process.exit(1);return}let n=e.execute===!0,r=D(n?"Regenerating Neurobagel artifacts...":"Checking what would change...").start(),o;try{o=await zpe({...n?{execute:!0}:{},...e.dataset&&e.dataset.length>0?{datasets:e.dataset}:{},...t!==void 0?{limit:t}:{},...e.force?{force:!0}:{}}),r.stop()}catch(i){Ct(i,r,"Neurobagel regenerate failed",{409:"Set NEUROBAGEL_WRITER_ENABLED=1 (and bind the bucket) to write. A dry run needs neither the switch nor --execute."}),process.exit(1);return}if(e.json)console.log(JSON.stringify(o,null,2));else h2t(o);let s=o.results.some((i)=>i.outcome==="error");if(o.status!=="ok"||s||o.index.contended||o.stopped==="index_patch"||(o.index.problems?.length??0)>0||o.anonymity_findings>0)process.exitCode=1});x1.command("status").description("What is eligible, written, stale and waiting on a person in the Neurobagel store, and the latest verification (exit 0 healthy, 1 alarm, 2 unknown)").option("--json","Output raw JSON instead of the human summary").action(async(e)=>{if(!ke())return;let t=D("Reading the Neurobagel store...").start(),n;try{n=await Vpe(),t.stop()}catch(l){Ct(l,t,"Neurobagel status failed"),process.exit(1);return}if(e.json){console.log(JSON.stringify(n,null,2));return}let r=n.writer.mode==="enabled"?u.green("enabled"):n.writer.mode==="disabled"?u.yellow("disabled (NEUROBAGEL_WRITER_ENABLED is not 1)"):u.red("store_unconfigured (no NEUROBAGEL bucket is bound)");console.log(),console.log(`${u.bold("Writer")} ${r}`),console.log(`${u.bold("Read route")} ${n.read_route.token_configured?u.green("token configured"):u.yellow("no NEUROBAGEL_READ_TOKEN: the route answers 404")}`),console.log(`${u.bold("Per tick")} ${n.limits.reconcile_max} datasets (hard limit ${n.limits.hard_max})`),console.log();let o=n.counts;console.log(`${u.bold("Datasets")} eligible=${Qi(o.eligible)} written=${Qi(o.written)} missing=${Qi(o.missing)} stale=${Qi(o.stale)} incomplete=${Qi(o.incomplete)} waiting to be removed=${Qi(o.residue)}`),console.log(`${u.bold("Store")} objects=${Qi(n.store.objects)} bytes=${Qi(n.store.total_bytes)}${n.store.over_loader_cap?u.red(" OVER the loader's total cap"):""}${(n.store.unexpected_objects??0)>0?u.yellow(` ${n.store.unexpected_objects} object(s) that are not the writer's`):""}`);let s=n.index.matches_store===null?u.yellow("unknown"):n.index.matches_store?u.green("matches the store"):u.yellow("differs from what the store and eligibility imply (the next run settles it)");console.log(`${u.bold("Index")} ${n.index.present===null?u.yellow("unknown"):n.index.present?`${Qi(n.index.entries)} entries, generated ${n.index.generated_at??"?"}`:u.dim("not written yet")} ${s}`);let i=n.last_reconcile;console.log(`${u.bold("Last reconcile")} ${i?`${i.at} (${JSON.stringify(i.summary)})`:u.dim("none recorded")}`),console.log(`${u.bold("Anonymity")} ${n.anonymity_findings===null?u.yellow("unknown"):n.anonymity_findings===0?"no findings":u.red(`${n.anonymity_findings} finding(s): see the audit log (neurobagel_anonymity_finding); ids are not shown here`)}`);let a=yZ({verification:n.verification,writerMode:n.writer.mode,now:new Date});if(n.verification)oDe(n.verification);if(a.note)console.log(`${u.bold("Verification")} ${lL(a.verdict)} ${a.note}`);else if(!n.verification)console.log(`${u.bold("Verification")} ${u.dim("none recorded; the writer is off, so none is expected")}`);if(n.needs_review.length>0){console.log(),console.log(u.bold(`Needs review (${n.needs_review.length})`));for(let l of n.needs_review)console.log(` ${l.id} ${l.source==="refusal"?u.red(`refused: ${l.code}${l.since?` (last confirmed ${l.since})`:""}`):u.yellow((l.flags??[]).join(", "))}`)}for(let l of n.warnings)console.log(u.yellow(`warning: ${l}`));let c=n.writer.mode==="store_unconfigured"||(n.anonymity_findings??0)>0||n.counts.eligible===null||a.verdict==="alarm";process.exitCode=c?1:RT(a.verdict)}).addHelpText("after","\nExit codes: 0 healthy or nothing to check, 1 an alarm, 2 could not be determined (no verification recorded while the writer is on, a record over 36 hours old, or an unknown verdict). The same as `verify`.");x1.command("verify").description("Run the verification sweep now: the store against eligibility, the node, registration and upstream drift (reports only; exit 0 healthy, 1 alarm, 2 unknown)").option("--json","Output raw JSON instead of the human summary").action(async(e)=>{if(!ke())return;let t=D("Verifying the Neurobagel federation...").start(),n;try{n=await Gpe(),t.stop()}catch(r){Ct(r,t,"Neurobagel verify failed"),process.exit(1);return}if(e.json)console.log(JSON.stringify(n,null,2));else if(console.log(),oDe(n),!n.heartbeat_written)console.log(u.yellow("The heartbeat could not be written: this run is not recorded."));process.exitCode=RT(n.overall)}).addHelpText("after","\nExit codes: 0 healthy or nothing to check, 1 an alarm, 2 could not be determined. The same as `status`.");Oe.addCommand(x1);Oe.addCommand(Xi);Oe.addCommand(Nl);Oe.addCommand(Qye);He();Ws();ro();Zm();th();Ym();He();Zm();th();var g2t=Nn["cli.gaps.section.title"];function sDe(e){if(e.gaps===void 0)return[e.unknownReason??Nn["cli.gaps.unknown"]];let t=nk(e.gaps,{orcidVerified:e.orcidVerified}).map(oZ);if(e.sandboxCompleted===!1)t.push(rk());return t.length>0?t:[Nn["gaps.none"]]}function y2t(e){let t=sDe(e);return t.length===1&&t[0]===Nn["gaps.none"]}function R_(e){let t=e.gaps===void 0||y2t(e);console.log(),console.log(u.bold(g2t));for(let n of sDe(e))console.log(` ${t?u.dim(n):u.yellow(n)}`)}function v1(e,t,n={}){let r=n.indent??" ";console.log(),console.log(`${r}${e}`);for(let o of t)console.log(`${r} ${u.yellow(o.label)} ${ET(o)}`)}Je();sp();gr();dn();He();ek();import{hostname as b2t}from"os";Je();dn();function w2t(e){let t=e.replace(/[\x00-\x1f\x7f]/g,"").replace(/\s+/g," ").trim();return t?t.slice(0,KQ):xT}function _2t(){try{return w2t(b2t())}catch{return xT}}function x2t(e,t,n=_T){return e+(t+n)*1000}function cDe(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 v2t=15000,iDe=1000,k2t=5000,aDe=3;function E2t(e){if(e instanceof L&&e.statusCode!==0)return`HTTP ${e.statusCode}`;return G(e)}function S2t(e){if(typeof AbortSignal.any==="function")return AbortSignal.any(e);let t=new AbortController;for(let n of e){if(n.aborted){t.abort();break}n.addEventListener("abort",()=>t.abort(),{once:!0})}return t.signal}function $2t(e,t){return new Promise((n)=>{if(t.aborted){n();return}let r=setTimeout(()=>{t.removeEventListener("abort",o),n()},e);function o(){clearTimeout(r),n()}t.addEventListener("abort",o,{once:!0})})}async function D2t(e,t={}){let n=Date.now(),r=x2t(n,e.expires_in,t.graceSeconds??_T),o=Math.max(e.interval*1000,iDe),s=new AbortController,i=()=>s.abort();process.on("SIGINT",i);let a=0;try{while(!0){if(s.signal.aborted)return{kind:"cancelled"};if(Date.now()>=r)return{kind:"unreachable",detail:"gave up waiting to reach NEMAR"};if(await $2t(o,s.signal),s.signal.aborted)return{kind:"cancelled"};let c=S2t([s.signal,AbortSignal.timeout(v2t)]),l;try{l=await rhe(e.device_code,c),a=0}catch(d){if(s.signal.aborted)return{kind:"cancelled"};if(d instanceof L&&d.statusCode===0){console.log(u.dim(" NEMAR is unreachable; retrying...")),a=0;continue}let f=E2t(d);if(a+=1,Dn(`poll error ${a}/${aDe}: ${f} -- ${G(d)}`),console.log(u.dim(` NEMAR answered with an error (${f}); retrying...`)),a>=aDe)return{kind:"server_error",detail:f};continue}if(l.status==="pending")continue;if(l.status==="slow_down"){o=Math.max(o+k2t,e.interval*1000,iDe);continue}if(l.status==="success")return{...l.data,kind:"success"};if(l.error==="expired_token")return{kind:"expired",message:l.message};if(l.error==="access_denied")return{kind:"denied",message:l.message};return{kind:"invalid",message:l.message}}}finally{process.off("SIGINT",i)}}async function yL(e={}){let t;try{t=await nhe(_2t())}catch(n){return{kind:"start_failed",detail:G(n)}}if(console.log(` ${t.verification_uri_complete}`),console.log(` Code: ${u.cyan(t.user_code)}`),console.log(u.dim(" (if the page asks for it)")),console.log(),e.open!==!1&&gg(t.verification_uri_complete))console.log(u.dim(" (trying to open your browser; use the link above if it doesn't)")),console.log();return D2t(t)}lo();var lDe="NEMAR_DATA_HOSTS",R2t="NEMAR_DATA_HOSTS_ONLY",C2t="https://private.nemar.org",A2t="https://private-test.nemar.org",O2t=/^[a-z]{2,3}[0-9]{6}$/;function k1(e){return O2t.test(e)}function T2t(e){return e}function uDe(e){return e==="127.0.0.1"||e==="localhost"||e==="[::1]"}function dDe(e){let t=e.trim();if(t===""||/[?#@]/.test(t))return null;let n;try{n=new URL(t)}catch{return null}if(n.username!==""||n.password!=="")return null;if(n.pathname!=="/")return null;if(n.protocol==="https:")return n.origin;if(n.protocol==="http:"&&uDe(n.hostname))return n.origin;return null}function fDe(e){let t=[],n=[];for(let r of(e??"").split(",")){let o=r.trim();if(o==="")continue;let s=dDe(o);if(s===null)n.push(o);else if(!t.includes(s))t.push(s)}return{origins:t,rejected:n}}function pDe(e){return e.env??process.env}function E1(e={}){let t=pDe(e),n=e.isDevBuild??Nf,r=t[R2t]==="1"?[]:[n?A2t:C2t],{origins:o}=fDe(t[lDe]);return[...r,...o.filter((s)=>!r.includes(s))].map(T2t)}function mDe(e={}){return fDe(pDe(e)[lDe]).rejected}function S1(e,t={}){let n=dDe(e);if(n===null)return null;return E1(t).find((r)=>r===n)??null}function $1(e,t={}){return S1(e,t)!==null}function hDe(e,t={}){let n;try{n=new URL(e)}catch{return null}if(n.username!==""||n.password!=="")return null;return S1(n.origin,t)}function Zdn(e,t){if(e.protocol==="https:")return!0;return e.protocol==="http:"&&uDe(e.hostname)&&new URL(t).protocol==="http:"}var P2t="NEMAR_DATA_HOST_TIMEOUT_MS";function gDe(e,t=process.env){let n=t[P2t];if(n===void 0||!/^[0-9]+$/.test(n))return e;let r=Number(n);return r>0&&r<e?r:e}function yDe(e){if(!(e instanceof Error))return"error";let t=e.code;return typeof t==="string"&&/^[A-Z][A-Z0-9_]+$/.test(t)?`${e.name} ${t}`:e.name}var I2t="nemar";function bDe(e){let t={};for(let n of e.split(`
|
|
1650
1650
|
`)){let r=n.replace(/\r$/,"");if(r==="")break;let o=r.indexOf("=");if(o<=0)continue;t[r.slice(0,o)]=r.slice(o+1)}return t}function bL(e,t={}){let{protocol:n,host:r}=e;if(!n||!r)return!1;if(/[/?#@\s]/.test(r))return!1;return $1(`${n}://${r}`,t)}function wDe(e,t,n,r={}){if(e!=="get"||!n||!bL(t,r))return"";return`username=${I2t}
|
|
1651
1651
|
password=${n}
|
|
1652
1652
|
`}function _De(e){let t=e.filter((n)=>!n.startsWith("-"));return t[0]==="auth"&&t[1]==="git-credential"}Rb();import{appendFileSync as N2t,existsSync as Gd,mkdirSync as xDe,readFileSync as R1,writeFileSync as F2t}from"fs";import{homedir as M2t}from"os";import{join as D1}from"path";var{spawn:vDe}=globalThis.Bun;function Tp(){let e=D1(M2t(),".ssh");return{sshDir:e,privateKey:D1(e,"nemar_ed25519"),publicKey:D1(e,"nemar_ed25519.pub"),configFile:D1(e,"config")}}function kDe(){let e=Tp();return Gd(e.privateKey)&&Gd(e.publicKey)}async function EDe(e){let t=Tp();if(!Gd(t.sshDir))try{xDe(t.sshDir,{mode:448})}catch(n){return{success:!1,error:`Cannot create ~/.ssh directory: ${n.message}`}}if(Gd(t.privateKey))try{return{success:!0,publicKey:R1(t.publicKey,"utf-8").trim()}}catch(n){return{success:!1,error:`NEMAR SSH key exists but cannot read public key: ${n.message}`}}try{let n=vDe({cmd:["ssh-keygen","-t","ed25519","-f",t.privateKey,"-N","","-C",`nemar-cli-${e}`],stdout:"pipe",stderr:"pipe"}),r=await new Response(n.stderr).text();if(await n.exited!==0)return{success:!1,error:`ssh-keygen failed: ${r}`};return{success:!0,publicKey:R1(t.publicKey,"utf-8").trim()}}catch(n){return{success:!1,error:`Failed to generate SSH key: ${n.message}`}}}function SDe(){let e=Tp();if(!Gd(e.publicKey))return null;try{return R1(e.publicKey,"utf-8").trim()}catch{return null}}function j2t(){let e=Tp();if(!Gd(e.configFile))return!1;try{let t=R1(e.configFile,"utf-8");return t.includes("IdentityFile ~/.ssh/nemar_ed25519")||t.includes(`IdentityFile ${e.privateKey}`)}catch{return!1}}function $De(){let e=Tp();if(!Gd(e.sshDir))try{xDe(e.sshDir,{mode:448})}catch(n){return{success:!1,error:`Cannot create ~/.ssh directory: ${n.message}`}}if(j2t())return{success:!0};let t=`
|
|
@@ -1686,7 +1686,7 @@ Examples:
|
|
|
1686
1686
|
$ nemar auth whoami # Alias for status
|
|
1687
1687
|
$ nemar auth switch # Switch between accounts
|
|
1688
1688
|
$ nemar auth logout # Clear active account
|
|
1689
|
-
$ nemar auth logout --all # Clear all accounts`);function L2t(e){if(!e.hasStoredKey)return{kind:"fresh"};let t=e.username||"unknown";return e.storedKeyState==="invalid"?{kind:"stale",username:t}:{kind:"active",username:t}}function _L(e){if(e.username&&Tfe(e.username)==="key_taken")console.log(u.yellow(` This machine already has a different account stored as '${e.username}'.`)),console.log(u.dim(" Your credentials stay under the old name; 'nemar auth switch' still selects that one."));if(Rn("username",e.username??void 0),Rn("email",e.email),Rn("githubUsername",e.github_username??void 0),e.service_access!==void 0)Rn("serviceAccess",e.service_access);if(e.profile_gaps!==void 0)Rn("profileGaps",e.profile_gaps);if(e.sandbox_completed!==void 0)Rn("sandboxCompleted",e.sandbox_completed);if(e.sandbox_dataset_id)Rn("sandboxDatasetId",e.sandbox_dataset_id);if(e.orcid_verified!==void 0)Rn("orcidVerified",e.orcid_verified);if(Rn("role",e.role),e.account_kind!==void 0)Rn("accountKind",e.account_kind)}async function xL(e,t,n,r){let o=Afe(e),s=n.source==="device"?{keySource:"device",keyId:n.key.id,keyName:n.key.name,keyCreatedAt:n.key.created_at}:{keySource:"paste",keyId:void 0,keyName:void 0,keyCreatedAt:void 0},i;try{({previous:i}=Ofe(o,{apiKey:t,email:e.email,...s}))}catch(l){if(n.source==="device")try{await ahe(n.key.id,t)}catch{}console.log(),console.log(u.red(` Could not save your credentials (${G(l)}).${n.source==="device"?" The new key was revoked;":""} fix ${zI()} and run \`nemar auth login\` again.`)),process.exitCode=1;return}_L(e),console.log();let a=n.source==="paste"?"Welcome back":"Welcome";if(console.log(` ${a}${e.username?`, ${u.cyan(e.username)}`:""}!`),e.role==="owner")console.log(` ${u.red("Owner access enabled")}`);else if(e.role==="admin")console.log(` ${u.magenta("Admin access enabled")}`);if(!e.sandbox_completed)console.log(),console.log(u.yellow(" Note: Sandbox training required before uploading datasets")),console.log(u.dim(" Run 'nemar sandbox' to complete training"));if(n.source==="device"&&i?.keySource==="device"&&i.keyId!==void 0&&i.keyId!==n.key.id)try{if(await PS(i.keyId),!r)console.log(u.dim(" (replaced this machine's previous key)"))}catch(l){console.log(u.yellow(` Could not revoke this machine's previous key (${G(l)}); it stays active until you run \`nemar auth keys revoke ${i.keyId}\`.`))}let c=Vt();R_({gaps:c.profileGaps,orcidVerified:c.orcidVerified,sandboxCompleted:c.sandboxCompleted})}function ODe(e){let{lines:t,exitCode:n}=cDe(e);console.log();let r=e.kind==="cancelled"?u.yellow:u.red;for(let o of t)console.log(r(o));process.exitCode=n}async function vL(e){if(e.key!==void 0&&e.key.trim()===""){console.log(u.red("--key was given but is empty.")),console.log(u.dim(" Pass the key itself, or drop --key to sign in with your browser instead.")),Ao(),process.exitCode=1;return}let t=e.key||process.env.NEMAR_API_KEY,n=!1;if(ze()){let o=Vt(),s=o.apiKey,i="unknown";if(s){let c=D("Checking your saved credentials...").start();try{i=(await _N(s)).valid?"valid":"invalid",c.stop()}catch(l){if(c.stop(),l instanceof vu)return;i=l instanceof L&&l.statusCode===401?"invalid":"unknown"}}n=i==="invalid";let a=L2t({hasStoredKey:!0,storedKeyState:i,username:o.username});if(t){if(a.kind==="active"){if(console.log(u.yellow(`Already logged in as ${a.username}`)),console.log(u.dim(" This will add another account (use 'nemar auth switch' to switch)")),await De("Add a different account?",e)!=="confirmed")return}else if(a.kind==="stale")console.log(u.yellow(`Your saved API key for ${a.username} is no longer valid.`)),console.log(u.dim(" It may have expired or been revoked (e.g. via 'nemar auth regenerate-key').")),console.log(u.dim(" Enter your new key below to re-authenticate."))}else if(a.kind==="active")console.log(u.yellow(`Already signed in as ${a.username}; signing in again refreshes this machine's key.`));else if(a.kind==="stale")console.log(u.yellow(`Your saved key for ${a.username} is no longer valid.`)),console.log(u.dim(" Sign in again below; the browser step continues."))}if(t){await q2t(t,n);return}let r=await yL({open:e.open});if(r.kind==="success"){await xL(r.user,r.api_key,{source:"device",key:r.key},n);return}ODe(r)}async function q2t(e,t){let n=D("Validating API key...").start();try{let r=await _N(e);if(!r.valid){go(n,"Invalid API key","Check that your API key is correct"),process.exitCode=1;return}n.succeed("Login successful"),await xL(r.user,e,{source:"paste"},t)}catch(r){if(process.exitCode=1,r instanceof L){if(n.fail(r.message),Ab(r.message),r.statusCode===401)console.log(u.dim(" Check that your API key is correct"));else if(r.statusCode===403)console.log(u.dim(" Your account is not active; verify your email first"))}else n.fail("Connection failed"),Ab("Connection failed"),console.log(u.dim(" Check your internet connection"))}}var B2t=eo.command("login").description("Sign in with your browser (opens NEMAR's device sign-in page)").option("-k, --key <key>","Paste an existing API key instead (alternative: NEMAR_API_KEY)").option("--no-open","Print the sign-in link instead of trying to open a browser").option(
|
|
1689
|
+
$ nemar auth logout --all # Clear all accounts`);function L2t(e){if(!e.hasStoredKey)return{kind:"fresh"};let t=e.username||"unknown";return e.storedKeyState==="invalid"?{kind:"stale",username:t}:{kind:"active",username:t}}function _L(e){if(e.username&&Tfe(e.username)==="key_taken")console.log(u.yellow(` This machine already has a different account stored as '${e.username}'.`)),console.log(u.dim(" Your credentials stay under the old name; 'nemar auth switch' still selects that one."));if(Rn("username",e.username??void 0),Rn("email",e.email),Rn("githubUsername",e.github_username??void 0),e.service_access!==void 0)Rn("serviceAccess",e.service_access);if(e.profile_gaps!==void 0)Rn("profileGaps",e.profile_gaps);if(e.sandbox_completed!==void 0)Rn("sandboxCompleted",e.sandbox_completed);if(e.sandbox_dataset_id)Rn("sandboxDatasetId",e.sandbox_dataset_id);if(e.orcid_verified!==void 0)Rn("orcidVerified",e.orcid_verified);if(Rn("role",e.role),e.account_kind!==void 0)Rn("accountKind",e.account_kind)}async function xL(e,t,n,r){let o=Afe(e),s=n.source==="device"?{keySource:"device",keyId:n.key.id,keyName:n.key.name,keyCreatedAt:n.key.created_at}:{keySource:"paste",keyId:void 0,keyName:void 0,keyCreatedAt:void 0},i;try{({previous:i}=Ofe(o,{apiKey:t,email:e.email,...s}))}catch(l){if(n.source==="device")try{await ahe(n.key.id,t)}catch{}console.log(),console.log(u.red(` Could not save your credentials (${G(l)}).${n.source==="device"?" The new key was revoked;":""} fix ${zI()} and run \`nemar auth login\` again.`)),process.exitCode=1;return}_L(e),console.log();let a=n.source==="paste"?"Welcome back":"Welcome";if(console.log(` ${a}${e.username?`, ${u.cyan(e.username)}`:""}!`),e.role==="owner")console.log(` ${u.red("Owner access enabled")}`);else if(e.role==="admin")console.log(` ${u.magenta("Admin access enabled")}`);if(!e.sandbox_completed)console.log(),console.log(u.yellow(" Note: Sandbox training required before uploading datasets")),console.log(u.dim(" Run 'nemar sandbox' to complete training"));if(n.source==="device"&&i?.keySource==="device"&&i.keyId!==void 0&&i.keyId!==n.key.id)try{if(await PS(i.keyId),!r)console.log(u.dim(" (replaced this machine's previous key)"))}catch(l){console.log(u.yellow(` Could not revoke this machine's previous key (${G(l)}); it stays active until you run \`nemar auth keys revoke ${i.keyId}\`.`))}let c=Vt();R_({gaps:c.profileGaps,orcidVerified:c.orcidVerified,sandboxCompleted:c.sandboxCompleted})}function ODe(e){let{lines:t,exitCode:n}=cDe(e);console.log();let r=e.kind==="cancelled"?u.yellow:u.red;for(let o of t)console.log(r(o));process.exitCode=n}async function vL(e){if(e.key!==void 0&&e.key.trim()===""){console.log(u.red("--key was given but is empty.")),console.log(u.dim(" Pass the key itself, or drop --key to sign in with your browser instead.")),Ao(),process.exitCode=1;return}let t=e.key||process.env.NEMAR_API_KEY,n=!1;if(ze()){let o=Vt(),s=o.apiKey,i="unknown";if(s){let c=D("Checking your saved credentials...").start();try{i=(await _N(s)).valid?"valid":"invalid",c.stop()}catch(l){if(c.stop(),l instanceof vu)return;i=l instanceof L&&l.statusCode===401?"invalid":"unknown"}}n=i==="invalid";let a=L2t({hasStoredKey:!0,storedKeyState:i,username:o.username});if(t){if(a.kind==="active"){if(console.log(u.yellow(`Already logged in as ${a.username}`)),console.log(u.dim(" This will add another account (use 'nemar auth switch' to switch)")),await De("Add a different account?",e)!=="confirmed")return}else if(a.kind==="stale")console.log(u.yellow(`Your saved API key for ${a.username} is no longer valid.`)),console.log(u.dim(" It may have expired or been revoked (e.g. via 'nemar auth regenerate-key').")),console.log(u.dim(" Enter your new key below to re-authenticate."))}else if(a.kind==="active")console.log(u.yellow(`Already signed in as ${a.username}; signing in again refreshes this machine's key.`));else if(a.kind==="stale")console.log(u.yellow(`Your saved key for ${a.username} is no longer valid.`)),console.log(u.dim(" Sign in again below; the browser step continues."))}if(t){await q2t(t,n);return}let r=await yL({open:e.open});if(r.kind==="success"){await xL(r.user,r.api_key,{source:"device",key:r.key},n);return}ODe(r)}async function q2t(e,t){let n=D("Validating API key...").start();try{let r=await _N(e);if(!r.valid){go(n,"Invalid API key","Check that your API key is correct"),process.exitCode=1;return}n.succeed("Login successful"),await xL(r.user,e,{source:"paste"},t)}catch(r){if(process.exitCode=1,r instanceof L){if(n.fail(r.message),Ab(r.message),r.statusCode===401)console.log(u.dim(" Check that your API key is correct"));else if(r.statusCode===403)console.log(u.dim(" Your account is not active; verify your email first"))}else n.fail("Connection failed"),Ab("Connection failed"),console.log(u.dim(" Check your internet connection"))}}var B2t=eo.command("login").description("Sign in with your browser (opens NEMAR's device sign-in page)").option("-k, --key <key>","Paste an existing API key instead (alternative: NEMAR_API_KEY)").option("--no-open","Print the sign-in link instead of trying to open a browser").option(Ye,nt).option(yt,ht).action(vL);vr(B2t,`
|
|
1690
1690
|
Description:
|
|
1691
1691
|
Prints a link and a code, tries to open your browser to it, then waits
|
|
1692
1692
|
for you to authorize this machine there. The link and code are the real
|
|
@@ -1705,7 +1705,7 @@ Examples:
|
|
|
1705
1705
|
$ nemar auth login # Browser sign-in
|
|
1706
1706
|
$ nemar auth login --no-open # Print the link only (headless)
|
|
1707
1707
|
$ nemar auth login -k nemar_abc123... # Paste an existing key`);function DDe(e){if(e.length===0||process.stdin.isTTY)return!1;return console.log(u.yellow(`Provide ${e.join(", ")} (this terminal cannot prompt).`)),process.exitCode=1,!0}async function C1(e){let{value:t}=await Ae.prompt([{type:"input",name:"value",message:e,validate:(n)=>n?.trim()?!0:"Required"}]);return String(t).trim()}async function U2t(e){let t=D("Checking your profile...").start(),n;try{n=await Wr(),t.stop()}catch(l){t.fail(`Could not read your profile: ${G(l)}`),process.exitCode=1;return}let r=new Set((n.profile_gaps??[]).map((l)=>l.field)),o=r.has("username")||!n.username,s=n.username_auto_assigned===!0,i=[];if(o&&!e.username)i.push("--username");if(s&&!e.username&&e.no===!0)i.push("--username");if(r.has("github_username")&&!e.github)i.push("--github");if(r.has("city")&&!e.city)i.push("--city");if(r.has("country")&&!e.country)i.push("--country");if(DDe(i))return;let a={};if(s){if(e.username){if(e.username!==n.username)a.username=e.username}else if(await De(`Keep the username '${n.username}'?`,e,!0)==="declined")a.username=e.username??await C1("New username:")}else if(o)if(e.username)a.username=e.username;else{let l=await che().catch(()=>null),{chosen:d}=await Ae.prompt([{type:"input",name:"chosen",message:"Choose a username:",default:l?.suggestion??void 0,validate:(f)=>f?.trim()?!0:"A username is required"}]);a.username=String(d).trim()}if(r.has("github_username"))a.github_username=e.github??await C1("GitHub username (for PR collaboration):");if(r.has("city"))a.city=e.city??await C1("City (for export-control screening):");if(r.has("country"))a.country=e.country??await C1("Country (for export-control screening):");if(Object.keys(a).length>0){let l=D("Saving your profile...").start();try{await xN(a),l.succeed("Profile updated")}catch(d){jl(l,d,"Could not save your profile");return}}if(e.uploadAccess!==!1){let l=e.why?.trim();if(!l){if(DDe(["--why"]))return;let d=await Ae.prompt([{type:"input",name:"why",message:"What do you intend to upload to NEMAR?",validate:TDe}]);l=String(d.why).trim()}await PDe(l)}await C_();let c=Vt();R_({gaps:c.profileGaps,orcidVerified:c.orcidVerified,sandboxCompleted:c.sandboxCompleted})}async function O1(e){console.log(u.cyan("NEMAR Account Sign-Up")),console.log(u.dim(`Sign in with your browser to create or continue your account
|
|
1708
|
-
`)),await cfe();let t=await yL({open:e.open});if(t.kind!=="success"){ODe(t);return}await xL(t.user,t.api_key,{source:"device",key:t.key},!1),await U2t(e)}var H2t=eo.command("signup").description("Create or continue your NEMAR account (browser sign-in, then a few questions)").option("--username <name>","Username to set, or to change to").option("--github <handle>","GitHub username").option("--city <city>","City").option("--country <country>","Country").option("--why <text>","What you intend to upload (20-500 characters)").option("--no-upload-access","Skip the upload-access request").option("--no-open","Print the sign-in link instead of trying to open a browser").option(
|
|
1708
|
+
`)),await cfe();let t=await yL({open:e.open});if(t.kind!=="success"){ODe(t);return}await xL(t.user,t.api_key,{source:"device",key:t.key},!1),await U2t(e)}var H2t=eo.command("signup").description("Create or continue your NEMAR account (browser sign-in, then a few questions)").option("--username <name>","Username to set, or to change to").option("--github <handle>","GitHub username").option("--city <city>","City").option("--country <country>","Country").option("--why <text>","What you intend to upload (20-500 characters)").option("--no-upload-access","Skip the upload-access request").option("--no-open","Print the sign-in link instead of trying to open a browser").option(Ye,nt).option(yt,ht).action(O1);vr(H2t,`
|
|
1709
1709
|
Description:
|
|
1710
1710
|
Signs in with your browser like 'nemar auth login' -- ORCID creates a
|
|
1711
1711
|
brand-new account the first time, or signs into an existing one. Then
|
|
@@ -1730,7 +1730,7 @@ Description:
|
|
|
1730
1730
|
Examples:
|
|
1731
1731
|
$ nemar auth switch # Interactive picker
|
|
1732
1732
|
$ nemar auth switch yahya # Switch by NEMAR username
|
|
1733
|
-
$ nemar auth switch cool-vibers # Switch by GitHub username`);async function RDe(e,t){if(t.revokeKey===!1)return;if(!(t.revokeKey===!0||e.keySource==="device")){if(e.keySource!=="device")console.log(u.dim(" This key may be used on other machines and was kept; revoke it with 'nemar auth keys revoke' or in Settings on nemar.org."));return}try{await PS("current")}catch(r){if(r instanceof L&&r.statusCode===401)return;console.log(u.yellow(` Could not revoke this machine's key (${G(r)}); it stays valid.`))}}async function EL(e){if(!ze()){console.log(u.yellow("Not currently authenticated"));return}if(e.all){let o=Nb();if(await De(`Log out all ${o.length} stored account(s)?`,e)!=="confirmed")return;for(let i of o)VI(i.key),await RDe(i,e);Cfe(),console.log(u.green("All accounts removed"));return}let t=Vt();if(await De(`Log out ${t.username||"current user"}?`,e)!=="confirmed")return;await RDe(t,e),Rfe(),console.log(u.green("Logged out successfully"));let r=Nb();if(r.length>0){let o=r.find((s)=>s.active);if(o)console.log(` Switched to ${u.cyan(o.username)}`)}}var W2t=eo.command("logout").description("Remove the active account (use --all to remove all)").option(
|
|
1733
|
+
$ nemar auth switch cool-vibers # Switch by GitHub username`);async function RDe(e,t){if(t.revokeKey===!1)return;if(!(t.revokeKey===!0||e.keySource==="device")){if(e.keySource!=="device")console.log(u.dim(" This key may be used on other machines and was kept; revoke it with 'nemar auth keys revoke' or in Settings on nemar.org."));return}try{await PS("current")}catch(r){if(r instanceof L&&r.statusCode===401)return;console.log(u.yellow(` Could not revoke this machine's key (${G(r)}); it stays valid.`))}}async function EL(e){if(!ze()){console.log(u.yellow("Not currently authenticated"));return}if(e.all){let o=Nb();if(await De(`Log out all ${o.length} stored account(s)?`,e)!=="confirmed")return;for(let i of o)VI(i.key),await RDe(i,e);Cfe(),console.log(u.green("All accounts removed"));return}let t=Vt();if(await De(`Log out ${t.username||"current user"}?`,e)!=="confirmed")return;await RDe(t,e),Rfe(),console.log(u.green("Logged out successfully"));let r=Nb();if(r.length>0){let o=r.find((s)=>s.active);if(o)console.log(` Switched to ${u.cyan(o.username)}`)}}var W2t=eo.command("logout").description("Remove the active account (use --all to remove all)").option(Ye,nt).option(yt,ht).option("--all","Remove all stored accounts").option("--revoke-key","Revoke this machine's key even if it may be shared").option("--no-revoke-key","Never revoke the key server-side, only clear it locally").action(EL);vr(W2t,`
|
|
1734
1734
|
Description:
|
|
1735
1735
|
Clears the active account's credential from this machine. A key this
|
|
1736
1736
|
machine's own 'nemar auth login' minted (device sign-in) is also revoked
|
|
@@ -1931,7 +1931,7 @@ Description:
|
|
|
1931
1931
|
Examples:
|
|
1932
1932
|
$ nemar auth profile orcid link
|
|
1933
1933
|
$ nemar auth profile orcid relink --no-open
|
|
1934
|
-
$ nemar auth profile orcid unlink --yes`);He();
|
|
1934
|
+
$ nemar auth profile orcid unlink --yes`);He();Je();ec();Ko();nh();import{mkdirSync as mOt,readFileSync as hOt,writeFileSync as gOt}from"fs";import{homedir as yOt}from"os";import{join as FDe}from"path";function MDe(){return process.env.NEMAR_CONFIG_DIR||FDe(yOt(),".config","nemar")}function jDe(){return FDe(MDe(),"completion-cache.json")}var bOt=3600000,wOt=ee({cachedAt:j(),data:Jv});function LDe(){try{let e=hOt(jDe(),"utf-8"),t=wOt.safeParse(JSON.parse(e));if(!t.success)return null;if(Date.now()-t.data.cachedAt>=bOt)return null;return t.data.data}catch(e){if(process.env.VERBOSE)process.stderr.write(`[completion] cache read failed: ${e instanceof Error?e.message:e}
|
|
1935
1935
|
`);return null}}function qDe(e){try{mOt(MDe(),{recursive:!0}),gOt(jDe(),JSON.stringify({cachedAt:Date.now(),data:e}))}catch(t){if(process.env.VERBOSE)process.stderr.write(`[completion] cache write failed: ${t instanceof Error?t.message:t}
|
|
1936
1936
|
`)}}async function $L(){let e=await Ome();qDe(e)}function Pp(){$L().catch((e)=>{if(process.env.VERBOSE)process.stderr.write(`[completion] opportunistic refresh failed: ${e instanceof Error?e.message:e}
|
|
1937
1937
|
`)})}var _Ot=["# nemar completion for bash","# Install (current shell): source <(nemar completion bash)","# Install (persistent): nemar completion bash > /usr/local/etc/bash_completion.d/nemar","_nemar_complete() {"," local cur words_to_complete raw line lines n",' cur="${COMP_WORDS[COMP_CWORD]}"',' words_to_complete=("${COMP_WORDS[@]:1:COMP_CWORD}")',' raw="$(nemar __complete -- "${words_to_complete[@]}" 2>/dev/null)"'," COMPREPLY=()",' if [[ -n "$raw" ]]; then'," lines=()",' while IFS= read -r line; do lines+=("$line"); done <<< "$raw"'," n=${#lines[@]}"," if (( n > 0 )); then",' COMPREPLY=("${lines[@]:0:n-1}")'," fi"," fi","}","complete -F _nemar_complete nemar",""],xOt=["#compdef nemar","# nemar completion for zsh","# Install (current shell): source <(nemar completion zsh)",'# Install (persistent): nemar completion zsh > "${fpath[1]}/_nemar" (then restart your shell)',"_nemar() {"," local -a request_words lines candidates",' request_words=("${(@)words[2,CURRENT]}")',' lines=("${(@f)$(nemar __complete -- "${request_words[@]}" 2>/dev/null)}")'," if (( ${#lines[@]} > 0 )); then",' candidates=("${(@)lines[1,-2]}")'," else"," candidates=()"," fi",' compadd -- "${candidates[@]}"',"}",'_nemar "$@"',""],vOt=["# nemar completion for fish","# Install: nemar completion fish > ~/.config/fish/completions/nemar.fish","function __nemar_complete_words"," set -l tokens (commandline -opc)"," set -l cur (commandline -ct)"," set -l request_words"," if test (count $tokens) -gt 1"," set request_words $tokens[2..-1]"," end"," set request_words $request_words $cur"," set -l lines (nemar __complete -- $request_words 2>/dev/null)"," if test (count $lines) -gt 0"," set -e lines[-1]"," end"," for line in $lines"," echo $line"," end","end","complete -c nemar -f -a '(__nemar_complete_words)'",""];function BDe(){return _Ot.join(`
|
|
@@ -1960,7 +1960,7 @@ Setup:
|
|
|
1960
1960
|
|
|
1961
1961
|
Examples:
|
|
1962
1962
|
$ nemar completion bash
|
|
1963
|
-
$ nemar completion refresh`);He();import{existsSync as ms,mkdtempSync as WPt,readFileSync as F_,writeFileSync as oCe}from"fs";import{tmpdir as KPt}from"os";import{join as jp,resolve as Ns}from"path";var{spawn:xo}=globalThis.Bun;Ws();ro();th();DL();Ep();var RL=["public","attribution","sharealike","noncommercial","noderiv","unknown"];var Kfn=["Filter by modality: a whole-token, case-insensitive match against the dataset's modality","list, so `eeg` does not match `ieeg`. A comma-separated list matches a dataset holding any","of its modalities, at most 32 distinct values; more is refused."].join(" "),CL=["Filter by modality (eeg, emg, meg, etc.), matched as a whole token;","a comma list matches any of up to 32"].join(" ");mk();class Zi extends Error{reason;constructor(e,t){super(t);this.name="RangeParseError",this.reason=e}}var SOt={"":1,b:1,kb:1024,mb:1048576,gb:1073741824,tb:1099511627776},$Ot={"":1,s:1,m:60,h:3600,d:86400},DOt={"":1};function ROt(e){switch(e){case"bytes":return SOt;case"duration":return $Ot;case"number":return DOt}}var COt=/^(-?\d+(?:\.\d+)?)([a-z]*)$/i;function AL(e,t){let n=COt.exec(e);if(!n)throw new Zi("non-numeric",`"${e}" is not a valid number`);let[,r,o]=n,s=o.toLowerCase(),i=Number(r);if(!Number.isFinite(i))throw new Zi("non-finite",`"${e}" is not a finite number`);if(i<0)throw new Zi("negative",`"${e}" must not be negative`);if(s!==""&&t==="number")throw new Zi("unit-not-allowed",`"${e}" has a unit, but this facet takes a plain number`);let c=ROt(t)[s];if(c===void 0)throw new Zi("unknown-unit",`"${s}" is not a recognized ${t} unit`);return i*c}function GDe(e,t){let n=e.trim();if(n.includes("..")){let o=n.split("..");if(o.length!==2)throw new Zi("malformed",`"${e}" must contain at most one ".." separator`);let[s,i]=o,a=s.trim(),c=i.trim();if(a===""&&c==="")throw new Zi("malformed",`"${e}" does not specify either bound`);let l=a===""?null:AL(a,t),d=c===""?null:AL(c,t);if(l!==null&&d!==null&&l>d)throw new Zi("inverted",`"${e}" is inverted: ${l} is greater than ${d}`);return{min:l,max:d}}let r=AL(n,t);return{min:r,max:r}}Za();ec();
|
|
1963
|
+
$ nemar completion refresh`);He();import{existsSync as ms,mkdtempSync as WPt,readFileSync as F_,writeFileSync as oCe}from"fs";import{tmpdir as KPt}from"os";import{join as jp,resolve as Ns}from"path";var{spawn:xo}=globalThis.Bun;Ws();ro();th();DL();Ep();var RL=["public","attribution","sharealike","noncommercial","noderiv","unknown"];var Kfn=["Filter by modality: a whole-token, case-insensitive match against the dataset's modality","list, so `eeg` does not match `ieeg`. A comma-separated list matches a dataset holding any","of its modalities, at most 32 distinct values; more is refused."].join(" "),CL=["Filter by modality (eeg, emg, meg, etc.), matched as a whole token;","a comma list matches any of up to 32"].join(" ");mk();class Zi extends Error{reason;constructor(e,t){super(t);this.name="RangeParseError",this.reason=e}}var SOt={"":1,b:1,kb:1024,mb:1048576,gb:1073741824,tb:1099511627776},$Ot={"":1,s:1,m:60,h:3600,d:86400},DOt={"":1};function ROt(e){switch(e){case"bytes":return SOt;case"duration":return $Ot;case"number":return DOt}}var COt=/^(-?\d+(?:\.\d+)?)([a-z]*)$/i;function AL(e,t){let n=COt.exec(e);if(!n)throw new Zi("non-numeric",`"${e}" is not a valid number`);let[,r,o]=n,s=o.toLowerCase(),i=Number(r);if(!Number.isFinite(i))throw new Zi("non-finite",`"${e}" is not a finite number`);if(i<0)throw new Zi("negative",`"${e}" must not be negative`);if(s!==""&&t==="number")throw new Zi("unit-not-allowed",`"${e}" has a unit, but this facet takes a plain number`);let c=ROt(t)[s];if(c===void 0)throw new Zi("unknown-unit",`"${s}" is not a recognized ${t} unit`);return i*c}function GDe(e,t){let n=e.trim();if(n.includes("..")){let o=n.split("..");if(o.length!==2)throw new Zi("malformed",`"${e}" must contain at most one ".." separator`);let[s,i]=o,a=s.trim(),c=i.trim();if(a===""&&c==="")throw new Zi("malformed",`"${e}" does not specify either bound`);let l=a===""?null:AL(a,t),d=c===""?null:AL(c,t);if(l!==null&&d!==null&&l>d)throw new Zi("inverted",`"${e}" is inverted: ${l} is greater than ${d}`);return{min:l,max:d}}let r=AL(n,t);return{min:r,max:r}}Za();ec();Je();Ni();He();Ws();var F1="https://docs.nemar.org/policies/contributor-terms/",WDe={deposit_type:"owner",key_status:"destroyed",deidentified:!0};function AOt(e){let{depositType:t,keyStatus:n,confirmDeidentified:r,affirmNoDuplicate:o,upstreamSource:s}=e;if(!(t!==void 0||n!==void 0||r===!0||o===!0||s!==void 0))return null;if(t!=="owner"&&t!=="redistribution")throw Error(`--deposit-type must be "owner" or "redistribution" (got ${t??"nothing"}); it is required when attesting via flags.`);if(n!=="destroyed"&&n!=="retained")throw Error(`--key-status must be "destroyed" or "retained" (got ${n??"nothing"}); it is required when attesting via flags.`);if(r!==!0)throw Error("--confirm-deidentified is required when attesting via flags: you must confirm the dataset contains no identifiable personal information.");if(t==="redistribution"&&o!==!0)throw Error("Redistribution deposits require --affirm-no-duplicate: you must affirm the dataset is not already on NEMAR or an upstream archive in BIDS format.");if(t==="owner"&&o)throw Error("--affirm-no-duplicate only applies to --deposit-type redistribution.");let a={deposit_type:t,key_status:n,deidentified:!0};if(t==="redistribution"){if(a.no_duplicate=!0,s)a.upstream_source=s}else if(s)throw Error("--upstream-source only applies to --deposit-type redistribution.");return a}async function OOt(){console.log(),console.log(u.bold("Deposit attestation")),console.log(u.dim(` These answers are recorded with the dataset. Terms: ${F1}`));let{depositType:e}=await Ae.prompt([{type:"list",name:"depositType",message:"Which describes this deposit?",choices:[{name:"I own this dataset (or am authorized by the owner) and hold ethics permissions for public sharing",value:"owner"},{name:"I am redistributing a publicly released dataset whose license permits it",value:"redistribution"}]}]),{keyStatus:t}=await Ae.prompt([{type:"list",name:"keyStatus",message:"The key linking subject codes to participant identities:",choices:[{name:"Has been destroyed (dataset is anonymous)",value:"destroyed"},{name:"Is retained by the owning institution and is never transmitted to NEMAR",value:"retained"}]}]),n={deposit_type:e,key_status:t,deidentified:!0};if(e==="redistribution"){let{noDuplicate:o}=await Ae.prompt([{type:"confirm",name:"noDuplicate",message:"Do you affirm this dataset is NOT already available on NEMAR or an upstream archive (e.g. OpenNeuro) in BIDS format?",default:!1}]);if(!o)throw Error("Upload cancelled: NEMAR does not accept duplicates of datasets already archived in BIDS format.");n.no_duplicate=!0;let{upstream:s}=await Ae.prompt([{type:"input",name:"upstream",message:"Upstream source of this dataset in its original form (URL or accession; blank if none):"}]);if(s.trim())n.upstream_source=s.trim()}let{deidentified:r}=await Ae.prompt([{type:"confirm",name:"deidentified",message:"Do you confirm the dataset contains no identifiable personal information (HIPAA Safe Harbor identifiers removed, anatomical images defaced, headers scrubbed)?",default:!0}]);if(!r)throw Error("Upload cancelled: datasets must be de-identified before deposit. See the contributor terms for what must be removed.");return n}async function KDe(e,t=process.stdin.isTTY===!0){let n=AOt(e);if(n)return n;if(!t)throw Error(`Deposit attestation required: run interactively, or pass --deposit-type, --key-status, and --confirm-deidentified (plus --affirm-no-duplicate for redistribution). --yes does not substitute for attestation. Terms: ${F1}`);return OOt()}$g();var{Glob:JDe}=globalThis.Bun;var TOt=["stimuli/**","**/stimuli/**"],POt=["derivatives/**","**/derivatives/**"];function YDe(e,t){let n=e.trim();if(!n)return"";let r=n.startsWith(`${t}-`)?n.slice(t.length+1):n;return`${t}-${r}`}function IOt(e){let t=e.trim().replace(/^run-/,"");if(!t)return[];if(/^[1-9]$/.test(t))return[t,`0${t}`];return[t]}function NOt(e,t){let n=e.trim();if(!n)return"";return n.startsWith(`${t}-`)?n.slice(t.length+1):n}function Np(e){if(!e)return[];return e.split(",").map((t)=>t.trim()).filter(Boolean)}function FOt(e){let t=Array.from(new Set(e)).filter(Boolean);if(t.length===0)return[];if(t.length===1)return["--include",t[0]];let n=["-("];for(let r=0;r<t.length;r++){if(r>0)n.push("--or");n.push("--include",t[r])}return n.push("-)"),n}function M1(e){let t=[],n=[],r=Np(e.subjects).map((m)=>YDe(m,"sub"));if(r.length>0)t.push(r.map((m)=>`${m}/**`)),n.push(`subjects: ${r.join(", ")}`);let o=Np(e.sessions).map((m)=>YDe(m,"ses"));if(o.length>0)t.push(o.map((m)=>`**/${m}/**`)),n.push(`sessions: ${o.join(", ")}`);let s=Np(e.tasks).map((m)=>NOt(m,"task"));if(s.length>0)t.push(s.map((m)=>`**/*_task-${m}_*`)),n.push(`tasks: ${s.join(", ")}`);let i=Np(e.runs).flatMap(IOt);if(i.length>0)t.push(i.map((m)=>`**/*_run-${m}_*`)),n.push(`runs: ${i.join(", ")}`);let a=Np(e.datatypes);if(a.length>0)t.push(a.map((m)=>`**/${m}/**`)),n.push(`datatypes: ${a.join(", ")}`);let c=Np(e.include);if(c.length>0)t.push(c),n.push(`include: ${c.join(", ")}`);let l=Np(e.exclude),d=t.length>0||l.length>0,f=[];if(e.excludeStimuli)f.push(...TOt),n.push("skipping stimuli/ (use --stimuli to include)");if(e.excludeDerivatives)f.push(...POt),n.push("skipping derivatives/ (use --derivatives to include)");let p=[];for(let m of t)p.push(...FOt(m));for(let m of f)p.push("--exclude",m);for(let m of l)p.push("--exclude",m);if(l.length>0)n.push(`exclude: ${l.join(", ")}`);return{args:p,active:d,summary:n,includeGroups:t,excludePatterns:[...f,...l]}}function QDe(e,t){let n=MOt(t);for(let r of n.excludes)if(r.match(e))return!1;for(let r of n.includes){if(r.length===0)continue;if(!r.some((o)=>o.match(e)))return!1}return!0}var XDe=new WeakMap;function MOt(e){let t=XDe.get(e);if(t)return t;let n={includes:e.includeGroups.map((r)=>r.map((o)=>new JDe(o))),excludes:e.excludePatterns.map((r)=>new JDe(r))};return XDe.set(e,n),n}function ZDe(e,t){if(e&&e.length>0)return M1({});return M1({excludeStimuli:t.stimuli!==!0,excludeDerivatives:t.derivatives!==!0})}import{existsSync as LOt,readFileSync as qOt,statSync as tRe,writeFileSync as eRe}from"fs";import{homedir as TL}from"os";import{join as A_}from"path";var{spawn:T_}=globalThis.Bun;var OL={version:"3.0.2",specifier:"jsr:@bids/validator"};var wy=OL.version,O_=`${OL.specifier}@${wy}`,BOt=86400000,j1=16;async function _y(){try{let e=T_({cmd:["deno","--version"],stdout:"pipe",stderr:"pipe"}),t=await new Response(e.stdout).text();await e.exited;let n=t.match(/deno\s+(\d+\.\d+\.\d+)/);return{installed:!0,version:n?n[1]:void 0}}catch{return{installed:!1}}}function PL(){try{let e=process.platform,t=process.env.DENO_DIR||(e==="darwin"?A_(TL(),"Library","Caches","deno"):e==="win32"?A_(process.env.LOCALAPPDATA||A_(TL(),"AppData","Local"),"deno"):A_(TL(),".cache","deno")),n=A_(t,"deps");if(!LOt(n))return!0;let r=tRe(n);return Date.now()-r.mtimeMs>BOt}catch{return!0}}async function IL(){try{let e=T_({cmd:["deno","run","--node-modules-dir=none",`--reload=${O_}`,"-ERWN",O_,"--version"],stdout:"pipe",stderr:"pipe"}),t=await new Response(e.stdout).text();await e.exited;let n=t.match(/(\d+\.\d+\.\d+)/);return n?n[1]:null}catch{return null}}async function NL(){try{let e=T_({cmd:["deno","run","--node-modules-dir=none","-ERWN",O_,"--version"],stdout:"pipe",stderr:"pipe"}),t=await new Response(e.stdout).text();await e.exited;let n=t.match(/(\d+\.\d+\.\d+)/);return n?n[1]:null}catch{return null}}function nRe(e,t={}){let n=["run","--node-modules-dir=none"];if(t.forceReload)n.push(`--reload=${O_}`);if(n.push("-ERWN",O_,e),t.json)n.push("--json");if(t.config)n.push("--config",t.config);if(t.ignoreWarnings)n.push("--ignoreWarnings");if(t.recursive)n.push("--recursive");if(t.prune)n.push("--prune");if(t.verbose)n.push("--verbose");if(t.extraArgs?.length)n.push(...t.extraArgs);return n}var UOt=/\u001b\[[0-9;]*[A-Za-z]/g;function HOt(e){let t=e.replace(UOt,"").split(`
|
|
1964
1964
|
`).map((n)=>n.trim()).filter((n)=>n!==""&&!n.startsWith("Download"));return t.find((n)=>n.startsWith("error:"))??t.filter((n)=>!n.startsWith("at ")).pop()}async function rRe(e,t={}){let n=nRe(e,{...t,json:!0}),r=T_({cmd:["deno",...n],stdout:"pipe",stderr:"pipe",env:{...process.env,NO_COLOR:"1"}}),o=await new Response(r.stdout).text(),s=await new Response(r.stderr).text(),i=await r.exited;if(i!==0&&i!==j1){let f=HOt(s);throw Error(f?`BIDS validator failed (exit ${i}): ${f}`:`BIDS validator failed with exit code ${i}`)}let a;try{a=JSON.parse(o)}catch{throw Error(`Failed to parse validator output: ${o.slice(0,200)}`)}if(!Array.isArray(a?.issues?.issues))throw Error("The BIDS validator's report has no list of issues");let c=a.issues.issues,l=c.filter((f)=>f.severity==="error").length,d=c.filter((f)=>f.severity==="warning").length;return{valid:l===0,issues:c,codeMessages:a.issues.codeMessages||{},summary:a.summary,errorCount:l,warningCount:d,validatorVersion:wy}}async function oRe(e,t={}){let n=nRe(e,t),r=T_({cmd:["deno",...n],stdout:"pipe",stderr:"pipe"}),o=await new Response(r.stdout).text(),s=await new Response(r.stderr).text(),i=await r.exited;return{stdout:o,stderr:s,exitCode:i}}function FL(e){let t;try{t=JSON.parse(e)}catch{throw Error("The BIDS validator did not print a JSON report")}if(typeof t!=="object"||t===null||Array.isArray(t))throw Error("The BIDS validator's JSON report is not an object");return JSON.stringify({...t,validatorVersion:wy})}function sRe(e){let t;for(let n=0;n<e.length;n++){let r=e[n];if(r==="--outfile"||r==="-o"){let o=e[n+1];if(o)t=o,n++}else if(r.startsWith("--outfile=")&&r.length>10)t=r.slice(10)}return t}function iRe(e,t){try{if(!tRe(e).isFile())return}catch(o){if(o.code==="ENOENT")throw Error(`The BIDS validator exited normally but wrote no report to ${e}`);throw o}let n=qOt(e,"utf-8");if(t){let o;try{o=FL(n)}catch{throw Error(`The BIDS validator's report file does not hold a JSON report: ${e}`)}eRe(e,o);return}let r=n===""||n.endsWith(`
|
|
1965
1965
|
`)?"":`
|
|
1966
1966
|
`;eRe(e,`${n}${r}Validator: @bids/validator ${wy}
|
|
@@ -1974,12 +1974,12 @@ Examples:
|
|
|
1974
1974
|
`)}function SRe(e,t,n){if(!pRe(e))return null;if(pRe(q1(e,".git")))return{kind:"git-repo"};let r=oTt(e);if(!r)return null;if(r.dataset_id!==t)return{kind:"other-dataset",datasetId:r.dataset_id};if(r.version!==n)return{kind:"other-version",version:r.version};return null}function $Re(e,t){if(t.length===0)return null;let n=q1(e,nTt);try{return mRe(gRe(n),{recursive:!0}),hRe(n,`${t.join(`
|
|
1975
1975
|
`)}
|
|
1976
1976
|
`),n}catch{return null}}function DRe(e){console.log(u.dim(" This is a file snapshot, not a git repository:")),console.log(u.dim(" - 'nemar dataset commit/push/update' need a git-annex clone, not this copy")),console.log(u.dim(` - to widen the selection, re-run the download into ${e} with`)),console.log(u.dim(" different filters; already-present files are skipped")),console.log(u.dim(" - files are checked against their declared size, but not checksum-verified;")),console.log(u.dim(" the git-annex path verifies content hashes, this one does not"))}function RRe(e,t){let n=e.files??{},r=t.files??{},o=[],s=[],i=[];for(let[a,c]of Object.entries(r)){let l=n[a];if(!l)o.push(a);else if(l.key!==c.key)s.push(a)}for(let a of Object.keys(n))if(!(a in r))i.push(a);return o.sort(),s.sort(),i.sort(),{added:o,changed:s,removed:i}}Pw();Rb();He();function CRe(e){return`${Ut(e)}/s`}function sTt(e){if(e<60)return`${Math.round(e)}s`;if(e<3600)return`${Math.floor(e/60)}m ${Math.round(e%60)}s`;return`${Math.floor(e/3600)}h ${Math.floor(e%3600/60)}m`}function iTt(e,t=20){let n=Math.round(e/100*t),r=t-n;return`[${"=".repeat(n)}${" ".repeat(r)}]`}class B1{filesCompleted=0;filesTotal;bytesTotal=0;inFlight=new Map;currentFile="";startTime;lastUpdateTime;lastBytesTransferred=0;totalBytesTransferred=0;speedSamples=[];lastRenderedLine="";constructor(e=0,t=0){this.filesTotal=e,this.bytesTotal=t,this.startTime=Date.now(),this.lastUpdateTime=this.startTime}inFlightBytes(){let e=0;for(let t of this.inFlight.values())e+=t.transferred;return e}processLine(e){let t=e.file??e.action?.file;if(e.ok===!0||e.success===!0){this.filesCompleted++;let n=t??this.currentFile,r=n?this.inFlight.get(n):void 0,o=r?r.total||r.transferred:0;if(this.totalBytesTransferred+=o,n)this.inFlight.delete(n);this.render();return}if(e["byte-progress"]!==void 0){let n=t??this.currentFile;if(!n)return;this.currentFile=n;let r=this.inFlight.get(n)??{transferred:0,total:0};if(r.transferred=e["byte-progress"]??r.transferred,e["total-size"]!==void 0)r.total=e["total-size"];this.inFlight.set(n,r);let o=Date.now(),s=(o-this.lastUpdateTime)/1000;if(s>0.5){let i=this.totalBytesTransferred+this.inFlightBytes(),c=(i-this.lastBytesTransferred)/s;if(c>0){if(this.speedSamples.push(c),this.speedSamples.length>5)this.speedSamples.shift()}this.lastBytesTransferred=i,this.lastUpdateTime=o}this.render()}}incrementFilesCompleted(){this.filesCompleted++}setFilesTotal(e){this.filesTotal=e}setBytesTotal(e){this.bytesTotal=e}getPercent(){let e=this.totalBytesTransferred+this.inFlightBytes();if(this.bytesTotal>0)return Math.min(100,Math.round(e/this.bytesTotal*100));if(this.filesTotal>0)return Math.min(100,Math.round(this.filesCompleted/this.filesTotal*100));return null}getProgress(){return{filesCompleted:this.filesCompleted,filesTotal:this.filesTotal,bytesTransferred:this.totalBytesTransferred+this.inFlightBytes(),bytesTotal:this.bytesTotal,currentFile:this.currentFile||void 0}}render(){let e=this.speedSamples.length>0?this.speedSamples.reduce((i,a)=>i+a,0)/this.speedSamples.length:0,t=this.totalBytesTransferred+this.inFlightBytes(),n=0,r=!1;if(this.bytesTotal>0)n=Math.min(100,Math.round(t/this.bytesTotal*100)),r=!0;else if(this.filesTotal>0)n=Math.min(100,Math.round(this.filesCompleted/this.filesTotal*100)),r=!0;let o=this.filesTotal>0?`${this.filesCompleted}/${this.filesTotal} files`:`${this.filesCompleted} files`,s;if(r)s=`${iTt(n)} ${n}% ${o}`;else s=o;if(t>0){let i=this.bytesTotal>0?`${Ut(t)}/${Ut(this.bytesTotal)}`:Ut(t);s+=` | ${i}`}if(e>0)s+=` | ${CRe(e)}`;if(e>0){let i=0;if(this.bytesTotal>0)i=Math.max(0,this.bytesTotal-t);else for(let a of this.inFlight.values())if(a.total>a.transferred)i+=a.total-a.transferred;if(i>0){let a=i/e;if(a>0)s+=` | ETA ${sTt(a)}`}}if(s!==this.lastRenderedLine)process.stderr.write(`\r${u.cyan(s)}${" ".repeat(10)}`),this.lastRenderedLine=s}finish(e){let t=(Date.now()-this.startTime)/1000;if(process.stderr.write(`\r${" ".repeat(this.lastRenderedLine.length+15)}\r`),e>0){let n=t>0?`${CRe(this.totalBytesTransferred/t)}`:"",r=[`${e} file${e!==1?"s":""} downloaded`,this.totalBytesTransferred>0?Ut(this.totalBytesTransferred):"",n].filter(Boolean).join(" | ");process.stderr.write(`${u.green(r)}
|
|
1977
|
-
`)}}}U0();
|
|
1977
|
+
`)}}}U0();Je();function ARe(e){return e instanceof L&&e.statusCode===422&&e.rawBody?.status==="blocked"&&Yv(e.blockReason)}function ORe(e){let t=e.rawBody?.ci_url;return typeof t==="string"&&/^https:\/\/\S+$/.test(t)?t:void 0}function HL(e){return e==="bids_validation_in_progress"?"Request recorded: BIDS validation is still running.":"Request recorded: BIDS validation has not started yet."}function zL(e,t=!1){let n=`nemar dataset publish request ${e}${t?" --anonymous":""}`;return[" Your request is recorded. NEMAR re-checks it automatically and continues once validation passes.",` If you would rather not wait for that, check validation with: nemar dataset ci ${e}`,` Once it has passed, request again: ${n}`," If it says a request already exists, nothing more is needed."," If validation fails or a submission minimum fails, the request stays blocked and nothing is emailed:",` check nemar dataset ci ${e} or nemar dataset publish status ${e}.`]}Je();gr();async function U1(){let e=Vt().sandboxCompleted;if(e!==void 0)return{status:e?"completed":"not_completed"};try{let t=await TS();if(Rn("sandboxCompleted",t.sandbox_completed),t.sandbox_dataset_id)Rn("sandboxDatasetId",t.sandbox_dataset_id);return t.sandbox_completed?{status:"completed"}:{status:"not_completed"}}catch(t){return{status:"unknown",reason:G(t)}}}He();ii();y6();He();ro();Qa();Je();sp();fD();qf();ii();Fi();gD();_6();Ad();ip();import{existsSync as VL,mkdirSync as aTt,readFileSync as cTt,statSync as lTt,writeFileSync as TRe}from"fs";import{join as uTt,resolve as GL}from"path";function PRe(e,t,n){if(!Hi(n,"metadata_write")){if(t)try{let r=GL(e,".nemar"),o=GL(r,"metadata.json");if(!VL(o)){if(!VL(r))aTt(r,{recursive:!0});TRe(o,JSON.stringify(t,null,2))}let s=GL(e,".bidsignore"),i="";if(VL(s))i=cTt(s,"utf-8");if(!i.includes(".nemar/")){let a=i?`${i.trimEnd()}
|
|
1978
1978
|
.nemar/
|
|
1979
1979
|
`:`.nemar/
|
|
1980
1980
|
`;TRe(s,a)}console.log(u.dim(" Updated .bidsignore for NEMAR metadata"))}catch(r){console.log(u.yellow(` Warning: Could not update .bidsignore: ${G(r)}`)),console.log(u.dim(" Upload will continue without author enrichment."))}gl(n,"metadata_write"),Nr(e,n)}else console.log(u.dim(" Metadata write already completed (skipping)"))}var IRe=1073741824;function dTt(e,t,n=IRe){let r=[],o=0;for(let s of t){let i=e.files[s];if(!i||i.mtimeMs===void 0)continue;r.push({path:s,size:i.size,mtimeMs:i.mtimeMs}),o+=i.size}return o>=n?r:null}function fTt(e,t){return t.filter((n)=>{try{return To(n.path,lTt(uTt(e,n.path)).size)}catch{return!0}})}function pTt(e){let t=0;for(let n of Object.values(e.files))t+=n.size;return t}function mTt(e){return["Warning: saving dataset changes has produced no stdout or stderr for",`${yD(e)}. git add -A is still running.`,"Wait, or interrupt and rerun the upload; the save step will run again."].join(" ")}async function NRe(e,t,n,r={}){if(!Hi(n,"dataset_save")){let o=D({text:"Saving dataset changes...",...r.spinnerStream?{stream:r.spinnerStream}:{}}).start(),s=r.skipMinBytes??IRe,i=[];if(pTt(n)>=s){let c=r.annexedPaths??null;if(c===null)try{c=await Cd(e)}catch(l){console.log(u.dim(` Could not list annexed files (${G(l)}); staging will re-read them`))}if(c!==null)i=fTt(e,dTt(n,c,s)??[])}let a=await cl(e,"Initial NEMAR dataset upload",t,{skipContentCheck:i,onInactivityWarning:(c)=>{o=Sw(o,mTt(c))},...r.inactivityWarningAfterMs===void 0?{}:{inactivityWarningAfterMs:r.inactivityWarningAfterMs}});if(!a.success)return Nr(e,n),go(o,"Failed to save dataset",a.error),console.log(),console.log(u.yellow("Re-run the same command to resume from this step.")),Ne;if(r.verifyRemote){let c;try{c=await D6(e,r.verifyRemote)}catch(l){return Nr(e,n),go(o,"Could not confirm the saved files are at the S3 remote",l),console.log(),console.log(u.yellow("Re-run the same command to resume from this step.")),Ne}if(c.length>0){yl(n,"s3_upload"),Nr(e,n);let l=FS(c.slice(0,5)),d=c.length>5?` (and ${c.length-5} more)`:"";return go(o,"Saved files are not at the S3 remote",`${c.length} annexed file(s) in the commit are not recorded at the remote: ${l}${d}. The save itself annexed them, after the upload step had run.`),console.log(),console.log(u.yellow("Re-run the same command: it uploads them and saves again.")),Ne}}o.succeed("Dataset changes saved"),gl(n,"dataset_save"),Nr(e,n)}else console.log(u.dim(" Dataset save already completed (skipping)"));return fn()}async function FRe(e,t){if(!Hi(t,"github_push")){let n=D("Pushing metadata to GitHub...").start(),r=await sr(e);if(!r.success)return Nr(e,t),go(n,"Failed to push to GitHub",r.error),console.log(),console.log(u.yellow("Re-run the same command to resume from this step.")),Ne;if(r.warning)n.warn("Metadata pushed to GitHub (with warning)"),console.log(u.yellow(` ${r.warning}`));else n.succeed("Metadata pushed to GitHub");gl(t,"github_push"),Nr(e,t)}else console.log(u.dim(" GitHub push already completed (skipping)"));return fn()}async function MRe(e,t,n){if(!Hi(n,"ci_deploy")){let r=D("Setting up BIDS validation CI...").start(),o="configured";try{await il(t),r.succeed("BIDS validation CI configured")}catch(s){if(o="not-configured",s instanceof L&&s.statusCode===403)r.info("CI workflow will be configured by an admin");else{let i=s instanceof Error?s.message:String(s);r.warn(`Could not configure CI: ${i}`),console.log(u.dim(` An admin can add it later with: nemar admin ci add ${t}`))}}return gl(n,"ci_deploy"),Nr(e,n),o}return console.log(u.dim(" CI deploy already completed (skipping)")),"unknown"}function hTt(e,t){let n=e.startsWith("xx");if(t==="not-configured"){if(n)return;console.log("BIDS validation is not set up yet."),console.log(` CI is set up when you request publication: ${u.cyan(`nemar dataset publish request ${e}`)}`),console.log();return}if(console.log("BIDS validation runs on GitHub after the upload."),console.log(` Check it with: ${u.cyan(`nemar dataset ci ${e}`)}`),!n)console.log(` Once it has passed, request publication: ${u.cyan(`nemar dataset publish request ${e}`)}`);console.log()}function jRe(e,t,n="unknown"){Ew(e),Iwe(e),console.log(),console.log(u.green.bold("Upload complete!")),console.log(),console.log(` Dataset ID: ${u.cyan(t.dataset_id)}`),console.log(` GitHub: ${u.cyan(t.github_url)}`),console.log(),console.log(u.dim("To download this dataset:")),console.log(u.dim(` nemar dataset download ${t.dataset_id}`)),console.log(),hTt(t.dataset_id,n),console.log(u.yellow("Note: This dataset is private. Only the owner and designated collaborators can")),console.log(u.yellow("download it, and only through the NEMAR CLI (not direct git-annex commands).")),console.log(u.yellow("After publishing, the data will be publicly available for everyone."))}Ad();ip();async function LRe(e,t={}){let n=await jhe(e.absolutePath);if(!n.success)return console.log(u.red(n.error)),console.log(u.yellow("Re-run the same command to retry.")),Ne;if(n.cleared>0)console.log(u.yellow(` Cleared ${n.cleared} assume-unchanged flag(s) an earlier, interrupted save left on annexed files`));let r=await qwe(e.absolutePath);if(r.status==="error")return console.log(u.red(r.error)),Ne;if(r.status==="warning")console.log(u.yellow(` ${r.warning}`));if(r.status==="restored")console.log(u.yellow(" Put back git-annex's filter process, which an earlier, interrupted upload had left out of this repository's configuration"));let o=await w_e(e.absolutePath,e.options,e.dataFiles,e.filesToUpload,e.uploadProgress,e.datasetInfo,{openRemote:t.openRemote,...t.primeMinBytes===void 0?{}:{primeMinBytes:t.primeMinBytes},...t.primeOnSuspended?{primeOnSuspended:t.primeOnSuspended}:{}});if(o.status==="fail")return Ne;let{progress:s,annexedPaths:i}=o.value;if(PRe(e.absolutePath,e.coAuthorEnrichment,s),(await(t.saveStep??NRe)(e.absolutePath,e.author,s,{annexedPaths:i,verifyRemote:mc,...t.skipMinBytes===void 0?{}:{skipMinBytes:t.skipMinBytes},...t.saveInactivityWarningAfterMs===void 0?{}:{inactivityWarningAfterMs:t.saveInactivityWarningAfterMs},...t.saveSpinnerStream===void 0?{}:{spinnerStream:t.saveSpinnerStream}})).status==="fail")return Ne;return fn(s)}He();ml();Ep();_w();dn();qt();import{randomBytes as XTt}from"crypto";import{constants as QL,accessSync as QTt,chmodSync as ZTt,chownSync as ePt,closeSync as n3,copyFileSync as tPt,existsSync as u1e,fsyncSync as d1e,lstatSync as Cc,mkdirSync as nPt,mkdtempSync as rPt,openSync as r3,readSync as oPt,readdirSync as sPt,renameSync as iPt,rmSync as o3,rmdirSync as aPt,statSync as f1e,writeSync as cPt}from"fs";import{tmpdir as lPt}from"os";import{dirname as J1,join as ea}from"path";He();import{lstatSync as HTt,readdirSync as zTt,statSync as QRe}from"fs";import{open as VTt}from"fs/promises";import{join as XRe}from"path";Ws();ro();ml();var zRe="nemar-identifier-scan/1.0 (+https://docs.nemar.org/policies/takedown/)",gTt="https://api.nemar.org",yTt="https://data.nemar.org",bTt="https://nemar.s3.us-east-2.amazonaws.com",wTt="https://api.github.com";function G1(e,t){if(!Number.isSafeInteger(t)||t<1)throw RangeError(`${e} must be a positive integer, got ${t}`)}async function H1(e,t,n){G1("pool size",t);let r=0,o=Array.from({length:Math.min(t,e.length)},async()=>{while(r<e.length){let a=e[r++];await n(a)}}),i=(await Promise.allSettled(o)).find((a)=>a.status==="rejected");if(i)throw i.reason}function _Tt(e){G1("limit",e);let t=0,n=[];return async(r)=>{if(t>=e)await new Promise((o)=>n.push(o));else t++;try{return await r()}finally{let o=n.shift();if(o)o();else t--}}}class Jn extends Error{cls;status;retryable;retryAfterMs;constructor(e,t={}){super(e);this.name="ReadFailure",this.cls=e,this.status=t.status,this.retryable=t.retryable??!1,this.retryAfterMs=t.retryAfterMs}}function xTt(e,t=Date.now()){let n=e?.trim();if(!n)return;if(/^\d+$/.test(n))return Number(n)*1000;let r=Date.parse(n);return Number.isNaN(r)?void 0:Math.max(0,r-t)}function vTt(e,t){let n=e>=500||e===429;return new Jn(`http-${e}`,{status:e,retryable:n,retryAfterMs:n?xTt(t):void 0})}class WL extends Error{constructor(e){super(e);this.name="RunAborted"}}function kTt(e){G1("abort streak",e.streak);let t=e.now??Date.now,n={tripped:null},r=(o)=>{let s=0,i=0,a=(c)=>{throw n.tripped=new WL(c),n.tripped};return{check(){if(n.tripped)throw n.tripped},ok(){s=0},pausedUntilMs(){return i},observe(c){if(n.tripped)throw n.tripped;if(c.retryAfterMs!==void 0&&c.retryAfterMs>e.retryAfterCapMs)a(`${o} asked to wait ${Math.round(c.retryAfterMs/1000)} s (Retry-After), over the ${Math.round(e.retryAfterCapMs/1000)} s cap (${c.cls})`);if(c.retryAfterMs!==void 0)i=Math.max(i,t()+c.retryAfterMs);if(!c.retryable){s=0;return}if(s++,s>=e.streak)a(`${s} consecutive 429, 5xx, timeout or network failures from ${o} (last ${c.cls})`)}}};return{worker:r("the Worker"),direct:r("direct reads")}}function qRe(e){let t=e instanceof Error?e.name:"";return new Jn(t==="TimeoutError"||t==="AbortError"?"timeout":"network",{retryable:!0})}function ETt(e){if(e instanceof Jn)return e.cls;return`error-${e instanceof Error?e.name:"unknown"}`}async function STt(e,t={}){let n=t.tries??3,r=t.baseMs??400,o=t.sleep??((s)=>new Promise((i)=>setTimeout(i,s)));G1("tries",n);for(let s=1;;s++)try{return await e()}catch(i){if(!(i instanceof Jn&&i.retryable)||s>=n)throw i;let c=i.retryAfterMs??0;if(c>(t.retryAfterCapMs??30000))throw i;await o(Math.max(r*2**(s-1),c))}}async function $Tt(e){await e.body?.cancel().catch(()=>{return})}async function DTt(e,t,n={}){let r;try{r=await fetch(e,{headers:{Range:`bytes=0-${t-1}`,"Accept-Encoding":"identity","User-Agent":n.userAgent??zRe},signal:AbortSignal.timeout(n.timeoutMs??30000)})}catch(a){throw qRe(a)}if(r.status!==200&&r.status!==206)throw await $Tt(r),vTt(r.status,r.headers.get("retry-after"));let o=r.body?.getReader();if(!o)throw new Jn("no-body");let s=new Uint8Array(t),i=0;try{while(i<t){let{done:a,value:c}=await o.read();if(a||!c)break;let l=Math.min(c.length,t-i);s.set(c.subarray(0,l),i),i+=l}}catch(a){throw qRe(a)}finally{await o.cancel().catch(()=>{return})}if(i<(n.minBytes??0))throw new Jn("short-body");return s.subarray(0,i)}var VRe={sideFileBytes:2097152,participantsBytes:16777216};function RTt(e,t){let n=/An error occurred \(([A-Za-z0-9]{1,40})\)/.exec(e)?.[1];if(n)return/^\d+$/.test(n)?`aws/http-${n}`:`aws/error-${n}`;return`aws/exit-${t}`}async function CTt(e,t,n={}){let r;try{let o=Bun.spawn(["aws","s3","cp",`s3://nemar/${e}/version/${t}.json`,"-"],{stdout:"pipe",stderr:"pipe",...n.env?{env:n.env}:{}}),s=!1;r=setTimeout(()=>{s=!0,o.kill("SIGKILL")},n.timeoutMs??600000);let[i,a,c]=await Promise.all([new Response(o.stdout).text(),new Response(o.stderr).text(),o.exited]);if(s)throw new Jn("aws/timeout");if(c!==0)throw new Jn(RTt(a,c));return i}catch(o){if(o instanceof Jn)throw o;throw new Jn("aws/unavailable")}finally{clearTimeout(r)}}function ATt(){let e;return async()=>{if(e!==void 0)return e;if(process.env.GITHUB_TOKEN)return e=process.env.GITHUB_TOKEN,e;try{let t=Bun.spawn(["gh","auth","token"],{stdout:"pipe",stderr:"ignore"}),n=(await new Response(t.stdout).text()).trim();e=n===""?null:n}catch{e=null}return e}}var z1=(e)=>e.replace(/\/+$/,"");function GRe(e={}){let t=e.retryAfterCapMs??30000,n=e.awsTimeoutMs??600000;return{api:z1(e.api??process.env.NEMAR_API_BASE??gTt),data:z1(e.data??process.env.NEMAR_DATA_BASE??yTt),s3Base:z1(e.s3Base??bTt),githubApi:z1(e.githubApi??wTt),userAgent:e.userAgent??zRe,fileConcurrency:e.fileConcurrency??24,workerLimit:_Tt(e.workerConcurrency??6),timeoutMs:e.timeoutMs??30000,manifestTimeoutMs:e.manifestTimeoutMs??120000,retryBaseMs:e.retryBaseMs??400,sleep:e.sleep??((r)=>new Promise((o)=>setTimeout(o,r))),now:e.now??Date.now,retryAfterCapMs:t,breakers:kTt({streak:e.abortStreak??25,retryAfterCapMs:t,now:e.now??Date.now}),limits:{treeHeaderSample:300,scansTables:1,jsonFiles:300,textFiles:300,sideFileBytes:65536,participantsBytes:1048576,...e.limits},readVersionManifest:e.readVersionManifest??((r,o)=>CTt(r,o,{timeoutMs:n,env:e.awsEnv})),githubToken:e.githubToken??ATt(),...e.readEntryHead?{readEntryHead:e.readEntryHead}:{}}}var WRe=(e,t)=>t.startsWith(`${e.data}/`),OTt=(e,t)=>WRe(e,t)||t.startsWith(`${e.api}/`)?e.breakers.worker:e.breakers.direct;async function TTt(e,t,n){let r=OTt(e,t);r.check();let o=r.pausedUntilMs()-e.now();if(o>0)await e.sleep(o),r.check();try{let s=await n();return r.ok(),s}catch(s){if(s instanceof Jn)r.observe(s);throw s}}var PTt=(e,t)=>({...t===void 0?{}:{tries:t},baseMs:e.retryBaseMs,sleep:e.sleep,retryAfterCapMs:e.retryAfterCapMs});var BRe=(e)=>/sub-([^/_]+)/.exec(e)?.[1]??"?";function URe(e,t,n){if(t<1)return[];if(e.length<=t)return[...e];let r=new Map;for(let c of e){let l=n(c),d=r.get(l);if(d)d.push(c);else r.set(l,[c])}let o=[...r.entries()].sort(([c],[l])=>c<l?-1:c>l?1:0).map(([,c])=>c);if(o.length>t)return Array.from({length:t},(c,l)=>o[Math.floor((l+0.5)*o.length/t)][0]);let s=o.map((c,l)=>({list:c,index:l})).sort((c,l)=>c.list.length-l.list.length||c.index-l.index),i=t,a=[];return s.forEach(({list:c},l)=>{let d=Math.min(c.length,Math.ceil(i/(s.length-l)));for(let f=0;f<d;f++)a.push(c[Math.floor((f+0.5)*c.length/d)]);i-=d}),a}var ITt=(e)=>e.severity==="identifier"&&Cbe.has(e.kind),NTt=(e)=>Qf.has(e.kind);function KRe(e){return e.headerRead===e.edfCount&&e.incompleteReasons.length===0}function FTt(e){if(e.findings.some(ITt))return"direct-identifiers";if(e.findings.some((t)=>!NTt(t)))return"review";if(!KRe(e))return"unchecked";if(e.edfCount>0&&e.unscreenedCount>0)return"clean-edf-only-others-unscreened";if(e.edfCount===0)return e.unscreenedCount>0?"not-screened":"no-recordings";return e.findings.length>0?"dates-only":"clean"}var MTt=/\.(edf|bdf)$/i,jTt=(e)=>e.edf===!0||MTt.test(e.path);function LTt(e){return{edf:e.filter(jTt),participants:e.find((t)=>t.path==="participants.tsv"),scans:e.filter((t)=>t.path.endsWith("_scans.tsv")),json:e.filter((t)=>t.path.endsWith(".json")).filter((t)=>t.path.startsWith("sourcedata/")||!qTt.test(t.path)).filter((t)=>!BTt.test(t.path)),text:e.filter((t)=>UTt.test(t.path)).filter((t)=>t.path.startsWith("sourcedata/")||t.path.startsWith("code/"))}}var qTt=/_(eeg|ieeg|meg|emg|nirs|beh|events|channels|electrodes|coordsystem|scans|physio|stim|photo|T1w|bold)\.(json|tsv)$/,BTt=/(^|\/)(dataset_description|participants|genetic_info)\.json$/,UTt=/\.(py|m|r|txt|md|ya?ml|xml|iml|cfg|ini)$/i;function JRe(e,t,n,r=0){let o=()=>TTt(e,t.url,()=>{let s={minBytes:r,userAgent:e.userAgent,timeoutMs:e.timeoutMs};return e.readEntryHead?e.readEntryHead(t,n,s):DTt(t.url,n,s)});return STt(()=>WRe(e,t.url)?e.workerLimit(o):o(),PTt(e))}async function V1(e,t,n){let r=await JRe(e,t,n),o=t.size===null?r.length>=n:t.size>n;return{text:new TextDecoder("utf-8",{fatal:!1}).decode(r),truncated:o}}function xy(e,t){for(let n of t)e.push(n)}var HRe="edf/superseded-absent";async function YRe(e,t,n,r,o,s={}){let i=r.map((Ce)=>Ce.path),a=o==="clone",c=(Ce,ot,Tn)=>a?[...Ce]:URe(Ce,ot,Tn),l=[...Y$([...i,...s.extraPaths??[]])],d=qbe(i),f=Object.values(d.unscreened).reduce((Ce,ot)=>Ce+ot,0),p={},m=(Ce,ot)=>{if(ot instanceof WL)throw ot;let Tn=`${Ce}/${ETt(ot)}`;p[Tn]=(p[Tn]??0)+1},h=(Ce)=>BRe(Ce.path),g=LTt(r),y=new Set(s.supersededEdf??[]),b=[...g.edf,...y],{participants:_,scans:x,json:k,text:v}=g,C=o==="git-tree"?URe(b,e.limits.treeHeaderSample,h):[...b],T=0,z=0,A=0,F=0,M={},U=new Set,B=new Set,P=new Set,O=new Set,H=new Set,re=new Set;await H1(C,e.fileConcurrency,async(Ce)=>{try{let ot=await JRe(e,Ce,vt,vt),Tn=kd(ot),{patient:Ll}=K$(ot);if(!Tn.some((hs)=>hs.kind==="edf-unreadable")){U.add(Ll);let hs=Ll.split(/\s+/);if(hs.length>=4)P.add(hs[0]),H.add(hs[2]),O.add(hs[3])}if(re.add(BRe(Ce.path)),Tn.some((hs)=>hs.severity==="identifier"))F++,B.add(Ll);xy(l,Tn);for(let hs of new Set(Tn.map((ky)=>ky.kind)))M[hs]=(M[hs]??0)+1;T++}catch(ot){if(y.has(Ce)&&ot instanceof Jn&&ot.status===404){A++,p[HRe]=(p[HRe]??0)+1;return}z++,m("edf",ot)}});let Ee=b.length-A,Qt=!1,ft=!1;if(_&&_.size!==0)try{let{text:Ce,truncated:ot}=await V1(e,_,e.limits.participantsBytes),Tn=Ce.indexOf(`
|
|
1981
1981
|
`);if(Tn<0&&ot)throw new Jn("header-truncated");xy(l,Fbe(Tn<0?Ce:Ce.slice(0,Tn))),xy(l,jbe(Ce)),ft=ot}catch(Ce){Qt=!0,m("participants",Ce)}let Ze=c(x,e.limits.scansTables,h),oe=0;await H1(Ze,e.fileConcurrency,async(Ce)=>{if(Ce.size===0){oe++;return}try{let{text:ot}=await V1(e,Ce,e.limits.sideFileBytes);xy(l,J$(ot)),oe++}catch(ot){m("scans",ot)}});let je=e.limits.sideFileBytes,Ie=(Ce)=>Ce.size!==null&&Ce.size>je,Q=c(k.filter((Ce)=>!Ie(Ce)),e.limits.jsonFiles,h),pt=c(v.filter((Ce)=>!Ie(Ce)),e.limits.textFiles,h),Be=0,W=0;await H1(Q,e.fileConcurrency,async(Ce)=>{if(Ce.size===0){Be++;return}try{let{text:ot}=await V1(e,Ce,je),Tn;try{Tn=JSON.parse(ot)}catch{throw new Jn("json-parse")}xy(l,Xf(Tn)),Be++}catch(ot){m("json",ot)}}),await H1(pt,e.fileConcurrency,async(Ce)=>{if(Ce.size===0){W++;return}try{let{text:ot}=await V1(e,Ce,je);xy(l,Lbe(ot)),W++}catch(ot){m("text",ot)}});let J={edf_headers:{candidates:Ee,oversize:0,selected:C.length-A,scanned:T},scans_tables:{candidates:x.length,oversize:0,selected:Ze.length,scanned:oe},json_files:{candidates:k.length,oversize:k.filter(Ie).length,selected:Q.length,scanned:Be},text_files:{candidates:v.length,oversize:v.filter(Ie).length,selected:pt.length,scanned:W}},le=new Set,ne=(Ce,ot)=>{if(ot.oversize>0)le.add(`${Ce}-oversize`);if(ot.candidates-ot.oversize>ot.selected)le.add(`${Ce}-sampled`);if(ot.scanned<ot.selected)le.add(`${Ce}-unread`)};if(ne("edf-headers",J.edf_headers),ne("json",J.json_files),ne("text",J.text_files),J.scans_tables.scanned<J.scans_tables.selected)le.add("scans-unread");if(Qt)le.add("participants-unread");if(ft)le.add("participants-truncated");for(let Ce of s.extraIncompleteReasons??[])le.add(Ce);let Ue=[...le].sort(),It={findings:l,edfCount:Ee,headerRead:T,unscreenedCount:f,incompleteReasons:Ue},mr=l.filter((Ce)=>Ce.severity==="identifier"),Oc=Object.entries(p).filter(([Ce])=>!Ce.startsWith("edf/")).reduce((Ce,[,ot])=>Ce+ot,0);return{id:t,version:n,scanned_at:new Date().toISOString(),manifest_source:o,status:FTt(It),incomplete:!KRe(It),incomplete_reasons:Ue,files:{total:r.length,edf_bdf:Ee,header_read:T,header_read_failed:z},sampling:J,read_failures:p,edf_bdf_files_flagged:F,distinct_patient_field_values:U.size,distinct_subjects_with_edf_bdf:re.size,distinct_patient_code_subfield:P.size,distinct_patient_name_subfield:O.size,distinct_patient_birth_subfield:H.size,distinct_patient_field_values_in_flagged_files:B.size,findings_by_kind:Bbe(l),edf_bdf_files_by_kind:M,unscreened_formats:d.unscreened,side_reads_failed:Oc,finding_fields:[...new Set(mr.map((Ce)=>`${Ce.kind}:${Ce.field}`))].sort()}}Ep();dn();If();ip();var Fp="--acknowledge-identifier-preflight",GTt=16,WTt="local:";function YL(e){let t=[],n=new Map,r=0,o=[""];while(o.length>0){let s=o.pop(),i;try{i=zTt(s===""?e:XRe(e,s),{withFileTypes:!0})}catch{r++;continue}i.sort((c,l)=>c.name<l.name?-1:c.name>l.name?1:0);let a=[];for(let c of i){let l=c.name;if(s===""&&(l===".git"||l===".nemar"))continue;let d=s===""?l:`${s}/${l}`;if(c.isDirectory()){a.push(d);continue}if(l===".gitattributes")continue;let f=`${WTt}${t.length}`,p=XRe(e,d),m=null;try{let h=QRe(p);if(h.isFile())m=h.size,n.set(f,p);else if(h.isDirectory()&&!HTt(p).isSymbolicLink()){a.push(d);continue}}catch{}t.push({path:d,size:m,url:f})}for(let c=a.length-1;c>=0;c--)o.push(a[c])}return{entries:t,readable:n,unlisted:r}}function KTt(e,t=new Map){return async(n,r,o)=>{let s=e.get(n.url);if(s===void 0)throw new Jn("unreadable-entry");let i=t.get(s),a;try{a=await VTt(s,"r")}catch{throw new Jn("unreadable-entry")}try{let c=n.size===null?r:Math.min(r,n.size),l=new Uint8Array(c),d=0;while(d<c){let{bytesRead:f}=await a.read(l,d,c-d,d);if(f===0)break;d+=f}if(d<o.minBytes)throw new Jn("short-body");if(i)l.set(i.subarray(0,Math.min(d,i.length)),0);return l.subarray(0,d)}catch(c){if(c instanceof Jn)throw c;throw new Jn("unreadable-entry")}finally{await a.close().catch(()=>{return})}}}async function ZRe(e,t){let n=YL(e),r=GRe({fileConcurrency:GTt,workerConcurrency:1,limits:{...VRe},readEntryHead:KTt(n.readable,t),githubToken:async()=>null,readVersionManifest:async()=>{throw new Jn("unreadable-entry")},sleep:async()=>{return}}),o=await YRe(r,"local",null,n.entries,"clone",{extraIncompleteReasons:n.unlisted>0?["tree-truncated"]:[]}),s={scanned_at:o.scanned_at,status:o.status,incomplete:o.incomplete,incomplete_reasons:o.incomplete_reasons,files:o.files,findings_by_kind:o.findings_by_kind,edf_bdf_files_flagged:o.edf_bdf_files_flagged,unscreened_formats:o.unscreened_formats,read_failures:o.read_failures};return KM(Ake(Oke(s)))}function K1(e){if(Bd(e.status)!=="acknowledge")return[];let t=new Set([e.status]);if(e.incomplete&&e.status!=="unchecked")t.add("unchecked");let n=Object.values(e.unscreened_formats).reduce((o,s)=>o+s,0),r=e.status==="not-screened"||e.status==="clean-edf-only-others-unscreened";if(n>0&&!r)t.add("not-screened");return[...t].sort()}var e1e=(e,t)=>e.length===t.length&&e.every((n,r)=>n===t[r]);function t1e(e,t){let n=e.split(",").map((o)=>o.trim()).filter((o)=>o!==""),r=RR;if(n.length===0||!n.every((o)=>r.includes(o)))throw new Ms(`Allowed verdicts are ${r.join(", ")}. Direct identifiers cannot be acknowledged.`);return[...t??[],...n]}function JTt(e,t){let n=Bd(e.status);if(n==="clear")return{action:"proceed",acknowledgedVia:null};if(n!=="acknowledge")return{action:"refuse"};if(t.acknowledge!==void 0){let r=[...new Set(t.acknowledge)].sort();return e1e(r,K1(e))?{action:"proceed",acknowledgedVia:"flag"}:{action:"stop",why:"acknowledgment-mismatch"}}if(t.dryRun)return{action:"preview"};if(t.no)return{action:"stop",why:"declined"};if(t.isTty)return{action:"prompt"};return{action:"stop",why:"acknowledgment-required"}}var YTt={review:"the scanner found something a person should look at (the kinds are listed above)",unchecked:"the scanner could not read everything it should have (see Incomplete above)","not-screened":"some recordings are in formats the scanner cannot read, so their headers were not checked","clean-edf-only-others-unscreened":"the EDF/BDF headers are clean, but other recordings are in formats the scanner cannot read"},KL=(e)=>`${Fp} ${e.join(",")}`;function JL(e){console.log(u.yellow(" This does not stop an upload, but it needs your explicit acknowledgment of:"));for(let t of e)console.log(u.yellow(` ${t}: ${YTt[t]??"not clean"}.`));console.log(u.dim(" Your acknowledgment is recorded with your deposit attestation. NEMAR screens the dataset again when you request publication, and an administrator decides then."))}function n1e(){console.log(),console.log(u.red(" Upload refused: the preflight found direct identifiers (a name, a birth date finer than the year, a record number, an age over 89, or an identifying column or key). Nothing was sent.")),console.log(u.red(" Remove them from the files (for EDF/BDF, the patient and recording fields of the header) and run the upload again.")),console.log(u.dim(` There is no override, and ${Fp} does not apply. If this is a false positive, please report it, so the scanner is fixed for every dataset. Terms: ${F1}`))}function r1e(e){if(e instanceof SR)return`report-${e.message}`;let t=e instanceof Error&&/^[A-Za-z]{1,40}$/.test(e.name)?e.name:"unknown",n=e?.code;return typeof n==="string"&&/^E[A-Z0-9]{1,20}$/.test(n)?`${t} ${n}`:t}function o1e(e,t){e.fail("Identifier preflight: DID NOT FINISH"),console.log(u.red(` The preflight could not produce a verdict, so nothing was uploaded (${r1e(t)}).`)),console.log(u.dim(" Please report this: https://github.com/nemarOrg/nemar-cli/issues"))}function W1(e,t,n=""){let r=JM(t,null),o=`${r.headline}${n}`;if(r.tone==="ok")e.succeed(o);else if(r.tone==="stop")e.fail(o);else e.warn(o);for(let s of $c({state:t.status,...r},2).slice(1))console.log(s)}function s1e(e,t){try{return fn(Tke({version:ER,scanner:`nemar-cli@${ks}`,scan:e,acknowledged_via:t}))}catch(n){return console.log(u.red(` The preflight's record did not fit the report contract (${r1e(n)}), so nothing was uploaded.`)),Ne}}async function i1e(e,t,n=process.stdin.isTTY===!0,r){let o=D("Screening for identifiers on this machine (nothing is sent)...").start(),s=!1;try{s=QRe(e).isDirectory()}catch{s=!1}if(!s)return o.fail("Identifier preflight: the dataset path is not a directory"),Ne;let i=new Map((r?.items??[]).map((p)=>[p.path,p.after])),a;try{a=await ZRe(e,i)}catch(p){return o1e(o,p),Ne}W1(o,a);let c=K1(a),l=JTt(a,{acknowledge:t.acknowledgeIdentifierPreflight,dryRun:t.dryRun,no:t.no,isTty:n}),d;switch(l.action){case"proceed":if(l.acknowledgedVia==="flag")console.log(u.dim(` Acknowledged with ${KL(c)}.`));else if(t.acknowledgeIdentifierPreflight!==void 0)console.log(u.dim(` Nothing to acknowledge; ${Fp} was not needed.`));d=l.acknowledgedVia;break;case"preview":return JL(c),console.log(u.yellow(` A real upload stops here until you acknowledge it: answer the prompt, or pass ${KL(c)}.`)),console.log(),fn(null);case"prompt":{JL(c);let p=!1,m=()=>{console.log(u.red(`
|
|
1982
|
-
Upload cancelled. Nothing was sent.`)),ce(),process.exit(130)};process.once("SIGINT",m);let h=setInterval(()=>{return},1000);try{({acknowledged:p}=await Ae.prompt([{type:"confirm",name:"acknowledged",message:"Upload anyway?",default:!1}]))}catch{p=!1}finally{clearInterval(h),process.off("SIGINT",m)}if(p!==!0)return console.log(u.red(" Upload cancelled. Nothing was sent.")),ce(),Ne;console.log(u.dim(" Acknowledged at the prompt.")),d="prompt";break}case"refuse":return n1e(),ce(),Ne;case"stop":if(l.why==="acknowledgment-mismatch")console.log(u.red(` ${Fp} must name exactly what was found, which is: ${c.join(",")}. It does not acknowledge this scan. Nothing was sent.`));else JL(c),console.log(u.red(l.why==="declined"?" Declined (--no). Nothing was sent.":` No terminal to ask at: run interactively, or pass ${KL(c)}. --yes does not acknowledge a finding. Nothing was sent.`));return ce(),Ne}let f=s1e(a,d);if(f.status==="ok")console.log();return f}async function a1e(e,t){let n=D("Screening again, right before anything is sent...").start(),r;try{r=await ZRe(e)}catch(a){return o1e(n,a),Ne}let o=Bd(r.status);if(o!=="clear"&&o!=="acknowledge")return W1(n,r),n1e(),ce(),Ne;let s=K1(t.scan),i=K1(r);if(!e1e(s,i))return W1(n,r),console.log(u.red(` The files changed since the preflight, and so did what it found (acknowledged: ${s.join(",")||"nothing"}; now: ${i.join(",")}). Nothing was sent. Run the upload again.`)),ce(),Ne;if($R(r.findings_by_kind)!==$R(t.scan.findings_by_kind))W1(n,r," (screened again)");else n.succeed(`${JM(r,null).headline} (screened again)`);return s1e(r,t.acknowledged_via)}var uPt=/\.(edf|bdf)$/i,p1e=ea(".nemar","date-normalization"),dPt=()=>({tracked:0,"nested-repository":0,ignored:0,"tracking-unknown":0,link:0,"not-writable":0,"other-filesystem":0,unverified:0});function fPt(){return{items:[],left:dPt()}}function pPt(e){if(process.env.GIT_DIR||process.env.GIT_WORK_TREE)return!0;for(let t=e;;t=J1(t)){if(u1e(ea(t,".git")))return!0;if(J1(t)===t)return!1}}var ZL=(e)=>e.normalize("NFC").toLowerCase();async function XL(e,t,n){try{let r=await R(e,{cwd:t,...n===void 0?{}:{stdin:n}});if(!(r.exitCode===0||e.includes("check-ignore")&&r.exitCode===1))return null;return new Set(r.stdout.split("\x00").filter(Boolean).map(ZL))}catch{return null}}async function mPt(e,t){let n=`${t.join("\x00")}\x00`;if(pPt(e)){let o=await XL(["git","ls-files","-z"],e),s=await XL(["git","check-ignore","-z","--stdin"],e,n);return o&&s?{tracked:o,ignored:s}:null}let r=null;try{if(r=rPt(ea(lPt(),"nemar-ignore-")),(await R(["git","init","-q","--bare",r],{cwd:e})).exitCode!==0)return null;let s=await XL(["git",`--git-dir=${r}`,`--work-tree=${e}`,"check-ignore","--no-index","-z","--stdin"],e,n);return s?{tracked:new Set,ignored:s}:null}catch{return null}finally{if(r!==null)try{o3(r,{recursive:!0,force:!0})}catch{}}}function e3(e){let t;try{t=r3(e,"r")}catch{return null}try{let n=new Uint8Array(vt),r=0;while(r<vt){let o=oPt(t,n,r,vt-r,r);if(o===0)break;r+=o}return r===vt?n:null}catch{return null}finally{try{n3(t)}catch{}}}var c1e=(e,t)=>e!==null&&e.length===t.length&&e.every((n,r)=>n===t[r]);function l1e(e){try{return QTt(e,QL.W_OK),!0}catch{return!1}}function hPt(e,t,n){let r=t.split("/").slice(0,-1);for(let o=1;o<=r.length;o++){let s=r.slice(0,o).join("/"),i=n.get(s);if(i===void 0){i=u1e(ea(e,s,".git"));try{i||=Cc(ea(e,s,".git")).isSymbolicLink()}catch{}n.set(s,i)}if(i)return!0}return!1}async function m1e(e){let t=fPt();try{await gPt(e,t)}catch(n){Dn(`date normalization: planning stopped (${n instanceof Error?n.name:"unknown"})`)}return t}async function gPt(e,t){let n=f1e(e).dev,r=YL(e),o=[];for(let c of r.entries){if(!uPt.test(c.path))continue;let l=r.readable.get(c.url);if(l===void 0)continue;let d=e3(l);if(d===null)continue;try{let f=a6(d);if(f.changed)o.push({path:l,rel:c.path,before:d,after:f.header})}catch(f){if(f instanceof Dd)continue;t.left.unverified++,Dn(`date normalization: a header was not planned (${f instanceof Error?f.name:"unknown"})`)}}if(o.length===0)return;let s=await mPt(e,o.map((c)=>c.rel)),i=new Map,a=typeof process.getuid==="function"?process.getuid():null;for(let c of o){if(s===null){t.left["tracking-unknown"]++;continue}if(s.tracked.has(ZL(c.rel))){t.left.tracked++;continue}if(hPt(e,c.rel,i)){t.left["nested-repository"]++;continue}if(s.ignored.has(ZL(c.rel))){t.left.ignored++;continue}let l;try{l=Cc(c.path)}catch{continue}if(l.isSymbolicLink()){t.left.link++;continue}if(!l.isFile())continue;if(l.dev!==n){t.left["other-filesystem"]++;continue}if(a!==null&&l.uid!==a||(l.mode&128)===0||!l1e(c.path)||!l1e(J1(c.path))){t.left["not-writable"]++;continue}t.items.push({path:c.path,rel:c.rel,dev:l.dev,ino:l.ino,size:l.size,mtimeMs:l.mtimeMs,mode:l.mode,gid:l.gid,before:c.before,after:c.after})}}var yPt=/^\d+-[0-9a-f]{16}$/;function bPt(e){try{let t=ea(e,p1e);for(let n of[ea(e,".nemar"),t])if(!Cc(n).isDirectory())return;for(let n of sPt(t))if(yPt.test(n))o3(ea(t,n),{force:!0})}catch{}}function t3(e){for(let t of e)try{aPt(t)}catch{}}function wPt(e,t){let n=[],r=ea(e,p1e);try{for(let o of[ea(e,".nemar"),r]){let s;try{s=Cc(o)}catch{nPt(o),n.push(o),s=Cc(o)}if(!s.isDirectory()||s.dev!==t)return t3([...n].reverse()),null}return{dir:r,made:n}}catch{return t3([...n].reverse()),null}}function _Pt(e){try{let t=r3(e,"r");try{d1e(t)}finally{n3(t)}}catch{}}function xPt(e,t){let n=null;try{let r=(s)=>s.isFile()&&s.dev===e.dev&&s.ino===e.ino&&s.size===e.size&&s.mtimeMs===e.mtimeMs;if(!r(Cc(e.path))||!c1e(e3(e.path),e.before))return null;if(n=ea(t,`${process.pid}-${XTt(8).toString("hex")}`),tPt(e.path,n,QL.COPYFILE_EXCL|QL.COPYFILE_FICLONE),Cc(n).gid!==e.gid)ePt(n,-1,e.gid);ZTt(n,e.mode&4095);let o=r3(n,"r+");try{if(cPt(o,e.after,0,vt,0)!==vt)return null;d1e(o)}finally{n3(o)}if(Cc(n).size!==e.size||!c1e(e3(n),e.after))return null;if(!r(Cc(e.path)))return null;return iPt(n,e.path),n=null,_Pt(J1(e.path)),Cc(e.path).mtimeMs}catch(r){return Dn(`date normalization: a header was not set (${r instanceof Error?r.name:"unknown"})`),null}finally{if(n!==null)try{o3(n,{force:!0})}catch{}}}function h1e(e,t){let n={set:0,left:0,mtimes:new Map};if(bPt(e),t.items.length===0)return n;let r=null;try{r=wPt(e,f1e(e).dev)}catch{}if(r===null)return n.left=t.items.length,Dn("date normalization: no work directory, nothing set"),n;try{for(let o of t.items){let s=xPt(o,r.dir);if(s===null){n.left++;continue}n.set++,n.mtimes.set(o.rel,s)}}finally{t3([r.dir,...[...r.made].reverse().filter((o)=>o!==r.dir)])}if(n.set>0)console.log(u.dim(` ${Dke(n.set)}`));return n}He();Ws();ro();import{existsSync as I_,mkdirSync as qPt,readFileSync as N_,writeFileSync as I1e}from"fs";import{basename as BPt,resolve as Mp}from"path";ec();Ke();Pr();Ws();import{existsSync as Y1,readFileSync as s3,writeFileSync as y1e}from"fs";import{resolve as X1}from"path";var i3=[{spdxId:"CC0-1.0",name:"CC0 1.0 Universal (Public Domain)",description:"No rights reserved. Anyone can use the data for any purpose.",url:"https://creativecommons.org/publicdomain/zero/1.0/",allowsResearchUse:!0},{spdxId:"PDDL-1.0",name:"Open Data Commons Public Domain Dedication and License (PDDL)",description:"Database-specific public domain dedication.",url:"https://opendatacommons.org/licenses/pddl/1-0/",allowsResearchUse:!0},{spdxId:"CC-BY-4.0",name:"Creative Commons Attribution 4.0 International",description:"Attribution required. Free for any use including commercial.",url:"https://creativecommons.org/licenses/by/4.0/",allowsResearchUse:!0},{spdxId:"CC-BY-SA-4.0",name:"Creative Commons Attribution-ShareAlike 4.0 International",description:"Attribution + share-alike required. Derivatives must use same license.",url:"https://creativecommons.org/licenses/by-sa/4.0/",allowsResearchUse:!0},{spdxId:"CC-BY-NC-4.0",name:"Creative Commons Attribution-NonCommercial 4.0 International",description:"Attribution required. Non-commercial use only.",url:"https://creativecommons.org/licenses/by-nc/4.0/",allowsResearchUse:!0},{spdxId:"CC-BY-NC-SA-4.0",name:"Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International",description:"Attribution + non-commercial + share-alike required.",url:"https://creativecommons.org/licenses/by-nc-sa/4.0/",allowsResearchUse:!0},{spdxId:"ODC-By-1.0",name:"Open Data Commons Attribution License v1.0",description:"Database-specific attribution license.",url:"https://opendatacommons.org/licenses/by/1.0/",allowsResearchUse:!0},{spdxId:"ODbL-1.0",name:"Open Data Commons Open Database License v1.0",description:"Database attribution + share-alike. Produced works can be any license.",url:"https://opendatacommons.org/licenses/odbl/1.0/",allowsResearchUse:!0}],g1e=new Set(["CC0-1.0","CC-BY-4.0","CC-BY-SA-4.0","CC-BY-NC-4.0","CC-BY-NC-SA-4.0","CC-BY-ND-4.0","CC-BY-NC-ND-4.0","PDDL-1.0","ODC-By-1.0","ODbL-1.0","MIT","Apache-2.0","GPL-2.0-only","GPL-2.0-or-later","GPL-3.0-only","GPL-3.0-or-later","LGPL-2.1-only","LGPL-2.1-or-later","LGPL-3.0-only","LGPL-3.0-or-later","BSD-2-Clause","BSD-3-Clause","ISC","Unlicense"]);function b1e(e){let t=X1(e,"dataset_description.json");if(Y1(t))try{let r=JSON.parse(s3(t,"utf-8"));if(typeof r.License==="string"&&r.License.trim())return{spdxId:r.License.trim(),source:"dataset_description"}}catch(r){if(r instanceof SyntaxError)console.warn(` Warning: dataset_description.json has invalid JSON: ${r.message}`);else console.warn(` Warning: Could not read dataset_description.json: ${r instanceof Error?r.message:String(r)}`)}let n=["LICENSE","LICENSE.txt","LICENSE.md","LICENCE","LICENCE.txt"];for(let r of n){let o=X1(e,r);if(Y1(o)){try{let s=s3(o,"utf-8").toLowerCase();if(s.includes("cc0")||s.includes("public domain dedication"))return{spdxId:"CC0-1.0",source:"license_file"};if(s.includes("attribution-noncommercial-sharealike"))return{spdxId:"CC-BY-NC-SA-4.0",source:"license_file"};if(s.includes("attribution-noncommercial"))return{spdxId:"CC-BY-NC-4.0",source:"license_file"};if(s.includes("attribution-sharealike"))return{spdxId:"CC-BY-SA-4.0",source:"license_file"};if(s.includes("creativecommons")&&s.includes("attribution"))return{spdxId:"CC-BY-4.0",source:"license_file"};if(s.includes("open database license")||s.includes("odbl"))return{spdxId:"ODbL-1.0",source:"license_file"};if(s.includes("open data commons")&&s.includes("attribution"))return{spdxId:"ODC-By-1.0",source:"license_file"};if(s.includes("public domain dedication and license")||s.includes("pddl"))return{spdxId:"PDDL-1.0",source:"license_file"};if(s.includes("permission is hereby granted, free of charge")||s.includes("mit license"))return{spdxId:"MIT",source:"license_file"}}catch(s){console.warn(` Warning: Could not read ${r}: ${s instanceof Error?s.message:String(s)}`)}return{spdxId:void 0,source:"license_file"}}}return{spdxId:void 0,source:"none"}}async function a3(e){let t=i3.map((o)=>({name:`${o.spdxId.padEnd(22)} ${o.description}`,value:o.spdxId,short:o.spdxId}));t.push({name:"Other (enter SPDX ID manually)",value:"__custom__",short:"Custom"});let n=e?i3.find((o)=>o.spdxId===e)?.spdxId:void 0,{selected:r}=await Ae.prompt([{type:"list",name:"selected",message:"Select a license for this dataset:",choices:t,default:n,pageSize:t.length}]);if(r==="__custom__"){let{customId:o}=await Ae.prompt([{type:"input",name:"customId",message:"Enter SPDX license ID (e.g., MIT, Apache-2.0):",validate:(s)=>{if(!s.trim())return"License ID is required";return!0}}]);return o.trim()}return r}function w1e(e){let t=e.toUpperCase().replace(/\s+/g,"-");if(g1e.has(e))return!0;for(let n of g1e)if(n.toUpperCase()===t)return!0;return!1}function vPt(e){let t=i3.find((n)=>n.spdxId===e);if(t)return`${t.name}
|
|
1982
|
+
Upload cancelled. Nothing was sent.`)),ce(),process.exit(130)};process.once("SIGINT",m);let h=setInterval(()=>{return},1000);try{({acknowledged:p}=await Ae.prompt([{type:"confirm",name:"acknowledged",message:"Upload anyway?",default:!1}]))}catch{p=!1}finally{clearInterval(h),process.off("SIGINT",m)}if(p!==!0)return console.log(u.red(" Upload cancelled. Nothing was sent.")),ce(),Ne;console.log(u.dim(" Acknowledged at the prompt.")),d="prompt";break}case"refuse":return n1e(),ce(),Ne;case"stop":if(l.why==="acknowledgment-mismatch")console.log(u.red(` ${Fp} must name exactly what was found, which is: ${c.join(",")}. It does not acknowledge this scan. Nothing was sent.`));else JL(c),console.log(u.red(l.why==="declined"?" Declined (--no). Nothing was sent.":` No terminal to ask at: run interactively, or pass ${KL(c)}. --yes does not acknowledge a finding. Nothing was sent.`));return ce(),Ne}let f=s1e(a,d);if(f.status==="ok")console.log();return f}async function a1e(e,t){let n=D("Screening again, right before anything is sent...").start(),r;try{r=await ZRe(e)}catch(a){return o1e(n,a),Ne}let o=Bd(r.status);if(o!=="clear"&&o!=="acknowledge")return W1(n,r),n1e(),ce(),Ne;let s=K1(t.scan),i=K1(r);if(!e1e(s,i))return W1(n,r),console.log(u.red(` The files changed since the preflight, and so did what it found (acknowledged: ${s.join(",")||"nothing"}; now: ${i.join(",")}). Nothing was sent. Run the upload again.`)),ce(),Ne;if($R(r.findings_by_kind)!==$R(t.scan.findings_by_kind))W1(n,r," (screened again)");else n.succeed(`${JM(r,null).headline} (screened again)`);return s1e(r,t.acknowledged_via)}var uPt=/\.(edf|bdf)$/i,p1e=ea(".nemar","date-normalization"),dPt=()=>({tracked:0,"nested-repository":0,ignored:0,"tracking-unknown":0,link:0,"not-writable":0,"other-filesystem":0,unverified:0});function fPt(){return{items:[],left:dPt()}}function pPt(e){if(process.env.GIT_DIR||process.env.GIT_WORK_TREE)return!0;for(let t=e;;t=J1(t)){if(u1e(ea(t,".git")))return!0;if(J1(t)===t)return!1}}var ZL=(e)=>e.normalize("NFC").toLowerCase();async function XL(e,t,n){try{let r=await R(e,{cwd:t,...n===void 0?{}:{stdin:n}});if(!(r.exitCode===0||e.includes("check-ignore")&&r.exitCode===1))return null;return new Set(r.stdout.split("\x00").filter(Boolean).map(ZL))}catch{return null}}async function mPt(e,t){let n=`${t.join("\x00")}\x00`;if(pPt(e)){let o=await XL(["git","ls-files","-z"],e),s=await XL(["git","check-ignore","-z","--stdin"],e,n);return o&&s?{tracked:o,ignored:s}:null}let r=null;try{if(r=rPt(ea(lPt(),"nemar-ignore-")),(await R(["git","init","-q","--bare",r],{cwd:e})).exitCode!==0)return null;let s=await XL(["git",`--git-dir=${r}`,`--work-tree=${e}`,"check-ignore","--no-index","-z","--stdin"],e,n);return s?{tracked:new Set,ignored:s}:null}catch{return null}finally{if(r!==null)try{o3(r,{recursive:!0,force:!0})}catch{}}}function e3(e){let t;try{t=r3(e,"r")}catch{return null}try{let n=new Uint8Array(vt),r=0;while(r<vt){let o=oPt(t,n,r,vt-r,r);if(o===0)break;r+=o}return r===vt?n:null}catch{return null}finally{try{n3(t)}catch{}}}var c1e=(e,t)=>e!==null&&e.length===t.length&&e.every((n,r)=>n===t[r]);function l1e(e){try{return QTt(e,QL.W_OK),!0}catch{return!1}}function hPt(e,t,n){let r=t.split("/").slice(0,-1);for(let o=1;o<=r.length;o++){let s=r.slice(0,o).join("/"),i=n.get(s);if(i===void 0){i=u1e(ea(e,s,".git"));try{i||=Cc(ea(e,s,".git")).isSymbolicLink()}catch{}n.set(s,i)}if(i)return!0}return!1}async function m1e(e){let t=fPt();try{await gPt(e,t)}catch(n){Dn(`date normalization: planning stopped (${n instanceof Error?n.name:"unknown"})`)}return t}async function gPt(e,t){let n=f1e(e).dev,r=YL(e),o=[];for(let c of r.entries){if(!uPt.test(c.path))continue;let l=r.readable.get(c.url);if(l===void 0)continue;let d=e3(l);if(d===null)continue;try{let f=a6(d);if(f.changed)o.push({path:l,rel:c.path,before:d,after:f.header})}catch(f){if(f instanceof Dd)continue;t.left.unverified++,Dn(`date normalization: a header was not planned (${f instanceof Error?f.name:"unknown"})`)}}if(o.length===0)return;let s=await mPt(e,o.map((c)=>c.rel)),i=new Map,a=typeof process.getuid==="function"?process.getuid():null;for(let c of o){if(s===null){t.left["tracking-unknown"]++;continue}if(s.tracked.has(ZL(c.rel))){t.left.tracked++;continue}if(hPt(e,c.rel,i)){t.left["nested-repository"]++;continue}if(s.ignored.has(ZL(c.rel))){t.left.ignored++;continue}let l;try{l=Cc(c.path)}catch{continue}if(l.isSymbolicLink()){t.left.link++;continue}if(!l.isFile())continue;if(l.dev!==n){t.left["other-filesystem"]++;continue}if(a!==null&&l.uid!==a||(l.mode&128)===0||!l1e(c.path)||!l1e(J1(c.path))){t.left["not-writable"]++;continue}t.items.push({path:c.path,rel:c.rel,dev:l.dev,ino:l.ino,size:l.size,mtimeMs:l.mtimeMs,mode:l.mode,gid:l.gid,before:c.before,after:c.after})}}var yPt=/^\d+-[0-9a-f]{16}$/;function bPt(e){try{let t=ea(e,p1e);for(let n of[ea(e,".nemar"),t])if(!Cc(n).isDirectory())return;for(let n of sPt(t))if(yPt.test(n))o3(ea(t,n),{force:!0})}catch{}}function t3(e){for(let t of e)try{aPt(t)}catch{}}function wPt(e,t){let n=[],r=ea(e,p1e);try{for(let o of[ea(e,".nemar"),r]){let s;try{s=Cc(o)}catch{nPt(o),n.push(o),s=Cc(o)}if(!s.isDirectory()||s.dev!==t)return t3([...n].reverse()),null}return{dir:r,made:n}}catch{return t3([...n].reverse()),null}}function _Pt(e){try{let t=r3(e,"r");try{d1e(t)}finally{n3(t)}}catch{}}function xPt(e,t){let n=null;try{let r=(s)=>s.isFile()&&s.dev===e.dev&&s.ino===e.ino&&s.size===e.size&&s.mtimeMs===e.mtimeMs;if(!r(Cc(e.path))||!c1e(e3(e.path),e.before))return null;if(n=ea(t,`${process.pid}-${XTt(8).toString("hex")}`),tPt(e.path,n,QL.COPYFILE_EXCL|QL.COPYFILE_FICLONE),Cc(n).gid!==e.gid)ePt(n,-1,e.gid);ZTt(n,e.mode&4095);let o=r3(n,"r+");try{if(cPt(o,e.after,0,vt,0)!==vt)return null;d1e(o)}finally{n3(o)}if(Cc(n).size!==e.size||!c1e(e3(n),e.after))return null;if(!r(Cc(e.path)))return null;return iPt(n,e.path),n=null,_Pt(J1(e.path)),Cc(e.path).mtimeMs}catch(r){return Dn(`date normalization: a header was not set (${r instanceof Error?r.name:"unknown"})`),null}finally{if(n!==null)try{o3(n,{force:!0})}catch{}}}function h1e(e,t){let n={set:0,left:0,mtimes:new Map};if(bPt(e),t.items.length===0)return n;let r=null;try{r=wPt(e,f1e(e).dev)}catch{}if(r===null)return n.left=t.items.length,Dn("date normalization: no work directory, nothing set"),n;try{for(let o of t.items){let s=xPt(o,r.dir);if(s===null){n.left++;continue}n.set++,n.mtimes.set(o.rel,s)}}finally{t3([r.dir,...[...r.made].reverse().filter((o)=>o!==r.dir)])}if(n.set>0)console.log(u.dim(` ${Dke(n.set)}`));return n}He();Ws();ro();import{existsSync as I_,mkdirSync as qPt,readFileSync as N_,writeFileSync as I1e}from"fs";import{basename as BPt,resolve as Mp}from"path";ec();Je();Pr();Ws();import{existsSync as Y1,readFileSync as s3,writeFileSync as y1e}from"fs";import{resolve as X1}from"path";var i3=[{spdxId:"CC0-1.0",name:"CC0 1.0 Universal (Public Domain)",description:"No rights reserved. Anyone can use the data for any purpose.",url:"https://creativecommons.org/publicdomain/zero/1.0/",allowsResearchUse:!0},{spdxId:"PDDL-1.0",name:"Open Data Commons Public Domain Dedication and License (PDDL)",description:"Database-specific public domain dedication.",url:"https://opendatacommons.org/licenses/pddl/1-0/",allowsResearchUse:!0},{spdxId:"CC-BY-4.0",name:"Creative Commons Attribution 4.0 International",description:"Attribution required. Free for any use including commercial.",url:"https://creativecommons.org/licenses/by/4.0/",allowsResearchUse:!0},{spdxId:"CC-BY-SA-4.0",name:"Creative Commons Attribution-ShareAlike 4.0 International",description:"Attribution + share-alike required. Derivatives must use same license.",url:"https://creativecommons.org/licenses/by-sa/4.0/",allowsResearchUse:!0},{spdxId:"CC-BY-NC-4.0",name:"Creative Commons Attribution-NonCommercial 4.0 International",description:"Attribution required. Non-commercial use only.",url:"https://creativecommons.org/licenses/by-nc/4.0/",allowsResearchUse:!0},{spdxId:"CC-BY-NC-SA-4.0",name:"Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International",description:"Attribution + non-commercial + share-alike required.",url:"https://creativecommons.org/licenses/by-nc-sa/4.0/",allowsResearchUse:!0},{spdxId:"ODC-By-1.0",name:"Open Data Commons Attribution License v1.0",description:"Database-specific attribution license.",url:"https://opendatacommons.org/licenses/by/1.0/",allowsResearchUse:!0},{spdxId:"ODbL-1.0",name:"Open Data Commons Open Database License v1.0",description:"Database attribution + share-alike. Produced works can be any license.",url:"https://opendatacommons.org/licenses/odbl/1.0/",allowsResearchUse:!0}],g1e=new Set(["CC0-1.0","CC-BY-4.0","CC-BY-SA-4.0","CC-BY-NC-4.0","CC-BY-NC-SA-4.0","CC-BY-ND-4.0","CC-BY-NC-ND-4.0","PDDL-1.0","ODC-By-1.0","ODbL-1.0","MIT","Apache-2.0","GPL-2.0-only","GPL-2.0-or-later","GPL-3.0-only","GPL-3.0-or-later","LGPL-2.1-only","LGPL-2.1-or-later","LGPL-3.0-only","LGPL-3.0-or-later","BSD-2-Clause","BSD-3-Clause","ISC","Unlicense"]);function b1e(e){let t=X1(e,"dataset_description.json");if(Y1(t))try{let r=JSON.parse(s3(t,"utf-8"));if(typeof r.License==="string"&&r.License.trim())return{spdxId:r.License.trim(),source:"dataset_description"}}catch(r){if(r instanceof SyntaxError)console.warn(` Warning: dataset_description.json has invalid JSON: ${r.message}`);else console.warn(` Warning: Could not read dataset_description.json: ${r instanceof Error?r.message:String(r)}`)}let n=["LICENSE","LICENSE.txt","LICENSE.md","LICENCE","LICENCE.txt"];for(let r of n){let o=X1(e,r);if(Y1(o)){try{let s=s3(o,"utf-8").toLowerCase();if(s.includes("cc0")||s.includes("public domain dedication"))return{spdxId:"CC0-1.0",source:"license_file"};if(s.includes("attribution-noncommercial-sharealike"))return{spdxId:"CC-BY-NC-SA-4.0",source:"license_file"};if(s.includes("attribution-noncommercial"))return{spdxId:"CC-BY-NC-4.0",source:"license_file"};if(s.includes("attribution-sharealike"))return{spdxId:"CC-BY-SA-4.0",source:"license_file"};if(s.includes("creativecommons")&&s.includes("attribution"))return{spdxId:"CC-BY-4.0",source:"license_file"};if(s.includes("open database license")||s.includes("odbl"))return{spdxId:"ODbL-1.0",source:"license_file"};if(s.includes("open data commons")&&s.includes("attribution"))return{spdxId:"ODC-By-1.0",source:"license_file"};if(s.includes("public domain dedication and license")||s.includes("pddl"))return{spdxId:"PDDL-1.0",source:"license_file"};if(s.includes("permission is hereby granted, free of charge")||s.includes("mit license"))return{spdxId:"MIT",source:"license_file"}}catch(s){console.warn(` Warning: Could not read ${r}: ${s instanceof Error?s.message:String(s)}`)}return{spdxId:void 0,source:"license_file"}}}return{spdxId:void 0,source:"none"}}async function a3(e){let t=i3.map((o)=>({name:`${o.spdxId.padEnd(22)} ${o.description}`,value:o.spdxId,short:o.spdxId}));t.push({name:"Other (enter SPDX ID manually)",value:"__custom__",short:"Custom"});let n=e?i3.find((o)=>o.spdxId===e)?.spdxId:void 0,{selected:r}=await Ae.prompt([{type:"list",name:"selected",message:"Select a license for this dataset:",choices:t,default:n,pageSize:t.length}]);if(r==="__custom__"){let{customId:o}=await Ae.prompt([{type:"input",name:"customId",message:"Enter SPDX license ID (e.g., MIT, Apache-2.0):",validate:(s)=>{if(!s.trim())return"License ID is required";return!0}}]);return o.trim()}return r}function w1e(e){let t=e.toUpperCase().replace(/\s+/g,"-");if(g1e.has(e))return!0;for(let n of g1e)if(n.toUpperCase()===t)return!0;return!1}function vPt(e){let t=i3.find((n)=>n.spdxId===e);if(t)return`${t.name}
|
|
1983
1983
|
|
|
1984
1984
|
${t.url}
|
|
1985
1985
|
|
|
@@ -1995,7 +1995,7 @@ Provide source dataset information so we can check license compatibility.`);whil
|
|
|
1995
1995
|
`);let{continueAnyway:l}=await Ae.prompt([{type:"confirm",name:"continueAnyway",message:"Continue despite the incompatibility warning?",default:!1}]);if(!l)throw Error("Upload cancelled due to license incompatibility.")}else if(a.reason&&!a.reason.includes("Compatible."))console.log(`
|
|
1996
1996
|
Note: ${a.reason}
|
|
1997
1997
|
`);n.push({identifier:s.trim(),license:i.trim()});let{more:c}=await Ae.prompt([{type:"confirm",name:"more",message:"Add another source dataset?",default:!1}]);r=c}let{confirmed:o}=await Ae.prompt([{type:"confirm",name:"confirmed",message:"Do you confirm you have the right to redistribute this derived dataset under the selected license, respecting the source dataset(s) terms?",default:!0}]);if(!o)throw Error("Upload cancelled: redistribution rights must be confirmed before uploading.");return{isDerived:!0,sourceDatasets:n,confirmedRedistributionRights:!0}}async function N1e(e,t){let n=D("Analyzing dataset files...").start(),r={};try{let i=Mp(e,"dataset_description.json");r=JSON.parse(N_(i,"utf-8"))}catch(i){if(i.code!=="ENOENT")console.log(u.yellow(`Warning: Could not read dataset_description.json: ${i.message}`))}let o=t.name||(typeof r.Name==="string"?r.Name:null)||BPt(e),s=await wbe(e);return n.succeed(`Found ${s.files.length} files (${s.dataFiles} data, ${s.metadataFiles} metadata)`),{datasetName:o,manifest:s,bidsDescription:r}}async function F1e(e,t,n){let r,o=Mp(e,".nemar","metadata.json"),s=Mp(e,"nemar_metadata.json");if(I_(o))try{r=JSON.parse(N_(o,"utf-8")),console.log(u.dim(" Using existing .nemar/metadata.json (author ORCIDs from prior run)"))}catch(i){console.log(u.yellow(` Warning: Could not read .nemar/metadata.json: ${i instanceof Error?i.message:i}. Will re-collect author information.`))}else if(I_(s))try{r=JSON.parse(N_(s,"utf-8")),console.log(u.dim(" Using existing nemar_metadata.json (author ORCIDs from prior run)"))}catch(i){console.log(u.yellow(` Warning: Could not read nemar_metadata.json: ${i instanceof Error?i.message:i}. Will re-collect author information.`))}if(!r&&!t.skipOrcid&&process.stdin.isTTY){let i=n.Authors,a=Array.isArray(i)?i.filter((c)=>typeof c==="string"):[];if(a.length>0)try{let c,l;try{let p=await Wr();c=p.orcid||void 0,l=p.username??void 0}catch(p){console.log(u.dim(` Could not fetch profile: ${G(p)}`))}console.log(),console.log(u.cyan("Authors found:"),a.join(" | "));let d={},f;if(c&&l){let p=l.toLowerCase(),m=a.find((h)=>h.toLowerCase().includes(p));if(m)d[m]={orcid:c},f=m,console.log(` Your ORCID (from profile): ${u.green(c)} (matched to "${m}")`)}try{await Promise.resolve().then(() => P1e());let m=D("Looking up author ORCIDs from referenced publications...").start(),h=await T1e(n,d),g=Object.keys(h.discoveries).length;if(g>0){m.succeed(`Found ${g} ORCID(s) from referenced DOIs`);for(let[b,_]of Object.entries(h.discoveries))console.log(` ${u.green(_.orcid)} -> "${b}" (from ${_.sourceDoi}, ${_.confidence} match)`);let{confirmOrcids:y}=await Ae.prompt([{type:"confirm",name:"confirmOrcids",message:"Accept these auto-discovered ORCIDs?",default:!0}]);if(y)for(let[b,_]of Object.entries(h.discoveries))d[b]={...d[b],orcid:_.orcid,..._.affiliations&&{affiliations:_.affiliations}}}else m.info("No ORCIDs found from referenced DOIs")}catch(p){console.log(u.yellow(` Could not auto-discover ORCIDs: ${G(p)}`))}for(let p of a){if(p===f)continue;if(d[p]?.orcid)continue;let{orcid:m}=await Ae.prompt([{type:"input",name:"orcid",message:`ORCID for "${p}" (Enter to skip):`,validate:(h)=>{if(!h)return!0;return DS.test(h)||"Invalid ORCID format (XXXX-XXXX-XXXX-XXXX)"}}]);if(m){let h={orcid:m},{affiliation:g}=await Ae.prompt([{type:"input",name:"affiliation",message:` Affiliation for "${p}" (optional):`}]);if(g)h.affiliations=[{name:g}];d[p]=h}}if(Object.keys(d).length>0){r={version:"2.0",authors:d};try{let p=Mp(e,".nemar");if(!I_(p))qPt(p,{recursive:!0});let m=Mp(p,"metadata.json");I1e(m,JSON.stringify(r,null,2)),console.log(u.dim(" Saved .nemar/metadata.json with author ORCIDs"))}catch(p){console.log(u.yellow(` Warning: Could not save .nemar/metadata.json: ${G(p)}`))}}console.log()}catch(c){if(c instanceof L)console.log(u.yellow(` Could not fetch profile: ${c.message}`));else console.log(u.yellow(` Could not collect ORCIDs: ${G(c)}`));console.log(u.dim(" Continuing without author enrichment."))}}return r}async function M1e(e,t){let n;if(process.stdin.isTTY&&!t.skipValidation){let r=b1e(e);if(r.spdxId){if(console.log(),console.log(u.cyan("License detected:"),u.bold(r.spdxId),u.dim(`(from ${r.source==="dataset_description"?"dataset_description.json":"LICENSE file"})`)),!w1e(r.spdxId))console.log(u.yellow(` Warning: "${r.spdxId}" is not in the list of known research-compatible licenses.`));let{keepLicense:s}=await Ae.prompt([{type:"confirm",name:"keepLicense",message:`Use "${r.spdxId}" as the dataset license?`,default:!0}]);if(s)n=r.spdxId;else n=await a3(r.spdxId)}else{if(console.log(),r.source==="license_file")console.log(u.yellow("A LICENSE file was found but the license could not be identified automatically."));else console.log(u.yellow("No license found in this dataset."));console.log(u.dim("A license is required to publish on NEMAR.")),n=await a3()}try{let s=Mp(e,"dataset_description.json");if(I_(s)){if(JSON.parse(N_(s,"utf-8")).License!==n)x1e(e,n),console.log(u.dim(` Updated dataset_description.json License -> ${n}`))}}catch(s){console.log(u.yellow(` Warning: Could not update license in dataset_description.json: ${G(s)}`))}if(_1e(e,n))console.log(u.dim(` Created LICENSE file (${n})`));console.log()}return n}async function j1e(e,t,n){if(process.stdin.isTTY&&!t.skipValidation&&n){let r=await v1e(n);if(r.isDerived&&r.sourceDatasets&&r.sourceDatasets.length>0){try{let o=Mp(e,"dataset_description.json");if(I_(o)){let s=JSON.parse(N_(o,"utf-8")),i=Array.isArray(s.SourceDatasets)?s.SourceDatasets:[],a=r.sourceDatasets.map((l)=>l.identifier),c=Array.from(new Set([...i,...a]));s.SourceDatasets=c,I1e(o,`${JSON.stringify(s,null,2)}
|
|
1998
|
-
`),console.log(u.dim(` Updated dataset_description.json SourceDatasets (${c.length} source(s))`))}}catch(o){console.log(u.yellow(` Warning: Could not update SourceDatasets: ${G(o)}`))}console.log()}}}He();fD();gD();Ad();ip();function L1e(e,t,n){if(t&&t.dataset_id!==n)return console.log(u.yellow(" Progress file is for a different dataset; starting fresh.")),Ew(e),null;return t}function q1e(e,t,n,r){let o=m6(e);if(console.log(),o)console.log(u.bold.yellow("Resume Upload:")),console.log(` Dataset ID: ${u.cyan(o.dataset_id)}`),console.log(` Last attempt: ${o.last_upload_at||o.created_at}`);else console.log(u.bold("Upload Plan:"));if(console.log(` Name: ${t}`),console.log(` Path: ${e}`),console.log(` Files: ${n.files.length}`),console.log(` Size: ${Ut(n.totalSize)}`),console.log(` Data files: ${n.dataFiles} (will be uploaded to S3)`),console.log(` Metadata files: ${n.metadataFiles} (will be stored in git)`),console.log(` Local git-annex add workers: ${r.annexJobs??qg}`),console.log(` Parallel S3 copy streams: ${r.jobs}`),console.log(),r.dryRun)return console.log(u.yellow("Dry run mode - no changes made")),o_e;return fn({existingConfig:o})}function B1e(e,t){return e?e_e(e,t):t}function U1e(e,t,n){let r=t.files.filter((s)=>s.type==="data");if(n.restart)Ew(e),console.log(u.dim(" Upload progress cleared (--restart)")),console.log();let o=n.restart?null:Ywe(e);if(o){let s=t_e(o);if(console.log(u.bold.cyan("Upload Progress:")),console.log(` Files: ${s.uploaded}/${s.total} uploaded, ${s.failed} failed, ${s.pending} pending`),s.completedSteps.length>0)console.log(` Completed steps: ${s.completedSteps.join(", ")}`);console.log()}return{dataFiles:r,uploadProgress:o}}He();ro();import{existsSync as UPt}from"fs";import{resolve as HPt}from"path";Zm();th();
|
|
1998
|
+
`),console.log(u.dim(` Updated dataset_description.json SourceDatasets (${c.length} source(s))`))}}catch(o){console.log(u.yellow(` Warning: Could not update SourceDatasets: ${G(o)}`))}console.log()}}}He();fD();gD();Ad();ip();function L1e(e,t,n){if(t&&t.dataset_id!==n)return console.log(u.yellow(" Progress file is for a different dataset; starting fresh.")),Ew(e),null;return t}function q1e(e,t,n,r){let o=m6(e);if(console.log(),o)console.log(u.bold.yellow("Resume Upload:")),console.log(` Dataset ID: ${u.cyan(o.dataset_id)}`),console.log(` Last attempt: ${o.last_upload_at||o.created_at}`);else console.log(u.bold("Upload Plan:"));if(console.log(` Name: ${t}`),console.log(` Path: ${e}`),console.log(` Files: ${n.files.length}`),console.log(` Size: ${Ut(n.totalSize)}`),console.log(` Data files: ${n.dataFiles} (will be uploaded to S3)`),console.log(` Metadata files: ${n.metadataFiles} (will be stored in git)`),console.log(` Local git-annex add workers: ${r.annexJobs??qg}`),console.log(` Parallel S3 copy streams: ${r.jobs}`),console.log(),r.dryRun)return console.log(u.yellow("Dry run mode - no changes made")),o_e;return fn({existingConfig:o})}function B1e(e,t){return e?e_e(e,t):t}function U1e(e,t,n){let r=t.files.filter((s)=>s.type==="data");if(n.restart)Ew(e),console.log(u.dim(" Upload progress cleared (--restart)")),console.log();let o=n.restart?null:Ywe(e);if(o){let s=t_e(o);if(console.log(u.bold.cyan("Upload Progress:")),console.log(` Files: ${s.uploaded}/${s.total} uploaded, ${s.failed} failed, ${s.pending} pending`),s.completedSteps.length>0)console.log(` Completed steps: ${s.completedSteps.join(", ")}`);console.log()}return{dataFiles:r,uploadProgress:o}}He();ro();import{existsSync as UPt}from"fs";import{resolve as HPt}from"path";Zm();th();Je();sp();rc();qt();ip();var zPt=17179869184;function VPt(e){let t=e.trim();if(t==="unlimited")return"unlimited";if(!/^\d+$/.test(t))return null;return Number(t)*1024}async function GPt(){try{let{stdout:e,exitCode:t}=await R(["sh","-c","ulimit -v"]);if(t!==0)return null;return VPt(e)}catch{return null}}async function H1e(e={}){let t=D("Checking upload access...").start(),n;try{n=await Wr()}catch(r){return t.warn(Xc(nr("cli.upload.preflight.unchecked"),{reason:G(r)})),console.log(),fn()}if(n.service_access===!0)return t.succeed("Upload access granted"),console.log(),fn();if(n.service_access===void 0)return t.warn(Xc(nr("cli.upload.preflight.unchecked"),{reason:"this backend does not report it"})),console.log(),fn();if(t.warn(nr("cli.upload.preflight.title")),console.log(),console.log(` ${nr("cli.upload.preflight.body")}`),n.profile_gaps===void 0)console.log(),console.log(` ${u.dim(nr("cli.upload.preflight.gaps_unknown"))}`);else{let r=nk(n.profile_gaps,{orcidVerified:n.orcid_verified===!0}).filter((o)=>o.blocks.includes("upload_access"));if(r.length>0)v1(nr("gaps.upload.title"),r)}if(console.log(),console.log(` ${u.cyan(nr("cli.upload_access.cta"))}`),e.dryRun)return console.log(` ${u.dim(nr("cli.upload.preflight.dry_run"))}`),console.log(),fn();return console.log(),Ne}async function z1e(){let e=D("Checking prerequisites...").start(),t=await m$();if(!t.allPassed){e.fail("Prerequisites check failed"),console.log();for(let r of t.errors)console.log(u.red(` - ${r}`));return Ne}if(e.succeed("Prerequisites check passed"),console.log(u.dim(` git-annex ${t.gitAnnex.version}`)),t.githubSSH.username)console.log(u.dim(` GitHub: ${t.githubSSH.username}`));let n=await GPt();if(typeof n==="number"&&n<zPt)console.log(u.yellow(` Warning: virtual memory limit is ${Ut(n)} (ulimit -v).`)),console.log(u.yellow(" git-annex may be killed with out-of-memory errors while tracking data files.")),console.log(u.yellow(" On HPC systems, run the upload from a compute node or raise the limit (ulimit -v unlimited)."));return console.log(),fn()}async function V1e(e){let t=D("Verifying GitHub CLI authentication...").start(),n=await MS(e.githubUsername);if(!n.authenticated)return go(t,"GitHub CLI not authenticated",n.error),console.log(),console.log("GitHub CLI is required for dataset uploads. Install and authenticate:"),console.log(u.cyan(" brew install gh # or visit https://cli.github.com/")),console.log(u.cyan(" gh auth login")),Ne;if(e.githubUsername&&!n.matches)t.warn("GitHub CLI user mismatch"),console.log(u.yellow(` ${n.error}`)),console.log(),console.log("Your gh CLI is authenticated as a different GitHub account than your NEMAR account."),console.log("This may cause issues with repository access. To fix:"),console.log(u.cyan(` gh auth login # Login as ${e.githubUsername}`)),console.log(),console.log(u.yellow("WARNING: If upload fails with permission errors, this mismatch is the likely cause.")),console.log();else t.succeed(`GitHub CLI authenticated as ${n.username}`);return fn()}async function G1e(e,t){if(!t.skipValidation){let n=D("Validating BIDS dataset...").start(),r=HPt(e,"dataset_description.json");if(!UPt(r))return n.fail("Not a valid BIDS dataset"),console.log(u.red("Missing required file: dataset_description.json")),Ne;if(!(await _y()).installed)return n.fail("Deno is required for BIDS validation"),console.log(),console.log(u.red("Error: Deno is not installed")),console.log(),console.log("The BIDS validator requires Deno runtime to run."),console.log("Install Deno with one of these commands:"),console.log(),console.log(u.cyan(" # macOS/Linux (curl)")),console.log(" curl -fsSL https://deno.land/install.sh | sh"),console.log(),console.log(u.cyan(" # macOS (Homebrew)")),console.log(" brew install deno"),console.log(),console.log(u.cyan(" # Windows (PowerShell)")),console.log(" irm https://deno.land/install.ps1 | iex"),console.log(),console.log("Learn more: https://docs.deno.com/runtime/getting_started/installation/"),console.log(),console.log(u.dim("To skip validation (not recommended): nemar dataset upload --skip-validation")),Ne;try{let s=await rRe(e,{prune:!0});if(!s.valid)return n.fail("Dataset has validation errors"),console.log(),console.log(aRe(s)),console.log(),console.log(u.yellow("Fix the errors above before uploading.")),console.log(u.dim("Or use --skip-validation to upload anyway (not recommended).")),Ne;n.succeed(`Dataset is valid BIDS (${s.warningCount} warnings)`)}catch(s){return n.fail("Validation failed"),console.log(u.red(s.message)),Ne}console.log()}return fn()}Ad();function l3(e,t){return e.startsWith("on")||t==="openneuro"}function W1e(e){if(!l3(e.datasetId,e.source))return null;let t=_l(e.current),n=_l(e.next);if(!t||!n)return`${e.datasetId} is a mirror, and its version ${JSON.stringify(e.current)} -> ${JSON.stringify(e.next)} cannot be read as two releases, so whether it is a major (an upstream re-pull, ADR 0111) is not known; it is not released by hand. A version is of the form X.Y.Z (three numbers, such as 1.2.0, with no prerelease): give one with --version X.Y.Z, or correct the dataset's Version to that form first.`;if(n.major<=t.major)return null;return`A major version of a mirror means an upstream re-pull (ADR 0006, ADR 0111): ${e.datasetId} ${e.current} -> ${e.next} is not released by hand. Plan one with: nemar admin repull plan ${e.datasetId}`}function sCe(e){if(e instanceof L){if(e.statusCode===404)return"Dataset not found";if(e.statusCode===403)return"Dataset not accessible";return`Could not read the dataset (HTTP ${e.statusCode})`}return"Could not reach the backend"}var On=new de("dataset").description("Dataset management").addHelpText("after",`
|
|
1999
1999
|
Description:
|
|
2000
2000
|
Manage BIDS datasets on NEMAR. Upload, download, validate, and version
|
|
2001
2001
|
neurophysiology datasets in Brain Imaging Data Structure (BIDS) format.
|
|
@@ -2046,7 +2046,7 @@ Learn More:
|
|
|
2046
2046
|
$ nemar dataset validate ./ds --ignoreNiftiHeaders # Pass-through flag
|
|
2047
2047
|
$ nemar dataset validate ./ds --max-rows 0 # Headers only`).action(async(e,t)=>{if(t.update){if(!(await _y()).installed)console.log(u.red("Deno is not installed")),console.log("Install Deno: https://deno.com"),process.exit(1);let d=await NL(),f=D("Updating BIDS validator to latest version...").start(),p=await IL();if(!p)f.fail("Failed to update BIDS validator"),process.exit(1);if(d&&d!==p)f.succeed(`BIDS validator updated: ${d} -> ${p}`);else f.succeed(`BIDS validator is up to date (v${p})`);if(!e||e==="."){let m=process.cwd();if(!ms(Ns(m,"dataset_description.json")))return}}if(t.versionInfo){let l=await _y();if(!l.installed)console.log(u.red("Deno is not installed")),console.log("Install Deno: https://deno.com"),process.exit(1);let d=PL(),f=await NL();console.log(`BIDS Validator: ${f||"unknown"}${d?u.yellow(" (cache may be stale, run --update to refresh)"):""}`),console.log(`Deno: ${l.version||"unknown"}`);return}if(!e)console.log(u.red("Error: Missing required argument: path")),console.log("Usage: nemar dataset validate <path>"),process.exit(1);if(!(await _y()).installed)console.log(u.red("Error: Deno is required for BIDS validation")),console.log(),console.log("The BIDS validator runs on Deno runtime."),console.log("Install Deno with one of these commands:"),console.log(),console.log(u.cyan(" # macOS/Linux (curl)")),console.log(" curl -fsSL https://deno.land/install.sh | sh"),console.log(),console.log(u.cyan(" # macOS (Homebrew)")),console.log(" brew install deno"),console.log(),console.log(u.cyan(" # Windows (PowerShell)")),console.log(" irm https://deno.land/install.ps1 | iex"),console.log(),console.log("Learn more: https://docs.deno.com/runtime/getting_started/installation/"),process.exit(1);let r=!!t.update;if(!r&&PL()){let l=D("Checking for BIDS validator updates...").start(),d=await IL();if(d)l.succeed(`BIDS validator updated to v${d}`);else l.info("Could not check for validator updates, using cached version")}let o=Ns(e);if(!ms(o))console.log(u.red(`Error: Path does not exist: ${o}`)),process.exit(1);let s=Ns(o,"dataset_description.json");if(!ms(s))console.log(u.red("Error: Not a valid BIDS dataset")),console.log("Missing required file: dataset_description.json"),console.log(`Path: ${o}`),process.exit(1);let i=JPt(),a=sRe(i),c=D("Validating BIDS dataset...").start();try{let{stdout:l,stderr:d,exitCode:f}=await oRe(o,{config:t.config,ignoreWarnings:t.ignoreWarnings,recursive:t.recursive,prune:t.prune,verbose:t.verbose,json:t.json,extraArgs:i,forceReload:r}),p=a!==void 0&&f===j1;if(!l.trim()&&f!==0&&!p){if(c.fail("Validation failed"),d.trim()){let m=d.split(`
|
|
2048
2048
|
`).filter((h)=>!h.includes("Ignored build scripts")).join(`
|
|
2049
|
-
`).trim();if(m)console.error(m)}process.exit(1)}if(f!==0&&f!==j1)c.fail("Validation failed"),console.error(d.trim()||l.trim()||`BIDS validator exited with code ${f}`),process.exit(f);if(a)iRe(Ns(a),Boolean(t.json));if(c.succeed("Validation complete"),t.json){if(!a)console.log(FL(l));else if(l.trim())console.log(l)}else{if(l.trim())console.log(l);console.log(`Validator: @bids/validator ${wy}`)}process.exit(f)}catch(l){c.fail("Validation failed"),console.error(u.red(l.message)),process.exit(1)}});function JPt(){let e=new Set(["--ignore-warnings","--config","-c","--recursive","-r","--prune","--verbose","-v","--json","--version-info","--help","-h"]),t=[],n=process.argv.indexOf("validate");if(n<0)return t;let r=process.argv.slice(n+1);for(let o=0;o<r.length;o++){let s=r[o];if(!s.startsWith("-"))continue;if(e.has(s)){if(s==="--config"||s==="-c")o++;continue}if(t.push(s),o+1<r.length&&!r[o+1].startsWith("-"))t.push(r[o+1]),o++}return t}function f3(){return new de("upload").description("Upload a BIDS dataset to NEMAR").argument("<path>","Path to BIDS dataset directory").option("-n, --name <name>","Dataset name (defaults to BIDS Name, then directory name)").option("-d, --description <desc>","Dataset description").option("--skip-validation","Skip BIDS validation (not recommended)").option("--skip-orcid","Skip co-author ORCID collection").option("--dry-run","Show what would be uploaded without doing it").option("-j, --jobs <number>","Parallel S3 copy streams","4").option("--annex-jobs <number>","Parallel local git-annex add workers",String(qg)).option(
|
|
2049
|
+
`).trim();if(m)console.error(m)}process.exit(1)}if(f!==0&&f!==j1)c.fail("Validation failed"),console.error(d.trim()||l.trim()||`BIDS validator exited with code ${f}`),process.exit(f);if(a)iRe(Ns(a),Boolean(t.json));if(c.succeed("Validation complete"),t.json){if(!a)console.log(FL(l));else if(l.trim())console.log(l)}else{if(l.trim())console.log(l);console.log(`Validator: @bids/validator ${wy}`)}process.exit(f)}catch(l){c.fail("Validation failed"),console.error(u.red(l.message)),process.exit(1)}});function JPt(){let e=new Set(["--ignore-warnings","--config","-c","--recursive","-r","--prune","--verbose","-v","--json","--version-info","--help","-h"]),t=[],n=process.argv.indexOf("validate");if(n<0)return t;let r=process.argv.slice(n+1);for(let o=0;o<r.length;o++){let s=r[o];if(!s.startsWith("-"))continue;if(e.has(s)){if(s==="--config"||s==="-c")o++;continue}if(t.push(s),o+1<r.length&&!r[o+1].startsWith("-"))t.push(r[o+1]),o++}return t}function f3(){return new de("upload").description("Upload a BIDS dataset to NEMAR").argument("<path>","Path to BIDS dataset directory").option("-n, --name <name>","Dataset name (defaults to BIDS Name, then directory name)").option("-d, --description <desc>","Dataset description").option("--skip-validation","Skip BIDS validation (not recommended)").option("--skip-orcid","Skip co-author ORCID collection").option("--dry-run","Show what would be uploaded without doing it").option("-j, --jobs <number>","Parallel S3 copy streams","4").option("--annex-jobs <number>","Parallel local git-annex add workers",String(qg)).option(Ye,nt).option("--restart","Clear upload progress and re-upload all files").option("--no",ht).option("--deposit-type <type>","Attestation: 'owner' or 'redistribution' (non-interactive)").option("--key-status <status>","Attestation: re-identification key 'destroyed' or 'retained'").option("--confirm-deidentified","Attestation: confirm the dataset contains no identifiable personal information").option("--affirm-no-duplicate","Attestation (redistribution only): affirm the dataset is not already archived in BIDS format").option("--upstream-source <ref>","Attestation (redistribution only): upstream release URL or accession").option("--dataset-id <id>","Name the dataset id instead of being allocated one (admin, non-production, reserved fixture band only)").addOption(new zp(`${Fp} <verdicts>`,`Upload despite what the identifier preflight found, naming every condition it reports (non-interactive; recorded; repeatable or comma-separated: ${RR.join(", ")}). Direct identifiers cannot be acknowledged`).argParser(t1e)).addHelpText("after",({command:e})=>`
|
|
2050
2050
|
Description:
|
|
2051
2051
|
Upload a BIDS dataset to NEMAR. The dataset will be validated, assigned
|
|
2052
2052
|
a unique ID (nm000XXX), and stored on GitHub (metadata) and S3 (data files).
|
|
@@ -2207,7 +2207,7 @@ Examples:
|
|
|
2207
2207
|
$ nemar dataset search "sleep spindles" --json
|
|
2208
2208
|
$ nemar dataset search "motor imagery" --license public --subjects 10..
|
|
2209
2209
|
$ nemar dataset search "P300 oddball" --verbose # Show README snippets`).action(async(e,t)=>{lCe(t.license);let n=uCe(t),r=D("Searching datasets...").start();try{let o=await Tme(e,{modality:t.modality,hasHed:!!t.hed,hasZarr:!!t.hasZarr,hasZarrVerified:!!t.hasZarrVerified,limit:Number.parseInt(t.limit,10),author:t.author,task:t.task,license:t.license,hasDoi:!!t.doi,dataComplete:!!t.complete,recent:t.recent?Number.parseInt(t.recent,10)||30:void 0,facets:n,includeUnknown:!!t.includeUnknown});if(r.stop(),t.json){console.log(JSON.stringify(o,null,2)),Pp();return}if(o.warning)console.log(uo.warn(`
|
|
2210
|
-
\u26A0 ${o.warning}`));if(o.excluded_unknown!==void 0&&o.excluded_unknown>0)console.error(uo.muted(UL(o.excluded_unknown,o.excluded_unknown_by_facet??{})));if(o.results.length===0){console.log(),console.log(uo.warn("No datasets match your search.")),console.log(uo.muted("Try different search terms or use 'nemar dataset list' for browsing.")),Pp();return}console.log(),console.log(uo.label(`Search results for "${e}" (${o.results.length} found, ${o.method}):`)),console.log();let s=u3;try{let i=process.stdout.columns;if(typeof i==="number"&&Number.isFinite(i)&&i>0)s=Math.floor(i)}catch{s=u3}try{for(let i of oIt(o.results,s,{snippets:sIt()}))console.log(i)}catch(i){if(process.env.VERBOSE)console.error(uo.muted(`[search] table rendering failed, falling back to a plain list: ${i instanceof Error?i.message:String(i)}`));for(let a of o.results)console.log(`${a.id} ${a.name}`)}console.log(),console.log(uo.muted("For details: nemar dataset status <dataset-id>")),Pp()}catch(o){if(r.fail("Search failed"),o instanceof L)console.log(u.red(` ${o.message}`));else console.log(u.red(` ${o.message}`));process.exit(1)}});On.command("release").description("Create a version bump PR for a dataset").argument("<dataset-id>","Dataset ID (e.g., nm000104)").option("--type <type>","Bump type: patch, minor, or major").option("--version <version>","Explicit version (e.g., 2.0.0)").option("--dir <path>","Use existing local clone instead of cloning").option("--monitor","Watch CI checks and offer to merge").option(
|
|
2210
|
+
\u26A0 ${o.warning}`));if(o.excluded_unknown!==void 0&&o.excluded_unknown>0)console.error(uo.muted(UL(o.excluded_unknown,o.excluded_unknown_by_facet??{})));if(o.results.length===0){console.log(),console.log(uo.warn("No datasets match your search.")),console.log(uo.muted("Try different search terms or use 'nemar dataset list' for browsing.")),Pp();return}console.log(),console.log(uo.label(`Search results for "${e}" (${o.results.length} found, ${o.method}):`)),console.log();let s=u3;try{let i=process.stdout.columns;if(typeof i==="number"&&Number.isFinite(i)&&i>0)s=Math.floor(i)}catch{s=u3}try{for(let i of oIt(o.results,s,{snippets:sIt()}))console.log(i)}catch(i){if(process.env.VERBOSE)console.error(uo.muted(`[search] table rendering failed, falling back to a plain list: ${i instanceof Error?i.message:String(i)}`));for(let a of o.results)console.log(`${a.id} ${a.name}`)}console.log(),console.log(uo.muted("For details: nemar dataset status <dataset-id>")),Pp()}catch(o){if(r.fail("Search failed"),o instanceof L)console.log(u.red(` ${o.message}`));else console.log(u.red(` ${o.message}`));process.exit(1)}});On.command("release").description("Create a version bump PR for a dataset").argument("<dataset-id>","Dataset ID (e.g., nm000104)").option("--type <type>","Bump type: patch, minor, or major").option("--version <version>","Explicit version (e.g., 2.0.0)").option("--dir <path>","Use existing local clone instead of cloning").option("--monitor","Watch CI checks and offer to merge").option(Ye,nt).addHelpText("after",`
|
|
2211
2211
|
Description:
|
|
2212
2212
|
Create a pull request that bumps the dataset version in
|
|
2213
2213
|
dataset_description.json. The PR triggers CI checks (BIDS validation,
|
|
@@ -2225,7 +2225,7 @@ Bumps ${e} from ${o} to ${s}.
|
|
|
2225
2225
|
On merge, CI will:
|
|
2226
2226
|
- Tag the release (v${s})
|
|
2227
2227
|
- Publish a version DOI (if concept DOI exists)`,T=xo({cmd:["gh","pr","create","--repo",r.github_repo,"--head",l,"--base","main","--title",v,"--body",C],cwd:a,stdout:"pipe",stderr:"pipe"}),z=(await new Response(T.stdout).text()).trim();if(await T.exited!==0){let A=await new Response(T.stderr).text();throw Error(A.trim()||"gh pr create failed")}x=!0,k.succeed("Created pull request"),console.log(),console.log(` ${u.cyan("PR:")} ${z}`)}catch(v){k.fail("Failed to create PR");let C=v instanceof Error?v.message:String(v);if(console.log(u.red(` ${C}`)),C.includes("not found")||C.includes("command not found"))console.log(u.yellow(" Install: brew install gh"));else if(C.includes("auth")||C.includes("401"))console.log(u.yellow(" Run: gh auth login"));console.log(u.dim(` Branch ${l} has been pushed. Create the PR manually.`))}if(t.monitor&&x){console.log(),console.log(u.dim("Monitoring CI checks...")),console.log(u.dim(" Press Ctrl+C to stop monitoring"));let v=0,C=60;while(v<C){await new Promise((F)=>setTimeout(F,1e4)),v++;let T=xo({cmd:["gh","pr","checks","--repo",r.github_repo,l],cwd:a,stdout:"pipe",stderr:"pipe"}),z=await new Response(T.stdout).text();if(await T.exited===0){if(console.log(u.green(" All checks passed!")),await De("Merge the PR?",{yes:t.yes})==="confirmed"){let M=xo({cmd:["gh","pr","merge","--repo",r.github_repo,l,"--squash","--delete-branch"],cwd:a,stdout:"pipe",stderr:"pipe"});if(await M.exited===0)console.log(u.green(" PR merged successfully!"));else{let B=await new Response(M.stderr).text();console.log(u.red(` Merge failed: ${B.trim()}`))}}break}if(z.includes("fail")||z.includes("X")){console.log(u.red(" Some checks failed:")),console.log(z);break}process.stdout.write(u.dim("."))}if(v>=C)console.log(u.yellow(`
|
|
2228
|
-
Timed out waiting for checks.`))}if(c)console.log(),console.log(u.dim(`Working directory: ${a}`)),console.log(u.dim("You can delete this directory after the PR is merged."))});var iIt={command:"nemar dataset update",title:"--message",description:"--description",example:'nemar dataset update -m "Add twelve subjects" --description "Adds sub-21 to sub-32, each with a resting-state recording."'},aIt={command:"nemar dataset push --pr",title:"--title",description:"--body",example:'nemar dataset push --pr -t "Add the second session" -b "Adds ses-02 for sub-01 to sub-05."'},cIt={title:"Title (one line saying what changed):",description:"Description (what changed and why):"},lIt={title:"The title",description:"The description"};function fCe(e,t,n){let r=n.terminal&&!n.yes,o={},s=[],i=[];for(let[a,c,l]of[["title",e.title,t.title],["description",e.description,t.description]]){if(c===void 0){i.push(l);continue}let d=gM(a,c);if(d)s.push(yM(`${lIt[a]} (${l})`,d));else o[a]=JD(a,c)}if(s.length===0&&(i.length===0||r))return o;for(let a of s)console.log(u.red(`Error: ${a}`));if(i.length>0&&!r)console.log(u.red(`Error: ${t.command} needs a pull request title and description; missing ${i.join(" and ")}.`)),console.log(" They are written into the pull request for a person to read, so say in plain words what changed."),console.log(n.yes?n.terminal?" --yes does not stand in for them: drop it to be asked for them here, or pass both.":" --yes does not stand in for them, and without a terminal nothing can ask for them: pass both.":" Without a terminal nothing can ask for them: pass both."),console.log(u.dim(` Example: ${t.example}`));Ao(),process.exit(1)}function d3(e){let t=XD(e);if(t===null)return;console.log(u.red(`Error: ${nve(e,t)}`)),console.log(u.dim(" Nothing was changed.")),Ao(),process.exit(1)}function pCe(e){let t=W1e(e);if(t===null)return;console.log(u.red(`Error: ${t}`)),console.log(u.dim(" Nothing was changed. NEMAR's own changes to a mirror take minor and patch.")),Ao(),process.exit(1)}function uIt(e,t){if(!["patch","minor","major"].includes(t))return null;try{let n=JSON.parse(F_(jp(e,"dataset_description.json"),"utf-8"));if(typeof n.Version!=="string"||!n.Version)return null;return hi(n.Version,t)}catch{return null}}async function X1e(e){for(;;){let{value:t}=await Ae.prompt([{type:"input",name:"value",message:cIt[e]}]),n=gM(e,t);if(!n)return JD(e,t);console.log(u.red(` ${yM("That",n)}`))}}async function mCe(e){let t=e.title??await X1e("title"),n=e.description??await X1e("description");return{title:t,description:n}}async function Q1e(e){let t=fCe({title:e.title,description:e.body},aIt,{yes:!1,terminal:process.stdin.isTTY===!0});return mCe(t)}var Z1e=(e)=>e==="main"||e==="master";On.command("update").description("Push local changes to a dataset via PR").argument("[path]","Path to local dataset clone (default: current directory)").option("--bump <type>","Version bump type: patch, minor, or major","patch").option("--branch <name>","Custom branch name").option("-m, --message <title>","Title of the update: the pull request title and the CHANGES entry (required)").option("--description <text>","What changed and why, in plain words: the pull request body (required)").option("--monitor","Watch CI checks and offer to merge").option(
|
|
2228
|
+
Timed out waiting for checks.`))}if(c)console.log(),console.log(u.dim(`Working directory: ${a}`)),console.log(u.dim("You can delete this directory after the PR is merged."))});var iIt={command:"nemar dataset update",title:"--message",description:"--description",example:'nemar dataset update -m "Add twelve subjects" --description "Adds sub-21 to sub-32, each with a resting-state recording."'},aIt={command:"nemar dataset push --pr",title:"--title",description:"--body",example:'nemar dataset push --pr -t "Add the second session" -b "Adds ses-02 for sub-01 to sub-05."'},cIt={title:"Title (one line saying what changed):",description:"Description (what changed and why):"},lIt={title:"The title",description:"The description"};function fCe(e,t,n){let r=n.terminal&&!n.yes,o={},s=[],i=[];for(let[a,c,l]of[["title",e.title,t.title],["description",e.description,t.description]]){if(c===void 0){i.push(l);continue}let d=gM(a,c);if(d)s.push(yM(`${lIt[a]} (${l})`,d));else o[a]=JD(a,c)}if(s.length===0&&(i.length===0||r))return o;for(let a of s)console.log(u.red(`Error: ${a}`));if(i.length>0&&!r)console.log(u.red(`Error: ${t.command} needs a pull request title and description; missing ${i.join(" and ")}.`)),console.log(" They are written into the pull request for a person to read, so say in plain words what changed."),console.log(n.yes?n.terminal?" --yes does not stand in for them: drop it to be asked for them here, or pass both.":" --yes does not stand in for them, and without a terminal nothing can ask for them: pass both.":" Without a terminal nothing can ask for them: pass both."),console.log(u.dim(` Example: ${t.example}`));Ao(),process.exit(1)}function d3(e){let t=XD(e);if(t===null)return;console.log(u.red(`Error: ${nve(e,t)}`)),console.log(u.dim(" Nothing was changed.")),Ao(),process.exit(1)}function pCe(e){let t=W1e(e);if(t===null)return;console.log(u.red(`Error: ${t}`)),console.log(u.dim(" Nothing was changed. NEMAR's own changes to a mirror take minor and patch.")),Ao(),process.exit(1)}function uIt(e,t){if(!["patch","minor","major"].includes(t))return null;try{let n=JSON.parse(F_(jp(e,"dataset_description.json"),"utf-8"));if(typeof n.Version!=="string"||!n.Version)return null;return hi(n.Version,t)}catch{return null}}async function X1e(e){for(;;){let{value:t}=await Ae.prompt([{type:"input",name:"value",message:cIt[e]}]),n=gM(e,t);if(!n)return JD(e,t);console.log(u.red(` ${yM("That",n)}`))}}async function mCe(e){let t=e.title??await X1e("title"),n=e.description??await X1e("description");return{title:t,description:n}}async function Q1e(e){let t=fCe({title:e.title,description:e.body},aIt,{yes:!1,terminal:process.stdin.isTTY===!0});return mCe(t)}var Z1e=(e)=>e==="main"||e==="master";On.command("update").description("Push local changes to a dataset via PR").argument("[path]","Path to local dataset clone (default: current directory)").option("--bump <type>","Version bump type: patch, minor, or major","patch").option("--branch <name>","Custom branch name").option("-m, --message <title>","Title of the update: the pull request title and the CHANGES entry (required)").option("--description <text>","What changed and why, in plain words: the pull request body (required)").option("--monitor","Watch CI checks and offer to merge").option(Ye,nt).addHelpText("after",`
|
|
2229
2229
|
Description:
|
|
2230
2230
|
Push local changes (metadata or data files) to a dataset via a pull
|
|
2231
2231
|
request. Automatically bumps the version, writes the CHANGES entry for
|
|
@@ -2410,7 +2410,7 @@ When to Use:
|
|
|
2410
2410
|
- Your request status is still "requested"
|
|
2411
2411
|
|
|
2412
2412
|
Examples:
|
|
2413
|
-
$ nemar dataset publish resend nm000104`).action(async(e)=>{Ir();let t=D(`Resending notification for ${e}...`).start();try{let n=await Ffe(e);t.succeed(n.message)}catch(n){if(n instanceof L){if(t.fail(n.message),console.log(u.dim(` ${n.message}`)),n.statusCode===404)console.log(u.dim(" Publication request not found for this dataset."))}else{t.fail("Failed to resend notification");let r=n instanceof Error?n.message:String(n);console.log(u.dim(` Error details: ${r}`))}process.exit(1)}});function dIt(e){let t=e.rawBody;if(typeof t==="object"&&t!==null&&"code"in t){let n=t.code;return typeof n==="string"?n:void 0}return}M_.command("withdraw").description("Take back your publication request (it ends as a withdrawn request; no admin step)").argument("<dataset-id>","Dataset ID (e.g., nm000104)").option(
|
|
2413
|
+
$ nemar dataset publish resend nm000104`).action(async(e)=>{Ir();let t=D(`Resending notification for ${e}...`).start();try{let n=await Ffe(e);t.succeed(n.message)}catch(n){if(n instanceof L){if(t.fail(n.message),console.log(u.dim(` ${n.message}`)),n.statusCode===404)console.log(u.dim(" Publication request not found for this dataset."))}else{t.fail("Failed to resend notification");let r=n instanceof Error?n.message:String(n);console.log(u.dim(` Error details: ${r}`))}process.exit(1)}});function dIt(e){let t=e.rawBody;if(typeof t==="object"&&t!==null&&"code"in t){let n=t.code;return typeof n==="string"?n:void 0}return}M_.command("withdraw").description("Take back your publication request (it ends as a withdrawn request; no admin step)").argument("<dataset-id>","Dataset ID (e.g., nm000104)").option(Ye,nt).option(yt,ht).addHelpText("after",`
|
|
2414
2414
|
Description:
|
|
2415
2415
|
Take back your own publication request. It ends as a "withdrawn request":
|
|
2416
2416
|
no administrator has to approve that, and nothing about the dataset changes.
|
|
@@ -2568,7 +2568,7 @@ Examples:
|
|
|
2568
2568
|
$ nemar dataset manifest -d nm000104 # Explicit dataset ID`).action(async(e,t)=>{Ir();let n=t.dataset;if(!n){let o=process.cwd();if(await Mi(o))n=await md(o);if(!n)console.log(u.red("Error: Could not detect dataset ID")),console.log(u.dim("Provide dataset ID: nemar dataset manifest -d <id>")),process.exit(1)}let r=D("Fetching manifest info...").start();try{if(!e){let o=await Rme(n);if(r.stop(),console.log(u.bold(`Manifests: ${n}`)),console.log(),o.versions.length===0)console.log(u.dim(" No manifests available yet.")),console.log(u.dim(" Manifests are generated when a version DOI is published."));else for(let s of o.versions)console.log(` ${u.cyan(s)}`);console.log()}else{let o=await CS(n,e);if(r.stop(),t.json)console.log(JSON.stringify(o,null,2));else{if(console.log(u.bold(`Manifest: ${n} ${o.version}`)),o.doi)console.log(` DOI: ${u.cyan(o.doi)}`);if(o.concept_doi)console.log(` Concept DOI: ${u.dim(o.concept_doi)}`);console.log(` Created: ${o.created}`),console.log();let s=Object.entries(o.files),i=s.filter(([,c])=>!c.key.startsWith("git:")),a=s.filter(([,c])=>c.key.startsWith("git:"));if(i.length>0){console.log(u.bold(` Annexed files (${i.length}):`));for(let[c,l]of i){let d=Ut(l.size);console.log(` ${c} ${u.dim(`(${d})`)}`)}}if(a.length>0){console.log(),console.log(u.bold(` Metadata files (${a.length}):`));for(let[c,l]of a){let d=Ut(l.size);console.log(` ${c} ${u.dim(`(${d})`)}`)}}console.log()}}}catch(o){if(o instanceof L)r.fail(o.message);else{r.fail("Failed to fetch manifest");let s=o instanceof Error?o.message:String(o);console.log(u.dim(` ${s}`))}process.exit(1)}});function fIt(e){if(!e.anonymity_status)return;let t=(s)=>{if(!s)return[];try{let i=JSON.parse(s);return Array.isArray(i)?i:[]}catch{return[]}},n=t(e.anonymity_findings),r=t(e.anonymity_unchecked).filter((s)=>typeof s==="string"),o=e.anonymity_checked_at?u.dim(` (checked ${new Date(e.anonymity_checked_at).toLocaleDateString()})`):"";if(e.anonymity_status==="findings"){console.log(` Blind check: ${u.red(`${n.length} finding(s)`)}${o}`);for(let s of n){if(typeof s!=="object"||s===null)continue;let i=s,a=typeof i.file==="string"?` ${u.dim(i.file)}`:"";if(console.log(` - ${String(i.check??"unknown")}${a}`),typeof i.detail==="string")console.log(u.dim(` ${i.detail}`))}}else if(e.anonymity_status==="unverifiable")console.log(` Blind check: ${u.yellow("could not be completed")}${o}`);else console.log(` Blind check: ${u.green("no findings")}${o}`);if(r.length>0)console.log(u.dim(` Not checked: ${r.join(", ")}`))}He();dn();Rb();async function pIt(e={}){if(e.report){console.log(await BI());return}let t=await Db();console.log(u.bold(`
|
|
2569
2569
|
NEMAR environment check
|
|
2570
2570
|
`));let n=process.versions.bun?`Bun ${process.versions.bun}`:`Node ${process.version}`;console.log(u.dim(` Runtime: ${n} on ${process.platform}/${process.arch}
|
|
2571
|
-
`));let r=0;for(let s of t){let i=s.available?u.green("\u2713"):u.red("\u2717"),a=s.available?s.version??"ok":u.red(s.timedOut?"timed out":"missing");if(console.log(` ${i} ${s.name.padEnd(16)} ${String(a).padEnd(12)} ${u.dim(s.purpose)}`),s.available)r++;else console.log(` ${u.yellow("Install")}: ${s.installInstruction}`)}let o=t.filter((s)=>!s.available&&s.required);if(console.log(""),o.length===0)console.log(u.green(`All ${t.length} required tools are installed.`));else console.log(`${r}/${t.length} tools installed. Install the ${o.length} missing one(s) above, then re-run ${u.cyan("nemar doctor")}.`),console.log(u.dim("Bun is the CLI runtime; the tools above are needed for upload, validation, and download."));console.log("")}var gCe=new de("doctor").description("Check that required tools (git, git-annex, gh, aws, deno) are installed").option("--report","Print a shareable environment report (no HTTP data) for bug reports").action(pIt);He();ro();Za();ec();
|
|
2571
|
+
`));let r=0;for(let s of t){let i=s.available?u.green("\u2713"):u.red("\u2717"),a=s.available?s.version??"ok":u.red(s.timedOut?"timed out":"missing");if(console.log(` ${i} ${s.name.padEnd(16)} ${String(a).padEnd(12)} ${u.dim(s.purpose)}`),s.available)r++;else console.log(` ${u.yellow("Install")}: ${s.installInstruction}`)}let o=t.filter((s)=>!s.available&&s.required);if(console.log(""),o.length===0)console.log(u.green(`All ${t.length} required tools are installed.`));else console.log(`${r}/${t.length} tools installed. Install the ${o.length} missing one(s) above, then re-run ${u.cyan("nemar doctor")}.`),console.log(u.dim("Bun is the CLI runtime; the tools above are needed for upload, validation, and download."));console.log("")}var gCe=new de("doctor").description("Check that required tools (git, git-annex, gh, aws, deno) are installed").option("--report","Print a shareable environment report (no HTTP data) for bug reports").action(pIt);He();ro();Za();ec();Je();gr();ii();rc();ji();cc();Pr();import{mkdirSync as mIt,rmSync as hIt,writeFileSync as j_}from"fs";import{tmpdir as gIt}from"os";import{join as Kd}from"path";function yIt(e){let t=Kd(e,"sub-01"),n=Kd(t,"eeg");return{root:e,datasetDescription:Kd(e,"dataset_description.json"),participants:Kd(e,"participants.tsv"),readme:Kd(e,"README"),subjectDir:t,eegDir:n,edfFile:Kd(n,"sub-01_task-rest_eeg.edf"),sidecarJson:Kd(n,"sub-01_task-rest_eeg.json")}}function yCe(e){let t=e||Kd(gIt(),`nemar-sandbox-${Date.now()}`),n=yIt(t);mIt(n.eegDir,{recursive:!0});let r={Name:"NEMAR Sandbox Training Dataset",BIDSVersion:"1.9.0",DatasetType:"raw",License:"CC0",Authors:["NEMAR CLI Training"],HowToAcknowledge:"This is a sandbox dataset for testing the NEMAR upload workflow.",DatasetDOI:"n/a"};j_(n.datasetDescription,JSON.stringify(r,null,2));let o=`participant_id age sex
|
|
2572
2572
|
sub-01 25 M
|
|
2573
2573
|
`;j_(n.participants,o);let s=`# NEMAR Sandbox Training Dataset
|
|
2574
2574
|
|
|
@@ -2604,7 +2604,7 @@ Examples:
|
|
|
2604
2604
|
$ nemar sandbox --verbose # Run with full subprocess output (debug stuck runs)
|
|
2605
2605
|
$ nemar sandbox status # Check if training is completed
|
|
2606
2606
|
$ nemar sandbox reset # Reset for re-training
|
|
2607
|
-
`).action(_It);async function wIt(e,t,n){let r=await cl(e,t,n);if(!r.success)return{ok:!1,step:"save",error:r.error??"unknown error"};let o=await sr(e);if(!o.success)return{ok:!1,step:"push",error:o.error??"unknown error"};return{ok:!0,...o.warning?{warning:o.warning}:{}}}async function _It(e={}){if(e.verbose)rfe(!0);if(console.log(),console.log(u.bold("NEMAR Sandbox Training")),console.log(u.dim("Verify your setup and learn the upload workflow")),e.verbose)console.log(u.dim("Verbose mode: subprocess invocations will be printed"));if(console.log(),!ze()){console.log(u.red("Not authenticated")),console.log(u.dim("Run 'nemar auth login' first"));return}let t=await U1();if(t.status==="unknown")console.log(u.yellow("Could not confirm your training status with the server.")),console.log(u.dim(` ${t.reason}`)),console.log(u.dim(" Continuing; run 'nemar sandbox status --refresh' to re-check.")),console.log();let n=Vt();if(t.status==="completed"){console.log(u.green("Sandbox training already completed!")),console.log(u.dim(`Dataset ID: ${n.sandboxDatasetId}`)),console.log(),console.log("You can upload real datasets with:"),console.log(u.cyan(" nemar dataset upload ./your-dataset")),console.log(),console.log(u.dim("To re-run training, use: nemar sandbox reset"));return}console.log(u.bold("Step 1/6: Checking prerequisites..."));let r=D("Checking prerequisites...").start(),o=await m$();if(!o.allPassed){r.fail("Prerequisites check failed"),console.log(),console.log(u.red("Missing requirements:"));for(let H of o.errors)console.log(u.yellow(` - ${H}`));if(o.errors.some((H)=>H.includes("GitHub")))console.log(u.dim(" Run 'gh auth login' to authenticate with GitHub"));return}r.succeed("All prerequisites met");let s=D("Verifying GitHub CLI authentication...").start(),i=await MS(n.githubUsername);if(!i.authenticated){s.fail("GitHub CLI not authenticated"),console.log(u.red(` ${i.error}`)),console.log(),console.log("GitHub CLI is required for sandbox training. Install and authenticate:"),console.log(u.cyan(" brew install gh # or visit https://cli.github.com/")),console.log(u.cyan(" gh auth login"));return}if(n.githubUsername&&!i.matches)s.warn("GitHub CLI user mismatch"),console.log(u.yellow(` ${i.error}`)),console.log(),console.log("Your gh CLI is authenticated as a different GitHub account than your NEMAR account."),console.log("This may cause issues with repository access. To fix:"),console.log(u.cyan(` gh auth login # Login as ${n.githubUsername}`)),console.log(),console.log(u.yellow("WARNING: If upload fails with permission errors, this mismatch is the likely cause.")),console.log();else s.succeed(`GitHub CLI authenticated as ${i.username}`);console.log(),console.log(u.bold("Step 2/6: Generating test dataset..."));let a=D("Creating minimal BIDS structure...").start(),c;try{let H=yCe();c=H.root;let re=bCe(H);a.succeed(`Test dataset created (${Ut(re)})`),console.log(u.dim(` Location: ${c}`))}catch(H){a.fail("Failed to generate test dataset"),console.log(u.red(` ${H instanceof Error?H.message:"Unknown error"}`));return}console.log(),console.log(u.bold("Step 3/6: Registering sandbox dataset..."));let l=D("Creating dataset on NEMAR...").start(),d,f,p,m,h;try{let H=await AS({name:"Sandbox Training Dataset",description:"Placeholder dataset for sandbox training",files:[{path:"sub-01/eeg/sub-01_task-rest_eeg.edf",size:512000,type:"data"},{path:"dataset_description.json",size:200,type:"metadata"},{path:"participants.tsv",size:50,type:"metadata"},{path:"README",size:500,type:"metadata"},{path:"sub-01/eeg/sub-01_task-rest_eeg.json",size:300,type:"metadata"}],sandbox:!0,attestation:WDe});d=H.dataset.dataset_id,f=H.dataset.ssh_url,p=H.dataset.github_url,m=H.s3_config,h=H.dataset.s3_prefix,l.succeed(`Sandbox dataset created: ${u.cyan(d)}`),console.log(u.dim(` GitHub: ${p}`)),await new Promise((re)=>setTimeout(re,1e4))}catch(H){if(l.fail("Failed to create sandbox dataset"),H instanceof L)console.log(u.red(` ${H.message}`));else console.log(u.red(` ${H instanceof Error?H.message:"Unknown error"}`));xi(c);return}let g=D("Accepting GitHub repository invitation...").start(),y=p?.match(/github\.com\/([a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+)/),b=y?y[1].replace(/\.git$/,""):null;if(!b){g.fail("Invalid GitHub repository URL from backend"),console.log(u.red(` Received: ${p||"(empty)"}`)),console.log(u.red(" Expected format: https://github.com/owner/repo")),console.log(),console.log("This may indicate a backend issue. Please contact support."),xi(c);return}let _=await jS(b);if(_.accepted)if(_.alreadyCollaborator)g.succeed("Already a collaborator on this repository");else g.succeed("GitHub invitation accepted");else g.warn("Could not auto-accept invitation"),console.log(u.yellow(` ${_.error}`)),console.log(),console.log("You may need to accept the invitation manually:"),console.log(u.cyan(` https://github.com/${b}/invitations`)),console.log();console.log(),console.log(u.bold("Step 4/6: Initializing repository..."));let x=D("Setting up git-annex...").start(),k=n.username&&n.email?{name:n.username,email:n.email}:void 0;try{let H=await lg(c,{author:k});if(!H.success)throw Error(H.error||"Failed to initialize dataset");await pd(c),await nc(c,f),x.succeed("Repository initialized")}catch(H){x.fail("Failed to initialize repository"),console.log(u.red(` ${H instanceof Error?H.message:"Unknown error"}`)),xi(c);return}console.log(),console.log(u.bold("Step 5/6: Uploading to S3..."));let v=D("Requesting upload credentials...").start(),C;try{C=await Gr(d),v.succeed("Upload credentials received")}catch(H){v.fail("Could not get upload credentials"),console.log(u.red(` ${H instanceof Error?H.message:"Unknown error"}`)),xi(c);return}let T=lr(C.credentials),z=D("Configuring S3 remote...").start(),A=await Fo(c,{name:"nemar-s3",bucket:C.s3.bucket,prefix:`${h}/objects`,region:C.s3.region,publicUrl:m.public_url},T);if(!A.success){z.fail("Failed to configure S3 remote"),console.log(u.red(` ${A.error}`)),console.log(u.dim(" Re-run with --verbose to see git-annex output.")),xi(c);return}z.succeed("S3 remote configured");let F=D("Tracking data files with git-annex...").start(),M=await oc(c);if(!M.success){F.fail("Failed to track data files"),console.log(u.red(` ${M.error}`)),console.log(u.dim(" Re-run with --verbose to see git-annex output.")),xi(c);return}F.succeed("Data files tracked by git-annex");let U=D("Uploading data files to S3...").start(),B=await wd(c,"nemar-s3",4,T);if(await Xr(c),!B.success){U.fail("S3 upload failed"),console.log(u.red(` ${B.error}`)),console.log(u.dim(" Re-run with --verbose to see git-annex output.")),xi(c);return}U.succeed(`Uploaded ${B.filesCopied} data file(s) to S3`),console.log(),console.log(u.bold("Step 6/6: Pushing to GitHub..."));let P=D("Saving and pushing...").start();try{let H=await wIt(c,"Initial sandbox training upload",k);if(!H.ok){P.fail(H.step==="save"?"Failed to save the dataset":"Failed to push to GitHub"),console.log(u.red(` ${H.error}`)),xi(c);return}if(H.warning)P.warn("Pushed to GitHub (with warning)"),console.log(u.yellow(` ${H.warning}`));else P.succeed("Pushed to GitHub")}catch(H){P.fail("Failed to save and push"),console.log(u.red(` ${H instanceof Error?H.message:"Unknown error"}`)),xi(c);return}let O=D("Finalizing...").start();try{await OS(d),await Jme(d),Rn("sandboxCompleted",!0),Rn("sandboxDatasetId",d),O.succeed("Sandbox training complete!")}catch(H){O.fail("Failed to finalize"),console.log(u.red(` ${H instanceof Error?H.message:"Unknown error"}`)),xi(c);return}xi(c),console.log(),console.log(u.green.bold("Congratulations! Sandbox training completed successfully.")),console.log(),console.log("Your setup is verified and you're ready to upload real datasets:"),console.log(u.cyan(" nemar dataset upload ./your-dataset")),console.log(),console.log(u.dim(`Sandbox dataset: ${d}`))}eC.command("status").description("Check sandbox training completion status").option("--refresh","Fetch latest status from server").action(async(e)=>{if(!ze()){console.log(u.red("Not authenticated")),console.log(u.dim("Run 'nemar auth login' first"));return}if(e.refresh){let t=D("Checking status...").start();try{let n=await TS();if(Rn("sandboxCompleted",n.sandbox_completed),n.sandbox_dataset_id)Rn("sandboxDatasetId",n.sandbox_dataset_id);if(t.stop(),n.sandbox_completed){if(console.log(u.green("Sandbox training: Completed")),console.log(u.dim(` Dataset ID: ${n.sandbox_dataset_id}`)),n.sandbox_completed_at)console.log(u.dim(` Completed: ${n.sandbox_completed_at}`))}else console.log(u.yellow("Sandbox training: Not completed")),console.log(),console.log("Run sandbox training with:"),console.log(u.cyan(" nemar sandbox"))}catch(n){if(t.fail("Failed to check status"),n instanceof L)console.log(u.red(` ${n.message}`))}}else{let t=Vt();if(t.sandboxCompleted)console.log(u.green("Sandbox training: Completed")),console.log(u.dim(` Dataset ID: ${t.sandboxDatasetId}`));else console.log(u.yellow("Sandbox training: Not completed")),console.log(),console.log("Run sandbox training with:"),console.log(u.cyan(" nemar sandbox"))}});eC.command("reset").description("Reset sandbox training status for re-training").option(Je,nt).option(yt,ht).action(async(e)=>{if(!ze()){console.log(u.red("Not authenticated")),console.log(u.dim("Run 'nemar auth login' first"));return}if(!Vt().sandboxCompleted){console.log(u.yellow("Sandbox training not yet completed")),console.log(u.dim("Nothing to reset"));return}let n=await De("Reset sandbox training status? You will need to complete training again.",e);if(n!=="confirmed"){console.log(u.dim(n==="declined"?"Skipped":"Cancelled"));return}let r=D("Resetting sandbox status...").start();try{await Yme(),Ib("sandboxCompleted"),Ib("sandboxDatasetId"),r.succeed("Sandbox status reset"),console.log(),console.log("Run sandbox training again with:"),console.log(u.cyan(" nemar sandbox"))}catch(o){if(r.fail("Failed to reset"),o instanceof L)console.log(u.red(` ${o.message}`));else console.log(u.red(` ${o instanceof Error?o.message:"Unknown error"}`))}});lo();Ke();class tC extends Error{command;option;code="commander.optionMissingArgument";constructor(e,t){super(`error: option '${t.flags}' argument missing`);this.command=e;this.option=t;this.name="MissingShadowedValueError"}}class nC extends Error{command;option;code="commander.unknownOption";constructor(e,t){super(`error: option '${t.flags}' must come after '${e.name()}'`);this.command=e;this.option=t;this.name="MisplacedShadowedOptionError"}}function wCe(e){return e==="-"||!!e&&!e.startsWith("-")}function _Ce(e,t){return e.commands.find((n)=>n.name()===t||n.aliases().includes(t))}function xCe(e,t){let n=new Map;for(let o of t)for(let s of o.options)if(s.long&&!n.has(s.long))n.set(s.long,s);let r=new Map;for(let o of e.options){if(!(o.required||o.optional)||!o.long)continue;let s=n.get(o.long);if(s&&!(s.required||s.optional))r.set(o.long,o)}return r}function vCe(e,t){let n=new Set(xCe(e,t).keys());for(let r of e.commands)for(let o of vCe(r,[...t,e]))n.add(o);return n}function kCe(e,t){let n=t.indexOf("--"),r=n<0?t.length:n,o=vCe(e,[]),s=[],i=[],a=e,c=-1;for(let p=0;p<r;p++){let m=t[p];if(m.startsWith("-")){if(a!==e&&o.has(m)){s.push({flag:m,index:p});let g=t[p+1];if(wCe(g)&&!_Ce(a,g))p++}continue}let h=_Ce(a,m);if(!h)break;i.push(a),a=h,c=p}if(c<0)return t;let l=xCe(a,i);if(l.size===0)return t;for(let{flag:p,index:m}of s){let h=l.get(p);if(h&&m<c)throw new nC(a,h)}let d=t.slice(0,r).some((p)=>p==="--help"||p==="-h"),f=t.slice(0,c+1);for(let p=c+1;p<r;p++){let m=t[p],h=l.get(m);if(!h){f.push(m);continue}let g=t[p+1];if(wCe(g))f.push(`${m}=${g}`),p++;else if(!d){if(h.required)throw new tC(a,h);f.push(m)}}return f.push(...t.slice(r)),f}ck();var SCe={Default:0,NoFileComp:4},xIt={"--task":"task","--modality":"modality","--license":"license","--bids-version":"bids-version","--hed-version":"hed-version","--electrode-system":"electrode-system"};function vIt(e){let t=xIt[e];if(!t)return;let n=LDe();if(!n)return;if(t==="task")return n.task?.values.map((o)=>o.value);return n[t]?.map((o)=>o.value)}function kIt(e){return _a.find((t)=>t.flag===e)?.enumValues}function h3(e){if(e.argChoices&&e.argChoices.length>0)return[...e.argChoices];let t=e.long??e.short;if(!t)return[];let n=vIt(t);if(n&&n.length>0)return n;let r=kIt(t);if(r)return[...r];return[]}function g3(e){return e.required||e.optional}function EIt(e,t){return e.commands.find((n)=>n.name()===t||n.aliases().includes(t))}function y3(e,t){return e.options.find((n)=>n.short===t||n.long===t)}function SIt(e){return Boolean(e._hidden)}function $It(e){let t=[];for(let n of e.commands){if(SIt(n))continue;t.push(n.name(),...n.aliases())}return t}function ECe(e){let t=[];for(let n of e.options){if(n.long)t.push(n.long);if(n.short)t.push(n.short)}return t}function vy(e,t){if(!t)return e;return e.filter((n)=>n.startsWith(t))}var DIt=/^(--[A-Za-z0-9][A-Za-z0-9-]*)=(.*)$/;function $Ce(e,t){let n=t.length>0?t[t.length-1]:"",r=t.length>0?t.slice(0,-1):[],o=e,s=0;while(s<r.length){let a=EIt(o,r[s]);if(!a)break;o=a,s++}let i=n.match(DIt);if(i){let[,a,c]=i,l=y3(o,a);if(!l||!g3(l))return[];return vy(h3(l),c).map((d)=>`${a}=${d}`)}if(r.length>s){let a=r[r.length-1],c=y3(o,a);if(c&&g3(c))return vy(h3(c),n);if(a==="="&&r.length>=2){let l=y3(o,r[r.length-2]);if(l&&g3(l))return vy(h3(l),n)}}if(n.startsWith("-"))return vy(ECe(o),n);if(s===r.length)return vy($It(o),n);return vy(ECe(o),n)}var RIt=/[\u0000-\u001f\u007f]/;async function DCe(e,t){let n=t[0]==="--"?t.slice(1):t,r=[];try{r=$Ce(e,n)}catch(o){if(process.env.VERBOSE)process.stderr.write(`[completion] candidate lookup failed: ${o instanceof Error?o.message:o}
|
|
2607
|
+
`).action(_It);async function wIt(e,t,n){let r=await cl(e,t,n);if(!r.success)return{ok:!1,step:"save",error:r.error??"unknown error"};let o=await sr(e);if(!o.success)return{ok:!1,step:"push",error:o.error??"unknown error"};return{ok:!0,...o.warning?{warning:o.warning}:{}}}async function _It(e={}){if(e.verbose)rfe(!0);if(console.log(),console.log(u.bold("NEMAR Sandbox Training")),console.log(u.dim("Verify your setup and learn the upload workflow")),e.verbose)console.log(u.dim("Verbose mode: subprocess invocations will be printed"));if(console.log(),!ze()){console.log(u.red("Not authenticated")),console.log(u.dim("Run 'nemar auth login' first"));return}let t=await U1();if(t.status==="unknown")console.log(u.yellow("Could not confirm your training status with the server.")),console.log(u.dim(` ${t.reason}`)),console.log(u.dim(" Continuing; run 'nemar sandbox status --refresh' to re-check.")),console.log();let n=Vt();if(t.status==="completed"){console.log(u.green("Sandbox training already completed!")),console.log(u.dim(`Dataset ID: ${n.sandboxDatasetId}`)),console.log(),console.log("You can upload real datasets with:"),console.log(u.cyan(" nemar dataset upload ./your-dataset")),console.log(),console.log(u.dim("To re-run training, use: nemar sandbox reset"));return}console.log(u.bold("Step 1/6: Checking prerequisites..."));let r=D("Checking prerequisites...").start(),o=await m$();if(!o.allPassed){r.fail("Prerequisites check failed"),console.log(),console.log(u.red("Missing requirements:"));for(let H of o.errors)console.log(u.yellow(` - ${H}`));if(o.errors.some((H)=>H.includes("GitHub")))console.log(u.dim(" Run 'gh auth login' to authenticate with GitHub"));return}r.succeed("All prerequisites met");let s=D("Verifying GitHub CLI authentication...").start(),i=await MS(n.githubUsername);if(!i.authenticated){s.fail("GitHub CLI not authenticated"),console.log(u.red(` ${i.error}`)),console.log(),console.log("GitHub CLI is required for sandbox training. Install and authenticate:"),console.log(u.cyan(" brew install gh # or visit https://cli.github.com/")),console.log(u.cyan(" gh auth login"));return}if(n.githubUsername&&!i.matches)s.warn("GitHub CLI user mismatch"),console.log(u.yellow(` ${i.error}`)),console.log(),console.log("Your gh CLI is authenticated as a different GitHub account than your NEMAR account."),console.log("This may cause issues with repository access. To fix:"),console.log(u.cyan(` gh auth login # Login as ${n.githubUsername}`)),console.log(),console.log(u.yellow("WARNING: If upload fails with permission errors, this mismatch is the likely cause.")),console.log();else s.succeed(`GitHub CLI authenticated as ${i.username}`);console.log(),console.log(u.bold("Step 2/6: Generating test dataset..."));let a=D("Creating minimal BIDS structure...").start(),c;try{let H=yCe();c=H.root;let re=bCe(H);a.succeed(`Test dataset created (${Ut(re)})`),console.log(u.dim(` Location: ${c}`))}catch(H){a.fail("Failed to generate test dataset"),console.log(u.red(` ${H instanceof Error?H.message:"Unknown error"}`));return}console.log(),console.log(u.bold("Step 3/6: Registering sandbox dataset..."));let l=D("Creating dataset on NEMAR...").start(),d,f,p,m,h;try{let H=await AS({name:"Sandbox Training Dataset",description:"Placeholder dataset for sandbox training",files:[{path:"sub-01/eeg/sub-01_task-rest_eeg.edf",size:512000,type:"data"},{path:"dataset_description.json",size:200,type:"metadata"},{path:"participants.tsv",size:50,type:"metadata"},{path:"README",size:500,type:"metadata"},{path:"sub-01/eeg/sub-01_task-rest_eeg.json",size:300,type:"metadata"}],sandbox:!0,attestation:WDe});d=H.dataset.dataset_id,f=H.dataset.ssh_url,p=H.dataset.github_url,m=H.s3_config,h=H.dataset.s3_prefix,l.succeed(`Sandbox dataset created: ${u.cyan(d)}`),console.log(u.dim(` GitHub: ${p}`)),await new Promise((re)=>setTimeout(re,1e4))}catch(H){if(l.fail("Failed to create sandbox dataset"),H instanceof L)console.log(u.red(` ${H.message}`));else console.log(u.red(` ${H instanceof Error?H.message:"Unknown error"}`));xi(c);return}let g=D("Accepting GitHub repository invitation...").start(),y=p?.match(/github\.com\/([a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+)/),b=y?y[1].replace(/\.git$/,""):null;if(!b){g.fail("Invalid GitHub repository URL from backend"),console.log(u.red(` Received: ${p||"(empty)"}`)),console.log(u.red(" Expected format: https://github.com/owner/repo")),console.log(),console.log("This may indicate a backend issue. Please contact support."),xi(c);return}let _=await jS(b);if(_.accepted)if(_.alreadyCollaborator)g.succeed("Already a collaborator on this repository");else g.succeed("GitHub invitation accepted");else g.warn("Could not auto-accept invitation"),console.log(u.yellow(` ${_.error}`)),console.log(),console.log("You may need to accept the invitation manually:"),console.log(u.cyan(` https://github.com/${b}/invitations`)),console.log();console.log(),console.log(u.bold("Step 4/6: Initializing repository..."));let x=D("Setting up git-annex...").start(),k=n.username&&n.email?{name:n.username,email:n.email}:void 0;try{let H=await lg(c,{author:k});if(!H.success)throw Error(H.error||"Failed to initialize dataset");await pd(c),await nc(c,f),x.succeed("Repository initialized")}catch(H){x.fail("Failed to initialize repository"),console.log(u.red(` ${H instanceof Error?H.message:"Unknown error"}`)),xi(c);return}console.log(),console.log(u.bold("Step 5/6: Uploading to S3..."));let v=D("Requesting upload credentials...").start(),C;try{C=await Gr(d),v.succeed("Upload credentials received")}catch(H){v.fail("Could not get upload credentials"),console.log(u.red(` ${H instanceof Error?H.message:"Unknown error"}`)),xi(c);return}let T=lr(C.credentials),z=D("Configuring S3 remote...").start(),A=await Fo(c,{name:"nemar-s3",bucket:C.s3.bucket,prefix:`${h}/objects`,region:C.s3.region,publicUrl:m.public_url},T);if(!A.success){z.fail("Failed to configure S3 remote"),console.log(u.red(` ${A.error}`)),console.log(u.dim(" Re-run with --verbose to see git-annex output.")),xi(c);return}z.succeed("S3 remote configured");let F=D("Tracking data files with git-annex...").start(),M=await oc(c);if(!M.success){F.fail("Failed to track data files"),console.log(u.red(` ${M.error}`)),console.log(u.dim(" Re-run with --verbose to see git-annex output.")),xi(c);return}F.succeed("Data files tracked by git-annex");let U=D("Uploading data files to S3...").start(),B=await wd(c,"nemar-s3",4,T);if(await Xr(c),!B.success){U.fail("S3 upload failed"),console.log(u.red(` ${B.error}`)),console.log(u.dim(" Re-run with --verbose to see git-annex output.")),xi(c);return}U.succeed(`Uploaded ${B.filesCopied} data file(s) to S3`),console.log(),console.log(u.bold("Step 6/6: Pushing to GitHub..."));let P=D("Saving and pushing...").start();try{let H=await wIt(c,"Initial sandbox training upload",k);if(!H.ok){P.fail(H.step==="save"?"Failed to save the dataset":"Failed to push to GitHub"),console.log(u.red(` ${H.error}`)),xi(c);return}if(H.warning)P.warn("Pushed to GitHub (with warning)"),console.log(u.yellow(` ${H.warning}`));else P.succeed("Pushed to GitHub")}catch(H){P.fail("Failed to save and push"),console.log(u.red(` ${H instanceof Error?H.message:"Unknown error"}`)),xi(c);return}let O=D("Finalizing...").start();try{await OS(d),await Jme(d),Rn("sandboxCompleted",!0),Rn("sandboxDatasetId",d),O.succeed("Sandbox training complete!")}catch(H){O.fail("Failed to finalize"),console.log(u.red(` ${H instanceof Error?H.message:"Unknown error"}`)),xi(c);return}xi(c),console.log(),console.log(u.green.bold("Congratulations! Sandbox training completed successfully.")),console.log(),console.log("Your setup is verified and you're ready to upload real datasets:"),console.log(u.cyan(" nemar dataset upload ./your-dataset")),console.log(),console.log(u.dim(`Sandbox dataset: ${d}`))}eC.command("status").description("Check sandbox training completion status").option("--refresh","Fetch latest status from server").action(async(e)=>{if(!ze()){console.log(u.red("Not authenticated")),console.log(u.dim("Run 'nemar auth login' first"));return}if(e.refresh){let t=D("Checking status...").start();try{let n=await TS();if(Rn("sandboxCompleted",n.sandbox_completed),n.sandbox_dataset_id)Rn("sandboxDatasetId",n.sandbox_dataset_id);if(t.stop(),n.sandbox_completed){if(console.log(u.green("Sandbox training: Completed")),console.log(u.dim(` Dataset ID: ${n.sandbox_dataset_id}`)),n.sandbox_completed_at)console.log(u.dim(` Completed: ${n.sandbox_completed_at}`))}else console.log(u.yellow("Sandbox training: Not completed")),console.log(),console.log("Run sandbox training with:"),console.log(u.cyan(" nemar sandbox"))}catch(n){if(t.fail("Failed to check status"),n instanceof L)console.log(u.red(` ${n.message}`))}}else{let t=Vt();if(t.sandboxCompleted)console.log(u.green("Sandbox training: Completed")),console.log(u.dim(` Dataset ID: ${t.sandboxDatasetId}`));else console.log(u.yellow("Sandbox training: Not completed")),console.log(),console.log("Run sandbox training with:"),console.log(u.cyan(" nemar sandbox"))}});eC.command("reset").description("Reset sandbox training status for re-training").option(Ye,nt).option(yt,ht).action(async(e)=>{if(!ze()){console.log(u.red("Not authenticated")),console.log(u.dim("Run 'nemar auth login' first"));return}if(!Vt().sandboxCompleted){console.log(u.yellow("Sandbox training not yet completed")),console.log(u.dim("Nothing to reset"));return}let n=await De("Reset sandbox training status? You will need to complete training again.",e);if(n!=="confirmed"){console.log(u.dim(n==="declined"?"Skipped":"Cancelled"));return}let r=D("Resetting sandbox status...").start();try{await Yme(),Ib("sandboxCompleted"),Ib("sandboxDatasetId"),r.succeed("Sandbox status reset"),console.log(),console.log("Run sandbox training again with:"),console.log(u.cyan(" nemar sandbox"))}catch(o){if(r.fail("Failed to reset"),o instanceof L)console.log(u.red(` ${o.message}`));else console.log(u.red(` ${o instanceof Error?o.message:"Unknown error"}`))}});lo();Je();class tC extends Error{command;option;code="commander.optionMissingArgument";constructor(e,t){super(`error: option '${t.flags}' argument missing`);this.command=e;this.option=t;this.name="MissingShadowedValueError"}}class nC extends Error{command;option;code="commander.unknownOption";constructor(e,t){super(`error: option '${t.flags}' must come after '${e.name()}'`);this.command=e;this.option=t;this.name="MisplacedShadowedOptionError"}}function wCe(e){return e==="-"||!!e&&!e.startsWith("-")}function _Ce(e,t){return e.commands.find((n)=>n.name()===t||n.aliases().includes(t))}function xCe(e,t){let n=new Map;for(let o of t)for(let s of o.options)if(s.long&&!n.has(s.long))n.set(s.long,s);let r=new Map;for(let o of e.options){if(!(o.required||o.optional)||!o.long)continue;let s=n.get(o.long);if(s&&!(s.required||s.optional))r.set(o.long,o)}return r}function vCe(e,t){let n=new Set(xCe(e,t).keys());for(let r of e.commands)for(let o of vCe(r,[...t,e]))n.add(o);return n}function kCe(e,t){let n=t.indexOf("--"),r=n<0?t.length:n,o=vCe(e,[]),s=[],i=[],a=e,c=-1;for(let p=0;p<r;p++){let m=t[p];if(m.startsWith("-")){if(a!==e&&o.has(m)){s.push({flag:m,index:p});let g=t[p+1];if(wCe(g)&&!_Ce(a,g))p++}continue}let h=_Ce(a,m);if(!h)break;i.push(a),a=h,c=p}if(c<0)return t;let l=xCe(a,i);if(l.size===0)return t;for(let{flag:p,index:m}of s){let h=l.get(p);if(h&&m<c)throw new nC(a,h)}let d=t.slice(0,r).some((p)=>p==="--help"||p==="-h"),f=t.slice(0,c+1);for(let p=c+1;p<r;p++){let m=t[p],h=l.get(m);if(!h){f.push(m);continue}let g=t[p+1];if(wCe(g))f.push(`${m}=${g}`),p++;else if(!d){if(h.required)throw new tC(a,h);f.push(m)}}return f.push(...t.slice(r)),f}ck();var SCe={Default:0,NoFileComp:4},xIt={"--task":"task","--modality":"modality","--license":"license","--bids-version":"bids-version","--hed-version":"hed-version","--electrode-system":"electrode-system"};function vIt(e){let t=xIt[e];if(!t)return;let n=LDe();if(!n)return;if(t==="task")return n.task?.values.map((o)=>o.value);return n[t]?.map((o)=>o.value)}function kIt(e){return _a.find((t)=>t.flag===e)?.enumValues}function h3(e){if(e.argChoices&&e.argChoices.length>0)return[...e.argChoices];let t=e.long??e.short;if(!t)return[];let n=vIt(t);if(n&&n.length>0)return n;let r=kIt(t);if(r)return[...r];return[]}function g3(e){return e.required||e.optional}function EIt(e,t){return e.commands.find((n)=>n.name()===t||n.aliases().includes(t))}function y3(e,t){return e.options.find((n)=>n.short===t||n.long===t)}function SIt(e){return Boolean(e._hidden)}function $It(e){let t=[];for(let n of e.commands){if(SIt(n))continue;t.push(n.name(),...n.aliases())}return t}function ECe(e){let t=[];for(let n of e.options){if(n.long)t.push(n.long);if(n.short)t.push(n.short)}return t}function vy(e,t){if(!t)return e;return e.filter((n)=>n.startsWith(t))}var DIt=/^(--[A-Za-z0-9][A-Za-z0-9-]*)=(.*)$/;function $Ce(e,t){let n=t.length>0?t[t.length-1]:"",r=t.length>0?t.slice(0,-1):[],o=e,s=0;while(s<r.length){let a=EIt(o,r[s]);if(!a)break;o=a,s++}let i=n.match(DIt);if(i){let[,a,c]=i,l=y3(o,a);if(!l||!g3(l))return[];return vy(h3(l),c).map((d)=>`${a}=${d}`)}if(r.length>s){let a=r[r.length-1],c=y3(o,a);if(c&&g3(c))return vy(h3(c),n);if(a==="="&&r.length>=2){let l=y3(o,r[r.length-2]);if(l&&g3(l))return vy(h3(l),n)}}if(n.startsWith("-"))return vy(ECe(o),n);if(s===r.length)return vy($It(o),n);return vy(ECe(o),n)}var RIt=/[\u0000-\u001f\u007f]/;async function DCe(e,t){let n=t[0]==="--"?t.slice(1):t,r=[];try{r=$Ce(e,n)}catch(o){if(process.env.VERBOSE)process.stderr.write(`[completion] candidate lookup failed: ${o instanceof Error?o.message:o}
|
|
2608
2608
|
`);r=[]}for(let o of r){if(RIt.test(o))continue;process.stdout.write(`${o}
|
|
2609
2609
|
`)}process.stdout.write(`:${SCe.NoFileComp}
|
|
2610
2610
|
`)}dn();GI();He();gr();var RCe=100;async function CCe(){try{let{notices:e}=await Bme();if(!e||e.length===0)return;let t=Vt(),n=new Set(t.dismissedNoticeIds||[]),r=e.filter((o)=>!n.has(o.id));if(r.length===0)return;for(let o of r)CIt(o);if(ze()){let o=["tip","announcement"],s=r.filter((i)=>o.includes(i.level)).map((i)=>i.id);if(s.length>0)AIt(s)}}catch(e){if(process.env.VERBOSE)process.stderr.write(`[notices] ${e instanceof Error?e.message:e}
|
|
@@ -2636,4 +2636,4 @@ Documentation:
|
|
|
2636
2636
|
https://docs.nemar.org
|
|
2637
2637
|
|
|
2638
2638
|
Support:
|
|
2639
|
-
https://github.com/nemarOrg/nemar-cli/issues`);Yn.addCommand(eo);Yn.addCommand(On);Yn.addCommand(eC);Yn.addCommand(Oe);Yn.addCommand(gCe);Yn.addCommand(Ip);Yn.command("login").description("Sign in with your browser (shortcut for 'auth login')").option("-k, --key <key>","Paste an existing API key instead (alternative: NEMAR_API_KEY)").option("--no-open","Print the sign-in link instead of trying to open a browser").option(
|
|
2639
|
+
https://github.com/nemarOrg/nemar-cli/issues`);Yn.addCommand(eo);Yn.addCommand(On);Yn.addCommand(eC);Yn.addCommand(Oe);Yn.addCommand(gCe);Yn.addCommand(Ip);Yn.command("login").description("Sign in with your browser (shortcut for 'auth login')").option("-k, --key <key>","Paste an existing API key instead (alternative: NEMAR_API_KEY)").option("--no-open","Print the sign-in link instead of trying to open a browser").option(Ye,nt).option(yt,ht).action(vL);Yn.command("logout").description("Remove the active account (shortcut for 'auth logout')").option(Ye,nt).option(yt,ht).option("--all","Remove all stored accounts").option("--revoke-key","Revoke this machine's key even if it may be shared").option("--no-revoke-key","Never revoke the key server-side, only clear it locally").action(EL);var LCe=(e)=>e.option("--username <name>","Username to set, or to change to").option("--github <handle>","GitHub username").option("--city <city>","City").option("--country <country>","Country").option("--why <text>","What you intend to upload (20-500 characters)").option("--no-upload-access","Skip the upload-access request").option("--no-open","Print the sign-in link instead of trying to open a browser").option(Ye,nt).option(yt,ht);LCe(Yn.command("signup").description("Create or continue your account (shortcut for 'auth signup')")).action(O1);LCe(Yn.command("register").description("Create or continue your account (alias for signup)")).action(O1);Yn.addCommand(p3().description("Download a dataset from NEMAR or OpenNeuro (shortcut for 'dataset download')"));Yn.addCommand(f3().description("Upload a BIDS dataset to NEMAR (shortcut for 'dataset upload')"));Yn.command("whoami").description("Show current user (shortcut for 'auth status')").option("--refresh","Refresh user info from server").action(T1);Yn.command("switch [username]").description("Switch between accounts (shortcut for 'auth switch')").action(kL);Sq(Yn);function qCe(e){e.exitOverride(()=>Ao());for(let t of e.commands)qCe(t)}qCe(Yn);Yn.hook("preAction",async()=>{if(qM(Ac))return;if(_3)return;await CCe()});if(Nf&&!_3)console.warn(u.yellow.bold("[DEV BUILD]")+u.yellow(" Connected to development backend. Not for production use."));async function HIt(){let e=jCe(Ac);if(e!==null){await DCe(Yn,Ac.slice(e+1));return}if(sl())await vfe();let t=_3?null:await MCe();if(t)Yn.hook("postAction",()=>w3(t)),process.on("exit",()=>w3(t));let n;try{n=kCe(Yn,Ac)}catch(r){if(r instanceof tC||r instanceof nC)r.command.error(r.message,{code:r.code});throw Error(`argv pre-pass failed: ${G(r)}`,{cause:r})}await Yn.parseAsync(n,{from:"user"})}HIt().catch((e)=>{if(e instanceof vu)wS(e),process.exit(1);console.error(G(e)),process.exit(1)});
|