nemar-cli 0.9.10-PR1165.ffb749a → 0.9.10-PR1167.6909e1c
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +22 -22
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -95,15 +95,15 @@ ${t}`,axe,cxe,uxe=(e,t,r)=>{let n=r===""?"":`with ${r.trim()}() `,i=oxe.bind(nul
|
|
|
95
95
|
|| ${o} === "boolean" || ${i} === null`).assign(a,pe._`[${i}]`)}}}function NCe({gen:e,parentData:t,parentDataProperty:r},n){e.if(pe._`${t} !== undefined`,()=>e.assign(pe._`${t}[${r}]`,n))}function Iv(e,t,r,n=nc.Correct){let i=n===nc.Correct?pe.operators.EQ:pe.operators.NEQ,s;switch(e){case"null":return pe._`${t} ${i} null`;case"array":s=pe._`Array.isArray(${t})`;break;case"object":s=pe._`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":s=o(pe._`!(${t} % 1) && !isNaN(${t})`);break;case"number":s=o();break;default:return pe._`typeof ${t} ${i} ${e}`}return n===nc.Correct?s:(0,pe.not)(s);function o(a=pe.nil){return(0,pe.and)(pe._`typeof ${t} == "number"`,a,r?pe._`isFinite(${t})`:pe.nil)}}uj.checkDataType=Iv;function Tv(e,t,r,n){if(e.length===1)return Iv(e[0],t,r,n);let i,s=(0,oj.toHash)(e);if(s.array&&s.object){let o=pe._`typeof ${t} != "object"`;i=s.null?o:pe._`!${t} || ${o}`,delete s.null,delete s.array,delete s.object}else i=pe.nil;if(s.number)delete s.integer;for(let o in s)i=(0,pe.and)(i,Iv(o,t,r,n));return i}uj.checkDataTypes=Tv;var qCe={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?pe._`{type: ${e}}`:pe._`{type: ${t}}`};function Nv(e){let t=jCe(e);(0,ACe.reportError)(t,qCe)}uj.reportTypeError=Nv;function jCe(e){let{gen:t,data:r,schema:n}=e,i=(0,oj.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:i,schemaValue:i,parentSchema:n,params:{},it:e}}});var mj=h(function(fj){Object.defineProperty(fj,"__esModule",{value:!0});fj.assignDefaults=void 0;var ic=me(),HCe=Pe();function GCe(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let i in r)dj(e,i,r[i].default);else if(t==="array"&&Array.isArray(n))n.forEach((i,s)=>dj(e,s,i.default))}fj.assignDefaults=GCe;function dj(e,t,r){let{gen:n,compositeRule:i,data:s,opts:o}=e;if(r===void 0)return;let a=ic._`${s}${(0,ic.getProperty)(t)}`;if(i){(0,HCe.checkStrictMode)(e,`default is ignored for: ${a}`);return}let c=ic._`${a} === undefined`;if(o.useDefaults==="empty")c=ic._`${c} || ${a} === null || ${a} === ""`;n.if(c,ic._`${a} = ${(0,ic.stringify)(r)}`)}});var Vr=h(function(yj){Object.defineProperty(yj,"__esModule",{value:!0});yj.validateUnion=yj.validateArray=yj.usePattern=yj.callValidateCode=yj.schemaProperties=yj.allSchemaProperties=yj.noPropertyInData=yj.propertyInData=yj.isOwnProperty=yj.hasPropFunc=yj.reportMissingProp=yj.checkMissingProp=yj.checkReportMissingProp=void 0;var Je=me(),qv=Pe(),Es=wi(),WCe=Pe();function KCe(e,t){let{gen:r,data:n,it:i}=e;r.if(Mv(r,n,t,i.opts.ownProperties),()=>{e.setParams({missingProperty:Je._`${t}`},!0),e.error()})}yj.checkReportMissingProp=KCe;function YCe({gen:e,data:t,it:{opts:r}},n,i){return(0,Je.or)(...n.map((s)=>(0,Je.and)(Mv(e,t,s,r.ownProperties),Je._`${i} = ${s}`)))}yj.checkMissingProp=YCe;function JCe(e,t){e.setParams({missingProperty:t},!0),e.error()}yj.reportMissingProp=JCe;function hj(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:Je._`Object.prototype.hasOwnProperty`})}yj.hasPropFunc=hj;function jv(e,t,r){return Je._`${hj(e)}.call(${t}, ${r})`}yj.isOwnProperty=jv;function XCe(e,t,r,n){let i=Je._`${t}${(0,Je.getProperty)(r)} !== undefined`;return n?Je._`${i} && ${jv(e,t,r)}`:i}yj.propertyInData=XCe;function Mv(e,t,r,n){let i=Je._`${t}${(0,Je.getProperty)(r)} === undefined`;return n?(0,Je.or)(i,(0,Je.not)(jv(e,t,r))):i}yj.noPropertyInData=Mv;function gj(e){return e?Object.keys(e).filter((t)=>t!=="__proto__"):[]}yj.allSchemaProperties=gj;function QCe(e,t){return gj(t).filter((r)=>!(0,qv.alwaysValidSchema)(e,t[r]))}yj.schemaProperties=QCe;function ZCe({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:i,errorPath:s},it:o},a,c,l){let d=l?Je._`${e}, ${t}, ${n}${i}`:t,f=[[Es.default.instancePath,(0,Je.strConcat)(Es.default.instancePath,s)],[Es.default.parentData,o.parentData],[Es.default.parentDataProperty,o.parentDataProperty],[Es.default.rootData,Es.default.rootData]];if(o.opts.dynamicRef)f.push([Es.default.dynamicAnchors,Es.default.dynamicAnchors]);let m=Je._`${d}, ${r.object(...f)}`;return c!==Je.nil?Je._`${a}.call(${c}, ${m})`:Je._`${a}(${m})`}yj.callValidateCode=ZCe;var e6e=Je._`new RegExp`;function t6e({gen:e,it:{opts:t}},r){let n=t.unicodeRegExp?"u":"",{regExp:i}=t.code,s=i(r,n);return e.scopeValue("pattern",{key:s.toString(),ref:s,code:Je._`${i.code==="new RegExp"?e6e:(0,WCe.useFunc)(e,i)}(${r}, ${n})`})}yj.usePattern=t6e;function r6e(e){let{gen:t,data:r,keyword:n,it:i}=e,s=t.name("valid");if(i.allErrors){let a=t.let("valid",!0);return o(()=>t.assign(a,!1)),a}return t.var(s,!0),o(()=>t.break()),s;function o(a){let c=t.const("len",Je._`${r}.length`);t.forRange("i",0,c,(l)=>{e.subschema({keyword:n,dataProp:l,dataPropType:qv.Type.Num},s),t.if((0,Je.not)(s),a)})}}yj.validateArray=r6e;function n6e(e){let{gen:t,schema:r,keyword:n,it:i}=e;if(!Array.isArray(r))throw Error("ajv implementation error");if(r.some((c)=>(0,qv.alwaysValidSchema)(i,c))&&!i.opts.unevaluated)return;let o=t.let("valid",!1),a=t.name("_valid");t.block(()=>r.forEach((c,l)=>{let d=e.subschema({keyword:n,schemaProp:l,compositeRule:!0},a);if(t.assign(o,Je._`${o} || ${a}`),!e.mergeValidEvaluated(d,a))t.if((0,Je.not)(o))})),e.result(o,()=>e.reset(),()=>e.error(!0))}yj.validateUnion=n6e});var wj=h(function(_j){Object.defineProperty(_j,"__esModule",{value:!0});_j.validateKeywordUsage=_j.validSchemaType=_j.funcKeywordCode=_j.macroKeywordCode=void 0;var Yt=me(),xo=wi(),g6e=Vr(),y6e=Cl();function x6e(e,t){let{gen:r,keyword:n,schema:i,parentSchema:s,it:o}=e,a=t.macro.call(o.self,i,s,o),c=vj(r,n,a);if(o.opts.validateSchema!==!1)o.self.validateSchema(a,!0);let l=r.name("valid");e.subschema({schema:a,schemaPath:Yt.nil,errSchemaPath:`${o.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),e.pass(l,()=>e.error(!0))}_j.macroKeywordCode=x6e;function b6e(e,t){var r;let{gen:n,keyword:i,schema:s,parentSchema:o,$data:a,it:c}=e;_6e(c,t);let l=!a&&t.compile?t.compile.call(c.self,s,o,c):t.validate,d=vj(n,i,l),f=n.let("valid");e.block$data(f,m),e.ok((r=t.valid)!==null&&r!==void 0?r:f);function m(){if(t.errors===!1){if(y(),t.modifying)bj(e);x(()=>e.error())}else{let v=t.async?p():g();if(t.modifying)bj(e);x(()=>v6e(e,v))}}function p(){let v=n.let("ruleErrs",null);return n.try(()=>y(Yt._`await `),(_)=>n.assign(f,!1).if(Yt._`${_} instanceof ${c.ValidationError}`,()=>n.assign(v,Yt._`${_}.errors`),()=>n.throw(_))),v}function g(){let v=Yt._`${d}.errors`;return n.assign(v,null),y(Yt.nil),v}function y(v=t.async?Yt._`await `:Yt.nil){let _=c.opts.passContext?xo.default.this:xo.default.self,E=!(("compile"in t)&&!a||t.schema===!1);n.assign(f,Yt._`${v}${(0,g6e.callValidateCode)(e,d,_,E)}`,t.modifying)}function x(v){var _;n.if((0,Yt.not)((_=t.valid)!==null&&_!==void 0?_:f),v)}}_j.funcKeywordCode=b6e;function bj(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,Yt._`${n.parentData}[${n.parentDataProperty}]`))}function v6e(e,t){let{gen:r}=e;r.if(Yt._`Array.isArray(${t})`,()=>{r.assign(xo.default.vErrors,Yt._`${xo.default.vErrors} === null ? ${t} : ${xo.default.vErrors}.concat(${t})`).assign(xo.default.errors,Yt._`${xo.default.vErrors}.length`),(0,y6e.extendErrors)(e)},()=>e.error())}function _6e({schemaEnv:e},t){if(t.async&&!e.$async)throw Error("async keyword in sync schema")}function vj(e,t,r){if(r===void 0)throw Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Yt.stringify)(r)})}function D6e(e,t,r=!1){return!t.length||t.some((n)=>n==="array"?Array.isArray(e):n==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==n||r&&typeof e>"u")}_j.validSchemaType=D6e;function w6e({schema:e,opts:t,self:r,errSchemaPath:n},i,s){if(Array.isArray(i.keyword)?!i.keyword.includes(s):i.keyword!==s)throw Error("ajv implementation error");let o=i.dependencies;if(o===null||o===void 0?void 0:o.some((a)=>!Object.prototype.hasOwnProperty.call(e,a)))throw Error(`parent schema must have dependencies of ${s}: ${o.join(",")}`);if(i.validateSchema){if(!i.validateSchema(e[s])){let c=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(i.validateSchema.errors);if(t.validateSchema==="log")r.logger.error(c);else throw Error(c)}}}_j.validateKeywordUsage=w6e});var Cj=h(function(Sj){Object.defineProperty(Sj,"__esModule",{value:!0});Sj.extendSubschemaMode=Sj.extendSubschemaData=Sj.getSubschema=void 0;var Kn=me(),Ej=Pe();function C6e(e,{keyword:t,schemaProp:r,schema:n,schemaPath:i,errSchemaPath:s,topSchemaRef:o}){if(t!==void 0&&n!==void 0)throw Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){let a=e.schema[t];return r===void 0?{schema:a,schemaPath:Kn._`${e.schemaPath}${(0,Kn.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:a[r],schemaPath:Kn._`${e.schemaPath}${(0,Kn.getProperty)(t)}${(0,Kn.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,Ej.escapeFragment)(r)}`}}if(n!==void 0){if(i===void 0||s===void 0||o===void 0)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:i,topSchemaRef:o,errSchemaPath:s}}throw Error('either "keyword" or "schema" must be passed')}Sj.getSubschema=C6e;function F6e(e,t,{dataProp:r,dataPropType:n,data:i,dataTypes:s,propertyName:o}){if(i!==void 0&&r!==void 0)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=t;if(r!==void 0){let{errorPath:l,dataPathArr:d,opts:f}=t,m=a.let("data",Kn._`${t.data}${(0,Kn.getProperty)(r)}`,!0);c(m),e.errorPath=Kn.str`${l}${(0,Ej.getErrorPath)(r,n,f.jsPropertySyntax)}`,e.parentDataProperty=Kn._`${r}`,e.dataPathArr=[...d,e.parentDataProperty]}if(i!==void 0){let l=i instanceof Kn.Name?i:a.let("data",i,!0);if(c(l),o!==void 0)e.propertyName=o}if(s)e.dataTypes=s;function c(l){e.data=l,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,l]}}Sj.extendSubschemaData=F6e;function R6e(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:n,createErrors:i,allErrors:s}){if(n!==void 0)e.compositeRule=n;if(i!==void 0)e.createErrors=i;if(s!==void 0)e.allErrors=s;e.jtdDiscriminator=t,e.jtdMetadata=r}Sj.extendSubschemaMode=R6e});var Rl=h(function(Aj){Object.defineProperty(Aj,"__esModule",{value:!0});Aj.getSchemaRefs=Aj.resolveUrl=Aj.normalizeId=Aj._getFullPath=Aj.getFullPath=Aj.inlineRef=void 0;var k6e=Pe(),P6e=sl(),I6e=Nb(),T6e=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function N6e(e,t=!0){if(typeof e=="boolean")return!0;if(t===!0)return!Bv(e);if(!t)return!1;return Fj(e)<=t}Aj.inlineRef=N6e;var q6e=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Bv(e){for(let t in e){if(q6e.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(Bv))return!0;if(typeof r=="object"&&Bv(r))return!0}return!1}function Fj(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,T6e.has(r))continue;if(typeof e[r]=="object")(0,k6e.eachItem)(e[r],(n)=>t+=Fj(n));if(t===1/0)return 1/0}return t}function Rj(e,t="",r){if(r!==!1)t=sc(t);let n=e.parse(t);return Oj(e,n)}Aj.getFullPath=Rj;function Oj(e,t){return e.serialize(t).split("#")[0]+"#"}Aj._getFullPath=Oj;var j6e=/#\/?$/;function sc(e){return e?e.replace(j6e,""):""}Aj.normalizeId=sc;function M6e(e,t,r){return r=sc(r),e.resolve(t,r)}Aj.resolveUrl=M6e;var B6e=/^[a-z_][-a-z0-9._]*$/i;function L6e(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,i=sc(e[r]||t),s={"":i},o=Rj(n,i,!1),a={},c=new Set;return I6e(e,{allKeys:!0},(f,m,p,g)=>{if(g===void 0)return;let y=o+m,x=s[g];if(typeof f[r]=="string")x=v.call(this,f[r]);_.call(this,f.$anchor),_.call(this,f.$dynamicAnchor),s[m]=x;function v(E){let S=this.opts.uriResolver.resolve;if(E=sc(x?S(x,E):E),c.has(E))throw d(E);c.add(E);let D=this.refs[E];if(typeof D=="string")D=this.refs[D];if(typeof D=="object")l(f,D.schema,E);else if(E!==sc(y))if(E[0]==="#")l(f,a[E],E),a[E]=f;else this.refs[E]=y;return E}function _(E){if(typeof E=="string"){if(!B6e.test(E))throw Error(`invalid anchor "${E}"`);v.call(this,`#${E}`)}}}),a;function l(f,m,p){if(m!==void 0&&!P6e(f,m))throw d(p)}function d(f){return Error(`reference "${f}" resolves to more than one schema`)}}Aj.getSchemaRefs=L6e});var kl=h(function(Wj){Object.defineProperty(Wj,"__esModule",{value:!0});Wj.getData=Wj.KeywordCxt=Wj.validateFunctionCode=void 0;var qj=Zq(),Pj=Fl(),Uv=Pv(),$0=Fl(),W6e=mj(),Al=wj(),Lv=Cj(),J=me(),re=wi(),K6e=Rl(),Ei=Pe(),Ol=Cl();function Y6e(e){if(Bj(e)){if(Lj(e),Mj(e)){Q6e(e);return}}jj(e,()=>(0,qj.topBoolOrEmptySchema)(e))}Wj.validateFunctionCode=Y6e;function jj({gen:e,validateName:t,schema:r,schemaEnv:n,opts:i},s){if(i.code.es5)e.func(t,J._`${re.default.data}, ${re.default.valCxt}`,n.$async,()=>{e.code(J._`"use strict"; ${Ij(r,i)}`),X6e(e,i),e.code(s)});else e.func(t,J._`${re.default.data}, ${J6e(i)}`,n.$async,()=>e.code(Ij(r,i)).code(s))}function J6e(e){return J._`{${re.default.instancePath}="", ${re.default.parentData}, ${re.default.parentDataProperty}, ${re.default.rootData}=${re.default.data}${e.dynamicRef?J._`, ${re.default.dynamicAnchors}={}`:J.nil}}={}`}function X6e(e,t){e.if(re.default.valCxt,()=>{if(e.var(re.default.instancePath,J._`${re.default.valCxt}.${re.default.instancePath}`),e.var(re.default.parentData,J._`${re.default.valCxt}.${re.default.parentData}`),e.var(re.default.parentDataProperty,J._`${re.default.valCxt}.${re.default.parentDataProperty}`),e.var(re.default.rootData,J._`${re.default.valCxt}.${re.default.rootData}`),t.dynamicRef)e.var(re.default.dynamicAnchors,J._`${re.default.valCxt}.${re.default.dynamicAnchors}`)},()=>{if(e.var(re.default.instancePath,J._`""`),e.var(re.default.parentData,J._`undefined`),e.var(re.default.parentDataProperty,J._`undefined`),e.var(re.default.rootData,re.default.data),t.dynamicRef)e.var(re.default.dynamicAnchors,J._`{}`)})}function Q6e(e){let{schema:t,opts:r,gen:n}=e;jj(e,()=>{if(r.$comment&&t.$comment)Vj(e);if(nFe(e),n.let(re.default.vErrors,null),n.let(re.default.errors,0),r.unevaluated)Z6e(e);Uj(e),oFe(e)});return}function Z6e(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",J._`${r}.evaluated`),t.if(J._`${e.evaluated}.dynamicProps`,()=>t.assign(J._`${e.evaluated}.props`,J._`undefined`)),t.if(J._`${e.evaluated}.dynamicItems`,()=>t.assign(J._`${e.evaluated}.items`,J._`undefined`))}function Ij(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?J._`/*# sourceURL=${r} */`:J.nil}function eFe(e,t){if(Bj(e)){if(Lj(e),Mj(e)){tFe(e,t);return}}(0,qj.boolOrEmptySchema)(e,t)}function Mj({schema:e,self:t}){if(typeof e=="boolean")return!e;for(let r in e)if(t.RULES.all[r])return!0;return!1}function Bj(e){return typeof e.schema!="boolean"}function tFe(e,t){let{schema:r,gen:n,opts:i}=e;if(i.$comment&&r.$comment)Vj(e);iFe(e),sFe(e);let s=n.const("_errs",re.default.errors);Uj(e,s),n.var(t,J._`${s} === ${re.default.errors}`)}function Lj(e){(0,Ei.checkUnknownRules)(e),rFe(e)}function Uj(e,t){if(e.opts.jtd)return Tj(e,[],!1,t);let r=(0,Pj.getSchemaTypes)(e.schema),n=(0,Pj.coerceAndCheckDataType)(e,r);Tj(e,r,!n,t)}function rFe(e){let{schema:t,errSchemaPath:r,opts:n,self:i}=e;if(t.$ref&&n.ignoreKeywordsWithRef&&(0,Ei.schemaHasRulesButRef)(t,i.RULES))i.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function nFe(e){let{schema:t,opts:r}=e;if(t.default!==void 0&&r.useDefaults&&r.strictSchema)(0,Ei.checkStrictMode)(e,"default is ignored in the schema root")}function iFe(e){let t=e.schema[e.opts.schemaId];if(t)e.baseId=(0,K6e.resolveUrl)(e.opts.uriResolver,e.baseId,t)}function sFe(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error("async schema in sync schema")}function Vj({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:i}){let s=r.$comment;if(i.$comment===!0)e.code(J._`${re.default.self}.logger.log(${s})`);else if(typeof i.$comment=="function"){let o=J.str`${n}/$comment`,a=e.scopeValue("root",{ref:t.root});e.code(J._`${re.default.self}.opts.$comment(${s}, ${o}, ${a}.schema)`)}}function oFe(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:i,opts:s}=e;if(r.$async)t.if(J._`${re.default.errors} === 0`,()=>t.return(re.default.data),()=>t.throw(J._`new ${i}(${re.default.vErrors})`));else{if(t.assign(J._`${n}.errors`,re.default.vErrors),s.unevaluated)aFe(e);t.return(J._`${re.default.errors} === 0`)}}function aFe({gen:e,evaluated:t,props:r,items:n}){if(r instanceof J.Name)e.assign(J._`${t}.props`,r);if(n instanceof J.Name)e.assign(J._`${t}.items`,n)}function Tj(e,t,r,n){let{gen:i,schema:s,data:o,allErrors:a,opts:c,self:l}=e,{RULES:d}=l;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,Ei.schemaHasRulesButRef)(s,d))){i.block(()=>Hj(e,"$ref",d.all.$ref.definition));return}if(!c.jtd)cFe(e,t);i.block(()=>{for(let m of d.rules)f(m);f(d.post)});function f(m){if(!(0,Uv.shouldUseGroup)(s,m))return;if(m.type){if(i.if((0,$0.checkDataType)(m.type,o,c.strictNumbers)),Nj(e,m),t.length===1&&t[0]===m.type&&r)i.else(),(0,$0.reportTypeError)(e);i.endIf()}else Nj(e,m);if(!a)i.if(J._`${re.default.errors} === ${n||0}`)}}function Nj(e,t){let{gen:r,schema:n,opts:{useDefaults:i}}=e;if(i)(0,W6e.assignDefaults)(e,t.type);r.block(()=>{for(let s of t.rules)if((0,Uv.shouldUseRule)(n,s))Hj(e,s.keyword,s.definition,t.type)})}function cFe(e,t){if(e.schemaEnv.meta||!e.opts.strictTypes)return;if(uFe(e,t),!e.opts.allowUnionTypes)lFe(e,t);dFe(e,e.dataTypes)}function uFe(e,t){if(!t.length)return;if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach((r)=>{if(!zj(e.dataTypes,r))Vv(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),pFe(e,t)}function lFe(e,t){if(t.length>1&&!(t.length===2&&t.includes("null")))Vv(e,"use allowUnionTypes to allow union type keyword")}function dFe(e,t){let r=e.self.RULES.all;for(let n in r){let i=r[n];if(typeof i=="object"&&(0,Uv.shouldUseRule)(e.schema,i)){let{type:s}=i.definition;if(s.length&&!s.some((o)=>fFe(t,o)))Vv(e,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function fFe(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function zj(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function pFe(e,t){let r=[];for(let n of e.dataTypes)if(zj(t,n))r.push(n);else if(t.includes("integer")&&n==="number")r.push("integer");e.dataTypes=r}function Vv(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,Ei.checkStrictMode)(e,t,e.opts.strictTypes)}class zv{constructor(e,t,r){if((0,Al.validateKeywordUsage)(e,t,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Ei.schemaRefOrVal)(e,this.schema,r,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const("vSchema",Gj(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Al.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw Error(`${r} value must be ${JSON.stringify(t.schemaType)}`);if("code"in t?t.trackErrors:t.errors!==!1)this.errsCount=e.gen.const("_errs",re.default.errors)}result(e,t,r){this.failResult((0,J.not)(e),t,r)}failResult(e,t,r){if(this.gen.if(e),r)r();else this.error();if(t){if(this.gen.else(),t(),this.allErrors)this.gen.endIf()}else if(this.allErrors)this.gen.endIf();else this.gen.else()}pass(e,t){this.failResult((0,J.not)(e),void 0,t)}fail(e){if(e===void 0){if(this.error(),!this.allErrors)this.gen.if(!1);return}if(this.gen.if(e),this.error(),this.allErrors)this.gen.endIf();else this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail(J._`${t} !== undefined && (${(0,J.or)(this.invalid$data(),e)})`)}error(e,t,r){if(t){this.setParams(t),this._error(e,r),this.setParams({});return}this._error(e,r)}_error(e,t){(e?Ol.reportExtraError:Ol.reportError)(this,this.def.error,t)}$dataError(){(0,Ol.reportError)(this,this.def.$dataError||Ol.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error('add "trackErrors" to keyword definition');(0,Ol.resetErrorsCount)(this.gen,this.errsCount)}ok(e){if(!this.allErrors)this.gen.if(e)}setParams(e,t){if(t)Object.assign(this.params,e);else this.params=e}block$data(e,t,r=J.nil){this.gen.block(()=>{this.check$data(e,r),t()})}check$data(e=J.nil,t=J.nil){if(!this.$data)return;let{gen:r,schemaCode:n,schemaType:i,def:s}=this;if(r.if((0,J.or)(J._`${n} === undefined`,t)),e!==J.nil)r.assign(e,!0);if(i.length||s.validateSchema){if(r.elseIf(this.invalid$data()),this.$dataError(),e!==J.nil)r.assign(e,!1)}r.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:r,def:n,it:i}=this;return(0,J.or)(s(),o());function s(){if(r.length){if(!(t instanceof J.Name))throw Error("ajv implementation error");let a=Array.isArray(r)?r:[r];return J._`${(0,$0.checkDataTypes)(a,t,i.opts.strictNumbers,$0.DataType.Wrong)}`}return J.nil}function o(){if(n.validateSchema){let a=e.scopeValue("validate$data",{ref:n.validateSchema});return J._`!${a}(${t})`}return J.nil}}subschema(e,t){let r=(0,Lv.getSubschema)(this.it,e);(0,Lv.extendSubschemaData)(r,this.it,e),(0,Lv.extendSubschemaMode)(r,e);let n={...this.it,...r,items:void 0,props:void 0};return eFe(n,t),n}mergeEvaluated(e,t){let{it:r,gen:n}=this;if(!r.opts.unevaluated)return;if(r.props!==!0&&e.props!==void 0)r.props=Ei.mergeEvaluated.props(n,e.props,r.props,t);if(r.items!==!0&&e.items!==void 0)r.items=Ei.mergeEvaluated.items(n,e.items,r.items,t)}mergeValidEvaluated(e,t){let{it:r,gen:n}=this;if(r.opts.unevaluated&&(r.props!==!0||r.items!==!0))return n.if(t,()=>this.mergeEvaluated(e,J.Name)),!0}}Wj.KeywordCxt=zv;function Hj(e,t,r,n){let i=new zv(e,r,t);if("code"in r)r.code(i,n);else if(i.$data&&r.validate)(0,Al.funcKeywordCode)(i,r);else if("macro"in r)(0,Al.macroKeywordCode)(i,r);else if(r.compile||r.validate)(0,Al.funcKeywordCode)(i,r)}var mFe=/^\/(?:[^~]|~0|~1)*$/,hFe=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Gj(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let i,s;if(e==="")return re.default.rootData;if(e[0]==="/"){if(!mFe.test(e))throw Error(`Invalid JSON-pointer: ${e}`);i=e,s=re.default.rootData}else{let l=hFe.exec(e);if(!l)throw Error(`Invalid JSON-pointer: ${e}`);let d=+l[1];if(i=l[2],i==="#"){if(d>=t)throw Error(c("property/index",d));return n[t-d]}if(d>t)throw Error(c("data",d));if(s=r[t-d],!i)return s}let o=s,a=i.split("/");for(let l of a)if(l)s=J._`${s}${(0,J.getProperty)((0,Ei.unescapeJsonPointer)(l))}`,o=J._`${o} && ${s}`;return o;function c(l,d){return`Cannot access ${l} ${d} levels up, current level is ${t}`}}Wj.getData=Gj});var C0=h(function(Jj){Object.defineProperty(Jj,"__esModule",{value:!0});class Yj extends Error{constructor(e){super("validation failed");this.errors=e,this.ajv=this.validation=!0}}Jj.default=Yj});var Pl=h(function(Qj){Object.defineProperty(Qj,"__esModule",{value:!0});var Hv=Rl();class Xj extends Error{constructor(e,t,r,n){super(n||`can't resolve reference ${r} from id ${t}`);this.missingRef=(0,Hv.resolveUrl)(e,t,r),this.missingSchema=(0,Hv.normalizeId)((0,Hv.getFullPath)(e,this.missingRef))}}Qj.default=Xj});var R0=h(function(tM){Object.defineProperty(tM,"__esModule",{value:!0});tM.resolveSchema=tM.getCompilingSchema=tM.resolveRef=tM.compileSchema=tM.SchemaEnv=void 0;var fn=me(),vFe=C0(),bo=wi(),pn=Rl(),Zj=Pe(),_Fe=kl();class Il{constructor(e){var t;this.refs={},this.dynamicAnchors={};let r;if(typeof e.schema=="object")r=e.schema;this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(t=e.baseId)!==null&&t!==void 0?t:(0,pn.normalizeId)(r===null||r===void 0?void 0:r[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=r===null||r===void 0?void 0:r.$async,this.refs={}}}tM.SchemaEnv=Il;function Wv(e){let t=eM.call(this,e);if(t)return t;let r=(0,pn.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:i}=this.opts.code,{ownProperties:s}=this.opts,o=new fn.CodeGen(this.scope,{es5:n,lines:i,ownProperties:s}),a;if(e.$async)a=o.scopeValue("Error",{ref:vFe.default,code:fn._`require("ajv/dist/runtime/validation_error").default`});let c=o.scopeName("validate");e.validateName=c;let l={gen:o,allErrors:this.opts.allErrors,data:bo.default.data,parentData:bo.default.parentData,parentDataProperty:bo.default.parentDataProperty,dataNames:[bo.default.data],dataPathArr:[fn.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:o.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,fn.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:fn.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:fn._`""`,opts:this.opts,self:this},d;try{this._compilations.add(e),(0,_Fe.validateFunctionCode)(l),o.optimize(this.opts.code.optimize);let f=o.toString();if(d=`${o.scopeRefs(bo.default.scope)}return ${f}`,this.opts.code.process)d=this.opts.code.process(d,e);let p=Function(`${bo.default.self}`,`${bo.default.scope}`,d)(this,this.scope.get());if(this.scope.value(c,{ref:p}),p.errors=null,p.schema=e.schema,p.schemaEnv=e,e.$async)p.$async=!0;if(this.opts.code.source===!0)p.source={validateName:c,validateCode:f,scopeValues:o._values};if(this.opts.unevaluated){let{props:g,items:y}=l;if(p.evaluated={props:g instanceof fn.Name?void 0:g,items:y instanceof fn.Name?void 0:y,dynamicProps:g instanceof fn.Name,dynamicItems:y instanceof fn.Name},p.source)p.source.evaluated=(0,fn.stringify)(p.evaluated)}return e.validate=p,e}catch(f){if(delete e.validate,delete e.validateName,d)this.logger.error("Error compiling schema, function code:",d);throw f}finally{this._compilations.delete(e)}}tM.compileSchema=Wv;function DFe(e,t,r){var n;r=(0,pn.resolveUrl)(this.opts.uriResolver,t,r);let i=e.refs[r];if(i)return i;let s=SFe.call(this,e,r);if(s===void 0){let o=(n=e.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;if(o)s=new Il({schema:o,schemaId:a,root:e,baseId:t})}if(s===void 0)return;return e.refs[r]=wFe.call(this,s)}tM.resolveRef=DFe;function wFe(e){if((0,pn.inlineRef)(e.schema,this.opts.inlineRefs))return e.schema;return e.validate?e:Wv.call(this,e)}function eM(e){for(let t of this._compilations)if(EFe(t,e))return t}tM.getCompilingSchema=eM;function EFe(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function SFe(e,t){let r;while(typeof(r=this.refs[t])=="string")t=r;return r||this.schemas[t]||F0.call(this,e,t)}function F0(e,t){let r=this.opts.uriResolver.parse(t),n=(0,pn._getFullPath)(this.opts.uriResolver,r),i=(0,pn.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===i)return Gv.call(this,r,e);let s=(0,pn.normalizeId)(n),o=this.refs[s]||this.schemas[s];if(typeof o=="string"){let a=F0.call(this,e,o);if(typeof(a===null||a===void 0?void 0:a.schema)!=="object")return;return Gv.call(this,r,a)}if(typeof(o===null||o===void 0?void 0:o.schema)!=="object")return;if(!o.validate)Wv.call(this,o);if(s===(0,pn.normalizeId)(t)){let{schema:a}=o,{schemaId:c}=this.opts,l=a[c];if(l)i=(0,pn.resolveUrl)(this.opts.uriResolver,i,l);return new Il({schema:a,schemaId:c,root:e,baseId:i})}return Gv.call(this,r,o)}tM.resolveSchema=F0;var $Fe=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Gv(e,{baseId:t,schema:r,root:n}){var i;if(((i=e.fragment)===null||i===void 0?void 0:i[0])!=="/")return;for(let a of e.fragment.slice(1).split("/")){if(typeof r==="boolean")return;let c=r[(0,Zj.unescapeFragment)(a)];if(c===void 0)return;r=c;let l=typeof r==="object"&&r[this.opts.schemaId];if(!$Fe.has(a)&&l)t=(0,pn.resolveUrl)(this.opts.uriResolver,t,l)}let s;if(typeof r!="boolean"&&r.$ref&&!(0,Zj.schemaHasRulesButRef)(r,this.RULES)){let a=(0,pn.resolveUrl)(this.opts.uriResolver,t,r.$ref);s=F0.call(this,n,a)}let{schemaId:o}=this.opts;if(s=s||new Il({schema:r,schemaId:o,root:n,baseId:t}),s.schema!==s.root.schema)return s;return}});var nM=h(function(sWe,AFe){AFe.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var oM=h(function(sM){Object.defineProperty(sM,"__esModule",{value:!0});var iM=Jb();iM.code='require("ajv/dist/runtime/uri").default';sM.default=iM});var mM=h(function(Si){Object.defineProperty(Si,"__esModule",{value:!0});Si.CodeGen=Si.Name=Si.nil=Si.stringify=Si.str=Si._=Si.KeywordCxt=void 0;var PFe=kl();Object.defineProperty(Si,"KeywordCxt",{enumerable:!0,get:function(){return PFe.KeywordCxt}});var oc=me();Object.defineProperty(Si,"_",{enumerable:!0,get:function(){return oc._}});Object.defineProperty(Si,"str",{enumerable:!0,get:function(){return oc.str}});Object.defineProperty(Si,"stringify",{enumerable:!0,get:function(){return oc.stringify}});Object.defineProperty(Si,"nil",{enumerable:!0,get:function(){return oc.nil}});Object.defineProperty(Si,"Name",{enumerable:!0,get:function(){return oc.Name}});Object.defineProperty(Si,"CodeGen",{enumerable:!0,get:function(){return oc.CodeGen}});var IFe=C0(),dM=Pl(),TFe=kv(),Tl=R0(),NFe=me(),Nl=Rl(),O0=Fl(),Yv=Pe(),aM=nM(),qFe=oM(),fM=(e,t)=>new RegExp(e,t);fM.code="new RegExp";var jFe=["removeAdditional","useDefaults","coerceTypes"],MFe=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),BFe={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},LFe={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},cM=200;function UFe(e){var t,r,n,i,s,o,a,c,l,d,f,m,p,g,y,x,v,_,E,S,D,O,C,j,k;let q=e.strict,Z=(t=e.code)===null||t===void 0?void 0:t.optimize,ve=Z===!0||Z===void 0?1:Z||0,Ne=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:fM,je=(i=e.uriResolver)!==null&&i!==void 0?i:qFe.default;return{strictSchema:(o=(s=e.strictSchema)!==null&&s!==void 0?s:q)!==null&&o!==void 0?o:!0,strictNumbers:(c=(a=e.strictNumbers)!==null&&a!==void 0?a:q)!==null&&c!==void 0?c:!0,strictTypes:(d=(l=e.strictTypes)!==null&&l!==void 0?l:q)!==null&&d!==void 0?d:"log",strictTuples:(m=(f=e.strictTuples)!==null&&f!==void 0?f:q)!==null&&m!==void 0?m:"log",strictRequired:(g=(p=e.strictRequired)!==null&&p!==void 0?p:q)!==null&&g!==void 0?g:!1,code:e.code?{...e.code,optimize:ve,regExp:Ne}:{optimize:ve,regExp:Ne},loopRequired:(y=e.loopRequired)!==null&&y!==void 0?y:cM,loopEnum:(x=e.loopEnum)!==null&&x!==void 0?x:cM,meta:(v=e.meta)!==null&&v!==void 0?v:!0,messages:(_=e.messages)!==null&&_!==void 0?_:!0,inlineRefs:(E=e.inlineRefs)!==null&&E!==void 0?E:!0,schemaId:(S=e.schemaId)!==null&&S!==void 0?S:"$id",addUsedSchema:(D=e.addUsedSchema)!==null&&D!==void 0?D:!0,validateSchema:(O=e.validateSchema)!==null&&O!==void 0?O:!0,validateFormats:(C=e.validateFormats)!==null&&C!==void 0?C:!0,unicodeRegExp:(j=e.unicodeRegExp)!==null&&j!==void 0?j:!0,int32range:(k=e.int32range)!==null&&k!==void 0?k:!0,uriResolver:je}}class A0{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...UFe(e)};let{es5:t,lines:r}=this.opts.code;this.scope=new NFe.ValueScope({scope:{},prefixes:MFe,es5:t,lines:r}),this.logger=KFe(e.logger);let n=e.validateFormats;if(e.validateFormats=!1,this.RULES=(0,TFe.getRules)(),uM.call(this,BFe,e,"NOT SUPPORTED"),uM.call(this,LFe,e,"DEPRECATED","warn"),this._metaOpts=GFe.call(this),e.formats)zFe.call(this);if(this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords)HFe.call(this,e.keywords);if(typeof e.meta=="object")this.addMetaSchema(e.meta);VFe.call(this),e.validateFormats=n}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:r}=this.opts,n=aM;if(r==="id")n={...aM},n.id=n.$id,delete n.$id;if(t&&e)this.addMetaSchema(n,n[r],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[t]||e:void 0}validate(e,t){let r;if(typeof e=="string"){if(r=this.getSchema(e),!r)throw Error(`no schema with key or ref "${e}"`)}else r=this.compile(e);let n=r(t);if(!("$async"in r))this.errors=r.errors;return n}compile(e,t){let r=this._addSchema(e,t);return r.validate||this._compileSchemaEnv(r)}compileAsync(e,t){if(typeof this.opts.loadSchema!="function")throw Error("options.loadSchema should be a function");let{loadSchema:r}=this.opts;return n.call(this,e,t);async function n(l,d){await i.call(this,l.$schema);let f=this._addSchema(l,d);return f.validate||s.call(this,f)}async function i(l){if(l&&!this.getSchema(l))await n.call(this,{$ref:l},!0)}async function s(l){try{return this._compileSchemaEnv(l)}catch(d){if(!(d instanceof dM.default))throw d;return o.call(this,d),await a.call(this,d.missingSchema),s.call(this,l)}}function o({missingSchema:l,missingRef:d}){if(this.refs[l])throw Error(`AnySchema ${l} is loaded but ${d} cannot be resolved`)}async function a(l){let d=await c.call(this,l);if(!this.refs[l])await i.call(this,d.$schema);if(!this.refs[l])this.addSchema(d,l,t)}async function c(l){let d=this._loading[l];if(d)return d;try{return await(this._loading[l]=r(l))}finally{delete this._loading[l]}}}addSchema(e,t,r,n=this.opts.validateSchema){if(Array.isArray(e)){for(let s of e)this.addSchema(s,void 0,r,n);return this}let i;if(typeof e==="object"){let{schemaId:s}=this.opts;if(i=e[s],i!==void 0&&typeof i!="string")throw Error(`schema ${s} must be string`)}return t=(0,Nl.normalizeId)(t||i),this._checkUnique(t),this.schemas[t]=this._addSchema(e,r,t,n,!0),this}addMetaSchema(e,t,r=this.opts.validateSchema){return this.addSchema(e,t,!0,r),this}validateSchema(e,t){if(typeof e=="boolean")return!0;let r;if(r=e.$schema,r!==void 0&&typeof r!="string")throw Error("$schema must be a string");if(r=r||this.opts.defaultMeta||this.defaultMeta(),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let n=this.validate(r,e);if(!n&&t){let i="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(i);else throw Error(i)}return n}getSchema(e){let t;while(typeof(t=lM.call(this,e))=="string")e=t;if(t===void 0){let{schemaId:r}=this.opts,n=new Tl.SchemaEnv({schema:{},schemaId:r});if(t=Tl.resolveSchema.call(this,n,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let t=lM.call(this,e);if(typeof t=="object")this._cache.delete(t.schema);return delete this.schemas[e],delete this.refs[e],this}case"object":{let t=e;this._cache.delete(t);let r=e[this.opts.schemaId];if(r)r=(0,Nl.normalizeId)(r),delete this.schemas[r],delete this.refs[r];return this}default:throw Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let r;if(typeof e=="string"){if(r=e,typeof t=="object")this.logger.warn("these parameters are deprecated, see docs for addKeyword"),t.keyword=r}else if(typeof e=="object"&&t===void 0){if(t=e,r=t.keyword,Array.isArray(r)&&!r.length)throw Error("addKeywords: keyword must be string or non-empty array")}else throw Error("invalid addKeywords parameters");if(JFe.call(this,r,t),!t)return(0,Yv.eachItem)(r,(i)=>Kv.call(this,i)),this;QFe.call(this,t);let n={...t,type:(0,O0.getJSONTypes)(t.type),schemaType:(0,O0.getJSONTypes)(t.schemaType)};return(0,Yv.eachItem)(r,n.type.length===0?(i)=>Kv.call(this,i,n):(i)=>n.type.forEach((s)=>Kv.call(this,i,n,s))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t=="object"?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let r of t.rules){let n=r.rules.findIndex((i)=>i.keyword===e);if(n>=0)r.rules.splice(n,1)}return this}addFormat(e,t){if(typeof t=="string")t=new RegExp(t);return this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=", ",dataVar:r="data"}={}){if(!e||e.length===0)return"No errors";return e.map((n)=>`${r}${n.instancePath} ${n.message}`).reduce((n,i)=>n+t+i)}$dataMetaSchema(e,t){let r=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let n of t){let i=n.split("/").slice(1),s=e;for(let o of i)s=s[o];for(let o in r){let a=r[o];if(typeof a!="object")continue;let{$data:c}=a.definition,l=s[o];if(c&&l)s[o]=pM(l)}}return e}_removeAllSchemas(e,t){for(let r in e){let n=e[r];if(!t||t.test(r)){if(typeof n=="string")delete e[r];else if(n&&!n.meta)this._cache.delete(n.schema),delete e[r]}}}_addSchema(e,t,r,n=this.opts.validateSchema,i=this.opts.addUsedSchema){let s,{schemaId:o}=this.opts;if(typeof e=="object")s=e[o];else if(this.opts.jtd)throw Error("schema must be object");else if(typeof e!="boolean")throw Error("schema must be object or boolean");let a=this._cache.get(e);if(a!==void 0)return a;r=(0,Nl.normalizeId)(s||r);let c=Nl.getSchemaRefs.call(this,e,r);if(a=new Tl.SchemaEnv({schema:e,schemaId:o,meta:t,baseId:r,localRefs:c}),this._cache.set(a.schema,a),i&&!r.startsWith("#")){if(r)this._checkUnique(r);this.refs[r]=a}if(n)this.validateSchema(e,!0);return a}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta)this._compileMetaSchema(e);else Tl.compileSchema.call(this,e);if(!e.validate)throw Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{Tl.compileSchema.call(this,e)}finally{this.opts=t}}}A0.ValidationError=IFe.default;A0.MissingRefError=dM.default;Si.default=A0;function uM(e,t,r,n="error"){for(let i in e){let s=i;if(s in t)this.logger[n](`${r}: option ${i}. ${e[s]}`)}}function lM(e){return e=(0,Nl.normalizeId)(e),this.schemas[e]||this.refs[e]}function VFe(){let e=this.opts.schemas;if(!e)return;if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}function zFe(){for(let e in this.opts.formats){let t=this.opts.formats[e];if(t)this.addFormat(e,t)}}function HFe(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let t in e){let r=e[t];if(!r.keyword)r.keyword=t;this.addKeyword(r)}}function GFe(){let e={...this.opts};for(let t of jFe)delete e[t];return e}var WFe={log(){},warn(){},error(){}};function KFe(e){if(e===!1)return WFe;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw Error("logger must implement log, warn and error methods")}var YFe=/^[a-z_$][a-z0-9_$:-]*$/i;function JFe(e,t){let{RULES:r}=this;if((0,Yv.eachItem)(e,(n)=>{if(r.keywords[n])throw Error(`Keyword ${n} is already defined`);if(!YFe.test(n))throw Error(`Keyword ${n} has invalid name`)}),!t)return;if(t.$data&&!(("code"in t)||("validate"in t)))throw Error('$data keyword must have "code" or "validate" function')}function Kv(e,t,r){var n;let i=t===null||t===void 0?void 0:t.post;if(r&&i)throw Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,o=i?s.post:s.rules.find(({type:c})=>c===r);if(!o)o={type:r,rules:[]},s.rules.push(o);if(s.keywords[e]=!0,!t)return;let a={keyword:e,definition:{...t,type:(0,O0.getJSONTypes)(t.type),schemaType:(0,O0.getJSONTypes)(t.schemaType)}};if(t.before)XFe.call(this,o,a,t.before);else o.rules.push(a);s.all[e]=a,(n=t.implements)===null||n===void 0||n.forEach((c)=>this.addKeyword(c))}function XFe(e,t,r){let n=e.rules.findIndex((i)=>i.keyword===r);if(n>=0)e.rules.splice(n,0,t);else e.rules.push(t),this.logger.warn(`rule ${r} is not defined`)}function QFe(e){let{metaSchema:t}=e;if(t===void 0)return;if(e.$data&&this.opts.$data)t=pM(t);e.validateSchema=this.compile(t,!0)}var ZFe={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function pM(e){return{anyOf:[e,ZFe]}}});var gM=h(function(hM){Object.defineProperty(hM,"__esModule",{value:!0});var rRe={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};hM.default=rRe});var DM=h(function(vM){Object.defineProperty(vM,"__esModule",{value:!0});vM.callRef=vM.getValidate=void 0;var iRe=Pl(),yM=Vr(),pr=me(),ac=wi(),xM=R0(),k0=Pe(),sRe={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:r,it:n}=e,{baseId:i,schemaEnv:s,validateName:o,opts:a,self:c}=n,{root:l}=s;if((r==="#"||r==="#/")&&i===l.baseId)return f();let d=xM.resolveRef.call(c,l,i,r);if(d===void 0)throw new iRe.default(n.opts.uriResolver,i,r);if(d instanceof xM.SchemaEnv)return m(d);return p(d);function f(){if(s===l)return P0(e,o,s,s.$async);let g=t.scopeValue("root",{ref:l});return P0(e,pr._`${g}.validate`,l,l.$async)}function m(g){let y=bM(e,g);P0(e,y,g,g.$async)}function p(g){let y=t.scopeValue("schema",a.code.source===!0?{ref:g,code:(0,pr.stringify)(g)}:{ref:g}),x=t.name("valid"),v=e.subschema({schema:g,dataTypes:[],schemaPath:pr.nil,topSchemaRef:y,errSchemaPath:r},x);e.mergeEvaluated(v),e.ok(x)}}};function bM(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):pr._`${r.scopeValue("wrapper",{ref:t})}.validate`}vM.getValidate=bM;function P0(e,t,r,n){let{gen:i,it:s}=e,{allErrors:o,schemaEnv:a,opts:c}=s,l=c.passContext?ac.default.this:pr.nil;if(n)d();else f();function d(){if(!a.$async)throw Error("async schema referenced by sync schema");let g=i.let("valid");i.try(()=>{if(i.code(pr._`await ${(0,yM.callValidateCode)(e,t,l)}`),p(t),!o)i.assign(g,!0)},(y)=>{if(i.if(pr._`!(${y} instanceof ${s.ValidationError})`,()=>i.throw(y)),m(y),!o)i.assign(g,!1)}),e.ok(g)}function f(){e.result((0,yM.callValidateCode)(e,t,l),()=>p(t),()=>m(t))}function m(g){let y=pr._`${g}.errors`;i.assign(ac.default.vErrors,pr._`${ac.default.vErrors} === null ? ${y} : ${ac.default.vErrors}.concat(${y})`),i.assign(ac.default.errors,pr._`${ac.default.vErrors}.length`)}function p(g){var y;if(!s.opts.unevaluated)return;let x=(y=r===null||r===void 0?void 0:r.validate)===null||y===void 0?void 0:y.evaluated;if(s.props!==!0)if(x&&!x.dynamicProps){if(x.props!==void 0)s.props=k0.mergeEvaluated.props(i,x.props,s.props)}else{let v=i.var("props",pr._`${g}.evaluated.props`);s.props=k0.mergeEvaluated.props(i,v,s.props,pr.Name)}if(s.items!==!0)if(x&&!x.dynamicItems){if(x.items!==void 0)s.items=k0.mergeEvaluated.items(i,x.items,s.items)}else{let v=i.var("items",pr._`${g}.evaluated.items`);s.items=k0.mergeEvaluated.items(i,v,s.items,pr.Name)}}}vM.callRef=P0;vM.default=sRe});var EM=h(function(wM){Object.defineProperty(wM,"__esModule",{value:!0});var cRe=gM(),uRe=DM(),lRe=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",cRe.default,uRe.default];wM.default=lRe});var $M=h(function(SM){Object.defineProperty(SM,"__esModule",{value:!0});var I0=me(),Ss=I0.operators,T0={maximum:{okStr:"<=",ok:Ss.LTE,fail:Ss.GT},minimum:{okStr:">=",ok:Ss.GTE,fail:Ss.LT},exclusiveMaximum:{okStr:"<",ok:Ss.LT,fail:Ss.GTE},exclusiveMinimum:{okStr:">",ok:Ss.GT,fail:Ss.LTE}},fRe={message:({keyword:e,schemaCode:t})=>I0.str`must be ${T0[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>I0._`{comparison: ${T0[e].okStr}, limit: ${t}}`},pRe={keyword:Object.keys(T0),type:"number",schemaType:"number",$data:!0,error:fRe,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data(I0._`${r} ${T0[t].fail} ${n} || isNaN(${r})`)}};SM.default=pRe});var FM=h(function(CM){Object.defineProperty(CM,"__esModule",{value:!0});var ql=me(),hRe={message:({schemaCode:e})=>ql.str`must be multiple of ${e}`,params:({schemaCode:e})=>ql._`{multipleOf: ${e}}`},gRe={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:hRe,code(e){let{gen:t,data:r,schemaCode:n,it:i}=e,s=i.opts.multipleOfPrecision,o=t.let("res"),a=s?ql._`Math.abs(Math.round(${o}) - ${o}) > 1e-${s}`:ql._`${o} !== parseInt(${o})`;e.fail$data(ql._`(${n} === 0 || (${o} = ${r}/${n}, ${a}))`)}};CM.default=gRe});var AM=h(function(OM){Object.defineProperty(OM,"__esModule",{value:!0});function RM(e){let t=e.length,r=0,n=0,i;while(n<t)if(r++,i=e.charCodeAt(n++),i>=55296&&i<=56319&&n<t){if(i=e.charCodeAt(n),(i&64512)===56320)n++}return r}OM.default=RM;RM.code='require("ajv/dist/runtime/ucs2length").default'});var PM=h(function(kM){Object.defineProperty(kM,"__esModule",{value:!0});var vo=me(),bRe=Pe(),vRe=AM(),_Re={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return vo.str`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>vo._`{limit: ${e}}`},DRe={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:_Re,code(e){let{keyword:t,data:r,schemaCode:n,it:i}=e,s=t==="maxLength"?vo.operators.GT:vo.operators.LT,o=i.opts.unicode===!1?vo._`${r}.length`:vo._`${(0,bRe.useFunc)(e.gen,vRe.default)}(${r})`;e.fail$data(vo._`${o} ${s} ${n}`)}};kM.default=DRe});var TM=h(function(IM){Object.defineProperty(IM,"__esModule",{value:!0});var ERe=Vr(),N0=me(),SRe={message:({schemaCode:e})=>N0.str`must match pattern "${e}"`,params:({schemaCode:e})=>N0._`{pattern: ${e}}`},$Re={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:SRe,code(e){let{data:t,$data:r,schema:n,schemaCode:i,it:s}=e,o=s.opts.unicodeRegExp?"u":"",a=r?N0._`(new RegExp(${i}, ${o}))`:(0,ERe.usePattern)(e,n);e.fail$data(N0._`!${a}.test(${t})`)}};IM.default=$Re});var qM=h(function(NM){Object.defineProperty(NM,"__esModule",{value:!0});var jl=me(),FRe={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return jl.str`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>jl._`{limit: ${e}}`},RRe={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:FRe,code(e){let{keyword:t,data:r,schemaCode:n}=e,i=t==="maxProperties"?jl.operators.GT:jl.operators.LT;e.fail$data(jl._`Object.keys(${r}).length ${i} ${n}`)}};NM.default=RRe});var MM=h(function(jM){Object.defineProperty(jM,"__esModule",{value:!0});var Ml=Vr(),Bl=me(),ARe=Pe(),kRe={message:({params:{missingProperty:e}})=>Bl.str`must have required property '${e}'`,params:({params:{missingProperty:e}})=>Bl._`{missingProperty: ${e}}`},PRe={keyword:"required",type:"object",schemaType:"array",$data:!0,error:kRe,code(e){let{gen:t,schema:r,schemaCode:n,data:i,$data:s,it:o}=e,{opts:a}=o;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(o.allErrors)l();else d();if(a.strictRequired){let p=e.parentSchema.properties,{definedProperties:g}=e.it;for(let y of r)if((p===null||p===void 0?void 0:p[y])===void 0&&!g.has(y)){let x=o.schemaEnv.baseId+o.errSchemaPath,v=`required property "${y}" is not defined at "${x}" (strictRequired)`;(0,ARe.checkStrictMode)(o,v,o.opts.strictRequired)}}function l(){if(c||s)e.block$data(Bl.nil,f);else for(let p of r)(0,Ml.checkReportMissingProp)(e,p)}function d(){let p=t.let("missing");if(c||s){let g=t.let("valid",!0);e.block$data(g,()=>m(p,g)),e.ok(g)}else t.if((0,Ml.checkMissingProp)(e,r,p)),(0,Ml.reportMissingProp)(e,p),t.else()}function f(){t.forOf("prop",n,(p)=>{e.setParams({missingProperty:p}),t.if((0,Ml.noPropertyInData)(t,i,p,a.ownProperties),()=>e.error())})}function m(p,g){e.setParams({missingProperty:p}),t.forOf(p,n,()=>{t.assign(g,(0,Ml.propertyInData)(t,i,p,a.ownProperties)),t.if((0,Bl.not)(g),()=>{e.error(),t.break()})},Bl.nil)}}};jM.default=PRe});var LM=h(function(BM){Object.defineProperty(BM,"__esModule",{value:!0});var Ll=me(),TRe={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return Ll.str`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>Ll._`{limit: ${e}}`},NRe={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:TRe,code(e){let{keyword:t,data:r,schemaCode:n}=e,i=t==="maxItems"?Ll.operators.GT:Ll.operators.LT;e.fail$data(Ll._`${r}.length ${i} ${n}`)}};BM.default=NRe});var q0=h(function(VM){Object.defineProperty(VM,"__esModule",{value:!0});var UM=sl();UM.code='require("ajv/dist/runtime/equal").default';VM.default=UM});var HM=h(function(zM){Object.defineProperty(zM,"__esModule",{value:!0});var Jv=Fl(),Ot=me(),MRe=Pe(),BRe=q0(),LRe={message:({params:{i:e,j:t}})=>Ot.str`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>Ot._`{i: ${e}, j: ${t}}`},URe={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:LRe,code(e){let{gen:t,data:r,$data:n,schema:i,parentSchema:s,schemaCode:o,it:a}=e;if(!n&&!i)return;let c=t.let("valid"),l=s.items?(0,Jv.getSchemaTypes)(s.items):[];e.block$data(c,d,Ot._`${o} === false`),e.ok(c);function d(){let g=t.let("i",Ot._`${r}.length`),y=t.let("j");e.setParams({i:g,j:y}),t.assign(c,!0),t.if(Ot._`${g} > 1`,()=>(f()?m:p)(g,y))}function f(){return l.length>0&&!l.some((g)=>g==="object"||g==="array")}function m(g,y){let x=t.name("item"),v=(0,Jv.checkDataTypes)(l,x,a.opts.strictNumbers,Jv.DataType.Wrong),_=t.const("indices",Ot._`{}`);t.for(Ot._`;${g}--;`,()=>{if(t.let(x,Ot._`${r}[${g}]`),t.if(v,Ot._`continue`),l.length>1)t.if(Ot._`typeof ${x} == "string"`,Ot._`${x} += "_"`);t.if(Ot._`typeof ${_}[${x}] == "number"`,()=>{t.assign(y,Ot._`${_}[${x}]`),e.error(),t.assign(c,!1).break()}).code(Ot._`${_}[${x}] = ${g}`)})}function p(g,y){let x=(0,MRe.useFunc)(t,BRe.default),v=t.name("outer");t.label(v).for(Ot._`;${g}--;`,()=>t.for(Ot._`${y} = ${g}; ${y}--;`,()=>t.if(Ot._`${x}(${r}[${g}], ${r}[${y}])`,()=>{e.error(),t.assign(c,!1).break(v)})))}}};zM.default=URe});var WM=h(function(GM){Object.defineProperty(GM,"__esModule",{value:!0});var Xv=me(),zRe=Pe(),HRe=q0(),GRe={message:"must be equal to constant",params:({schemaCode:e})=>Xv._`{allowedValue: ${e}}`},WRe={keyword:"const",$data:!0,error:GRe,code(e){let{gen:t,data:r,$data:n,schemaCode:i,schema:s}=e;if(n||s&&typeof s=="object")e.fail$data(Xv._`!${(0,zRe.useFunc)(t,HRe.default)}(${r}, ${i})`);else e.fail(Xv._`${s} !== ${r}`)}};GM.default=WRe});var YM=h(function(KM){Object.defineProperty(KM,"__esModule",{value:!0});var Ul=me(),YRe=Pe(),JRe=q0(),XRe={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>Ul._`{allowedValues: ${e}}`},QRe={keyword:"enum",schemaType:"array",$data:!0,error:XRe,code(e){let{gen:t,data:r,$data:n,schema:i,schemaCode:s,it:o}=e;if(!n&&i.length===0)throw Error("enum must have non-empty array");let a=i.length>=o.opts.loopEnum,c,l=()=>c!==null&&c!==void 0?c:c=(0,YRe.useFunc)(t,JRe.default),d;if(a||n)d=t.let("valid"),e.block$data(d,f);else{if(!Array.isArray(i))throw Error("ajv implementation error");let p=t.const("vSchema",s);d=(0,Ul.or)(...i.map((g,y)=>m(p,y)))}e.pass(d);function f(){t.assign(d,!1),t.forOf("v",s,(p)=>t.if(Ul._`${l()}(${r}, ${p})`,()=>t.assign(d,!0).break()))}function m(p,g){let y=i[g];return typeof y==="object"&&y!==null?Ul._`${l()}(${r}, ${p}[${g}])`:Ul._`${r} === ${y}`}}};KM.default=QRe});var XM=h(function(JM){Object.defineProperty(JM,"__esModule",{value:!0});var eOe=$M(),tOe=FM(),rOe=PM(),nOe=TM(),iOe=qM(),sOe=MM(),oOe=LM(),aOe=HM(),cOe=WM(),uOe=YM(),lOe=[eOe.default,tOe.default,rOe.default,nOe.default,iOe.default,sOe.default,oOe.default,aOe.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},cOe.default,uOe.default];JM.default=lOe});var Zv=h(function(ZM){Object.defineProperty(ZM,"__esModule",{value:!0});ZM.validateAdditionalItems=void 0;var _o=me(),Qv=Pe(),fOe={message:({params:{len:e}})=>_o.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>_o._`{limit: ${e}}`},pOe={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:fOe,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,Qv.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}QM(e,n)}};function QM(e,t){let{gen:r,schema:n,data:i,keyword:s,it:o}=e;o.items=!0;let a=r.const("len",_o._`${i}.length`);if(n===!1)e.setParams({len:t.length}),e.pass(_o._`${a} <= ${t.length}`);else if(typeof n=="object"&&!(0,Qv.alwaysValidSchema)(o,n)){let l=r.var("valid",_o._`${a} <= ${t.length}`);r.if((0,_o.not)(l),()=>c(l)),e.ok(l)}function c(l){r.forRange("i",t.length,a,(d)=>{if(e.subschema({keyword:s,dataProp:d,dataPropType:Qv.Type.Num},l),!o.allErrors)r.if((0,_o.not)(l),()=>r.break())})}}ZM.validateAdditionalItems=QM;ZM.default=pOe});var e_=h(function(nB){Object.defineProperty(nB,"__esModule",{value:!0});nB.validateTuple=void 0;var tB=me(),j0=Pe(),hOe=Vr(),gOe={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return rB(e,"additionalItems",t);if(r.items=!0,(0,j0.alwaysValidSchema)(r,t))return;e.ok((0,hOe.validateArray)(e))}};function rB(e,t,r=e.schema){let{gen:n,parentSchema:i,data:s,keyword:o,it:a}=e;if(d(i),a.opts.unevaluated&&r.length&&a.items!==!0)a.items=j0.mergeEvaluated.items(n,r.length,a.items);let c=n.name("valid"),l=n.const("len",tB._`${s}.length`);r.forEach((f,m)=>{if((0,j0.alwaysValidSchema)(a,f))return;n.if(tB._`${l} > ${m}`,()=>e.subschema({keyword:o,schemaProp:m,dataProp:m},c)),e.ok(c)});function d(f){let{opts:m,errSchemaPath:p}=a,g=r.length,y=g===f.minItems&&(g===f.maxItems||f[t]===!1);if(m.strictTuples&&!y){let x=`"${o}" is ${g}-tuple, but minItems or maxItems/${t} are not specified or different at path "${p}"`;(0,j0.checkStrictMode)(a,x,m.strictTuples)}}}nB.validateTuple=rB;nB.default=gOe});var oB=h(function(sB){Object.defineProperty(sB,"__esModule",{value:!0});var xOe=e_(),bOe={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:(e)=>(0,xOe.validateTuple)(e,"items")};sB.default=bOe});var uB=h(function(cB){Object.defineProperty(cB,"__esModule",{value:!0});var aB=me(),_Oe=Pe(),DOe=Vr(),wOe=Zv(),EOe={message:({params:{len:e}})=>aB.str`must NOT have more than ${e} items`,params:({params:{len:e}})=>aB._`{limit: ${e}}`},SOe={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:EOe,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:i}=r;if(n.items=!0,(0,_Oe.alwaysValidSchema)(n,t))return;if(i)(0,wOe.validateAdditionalItems)(e,i);else e.ok((0,DOe.validateArray)(e))}};cB.default=SOe});var dB=h(function(lB){Object.defineProperty(lB,"__esModule",{value:!0});var zr=me(),M0=Pe(),COe={message:({params:{min:e,max:t}})=>t===void 0?zr.str`must contain at least ${e} valid item(s)`:zr.str`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?zr._`{minContains: ${e}}`:zr._`{minContains: ${e}, maxContains: ${t}}`},FOe={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:COe,code(e){let{gen:t,schema:r,parentSchema:n,data:i,it:s}=e,o,a,{minContains:c,maxContains:l}=n;if(s.opts.next)o=c===void 0?1:c,a=l;else o=1;let d=t.const("len",zr._`${i}.length`);if(e.setParams({min:o,max:a}),a===void 0&&o===0){(0,M0.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&o>a){(0,M0.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,M0.alwaysValidSchema)(s,r)){let y=zr._`${d} >= ${o}`;if(a!==void 0)y=zr._`${y} && ${d} <= ${a}`;e.pass(y);return}s.items=!0;let f=t.name("valid");if(a===void 0&&o===1)p(f,()=>t.if(f,()=>t.break()));else if(o===0){if(t.let(f,!0),a!==void 0)t.if(zr._`${i}.length > 0`,m)}else t.let(f,!1),m();e.result(f,()=>e.reset());function m(){let y=t.name("_valid"),x=t.let("count",0);p(y,()=>t.if(y,()=>g(x)))}function p(y,x){t.forRange("i",0,d,(v)=>{e.subschema({keyword:"contains",dataProp:v,dataPropType:M0.Type.Num,compositeRule:!0},y),x()})}function g(y){if(t.code(zr._`${y}++`),a===void 0)t.if(zr._`${y} >= ${o}`,()=>t.assign(f,!0).break());else if(t.if(zr._`${y} > ${a}`,()=>t.assign(f,!1).break()),o===1)t.assign(f,!0);else t.if(zr._`${y} >= ${o}`,()=>t.assign(f,!0))}}};lB.default=FOe});var yB=h(function(mB){Object.defineProperty(mB,"__esModule",{value:!0});mB.validateSchemaDeps=mB.validatePropertyDeps=mB.error=void 0;var t_=me(),OOe=Pe(),Vl=Vr();mB.error={message:({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return t_.str`must have ${n} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>t_._`{property: ${e},
|
|
96
96
|
missingProperty: ${n},
|
|
97
97
|
depsCount: ${t},
|
|
98
|
-
deps: ${r}}`};var AOe={keyword:"dependencies",type:"object",schemaType:"object",error:mB.error,code(e){let[t,r]=kOe(e);fB(e,t),pB(e,r)}};function kOe({schema:e}){let t={},r={};for(let n in e){if(n==="__proto__")continue;let i=Array.isArray(e[n])?t:r;i[n]=e[n]}return[t,r]}function fB(e,t=e.schema){let{gen:r,data:n,it:i}=e;if(Object.keys(t).length===0)return;let s=r.let("missing");for(let o in t){let a=t[o];if(a.length===0)continue;let c=(0,Vl.propertyInData)(r,n,o,i.opts.ownProperties);if(e.setParams({property:o,depsCount:a.length,deps:a.join(", ")}),i.allErrors)r.if(c,()=>{for(let l of a)(0,Vl.checkReportMissingProp)(e,l)});else r.if(t_._`${c} && (${(0,Vl.checkMissingProp)(e,a,s)})`),(0,Vl.reportMissingProp)(e,s),r.else()}}mB.validatePropertyDeps=fB;function pB(e,t=e.schema){let{gen:r,data:n,keyword:i,it:s}=e,o=r.name("valid");for(let a in t){if((0,OOe.alwaysValidSchema)(s,t[a]))continue;r.if((0,Vl.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let c=e.subschema({keyword:i,schemaProp:a},o);e.mergeValidEvaluated(c,o)},()=>r.var(o,!0)),e.ok(o)}}mB.validateSchemaDeps=pB;mB.default=AOe});var vB=h(function(bB){Object.defineProperty(bB,"__esModule",{value:!0});var xB=me(),TOe=Pe(),NOe={message:"property name must be valid",params:({params:e})=>xB._`{propertyName: ${e.propertyName}}`},qOe={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:NOe,code(e){let{gen:t,schema:r,data:n,it:i}=e;if((0,TOe.alwaysValidSchema)(i,r))return;let s=t.name("valid");t.forIn("key",n,(o)=>{e.setParams({propertyName:o}),e.subschema({keyword:"propertyNames",data:o,dataTypes:["string"],propertyName:o,compositeRule:!0},s),t.if((0,xB.not)(s),()=>{if(e.error(!0),!i.allErrors)t.break()})}),e.ok(s)}};bB.default=qOe});var r_=h(function(_B){Object.defineProperty(_B,"__esModule",{value:!0});var B0=Vr(),mn=me(),MOe=wi(),L0=Pe(),BOe={message:"must NOT have additional properties",params:({params:e})=>mn._`{additionalProperty: ${e.additionalProperty}}`},LOe={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:BOe,code(e){let{gen:t,schema:r,parentSchema:n,data:i,errsCount:s,it:o}=e;if(!s)throw Error("ajv implementation error");let{allErrors:a,opts:c}=o;if(o.props=!0,c.removeAdditional!=="all"&&(0,L0.alwaysValidSchema)(o,r))return;let l=(0,B0.allSchemaProperties)(n.properties),d=(0,B0.allSchemaProperties)(n.patternProperties);f(),e.ok(mn._`${s} === ${MOe.default.errors}`);function f(){t.forIn("key",i,(x)=>{if(!l.length&&!d.length)g(x);else t.if(m(x),()=>g(x))})}function m(x){let v;if(l.length>8){let _=(0,L0.schemaRefOrVal)(o,n.properties,"properties");v=(0,B0.isOwnProperty)(t,_,x)}else if(l.length)v=(0,mn.or)(...l.map((_)=>mn._`${x} === ${_}`));else v=mn.nil;if(d.length)v=(0,mn.or)(v,...d.map((_)=>mn._`${(0,B0.usePattern)(e,_)}.test(${x})`));return(0,mn.not)(v)}function p(x){t.code(mn._`delete ${i}[${x}]`)}function g(x){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){p(x);return}if(r===!1){if(e.setParams({additionalProperty:x}),e.error(),!a)t.break();return}if(typeof r=="object"&&!(0,L0.alwaysValidSchema)(o,r)){let v=t.name("valid");if(c.removeAdditional==="failing")y(x,v,!1),t.if((0,mn.not)(v),()=>{e.reset(),p(x)});else if(y(x,v),!a)t.if((0,mn.not)(v),()=>t.break())}}function y(x,v,_){let E={keyword:"additionalProperties",dataProp:x,dataPropType:L0.Type.Str};if(_===!1)Object.assign(E,{compositeRule:!0,createErrors:!1,allErrors:!1});e.subschema(E,v)}}};_B.default=LOe});var SB=h(function(EB){Object.defineProperty(EB,"__esModule",{value:!0});var VOe=kl(),DB=Vr(),n_=Pe(),wB=r_(),zOe={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,parentSchema:n,data:i,it:s}=e;if(s.opts.removeAdditional==="all"&&n.additionalProperties===void 0)wB.default.code(new VOe.KeywordCxt(s,wB.default,"additionalProperties"));let o=(0,DB.allSchemaProperties)(r);for(let f of o)s.definedProperties.add(f);if(s.opts.unevaluated&&o.length&&s.props!==!0)s.props=n_.mergeEvaluated.props(t,(0,n_.toHash)(o),s.props);let a=o.filter((f)=>!(0,n_.alwaysValidSchema)(s,r[f]));if(a.length===0)return;let c=t.name("valid");for(let f of a){if(l(f))d(f);else{if(t.if((0,DB.propertyInData)(t,i,f,s.opts.ownProperties)),d(f),!s.allErrors)t.else().var(c,!0);t.endIf()}e.it.definedProperties.add(f),e.ok(c)}function l(f){return s.opts.useDefaults&&!s.compositeRule&&r[f].default!==void 0}function d(f){e.subschema({keyword:"properties",schemaProp:f,dataProp:f},c)}}};EB.default=zOe});var OB=h(function(RB){Object.defineProperty(RB,"__esModule",{value:!0});var $B=Vr(),U0=me(),CB=Pe(),FB=Pe(),GOe={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,data:n,parentSchema:i,it:s}=e,{opts:o}=s,a=(0,$B.allSchemaProperties)(r),c=a.filter((y)=>(0,CB.alwaysValidSchema)(s,r[y]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let l=o.strictSchema&&!o.allowMatchingProperties&&i.properties,d=t.name("valid");if(s.props!==!0&&!(s.props instanceof U0.Name))s.props=(0,FB.evaluatedPropsToName)(t,s.props);let{props:f}=s;m();function m(){for(let y of a){if(l)p(y);if(s.allErrors)g(y);else t.var(d,!0),g(y),t.if(d)}}function p(y){for(let x in l)if(new RegExp(y).test(x))(0,CB.checkStrictMode)(s,`property ${x} matches pattern ${y} (use allowMatchingProperties)`)}function g(y){t.forIn("key",n,(x)=>{t.if(U0._`${(0,$B.usePattern)(e,y)}.test(${x})`,()=>{let v=c.includes(y);if(!v)e.subschema({keyword:"patternProperties",schemaProp:y,dataProp:x,dataPropType:FB.Type.Str},d);if(s.opts.unevaluated&&f!==!0)t.assign(U0._`${f}[${x}]`,!0);else if(!v&&!s.allErrors)t.if((0,U0.not)(d),()=>t.break())})})}}};RB.default=GOe});var kB=h(function(AB){Object.defineProperty(AB,"__esModule",{value:!0});var KOe=Pe(),YOe={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,KOe.alwaysValidSchema)(n,r)){e.fail();return}let i=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},i),e.failResult(i,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};AB.default=YOe});var IB=h(function(PB){Object.defineProperty(PB,"__esModule",{value:!0});var XOe=Vr(),QOe={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:XOe.validateUnion,error:{message:"must match a schema in anyOf"}};PB.default=QOe});var NB=h(function(TB){Object.defineProperty(TB,"__esModule",{value:!0});var V0=me(),eAe=Pe(),tAe={message:"must match exactly one schema in oneOf",params:({params:e})=>V0._`{passingSchemas: ${e.passing}}`},rAe={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:tAe,code(e){let{gen:t,schema:r,parentSchema:n,it:i}=e;if(!Array.isArray(r))throw Error("ajv implementation error");if(i.opts.discriminator&&n.discriminator)return;let s=r,o=t.let("valid",!1),a=t.let("passing",null),c=t.name("_valid");e.setParams({passing:a}),t.block(l),e.result(o,()=>e.reset(),()=>e.error(!0));function l(){s.forEach((d,f)=>{let m;if((0,eAe.alwaysValidSchema)(i,d))t.var(c,!0);else m=e.subschema({keyword:"oneOf",schemaProp:f,compositeRule:!0},c);if(f>0)t.if(V0._`${c} && ${o}`).assign(o,!1).assign(a,V0._`[${a}, ${f}]`).else();t.if(c,()=>{if(t.assign(o,!0),t.assign(a,f),m)e.mergeEvaluated(m,V0.Name)})})}}};TB.default=rAe});var jB=h(function(qB){Object.defineProperty(qB,"__esModule",{value:!0});var iAe=Pe(),sAe={keyword:"allOf",schemaType:"array",code(e){let{gen:t,schema:r,it:n}=e;if(!Array.isArray(r))throw Error("ajv implementation error");let i=t.name("valid");r.forEach((s,o)=>{if((0,iAe.alwaysValidSchema)(n,s))return;let a=e.subschema({keyword:"allOf",schemaProp:o},i);e.ok(i),e.mergeEvaluated(a)})}};qB.default=sAe});var UB=h(function(LB){Object.defineProperty(LB,"__esModule",{value:!0});var z0=me(),BB=Pe(),aAe={message:({params:e})=>z0.str`must match "${e.ifClause}" schema`,params:({params:e})=>z0._`{failingKeyword: ${e.ifClause}}`},cAe={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:aAe,code(e){let{gen:t,parentSchema:r,it:n}=e;if(r.then===void 0&&r.else===void 0)(0,BB.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let i=MB(n,"then"),s=MB(n,"else");if(!i&&!s)return;let o=t.let("valid",!0),a=t.name("_valid");if(c(),e.reset(),i&&s){let d=t.let("ifClause");e.setParams({ifClause:d}),t.if(a,l("then",d),l("else",d))}else if(i)t.if(a,l("then"));else t.if((0,z0.not)(a),l("else"));e.pass(o,()=>e.error(!0));function c(){let d=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);e.mergeEvaluated(d)}function l(d,f){return()=>{let m=e.subschema({keyword:d},a);if(t.assign(o,a),e.mergeValidEvaluated(m,o),f)t.assign(f,z0._`${d}`);else e.setParams({ifClause:d})}}}};function MB(e,t){let r=e.schema[t];return r!==void 0&&!(0,BB.alwaysValidSchema)(e,r)}LB.default=cAe});var zB=h(function(VB){Object.defineProperty(VB,"__esModule",{value:!0});var lAe=Pe(),dAe={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){if(t.if===void 0)(0,lAe.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};VB.default=dAe});var GB=h(function(HB){Object.defineProperty(HB,"__esModule",{value:!0});var pAe=Zv(),mAe=oB(),hAe=e_(),gAe=uB(),yAe=dB(),xAe=yB(),bAe=vB(),vAe=r_(),_Ae=SB(),DAe=OB(),wAe=kB(),EAe=IB(),SAe=NB(),$Ae=jB(),CAe=UB(),FAe=zB();function RAe(e=!1){let t=[wAe.default,EAe.default,SAe.default,$Ae.default,CAe.default,FAe.default,bAe.default,vAe.default,xAe.default,_Ae.default,DAe.default];if(e)t.push(mAe.default,gAe.default);else t.push(pAe.default,hAe.default);return t.push(yAe.default),t}HB.default=RAe});var KB=h(function(WB){Object.defineProperty(WB,"__esModule",{value:!0});var mt=me(),AAe={message:({schemaCode:e})=>mt.str`must match format "${e}"`,params:({schemaCode:e})=>mt._`{format: ${e}}`},kAe={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:AAe,code(e,t){let{gen:r,data:n,$data:i,schema:s,schemaCode:o,it:a}=e,{opts:c,errSchemaPath:l,schemaEnv:d,self:f}=a;if(!c.validateFormats)return;if(i)m();else p();function m(){let g=r.scopeValue("formats",{ref:f.formats,code:c.code.formats}),y=r.const("fDef",mt._`${g}[${o}]`),x=r.let("fType"),v=r.let("format");r.if(mt._`typeof ${y} == "object" && !(${y} instanceof RegExp)`,()=>r.assign(x,mt._`${y}.type || "string"`).assign(v,mt._`${y}.validate`),()=>r.assign(x,mt._`"string"`).assign(v,y)),e.fail$data((0,mt.or)(_(),E()));function _(){if(c.strictSchema===!1)return mt.nil;return mt._`${o} && !${v}`}function E(){let S=d.$async?mt._`(${y}.async ? await ${v}(${n}) : ${v}(${n}))`:mt._`${v}(${n})`,D=mt._`(typeof ${v} == "function" ? ${S} : ${v}.test(${n}))`;return mt._`${v} && ${v} !== true && ${x} === ${t} && !${D}`}}function p(){let g=f.formats[s];if(!g){_();return}if(g===!0)return;let[y,x,v]=E(g);if(y===t)e.pass(S());function _(){if(c.strictSchema===!1){f.logger.warn(D());return}throw Error(D());function D(){return`unknown format "${s}" ignored in schema at path "${l}"`}}function E(D){let O=D instanceof RegExp?(0,mt.regexpCode)(D):c.code.formats?mt._`${c.code.formats}${(0,mt.getProperty)(s)}`:void 0,C=r.scopeValue("formats",{key:s,ref:D,code:O});if(typeof D=="object"&&!(D instanceof RegExp))return[D.type||"string",D.validate,mt._`${C}.validate`];return["string",D,C]}function S(){if(typeof g=="object"&&!(g instanceof RegExp)&&g.async){if(!d.$async)throw Error("async format in sync schema");return mt._`await ${v}(${n})`}return typeof x=="function"?mt._`${v}(${n})`:mt._`${v}.test(${n})`}}}};WB.default=kAe});var JB=h(function(YB){Object.defineProperty(YB,"__esModule",{value:!0});var IAe=KB(),TAe=[IAe.default];YB.default=TAe});var ZB=h(function(XB){Object.defineProperty(XB,"__esModule",{value:!0});XB.contentVocabulary=XB.metadataVocabulary=void 0;XB.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];XB.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var rL=h(function(tL){Object.defineProperty(tL,"__esModule",{value:!0});var jAe=EM(),MAe=XM(),BAe=GB(),LAe=JB(),eL=ZB(),UAe=[jAe.default,MAe.default,(0,BAe.default)(),LAe.default,eL.metadataVocabulary,eL.contentVocabulary];tL.default=UAe});var oL=h(function(iL){Object.defineProperty(iL,"__esModule",{value:!0});iL.DiscrError=void 0;var nL;(function(e){e.Tag="tag",e.Mapping="mapping"})(nL||(iL.DiscrError=nL={}))});var uL=h(function(cL){Object.defineProperty(cL,"__esModule",{value:!0});var cc=me(),i_=oL(),aL=R0(),zAe=Pl(),HAe=Pe(),GAe={message:({params:{discrError:e,tagName:t}})=>e===i_.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>cc._`{error: ${e}, tag: ${r}, tagValue: ${t}}`},WAe={keyword:"discriminator",type:"object",schemaType:"object",error:GAe,code(e){let{gen:t,data:r,schema:n,parentSchema:i,it:s}=e,{oneOf:o}=i;if(!s.opts.discriminator)throw Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw Error("discriminator: requires propertyName");if(n.mapping)throw Error("discriminator: mapping is not supported");if(!o)throw Error("discriminator: requires oneOf keyword");let c=t.let("valid",!1),l=t.const("tag",cc._`${r}${(0,cc.getProperty)(a)}`);t.if(cc._`typeof ${l} == "string"`,()=>d(),()=>e.error(!1,{discrError:i_.DiscrError.Tag,tag:l,tagName:a})),e.ok(c);function d(){let p=m();t.if(!1);for(let g in p)t.elseIf(cc._`${l} === ${g}`),t.assign(c,f(p[g]));t.else(),e.error(!1,{discrError:i_.DiscrError.Mapping,tag:l,tagName:a}),t.endIf()}function f(p){let g=t.name("valid"),y=e.subschema({keyword:"oneOf",schemaProp:p},g);return e.mergeEvaluated(y,cc.Name),g}function m(){var p;let g={},y=v(i),x=!0;for(let S=0;S<o.length;S++){let D=o[S];if((D===null||D===void 0?void 0:D.$ref)&&!(0,HAe.schemaHasRulesButRef)(D,s.self.RULES)){let C=D.$ref;if(D=aL.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,C),D instanceof aL.SchemaEnv)D=D.schema;if(D===void 0)throw new zAe.default(s.opts.uriResolver,s.baseId,C)}let O=(p=D===null||D===void 0?void 0:D.properties)===null||p===void 0?void 0:p[a];if(typeof O!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);x=x&&(y||v(D)),_(O,S)}if(!x)throw Error(`discriminator: "${a}" must be required`);return g;function v({required:S}){return Array.isArray(S)&&S.includes(a)}function _(S,D){if(S.const)E(S.const,D);else if(S.enum)for(let O of S.enum)E(O,D);else throw Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function E(S,D){if(typeof S!="string"||S in g)throw Error(`discriminator: "${a}" values must be unique strings`);g[S]=D}}}};cL.default=WAe});var lL=h(function(ZWe,YAe){YAe.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var fL=h(function(mr,s_){Object.defineProperty(mr,"__esModule",{value:!0});mr.MissingRefError=mr.ValidationError=mr.CodeGen=mr.Name=mr.nil=mr.stringify=mr.str=mr._=mr.KeywordCxt=mr.Ajv=void 0;var JAe=mM(),XAe=rL(),QAe=uL(),dL=lL(),ZAe=["/properties"],H0="http://json-schema.org/draft-07/schema";class zl extends JAe.default{_addVocabularies(){if(super._addVocabularies(),XAe.default.forEach((e)=>this.addVocabulary(e)),this.opts.discriminator)this.addKeyword(QAe.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(dL,ZAe):dL;this.addMetaSchema(e,H0,!1),this.refs["http://json-schema.org/schema"]=H0}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(H0)?H0:void 0)}}mr.Ajv=zl;s_.exports=mr=zl;s_.exports.Ajv=zl;Object.defineProperty(mr,"__esModule",{value:!0});mr.default=zl;var eke=kl();Object.defineProperty(mr,"KeywordCxt",{enumerable:!0,get:function(){return eke.KeywordCxt}});var uc=me();Object.defineProperty(mr,"_",{enumerable:!0,get:function(){return uc._}});Object.defineProperty(mr,"str",{enumerable:!0,get:function(){return uc.str}});Object.defineProperty(mr,"stringify",{enumerable:!0,get:function(){return uc.stringify}});Object.defineProperty(mr,"nil",{enumerable:!0,get:function(){return uc.nil}});Object.defineProperty(mr,"Name",{enumerable:!0,get:function(){return uc.Name}});Object.defineProperty(mr,"CodeGen",{enumerable:!0,get:function(){return uc.CodeGen}});var tke=C0();Object.defineProperty(mr,"ValidationError",{enumerable:!0,get:function(){return tke.default}});var rke=Pl();Object.defineProperty(mr,"MissingRefError",{enumerable:!0,get:function(){return rke.default}})});var mL=h(function(pL){Object.defineProperty(pL,"__esModule",{value:!0});pL.formatLimitDefinition=void 0;var ske=fL(),hn=me(),$s=hn.operators,G0={formatMaximum:{okStr:"<=",ok:$s.LTE,fail:$s.GT},formatMinimum:{okStr:">=",ok:$s.GTE,fail:$s.LT},formatExclusiveMaximum:{okStr:"<",ok:$s.LT,fail:$s.GTE},formatExclusiveMinimum:{okStr:">",ok:$s.GT,fail:$s.LTE}},oke={message:({keyword:e,schemaCode:t})=>hn.str`should be ${G0[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>hn._`{comparison: ${G0[e].okStr}, limit: ${t}}`};pL.formatLimitDefinition={keyword:Object.keys(G0),type:"string",schemaType:"string",$data:!0,error:oke,code(e){let{gen:t,data:r,schemaCode:n,keyword:i,it:s}=e,{opts:o,self:a}=s;if(!o.validateFormats)return;let c=new ske.KeywordCxt(s,a.RULES.all.format.definition,"format");if(c.$data)l();else d();function l(){let m=t.scopeValue("formats",{ref:a.formats,code:o.code.formats}),p=t.const("fmt",hn._`${m}[${c.schemaCode}]`);e.fail$data((0,hn.or)(hn._`typeof ${p} != "object"`,hn._`${p} instanceof RegExp`,hn._`typeof ${p}.compare != "function"`,f(p)))}function d(){let m=c.schema,p=a.formats[m];if(!p||p===!0)return;if(typeof p!="object"||p instanceof RegExp||typeof p.compare!="function")throw Error(`"${i}": format "${m}" does not define "compare" function`);let g=t.scopeValue("formats",{key:m,ref:p,code:o.code.formats?hn._`${o.code.formats}${(0,hn.getProperty)(m)}`:void 0});e.fail$data(f(g))}function f(m){return hn._`${m}.compare(${r}, ${n}) ${G0[i].fail} 0`}},dependencies:["format"]};var ake=(e)=>(e.addKeyword(pL.formatLimitDefinition),e);pL.default=ake});var xL=h(function(Hl,yL){Object.defineProperty(Hl,"__esModule",{value:!0});var lc=fq(),uke=mL(),a_=me(),hL=new a_.Name("fullFormats"),lke=new a_.Name("fastFormats"),c_=(e,t={keywords:!0})=>{if(Array.isArray(t))return gL(e,t,lc.fullFormats,hL),e;let[r,n]=t.mode==="fast"?[lc.fastFormats,lke]:[lc.fullFormats,hL],i=t.formats||lc.formatNames;if(gL(e,i,r,n),t.keywords)(0,uke.default)(e);return e};c_.get=(e,t="full")=>{let n=(t==="fast"?lc.fastFormats:lc.fullFormats)[e];if(!n)throw Error(`Unknown format "${e}"`);return n};function gL(e,t,r,n){var i,s;(i=(s=e.opts.code).formats)!==null&&i!==void 0||(s.formats=a_._`require("ajv-formats/dist/formats").${n}`);for(let o of t)e.addFormat(o,r[o])}yL.exports=Hl=c_;Object.defineProperty(Hl,"__esModule",{value:!0});Hl.default=c_});var dke=(e,t={})=>{if(typeof e!=="function")throw TypeError(`Expected the first argument to be a function, got \`${typeof e}\``);let{wait:r=0,maxWait:n=Number.POSITIVE_INFINITY,before:i=!1,after:s=!0}=t;if(r<0||n<0)throw RangeError("`wait` and `maxWait` must not be negative.");if(!i&&!s)throw Error("Both `before` and `after` are false, function wouldn't be called.");let o,a,c,l=function(...d){let f=this,m=()=>{if(o=void 0,a)clearTimeout(a),a=void 0;if(s)c=e.apply(f,d)},p=()=>{if(a=void 0,o)clearTimeout(o),o=void 0;if(s)c=e.apply(f,d)},g=i&&!o;if(clearTimeout(o),o=setTimeout(m,r),n>0&&n!==Number.POSITIVE_INFINITY&&!a)a=setTimeout(p,n);if(g)c=e.apply(f,d);return c};return Wu(l,e),l.cancel=()=>{if(o)clearTimeout(o),o=void 0;if(a)clearTimeout(a),a=void 0},l},u_;var bL=A(()=>{Mx();u_=dke});var Gl=h(function(dKe,vL){var fke=Number.MAX_SAFE_INTEGER||9007199254740991,pke=["major","premajor","minor","preminor","patch","prepatch","prerelease"];vL.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:16,MAX_SAFE_BUILD_LENGTH:250,MAX_SAFE_INTEGER:fke,RELEASE_TYPES:pke,SEMVER_SPEC_VERSION:"2.0.0",FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var Wl=h(function(fKe,_L){var mke=typeof process==="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};_L.exports=mke});var dc=h(function(Yn,DL){var{MAX_SAFE_COMPONENT_LENGTH:l_,MAX_SAFE_BUILD_LENGTH:hke,MAX_LENGTH:gke}=Gl(),yke=Wl();Yn=DL.exports={};var xke=Yn.re=[],bke=Yn.safeRe=[],V=Yn.src=[],vke=Yn.safeSrc=[],z=Yn.t={},_ke=0,d_="[a-zA-Z0-9-]",Dke=[["\\s",1],["\\d",gke],[d_,hke]],wke=(e)=>{for(let[t,r]of Dke)e=e.split(`${t}*`).join(`${t}{0,${r}}`).split(`${t}+`).join(`${t}{1,${r}}`);return e},se=(e,t,r)=>{let n=wke(t),i=_ke++;yke(e,i,t),z[e]=i,V[i]=t,vke[i]=n,xke[i]=new RegExp(t,r?"g":void 0),bke[i]=new RegExp(n,r?"g":void 0)};se("NUMERICIDENTIFIER","0|[1-9]\\d*");se("NUMERICIDENTIFIERLOOSE","\\d+");se("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${d_}*`);se("MAINVERSION",`(${V[z.NUMERICIDENTIFIER]})\\.(${V[z.NUMERICIDENTIFIER]})\\.(${V[z.NUMERICIDENTIFIER]})`);se("MAINVERSIONLOOSE",`(${V[z.NUMERICIDENTIFIERLOOSE]})\\.(${V[z.NUMERICIDENTIFIERLOOSE]})\\.(${V[z.NUMERICIDENTIFIERLOOSE]})`);se("PRERELEASEIDENTIFIER",`(?:${V[z.NONNUMERICIDENTIFIER]}|${V[z.NUMERICIDENTIFIER]})`);se("PRERELEASEIDENTIFIERLOOSE",`(?:${V[z.NONNUMERICIDENTIFIER]}|${V[z.NUMERICIDENTIFIERLOOSE]})`);se("PRERELEASE",`(?:-(${V[z.PRERELEASEIDENTIFIER]}(?:\\.${V[z.PRERELEASEIDENTIFIER]})*))`);se("PRERELEASELOOSE",`(?:-?(${V[z.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${V[z.PRERELEASEIDENTIFIERLOOSE]})*))`);se("BUILDIDENTIFIER",`${d_}+`);se("BUILD",`(?:\\+(${V[z.BUILDIDENTIFIER]}(?:\\.${V[z.BUILDIDENTIFIER]})*))`);se("FULLPLAIN",`v?${V[z.MAINVERSION]}${V[z.PRERELEASE]}?${V[z.BUILD]}?`);se("FULL",`^${V[z.FULLPLAIN]}$`);se("LOOSEPLAIN",`[v=\\s]*${V[z.MAINVERSIONLOOSE]}${V[z.PRERELEASELOOSE]}?${V[z.BUILD]}?`);se("LOOSE",`^${V[z.LOOSEPLAIN]}$`);se("GTLT","((?:<|>)?=?)");se("XRANGEIDENTIFIERLOOSE",`${V[z.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);se("XRANGEIDENTIFIER",`${V[z.NUMERICIDENTIFIER]}|x|X|\\*`);se("XRANGEPLAIN",`[v=\\s]*(${V[z.XRANGEIDENTIFIER]})(?:\\.(${V[z.XRANGEIDENTIFIER]})(?:\\.(${V[z.XRANGEIDENTIFIER]})(?:${V[z.PRERELEASE]})?${V[z.BUILD]}?)?)?`);se("XRANGEPLAINLOOSE",`[v=\\s]*(${V[z.XRANGEIDENTIFIERLOOSE]})(?:\\.(${V[z.XRANGEIDENTIFIERLOOSE]})(?:\\.(${V[z.XRANGEIDENTIFIERLOOSE]})(?:${V[z.PRERELEASELOOSE]})?${V[z.BUILD]}?)?)?`);se("XRANGE",`^${V[z.GTLT]}\\s*${V[z.XRANGEPLAIN]}$`);se("XRANGELOOSE",`^${V[z.GTLT]}\\s*${V[z.XRANGEPLAINLOOSE]}$`);se("COERCEPLAIN",`(^|[^\\d])(\\d{1,${l_}})(?:\\.(\\d{1,${l_}}))?(?:\\.(\\d{1,${l_}}))?`);se("COERCE",`${V[z.COERCEPLAIN]}(?:$|[^\\d])`);se("COERCEFULL",V[z.COERCEPLAIN]+`(?:${V[z.PRERELEASE]})?(?:${V[z.BUILD]})?(?:$|[^\\d])`);se("COERCERTL",V[z.COERCE],!0);se("COERCERTLFULL",V[z.COERCEFULL],!0);se("LONETILDE","(?:~>?)");se("TILDETRIM",`(\\s*)${V[z.LONETILDE]}\\s+`,!0);Yn.tildeTrimReplace="$1~";se("TILDE",`^${V[z.LONETILDE]}${V[z.XRANGEPLAIN]}$`);se("TILDELOOSE",`^${V[z.LONETILDE]}${V[z.XRANGEPLAINLOOSE]}$`);se("LONECARET","(?:\\^)");se("CARETTRIM",`(\\s*)${V[z.LONECARET]}\\s+`,!0);Yn.caretTrimReplace="$1^";se("CARET",`^${V[z.LONECARET]}${V[z.XRANGEPLAIN]}$`);se("CARETLOOSE",`^${V[z.LONECARET]}${V[z.XRANGEPLAINLOOSE]}$`);se("COMPARATORLOOSE",`^${V[z.GTLT]}\\s*(${V[z.LOOSEPLAIN]})$|^$`);se("COMPARATOR",`^${V[z.GTLT]}\\s*(${V[z.FULLPLAIN]})$|^$`);se("COMPARATORTRIM",`(\\s*)${V[z.GTLT]}\\s*(${V[z.LOOSEPLAIN]}|${V[z.XRANGEPLAIN]})`,!0);Yn.comparatorTrimReplace="$1$2$3";se("HYPHENRANGE",`^\\s*(${V[z.XRANGEPLAIN]})\\s+-\\s+(${V[z.XRANGEPLAIN]})\\s*$`);se("HYPHENRANGELOOSE",`^\\s*(${V[z.XRANGEPLAINLOOSE]})\\s+-\\s+(${V[z.XRANGEPLAINLOOSE]})\\s*$`);se("STAR","(<|>)?=?\\s*\\*");se("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");se("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var W0=h(function(pKe,wL){var Eke=Object.freeze({loose:!0}),Ske=Object.freeze({}),$ke=(e)=>{if(!e)return Ske;if(typeof e!=="object")return Eke;return e};wL.exports=$ke});var f_=h(function(mKe,$L){var EL=/^[0-9]+$/,SL=(e,t)=>{if(typeof e==="number"&&typeof t==="number")return e===t?0:e<t?-1:1;let r=EL.test(e),n=EL.test(t);if(r&&n)e=+e,t=+t;return e===t?0:r&&!n?-1:n&&!r?1:e<t?-1:1},Cke=(e,t)=>SL(t,e);$L.exports={compareIdentifiers:SL,rcompareIdentifiers:Cke}});var qt=h(function(hKe,FL){var K0=Wl(),{MAX_LENGTH:CL,MAX_SAFE_INTEGER:Y0}=Gl(),{safeRe:J0,t:X0}=dc(),Fke=W0(),{compareIdentifiers:p_}=f_();class gn{constructor(e,t){if(t=Fke(t),e instanceof gn)if(e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease)return e;else e=e.version;else if(typeof e!=="string")throw TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`);if(e.length>CL)throw TypeError(`version is longer than ${CL} characters`);K0("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;let r=e.trim().match(t.loose?J0[X0.LOOSE]:J0[X0.FULL]);if(!r)throw TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+r[1],this.minor=+r[2],this.patch=+r[3],this.major>Y0||this.major<0)throw TypeError("Invalid major version");if(this.minor>Y0||this.minor<0)throw TypeError("Invalid minor version");if(this.patch>Y0||this.patch<0)throw TypeError("Invalid patch version");if(!r[4])this.prerelease=[];else this.prerelease=r[4].split(".").map((n)=>{if(/^[0-9]+$/.test(n)){let i=+n;if(i>=0&&i<Y0)return i}return n});this.build=r[5]?r[5].split("."):[],this.format()}format(){if(this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length)this.version+=`-${this.prerelease.join(".")}`;return this.version}toString(){return this.version}compare(e){if(K0("SemVer.compare",this.version,this.options,e),!(e instanceof gn)){if(typeof e==="string"&&e===this.version)return 0;e=new gn(e,this.options)}if(e.version===this.version)return 0;return this.compareMain(e)||this.comparePre(e)}compareMain(e){if(!(e instanceof gn))e=new gn(e,this.options);if(this.major<e.major)return-1;if(this.major>e.major)return 1;if(this.minor<e.minor)return-1;if(this.minor>e.minor)return 1;if(this.patch<e.patch)return-1;if(this.patch>e.patch)return 1;return 0}comparePre(e){if(!(e instanceof gn))e=new gn(e,this.options);if(this.prerelease.length&&!e.prerelease.length)return-1;else if(!this.prerelease.length&&e.prerelease.length)return 1;else if(!this.prerelease.length&&!e.prerelease.length)return 0;let t=0;do{let r=this.prerelease[t],n=e.prerelease[t];if(K0("prerelease compare",t,r,n),r===void 0&&n===void 0)return 0;else if(n===void 0)return 1;else if(r===void 0)return-1;else if(r===n)continue;else return p_(r,n)}while(++t)}compareBuild(e){if(!(e instanceof gn))e=new gn(e,this.options);let t=0;do{let r=this.build[t],n=e.build[t];if(K0("build compare",t,r,n),r===void 0&&n===void 0)return 0;else if(n===void 0)return 1;else if(r===void 0)return-1;else if(r===n)continue;else return p_(r,n)}while(++t)}inc(e,t,r){if(e.startsWith("pre")){if(!t&&r===!1)throw Error("invalid increment argument: identifier is empty");if(t){let n=`-${t}`.match(this.options.loose?J0[X0.PRERELEASELOOSE]:J0[X0.PRERELEASE]);if(!n||n[1]!==t)throw Error(`invalid identifier: ${t}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t,r);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t,r);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t,r),this.inc("pre",t,r);break;case"prerelease":if(this.prerelease.length===0)this.inc("patch",t,r);this.inc("pre",t,r);break;case"release":if(this.prerelease.length===0)throw Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":if(this.minor!==0||this.patch!==0||this.prerelease.length===0)this.major++;this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":if(this.patch!==0||this.prerelease.length===0)this.minor++;this.patch=0,this.prerelease=[];break;case"patch":if(this.prerelease.length===0)this.patch++;this.prerelease=[];break;case"pre":{let n=Number(r)?1:0;if(this.prerelease.length===0)this.prerelease=[n];else{let i=this.prerelease.length;while(--i>=0)if(typeof this.prerelease[i]==="number")this.prerelease[i]++,i=-2;if(i===-1){if(t===this.prerelease.join(".")&&r===!1)throw Error("invalid increment argument: identifier already exists");this.prerelease.push(n)}}if(t){let i=[t,n];if(r===!1)i=[t];if(p_(this.prerelease[0],t)===0){if(isNaN(this.prerelease[1]))this.prerelease=i}else this.prerelease=i}break}default:throw Error(`invalid increment argument: ${e}`)}if(this.raw=this.format(),this.build.length)this.raw+=`+${this.build.join(".")}`;return this}}FL.exports=gn});var Do=h(function(gKe,OL){var RL=qt(),Rke=(e,t,r=!1)=>{if(e instanceof RL)return e;try{return new RL(e,t)}catch(n){if(!r)return null;throw n}};OL.exports=Rke});var kL=h(function(yKe,AL){var Oke=Do(),Ake=(e,t)=>{let r=Oke(e,t);return r?r.version:null};AL.exports=Ake});var IL=h(function(xKe,PL){var kke=Do(),Pke=(e,t)=>{let r=kke(e.trim().replace(/^[=v]+/,""),t);return r?r.version:null};PL.exports=Pke});var qL=h(function(bKe,NL){var TL=qt(),Ike=(e,t,r,n,i)=>{if(typeof r==="string")i=n,n=r,r=void 0;try{return new TL(e instanceof TL?e.version:e,r).inc(t,n,i).version}catch(s){return null}};NL.exports=Ike});var BL=h(function(vKe,ML){var jL=Do(),Tke=(e,t)=>{let r=jL(e,null,!0),n=jL(t,null,!0),i=r.compare(n);if(i===0)return null;let s=i>0,o=s?r:n,a=s?n:r,c=!!o.prerelease.length;if(!!a.prerelease.length&&!c){if(!a.patch&&!a.minor)return"major";if(a.compareMain(o)===0){if(a.minor&&!a.patch)return"minor";return"patch"}}let d=c?"pre":"";if(r.major!==n.major)return d+"major";if(r.minor!==n.minor)return d+"minor";if(r.patch!==n.patch)return d+"patch";return"prerelease"};ML.exports=Tke});var UL=h(function(_Ke,LL){var Nke=qt(),qke=(e,t)=>new Nke(e,t).major;LL.exports=qke});var zL=h(function(DKe,VL){var jke=qt(),Mke=(e,t)=>new jke(e,t).minor;VL.exports=Mke});var GL=h(function(wKe,HL){var Bke=qt(),Lke=(e,t)=>new Bke(e,t).patch;HL.exports=Lke});var KL=h(function(EKe,WL){var Uke=Do(),Vke=(e,t)=>{let r=Uke(e,t);return r&&r.prerelease.length?r.prerelease:null};WL.exports=Vke});var Hr=h(function(SKe,JL){var YL=qt(),zke=(e,t,r)=>new YL(e,r).compare(new YL(t,r));JL.exports=zke});var QL=h(function($Ke,XL){var Hke=Hr(),Gke=(e,t,r)=>Hke(t,e,r);XL.exports=Gke});var eU=h(function(CKe,ZL){var Wke=Hr(),Kke=(e,t)=>Wke(e,t,!0);ZL.exports=Kke});var Q0=h(function(FKe,rU){var tU=qt(),Yke=(e,t,r)=>{let n=new tU(e,r),i=new tU(t,r);return n.compare(i)||n.compareBuild(i)};rU.exports=Yke});var iU=h(function(RKe,nU){var Jke=Q0(),Xke=(e,t)=>e.sort((r,n)=>Jke(r,n,t));nU.exports=Xke});var oU=h(function(OKe,sU){var Qke=Q0(),Zke=(e,t)=>e.sort((r,n)=>Qke(n,r,t));sU.exports=Zke});var Kl=h(function(AKe,aU){var e8e=Hr(),t8e=(e,t,r)=>e8e(e,t,r)>0;aU.exports=t8e});var Z0=h(function(kKe,cU){var r8e=Hr(),n8e=(e,t,r)=>r8e(e,t,r)<0;cU.exports=n8e});var m_=h(function(PKe,uU){var i8e=Hr(),s8e=(e,t,r)=>i8e(e,t,r)===0;uU.exports=s8e});var h_=h(function(IKe,lU){var o8e=Hr(),a8e=(e,t,r)=>o8e(e,t,r)!==0;lU.exports=a8e});var em=h(function(TKe,dU){var c8e=Hr(),u8e=(e,t,r)=>c8e(e,t,r)>=0;dU.exports=u8e});var tm=h(function(NKe,fU){var l8e=Hr(),d8e=(e,t,r)=>l8e(e,t,r)<=0;fU.exports=d8e});var g_=h(function(qKe,pU){var f8e=m_(),p8e=h_(),m8e=Kl(),h8e=em(),g8e=Z0(),y8e=tm(),x8e=(e,t,r,n)=>{switch(t){case"===":if(typeof e==="object")e=e.version;if(typeof r==="object")r=r.version;return e===r;case"!==":if(typeof e==="object")e=e.version;if(typeof r==="object")r=r.version;return e!==r;case"":case"=":case"==":return f8e(e,r,n);case"!=":return p8e(e,r,n);case">":return m8e(e,r,n);case">=":return h8e(e,r,n);case"<":return g8e(e,r,n);case"<=":return y8e(e,r,n);default:throw TypeError(`Invalid operator: ${t}`)}};pU.exports=x8e});var hU=h(function(jKe,mU){var b8e=qt(),v8e=Do(),{safeRe:rm,t:nm}=dc(),_8e=(e,t)=>{if(e instanceof b8e)return e;if(typeof e==="number")e=String(e);if(typeof e!=="string")return null;t=t||{};let r=null;if(!t.rtl)r=e.match(t.includePrerelease?rm[nm.COERCEFULL]:rm[nm.COERCE]);else{let c=t.includePrerelease?rm[nm.COERCERTLFULL]:rm[nm.COERCERTL],l;while((l=c.exec(e))&&(!r||r.index+r[0].length!==e.length)){if(!r||l.index+l[0].length!==r.index+r[0].length)r=l;c.lastIndex=l.index+l[1].length+l[2].length}c.lastIndex=-1}if(r===null)return null;let n=r[2],i=r[3]||"0",s=r[4]||"0",o=t.includePrerelease&&r[5]?`-${r[5]}`:"",a=t.includePrerelease&&r[6]?`+${r[6]}`:"";return v8e(`${n}.${i}.${s}${o}${a}`,t)};mU.exports=_8e});var xU=h(function(MKe,yU){class gU{constructor(){this.max=1000,this.map=new Map}get(e){let t=this.map.get(e);if(t===void 0)return;else return this.map.delete(e),this.map.set(e,t),t}delete(e){return this.map.delete(e)}set(e,t){if(!this.delete(e)&&t!==void 0){if(this.map.size>=this.max){let n=this.map.keys().next().value;this.delete(n)}this.map.set(e,t)}return this}}yU.exports=gU});var Gr=h(function(BKe,DU){var D8e=/\s+/g;class Yl{constructor(e,t){if(t=E8e(t),e instanceof Yl)if(e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease)return e;else return new Yl(e.raw,t);if(e instanceof y_)return this.raw=e.value,this.set=[[e]],this.formatted=void 0,this;if(this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease,this.raw=e.trim().replace(D8e," "),this.set=this.raw.split("||").map((r)=>this.parseRange(r.trim())).filter((r)=>r.length),!this.set.length)throw TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let r=this.set[0];if(this.set=this.set.filter((n)=>!vU(n[0])),this.set.length===0)this.set=[r];else if(this.set.length>1){for(let n of this.set)if(n.length===1&&A8e(n[0])){this.set=[n];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let e=0;e<this.set.length;e++){if(e>0)this.formatted+="||";let t=this.set[e];for(let r=0;r<t.length;r++){if(r>0)this.formatted+=" ";this.formatted+=t[r].toString().trim()}}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){let r=((this.options.includePrerelease&&R8e)|(this.options.loose&&O8e))+":"+e,n=bU.get(r);if(n)return n;let i=this.options.loose,s=i?Jt[jt.HYPHENRANGELOOSE]:Jt[jt.HYPHENRANGE];e=e.replace(s,L8e(this.options.includePrerelease)),Xe("hyphen replace",e),e=e.replace(Jt[jt.COMPARATORTRIM],$8e),Xe("comparator trim",e),e=e.replace(Jt[jt.TILDETRIM],C8e),Xe("tilde trim",e),e=e.replace(Jt[jt.CARETTRIM],F8e),Xe("caret trim",e);let o=e.split(" ").map((d)=>k8e(d,this.options)).join(" ").split(/\s+/).map((d)=>B8e(d,this.options));if(i)o=o.filter((d)=>(Xe("loose invalid filter",d,this.options),!!d.match(Jt[jt.COMPARATORLOOSE])));Xe("range list",o);let a=new Map,c=o.map((d)=>new y_(d,this.options));for(let d of c){if(vU(d))return[d];a.set(d.value,d)}if(a.size>1&&a.has(""))a.delete("");let l=[...a.values()];return bU.set(r,l),l}intersects(e,t){if(!(e instanceof Yl))throw TypeError("a Range is required");return this.set.some((r)=>_U(r,t)&&e.set.some((n)=>_U(n,t)&&r.every((i)=>n.every((s)=>i.intersects(s,t)))))}test(e){if(!e)return!1;if(typeof e==="string")try{e=new S8e(e,this.options)}catch(t){return!1}for(let t=0;t<this.set.length;t++)if(U8e(this.set[t],e,this.options))return!0;return!1}}DU.exports=Yl;var w8e=xU(),bU=new w8e,E8e=W0(),y_=Jl(),Xe=Wl(),S8e=qt(),{safeRe:Jt,t:jt,comparatorTrimReplace:$8e,tildeTrimReplace:C8e,caretTrimReplace:F8e}=dc(),{FLAG_INCLUDE_PRERELEASE:R8e,FLAG_LOOSE:O8e}=Gl(),vU=(e)=>e.value==="<0.0.0-0",A8e=(e)=>e.value==="",_U=(e,t)=>{let r=!0,n=e.slice(),i=n.pop();while(r&&n.length)r=n.every((s)=>i.intersects(s,t)),i=n.pop();return r},k8e=(e,t)=>(e=e.replace(Jt[jt.BUILD],""),Xe("comp",e,t),e=T8e(e,t),Xe("caret",e),e=P8e(e,t),Xe("tildes",e),e=q8e(e,t),Xe("xrange",e),e=M8e(e,t),Xe("stars",e),e),Xt=(e)=>!e||e.toLowerCase()==="x"||e==="*",P8e=(e,t)=>e.trim().split(/\s+/).map((r)=>I8e(r,t)).join(" "),I8e=(e,t)=>{let r=t.loose?Jt[jt.TILDELOOSE]:Jt[jt.TILDE];return e.replace(r,(n,i,s,o,a)=>{Xe("tilde",e,n,i,s,o,a);let c;if(Xt(i))c="";else if(Xt(s))c=`>=${i}.0.0 <${+i+1}.0.0-0`;else if(Xt(o))c=`>=${i}.${s}.0 <${i}.${+s+1}.0-0`;else if(a)Xe("replaceTilde pr",a),c=`>=${i}.${s}.${o}-${a} <${i}.${+s+1}.0-0`;else c=`>=${i}.${s}.${o} <${i}.${+s+1}.0-0`;return Xe("tilde return",c),c})},T8e=(e,t)=>e.trim().split(/\s+/).map((r)=>N8e(r,t)).join(" "),N8e=(e,t)=>{Xe("caret",e,t);let r=t.loose?Jt[jt.CARETLOOSE]:Jt[jt.CARET],n=t.includePrerelease?"-0":"";return e.replace(r,(i,s,o,a,c)=>{Xe("caret",e,i,s,o,a,c);let l;if(Xt(s))l="";else if(Xt(o))l=`>=${s}.0.0${n} <${+s+1}.0.0-0`;else if(Xt(a))if(s==="0")l=`>=${s}.${o}.0${n} <${s}.${+o+1}.0-0`;else l=`>=${s}.${o}.0${n} <${+s+1}.0.0-0`;else if(c)if(Xe("replaceCaret pr",c),s==="0")if(o==="0")l=`>=${s}.${o}.${a}-${c} <${s}.${o}.${+a+1}-0`;else l=`>=${s}.${o}.${a}-${c} <${s}.${+o+1}.0-0`;else l=`>=${s}.${o}.${a}-${c} <${+s+1}.0.0-0`;else if(Xe("no pr"),s==="0")if(o==="0")l=`>=${s}.${o}.${a}${n} <${s}.${o}.${+a+1}-0`;else l=`>=${s}.${o}.${a}${n} <${s}.${+o+1}.0-0`;else l=`>=${s}.${o}.${a} <${+s+1}.0.0-0`;return Xe("caret return",l),l})},q8e=(e,t)=>(Xe("replaceXRanges",e,t),e.split(/\s+/).map((r)=>j8e(r,t)).join(" ")),j8e=(e,t)=>{e=e.trim();let r=t.loose?Jt[jt.XRANGELOOSE]:Jt[jt.XRANGE];return e.replace(r,(n,i,s,o,a,c)=>{Xe("xRange",e,n,i,s,o,a,c);let l=Xt(s),d=l||Xt(o),f=d||Xt(a),m=f;if(i==="="&&m)i="";if(c=t.includePrerelease?"-0":"",l)if(i===">"||i==="<")n="<0.0.0-0";else n="*";else if(i&&m){if(d)o=0;if(a=0,i===">")if(i=">=",d)s=+s+1,o=0,a=0;else o=+o+1,a=0;else if(i==="<=")if(i="<",d)s=+s+1;else o=+o+1;if(i==="<")c="-0";n=`${i+s}.${o}.${a}${c}`}else if(d)n=`>=${s}.0.0${c} <${+s+1}.0.0-0`;else if(f)n=`>=${s}.${o}.0${c} <${s}.${+o+1}.0-0`;return Xe("xRange return",n),n})},M8e=(e,t)=>(Xe("replaceStars",e,t),e.trim().replace(Jt[jt.STAR],"")),B8e=(e,t)=>(Xe("replaceGTE0",e,t),e.trim().replace(Jt[t.includePrerelease?jt.GTE0PRE:jt.GTE0],"")),L8e=(e)=>(t,r,n,i,s,o,a,c,l,d,f,m)=>{if(Xt(n))r="";else if(Xt(i))r=`>=${n}.0.0${e?"-0":""}`;else if(Xt(s))r=`>=${n}.${i}.0${e?"-0":""}`;else if(o)r=`>=${r}`;else r=`>=${r}${e?"-0":""}`;if(Xt(l))c="";else if(Xt(d))c=`<${+l+1}.0.0-0`;else if(Xt(f))c=`<${l}.${+d+1}.0-0`;else if(m)c=`<=${l}.${d}.${f}-${m}`;else if(e)c=`<${l}.${d}.${+f+1}-0`;else c=`<=${c}`;return`${r} ${c}`.trim()},U8e=(e,t,r)=>{for(let n=0;n<e.length;n++)if(!e[n].test(t))return!1;if(t.prerelease.length&&!r.includePrerelease){for(let n=0;n<e.length;n++){if(Xe(e[n].semver),e[n].semver===y_.ANY)continue;if(e[n].semver.prerelease.length>0){let i=e[n].semver;if(i.major===t.major&&i.minor===t.minor&&i.patch===t.patch)return!0}}return!1}return!0}});var Jl=h(function(LKe,FU){var Xl=Symbol("SemVer ANY");class im{static get ANY(){return Xl}constructor(e,t){if(t=wU(t),e instanceof im)if(e.loose===!!t.loose)return e;else e=e.value;if(e=e.trim().split(/\s+/).join(" "),b_("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===Xl)this.value="";else this.value=this.operator+this.semver.version;b_("comp",this)}parse(e){let t=this.options.loose?EU[SU.COMPARATORLOOSE]:EU[SU.COMPARATOR],r=e.match(t);if(!r)throw TypeError(`Invalid comparator: ${e}`);if(this.operator=r[1]!==void 0?r[1]:"",this.operator==="=")this.operator="";if(!r[2])this.semver=Xl;else this.semver=new $U(r[2],this.options.loose)}toString(){return this.value}test(e){if(b_("Comparator.test",e,this.options.loose),this.semver===Xl||e===Xl)return!0;if(typeof e==="string")try{e=new $U(e,this.options)}catch(t){return!1}return x_(e,this.operator,this.semver,this.options)}intersects(e,t){if(!(e instanceof im))throw TypeError("a Comparator is required");if(this.operator===""){if(this.value==="")return!0;return new CU(e.value,t).test(this.value)}else if(e.operator===""){if(e.value==="")return!0;return new CU(this.value,t).test(e.semver)}if(t=wU(t),t.includePrerelease&&(this.value==="<0.0.0-0"||e.value==="<0.0.0-0"))return!1;if(!t.includePrerelease&&(this.value.startsWith("<0.0.0")||e.value.startsWith("<0.0.0")))return!1;if(this.operator.startsWith(">")&&e.operator.startsWith(">"))return!0;if(this.operator.startsWith("<")&&e.operator.startsWith("<"))return!0;if(this.semver.version===e.semver.version&&this.operator.includes("=")&&e.operator.includes("="))return!0;if(x_(this.semver,"<",e.semver,t)&&this.operator.startsWith(">")&&e.operator.startsWith("<"))return!0;if(x_(this.semver,">",e.semver,t)&&this.operator.startsWith("<")&&e.operator.startsWith(">"))return!0;return!1}}FU.exports=im;var wU=W0(),{safeRe:EU,t:SU}=dc(),x_=g_(),b_=Wl(),$U=qt(),CU=Gr()});var Ql=h(function(UKe,RU){var V8e=Gr(),z8e=(e,t,r)=>{try{t=new V8e(t,r)}catch(n){return!1}return t.test(e)};RU.exports=z8e});var AU=h(function(VKe,OU){var H8e=Gr(),G8e=(e,t)=>new H8e(e,t).set.map((r)=>r.map((n)=>n.value).join(" ").trim().split(" "));OU.exports=G8e});var PU=h(function(zKe,kU){var W8e=qt(),K8e=Gr(),Y8e=(e,t,r)=>{let n=null,i=null,s=null;try{s=new K8e(t,r)}catch(o){return null}return e.forEach((o)=>{if(s.test(o)){if(!n||i.compare(o)===-1)n=o,i=new W8e(n,r)}}),n};kU.exports=Y8e});var TU=h(function(HKe,IU){var J8e=qt(),X8e=Gr(),Q8e=(e,t,r)=>{let n=null,i=null,s=null;try{s=new X8e(t,r)}catch(o){return null}return e.forEach((o)=>{if(s.test(o)){if(!n||i.compare(o)===1)n=o,i=new J8e(n,r)}}),n};IU.exports=Q8e});var jU=h(function(GKe,qU){var v_=qt(),Z8e=Gr(),NU=Kl(),ePe=(e,t)=>{e=new Z8e(e,t);let r=new v_("0.0.0");if(e.test(r))return r;if(r=new v_("0.0.0-0"),e.test(r))return r;r=null;for(let n=0;n<e.set.length;++n){let i=e.set[n],s=null;if(i.forEach((o)=>{let a=new v_(o.semver.version);switch(o.operator){case">":if(a.prerelease.length===0)a.patch++;else a.prerelease.push(0);a.raw=a.format();case"":case">=":if(!s||NU(a,s))s=a;break;case"<":case"<=":break;default:throw Error(`Unexpected operation: ${o.operator}`)}}),s&&(!r||NU(r,s)))r=s}if(r&&e.test(r))return r;return null};qU.exports=ePe});var BU=h(function(WKe,MU){var tPe=Gr(),rPe=(e,t)=>{try{return new tPe(e,t).range||"*"}catch(r){return null}};MU.exports=rPe});var sm=h(function(KKe,zU){var nPe=qt(),VU=Jl(),{ANY:iPe}=VU,sPe=Gr(),oPe=Ql(),LU=Kl(),UU=Z0(),aPe=tm(),cPe=em(),uPe=(e,t,r,n)=>{e=new nPe(e,n),t=new sPe(t,n);let i,s,o,a,c;switch(r){case">":i=LU,s=aPe,o=UU,a=">",c=">=";break;case"<":i=UU,s=cPe,o=LU,a="<",c="<=";break;default:throw TypeError('Must provide a hilo val of "<" or ">"')}if(oPe(e,t,n))return!1;for(let l=0;l<t.set.length;++l){let d=t.set[l],f=null,m=null;if(d.forEach((p)=>{if(p.semver===iPe)p=new VU(">=0.0.0");if(f=f||p,m=m||p,i(p.semver,f.semver,n))f=p;else if(o(p.semver,m.semver,n))m=p}),f.operator===a||f.operator===c)return!1;if((!m.operator||m.operator===a)&&s(e,m.semver))return!1;else if(m.operator===c&&o(e,m.semver))return!1}return!0};zU.exports=uPe});var GU=h(function(YKe,HU){var lPe=sm(),dPe=(e,t,r)=>lPe(e,t,">",r);HU.exports=dPe});var KU=h(function(JKe,WU){var fPe=sm(),pPe=(e,t,r)=>fPe(e,t,"<",r);WU.exports=pPe});var XU=h(function(XKe,JU){var YU=Gr(),mPe=(e,t,r)=>(e=new YU(e,r),t=new YU(t,r),e.intersects(t,r));JU.exports=mPe});var ZU=h(function(QKe,QU){var hPe=Ql(),gPe=Hr();QU.exports=(e,t,r)=>{let n=[],i=null,s=null,o=e.sort((d,f)=>gPe(d,f,r));for(let d of o)if(hPe(d,t,r)){if(s=d,!i)i=d}else{if(s)n.push([i,s]);s=null,i=null}if(i)n.push([i,null]);let a=[];for(let[d,f]of n)if(d===f)a.push(d);else if(!f&&d===o[0])a.push("*");else if(!f)a.push(`>=${d}`);else if(d===o[0])a.push(`<=${f}`);else a.push(`${d} - ${f}`);let c=a.join(" || "),l=typeof t.raw==="string"?t.raw:String(t);return c.length<l.length?c:t}});var sV=h(function(ZKe,iV){var eV=Gr(),D_=Jl(),{ANY:__}=D_,Zl=Ql(),w_=Hr(),yPe=(e,t,r={})=>{if(e===t)return!0;e=new eV(e,r),t=new eV(t,r);let n=!1;e:for(let i of e.set){for(let s of t.set){let o=bPe(i,s,r);if(n=n||o!==null,o)continue e}if(n)return!1}return!0},xPe=[new D_(">=0.0.0-0")],tV=[new D_(">=0.0.0")],bPe=(e,t,r)=>{if(e===t)return!0;if(e.length===1&&e[0].semver===__)if(t.length===1&&t[0].semver===__)return!0;else if(r.includePrerelease)e=xPe;else e=tV;if(t.length===1&&t[0].semver===__)if(r.includePrerelease)return!0;else t=tV;let n=new Set,i,s;for(let p of e)if(p.operator===">"||p.operator===">=")i=rV(i,p,r);else if(p.operator==="<"||p.operator==="<=")s=nV(s,p,r);else n.add(p.semver);if(n.size>1)return null;let o;if(i&&s){if(o=w_(i.semver,s.semver,r),o>0)return null;else if(o===0&&(i.operator!==">="||s.operator!=="<="))return null}for(let p of n){if(i&&!Zl(p,String(i),r))return null;if(s&&!Zl(p,String(s),r))return null;for(let g of t)if(!Zl(p,String(g),r))return!1;return!0}let a,c,l,d,f=s&&!r.includePrerelease&&s.semver.prerelease.length?s.semver:!1,m=i&&!r.includePrerelease&&i.semver.prerelease.length?i.semver:!1;if(f&&f.prerelease.length===1&&s.operator==="<"&&f.prerelease[0]===0)f=!1;for(let p of t){if(d=d||p.operator===">"||p.operator===">=",l=l||p.operator==="<"||p.operator==="<=",i){if(m){if(p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===m.major&&p.semver.minor===m.minor&&p.semver.patch===m.patch)m=!1}if(p.operator===">"||p.operator===">="){if(a=rV(i,p,r),a===p&&a!==i)return!1}else if(i.operator===">="&&!Zl(i.semver,String(p),r))return!1}if(s){if(f){if(p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===f.major&&p.semver.minor===f.minor&&p.semver.patch===f.patch)f=!1}if(p.operator==="<"||p.operator==="<="){if(c=nV(s,p,r),c===p&&c!==s)return!1}else if(s.operator==="<="&&!Zl(s.semver,String(p),r))return!1}if(!p.operator&&(s||i)&&o!==0)return!1}if(i&&l&&!s&&o!==0)return!1;if(s&&d&&!i&&o!==0)return!1;if(m||f)return!1;return!0},rV=(e,t,r)=>{if(!e)return t;let n=w_(e.semver,t.semver,r);return n>0?e:n<0?t:t.operator===">"&&e.operator===">="?t:e},nV=(e,t,r)=>{if(!e)return t;let n=w_(e.semver,t.semver,r);return n<0?e:n>0?t:t.operator==="<"&&e.operator==="<="?t:e};iV.exports=yPe});var uV=h(function(eYe,cV){var E_=dc(),oV=Gl(),vPe=qt(),aV=f_(),_Pe=Do(),DPe=kL(),wPe=IL(),EPe=qL(),SPe=BL(),$Pe=UL(),CPe=zL(),FPe=GL(),RPe=KL(),OPe=Hr(),APe=QL(),kPe=eU(),PPe=Q0(),IPe=iU(),TPe=oU(),NPe=Kl(),qPe=Z0(),jPe=m_(),MPe=h_(),BPe=em(),LPe=tm(),UPe=g_(),VPe=hU(),zPe=Jl(),HPe=Gr(),GPe=Ql(),WPe=AU(),KPe=PU(),YPe=TU(),JPe=jU(),XPe=BU(),QPe=sm(),ZPe=GU(),e4e=KU(),t4e=XU(),r4e=ZU(),n4e=sV();cV.exports={parse:_Pe,valid:DPe,clean:wPe,inc:EPe,diff:SPe,major:$Pe,minor:CPe,patch:FPe,prerelease:RPe,compare:OPe,rcompare:APe,compareLoose:kPe,compareBuild:PPe,sort:IPe,rsort:TPe,gt:NPe,lt:qPe,eq:jPe,neq:MPe,gte:BPe,lte:LPe,cmp:UPe,coerce:VPe,Comparator:zPe,Range:HPe,satisfies:GPe,toComparators:WPe,maxSatisfying:KPe,minSatisfying:YPe,minVersion:JPe,validRange:XPe,outside:QPe,gtr:ZPe,ltr:e4e,intersects:t4e,simplifyRange:r4e,subset:n4e,SemVer:vPe,re:E_.re,src:E_.src,tokens:E_.t,SEMVER_SPEC_VERSION:oV.SEMVER_SPEC_VERSION,RELEASE_TYPES:oV.RELEASE_TYPES,compareIdentifiers:aV.compareIdentifiers,rcompareIdentifiers:aV.rcompareIdentifiers}});function dV(e,t,r){if(!e)return!1;if(e.constructor===t)return!0;return i4e.call(e)===r}function fV(e){return dV(e,Uint8Array,"[object Uint8Array]")}function s4e(e){return dV(e,ArrayBuffer,"[object ArrayBuffer]")}function o4e(e){return fV(e)||s4e(e)}function a4e(e){if(!fV(e))throw TypeError(`Expected \`Uint8Array\`, got \`${typeof e}\``)}function c4e(e){if(!o4e(e))throw TypeError(`Expected \`Uint8Array\` or \`ArrayBuffer\`, got \`${typeof e}\``)}function S_(e,t){if(e.length===0)return new Uint8Array(0);t??=e.reduce((i,s)=>i+s.length,0);let r=new Uint8Array(t),n=0;for(let i of e)a4e(i),r.set(i,n),n+=i.length;return r}function $_(e,t="utf8"){return c4e(e),lV[t]??=new globalThis.TextDecoder(t),lV[t].decode(e)}function u4e(e){if(typeof e!=="string")throw TypeError(`Expected \`string\`, got \`${typeof e}\``)}function om(e){return u4e(e),l4e.encode(e)}var i4e,lV,l4e,tYe;var pV=A(()=>{i4e=Object.prototype.toString;lV={utf8:new globalThis.TextDecoder("utf8")};l4e=new globalThis.TextEncoder;tYe=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"))});import{isDeepStrictEqual as d4e}from"util";import mV from"process";import wo from"fs";import hV from"path";import ed from"crypto";import f4e from"assert";var yV,xV,Eo,p4e,gV="aes-256-cbc",fc=()=>Object.create(null),m4e=(e)=>e!==void 0&&e!==null,h4e=(e,t)=>{let r=new Set(["undefined","symbol","function"]),n=typeof t;if(r.has(n))throw TypeError(`Setting a value of type \`${n}\` for key \`${e}\` is not allowed as it's not supported by JSON`)},am="__internal__",C_,cm;var bV=A(()=>{CI();RI();sT();bL();pV();yV=ne(rq(),1),xV=ne(xL(),1),Eo=ne(uV(),1),p4e=xV.default.default,C_=`${am}.migrations.version`;cm=class cm{path;events;#r;#t;#e;#i={};constructor(e={}){let t={configName:"config",fileExtension:"json",projectSuffix:"nodejs",clearInvalidConfig:!1,accessPropertiesByDotNotation:!0,configFileMode:438,...e};if(!t.cwd){if(!t.projectName)throw Error("Please specify the `projectName` option.");t.cwd=nb(t.projectName,{suffix:t.projectSuffix}).config}if(this.#e=t,t.schema??t.ajvOptions??t.rootSchema){if(t.schema&&typeof t.schema!=="object")throw TypeError("The `schema` option must be an object.");let s=new yV.Ajv2020({allErrors:!0,useDefaults:!0,...t.ajvOptions});p4e(s);let o={...t.rootSchema,type:"object",properties:t.schema};this.#r=s.compile(o);for(let[a,c]of Object.entries(t.schema??{}))if(c?.default)this.#i[a]=c.default}if(t.defaults)this.#i={...this.#i,...t.defaults};if(t.serialize)this._serialize=t.serialize;if(t.deserialize)this._deserialize=t.deserialize;this.events=new EventTarget,this.#t=t.encryptionKey;let r=t.fileExtension?`.${t.fileExtension}`:"";this.path=hV.resolve(t.cwd,`${t.configName??"config"}${r}`);let n=this.store,i=Object.assign(fc(),t.defaults,n);if(t.migrations){if(!t.projectVersion)throw Error("Please specify the `projectVersion` option.");this._migrate(t.migrations,t.projectVersion,t.beforeEachMigration)}this._validate(i);try{f4e.deepEqual(n,i)}catch{this.store=i}if(t.watch)this._watch()}get(e,t){if(this.#e.accessPropertiesByDotNotation)return this._get(e,t);let{store:r}=this;return e in r?r[e]:t}set(e,t){if(typeof e!=="string"&&typeof e!=="object")throw TypeError(`Expected \`key\` to be of type \`string\` or \`object\`, got ${typeof e}`);if(typeof e!=="object"&&t===void 0)throw TypeError("Use `delete()` to clear values");if(this._containsReservedKey(e))throw TypeError(`Please don't use the ${am} key, as it's used to manage this module internal operations.`);let{store:r}=this,n=(i,s)=>{if(h4e(i,s),this.#e.accessPropertiesByDotNotation)eb(r,i,s);else r[i]=s};if(typeof e==="object"){let i=e;for(let[s,o]of Object.entries(i))n(s,o)}else n(e,t);this.store=r}has(e){if(this.#e.accessPropertiesByDotNotation)return $I(this.store,e);return e in this.store}reset(...e){for(let t of e)if(m4e(this.#i[t]))this.set(t,this.#i[t])}delete(e){let{store:t}=this;if(this.#e.accessPropertiesByDotNotation)SI(t,e);else delete t[e];this.store=t}clear(){this.store=fc();for(let e of Object.keys(this.#i))this.reset(e)}onDidChange(e,t){if(typeof e!=="string")throw TypeError(`Expected \`key\` to be of type \`string\`, got ${typeof e}`);if(typeof t!=="function")throw TypeError(`Expected \`callback\` to be of type \`function\`, got ${typeof t}`);return this._handleChange(()=>this.get(e),t)}onDidAnyChange(e){if(typeof e!=="function")throw TypeError(`Expected \`callback\` to be of type \`function\`, got ${typeof e}`);return this._handleChange(()=>this.store,e)}get size(){return Object.keys(this.store).length}get store(){try{let e=wo.readFileSync(this.path,this.#t?null:"utf8"),t=this._encryptData(e),r=this._deserialize(t);return this._validate(r),Object.assign(fc(),r)}catch(e){if(e?.code==="ENOENT")return this._ensureDirectory(),fc();if(this.#e.clearInvalidConfig&&e.name==="SyntaxError")return fc();throw e}}set store(e){this._ensureDirectory(),this._validate(e),this._write(e),this.events.dispatchEvent(new Event("change"))}*[Symbol.iterator](){for(let[e,t]of Object.entries(this.store))yield[e,t]}_encryptData(e){if(!this.#t)return typeof e==="string"?e:$_(e);try{let t=e.slice(0,16),r=ed.pbkdf2Sync(this.#t,t.toString(),1e4,32,"sha512"),n=ed.createDecipheriv(gV,r,t),i=e.slice(17),s=typeof i==="string"?om(i):i;return $_(S_([n.update(s),n.final()]))}catch{}return e.toString()}_handleChange(e,t){let r=e(),n=()=>{let i=r,s=e();if(d4e(s,i))return;r=s,t.call(this,s,i)};return this.events.addEventListener("change",n),()=>{this.events.removeEventListener("change",n)}}_deserialize=(e)=>JSON.parse(e);_serialize=(e)=>JSON.stringify(e,void 0,"\t");_validate(e){if(!this.#r)return;if(this.#r(e)||!this.#r.errors)return;let r=this.#r.errors.map(({instancePath:n,message:i=""})=>`\`${n.slice(1)}\` ${i}`);throw Error("Config schema violation: "+r.join("; "))}_ensureDirectory(){wo.mkdirSync(hV.dirname(this.path),{recursive:!0})}_write(e){let t=this._serialize(e);if(this.#t){let r=ed.randomBytes(16),n=ed.pbkdf2Sync(this.#t,r.toString(),1e4,32,"sha512"),i=ed.createCipheriv(gV,n,r);t=S_([r,om(":"),i.update(om(t)),i.final()])}if(mV.env.SNAP)wo.writeFileSync(this.path,t,{mode:this.#e.configFileMode});else try{mb(this.path,t,{mode:this.#e.configFileMode})}catch(r){if(r?.code==="EXDEV"){wo.writeFileSync(this.path,t,{mode:this.#e.configFileMode});return}throw r}}_watch(){if(this._ensureDirectory(),!wo.existsSync(this.path))this._write(fc());if(mV.platform==="win32")wo.watch(this.path,{persistent:!1},u_(()=>{this.events.dispatchEvent(new Event("change"))},{wait:100}));else wo.watchFile(this.path,{persistent:!1},u_(()=>{this.events.dispatchEvent(new Event("change"))},{wait:5000}))}_migrate(e,t,r){let n=this._get(C_,"0.0.0"),i=Object.keys(e).filter((o)=>this._shouldPerformMigration(o,n,t)),s={...this.store};for(let o of i)try{if(r)r(this,{fromVersion:n,toVersion:o,finalVersion:t,versions:i});let a=e[o];a?.(this),this._set(C_,o),n=o,s={...this.store}}catch(a){throw this.store=s,Error(`Something went wrong during the migration! Changes applied to the store until this failed migration will be restored. ${a}`)}if(this._isVersionInRangeFormat(n)||!Eo.default.eq(n,t))this._set(C_,t)}_containsReservedKey(e){if(typeof e==="object"){if(Object.keys(e)[0]===am)return!0}if(typeof e!=="string")return!1;if(this.#e.accessPropertiesByDotNotation){if(e.startsWith(`${am}.`))return!0;return!1}return!1}_isVersionInRangeFormat(e){return Eo.default.clean(e)===null}_shouldPerformMigration(e,t,r){if(this._isVersionInRangeFormat(e)){if(t!=="0.0.0"&&Eo.default.satisfies(t,e))return!1;return Eo.default.satisfies(r,e)}if(Eo.default.lte(e,t))return!1;if(Eo.default.gt(e,r))return!1;return!0}_get(e,t){return EI(this.store,e,t)}_set(e,t){let{store:r}=this;eb(r,e,t),this.store=r}}});var be,F_,N,Jn=(e)=>{switch(typeof e){case"undefined":return N.undefined;case"string":return N.string;case"number":return Number.isNaN(e)?N.nan:N.number;case"boolean":return N.boolean;case"function":return N.function;case"bigint":return N.bigint;case"symbol":return N.symbol;case"object":if(Array.isArray(e))return N.array;if(e===null)return N.null;if(e.then&&typeof e.then==="function"&&e.catch&&typeof e.catch==="function")return N.promise;if(typeof Map<"u"&&e instanceof Map)return N.map;if(typeof Set<"u"&&e instanceof Set)return N.set;if(typeof Date<"u"&&e instanceof Date)return N.date;return N.object;default:return N.unknown}};var td=A(()=>{(function(e){e.assertEqual=(i)=>{};function t(i){}e.assertIs=t;function r(i){throw Error()}e.assertNever=r,e.arrayToEnum=(i)=>{let s={};for(let o of i)s[o]=o;return s},e.getValidEnumValues=(i)=>{let s=e.objectKeys(i).filter((a)=>typeof i[i[a]]!=="number"),o={};for(let a of s)o[a]=i[a];return e.objectValues(o)},e.objectValues=(i)=>e.objectKeys(i).map(function(s){return i[s]}),e.objectKeys=typeof Object.keys==="function"?(i)=>Object.keys(i):(i)=>{let s=[];for(let o in i)if(Object.prototype.hasOwnProperty.call(i,o))s.push(o);return s},e.find=(i,s)=>{for(let o of i)if(s(o))return o;return},e.isInteger=typeof Number.isInteger==="function"?(i)=>Number.isInteger(i):(i)=>typeof i==="number"&&Number.isFinite(i)&&Math.floor(i)===i;function n(i,s=" | "){return i.map((o)=>typeof o==="string"?`'${o}'`:o).join(s)}e.joinValues=n,e.jsonStringifyReplacer=(i,s)=>{if(typeof s==="bigint")return s.toString();return s}})(be||(be={}));(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(F_||(F_={}));N=be.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"])});var P,g4e=(e)=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),hr;var um=A(()=>{td();P=be.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"]);hr=class hr extends Error{get errors(){return this.issues}constructor(e){super();this.issues=[],this.addIssue=(r)=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};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(i){return i.message},r={_errors:[]},n=(i)=>{for(let s of i.issues)if(s.code==="invalid_union")s.unionErrors.map(n);else if(s.code==="invalid_return_type")n(s.returnTypeError);else if(s.code==="invalid_arguments")n(s.argumentsError);else if(s.path.length===0)r._errors.push(t(s));else{let o=r,a=0;while(a<s.path.length){let c=s.path[a];if(a!==s.path.length-1)o[c]=o[c]||{_errors:[]};else o[c]=o[c]||{_errors:[]},o[c]._errors.push(t(s));o=o[c],a++}}};return n(this),r}static assert(e){if(!(e instanceof hr))throw Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,be.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=(t)=>t.message){let t={},r=[];for(let n of this.issues)if(n.path.length>0){let i=n.path[0];t[i]=t[i]||[],t[i].push(e(n))}else r.push(e(n));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}};hr.create=(e)=>new hr(e)});var y4e=(e,t)=>{let r;switch(e.code){case P.invalid_type:if(e.received===N.undefined)r="Required";else r=`Expected ${e.expected}, received ${e.received}`;break;case P.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,be.jsonStringifyReplacer)}`;break;case P.unrecognized_keys:r=`Unrecognized key(s) in object: ${be.joinValues(e.keys,", ")}`;break;case P.invalid_union:r="Invalid input";break;case P.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${be.joinValues(e.options)}`;break;case P.invalid_enum_value:r=`Invalid enum value. Expected ${be.joinValues(e.options)}, received '${e.received}'`;break;case P.invalid_arguments:r="Invalid function arguments";break;case P.invalid_return_type:r="Invalid function return type";break;case P.invalid_date:r="Invalid date";break;case P.invalid_string:if(typeof e.validation==="object")if("includes"in e.validation){if(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==="number")r=`${r} at one or more positions greater than or equal to ${e.validation.position}`}else if("startsWith"in e.validation)r=`Invalid input: must start with "${e.validation.startsWith}"`;else if("endsWith"in e.validation)r=`Invalid input: must end with "${e.validation.endsWith}"`;else be.assertNever(e.validation);else if(e.validation!=="regex")r=`Invalid ${e.validation}`;else r="Invalid";break;case P.too_small:if(e.type==="array")r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`;else if(e.type==="string")r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`;else if(e.type==="number")r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`;else if(e.type==="bigint")r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`;else if(e.type==="date")r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`;else r="Invalid input";break;case P.too_big:if(e.type==="array")r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`;else if(e.type==="string")r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`;else if(e.type==="number")r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`;else if(e.type==="bigint")r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`;else if(e.type==="date")r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`;else r="Invalid input";break;case P.custom:r="Invalid input";break;case P.invalid_intersection_types:r="Intersection results could not be merged";break;case P.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case P.not_finite:r="Number must be finite";break;default:r=t.defaultError,be.assertNever(e)}return{message:r}},$i;var R_=A(()=>{um();td();$i=y4e});function x4e(e){vV=e}function pc(){return vV}var vV;var lm=A(()=>{R_();vV=$i});function B(e,t){let r=pc(),n=rd({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===$i?void 0:$i].filter((i)=>!!i)});e.common.issues.push(n)}class At{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 r=[];for(let n of t){if(n.status==="aborted")return Q;if(n.status==="dirty")e.dirty();r.push(n.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){let r=[];for(let n of t){let i=await n.key,s=await n.value;r.push({key:i,value:s})}return At.mergeObjectSync(e,r)}static mergeObjectSync(e,t){let r={};for(let n of t){let{key:i,value:s}=n;if(i.status==="aborted")return Q;if(s.status==="aborted")return Q;if(i.status==="dirty")e.dirty();if(s.status==="dirty")e.dirty();if(i.value!=="__proto__"&&(typeof s.value<"u"||n.alwaysSet))r[i.value]=s.value}return{status:e.value,value:r}}}var rd=(e)=>{let{data:t,path:r,errorMaps:n,issueData:i}=e,s=[...r,...i.path||[]],o={...i,path:s};if(i.message!==void 0)return{...i,path:s,message:i.message};let a="",c=n.filter((l)=>!!l).slice().reverse();for(let l of c)a=l(o,{data:t,defaultError:a}).message;return{...i,path:s,message:a}},b4e,Q,So=(e)=>({status:"dirty",value:e}),Mt=(e)=>({status:"valid",value:e}),dm=(e)=>e.status==="aborted",fm=(e)=>e.status==="dirty",Cs=(e)=>e.status==="valid",mc=(e)=>typeof Promise<"u"&&e instanceof Promise;var O_=A(()=>{lm();R_();b4e=[];Q=Object.freeze({status:"aborted"})});var _V=()=>{};var W;var DV=A(()=>{(function(e){e.errToObj=(t)=>typeof t==="string"?{message:t}:t||{},e.toString=(t)=>typeof t==="string"?t:t?.message})(W||(W={}))});class vn{constructor(e,t,r,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=n}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 le(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:n,description:i}=e;if(t&&(r||n))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(t)return{errorMap:t,description:i};return{errorMap:(o,a)=>{let{message:c}=e;if(o.code==="invalid_enum_value")return{message:c??a.defaultError};if(typeof a.data>"u")return{message:c??n??a.defaultError};if(o.code!=="invalid_type")return{message:a.defaultError};return{message:c??r??a.defaultError}},description:i}}class he{get description(){return this._def.description}_getType(e){return Jn(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Jn(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new At,ctx:{common:e.parent.common,data:e.data,parsedType:Jn(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(mc(t))throw Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){let r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Jn(e)},n=this._parseSync({data:e,path:r.path,parent:r});return wV(r,n)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Jn(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:t});return Cs(r)?{value:r.value}:{issues:t.common.issues}}catch(r){if(r?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then((r)=>Cs(r)?{value:r.value}:{issues:t.common.issues})}async parseAsync(e,t){let r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){let r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Jn(e)},n=this._parse({data:e,path:r.path,parent:r}),i=await(mc(n)?n:Promise.resolve(n));return wV(r,i)}refine(e,t){let r=(n)=>{if(typeof t==="string"||typeof t>"u")return{message:t};else if(typeof t==="function")return t(n);else return t};return this._refinement((n,i)=>{let s=e(n),o=()=>i.addIssue({code:P.custom,...r(n)});if(typeof Promise<"u"&&s instanceof Promise)return s.then((a)=>{if(!a)return o(),!1;else return!0});if(!s)return o(),!1;else return!0})}refinement(e,t){return this._refinement((r,n)=>{if(!e(r))return n.addIssue(typeof t==="function"?t(r,n):t),!1;else return!0})}_refinement(e){return new _n({schema:this,typeName:ee.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 bn.create(this,this._def)}nullable(){return Fi.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return xn.create(this)}promise(){return Ro.create(this,this._def)}or(e){return vc.create([this,e],this._def)}and(e){return _c.create(this,e,this._def)}transform(e){return new _n({...le(this._def),schema:this,typeName:ee.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e==="function"?e:()=>e;return new Sc({...le(this._def),innerType:this,defaultValue:t,typeName:ee.ZodDefault})}brand(){return new mm({typeName:ee.ZodBranded,type:this,...le(this._def)})}catch(e){let t=typeof e==="function"?e:()=>e;return new $c({...le(this._def),innerType:this,catchValue:t,typeName:ee.ZodCatch})}describe(e){return new this.constructor({...this._def,description:e})}pipe(e){return cd.create(this,e)}readonly(){return Cc.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}function $V(e){let t="[0-5]\\d";if(e.precision)t=`${t}\\.\\d{${e.precision}}`;else if(e.precision==null)t=`${t}(\\.\\d+)?`;let r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function N4e(e){return new RegExp(`^${$V(e)}$`)}function CV(e){let t=`${SV}T${$V(e)}`,r=[];if(r.push(e.local?"Z?":"Z"),e.offset)r.push("([+-]\\d{2}:?\\d{2})");return t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function q4e(e,t){if((t==="v4"||!t)&&R4e.test(e))return!0;if((t==="v6"||!t)&&A4e.test(e))return!0;return!1}function j4e(e,t){if(!S4e.test(e))return!1;try{let[r]=e.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(n));if(typeof i!=="object"||i===null)return!1;if("typ"in i&&i?.typ!=="JWT")return!1;if(!i.alg)return!1;if(t&&i.alg!==t)return!1;return!0}catch{return!1}}function M4e(e,t){if((t==="v4"||!t)&&O4e.test(e))return!0;if((t==="v6"||!t)&&k4e.test(e))return!0;return!1}function B4e(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,i=r>n?r:n,s=Number.parseInt(e.toFixed(i).replace(".","")),o=Number.parseInt(t.toFixed(i).replace(".",""));return s%o/10**i}function hc(e){if(e instanceof ut){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=bn.create(hc(n))}return new ut({...e._def,shape:()=>t})}else if(e instanceof xn)return new xn({...e._def,type:hc(e.element)});else if(e instanceof bn)return bn.create(hc(e.unwrap()));else if(e instanceof Fi)return Fi.create(hc(e.unwrap()));else if(e instanceof Qn)return Qn.create(e.items.map((t)=>hc(t)));else return e}function k_(e,t){let r=Jn(e),n=Jn(t);if(e===t)return{valid:!0,data:e};else if(r===N.object&&n===N.object){let i=be.objectKeys(t),s=be.objectKeys(e).filter((a)=>i.indexOf(a)!==-1),o={...e,...t};for(let a of s){let c=k_(e[a],t[a]);if(!c.valid)return{valid:!1};o[a]=c.data}return{valid:!0,data:o}}else if(r===N.array&&n===N.array){if(e.length!==t.length)return{valid:!1};let i=[];for(let s=0;s<e.length;s++){let o=e[s],a=t[s],c=k_(o,a);if(!c.valid)return{valid:!1};i.push(c.data)}return{valid:!0,data:i}}else if(r===N.date&&n===N.date&&+e===+t)return{valid:!0,data:e};else return{valid:!1}}function FV(e,t){return new As({values:e,typeName:ee.ZodEnum,...le(t)})}function EV(e,t){let r=typeof e==="function"?e(t):typeof e==="string"?{message:e}:e;return typeof r==="string"?{message:r}:r}function RV(e,t={},r){if(e)return Co.create().superRefine((n,i)=>{let s=e(n);if(s instanceof Promise)return s.then((o)=>{if(!o){let a=EV(t,n),c=a.fatal??r??!0;i.addIssue({code:"custom",...a,fatal:c})}});if(!s){let o=EV(t,n),a=o.fatal??r??!0;i.addIssue({code:"custom",...o,fatal:a})}return});return Co.create()}var wV=(e,t)=>{if(Cs(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 r=new hr(e.common.issues);return this._error=r,this._error}}}},v4e,_4e,D4e,w4e,E4e,S4e,$4e,C4e,F4e="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",A_,R4e,O4e,A4e,k4e,P4e,I4e,SV="((\\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])))",T4e,yn,Rs,Os,yc,$o,nd,xc,bc,Co,Fs,Xn,id,xn,ut,vc,Ci=(e)=>{if(e instanceof Dc)return Ci(e.schema);else if(e instanceof _n)return Ci(e.innerType());else if(e instanceof wc)return[e.value];else if(e instanceof As)return e.options;else if(e instanceof Ec)return be.objectValues(e.enum);else if(e instanceof Sc)return Ci(e._def.innerType);else if(e instanceof xc)return[void 0];else if(e instanceof bc)return[null];else if(e instanceof bn)return[void 0,...Ci(e.unwrap())];else if(e instanceof Fi)return[null,...Ci(e.unwrap())];else if(e instanceof mm)return Ci(e.unwrap());else if(e instanceof Cc)return Ci(e.unwrap());else if(e instanceof $c)return Ci(e._def.innerType);else return[]},pm,_c,Qn,sd,od,Fo,gc,Dc,wc,As,Ec,Ro,_n,bn,Fi,Sc,$c,ad,L4e,mm,cd,Cc,U4e,ee,V4e=(e,t={message:`Input not instance of ${e.name}`})=>RV((r)=>r instanceof e,t),OV,AV,z4e,H4e,kV,G4e,W4e,K4e,Y4e,J4e,X4e,Q4e,Z4e,e3e,t3e,r3e,n3e,i3e,s3e,o3e,a3e,c3e,u3e,l3e,d3e,f3e,p3e,m3e,h3e,g3e,y3e,x3e,b3e,v3e,_3e=()=>OV().optional(),D3e=()=>AV().optional(),w3e=()=>kV().optional(),E3e,S3e;var PV=A(()=>{um();lm();DV();O_();td();v4e=/^c[^\s-]{8,}$/i,_4e=/^[0-9a-z]+$/,D4e=/^[0-9A-HJKMNP-TV-Z]{26}$/i,w4e=/^[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,E4e=/^[a-z0-9_-]{21}$/i,S4e=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,$4e=/^[-+]?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)?)??$/,C4e=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,R4e=/^(?:(?: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])$/,O4e=/^(?:(?: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])$/,A4e=/^(([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]))$/,k4e=/^(([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])$/,P4e=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,I4e=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,T4e=new RegExp(`^${SV}$`);yn=class yn extends he{_parse(e){if(this._def.coerce)e.data=String(e.data);if(this._getType(e)!==N.string){let i=this._getOrReturnCtx(e);return B(i,{code:P.invalid_type,expected:N.string,received:i.parsedType}),Q}let r=new At,n=void 0;for(let i of this._def.checks)if(i.kind==="min"){if(e.data.length<i.value)n=this._getOrReturnCtx(e,n),B(n,{code:P.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty()}else if(i.kind==="max"){if(e.data.length>i.value)n=this._getOrReturnCtx(e,n),B(n,{code:P.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty()}else if(i.kind==="length"){let s=e.data.length>i.value,o=e.data.length<i.value;if(s||o){if(n=this._getOrReturnCtx(e,n),s)B(n,{code:P.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message});else if(o)B(n,{code:P.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message});r.dirty()}}else if(i.kind==="email"){if(!C4e.test(e.data))n=this._getOrReturnCtx(e,n),B(n,{validation:"email",code:P.invalid_string,message:i.message}),r.dirty()}else if(i.kind==="emoji"){if(!A_)A_=new RegExp(F4e,"u");if(!A_.test(e.data))n=this._getOrReturnCtx(e,n),B(n,{validation:"emoji",code:P.invalid_string,message:i.message}),r.dirty()}else if(i.kind==="uuid"){if(!w4e.test(e.data))n=this._getOrReturnCtx(e,n),B(n,{validation:"uuid",code:P.invalid_string,message:i.message}),r.dirty()}else if(i.kind==="nanoid"){if(!E4e.test(e.data))n=this._getOrReturnCtx(e,n),B(n,{validation:"nanoid",code:P.invalid_string,message:i.message}),r.dirty()}else if(i.kind==="cuid"){if(!v4e.test(e.data))n=this._getOrReturnCtx(e,n),B(n,{validation:"cuid",code:P.invalid_string,message:i.message}),r.dirty()}else if(i.kind==="cuid2"){if(!_4e.test(e.data))n=this._getOrReturnCtx(e,n),B(n,{validation:"cuid2",code:P.invalid_string,message:i.message}),r.dirty()}else if(i.kind==="ulid"){if(!D4e.test(e.data))n=this._getOrReturnCtx(e,n),B(n,{validation:"ulid",code:P.invalid_string,message:i.message}),r.dirty()}else if(i.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),B(n,{validation:"url",code:P.invalid_string,message:i.message}),r.dirty()}else if(i.kind==="regex"){if(i.regex.lastIndex=0,!i.regex.test(e.data))n=this._getOrReturnCtx(e,n),B(n,{validation:"regex",code:P.invalid_string,message:i.message}),r.dirty()}else if(i.kind==="trim")e.data=e.data.trim();else if(i.kind==="includes"){if(!e.data.includes(i.value,i.position))n=this._getOrReturnCtx(e,n),B(n,{code:P.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()}else if(i.kind==="toLowerCase")e.data=e.data.toLowerCase();else if(i.kind==="toUpperCase")e.data=e.data.toUpperCase();else if(i.kind==="startsWith"){if(!e.data.startsWith(i.value))n=this._getOrReturnCtx(e,n),B(n,{code:P.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()}else if(i.kind==="endsWith"){if(!e.data.endsWith(i.value))n=this._getOrReturnCtx(e,n),B(n,{code:P.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()}else if(i.kind==="datetime"){if(!CV(i).test(e.data))n=this._getOrReturnCtx(e,n),B(n,{code:P.invalid_string,validation:"datetime",message:i.message}),r.dirty()}else if(i.kind==="date"){if(!T4e.test(e.data))n=this._getOrReturnCtx(e,n),B(n,{code:P.invalid_string,validation:"date",message:i.message}),r.dirty()}else if(i.kind==="time"){if(!N4e(i).test(e.data))n=this._getOrReturnCtx(e,n),B(n,{code:P.invalid_string,validation:"time",message:i.message}),r.dirty()}else if(i.kind==="duration"){if(!$4e.test(e.data))n=this._getOrReturnCtx(e,n),B(n,{validation:"duration",code:P.invalid_string,message:i.message}),r.dirty()}else if(i.kind==="ip"){if(!q4e(e.data,i.version))n=this._getOrReturnCtx(e,n),B(n,{validation:"ip",code:P.invalid_string,message:i.message}),r.dirty()}else if(i.kind==="jwt"){if(!j4e(e.data,i.alg))n=this._getOrReturnCtx(e,n),B(n,{validation:"jwt",code:P.invalid_string,message:i.message}),r.dirty()}else if(i.kind==="cidr"){if(!M4e(e.data,i.version))n=this._getOrReturnCtx(e,n),B(n,{validation:"cidr",code:P.invalid_string,message:i.message}),r.dirty()}else if(i.kind==="base64"){if(!P4e.test(e.data))n=this._getOrReturnCtx(e,n),B(n,{validation:"base64",code:P.invalid_string,message:i.message}),r.dirty()}else if(i.kind==="base64url"){if(!I4e.test(e.data))n=this._getOrReturnCtx(e,n),B(n,{validation:"base64url",code:P.invalid_string,message:i.message}),r.dirty()}else be.assertNever(i);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement((n)=>e.test(n),{validation:t,code:P.invalid_string,...W.errToObj(r)})}_addCheck(e){return new yn({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...W.errToObj(e)})}url(e){return this._addCheck({kind:"url",...W.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...W.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...W.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...W.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...W.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...W.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...W.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...W.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...W.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...W.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...W.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...W.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,...W.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,...W.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...W.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...W.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...W.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...W.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...W.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...W.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...W.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...W.errToObj(t)})}nonempty(e){return this.min(1,W.errToObj(e))}trim(){return new yn({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new yn({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new yn({...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}};yn.create=(e)=>new yn({checks:[],typeName:ee.ZodString,coerce:e?.coerce??!1,...le(e)});Rs=class Rs extends he{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)!==N.number){let i=this._getOrReturnCtx(e);return B(i,{code:P.invalid_type,expected:N.number,received:i.parsedType}),Q}let r=void 0,n=new At;for(let i of this._def.checks)if(i.kind==="int"){if(!be.isInteger(e.data))r=this._getOrReturnCtx(e,r),B(r,{code:P.invalid_type,expected:"integer",received:"float",message:i.message}),n.dirty()}else if(i.kind==="min"){if(i.inclusive?e.data<i.value:e.data<=i.value)r=this._getOrReturnCtx(e,r),B(r,{code:P.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),n.dirty()}else if(i.kind==="max"){if(i.inclusive?e.data>i.value:e.data>=i.value)r=this._getOrReturnCtx(e,r),B(r,{code:P.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),n.dirty()}else if(i.kind==="multipleOf"){if(B4e(e.data,i.value)!==0)r=this._getOrReturnCtx(e,r),B(r,{code:P.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()}else if(i.kind==="finite"){if(!Number.isFinite(e.data))r=this._getOrReturnCtx(e,r),B(r,{code:P.not_finite,message:i.message}),n.dirty()}else be.assertNever(i);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,W.toString(t))}gt(e,t){return this.setLimit("min",e,!1,W.toString(t))}lte(e,t){return this.setLimit("max",e,!0,W.toString(t))}lt(e,t){return this.setLimit("max",e,!1,W.toString(t))}setLimit(e,t,r,n){return new Rs({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:W.toString(n)}]})}_addCheck(e){return new Rs({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:W.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:W.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:W.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:W.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:W.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:W.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:W.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:W.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:W.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"&&be.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let r of this._def.checks)if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;else if(r.kind==="min"){if(t===null||r.value>t)t=r.value}else if(r.kind==="max"){if(e===null||r.value<e)e=r.value}return Number.isFinite(t)&&Number.isFinite(e)}};Rs.create=(e)=>new Rs({checks:[],typeName:ee.ZodNumber,coerce:e?.coerce||!1,...le(e)});Os=class Os extends he{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)!==N.bigint)return this._getInvalidInput(e);let r=void 0,n=new At;for(let i of this._def.checks)if(i.kind==="min"){if(i.inclusive?e.data<i.value:e.data<=i.value)r=this._getOrReturnCtx(e,r),B(r,{code:P.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),n.dirty()}else if(i.kind==="max"){if(i.inclusive?e.data>i.value:e.data>=i.value)r=this._getOrReturnCtx(e,r),B(r,{code:P.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),n.dirty()}else if(i.kind==="multipleOf"){if(e.data%i.value!==BigInt(0))r=this._getOrReturnCtx(e,r),B(r,{code:P.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()}else be.assertNever(i);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return B(t,{code:P.invalid_type,expected:N.bigint,received:t.parsedType}),Q}gte(e,t){return this.setLimit("min",e,!0,W.toString(t))}gt(e,t){return this.setLimit("min",e,!1,W.toString(t))}lte(e,t){return this.setLimit("max",e,!0,W.toString(t))}lt(e,t){return this.setLimit("max",e,!1,W.toString(t))}setLimit(e,t,r,n){return new Os({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:W.toString(n)}]})}_addCheck(e){return new Os({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:W.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:W.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:W.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:W.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:W.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}};Os.create=(e)=>new Os({checks:[],typeName:ee.ZodBigInt,coerce:e?.coerce??!1,...le(e)});yc=class yc extends he{_parse(e){if(this._def.coerce)e.data=Boolean(e.data);if(this._getType(e)!==N.boolean){let r=this._getOrReturnCtx(e);return B(r,{code:P.invalid_type,expected:N.boolean,received:r.parsedType}),Q}return Mt(e.data)}};yc.create=(e)=>new yc({typeName:ee.ZodBoolean,coerce:e?.coerce||!1,...le(e)});$o=class $o extends he{_parse(e){if(this._def.coerce)e.data=new Date(e.data);if(this._getType(e)!==N.date){let i=this._getOrReturnCtx(e);return B(i,{code:P.invalid_type,expected:N.date,received:i.parsedType}),Q}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return B(i,{code:P.invalid_date}),Q}let r=new At,n=void 0;for(let i of this._def.checks)if(i.kind==="min"){if(e.data.getTime()<i.value)n=this._getOrReturnCtx(e,n),B(n,{code:P.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()}else if(i.kind==="max"){if(e.data.getTime()>i.value)n=this._getOrReturnCtx(e,n),B(n,{code:P.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()}else be.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new $o({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:W.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:W.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}};$o.create=(e)=>new $o({checks:[],coerce:e?.coerce||!1,typeName:ee.ZodDate,...le(e)});nd=class nd extends he{_parse(e){if(this._getType(e)!==N.symbol){let r=this._getOrReturnCtx(e);return B(r,{code:P.invalid_type,expected:N.symbol,received:r.parsedType}),Q}return Mt(e.data)}};nd.create=(e)=>new nd({typeName:ee.ZodSymbol,...le(e)});xc=class xc extends he{_parse(e){if(this._getType(e)!==N.undefined){let r=this._getOrReturnCtx(e);return B(r,{code:P.invalid_type,expected:N.undefined,received:r.parsedType}),Q}return Mt(e.data)}};xc.create=(e)=>new xc({typeName:ee.ZodUndefined,...le(e)});bc=class bc extends he{_parse(e){if(this._getType(e)!==N.null){let r=this._getOrReturnCtx(e);return B(r,{code:P.invalid_type,expected:N.null,received:r.parsedType}),Q}return Mt(e.data)}};bc.create=(e)=>new bc({typeName:ee.ZodNull,...le(e)});Co=class Co extends he{constructor(){super(...arguments);this._any=!0}_parse(e){return Mt(e.data)}};Co.create=(e)=>new Co({typeName:ee.ZodAny,...le(e)});Fs=class Fs extends he{constructor(){super(...arguments);this._unknown=!0}_parse(e){return Mt(e.data)}};Fs.create=(e)=>new Fs({typeName:ee.ZodUnknown,...le(e)});Xn=class Xn extends he{_parse(e){let t=this._getOrReturnCtx(e);return B(t,{code:P.invalid_type,expected:N.never,received:t.parsedType}),Q}};Xn.create=(e)=>new Xn({typeName:ee.ZodNever,...le(e)});id=class id extends he{_parse(e){if(this._getType(e)!==N.undefined){let r=this._getOrReturnCtx(e);return B(r,{code:P.invalid_type,expected:N.void,received:r.parsedType}),Q}return Mt(e.data)}};id.create=(e)=>new id({typeName:ee.ZodVoid,...le(e)});xn=class xn extends he{_parse(e){let{ctx:t,status:r}=this._processInputParams(e),n=this._def;if(t.parsedType!==N.array)return B(t,{code:P.invalid_type,expected:N.array,received:t.parsedType}),Q;if(n.exactLength!==null){let s=t.data.length>n.exactLength.value,o=t.data.length<n.exactLength.value;if(s||o)B(t,{code:s?P.too_big:P.too_small,minimum:o?n.exactLength.value:void 0,maximum:s?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),r.dirty()}if(n.minLength!==null){if(t.data.length<n.minLength.value)B(t,{code:P.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),r.dirty()}if(n.maxLength!==null){if(t.data.length>n.maxLength.value)B(t,{code:P.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),r.dirty()}if(t.common.async)return Promise.all([...t.data].map((s,o)=>n.type._parseAsync(new vn(t,s,t.path,o)))).then((s)=>At.mergeArray(r,s));let i=[...t.data].map((s,o)=>n.type._parseSync(new vn(t,s,t.path,o)));return At.mergeArray(r,i)}get element(){return this._def.type}min(e,t){return new xn({...this._def,minLength:{value:e,message:W.toString(t)}})}max(e,t){return new xn({...this._def,maxLength:{value:e,message:W.toString(t)}})}length(e,t){return new xn({...this._def,exactLength:{value:e,message:W.toString(t)}})}nonempty(e){return this.min(1,e)}};xn.create=(e,t)=>new xn({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ee.ZodArray,...le(t)});ut=class ut extends he{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=be.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==N.object){let c=this._getOrReturnCtx(e);return B(c,{code:P.invalid_type,expected:N.object,received:c.parsedType}),Q}let{status:r,ctx:n}=this._processInputParams(e),{shape:i,keys:s}=this._getCached(),o=[];if(!(this._def.catchall instanceof Xn&&this._def.unknownKeys==="strip")){for(let c in n.data)if(!s.includes(c))o.push(c)}let a=[];for(let c of s){let l=i[c],d=n.data[c];a.push({key:{status:"valid",value:c},value:l._parse(new vn(n,d,n.path,c)),alwaysSet:c in n.data})}if(this._def.catchall instanceof Xn){let c=this._def.unknownKeys;if(c==="passthrough")for(let l of o)a.push({key:{status:"valid",value:l},value:{status:"valid",value:n.data[l]}});else if(c==="strict"){if(o.length>0)B(n,{code:P.unrecognized_keys,keys:o}),r.dirty()}else if(c==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let l of o){let d=n.data[l];a.push({key:{status:"valid",value:l},value:c._parse(new vn(n,d,n.path,l)),alwaysSet:l in n.data})}}if(n.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)=>At.mergeObjectSync(r,c));else return At.mergeObjectSync(r,a)}get shape(){return this._def.shape()}strict(e){return W.errToObj,new ut({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,r)=>{let n=this._def.errorMap?.(t,r).message??r.defaultError;if(t.code==="unrecognized_keys")return{message:W.errToObj(e).message??n};return{message:n}}}:{}})}strip(){return new ut({...this._def,unknownKeys:"strip"})}passthrough(){return new ut({...this._def,unknownKeys:"passthrough"})}extend(e){return new ut({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ut({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:ee.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ut({...this._def,catchall:e})}pick(e){let t={};for(let r of be.objectKeys(e))if(e[r]&&this.shape[r])t[r]=this.shape[r];return new ut({...this._def,shape:()=>t})}omit(e){let t={};for(let r of be.objectKeys(this.shape))if(!e[r])t[r]=this.shape[r];return new ut({...this._def,shape:()=>t})}deepPartial(){return hc(this)}partial(e){let t={};for(let r of be.objectKeys(this.shape)){let n=this.shape[r];if(e&&!e[r])t[r]=n;else t[r]=n.optional()}return new ut({...this._def,shape:()=>t})}required(e){let t={};for(let r of be.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let i=this.shape[r];while(i instanceof bn)i=i._def.innerType;t[r]=i}return new ut({...this._def,shape:()=>t})}keyof(){return FV(be.objectKeys(this.shape))}};ut.create=(e,t)=>new ut({shape:()=>e,unknownKeys:"strip",catchall:Xn.create(),typeName:ee.ZodObject,...le(t)});ut.strictCreate=(e,t)=>new ut({shape:()=>e,unknownKeys:"strict",catchall:Xn.create(),typeName:ee.ZodObject,...le(t)});ut.lazycreate=(e,t)=>new ut({shape:e,unknownKeys:"strip",catchall:Xn.create(),typeName:ee.ZodObject,...le(t)});vc=class vc extends he{_parse(e){let{ctx:t}=this._processInputParams(e),r=this._def.options;function n(i){for(let o of i)if(o.result.status==="valid")return o.result;for(let o of i)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;let s=i.map((o)=>new hr(o.ctx.common.issues));return B(t,{code:P.invalid_union,unionErrors:s}),Q}if(t.common.async)return Promise.all(r.map(async(i)=>{let s={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:s}),ctx:s}})).then(n);else{let i=void 0,s=[];for(let a of r){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"&&!i)i={result:l,ctx:c};if(c.common.issues.length)s.push(c.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;let o=s.map((a)=>new hr(a));return B(t,{code:P.invalid_union,unionErrors:o}),Q}}get options(){return this._def.options}};vc.create=(e,t)=>new vc({options:e,typeName:ee.ZodUnion,...le(t)});pm=class pm extends he{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==N.object)return B(t,{code:P.invalid_type,expected:N.object,received:t.parsedType}),Q;let r=this.discriminator,n=t.data[r],i=this.optionsMap.get(n);if(!i)return B(t,{code:P.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),Q;if(t.common.async)return i._parseAsync({data:t.data,path:t.path,parent:t});else return i._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,r){let n=new Map;for(let i of t){let s=Ci(i.shape[e]);if(!s.length)throw Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let o of s){if(n.has(o))throw Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);n.set(o,i)}}return new pm({typeName:ee.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...le(r)})}};_c=class _c extends he{_parse(e){let{status:t,ctx:r}=this._processInputParams(e),n=(i,s)=>{if(dm(i)||dm(s))return Q;let o=k_(i.value,s.value);if(!o.valid)return B(r,{code:P.invalid_intersection_types}),Q;if(fm(i)||fm(s))t.dirty();return{status:t.value,value:o.data}};if(r.common.async)return Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,s])=>n(i,s));else return n(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};_c.create=(e,t,r)=>new _c({left:e,right:t,typeName:ee.ZodIntersection,...le(r)});Qn=class Qn extends he{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==N.array)return B(r,{code:P.invalid_type,expected:N.array,received:r.parsedType}),Q;if(r.data.length<this._def.items.length)return B(r,{code:P.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Q;if(!this._def.rest&&r.data.length>this._def.items.length)B(r,{code:P.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty();let i=[...r.data].map((s,o)=>{let a=this._def.items[o]||this._def.rest;if(!a)return null;return a._parse(new vn(r,s,r.path,o))}).filter((s)=>!!s);if(r.common.async)return Promise.all(i).then((s)=>At.mergeArray(t,s));else return At.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new Qn({...this._def,rest:e})}};Qn.create=(e,t)=>{if(!Array.isArray(e))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new Qn({items:e,typeName:ee.ZodTuple,rest:null,...le(t)})};sd=class sd extends he{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==N.object)return B(r,{code:P.invalid_type,expected:N.object,received:r.parsedType}),Q;let n=[],i=this._def.keyType,s=this._def.valueType;for(let o in r.data)n.push({key:i._parse(new vn(r,o,r.path,o)),value:s._parse(new vn(r,r.data[o],r.path,o)),alwaysSet:o in r.data});if(r.common.async)return At.mergeObjectAsync(t,n);else return At.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,r){if(t instanceof he)return new sd({keyType:e,valueType:t,typeName:ee.ZodRecord,...le(r)});return new sd({keyType:yn.create(),valueType:e,typeName:ee.ZodRecord,...le(t)})}};od=class od extends he{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==N.map)return B(r,{code:P.invalid_type,expected:N.map,received:r.parsedType}),Q;let n=this._def.keyType,i=this._def.valueType,s=[...r.data.entries()].map(([o,a],c)=>({key:n._parse(new vn(r,o,r.path,[c,"key"])),value:i._parse(new vn(r,a,r.path,[c,"value"]))}));if(r.common.async){let o=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 Q;if(c.status==="dirty"||l.status==="dirty")t.dirty();o.set(c.value,l.value)}return{status:t.value,value:o}})}else{let o=new Map;for(let a of s){let{key:c,value:l}=a;if(c.status==="aborted"||l.status==="aborted")return Q;if(c.status==="dirty"||l.status==="dirty")t.dirty();o.set(c.value,l.value)}return{status:t.value,value:o}}}};od.create=(e,t,r)=>new od({valueType:t,keyType:e,typeName:ee.ZodMap,...le(r)});Fo=class Fo extends he{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==N.set)return B(r,{code:P.invalid_type,expected:N.set,received:r.parsedType}),Q;let n=this._def;if(n.minSize!==null){if(r.data.size<n.minSize.value)B(r,{code:P.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()}if(n.maxSize!==null){if(r.data.size>n.maxSize.value)B(r,{code:P.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty()}let i=this._def.valueType;function s(a){let c=new Set;for(let l of a){if(l.status==="aborted")return Q;if(l.status==="dirty")t.dirty();c.add(l.value)}return{status:t.value,value:c}}let o=[...r.data.values()].map((a,c)=>i._parse(new vn(r,a,r.path,c)));if(r.common.async)return Promise.all(o).then((a)=>s(a));else return s(o)}min(e,t){return new Fo({...this._def,minSize:{value:e,message:W.toString(t)}})}max(e,t){return new Fo({...this._def,maxSize:{value:e,message:W.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};Fo.create=(e,t)=>new Fo({valueType:e,minSize:null,maxSize:null,typeName:ee.ZodSet,...le(t)});gc=class gc extends he{constructor(){super(...arguments);this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==N.function)return B(t,{code:P.invalid_type,expected:N.function,received:t.parsedType}),Q;function r(o,a){return rd({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,pc(),$i].filter((c)=>!!c),issueData:{code:P.invalid_arguments,argumentsError:a}})}function n(o,a){return rd({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,pc(),$i].filter((c)=>!!c),issueData:{code:P.invalid_return_type,returnTypeError:a}})}let i={errorMap:t.common.contextualErrorMap},s=t.data;if(this._def.returns instanceof Ro){let o=this;return Mt(async function(...a){let c=new hr([]),l=await o._def.args.parseAsync(a,i).catch((m)=>{throw c.addIssue(r(a,m)),c}),d=await Reflect.apply(s,this,l);return await o._def.returns._def.type.parseAsync(d,i).catch((m)=>{throw c.addIssue(n(d,m)),c})})}else{let o=this;return Mt(function(...a){let c=o._def.args.safeParse(a,i);if(!c.success)throw new hr([r(a,c.error)]);let l=Reflect.apply(s,this,c.data),d=o._def.returns.safeParse(l,i);if(!d.success)throw new hr([n(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new gc({...this._def,args:Qn.create(e).rest(Fs.create())})}returns(e){return new gc({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new gc({args:e?e:Qn.create([]).rest(Fs.create()),returns:t||Fs.create(),typeName:ee.ZodFunction,...le(r)})}};Dc=class Dc extends he{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})}};Dc.create=(e,t)=>new Dc({getter:e,typeName:ee.ZodLazy,...le(t)});wc=class wc extends he{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return B(t,{received:t.data,code:P.invalid_literal,expected:this._def.value}),Q}return{status:"valid",value:e.data}}get value(){return this._def.value}};wc.create=(e,t)=>new wc({value:e,typeName:ee.ZodLiteral,...le(t)});As=class As extends he{_parse(e){if(typeof e.data!=="string"){let t=this._getOrReturnCtx(e),r=this._def.values;return B(t,{expected:be.joinValues(r),received:t.parsedType,code:P.invalid_type}),Q}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),r=this._def.values;return B(t,{received:t.data,code:P.invalid_enum_value,options:r}),Q}return Mt(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 As.create(e,{...this._def,...t})}exclude(e,t=this._def){return As.create(this.options.filter((r)=>!e.includes(r)),{...this._def,...t})}};As.create=FV;Ec=class Ec extends he{_parse(e){let t=be.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==N.string&&r.parsedType!==N.number){let n=be.objectValues(t);return B(r,{expected:be.joinValues(n),received:r.parsedType,code:P.invalid_type}),Q}if(!this._cache)this._cache=new Set(be.getValidEnumValues(this._def.values));if(!this._cache.has(e.data)){let n=be.objectValues(t);return B(r,{received:r.data,code:P.invalid_enum_value,options:n}),Q}return Mt(e.data)}get enum(){return this._def.values}};Ec.create=(e,t)=>new Ec({values:e,typeName:ee.ZodNativeEnum,...le(t)});Ro=class Ro extends he{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==N.promise&&t.common.async===!1)return B(t,{code:P.invalid_type,expected:N.promise,received:t.parsedType}),Q;let r=t.parsedType===N.promise?t.data:Promise.resolve(t.data);return Mt(r.then((n)=>this._def.type.parseAsync(n,{path:t.path,errorMap:t.common.contextualErrorMap})))}};Ro.create=(e,t)=>new Ro({type:e,typeName:ee.ZodPromise,...le(t)});_n=class _n extends he{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ee.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),n=this._def.effect||null,i={addIssue:(s)=>{if(B(r,s),s.fatal)t.abort();else t.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),n.type==="preprocess"){let s=n.transform(r.data,i);if(r.common.async)return Promise.resolve(s).then(async(o)=>{if(t.value==="aborted")return Q;let a=await this._def.schema._parseAsync({data:o,path:r.path,parent:r});if(a.status==="aborted")return Q;if(a.status==="dirty")return So(a.value);if(t.value==="dirty")return So(a.value);return a});else{if(t.value==="aborted")return Q;let o=this._def.schema._parseSync({data:s,path:r.path,parent:r});if(o.status==="aborted")return Q;if(o.status==="dirty")return So(o.value);if(t.value==="dirty")return So(o.value);return o}}if(n.type==="refinement"){let s=(o)=>{let a=n.refinement(o,i);if(r.common.async)return Promise.resolve(a);if(a instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(r.common.async===!1){let o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(o.status==="aborted")return Q;if(o.status==="dirty")t.dirty();return s(o.value),{status:t.value,value:o.value}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then((o)=>{if(o.status==="aborted")return Q;if(o.status==="dirty")t.dirty();return s(o.value).then(()=>({status:t.value,value:o.value}))})}if(n.type==="transform")if(r.common.async===!1){let s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Cs(s))return Q;let o=n.transform(s.value,i);if(o instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:o}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then((s)=>{if(!Cs(s))return Q;return Promise.resolve(n.transform(s.value,i)).then((o)=>({status:t.value,value:o}))});be.assertNever(n)}};_n.create=(e,t,r)=>new _n({schema:e,typeName:ee.ZodEffects,effect:t,...le(r)});_n.createWithPreprocess=(e,t,r)=>new _n({schema:t,effect:{type:"preprocess",transform:e},typeName:ee.ZodEffects,...le(r)});bn=class bn extends he{_parse(e){if(this._getType(e)===N.undefined)return Mt(void 0);return this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};bn.create=(e,t)=>new bn({innerType:e,typeName:ee.ZodOptional,...le(t)});Fi=class Fi extends he{_parse(e){if(this._getType(e)===N.null)return Mt(null);return this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Fi.create=(e,t)=>new Fi({innerType:e,typeName:ee.ZodNullable,...le(t)});Sc=class Sc extends he{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;if(t.parsedType===N.undefined)r=this._def.defaultValue();return this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Sc.create=(e,t)=>new Sc({innerType:e,typeName:ee.ZodDefault,defaultValue:typeof t.default==="function"?t.default:()=>t.default,...le(t)});$c=class $c extends he{_parse(e){let{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});if(mc(n))return n.then((i)=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new hr(r.common.issues)},input:r.data})}));else return{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new hr(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};$c.create=(e,t)=>new $c({innerType:e,typeName:ee.ZodCatch,catchValue:typeof t.catch==="function"?t.catch:()=>t.catch,...le(t)});ad=class ad extends he{_parse(e){if(this._getType(e)!==N.nan){let r=this._getOrReturnCtx(e);return B(r,{code:P.invalid_type,expected:N.nan,received:r.parsedType}),Q}return{status:"valid",value:e.data}}};ad.create=(e)=>new ad({typeName:ee.ZodNaN,...le(e)});L4e=Symbol("zod_brand");mm=class mm extends he{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}};cd=class cd extends he{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});if(i.status==="aborted")return Q;if(i.status==="dirty")return t.dirty(),So(i.value);else return this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();else{let n=this._def.in._parseSync({data:r.data,path:r.path,parent:r});if(n.status==="aborted")return Q;if(n.status==="dirty")return t.dirty(),{status:"dirty",value:n.value};else return this._def.out._parseSync({data:n.value,path:r.path,parent:r})}}static create(e,t){return new cd({in:e,out:t,typeName:ee.ZodPipeline})}};Cc=class Cc extends he{_parse(e){let t=this._def.innerType._parse(e),r=(n)=>{if(Cs(n))n.value=Object.freeze(n.value);return n};return mc(t)?t.then((n)=>r(n)):r(t)}unwrap(){return this._def.innerType}};Cc.create=(e,t)=>new Cc({innerType:e,typeName:ee.ZodReadonly,...le(t)});U4e={object:ut.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"})(ee||(ee={}));OV=yn.create,AV=Rs.create,z4e=ad.create,H4e=Os.create,kV=yc.create,G4e=$o.create,W4e=nd.create,K4e=xc.create,Y4e=bc.create,J4e=Co.create,X4e=Fs.create,Q4e=Xn.create,Z4e=id.create,e3e=xn.create,t3e=ut.create,r3e=ut.strictCreate,n3e=vc.create,i3e=pm.create,s3e=_c.create,o3e=Qn.create,a3e=sd.create,c3e=od.create,u3e=Fo.create,l3e=gc.create,d3e=Dc.create,f3e=wc.create,p3e=As.create,m3e=Ec.create,h3e=Ro.create,g3e=_n.create,y3e=bn.create,x3e=Fi.create,b3e=_n.createWithPreprocess,v3e=cd.create,E3e={string:(e)=>yn.create({...e,coerce:!0}),number:(e)=>Rs.create({...e,coerce:!0}),boolean:(e)=>yc.create({...e,coerce:!0}),bigint:(e)=>Os.create({...e,coerce:!0}),date:(e)=>$o.create({...e,coerce:!0})},S3e=Q});var F={};Ti(F,{BRAND:()=>L4e,DIRTY:()=>So,EMPTY_PATH:()=>b4e,INVALID:()=>Q,NEVER:()=>S3e,OK:()=>Mt,ParseStatus:()=>At,Schema:()=>he,ZodAny:()=>Co,ZodArray:()=>xn,ZodBigInt:()=>Os,ZodBoolean:()=>yc,ZodBranded:()=>mm,ZodCatch:()=>$c,ZodDate:()=>$o,ZodDefault:()=>Sc,ZodDiscriminatedUnion:()=>pm,ZodEffects:()=>_n,ZodEnum:()=>As,ZodError:()=>hr,ZodFirstPartyTypeKind:()=>ee,ZodFunction:()=>gc,ZodIntersection:()=>_c,ZodIssueCode:()=>P,ZodLazy:()=>Dc,ZodLiteral:()=>wc,ZodMap:()=>od,ZodNaN:()=>ad,ZodNativeEnum:()=>Ec,ZodNever:()=>Xn,ZodNull:()=>bc,ZodNullable:()=>Fi,ZodNumber:()=>Rs,ZodObject:()=>ut,ZodOptional:()=>bn,ZodParsedType:()=>N,ZodPipeline:()=>cd,ZodPromise:()=>Ro,ZodReadonly:()=>Cc,ZodRecord:()=>sd,ZodSchema:()=>he,ZodSet:()=>Fo,ZodString:()=>yn,ZodSymbol:()=>nd,ZodTransformer:()=>_n,ZodTuple:()=>Qn,ZodType:()=>he,ZodUndefined:()=>xc,ZodUnion:()=>vc,ZodUnknown:()=>Fs,ZodVoid:()=>id,addIssueToContext:()=>B,any:()=>J4e,array:()=>e3e,bigint:()=>H4e,boolean:()=>kV,coerce:()=>E3e,custom:()=>RV,date:()=>G4e,datetimeRegex:()=>CV,defaultErrorMap:()=>$i,discriminatedUnion:()=>i3e,effect:()=>g3e,enum:()=>p3e,function:()=>l3e,getErrorMap:()=>pc,getParsedType:()=>Jn,instanceof:()=>V4e,intersection:()=>s3e,isAborted:()=>dm,isAsync:()=>mc,isDirty:()=>fm,isValid:()=>Cs,late:()=>U4e,lazy:()=>d3e,literal:()=>f3e,makeIssue:()=>rd,map:()=>c3e,nan:()=>z4e,nativeEnum:()=>m3e,never:()=>Q4e,null:()=>Y4e,nullable:()=>x3e,number:()=>AV,object:()=>t3e,objectUtil:()=>F_,oboolean:()=>w3e,onumber:()=>D3e,optional:()=>y3e,ostring:()=>_3e,pipeline:()=>v3e,preprocess:()=>b3e,promise:()=>h3e,quotelessJson:()=>g4e,record:()=>a3e,set:()=>u3e,setErrorMap:()=>x4e,strictObject:()=>r3e,string:()=>OV,symbol:()=>W4e,transformer:()=>g3e,tuple:()=>o3e,undefined:()=>K4e,union:()=>n3e,unknown:()=>X4e,util:()=>be,void:()=>Z4e});var P_=A(()=>{lm();O_();_V();td();PV();um()});var ud=A(()=>{P_();P_()});import{copyFileSync as $3e,existsSync as IV,mkdirSync as C3e}from"fs";import{homedir as gm}from"os";import{join as Fc}from"path";function R3e(e){let t=e.trim().replace(/\/+$/,"");try{let r=new URL(t);return r.protocol=r.protocol.toLowerCase(),r.host=r.host.toLowerCase(),r.toString().replace(/\/+$/,"")}catch{return console.error(`[nemar] could not parse stored apiUrl ${JSON.stringify(e)}; leaving as-is`),t}}function O3e(){return process.env.NEMAR_CONFIG_DIR||Fc(gm(),".config","nemar")}function A3e(e){if(process.env.NEMAR_CONFIG_DIR)return;let t=Fc(e,"config.json");if(IV(t))return;let r=[];if(process.platform==="darwin")r.push(Fc(gm(),"Library","Preferences","nemar-nodejs","config.json"));if(process.platform==="win32"){let n=process.env.APPDATA||Fc(gm(),"AppData","Roaming");r.push(Fc(n,"nemar-nodejs","config.json"))}r.push(Fc(gm(),".config","nemar-nodejs","config.json"));for(let n of r)if(IV(n))try{C3e(e,{recursive:!0}),$3e(n,t),console.error(`[nemar] Config migrated from ${n} to ${t}
|
|
98
|
+
deps: ${r}}`};var AOe={keyword:"dependencies",type:"object",schemaType:"object",error:mB.error,code(e){let[t,r]=kOe(e);fB(e,t),pB(e,r)}};function kOe({schema:e}){let t={},r={};for(let n in e){if(n==="__proto__")continue;let i=Array.isArray(e[n])?t:r;i[n]=e[n]}return[t,r]}function fB(e,t=e.schema){let{gen:r,data:n,it:i}=e;if(Object.keys(t).length===0)return;let s=r.let("missing");for(let o in t){let a=t[o];if(a.length===0)continue;let c=(0,Vl.propertyInData)(r,n,o,i.opts.ownProperties);if(e.setParams({property:o,depsCount:a.length,deps:a.join(", ")}),i.allErrors)r.if(c,()=>{for(let l of a)(0,Vl.checkReportMissingProp)(e,l)});else r.if(t_._`${c} && (${(0,Vl.checkMissingProp)(e,a,s)})`),(0,Vl.reportMissingProp)(e,s),r.else()}}mB.validatePropertyDeps=fB;function pB(e,t=e.schema){let{gen:r,data:n,keyword:i,it:s}=e,o=r.name("valid");for(let a in t){if((0,OOe.alwaysValidSchema)(s,t[a]))continue;r.if((0,Vl.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let c=e.subschema({keyword:i,schemaProp:a},o);e.mergeValidEvaluated(c,o)},()=>r.var(o,!0)),e.ok(o)}}mB.validateSchemaDeps=pB;mB.default=AOe});var vB=h(function(bB){Object.defineProperty(bB,"__esModule",{value:!0});var xB=me(),TOe=Pe(),NOe={message:"property name must be valid",params:({params:e})=>xB._`{propertyName: ${e.propertyName}}`},qOe={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:NOe,code(e){let{gen:t,schema:r,data:n,it:i}=e;if((0,TOe.alwaysValidSchema)(i,r))return;let s=t.name("valid");t.forIn("key",n,(o)=>{e.setParams({propertyName:o}),e.subschema({keyword:"propertyNames",data:o,dataTypes:["string"],propertyName:o,compositeRule:!0},s),t.if((0,xB.not)(s),()=>{if(e.error(!0),!i.allErrors)t.break()})}),e.ok(s)}};bB.default=qOe});var r_=h(function(_B){Object.defineProperty(_B,"__esModule",{value:!0});var B0=Vr(),mn=me(),MOe=wi(),L0=Pe(),BOe={message:"must NOT have additional properties",params:({params:e})=>mn._`{additionalProperty: ${e.additionalProperty}}`},LOe={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:BOe,code(e){let{gen:t,schema:r,parentSchema:n,data:i,errsCount:s,it:o}=e;if(!s)throw Error("ajv implementation error");let{allErrors:a,opts:c}=o;if(o.props=!0,c.removeAdditional!=="all"&&(0,L0.alwaysValidSchema)(o,r))return;let l=(0,B0.allSchemaProperties)(n.properties),d=(0,B0.allSchemaProperties)(n.patternProperties);f(),e.ok(mn._`${s} === ${MOe.default.errors}`);function f(){t.forIn("key",i,(x)=>{if(!l.length&&!d.length)g(x);else t.if(m(x),()=>g(x))})}function m(x){let v;if(l.length>8){let _=(0,L0.schemaRefOrVal)(o,n.properties,"properties");v=(0,B0.isOwnProperty)(t,_,x)}else if(l.length)v=(0,mn.or)(...l.map((_)=>mn._`${x} === ${_}`));else v=mn.nil;if(d.length)v=(0,mn.or)(v,...d.map((_)=>mn._`${(0,B0.usePattern)(e,_)}.test(${x})`));return(0,mn.not)(v)}function p(x){t.code(mn._`delete ${i}[${x}]`)}function g(x){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){p(x);return}if(r===!1){if(e.setParams({additionalProperty:x}),e.error(),!a)t.break();return}if(typeof r=="object"&&!(0,L0.alwaysValidSchema)(o,r)){let v=t.name("valid");if(c.removeAdditional==="failing")y(x,v,!1),t.if((0,mn.not)(v),()=>{e.reset(),p(x)});else if(y(x,v),!a)t.if((0,mn.not)(v),()=>t.break())}}function y(x,v,_){let E={keyword:"additionalProperties",dataProp:x,dataPropType:L0.Type.Str};if(_===!1)Object.assign(E,{compositeRule:!0,createErrors:!1,allErrors:!1});e.subschema(E,v)}}};_B.default=LOe});var SB=h(function(EB){Object.defineProperty(EB,"__esModule",{value:!0});var VOe=kl(),DB=Vr(),n_=Pe(),wB=r_(),zOe={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,parentSchema:n,data:i,it:s}=e;if(s.opts.removeAdditional==="all"&&n.additionalProperties===void 0)wB.default.code(new VOe.KeywordCxt(s,wB.default,"additionalProperties"));let o=(0,DB.allSchemaProperties)(r);for(let f of o)s.definedProperties.add(f);if(s.opts.unevaluated&&o.length&&s.props!==!0)s.props=n_.mergeEvaluated.props(t,(0,n_.toHash)(o),s.props);let a=o.filter((f)=>!(0,n_.alwaysValidSchema)(s,r[f]));if(a.length===0)return;let c=t.name("valid");for(let f of a){if(l(f))d(f);else{if(t.if((0,DB.propertyInData)(t,i,f,s.opts.ownProperties)),d(f),!s.allErrors)t.else().var(c,!0);t.endIf()}e.it.definedProperties.add(f),e.ok(c)}function l(f){return s.opts.useDefaults&&!s.compositeRule&&r[f].default!==void 0}function d(f){e.subschema({keyword:"properties",schemaProp:f,dataProp:f},c)}}};EB.default=zOe});var OB=h(function(RB){Object.defineProperty(RB,"__esModule",{value:!0});var $B=Vr(),U0=me(),CB=Pe(),FB=Pe(),GOe={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,data:n,parentSchema:i,it:s}=e,{opts:o}=s,a=(0,$B.allSchemaProperties)(r),c=a.filter((y)=>(0,CB.alwaysValidSchema)(s,r[y]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let l=o.strictSchema&&!o.allowMatchingProperties&&i.properties,d=t.name("valid");if(s.props!==!0&&!(s.props instanceof U0.Name))s.props=(0,FB.evaluatedPropsToName)(t,s.props);let{props:f}=s;m();function m(){for(let y of a){if(l)p(y);if(s.allErrors)g(y);else t.var(d,!0),g(y),t.if(d)}}function p(y){for(let x in l)if(new RegExp(y).test(x))(0,CB.checkStrictMode)(s,`property ${x} matches pattern ${y} (use allowMatchingProperties)`)}function g(y){t.forIn("key",n,(x)=>{t.if(U0._`${(0,$B.usePattern)(e,y)}.test(${x})`,()=>{let v=c.includes(y);if(!v)e.subschema({keyword:"patternProperties",schemaProp:y,dataProp:x,dataPropType:FB.Type.Str},d);if(s.opts.unevaluated&&f!==!0)t.assign(U0._`${f}[${x}]`,!0);else if(!v&&!s.allErrors)t.if((0,U0.not)(d),()=>t.break())})})}}};RB.default=GOe});var kB=h(function(AB){Object.defineProperty(AB,"__esModule",{value:!0});var KOe=Pe(),YOe={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,KOe.alwaysValidSchema)(n,r)){e.fail();return}let i=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},i),e.failResult(i,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};AB.default=YOe});var IB=h(function(PB){Object.defineProperty(PB,"__esModule",{value:!0});var XOe=Vr(),QOe={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:XOe.validateUnion,error:{message:"must match a schema in anyOf"}};PB.default=QOe});var NB=h(function(TB){Object.defineProperty(TB,"__esModule",{value:!0});var V0=me(),eAe=Pe(),tAe={message:"must match exactly one schema in oneOf",params:({params:e})=>V0._`{passingSchemas: ${e.passing}}`},rAe={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:tAe,code(e){let{gen:t,schema:r,parentSchema:n,it:i}=e;if(!Array.isArray(r))throw Error("ajv implementation error");if(i.opts.discriminator&&n.discriminator)return;let s=r,o=t.let("valid",!1),a=t.let("passing",null),c=t.name("_valid");e.setParams({passing:a}),t.block(l),e.result(o,()=>e.reset(),()=>e.error(!0));function l(){s.forEach((d,f)=>{let m;if((0,eAe.alwaysValidSchema)(i,d))t.var(c,!0);else m=e.subschema({keyword:"oneOf",schemaProp:f,compositeRule:!0},c);if(f>0)t.if(V0._`${c} && ${o}`).assign(o,!1).assign(a,V0._`[${a}, ${f}]`).else();t.if(c,()=>{if(t.assign(o,!0),t.assign(a,f),m)e.mergeEvaluated(m,V0.Name)})})}}};TB.default=rAe});var jB=h(function(qB){Object.defineProperty(qB,"__esModule",{value:!0});var iAe=Pe(),sAe={keyword:"allOf",schemaType:"array",code(e){let{gen:t,schema:r,it:n}=e;if(!Array.isArray(r))throw Error("ajv implementation error");let i=t.name("valid");r.forEach((s,o)=>{if((0,iAe.alwaysValidSchema)(n,s))return;let a=e.subschema({keyword:"allOf",schemaProp:o},i);e.ok(i),e.mergeEvaluated(a)})}};qB.default=sAe});var UB=h(function(LB){Object.defineProperty(LB,"__esModule",{value:!0});var z0=me(),BB=Pe(),aAe={message:({params:e})=>z0.str`must match "${e.ifClause}" schema`,params:({params:e})=>z0._`{failingKeyword: ${e.ifClause}}`},cAe={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:aAe,code(e){let{gen:t,parentSchema:r,it:n}=e;if(r.then===void 0&&r.else===void 0)(0,BB.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let i=MB(n,"then"),s=MB(n,"else");if(!i&&!s)return;let o=t.let("valid",!0),a=t.name("_valid");if(c(),e.reset(),i&&s){let d=t.let("ifClause");e.setParams({ifClause:d}),t.if(a,l("then",d),l("else",d))}else if(i)t.if(a,l("then"));else t.if((0,z0.not)(a),l("else"));e.pass(o,()=>e.error(!0));function c(){let d=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);e.mergeEvaluated(d)}function l(d,f){return()=>{let m=e.subschema({keyword:d},a);if(t.assign(o,a),e.mergeValidEvaluated(m,o),f)t.assign(f,z0._`${d}`);else e.setParams({ifClause:d})}}}};function MB(e,t){let r=e.schema[t];return r!==void 0&&!(0,BB.alwaysValidSchema)(e,r)}LB.default=cAe});var zB=h(function(VB){Object.defineProperty(VB,"__esModule",{value:!0});var lAe=Pe(),dAe={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){if(t.if===void 0)(0,lAe.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};VB.default=dAe});var GB=h(function(HB){Object.defineProperty(HB,"__esModule",{value:!0});var pAe=Zv(),mAe=oB(),hAe=e_(),gAe=uB(),yAe=dB(),xAe=yB(),bAe=vB(),vAe=r_(),_Ae=SB(),DAe=OB(),wAe=kB(),EAe=IB(),SAe=NB(),$Ae=jB(),CAe=UB(),FAe=zB();function RAe(e=!1){let t=[wAe.default,EAe.default,SAe.default,$Ae.default,CAe.default,FAe.default,bAe.default,vAe.default,xAe.default,_Ae.default,DAe.default];if(e)t.push(mAe.default,gAe.default);else t.push(pAe.default,hAe.default);return t.push(yAe.default),t}HB.default=RAe});var KB=h(function(WB){Object.defineProperty(WB,"__esModule",{value:!0});var mt=me(),AAe={message:({schemaCode:e})=>mt.str`must match format "${e}"`,params:({schemaCode:e})=>mt._`{format: ${e}}`},kAe={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:AAe,code(e,t){let{gen:r,data:n,$data:i,schema:s,schemaCode:o,it:a}=e,{opts:c,errSchemaPath:l,schemaEnv:d,self:f}=a;if(!c.validateFormats)return;if(i)m();else p();function m(){let g=r.scopeValue("formats",{ref:f.formats,code:c.code.formats}),y=r.const("fDef",mt._`${g}[${o}]`),x=r.let("fType"),v=r.let("format");r.if(mt._`typeof ${y} == "object" && !(${y} instanceof RegExp)`,()=>r.assign(x,mt._`${y}.type || "string"`).assign(v,mt._`${y}.validate`),()=>r.assign(x,mt._`"string"`).assign(v,y)),e.fail$data((0,mt.or)(_(),E()));function _(){if(c.strictSchema===!1)return mt.nil;return mt._`${o} && !${v}`}function E(){let S=d.$async?mt._`(${y}.async ? await ${v}(${n}) : ${v}(${n}))`:mt._`${v}(${n})`,D=mt._`(typeof ${v} == "function" ? ${S} : ${v}.test(${n}))`;return mt._`${v} && ${v} !== true && ${x} === ${t} && !${D}`}}function p(){let g=f.formats[s];if(!g){_();return}if(g===!0)return;let[y,x,v]=E(g);if(y===t)e.pass(S());function _(){if(c.strictSchema===!1){f.logger.warn(D());return}throw Error(D());function D(){return`unknown format "${s}" ignored in schema at path "${l}"`}}function E(D){let O=D instanceof RegExp?(0,mt.regexpCode)(D):c.code.formats?mt._`${c.code.formats}${(0,mt.getProperty)(s)}`:void 0,C=r.scopeValue("formats",{key:s,ref:D,code:O});if(typeof D=="object"&&!(D instanceof RegExp))return[D.type||"string",D.validate,mt._`${C}.validate`];return["string",D,C]}function S(){if(typeof g=="object"&&!(g instanceof RegExp)&&g.async){if(!d.$async)throw Error("async format in sync schema");return mt._`await ${v}(${n})`}return typeof x=="function"?mt._`${v}(${n})`:mt._`${v}.test(${n})`}}}};WB.default=kAe});var JB=h(function(YB){Object.defineProperty(YB,"__esModule",{value:!0});var IAe=KB(),TAe=[IAe.default];YB.default=TAe});var ZB=h(function(XB){Object.defineProperty(XB,"__esModule",{value:!0});XB.contentVocabulary=XB.metadataVocabulary=void 0;XB.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];XB.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var rL=h(function(tL){Object.defineProperty(tL,"__esModule",{value:!0});var jAe=EM(),MAe=XM(),BAe=GB(),LAe=JB(),eL=ZB(),UAe=[jAe.default,MAe.default,(0,BAe.default)(),LAe.default,eL.metadataVocabulary,eL.contentVocabulary];tL.default=UAe});var oL=h(function(iL){Object.defineProperty(iL,"__esModule",{value:!0});iL.DiscrError=void 0;var nL;(function(e){e.Tag="tag",e.Mapping="mapping"})(nL||(iL.DiscrError=nL={}))});var uL=h(function(cL){Object.defineProperty(cL,"__esModule",{value:!0});var cc=me(),i_=oL(),aL=R0(),zAe=Pl(),HAe=Pe(),GAe={message:({params:{discrError:e,tagName:t}})=>e===i_.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>cc._`{error: ${e}, tag: ${r}, tagValue: ${t}}`},WAe={keyword:"discriminator",type:"object",schemaType:"object",error:GAe,code(e){let{gen:t,data:r,schema:n,parentSchema:i,it:s}=e,{oneOf:o}=i;if(!s.opts.discriminator)throw Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw Error("discriminator: requires propertyName");if(n.mapping)throw Error("discriminator: mapping is not supported");if(!o)throw Error("discriminator: requires oneOf keyword");let c=t.let("valid",!1),l=t.const("tag",cc._`${r}${(0,cc.getProperty)(a)}`);t.if(cc._`typeof ${l} == "string"`,()=>d(),()=>e.error(!1,{discrError:i_.DiscrError.Tag,tag:l,tagName:a})),e.ok(c);function d(){let p=m();t.if(!1);for(let g in p)t.elseIf(cc._`${l} === ${g}`),t.assign(c,f(p[g]));t.else(),e.error(!1,{discrError:i_.DiscrError.Mapping,tag:l,tagName:a}),t.endIf()}function f(p){let g=t.name("valid"),y=e.subschema({keyword:"oneOf",schemaProp:p},g);return e.mergeEvaluated(y,cc.Name),g}function m(){var p;let g={},y=v(i),x=!0;for(let S=0;S<o.length;S++){let D=o[S];if((D===null||D===void 0?void 0:D.$ref)&&!(0,HAe.schemaHasRulesButRef)(D,s.self.RULES)){let C=D.$ref;if(D=aL.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,C),D instanceof aL.SchemaEnv)D=D.schema;if(D===void 0)throw new zAe.default(s.opts.uriResolver,s.baseId,C)}let O=(p=D===null||D===void 0?void 0:D.properties)===null||p===void 0?void 0:p[a];if(typeof O!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);x=x&&(y||v(D)),_(O,S)}if(!x)throw Error(`discriminator: "${a}" must be required`);return g;function v({required:S}){return Array.isArray(S)&&S.includes(a)}function _(S,D){if(S.const)E(S.const,D);else if(S.enum)for(let O of S.enum)E(O,D);else throw Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function E(S,D){if(typeof S!="string"||S in g)throw Error(`discriminator: "${a}" values must be unique strings`);g[S]=D}}}};cL.default=WAe});var lL=h(function(ZWe,YAe){YAe.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var fL=h(function(mr,s_){Object.defineProperty(mr,"__esModule",{value:!0});mr.MissingRefError=mr.ValidationError=mr.CodeGen=mr.Name=mr.nil=mr.stringify=mr.str=mr._=mr.KeywordCxt=mr.Ajv=void 0;var JAe=mM(),XAe=rL(),QAe=uL(),dL=lL(),ZAe=["/properties"],H0="http://json-schema.org/draft-07/schema";class zl extends JAe.default{_addVocabularies(){if(super._addVocabularies(),XAe.default.forEach((e)=>this.addVocabulary(e)),this.opts.discriminator)this.addKeyword(QAe.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(dL,ZAe):dL;this.addMetaSchema(e,H0,!1),this.refs["http://json-schema.org/schema"]=H0}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(H0)?H0:void 0)}}mr.Ajv=zl;s_.exports=mr=zl;s_.exports.Ajv=zl;Object.defineProperty(mr,"__esModule",{value:!0});mr.default=zl;var eke=kl();Object.defineProperty(mr,"KeywordCxt",{enumerable:!0,get:function(){return eke.KeywordCxt}});var uc=me();Object.defineProperty(mr,"_",{enumerable:!0,get:function(){return uc._}});Object.defineProperty(mr,"str",{enumerable:!0,get:function(){return uc.str}});Object.defineProperty(mr,"stringify",{enumerable:!0,get:function(){return uc.stringify}});Object.defineProperty(mr,"nil",{enumerable:!0,get:function(){return uc.nil}});Object.defineProperty(mr,"Name",{enumerable:!0,get:function(){return uc.Name}});Object.defineProperty(mr,"CodeGen",{enumerable:!0,get:function(){return uc.CodeGen}});var tke=C0();Object.defineProperty(mr,"ValidationError",{enumerable:!0,get:function(){return tke.default}});var rke=Pl();Object.defineProperty(mr,"MissingRefError",{enumerable:!0,get:function(){return rke.default}})});var mL=h(function(pL){Object.defineProperty(pL,"__esModule",{value:!0});pL.formatLimitDefinition=void 0;var ske=fL(),hn=me(),$s=hn.operators,G0={formatMaximum:{okStr:"<=",ok:$s.LTE,fail:$s.GT},formatMinimum:{okStr:">=",ok:$s.GTE,fail:$s.LT},formatExclusiveMaximum:{okStr:"<",ok:$s.LT,fail:$s.GTE},formatExclusiveMinimum:{okStr:">",ok:$s.GT,fail:$s.LTE}},oke={message:({keyword:e,schemaCode:t})=>hn.str`should be ${G0[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>hn._`{comparison: ${G0[e].okStr}, limit: ${t}}`};pL.formatLimitDefinition={keyword:Object.keys(G0),type:"string",schemaType:"string",$data:!0,error:oke,code(e){let{gen:t,data:r,schemaCode:n,keyword:i,it:s}=e,{opts:o,self:a}=s;if(!o.validateFormats)return;let c=new ske.KeywordCxt(s,a.RULES.all.format.definition,"format");if(c.$data)l();else d();function l(){let m=t.scopeValue("formats",{ref:a.formats,code:o.code.formats}),p=t.const("fmt",hn._`${m}[${c.schemaCode}]`);e.fail$data((0,hn.or)(hn._`typeof ${p} != "object"`,hn._`${p} instanceof RegExp`,hn._`typeof ${p}.compare != "function"`,f(p)))}function d(){let m=c.schema,p=a.formats[m];if(!p||p===!0)return;if(typeof p!="object"||p instanceof RegExp||typeof p.compare!="function")throw Error(`"${i}": format "${m}" does not define "compare" function`);let g=t.scopeValue("formats",{key:m,ref:p,code:o.code.formats?hn._`${o.code.formats}${(0,hn.getProperty)(m)}`:void 0});e.fail$data(f(g))}function f(m){return hn._`${m}.compare(${r}, ${n}) ${G0[i].fail} 0`}},dependencies:["format"]};var ake=(e)=>(e.addKeyword(pL.formatLimitDefinition),e);pL.default=ake});var xL=h(function(Hl,yL){Object.defineProperty(Hl,"__esModule",{value:!0});var lc=fq(),uke=mL(),a_=me(),hL=new a_.Name("fullFormats"),lke=new a_.Name("fastFormats"),c_=(e,t={keywords:!0})=>{if(Array.isArray(t))return gL(e,t,lc.fullFormats,hL),e;let[r,n]=t.mode==="fast"?[lc.fastFormats,lke]:[lc.fullFormats,hL],i=t.formats||lc.formatNames;if(gL(e,i,r,n),t.keywords)(0,uke.default)(e);return e};c_.get=(e,t="full")=>{let n=(t==="fast"?lc.fastFormats:lc.fullFormats)[e];if(!n)throw Error(`Unknown format "${e}"`);return n};function gL(e,t,r,n){var i,s;(i=(s=e.opts.code).formats)!==null&&i!==void 0||(s.formats=a_._`require("ajv-formats/dist/formats").${n}`);for(let o of t)e.addFormat(o,r[o])}yL.exports=Hl=c_;Object.defineProperty(Hl,"__esModule",{value:!0});Hl.default=c_});var dke=(e,t={})=>{if(typeof e!=="function")throw TypeError(`Expected the first argument to be a function, got \`${typeof e}\``);let{wait:r=0,maxWait:n=Number.POSITIVE_INFINITY,before:i=!1,after:s=!0}=t;if(r<0||n<0)throw RangeError("`wait` and `maxWait` must not be negative.");if(!i&&!s)throw Error("Both `before` and `after` are false, function wouldn't be called.");let o,a,c,l=function(...d){let f=this,m=()=>{if(o=void 0,a)clearTimeout(a),a=void 0;if(s)c=e.apply(f,d)},p=()=>{if(a=void 0,o)clearTimeout(o),o=void 0;if(s)c=e.apply(f,d)},g=i&&!o;if(clearTimeout(o),o=setTimeout(m,r),n>0&&n!==Number.POSITIVE_INFINITY&&!a)a=setTimeout(p,n);if(g)c=e.apply(f,d);return c};return Wu(l,e),l.cancel=()=>{if(o)clearTimeout(o),o=void 0;if(a)clearTimeout(a),a=void 0},l},u_;var bL=A(()=>{Mx();u_=dke});var Gl=h(function(dKe,vL){var fke=Number.MAX_SAFE_INTEGER||9007199254740991,pke=["major","premajor","minor","preminor","patch","prepatch","prerelease"];vL.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:16,MAX_SAFE_BUILD_LENGTH:250,MAX_SAFE_INTEGER:fke,RELEASE_TYPES:pke,SEMVER_SPEC_VERSION:"2.0.0",FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var Wl=h(function(fKe,_L){var mke=typeof process==="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};_L.exports=mke});var dc=h(function(Yn,DL){var{MAX_SAFE_COMPONENT_LENGTH:l_,MAX_SAFE_BUILD_LENGTH:hke,MAX_LENGTH:gke}=Gl(),yke=Wl();Yn=DL.exports={};var xke=Yn.re=[],bke=Yn.safeRe=[],V=Yn.src=[],vke=Yn.safeSrc=[],z=Yn.t={},_ke=0,d_="[a-zA-Z0-9-]",Dke=[["\\s",1],["\\d",gke],[d_,hke]],wke=(e)=>{for(let[t,r]of Dke)e=e.split(`${t}*`).join(`${t}{0,${r}}`).split(`${t}+`).join(`${t}{1,${r}}`);return e},se=(e,t,r)=>{let n=wke(t),i=_ke++;yke(e,i,t),z[e]=i,V[i]=t,vke[i]=n,xke[i]=new RegExp(t,r?"g":void 0),bke[i]=new RegExp(n,r?"g":void 0)};se("NUMERICIDENTIFIER","0|[1-9]\\d*");se("NUMERICIDENTIFIERLOOSE","\\d+");se("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${d_}*`);se("MAINVERSION",`(${V[z.NUMERICIDENTIFIER]})\\.(${V[z.NUMERICIDENTIFIER]})\\.(${V[z.NUMERICIDENTIFIER]})`);se("MAINVERSIONLOOSE",`(${V[z.NUMERICIDENTIFIERLOOSE]})\\.(${V[z.NUMERICIDENTIFIERLOOSE]})\\.(${V[z.NUMERICIDENTIFIERLOOSE]})`);se("PRERELEASEIDENTIFIER",`(?:${V[z.NONNUMERICIDENTIFIER]}|${V[z.NUMERICIDENTIFIER]})`);se("PRERELEASEIDENTIFIERLOOSE",`(?:${V[z.NONNUMERICIDENTIFIER]}|${V[z.NUMERICIDENTIFIERLOOSE]})`);se("PRERELEASE",`(?:-(${V[z.PRERELEASEIDENTIFIER]}(?:\\.${V[z.PRERELEASEIDENTIFIER]})*))`);se("PRERELEASELOOSE",`(?:-?(${V[z.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${V[z.PRERELEASEIDENTIFIERLOOSE]})*))`);se("BUILDIDENTIFIER",`${d_}+`);se("BUILD",`(?:\\+(${V[z.BUILDIDENTIFIER]}(?:\\.${V[z.BUILDIDENTIFIER]})*))`);se("FULLPLAIN",`v?${V[z.MAINVERSION]}${V[z.PRERELEASE]}?${V[z.BUILD]}?`);se("FULL",`^${V[z.FULLPLAIN]}$`);se("LOOSEPLAIN",`[v=\\s]*${V[z.MAINVERSIONLOOSE]}${V[z.PRERELEASELOOSE]}?${V[z.BUILD]}?`);se("LOOSE",`^${V[z.LOOSEPLAIN]}$`);se("GTLT","((?:<|>)?=?)");se("XRANGEIDENTIFIERLOOSE",`${V[z.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);se("XRANGEIDENTIFIER",`${V[z.NUMERICIDENTIFIER]}|x|X|\\*`);se("XRANGEPLAIN",`[v=\\s]*(${V[z.XRANGEIDENTIFIER]})(?:\\.(${V[z.XRANGEIDENTIFIER]})(?:\\.(${V[z.XRANGEIDENTIFIER]})(?:${V[z.PRERELEASE]})?${V[z.BUILD]}?)?)?`);se("XRANGEPLAINLOOSE",`[v=\\s]*(${V[z.XRANGEIDENTIFIERLOOSE]})(?:\\.(${V[z.XRANGEIDENTIFIERLOOSE]})(?:\\.(${V[z.XRANGEIDENTIFIERLOOSE]})(?:${V[z.PRERELEASELOOSE]})?${V[z.BUILD]}?)?)?`);se("XRANGE",`^${V[z.GTLT]}\\s*${V[z.XRANGEPLAIN]}$`);se("XRANGELOOSE",`^${V[z.GTLT]}\\s*${V[z.XRANGEPLAINLOOSE]}$`);se("COERCEPLAIN",`(^|[^\\d])(\\d{1,${l_}})(?:\\.(\\d{1,${l_}}))?(?:\\.(\\d{1,${l_}}))?`);se("COERCE",`${V[z.COERCEPLAIN]}(?:$|[^\\d])`);se("COERCEFULL",V[z.COERCEPLAIN]+`(?:${V[z.PRERELEASE]})?(?:${V[z.BUILD]})?(?:$|[^\\d])`);se("COERCERTL",V[z.COERCE],!0);se("COERCERTLFULL",V[z.COERCEFULL],!0);se("LONETILDE","(?:~>?)");se("TILDETRIM",`(\\s*)${V[z.LONETILDE]}\\s+`,!0);Yn.tildeTrimReplace="$1~";se("TILDE",`^${V[z.LONETILDE]}${V[z.XRANGEPLAIN]}$`);se("TILDELOOSE",`^${V[z.LONETILDE]}${V[z.XRANGEPLAINLOOSE]}$`);se("LONECARET","(?:\\^)");se("CARETTRIM",`(\\s*)${V[z.LONECARET]}\\s+`,!0);Yn.caretTrimReplace="$1^";se("CARET",`^${V[z.LONECARET]}${V[z.XRANGEPLAIN]}$`);se("CARETLOOSE",`^${V[z.LONECARET]}${V[z.XRANGEPLAINLOOSE]}$`);se("COMPARATORLOOSE",`^${V[z.GTLT]}\\s*(${V[z.LOOSEPLAIN]})$|^$`);se("COMPARATOR",`^${V[z.GTLT]}\\s*(${V[z.FULLPLAIN]})$|^$`);se("COMPARATORTRIM",`(\\s*)${V[z.GTLT]}\\s*(${V[z.LOOSEPLAIN]}|${V[z.XRANGEPLAIN]})`,!0);Yn.comparatorTrimReplace="$1$2$3";se("HYPHENRANGE",`^\\s*(${V[z.XRANGEPLAIN]})\\s+-\\s+(${V[z.XRANGEPLAIN]})\\s*$`);se("HYPHENRANGELOOSE",`^\\s*(${V[z.XRANGEPLAINLOOSE]})\\s+-\\s+(${V[z.XRANGEPLAINLOOSE]})\\s*$`);se("STAR","(<|>)?=?\\s*\\*");se("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");se("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var W0=h(function(pKe,wL){var Eke=Object.freeze({loose:!0}),Ske=Object.freeze({}),$ke=(e)=>{if(!e)return Ske;if(typeof e!=="object")return Eke;return e};wL.exports=$ke});var f_=h(function(mKe,$L){var EL=/^[0-9]+$/,SL=(e,t)=>{if(typeof e==="number"&&typeof t==="number")return e===t?0:e<t?-1:1;let r=EL.test(e),n=EL.test(t);if(r&&n)e=+e,t=+t;return e===t?0:r&&!n?-1:n&&!r?1:e<t?-1:1},Cke=(e,t)=>SL(t,e);$L.exports={compareIdentifiers:SL,rcompareIdentifiers:Cke}});var qt=h(function(hKe,FL){var K0=Wl(),{MAX_LENGTH:CL,MAX_SAFE_INTEGER:Y0}=Gl(),{safeRe:J0,t:X0}=dc(),Fke=W0(),{compareIdentifiers:p_}=f_();class gn{constructor(e,t){if(t=Fke(t),e instanceof gn)if(e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease)return e;else e=e.version;else if(typeof e!=="string")throw TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`);if(e.length>CL)throw TypeError(`version is longer than ${CL} characters`);K0("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;let r=e.trim().match(t.loose?J0[X0.LOOSE]:J0[X0.FULL]);if(!r)throw TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+r[1],this.minor=+r[2],this.patch=+r[3],this.major>Y0||this.major<0)throw TypeError("Invalid major version");if(this.minor>Y0||this.minor<0)throw TypeError("Invalid minor version");if(this.patch>Y0||this.patch<0)throw TypeError("Invalid patch version");if(!r[4])this.prerelease=[];else this.prerelease=r[4].split(".").map((n)=>{if(/^[0-9]+$/.test(n)){let i=+n;if(i>=0&&i<Y0)return i}return n});this.build=r[5]?r[5].split("."):[],this.format()}format(){if(this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length)this.version+=`-${this.prerelease.join(".")}`;return this.version}toString(){return this.version}compare(e){if(K0("SemVer.compare",this.version,this.options,e),!(e instanceof gn)){if(typeof e==="string"&&e===this.version)return 0;e=new gn(e,this.options)}if(e.version===this.version)return 0;return this.compareMain(e)||this.comparePre(e)}compareMain(e){if(!(e instanceof gn))e=new gn(e,this.options);if(this.major<e.major)return-1;if(this.major>e.major)return 1;if(this.minor<e.minor)return-1;if(this.minor>e.minor)return 1;if(this.patch<e.patch)return-1;if(this.patch>e.patch)return 1;return 0}comparePre(e){if(!(e instanceof gn))e=new gn(e,this.options);if(this.prerelease.length&&!e.prerelease.length)return-1;else if(!this.prerelease.length&&e.prerelease.length)return 1;else if(!this.prerelease.length&&!e.prerelease.length)return 0;let t=0;do{let r=this.prerelease[t],n=e.prerelease[t];if(K0("prerelease compare",t,r,n),r===void 0&&n===void 0)return 0;else if(n===void 0)return 1;else if(r===void 0)return-1;else if(r===n)continue;else return p_(r,n)}while(++t)}compareBuild(e){if(!(e instanceof gn))e=new gn(e,this.options);let t=0;do{let r=this.build[t],n=e.build[t];if(K0("build compare",t,r,n),r===void 0&&n===void 0)return 0;else if(n===void 0)return 1;else if(r===void 0)return-1;else if(r===n)continue;else return p_(r,n)}while(++t)}inc(e,t,r){if(e.startsWith("pre")){if(!t&&r===!1)throw Error("invalid increment argument: identifier is empty");if(t){let n=`-${t}`.match(this.options.loose?J0[X0.PRERELEASELOOSE]:J0[X0.PRERELEASE]);if(!n||n[1]!==t)throw Error(`invalid identifier: ${t}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t,r);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t,r);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t,r),this.inc("pre",t,r);break;case"prerelease":if(this.prerelease.length===0)this.inc("patch",t,r);this.inc("pre",t,r);break;case"release":if(this.prerelease.length===0)throw Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":if(this.minor!==0||this.patch!==0||this.prerelease.length===0)this.major++;this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":if(this.patch!==0||this.prerelease.length===0)this.minor++;this.patch=0,this.prerelease=[];break;case"patch":if(this.prerelease.length===0)this.patch++;this.prerelease=[];break;case"pre":{let n=Number(r)?1:0;if(this.prerelease.length===0)this.prerelease=[n];else{let i=this.prerelease.length;while(--i>=0)if(typeof this.prerelease[i]==="number")this.prerelease[i]++,i=-2;if(i===-1){if(t===this.prerelease.join(".")&&r===!1)throw Error("invalid increment argument: identifier already exists");this.prerelease.push(n)}}if(t){let i=[t,n];if(r===!1)i=[t];if(p_(this.prerelease[0],t)===0){if(isNaN(this.prerelease[1]))this.prerelease=i}else this.prerelease=i}break}default:throw Error(`invalid increment argument: ${e}`)}if(this.raw=this.format(),this.build.length)this.raw+=`+${this.build.join(".")}`;return this}}FL.exports=gn});var Do=h(function(gKe,OL){var RL=qt(),Rke=(e,t,r=!1)=>{if(e instanceof RL)return e;try{return new RL(e,t)}catch(n){if(!r)return null;throw n}};OL.exports=Rke});var kL=h(function(yKe,AL){var Oke=Do(),Ake=(e,t)=>{let r=Oke(e,t);return r?r.version:null};AL.exports=Ake});var IL=h(function(xKe,PL){var kke=Do(),Pke=(e,t)=>{let r=kke(e.trim().replace(/^[=v]+/,""),t);return r?r.version:null};PL.exports=Pke});var qL=h(function(bKe,NL){var TL=qt(),Ike=(e,t,r,n,i)=>{if(typeof r==="string")i=n,n=r,r=void 0;try{return new TL(e instanceof TL?e.version:e,r).inc(t,n,i).version}catch(s){return null}};NL.exports=Ike});var BL=h(function(vKe,ML){var jL=Do(),Tke=(e,t)=>{let r=jL(e,null,!0),n=jL(t,null,!0),i=r.compare(n);if(i===0)return null;let s=i>0,o=s?r:n,a=s?n:r,c=!!o.prerelease.length;if(!!a.prerelease.length&&!c){if(!a.patch&&!a.minor)return"major";if(a.compareMain(o)===0){if(a.minor&&!a.patch)return"minor";return"patch"}}let d=c?"pre":"";if(r.major!==n.major)return d+"major";if(r.minor!==n.minor)return d+"minor";if(r.patch!==n.patch)return d+"patch";return"prerelease"};ML.exports=Tke});var UL=h(function(_Ke,LL){var Nke=qt(),qke=(e,t)=>new Nke(e,t).major;LL.exports=qke});var zL=h(function(DKe,VL){var jke=qt(),Mke=(e,t)=>new jke(e,t).minor;VL.exports=Mke});var GL=h(function(wKe,HL){var Bke=qt(),Lke=(e,t)=>new Bke(e,t).patch;HL.exports=Lke});var KL=h(function(EKe,WL){var Uke=Do(),Vke=(e,t)=>{let r=Uke(e,t);return r&&r.prerelease.length?r.prerelease:null};WL.exports=Vke});var Hr=h(function(SKe,JL){var YL=qt(),zke=(e,t,r)=>new YL(e,r).compare(new YL(t,r));JL.exports=zke});var QL=h(function($Ke,XL){var Hke=Hr(),Gke=(e,t,r)=>Hke(t,e,r);XL.exports=Gke});var eU=h(function(CKe,ZL){var Wke=Hr(),Kke=(e,t)=>Wke(e,t,!0);ZL.exports=Kke});var Q0=h(function(FKe,rU){var tU=qt(),Yke=(e,t,r)=>{let n=new tU(e,r),i=new tU(t,r);return n.compare(i)||n.compareBuild(i)};rU.exports=Yke});var iU=h(function(RKe,nU){var Jke=Q0(),Xke=(e,t)=>e.sort((r,n)=>Jke(r,n,t));nU.exports=Xke});var oU=h(function(OKe,sU){var Qke=Q0(),Zke=(e,t)=>e.sort((r,n)=>Qke(n,r,t));sU.exports=Zke});var Kl=h(function(AKe,aU){var e8e=Hr(),t8e=(e,t,r)=>e8e(e,t,r)>0;aU.exports=t8e});var Z0=h(function(kKe,cU){var r8e=Hr(),n8e=(e,t,r)=>r8e(e,t,r)<0;cU.exports=n8e});var m_=h(function(PKe,uU){var i8e=Hr(),s8e=(e,t,r)=>i8e(e,t,r)===0;uU.exports=s8e});var h_=h(function(IKe,lU){var o8e=Hr(),a8e=(e,t,r)=>o8e(e,t,r)!==0;lU.exports=a8e});var em=h(function(TKe,dU){var c8e=Hr(),u8e=(e,t,r)=>c8e(e,t,r)>=0;dU.exports=u8e});var tm=h(function(NKe,fU){var l8e=Hr(),d8e=(e,t,r)=>l8e(e,t,r)<=0;fU.exports=d8e});var g_=h(function(qKe,pU){var f8e=m_(),p8e=h_(),m8e=Kl(),h8e=em(),g8e=Z0(),y8e=tm(),x8e=(e,t,r,n)=>{switch(t){case"===":if(typeof e==="object")e=e.version;if(typeof r==="object")r=r.version;return e===r;case"!==":if(typeof e==="object")e=e.version;if(typeof r==="object")r=r.version;return e!==r;case"":case"=":case"==":return f8e(e,r,n);case"!=":return p8e(e,r,n);case">":return m8e(e,r,n);case">=":return h8e(e,r,n);case"<":return g8e(e,r,n);case"<=":return y8e(e,r,n);default:throw TypeError(`Invalid operator: ${t}`)}};pU.exports=x8e});var hU=h(function(jKe,mU){var b8e=qt(),v8e=Do(),{safeRe:rm,t:nm}=dc(),_8e=(e,t)=>{if(e instanceof b8e)return e;if(typeof e==="number")e=String(e);if(typeof e!=="string")return null;t=t||{};let r=null;if(!t.rtl)r=e.match(t.includePrerelease?rm[nm.COERCEFULL]:rm[nm.COERCE]);else{let c=t.includePrerelease?rm[nm.COERCERTLFULL]:rm[nm.COERCERTL],l;while((l=c.exec(e))&&(!r||r.index+r[0].length!==e.length)){if(!r||l.index+l[0].length!==r.index+r[0].length)r=l;c.lastIndex=l.index+l[1].length+l[2].length}c.lastIndex=-1}if(r===null)return null;let n=r[2],i=r[3]||"0",s=r[4]||"0",o=t.includePrerelease&&r[5]?`-${r[5]}`:"",a=t.includePrerelease&&r[6]?`+${r[6]}`:"";return v8e(`${n}.${i}.${s}${o}${a}`,t)};mU.exports=_8e});var xU=h(function(MKe,yU){class gU{constructor(){this.max=1000,this.map=new Map}get(e){let t=this.map.get(e);if(t===void 0)return;else return this.map.delete(e),this.map.set(e,t),t}delete(e){return this.map.delete(e)}set(e,t){if(!this.delete(e)&&t!==void 0){if(this.map.size>=this.max){let n=this.map.keys().next().value;this.delete(n)}this.map.set(e,t)}return this}}yU.exports=gU});var Gr=h(function(BKe,DU){var D8e=/\s+/g;class Yl{constructor(e,t){if(t=E8e(t),e instanceof Yl)if(e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease)return e;else return new Yl(e.raw,t);if(e instanceof y_)return this.raw=e.value,this.set=[[e]],this.formatted=void 0,this;if(this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease,this.raw=e.trim().replace(D8e," "),this.set=this.raw.split("||").map((r)=>this.parseRange(r.trim())).filter((r)=>r.length),!this.set.length)throw TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let r=this.set[0];if(this.set=this.set.filter((n)=>!vU(n[0])),this.set.length===0)this.set=[r];else if(this.set.length>1){for(let n of this.set)if(n.length===1&&A8e(n[0])){this.set=[n];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let e=0;e<this.set.length;e++){if(e>0)this.formatted+="||";let t=this.set[e];for(let r=0;r<t.length;r++){if(r>0)this.formatted+=" ";this.formatted+=t[r].toString().trim()}}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){let r=((this.options.includePrerelease&&R8e)|(this.options.loose&&O8e))+":"+e,n=bU.get(r);if(n)return n;let i=this.options.loose,s=i?Jt[jt.HYPHENRANGELOOSE]:Jt[jt.HYPHENRANGE];e=e.replace(s,L8e(this.options.includePrerelease)),Xe("hyphen replace",e),e=e.replace(Jt[jt.COMPARATORTRIM],$8e),Xe("comparator trim",e),e=e.replace(Jt[jt.TILDETRIM],C8e),Xe("tilde trim",e),e=e.replace(Jt[jt.CARETTRIM],F8e),Xe("caret trim",e);let o=e.split(" ").map((d)=>k8e(d,this.options)).join(" ").split(/\s+/).map((d)=>B8e(d,this.options));if(i)o=o.filter((d)=>(Xe("loose invalid filter",d,this.options),!!d.match(Jt[jt.COMPARATORLOOSE])));Xe("range list",o);let a=new Map,c=o.map((d)=>new y_(d,this.options));for(let d of c){if(vU(d))return[d];a.set(d.value,d)}if(a.size>1&&a.has(""))a.delete("");let l=[...a.values()];return bU.set(r,l),l}intersects(e,t){if(!(e instanceof Yl))throw TypeError("a Range is required");return this.set.some((r)=>_U(r,t)&&e.set.some((n)=>_U(n,t)&&r.every((i)=>n.every((s)=>i.intersects(s,t)))))}test(e){if(!e)return!1;if(typeof e==="string")try{e=new S8e(e,this.options)}catch(t){return!1}for(let t=0;t<this.set.length;t++)if(U8e(this.set[t],e,this.options))return!0;return!1}}DU.exports=Yl;var w8e=xU(),bU=new w8e,E8e=W0(),y_=Jl(),Xe=Wl(),S8e=qt(),{safeRe:Jt,t:jt,comparatorTrimReplace:$8e,tildeTrimReplace:C8e,caretTrimReplace:F8e}=dc(),{FLAG_INCLUDE_PRERELEASE:R8e,FLAG_LOOSE:O8e}=Gl(),vU=(e)=>e.value==="<0.0.0-0",A8e=(e)=>e.value==="",_U=(e,t)=>{let r=!0,n=e.slice(),i=n.pop();while(r&&n.length)r=n.every((s)=>i.intersects(s,t)),i=n.pop();return r},k8e=(e,t)=>(e=e.replace(Jt[jt.BUILD],""),Xe("comp",e,t),e=T8e(e,t),Xe("caret",e),e=P8e(e,t),Xe("tildes",e),e=q8e(e,t),Xe("xrange",e),e=M8e(e,t),Xe("stars",e),e),Xt=(e)=>!e||e.toLowerCase()==="x"||e==="*",P8e=(e,t)=>e.trim().split(/\s+/).map((r)=>I8e(r,t)).join(" "),I8e=(e,t)=>{let r=t.loose?Jt[jt.TILDELOOSE]:Jt[jt.TILDE];return e.replace(r,(n,i,s,o,a)=>{Xe("tilde",e,n,i,s,o,a);let c;if(Xt(i))c="";else if(Xt(s))c=`>=${i}.0.0 <${+i+1}.0.0-0`;else if(Xt(o))c=`>=${i}.${s}.0 <${i}.${+s+1}.0-0`;else if(a)Xe("replaceTilde pr",a),c=`>=${i}.${s}.${o}-${a} <${i}.${+s+1}.0-0`;else c=`>=${i}.${s}.${o} <${i}.${+s+1}.0-0`;return Xe("tilde return",c),c})},T8e=(e,t)=>e.trim().split(/\s+/).map((r)=>N8e(r,t)).join(" "),N8e=(e,t)=>{Xe("caret",e,t);let r=t.loose?Jt[jt.CARETLOOSE]:Jt[jt.CARET],n=t.includePrerelease?"-0":"";return e.replace(r,(i,s,o,a,c)=>{Xe("caret",e,i,s,o,a,c);let l;if(Xt(s))l="";else if(Xt(o))l=`>=${s}.0.0${n} <${+s+1}.0.0-0`;else if(Xt(a))if(s==="0")l=`>=${s}.${o}.0${n} <${s}.${+o+1}.0-0`;else l=`>=${s}.${o}.0${n} <${+s+1}.0.0-0`;else if(c)if(Xe("replaceCaret pr",c),s==="0")if(o==="0")l=`>=${s}.${o}.${a}-${c} <${s}.${o}.${+a+1}-0`;else l=`>=${s}.${o}.${a}-${c} <${s}.${+o+1}.0-0`;else l=`>=${s}.${o}.${a}-${c} <${+s+1}.0.0-0`;else if(Xe("no pr"),s==="0")if(o==="0")l=`>=${s}.${o}.${a}${n} <${s}.${o}.${+a+1}-0`;else l=`>=${s}.${o}.${a}${n} <${s}.${+o+1}.0-0`;else l=`>=${s}.${o}.${a} <${+s+1}.0.0-0`;return Xe("caret return",l),l})},q8e=(e,t)=>(Xe("replaceXRanges",e,t),e.split(/\s+/).map((r)=>j8e(r,t)).join(" ")),j8e=(e,t)=>{e=e.trim();let r=t.loose?Jt[jt.XRANGELOOSE]:Jt[jt.XRANGE];return e.replace(r,(n,i,s,o,a,c)=>{Xe("xRange",e,n,i,s,o,a,c);let l=Xt(s),d=l||Xt(o),f=d||Xt(a),m=f;if(i==="="&&m)i="";if(c=t.includePrerelease?"-0":"",l)if(i===">"||i==="<")n="<0.0.0-0";else n="*";else if(i&&m){if(d)o=0;if(a=0,i===">")if(i=">=",d)s=+s+1,o=0,a=0;else o=+o+1,a=0;else if(i==="<=")if(i="<",d)s=+s+1;else o=+o+1;if(i==="<")c="-0";n=`${i+s}.${o}.${a}${c}`}else if(d)n=`>=${s}.0.0${c} <${+s+1}.0.0-0`;else if(f)n=`>=${s}.${o}.0${c} <${s}.${+o+1}.0-0`;return Xe("xRange return",n),n})},M8e=(e,t)=>(Xe("replaceStars",e,t),e.trim().replace(Jt[jt.STAR],"")),B8e=(e,t)=>(Xe("replaceGTE0",e,t),e.trim().replace(Jt[t.includePrerelease?jt.GTE0PRE:jt.GTE0],"")),L8e=(e)=>(t,r,n,i,s,o,a,c,l,d,f,m)=>{if(Xt(n))r="";else if(Xt(i))r=`>=${n}.0.0${e?"-0":""}`;else if(Xt(s))r=`>=${n}.${i}.0${e?"-0":""}`;else if(o)r=`>=${r}`;else r=`>=${r}${e?"-0":""}`;if(Xt(l))c="";else if(Xt(d))c=`<${+l+1}.0.0-0`;else if(Xt(f))c=`<${l}.${+d+1}.0-0`;else if(m)c=`<=${l}.${d}.${f}-${m}`;else if(e)c=`<${l}.${d}.${+f+1}-0`;else c=`<=${c}`;return`${r} ${c}`.trim()},U8e=(e,t,r)=>{for(let n=0;n<e.length;n++)if(!e[n].test(t))return!1;if(t.prerelease.length&&!r.includePrerelease){for(let n=0;n<e.length;n++){if(Xe(e[n].semver),e[n].semver===y_.ANY)continue;if(e[n].semver.prerelease.length>0){let i=e[n].semver;if(i.major===t.major&&i.minor===t.minor&&i.patch===t.patch)return!0}}return!1}return!0}});var Jl=h(function(LKe,FU){var Xl=Symbol("SemVer ANY");class im{static get ANY(){return Xl}constructor(e,t){if(t=wU(t),e instanceof im)if(e.loose===!!t.loose)return e;else e=e.value;if(e=e.trim().split(/\s+/).join(" "),b_("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===Xl)this.value="";else this.value=this.operator+this.semver.version;b_("comp",this)}parse(e){let t=this.options.loose?EU[SU.COMPARATORLOOSE]:EU[SU.COMPARATOR],r=e.match(t);if(!r)throw TypeError(`Invalid comparator: ${e}`);if(this.operator=r[1]!==void 0?r[1]:"",this.operator==="=")this.operator="";if(!r[2])this.semver=Xl;else this.semver=new $U(r[2],this.options.loose)}toString(){return this.value}test(e){if(b_("Comparator.test",e,this.options.loose),this.semver===Xl||e===Xl)return!0;if(typeof e==="string")try{e=new $U(e,this.options)}catch(t){return!1}return x_(e,this.operator,this.semver,this.options)}intersects(e,t){if(!(e instanceof im))throw TypeError("a Comparator is required");if(this.operator===""){if(this.value==="")return!0;return new CU(e.value,t).test(this.value)}else if(e.operator===""){if(e.value==="")return!0;return new CU(this.value,t).test(e.semver)}if(t=wU(t),t.includePrerelease&&(this.value==="<0.0.0-0"||e.value==="<0.0.0-0"))return!1;if(!t.includePrerelease&&(this.value.startsWith("<0.0.0")||e.value.startsWith("<0.0.0")))return!1;if(this.operator.startsWith(">")&&e.operator.startsWith(">"))return!0;if(this.operator.startsWith("<")&&e.operator.startsWith("<"))return!0;if(this.semver.version===e.semver.version&&this.operator.includes("=")&&e.operator.includes("="))return!0;if(x_(this.semver,"<",e.semver,t)&&this.operator.startsWith(">")&&e.operator.startsWith("<"))return!0;if(x_(this.semver,">",e.semver,t)&&this.operator.startsWith("<")&&e.operator.startsWith(">"))return!0;return!1}}FU.exports=im;var wU=W0(),{safeRe:EU,t:SU}=dc(),x_=g_(),b_=Wl(),$U=qt(),CU=Gr()});var Ql=h(function(UKe,RU){var V8e=Gr(),z8e=(e,t,r)=>{try{t=new V8e(t,r)}catch(n){return!1}return t.test(e)};RU.exports=z8e});var AU=h(function(VKe,OU){var H8e=Gr(),G8e=(e,t)=>new H8e(e,t).set.map((r)=>r.map((n)=>n.value).join(" ").trim().split(" "));OU.exports=G8e});var PU=h(function(zKe,kU){var W8e=qt(),K8e=Gr(),Y8e=(e,t,r)=>{let n=null,i=null,s=null;try{s=new K8e(t,r)}catch(o){return null}return e.forEach((o)=>{if(s.test(o)){if(!n||i.compare(o)===-1)n=o,i=new W8e(n,r)}}),n};kU.exports=Y8e});var TU=h(function(HKe,IU){var J8e=qt(),X8e=Gr(),Q8e=(e,t,r)=>{let n=null,i=null,s=null;try{s=new X8e(t,r)}catch(o){return null}return e.forEach((o)=>{if(s.test(o)){if(!n||i.compare(o)===1)n=o,i=new J8e(n,r)}}),n};IU.exports=Q8e});var jU=h(function(GKe,qU){var v_=qt(),Z8e=Gr(),NU=Kl(),ePe=(e,t)=>{e=new Z8e(e,t);let r=new v_("0.0.0");if(e.test(r))return r;if(r=new v_("0.0.0-0"),e.test(r))return r;r=null;for(let n=0;n<e.set.length;++n){let i=e.set[n],s=null;if(i.forEach((o)=>{let a=new v_(o.semver.version);switch(o.operator){case">":if(a.prerelease.length===0)a.patch++;else a.prerelease.push(0);a.raw=a.format();case"":case">=":if(!s||NU(a,s))s=a;break;case"<":case"<=":break;default:throw Error(`Unexpected operation: ${o.operator}`)}}),s&&(!r||NU(r,s)))r=s}if(r&&e.test(r))return r;return null};qU.exports=ePe});var BU=h(function(WKe,MU){var tPe=Gr(),rPe=(e,t)=>{try{return new tPe(e,t).range||"*"}catch(r){return null}};MU.exports=rPe});var sm=h(function(KKe,zU){var nPe=qt(),VU=Jl(),{ANY:iPe}=VU,sPe=Gr(),oPe=Ql(),LU=Kl(),UU=Z0(),aPe=tm(),cPe=em(),uPe=(e,t,r,n)=>{e=new nPe(e,n),t=new sPe(t,n);let i,s,o,a,c;switch(r){case">":i=LU,s=aPe,o=UU,a=">",c=">=";break;case"<":i=UU,s=cPe,o=LU,a="<",c="<=";break;default:throw TypeError('Must provide a hilo val of "<" or ">"')}if(oPe(e,t,n))return!1;for(let l=0;l<t.set.length;++l){let d=t.set[l],f=null,m=null;if(d.forEach((p)=>{if(p.semver===iPe)p=new VU(">=0.0.0");if(f=f||p,m=m||p,i(p.semver,f.semver,n))f=p;else if(o(p.semver,m.semver,n))m=p}),f.operator===a||f.operator===c)return!1;if((!m.operator||m.operator===a)&&s(e,m.semver))return!1;else if(m.operator===c&&o(e,m.semver))return!1}return!0};zU.exports=uPe});var GU=h(function(YKe,HU){var lPe=sm(),dPe=(e,t,r)=>lPe(e,t,">",r);HU.exports=dPe});var KU=h(function(JKe,WU){var fPe=sm(),pPe=(e,t,r)=>fPe(e,t,"<",r);WU.exports=pPe});var XU=h(function(XKe,JU){var YU=Gr(),mPe=(e,t,r)=>(e=new YU(e,r),t=new YU(t,r),e.intersects(t,r));JU.exports=mPe});var ZU=h(function(QKe,QU){var hPe=Ql(),gPe=Hr();QU.exports=(e,t,r)=>{let n=[],i=null,s=null,o=e.sort((d,f)=>gPe(d,f,r));for(let d of o)if(hPe(d,t,r)){if(s=d,!i)i=d}else{if(s)n.push([i,s]);s=null,i=null}if(i)n.push([i,null]);let a=[];for(let[d,f]of n)if(d===f)a.push(d);else if(!f&&d===o[0])a.push("*");else if(!f)a.push(`>=${d}`);else if(d===o[0])a.push(`<=${f}`);else a.push(`${d} - ${f}`);let c=a.join(" || "),l=typeof t.raw==="string"?t.raw:String(t);return c.length<l.length?c:t}});var sV=h(function(ZKe,iV){var eV=Gr(),D_=Jl(),{ANY:__}=D_,Zl=Ql(),w_=Hr(),yPe=(e,t,r={})=>{if(e===t)return!0;e=new eV(e,r),t=new eV(t,r);let n=!1;e:for(let i of e.set){for(let s of t.set){let o=bPe(i,s,r);if(n=n||o!==null,o)continue e}if(n)return!1}return!0},xPe=[new D_(">=0.0.0-0")],tV=[new D_(">=0.0.0")],bPe=(e,t,r)=>{if(e===t)return!0;if(e.length===1&&e[0].semver===__)if(t.length===1&&t[0].semver===__)return!0;else if(r.includePrerelease)e=xPe;else e=tV;if(t.length===1&&t[0].semver===__)if(r.includePrerelease)return!0;else t=tV;let n=new Set,i,s;for(let p of e)if(p.operator===">"||p.operator===">=")i=rV(i,p,r);else if(p.operator==="<"||p.operator==="<=")s=nV(s,p,r);else n.add(p.semver);if(n.size>1)return null;let o;if(i&&s){if(o=w_(i.semver,s.semver,r),o>0)return null;else if(o===0&&(i.operator!==">="||s.operator!=="<="))return null}for(let p of n){if(i&&!Zl(p,String(i),r))return null;if(s&&!Zl(p,String(s),r))return null;for(let g of t)if(!Zl(p,String(g),r))return!1;return!0}let a,c,l,d,f=s&&!r.includePrerelease&&s.semver.prerelease.length?s.semver:!1,m=i&&!r.includePrerelease&&i.semver.prerelease.length?i.semver:!1;if(f&&f.prerelease.length===1&&s.operator==="<"&&f.prerelease[0]===0)f=!1;for(let p of t){if(d=d||p.operator===">"||p.operator===">=",l=l||p.operator==="<"||p.operator==="<=",i){if(m){if(p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===m.major&&p.semver.minor===m.minor&&p.semver.patch===m.patch)m=!1}if(p.operator===">"||p.operator===">="){if(a=rV(i,p,r),a===p&&a!==i)return!1}else if(i.operator===">="&&!Zl(i.semver,String(p),r))return!1}if(s){if(f){if(p.semver.prerelease&&p.semver.prerelease.length&&p.semver.major===f.major&&p.semver.minor===f.minor&&p.semver.patch===f.patch)f=!1}if(p.operator==="<"||p.operator==="<="){if(c=nV(s,p,r),c===p&&c!==s)return!1}else if(s.operator==="<="&&!Zl(s.semver,String(p),r))return!1}if(!p.operator&&(s||i)&&o!==0)return!1}if(i&&l&&!s&&o!==0)return!1;if(s&&d&&!i&&o!==0)return!1;if(m||f)return!1;return!0},rV=(e,t,r)=>{if(!e)return t;let n=w_(e.semver,t.semver,r);return n>0?e:n<0?t:t.operator===">"&&e.operator===">="?t:e},nV=(e,t,r)=>{if(!e)return t;let n=w_(e.semver,t.semver,r);return n<0?e:n>0?t:t.operator==="<"&&e.operator==="<="?t:e};iV.exports=yPe});var uV=h(function(eYe,cV){var E_=dc(),oV=Gl(),vPe=qt(),aV=f_(),_Pe=Do(),DPe=kL(),wPe=IL(),EPe=qL(),SPe=BL(),$Pe=UL(),CPe=zL(),FPe=GL(),RPe=KL(),OPe=Hr(),APe=QL(),kPe=eU(),PPe=Q0(),IPe=iU(),TPe=oU(),NPe=Kl(),qPe=Z0(),jPe=m_(),MPe=h_(),BPe=em(),LPe=tm(),UPe=g_(),VPe=hU(),zPe=Jl(),HPe=Gr(),GPe=Ql(),WPe=AU(),KPe=PU(),YPe=TU(),JPe=jU(),XPe=BU(),QPe=sm(),ZPe=GU(),e4e=KU(),t4e=XU(),r4e=ZU(),n4e=sV();cV.exports={parse:_Pe,valid:DPe,clean:wPe,inc:EPe,diff:SPe,major:$Pe,minor:CPe,patch:FPe,prerelease:RPe,compare:OPe,rcompare:APe,compareLoose:kPe,compareBuild:PPe,sort:IPe,rsort:TPe,gt:NPe,lt:qPe,eq:jPe,neq:MPe,gte:BPe,lte:LPe,cmp:UPe,coerce:VPe,Comparator:zPe,Range:HPe,satisfies:GPe,toComparators:WPe,maxSatisfying:KPe,minSatisfying:YPe,minVersion:JPe,validRange:XPe,outside:QPe,gtr:ZPe,ltr:e4e,intersects:t4e,simplifyRange:r4e,subset:n4e,SemVer:vPe,re:E_.re,src:E_.src,tokens:E_.t,SEMVER_SPEC_VERSION:oV.SEMVER_SPEC_VERSION,RELEASE_TYPES:oV.RELEASE_TYPES,compareIdentifiers:aV.compareIdentifiers,rcompareIdentifiers:aV.rcompareIdentifiers}});function dV(e,t,r){if(!e)return!1;if(e.constructor===t)return!0;return i4e.call(e)===r}function fV(e){return dV(e,Uint8Array,"[object Uint8Array]")}function s4e(e){return dV(e,ArrayBuffer,"[object ArrayBuffer]")}function o4e(e){return fV(e)||s4e(e)}function a4e(e){if(!fV(e))throw TypeError(`Expected \`Uint8Array\`, got \`${typeof e}\``)}function c4e(e){if(!o4e(e))throw TypeError(`Expected \`Uint8Array\` or \`ArrayBuffer\`, got \`${typeof e}\``)}function S_(e,t){if(e.length===0)return new Uint8Array(0);t??=e.reduce((i,s)=>i+s.length,0);let r=new Uint8Array(t),n=0;for(let i of e)a4e(i),r.set(i,n),n+=i.length;return r}function $_(e,t="utf8"){return c4e(e),lV[t]??=new globalThis.TextDecoder(t),lV[t].decode(e)}function u4e(e){if(typeof e!=="string")throw TypeError(`Expected \`string\`, got \`${typeof e}\``)}function om(e){return u4e(e),l4e.encode(e)}var i4e,lV,l4e,tYe;var pV=A(()=>{i4e=Object.prototype.toString;lV={utf8:new globalThis.TextDecoder("utf8")};l4e=new globalThis.TextEncoder;tYe=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"))});import{isDeepStrictEqual as d4e}from"util";import mV from"process";import wo from"fs";import hV from"path";import ed from"crypto";import f4e from"assert";var yV,xV,Eo,p4e,gV="aes-256-cbc",fc=()=>Object.create(null),m4e=(e)=>e!==void 0&&e!==null,h4e=(e,t)=>{let r=new Set(["undefined","symbol","function"]),n=typeof t;if(r.has(n))throw TypeError(`Setting a value of type \`${n}\` for key \`${e}\` is not allowed as it's not supported by JSON`)},am="__internal__",C_,cm;var bV=A(()=>{CI();RI();sT();bL();pV();yV=ne(rq(),1),xV=ne(xL(),1),Eo=ne(uV(),1),p4e=xV.default.default,C_=`${am}.migrations.version`;cm=class cm{path;events;#r;#t;#e;#i={};constructor(e={}){let t={configName:"config",fileExtension:"json",projectSuffix:"nodejs",clearInvalidConfig:!1,accessPropertiesByDotNotation:!0,configFileMode:438,...e};if(!t.cwd){if(!t.projectName)throw Error("Please specify the `projectName` option.");t.cwd=nb(t.projectName,{suffix:t.projectSuffix}).config}if(this.#e=t,t.schema??t.ajvOptions??t.rootSchema){if(t.schema&&typeof t.schema!=="object")throw TypeError("The `schema` option must be an object.");let s=new yV.Ajv2020({allErrors:!0,useDefaults:!0,...t.ajvOptions});p4e(s);let o={...t.rootSchema,type:"object",properties:t.schema};this.#r=s.compile(o);for(let[a,c]of Object.entries(t.schema??{}))if(c?.default)this.#i[a]=c.default}if(t.defaults)this.#i={...this.#i,...t.defaults};if(t.serialize)this._serialize=t.serialize;if(t.deserialize)this._deserialize=t.deserialize;this.events=new EventTarget,this.#t=t.encryptionKey;let r=t.fileExtension?`.${t.fileExtension}`:"";this.path=hV.resolve(t.cwd,`${t.configName??"config"}${r}`);let n=this.store,i=Object.assign(fc(),t.defaults,n);if(t.migrations){if(!t.projectVersion)throw Error("Please specify the `projectVersion` option.");this._migrate(t.migrations,t.projectVersion,t.beforeEachMigration)}this._validate(i);try{f4e.deepEqual(n,i)}catch{this.store=i}if(t.watch)this._watch()}get(e,t){if(this.#e.accessPropertiesByDotNotation)return this._get(e,t);let{store:r}=this;return e in r?r[e]:t}set(e,t){if(typeof e!=="string"&&typeof e!=="object")throw TypeError(`Expected \`key\` to be of type \`string\` or \`object\`, got ${typeof e}`);if(typeof e!=="object"&&t===void 0)throw TypeError("Use `delete()` to clear values");if(this._containsReservedKey(e))throw TypeError(`Please don't use the ${am} key, as it's used to manage this module internal operations.`);let{store:r}=this,n=(i,s)=>{if(h4e(i,s),this.#e.accessPropertiesByDotNotation)eb(r,i,s);else r[i]=s};if(typeof e==="object"){let i=e;for(let[s,o]of Object.entries(i))n(s,o)}else n(e,t);this.store=r}has(e){if(this.#e.accessPropertiesByDotNotation)return $I(this.store,e);return e in this.store}reset(...e){for(let t of e)if(m4e(this.#i[t]))this.set(t,this.#i[t])}delete(e){let{store:t}=this;if(this.#e.accessPropertiesByDotNotation)SI(t,e);else delete t[e];this.store=t}clear(){this.store=fc();for(let e of Object.keys(this.#i))this.reset(e)}onDidChange(e,t){if(typeof e!=="string")throw TypeError(`Expected \`key\` to be of type \`string\`, got ${typeof e}`);if(typeof t!=="function")throw TypeError(`Expected \`callback\` to be of type \`function\`, got ${typeof t}`);return this._handleChange(()=>this.get(e),t)}onDidAnyChange(e){if(typeof e!=="function")throw TypeError(`Expected \`callback\` to be of type \`function\`, got ${typeof e}`);return this._handleChange(()=>this.store,e)}get size(){return Object.keys(this.store).length}get store(){try{let e=wo.readFileSync(this.path,this.#t?null:"utf8"),t=this._encryptData(e),r=this._deserialize(t);return this._validate(r),Object.assign(fc(),r)}catch(e){if(e?.code==="ENOENT")return this._ensureDirectory(),fc();if(this.#e.clearInvalidConfig&&e.name==="SyntaxError")return fc();throw e}}set store(e){this._ensureDirectory(),this._validate(e),this._write(e),this.events.dispatchEvent(new Event("change"))}*[Symbol.iterator](){for(let[e,t]of Object.entries(this.store))yield[e,t]}_encryptData(e){if(!this.#t)return typeof e==="string"?e:$_(e);try{let t=e.slice(0,16),r=ed.pbkdf2Sync(this.#t,t.toString(),1e4,32,"sha512"),n=ed.createDecipheriv(gV,r,t),i=e.slice(17),s=typeof i==="string"?om(i):i;return $_(S_([n.update(s),n.final()]))}catch{}return e.toString()}_handleChange(e,t){let r=e(),n=()=>{let i=r,s=e();if(d4e(s,i))return;r=s,t.call(this,s,i)};return this.events.addEventListener("change",n),()=>{this.events.removeEventListener("change",n)}}_deserialize=(e)=>JSON.parse(e);_serialize=(e)=>JSON.stringify(e,void 0,"\t");_validate(e){if(!this.#r)return;if(this.#r(e)||!this.#r.errors)return;let r=this.#r.errors.map(({instancePath:n,message:i=""})=>`\`${n.slice(1)}\` ${i}`);throw Error("Config schema violation: "+r.join("; "))}_ensureDirectory(){wo.mkdirSync(hV.dirname(this.path),{recursive:!0})}_write(e){let t=this._serialize(e);if(this.#t){let r=ed.randomBytes(16),n=ed.pbkdf2Sync(this.#t,r.toString(),1e4,32,"sha512"),i=ed.createCipheriv(gV,n,r);t=S_([r,om(":"),i.update(om(t)),i.final()])}if(mV.env.SNAP)wo.writeFileSync(this.path,t,{mode:this.#e.configFileMode});else try{mb(this.path,t,{mode:this.#e.configFileMode})}catch(r){if(r?.code==="EXDEV"){wo.writeFileSync(this.path,t,{mode:this.#e.configFileMode});return}throw r}}_watch(){if(this._ensureDirectory(),!wo.existsSync(this.path))this._write(fc());if(mV.platform==="win32")wo.watch(this.path,{persistent:!1},u_(()=>{this.events.dispatchEvent(new Event("change"))},{wait:100}));else wo.watchFile(this.path,{persistent:!1},u_(()=>{this.events.dispatchEvent(new Event("change"))},{wait:5000}))}_migrate(e,t,r){let n=this._get(C_,"0.0.0"),i=Object.keys(e).filter((o)=>this._shouldPerformMigration(o,n,t)),s={...this.store};for(let o of i)try{if(r)r(this,{fromVersion:n,toVersion:o,finalVersion:t,versions:i});let a=e[o];a?.(this),this._set(C_,o),n=o,s={...this.store}}catch(a){throw this.store=s,Error(`Something went wrong during the migration! Changes applied to the store until this failed migration will be restored. ${a}`)}if(this._isVersionInRangeFormat(n)||!Eo.default.eq(n,t))this._set(C_,t)}_containsReservedKey(e){if(typeof e==="object"){if(Object.keys(e)[0]===am)return!0}if(typeof e!=="string")return!1;if(this.#e.accessPropertiesByDotNotation){if(e.startsWith(`${am}.`))return!0;return!1}return!1}_isVersionInRangeFormat(e){return Eo.default.clean(e)===null}_shouldPerformMigration(e,t,r){if(this._isVersionInRangeFormat(e)){if(t!=="0.0.0"&&Eo.default.satisfies(t,e))return!1;return Eo.default.satisfies(r,e)}if(Eo.default.lte(e,t))return!1;if(Eo.default.gt(e,r))return!1;return!0}_get(e,t){return EI(this.store,e,t)}_set(e,t){let{store:r}=this;eb(r,e,t),this.store=r}}});var be,F_,N,Jn=(e)=>{switch(typeof e){case"undefined":return N.undefined;case"string":return N.string;case"number":return Number.isNaN(e)?N.nan:N.number;case"boolean":return N.boolean;case"function":return N.function;case"bigint":return N.bigint;case"symbol":return N.symbol;case"object":if(Array.isArray(e))return N.array;if(e===null)return N.null;if(e.then&&typeof e.then==="function"&&e.catch&&typeof e.catch==="function")return N.promise;if(typeof Map<"u"&&e instanceof Map)return N.map;if(typeof Set<"u"&&e instanceof Set)return N.set;if(typeof Date<"u"&&e instanceof Date)return N.date;return N.object;default:return N.unknown}};var td=A(()=>{(function(e){e.assertEqual=(i)=>{};function t(i){}e.assertIs=t;function r(i){throw Error()}e.assertNever=r,e.arrayToEnum=(i)=>{let s={};for(let o of i)s[o]=o;return s},e.getValidEnumValues=(i)=>{let s=e.objectKeys(i).filter((a)=>typeof i[i[a]]!=="number"),o={};for(let a of s)o[a]=i[a];return e.objectValues(o)},e.objectValues=(i)=>e.objectKeys(i).map(function(s){return i[s]}),e.objectKeys=typeof Object.keys==="function"?(i)=>Object.keys(i):(i)=>{let s=[];for(let o in i)if(Object.prototype.hasOwnProperty.call(i,o))s.push(o);return s},e.find=(i,s)=>{for(let o of i)if(s(o))return o;return},e.isInteger=typeof Number.isInteger==="function"?(i)=>Number.isInteger(i):(i)=>typeof i==="number"&&Number.isFinite(i)&&Math.floor(i)===i;function n(i,s=" | "){return i.map((o)=>typeof o==="string"?`'${o}'`:o).join(s)}e.joinValues=n,e.jsonStringifyReplacer=(i,s)=>{if(typeof s==="bigint")return s.toString();return s}})(be||(be={}));(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(F_||(F_={}));N=be.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"])});var P,g4e=(e)=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),hr;var um=A(()=>{td();P=be.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"]);hr=class hr extends Error{get errors(){return this.issues}constructor(e){super();this.issues=[],this.addIssue=(r)=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};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(i){return i.message},r={_errors:[]},n=(i)=>{for(let s of i.issues)if(s.code==="invalid_union")s.unionErrors.map(n);else if(s.code==="invalid_return_type")n(s.returnTypeError);else if(s.code==="invalid_arguments")n(s.argumentsError);else if(s.path.length===0)r._errors.push(t(s));else{let o=r,a=0;while(a<s.path.length){let c=s.path[a];if(a!==s.path.length-1)o[c]=o[c]||{_errors:[]};else o[c]=o[c]||{_errors:[]},o[c]._errors.push(t(s));o=o[c],a++}}};return n(this),r}static assert(e){if(!(e instanceof hr))throw Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,be.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=(t)=>t.message){let t={},r=[];for(let n of this.issues)if(n.path.length>0){let i=n.path[0];t[i]=t[i]||[],t[i].push(e(n))}else r.push(e(n));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}};hr.create=(e)=>new hr(e)});var y4e=(e,t)=>{let r;switch(e.code){case P.invalid_type:if(e.received===N.undefined)r="Required";else r=`Expected ${e.expected}, received ${e.received}`;break;case P.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,be.jsonStringifyReplacer)}`;break;case P.unrecognized_keys:r=`Unrecognized key(s) in object: ${be.joinValues(e.keys,", ")}`;break;case P.invalid_union:r="Invalid input";break;case P.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${be.joinValues(e.options)}`;break;case P.invalid_enum_value:r=`Invalid enum value. Expected ${be.joinValues(e.options)}, received '${e.received}'`;break;case P.invalid_arguments:r="Invalid function arguments";break;case P.invalid_return_type:r="Invalid function return type";break;case P.invalid_date:r="Invalid date";break;case P.invalid_string:if(typeof e.validation==="object")if("includes"in e.validation){if(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==="number")r=`${r} at one or more positions greater than or equal to ${e.validation.position}`}else if("startsWith"in e.validation)r=`Invalid input: must start with "${e.validation.startsWith}"`;else if("endsWith"in e.validation)r=`Invalid input: must end with "${e.validation.endsWith}"`;else be.assertNever(e.validation);else if(e.validation!=="regex")r=`Invalid ${e.validation}`;else r="Invalid";break;case P.too_small:if(e.type==="array")r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`;else if(e.type==="string")r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`;else if(e.type==="number")r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`;else if(e.type==="bigint")r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`;else if(e.type==="date")r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`;else r="Invalid input";break;case P.too_big:if(e.type==="array")r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`;else if(e.type==="string")r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`;else if(e.type==="number")r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`;else if(e.type==="bigint")r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`;else if(e.type==="date")r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`;else r="Invalid input";break;case P.custom:r="Invalid input";break;case P.invalid_intersection_types:r="Intersection results could not be merged";break;case P.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case P.not_finite:r="Number must be finite";break;default:r=t.defaultError,be.assertNever(e)}return{message:r}},$i;var R_=A(()=>{um();td();$i=y4e});function x4e(e){vV=e}function pc(){return vV}var vV;var lm=A(()=>{R_();vV=$i});function B(e,t){let r=pc(),n=rd({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===$i?void 0:$i].filter((i)=>!!i)});e.common.issues.push(n)}class At{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 r=[];for(let n of t){if(n.status==="aborted")return Q;if(n.status==="dirty")e.dirty();r.push(n.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){let r=[];for(let n of t){let i=await n.key,s=await n.value;r.push({key:i,value:s})}return At.mergeObjectSync(e,r)}static mergeObjectSync(e,t){let r={};for(let n of t){let{key:i,value:s}=n;if(i.status==="aborted")return Q;if(s.status==="aborted")return Q;if(i.status==="dirty")e.dirty();if(s.status==="dirty")e.dirty();if(i.value!=="__proto__"&&(typeof s.value<"u"||n.alwaysSet))r[i.value]=s.value}return{status:e.value,value:r}}}var rd=(e)=>{let{data:t,path:r,errorMaps:n,issueData:i}=e,s=[...r,...i.path||[]],o={...i,path:s};if(i.message!==void 0)return{...i,path:s,message:i.message};let a="",c=n.filter((l)=>!!l).slice().reverse();for(let l of c)a=l(o,{data:t,defaultError:a}).message;return{...i,path:s,message:a}},b4e,Q,So=(e)=>({status:"dirty",value:e}),Mt=(e)=>({status:"valid",value:e}),dm=(e)=>e.status==="aborted",fm=(e)=>e.status==="dirty",Cs=(e)=>e.status==="valid",mc=(e)=>typeof Promise<"u"&&e instanceof Promise;var O_=A(()=>{lm();R_();b4e=[];Q=Object.freeze({status:"aborted"})});var _V=()=>{};var W;var DV=A(()=>{(function(e){e.errToObj=(t)=>typeof t==="string"?{message:t}:t||{},e.toString=(t)=>typeof t==="string"?t:t?.message})(W||(W={}))});class vn{constructor(e,t,r,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=n}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 le(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:n,description:i}=e;if(t&&(r||n))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(t)return{errorMap:t,description:i};return{errorMap:(o,a)=>{let{message:c}=e;if(o.code==="invalid_enum_value")return{message:c??a.defaultError};if(typeof a.data>"u")return{message:c??n??a.defaultError};if(o.code!=="invalid_type")return{message:a.defaultError};return{message:c??r??a.defaultError}},description:i}}class he{get description(){return this._def.description}_getType(e){return Jn(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Jn(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new At,ctx:{common:e.parent.common,data:e.data,parsedType:Jn(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(mc(t))throw Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){let r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Jn(e)},n=this._parseSync({data:e,path:r.path,parent:r});return wV(r,n)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Jn(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:t});return Cs(r)?{value:r.value}:{issues:t.common.issues}}catch(r){if(r?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then((r)=>Cs(r)?{value:r.value}:{issues:t.common.issues})}async parseAsync(e,t){let r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){let r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Jn(e)},n=this._parse({data:e,path:r.path,parent:r}),i=await(mc(n)?n:Promise.resolve(n));return wV(r,i)}refine(e,t){let r=(n)=>{if(typeof t==="string"||typeof t>"u")return{message:t};else if(typeof t==="function")return t(n);else return t};return this._refinement((n,i)=>{let s=e(n),o=()=>i.addIssue({code:P.custom,...r(n)});if(typeof Promise<"u"&&s instanceof Promise)return s.then((a)=>{if(!a)return o(),!1;else return!0});if(!s)return o(),!1;else return!0})}refinement(e,t){return this._refinement((r,n)=>{if(!e(r))return n.addIssue(typeof t==="function"?t(r,n):t),!1;else return!0})}_refinement(e){return new _n({schema:this,typeName:ee.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 bn.create(this,this._def)}nullable(){return Fi.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return xn.create(this)}promise(){return Ro.create(this,this._def)}or(e){return vc.create([this,e],this._def)}and(e){return _c.create(this,e,this._def)}transform(e){return new _n({...le(this._def),schema:this,typeName:ee.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e==="function"?e:()=>e;return new Sc({...le(this._def),innerType:this,defaultValue:t,typeName:ee.ZodDefault})}brand(){return new mm({typeName:ee.ZodBranded,type:this,...le(this._def)})}catch(e){let t=typeof e==="function"?e:()=>e;return new $c({...le(this._def),innerType:this,catchValue:t,typeName:ee.ZodCatch})}describe(e){return new this.constructor({...this._def,description:e})}pipe(e){return cd.create(this,e)}readonly(){return Cc.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}function $V(e){let t="[0-5]\\d";if(e.precision)t=`${t}\\.\\d{${e.precision}}`;else if(e.precision==null)t=`${t}(\\.\\d+)?`;let r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function N4e(e){return new RegExp(`^${$V(e)}$`)}function CV(e){let t=`${SV}T${$V(e)}`,r=[];if(r.push(e.local?"Z?":"Z"),e.offset)r.push("([+-]\\d{2}:?\\d{2})");return t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function q4e(e,t){if((t==="v4"||!t)&&R4e.test(e))return!0;if((t==="v6"||!t)&&A4e.test(e))return!0;return!1}function j4e(e,t){if(!S4e.test(e))return!1;try{let[r]=e.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(n));if(typeof i!=="object"||i===null)return!1;if("typ"in i&&i?.typ!=="JWT")return!1;if(!i.alg)return!1;if(t&&i.alg!==t)return!1;return!0}catch{return!1}}function M4e(e,t){if((t==="v4"||!t)&&O4e.test(e))return!0;if((t==="v6"||!t)&&k4e.test(e))return!0;return!1}function B4e(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,i=r>n?r:n,s=Number.parseInt(e.toFixed(i).replace(".","")),o=Number.parseInt(t.toFixed(i).replace(".",""));return s%o/10**i}function hc(e){if(e instanceof ut){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=bn.create(hc(n))}return new ut({...e._def,shape:()=>t})}else if(e instanceof xn)return new xn({...e._def,type:hc(e.element)});else if(e instanceof bn)return bn.create(hc(e.unwrap()));else if(e instanceof Fi)return Fi.create(hc(e.unwrap()));else if(e instanceof Qn)return Qn.create(e.items.map((t)=>hc(t)));else return e}function k_(e,t){let r=Jn(e),n=Jn(t);if(e===t)return{valid:!0,data:e};else if(r===N.object&&n===N.object){let i=be.objectKeys(t),s=be.objectKeys(e).filter((a)=>i.indexOf(a)!==-1),o={...e,...t};for(let a of s){let c=k_(e[a],t[a]);if(!c.valid)return{valid:!1};o[a]=c.data}return{valid:!0,data:o}}else if(r===N.array&&n===N.array){if(e.length!==t.length)return{valid:!1};let i=[];for(let s=0;s<e.length;s++){let o=e[s],a=t[s],c=k_(o,a);if(!c.valid)return{valid:!1};i.push(c.data)}return{valid:!0,data:i}}else if(r===N.date&&n===N.date&&+e===+t)return{valid:!0,data:e};else return{valid:!1}}function FV(e,t){return new As({values:e,typeName:ee.ZodEnum,...le(t)})}function EV(e,t){let r=typeof e==="function"?e(t):typeof e==="string"?{message:e}:e;return typeof r==="string"?{message:r}:r}function RV(e,t={},r){if(e)return Co.create().superRefine((n,i)=>{let s=e(n);if(s instanceof Promise)return s.then((o)=>{if(!o){let a=EV(t,n),c=a.fatal??r??!0;i.addIssue({code:"custom",...a,fatal:c})}});if(!s){let o=EV(t,n),a=o.fatal??r??!0;i.addIssue({code:"custom",...o,fatal:a})}return});return Co.create()}var wV=(e,t)=>{if(Cs(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 r=new hr(e.common.issues);return this._error=r,this._error}}}},v4e,_4e,D4e,w4e,E4e,S4e,$4e,C4e,F4e="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",A_,R4e,O4e,A4e,k4e,P4e,I4e,SV="((\\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])))",T4e,yn,Rs,Os,yc,$o,nd,xc,bc,Co,Fs,Xn,id,xn,ut,vc,Ci=(e)=>{if(e instanceof Dc)return Ci(e.schema);else if(e instanceof _n)return Ci(e.innerType());else if(e instanceof wc)return[e.value];else if(e instanceof As)return e.options;else if(e instanceof Ec)return be.objectValues(e.enum);else if(e instanceof Sc)return Ci(e._def.innerType);else if(e instanceof xc)return[void 0];else if(e instanceof bc)return[null];else if(e instanceof bn)return[void 0,...Ci(e.unwrap())];else if(e instanceof Fi)return[null,...Ci(e.unwrap())];else if(e instanceof mm)return Ci(e.unwrap());else if(e instanceof Cc)return Ci(e.unwrap());else if(e instanceof $c)return Ci(e._def.innerType);else return[]},pm,_c,Qn,sd,od,Fo,gc,Dc,wc,As,Ec,Ro,_n,bn,Fi,Sc,$c,ad,L4e,mm,cd,Cc,U4e,ee,V4e=(e,t={message:`Input not instance of ${e.name}`})=>RV((r)=>r instanceof e,t),OV,AV,z4e,H4e,kV,G4e,W4e,K4e,Y4e,J4e,X4e,Q4e,Z4e,e3e,t3e,r3e,n3e,i3e,s3e,o3e,a3e,c3e,u3e,l3e,d3e,f3e,p3e,m3e,h3e,g3e,y3e,x3e,b3e,v3e,_3e=()=>OV().optional(),D3e=()=>AV().optional(),w3e=()=>kV().optional(),E3e,S3e;var PV=A(()=>{um();lm();DV();O_();td();v4e=/^c[^\s-]{8,}$/i,_4e=/^[0-9a-z]+$/,D4e=/^[0-9A-HJKMNP-TV-Z]{26}$/i,w4e=/^[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,E4e=/^[a-z0-9_-]{21}$/i,S4e=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,$4e=/^[-+]?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)?)??$/,C4e=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,R4e=/^(?:(?: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])$/,O4e=/^(?:(?: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])$/,A4e=/^(([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]))$/,k4e=/^(([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])$/,P4e=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,I4e=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,T4e=new RegExp(`^${SV}$`);yn=class yn extends he{_parse(e){if(this._def.coerce)e.data=String(e.data);if(this._getType(e)!==N.string){let i=this._getOrReturnCtx(e);return B(i,{code:P.invalid_type,expected:N.string,received:i.parsedType}),Q}let r=new At,n=void 0;for(let i of this._def.checks)if(i.kind==="min"){if(e.data.length<i.value)n=this._getOrReturnCtx(e,n),B(n,{code:P.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty()}else if(i.kind==="max"){if(e.data.length>i.value)n=this._getOrReturnCtx(e,n),B(n,{code:P.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty()}else if(i.kind==="length"){let s=e.data.length>i.value,o=e.data.length<i.value;if(s||o){if(n=this._getOrReturnCtx(e,n),s)B(n,{code:P.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message});else if(o)B(n,{code:P.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message});r.dirty()}}else if(i.kind==="email"){if(!C4e.test(e.data))n=this._getOrReturnCtx(e,n),B(n,{validation:"email",code:P.invalid_string,message:i.message}),r.dirty()}else if(i.kind==="emoji"){if(!A_)A_=new RegExp(F4e,"u");if(!A_.test(e.data))n=this._getOrReturnCtx(e,n),B(n,{validation:"emoji",code:P.invalid_string,message:i.message}),r.dirty()}else if(i.kind==="uuid"){if(!w4e.test(e.data))n=this._getOrReturnCtx(e,n),B(n,{validation:"uuid",code:P.invalid_string,message:i.message}),r.dirty()}else if(i.kind==="nanoid"){if(!E4e.test(e.data))n=this._getOrReturnCtx(e,n),B(n,{validation:"nanoid",code:P.invalid_string,message:i.message}),r.dirty()}else if(i.kind==="cuid"){if(!v4e.test(e.data))n=this._getOrReturnCtx(e,n),B(n,{validation:"cuid",code:P.invalid_string,message:i.message}),r.dirty()}else if(i.kind==="cuid2"){if(!_4e.test(e.data))n=this._getOrReturnCtx(e,n),B(n,{validation:"cuid2",code:P.invalid_string,message:i.message}),r.dirty()}else if(i.kind==="ulid"){if(!D4e.test(e.data))n=this._getOrReturnCtx(e,n),B(n,{validation:"ulid",code:P.invalid_string,message:i.message}),r.dirty()}else if(i.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),B(n,{validation:"url",code:P.invalid_string,message:i.message}),r.dirty()}else if(i.kind==="regex"){if(i.regex.lastIndex=0,!i.regex.test(e.data))n=this._getOrReturnCtx(e,n),B(n,{validation:"regex",code:P.invalid_string,message:i.message}),r.dirty()}else if(i.kind==="trim")e.data=e.data.trim();else if(i.kind==="includes"){if(!e.data.includes(i.value,i.position))n=this._getOrReturnCtx(e,n),B(n,{code:P.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()}else if(i.kind==="toLowerCase")e.data=e.data.toLowerCase();else if(i.kind==="toUpperCase")e.data=e.data.toUpperCase();else if(i.kind==="startsWith"){if(!e.data.startsWith(i.value))n=this._getOrReturnCtx(e,n),B(n,{code:P.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()}else if(i.kind==="endsWith"){if(!e.data.endsWith(i.value))n=this._getOrReturnCtx(e,n),B(n,{code:P.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()}else if(i.kind==="datetime"){if(!CV(i).test(e.data))n=this._getOrReturnCtx(e,n),B(n,{code:P.invalid_string,validation:"datetime",message:i.message}),r.dirty()}else if(i.kind==="date"){if(!T4e.test(e.data))n=this._getOrReturnCtx(e,n),B(n,{code:P.invalid_string,validation:"date",message:i.message}),r.dirty()}else if(i.kind==="time"){if(!N4e(i).test(e.data))n=this._getOrReturnCtx(e,n),B(n,{code:P.invalid_string,validation:"time",message:i.message}),r.dirty()}else if(i.kind==="duration"){if(!$4e.test(e.data))n=this._getOrReturnCtx(e,n),B(n,{validation:"duration",code:P.invalid_string,message:i.message}),r.dirty()}else if(i.kind==="ip"){if(!q4e(e.data,i.version))n=this._getOrReturnCtx(e,n),B(n,{validation:"ip",code:P.invalid_string,message:i.message}),r.dirty()}else if(i.kind==="jwt"){if(!j4e(e.data,i.alg))n=this._getOrReturnCtx(e,n),B(n,{validation:"jwt",code:P.invalid_string,message:i.message}),r.dirty()}else if(i.kind==="cidr"){if(!M4e(e.data,i.version))n=this._getOrReturnCtx(e,n),B(n,{validation:"cidr",code:P.invalid_string,message:i.message}),r.dirty()}else if(i.kind==="base64"){if(!P4e.test(e.data))n=this._getOrReturnCtx(e,n),B(n,{validation:"base64",code:P.invalid_string,message:i.message}),r.dirty()}else if(i.kind==="base64url"){if(!I4e.test(e.data))n=this._getOrReturnCtx(e,n),B(n,{validation:"base64url",code:P.invalid_string,message:i.message}),r.dirty()}else be.assertNever(i);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement((n)=>e.test(n),{validation:t,code:P.invalid_string,...W.errToObj(r)})}_addCheck(e){return new yn({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...W.errToObj(e)})}url(e){return this._addCheck({kind:"url",...W.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...W.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...W.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...W.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...W.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...W.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...W.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...W.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...W.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...W.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...W.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...W.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,...W.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,...W.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...W.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...W.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...W.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...W.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...W.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...W.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...W.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...W.errToObj(t)})}nonempty(e){return this.min(1,W.errToObj(e))}trim(){return new yn({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new yn({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new yn({...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}};yn.create=(e)=>new yn({checks:[],typeName:ee.ZodString,coerce:e?.coerce??!1,...le(e)});Rs=class Rs extends he{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)!==N.number){let i=this._getOrReturnCtx(e);return B(i,{code:P.invalid_type,expected:N.number,received:i.parsedType}),Q}let r=void 0,n=new At;for(let i of this._def.checks)if(i.kind==="int"){if(!be.isInteger(e.data))r=this._getOrReturnCtx(e,r),B(r,{code:P.invalid_type,expected:"integer",received:"float",message:i.message}),n.dirty()}else if(i.kind==="min"){if(i.inclusive?e.data<i.value:e.data<=i.value)r=this._getOrReturnCtx(e,r),B(r,{code:P.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),n.dirty()}else if(i.kind==="max"){if(i.inclusive?e.data>i.value:e.data>=i.value)r=this._getOrReturnCtx(e,r),B(r,{code:P.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),n.dirty()}else if(i.kind==="multipleOf"){if(B4e(e.data,i.value)!==0)r=this._getOrReturnCtx(e,r),B(r,{code:P.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()}else if(i.kind==="finite"){if(!Number.isFinite(e.data))r=this._getOrReturnCtx(e,r),B(r,{code:P.not_finite,message:i.message}),n.dirty()}else be.assertNever(i);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,W.toString(t))}gt(e,t){return this.setLimit("min",e,!1,W.toString(t))}lte(e,t){return this.setLimit("max",e,!0,W.toString(t))}lt(e,t){return this.setLimit("max",e,!1,W.toString(t))}setLimit(e,t,r,n){return new Rs({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:W.toString(n)}]})}_addCheck(e){return new Rs({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:W.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:W.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:W.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:W.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:W.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:W.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:W.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:W.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:W.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"&&be.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let r of this._def.checks)if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;else if(r.kind==="min"){if(t===null||r.value>t)t=r.value}else if(r.kind==="max"){if(e===null||r.value<e)e=r.value}return Number.isFinite(t)&&Number.isFinite(e)}};Rs.create=(e)=>new Rs({checks:[],typeName:ee.ZodNumber,coerce:e?.coerce||!1,...le(e)});Os=class Os extends he{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)!==N.bigint)return this._getInvalidInput(e);let r=void 0,n=new At;for(let i of this._def.checks)if(i.kind==="min"){if(i.inclusive?e.data<i.value:e.data<=i.value)r=this._getOrReturnCtx(e,r),B(r,{code:P.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),n.dirty()}else if(i.kind==="max"){if(i.inclusive?e.data>i.value:e.data>=i.value)r=this._getOrReturnCtx(e,r),B(r,{code:P.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),n.dirty()}else if(i.kind==="multipleOf"){if(e.data%i.value!==BigInt(0))r=this._getOrReturnCtx(e,r),B(r,{code:P.not_multiple_of,multipleOf:i.value,message:i.message}),n.dirty()}else be.assertNever(i);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return B(t,{code:P.invalid_type,expected:N.bigint,received:t.parsedType}),Q}gte(e,t){return this.setLimit("min",e,!0,W.toString(t))}gt(e,t){return this.setLimit("min",e,!1,W.toString(t))}lte(e,t){return this.setLimit("max",e,!0,W.toString(t))}lt(e,t){return this.setLimit("max",e,!1,W.toString(t))}setLimit(e,t,r,n){return new Os({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:W.toString(n)}]})}_addCheck(e){return new Os({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:W.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:W.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:W.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:W.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:W.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}};Os.create=(e)=>new Os({checks:[],typeName:ee.ZodBigInt,coerce:e?.coerce??!1,...le(e)});yc=class yc extends he{_parse(e){if(this._def.coerce)e.data=Boolean(e.data);if(this._getType(e)!==N.boolean){let r=this._getOrReturnCtx(e);return B(r,{code:P.invalid_type,expected:N.boolean,received:r.parsedType}),Q}return Mt(e.data)}};yc.create=(e)=>new yc({typeName:ee.ZodBoolean,coerce:e?.coerce||!1,...le(e)});$o=class $o extends he{_parse(e){if(this._def.coerce)e.data=new Date(e.data);if(this._getType(e)!==N.date){let i=this._getOrReturnCtx(e);return B(i,{code:P.invalid_type,expected:N.date,received:i.parsedType}),Q}if(Number.isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return B(i,{code:P.invalid_date}),Q}let r=new At,n=void 0;for(let i of this._def.checks)if(i.kind==="min"){if(e.data.getTime()<i.value)n=this._getOrReturnCtx(e,n),B(n,{code:P.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()}else if(i.kind==="max"){if(e.data.getTime()>i.value)n=this._getOrReturnCtx(e,n),B(n,{code:P.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()}else be.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new $o({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:W.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:W.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}};$o.create=(e)=>new $o({checks:[],coerce:e?.coerce||!1,typeName:ee.ZodDate,...le(e)});nd=class nd extends he{_parse(e){if(this._getType(e)!==N.symbol){let r=this._getOrReturnCtx(e);return B(r,{code:P.invalid_type,expected:N.symbol,received:r.parsedType}),Q}return Mt(e.data)}};nd.create=(e)=>new nd({typeName:ee.ZodSymbol,...le(e)});xc=class xc extends he{_parse(e){if(this._getType(e)!==N.undefined){let r=this._getOrReturnCtx(e);return B(r,{code:P.invalid_type,expected:N.undefined,received:r.parsedType}),Q}return Mt(e.data)}};xc.create=(e)=>new xc({typeName:ee.ZodUndefined,...le(e)});bc=class bc extends he{_parse(e){if(this._getType(e)!==N.null){let r=this._getOrReturnCtx(e);return B(r,{code:P.invalid_type,expected:N.null,received:r.parsedType}),Q}return Mt(e.data)}};bc.create=(e)=>new bc({typeName:ee.ZodNull,...le(e)});Co=class Co extends he{constructor(){super(...arguments);this._any=!0}_parse(e){return Mt(e.data)}};Co.create=(e)=>new Co({typeName:ee.ZodAny,...le(e)});Fs=class Fs extends he{constructor(){super(...arguments);this._unknown=!0}_parse(e){return Mt(e.data)}};Fs.create=(e)=>new Fs({typeName:ee.ZodUnknown,...le(e)});Xn=class Xn extends he{_parse(e){let t=this._getOrReturnCtx(e);return B(t,{code:P.invalid_type,expected:N.never,received:t.parsedType}),Q}};Xn.create=(e)=>new Xn({typeName:ee.ZodNever,...le(e)});id=class id extends he{_parse(e){if(this._getType(e)!==N.undefined){let r=this._getOrReturnCtx(e);return B(r,{code:P.invalid_type,expected:N.void,received:r.parsedType}),Q}return Mt(e.data)}};id.create=(e)=>new id({typeName:ee.ZodVoid,...le(e)});xn=class xn extends he{_parse(e){let{ctx:t,status:r}=this._processInputParams(e),n=this._def;if(t.parsedType!==N.array)return B(t,{code:P.invalid_type,expected:N.array,received:t.parsedType}),Q;if(n.exactLength!==null){let s=t.data.length>n.exactLength.value,o=t.data.length<n.exactLength.value;if(s||o)B(t,{code:s?P.too_big:P.too_small,minimum:o?n.exactLength.value:void 0,maximum:s?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),r.dirty()}if(n.minLength!==null){if(t.data.length<n.minLength.value)B(t,{code:P.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),r.dirty()}if(n.maxLength!==null){if(t.data.length>n.maxLength.value)B(t,{code:P.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),r.dirty()}if(t.common.async)return Promise.all([...t.data].map((s,o)=>n.type._parseAsync(new vn(t,s,t.path,o)))).then((s)=>At.mergeArray(r,s));let i=[...t.data].map((s,o)=>n.type._parseSync(new vn(t,s,t.path,o)));return At.mergeArray(r,i)}get element(){return this._def.type}min(e,t){return new xn({...this._def,minLength:{value:e,message:W.toString(t)}})}max(e,t){return new xn({...this._def,maxLength:{value:e,message:W.toString(t)}})}length(e,t){return new xn({...this._def,exactLength:{value:e,message:W.toString(t)}})}nonempty(e){return this.min(1,e)}};xn.create=(e,t)=>new xn({type:e,minLength:null,maxLength:null,exactLength:null,typeName:ee.ZodArray,...le(t)});ut=class ut extends he{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=be.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==N.object){let c=this._getOrReturnCtx(e);return B(c,{code:P.invalid_type,expected:N.object,received:c.parsedType}),Q}let{status:r,ctx:n}=this._processInputParams(e),{shape:i,keys:s}=this._getCached(),o=[];if(!(this._def.catchall instanceof Xn&&this._def.unknownKeys==="strip")){for(let c in n.data)if(!s.includes(c))o.push(c)}let a=[];for(let c of s){let l=i[c],d=n.data[c];a.push({key:{status:"valid",value:c},value:l._parse(new vn(n,d,n.path,c)),alwaysSet:c in n.data})}if(this._def.catchall instanceof Xn){let c=this._def.unknownKeys;if(c==="passthrough")for(let l of o)a.push({key:{status:"valid",value:l},value:{status:"valid",value:n.data[l]}});else if(c==="strict"){if(o.length>0)B(n,{code:P.unrecognized_keys,keys:o}),r.dirty()}else if(c==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let l of o){let d=n.data[l];a.push({key:{status:"valid",value:l},value:c._parse(new vn(n,d,n.path,l)),alwaysSet:l in n.data})}}if(n.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)=>At.mergeObjectSync(r,c));else return At.mergeObjectSync(r,a)}get shape(){return this._def.shape()}strict(e){return W.errToObj,new ut({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,r)=>{let n=this._def.errorMap?.(t,r).message??r.defaultError;if(t.code==="unrecognized_keys")return{message:W.errToObj(e).message??n};return{message:n}}}:{}})}strip(){return new ut({...this._def,unknownKeys:"strip"})}passthrough(){return new ut({...this._def,unknownKeys:"passthrough"})}extend(e){return new ut({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ut({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:ee.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ut({...this._def,catchall:e})}pick(e){let t={};for(let r of be.objectKeys(e))if(e[r]&&this.shape[r])t[r]=this.shape[r];return new ut({...this._def,shape:()=>t})}omit(e){let t={};for(let r of be.objectKeys(this.shape))if(!e[r])t[r]=this.shape[r];return new ut({...this._def,shape:()=>t})}deepPartial(){return hc(this)}partial(e){let t={};for(let r of be.objectKeys(this.shape)){let n=this.shape[r];if(e&&!e[r])t[r]=n;else t[r]=n.optional()}return new ut({...this._def,shape:()=>t})}required(e){let t={};for(let r of be.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let i=this.shape[r];while(i instanceof bn)i=i._def.innerType;t[r]=i}return new ut({...this._def,shape:()=>t})}keyof(){return FV(be.objectKeys(this.shape))}};ut.create=(e,t)=>new ut({shape:()=>e,unknownKeys:"strip",catchall:Xn.create(),typeName:ee.ZodObject,...le(t)});ut.strictCreate=(e,t)=>new ut({shape:()=>e,unknownKeys:"strict",catchall:Xn.create(),typeName:ee.ZodObject,...le(t)});ut.lazycreate=(e,t)=>new ut({shape:e,unknownKeys:"strip",catchall:Xn.create(),typeName:ee.ZodObject,...le(t)});vc=class vc extends he{_parse(e){let{ctx:t}=this._processInputParams(e),r=this._def.options;function n(i){for(let o of i)if(o.result.status==="valid")return o.result;for(let o of i)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;let s=i.map((o)=>new hr(o.ctx.common.issues));return B(t,{code:P.invalid_union,unionErrors:s}),Q}if(t.common.async)return Promise.all(r.map(async(i)=>{let s={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:s}),ctx:s}})).then(n);else{let i=void 0,s=[];for(let a of r){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"&&!i)i={result:l,ctx:c};if(c.common.issues.length)s.push(c.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;let o=s.map((a)=>new hr(a));return B(t,{code:P.invalid_union,unionErrors:o}),Q}}get options(){return this._def.options}};vc.create=(e,t)=>new vc({options:e,typeName:ee.ZodUnion,...le(t)});pm=class pm extends he{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==N.object)return B(t,{code:P.invalid_type,expected:N.object,received:t.parsedType}),Q;let r=this.discriminator,n=t.data[r],i=this.optionsMap.get(n);if(!i)return B(t,{code:P.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),Q;if(t.common.async)return i._parseAsync({data:t.data,path:t.path,parent:t});else return i._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,r){let n=new Map;for(let i of t){let s=Ci(i.shape[e]);if(!s.length)throw Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let o of s){if(n.has(o))throw Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);n.set(o,i)}}return new pm({typeName:ee.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...le(r)})}};_c=class _c extends he{_parse(e){let{status:t,ctx:r}=this._processInputParams(e),n=(i,s)=>{if(dm(i)||dm(s))return Q;let o=k_(i.value,s.value);if(!o.valid)return B(r,{code:P.invalid_intersection_types}),Q;if(fm(i)||fm(s))t.dirty();return{status:t.value,value:o.data}};if(r.common.async)return Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,s])=>n(i,s));else return n(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};_c.create=(e,t,r)=>new _c({left:e,right:t,typeName:ee.ZodIntersection,...le(r)});Qn=class Qn extends he{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==N.array)return B(r,{code:P.invalid_type,expected:N.array,received:r.parsedType}),Q;if(r.data.length<this._def.items.length)return B(r,{code:P.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Q;if(!this._def.rest&&r.data.length>this._def.items.length)B(r,{code:P.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty();let i=[...r.data].map((s,o)=>{let a=this._def.items[o]||this._def.rest;if(!a)return null;return a._parse(new vn(r,s,r.path,o))}).filter((s)=>!!s);if(r.common.async)return Promise.all(i).then((s)=>At.mergeArray(t,s));else return At.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new Qn({...this._def,rest:e})}};Qn.create=(e,t)=>{if(!Array.isArray(e))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new Qn({items:e,typeName:ee.ZodTuple,rest:null,...le(t)})};sd=class sd extends he{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==N.object)return B(r,{code:P.invalid_type,expected:N.object,received:r.parsedType}),Q;let n=[],i=this._def.keyType,s=this._def.valueType;for(let o in r.data)n.push({key:i._parse(new vn(r,o,r.path,o)),value:s._parse(new vn(r,r.data[o],r.path,o)),alwaysSet:o in r.data});if(r.common.async)return At.mergeObjectAsync(t,n);else return At.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,r){if(t instanceof he)return new sd({keyType:e,valueType:t,typeName:ee.ZodRecord,...le(r)});return new sd({keyType:yn.create(),valueType:e,typeName:ee.ZodRecord,...le(t)})}};od=class od extends he{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==N.map)return B(r,{code:P.invalid_type,expected:N.map,received:r.parsedType}),Q;let n=this._def.keyType,i=this._def.valueType,s=[...r.data.entries()].map(([o,a],c)=>({key:n._parse(new vn(r,o,r.path,[c,"key"])),value:i._parse(new vn(r,a,r.path,[c,"value"]))}));if(r.common.async){let o=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 Q;if(c.status==="dirty"||l.status==="dirty")t.dirty();o.set(c.value,l.value)}return{status:t.value,value:o}})}else{let o=new Map;for(let a of s){let{key:c,value:l}=a;if(c.status==="aborted"||l.status==="aborted")return Q;if(c.status==="dirty"||l.status==="dirty")t.dirty();o.set(c.value,l.value)}return{status:t.value,value:o}}}};od.create=(e,t,r)=>new od({valueType:t,keyType:e,typeName:ee.ZodMap,...le(r)});Fo=class Fo extends he{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==N.set)return B(r,{code:P.invalid_type,expected:N.set,received:r.parsedType}),Q;let n=this._def;if(n.minSize!==null){if(r.data.size<n.minSize.value)B(r,{code:P.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()}if(n.maxSize!==null){if(r.data.size>n.maxSize.value)B(r,{code:P.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty()}let i=this._def.valueType;function s(a){let c=new Set;for(let l of a){if(l.status==="aborted")return Q;if(l.status==="dirty")t.dirty();c.add(l.value)}return{status:t.value,value:c}}let o=[...r.data.values()].map((a,c)=>i._parse(new vn(r,a,r.path,c)));if(r.common.async)return Promise.all(o).then((a)=>s(a));else return s(o)}min(e,t){return new Fo({...this._def,minSize:{value:e,message:W.toString(t)}})}max(e,t){return new Fo({...this._def,maxSize:{value:e,message:W.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};Fo.create=(e,t)=>new Fo({valueType:e,minSize:null,maxSize:null,typeName:ee.ZodSet,...le(t)});gc=class gc extends he{constructor(){super(...arguments);this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==N.function)return B(t,{code:P.invalid_type,expected:N.function,received:t.parsedType}),Q;function r(o,a){return rd({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,pc(),$i].filter((c)=>!!c),issueData:{code:P.invalid_arguments,argumentsError:a}})}function n(o,a){return rd({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,pc(),$i].filter((c)=>!!c),issueData:{code:P.invalid_return_type,returnTypeError:a}})}let i={errorMap:t.common.contextualErrorMap},s=t.data;if(this._def.returns instanceof Ro){let o=this;return Mt(async function(...a){let c=new hr([]),l=await o._def.args.parseAsync(a,i).catch((m)=>{throw c.addIssue(r(a,m)),c}),d=await Reflect.apply(s,this,l);return await o._def.returns._def.type.parseAsync(d,i).catch((m)=>{throw c.addIssue(n(d,m)),c})})}else{let o=this;return Mt(function(...a){let c=o._def.args.safeParse(a,i);if(!c.success)throw new hr([r(a,c.error)]);let l=Reflect.apply(s,this,c.data),d=o._def.returns.safeParse(l,i);if(!d.success)throw new hr([n(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new gc({...this._def,args:Qn.create(e).rest(Fs.create())})}returns(e){return new gc({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new gc({args:e?e:Qn.create([]).rest(Fs.create()),returns:t||Fs.create(),typeName:ee.ZodFunction,...le(r)})}};Dc=class Dc extends he{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})}};Dc.create=(e,t)=>new Dc({getter:e,typeName:ee.ZodLazy,...le(t)});wc=class wc extends he{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return B(t,{received:t.data,code:P.invalid_literal,expected:this._def.value}),Q}return{status:"valid",value:e.data}}get value(){return this._def.value}};wc.create=(e,t)=>new wc({value:e,typeName:ee.ZodLiteral,...le(t)});As=class As extends he{_parse(e){if(typeof e.data!=="string"){let t=this._getOrReturnCtx(e),r=this._def.values;return B(t,{expected:be.joinValues(r),received:t.parsedType,code:P.invalid_type}),Q}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),r=this._def.values;return B(t,{received:t.data,code:P.invalid_enum_value,options:r}),Q}return Mt(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 As.create(e,{...this._def,...t})}exclude(e,t=this._def){return As.create(this.options.filter((r)=>!e.includes(r)),{...this._def,...t})}};As.create=FV;Ec=class Ec extends he{_parse(e){let t=be.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==N.string&&r.parsedType!==N.number){let n=be.objectValues(t);return B(r,{expected:be.joinValues(n),received:r.parsedType,code:P.invalid_type}),Q}if(!this._cache)this._cache=new Set(be.getValidEnumValues(this._def.values));if(!this._cache.has(e.data)){let n=be.objectValues(t);return B(r,{received:r.data,code:P.invalid_enum_value,options:n}),Q}return Mt(e.data)}get enum(){return this._def.values}};Ec.create=(e,t)=>new Ec({values:e,typeName:ee.ZodNativeEnum,...le(t)});Ro=class Ro extends he{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==N.promise&&t.common.async===!1)return B(t,{code:P.invalid_type,expected:N.promise,received:t.parsedType}),Q;let r=t.parsedType===N.promise?t.data:Promise.resolve(t.data);return Mt(r.then((n)=>this._def.type.parseAsync(n,{path:t.path,errorMap:t.common.contextualErrorMap})))}};Ro.create=(e,t)=>new Ro({type:e,typeName:ee.ZodPromise,...le(t)});_n=class _n extends he{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ee.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),n=this._def.effect||null,i={addIssue:(s)=>{if(B(r,s),s.fatal)t.abort();else t.dirty()},get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),n.type==="preprocess"){let s=n.transform(r.data,i);if(r.common.async)return Promise.resolve(s).then(async(o)=>{if(t.value==="aborted")return Q;let a=await this._def.schema._parseAsync({data:o,path:r.path,parent:r});if(a.status==="aborted")return Q;if(a.status==="dirty")return So(a.value);if(t.value==="dirty")return So(a.value);return a});else{if(t.value==="aborted")return Q;let o=this._def.schema._parseSync({data:s,path:r.path,parent:r});if(o.status==="aborted")return Q;if(o.status==="dirty")return So(o.value);if(t.value==="dirty")return So(o.value);return o}}if(n.type==="refinement"){let s=(o)=>{let a=n.refinement(o,i);if(r.common.async)return Promise.resolve(a);if(a instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(r.common.async===!1){let o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(o.status==="aborted")return Q;if(o.status==="dirty")t.dirty();return s(o.value),{status:t.value,value:o.value}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then((o)=>{if(o.status==="aborted")return Q;if(o.status==="dirty")t.dirty();return s(o.value).then(()=>({status:t.value,value:o.value}))})}if(n.type==="transform")if(r.common.async===!1){let s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Cs(s))return Q;let o=n.transform(s.value,i);if(o instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:o}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then((s)=>{if(!Cs(s))return Q;return Promise.resolve(n.transform(s.value,i)).then((o)=>({status:t.value,value:o}))});be.assertNever(n)}};_n.create=(e,t,r)=>new _n({schema:e,typeName:ee.ZodEffects,effect:t,...le(r)});_n.createWithPreprocess=(e,t,r)=>new _n({schema:t,effect:{type:"preprocess",transform:e},typeName:ee.ZodEffects,...le(r)});bn=class bn extends he{_parse(e){if(this._getType(e)===N.undefined)return Mt(void 0);return this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};bn.create=(e,t)=>new bn({innerType:e,typeName:ee.ZodOptional,...le(t)});Fi=class Fi extends he{_parse(e){if(this._getType(e)===N.null)return Mt(null);return this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Fi.create=(e,t)=>new Fi({innerType:e,typeName:ee.ZodNullable,...le(t)});Sc=class Sc extends he{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;if(t.parsedType===N.undefined)r=this._def.defaultValue();return this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Sc.create=(e,t)=>new Sc({innerType:e,typeName:ee.ZodDefault,defaultValue:typeof t.default==="function"?t.default:()=>t.default,...le(t)});$c=class $c extends he{_parse(e){let{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});if(mc(n))return n.then((i)=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new hr(r.common.issues)},input:r.data})}));else return{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new hr(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};$c.create=(e,t)=>new $c({innerType:e,typeName:ee.ZodCatch,catchValue:typeof t.catch==="function"?t.catch:()=>t.catch,...le(t)});ad=class ad extends he{_parse(e){if(this._getType(e)!==N.nan){let r=this._getOrReturnCtx(e);return B(r,{code:P.invalid_type,expected:N.nan,received:r.parsedType}),Q}return{status:"valid",value:e.data}}};ad.create=(e)=>new ad({typeName:ee.ZodNaN,...le(e)});L4e=Symbol("zod_brand");mm=class mm extends he{_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}};cd=class cd extends he{_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});if(i.status==="aborted")return Q;if(i.status==="dirty")return t.dirty(),So(i.value);else return this._def.out._parseAsync({data:i.value,path:r.path,parent:r})})();else{let n=this._def.in._parseSync({data:r.data,path:r.path,parent:r});if(n.status==="aborted")return Q;if(n.status==="dirty")return t.dirty(),{status:"dirty",value:n.value};else return this._def.out._parseSync({data:n.value,path:r.path,parent:r})}}static create(e,t){return new cd({in:e,out:t,typeName:ee.ZodPipeline})}};Cc=class Cc extends he{_parse(e){let t=this._def.innerType._parse(e),r=(n)=>{if(Cs(n))n.value=Object.freeze(n.value);return n};return mc(t)?t.then((n)=>r(n)):r(t)}unwrap(){return this._def.innerType}};Cc.create=(e,t)=>new Cc({innerType:e,typeName:ee.ZodReadonly,...le(t)});U4e={object:ut.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"})(ee||(ee={}));OV=yn.create,AV=Rs.create,z4e=ad.create,H4e=Os.create,kV=yc.create,G4e=$o.create,W4e=nd.create,K4e=xc.create,Y4e=bc.create,J4e=Co.create,X4e=Fs.create,Q4e=Xn.create,Z4e=id.create,e3e=xn.create,t3e=ut.create,r3e=ut.strictCreate,n3e=vc.create,i3e=pm.create,s3e=_c.create,o3e=Qn.create,a3e=sd.create,c3e=od.create,u3e=Fo.create,l3e=gc.create,d3e=Dc.create,f3e=wc.create,p3e=As.create,m3e=Ec.create,h3e=Ro.create,g3e=_n.create,y3e=bn.create,x3e=Fi.create,b3e=_n.createWithPreprocess,v3e=cd.create,E3e={string:(e)=>yn.create({...e,coerce:!0}),number:(e)=>Rs.create({...e,coerce:!0}),boolean:(e)=>yc.create({...e,coerce:!0}),bigint:(e)=>Os.create({...e,coerce:!0}),date:(e)=>$o.create({...e,coerce:!0})},S3e=Q});var R={};Ti(R,{BRAND:()=>L4e,DIRTY:()=>So,EMPTY_PATH:()=>b4e,INVALID:()=>Q,NEVER:()=>S3e,OK:()=>Mt,ParseStatus:()=>At,Schema:()=>he,ZodAny:()=>Co,ZodArray:()=>xn,ZodBigInt:()=>Os,ZodBoolean:()=>yc,ZodBranded:()=>mm,ZodCatch:()=>$c,ZodDate:()=>$o,ZodDefault:()=>Sc,ZodDiscriminatedUnion:()=>pm,ZodEffects:()=>_n,ZodEnum:()=>As,ZodError:()=>hr,ZodFirstPartyTypeKind:()=>ee,ZodFunction:()=>gc,ZodIntersection:()=>_c,ZodIssueCode:()=>P,ZodLazy:()=>Dc,ZodLiteral:()=>wc,ZodMap:()=>od,ZodNaN:()=>ad,ZodNativeEnum:()=>Ec,ZodNever:()=>Xn,ZodNull:()=>bc,ZodNullable:()=>Fi,ZodNumber:()=>Rs,ZodObject:()=>ut,ZodOptional:()=>bn,ZodParsedType:()=>N,ZodPipeline:()=>cd,ZodPromise:()=>Ro,ZodReadonly:()=>Cc,ZodRecord:()=>sd,ZodSchema:()=>he,ZodSet:()=>Fo,ZodString:()=>yn,ZodSymbol:()=>nd,ZodTransformer:()=>_n,ZodTuple:()=>Qn,ZodType:()=>he,ZodUndefined:()=>xc,ZodUnion:()=>vc,ZodUnknown:()=>Fs,ZodVoid:()=>id,addIssueToContext:()=>B,any:()=>J4e,array:()=>e3e,bigint:()=>H4e,boolean:()=>kV,coerce:()=>E3e,custom:()=>RV,date:()=>G4e,datetimeRegex:()=>CV,defaultErrorMap:()=>$i,discriminatedUnion:()=>i3e,effect:()=>g3e,enum:()=>p3e,function:()=>l3e,getErrorMap:()=>pc,getParsedType:()=>Jn,instanceof:()=>V4e,intersection:()=>s3e,isAborted:()=>dm,isAsync:()=>mc,isDirty:()=>fm,isValid:()=>Cs,late:()=>U4e,lazy:()=>d3e,literal:()=>f3e,makeIssue:()=>rd,map:()=>c3e,nan:()=>z4e,nativeEnum:()=>m3e,never:()=>Q4e,null:()=>Y4e,nullable:()=>x3e,number:()=>AV,object:()=>t3e,objectUtil:()=>F_,oboolean:()=>w3e,onumber:()=>D3e,optional:()=>y3e,ostring:()=>_3e,pipeline:()=>v3e,preprocess:()=>b3e,promise:()=>h3e,quotelessJson:()=>g4e,record:()=>a3e,set:()=>u3e,setErrorMap:()=>x4e,strictObject:()=>r3e,string:()=>OV,symbol:()=>W4e,transformer:()=>g3e,tuple:()=>o3e,undefined:()=>K4e,union:()=>n3e,unknown:()=>X4e,util:()=>be,void:()=>Z4e});var P_=A(()=>{lm();O_();_V();td();PV();um()});var ud=A(()=>{P_();P_()});import{copyFileSync as $3e,existsSync as IV,mkdirSync as C3e}from"fs";import{homedir as gm}from"os";import{join as Fc}from"path";function R3e(e){let t=e.trim().replace(/\/+$/,"");try{let r=new URL(t);return r.protocol=r.protocol.toLowerCase(),r.host=r.host.toLowerCase(),r.toString().replace(/\/+$/,"")}catch{return console.error(`[nemar] could not parse stored apiUrl ${JSON.stringify(e)}; leaving as-is`),t}}function O3e(){return process.env.NEMAR_CONFIG_DIR||Fc(gm(),".config","nemar")}function A3e(e){if(process.env.NEMAR_CONFIG_DIR)return;let t=Fc(e,"config.json");if(IV(t))return;let r=[];if(process.platform==="darwin")r.push(Fc(gm(),"Library","Preferences","nemar-nodejs","config.json"));if(process.platform==="win32"){let n=process.env.APPDATA||Fc(gm(),"AppData","Roaming");r.push(Fc(n,"nemar-nodejs","config.json"))}r.push(Fc(gm(),".config","nemar-nodejs","config.json"));for(let n of r)if(IV(n))try{C3e(e,{recursive:!0}),$3e(n,t),console.error(`[nemar] Config migrated from ${n} to ${t}
|
|
99
99
|
[nemar] You can safely remove the old file.`);return}catch(i){console.error(`[nemar] Failed to migrate config from ${n}:`,i,`
|
|
100
|
-
[nemar] You can manually copy ${n} to ${t}`)}}function Dn(){let e=O3e();if(hm&&TV===e)return hm;if(A3e(e),hm=new cm({projectName:"nemar",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}),TV=e,!NV.has(e))NV.add(e),P3e(),I3e();return hm}function P3e(){let e=Dn(),t=e.get("accounts");if(t&&Object.keys(t).length>0)return;let r=e.get("apiKey"),n=e.get("username");if(!r&&!n)return;try{let i=n||"default",s={};for(let o of k3e){let a=e.get(o);if(a!==void 0)s[o]=a}e.store={activeAccount:i,accounts:{[i]:s}}}catch(i){console.error("Config migration failed (legacy config preserved):",i)}}function I3e(){let e=Dn(),t=e.store,r=t.accounts,n=!1;if(r)for(let[s,o]of Object.entries(r)){let a=o?.apiUrl;if(!a)continue;if(F3e.has(R3e(a)))r[s]={...o,apiUrl:Oo},console.error(`[nemar] migrated stored apiUrl for account "${s}": ${a} -> ${Oo}`),n=!0}let i=t.apiUrl;if(r&&Object.keys(r).length>0&&i!==void 0){let{apiUrl:s,...o}=t;try{e.store=o,console.error(`[nemar] removed stale top-level apiUrl from config (was: ${i})`),n=!1}catch(a){console.error("API URL cleanup failed (config file unchanged):",a)}}if(n)try{e.store={...e.store,accounts:r}}catch(s){console.error("API URL migration failed (config file unchanged):",s)}}function ym(){return Dn().get("activeAccount")}function Rc(){return Dn().get("accounts")||{}}function ht(){let e={apiUrl:Oo},t=ym();if(!t)return e;return Rc()[t]||e}function qV(){return!!ht().sandboxCompleted}function wn(e,t){let r=Dn(),n=r.get("activeAccount")||"default",i=r.get("accounts")||{};if(!i[n])i[n]={apiUrl:Oo};i[n][e]=t,r.store={...r.store,accounts:i,activeAccount:n}}function I_(e){let t=ym();if(!t)return;let r=Rc();if(r[t])delete r[t][e],Dn().set("accounts",r)}function jV(){let e=Dn(),t=ym();if(!t){e.clear();return}let r=Rc();delete r[t];let n=Object.keys(r);if(n.length>0)e.store={...e.store,accounts:r,activeAccount:n[0]};else e.clear()}function MV(){Dn().clear()}function Ue(){return!!ht().apiKey}function BV(){return Dn().path}function ld(){let e=Rc(),t=ym();return Object.entries(e).map(([r,n])=>({username:n.username||r,email:n.email,githubUsername:n.githubUsername,active:r===t}))}function LV(e,t){let r=Dn(),n=Rc();n[e]=t,r.store={...r.store,accounts:n,activeAccount:e}}function UV(e){let t=Dn(),r=Rc();if(r[e])return t.store={...t.store,activeAccount:e},r[e];for(let[n,i]of Object.entries(r))if(i.githubUsername===e)return t.store={...t.store,activeAccount:n},i;return null}var Oo="https://api.nemar.org",F3e,GYe,hm=null,TV=null,NV,k3e;var ks=A(()=>{bV();ud();F3e=new Set(["https://api.osc.earth/nemar","https://nemar-api.neuromechanist.workers.dev","https://nemar-api-dev.shirazi-10f.workers.dev"]);GYe=
|
|
100
|
+
[nemar] You can manually copy ${n} to ${t}`)}}function Dn(){let e=O3e();if(hm&&TV===e)return hm;if(A3e(e),hm=new cm({projectName:"nemar",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}),TV=e,!NV.has(e))NV.add(e),P3e(),I3e();return hm}function P3e(){let e=Dn(),t=e.get("accounts");if(t&&Object.keys(t).length>0)return;let r=e.get("apiKey"),n=e.get("username");if(!r&&!n)return;try{let i=n||"default",s={};for(let o of k3e){let a=e.get(o);if(a!==void 0)s[o]=a}e.store={activeAccount:i,accounts:{[i]:s}}}catch(i){console.error("Config migration failed (legacy config preserved):",i)}}function I3e(){let e=Dn(),t=e.store,r=t.accounts,n=!1;if(r)for(let[s,o]of Object.entries(r)){let a=o?.apiUrl;if(!a)continue;if(F3e.has(R3e(a)))r[s]={...o,apiUrl:Oo},console.error(`[nemar] migrated stored apiUrl for account "${s}": ${a} -> ${Oo}`),n=!0}let i=t.apiUrl;if(r&&Object.keys(r).length>0&&i!==void 0){let{apiUrl:s,...o}=t;try{e.store=o,console.error(`[nemar] removed stale top-level apiUrl from config (was: ${i})`),n=!1}catch(a){console.error("API URL cleanup failed (config file unchanged):",a)}}if(n)try{e.store={...e.store,accounts:r}}catch(s){console.error("API URL migration failed (config file unchanged):",s)}}function ym(){return Dn().get("activeAccount")}function Rc(){return Dn().get("accounts")||{}}function ht(){let e={apiUrl:Oo},t=ym();if(!t)return e;return Rc()[t]||e}function qV(){return!!ht().sandboxCompleted}function wn(e,t){let r=Dn(),n=r.get("activeAccount")||"default",i=r.get("accounts")||{};if(!i[n])i[n]={apiUrl:Oo};i[n][e]=t,r.store={...r.store,accounts:i,activeAccount:n}}function I_(e){let t=ym();if(!t)return;let r=Rc();if(r[t])delete r[t][e],Dn().set("accounts",r)}function jV(){let e=Dn(),t=ym();if(!t){e.clear();return}let r=Rc();delete r[t];let n=Object.keys(r);if(n.length>0)e.store={...e.store,accounts:r,activeAccount:n[0]};else e.clear()}function MV(){Dn().clear()}function Ue(){return!!ht().apiKey}function BV(){return Dn().path}function ld(){let e=Rc(),t=ym();return Object.entries(e).map(([r,n])=>({username:n.username||r,email:n.email,githubUsername:n.githubUsername,active:r===t}))}function LV(e,t){let r=Dn(),n=Rc();n[e]=t,r.store={...r.store,accounts:n,activeAccount:e}}function UV(e){let t=Dn(),r=Rc();if(r[e])return t.store={...t.store,activeAccount:e},r[e];for(let[n,i]of Object.entries(r))if(i.githubUsername===e)return t.store={...t.store,activeAccount:n},i;return null}var Oo="https://api.nemar.org",F3e,GYe,hm=null,TV=null,NV,k3e;var ks=A(()=>{bV();ud();F3e=new Set(["https://api.osc.earth/nemar","https://nemar-api.neuromechanist.workers.dev","https://nemar-api-dev.shirazi-10f.workers.dev"]);GYe=R.object({apiKey:R.string().optional(),apiUrl:R.string().url().default(Oo),username:R.string().optional(),email:R.string().email().optional(),githubUsername:R.string().optional(),sandboxCompleted:R.boolean().optional(),sandboxDatasetId:R.string().optional(),dismissedNoticeIds:R.array(R.number()).optional()});NV=new Set;k3e=["apiKey","apiUrl","username","email","githubUsername","sandboxCompleted","sandboxDatasetId","dismissedNoticeIds"]});function xm(e){if(VV)return;VV=!0;let t=u.yellow("\u2500".repeat(60)),r=u.yellow.bold("[MAINTENANCE]"),n=u.dim(`mode: ${e.mode}`),i=e.eta?`
|
|
101
101
|
${u.dim(`eta: ${e.eta}`)}`:"";process.stderr.write(`${t}
|
|
102
102
|
${r} ${e.message}
|
|
103
103
|
${n}${i}
|
|
104
104
|
${t}
|
|
105
|
-
`)}var VV=!1;var T_=A(()=>{Ke()});var HV;var zV=A(()=>{HV={name:"nemar-cli",version:"0.9.10-PR1165.ffb749a",description:"CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",type:"module",main:"dist/index.js",bin:{nemar:"dist/index.js"},scripts:{dev:"bun run src/index.ts",build:"bun build src/index.ts --outdir dist --target bun --minify && sed '1s|#!/usr/bin/env node|#!/usr/bin/env bun|' dist/index.js > dist/index.js.tmp && mv dist/index.js.tmp dist/index.js",test:"bun test",lint:"biome check src/","lint:fix":"biome check --fix src/",format:"biome format --write src/",typecheck:"tsc --noEmit && tsc --noEmit -p backend",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","README.md","LICENSE"],dependencies:{chalk:"^5.3.0",commander:"^12.1.0",conf:"^13.0.1","fuse.js":"^7.1.0",inquirer:"^9.2.15",ora:"^8.0.1",zod:"^3.23.8"},"lint-staged":{"src/**/*.{ts,tsx}":["biome check --fix"],"backend/src/**/*.{ts,tsx}":["biome check --fix"]},devDependencies:{"@biomejs/biome":"1.9.4","@types/bcryptjs":"^3.0.0","@types/bun":"latest","@types/inquirer":"^9.0.7",ajv:"^8.20.0","ajv-formats":"^3.0.1",bcryptjs:"^3.0.3",husky:"^9.1.7","lint-staged":"^16.3.2",typescript:"^5.5.4",wrangler:"^4.70.0",yaml:"^2.8.4"}}});var Ao;var bm=A(()=>{zV();Ao=HV.version});function U(e){if(e instanceof Error)return e.message;return String(e)}var M,ko;var gr=A(()=>{M=class M extends Error{statusCode;details;step;constructor(e,t,r,n){super(t);this.statusCode=e;this.details=r;this.step=n;this.name="ApiError"}};ko=class ko extends M{mode;eta;constructor(e,t,r,n){super(503,t,n);this.mode=e;this.eta=r;this.name="MaintenanceError"}}});function GV(){if(process.env.TEST_API_URL)return process.env.TEST_API_URL;if(q_)return N_;return ht().apiUrl||N_}async function I(e,t={},r=!1,n){let i=`${GV()}${e}`,s={"Content-Type":"application/json","X-CLI-Version":Ao,...t.headers};if(r){let c=ht();if(!c.apiKey&&r===!0)throw new M(401,"Not authenticated. Run 'nemar auth login' first.");if(c.apiKey)s.Authorization=`Bearer ${c.apiKey}`}let o;try{o=await fetch(i,{...t,headers:s})}catch(c){throw new M(0,`Network error: Could not connect to ${GV()}`,{originalError:c instanceof Error?c.message:String(c)})}let a;try{a=await o.json()}catch{throw new M(o.status,`Invalid response from server (status ${o.status})`)}if(!o.ok){if(o.status===503&&(a.mode==="read-only"||a.mode==="full")){let c=typeof a.message==="string"?a.message:"NEMAR is in maintenance mode. Please retry shortly.",l=typeof a.eta==="string"?a.eta:null,d=new ko(a.mode,c,l,a.details);throw xm(d),d}throw new M(o.status,a.error||a.message||"Request failed",a.details,typeof a.step==="string"?a.step:void 0)}if(n){let c=n.safeParse(a);if(!c.success)throw new M(o.status,`Response for ${e} did not match the expected NEMAR contract`,{issues:c.error.issues});return c.data}return a}var N_="https://api.nemar.org",q_;var Ps=A(()=>{ks();T_();bm();gr();q_=N_.includes("workers.dev")});async function WV(e,t){let r=new URLSearchParams;if(e)r.set("status",e);if(t)r.set("role",t);let n=r.toString()?`?${r.toString()}`:"";return I(`/admin/users${n}`,{},!0)}async function KV(e){return I(`/admin/approve/${e}`,{method:"POST"},!0)}async function YV(e){return I(`/admin/approve/by-id/${e}`,{method:"POST"},!0)}async function JV(e){return I(`/admin/revoke/${e}`,{method:"POST"},!0)}async function XV(e,t){return I(`/admin/users/${e}/role`,{method:"POST",body:JSON.stringify({role:t})},!0)}async function j_(e,t){return I(`/admin/datasets/${e}/visibility`,{method:"PATCH",body:JSON.stringify({visibility:t})},!0)}async function QV(e){return I(`/datasets/${e}/publish`,{method:"POST"},!0)}async function ZV(e){return I(`/admin/datasets/${e}/ci`,{},!0)}async function Ri(e){return I(`/admin/datasets/${e}/ci`,{method:"POST"},!0)}async function M_(e){return I(`/admin/datasets/${e}/ci/validate`,{method:"POST"},!0)}async function B_(e){return I(`/admin/datasets/${e}/ci/sync`,{method:"POST"},!0)}async function ez(e,t){return I(`/admin/datasets/${e}/doi/concept`,{method:"POST",body:JSON.stringify(t)},!0)}async function dd(e){return I(`/admin/datasets/${e}/doi`,{},!0)}async function L_(e,t){return I(`/admin/datasets/${e}/doi/update`,{method:"POST",body:JSON.stringify(t)},!0)}async function tz(e,t){return I(`/admin/datasets/${e}/withdraw`,{method:"POST",body:JSON.stringify({reason:t.reason,dry_run:t.dryRun})},!0)}async function rz(e,t){return I(`/admin/datasets/${e}/restore`,{method:"POST",body:JSON.stringify({dry_run:t.dryRun})},!0)}async function nz(e){return I(`/admin/datasets/${e}/reset`,{method:"POST"},!0)}async function iz(e,t=!1){return I(`/admin/datasets/${e}`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({force:t})},!0)}async function sz(e){return I("/admin/datasets/bulk-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dataset_ids:e})},!0)}async function oz(e){return I("/admin/datasets/import",{method:"POST",body:JSON.stringify(e)},!0)}async function az(e){return I("/admin/datasets/exemplar",{method:"POST",body:JSON.stringify(e)},!0)}async function cz(e){return I(`/admin/datasets/${e}/exemplar/remint-dois`,{method:"POST"},!0)}async function U_(e,t){let r=new URLSearchParams;if(e)r.set("status",e);if(t!==void 0)r.set("blocklisted",t?"1":"0");let n=r.toString();return I(`/admin/imports${n?`?${n}`:""}`,{},!0)}async function uz(e){return I(`/admin/imports/${e}/rollback`,{method:"POST"},!0)}async function lz(e){return I(`/admin/imports/${e}/retry`,{method:"POST"},!0)}async function V_(e){return I(`/admin/imports/${e}/verify`,{method:"POST"},!0)}async function dz(e){return I("/admin/imports/dispatch-cooldown",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dataset_ids:e})},!0)}async function Oc(e,t){return I(`/admin/datasets/${e}/reindex`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})},!0)}async function fz(e,t){return I("/admin/datasets/reindex/bulk",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filter:e,...t??{}})},!0)}async function pz(e){let t=e?.limit??15;return I(`/admin/datasets/hed-sweep?limit=${encodeURIComponent(String(t))}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function mz(){return I("/admin/datasets/hed-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function hz(e){let t=e?.limit??15,r=new URLSearchParams({limit:String(t)});if(e?.olderThan!=null)r.set("older-than",String(e.olderThan));if(e?.before!=null)r.set("before",e.before);return I(`/admin/datasets/data-integrity-sweep?${r.toString()}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function gz(){return I("/admin/datasets/data-integrity-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function yz(e,t){let r=t?.write?"":"?dry_run=1";return I(`/admin/datasets/${e}/availability-report${r}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function xz(e){let t=e?.limit??30,r=new URLSearchParams({limit:String(t)});if(e?.missingOnly)r.set("missing-only","1");return I(`/admin/datasets/availability-report-sweep?${r.toString()}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function bz(){return I("/admin/datasets/availability-report-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function vz(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 r=t.toString()?`?${t.toString()}`:"";return I(`/admin/fleet/drift${r}`,{},!0)}async function Ac(e,t){return I(`/admin/datasets/${e}/enforce`,{method:"POST",body:JSON.stringify({dry_run:t})},!0)}async function _z(e){return I("/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 Dz(e,t=!1){return I(`/admin/datasets/${e}/revalidate${t?"?force=true":""}`,{method:"POST"},!0)}async function wz(e){let t=e?`?user=${encodeURIComponent(e)}`:"";return I(`/admin/email-preferences${t}`,{},!0)}async function Ez(e,t){let r=t?`?user=${encodeURIComponent(t)}`:"";return I(`/admin/email-preferences${r}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)},!0)}async function z_(e){return I("/admin/notify",{method:"POST",body:JSON.stringify(e)},!0)}async function Sz(){return I("/admin/summary/coverage",{},!0)}async function $z(e,t,r){return I("/admin/manifest/dispatch",{method:"POST",body:JSON.stringify({dataset_id:e,version:t,skip_canary:r?.skipCanary??!1})},!0)}async function H_(e){return I("/admin/doctor/scan",{method:"POST",body:JSON.stringify({...e?.check&&{check:e.check},...e?.datasetId&&{dataset_id:e.datasetId}})},!0)}async function G_(e){return I("/admin/doctor/fix",{method:"POST",body:JSON.stringify({check:e.check,...e.datasetId&&{dataset_id:e.datasetId},...e.dryRun&&{dry_run:!0}})},!0)}var kc=A(()=>{Ps()});async function Zn(e,t){return I(`/datasets/${e}/upload-credentials`,{method:"POST",body:JSON.stringify({duration_seconds:t})},!0)}async function W_(e,t){return I(`/datasets/${e}/download-credentials`,{method:"POST",body:JSON.stringify({duration_seconds:t})},!0)}async function Cz(e){return I(`/admin/datasets/${e}/files`,{},!0)}async function Fz(e){let t,r=0,n=[],i=!0;while(i){let s=await I(`/admin/datasets/${e}/s3-lock`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({continuation_token:t})},!0);if(r+=s.locked,s.failed?.length)n.push(...s.failed);if(i=s.hasMore,t=s.continuation_token,i&&!t)throw new M(500,"S3 lock paginated response missing continuation_token; aborting to avoid infinite loop")}return{locked:r,failed:n}}var Pc=A(()=>{Ps();gr()});function j3e(e){return e.startsWith("v")?e:`v${e}`}var N3e,q3e,Rz,dJe;var K_=A(()=>{ud();N3e=/^v?\d+\.\d+\.\d+(?:-(?:rc|alpha|beta)\d*)?$/,q3e=/^v\d+\.\d+\.\d+(?:-(?:rc|alpha|beta)\d*)?$/;Rz=F.string().regex(N3e,"must be a semver version, optionally v-prefixed").transform(j3e),dJe=F.string().regex(q3e,"must be the canonical v-prefixed tag (vX.Y.Z)")});var M3e,B3e,Oz;var Az=A(()=>{ud();M3e=F.object({id:F.number().int(),username:F.string().nullable(),email:F.string(),github_username:F.string().nullable(),role:F.string(),orcid:F.string().nullable().optional(),created_at:F.string().optional(),approved_at:F.string().nullable().optional(),dataset_count:F.number().int().optional(),sandbox_completed:F.boolean().optional(),sandbox_completed_at:F.string().nullable().optional(),sandbox_dataset_id:F.string().nullable().optional()}).passthrough(),B3e=F.object({prefix:F.string(),created_at:F.string(),last_used_at:F.string().nullable()}).passthrough().nullable(),Oz=F.object({user:M3e,token:B3e.optional()}).passthrough()});var L3e="0.4.0",U3e,fd,kz,V3e,z3e,yJe,Pz,xJe,bJe;var Iz=A(()=>{ud();K_();U3e=F.enum(["openneuro","nemar","gin","other"]),fd=F.union([F.literal(0),F.literal(1)]).nullable(),kz=F.object({dataset_id:F.string(),id:F.string().optional(),name:F.string(),description:F.string().nullable().optional(),status:F.string(),visibility:F.string(),concept_doi:F.string().nullable().optional(),doi:F.string().nullable().optional(),created_at:F.string(),updated_at:F.string().optional(),owner_username:F.string().nullable().optional(),source:F.string().nullable().optional(),modalities:F.string().optional(),participants:F.number().int().nonnegative(),tasks:F.string().optional(),authors:F.string().optional(),license:F.string().optional(),file_size:F.number().nonnegative(),file_size_formatted:F.string().optional(),total_files:F.number().nonnegative().nullable().optional(),num_citations:F.number().int().nonnegative().optional(),n_channels:F.number().int().nullable().optional(),electrode_system:F.string().nullable().optional(),has_hed:fd.optional(),hed_version:F.string().nullable().optional(),data_complete:fd.optional(),bytes_present:F.number().nonnegative().nullable().optional(),latest_version:Rz.nullable().optional(),sessions_count:F.number().int().nullable().optional(),age_min:F.number().nullable().optional(),age_max:F.number().nullable().optional(),bids_version:F.string().nullable().optional(),zarr_status:F.enum(["pending","ready","failed"]).nullable().optional(),total_recording_duration:F.number().nullable().optional(),recording_duration_min:F.number().nullable().optional(),recording_duration_max:F.number().nullable().optional(),recording_count:F.number().int().nullable().optional(),recordings_unavailable:F.number().int().nullable().optional(),channel_count_min:F.number().int().nullable().optional(),channel_count_max:F.number().int().nullable().optional(),sampling_frequency:F.number().nullable().optional(),power_line_frequency:F.number().nullable().optional(),eeg_reference:F.string().nullable().optional(),placement_scheme:F.string().nullable().optional()}).passthrough(),V3e=kz.extend({file_size:F.number().nonnegative().nullable(),modalities:F.string().nullable().optional(),tasks:F.string().nullable().optional(),authors:F.string().nullable().optional(),license:F.string().nullable().optional(),owner_github:F.string().nullable().optional(),attestation_deposit_type:F.enum(["owner","redistribution"]).nullable().optional(),attestation_key_status:F.enum(["destroyed","retained"]).nullable().optional(),attestation_deidentified:fd.optional(),attestation_no_duplicate:fd.optional(),attestation_upstream_source:F.string().nullable().optional(),attestation_accepted_at:F.string().nullable().optional()}).passthrough(),z3e=F.object({id:F.string(),name:F.string(),modalities:F.string().nullable().optional(),participants:F.number().int().nullable().optional(),doi:F.string().nullable().optional(),tasks:F.string().nullable().optional(),authors:F.string().nullable().optional(),has_hed:fd.optional(),score:F.number().optional(),snippet:F.string().optional()}).passthrough(),yJe=F.object({datasets:F.array(kz),count:F.number().int().nonnegative(),total_count:F.number().int().nonnegative().optional(),limit:F.number().int().optional(),offset:F.number().int().optional(),excluded_unknown:F.number().int().nonnegative().optional()}).passthrough(),Pz=F.object({results:F.array(z3e),count:F.number().int().nonnegative(),returned:F.number().int().nonnegative().optional(),offset:F.number().int().nonnegative().optional(),limit:F.number().int().optional(),candidate_ceiling:F.number().int().optional(),truncated:F.boolean().optional(),method:F.enum(["exact_id","text","text_fallback","semantic","unavailable"]).optional(),min_score:F.number().optional(),warning:F.string().optional(),excluded_unknown:F.number().int().nonnegative().optional()}).passthrough(),xJe=F.object({dataset:V3e}).passthrough(),bJe=F.object({schema_version:F.literal(L3e),doc_type:F.literal("dataset"),dataset_id:F.string().regex(/^[a-z]{2}\d+$/,"neuroschema dataset_id pattern"),name:F.string(),source:U3e,recording_modality:F.array(F.string()).min(1),description:F.string().nullable().optional(),bids_version:F.string().nullable().optional(),license:F.string().nullable().optional()}).passthrough()});var Y_=A(()=>{K_();Az();Iz()});async function _m(e){return I(`/datasets/${e}/ci/status`,{},!0)}async function Tz(e){return I(`/datasets/${e}/manifest`,{},!0)}async function Dm(e,t){return I(`/datasets/${e}/manifest/${t}`,{},!0)}function Nz(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 Ic(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.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);let r=t.toString()?`?${t.toString()}`:"",n=await I(`/datasets${r}`,{},e.mine?!0:"optional");return n.datasets=n.datasets.map(Nz),n}async function qz(e){return I(`/datasets/resolve/${e}`,{},"optional")}async function jz(e,t={}){let r=new URLSearchParams({q:e});if(t.modality)r.set("modality",t.modality);if(t.limit)r.set("limit",String(t.limit));if(t.hasHed)r.set("has_hed","1");return await I(`/datasets/search?${r.toString()}`,{},"optional",Pz)}async function gt(e){let t=await I(`/datasets/${e}`,{},"optional");return Nz(t.dataset)}async function Mz(e){return I(`/datasets/${e}/versions`,{},!0)}async function wm(e){return I("/datasets",{method:"POST",body:JSON.stringify(e)},!0)}async function Em(e){return I(`/datasets/${e}/finalize`,{method:"POST"},!0)}async function J_(e){return I(`/datasets/${e}/request-access`,{method:"POST"},!0)}async function Bz(e,t){let r=t?`?status=${t}`:"";return I(`/datasets/${e}/access-requests${r}`,{},!0)}async function Lz(e,t){return I(`/datasets/${e}/access-requests/${t}/approve`,{method:"POST"},!0)}async function Uz(e,t){return I(`/datasets/${e}/access-requests/${t}/deny`,{method:"POST"},!0)}async function Vz(e,t){return I(`/datasets/${e}/invite`,{method:"POST",body:JSON.stringify({username:t})},!0)}async function zz(e){return I(`/datasets/${e}/collaborators`,{},!0)}async function Hz(e,t){return I(`/admin/datasets/${e}/enrichment`,{method:"POST",body:JSON.stringify(t)},!0)}var vm;var Po=A(()=>{Y_();Ps();vm=/^\d{4}-\d{4}-\d{4}-\d{3}[\dX]$/});var Tc;var Jz=A(()=>{Tc=["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"]});async function Nc(e){return I(`/datasets/${e}/publish/request`,{method:"POST"},!0)}async function Qz(e){return I(`/datasets/${e}/publish/status`,{},!0)}async function Zz(e){return I(`/datasets/${e}/publish/resend`,{method:"POST"},!0)}async function eH(e){let t=e?`?status=${e}`:"";return I(`/admin/publish/requests${t}`,{},!0)}async function tH(e,t){return I(`/admin/publish/${e}/deny`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:t})},!0)}function H3e(e,t=[]){if(e){let r=Tc.indexOf(e);if(r>=0)return r+1}return Math.min(t.length+1,Tc.length)}function G3e(e){if(!(e instanceof M))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}async function qc(e,t=!1,r=!1,n=!1,i,s){let c,l,d=0,f=!1,m,p=t,g=[],y;function x(v,_,E,S){if(!s)return;s({step:v,stepIndex:H3e(v,_),stepTotal:Tc.length,s3LockLocked:E,s3LockTotal:S,s3LockResumed:v==="s3_lock"&&f?!0:void 0})}for(let v=1;v<=5;v++)try{let _,E=!0;do{if(_=await I(`/admin/publish/${e}/approve`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({resume:E?p:!0,sandbox:r,s3_lock_continuation_token:c,s3_lock_total:l,skip_ci_check:n})},!0),E=!1,_.step_results)g.push(..._.step_results);if(_.s3_lock_total!==void 0)l=_.s3_lock_total;if(_.s3_lock_batch_count!==void 0)d+=_.s3_lock_batch_count;let S=_.step??_.step_results?.[_.step_results.length-1]?.step;if(S&&(S!==m||S==="s3_lock"))x(S,_.steps_completed??[],S==="s3_lock"?d:void 0,S==="s3_lock"?l:void 0),m=S;if(_.hasMore&&_.s3_lock_continuation_token!==void 0)c=_.s3_lock_continuation_token;else break}while(_.hasMore);if(g.length>0)_.step_results=Xz(g);return _}catch(_){if(y=_,v===5||!G3e(_)){if(_ instanceof M&&g.length>0)_.stepResults=Xz(g);throw _}let S=_;if(i?.({attempt:v,maxAttempts:5,delayMs:1e4,step:S.step,error:S.message}),await new Promise((D)=>setTimeout(D,1e4)),p=!0,c!==void 0)f=!0}throw y}function Xz(e){let t=new Map;for(let r of e)t.set(r.step,r);return Array.from(t.values())}var pd=A(()=>{Jz();Ps();gr()});function iH(e){Z_=e}function eD(){return Z_}function md(e){if(Z_)process.stderr.write(`${e}
|
|
106
|
-
`)}var Z_=!1;var sH={};Ti(sH,{runCommand:()=>
|
|
105
|
+
`)}var VV=!1;var T_=A(()=>{Ke()});var HV;var zV=A(()=>{HV={name:"nemar-cli",version:"0.9.10-PR1167.6909e1c",description:"CLI for NEMAR (Neuroelectromagnetic Data Archive and Tools Resource) dataset management",type:"module",main:"dist/index.js",bin:{nemar:"dist/index.js"},scripts:{dev:"bun run src/index.ts",build:"bun build src/index.ts --outdir dist --target bun --minify && sed '1s|#!/usr/bin/env node|#!/usr/bin/env bun|' dist/index.js > dist/index.js.tmp && mv dist/index.js.tmp dist/index.js",test:"bun test",lint:"biome check src/","lint:fix":"biome check --fix src/",format:"biome format --write src/",typecheck:"tsc --noEmit && tsc --noEmit -p backend",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","README.md","LICENSE"],dependencies:{chalk:"^5.3.0",commander:"^12.1.0",conf:"^13.0.1","fuse.js":"^7.1.0",inquirer:"^9.2.15",ora:"^8.0.1",zod:"^3.23.8"},"lint-staged":{"src/**/*.{ts,tsx}":["biome check --fix"],"backend/src/**/*.{ts,tsx}":["biome check --fix"]},devDependencies:{"@biomejs/biome":"1.9.4","@types/bcryptjs":"^3.0.0","@types/bun":"latest","@types/inquirer":"^9.0.7",ajv:"^8.20.0","ajv-formats":"^3.0.1",bcryptjs:"^3.0.3",husky:"^9.1.7","lint-staged":"^16.3.2",typescript:"^5.5.4",wrangler:"^4.70.0",yaml:"^2.8.4"}}});var Ao;var bm=A(()=>{zV();Ao=HV.version});function U(e){if(e instanceof Error)return e.message;return String(e)}var M,ko;var gr=A(()=>{M=class M extends Error{statusCode;details;step;constructor(e,t,r,n){super(t);this.statusCode=e;this.details=r;this.step=n;this.name="ApiError"}};ko=class ko extends M{mode;eta;constructor(e,t,r,n){super(503,t,n);this.mode=e;this.eta=r;this.name="MaintenanceError"}}});function GV(){if(process.env.TEST_API_URL)return process.env.TEST_API_URL;if(q_)return N_;return ht().apiUrl||N_}async function I(e,t={},r=!1,n){let i=`${GV()}${e}`,s={"Content-Type":"application/json","X-CLI-Version":Ao,...t.headers};if(r){let c=ht();if(!c.apiKey&&r===!0)throw new M(401,"Not authenticated. Run 'nemar auth login' first.");if(c.apiKey)s.Authorization=`Bearer ${c.apiKey}`}let o;try{o=await fetch(i,{...t,headers:s})}catch(c){throw new M(0,`Network error: Could not connect to ${GV()}`,{originalError:c instanceof Error?c.message:String(c)})}let a;try{a=await o.json()}catch{throw new M(o.status,`Invalid response from server (status ${o.status})`)}if(!o.ok){if(o.status===503&&(a.mode==="read-only"||a.mode==="full")){let c=typeof a.message==="string"?a.message:"NEMAR is in maintenance mode. Please retry shortly.",l=typeof a.eta==="string"?a.eta:null,d=new ko(a.mode,c,l,a.details);throw xm(d),d}throw new M(o.status,a.error||a.message||"Request failed",a.details,typeof a.step==="string"?a.step:void 0)}if(n){let c=n.safeParse(a);if(!c.success)throw new M(o.status,`Response for ${e} did not match the expected NEMAR contract`,{issues:c.error.issues});return c.data}return a}var N_="https://api.nemar.org",q_;var Ps=A(()=>{ks();T_();bm();gr();q_=N_.includes("workers.dev")});async function WV(e,t){let r=new URLSearchParams;if(e)r.set("status",e);if(t)r.set("role",t);let n=r.toString()?`?${r.toString()}`:"";return I(`/admin/users${n}`,{},!0)}async function KV(e){return I(`/admin/approve/${e}`,{method:"POST"},!0)}async function YV(e){return I(`/admin/approve/by-id/${e}`,{method:"POST"},!0)}async function JV(e){return I(`/admin/revoke/${e}`,{method:"POST"},!0)}async function XV(e,t){return I(`/admin/users/${e}/role`,{method:"POST",body:JSON.stringify({role:t})},!0)}async function j_(e,t){return I(`/admin/datasets/${e}/visibility`,{method:"PATCH",body:JSON.stringify({visibility:t})},!0)}async function QV(e){return I(`/datasets/${e}/publish`,{method:"POST"},!0)}async function ZV(e){return I(`/admin/datasets/${e}/ci`,{},!0)}async function Ri(e){return I(`/admin/datasets/${e}/ci`,{method:"POST"},!0)}async function M_(e){return I(`/admin/datasets/${e}/ci/validate`,{method:"POST"},!0)}async function B_(e){return I(`/admin/datasets/${e}/ci/sync`,{method:"POST"},!0)}async function ez(e,t){return I(`/admin/datasets/${e}/doi/concept`,{method:"POST",body:JSON.stringify(t)},!0)}async function dd(e){return I(`/admin/datasets/${e}/doi`,{},!0)}async function L_(e,t){return I(`/admin/datasets/${e}/doi/update`,{method:"POST",body:JSON.stringify(t)},!0)}async function tz(e,t){return I(`/admin/datasets/${e}/withdraw`,{method:"POST",body:JSON.stringify({reason:t.reason,dry_run:t.dryRun})},!0)}async function rz(e,t){return I(`/admin/datasets/${e}/restore`,{method:"POST",body:JSON.stringify({dry_run:t.dryRun})},!0)}async function nz(e){return I(`/admin/datasets/${e}/reset`,{method:"POST"},!0)}async function iz(e,t=!1){return I(`/admin/datasets/${e}`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({force:t})},!0)}async function sz(e){return I("/admin/datasets/bulk-delete",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dataset_ids:e})},!0)}async function oz(e){return I("/admin/datasets/import",{method:"POST",body:JSON.stringify(e)},!0)}async function az(e){return I("/admin/datasets/exemplar",{method:"POST",body:JSON.stringify(e)},!0)}async function cz(e){return I(`/admin/datasets/${e}/exemplar/remint-dois`,{method:"POST"},!0)}async function U_(e,t){let r=new URLSearchParams;if(e)r.set("status",e);if(t!==void 0)r.set("blocklisted",t?"1":"0");let n=r.toString();return I(`/admin/imports${n?`?${n}`:""}`,{},!0)}async function uz(e){return I(`/admin/imports/${e}/rollback`,{method:"POST"},!0)}async function lz(e){return I(`/admin/imports/${e}/retry`,{method:"POST"},!0)}async function V_(e){return I(`/admin/imports/${e}/verify`,{method:"POST"},!0)}async function dz(e){return I("/admin/imports/dispatch-cooldown",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({dataset_ids:e})},!0)}async function Oc(e,t){return I(`/admin/datasets/${e}/reindex`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t??{})},!0)}async function fz(e,t){return I("/admin/datasets/reindex/bulk",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({filter:e,...t??{}})},!0)}async function pz(e){let t=e?.limit??15;return I(`/admin/datasets/hed-sweep?limit=${encodeURIComponent(String(t))}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function mz(){return I("/admin/datasets/hed-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function hz(e){let t=e?.limit??15,r=new URLSearchParams({limit:String(t)});if(e?.olderThan!=null)r.set("older-than",String(e.olderThan));if(e?.before!=null)r.set("before",e.before);return I(`/admin/datasets/data-integrity-sweep?${r.toString()}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function gz(){return I("/admin/datasets/data-integrity-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function yz(e,t){let r=t?.write?"":"?dry_run=1";return I(`/admin/datasets/${e}/availability-report${r}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function xz(e){let t=e?.limit??30,r=new URLSearchParams({limit:String(t)});if(e?.missingOnly)r.set("missing-only","1");return I(`/admin/datasets/availability-report-sweep?${r.toString()}`,{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function bz(){return I("/admin/datasets/availability-report-sweep?reset=1",{method:"POST",headers:{"Content-Type":"application/json"}},!0)}async function vz(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 r=t.toString()?`?${t.toString()}`:"";return I(`/admin/fleet/drift${r}`,{},!0)}async function Ac(e,t){return I(`/admin/datasets/${e}/enforce`,{method:"POST",body:JSON.stringify({dry_run:t})},!0)}async function _z(e){return I("/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 Dz(e,t=!1){return I(`/admin/datasets/${e}/revalidate${t?"?force=true":""}`,{method:"POST"},!0)}async function wz(e){let t=e?`?user=${encodeURIComponent(e)}`:"";return I(`/admin/email-preferences${t}`,{},!0)}async function Ez(e,t){let r=t?`?user=${encodeURIComponent(t)}`:"";return I(`/admin/email-preferences${r}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)},!0)}async function z_(e){return I("/admin/notify",{method:"POST",body:JSON.stringify(e)},!0)}async function Sz(){return I("/admin/summary/coverage",{},!0)}async function $z(e,t,r){return I("/admin/manifest/dispatch",{method:"POST",body:JSON.stringify({dataset_id:e,version:t,skip_canary:r?.skipCanary??!1})},!0)}async function H_(e){return I("/admin/doctor/scan",{method:"POST",body:JSON.stringify({...e?.check&&{check:e.check},...e?.datasetId&&{dataset_id:e.datasetId}})},!0)}async function G_(e){return I("/admin/doctor/fix",{method:"POST",body:JSON.stringify({check:e.check,...e.datasetId&&{dataset_id:e.datasetId},...e.dryRun&&{dry_run:!0}})},!0)}var kc=A(()=>{Ps()});async function Zn(e,t){return I(`/datasets/${e}/upload-credentials`,{method:"POST",body:JSON.stringify({duration_seconds:t})},!0)}async function W_(e,t){return I(`/datasets/${e}/download-credentials`,{method:"POST",body:JSON.stringify({duration_seconds:t})},!0)}async function Cz(e){return I(`/admin/datasets/${e}/files`,{},!0)}async function Fz(e){let t,r=0,n=[],i=!0;while(i){let s=await I(`/admin/datasets/${e}/s3-lock`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({continuation_token:t})},!0);if(r+=s.locked,s.failed?.length)n.push(...s.failed);if(i=s.hasMore,t=s.continuation_token,i&&!t)throw new M(500,"S3 lock paginated response missing continuation_token; aborting to avoid infinite loop")}return{locked:r,failed:n}}var Pc=A(()=>{Ps();gr()});function j3e(e){return e.startsWith("v")?e:`v${e}`}var N3e,q3e,Rz,dJe;var K_=A(()=>{ud();N3e=/^v?\d+\.\d+\.\d+(?:-(?:rc|alpha|beta)\d*)?$/,q3e=/^v\d+\.\d+\.\d+(?:-(?:rc|alpha|beta)\d*)?$/;Rz=R.string().regex(N3e,"must be a semver version, optionally v-prefixed").transform(j3e),dJe=R.string().regex(q3e,"must be the canonical v-prefixed tag (vX.Y.Z)")});var M3e,B3e,Oz;var Az=A(()=>{ud();M3e=R.object({id:R.number().int(),username:R.string().nullable(),email:R.string(),github_username:R.string().nullable(),role:R.string(),orcid:R.string().nullable().optional(),created_at:R.string().optional(),approved_at:R.string().nullable().optional(),dataset_count:R.number().int().optional(),sandbox_completed:R.boolean().optional(),sandbox_completed_at:R.string().nullable().optional(),sandbox_dataset_id:R.string().nullable().optional()}).passthrough(),B3e=R.object({prefix:R.string(),created_at:R.string(),last_used_at:R.string().nullable()}).passthrough().nullable(),Oz=R.object({user:M3e,token:B3e.optional()}).passthrough()});var L3e="0.4.0",U3e,fd,kz,V3e,z3e,yJe,Pz,xJe,bJe;var Iz=A(()=>{ud();K_();U3e=R.enum(["openneuro","nemar","gin","other"]),fd=R.union([R.literal(0),R.literal(1)]).nullable(),kz=R.object({dataset_id:R.string(),id:R.string().optional(),name:R.string(),description:R.string().nullable().optional(),status:R.string(),visibility:R.string(),concept_doi:R.string().nullable().optional(),doi:R.string().nullable().optional(),created_at:R.string(),updated_at:R.string().optional(),owner_username:R.string().nullable().optional(),source:R.string().nullable().optional(),modalities:R.string().optional(),participants:R.number().int().nonnegative(),tasks:R.string().optional(),authors:R.string().optional(),license:R.string().optional(),file_size:R.number().nonnegative(),file_size_formatted:R.string().optional(),total_files:R.number().nonnegative().nullable().optional(),num_citations:R.number().int().nonnegative().optional(),n_channels:R.number().int().nullable().optional(),electrode_system:R.string().nullable().optional(),has_hed:fd.optional(),hed_version:R.string().nullable().optional(),data_complete:fd.optional(),bytes_present:R.number().nonnegative().nullable().optional(),latest_version:Rz.nullable().optional()}).passthrough(),V3e=kz.extend({file_size:R.number().nonnegative().nullable(),modalities:R.string().nullable().optional(),tasks:R.string().nullable().optional(),authors:R.string().nullable().optional(),license:R.string().nullable().optional(),owner_github:R.string().nullable().optional(),attestation_deposit_type:R.enum(["owner","redistribution"]).nullable().optional(),attestation_key_status:R.enum(["destroyed","retained"]).nullable().optional(),attestation_deidentified:fd.optional(),attestation_no_duplicate:fd.optional(),attestation_upstream_source:R.string().nullable().optional(),attestation_accepted_at:R.string().nullable().optional()}).passthrough(),z3e=R.object({id:R.string(),name:R.string(),modalities:R.string().nullable().optional(),participants:R.number().int().nullable().optional(),doi:R.string().nullable().optional(),tasks:R.string().nullable().optional(),authors:R.string().nullable().optional(),has_hed:fd.optional(),score:R.number().optional(),snippet:R.string().optional()}).passthrough(),yJe=R.object({datasets:R.array(kz),count:R.number().int().nonnegative(),total_count:R.number().int().nonnegative().optional(),limit:R.number().int().optional(),offset:R.number().int().optional()}).passthrough(),Pz=R.object({results:R.array(z3e),count:R.number().int().nonnegative(),returned:R.number().int().nonnegative().optional(),offset:R.number().int().nonnegative().optional(),limit:R.number().int().optional(),candidate_ceiling:R.number().int().optional(),truncated:R.boolean().optional(),method:R.enum(["exact_id","text","text_fallback","semantic","unavailable"]).optional(),min_score:R.number().optional(),warning:R.string().optional()}).passthrough(),xJe=R.object({dataset:V3e}).passthrough(),bJe=R.object({schema_version:R.literal(L3e),doc_type:R.literal("dataset"),dataset_id:R.string().regex(/^[a-z]{2}\d+$/,"neuroschema dataset_id pattern"),name:R.string(),source:U3e,recording_modality:R.array(R.string()).min(1),description:R.string().nullable().optional(),bids_version:R.string().nullable().optional(),license:R.string().nullable().optional()}).passthrough()});var Y_=A(()=>{K_();Az();Iz()});async function _m(e){return I(`/datasets/${e}/ci/status`,{},!0)}async function Tz(e){return I(`/datasets/${e}/manifest`,{},!0)}async function Dm(e,t){return I(`/datasets/${e}/manifest/${t}`,{},!0)}function Nz(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 Ic(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.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);let r=t.toString()?`?${t.toString()}`:"",n=await I(`/datasets${r}`,{},e.mine?!0:"optional");return n.datasets=n.datasets.map(Nz),n}async function qz(e){return I(`/datasets/resolve/${e}`,{},"optional")}async function jz(e,t={}){let r=new URLSearchParams({q:e});if(t.modality)r.set("modality",t.modality);if(t.limit)r.set("limit",String(t.limit));if(t.hasHed)r.set("has_hed","1");return await I(`/datasets/search?${r.toString()}`,{},"optional",Pz)}async function gt(e){let t=await I(`/datasets/${e}`,{},"optional");return Nz(t.dataset)}async function Mz(e){return I(`/datasets/${e}/versions`,{},!0)}async function wm(e){return I("/datasets",{method:"POST",body:JSON.stringify(e)},!0)}async function Em(e){return I(`/datasets/${e}/finalize`,{method:"POST"},!0)}async function J_(e){return I(`/datasets/${e}/request-access`,{method:"POST"},!0)}async function Bz(e,t){let r=t?`?status=${t}`:"";return I(`/datasets/${e}/access-requests${r}`,{},!0)}async function Lz(e,t){return I(`/datasets/${e}/access-requests/${t}/approve`,{method:"POST"},!0)}async function Uz(e,t){return I(`/datasets/${e}/access-requests/${t}/deny`,{method:"POST"},!0)}async function Vz(e,t){return I(`/datasets/${e}/invite`,{method:"POST",body:JSON.stringify({username:t})},!0)}async function zz(e){return I(`/datasets/${e}/collaborators`,{},!0)}async function Hz(e,t){return I(`/admin/datasets/${e}/enrichment`,{method:"POST",body:JSON.stringify(t)},!0)}var vm;var Po=A(()=>{Y_();Ps();vm=/^\d{4}-\d{4}-\d{4}-\d{3}[\dX]$/});var Tc;var Jz=A(()=>{Tc=["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"]});async function Nc(e){return I(`/datasets/${e}/publish/request`,{method:"POST"},!0)}async function Qz(e){return I(`/datasets/${e}/publish/status`,{},!0)}async function Zz(e){return I(`/datasets/${e}/publish/resend`,{method:"POST"},!0)}async function eH(e){let t=e?`?status=${e}`:"";return I(`/admin/publish/requests${t}`,{},!0)}async function tH(e,t){return I(`/admin/publish/${e}/deny`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({reason:t})},!0)}function H3e(e,t=[]){if(e){let r=Tc.indexOf(e);if(r>=0)return r+1}return Math.min(t.length+1,Tc.length)}function G3e(e){if(!(e instanceof M))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}async function qc(e,t=!1,r=!1,n=!1,i,s){let c,l,d=0,f=!1,m,p=t,g=[],y;function x(v,_,E,S){if(!s)return;s({step:v,stepIndex:H3e(v,_),stepTotal:Tc.length,s3LockLocked:E,s3LockTotal:S,s3LockResumed:v==="s3_lock"&&f?!0:void 0})}for(let v=1;v<=5;v++)try{let _,E=!0;do{if(_=await I(`/admin/publish/${e}/approve`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({resume:E?p:!0,sandbox:r,s3_lock_continuation_token:c,s3_lock_total:l,skip_ci_check:n})},!0),E=!1,_.step_results)g.push(..._.step_results);if(_.s3_lock_total!==void 0)l=_.s3_lock_total;if(_.s3_lock_batch_count!==void 0)d+=_.s3_lock_batch_count;let S=_.step??_.step_results?.[_.step_results.length-1]?.step;if(S&&(S!==m||S==="s3_lock"))x(S,_.steps_completed??[],S==="s3_lock"?d:void 0,S==="s3_lock"?l:void 0),m=S;if(_.hasMore&&_.s3_lock_continuation_token!==void 0)c=_.s3_lock_continuation_token;else break}while(_.hasMore);if(g.length>0)_.step_results=Xz(g);return _}catch(_){if(y=_,v===5||!G3e(_)){if(_ instanceof M&&g.length>0)_.stepResults=Xz(g);throw _}let S=_;if(i?.({attempt:v,maxAttempts:5,delayMs:1e4,step:S.step,error:S.message}),await new Promise((D)=>setTimeout(D,1e4)),p=!0,c!==void 0)f=!0}throw y}function Xz(e){let t=new Map;for(let r of e)t.set(r.step,r);return Array.from(t.values())}var pd=A(()=>{Jz();Ps();gr()});function iH(e){Z_=e}function eD(){return Z_}function md(e){if(Z_)process.stderr.write(`${e}
|
|
106
|
+
`)}var Z_=!1;var sH={};Ti(sH,{runCommand:()=>F});var{spawn:W3e}=globalThis.Bun;async function F(e,t={}){let r={...process.env,GIT_TERMINAL_PROMPT:"0",...t.env};for(let l of t.unsetEnv??[])delete r[l];let n=W3e({cmd:e,cwd:t.cwd,stdout:"pipe",stderr:"pipe",env:r}),i=!1,s;if(t.timeout)s=setTimeout(()=>{i=!0,n.kill()},t.timeout);if(eD()){let l=t.cwd?` (cwd=${t.cwd})`:"";md(u.dim(`$ ${e.join(" ")}${l}`))}let o=await new Response(n.stdout).text(),a=await new Response(n.stderr).text(),c=await n.exited;if(s)clearTimeout(s);if(eD()){if(o.trim())md(u.dim(o.trimEnd()));if(a.trim())md(u.yellow(a.trimEnd()));md(u.dim(`(exit ${c})`))}if(i)return{stdout:o,stderr:a||`Command timed out after ${Math.round(t.timeout/1000)}s`,exitCode:c??1};return{stdout:o,stderr:a,exitCode:c}}var Bt=A(()=>{Ke()});async function K3e(){try{let{exitCode:e,stderr:t}=await F(["ssh","-T","-o","BatchMode=yes","-o","ConnectTimeout=5","git@github.com"]),r=t.includes("successfully authenticated");if(!r)console.warn("SSH test to github.com failed:",{exitCode:e,stderr:t.trim().slice(0,500)});return{works:r,error:r?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 hd(){try{let{stdout:e,exitCode:t,stderr:r}=await F(["gh","auth","token"]);if(t!==0)return console.warn("gh CLI returned non-zero exit code:",t),console.warn("stderr:",r),{token:null,error:`gh auth token failed: ${r.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 Sm(e){try{let{stdout:t,exitCode:r,stderr:n}=await F(["gh","api","user","--jq",".login"]);if(r!==0){if(n.includes("not logged in")||n.includes("auth login"))return{authenticated:!1,error:"gh CLI not authenticated. Run 'gh auth login' to authenticate."};return{authenticated:!1,error:`gh CLI error: ${n.trim()||"unknown error"}`}}let i=t.trim();if(!i)return{authenticated:!1,error:"gh CLI returned empty username"};if(e){let s=i.toLowerCase()===e.toLowerCase();return{authenticated:!0,username:i,matches:s,error:s?void 0:`gh CLI authenticated as '${i}', expected '${e}'`}}return{authenticated:!0,username:i}}catch(t){let r=t instanceof Error?t.message:String(t);if(r.includes("ENOENT")||r.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: ${r}`}}}async function $m(e){if(!/^[a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+$/.test(e))return{accepted:!1,error:`Invalid repository format: ${e}`};let{stdout:t,exitCode:r,stderr:n}=await F(["gh","api","/user/repository_invitations"]);if(r!==0){if(n.includes("not logged in")||n.includes("auth login"))return{accepted:!1,error:"gh CLI not authenticated. Run 'gh auth login' to authenticate."};if(n.includes("API rate limit")||n.includes("403"))return{accepted:!1,error:"GitHub API rate limit exceeded. Please try again in a few minutes."};if(n.includes("ENOENT")||n.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: ${n.trim()||"unknown error"}`}}let i=null;try{i=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(!i){let{exitCode:a}=await F(["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:o}=await F(["gh","api","--method","PATCH",`/user/repository_invitations/${i}`]);if(s!==0)return{accepted:!1,error:`Failed to accept invitation: ${o.trim()||"unknown error"}`};return{accepted:!0}}async function ei(e,t,r="origin"){let n=t;if(process.env.GH_TOKEN&&t.startsWith("git@github.com:")){let i=process.env.GH_TOKEN.trim();if(!i||/\s/.test(i))return{success:!1,error:"GH_TOKEN environment variable is set but appears malformed (empty or contains whitespace)"};n=`https://github.com/${t.replace("git@github.com:","")}`,await F(["git","config","credential.https://github.com.helper",`!printf 'username=x-access-token\\npassword=${i}'`],{cwd:e})}else if(t.startsWith("git@github.com:")){let i=t.replace("git@github.com:",""),s=await hd();if(s.token)n=`https://github.com/${i}`,await F(["git","config","credential.https://github.com.helper",`!printf 'username=x-access-token\\npassword=${s.token}'`],{cwd:e});else{let o=await K3e();if(o.works)n=t;else return{success:!1,error:`GitHub authentication not configured.
|
|
107
107
|
|
|
108
108
|
gh CLI failed: ${s.error||"could not get token"}
|
|
109
109
|
SSH failed: ${o.error||"could not connect"}
|
|
@@ -115,24 +115,24 @@ Fix one of these:
|
|
|
115
115
|
2. Configure SSH for GitHub:
|
|
116
116
|
ssh-keygen -t ed25519 -C "your@email.com"
|
|
117
117
|
Add the public key to https://github.com/settings/keys
|
|
118
|
-
Test with: ssh -T git@github.com`}}}try{let{stdout:i}=await
|
|
119
|
-
`).filter(Boolean).length;return{files:r,size:"unknown",sizeBytes:0,annexedFiles:0,presentFiles:r,missingFiles:0}}catch(t){let r=t instanceof Error?t.message:String(t);return console.warn(`Failed to count files in ${e}: ${r}`),null}}async function uH(e){try{let{stdout:t,exitCode:r}=await
|
|
120
|
-
`).map((n)=>{let[i,s,o]=n.split("|");return{version:i,date:s,commit:o}})}catch{return[]}}async function lH(e,t){try{let r=t.startsWith("v")?t:`v${t}`,{stdout:n,exitCode:i}=await
|
|
118
|
+
Test with: ssh -T git@github.com`}}}try{let{stdout:i}=await F(["git","remote","get-url",r],{cwd:e});if(i.trim()){let{stderr:s,exitCode:o}=await F(["git","remote","set-url",r,n],{cwd:e});if(o!==0)return{success:!1,error:s.trim()}}else{let{stderr:s,exitCode:o}=await F(["git","remote","add",r,n],{cwd:e});if(o!==0)return{success:!1,error:s.trim()}}return{success:!0}}catch(i){return{success:!1,error:i.message}}}function Y3e(e){return`!printf 'username=x-access-token\\npassword=${e}'`}function oH(e,t){if(!e.startsWith("git@github.com:"))return{url:e};let r=t?.trim();if(!r||/[\s']/.test(r))return{url:e};return{url:`https://github.com/${e.replace("git@github.com:","")}`,credentialHelper:Y3e(r)}}var Oi=A(()=>{Bt()});import{existsSync as aH,readFileSync as J3e}from"fs";import{join as X3e}from"path";async function tD(e){try{let{stdout:t,exitCode:r}=await F(["git","log","-1","--format=%H","--",".nemar/metadata.json"],{cwd:e});if(r!==0)return"unknown";return t.trim().length>0?"present":"absent"}catch{return"unknown"}}async function cH(e){if(!aH(e))return null;try{let{stdout:t,exitCode:r}=await F(["git","annex","info","--json"],{cwd:e});if(r===0){let n=JSON.parse(t),i=0,s=n["local annex size"]||"0 bytes",o=s.match(/([\d.]+)\s*(bytes?|KB|MB|GB|TB)/i);if(o){let l=Number.parseFloat(o[1]),d=o[2].toLowerCase();i=l*({byte:1,bytes:1,kb:1024,mb:1048576,gb:1073741824,tb:1099511627776}[d]||1)}let a=n["annexed files in working tree"]||0,c=n["local annex keys"]||0;return{files:a,size:s,sizeBytes:i,annexedFiles:a,presentFiles:c,missingFiles:a-c}}}catch(t){let r=t instanceof Error?t.message:String(t);console.warn(`Failed to get git-annex info for ${e}: ${r}`)}try{let{stdout:t}=await F(["find",".","-type","f","-not","-path","./.git/*"],{cwd:e}),r=t.trim().split(`
|
|
119
|
+
`).filter(Boolean).length;return{files:r,size:"unknown",sizeBytes:0,annexedFiles:0,presentFiles:r,missingFiles:0}}catch(t){let r=t instanceof Error?t.message:String(t);return console.warn(`Failed to count files in ${e}: ${r}`),null}}async function uH(e){try{let{stdout:t,exitCode:r}=await F(["git","tag","-l","--sort=-version:refname","--format=%(refname:short)|%(creatordate:short)|%(objectname:short)"],{cwd:e});if(r!==0||!t.trim())return[];return t.trim().split(`
|
|
120
|
+
`).map((n)=>{let[i,s,o]=n.split("|");return{version:i,date:s,commit:o}})}catch{return[]}}async function lH(e,t){try{let r=t.startsWith("v")?t:`v${t}`,{stdout:n,exitCode:i}=await F(["git","rev-parse",r],{cwd:e});if(i!==0)return null;return n.trim()}catch{return null}}async function ti(e){try{let{stdout:t,exitCode:r}=await F(["git","rev-parse","--abbrev-ref","HEAD"],{cwd:e});if(r!==0)return null;return t.trim()}catch{return null}}async function Cm(e,t={}){let r=await ti(e);if(!r)return console.log(u.yellow(`
|
|
121
121
|
Warning: Could not determine current branch name.`)),console.log(u.yellow(" Proceeding with upload; ensure your branch is named 'main'.")),!0;if(r==="main"||r.startsWith("adjusted/main"))return!0;if(console.log(u.yellow(`
|
|
122
|
-
Warning: Your current branch is "${r}", but NEMAR requires "main".`)),console.log(u.yellow(" Without renaming, CI validation, branch protection, and metadata pipelines will not work.")),!t.yes){if(!await Q3e(r))return!1}let{exitCode:n,stderr:i}=await
|
|
122
|
+
Warning: Your current branch is "${r}", but NEMAR requires "main".`)),console.log(u.yellow(" Without renaming, CI validation, branch protection, and metadata pipelines will not work.")),!t.yes){if(!await Q3e(r))return!1}let{exitCode:n,stderr:i}=await F(["git","branch","-m",r,"main"],{cwd:e});if(n!==0){if(console.log(u.red(` Failed to rename branch "${r}" to "main".`)),i.trim())console.log(u.red(` Git error: ${i.trim()}`));return!1}return console.log(u.green(` Renamed branch "${r}" to "main".`)),!0}async function Q3e(e){let t=(await Promise.resolve().then(() => (Bn(),W3))).default;try{let{rename:r}=await t.prompt([{type:"confirm",name:"rename",message:`Rename branch "${e}" to "main"?`,default:!0}]);if(!r)console.log(u.red(" Upload cancelled. Rename your branch to main before uploading:")),console.log(u.dim(` git branch -m '${e}' main`));return r}catch(r){return console.log(u.red(` Failed to prompt: ${r instanceof Error?r.message:String(r)}`)),console.log(u.dim(` You can manually rename: git branch -m '${e}' main`)),!1}}async function Is(e){try{let{stdout:t,exitCode:r}=await F(["git","remote","get-url","origin"],{cwd:e});if(r!==0||!t.trim())return null;let i=t.trim().match(/[/:]([^/]+?)(?:\.git)?$/);if(!i)return null;return i[1]}catch{return null}}function dH(e){let t=X3e(e,"dataset_description.json");if(!aH(t))return{version:null};try{let r=JSON.parse(J3e(t,"utf-8"));return{version:typeof r.DatasetVersion==="string"?r.DatasetVersion:null}}catch(r){return{version:null,error:`dataset_description.json is unreadable: ${r.message}`}}}async function fH(e){let t=[];for(let r of["origin/HEAD","origin/main","origin/master"]){let{stdout:n,stderr:i,exitCode:s}=await F(["git","show",`${r}:dataset_description.json`],{cwd:e});if(s!==0){if(i&&!/unknown revision|bad revision|does not exist/i.test(i))t.push(`git show ${r} failed: ${i.trim()}`);continue}if(!n.trim())continue;try{let o=JSON.parse(n);if(typeof o.DatasetVersion==="string")return{version:o.DatasetVersion,warnings:t}}catch(o){t.push(`${r}:dataset_description.json is malformed: ${o.message}`)}}return{version:null,warnings:t}}async function pH(e){let{stdout:t,exitCode:r}=await F(["git","rev-parse","--abbrev-ref","@{upstream}"],{cwd:e});if(r===0&&t.trim())return{ref:t.trim()};for(let n of["origin/HEAD","origin/main","origin/master"]){let{exitCode:i}=await F(["git","rev-parse","--verify","--quiet",n],{cwd:e});if(i===0)return{ref:n}}return{ref:null,error:"Could not resolve a remote tracking branch (origin/HEAD, origin/main, origin/master all missing)"}}async function mH(e){let{stdout:t,stderr:r,exitCode:n}=await F(["git","status","--porcelain"],{cwd:e});if(n!==0)return{dirty:!1,error:r.trim()||"git status failed"};return{dirty:t.trim().length>0}}async function hH(e){let{stderr:t,exitCode:r}=await F(["git","fetch","--tags","origin"],{cwd:e});if(r!==0)return{success:!1,error:t.trim()||"git fetch failed"};return{success:!0}}async function gH(e,t){let{stderr:r,exitCode:n}=await F(["git","merge","--ff-only",t],{cwd:e});if(n!==0)return{success:!1,error:r.trim()||`Cannot fast-forward to ${t}`};return{success:!0}}var jc=A(()=>{Ke();Bt()});async function Ai(e,t,r){try{let n={};if(r)n.GIT_AUTHOR_NAME=r.name,n.GIT_AUTHOR_EMAIL=r.email,n.GIT_COMMITTER_NAME=r.name,n.GIT_COMMITTER_EMAIL=r.email;let{stderr:i,exitCode:s}=await F(["git","add","-A"],{cwd:e,...Object.keys(n).length>0?{env:n}:{}});if(s!==0)return{success:!1,error:i.trim()||"Failed to stage changes"};let{stdout:o,exitCode:a,stderr:c}=await F(["git","status","--porcelain"],{cwd:e});if(a!==0)return{success:!1,error:c.trim()||"Failed to check git status"};if(!o.trim())return{success:!0};let{stderr:l,exitCode:d}=await F(["git","commit","-m",t],{cwd:e,...Object.keys(n).length>0?{env:n}:{}});if(d!==0){if(l.includes("nothing to commit"))return{success:!0};return{success:!1,error:l.trim()||"Failed to commit changes"}}return{success:!0}}catch(n){return{success:!1,error:n.message}}}function yH(e){return/\[rejected\]|fetch first|non-fast-forward|Updates were rejected/i.test(e)}async function Qt(e,t="origin",r){try{let n=r;if(!n){let m=await ti(e);if(!m||m==="HEAD"){let{exitCode:p}=await F(["git","log","-1","--oneline"],{cwd:e});if(p!==0)return{success:!1,error:"No commits found. The repository may not have been initialized correctly, or no changes were saved before pushing."};if(m==="HEAD")n="HEAD:main";else return{success:!1,error:"Could not detect current branch"}}else if(m.startsWith("adjusted/")){let p=m.replace(/^adjusted\//,"").replace(/\(.*\)$/,"");n=`${m}:${p}`}else n=m}let i=n.includes(":")?n.slice(n.indexOf(":")+1):n,s=!n.startsWith("adjusted/")&&n!=="HEAD:main",o="",a=!1,c=0;for(let m=0;m<=Fm;m++){let p=await F(["git","push","-u",t,n],{cwd:e});if(p.exitCode===0){a=!0;break}if(o=p.stderr,!s||m===Fm||!yH(p.stderr))break;let g=await F(["git","fetch",t],{cwd:e});if(g.exitCode!==0)return{success:!1,error:`Push rejected (non-fast-forward) and the retry fetch of ${t} failed: ${g.stderr.trim()||`exit ${g.exitCode}`}. Cannot integrate remote commits.`};let y=await F(["git","rebase",`${t}/${i}`],{cwd:e});if(y.exitCode!==0)return await F(["git","rebase","--abort"],{cwd:e}),{success:!1,error:`Push rejected: ${t}/${i} has diverging commits and auto-rebase failed: ${y.stderr.trim()}`};c++}if(!a){let m=c>0?` (still rejected after ${c} fetch+rebase retry cycle(s))`:"";return{success:!1,error:`${o.trim()||"Failed to push to GitHub"}${m}`}}let l="",d=!1,f=0;for(let m=0;m<=Fm;m++){let p=await F(["git","push",t,"git-annex"],{cwd:e});if(p.exitCode===0){d=!0;break}if(l=p.stderr,m===Fm||!yH(p.stderr))break;if((await F(["git","fetch",t,"git-annex"],{cwd:e})).exitCode!==0)break;if((await F(["git","annex","merge"],{cwd:e})).exitCode!==0)break;f++}if(!d){let m=f>0?` (still rejected after ${f} fetch+merge retry cycle(s))`:"";return{success:!0,warning:`Main branch pushed, but git-annex branch failed: ${l.trim()}${m}. Clone operations may have issues.`}}return{success:!0}}catch(n){return{success:!1,error:n.message}}}async function yr(e,t,r={}){try{let n=e,i;if(r.useGitHubToken){let d=process.env.GH_TOKEN?.trim()||null,f;if(!d){let p=await hd();d=p.token,f=p.error}let m=oH(e,d);if(n=m.url,i=m.credentialHelper,e.startsWith("git@github.com:")&&!i)return{success:!1,error:`No usable GitHub token for authenticated clone of ${e} (GH_TOKEN unset/malformed${f?`; gh CLI: ${f}`:""}). Set GH_TOKEN on this runner.`}}let s=i?{GIT_CONFIG_COUNT:"1",GIT_CONFIG_KEY_0:"credential.https://github.com.helper",GIT_CONFIG_VALUE_0:i}:void 0,{stderr:o,exitCode:a}=await F(["git","clone",n,t],s?{env:s}:{});if(a!==0)return{success:!1,error:o.trim()||"Failed to clone dataset"};if(i){let{exitCode:d,stderr:f}=await F(["git","config","credential.https://github.com.helper",i],{cwd:t});if(d!==0)return{success:!1,error:`Cloned but failed to persist the credential helper (later pushes would fail to authenticate): ${f.trim()||"git config returned non-zero"}`}}let{stderr:c,exitCode:l}=await F(["git","annex","init"],{cwd:t});if(l!==0){let{exitCode:d}=await F(["git","annex","info"],{cwd:t});if(d!==0)return{success:!1,error:`Cloned repository but git-annex initialization failed: ${c.trim()}`};console.warn("git annex init returned non-zero but annex is initialized")}return{success:!0}}catch(n){return{success:!1,error:n instanceof Error?n.message:String(n)}}}async function xH(e,t,r){try{let{stderr:n,exitCode:i}=await F(["git","checkout","-b",r],{cwd:e});if(i!==0)return{success:!1,error:n.trim()||"Failed to create branch"};let s=t.startsWith("v")?t:`v${t}`,{stderr:o,exitCode:a}=await F(["git","checkout",s,"--","."],{cwd:e});if(a!==0)return{success:!1,error:o.trim()||"Failed to checkout files from target version"};return{success:!0}}catch(n){return{success:!1,error:n.message}}}async function bH(e,t,r){let n=r||`Revert to ${t}`;try{let{exitCode:i}=await F(["git","add","-A"],{cwd:e});if(i!==0)return{success:!1,error:"Failed to stage changes"};let{stdout:s}=await F(["git","status","--porcelain"],{cwd:e});if(!s.trim())return{success:!1,error:"No changes to revert (already at target version)"};let{stderr:o,exitCode:a}=await F(["git","commit","-m",n],{cwd:e});if(a!==0)return{success:!1,error:o.trim()||"Failed to commit"};return{success:!0}}catch(i){return{success:!1,error:i.message}}}async function gd(e,t,r="origin"){try{let{stderr:n,exitCode:i}=await F(["git","push","-u",r,t],{cwd:e});if(i!==0)return{success:!1,error:n.trim()||"Failed to push branch"};return{success:!0}}catch(n){return{success:!1,error:n.message}}}var Fm=3;var Ts=A(()=>{Oi();jc();Bt()});function Lt(e){return{accessKeyId:e.access_key_id,secretAccessKey:e.secret_access_key,sessionToken:e.session_token}}function sD(e){let t=[/^\(merging .* into .*\.\.\.\)$/,/^\(recording state in git\.\.\.\)$/,/^\(scanning for /,/^\(checking /];return e.split(`
|
|
123
123
|
`).filter((r)=>{let n=r.trim();if(!n)return!1;if(n.includes("setting annex-ignore"))return!1;if(t.some((i)=>i.test(n)))return!1;return!0}).join(`
|
|
124
|
-
`).trim()}function lIe(e){let t=["type=S3","encryption=none",`bucket=${e.bucket}`,`fileprefix=${e.prefix.replace(/\/$/,"")}/`,`datacenter=${e.region}`,"signature=v4","autoenable=true","protocol=https",`partsize=${e.partsize??uIe}`];if(e.publicUrl)t.push(`publicurl=${e.publicUrl}`);return t}async function fIe(e,t){let{stdout:r,exitCode:n}=await
|
|
125
|
-
`)){let a=o.match(/^remote\.(.+?)\.annex-/);if(a&&RH.test(a[1]))t.push(a[1])}if(t.length===0){let{stdout:o,exitCode:a,stderr:c}=await
|
|
124
|
+
`).trim()}function lIe(e){let t=["type=S3","encryption=none",`bucket=${e.bucket}`,`fileprefix=${e.prefix.replace(/\/$/,"")}/`,`datacenter=${e.region}`,"signature=v4","autoenable=true","protocol=https",`partsize=${e.partsize??uIe}`];if(e.publicUrl)t.push(`publicurl=${e.publicUrl}`);return t}async function fIe(e,t){let{stdout:r,exitCode:n}=await F(["git","annex","info",t,"--json"],{cwd:e});if(n!==0)return!1;try{let i=JSON.parse(r);return i?.success===!0&&typeof i.uuid==="string"&&i.uuid.length>0&&i.remote===t}catch{return!1}}async function FH(e,t,r,n){let i=await F(["git","annex","enableremote",t,...r],{cwd:e,env:n});if(i.exitCode!==0)return{success:!1,error:sD(i.stderr)||i.stderr.trim()||`enableremote exited with code ${i.exitCode}`};return{success:!0}}async function pIe(e,t,r,n){if(await fIe(e,t))return FH(e,t,r,n);let{stderr:i,exitCode:s}=await F(["git","annex","initremote",t,...r],{cwd:e,env:n});if(s!==0){if(dIe.test(i))return FH(e,t,r,n);return{success:!1,error:sD(i)||i.trim()||`initremote exited with code ${s}`}}let o=sD(i);if(o)console.warn(` Warning during special remote setup: ${o}`);return{success:!0}}function Am(e){if(!e)return;return{AWS_ACCESS_KEY_ID:e.accessKeyId,AWS_SECRET_ACCESS_KEY:e.secretAccessKey,...e.sessionToken?{AWS_SESSION_TOKEN:e.sessionToken}:{}}}async function $r(e,t,r){let n={AWS_ACCESS_KEY_ID:r.accessKeyId,AWS_SECRET_ACCESS_KEY:r.secretAccessKey};if(r.sessionToken)n.AWS_SESSION_TOKEN=r.sessionToken;let i=await F(["git","config","remote.origin.annex-ignore","true"],{cwd:e});if(i.exitCode!==0)console.warn(`Warning: could not set remote.origin.annex-ignore: ${i.stderr.trim()}`);try{return await pIe(e,t.name,lIe(t),n)}catch(s){return{success:!1,error:`S3 remote configuration failed: ${s instanceof Error?s.message:String(s)}`}}}async function Ut(e){let{join:t}=await import("path"),{readdirSync:r,unlinkSync:n}=await import("fs"),i=t(e,".git","annex","creds"),s;try{s=r(i)}catch(o){if(o.code==="ENOENT")return;console.warn(`Warning: Could not read ${i}: ${o.message}`);return}for(let o of s)try{n(t(i,o))}catch(a){console.warn(`Warning: Could not delete ${o}: ${a.message}`)}}async function Mc(e,t="nemar-s3",r){try{let n=Am(r)??{},{stderr:i,exitCode:s}=await F(["git","annex","enableremote",t],{cwd:e,...Object.keys(n).length>0&&{env:Object.fromEntries(Object.entries({...process.env,...n}).filter((o)=>o[1]!=null))}});if(s===0)return{success:!0,enabled:!0};if(i.includes("there is no special remote named")||i.includes("not a special remote")||i.includes("Unknown remote")||i.includes("not found"))return{success:!0,enabled:!1};return{success:!1,enabled:!1,error:i.trim()}}catch(n){return{success:!1,enabled:!1,error:n.message}}}async function mIe(e,t){let{stdout:r,exitCode:n}=await F(["git","config",`remote.${t}.annex-ignore`],{cwd:e});if(n!==0)return!1;return r.trim().toLowerCase()==="true"}async function km(e){let t=[],{stdout:r,exitCode:n}=await F(["git","config","--get-regexp","^remote\\..*\\.annex-s3"],{cwd:e});if(n===0&&r.trim())for(let o of r.trim().split(`
|
|
125
|
+
`)){let a=o.match(/^remote\.(.+?)\.annex-/);if(a&&RH.test(a[1]))t.push(a[1])}if(t.length===0){let{stdout:o,exitCode:a,stderr:c}=await F(["git","annex","info","--json"],{cwd:e});if(a!==0){if(c.trim())console.error(`git annex info failed: ${c.trim()}`);return[]}if(!o.trim())return[];let l;try{l=JSON.parse(o)}catch(f){let m=f instanceof Error?f.message:String(f);return console.error(`Failed to parse git-annex info JSON: ${m}`),[]}let d=[...Array.isArray(l["trusted repositories"])?l["trusted repositories"]:[],...Array.isArray(l["semitrusted repositories"])?l["semitrusted repositories"]:[],...Array.isArray(l["untrusted repositories"])?l["untrusted repositories"]:[]];for(let f of d){if(!f?.description?.includes("["))continue;let m=f.description.match(/\[(.+?)\]/);if(!m)continue;let p=m[1];if(!RH.test(p))continue;let{stdout:g}=await F(["git","config",`remote.${p}.annex-s3`],{cwd:e});if(g.trim())t.push(p)}}let i=[...new Set(t)],s=[];for(let o of i){if(await mIe(e,o))continue;s.push(o)}return s}async function Pm(e,t,r=["s3-PUBLIC","s3-PRIVATE"]){let n=[];for(let i of r){let s=await F(["git","config",`remote.${i}.annex-uuid`],{cwd:e});if(s.exitCode!==0||!s.stdout.trim())continue;let o=await F(["git","config",`remote.${i}.annex-ignore`,"true"],{cwd:e});if(o.exitCode!==0){t?.(i,o.stderr.trim()||"unknown error");continue}n.push(i)}return n}async function OH(e,t){if(t.length===0)return null;if(t.length===1)return t[0];if(t.includes(iD))return iD;let{stdout:r,exitCode:n}=await F(["git","annex","info","--json"],{cwd:e});if(n===0&&r.trim())try{let i=JSON.parse(r),s=[...Array.isArray(i["trusted repositories"])?i["trusted repositories"]:[],...Array.isArray(i["semitrusted repositories"])?i["semitrusted repositories"]:[],...Array.isArray(i["untrusted repositories"])?i["untrusted repositories"]:[]];for(let o of s){if(o?.description!==`[${iD}]`)continue;let a=typeof o.uuid==="string"?o.uuid:null;if(!a)continue;for(let c of t){let{stdout:l}=await F(["git","config",`remote.${c}.annex-uuid`],{cwd:e});if(l.trim()===a)return c}}}catch(i){let s=i instanceof Error?i.message:String(i);console.warn(`Could not parse git annex info JSON for remote selection: ${s}`)}return t[0]}var uIe="1GiB",dIe,RH,iD="nemar-s3";var Ns=A(()=>{Bt();dIe=/There is already a special remote named "[^"]+"/;RH=/^[a-zA-Z0-9._-]+$/});import{statSync as hIe}from"fs";import{join as gIe}from"path";var{spawn:kH}=globalThis.Bun;async function aD(e,t,r){let n=t&&t.length>0?t:["."],i=r&&r.length>0?r:[];try{let{stdout:s,stderr:o,exitCode:a}=await F(["git","annex","find","--not","--in=here",...i,"--json",...n],{cwd:e});if(a!==0){if(process.env.VERBOSE&&o.trim())console.warn(`countPendingDownload: git annex find failed: ${o.trim()}`);return null}let c=0,l=0,d=!1,f=!1;for(let m of s.split(`
|
|
126
126
|
`)){let p=m.trim();if(!p)continue;if(f=!0,!p.startsWith("{")){d=!0;continue}try{let g=JSON.parse(p);if(c++,g.bytesize){let y=Number.parseInt(g.bytesize,10);if(Number.isFinite(y))l+=y}}catch{d=!0}}if(c===0&&f&&d)return null;return{fileCount:c,totalBytes:l}}catch(s){if(process.env.VERBOSE)console.warn(`countPendingDownload: ${s.message}`);return null}}function xIe(e,t,r){if(e==="failed")return{success:!1,outcome:e,error:r.trim()||`${t.filesUnavailable} file(s) unavailable from every configured remote`,...t};return{success:!0,outcome:e,...t}}function _Ie(e){let{retrieved:t,unavailable:r,requireComplete:n=!1,failureText:i=""}=e;if(r<=0)return"complete";if(n)return"failed";if(vIe.test(i))return"failed";if(t>0)return"partial";return bIe.test(i)?"partial":"failed"}async function cD(e,t={}){let r=t.jobs||4,n=t.paths&&t.paths.length>0?t.paths:["."],i=t.extraArgs??[],s=Am(t.credentials)??{},o=Object.fromEntries(Object.entries({...process.env,...s}).filter((a)=>a[1]!=null));try{let a=["git","annex","get","--json","--json-progress","-J",r.toString(),...i,...n],c=kH({cmd:a,cwd:e,stdout:"pipe",stderr:"pipe",env:o}),l=0,d=0,f=[],m=[],p="",g=[],y=(C)=>{if(t.onProgress?.(C),C.ok===!0||C.success===!0)l++;else if(C.ok===!1||C.success===!1){d++;let j=C.file??C.action?.file;if(j&&f.length<yIe)f.push(j);if(C.note)m.push(C.note);if(C["error-messages"]?.length)m.push(...C["error-messages"]);if(C.error)m.push(C.error)}},x=(async()=>{let C=c.stderr.getReader(),j=new TextDecoder;for(;;){let{done:k,value:q}=await C.read();if(k)break;g.push(q)}p=j.decode(g.reduce((k,q)=>{let Z=new Uint8Array(k.length+q.length);return Z.set(k),Z.set(q,k.length),Z},new Uint8Array))})(),v=c.stdout.getReader(),_=new TextDecoder,E="";for(;;){let{done:C,value:j}=await v.read();if(C)break;E+=_.decode(j,{stream:!0});let k=E.split(`
|
|
127
127
|
`);E=k.pop()??"";for(let q of k){let Z=q.trim();if(!Z||!Z.startsWith("{"))continue;try{y(JSON.parse(Z))}catch{}}}if(E.trim().startsWith("{"))try{y(JSON.parse(E.trim()))}catch{}if(await x,await c.exited!==0&&d===0)return{success:!1,outcome:"failed",error:p.trim()||"Failed to get dataset data",filesDownloaded:l,filesUnavailable:d,unavailablePaths:f};let D=`${p}
|
|
128
128
|
${m.join(`
|
|
129
|
-
`)}`,O=_Ie({retrieved:l,unavailable:d,requireComplete:t.requireComplete,failureText:D});return xIe(O,{filesDownloaded:l,filesUnavailable:d,unavailablePaths:f},p)}catch(a){return{success:!1,outcome:"failed",error:a.message,filesDownloaded:0,filesUnavailable:0,unavailablePaths:[]}}}async function PH(e,t){let r=t&&t.length>0?t:["."];try{let n=["git","annex","drop",...r],{stdout:i,stderr:s,exitCode:o}=await
|
|
129
|
+
`)}`,O=_Ie({retrieved:l,unavailable:d,requireComplete:t.requireComplete,failureText:D});return xIe(O,{filesDownloaded:l,filesUnavailable:d,unavailablePaths:f},p)}catch(a){return{success:!1,outcome:"failed",error:a.message,filesDownloaded:0,filesUnavailable:0,unavailablePaths:[]}}}async function PH(e,t){let r=t&&t.length>0?t:["."];try{let n=["git","annex","drop",...r],{stdout:i,stderr:s,exitCode:o}=await F(n,{cwd:e});if(o!==0){let l=[];for(let m of s.split(`
|
|
130
130
|
`)){let p=m.match(/^drop (.+) \(unsafe\)/);if(p)l.push(p[1])}let d=i.match(/^drop .+ ok$/gm),f=d?d.length:0;return{success:!1,error:s.trim(),dropped:f,kept:l}}let a=i.match(/^drop .+ ok$/gm);return{success:!0,dropped:a?a.length:0,kept:[]}}catch(n){return{success:!1,error:(n instanceof Error?n.message:String(n))||"Unknown error during drop",dropped:0,kept:[]}}}function wIe(e,t){let r=t.trim();if(r)return r;let n=e.split(`
|
|
131
131
|
`).map((a)=>a.trim()).filter(Boolean),i=n.filter((a)=>DIe.test(a)),s;if(i.length>oD)s=[`...(${i.length-oD} earlier error lines omitted)`,...i.slice(-oD)];else if(i.length)s=i;else s=n.slice(-8);return s.join(`
|
|
132
|
-
`).trim()||"Failed to copy to remote"}async function ri(e,t,r=4,n){try{let i=["git","annex","copy","--to",t,"-J",r.toString(),"."],s=Am(n),{stdout:o,stderr:a,exitCode:c}=await
|
|
132
|
+
`).trim()||"Failed to copy to remote"}async function ri(e,t,r=4,n){try{let i=["git","annex","copy","--to",t,"-J",r.toString(),"."],s=Am(n),{stdout:o,stderr:a,exitCode:c}=await F(i,{cwd:e,env:s});if(c!==0)return{success:!1,error:wIe(o,a),filesCopied:0};let l=o.match(/^copy .+ ok$/gm);return{success:!0,filesCopied:l?l.length:0}}catch(i){return{success:!1,error:(i instanceof Error?i.message:String(i))||"Unknown error during copy",filesCopied:0}}}async function IH(e){let{stderr:t,exitCode:r}=await F(["git","fetch","--prune","--prune-tags","origin"],{cwd:e});if(r!==0)return{success:!1,error:t.trim()||"git fetch --prune-tags failed"};let{exitCode:n,stderr:i}=await F(["git","annex","unused"],{cwd:e});if(n!==0)return{success:!1,error:i.trim()||"git annex unused failed"};let{stdout:s,stderr:o,exitCode:a}=await F(["git","annex","dropunused","--force","all"],{cwd:e});if(a!==0)return{success:!1,error:o.trim()||"git annex dropunused failed"};let c=s.match(/^dropunused .+ ok$/gm);return{success:!0,dropped:c?c.length:0}}async function TH(e){let t=[],r=0,n=0,i=0,{stdout:s,exitCode:o}=await F(["find",".","(","-type","f","-o","-type","l",")","-not","-path","./.git/*","-not","-path","./.nemar/*","-not","-name",".gitattributes"],{cwd:e});if(o!==0)return{files:t,totalSize:r,dataFiles:n,metadataFiles:i};let a=s.trim().split(`
|
|
133
133
|
`).filter(Boolean);for(let c of a){let l=c.startsWith("./")?c.slice(2):c,d=gIe(e,l);try{let f=hIe(d),m=f.size;r+=m;let p=l.toLowerCase().match(/\.[^.]+$/)?.[0]||"",g=SIe.has(p)||m>EIe,y=g?"data":"metadata";if(g)n++;else i++;t.push({path:l,size:m,type:y,mtimeMs:f.mtimeMs})}catch{}}return{files:t,totalSize:r,dataFiles:n,metadataFiles:i}}function AH(e,t){let r=e.trim();if(!r)return;try{let n=JSON.parse(r),i=n.key;if(!i)return;let s=[...n.whereis||[],...n.untrusted||[]];for(let o of s){if(!Array.isArray(o.urls))continue;for(let a of o.urls)if(typeof a==="string"&&(a.startsWith("http")||a.startsWith("s3://"))){t.set(i,a);break}if(t.has(i))break}}catch(n){if(n instanceof SyntaxError)return;console.error(`Warning: failed to process whereis entry: ${n instanceof Error?n.message:String(n)}`)}}async function uD(e){let t=kH({cmd:["git","annex","whereis","--json","--","."],cwd:e,stdout:"pipe",stderr:"pipe",env:{...process.env,GIT_TERMINAL_PROMPT:"0"}}),r=new Response(t.stderr).text(),n=new Map,i=new TextDecoder,s="",o=!1,a=0;for await(let d of t.stdout){s+=i.decode(d,{stream:!0});let f=s.indexOf(`
|
|
134
134
|
`);while(f!==-1){let m=s.slice(0,f);if(s=s.slice(f+1),m.trim())o=!0,a++,AH(m,n);f=s.indexOf(`
|
|
135
|
-
`)}}if(s+=i.decode(),s.trim())o=!0,a++,AH(s,n);let c=(await r).trim(),l=await t.exited;if(l!==0&&!o)throw Error(`git annex whereis failed: ${c}`);if(l!==0){let d=c.match(/whereis:\s*(\d+)\s*failed/);if(d)console.warn(` Warning: ${d[1]} files had no location info (continuing with available files)`);else throw Error(`git annex whereis failed (exit ${l}): ${c}`)}return{urlMap:n,fileCount:a}}async function Bc(e,t){let r=await R(["git","config",`remote.${t}.annex-uuid`],{cwd:e});if(r.exitCode!==0)return null;return r.stdout.trim()||null}async function $Ie(e,t,r){return(await R(["git","annex","setpresentkey",t,r,"1"],{cwd:e})).exitCode===0}async function Im(e,t,r){let n=0,i=0,s=50;for(let o=0;o<t.length;o+=s){let a=t.slice(o,o+s),c=await Promise.all(a.map((l)=>$Ie(e,l,r)));for(let l of c)if(l)n++;else i++}return{success:n,failed:i}}var yIe=10,bIe,vIe,DIe,oD=20,EIe=102400,SIe;var qs=A(()=>{Bt();Ns();bIe=/not found|nosuchkey|no such key|does not exist/i,vIe=/access ?denied|forbidden|unauthori[sz]ed|invalid[^\n]*(key|token|credential)|expired|signaturedoesnotmatch|requesttimetooskewed|slow ?down|serviceunavailable|internalerror|throttl|could ?n[o']?t connect|connection (refused|reset|timed ?out)|network is unreachable|(?:could not |unable to )?resolve host|timed ?out/i;DIe=/fail|error|denied|forbidden|entitytoolarge|too large|multipart|exceed|timed?\s*out|not\s+enough|no\s+space|access\s+key/i;SIe=new Set([".edf",".bdf",".eeg",".vhdr",".vmrk",".set",".fdt",".cnt",".mff",".fif",".nii",".nii.gz",".mat",".bin"])});var zH={};Ti(zH,{annexKeyDeclaredSize:()=>Nm,batchServerSideCopy:()=>Lc,cleanupStaging:()=>mD,curlStreamCopy:()=>LH,expectedSizesFromItems:()=>vd,filterAlreadyCopied:()=>bd,isAccessDeniedError:()=>UH,isKeyPresentAtDeclaredSize:()=>xd,keyInShard:()=>fD,listExistingObjects:()=>js,parseS3Url:()=>dD,parseShardArg:()=>PIe,readManifestFromS3:()=>qm,serverSideS3Copy:()=>BH,writeManifestToS3:()=>pD});import{existsSync as CIe,mkdtempSync as qH,rmSync as jH,statSync as FIe,writeFileSync as RIe}from"fs";import{tmpdir as MH}from"os";import{join as Tm}from"path";function Nm(e){let t=e.match(/-s(\d+)--/);return t?Number.parseInt(t[1],10):null}function xd(e,t){let r=t.get(e);if(r===void 0)return!1;let n=Nm(e);if(n===null)return!0;return r===n}function AIe(e){let t=0,r=[];return{acquire(){if(t<e)return t++,Promise.resolve();return new Promise((n)=>r.push(n))},release(){let n=r.shift();if(n)n();else t--}}}function lD(e){try{return decodeURIComponent(e)}catch{return e}}function dD(e){if(!e)return null;if(e.startsWith("s3://")){let l=e.slice(5),d=l.indexOf("/");if(d<0)return null;let f=l.slice(0,d),m=l.slice(d+1);if(!f||!m)return null;return{bucket:f,key:lD(m)}}let t;try{t=new URL(e)}catch{return null}if(t.protocol!=="http:"&&t.protocol!=="https:")return null;let r=t.hostname;if(!r.endsWith(".amazonaws.com"))return null;let n=r.split("."),i=n.findIndex((l)=>l==="s3"||l.startsWith("s3-"));if(i===-1)return null;let s=t.pathname.replace(/^\//,"");if(i===0){let l=n.length===4?n[1]:void 0,d=s.indexOf("/");if(d<0)return null;let f=s.slice(0,d),m=s.slice(d+1);if(!f||!m)return null;return{bucket:f,key:lD(m),region:l}}let o=n.slice(0,i).join("."),a=n[i],c;if(a.startsWith("s3-"))c=a.slice(3);else if(n[i+1]&&n[i+1]!=="amazonaws")c=n[i+1];if(!o||!s)return null;return{bucket:o,key:lD(s),region:c}}async function BH(e,t,r){let n=`s3://${e.bucket}/${e.key}`,i=await R(["aws","s3","cp",n,t,"--source-region",e.region??"us-east-1","--region",r,"--only-show-errors"],{});if(i.exitCode!==0)return{success:!1,error:i.stderr.trim()||`aws exit ${i.exitCode}`};return{success:!0}}async function LH(e,t,r){let n=Nm(t);if(n!==null&&n>NH)return{success:!1,error:`declared size ${n} bytes exceeds the ${NH}-byte runner-buffered-fallback limit; needs large-disk/manual copy`};let i=qH(Tm(MH(),"nemar-curl-")),s=Tm(i,"blob");try{let o=await R(["curl","-sfL","-o",s,e],{});if(o.exitCode!==0)return{success:!1,error:o.stderr.trim()||`curl exit ${o.exitCode}`};let a=CIe(s)?FIe(s).size:0;if(a===0&&n!==0)return{success:!1,error:"curl produced an empty file (0 bytes)"};if(n!==null&&a!==n)return{success:!1,error:`downloaded ${a} bytes but the annex key declares ${n}`};let c=await R(["aws","s3","cp",s,t,"--region",r,"--only-show-errors"],{});if(c.exitCode!==0)return{success:!1,error:c.stderr.trim()||`aws exit ${c.exitCode}`};return{success:!0}}finally{jH(i,{recursive:!0,force:!0})}}function UH(e){return/Access ?Denied|\bForbidden\b|\b403\b/i.test(e)}async function Lc(e,t,r,n,i=3){let s=0,o=0,a=[],c=AIe(OIe),l=async(d)=>{let f="no S3 source";if(d.source)for(let m=1;m<=i;m++){let p=await BH(d.source,d.destUri,t);if(p.success)return"ok";if(f=p.error??"unknown server-side copy error",UH(f))break;if(m<i)await new Promise((g)=>setTimeout(g,m*m*1000))}if(d.httpUrl?.startsWith("http")){await c.acquire();try{let m=await LH(d.httpUrl,d.destUri,t);if(m.success)return d.source?"fallback":"ok";throw Error(`server-side failed (${f}); fallback failed (${m.error})`)}finally{c.release()}}throw Error(f)};for(let d=0;d<e.length;d+=r){let f=e.slice(d,d+r),m=await Promise.allSettled(f.map((p)=>l(p)));for(let p=0;p<m.length;p++){let g=m[p];if(g.status==="fulfilled"){if(s++,g.value==="fallback")o++}else a.push({key:f[p].key,error:g.reason instanceof Error?g.reason.message:String(g.reason)})}n?.(s,e.length,f[f.length-1].key)}return{copied:s,fellBack:o,failed:a}}async function js(e,t,r){let n=new Map,i=await R(["aws","s3api","list-objects-v2","--bucket",e,"--prefix",t,"--region",r,"--output","json"],{});if(i.exitCode!==0)throw Error(`list-objects-v2 failed for ${t}: ${i.stderr.trim()}`);let s=i.stdout.trim();if(!s)return n;let o;try{o=JSON.parse(s)}catch(a){throw Error(`list-objects-v2 returned unparseable JSON for ${t}: ${a instanceof Error?a.message:String(a)}`)}if(o.IsTruncated===!0||o.NextContinuationToken)throw Error(`list-objects-v2 returned a truncated page for ${t} (auto-pagination disabled?). Refusing to proceed on a partial destination view.`);for(let a of o.Contents??[]){if(typeof a.Key!=="string")continue;if(!a.Key.startsWith(t))continue;let c=a.Key.slice(t.length);if(c.length===0)continue;n.set(c,typeof a.Size==="number"?a.Size:0)}return n}function bd(e,t,r){let n=[],i=[];for(let s of e){if(!t.has(s.key)){n.push(s);continue}let o=r?.get(s.key);if(o!==void 0&&t.get(s.key)!==o)n.push(s);else i.push(s.key)}return{toCopy:n,skipped:i}}function vd(e){let t=new Map;for(let r of e){let n=Nm(r.key);if(n!==null)t.set(r.key,n)}return t}function kIe(e){let t=2166136261;for(let r=0;r<e.length;r++)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return t>>>0}function PIe(e){let t=e.match(/^(\d+)\/(\d+)$/);if(!t)throw Error(`Invalid --shard "${e}". Expected "i/N" (e.g. "0/8").`);let r=Number(t[1]),n=Number(t[2]);if(n<1)throw Error(`Invalid shard count in "${e}": N must be >= 1.`);if(r<0||r>=n)throw Error(`Invalid shard index in "${e}": i must satisfy 0 <= i < N.`);return{index:r,count:n}}function fD(e,t,r){if(r<=1)return!0;return kIe(e)%r===t}function VH(e,t){return`s3://${e}/${t}/staging/import-manifest.json`}async function IIe(e,t,r){let n=qH(Tm(MH(),"nemar-staging-")),i=Tm(n,"payload.json");try{RIe(i,JSON.stringify(e));let s=await R(["aws","s3","cp",i,t,"--region",r,"--content-type","application/json"],{});if(s.exitCode!==0)throw Error(`Failed to write ${t}: ${s.stderr.trim()}`)}finally{jH(n,{recursive:!0,force:!0})}}async function TIe(e,t){let r=await R(["aws","s3","cp",e,"-","--region",t],{});if(r.exitCode!==0)throw Error(`Failed to read ${e}: ${r.stderr.trim()}`);try{return JSON.parse(r.stdout)}catch(n){throw Error(`Failed to parse JSON from ${e} (corrupt or truncated staging object): ${n instanceof Error?n.message:String(n)}`)}}async function pD(e,t,r){await IIe(e,VH(t,e.nemarId),r)}async function qm(e,t,r){return TIe(VH(t,e),r)}async function mD(e,t,r){let n=await R(["aws","s3","rm",`s3://${t}/${e}/staging/`,"--recursive","--region",r],{});if(n.exitCode!==0)console.warn(` Staging cleanup failed (non-fatal): ${n.stderr.trim()}`)}var NH=5368709120,OIe=3;var jm=A(()=>{Bt()});var yD={};Ti(yD,{OPENNEURO_UPSTREAM_MARKER:()=>tG,coerceFunding:()=>oG,copyShard:()=>lG,decidePublicationRequestAction:()=>XH,decideReimportMainReset:()=>QH,decideSkipCiCheck:()=>YH,detectModalitiesFromDataset:()=>sG,ensureReadmeMd:()=>cG,ensureRootMetadataUnannexed:()=>nG,finalizeImport:()=>dG,findAnnexedRootMetadata:()=>eG,importOpenNeuro:()=>WIe,isAlreadyExistsImportError:()=>JH,isNeverAnnexedMetadata:()=>ZH,openNeuroCurrentUrl:()=>rG,prepareImport:()=>uG,seedMetadata:()=>aG,waitForBidsValidationRun:()=>Mm});import{existsSync as GH,mkdirSync as NIe,mkdtempSync as WH,readFileSync as qIe,readdirSync as _d,readlinkSync as jIe,renameSync as MIe,rmSync as BIe,writeFileSync as hD}from"fs";import{tmpdir as KH}from"os";import{join as xr}from"path";async function Mm(e,t,r=120000,n=5000){let i=Date.now()+r,s,o=!1;while(Date.now()<i){try{let c=await _m(e);if(o=!0,c.bids_validation.present&&c.bids_validation.status!=="no_runs")return{kind:"found"}}catch(c){s=c}let a=Math.max(0,i-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(n,a)))}if(!o&&s!==void 0)return{kind:"error",lastError:s};return{kind:"timeout"}}function YH(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 JH(e){return e.includes("already exists")||e.includes("409")}function XH(e){return e==="public"?"skip-already-published":"request"}function QH(e){return e.originMainSha!==null&&e.originMainSha!==""&&e.currentBranch==="main"}function gD(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]}`}function ZH(e){let t=e.toLowerCase();if(t.startsWith("readme")||t.startsWith("license")||t.startsWith("changes"))return!0;if(t===".bidsignore"||t===".gitignore")return!0;return/\.(tsv|json|md|txt|yml|yaml)$/.test(t)}function eG(e){let t;try{t=_d(e,{withFileTypes:!0})}catch(n){let i=n.code;if(i==="ENOENT"||i==="ENOTDIR")return[];throw Error(`Cannot scan ${e} for annexed metadata: ${n instanceof Error?n.message:String(n)}`)}let r=[];for(let n of t){if(!n.isSymbolicLink())continue;if(!ZH(n.name))continue;try{if(jIe(xr(e,n.name)).includes("annex/objects"))r.push(n.name)}catch{}}return r.sort()}function rG(e,t){let r=t.split("/").map(encodeURIComponent).join("/");return`https://s3.amazonaws.com/openneuro.org/${e}/${r}`}async function nG(e,t){let r=eG(e);if(r.length===0)return[];let n=[];for(let s of r){let o=rG(t,s),a;try{let l=await fetch(o);if(!l.ok){n.push(`${s} (HTTP ${l.status})`);continue}a=Buffer.from(await l.arrayBuffer())}catch(l){n.push(`${s} (fetch failed: ${l instanceof Error?l.message:String(l)})`);continue}if(a.length===0){n.push(`${s} (HTTP 200 but empty body)`);continue}let c=xr(e,s);try{BIe(c,{force:!0}),hD(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(n.length>0)throw Error(`${tG} cannot fetch metadata from OpenNeuro: ${n.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 i=await R(["git","-c","annex.largefiles=nothing","add",...r],{cwd:e});if(i.exitCode!==0)throw Error(`Failed to stage un-annexed metadata (${r.join(", ")}): ${i.stderr.trim()}. The files are already regular files on disk; recover with: git -C ${e} -c annex.largefiles=nothing add ${r.join(" ")}`);return r}function VIe(e){let t=xr(e,"dataset_description.json");if(!GH(t))throw Error(`dataset_description.json not found at ${t}`);try{return JSON.parse(qIe(t,"utf-8"))}catch(r){throw Error(`Failed to parse dataset_description.json at ${t}: ${r instanceof Error?r.message:String(r)}`)}}function iG(){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 zIe(e){return typeof e.DatasetDOI==="string"?e.DatasetDOI.replace(/^doi:/,""):null}function sG(e){let t=new Set,r=[];try{r=_d(e,{withFileTypes:!0}).filter((n)=>n.isDirectory()&&n.name.startsWith("sub-")).map((n)=>n.name)}catch{return[]}for(let n of r){let i=xr(e,n),s=[];try{s=_d(i,{withFileTypes:!0})}catch{continue}for(let o of s){if(!o.isDirectory())continue;if(o.name.startsWith("ses-")){let a=[];try{a=_d(xr(i,o.name),{withFileTypes:!0})}catch{continue}for(let c of a)if(c.isDirectory()&&HH.includes(c.name))t.add(c.name)}else if(HH.includes(o.name))t.add(o.name)}}return[...t].sort()}function oG(e){let t=e.Funding;if(!Array.isArray(t))return[];return t.filter((r)=>typeof r==="string"&&r.trim().length>0).map((r)=>({funder_name:r.trim()}))}function aG(e,t,r,n,i){let s=xr(e,".nemar");if(!GH(s))NIe(s,{recursive:!0});let o=i?[{identifier:i,identifier_type:"DOI",relation_type:"IsIdenticalTo"}]:[],a=sG(e),c=oG(n),l={version:"2.0",dataset_id:t,source:"openneuro",source_id:r,title:n.Name||t,authors:Array.isArray(n.Authors)?Object.fromEntries(n.Authors.map((d)=>[d,{}])):{},license:n.License||"CC0",dataset_type:n.DatasetType||"raw",related_identifiers:o,pipeline_stage:"seeded"};if(typeof n.BIDSVersion==="string")l.bids_version=n.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 n.Acknowledgements==="string"&&n.Acknowledgements.trim().length>0)l.acknowledgements=n.Acknowledgements.trim();hD(xr(s,"metadata.json"),`${JSON.stringify(l,null,2)}
|
|
135
|
+
`)}}if(s+=i.decode(),s.trim())o=!0,a++,AH(s,n);let c=(await r).trim(),l=await t.exited;if(l!==0&&!o)throw Error(`git annex whereis failed: ${c}`);if(l!==0){let d=c.match(/whereis:\s*(\d+)\s*failed/);if(d)console.warn(` Warning: ${d[1]} files had no location info (continuing with available files)`);else throw Error(`git annex whereis failed (exit ${l}): ${c}`)}return{urlMap:n,fileCount:a}}async function Bc(e,t){let r=await F(["git","config",`remote.${t}.annex-uuid`],{cwd:e});if(r.exitCode!==0)return null;return r.stdout.trim()||null}async function $Ie(e,t,r){return(await F(["git","annex","setpresentkey",t,r,"1"],{cwd:e})).exitCode===0}async function Im(e,t,r){let n=0,i=0,s=50;for(let o=0;o<t.length;o+=s){let a=t.slice(o,o+s),c=await Promise.all(a.map((l)=>$Ie(e,l,r)));for(let l of c)if(l)n++;else i++}return{success:n,failed:i}}var yIe=10,bIe,vIe,DIe,oD=20,EIe=102400,SIe;var qs=A(()=>{Bt();Ns();bIe=/not found|nosuchkey|no such key|does not exist/i,vIe=/access ?denied|forbidden|unauthori[sz]ed|invalid[^\n]*(key|token|credential)|expired|signaturedoesnotmatch|requesttimetooskewed|slow ?down|serviceunavailable|internalerror|throttl|could ?n[o']?t connect|connection (refused|reset|timed ?out)|network is unreachable|(?:could not |unable to )?resolve host|timed ?out/i;DIe=/fail|error|denied|forbidden|entitytoolarge|too large|multipart|exceed|timed?\s*out|not\s+enough|no\s+space|access\s+key/i;SIe=new Set([".edf",".bdf",".eeg",".vhdr",".vmrk",".set",".fdt",".cnt",".mff",".fif",".nii",".nii.gz",".mat",".bin"])});var zH={};Ti(zH,{annexKeyDeclaredSize:()=>Nm,batchServerSideCopy:()=>Lc,cleanupStaging:()=>mD,curlStreamCopy:()=>LH,expectedSizesFromItems:()=>vd,filterAlreadyCopied:()=>bd,isAccessDeniedError:()=>UH,isKeyPresentAtDeclaredSize:()=>xd,keyInShard:()=>fD,listExistingObjects:()=>js,parseS3Url:()=>dD,parseShardArg:()=>PIe,readManifestFromS3:()=>qm,serverSideS3Copy:()=>BH,writeManifestToS3:()=>pD});import{existsSync as CIe,mkdtempSync as qH,rmSync as jH,statSync as FIe,writeFileSync as RIe}from"fs";import{tmpdir as MH}from"os";import{join as Tm}from"path";function Nm(e){let t=e.match(/-s(\d+)--/);return t?Number.parseInt(t[1],10):null}function xd(e,t){let r=t.get(e);if(r===void 0)return!1;let n=Nm(e);if(n===null)return!0;return r===n}function AIe(e){let t=0,r=[];return{acquire(){if(t<e)return t++,Promise.resolve();return new Promise((n)=>r.push(n))},release(){let n=r.shift();if(n)n();else t--}}}function lD(e){try{return decodeURIComponent(e)}catch{return e}}function dD(e){if(!e)return null;if(e.startsWith("s3://")){let l=e.slice(5),d=l.indexOf("/");if(d<0)return null;let f=l.slice(0,d),m=l.slice(d+1);if(!f||!m)return null;return{bucket:f,key:lD(m)}}let t;try{t=new URL(e)}catch{return null}if(t.protocol!=="http:"&&t.protocol!=="https:")return null;let r=t.hostname;if(!r.endsWith(".amazonaws.com"))return null;let n=r.split("."),i=n.findIndex((l)=>l==="s3"||l.startsWith("s3-"));if(i===-1)return null;let s=t.pathname.replace(/^\//,"");if(i===0){let l=n.length===4?n[1]:void 0,d=s.indexOf("/");if(d<0)return null;let f=s.slice(0,d),m=s.slice(d+1);if(!f||!m)return null;return{bucket:f,key:lD(m),region:l}}let o=n.slice(0,i).join("."),a=n[i],c;if(a.startsWith("s3-"))c=a.slice(3);else if(n[i+1]&&n[i+1]!=="amazonaws")c=n[i+1];if(!o||!s)return null;return{bucket:o,key:lD(s),region:c}}async function BH(e,t,r){let n=`s3://${e.bucket}/${e.key}`,i=await F(["aws","s3","cp",n,t,"--source-region",e.region??"us-east-1","--region",r,"--only-show-errors"],{});if(i.exitCode!==0)return{success:!1,error:i.stderr.trim()||`aws exit ${i.exitCode}`};return{success:!0}}async function LH(e,t,r){let n=Nm(t);if(n!==null&&n>NH)return{success:!1,error:`declared size ${n} bytes exceeds the ${NH}-byte runner-buffered-fallback limit; needs large-disk/manual copy`};let i=qH(Tm(MH(),"nemar-curl-")),s=Tm(i,"blob");try{let o=await F(["curl","-sfL","-o",s,e],{});if(o.exitCode!==0)return{success:!1,error:o.stderr.trim()||`curl exit ${o.exitCode}`};let a=CIe(s)?FIe(s).size:0;if(a===0&&n!==0)return{success:!1,error:"curl produced an empty file (0 bytes)"};if(n!==null&&a!==n)return{success:!1,error:`downloaded ${a} bytes but the annex key declares ${n}`};let c=await F(["aws","s3","cp",s,t,"--region",r,"--only-show-errors"],{});if(c.exitCode!==0)return{success:!1,error:c.stderr.trim()||`aws exit ${c.exitCode}`};return{success:!0}}finally{jH(i,{recursive:!0,force:!0})}}function UH(e){return/Access ?Denied|\bForbidden\b|\b403\b/i.test(e)}async function Lc(e,t,r,n,i=3){let s=0,o=0,a=[],c=AIe(OIe),l=async(d)=>{let f="no S3 source";if(d.source)for(let m=1;m<=i;m++){let p=await BH(d.source,d.destUri,t);if(p.success)return"ok";if(f=p.error??"unknown server-side copy error",UH(f))break;if(m<i)await new Promise((g)=>setTimeout(g,m*m*1000))}if(d.httpUrl?.startsWith("http")){await c.acquire();try{let m=await LH(d.httpUrl,d.destUri,t);if(m.success)return d.source?"fallback":"ok";throw Error(`server-side failed (${f}); fallback failed (${m.error})`)}finally{c.release()}}throw Error(f)};for(let d=0;d<e.length;d+=r){let f=e.slice(d,d+r),m=await Promise.allSettled(f.map((p)=>l(p)));for(let p=0;p<m.length;p++){let g=m[p];if(g.status==="fulfilled"){if(s++,g.value==="fallback")o++}else a.push({key:f[p].key,error:g.reason instanceof Error?g.reason.message:String(g.reason)})}n?.(s,e.length,f[f.length-1].key)}return{copied:s,fellBack:o,failed:a}}async function js(e,t,r){let n=new Map,i=await F(["aws","s3api","list-objects-v2","--bucket",e,"--prefix",t,"--region",r,"--output","json"],{});if(i.exitCode!==0)throw Error(`list-objects-v2 failed for ${t}: ${i.stderr.trim()}`);let s=i.stdout.trim();if(!s)return n;let o;try{o=JSON.parse(s)}catch(a){throw Error(`list-objects-v2 returned unparseable JSON for ${t}: ${a instanceof Error?a.message:String(a)}`)}if(o.IsTruncated===!0||o.NextContinuationToken)throw Error(`list-objects-v2 returned a truncated page for ${t} (auto-pagination disabled?). Refusing to proceed on a partial destination view.`);for(let a of o.Contents??[]){if(typeof a.Key!=="string")continue;if(!a.Key.startsWith(t))continue;let c=a.Key.slice(t.length);if(c.length===0)continue;n.set(c,typeof a.Size==="number"?a.Size:0)}return n}function bd(e,t,r){let n=[],i=[];for(let s of e){if(!t.has(s.key)){n.push(s);continue}let o=r?.get(s.key);if(o!==void 0&&t.get(s.key)!==o)n.push(s);else i.push(s.key)}return{toCopy:n,skipped:i}}function vd(e){let t=new Map;for(let r of e){let n=Nm(r.key);if(n!==null)t.set(r.key,n)}return t}function kIe(e){let t=2166136261;for(let r=0;r<e.length;r++)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return t>>>0}function PIe(e){let t=e.match(/^(\d+)\/(\d+)$/);if(!t)throw Error(`Invalid --shard "${e}". Expected "i/N" (e.g. "0/8").`);let r=Number(t[1]),n=Number(t[2]);if(n<1)throw Error(`Invalid shard count in "${e}": N must be >= 1.`);if(r<0||r>=n)throw Error(`Invalid shard index in "${e}": i must satisfy 0 <= i < N.`);return{index:r,count:n}}function fD(e,t,r){if(r<=1)return!0;return kIe(e)%r===t}function VH(e,t){return`s3://${e}/${t}/staging/import-manifest.json`}async function IIe(e,t,r){let n=qH(Tm(MH(),"nemar-staging-")),i=Tm(n,"payload.json");try{RIe(i,JSON.stringify(e));let s=await F(["aws","s3","cp",i,t,"--region",r,"--content-type","application/json"],{});if(s.exitCode!==0)throw Error(`Failed to write ${t}: ${s.stderr.trim()}`)}finally{jH(n,{recursive:!0,force:!0})}}async function TIe(e,t){let r=await F(["aws","s3","cp",e,"-","--region",t],{});if(r.exitCode!==0)throw Error(`Failed to read ${e}: ${r.stderr.trim()}`);try{return JSON.parse(r.stdout)}catch(n){throw Error(`Failed to parse JSON from ${e} (corrupt or truncated staging object): ${n instanceof Error?n.message:String(n)}`)}}async function pD(e,t,r){await IIe(e,VH(t,e.nemarId),r)}async function qm(e,t,r){return TIe(VH(t,e),r)}async function mD(e,t,r){let n=await F(["aws","s3","rm",`s3://${t}/${e}/staging/`,"--recursive","--region",r],{});if(n.exitCode!==0)console.warn(` Staging cleanup failed (non-fatal): ${n.stderr.trim()}`)}var NH=5368709120,OIe=3;var jm=A(()=>{Bt()});var yD={};Ti(yD,{OPENNEURO_UPSTREAM_MARKER:()=>tG,coerceFunding:()=>oG,copyShard:()=>lG,decidePublicationRequestAction:()=>XH,decideReimportMainReset:()=>QH,decideSkipCiCheck:()=>YH,detectModalitiesFromDataset:()=>sG,ensureReadmeMd:()=>cG,ensureRootMetadataUnannexed:()=>nG,finalizeImport:()=>dG,findAnnexedRootMetadata:()=>eG,importOpenNeuro:()=>WIe,isAlreadyExistsImportError:()=>JH,isNeverAnnexedMetadata:()=>ZH,openNeuroCurrentUrl:()=>rG,prepareImport:()=>uG,seedMetadata:()=>aG,waitForBidsValidationRun:()=>Mm});import{existsSync as GH,mkdirSync as NIe,mkdtempSync as WH,readFileSync as qIe,readdirSync as _d,readlinkSync as jIe,renameSync as MIe,rmSync as BIe,writeFileSync as hD}from"fs";import{tmpdir as KH}from"os";import{join as xr}from"path";async function Mm(e,t,r=120000,n=5000){let i=Date.now()+r,s,o=!1;while(Date.now()<i){try{let c=await _m(e);if(o=!0,c.bids_validation.present&&c.bids_validation.status!=="no_runs")return{kind:"found"}}catch(c){s=c}let a=Math.max(0,i-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(n,a)))}if(!o&&s!==void 0)return{kind:"error",lastError:s};return{kind:"timeout"}}function YH(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 JH(e){return e.includes("already exists")||e.includes("409")}function XH(e){return e==="public"?"skip-already-published":"request"}function QH(e){return e.originMainSha!==null&&e.originMainSha!==""&&e.currentBranch==="main"}function gD(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]}`}function ZH(e){let t=e.toLowerCase();if(t.startsWith("readme")||t.startsWith("license")||t.startsWith("changes"))return!0;if(t===".bidsignore"||t===".gitignore")return!0;return/\.(tsv|json|md|txt|yml|yaml)$/.test(t)}function eG(e){let t;try{t=_d(e,{withFileTypes:!0})}catch(n){let i=n.code;if(i==="ENOENT"||i==="ENOTDIR")return[];throw Error(`Cannot scan ${e} for annexed metadata: ${n instanceof Error?n.message:String(n)}`)}let r=[];for(let n of t){if(!n.isSymbolicLink())continue;if(!ZH(n.name))continue;try{if(jIe(xr(e,n.name)).includes("annex/objects"))r.push(n.name)}catch{}}return r.sort()}function rG(e,t){let r=t.split("/").map(encodeURIComponent).join("/");return`https://s3.amazonaws.com/openneuro.org/${e}/${r}`}async function nG(e,t){let r=eG(e);if(r.length===0)return[];let n=[];for(let s of r){let o=rG(t,s),a;try{let l=await fetch(o);if(!l.ok){n.push(`${s} (HTTP ${l.status})`);continue}a=Buffer.from(await l.arrayBuffer())}catch(l){n.push(`${s} (fetch failed: ${l instanceof Error?l.message:String(l)})`);continue}if(a.length===0){n.push(`${s} (HTTP 200 but empty body)`);continue}let c=xr(e,s);try{BIe(c,{force:!0}),hD(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(n.length>0)throw Error(`${tG} cannot fetch metadata from OpenNeuro: ${n.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 i=await F(["git","-c","annex.largefiles=nothing","add",...r],{cwd:e});if(i.exitCode!==0)throw Error(`Failed to stage un-annexed metadata (${r.join(", ")}): ${i.stderr.trim()}. The files are already regular files on disk; recover with: git -C ${e} -c annex.largefiles=nothing add ${r.join(" ")}`);return r}function VIe(e){let t=xr(e,"dataset_description.json");if(!GH(t))throw Error(`dataset_description.json not found at ${t}`);try{return JSON.parse(qIe(t,"utf-8"))}catch(r){throw Error(`Failed to parse dataset_description.json at ${t}: ${r instanceof Error?r.message:String(r)}`)}}function iG(){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 zIe(e){return typeof e.DatasetDOI==="string"?e.DatasetDOI.replace(/^doi:/,""):null}function sG(e){let t=new Set,r=[];try{r=_d(e,{withFileTypes:!0}).filter((n)=>n.isDirectory()&&n.name.startsWith("sub-")).map((n)=>n.name)}catch{return[]}for(let n of r){let i=xr(e,n),s=[];try{s=_d(i,{withFileTypes:!0})}catch{continue}for(let o of s){if(!o.isDirectory())continue;if(o.name.startsWith("ses-")){let a=[];try{a=_d(xr(i,o.name),{withFileTypes:!0})}catch{continue}for(let c of a)if(c.isDirectory()&&HH.includes(c.name))t.add(c.name)}else if(HH.includes(o.name))t.add(o.name)}}return[...t].sort()}function oG(e){let t=e.Funding;if(!Array.isArray(t))return[];return t.filter((r)=>typeof r==="string"&&r.trim().length>0).map((r)=>({funder_name:r.trim()}))}function aG(e,t,r,n,i){let s=xr(e,".nemar");if(!GH(s))NIe(s,{recursive:!0});let o=i?[{identifier:i,identifier_type:"DOI",relation_type:"IsIdenticalTo"}]:[],a=sG(e),c=oG(n),l={version:"2.0",dataset_id:t,source:"openneuro",source_id:r,title:n.Name||t,authors:Array.isArray(n.Authors)?Object.fromEntries(n.Authors.map((d)=>[d,{}])):{},license:n.License||"CC0",dataset_type:n.DatasetType||"raw",related_identifiers:o,pipeline_stage:"seeded"};if(typeof n.BIDSVersion==="string")l.bids_version=n.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 n.Acknowledgements==="string"&&n.Acknowledgements.trim().length>0)l.acknowledgements=n.Acknowledgements.trim();hD(xr(s,"metadata.json"),`${JSON.stringify(l,null,2)}
|
|
136
136
|
`)}function cG(e,t,r){let i=_d(e,{withFileTypes:!0}).filter((f)=>f.isFile()&&HIe.test(f.name)),s=i.find((f)=>f.name.includes("."));if(s)return{kind:"kept",path:s.name};let o=i.find((f)=>!f.name.includes("."));if(o)return MIe(xr(e,o.name),xr(e,"README.md")),{kind:"renamed",from:"README",to:"README.md"};let a="<!-- nemar:provenance -->",c=`https://openneuro.org/datasets/${t}`,l=r?`
|
|
137
137
|
- DOI: [${r}](https://doi.org/${r})`:"",d=`${a}
|
|
138
138
|
## Provenance
|
|
@@ -142,16 +142,16 @@ This dataset is mirrored on NEMAR from OpenNeuro.
|
|
|
142
142
|
- Source: [${t}](${c})${l}
|
|
143
143
|
`;return hD(xr(e,"README.md"),d),{kind:"created",path:"README.md"}}function GIe(e,t){let r=[],n=0;for(let[i,s]of e){let o=dD(s),a=s.startsWith("http")?s:null;if(!o&&!a){n++;continue}r.push({key:i,sourceUrl:a,source:o,destUri:`s3://${ni}/${t}/objects/${i}`})}return{items:r,skipped:n}}async function uG(e,t={}){let r=gD(e),n=t.workDir||WH(xr(KH(),`nemar-import-${r}-`)),i=xr(n,r);console.log(u.cyan(`
|
|
144
144
|
[prepare] ${e} -> ${r}
|
|
145
|
-
`)),console.log(u.dim(`Working directory: ${n}`));let s=w("Cloning OpenNeuro dataset...").start(),o=`https://github.com/${LIe}/${e}.git`,a=await yr(o,i);if(!a.success)s.fail(`Failed to clone: ${a.error}`),process.exit(1);if(s.succeed(`Cloned ${e}`),!await Cm(i,{yes:!0}))console.error(u.red("Cannot proceed with import: branch must be named 'main'.")),process.exit(1);let l=w("Normalizing dataset metadata...").start();try{let H=await nG(i,e);if(H.length>0)l.succeed(`Un-annexed ${H.length} metadata file(s): ${H.join(", ")}`);else l.stop()}catch(H){l.fail(`Failed to normalize annexed metadata: ${H instanceof Error?H.message:String(H)}`),process.exit(1)}let d=VIe(i),f=d.Name||e,m=zIe(d);if(console.log(u.dim(` Dataset: ${f}`)),m)console.log(u.dim(` OpenNeuro DOI: ${m}`));let p=w("Creating NEMAR dataset record...").start();try{let H=await oz({dataset_id:r,name:f,source:"openneuro",source_id:e});p.succeed(`Created ${H.dataset_id} (${H.github_repo})`)}catch(H){let Me=H instanceof Error?H.message:String(H);if(JH(Me))p.warn(`Dataset ${r} already exists, continuing...`);else p.fail(`Failed to create dataset: ${Me}`),process.exit(1)}let g=new Map;if(!t.skipData){let H=w("Mapping annexed files from OpenNeuro S3...").start(),Me=await
|
|
145
|
+
`)),console.log(u.dim(`Working directory: ${n}`));let s=w("Cloning OpenNeuro dataset...").start(),o=`https://github.com/${LIe}/${e}.git`,a=await yr(o,i);if(!a.success)s.fail(`Failed to clone: ${a.error}`),process.exit(1);if(s.succeed(`Cloned ${e}`),!await Cm(i,{yes:!0}))console.error(u.red("Cannot proceed with import: branch must be named 'main'.")),process.exit(1);let l=w("Normalizing dataset metadata...").start();try{let H=await nG(i,e);if(H.length>0)l.succeed(`Un-annexed ${H.length} metadata file(s): ${H.join(", ")}`);else l.stop()}catch(H){l.fail(`Failed to normalize annexed metadata: ${H instanceof Error?H.message:String(H)}`),process.exit(1)}let d=VIe(i),f=d.Name||e,m=zIe(d);if(console.log(u.dim(` Dataset: ${f}`)),m)console.log(u.dim(` OpenNeuro DOI: ${m}`));let p=w("Creating NEMAR dataset record...").start();try{let H=await oz({dataset_id:r,name:f,source:"openneuro",source_id:e});p.succeed(`Created ${H.dataset_id} (${H.github_repo})`)}catch(H){let Me=H instanceof Error?H.message:String(H);if(JH(Me))p.warn(`Dataset ${r} already exists, continuing...`);else p.fail(`Failed to create dataset: ${Me}`),process.exit(1)}let g=new Map;if(!t.skipData){let H=w("Mapping annexed files from OpenNeuro S3...").start(),Me=await F(["git","annex","enableremote","s3-PUBLIC"],{cwd:i});if(Me.exitCode!==0)H.fail(`Failed to enable s3-PUBLIC remote: ${Me.stderr.trim()}`),process.exit(1);let ot=await uD(i);if(g=ot.urlMap,g.size===0){if(ot.fileCount>0)throw H.fail(`${ot.fileCount} annexed file(s) present but none had a copyable source URL`),Error(`Import aborted: ${r} has ${ot.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.`);H.warn("No annexed files found, skipping data copy")}else H.succeed(`Found ${g.size} annexed files`)}await Pm(i,(H,Me)=>{console.log(u.yellow(` Warning: could not mark ${H} as annex-ignore (${Me}). Future pushes may try to upload to ${H}; run 'git config remote.${H}.annex-ignore true' manually.`))});let y=w("Configuring NEMAR remote...").start(),x=await F(["git","remote","remove","origin"],{cwd:i});if(x.exitCode!==0&&!x.stderr.includes("No such remote"))y.fail(`Failed to remove OpenNeuro remote: ${x.stderr.trim()}`),process.exit(1);let v=`git@github.com:nemarDatasets/${r}.git`,_=await ei(i,v,"origin");if(!_.success)y.fail(`Failed to configure remote: ${_.error}`),process.exit(1);if(y.succeed("Configured NEMAR remote"),(await F(["git","fetch","origin","git-annex"],{cwd:i})).exitCode===0){let H=await F(["git","annex","merge"],{cwd:i});if(H.exitCode!==0)console.log(u.yellow(` Warning: found existing NEMAR git-annex state for ${r} but could not merge it (${H.stderr.trim()}). A retry may register the S3 remote under a new UUID; investigate before re-running finalize.`))}if((await F(["git","fetch","origin","main"],{cwd:i})).exitCode===0){let H=await F(["git","rev-parse","--verify","--quiet","origin/main"],{cwd:i}),Me=await F(["git","rev-parse","--abbrev-ref","HEAD"],{cwd:i});if(QH({originMainSha:H.stdout.trim()||null,currentBranch:Me.stdout.trim()})){let tr=await F(["git","reset","--hard","origin/main"],{cwd:i});if(tr.exitCode!==0)console.log(u.yellow(` Warning: found origin/main for ${r} (re-import) but could not reset onto it (${tr.stderr.trim()}). Falling back to the normal push path.`));else console.log(u.dim(" Re-import: based main on origin/main for an idempotent metadata commit"))}}let D="",O=[];if(!t.skipData&&g.size>0){let H=w("Setting up NEMAR S3 remote...").start(),Me=iG(),ot=await $r(i,{name:"nemar-s3",bucket:ni,prefix:`${r}/objects`,region:ki},Me);if(!ot.success)H.fail(`Failed to configure S3 remote: ${ot.error}`),process.exit(1);let tr=await Bc(i,"nemar-s3");if(!tr)H.fail("Failed to get NEMAR S3 remote UUID"),process.exit(1);D=tr,H.succeed("Configured NEMAR S3 remote");let yt=GIe(g,r);if(O=yt.items,yt.skipped>0)console.log(u.yellow(` Skipped ${yt.skipped} keys (no usable source URL)`));console.log(u.dim(` Prepared ${O.length} files for server-side copy`))}let C=w("Seeding metadata...").start(),j;try{aG(i,r,e,d,m),j=cG(i,e,m)}catch(H){C.fail(`Failed to seed metadata: ${H instanceof Error?H.message:String(H)}`),process.exit(1)}let k=[".nemar/metadata.json"];if(j.kind==="renamed")k.push("README","README.md");else if(j.kind==="created")k.push("README.md");let q=await F(["git","add",...k],{cwd:i});if(q.exitCode!==0)C.fail(`Failed to stage metadata: ${q.stderr.trim()}`),process.exit(1);let Z=await F(["git","commit","-m",`Add NEMAR metadata (imported from OpenNeuro ${e})`],{cwd:i});if(Z.exitCode!==0&&!Z.stdout.includes("nothing to commit"))C.fail(`Failed to commit metadata: ${Z.stderr.trim()}`),process.exit(1);let ve=j.kind==="renamed"?"renamed README -> README.md":j.kind==="kept"?`kept upstream ${j.path}`:"wrote provenance stub README.md (no upstream README)";C.succeed(`Seeded .nemar/metadata.json (${ve})`);let Ne=w("Pushing to nemarDatasets...").start(),je=await Qt(i,"origin");if(!je.success)Ne.fail(`Failed to push: ${je.error}`),process.exit(1);if(je.warning)Ne.fail(`Pushed main but git-annex branch failed: ${je.warning}. Aborting \u2014 published dataset would be uncloneable. Investigate the git-annex push failure and re-run.`),process.exit(1);Ne.succeed("Pushed to nemarDatasets");let T={openneuroId:e,nemarId:r,nemarUuid:D,items:O};if(t.persistStaging)await pD(T,ni,ki),console.log(u.dim(` Wrote import manifest to s3://${ni}/${r}/staging/`));return console.log(u.green(`[prepare] done: ${r} (${O.length} files to copy)`)),T}async function lG(e,t,r={},n){let i=gD(e),s=n??await qm(i,ni,ki),o=`copy ${t.index}/${t.count}`;if(r.skipData||s.items.length===0){console.log(u.dim(`[${o}] no data to copy`));return}let a=s.items.filter((p)=>fD(p.key,t.index,t.count)).map((p)=>({key:p.key,source:p.source,httpUrl:p.sourceUrl,destUri:p.destUri}));if(a.length===0){console.log(u.dim(`[${o}] empty shard`));return}let c=await js(ni,`${i}/objects/`,ki),{toCopy:l,skipped:d}=bd(a,c,vd(a));if(d.length>0)console.log(u.dim(`[${o}] skipped ${d.length} already present`));if(l.length===0){console.log(u.green(`[${o}] nothing to copy (all ${d.length} present)`));return}let f=w(`[${o}] copying ${l.length} files...`).start(),m=await Lc(l,ki,UIe,(p,g)=>{f.text=`[${o}] ${p}/${g}`});if(m.fellBack>0)console.log(u.yellow(` ${m.fellBack} objects needed the curl fallback (check S3 permissions)`));if(m.failed.length>0){f.fail(`[${o}] ${m.failed.length} of ${l.length} files failed`);for(let p of m.failed.slice(0,5))console.error(u.red(` ${p.key}: ${p.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)}f.succeed(`[${o}] copied ${m.copied}, skipped ${d.length}`)}async function dG(e,t={},r){let n=gD(e),i=r??await qm(n,ni,ki),s=t.workDir||WH(xr(KH(),`nemar-finalize-${n}-`)),o=xr(s,`${n}-finalize`);console.log(u.cyan(`
|
|
146
146
|
[finalize] ${e} -> ${n}
|
|
147
147
|
`));let a=!t.skipData&&i.items.length>0;if(!t.skipData&&i.items.length===0){let C=w("Confirming dataset has no annexed data...").start(),j=await yr(`git@github.com:nemarDatasets/${n}.git`,o,{useGitHubToken:!0});if(!j.success)C.fail(`Failed to clone ${n} for the empty-manifest check: ${j.error}`),process.exit(1);let{fileCount:k}=await uD(o);if(k>0)throw C.fail(`${k} annexed file(s) but the import manifest is empty`),Error(`Finalize aborted: ${n} has ${k} 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.`);C.succeed("Confirmed metadata-only dataset (no annexed data)")}if(a){let C=w("Verifying copied data...").start(),j=await js(ni,`${n}/objects/`,ki),k=i.items.filter((yt)=>!xd(yt.key,j));if(k.length>0)C.fail(`${k.length} of ${i.items.length} objects missing or wrong size at the destination. Re-run the copy phase (a shard likely failed or was cancelled) before finalizing.`),process.exit(1);C.succeed(`Verified ${i.items.length} objects present`);let q=w("Re-cloning for git-annex finalize...").start(),Z=await yr(`git@github.com:nemarDatasets/${n}.git`,o,{useGitHubToken:!0});if(!Z.success)q.fail(`Failed to clone ${n}: ${Z.error}`),process.exit(1);q.succeed(`Cloned ${n}`);let ve=iG(),Ne=await $r(o,{name:"nemar-s3",bucket:ni,prefix:`${n}/objects`,region:ki},ve);if(!Ne.success)console.error(u.red(`Failed to enable S3 remote: ${Ne.error}`)),process.exit(1);let je=await Bc(o,"nemar-s3");if(!je)console.error(u.red("Failed to get NEMAR S3 remote UUID on finalize clone")),process.exit(1);if(i.nemarUuid&&je!==i.nemarUuid)console.error(u.red(`nemar-s3 uuid mismatch (prepare=${i.nemarUuid} finalize=${je}). Aborting to avoid registering keys against the wrong remote.`)),process.exit(1);let T=w("Registering files in git-annex...").start(),H=i.items.map((yt)=>yt.key),Me=await Im(o,H,je);if(Me.failed>0)T.fail(`${Me.failed} of ${H.length} git-annex key registrations failed. Aborting before publish \u2014 those blobs would be unfindable for clones. Re-run finalize to retry.`),process.exit(1);T.succeed(`Registered ${Me.success} files in git-annex`);let ot=w("Pushing git-annex branch...").start(),tr=await Qt(o,"origin");if(!tr.success)ot.fail(`Failed to push git-annex branch: ${tr.error}`),process.exit(1);if(tr.warning)ot.fail(`git-annex branch push failed: ${tr.warning}. Aborting \u2014 published dataset would be uncloneable.`),process.exit(1);ot.succeed("Pushed git-annex branch")}let c=!1,l=w("Deploying CI workflows...").start();try{await Ri(n),l.succeed("CI workflows deployed (BIDS validation, LLM enrichment, archive generation)"),c=!0}catch(C){let j=C instanceof Error?C.message:String(C);l.fail(`CI deployment failed: ${j}`),console.log(u.dim(` After fixing the deploy failure, run 'nemar admin ci add ${n}' and 'nemar admin publish request/approve ${n}' to resume.`))}let d=null;if(c){let C=w("Waiting for BIDS validation run to register...").start();if(d=await Mm(n,C),d.kind==="found")C.succeed("BIDS validation run registered; deferring to ci_check at approval");else if(d.kind==="timeout"){let j=t.trustUpstream?"trusting upstream OpenNeuro validation (--trust-upstream)":"no --trust-upstream \u2014 aborting";C.warn(`BIDS validation run did not register within 120s; ${j}`)}else{let j=d.lastError instanceof Error?d.lastError.message:String(d.lastError);C.fail(`All BIDS validation polls failed (last error: ${j})`)}}let f=YH({ciDeployed:c,poll:d,trustUpstream:t.trustUpstream??!1});if(f.abortReason)console.error(u.red(f.abortReason)),process.exit(1);let m=f.skipCiCheck,p=null;try{p=(await gt(n)).visibility}catch{}let g=p!==null&&XH(p)==="skip-already-published",y=5,x=300000,v=w("Requesting publication...").start(),_=!1;if(g)_=!0,v.succeed(`${n} is already published; skipping publish/request (data re-copy only)`);for(let C=1;!g&&C<=y;C++)try{await Nc(n),_=!0;break}catch(j){let k=j instanceof Error?j.message:String(j);if(k==="Dataset is already published"){g=!0,_=!0,v.succeed(`${n} is already published; skipping publish/request (data re-copy only)`);break}if(!k.includes("BIDS validation is currently running"))v.fail(`Failed to request publication: ${k}`),process.exit(1);if(C===y)v.fail(`BIDS validation still in progress after ${y} attempts (~${Math.round(y*x/60000)}min). Re-run 'nemar admin publish request/approve ${n}' once validation completes.`),process.exit(1);v.text=`Waiting for BIDS validation to complete... (attempt ${C}/${y}, next retry in 5min)`,await new Promise((Z)=>setTimeout(Z,x))}if(_&&!g)v.succeed("Publication requested");let E=w("Approving publication...").start(),S=10,D=!1;if(g)D=!0,E.succeed(`${n} is already published; skipping publish/approve (data re-copy only)`);for(let C=1;!g&&C<=S;C++)try{await qc(n,C>1,!1,m),D=!0;break}catch(j){let k=j instanceof Error?j.message:String(j);if(C<S)E.text=`Approving publication... (attempt ${C+1}/${S})`,await new Promise((q)=>setTimeout(q,3000));else E.fail(`Failed to approve publication after ${S} attempts: ${k}`),process.exit(1)}if(D&&!g)E.succeed("Publication approved");let O=w("Refreshing metadata + LLM enrichment...").start();try{let C=await Oc(n),j=C.enrichment?.status==="ok",k=C.sync?.metadata_columns_written===!0;if(j&&k)O.succeed("Refreshed enrichment + metadata columns");else{let q=[];if(!j)q.push(`enrichment ${C.enrichment?.status??"missing"}`);if(!k)q.push("metadata columns not written");O.warn(`Partial reindex: ${q.join(", ")} (run 'nemar admin reindex ${n}' to retry)`)}}catch(C){let j=C instanceof Error?C.message:String(C);O.warn(`Reindex failed (non-fatal): ${j}. Run 'nemar admin reindex ${n}' to retry.`)}if(t.persistStaging)await mD(n,ni,ki);console.log(u.green(`
|
|
148
|
-
Import and publish complete: ${e} -> ${n}`)),console.log(u.dim(` GitHub: https://github.com/nemarDatasets/${n}`)),console.log(u.dim(` Working dir: ${o}`))}async function WIe(e,t={}){let r=await uG(e,t);if(!t.skipData)await lG(e,{index:0,count:1},t,r);await dG(e,t,r)}var LIe="OpenNeuroDatasets",ni="nemar",ki="us-east-2",UIe=16,tG="[openneuro-upstream-inaccessible]",HH,HIe;var Bm=A(()=>{Ke();rn();kc();Po();pd();Ts();Oi();jc();Bt();Ns();qs();jm();HH=["anat","beh","dwi","eeg","emg","fmap","func","ieeg","meg","micr","motion","nirs","perf","pet"];HIe=/^README(\.[A-Za-z0-9]+)?$/i});import{existsSync as KIe}from"fs";import{join as YIe}from"path";async function En(e){if(!KIe(YIe(e,".git")))return!1;try{let{exitCode:t}=await
|
|
148
|
+
Import and publish complete: ${e} -> ${n}`)),console.log(u.dim(` GitHub: https://github.com/nemarDatasets/${n}`)),console.log(u.dim(` Working dir: ${o}`))}async function WIe(e,t={}){let r=await uG(e,t);if(!t.skipData)await lG(e,{index:0,count:1},t,r);await dG(e,t,r)}var LIe="OpenNeuroDatasets",ni="nemar",ki="us-east-2",UIe=16,tG="[openneuro-upstream-inaccessible]",HH,HIe;var Bm=A(()=>{Ke();rn();kc();Po();pd();Ts();Oi();jc();Bt();Ns();qs();jm();HH=["anat","beh","dwi","eeg","emg","fmap","func","ieeg","meg","micr","motion","nirs","perf","pet"];HIe=/^README(\.[A-Za-z0-9]+)?$/i});import{existsSync as KIe}from"fs";import{join as YIe}from"path";async function En(e){if(!KIe(YIe(e,".git")))return!1;try{let{exitCode:t}=await F(["git","annex","info"],{cwd:e});return t===0}catch(t){let r=t instanceof Error?t.message:String(t);if(!r.includes("ENOENT")&&!r.includes("not found"))console.error(`Error checking if ${e} is a git-annex dataset:`,r);return!1}}async function Uc(e,t={}){if(!t.force&&await En(e))return{success:!0};try{let r={};if(t.author)r.GIT_AUTHOR_NAME=t.author.name,r.GIT_AUTHOR_EMAIL=t.author.email,r.GIT_COMMITTER_NAME=t.author.name,r.GIT_COMMITTER_EMAIL=t.author.email;let{stderr:n,exitCode:i}=await F(["git","init","-b","main",e],{...Object.keys(r).length>0?{env:r}:{}});if(i!==0)return{success:!1,error:n.trim()||"Failed to initialize git repository"};let s=Object.keys(r).length>0?{env:r}:{},{stderr:o,exitCode:a}=await F(["git","annex","init"],{cwd:e,...s});if(a!==0)return{success:!1,error:o.trim()||"Failed to initialize git-annex"};let{stderr:c,exitCode:l}=await F(["git","commit","--allow-empty","-m","Initialize dataset"],{cwd:e,...s});if(l!==0)return{success:!1,error:c.trim()||"Failed to create initial commit"};let{stderr:d,exitCode:f}=await F(["git","annex","adjust","--unlock"],{cwd:e,...s});if(f!==0)return{success:!1,error:d.trim()||"Failed to switch to unlocked mode"};return{success:!0}}catch(r){return{success:!1,error:r.message}}}async function fG(e){try{let{exitCode:t,stderr:r}=await F(["git","annex","info"],{cwd:e});if(t===0)return{success:!0};if(r.includes("First run: git-annex init")){let{stderr:n,exitCode:i}=await F(["git","annex","init"],{cwd:e});if(i!==0)return{success:!1,error:n.trim()||"Failed to initialize git-annex"};return{success:!0}}return{success:!1,error:r.trim()||"Failed to check git-annex status"}}catch(t){return{success:!1,error:t.message}}}async function Vc(e,t){let r=["*.edf","*.bdf","*.set","*.fif","*.vhdr","*.eeg","*.cnt","*.fdt"],n=["*.tsv","*.json","*.md","*.txt","*.yml","*.yaml","README*","LICENSE*","CHANGES*",".bidsignore",".gitignore"],i=r.map((c)=>`include=${c}`).join(" or "),s=n.map((c)=>`exclude=${c}`).join(" and "),o=`(${i} or largerthan=100kb) and ${s}`,a=t||o;try{let{stderr:c,exitCode:l}=await F(["git","annex","config","--set","annex.largefiles",a],{cwd:e});if(l!==0)return{success:!1,error:c.trim()||"Failed to configure largefiles"};return{success:!0}}catch(c){return{success:!1,error:c.message}}}function JIe(e,t=pG,r=mG){let n=[],i=[],s=0;for(let o of e){let a=Buffer.byteLength(o,"utf8")+1;if(i.length>0&&(i.length>=t||s+a>r))n.push(i),i=[],s=0;i.push(o),s+=a}if(i.length>0)n.push(i);return n}async function Io(e,t=".",r={}){let n=typeof t==="string"?[[t]]:JIe(t,r.maxPaths??pG,r.maxBytes??mG);try{for(let i of n){let{stderr:s,exitCode:o}=await F(["git","annex","add","--",...i],{cwd:e});if(o!==0)return{success:!1,error:s.trim()||"Failed to add files to git-annex"}}return{success:!0}}catch(i){return{success:!1,error:i.message}}}var pG=500,mG=131072;var Dd=A(()=>{Bt()});var bG={};Ti(bG,{runE2ETest:()=>rTe});import{cpSync as XIe,existsSync as _D,mkdirSync as QIe,mkdtempSync as hG,readFileSync as ZIe,rmSync as xD,writeFileSync as bD}from"fs";import{tmpdir as gG}from"os";import{join as Pi,resolve as vD}from"path";function Vt(e,...t){if(e.verbose)console.log(" ",...t)}async function xG(e,t){let r=performance.now();try{return await t(),{name:e,passed:!0,duration_ms:Math.round(performance.now()-r)}}catch(n){let i=n instanceof Error?n.message:String(n);return{name:e,passed:!1,duration_ms:Math.round(performance.now()-r),error:i}}}async function eTe(e){let t=[];for(let{name:r,fn:n}of e){let i=await xG(r,n);if(t.push(i),!i.passed)break}return t}function Cr(e,t){if(!e.success)throw Error(`${t}: ${e.error}`)}function yG(e){if(!e.creds)throw Error("credentials not yet fetched");return e.creds}function tTe(){let e=[vD(__dirname,"../../test/fixtures/bids-minimal"),vD(__dirname,"../test/fixtures/bids-minimal"),vD(process.cwd(),"test/fixtures/bids-minimal")];for(let t of e)if(_D(t))return t;throw Error("Could not find test/fixtures/bids-minimal. Run from the nemar-cli root directory.")}async function rTe(e){let t=e.verbose??!1,r=performance.now(),n=hG(Pi(gG(),"nemar-e2e-upload-")),i=hG(Pi(gG(),"nemar-e2e-clone-")),s={uploadDir:n,cloneDir:i,verbose:t},o=[];if(!e.skipReset)o.push({name:"Reset nm099999",fn:async()=>{let c=await nz(To);if(Vt(s,`S3 objects deleted: ${c.steps.s3_deleted}`),Vt(s,`GitHub recreated: ${c.steps.github_recreated}`),Vt(s,`D1 cleaned: ${c.steps.d1_cleaned}`),!c.success){let l=[];if(!c.steps.github_recreated)l.push("GitHub");if(!c.steps.d1_cleaned)l.push("D1");throw Error(`Reset partially failed: ${l.join(", ")}`)}}});o.push({name:"Prepare upload",fn:async()=>{let c=tTe();XIe(c,n,{recursive:!0});for(let l of[".git",".nemar",".gitattributes"]){let d=Pi(n,l);if(_D(d)){let f=await F(["chmod","-R","u+w",d]);if(f.exitCode!==0)console.warn(`chmod failed for ${d} (exit ${f.exitCode}): ${f.stderr}`);xD(d,{recursive:!0,force:!0})}}Vt(s,`Copied fixtures to ${n}`)}},{name:"Init git + annex",fn:async()=>{Cr(await Uc(n,{force:!0}),"initDataset"),Cr(await Vc(n),"configureLargefiles"),Vt(s,"Git + git-annex initialized")}},{name:"Configure remotes",fn:async()=>{s.creds=await Zn(To),Vt(s,`S3 prefix: ${s.creds.s3.prefix}`),Cr(await $r(n,{name:"nemar-s3",bucket:s.creds.s3.bucket,prefix:`${To}/objects`,region:s.creds.s3.region,publicUrl:`https://${s.creds.s3.bucket}.s3.${s.creds.s3.region}.amazonaws.com/${To}/objects`},Lt(s.creds.credentials)),"configureS3Remote");let c=`git@github.com:nemarDatasets/${To}.git`;Cr(await ei(n,c),"configureGitHubRemote"),Vt(s,"S3 + GitHub remotes configured")}},{name:"Upload to S3",fn:async()=>{Cr(await Io(n),"gitAnnexAdd"),Cr(await Ai(n,"Initial BIDS dataset"),"saveDataset");let c=await ri(n,"nemar-s3",4,Lt(yG(s).credentials));Cr(c,"copyToAnnexRemote"),Vt(s,`Files copied to S3: ${c.filesCopied}`),await Ut(n)}},{name:"Push to GitHub",fn:async()=>{let c=await Qt(n);if(Cr(c,"pushToGitHub"),c.warning)Vt(s,`Warning: ${c.warning}`);Vt(s,"Pushed to GitHub (main + git-annex branches)")}},{name:"Clone fresh",fn:async()=>{let c=`git@github.com:nemarDatasets/${To}.git`;Cr(await yr(c,i),"cloneDataset");let l=await Mc(i,"nemar-s3");if(!l.success)throw Error(`enableS3Remote: ${l.error}`);Vt(s,`Clone at ${i}, S3 remote enabled: ${l.enabled}`)}},{name:"Download + verify",fn:async()=>{let c=Lt(yG(s).credentials),l={AWS_ACCESS_KEY_ID:c.accessKeyId,AWS_SECRET_ACCESS_KEY:c.secretAccessKey};if(c.sessionToken)l.AWS_SESSION_TOKEN=c.sessionToken;let{stdout:d,stderr:f,exitCode:m}=await F(["git","annex","get","."],{cwd:i,env:l});if(m!==0)throw Error(`getDatasetData: ${f.trim()}`);let p=d.match(/^get .+ ok$/gm);Vt(s,`Files downloaded: ${p?p.length:0}`);let g=Pi(i,"sub-01/eeg/sub-01_task-rest_eeg.edf");if(!_D(g))throw Error("EDF file not found after download");let{size:y}=Bun.file(g);if(y<512)throw Error(`EDF file too small: ${y} bytes`);Vt(s,`EDF file verified: ${y} bytes`)}},{name:"Update cycle",fn:async()=>{let c=Pi(i,"sub-02/eeg");QIe(c,{recursive:!0});let l=Buffer.alloc(1024);l.write("0".padEnd(8),0,"ascii"),bD(Pi(c,"sub-02_task-rest_eeg.edf"),l),bD(Pi(c,"sub-02_task-rest_eeg.json"),JSON.stringify({TaskName:"rest",SamplingFrequency:256}));let d=ZIe(Pi(i,"participants.tsv"),"utf-8");bD(Pi(i,"participants.tsv"),`${d.trimEnd()}
|
|
149
149
|
sub-02 30 F
|
|
150
|
-
`);let f=`e2e-update-${Date.now()}`,{exitCode:m}=await
|
|
151
|
-
`).filter(Boolean);if(n.length===0)return;let i=await
|
|
150
|
+
`);let f=`e2e-update-${Date.now()}`,{exitCode:m}=await F(["git","checkout","-b",f],{cwd:i});if(m!==0)throw Error("Failed to create update branch");Cr(await Io(i),"gitAnnexAdd (update)"),Cr(await Ai(i,"Add sub-02"),"saveDataset (update)"),s.creds=await Zn(To);let p=await ri(i,"nemar-s3",4,Lt(s.creds.credentials));Cr(p,"copyToAnnexRemote (update)"),Vt(s,`Update files copied to S3: ${p.filesCopied}`),await Ut(i);let g=await Qt(i,"origin",f);Cr(g,"pushToGitHub (update branch)");let{exitCode:y,stderr:x}=await F(["git","push","origin","git-annex"],{cwd:i});if(y!==0)throw Error(`Failed to push git-annex branch: ${x.trim()}`);Vt(s,`Update pushed to branch: ${f}`)}});let a=await eTe(o);if(!e.skipCleanup&&a.every((c)=>c.passed))a.push(await xG("Cleanup",async()=>{await F(["chmod","-R","u+w",n]),await F(["chmod","-R","u+w",i]),xD(n,{recursive:!0,force:!0}),xD(i,{recursive:!0,force:!0}),Vt(s,"Temp directories cleaned up")}));return nTe(a,r,n,i,e.skipCleanup)}function nTe(e,t,r,n,i){let s={passed:e.every((o)=>o.passed),steps:e,total_duration_ms:Math.round(performance.now()-t)};if(i)s.upload_dir=r,s.clone_dir=n;return s}var __dirname="/home/runner/work/nemar-cli/nemar-cli/src/lib",To="nm099999";var vG=A(()=>{kc();Pc();Ts();Oi();Dd();Bt();Ns();qs()});var SD={};Ti(SD,{EXEMPLAR_ID_RE:()=>wD,EXEMPLAR_SOURCE_ID_RE:()=>ED,cloneExemplar:()=>pTe,copyExemplarData:()=>AG,finalizeExemplar:()=>PG,findMissingCopiedKeys:()=>kG,isAnnexContentKey:()=>CG,loadExemplarFleet:()=>cTe,parseExemplarFleet:()=>$G,planSubPrefixCopy:()=>RG,prepareExemplar:()=>OG,rewriteObjectKeyPrefix:()=>SG,scrubDatasetDescription:()=>EG});import{existsSync as iTe,mkdtempSync as sTe,readFileSync as DG,writeFileSync as oTe}from"fs";import{tmpdir as aTe}from"os";import{join as Lm}from"path";function EG(e){let t=typeof e.Name==="string"?e.Name:"",{DatasetDOI:r,...n}=e;return{...n,Name:`[TEST COPY] ${t}`}}function SG(e,t,r){let n=`${t}/`;if(!e.startsWith(n))throw Error(`Key "${e}" does not start with expected source prefix "${n}"`);return`${r}/${e.slice(n.length)}`}function $G(e){if(!Array.isArray(e))throw Error("Exemplar fleet file must be a JSON array");return e.map((t,r)=>{if(typeof t!=="object"||t===null)throw Error(`Fleet entry ${r} is not an object`);let{xx_id:n,source_id:i,modality:s,note:o}=t;if(typeof n!=="string"||!wD.test(n))throw Error(`Fleet entry ${r}: xx_id "${n}" must match xx099900-xx099999`);if(typeof i!=="string"||!ED.test(i))throw Error(`Fleet entry ${r} (${n}): source_id "${i}" must be an nm/on dataset id`);if(typeof s!=="string"||s.length===0)throw Error(`Fleet entry ${r} (${n}): modality is required`);if(o!==void 0&&typeof o!=="string")throw Error(`Fleet entry ${r} (${n}): note must be a string when present`);return{xx_id:n,source_id:i,modality:s,...o!==void 0?{note:o}:{}}})}function cTe(e){let t;try{t=JSON.parse(DG(e,"utf-8"))}catch(r){throw Error(`Failed to read/parse exemplar fleet file at ${e}: ${r instanceof Error?r.message:String(r)}`)}return $G(t)}function uTe(){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 lTe(e){let t=Lm(e,"dataset_description.json");if(!iTe(t))throw Error(`dataset_description.json not found at ${t}`);try{return JSON.parse(DG(t,"utf-8"))}catch(r){throw Error(`Failed to parse dataset_description.json at ${t}: ${r instanceof Error?r.message:String(r)}`)}}async function dTe(e){let{stdout:t,exitCode:r}=await F(["git","tag","-l"],{cwd:e});if(r!==0)return;let n=t.trim().split(`
|
|
151
|
+
`).filter(Boolean);if(n.length===0)return;let i=await F(["git","tag","-d",...n],{cwd:e});if(i.exitCode!==0)console.warn(u.yellow(` Warning: failed to strip local tags: ${i.stderr.trim()}`))}function CG(e){return e!==fTe}async function FG(e,t,r){let n=`${e}/${r}`;return[...(await js(_G,n,No)).keys()].filter(CG).map((s)=>{let o=`${n}${s}`,a=SG(o,e,t);return{key:s,source:{bucket:_G,key:o,region:No},httpUrl:null,destUri:`s3://${Ed}/${a}`}})}function RG(e,t){return bd(e,t,vd(e))}async function DD(e,t,r,n){let i=await FG(e,t,r);if(i.length===0)return console.log(u.dim(` [${n}] nothing to copy`)),[];let s=await js(Ed,`${t}/${r}`,No),{toCopy:o,skipped:a}=RG(i,s);if(o.length===0)return console.log(u.green(` [${n}] nothing to copy (all ${a.length} present)`)),i.map((d)=>d.key);let c=w(`[${n}] copying ${o.length} files...`).start(),l=await Lc(o,No,wG,(d,f)=>{c.text=`[${n}] ${d}/${f}`});if(l.failed.length>0){c.fail(`[${n}] ${l.failed.length} of ${o.length} files failed`);for(let d of l.failed.slice(0,5))console.error(u.red(` ${d.key}: ${d.error}`));throw console.error(u.red(`Re-run to resume [${n}] (already-copied objects are skipped).`)),Error(`[${n}] ${l.failed.length} of ${o.length} files failed to copy: ${l.failed.slice(0,5).map((d)=>`${d.key}: ${d.error}`).join("; ")}`)}return c.succeed(`[${n}] copied ${l.copied}, skipped ${a.length}`),i.map((d)=>d.key)}async function OG(e,t,r={}){if(!wD.test(e))throw Error(`Invalid exemplar id "${e}". Expected xx099900-xx099999.`);if(!ED.test(t))throw Error(`Invalid source id "${t}". Expected an nm/on dataset id.`);let n=r.workDir||sTe(Lm(aTe(),`nemar-exemplar-${e}-`)),i=Lm(n,e);console.log(u.cyan(`
|
|
152
152
|
[prepare] ${t} -> ${e}
|
|
153
153
|
`)),console.log(u.dim(`Working directory: ${n}`));let s=w(`Cloning ${t}...`).start(),o=`https://github.com/${wd}/${t}.git`,a=await yr(o,i);if(!a.success){let k=`Failed to clone: ${a.error}`;throw s.fail(k),Error(k)}s.succeed(`Cloned ${t}`),await dTe(i);let c=w("Scrubbing dataset_description.json...").start(),l=lTe(i),d=EG(l);oTe(Lm(i,"dataset_description.json"),`${JSON.stringify(d,null,2)}
|
|
154
|
-
`);let f=await
|
|
154
|
+
`);let f=await F(["git","add","dataset_description.json"],{cwd:i});if(f.exitCode!==0){let k=`Failed to stage scrubbed metadata: ${f.stderr.trim()}`;throw c.fail(k),Error(k)}let m=await F(["git","commit","-m",`Scrub dataset_description.json for exemplar clone (source: ${t})`],{cwd:i});if(m.exitCode!==0&&!m.stdout.includes("nothing to commit")){let k=`Failed to commit scrubbed metadata: ${m.stderr.trim()}`;throw c.fail(k),Error(k)}c.succeed("Scrubbed dataset_description.json");let p=r.name||(typeof d.Name==="string"?d.Name:void 0),g=w("Creating exemplar dataset record...").start();try{let k=await az({dataset_id:e,source_id:t,name:p,description:r.description});g.succeed(`Created ${k.dataset_id} (${k.github_repo})`)}catch(k){let q=k instanceof Error?k.message:String(k),Z=k instanceof M&&k.statusCode===409;if(Z&&q.includes("Dataset"))g.warn(`Exemplar ${e} already exists, continuing...`);else if(Z){let ve=`GitHub repo for ${e} exists but has no dataset record \u2014 a previous run failed between repo creation and the D1 insert. Delete the orphan with 'nemar admin delete-dataset ${e}' (or remove the repo manually) and re-run. Original: ${q}`;throw g.fail(ve),Error(ve)}else{let ve=`Failed to create exemplar: ${q}`;throw g.fail(ve),Error(ve)}}await Pm(i,(k,q)=>{console.log(u.yellow(` Warning: could not mark ${k} as annex-ignore (${q}). Run 'git config remote.${k}.annex-ignore true' manually.`))},["nemar-s3"]);let y=w("Configuring nemar-s3-dev remote...").start(),x=uTe(),v=await $r(i,{name:"nemar-s3-dev",bucket:Ed,prefix:`${e}/objects`,region:No},x);if(!v.success){let k=`Failed to configure nemar-s3-dev: ${v.error}`;throw y.fail(k),Error(k)}let _=await Bc(i,"nemar-s3-dev");if(!_)throw y.fail("Failed to get nemar-s3-dev remote UUID"),Error("Failed to get nemar-s3-dev remote UUID");y.succeed("Configured nemar-s3-dev remote");let E=w("Configuring NEMAR remote...").start(),S=await F(["git","remote","remove","origin"],{cwd:i});if(S.exitCode!==0&&!S.stderr.includes("No such remote")){let k=`Failed to remove source remote: ${S.stderr.trim()}`;throw E.fail(k),Error(k)}let D=`git@github.com:${wd}/${e}.git`,O=await ei(i,D,"origin");if(!O.success){let k=`Failed to configure remote: ${O.error}`;throw E.fail(k),Error(k)}E.succeed("Configured NEMAR remote");let C=w(`Pushing to ${wd}...`).start(),j=await Qt(i,"origin");if(!j.success){let k=`Failed to push: ${j.error}`;throw C.fail(k),Error(k)}if(j.warning){let k=`Pushed main but git-annex branch failed: ${j.warning}. Aborting \u2014 the exemplar would be uncloneable.`;throw C.fail(k),Error(k)}return C.succeed(`Pushed to ${wd}`),console.log(u.green(`[prepare] done: ${e}`)),{datasetPath:i,xxId:e,sourceId:t,nemarS3DevUuid:_}}async function AG(e,t={}){let{xxId:r,sourceId:n}=e;console.log(u.cyan(`
|
|
155
155
|
[copy] ${n} -> ${r}
|
|
156
156
|
`));let i=await DD(n,r,"objects/","objects");if(t.includeDerived){await DD(n,r,"zarr/","zarr"),await DD(n,r,"archives/","archives");let o=(await FG(n,r,"version/")).filter((a)=>a.key.endsWith("-records.json"));if(o.length>0){let a=w(`[records.json] copying ${o.length} file(s)...`).start(),c=await Lc(o,No,wG);if(c.failed.length>0)throw a.fail(`[records.json] ${c.failed.length} of ${o.length} failed`),Error(`[records.json] ${c.failed.length} of ${o.length} file(s) failed to copy: ${c.failed.slice(0,5).map((l)=>`${l.key}: ${l.error}`).join("; ")}`);a.succeed(`[records.json] copied ${c.copied}`)}}return{keys:i}}function kG(e,t){return e.filter((r)=>!xd(r,t))}async function PG(e,t,r={}){let{datasetPath:n,xxId:i,sourceId:s,nemarS3DevUuid:o}=e;if(console.log(u.cyan(`
|
|
157
157
|
[finalize] ${s} -> ${i}
|
|
@@ -161,7 +161,7 @@ Exemplar clone + publish complete: ${s} -> ${i}`)),console.log(u.dim(` GitHub:
|
|
|
161
161
|
Run with --help-all for examples and detailed descriptions.
|
|
162
162
|
`,jd=new WeakSet;Ee.prototype.addHelpText=function(e,t){if(e==="after"||e==="afterAll"){if(qw)return Xc.call(this,e,t);if(!jd.has(this))return jd.add(this),Xc.call(this,e,jw);return this}return Xc.call(this,e,t)};var xJ={formatHelp(e,t){let r=t.padWidth(e,t),n=t.helpWidth??80,i=2,s=2;function o(g,y,x){if(x){let v=" ".repeat(Math.max(0,r+2-g.length)),_=`${y}${v}${x}`;return t.wrap(_,n-2,r+2)}return y}function a(g){return g.join(`
|
|
163
163
|
`).replace(/^/gm," ".repeat(2))}let c=[];c.push(`Usage: ${t.commandUsage(e)}`,"");let l=t.commandDescription(e);if(l.length>0)c.push(t.wrap(l,n,0),"");let d=t.visibleArguments(e).map((g)=>{let y=t.argumentTerm(g);return o(y,u.blue(y),t.argumentDescription(g))});if(d.length>0)c.push(u.bold("Arguments:"),a(d),"");let f=t.visibleOptions(e).map((g)=>{let y=t.optionTerm(g);return o(y,u.cyan(y),t.optionDescription(g))});if(f.length>0)c.push(u.bold("Options:"),a(f),"");let p=t.visibleCommands(e).sort((g,y)=>g.name().localeCompare(y.name())).map((g)=>{let y=t.subcommandTerm(g);return o(y,u.bold.cyan(y),t.subcommandDescription(g))});if(p.length>0)c.push(u.bold("Commands:"),a(p),"");return c.join(`
|
|
164
|
-
`)}};function Mw(e){Bw(e)}function Bw(e){e.configureHelp(xJ);for(let t of e.commands)Bw(t)}function Us(e,t){if(qw)Xc.call(e,"after",t);else if(!jd.has(e))jd.add(e),Xc.call(e,"after",jw)}Ke();Ke();import{existsSync as jG,readFileSync as mTe}from"fs";import{join as Um}from"path";Bn();rn();kc();Pc();Po();gr();Ps();var X_=["critical","warning","maintenance","announcement","tip"];async function Gz(){return I("/notices",{},"optional")}async function Wz(){return I("/admin/notices",{},!0)}async function Kz(e){return I("/admin/notices",{method:"POST",body:JSON.stringify(e)},!0)}async function Yz(e){return I(`/admin/notices/${e}`,{method:"DELETE"},!0)}pd();ks();Bn();async function Fe(e,t,r=!1){if(t.no)return"declined";if(t.yes)return"confirmed";try{let{confirmed:n}=await X.prompt([{type:"confirm",name:"confirmed",message:e,default:r}]);return n?"confirmed":"cancelled"}catch(n){let i=n instanceof Error?n.message:String(n);if(i.includes("closed")||i.includes("TTY")||i.includes("SIGINT")||i.includes("readline"))console.error("Interactive prompt unavailable (non-interactive terminal or interrupted)"),console.error(" Use --yes or --no flags for non-interactive mode");else console.error("Prompt error:",i);return"cancelled"}}async function rH(e,t,r){if(r.no)return"declined";if(r.yes)return"confirmed";try{let{input:n}=await X.prompt([{type:"input",name:"input",message:e,validate:(i)=>{if(i!==t)return`Input does not match. Expected: ${t}`;return!0}}]);return n===t?"confirmed":"cancelled"}catch(n){let i=n instanceof Error?n.message:String(n);if(i.includes("closed")||i.includes("TTY")||i.includes("SIGINT")||i.includes("readline"))console.error("Interactive prompt unavailable (non-interactive terminal or interrupted)"),console.error(" Use --yes or --no flags for non-interactive mode");else console.error("Prompt error:",i);return"cancelled"}}var Re="-y, --yes",qe="-n, --no",Oe="Skip confirmation and proceed",Te="Skip confirmation and decline";var Q_=new Set(["nm000103","nm000104","nm000105","nm000106","nm000107"]);function nH(e,t){return e.filter((r)=>r.visibility==="public").map((r)=>r.dataset_id).filter((r)=>r.startsWith("nm")||r.startsWith("on")).filter((r)=>r!=="nm099999"&&!Q_.has(r)).filter((r)=>t.prefix?r.startsWith(t.prefix):!0).sort()}Ts();Oi();Bt();function vH(e){return e.split(".").map((t)=>{let r=Number.parseInt(t.replace(/[^0-9]/g,""),10);return Number.isNaN(r)?0:r})}function Z3e(e,t){let r=vH(e),n=vH(t);for(let i=0;i<Math.max(r.length,n.length);i++){let s=r[i]||0,o=n[i]||0;if(s>o)return!0;if(s<o)return!1}return!0}async function _H(){try{let{stdout:t,exitCode:r,stderr:n}=await
|
|
164
|
+
`)}};function Mw(e){Bw(e)}function Bw(e){e.configureHelp(xJ);for(let t of e.commands)Bw(t)}function Us(e,t){if(qw)Xc.call(e,"after",t);else if(!jd.has(e))jd.add(e),Xc.call(e,"after",jw)}Ke();Ke();import{existsSync as jG,readFileSync as mTe}from"fs";import{join as Um}from"path";Bn();rn();kc();Pc();Po();gr();Ps();var X_=["critical","warning","maintenance","announcement","tip"];async function Gz(){return I("/notices",{},"optional")}async function Wz(){return I("/admin/notices",{},!0)}async function Kz(e){return I("/admin/notices",{method:"POST",body:JSON.stringify(e)},!0)}async function Yz(e){return I(`/admin/notices/${e}`,{method:"DELETE"},!0)}pd();ks();Bn();async function Fe(e,t,r=!1){if(t.no)return"declined";if(t.yes)return"confirmed";try{let{confirmed:n}=await X.prompt([{type:"confirm",name:"confirmed",message:e,default:r}]);return n?"confirmed":"cancelled"}catch(n){let i=n instanceof Error?n.message:String(n);if(i.includes("closed")||i.includes("TTY")||i.includes("SIGINT")||i.includes("readline"))console.error("Interactive prompt unavailable (non-interactive terminal or interrupted)"),console.error(" Use --yes or --no flags for non-interactive mode");else console.error("Prompt error:",i);return"cancelled"}}async function rH(e,t,r){if(r.no)return"declined";if(r.yes)return"confirmed";try{let{input:n}=await X.prompt([{type:"input",name:"input",message:e,validate:(i)=>{if(i!==t)return`Input does not match. Expected: ${t}`;return!0}}]);return n===t?"confirmed":"cancelled"}catch(n){let i=n instanceof Error?n.message:String(n);if(i.includes("closed")||i.includes("TTY")||i.includes("SIGINT")||i.includes("readline"))console.error("Interactive prompt unavailable (non-interactive terminal or interrupted)"),console.error(" Use --yes or --no flags for non-interactive mode");else console.error("Prompt error:",i);return"cancelled"}}var Re="-y, --yes",qe="-n, --no",Oe="Skip confirmation and proceed",Te="Skip confirmation and decline";var Q_=new Set(["nm000103","nm000104","nm000105","nm000106","nm000107"]);function nH(e,t){return e.filter((r)=>r.visibility==="public").map((r)=>r.dataset_id).filter((r)=>r.startsWith("nm")||r.startsWith("on")).filter((r)=>r!=="nm099999"&&!Q_.has(r)).filter((r)=>t.prefix?r.startsWith(t.prefix):!0).sort()}Ts();Oi();Bt();function vH(e){return e.split(".").map((t)=>{let r=Number.parseInt(t.replace(/[^0-9]/g,""),10);return Number.isNaN(r)?0:r})}function Z3e(e,t){let r=vH(e),n=vH(t);for(let i=0;i<Math.max(r.length,n.length);i++){let s=r[i]||0,o=n[i]||0;if(s>o)return!0;if(s<o)return!1}return!0}async function _H(){try{let{stdout:t,exitCode:r,stderr:n}=await F(["git-annex","version"]);if(r!==0)return console.warn("git-annex version returned non-zero exit code:",r),console.warn("stderr:",n),{installed:!1,minVersion:"10.0",error:`Version check failed: ${n.trim()}`};let i=t.match(/version:\s*(\d+\.\d+)/),s=i?i[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?Z3e(s,"10.0"):void 0}}catch(t){let r=t instanceof Error?t.message:String(t);if(r.includes("ENOENT")||r.includes("not found"))return console.info("git-annex not found in PATH"),{installed:!1,minVersion:"10.0"};return console.error("Error checking git-annex installation:",r),{installed:!1,minVersion:"10.0",error:r}}}async function eIe(){if(process.env.GH_TOKEN)return{accessible:!0,username:"token-auth",useHttps:!0};try{let{stdout:e,stderr:t}=await F(["ssh","-T","-o","BatchMode=yes","-o","StrictHostKeyChecking=accept-new","-o","ConnectTimeout=10","git@github.com"]),r=e+t,n=r.match(/Hi ([^!]+)!/);if(n)return{accessible:!0,username:n[1]};if(r.includes("Permission denied"))return{accessible:!1};return{accessible:r.includes("successfully authenticated")}}catch(e){let t=e instanceof Error?e.message:String(e);if(t.includes("ENOENT")||t.includes("not found"))console.info("SSH command not found");else console.error("Error checking GitHub SSH access:",t);return{accessible:!1}}}function DH(){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 Rm(){let[e,t]=await Promise.all([_H(),eIe()]),r=[];if(!e.installed)r.push(`git-annex is not installed. Install: ${DH()}`);else if(e.compatible===!1)r.push(`git-annex version ${e.version} is too old. Required: >= ${e.minVersion}`);if(!t.accessible){if(!(await hd()).token)r.push("GitHub authentication not configured. Run 'gh auth login' to authenticate.")}return{gitAnnex:e,githubSSH:t,allPassed:r.length===0,errors:r}}async function yd(){let e=await _H(),t=[];if(!e.installed)t.push(`git-annex is not installed. Install: ${DH()}`);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}}jc();Ke();function Qe(e){if(e===0)return"0 B";let t=["B","KB","MB","GB","TB"],r=Math.min(Math.floor(Math.log(e)/Math.log(1024)),t.length-1);return`${(e/1024**r).toFixed(r===0?0:1)} ${t[r]}`}function wH(e){return`${Qe(e)}/s`}function tIe(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 rIe(e,t=20){let r=Math.round(e/100*t),n=t-r;return`[${"=".repeat(r)}${" ".repeat(n)}]`}class Om{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 r=t??this.currentFile,n=r?this.inFlight.get(r):void 0,i=n?n.total||n.transferred:0;if(this.totalBytesTransferred+=i,r)this.inFlight.delete(r);this.render();return}if(e["byte-progress"]!==void 0){let r=t??this.currentFile;if(!r)return;this.currentFile=r;let n=this.inFlight.get(r)??{transferred:0,total:0};if(n.transferred=e["byte-progress"]??n.transferred,e["total-size"]!==void 0)n.total=e["total-size"];this.inFlight.set(r,n);let i=Date.now(),s=(i-this.lastUpdateTime)/1000;if(s>0.5){let o=this.totalBytesTransferred+this.inFlightBytes(),c=(o-this.lastBytesTransferred)/s;if(c>0){if(this.speedSamples.push(c),this.speedSamples.length>5)this.speedSamples.shift()}this.lastBytesTransferred=o,this.lastUpdateTime=i}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((o,a)=>o+a,0)/this.speedSamples.length:0,t=this.totalBytesTransferred+this.inFlightBytes(),r=0,n=!1;if(this.bytesTotal>0)r=Math.min(100,Math.round(t/this.bytesTotal*100)),n=!0;else if(this.filesTotal>0)r=Math.min(100,Math.round(this.filesCompleted/this.filesTotal*100)),n=!0;let i=this.filesTotal>0?`${this.filesCompleted}/${this.filesTotal} files`:`${this.filesCompleted} files`,s;if(n)s=`${rIe(r)} ${r}% ${i}`;else s=i;if(t>0){let o=this.bytesTotal>0?`${Qe(t)}/${Qe(this.bytesTotal)}`:Qe(t);s+=` | ${o}`}if(e>0)s+=` | ${wH(e)}`;if(e>0){let o=0;if(this.bytesTotal>0)o=Math.max(0,this.bytesTotal-t);else for(let a of this.inFlight.values())if(a.total>a.transferred)o+=a.total-a.transferred;if(o>0){let a=o/e;if(a>0)s+=` | ETA ${tIe(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 r=t>0?`${wH(this.totalBytesTransferred/t)}`:"",n=[`${e} file${e!==1?"s":""} downloaded`,this.totalBytesTransferred>0?Qe(this.totalBytesTransferred):"",r].filter(Boolean).join(" | ");process.stderr.write(`${u.green(n)}
|
|
165
165
|
`)}}}import{readFileSync as nIe}from"fs";var iIe=/^on\d{6}$/;function sIe(e){if(!Array.isArray(e))throw Error("Recover-datasets file must be a JSON array");return e.map((t,r)=>{if(typeof t!=="object"||t===null)throw Error(`Recover-datasets entry ${r} is not an object`);let{dataset_id:n,note:i}=t;if(typeof n!=="string"||!iIe.test(n))throw Error(`Recover-datasets entry ${r}: dataset_id "${n}" is not valid`);if(typeof i!=="string"||i.length===0)throw Error(`Recover-datasets entry ${r} (${n}): note is required`);return{dataset_id:n,note:i}})}function rD(e){let t;try{t=JSON.parse(nIe(e,"utf-8"))}catch(r){throw Error(`Failed to read/parse recover-datasets file at ${e}: ${r instanceof Error?r.message:String(r)}`)}return sIe(t)}function EH(e,t,r){let n=new Set(t.map((i)=>i.dataset_id));for(let i of e)if(!n.has(i)&&!r.force)return{error:`${i} is not on the checked-in recover-datasets list. Pass --force to override.`};return{targets:e}}function SH(e,t){let r=new Set(e),n=new Map;for(let s of t)if(r.has(s.dataset_id)&&s.source_id)n.set(s.dataset_id,s.source_id);let i=e.filter((s)=>!n.has(s));return{sourceByTarget:n,missingSource:i}}import{readFileSync as oIe}from"fs";var $H=new Set(["upstream_403","no_source"]),aIe=/^(nm|xx|on)\d{6}$/;function cIe(e){if(!Array.isArray(e))throw Error("Withdrawn-datasets file must be a JSON array");return e.map((t,r)=>{if(typeof t!=="object"||t===null)throw Error(`Withdrawn-datasets entry ${r} is not an object`);let{dataset_id:n,reason:i,note:s}=t;if(typeof n!=="string"||!aIe.test(n))throw Error(`Withdrawn-datasets entry ${r}: dataset_id "${n}" is not valid`);if(typeof i!=="string"||!$H.has(i))throw Error(`Withdrawn-datasets entry ${r} (${n}): reason "${i}" must be one of ${[...$H].join(", ")}`);if(typeof s!=="string"||s.length===0)throw Error(`Withdrawn-datasets entry ${r} (${n}): note is required`);return{dataset_id:n,reason:i,note:s}})}function nD(e){let t;try{t=JSON.parse(oIe(e,"utf-8"))}catch(r){throw Error(`Failed to read/parse withdrawn-datasets file at ${e}: ${r instanceof Error?r.message:String(r)}`)}return cIe(t)}function CH(e,t,r){let n=new Map(t.map((s)=>[s.dataset_id,s])),i=[];for(let s of e){let o=n.get(s);if(!o&&!r.force)return{error:`${s} is not on the checked-in withdrawn-datasets list. Pass --force to override.`};let a=r.reason||o?.reason;if(!a)return{error:`${s}: no --reason given and it has no default entry in the list.`};i.push({datasetId:s,reason:a})}return{targets:i}}function Ze(e,t,r,n){if(e instanceof M){t.fail(e.message);let i=n?.[e.statusCode];if(i)console.log(u.dim(` ${i}`));else if(e.statusCode===403)console.log(u.dim(" This command requires admin privileges"))}else t.fail(r),console.log(u.dim(` Error details: ${U(e)}`))}async function IG(e,t){let{spawn:r}=awaitPromise.resolve(globalThis.Bun),n=t==="README"?`repos/${e}/readme`:`repos/${e}/contents/${t}`,i=r({cmd:["gh","api",n,"--jq",".content"],stdout:"pipe",stderr:"pipe"}),s=await new Response(i.stdout).text(),o=await new Response(i.stderr).text();if(await i.exited!==0){if(o.trim()&&!o.includes("404"))console.warn(`[fetchGitHubFileContent] Error fetching ${t}: ${o.trim()}`);return null}if(!s.trim())return null;return Buffer.from(s.trim(),"base64").toString("utf-8")}var Ie=new Ee("admin").description("Admin commands (requires admin privileges)").addHelpText("after",`
|
|
166
166
|
Description:
|
|
167
167
|
Administrative commands for managing NEMAR users and datasets.
|
|
@@ -456,7 +456,7 @@ Exemplar Fleet (${n.length})
|
|
|
456
456
|
${i} finding(s). Preview the remediation with: nemar admin doctor fix <check> --dry-run`))}catch(n){r.fail("Doctor scan failed"),console.error(u.red(U(n))),process.exit(1)}});OD.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,r)=>{if(!oe())return;if(r.dryRun){let c=w(`Listing ${e} findings (dry run)...`).start();try{let l=await G_({check:e,datasetId:t,dryRun:!0});if(c.stop(),r.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(U(l))),process.exit(1)}return}let n=w(`Scanning for ${e} findings...`).start(),i;try{i=(await H_({check:e,datasetId:t})).results[e]?.findings??[]}catch(c){n.fail("Doctor scan failed"),console.error(u.red(U(c))),process.exit(1);return}if(i.length===0){if(n.succeed(`${e}: nothing to fix`),r.json)console.log(JSON.stringify({check:e,total:0,results:[]},null,2));return}n.stop(),console.log(`${u.bold(e)}: ${i.length} finding(s) to fix`);let s=[...new Set(i.map((c)=>c.dataset_id))];n.start();let{totals:o,results:a}=await ETe(s,(c,l)=>{let d=i.filter((f)=>f.dataset_id===c&&f.version).map((f)=>`v${f.version}`).join(", ");return n.text=`Fixing ${c}${d?` (${d})`:""} [${l+1}/${s.length}]...`,G_({check:e,datasetId:c})},{onDataset:(c,l)=>{if(n.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"}`)}n.start()}});if(n.stop(),r.json)console.log(JSON.stringify({check:e,total:i.length,...o,results:a},null,2));else{let c=o.resolved>0?`, ${o.resolved} already resolved`:"";console.log(`
|
|
457
457
|
${u.bold(e)}: ${u.green(`${o.fixed} fixed`)}, ${o.skipped} skipped, ${o.failed>0?u.red(`${o.failed} failed`):"0 failed"}${c}`)}if(o.failed>0)process.exit(1)});async function ETe(e,t,r){let n={fixed:0,skipped:0,failed:0,resolved:0},i=[];for(let[s,o]of e.entries()){let a;try{let c=await t(o,s);if(a=c.results,a.length===0)n.resolved++;else n.fixed+=c.fixed,n.skipped+=c.skipped,n.failed+=c.failed}catch(c){n.failed++,a=[{dataset_id:o,status:"failed",message:U(c)}]}i.push(...a),r?.onDataset?.(o,a)}return{totals:n,results:i}}Ie.addCommand(OD);var AD=new Ee("email-preferences").description("Manage email notification preferences");AD.command("show").description("Show email notification preferences").option("--user <username>","(owner only) show another user's preferences").action(async(e)=>{if(!Ue())console.error(u.red("Not authenticated. Run: nemar auth login")),process.exit(1);let t=w("Fetching email preferences...").start();try{let r=await wz(e.user),n=r.username?`${r.username}'s`:"Your";t.succeed(`${n} email notification preferences:`),console.log();let i=[{key:"user_approval",label:"User approval notifications"},{key:"publication_request",label:"Publication request notifications"},{key:"announcements",label:"Announcement emails"}];for(let s of i){let a=r[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(r){t.fail("Failed to fetch preferences"),console.error(u.red(U(r)))}});AD.command("update").description("Update email notification preferences").option("--user-approval <bool>","Enable/disable user approval notifications").option("--publication-request <bool>","Enable/disable publication request notifications").option("--announcements <bool>","Enable/disable announcement emails").option("--all <bool>","Enable/disable all notifications").option("--user <username>","(owner only) update another user's preferences").action(async(e)=>{if(!Ue())console.error(u.red("Not authenticated. Run: nemar auth login")),process.exit(1);function t(i){if(i===void 0)return;let s=i.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: "${i}". Use true/false, on/off, yes/no.`)),process.exit(1)}let r={};if(e.all!==void 0){let i=t(e.all);r.user_approval=i,r.publication_request=i,r.announcements=i}else{let i=t(e.userApproval),s=t(e.publicationRequest),o=t(e.announcements);if(i===void 0&&s===void 0&&o===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(" --all <bool> All notifications"),process.exit(1);if(i!==void 0)r.user_approval=i;if(s!==void 0)r.publication_request=s;if(o!==void 0)r.announcements=o}let n=w("Updating email preferences...").start();try{let i=await Ez(r,e.user),s=i.username?`${i.username}'s`:"Your";n.succeed(`${s} email preferences updated:`),console.log(),console.log(` User approval: ${i.user_approval?u.green("enabled"):u.dim("disabled")}`),console.log(` Publication request: ${i.publication_request?u.green("enabled"):u.dim("disabled")}`),console.log(` Announcements: ${i.announcements?u.green("enabled"):u.dim("disabled")}`)}catch(i){n.fail("Failed to update preferences"),console.error(u.red(U(i)))}});Ie.addCommand(AD);var Gm=new Ee("notice").description("Manage system notices displayed to CLI users");Gm.command("list").description("List all notices (including expired)").action(async()=>{if(!Ue())console.error(u.red("Not authenticated. Run: nemar auth login")),process.exit(1);let e=w("Fetching notices...").start();try{let{notices:t}=await Wz();if(t.length===0){e.succeed("No notices found.");return}e.succeed(`${t.length} notice(s):`),console.log();for(let r of t){let i={critical:u.red.bold,warning:u.yellow,maintenance:u.magenta,announcement:u.green,tip:u.blue,info:u.blue}[r.level]||u.white,s=r.expires_at&&new Date(r.expires_at)<new Date?u.dim(" (expired)"):"";if(console.log(` ${u.dim(`#${r.id}`)} ${i(`[${r.level.toUpperCase()}]`)} ${u.dim(`scope:${r.scope}`)}${s}`),console.log(` ${r.message}`),console.log(` ${u.dim(`Created: ${r.created_at}`)}`),r.expires_at)console.log(` ${u.dim(`Expires: ${r.expires_at}`)}`);console.log()}}catch(t){Ze(t,e,"Failed to fetch notices")}});Gm.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(!Ue())console.error(u.red("Not authenticated. Run: nemar auth login")),process.exit(1);if(![...X_,"info"].includes(e.level))console.error(u.red(`Invalid level: ${e.level}. Use ${X_.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=w("Creating notice...").start();try{let r=await Kz({message:e.message,level:e.level,scope:e.scope,expires_at:e.expires});if(t.succeed(`Notice created (ID: ${r.id})`),console.log(` Level: ${r.level}`),console.log(` Scope: ${r.scope}`),console.log(` Message: ${r.message}`),r.expires_at)console.log(` Expires: ${r.expires_at}`)}catch(r){Ze(r,t,"Failed to create notice")}});Gm.command("clear <id>").description("Delete a notice by ID").option(Re,Oe).option(qe,Te).action(async(e,t)=>{if(!Ue())console.error(u.red("Not authenticated. Run: nemar auth login")),process.exit(1);let r=Number.parseInt(e,10);if(Number.isNaN(r))console.error(u.red("Invalid notice ID")),process.exit(1);if(!await Fe(`Delete notice #${r}?`,t,!1))return;let i=w("Deleting notice...").start();try{await Yz(r),i.succeed(`Notice #${r} deleted`)}catch(s){Ze(s,i,"Failed to delete notice")}});Ie.addCommand(Gm);Ie.command("notify").description("Send an email to a group or a single user").option("--to <group>","Recipient group: all, admins, members").option("--user <username>","Send to a single user by username").requiredOption("--subject <text>","Email subject line").option("--body <text>","Email body (markdown)").option("--body-file <path>","Read email body from file (markdown)").option("--dry-run","Preview recipients without sending").option(Re,Oe).option(qe,Te).action(async(e)=>{if(!Ue())console.error(u.red("Not authenticated. Run: nemar auth login")),process.exit(1);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 t;if(e.bodyFile){if(!jG(e.bodyFile))console.error(u.red(`File not found: ${e.bodyFile}`)),process.exit(1);t=mTe(e.bodyFile,"utf-8")}else if(e.body)t=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,n=e.user?{user:e.user,subject:e.subject,body:t}:{to:e.to,subject:e.subject,body:t};if(e.dryRun){let a=w("Checking recipients...").start();try{let c=await z_({...n,dry_run:!0});if("dry_run"in c){a.succeed(`Dry run: ${c.recipient_count} recipient(s) for "${c.recipient_group}"`),console.log();for(let l of c.recipients)console.log(` ${l}`)}}catch(c){Ze(c,a,"Failed to check recipients")}return}console.log(u.bold("Email preview:")),console.log(` To: ${u.cyan(r)}`),console.log(` Subject: ${e.subject}`),console.log(` Body: ${t.length>100?`${t.substring(0,100)}...`:t}`),console.log();let i=e.user?`Send this email to ${e.user}?`:"Send this broadcast email?";if(!await Fe(i,e,!1))return;let o=w(e.user?`Sending to ${e.user}...`:"Sending broadcast...").start();try{let a=await z_(n);if("broadcast_id"in a)if(a.failure_count>0){o.warn(`Email send: ${a.recipient_count} delivered, ${a.failure_count} failed`);for(let c of a.failed_recipients)console.log(u.red(` Failed: ${c}`))}else{let c=e.user?`Email sent to ${e.user}`:`Broadcast sent to ${a.recipient_count} recipient(s)`;o.succeed(`${c} (ID: ${a.broadcast_id})`)}}catch(a){Ze(a,o,"Failed to send email")}});var STe=1500;function $Te(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 CTe(e){return e.kind==="stale"||e.kind==="missing"}function FTe(e){let r=e.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${r}$`)}var YG=new Ee("summary").description("summary.json coverage across published dataset versions");YG.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(Re,Oe).option(qe,Te).action(async(e)=>{if(!oe())return;let t=w("Building coverage report...").start(),r;try{r=await Sz()}catch(m){Ze(m,t,"Failed to fetch coverage report");return}t.succeed(`Coverage: target=schema ${r.target_schema}, versions=${r.totals.versions}`);let n=r.versions,i=null;if(e.id){if(n=n.filter((m)=>m.dataset_id===e.id),i=`dataset_id=${e.id}`,n.length===0){console.log(u.yellow(`No rows for ${i}`));return}}else if(e.match){let m=FTe(e.match);if(n=n.filter((p)=>m.test(p.dataset_id)),i=`--match ${e.match}`,n.length===0){console.log(u.yellow(`No rows match ${i}`));return}console.log(u.dim(`Scoped to ${n.length} version(s) matching ${e.match}`))}if(e.json){console.log(JSON.stringify(i?{...r,versions:n,totals:qG(n)}:r,null,2));return}let s=e.onlyStale?n.filter((m)=>m.state.kind!=="ok"):n;if(s.length===0)console.log(u.green("All versions at target schema \u2014 no drift."));else{let m=Math.max(...s.map((g)=>g.dataset_id.length),10),p=Math.max(...s.map((g)=>g.version.length),7);for(let g of s)console.log(` ${g.dataset_id.padEnd(m)} ${g.version.padEnd(p)} ${$Te(g.state)}`)}let o=i?qG(n):r.totals;if(console.log(),console.log(` Total: ${o.versions} ${u.green(`ok=${o.ok}`)} ${u.yellow(`stale=${o.stale}`)} ${u.red(`missing=${o.missing}`)} ${u.red(`error=${o.error}`)}`),!e.fix){if(o.stale+o.missing>0)console.log(u.dim(`
|
|
458
458
|
Run with --fix to dispatch generate-manifest for the ${o.stale+o.missing} drifted version(s).`));return}let a=n.filter((m)=>CTe(m.state));if(a.length===0){console.log(u.green(`
|
|
459
|
-
Nothing to dispatch.`));return}let c=i?` (scoped to ${i})`:"",l=await Fe(`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[m,p]of a.entries()){let g=`${p.dataset_id}@${p.version}`,y=w(`[${m+1}/${a.length}] dispatching ${g}...`).start();try{await $z(p.dataset_id,p.version),y.succeed(`[${m+1}/${a.length}] dispatched ${g}`),d++}catch(x){y.fail(`[${m+1}/${a.length}] ${g}: ${U(x)}`),f++}if(m<a.length-1)await new Promise((x)=>setTimeout(x,STe))}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 qG(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}}Ie.addCommand(YG);Ke();Bn();rn();Y_();Ps();async function JG(e){return I(`/auth/check-username?username=${encodeURIComponent(e)}`)}async function XG(e){return I(`/auth/check-github?username=${encodeURIComponent(e)}`)}async function QG(e){return I("/auth/signup",{method:"POST",body:JSON.stringify(e)})}async function kD(e){return I("/auth/login",{method:"POST",body:JSON.stringify({api_key:e})})}async function ZG(e){return I("/auth/resend-verification",{method:"POST",body:JSON.stringify({email:e})})}async function eW(e,t){return I("/auth/retrieve-key",{method:"POST",body:JSON.stringify({email:e,password:t})})}async function tW(e){return I("/auth/request-key-regeneration",{method:"POST",body:JSON.stringify({email:e})})}async function Wm(){return(await I("/users/me",{},!0,Oz)).user}async function rW(e){return I("/sandbox/complete",{method:"POST",body:JSON.stringify({dataset_id:e})},!0)}async function nW(){return I("/sandbox/reset",{method:"POST"},!0)}async function iW(){return I("/sandbox/status",{},!0)}gr();ks();Bt();var sW={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)"}}},RTe={upload:["git-annex","gh","aws","deno"],download:["gh"],clone:["git","gh"],push:["git-annex","gh"],publish:["gh","aws"],update:["git","gh"],release:["git","gh"]};function OTe(){if(process.platform==="darwin")return"macos";if(process.platform==="win32")return"windows";return"linux"}function oW(e,t=OTe()){return e.installInstructions[t]}function ATe(e){let t=e.match(/(\d+\.\d+(?:\.\d+)?)/);return t?t[1]:void 0}async function aW(e){try{let{exitCode:t,stdout:r}=await
|
|
459
|
+
Nothing to dispatch.`));return}let c=i?` (scoped to ${i})`:"",l=await Fe(`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[m,p]of a.entries()){let g=`${p.dataset_id}@${p.version}`,y=w(`[${m+1}/${a.length}] dispatching ${g}...`).start();try{await $z(p.dataset_id,p.version),y.succeed(`[${m+1}/${a.length}] dispatched ${g}`),d++}catch(x){y.fail(`[${m+1}/${a.length}] ${g}: ${U(x)}`),f++}if(m<a.length-1)await new Promise((x)=>setTimeout(x,STe))}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 qG(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}}Ie.addCommand(YG);Ke();Bn();rn();Y_();Ps();async function JG(e){return I(`/auth/check-username?username=${encodeURIComponent(e)}`)}async function XG(e){return I(`/auth/check-github?username=${encodeURIComponent(e)}`)}async function QG(e){return I("/auth/signup",{method:"POST",body:JSON.stringify(e)})}async function kD(e){return I("/auth/login",{method:"POST",body:JSON.stringify({api_key:e})})}async function ZG(e){return I("/auth/resend-verification",{method:"POST",body:JSON.stringify({email:e})})}async function eW(e,t){return I("/auth/retrieve-key",{method:"POST",body:JSON.stringify({email:e,password:t})})}async function tW(e){return I("/auth/request-key-regeneration",{method:"POST",body:JSON.stringify({email:e})})}async function Wm(){return(await I("/users/me",{},!0,Oz)).user}async function rW(e){return I("/sandbox/complete",{method:"POST",body:JSON.stringify({dataset_id:e})},!0)}async function nW(){return I("/sandbox/reset",{method:"POST"},!0)}async function iW(){return I("/sandbox/status",{},!0)}gr();ks();Bt();var sW={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)"}}},RTe={upload:["git-annex","gh","aws","deno"],download:["gh"],clone:["git","gh"],push:["git-annex","gh"],publish:["gh","aws"],update:["git","gh"],release:["git","gh"]};function OTe(){if(process.platform==="darwin")return"macos";if(process.platform==="win32")return"windows";return"linux"}function oW(e,t=OTe()){return e.installInstructions[t]}function ATe(e){let t=e.match(/(\d+\.\d+(?:\.\d+)?)/);return t?t[1]:void 0}async function aW(e){try{let{exitCode:t,stdout:r}=await F(e.cmd);if(t!==0)return{available:!1};return{available:!0,version:ATe(r)}}catch(t){let r=t instanceof Error?t.message:String(t);if(!r.includes("ENOENT")&&!r.includes("not found"))console.error(` Warning: ${e.name} check failed unexpectedly: ${r}`);return{available:!1}}}async function PD(){let e=Object.entries(sW);return Promise.all(e.map(async([t,r])=>{let{available:n,version:i}=await aW(r);return{key:t,name:r.name,purpose:r.purpose,required:r.required,available:n,version:i,installInstruction:oW(r)}}))}async function cW(){let t=(await PD()).filter((r)=>r.required&&!r.available);if(t.length===0)return[];console.warn(`
|
|
460
460
|
Heads up: some tools NEMAR needs for uploading/validating aren't installed yet:`);for(let r of t)console.warn(` - ${r.name} (${r.purpose})`),console.warn(` Install: ${r.installInstruction}`);return console.warn("Run `nemar doctor` anytime to re-check. You can finish signup without them.\n"),t}async function qo(e){let r=RTe[e].map((o)=>sW[o]).filter(Boolean),i=(await Promise.all(r.map(async(o)=>({check:o,available:(await aW(o)).available})))).filter((o)=>!o.available&&o.check.required).map((o)=>({tool:o.check.name,installInstruction:oW(o.check)}));if(i.length===0)return;let s=[`
|
|
461
461
|
Missing required tools:`];for(let o of i)s.push(` ${o.tool} not installed`),s.push(` Install: ${o.installInstruction}`);throw Error(s.join(`
|
|
462
462
|
`))}import{appendFileSync as kTe,existsSync as Ms,mkdirSync as uW,readFileSync as Ym,writeFileSync as PTe}from"fs";import{homedir as ITe}from"os";import{join as Km}from"path";var{spawn:lW}=globalThis.Bun;function jo(){let e=Km(ITe(),".ssh");return{sshDir:e,privateKey:Km(e,"nemar_ed25519"),publicKey:Km(e,"nemar_ed25519.pub"),configFile:Km(e,"config")}}function dW(){let e=jo();return Ms(e.privateKey)&&Ms(e.publicKey)}async function fW(e){let t=jo();if(!Ms(t.sshDir))try{uW(t.sshDir,{mode:448})}catch(r){return{success:!1,error:`Cannot create ~/.ssh directory: ${r.message}`}}if(Ms(t.privateKey))try{return{success:!0,publicKey:Ym(t.publicKey,"utf-8").trim()}}catch(r){return{success:!1,error:`NEMAR SSH key exists but cannot read public key: ${r.message}`}}try{let r=lW({cmd:["ssh-keygen","-t","ed25519","-f",t.privateKey,"-N","","-C",`nemar-cli-${e}`],stdout:"pipe",stderr:"pipe"}),n=await new Response(r.stderr).text();if(await r.exited!==0)return{success:!1,error:`ssh-keygen failed: ${n}`};return{success:!0,publicKey:Ym(t.publicKey,"utf-8").trim()}}catch(r){return{success:!1,error:`Failed to generate SSH key: ${r.message}`}}}function pW(){let e=jo();if(!Ms(e.publicKey))return null;try{return Ym(e.publicKey,"utf-8").trim()}catch{return null}}function TTe(){let e=jo();if(!Ms(e.configFile))return!1;try{let t=Ym(e.configFile,"utf-8");return t.includes("IdentityFile ~/.ssh/nemar_ed25519")||t.includes(`IdentityFile ${e.privateKey}`)}catch{return!1}}function mW(){let e=jo();if(!Ms(e.sshDir))try{uW(e.sshDir,{mode:448})}catch(r){return{success:!1,error:`Cannot create ~/.ssh directory: ${r.message}`}}if(TTe())return{success:!0};let t=`
|
|
@@ -570,10 +570,10 @@ Provide source dataset information so we can check license compatibility.`);whil
|
|
|
570
570
|
`),console.log(u.dim(` Updated dataset_description.json SourceDatasets (${c.length} source(s))`))}}catch(i){console.log(u.yellow(` Warning: Could not update SourceDatasets: ${U(i)}`))}console.log()}}}Ke();rn();kc();gr();import{existsSync as iw,mkdirSync as I5e,readFileSync as T5e,writeFileSync as DK}from"fs";import{resolve as sw}from"path";import{existsSync as cK,mkdirSync as v5e,readFileSync as _5e,writeFileSync as D5e}from"fs";import{join as uK}from"path";var w5e=".nemar",E5e="config.json";function QD(e){return uK(e,w5e)}function lK(e){return uK(QD(e),E5e)}function S5e(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 ZD(e){let t=lK(e);if(!cK(t))return null;try{let r=_5e(t,"utf-8"),n=JSON.parse(r);if(!S5e(n))return console.error(`Warning: Local config at ${t} is invalid or corrupted`),console.error(` Delete it to start fresh: rm -rf ${QD(e)}`),null;return n}catch(r){let n=r instanceof Error?r.message:String(r);return console.error(`Warning: Could not read local config at ${t}`),console.error(` Error: ${n}`),null}}function ew(e,t){let r=QD(e),n=lK(e);try{if(!cK(r))v5e(r,{recursive:!0});return D5e(n,JSON.stringify(t,null,2)),!0}catch(i){let s=i instanceof Error?i.message:String(i);return console.error(`Warning: Could not save local config to ${n}`),console.error(` Error: ${s}`),console.error(" Resume capability will not be available for this dataset."),!1}}function dK(e){let t=ZD(e);if(!t)return!1;return t.last_upload_at=new Date().toISOString(),ew(e,t)}Ts();import{existsSync as tw,mkdirSync as $5e,readFileSync as C5e,unlinkSync as F5e,writeFileSync as R5e}from"fs";import{join as fK}from"path";var O5e=new Set(["pending","uploaded","failed"]),A5e=new Set(["tracking","s3_upload","url_registration","metadata_write","dataset_save","github_push","ci_deploy"]),pK=".nemar",k5e="upload-progress.json";function rw(e){return fK(e,pK,k5e)}function mK(e,t,r){let n=new Date().toISOString(),i={dataset_id:t,started_at:n,updated_at:n,files:{},completed_steps:[]};for(let s of r)i.files[s.path]={status:"pending",size:s.size,mtimeMs:s.mtimeMs,updated_at:n};return br(e,i),i}function hK(e){let t=rw(e);if(!tw(t))return null;try{let r=C5e(t,"utf-8"),n=JSON.parse(r);if(!P5e(n))return console.warn(`Warning: Upload progress file is invalid or corrupted (${t})`),console.warn(" Use --restart to clear progress and start fresh."),null;return n}catch(r){let n=r instanceof Error?r.message:String(r);return console.warn(`Warning: Could not read upload progress (${t}): ${n}`),console.warn(" Use --restart to clear progress and start fresh."),null}}function br(e,t){let r=fK(e,pK),n=rw(e);try{if(!tw(r))$5e(r,{recursive:!0});return t.updated_at=new Date().toISOString(),R5e(n,JSON.stringify(t,null,2)),!0}catch(i){let s=i instanceof Error?i.message:String(i);return console.warn(`Warning: Could not save upload progress (${n}): ${s}`),console.warn(" If the upload is interrupted, resume may not work correctly."),!1}}function gK(e,t,r){let n=e.files[t];if(n){if(n.status="uploaded",n.updated_at=new Date().toISOString(),n.error=void 0,r){if(n.size=r.size,r.mtimeMs!==void 0)n.mtimeMs=r.mtimeMs}}}function Bs(e,t){if(!e.completed_steps.includes(t))e.completed_steps.push(t)}function ii(e,t){return e.completed_steps.includes(t)}function nw(e,t){e.completed_steps=e.completed_steps.filter((r)=>r!==t)}function yK(e,t){return t.some((r)=>xK(e.files[r.path],r))}function xK(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 bK(e,t){return t.filter((r)=>{let n=e.files[r.path];return!n||n.status!=="uploaded"||xK(n,r)})}function Pd(e){let t=rw(e);try{if(tw(t))F5e(t);return!0}catch(r){let n=r instanceof Error?r.message:String(r);return console.warn(`Warning: Could not clear upload progress (${t}): ${n}`),!1}}function vK(e){let t=Object.values(e.files),r=0,n=0,i=0;for(let s of t)switch(s.status){case"uploaded":r++;break;case"failed":n++;break;case"pending":i++;break}return{total:t.length,uploaded:r,failed:n,pending:i,completedSteps:e.completed_steps}}function P5e(e){if(!e||typeof e!=="object")return!1;let t=e;if(typeof t.dataset_id!=="string"||t.dataset_id.length===0||typeof t.started_at!=="string"||typeof t.updated_at!=="string"||typeof t.files!=="object"||t.files===null||!Array.isArray(t.completed_steps))return!1;for(let r of Object.values(t.files)){if(!r||typeof r!=="object")return!1;let n=r;if(typeof n.status!=="string"||!O5e.has(n.status))return!1;if(typeof n.size!=="number"||n.size<0)return!1;if(n.mtimeMs!==void 0&&(typeof n.mtimeMs!=="number"||n.mtimeMs<0))return!1}for(let r of t.completed_steps)if(typeof r!=="string"||!A5e.has(r))return!1;return!0}function er(e){return{status:"ok",value:e}}var et={status:"fail"},_K={status:"stop"};function wK(e,t,r){if(!ii(r,"metadata_write")){if(t)try{let n=sw(e,".nemar"),i=sw(n,"metadata.json");if(!iw(i)){if(!iw(n))I5e(n,{recursive:!0});DK(i,JSON.stringify(t,null,2))}let s=sw(e,".bidsignore"),o="";if(iw(s))o=T5e(s,"utf-8");if(!o.includes(".nemar/")){let a=o?`${o.trimEnd()}
|
|
571
571
|
.nemar/
|
|
572
572
|
`:`.nemar/
|
|
573
|
-
`;DK(s,a)}console.log(u.dim(" Updated .bidsignore for NEMAR metadata"))}catch(n){console.log(u.yellow(` Warning: Could not update .bidsignore: ${U(n)}`)),console.log(u.dim(" Upload will continue without author enrichment."))}Bs(r,"metadata_write"),br(e,r)}else console.log(u.dim(" Metadata write already completed (skipping)"))}async function EK(e,t,r){if(!ii(r,"dataset_save")){let n=w("Saving dataset changes...").start(),i=await Ai(e,"Initial NEMAR dataset upload",t);if(!i.success)return br(e,r),Sn(n,"Failed to save dataset",i.error),console.log(),console.log(u.yellow("Re-run the same command to resume from this step.")),et;n.succeed("Dataset changes saved"),Bs(r,"dataset_save"),br(e,r)}else console.log(u.dim(" Dataset save already completed (skipping)"));return er()}async function SK(e,t){if(!ii(t,"github_push")){let r=w("Pushing metadata to GitHub...").start(),n=await Qt(e);if(!n.success)return br(e,t),Sn(r,"Failed to push to GitHub",n.error),console.log(),console.log(u.yellow("Re-run the same command to resume from this step.")),et;if(n.warning)r.warn("Metadata pushed to GitHub (with warning)"),console.log(u.yellow(` ${n.warning}`));else r.succeed("Metadata pushed to GitHub");Bs(t,"github_push"),br(e,t)}else console.log(u.dim(" GitHub push already completed (skipping)"));return er()}async function $K(e,t,r){if(!ii(r,"ci_deploy")){let n=w("Setting up BIDS validation CI...").start();try{await Ri(t),n.succeed("BIDS validation CI configured")}catch(i){if(i instanceof M&&i.statusCode===403)n.info("CI workflow will be configured by an admin");else{let s=i instanceof Error?i.message:String(i);n.warn(`Could not configure CI: ${s}`),console.log(u.dim(` An admin can add it later with: nemar admin ci add ${t}`))}}Bs(r,"ci_deploy"),br(e,r)}else console.log(u.dim(" CI deploy already completed (skipping)"))}function CK(e,t){Pd(e),dK(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(),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."))}Ke();function FK(e,t,r){if(t&&t.dataset_id!==r)return console.log(u.yellow(" Progress file is for a different dataset; starting fresh.")),Pd(e),null;return t}function RK(e,t,r,n){let i=ZD(e);if(console.log(),i)console.log(u.bold.yellow("Resume Upload:")),console.log(` Dataset ID: ${u.cyan(i.dataset_id)}`),console.log(` Last attempt: ${i.last_upload_at||i.created_at}`);else console.log(u.bold("Upload Plan:"));if(console.log(` Name: ${t}`),console.log(` Path: ${e}`),console.log(` Files: ${r.files.length}`),console.log(` Size: ${Qe(r.totalSize)}`),console.log(` Data files: ${r.dataFiles} (will be uploaded to S3)`),console.log(` Metadata files: ${r.metadataFiles} (will be stored in git)`),console.log(` Parallel jobs: ${n.jobs}`),console.log(),n.dryRun)return console.log(u.yellow("Dry run mode - no changes made")),_K;return er({existingConfig:i})}function OK(e,t){return e?bK(e,t):t}function AK(e,t,r){let n=t.files.filter((s)=>s.type==="data");if(r.restart)Pd(e),console.log(u.dim(" Upload progress cleared (--restart)")),console.log();let i=r.restart?null:hK(e);if(i){let s=vK(i);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:n,uploadProgress:i}}Ke();rn();import{existsSync as N5e}from"fs";import{resolve as q5e}from"path";Oi();Bt();var j5e=17179869184;function M5e(e){let t=e.trim();if(t==="unlimited")return"unlimited";if(!/^\d+$/.test(t))return null;return Number(t)*1024}async function B5e(){try{let{stdout:e,exitCode:t}=await
|
|
573
|
+
`;DK(s,a)}console.log(u.dim(" Updated .bidsignore for NEMAR metadata"))}catch(n){console.log(u.yellow(` Warning: Could not update .bidsignore: ${U(n)}`)),console.log(u.dim(" Upload will continue without author enrichment."))}Bs(r,"metadata_write"),br(e,r)}else console.log(u.dim(" Metadata write already completed (skipping)"))}async function EK(e,t,r){if(!ii(r,"dataset_save")){let n=w("Saving dataset changes...").start(),i=await Ai(e,"Initial NEMAR dataset upload",t);if(!i.success)return br(e,r),Sn(n,"Failed to save dataset",i.error),console.log(),console.log(u.yellow("Re-run the same command to resume from this step.")),et;n.succeed("Dataset changes saved"),Bs(r,"dataset_save"),br(e,r)}else console.log(u.dim(" Dataset save already completed (skipping)"));return er()}async function SK(e,t){if(!ii(t,"github_push")){let r=w("Pushing metadata to GitHub...").start(),n=await Qt(e);if(!n.success)return br(e,t),Sn(r,"Failed to push to GitHub",n.error),console.log(),console.log(u.yellow("Re-run the same command to resume from this step.")),et;if(n.warning)r.warn("Metadata pushed to GitHub (with warning)"),console.log(u.yellow(` ${n.warning}`));else r.succeed("Metadata pushed to GitHub");Bs(t,"github_push"),br(e,t)}else console.log(u.dim(" GitHub push already completed (skipping)"));return er()}async function $K(e,t,r){if(!ii(r,"ci_deploy")){let n=w("Setting up BIDS validation CI...").start();try{await Ri(t),n.succeed("BIDS validation CI configured")}catch(i){if(i instanceof M&&i.statusCode===403)n.info("CI workflow will be configured by an admin");else{let s=i instanceof Error?i.message:String(i);n.warn(`Could not configure CI: ${s}`),console.log(u.dim(` An admin can add it later with: nemar admin ci add ${t}`))}}Bs(r,"ci_deploy"),br(e,r)}else console.log(u.dim(" CI deploy already completed (skipping)"))}function CK(e,t){Pd(e),dK(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(),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."))}Ke();function FK(e,t,r){if(t&&t.dataset_id!==r)return console.log(u.yellow(" Progress file is for a different dataset; starting fresh.")),Pd(e),null;return t}function RK(e,t,r,n){let i=ZD(e);if(console.log(),i)console.log(u.bold.yellow("Resume Upload:")),console.log(` Dataset ID: ${u.cyan(i.dataset_id)}`),console.log(` Last attempt: ${i.last_upload_at||i.created_at}`);else console.log(u.bold("Upload Plan:"));if(console.log(` Name: ${t}`),console.log(` Path: ${e}`),console.log(` Files: ${r.files.length}`),console.log(` Size: ${Qe(r.totalSize)}`),console.log(` Data files: ${r.dataFiles} (will be uploaded to S3)`),console.log(` Metadata files: ${r.metadataFiles} (will be stored in git)`),console.log(` Parallel jobs: ${n.jobs}`),console.log(),n.dryRun)return console.log(u.yellow("Dry run mode - no changes made")),_K;return er({existingConfig:i})}function OK(e,t){return e?bK(e,t):t}function AK(e,t,r){let n=t.files.filter((s)=>s.type==="data");if(r.restart)Pd(e),console.log(u.dim(" Upload progress cleared (--restart)")),console.log();let i=r.restart?null:hK(e);if(i){let s=vK(i);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:n,uploadProgress:i}}Ke();rn();import{existsSync as N5e}from"fs";import{resolve as q5e}from"path";Oi();Bt();var j5e=17179869184;function M5e(e){let t=e.trim();if(t==="unlimited")return"unlimited";if(!/^\d+$/.test(t))return null;return Number(t)*1024}async function B5e(){try{let{stdout:e,exitCode:t}=await F(["sh","-c","ulimit -v"]);if(t!==0)return null;return M5e(e)}catch{return null}}async function kK(){let e=w("Checking prerequisites...").start(),t=await Rm();if(!t.allPassed){e.fail("Prerequisites check failed"),console.log();for(let n of t.errors)console.log(u.red(` - ${n}`));return et}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 r=await B5e();if(typeof r==="number"&&r<j5e)console.log(u.yellow(` Warning: virtual memory limit is ${Qe(r)} (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(),er()}async function PK(e){let t=w("Verifying GitHub CLI authentication...").start(),r=await Sm(e.githubUsername);if(!r.authenticated)return Sn(t,"GitHub CLI not authenticated",r.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")),et;if(e.githubUsername&&!r.matches)t.warn("GitHub CLI user mismatch"),console.log(u.yellow(` ${r.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 ${r.username}`);return er()}async function IK(e,t){if(!t.skipValidation){let r=w("Validating BIDS dataset...").start(),n=q5e(e,"dataset_description.json");if(!N5e(n))return r.fail("Not a valid BIDS dataset"),console.log(u.red("Missing required file: dataset_description.json")),et;if(!(await Hc()).installed)return r.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")),et;try{let s=await _W(e,{prune:!0});if(!s.valid)return r.fail("Dataset has validation errors"),console.log(),console.log(wW(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).")),et;r.succeed(`Dataset is valid BIDS (${s.warningCount} warnings)`)}catch(s){return r.fail("Validation failed"),console.log(u.red(s.message)),et}console.log()}return er()}Ke();rn();Pc();Po();gr();import{existsSync as L5e,readFileSync as U5e,writeFileSync as V5e}from"fs";import{resolve as z5e}from"path";Oi();Dd();jc();Bt();Ns();qs();function H5e(e){let t=e?.match(/github\.com\/([a-zA-Z0-9_.-]+\/[a-zA-Z0-9_.-]+)/);return t?t[1].replace(/\.git$/,""):null}function G5e(e){try{let t=z5e(e,".gitignore"),r="";if(L5e(t))r=U5e(t,"utf-8");if(!r.includes(".nemar/")){let n=r?`${r.trimEnd()}
|
|
574
574
|
.nemar/
|
|
575
575
|
`:`.nemar/
|
|
576
|
-
`;V5e(t,n)}}catch(t){console.log(u.yellow(` Warning: Could not update .gitignore: ${U(t)}`))}}async function NK(e,t,r,n,i,s){let o,a=i!==null,c;if(a){c=w(`Resuming upload for ${i.dataset_id}...`).start();try{await gt(i.dataset_id),o={dataset_id:i.dataset_id,ssh_url:i.ssh_url,s3_prefix:i.s3_prefix,github_url:i.github_url,upload_urls:{},s3_config:i.s3_config},c.succeed(`Resuming upload: ${o.dataset_id}`)}catch(l){if(Sn(c,"Failed to resume upload",l),l instanceof M&&l.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 et}}else{c=w("Creating dataset in NEMAR...").start();try{let l=await wm({name:r,description:t.description,files:n.map((f)=>({path:f.path,size:f.size,type:f.type})),attestation:s});o={dataset_id:l.dataset.dataset_id,ssh_url:l.dataset.ssh_url,s3_prefix:l.dataset.s3_prefix,github_url:l.dataset.github_url,upload_urls:l.upload_urls||{},s3_config:l.s3_config};let d={dataset_id:o.dataset_id,github_url:o.github_url,ssh_url:o.ssh_url,s3_prefix:o.s3_prefix,s3_config:o.s3_config,created_at:new Date().toISOString()};if(ew(e,d),l.resumed)c.succeed(`Resumed existing dataset: ${o.dataset_id}`);else c.succeed(`Dataset created: ${o.dataset_id}`),await new Promise((f)=>setTimeout(f,1e4))}catch(l){return Sn(c,"Failed to create dataset",l),et}}return er(o)}async function qK(e){let t=w("Accepting GitHub repository invitation...").start(),r=H5e(e.github_url);if(!r)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."),et;let n=await $m(r);if(n.accepted)if(n.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(` ${n.error}`)),console.log(),console.log("You may need to accept the invitation manually:"),console.log(u.cyan(` https://github.com/${r}/invitations`)),console.log();return er()}async function jK(e,t){let r=w("Initializing git-annex dataset...").start();if(!await En(e)){let a=await Uc(e,{author:t});if(!a.success)return Sn(r,"Failed to initialize git-annex dataset",a.error),et}let i=await fG(e);if(!i.success)return Sn(r,"Failed to initialize git-annex",i.error),et;let s=await Vc(e);if(!s.success)r.warn("Could not configure largefiles pattern"),console.log(u.dim(` ${s.error}`));r.succeed("git-annex dataset initialized");let o=await ti(e);if(o?.startsWith("adjusted/"))console.log(u.dim(` Note: Your local branch is "${o}".`)),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 G5e(e),er()}async function MK(e,t,r){let n=w("Configuring GitHub remote...").start(),i=await ei(e,t.ssh_url);if(!i.success)return Sn(n,"Failed to configure GitHub remote",i.error),et;if(n.succeed("GitHub remote configured"),!await Cm(e,{yes:r.yes}))return et;return er()}async function W5e(e){let{stdout:t,stderr:r,exitCode:n}=await
|
|
576
|
+
`;V5e(t,n)}}catch(t){console.log(u.yellow(` Warning: Could not update .gitignore: ${U(t)}`))}}async function NK(e,t,r,n,i,s){let o,a=i!==null,c;if(a){c=w(`Resuming upload for ${i.dataset_id}...`).start();try{await gt(i.dataset_id),o={dataset_id:i.dataset_id,ssh_url:i.ssh_url,s3_prefix:i.s3_prefix,github_url:i.github_url,upload_urls:{},s3_config:i.s3_config},c.succeed(`Resuming upload: ${o.dataset_id}`)}catch(l){if(Sn(c,"Failed to resume upload",l),l instanceof M&&l.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 et}}else{c=w("Creating dataset in NEMAR...").start();try{let l=await wm({name:r,description:t.description,files:n.map((f)=>({path:f.path,size:f.size,type:f.type})),attestation:s});o={dataset_id:l.dataset.dataset_id,ssh_url:l.dataset.ssh_url,s3_prefix:l.dataset.s3_prefix,github_url:l.dataset.github_url,upload_urls:l.upload_urls||{},s3_config:l.s3_config};let d={dataset_id:o.dataset_id,github_url:o.github_url,ssh_url:o.ssh_url,s3_prefix:o.s3_prefix,s3_config:o.s3_config,created_at:new Date().toISOString()};if(ew(e,d),l.resumed)c.succeed(`Resumed existing dataset: ${o.dataset_id}`);else c.succeed(`Dataset created: ${o.dataset_id}`),await new Promise((f)=>setTimeout(f,1e4))}catch(l){return Sn(c,"Failed to create dataset",l),et}}return er(o)}async function qK(e){let t=w("Accepting GitHub repository invitation...").start(),r=H5e(e.github_url);if(!r)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."),et;let n=await $m(r);if(n.accepted)if(n.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(` ${n.error}`)),console.log(),console.log("You may need to accept the invitation manually:"),console.log(u.cyan(` https://github.com/${r}/invitations`)),console.log();return er()}async function jK(e,t){let r=w("Initializing git-annex dataset...").start();if(!await En(e)){let a=await Uc(e,{author:t});if(!a.success)return Sn(r,"Failed to initialize git-annex dataset",a.error),et}let i=await fG(e);if(!i.success)return Sn(r,"Failed to initialize git-annex",i.error),et;let s=await Vc(e);if(!s.success)r.warn("Could not configure largefiles pattern"),console.log(u.dim(` ${s.error}`));r.succeed("git-annex dataset initialized");let o=await ti(e);if(o?.startsWith("adjusted/"))console.log(u.dim(` Note: Your local branch is "${o}".`)),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 G5e(e),er()}async function MK(e,t,r){let n=w("Configuring GitHub remote...").start(),i=await ei(e,t.ssh_url);if(!i.success)return Sn(n,"Failed to configure GitHub remote",i.error),et;if(n.succeed("GitHub remote configured"),!await Cm(e,{yes:r.yes}))return et;return er()}async function W5e(e){let{stdout:t,stderr:r,exitCode:n}=await F(["git","ls-files","-z"],{cwd:e});if(n!==0)throw Error(r.trim()||"git ls-files failed");return new Set(t.split("\x00").filter(Boolean))}async function TK(e,t){let r=t?["git","annex","find","--in",t]:["git","annex","find","--include","*"],{stdout:n,stderr:i,exitCode:s}=await F(r,{cwd:e});if(s!==0)throw Error(i.trim()||"git annex find failed");return new Set(n.split(`
|
|
577
577
|
`).filter(Boolean))}function K5e(e,t,r){let n=[...e],i=new Set(e.map((s)=>s.path));for(let s of t)if(!r.has(s.path)&&!i.has(s.path))n.push(s),i.add(s.path);return n}async function BK(e,t,r,n,i,s){let o=i,a;if(!o)o=mK(e,s.dataset_id,r);else{if(ii(o,"tracking")&&yK(o,r))nw(o,"tracking"),console.log(u.dim(" Data files changed since the last run; re-running git-annex add"));for(let c of r)if(!o.files[c.path])o.files[c.path]={status:"pending",size:c.size,mtimeMs:c.mtimeMs,updated_at:new Date().toISOString()};br(e,o)}if(!ii(o,"s3_upload")){let c;try{c=await W5e(e)}catch(f){return console.log(u.red(`Failed to read the git index: ${U(f)}`)),console.log(u.dim(" Re-run the command to retry.")),et}let l=K5e(n,r,c),d=l.length-n.length;if(d>0&&ii(o,"tracking"))nw(o,"tracking"),br(e,o),console.log(u.yellow(` ${d} data files are missing from git despite recorded progress; re-tracking them`));if(l.length>0){if(!ii(o,"tracking")){a=w(`Tracking ${l.length} data files with git-annex...`).start();let v=await Io(e,l.map((_)=>_.path));if(!v.success)return a.fail(`Failed to track data files: ${v.error}`),console.log(u.yellow("Re-run the same command to resume tracking.")),et;a.succeed("Data files tracked by git-annex"),Bs(o,"tracking"),br(e,o)}else console.log(u.dim(" Data files already tracked by git-annex (skipping)"));a=w("Requesting upload credentials...").start();let f;try{f=await Zn(s.dataset_id),a.succeed("Upload credentials received (2h expiry)")}catch(v){return a.fail(`Could not get upload credentials: ${U(v)}`),console.log(u.red(" Upload credentials are required for S3 access.")),console.log(u.dim(" Re-run the command to retry.")),et}a=w("Configuring S3 remote...").start();let m=await $r(e,{name:"nemar-s3",bucket:f.s3.bucket,prefix:`${s.dataset_id}/objects`,region:f.s3.region,publicUrl:s.s3_config.public_url},Lt(f.credentials));if(!m.success)return a.fail(`Failed to configure S3 remote: ${m.error}`),console.log(u.dim(" Re-run the command to retry.")),et;a.succeed("S3 remote configured"),a=w(`Uploading ${l.length} data files to S3...`).start();let p=await ri(e,"nemar-s3",Number.parseInt(t.jobs,10),Lt(f.credentials));if(await Ut(e),!p.success)return a.fail(`S3 upload failed: ${p.error}`),console.log(u.yellow("Re-run the same command to resume uploading.")),et;let g,y;try{g=await TK(e),y=await TK(e,"nemar-s3")}catch(v){return a.fail(`Could not verify the S3 upload: ${U(v)}`),console.log(u.yellow("Re-run the same command to retry.")),et}let x=l.filter((v)=>g.has(v.path)&&!y.has(v.path));if(x.length>0){a.fail(`S3 upload incomplete: ${x.length} of ${l.length} data files are not recorded at the S3 remote`);for(let v of x.slice(0,5))console.log(u.red(` - ${v.path}`));if(x.length>5)console.log(u.dim(` ... and ${x.length-5} more`));return console.log(u.yellow("Re-run the same command to resume uploading.")),et}for(let v of l)gK(o,v.path,{size:v.size,mtimeMs:v.mtimeMs});br(e,o),a.succeed(`Uploaded ${p.filesCopied} data files to S3`)}else console.log(u.dim("No data files to upload to S3"));Bs(o,"s3_upload"),br(e,o)}else console.log(u.dim(" S3 upload already completed (skipping)"));return er(o)}var lt=new Ee("dataset").description("Dataset management").addHelpText("after",`
|
|
578
578
|
Description:
|
|
579
579
|
Manage BIDS datasets on NEMAR. Upload, download, validate, and version
|